diff --git a/.gitattributes b/.gitattributes index 0b245f1..947fdca 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,2 +1,7 @@ # The same lockfile bytes identify production artifacts on every build host. Cargo.lock text eol=lf + +# Preserve the reviewed third-party package and patch byte identities. +/vendor/h2/** -text +# Unified diff context lines contain a required leading space. +/scripts/native/h2/initial-write-buffer.patch -text whitespace=-blank-at-eol diff --git a/.github/workflows/pr-native.yml b/.github/workflows/pr-native.yml new file mode 100644 index 0000000..59da298 --- /dev/null +++ b/.github/workflows/pr-native.yml @@ -0,0 +1,214 @@ +name: PR Native + +on: + workflow_call: + +permissions: + contents: read + +env: + UV_PYTHON_PREFERENCE: only-system + UV_PYTHON_DOWNLOADS: never + +defaults: + run: + shell: bash + +jobs: + macos: + name: macOS arm64 + runs-on: macos-26 + timeout-minutes: 90 + outputs: + apple-mobile: ${{ steps.scope.outputs['apple-mobile'] }} + android: ${{ steps.scope.outputs.android }} + steps: + - uses: actions/checkout@v7 + with: + fetch-depth: 2 + persist-credentials: false + - name: Select mobile build targets + id: scope + run: | + set -euo pipefail + shared=( + Cargo.toml Cargo.lock build.rs .cargo .github/workflows + include scripts crates/vole-blake3-raw + src/lib.rs src/ffi src/invoke src/platform + ) + changed() { + if git diff --quiet HEAD^1 HEAD -- "$@"; then + printf false + else + local status=$? + if [[ "$status" != 1 ]]; then return "$status"; fi + printf true + fi + } + + git rev-parse --verify HEAD >/dev/null + if git rev-parse --verify --quiet 'HEAD^1^{commit}' >/dev/null; then + apple_mobile="$(changed "${shared[@]}" src/http_processing)" + android="$(changed "${shared[@]}")" + else + status=$? + if [[ "$status" != 1 ]]; then exit "$status"; fi + apple_mobile=true + android=true + fi + printf 'apple-mobile=%s\nandroid=%s\n' "$apple_mobile" "$android" >> "$GITHUB_OUTPUT" + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-python@v7 + with: + python-version: "3.x" + check-latest: true + architecture: arm64 + - uses: astral-sh/setup-uv@v10.3.3 + with: + version: "0.13.6" + - uses: Swatinem/rust-cache@v2 + with: + key: pr-native-macos-arm64-${{ hashFiles('scripts/src/vole_scripts/*.py', 'scripts/cmake/**', 'scripts/native/**') }} + workspaces: ". -> target" + env-vars: ImageOS ImageVersion SDKROOT DEVELOPER_DIR VOLE BORING AWS_LC LIBCLANG BINDGEN + cache-bin: "false" + - name: Build and check the native CLI and FFI + run: | + uv run --project scripts --locked python - <<'PY' + from vole_scripts.builds import build_apple_target, build_cli + from vole_scripts.release import _smoke + + _smoke(build_cli()) + if not build_apple_target("aarch64-apple-darwin").is_file(): + raise SystemExit("Missing macOS static library") + PY + + windows: + name: Windows arm64 + runs-on: windows-11-arm + timeout-minutes: 180 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + - uses: actions/setup-python@v7 + with: + python-version: "3.x" + check-latest: true + architecture: arm64 + - uses: astral-sh/setup-uv@v10.3.3 + with: + version: "0.13.6" + - uses: Swatinem/rust-cache@v2 + with: + key: pr-native-windows-arm64-${{ hashFiles('scripts/src/vole_scripts/*.py', 'scripts/cmake/**', 'scripts/native/**') }} + workspaces: ". -> target" + env-vars: ImageOS ImageVersion VOLE BORING AWS_LC LIBCLANG BINDGEN + cache-bin: "false" + - name: Build and smoke the Wintun CLI + run: | + uv run --project scripts --locked python - <<'PY' + from vole_scripts.builds import build_cli + from vole_scripts.release import _smoke + + _smoke(build_cli()) + PY + - name: Build Wintun FFI + run: uv run --project scripts --locked vole-scripts build windows --backend wintun + - name: Build UWP FFI and hosts + run: uv run --project scripts --locked vole-scripts build windows --backend uwp + - name: Check unpackaged UWP COM lifecycle + run: python scripts/check_windows_com.py --dll dist/windows/arm64/uwp/vole.dll + + apple-mobile: + name: ${{ matrix.name }} + needs: macos + if: needs.macos.outputs['apple-mobile'] == 'true' + runs-on: macos-26 + timeout-minutes: 90 + strategy: + fail-fast: false + matrix: + include: + - name: iOS arm64 + target: aarch64-apple-ios + - name: tvOS arm64 + target: aarch64-apple-tvos + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + targets: ${{ matrix.target }} + - uses: actions/setup-python@v7 + with: + python-version: "3.x" + check-latest: true + architecture: arm64 + - uses: astral-sh/setup-uv@v10.3.3 + with: + version: "0.13.6" + - uses: Swatinem/rust-cache@v2 + with: + key: pr-native-${{ matrix.target }}-${{ hashFiles('scripts/src/vole_scripts/*.py', 'scripts/cmake/**', 'scripts/native/**') }} + workspaces: ". -> target" + env-vars: ImageOS ImageVersion SDKROOT DEVELOPER_DIR VOLE BORING AWS_LC LIBCLANG BINDGEN + cache-bin: "false" + - name: Build the device-target static library + env: + VOLE_TARGET: ${{ matrix.target }} + run: | + uv run --project scripts --locked python - "$VOLE_TARGET" <<'PY' + import sys + + from vole_scripts.builds import build_apple_target + + if not build_apple_target(sys.argv[1]).is_file(): + raise SystemExit("Missing Apple static library") + PY + + android: + name: Android + needs: macos + if: needs.macos.outputs.android == 'true' + runs-on: ubuntu-24.04 + timeout-minutes: 90 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + - uses: dtolnay/rust-toolchain@stable + with: + targets: aarch64-linux-android,x86_64-linux-android + - uses: actions/setup-python@v7 + with: + python-version: "3.x" + check-latest: true + - uses: astral-sh/setup-uv@v10.3.3 + with: + version: "0.13.6" + - name: Install stable Android NDK r30 + run: | + set -euo pipefail + sdkmanager="$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" + ndk_package="$("$sdkmanager" --list --channel=0 | awk -F '|' ' + NF == 1 { split($0, fields, " "); $1 = fields[1]; $2 = fields[2] } + { gsub(/[[:space:]]/, "", $1); gsub(/[[:space:]]/, "", $2) } + $1 ~ /^ndk[;\/]30\.[0-9]+\.[0-9]+$/ && + $2 ~ /^30\.[0-9]+\.[0-9]+$/ { + sub(/^ndk\//, "ndk;", $1); print $1 + } + ' | sort -Vu | tail -n 1)" + test -n "$ndk_package" || { echo "Stable NDK r30 is unavailable" >&2; exit 1; } + "$sdkmanager" --channel=0 "$ndk_package" + echo "ANDROID_NDK_HOME=$ANDROID_HOME/ndk/${ndk_package#ndk;}" >> "$GITHUB_ENV" + - uses: Swatinem/rust-cache@v2 + with: + key: pr-native-android-${{ hashFiles('scripts/src/vole_scripts/*.py', 'scripts/cmake/**', 'scripts/native/**') }} + workspaces: ". -> target" + env-vars: ImageOS ImageVersion ANDROID_NDK_HOME VOLE BORING AWS_LC LIBCLANG BINDGEN + cache-bin: "false" + - name: Build Android arm64 and x86_64 FFI + run: uv run --project scripts --locked vole-scripts build android diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e614808..267d7a1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -198,6 +198,9 @@ jobs: version: "0.13.6" - name: Locked source run: cargo fetch --locked + - name: Audit the official h2 dependency + if: matrix.name == 'ffi-linux-amd64' + run: uv run --project scripts --locked python -m vole_scripts.h2_source - name: Linux native dependencies if: matrix.platform == 'linux' run: | diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 6365e61..e5f2fbf 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -18,19 +18,15 @@ env: jobs: client-contracts: - name: ${{ matrix.name }} + name: ${{ fromJSON('{"debug":"Core (Debug)","release":"Core (Release)","features":"Quality"}')[matrix.profile] }} runs-on: ubuntu-26.04 timeout-minutes: 90 strategy: fail-fast: false matrix: - include: - - name: Core (Debug) - profile: debug - - name: Core (Release) - profile: release - - name: Quality - profile: features + profile: >- + ${{ fromJSON(github.event_name == 'pull_request' + && '["debug","features"]' || '["debug","release","features"]') }} steps: - uses: actions/checkout@v7 - uses: dtolnay/rust-toolchain@stable @@ -132,7 +128,8 @@ jobs: for spec in boring_specs: require(spec.get("git") == boring_repository and spec.get("rev") == boring_revision and not {"path", "branch", "tag"} & spec.keys(), "Boring dependencies and patches must share one Git commit source") boring_source = f"git+{boring_repository}?rev={boring_revision}#{boring_revision}" - require(not (workspace_root / "vendor").exists(), "Core vendor sources are forbidden") + from vole_scripts.h2_source import audit_h2_source + audit_h2_source(workspace_root, metadata) require(not (workspace_root / "crates" / "vole-blake3-raw" / "vendor").exists(), "BLAKE3 must use the installed official C library") native_manifest = json.loads((workspace_root / "scripts" / "native" / "blake3" / "vcpkg.json").read_text(encoding="utf-8")) require(native_manifest.get("builtin-baseline") == "9eec002df1cd109f8f104cd966a763daf9751489", "unapproved official BLAKE3 C registry baseline") @@ -196,7 +193,7 @@ jobs: package("ml-kem", "0.3.4") native = {} for name, required in (("boring", {"reality", "client-fingerprint", "shadow-tls-v3", "jls"}), ("boring-sys", {"reality", "shadow-tls-v3", "jls"}), ("tokio-boring", set())): - item = package(name, "5.4.0", {boring_source}) + item = package(name, "5.5.1", {boring_source}) native[name] = item require(required <= features(item), f"{name} is missing required TLS features") require(not features(item) & {"fips", "fips-precompiled", "rpk", "pq-experimental", "restls"}, f"{name} enables an unapproved TLS mode") @@ -223,11 +220,6 @@ jobs: if: matrix.profile == 'features' run: | cargo test --locked -p vole-blake3-raw - - name: H3 memory fixtures - if: matrix.profile == 'features' - run: | - cargo test --locked --features cli --lib transport::quiche_h3::tests:: - cargo test --locked --features cli --lib transport::quinn_h3::tests:: - name: Production and netstack clippy if: matrix.profile == 'features' run: | @@ -235,7 +227,7 @@ jobs: cargo clippy --locked --no-default-features --features cli --lib --bin vole -- -D warnings cargo clippy --locked --all-features --lib --bins -- -D warnings cargo clippy --locked --manifest-path crates/vole-netstack/Cargo.toml --all-targets -- -D warnings - - name: Run memory-only ${{ matrix.name }} + - name: Run memory-only core tests if: matrix.profile != 'features' shell: bash env: @@ -272,7 +264,7 @@ jobs: # Keep this explicit allowlist: unfiltered legacy tests may open host listeners. filters=( geodata:: routing:: security:: outbound::vless::encryption config:: - connections::tests:: routing::diagnostics::tests:: dialer::connections::tests:: + connections::tests:: polled_datagram_ resource::http::tests:: fake_ip_ sniffing::tests:: tcp_sniffer::tests:: resource::age_provider::tests:: resource::bundle::tests:: resource::bundle_limits::tests:: @@ -285,9 +277,11 @@ jobs: controller_secure_ outbound::http::tests:: outbound::wireguard::tests:: inbound::mixed::tests:: inbound::socks5::association::tests:: inbound::http::parser::tests:: inbound::http::framing::tests:: + http_processing::h2_frame_validation:: + h2_remote_goaway_moves_unsent_post_to_fresh_origin_without_interrupting_inflight_get outbound::hysteria2:: outbound::shadowsocks::tests::official_tcp_ outbound::anytls:: outbound::uot:: outbound::tuic:: transport::h2_write::tests:: - outbound::trusttunnel:: outbound::mieru:: outbound::masque:: security::masque:: config::masque:: + outbound::trusttunnel:: outbound::mieru:: outbound::masque:: transport::quic:: transport::quinn_h3:: transport::quiche_h3:: transport::masque_codec:: transport::h3_connect:: transport::smux::tests:: transport::sing_mux::tests:: grpc_duplex_pool_keeps_response @@ -333,7 +327,11 @@ jobs: ) for test_name in "${exact_tests[@]}"; do run_test 1 --lib "$test_name" -- --exact; done run_test 1 --test quic_datagram_foundations pending_send_is_not_restarted_and_stop_cancels_without_waiting_for_writable -- --exact - - name: Feature admission and complete compilation + - name: Compile all test targets + if: matrix.profile == 'debug' + # Historical listener fixtures must only be compiled on CI hosts. + run: cargo test --locked --all-features --all-targets --no-run + - name: Feature admission if: matrix.profile == 'features' shell: bash run: | @@ -354,7 +352,7 @@ jobs: cargo check --locked --no-default-features --features "outbound-$protocol" --lib run_test 1 --features "outbound-$protocol" --lib runtime::tests::integration_feature_admission_is_explicit_without_opening_sockets -- --exact done - for feature in outbound-http inbound-http inbound-socks5 stream-transport quic-transport quinn-h3-transport quiche-h3-transport dns-quic sing-mux shadow-tls-v3 tun invoke ffi cli windows-wintun windows-uwp; do + for feature in outbound-http inbound-http inbound-socks5 stream-transport quic-transport quinn-h3-transport quiche-h3-transport dns-quic sing-mux shadow-tls-v3 tun invoke ffi windows-wintun windows-uwp; do cargo check --locked --no-default-features --features "$feature" --lib done dns_graph="$(mktemp "$RUNNER_TEMP/vole-dns-graph.XXXXXX")" @@ -364,19 +362,20 @@ jobs: exit 1 fi rm -f "$dns_graph" - cargo check --locked --no-default-features --features cli --bin vole run_test 2 --test feature_foundations --test hysteria2_config cargo check --locked --lib - # Compilation only: historical listener fixtures must not execute on CI hosts. - cargo test --locked --all-features --all-targets --no-run - # The unified release matrix builds CLI and FFI with the unchanged - # production release profile, including both macOS targets. - name: Memory-only netstack tests if: matrix.profile == 'features' run: cargo test --locked --manifest-path crates/vole-netstack/Cargo.toml --all-targets + native-build: + name: Native + if: github.event_name == 'pull_request' + uses: ./.github/workflows/pr-native.yml + release-build: name: Build + if: github.event_name == 'push' # Reusable-workflow permissions are statically bounded by the caller, even # for skipped jobs. Build/assemble jobs downgrade to read; only a direct # release.yml tag push can execute the callee's write-permission publish job. diff --git a/AGENTS.md b/AGENTS.md index 2b51361..d7e86b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -29,7 +29,7 @@ Read the relevant document completely before changing that area: - Builds: `scripts/README.md`; `vole-scripts build` compiles platform outputs, and `vole_scripts.release` packages them for CI. - Offline regressions: `tests/README.md`. Rust memory/configuration tests remain in Vole; run explicit pure-memory filters, with all-target coverage limited to `--no-run`. - Protocol interoperability or pressure: isolated benchmark tooling owns container orchestration and fixtures. Supply the checkout explicitly with `--source vole=PATH`; Vole builds do not import it or infer workspace paths. Keep benchmark results, comparisons and conclusions in the benchmark project; Vole documents implementation contracts and acceptance criteria. Keep tooling repository addresses and raw runs outside Vole. -- Server-side tests: `docs/testing-isolation.md`. Use isolated benchmark containers for every server peer and network origin; container failure is not permission for a host fallback. +- Server-side tests: `docs/testing-isolation.md`. Use isolated benchmark containers for ordinary peers and origins; use its explicit native-Mac origin and socketpair diagnosis scopes only for the authorized Apple benchmark. Container failure does not expand those scopes. - Claims that something passed: `docs/acceptance.md`. Record only commands and environments actually executed; host tests and cross-builds do not prove physical-device data paths. # Architecture Boundaries @@ -54,10 +54,20 @@ Read the relevant document completely before changing that area: 5. Packaged Windows VPN uses official `Windows.Networking.Vpn` through `windows-rs`. `VpnPacketBuffer` bytes are copied within callbacks. After acquiring a framework buffer, return it to Windows before propagating any later local error; a return-API failure propagates the platform error and fails closed. Every framework buffer is returned exactly once. Network changes stop this path; they do not silently rebind or reconnect. 6. Reuse the existing raw-IP netstack, runtime and outbound graph. Windows WinRT VPN and desktop Wintun use separate platform adapters with the shared Dialer and synchronous stop barrier; Wintun's DLL and first-release network configuration are host-owned. Add no second Windows proxy core, per-protocol socket factory or fake fd layer. 7. Keep optional protocol/platform code feature- and target-gated. Default non-TUN builds must continue to compile. -8. When copying or modifying third-party source, record the upstream project and preserve all applicable license terms. Audit linked dependencies against the resolved release graph. Do not describe independent rewrites, protocol interoperability, or architectural references as derived source without evidence; Credits provide context and attribution, not a substitute for release license review. +8. Use official third-party releases through supported public APIs. Do not vendor, copy or embed third-party source in Vole, or modify or patch third-party source, without the user's explicit approval for that dependency and scope. The existing Boring exception is limited to the scope in `docs/tls-dependencies.md`; it does not authorize other dependencies or broader changes. Preserve upstream attribution and applicable license terms, and audit linked dependencies against the resolved release graph. Do not describe independent rewrites, protocol interoperability, or architectural references as derived source without evidence; Credits provide context and attribution, not a substitute for release license review. 9. Keep every public surface—code, documentation, tests, examples, commits, issues, pull requests, reviews, CI output, and releases—limited to Vole and public dependencies. Keep private downstream repository or product identities, links, implementation details, status, artifacts, and roadmaps outside this repository and its GitHub surfaces. Before publishing, search the staged diff and proposed GitHub text for downstream identifiers. 10. Make changes on a separate branch, never directly on `main`. -11. Use the official latest stable third-party dependencies, including test-only experiments. Check current non-prerelease, non-yanked releases when selecting or upgrading them; reference projects' old pins are not a version policy. Keep lockfiles for reproducible validation, refresh affected dependency audits, and rerun applicable tests. If freshness conflicts with the approved fork/provider or a platform's compatible dependency set, report the conflict and obtain an explicit exception or scope decision instead of silently retaining an old version or changing the security architecture. +11. Use the latest stable versions of third-party dependencies, including test-only experiments. Check current non-prerelease, non-yanked releases when selecting or upgrading them; reference projects' old pins are not a version policy. Keep lockfiles for reproducible validation, refresh affected dependency audits, and rerun applicable tests. If freshness conflicts with an explicitly approved dependency scope or a platform's compatible dependency set, report the conflict and obtain an explicit version exception or scope decision instead of silently retaining an old version or changing the security architecture. Version exceptions do not expand the source-change approvals in rule 8. + +## Commit messages + +- Write one English imperative sentence on a single line, without a body or final punctuation. +- Aim for 50 characters and keep the entire message within 72 characters. +- State the concrete change with a verb and its object; use one commit for one purpose. +- Keep type prefixes, ticket IDs, test results and benchmark numbers in their own records rather than the message. +- Commit each independent optimization after its relevant checks; preserve unsuccessful measurements in the benchmark records. + +Examples: `Reuse HTTP2 upstream connections`; `End empty HTTP2 requests in headers`. # Validation diff --git a/Cargo.lock b/Cargo.lock index 7222452..ed5b8aa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -134,6 +134,18 @@ dependencies = [ "alloc-no-stdlib", ] +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "antidote" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "307f1158c6f649671b2c5b2939b7513de520500dfe92913a49d5d313e44a6ee7" + [[package]] name = "anyhow" version = "1.0.104" @@ -404,8 +416,8 @@ dependencies = [ [[package]] name = "boring" -version = "5.4.0" -source = "git+https://github.com/YuanDevTeam/boring?rev=c717137e6c794a0b069f64686a375858ffc80818#c717137e6c794a0b069f64686a375858ffc80818" +version = "5.5.1" +source = "git+https://github.com/YuanDevTeam/boring?rev=11b94943426eebf365ace0e3eb70aa7a411a5463#11b94943426eebf365ace0e3eb70aa7a411a5463" dependencies = [ "bitflags 2.13.2", "boring-sys", @@ -418,8 +430,8 @@ dependencies = [ [[package]] name = "boring-sys" -version = "5.4.0" -source = "git+https://github.com/YuanDevTeam/boring?rev=c717137e6c794a0b069f64686a375858ffc80818#c717137e6c794a0b069f64686a375858ffc80818" +version = "5.5.1" +source = "git+https://github.com/YuanDevTeam/boring?rev=11b94943426eebf365ace0e3eb70aa7a411a5463#11b94943426eebf365ace0e3eb70aa7a411a5463" dependencies = [ "bindgen", "cmake", @@ -485,6 +497,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11aade7a05aa8c3a351cedc44c3fc45806430543382fcc4743a9b757a2a0b4ed" +[[package]] +name = "bytecount" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175812e0be2bccb6abe50bb8d566126198344f707e304f45c648fd8f2cc0365e" + [[package]] name = "byteorder" version = "1.5.0" @@ -497,6 +515,15 @@ version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" +[[package]] +name = "castaway" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dec551ab6e7578819132c713a93c022a05d60159dc86e7a7050223577484c55a" +dependencies = [ + "rustversion", +] + [[package]] name = "cc" version = "1.11.0" @@ -628,6 +655,19 @@ version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" +[[package]] +name = "compact_str" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79fcda08c33bb58b97008b2cdada6622500e949e060f5913361763121abd2416" +dependencies = [ + "castaway", + "cfg-if", + "itoa", + "static_assertions", + "zmij", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -677,6 +717,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" +[[package]] +name = "cow-utils" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417bef24afe1460300965a25ff4a24b8b45ad011948302ec221e8a0a81eb2c79" + [[package]] name = "cpubits" version = "0.1.1" @@ -879,7 +925,7 @@ dependencies = [ "asn1-rs", "displaydoc", "nom", - "num-bigint", + "num-bigint 0.4.8", "num-traits", "rusticata-macros", ] @@ -1469,6 +1515,7 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" dependencies = [ + "allocator-api2", "foldhash", ] @@ -1745,11 +1792,32 @@ checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" dependencies = [ "displaydoc", "litemap", + "serde", "tinystr", "writeable", "zerovec", ] +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + [[package]] name = "icu_normalizer" version = "2.4.0" @@ -1799,6 +1867,8 @@ checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" dependencies = [ "displaydoc", "icu_locale_core", + "serde", + "stable_deref_trait", "writeable", "yoke", "zerofrom", @@ -1806,6 +1876,29 @@ dependencies = [ "zerovec", ] +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + [[package]] name = "idna" version = "1.1.0" @@ -2063,6 +2156,21 @@ version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" +[[package]] +name = "linked-hash-map" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f" + +[[package]] +name = "linked_hash_set" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "984fb35d06508d1e69fc91050cceba9c0b748f983e6739fa2c7a9237154c52c8" +dependencies = [ + "linked-hash-map", +] + [[package]] name = "linux-raw-sys" version = "0.12.1" @@ -2142,6 +2250,15 @@ version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + [[package]] name = "memoffset" version = "0.9.1" @@ -2352,6 +2469,12 @@ dependencies = [ "minimal-lexical", ] +[[package]] +name = "nonmax" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "610a5acd306ec67f907abe5567859a3c693fb9886eb1f012ab8f2a47bef3db51" + [[package]] name = "num-bigint" version = "0.4.8" @@ -2362,6 +2485,16 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-bigint-dig" version = "0.8.6" @@ -2476,6 +2609,193 @@ dependencies = [ "cc", ] +[[package]] +name = "oxc_allocator" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ec74ff7b9107ea8cfee79737b7eff78cc38aa8ba9866ba68ccec5fa1aff703" +dependencies = [ + "allocator-api2", + "hashbrown", + "oxc_data_structures", + "rustc-hash 2.1.3", +] + +[[package]] +name = "oxc_ast" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62cf69f854ebef3d2f8130e0882bd0970405a584cdf2f0325a936dbdad476106" +dependencies = [ + "bitflags 2.13.2", + "oxc_allocator", + "oxc_ast_macros", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_estree", + "oxc_regular_expression", + "oxc_span", + "oxc_str", + "oxc_syntax", +] + +[[package]] +name = "oxc_ast_macros" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddbddb57f889d6da3d4efb70e67249b2fd9e6767484d7b4d888adad0d48dfc04" +dependencies = [ + "phf", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "oxc_data_structures" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f5a93745ef56da781d571d2f1b73204b6cf798f43576371e025983eeb9a671c" + +[[package]] +name = "oxc_diagnostics" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58c6b5b618484b442fc5de6dc678f4897b3d7e72b38cb07525f7c9981d17e418" +dependencies = [ + "bytecount", + "cow-utils", + "itoa", + "memchr", + "oxc_span", + "percent-encoding", + "smallvec", + "textwrap", + "unicode-segmentation", + "unicode-width", +] + +[[package]] +name = "oxc_ecmascript" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db30ae962dfe1bf909976e4eecdc6912e95d033ee2f4a23d130277935d81cb8" +dependencies = [ + "itoa", + "memchr", + "num-bigint 0.5.1", + "num-traits", + "oxc_ast", + "oxc_data_structures", + "oxc_span", + "oxc_str", + "oxc_syntax", + "zmij_ecma", +] + +[[package]] +name = "oxc_estree" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c00eabcc7d5192186f18430cf9b715d308bd677d2c759555f340f54da63cab4d" + +[[package]] +name = "oxc_index" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "191884bee6c3744909a51acc7d78d4ae370d817b25875b10642f632327b6296e" +dependencies = [ + "nonmax", + "serde", +] + +[[package]] +name = "oxc_parser" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d575332e9df032cc25e781b2aa2d1c10fed2b592f46c8f159e4ae8798f5451b5" +dependencies = [ + "bitflags 2.13.2", + "cow-utils", + "memchr", + "num-bigint 0.5.1", + "num-traits", + "oxc_allocator", + "oxc_ast", + "oxc_data_structures", + "oxc_diagnostics", + "oxc_ecmascript", + "oxc_regular_expression", + "oxc_span", + "oxc_str", + "oxc_syntax", + "rustc-hash 2.1.3", + "seq-macro", +] + +[[package]] +name = "oxc_regular_expression" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27d21be07f700bbcb2a5ed58ae19bf04e4ffe0a165e883eb87190756c7e4652" +dependencies = [ + "bitflags 2.13.2", + "oxc_allocator", + "oxc_ast_macros", + "oxc_diagnostics", + "oxc_span", + "oxc_str", + "phf", + "rustc-hash 2.1.3", + "unicode-id-start", +] + +[[package]] +name = "oxc_span" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f95c05b5dffdef9921037eee90b4b79762cf5dab1fb2daa380253cbf3f053a49" +dependencies = [ + "compact_str", + "oxc_allocator", + "oxc_ast_macros", + "oxc_estree", + "oxc_str", +] + +[[package]] +name = "oxc_str" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b840f3ac441b53e08f49c8f63349fa24ae4b943886a54f28a885ba36cf125af4" +dependencies = [ + "compact_str", + "hashbrown", + "memchr", + "oxc_allocator", + "oxc_estree", +] + +[[package]] +name = "oxc_syntax" +version = "0.157.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f5c900d06effaaca788faba9558bc5520d9de9c6b2bcdc708875751b04db59c" +dependencies = [ + "bitflags 2.13.2", + "cow-utils", + "nonmax", + "oxc_allocator", + "oxc_ast_macros", + "oxc_estree", + "oxc_index", + "oxc_span", + "oxc_str", + "phf", + "unicode-id-start", + "zmij_ecma", +] + [[package]] name = "p256" version = "0.14.0" @@ -2556,6 +2876,49 @@ version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -2662,6 +3025,8 @@ version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" dependencies = [ + "serde_core", + "writeable", "zerovec", ] @@ -3308,6 +3673,12 @@ dependencies = [ "tokio", ] +[[package]] +name = "seq-macro" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bc711410fbe7399f390ca1c3b60ad0f53f80e95c5eb935e52268a0e2cd49acc" + [[package]] name = "serde" version = "1.0.229" @@ -3545,6 +3916,12 @@ version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + [[package]] name = "slab" version = "0.4.12" @@ -3556,6 +3933,15 @@ name = "smallvec" version = "1.16.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" +dependencies = [ + "serde", +] + +[[package]] +name = "smawk" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8e2fb0f499abb4d162f2bedad68f5ef91a1682b5a03596ddb67efd37768d100" [[package]] name = "smoltcp" @@ -3708,6 +4094,17 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "textwrap" +version = "0.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ecfad6c3abc80a577f2b91c1e412ee57e7a060d430b553c1b0c940974ebcd49" +dependencies = [ + "icu_segmenter", + "smawk", + "unicode-width", +] + [[package]] name = "thiserror" version = "1.0.69" @@ -3814,11 +4211,13 @@ dependencies = [ [[package]] name = "tokio-boring" -version = "5.4.0" -source = "git+https://github.com/YuanDevTeam/boring?rev=c717137e6c794a0b069f64686a375858ffc80818#c717137e6c794a0b069f64686a375858ffc80818" +version = "5.5.1" +source = "git+https://github.com/YuanDevTeam/boring?rev=11b94943426eebf365ace0e3eb70aa7a411a5463#11b94943426eebf365ace0e3eb70aa7a411a5463" dependencies = [ + "antidote", "boring", "boring-sys", + "linked_hash_set", "tokio", ] @@ -4036,12 +4435,30 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" +[[package]] +name = "unicode-id-start" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0825d2e09dcae814a4273c1e1435979d414ede25b2ee235b1545da6682483765" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-width" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca718471876992059f251e33aafc334346ada08042b7661dd1fe313a9bced557" + [[package]] name = "universal-hash" version = "0.5.1" @@ -4171,7 +4588,12 @@ dependencies = [ "libc", "maxminddb", "md-5", + "memmap2", "oslog", + "oxc_allocator", + "oxc_ast", + "oxc_parser", + "oxc_span", "prost", "psl", "quiche", @@ -4236,6 +4658,7 @@ version = "0.1.0" dependencies = [ "bytes", "futures-util", + "memmap2", "smoltcp", "thiserror 2.0.21", "tokio", @@ -4957,6 +5380,7 @@ dependencies = [ "displaydoc", "yoke", "zerofrom", + "zerovec", ] [[package]] @@ -4988,6 +5412,12 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" +[[package]] +name = "zmij_ecma" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "458b3e7a977f14499066b6bdb63d69da30ce337d6c160f077e6c575c82a44db9" + [[package]] name = "zstd" version = "0.14.3" diff --git a/Cargo.toml b/Cargo.toml index 3d32002..09a3547 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -49,7 +49,8 @@ default = [ "shadow-tls-v3", "sing-mux", ] -inbound-http = ["dep:rcgen", "rcgen/x509-parser", "dep:rsa", "dep:tokio-tungstenite", "dep:hyper", "dep:hyper-util", "dep:x509-parser"] +inbound-http = ["dep:memmap2", "dep:rcgen", "rcgen/x509-parser", "dep:rsa", "dep:tokio-tungstenite", "dep:hyper", "dep:hyper-util", "dep:x509-parser", "dep:oxc_allocator", "dep:oxc_ast", "dep:oxc_parser", "dep:oxc_span", "tokio/rt-multi-thread"] +http-diagnostics = ["inbound-http", "vole-netstack?/diagnostics"] inbound-socks5 = ["dep:rcgen", "dep:rsa", "dep:ring", "dep:tokio-tungstenite"] outbound-anytls = ["dep:md-5", "stream-security", "ech"] outbound-socks5 = [] @@ -105,6 +106,10 @@ tun = [ ] [dependencies] +oxc_allocator = { version = "=0.157.0", optional = true } +oxc_ast = { version = "=0.157.0", optional = true } +oxc_parser = { version = "=0.157.0", optional = true } +oxc_span = { version = "=0.157.0", optional = true } age = { version = "=0.11.5", default-features = false, features = ["armor"] } age-core = "=0.11.0" aes = { version = "0.9.4", optional = true, features = ["zeroize"] } @@ -115,7 +120,7 @@ bech32 = "=0.12.0" blake2 = { version = "=0.11.0", optional = true } blake3 = { version = "=1.8.7", optional = true } boringtun = { version = "=0.7.1", default-features = false, optional = true } -boring = { git = "https://github.com/YuanDevTeam/boring", rev = "c717137e6c794a0b069f64686a375858ffc80818", version = "=5.4.0", features = ["client-fingerprint"], optional = true } +boring = { git = "https://github.com/YuanDevTeam/boring", rev = "11b94943426eebf365ace0e3eb70aa7a411a5463", version = "=5.5.1", features = ["client-fingerprint"], optional = true } bytes = "1" chacha20poly1305 = { version = "=0.11.0", default-features = false, features = ["zeroize"], optional = true } crc32fast = "=1.5.4" @@ -165,7 +170,7 @@ socket2 = { version = "0.6", features = ["all"] } thiserror = "2" time = { version = "=0.3.55", features = ["formatting"] } tokio = { version = "1", features = ["io-util", "macros", "net", "rt", "sync", "time"] } -tokio-boring = { git = "https://github.com/YuanDevTeam/boring", rev = "c717137e6c794a0b069f64686a375858ffc80818", version = "=5.4.0", optional = true } +tokio-boring = { git = "https://github.com/YuanDevTeam/boring", rev = "11b94943426eebf365ace0e3eb70aa7a411a5463", version = "=5.5.1", optional = true } tokio-rustls = { version = "=0.26.6", default-features = false, features = ["ring", "tls12"] } tokio-tungstenite = { version = "=0.30.0", default-features = false, features = ["handshake"], optional = true } tokio-util = { version = "0.7", features = ["rt"] } @@ -191,6 +196,8 @@ tokio-tfo = "=0.4.3" tun-rs = { version = "=2.8.16", default-features = false, features = ["address-management"] } [target.'cfg(unix)'.dependencies] +# Safe anonymous backing for selected large, fixed-bound byte outputs. +memmap2 = { version = "=0.9.12", optional = true } # Keep one Cargo dependency name across target tables. Unix compiles this small # adapter dependency; platform I/O remains gated by the tun feature. tun-rs = { version = "=2.8.16", default-features = false } @@ -234,7 +241,7 @@ h3 = { version = "=0.0.8", default-features = false } h3-quinn = { version = "=0.0.10", default-features = false } sevenz-rust2 = { version = "=0.24.2", default-features = false, features = ["compress"] } # Native peer controls for bounded in-memory ALPS tests; same source as boring. -boring-sys = { git = "https://github.com/YuanDevTeam/boring", rev = "c717137e6c794a0b069f64686a375858ffc80818", version = "=5.4.0" } +boring-sys = { git = "https://github.com/YuanDevTeam/boring", rev = "11b94943426eebf365ace0e3eb70aa7a411a5463", version = "=5.5.1" } foreign-types = "=0.5.0" tokio = { version = "1", features = ["test-util"] } # Independent EIH relay fixture only; production crypto remains the official SS crate. @@ -267,5 +274,5 @@ pedantic = "allow" [patch.crates-io] # quiche and Vole share the same approved Boring commit. -boring = { git = "https://github.com/YuanDevTeam/boring", rev = "c717137e6c794a0b069f64686a375858ffc80818" } -boring-sys = { git = "https://github.com/YuanDevTeam/boring", rev = "c717137e6c794a0b069f64686a375858ffc80818" } +boring = { git = "https://github.com/YuanDevTeam/boring", rev = "11b94943426eebf365ace0e3eb70aa7a411a5463" } +boring-sys = { git = "https://github.com/YuanDevTeam/boring", rev = "11b94943426eebf365ace0e3eb70aa7a411a5463" } diff --git a/README.md b/README.md index 67538be..d3889ae 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,7 @@ Vole builds on and learns from public dependencies, protocol implementations and - TUN dependencies: the local [`vole-netstack`](crates/vole-netstack/README.md) uses [smoltcp](https://github.com/smoltcp-rs/smoltcp); Unix and Windows Wintun packet I/O use [tun-rs](https://github.com/tun-rs/tun-rs) (Apache-2.0). - Provider case mapping uses Rust's standard Unicode case conversion through a bounded adapter. +- HTTP/2 uses a reviewed local copy of [h2](https://github.com/hyperium/h2) 0.4.20 (MIT), with a per-instance initial-write allocation hint. The unchanged [upstream notice](vendor/h2/LICENSE), [source provenance and patch](scripts/native/h2/README.md) accompany the modified source; the default remains 16 KiB. - WireGuard: [boringtun](https://github.com/cloudflare/boringtun) (BSD-3-Clause), without host-device, FFI or JNI features. - [Wintun](https://www.wintun.net/): the runtime DLL is supplied by the host, not bundled. The upstream [API header](https://github.com/tun-rs/tun-rs/blob/2.8.11/src/platform/windows/tun/wintun.h) included by tun-rs is copyright 2018–2021 WireGuard LLC, licensed `GPL-2.0 OR MIT`; distribution of the linked API bindings must retain its copyright and MIT alternative license notice. - Offline archives: [sevenz-rust2](https://github.com/hasenbanck/sevenz-rust2) and [lzma-rust2](https://github.com/hasenbanck/lzma-rust2) (Apache-2.0), used through a bounded member reader. diff --git a/crates/vole-netstack/Cargo.toml b/crates/vole-netstack/Cargo.toml index 961eecb..e0996c3 100644 --- a/crates/vole-netstack/Cargo.toml +++ b/crates/vole-netstack/Cargo.toml @@ -6,9 +6,14 @@ publish = false license = "MIT" description = "Bounded userspace IPv4/IPv6 TCP and UDP netstack for Vole" +[features] +default = [] +diagnostics = [] + [dependencies] bytes = "1" futures-util = "0.3" +memmap2 = "=0.9.12" # Upstream recovery fixes preserve retries when bounded packet output is full. smoltcp = { git = "https://github.com/smoltcp-rs/smoltcp", rev = "24bda3b4f982625d8453d4360172557d24921c76", default-features = false, features = [ "std", diff --git a/crates/vole-netstack/README.md b/crates/vole-netstack/README.md index 0da7b71..e5a6b51 100644 --- a/crates/vole-netstack/README.md +++ b/crates/vole-netstack/README.md @@ -58,6 +58,11 @@ fragment or IPv6 extension-header validation. Encoding emits checksums, reuses the caller's `Vec`, and leaves it unchanged on address-family or MTU errors. UDP mistakenly sent into the TCP-only driver is ignored. +The optional `diagnostics` feature exposes `NetStack::start_tcp_observed`. +Its synchronous, nonblocking, nonpanicking callback reports completed drive passes, +entries visited, bytes moved, and ingress, notification, or timer wake counts. +Observations contain counters and wake sources only and use the existing stop barrier. + ## Generic TCP and UDP API ```rust,ignore @@ -132,6 +137,13 @@ budgets, increases, expired deadlines or an already started TCP flow fail. ## Driver buffering and scheduling +On macOS, a TCP write or flush that remains pending after registering its +waker and rechecking the queue does not request another driver pass. Successful +reads and writes, shutdown, Drop, packet ingress, output-capacity recovery and +protocol timers retain their existing wakeups. Flush still completes when the +application send queue is empty, without waiting for remote acknowledgement. +Other targets retain their existing pending-write and pending-flush wakeups. + TCP uses the official unmodified smoltcp engine. Active clients initialize its device with the known transport MTU; callers should use their actual packet budget when available. ICMP feedback cannot change smoltcp's socket MSS. diff --git a/crates/vole-netstack/src/config.rs b/crates/vole-netstack/src/config.rs index cca0402..aa21250 100644 --- a/crates/vole-netstack/src/config.rs +++ b/crates/vole-netstack/src/config.rs @@ -34,6 +34,10 @@ pub struct NetStackConfig { /// Must be even and at least 4096 bytes, split equally between smoltcp and /// the application-facing receive queue. pub tcp_recv_buffer: usize, + /// Opt in to a Driver-owned empty-mapping cache for the application RX + /// queue on Unix. The smoltcp array and all logical byte limits are + /// unchanged. Defaults false; unsupported targets keep bounded Vec storage. + pub map_tcp_recv_buffer: bool, /// Total send bytes per TCP flow, from `TcpStream::AsyncWrite` to raw IP. /// /// Must be even and at least 4096 bytes, split equally between smoltcp and @@ -58,6 +62,7 @@ impl Default for NetStackConfig { tcp_accept_queue: 32, udp_queue: 128, tcp_recv_buffer: 32 * 1024, + map_tcp_recv_buffer: false, tcp_send_buffer: 32 * 1024, tcp_idle_timeout: Duration::from_mins(2), max_poll_interval: Duration::from_millis(100), @@ -159,6 +164,7 @@ mod tests { assert_eq!(config.tcp_accept_queue, 32); assert_eq!(config.udp_queue, 128); assert_eq!(config.tcp_recv_buffer, 32 * 1024); + assert!(!config.map_tcp_recv_buffer); assert_eq!(config.tcp_send_buffer, 32 * 1024); assert_eq!(config.recv_layer_buffer_size(), 16 * 1024); assert_eq!(config.send_layer_buffer_size(), 16 * 1024); diff --git a/crates/vole-netstack/src/device.rs b/crates/vole-netstack/src/device.rs index e17ea08..c5dac65 100644 --- a/crates/vole-netstack/src/device.rs +++ b/crates/vole-netstack/src/device.rs @@ -253,20 +253,25 @@ impl TxToken for RawTxToken<'_> { if let Some(paths) = self.path_mtu.as_mut() { // Metadata parsing is limited to trusted smoltcp output. Packets // within the path budget keep their allocation and byte contents. - if let Some(mut pending) = PendingSegments::new(packet.clone()) { - let budget = paths.budget(pending.flow(), self.mtu); - if packet.len() > budget { - let Some(first) = pending.next(budget) else { - return result; - }; - packet = first; - if !pending.is_finished() { - *self.pending = Some(PendingTransmit::Segments(pending)); + // Before a path reduction, an in-MTU packet cannot need splitting. + // Avoid promoting its Bytes owner to shared just to inspect it. + // The emitted metadata below still authorizes the first real hint. + if packet.len() > self.mtu || paths.has_reductions() { + if let Some(mut pending) = PendingSegments::new(packet.clone()) { + let budget = paths.budget(pending.flow(), self.mtu); + if packet.len() > budget { + let Some(first) = pending.next(budget) else { + return result; + }; + packet = first; + if !pending.is_finished() { + *self.pending = Some(PendingTransmit::Segments(pending)); + } } + } else if packet.len() > self.mtu { + // No UDP boundary splitting or implicit IP fragmentation. + return result; } - } else if packet.len() > self.mtu { - // No UDP boundary splitting or implicit IP fragmentation. - return result; } paths.emitted(&packet); } @@ -556,4 +561,72 @@ mod tests { .consume(packet.len(), |bytes| bytes.copy_from_slice(packet.data())); assert_eq!(receiver.try_recv().unwrap().len(), packet.len()); } + + #[test] + fn no_learned_path_still_enforces_initial_mtu_and_drops_unsupported_oversize() { + use crate::segmentation::tests::tcp_packet; + for ipv6 in [false, true] { + let flow = if ipv6 { + FlowKey { + source: "[2001:db8::2]:4000".parse().unwrap(), + destination: "[2001:db8:1::2]:443".parse().unwrap(), + } + } else { + FlowKey { + source: "10.23.0.2:4000".parse().unwrap(), + destination: "198.51.100.2:443".parse().unwrap(), + } + }; + let (output, mut receiver) = mpsc::channel(1); + let mut device = RawIpDevice::new(1500, output); + device.enable_path_mtu(); + let original = tcp_packet(flow, 1000, 91, 16, 4000); + device + .transmit(Instant::now()) + .unwrap() + .consume(original.len(), |bytes| { + bytes.copy_from_slice(original.data()); + }); + let header_length = (if ipv6 { 40 } else { 24 }) + 32; + let mut observed = Vec::new(); + let mut emitted_packets = 0_u64; + for _ in 0..8 { + let packet = receiver.try_recv().unwrap(); + assert!(packet.len() <= 1500); + assert!(packet.len() > header_length); + observed.extend_from_slice(&packet.data()[header_length..]); + emitted_packets += 1; + if device.pending_tx.is_none() { + break; + } + device.flush_pending(); + } + assert!(device.pending_tx.is_none(), "bounded split did not finish"); + assert!(emitted_packets >= 3); + assert_eq!(observed, original.data()[header_length..]); + assert!(!device.path_mtu.as_ref().unwrap().has_reductions()); + + let mut unsupported = original.data().to_vec(); + if ipv6 { + unsupported[6] = 17; // Not TCP; no UDP/IP fragmentation is invented. + } else { + unsupported[9] = 17; + smoltcp::wire::Ipv4Packet::new_unchecked(&mut unsupported).fill_checksum(); + } + device + .transmit(Instant::now()) + .unwrap() + .consume(unsupported.len(), |bytes| { + bytes.copy_from_slice(&unsupported); + }); + assert!(matches!( + receiver.try_recv(), + Err(mpsc::error::TryRecvError::Empty) + )); + assert!(device.pending_tx.is_none()); + assert_eq!(device.emitted(), emitted_packets); + device.clear(); + assert!(device.path_mtu.is_none()); + } + } } diff --git a/crates/vole-netstack/src/diagnostics.rs b/crates/vole-netstack/src/diagnostics.rs new file mode 100644 index 0000000..72d7e82 --- /dev/null +++ b/crates/vole-netstack/src/diagnostics.rs @@ -0,0 +1,20 @@ +//! Default-off, integer-only observations for an explicitly observed passive stack. +//! The callback is synchronous, nonblocking and must not panic or perform I/O. + +/// One completed driver pass or one selected normal wait result. +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub enum DriverObservation { + DrivePass { + tcp_entry_visits: u64, + app_rx_bytes: u64, + app_tx_bytes: u64, + /// No app bytes moved and no packet emitted; protocol state may progress. + no_data_progress: bool, + }, + WaitIngress, + WaitNotify, + WaitTimer, +} + +/// A plain function pointer, carrying no traffic, task, queue or runtime owner. +pub type DriverObserver = fn(DriverObservation); diff --git a/crates/vole-netstack/src/lib.rs b/crates/vole-netstack/src/lib.rs index 08e74ae..c773e3e 100644 --- a/crates/vole-netstack/src/lib.rs +++ b/crates/vole-netstack/src/lib.rs @@ -8,6 +8,8 @@ mod client; mod config; mod device; +#[cfg(feature = "diagnostics")] +pub mod diagnostics; mod echo; mod icmp; mod packet; diff --git a/crates/vole-netstack/src/packet_recover_memory_tests.rs b/crates/vole-netstack/src/packet_recover_memory_tests.rs new file mode 100644 index 0000000..920f1be --- /dev/null +++ b/crates/vole-netstack/src/packet_recover_memory_tests.rs @@ -0,0 +1,108 @@ +use super::*; +use futures_util::task::noop_waker; +use std::{future::Future, task::Context}; + +fn fixture() -> (PacketSink, mpsc::Receiver, CancellationToken) { + let (sender, receiver) = mpsc::channel(32); + let cancellation = CancellationToken::new(); + ( + PacketSink { + sender, + cancellation: cancellation.clone(), + mtu: 1408, + }, + receiver, + cancellation, + ) +} +fn packet(id: u8) -> Packet { + let mut bytes = vec![0x45; 40]; + bytes[1] = id; + Packet::new(bytes) +} + +#[tokio::test(flavor = "current_thread")] +async fn packet_recover_returns_same_full_owner_and_persistent_send_keeps_fifo() { + let (sink, mut receiver, _) = fixture(); + for id in 0..32 { + sink.try_send_recover(packet(id)).unwrap(); + } + let original = packet(32); + let address = original.data().as_ptr(); + let (error, recovered) = sink.try_send_recover(original).unwrap_err(); + assert!(matches!(error, NetStackError::Backpressure)); + assert_eq!(recovered.data().as_ptr(), address); + let mut first = Box::pin(sink.send(recovered)); + let mut second = Box::pin(sink.send(packet(33))); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!(first.as_mut().poll(&mut cx).is_pending()); + assert!(second.as_mut().poll(&mut cx).is_pending()); + // Re-polling wrappers must not replace first's actual semaphore waiter. + for _ in 0..3 { + assert!(first.as_mut().poll(&mut cx).is_pending()); + } + assert_eq!(receiver.try_recv().unwrap().data()[1], 0); + assert!(second.as_mut().poll(&mut cx).is_pending()); + assert!(matches!(first.as_mut().poll(&mut cx), Poll::Ready(Ok(())))); + drop(first); + assert_eq!(receiver.try_recv().unwrap().data()[1], 1); + assert!(matches!(second.as_mut().poll(&mut cx), Poll::Ready(Ok(())))); + drop(second); + for id in 2..34 { + assert_eq!(receiver.try_recv().unwrap().data()[1], id); + } + assert!(receiver.try_recv().is_err()); +} + +#[tokio::test(flavor = "current_thread")] +async fn packet_recover_validation_closed_and_cancel_return_original_packet() { + let (sink, receiver, cancellation) = fixture(); + for original in [ + Packet::new(Vec::new()), + Packet::new(vec![0; 40]), + Packet::new(vec![0x45; 1409]), + ] { + let expected = original.clone(); + let (error, returned) = sink.try_send_recover(original).unwrap_err(); + assert!(!matches!( + error, + NetStackError::Backpressure | NetStackError::Stopped + )); + assert_eq!(returned, expected); + } + drop(receiver); + let original = packet(1); + let address = original.data().as_ptr(); + let (error, returned) = sink.try_send_recover(original).unwrap_err(); + assert!(matches!(error, NetStackError::Stopped)); + assert_eq!(returned.data().as_ptr(), address); + cancellation.cancel(); + let original = packet(2); + let expected = original.clone(); + let (error, returned) = sink.try_send_recover(original).unwrap_err(); + assert!(matches!(error, NetStackError::Stopped)); + assert_eq!(returned, expected); +} + +#[tokio::test(flavor = "current_thread")] +async fn packet_recover_pending_send_cancel_precedes_simultaneously_ready_capacity() { + let (sink, mut receiver, cancellation) = fixture(); + for id in 0..32 { + sink.try_send(packet(id)).unwrap(); + } + let mut admission = Box::pin(sink.send(packet(99))); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!(admission.as_mut().poll(&mut cx).is_pending()); + receiver.try_recv().unwrap(); + cancellation.cancel(); + assert!(matches!( + admission.as_mut().poll(&mut cx), + Poll::Ready(Err(NetStackError::Stopped)) + )); + drop(admission); + while let Ok(value) = receiver.try_recv() { + assert_ne!(value.data()[1], 99); + } +} diff --git a/crates/vole-netstack/src/segmentation.rs b/crates/vole-netstack/src/segmentation.rs index 8104d08..48f627f 100644 --- a/crates/vole-netstack/src/segmentation.rs +++ b/crates/vole-netstack/src/segmentation.rs @@ -182,6 +182,11 @@ pub(crate) struct PathMtu { } impl PathMtu { + /// With no learned path, every flow still uses the interface MTU. + pub(crate) fn has_reductions(&self) -> bool { + !self.paths.is_empty() + } + pub(crate) fn emitted(&mut self, packet: &Packet) { let Some(view) = TcpView::parse(packet.data(), false) else { return; diff --git a/crates/vole-netstack/src/stack.rs b/crates/vole-netstack/src/stack.rs index 027233a..3e06ca7 100644 --- a/crates/vole-netstack/src/stack.rs +++ b/crates/vole-netstack/src/stack.rs @@ -1,10 +1,12 @@ use std::{ collections::{HashMap, HashSet}, + future::poll_fn, net::{IpAddr, SocketAddr}, sync::{ Arc, atomic::{AtomicUsize, Ordering}, }, + task::Poll, time::Duration, }; @@ -28,12 +30,22 @@ use crate::{ icmp::{IcmpIngress, classify as classify_icmp}, pmtu::parse_path_mtu_hint, tcp::{ - ClientRequest, ConnectRequest, FlowKey, InitialMtuRequest, TcpConnector, TcpListener, - TcpStream, TcpStreamHandle, connect_stopped, connect_timeout, + ClientRequest, ConnectRequest, FlowKey, InitialMtuRequest, MapCache, TcpConnector, + TcpListener, TcpStream, TcpStreamHandle, connect_stopped, connect_timeout, }, udp::{UdpDatagram, UdpSocket, parse_udp_packet}, }; +#[cfg(feature = "diagnostics")] +type MaintenanceObservation = [u64; 3]; +#[cfg(not(feature = "diagnostics"))] +type MaintenanceObservation = (); + +#[cfg(feature = "diagnostics")] +fn add_observed_count(total: &mut u64, count: usize) { + *total = total.saturating_add(u64::try_from(count).unwrap_or(u64::MAX)); +} + const RAW_INGRESS_BATCH: usize = 8; const TCP_CONNECT_QUEUE: usize = 32; const EPHEMERAL_PORT_START: u16 = 49_152; @@ -124,7 +136,14 @@ impl NetStack { /// Returns [`NetStackError::Config`] for inconsistent bounds and /// [`NetStackError::NoRuntime`] when called outside a Tokio runtime. pub fn start(config: NetStackConfig) -> Result { - Self::start_parts(config, true, None).map(DriverParts::into_stack) + Self::start_parts( + config, + true, + None, + #[cfg(feature = "diagnostics")] + None, + ) + .map(DriverParts::into_stack) } /// Starts only the TCP/ICMP driver; callers handle UDP with the pure codec. @@ -133,7 +152,27 @@ impl NetStack { /// /// Returns the same configuration and runtime errors as [`Self::start`]. pub fn start_tcp(config: NetStackConfig) -> Result { - Self::start_parts(config, false, None).map(DriverParts::into_tcp) + Self::start_parts( + config, + false, + None, + #[cfg(feature = "diagnostics")] + None, + ) + .map(DriverParts::into_tcp) + } + + /// Starts passive TCP with an integer-only diagnostic observer. + /// + /// # Errors + /// + /// Returns the same configuration and runtime errors as [`Self::start`]. + #[cfg(feature = "diagnostics")] + pub fn start_tcp_observed( + config: NetStackConfig, + observer: crate::diagnostics::DriverObserver, + ) -> Result { + Self::start_parts(config, false, None, Some(observer)).map(DriverParts::into_tcp) } /// Starts active TCP using only the supplied local IP addresses. @@ -150,13 +189,21 @@ impl NetStack { addresses: impl Into, ) -> Result { let addresses = addresses.into().validate(config.mtu)?; - Self::start_parts(config, false, Some(addresses)).map(DriverParts::into_client) + Self::start_parts( + config, + false, + Some(addresses), + #[cfg(feature = "diagnostics")] + None, + ) + .map(DriverParts::into_client) } fn start_parts( config: NetStackConfig, with_udp: bool, addresses: Option, + #[cfg(feature = "diagnostics")] observer: Option, ) -> Result { if let Some(client) = &addresses { config.validate_client(client)?; @@ -229,6 +276,10 @@ impl NetStack { stats.clone(), stopped_tx, ); + #[cfg(feature = "diagnostics")] + { + driver.observer = observer; + } if let Some(client) = client { driver.configure_client(&client.addresses); driver.client = Some(client); @@ -290,6 +341,27 @@ impl PacketSink { } } + /// Tries raw ingress while returning the original packet on every error. + /// + /// This reserves no extra capacity. Callers may keep at most their own + /// explicit bounded pending packet and drive readiness outside callbacks. + /// + /// # Errors + /// + /// Returns the same errors as [`Self::try_send`] together with the packet. + pub fn try_send_recover(&self, packet: Packet) -> Result<(), (NetStackError, Packet)> { + if self.cancellation.is_cancelled() { + return Err((NetStackError::Stopped, packet)); + } + if let Err(error) = validate_raw_packet(&packet, self.mtu) { + return Err((error, packet)); + } + self.sender.try_send(packet).map_err(|error| match error { + mpsc::error::TrySendError::Full(packet) => (NetStackError::Backpressure, packet), + mpsc::error::TrySendError::Closed(packet) => (NetStackError::Stopped, packet), + }) + } + /// Non-blocking ingress used by edge-triggered TUN adapters. /// /// # Errors @@ -525,6 +597,10 @@ struct Driver { sockets: SocketSet<'static>, tcp_entries: HashMap, half_open: HashSet, + tx_map_cache: Arc, + rx_map_cache: Option>, + #[cfg(feature = "diagnostics")] + observer: Option, } impl Driver { @@ -569,6 +645,13 @@ impl Driver { .add_default_ipv6_route(Ipv6Address::new(0xfd00, 0x5643, 0x6f72, 0x6500, 0, 0, 0, 1)) .expect("smoltcp IPv6 route capacity"); + let tx_map_cache = Arc::new(MapCache::new(config.tcp_send_buffer)); + #[cfg(unix)] + let rx_map_cache = config + .map_tcp_recv_buffer + .then(|| Arc::new(MapCache::new(config.tcp_recv_buffer))); + #[cfg(not(unix))] + let rx_map_cache = None; Self { config, raw_inbound, @@ -585,6 +668,10 @@ impl Driver { sockets: SocketSet::new(Vec::new()), tcp_entries: HashMap::new(), half_open: HashSet::new(), + tx_map_cache, + rx_map_cache, + #[cfg(feature = "diagnostics")] + observer: None, } } @@ -631,6 +718,13 @@ impl Driver { } } + #[cfg(feature = "diagnostics")] + fn observe(&self, event: crate::diagnostics::DriverObservation) { + if let Some(observer) = self.observer { + observer(event); + } + } + async fn next_request(client: &mut Option) -> Option { match client { Some(client) => client.requests.recv().await, @@ -648,6 +742,25 @@ impl Driver { } async fn wait_for_work(&mut self) -> bool { + if self.device.rx_is_empty() { + // Avoid an advisory all-socket timer scan when real ingress can + // already progress. poll_recv retains the first packet's coop + // accounting; Pending still enters the original wait below. + let ready = tokio::select! { + biased; + () = self.cancellation.cancelled() => return false, + ready = poll_fn(|cx| Poll::Ready(self.raw_inbound.poll_recv(cx))) => ready, + }; + match ready { + Poll::Ready(Some(packet)) => { + #[cfg(feature = "diagnostics")] + self.observe(crate::diagnostics::DriverObservation::WaitIngress); + return self.receive_packet_batch(packet).await; + } + Poll::Ready(None) => return false, + Poll::Pending => {} + } + } let delay = self.next_delay(); let has_connect_requests = self .client @@ -661,19 +774,18 @@ impl Driver { // one pending packet until output capacity returns. packet = self.raw_inbound.recv(), if self.device.rx_is_empty() => { let Some(packet) = packet else { return false; }; - let batch_count = self.handle_packet_batch(packet); - // recv() already charges the first packet. try_recv() - // does not, so retain the old per-packet cooperative - // accounting without repeating socket maintenance. - for _ in 1..batch_count { - tokio::task::consume_budget().await; - } - true + #[cfg(feature = "diagnostics")] + self.observe(crate::diagnostics::DriverObservation::WaitIngress); + self.receive_packet_batch(packet).await } // Socket maintenance runs before this wait on every iteration. // Its own notifications must not outrank an already-ready packet, // especially TCP ACKs which release the relay's bounded buffers. - () = self.notify.notified() => true, + () = self.notify.notified() => { + #[cfg(feature = "diagnostics")] + self.observe(crate::diagnostics::DriverObservation::WaitNotify); + true + }, request = Self::next_request(&mut self.client), if has_connect_requests => { if let Some(request) = request { self.handle_client_request(request); @@ -681,10 +793,24 @@ impl Driver { } true } - () = tokio::time::sleep(delay) => true, + () = tokio::time::sleep(delay) => { + #[cfg(feature = "diagnostics")] + self.observe(crate::diagnostics::DriverObservation::WaitTimer); + true + }, } } + async fn receive_packet_batch(&mut self, packet: Packet) -> bool { + let batch_count = self.handle_packet_batch(packet); + // Both recv() and poll_recv() charge the first packet. try_recv() + // does not, so preserve accounting for the remaining accepted prefix. + for _ in 1..batch_count { + tokio::task::consume_budget().await; + } + true + } + fn handle_packet_batch(&mut self, first: Packet) -> usize { let mut packet = first; let mut count = 0; @@ -829,6 +955,19 @@ impl Driver { } } + fn new_tcp_handle(&self) -> Arc { + let mut handle = TcpStreamHandle::new( + self.config.recv_layer_buffer_size(), + self.config.send_layer_buffer_size(), + self.notify.clone(), + ) + .with_tx_cache(Arc::downgrade(&self.tx_map_cache)); + if let Some(cache) = &self.rx_map_cache { + handle = handle.with_rx_cache(Arc::downgrade(cache)); + } + Arc::new(handle) + } + fn admit_tcp(&mut self, flow: FlowKey) -> bool { let Some(accept) = self.tcp_accept.as_ref() else { return false; @@ -844,11 +983,7 @@ impl Driver { return false; } - let handle = Arc::new(TcpStreamHandle::new( - self.config.recv_layer_buffer_size(), - self.config.send_layer_buffer_size(), - self.notify.clone(), - )); + let handle = self.new_tcp_handle(); let socket_handle = self.sockets.add(socket); let stream = TcpStream::new(flow, handle.clone()); if accept.try_send(stream).is_err() { @@ -942,11 +1077,7 @@ impl Driver { ))); return; } - let handle = Arc::new(TcpStreamHandle::new( - self.config.recv_layer_buffer_size(), - self.config.send_layer_buffer_size(), - self.notify.clone(), - )); + let handle = self.new_tcp_handle(); let socket = self.sockets.add(socket); let connect_cancellation = Some(request.cancellation.clone()); self.tcp_entries.insert( @@ -1014,6 +1145,8 @@ impl Driver { self.cancellation.cancel(); return; } + #[cfg(feature = "diagnostics")] + let emitted_before = self.device.emitted(); self.device.flush_pending(); // Busy packet traffic must not starve command admission. The same // bounded prefix as raw ingress avoids draining an unbounded burst. @@ -1037,6 +1170,9 @@ impl Driver { self.interface .poll_ingress_single(Instant::now(), &mut self.device, &mut self.sockets); } + #[cfg(feature = "diagnostics")] + let observation = self.drive_tcp_sockets(); + #[cfg(not(feature = "diagnostics"))] self.drive_tcp_sockets(); self.device.flush_pending(); if !self.device.tx_is_full() { @@ -1044,9 +1180,20 @@ impl Driver { .poll(Instant::now(), &mut self.device, &mut self.sockets); } self.device.flush_pending(); + #[cfg(feature = "diagnostics")] + self.observe(crate::diagnostics::DriverObservation::DrivePass { + tcp_entry_visits: observation[0], + app_rx_bytes: observation[1], + app_tx_bytes: observation[2], + no_data_progress: observation[1] == 0 + && observation[2] == 0 + && self.device.emitted() == emitted_before, + }); } - fn drive_tcp_sockets(&mut self) { + fn drive_tcp_sockets(&mut self) -> MaintenanceObservation { + #[cfg(feature = "diagnostics")] + let mut observation = [0_u64; 3]; let pending_flow = self .device .pending_rx() @@ -1054,6 +1201,8 @@ impl Driver { .map(|(flow, _, _)| flow); let mut inactive = Vec::new(); for (flow, entry) in &mut self.tcp_entries { + #[cfg(feature = "diagnostics")] + add_observed_count(&mut observation[0], 1); let socket = self.sockets.get_mut::(entry.socket); Self::finish_connect(*flow, entry, socket); let handle = &entry.handle; @@ -1065,7 +1214,11 @@ impl Driver { (count, count) }) { Ok(0) | Err(_) => break, - Ok(_) => received = true, + Ok(count) => { + received = count > 0; + #[cfg(feature = "diagnostics")] + add_observed_count(&mut observation[1], count); + } } } if received { @@ -1073,13 +1226,20 @@ impl Driver { } let mut sent = false; - while socket.can_send() { + // The hint skips only an empty application copy. New writes still + // notify this driver; FIN/flush and socket maintenance use their + // existing authoritative checks below. + while handle.app_send.may_have_data() && socket.can_send() { match socket.send(|bytes| { let count = handle.app_send.read(bytes); (count, count) }) { Ok(0) | Err(_) => break, - Ok(_) => sent = true, + Ok(count) => { + sent = count > 0; + #[cfg(feature = "diagnostics")] + add_observed_count(&mut observation[2], count); + } } } if sent { @@ -1109,8 +1269,8 @@ impl Driver { socket.abort(); } else if (handle.write_shutdown.load(Ordering::Acquire) || handle.dropped.load(Ordering::Acquire)) - && handle.app_send.is_empty() && socket.may_send() + && handle.app_send.is_empty() { socket.close(); } @@ -1142,6 +1302,10 @@ impl Driver { } } self.update_flow_stats(); + #[cfg(feature = "diagnostics")] + { + observation + } } fn finish_connect(incoming: FlowKey, entry: &mut TcpEntry, socket: &mut tcp::Socket<'_>) { @@ -1237,6 +1401,11 @@ impl Driver { } fn shutdown(&mut self) { + // Idle mapping owners end before waking streams/publishing stopped. + self.tx_map_cache.close(); + if let Some(cache) = &self.rx_map_cache { + cache.close(); + } self.cancellation.cancel(); self.device.clear(); if let Some(client) = &mut self.client { @@ -1359,6 +1528,193 @@ mod tests { Packet::new(ip.into_inner()) } + #[cfg(unix)] + #[tokio::test] + async fn mapped_rx_driver_opt_in_stop_clears_idle_and_preserves_accepted_tail() { + for (rx_total, tx_total) in [(112 * 1024, 64 * 1024), (128 * 1024, 32 * 1024)] { + for enabled in [false, true] { + assert_mapped_rx_driver_stop(rx_total, tx_total, enabled).await; + } + } + } + + #[cfg(unix)] + async fn assert_mapped_rx_driver_stop( + tcp_recv_buffer: usize, + tcp_send_buffer: usize, + enabled: bool, + ) { + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + let config = NetStackConfig { + tcp_recv_buffer, + tcp_send_buffer, + map_tcp_recv_buffer: enabled, + ..NetStackConfig::default() + }; + let (_sender, inbound) = mpsc::channel(config.packet_queue); + let (outbound, mut packets) = mpsc::channel(config.packet_queue); + let (accept, mut streams) = mpsc::channel(config.tcp_accept_queue); + let (stopped, observed) = watch::channel(false); + let mut driver = Driver::new( + config, + inbound, + outbound, + Some(accept), + None, + CancellationToken::new(), + Arc::new(Notify::new()), + NetStackStats::default(), + stopped, + ); + assert_eq!(driver.rx_map_cache.is_some(), enabled); + driver.handle_packet_batch(tcp_handshake_packet(100, None)); + driver.drive(); + let syn_ack = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(syn_ack.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + let acknowledged = tcp.seq_number().0.wrapping_add(1); + driver.handle_packet_batch(tcp_handshake_packet(101, Some(acknowledged))); + driver.drive(); + let mut stream = streams.try_recv().unwrap(); + let handle = driver.tcp_entries.values().next().unwrap().handle.clone(); + let tx_capacity = tcp_send_buffer / 2; + assert_eq!( + handle.app_send.write(&vec![0x61; tx_capacity + 1]), + tx_capacity + ); + assert_eq!(handle.app_send.write(b"full"), 0); + assert!(handle.app_send.mapped_lifetime_for_test().is_none()); + let mut drained_tx = vec![0; tx_capacity]; + assert_eq!(handle.app_send.read(&mut drained_tx), tx_capacity); + assert!(drained_tx.iter().all(|byte| *byte == 0x61)); + assert_eq!(handle.app_recv.write(b"first"), 5); + let first = handle.app_recv.mapped_lifetime_for_test(); + assert_eq!(first.is_some(), enabled); + stream.read_exact(&mut [0; 5]).await.unwrap(); + if let Some(cache) = &driver.rx_map_cache { + assert_eq!(cache.retained_for_test(), tcp_recv_buffer / 2); + } + assert_eq!(handle.app_recv.write(b"accepted-tail"), 13); + let tail = handle.app_recv.mapped_lifetime_for_test(); + let cache = driver.rx_map_cache.clone(); + driver.shutdown(); + assert!(*observed.borrow()); + assert!(handle.stopped.load(Ordering::Acquire)); + if let (Some(cache), Some(tail)) = (&cache, &tail) { + assert_eq!(cache.retained_for_test(), 0); + assert!( + tail.upgrade().is_some(), + "Stop must keep the real nonempty RX owner" + ); + } + assert_eq!( + stream.write_all(b"late").await.unwrap_err().kind(), + std::io::ErrorKind::BrokenPipe + ); + let mut bytes = [0; 13]; + stream.read_exact(&mut bytes).await.unwrap(); + assert_eq!(&bytes, b"accepted-tail"); + assert_eq!(stream.read(&mut [0; 1]).await.unwrap(), 0); + if let (Some(cache), Some(tail)) = (&cache, &tail) { + assert!(tail.upgrade().is_none()); + assert_eq!(cache.retained_for_test(), 0); + } + } + + #[cfg(unix)] + #[tokio::test] + async fn mapped_tx_packet_admission_and_data_have_a_real_mapping_owner() { + use tokio::io::AsyncWriteExt; + let config = NetStackConfig { + tcp_send_buffer: 128 * 1024, + ..NetStackConfig::default() + }; + let (_sender, inbound) = mpsc::channel(config.packet_queue); + let (outbound, mut packets) = mpsc::channel(config.packet_queue); + let (accept, mut streams) = mpsc::channel(config.tcp_accept_queue); + let (stopped, observed) = watch::channel(false); + let mut driver = Driver::new( + config, + inbound, + outbound, + Some(accept), + None, + CancellationToken::new(), + Arc::new(Notify::new()), + NetStackStats::default(), + stopped, + ); + driver.handle_packet_batch(tcp_handshake_packet(100, None)); + driver.drive(); + let syn_ack = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(syn_ack.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + let acknowledged = tcp.seq_number().0.wrapping_add(1); + driver.handle_packet_batch(tcp_handshake_packet(101, Some(acknowledged))); + driver.drive(); + let mut stream = streams.try_recv().unwrap(); + let payload = b"actual-mapped-packet-data"; + stream.write_all(payload).await.unwrap(); + let handle = driver.tcp_entries.values().next().unwrap().handle.clone(); + let lifetime = handle.app_send.mapped_lifetime_for_test().unwrap(); + assert!(lifetime.upgrade().is_some()); + driver.drive(); + let data = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(data.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + assert_eq!(tcp.payload(), payload); + assert_eq!(handle.app_send.len(), 0); + assert!(driver.tx_map_cache.retained_for_test() > 0); + driver.shutdown(); + assert!(*observed.borrow()); + assert!(lifetime.upgrade().is_none()); + assert_eq!( + stream.write_all(b"stopped").await.unwrap_err().kind(), + std::io::ErrorKind::BrokenPipe + ); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_shutdown_clears_real_idle_owners_before_stopped() { + let config = NetStackConfig { + tcp_send_buffer: 128 * 1024, + ..NetStackConfig::default() + }; + let (_sender, inbound) = mpsc::channel(config.packet_queue); + let (outbound, _packets) = mpsc::channel(config.packet_queue); + let (accept, _streams) = mpsc::channel(config.tcp_accept_queue); + let (stopped, observed) = watch::channel(false); + let mut driver = Driver::new( + config, + inbound, + outbound, + Some(accept), + None, + CancellationToken::new(), + Arc::new(Notify::new()), + NetStackStats::default(), + stopped, + ); + let handle = TcpStreamHandle::new(16, 64 * 1024, Arc::new(Notify::new())) + .with_tx_cache(Arc::downgrade(&driver.tx_map_cache)); + let cache = Arc::downgrade(&driver.tx_map_cache); + assert_eq!(handle.app_send.write(b"owned"), 5); + let lifetime = handle.app_send.mapped_lifetime_for_test().unwrap(); + assert_eq!(handle.app_send.read(&mut [0; 5]), 5); + assert!(driver.tx_map_cache.retained_for_test() > 0); + assert!(lifetime.upgrade().is_some()); + driver.shutdown(); + assert!(*observed.borrow()); + assert_eq!(driver.tx_map_cache.retained_for_test(), 0); + assert!(lifetime.upgrade().is_none()); + assert_eq!(handle.app_send.write(b"late"), 4); + assert_eq!(handle.app_send.read(&mut [0; 4]), 4); + assert_eq!(driver.tx_map_cache.retained_for_test(), 0); + drop(driver); + assert!(cache.upgrade().is_none()); + } + // Keep both real handshakes and the failed-emit timeline in one regression. #[allow(clippy::too_many_lines)] #[tokio::test] @@ -1505,6 +1861,235 @@ mod tests { ); } + #[tokio::test] + async fn tx_hint_empty_observation_then_write_wakes_and_sends_without_new_ingress() { + use tokio::io::AsyncWriteExt; + let config = NetStackConfig { + max_poll_interval: Duration::from_secs(5), + ..NetStackConfig::default() + }; + let (_sender, inbound) = mpsc::channel(config.packet_queue); + let (outbound, mut packets) = mpsc::channel(config.packet_queue); + let (accept, mut streams) = mpsc::channel(config.tcp_accept_queue); + let (stopped, _) = watch::channel(false); + let notify = Arc::new(Notify::new()); + let mut driver = Driver::new( + config, + inbound, + outbound, + Some(accept), + None, + CancellationToken::new(), + notify.clone(), + NetStackStats::default(), + stopped, + ); + driver.handle_packet_batch(tcp_handshake_packet(100, None)); + driver.drive(); + let syn_ack = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(syn_ack.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + let acknowledged = tcp.seq_number().0.wrapping_add(1); + driver.handle_packet_batch(tcp_handshake_packet(101, Some(acknowledged))); + driver.drive(); + let mut stream = streams.try_recv().unwrap(); + let handle = driver.tcp_entries.values().next().unwrap().handle.clone(); + assert!(!handle.app_send.may_have_data()); + assert!(packets.try_recv().is_err()); + + // A prior empty maintenance pass must not require a new packet or the + // five-second maintenance timer to notice this subsequent real write. + // Drain at most the one stored Notify permit before checking its wait. + let _ = notify.notified().now_or_never(); + let mut waiting = Box::pin(driver.wait_for_work()); + assert!(futures_util::poll!(waiting.as_mut()).is_pending()); + let payload = b"published-after-driver-observed-empty"; + stream.write_all(payload).await.unwrap(); + assert!(handle.app_send.may_have_data()); + assert_eq!( + futures_util::poll!(waiting.as_mut()), + std::task::Poll::Ready(true) + ); + drop(waiting); + driver.drive(); + let data = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(data.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + assert_eq!(tcp.payload(), payload); + assert_eq!(handle.app_send.len(), 0); + assert!(!handle.app_send.may_have_data()); + driver.shutdown(); + } + + #[tokio::test] + #[allow(clippy::too_many_lines)] + async fn pending_write_flush_resume_on_real_window_ack_then_fin() { + use std::task::{Context, Wake, Waker}; + use tokio::io::{AsyncWrite, AsyncWriteExt}; + + struct WakeCount(AtomicUsize); + impl Wake for WakeCount { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::Relaxed); + } + fn wake_by_ref(self: &Arc) { + self.0.fetch_add(1, Ordering::Relaxed); + } + } + let config = NetStackConfig { + tcp_send_buffer: 4096, + max_poll_interval: Duration::from_secs(5), + ..NetStackConfig::default() + }; + let (_sender, inbound) = mpsc::channel(config.packet_queue); + let (outbound, mut packets) = mpsc::channel(config.packet_queue); + let (accept, mut streams) = mpsc::channel(config.tcp_accept_queue); + let (stopped, observed) = watch::channel(false); + let notify = Arc::new(Notify::new()); + let mut driver = Driver::new( + config, + inbound, + outbound, + Some(accept), + None, + CancellationToken::new(), + notify.clone(), + NetStackStats::default(), + stopped, + ); + driver.handle_packet_batch(tcp_handshake_packet(100, None)); + driver.drive(); + let syn_ack = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(syn_ack.data()).unwrap(); + let sequence = TcpPacket::new_checked(ip.payload()) + .unwrap() + .seq_number() + .0 + .wrapping_add(1); + driver.handle_packet_batch(tcp_handshake_packet(101, Some(sequence))); + driver.drive(); + let mut stream = streams.try_recv().unwrap(); + let entry = driver.tcp_entries.values().next().unwrap(); + let socket = entry.socket; + let handle = entry.handle.clone(); + let first = [0x41; 2048]; + let tail = [0x42; 2048]; + stream.write_all(&first).await.unwrap(); + driver.drive(); + assert_pending_notify_wire_bytes(&mut packets, sequence, &first); + assert_eq!( + driver.sockets.get::(socket).send_queue(), + first.len() + ); + stream.write_all(&tail).await.unwrap(); + driver.drive(); + assert_eq!(handle.app_send.len(), tail.len()); + assert!(packets.try_recv().is_err()); + let _ = notify.notified().now_or_never(); + let observed_wakes = Arc::new(WakeCount(AtomicUsize::new(0))); + let task_waker = Waker::from(observed_wakes.clone()); + let mut context = Context::from_waker(&task_waker); + assert!( + std::pin::Pin::new(&mut stream) + .poll_write(&mut context, b"!") + .is_pending() + ); + assert!( + std::pin::Pin::new(&mut stream) + .poll_flush(&mut context) + .is_pending() + ); + + // A real zero-window update acknowledges no DATA and cannot free the + // full application queue. No fabricated socket flags or app draining. + driver.handle_packet_batch(pending_notify_window_ack(sequence, 0)); + driver.drive(); + assert_eq!(handle.app_send.len(), tail.len()); + assert_eq!(observed_wakes.0.load(Ordering::Relaxed), 0); + assert!(packets.try_recv().is_err()); + // The same peer now opens its window and acknowledges the actual wire + // prefix. This ingress, not a new application write or timer, wakes it. + let first_end = sequence.wrapping_add(2048); + driver.handle_packet_batch(pending_notify_window_ack(first_end, u16::MAX)); + driver.drive(); + assert!(observed_wakes.0.load(Ordering::Relaxed) > 0); + assert_eq!(handle.app_send.len(), 0); + assert!(matches!( + std::pin::Pin::new(&mut stream).poll_flush(&mut context), + Poll::Ready(Ok(())) + )); + assert!(matches!( + std::pin::Pin::new(&mut stream).poll_write(&mut context, b"!"), + Poll::Ready(Ok(1)) + )); + assert_pending_notify_wire_bytes(&mut packets, first_end, &tail); + let tail_end = sequence.wrapping_add(4096); + driver.handle_packet_batch(pending_notify_window_ack(tail_end, u16::MAX)); + driver.drive(); + assert_pending_notify_wire_bytes(&mut packets, tail_end, b"!"); + // Flush has its original local-queue contract; FIN may follow accepted + // DATA without waiting for that final byte's ACK. + assert!(matches!( + std::pin::Pin::new(&mut stream).poll_shutdown(&mut context), + Poll::Ready(Ok(())) + )); + driver.drive(); + let fin = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(fin.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + assert!(tcp.fin() && !tcp.rst()); + assert_eq!(tcp.payload(), b""); + assert_eq!(tcp.seq_number().0, tail_end.wrapping_add(1)); + driver.cancellation.cancel(); + driver.shutdown(); + drop(stream); + assert!(*observed.borrow()); + assert!(handle.stopped.load(Ordering::Acquire)); + assert!(driver.tcp_entries.is_empty()); + assert_eq!(driver.sockets.iter().count(), 0); + assert!(driver.device.rx_is_empty()); + } + + fn pending_notify_window_ack(acknowledgement: i32, window: u16) -> Packet { + let mut ip = Ipv4Packet::new_unchecked( + tcp_handshake_packet(101, Some(acknowledgement)) + .data() + .to_vec(), + ); + let source = ip.src_addr(); + let destination = ip.dst_addr(); + let mut tcp = TcpPacket::new_unchecked(ip.payload_mut()); + tcp.set_window_len(window); + tcp.fill_checksum(&source.into(), &destination.into()); + ip.fill_checksum(); + Packet::new(ip.into_inner()) + } + + fn assert_pending_notify_wire_bytes( + packets: &mut mpsc::Receiver, + sequence: i32, + expected: &[u8], + ) { + let mut received = 0; + while let Ok(packet) = packets.try_recv() { + let ip = Ipv4Packet::new_checked(packet.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + assert!(!tcp.rst() && !tcp.fin()); + if tcp.payload().is_empty() { + continue; + } + assert_eq!( + tcp.seq_number().0, + sequence.wrapping_add(i32::try_from(received).unwrap()) + ); + let end = received + tcp.payload().len(); + assert!(end <= expected.len()); + assert_eq!(tcp.payload(), &expected[received..end]); + received = end; + } + assert_eq!(received, expected.len()); + } + #[tokio::test] async fn full_tx_pure_ack_releases_actual_smoltcp_send_queue() { use tokio::io::AsyncWriteExt; @@ -1665,6 +2250,46 @@ mod tests { } } + #[tokio::test] + async fn ingress_wait_wakes_after_pending_and_drains_a_closed_prefix() { + let config = NetStackConfig::default(); + let (sender, inbound) = mpsc::channel(config.packet_queue); + let (outbound, mut packets) = mpsc::channel(config.packet_queue); + let (accept, _streams) = mpsc::channel(config.tcp_accept_queue); + let (stopped, _) = watch::channel(false); + let mut driver = Driver::new( + config, + inbound, + outbound, + Some(accept), + None, + CancellationToken::new(), + Arc::new(Notify::new()), + NetStackStats::default(), + stopped, + ); + { + let mut waiting = Box::pin(driver.wait_for_work()); + assert!(futures_util::poll!(waiting.as_mut()).is_pending()); + sender.try_send(tcp_handshake_packet(100, None)).unwrap(); + drop(sender); + assert!( + tokio::time::timeout(Duration::from_secs(1), waiting) + .await + .unwrap() + ); + } + assert!(driver.raw_inbound.is_empty()); + driver.drive(); + let syn_ack = packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(syn_ack.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + assert!(tcp.syn() && tcp.ack()); + assert!(!driver.wait_for_work().await); + driver.shutdown(); + assert!(driver.cancellation.is_cancelled()); + } + #[tokio::test] async fn driver_batch_preserves_queued_suffix_when_tcp_ingress_fills_tx() { let config = NetStackConfig { @@ -2001,4 +2626,230 @@ mod tests { Err(NetStackError::MtuExceeded { .. }) )); } + + #[cfg(feature = "diagnostics")] + mod driver_observer_fixture { + use super::*; + use crate::diagnostics::DriverObservation; + use std::cell::RefCell; + use tokio::io::{AsyncReadExt, AsyncWriteExt}; + + #[derive(Clone, Copy, Debug, Default, Eq, PartialEq)] + struct Totals { + passes: u64, + visits: u64, + rx: u64, + tx: u64, + no_data: u64, + ingress: u64, + notified: u64, + timer: u64, + } + thread_local! { + static TOTALS: RefCell = const { RefCell::new(Totals { + passes: 0, visits: 0, rx: 0, tx: 0, + no_data: 0, ingress: 0, notified: 0, timer: 0, + }) }; + } + fn observed(event: DriverObservation) { + TOTALS.with(|totals| { + let mut totals = totals.borrow_mut(); + match event { + DriverObservation::DrivePass { + tcp_entry_visits, + app_rx_bytes, + app_tx_bytes, + no_data_progress, + } => { + totals.passes += 1; + totals.visits += tcp_entry_visits; + totals.rx += app_rx_bytes; + totals.tx += app_tx_bytes; + totals.no_data += u64::from(no_data_progress); + } + DriverObservation::WaitIngress => totals.ingress += 1, + DriverObservation::WaitNotify => totals.notified += 1, + DriverObservation::WaitTimer => totals.timer += 1, + } + }); + } + fn totals() -> Totals { + TOTALS.with(|value| *value.borrow()) + } + fn reset() { + TOTALS.with(|value| *value.borrow_mut() = Totals::default()); + } + struct Fixture { + driver: Driver, + ingress: mpsc::Sender, + packets: mpsc::Receiver, + streams: mpsc::Receiver, + stopped: watch::Receiver, + } + fn fixture() -> Fixture { + let config = NetStackConfig { + max_poll_interval: Duration::from_millis(1), + ..NetStackConfig::default() + }; + let (ingress, inbound) = mpsc::channel(config.packet_queue); + let (outbound, packets) = mpsc::channel(config.packet_queue); + let (accept, streams) = mpsc::channel(config.tcp_accept_queue); + let (stopped_tx, stopped) = watch::channel(false); + let mut driver = Driver::new( + config, + inbound, + outbound, + Some(accept), + None, + CancellationToken::new(), + Arc::new(Notify::new()), + NetStackStats::default(), + stopped_tx, + ); + driver.observer = Some(observed); + Fixture { + driver, + ingress, + packets, + streams, + stopped, + } + } + fn data_packet(sequence: i32, acknowledgement: i32, data: &[u8]) -> Packet { + let mut bytes = tcp_handshake_packet(sequence, Some(acknowledgement)) + .data() + .to_vec(); + bytes.resize(40 + data.len(), 0); + let mut ip = Ipv4Packet::new_unchecked(bytes); + ip.set_total_len(u16::try_from(40 + data.len()).unwrap()); + let source = ip.src_addr(); + let destination = ip.dst_addr(); + { + let mut tcp = TcpPacket::new_unchecked(ip.payload_mut()); + tcp.payload_mut().copy_from_slice(data); + tcp.fill_checksum(&source.into(), &destination.into()); + } + ip.fill_checksum(); + Packet::new(ip.into_inner()) + } + #[tokio::test(flavor = "current_thread")] + async fn driver_observer_counts_selected_waits_but_not_cancel_or_eof() { + reset(); + let mut f = fixture(); + f.driver.drive(); + assert_eq!(totals().passes, 1); + assert_eq!(totals().no_data, 1); + f.ingress.try_send(packet(1)).unwrap(); + assert!(f.driver.wait_for_work().await); + assert_eq!(totals().ingress, 1); + { + let mut waiting = Box::pin(f.driver.wait_for_work()); + assert!(waiting.as_mut().now_or_never().is_none()); + f.ingress.try_send(packet(2)).unwrap(); + assert!(waiting.await); + } + assert_eq!(totals().ingress, 2); + f.driver.notify.notify_one(); + assert!(f.driver.wait_for_work().await); + assert_eq!(totals().notified, 1); + assert!( + tokio::time::timeout(Duration::from_secs(1), f.driver.wait_for_work()) + .await + .unwrap() + ); + assert_eq!(totals().timer, 1); + let before = totals(); + f.driver.cancellation.cancel(); + assert!(!f.driver.wait_for_work().await); + assert_eq!(totals(), before, "cancellation is not a normal wake"); + f.driver.shutdown(); + assert!(*f.stopped.borrow()); + let mut eof = fixture(); + drop(eof.ingress); + let before = totals(); + assert!(!eof.driver.wait_for_work().await); + assert_eq!(totals(), before, "EOF is not ingress"); + eof.driver.shutdown(); + assert!(*eof.stopped.borrow()); + } + #[tokio::test(flavor = "current_thread")] + async fn driver_observer_tracks_actual_duplex_bytes_and_join() { + reset(); + let mut f = fixture(); + f.ingress.try_send(tcp_handshake_packet(100, None)).unwrap(); + assert!(f.driver.wait_for_work().await); + f.driver.drive(); + let syn_ack = f.packets.try_recv().unwrap(); + let ip = Ipv4Packet::new_checked(syn_ack.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + let ack = tcp.seq_number().0.wrapping_add(1); + f.ingress + .try_send(tcp_handshake_packet(101, Some(ack))) + .unwrap(); + assert!(f.driver.wait_for_work().await); + f.driver.drive(); + let mut stream = f.streams.try_recv().unwrap(); + let before = totals(); + let upload = b"observed-peer-upload"; + f.ingress.try_send(data_packet(101, ack, upload)).unwrap(); + assert!(f.driver.wait_for_work().await); + f.driver.drive(); + let mut received = vec![0; upload.len()]; + tokio::time::timeout(Duration::from_secs(1), stream.read_exact(&mut received)) + .await + .unwrap() + .unwrap(); + assert_eq!(received.as_slice(), upload); + let download = b"observed-app-download"; + stream.write_all(&download[..7]).await.unwrap(); + stream.write_all(&download[7..]).await.unwrap(); + f.driver.drive(); + let mut payload = Vec::new(); + while let Ok(packet) = f.packets.try_recv() { + let ip = Ipv4Packet::new_checked(packet.data()).unwrap(); + let tcp = TcpPacket::new_checked(ip.payload()).unwrap(); + payload.extend_from_slice(tcp.payload()); + } + assert_eq!(payload.as_slice(), download); + let after = totals(); + assert_eq!(after.rx - before.rx, u64::try_from(upload.len()).unwrap()); + assert_eq!(after.tx - before.tx, u64::try_from(download.len()).unwrap()); + assert_eq!(after.passes - before.passes, 2); + assert_eq!(after.visits - before.visits, 2); + assert_eq!( + after.no_data - before.no_data, + 0, + "real data progress is not idle" + ); + f.driver.shutdown(); + assert!(*f.stopped.borrow()); + assert_eq!( + stream.write_all(b"stopped").await.unwrap_err().kind(), + std::io::ErrorKind::BrokenPipe + ); + } + #[tokio::test(flavor = "current_thread")] + async fn driver_observer_default_start_is_unobserved_and_observed_start_joins() { + reset(); + let ordinary = NetStack::start_tcp(NetStackConfig::default()).unwrap(); + tokio::time::timeout(Duration::from_secs(1), ordinary.control.stop()) + .await + .unwrap(); + assert_eq!(totals(), Totals::default()); + let selected = + NetStack::start_tcp_observed(NetStackConfig::default(), observed).unwrap(); + tokio::time::timeout(Duration::from_secs(1), selected.control.stop()) + .await + .unwrap(); + assert!(selected.control.is_stopped()); + assert_eq!(selected.stats.snapshot().active_tcp, 0); + assert_eq!(totals().passes, 1); + assert_eq!(totals().no_data, 1); + assert_eq!(totals().ingress + totals().notified + totals().timer, 0); + } + } } + +#[cfg(test)] +#[path = "packet_recover_memory_tests.rs"] +mod packet_recover_memory_tests; diff --git a/crates/vole-netstack/src/tcp.rs b/crates/vole-netstack/src/tcp.rs index 30cb38b..0d0bfcb 100644 --- a/crates/vole-netstack/src/tcp.rs +++ b/crates/vole-netstack/src/tcp.rs @@ -4,13 +4,14 @@ use std::{ net::SocketAddr, pin::Pin, sync::{ - Arc, Mutex, MutexGuard, + Arc, Mutex, MutexGuard, Weak, atomic::{AtomicBool, Ordering}, }, task::{Context, Poll, ready}, }; use futures_util::task::AtomicWaker; +use memmap2::MmapMut; use tokio::{ io::{AsyncRead, AsyncWrite, ReadBuf}, sync::{Notify, mpsc, oneshot}, @@ -184,57 +185,376 @@ pub(crate) struct FlowKey { pub(crate) destination: SocketAddr, } -/// A bounded queue whose storage grows with use and is retained until drop. -pub(crate) struct ByteQueue { - bytes: Mutex>, +#[cfg(any(unix, test))] +const MAPPED_TX_MINIMUM: usize = 64 * 1024; +const MAPPED_IDLE_SLOTS: usize = 4; + +type MapSlots = [Option; MAPPED_IDLE_SLOTS]; + +struct QueueMapping { + bytes: MmapMut, + // Fields drop in declaration order: this marker ends only after the real + // safe memmap2 owner has run its unmap Drop. + #[cfg(test)] + lifetime: Arc<()>, +} + +impl QueueMapping { + #[cfg(unix)] + fn new(capacity: usize) -> std::io::Result { + if capacity == 0 || capacity > isize::MAX.unsigned_abs() { + return Err(ErrorKind::InvalidInput.into()); + } + Ok(Self { + bytes: MmapMut::map_anon(capacity)?, + #[cfg(test)] + lifetime: Arc::new(()), + }) + } + + #[cfg(not(unix))] + fn new(_capacity: usize) -> std::io::Result { + // Keep non-Unix queues on their existing bounded Vec path. Do not + // invoke another platform's anonymous-mapping failure path here. + Err(ErrorKind::Unsupported.into()) + } + + fn capacity(&self) -> usize { + self.bytes.len() + } +} + +struct MappedByteRing { + mapping: QueueMapping, + head: usize, + length: usize, +} + +impl MappedByteRing { + fn new(mapping: QueueMapping) -> Self { + Self { + mapping, + head: 0, + length: 0, + } + } + + fn capacity(&self) -> usize { + self.mapping.capacity() + } + fn is_empty(&self) -> bool { + self.length == 0 + } + + fn write(&mut self, source: &[u8]) -> usize { + let capacity = self.capacity(); + let count = source.len().min(capacity - self.length); + if count == 0 { + return 0; + } + let tail = (self.head + self.length) % capacity; + let first = count.min(capacity - tail); + self.mapping.bytes[tail..tail + first].copy_from_slice(&source[..first]); + if first < count { + self.mapping.bytes[..count - first].copy_from_slice(&source[first..count]); + } + self.length += count; + count + } + + fn read(&mut self, target: &mut [u8]) -> usize { + // Match the original VecDeque Read contract: one contiguous prefix is + // valid progress, and a caller can repeat for the wrapped suffix. + let count = target + .len() + .min(self.length) + .min(self.capacity() - self.head); + if count == 0 { + return 0; + } + target[..count].copy_from_slice(&self.mapping.bytes[self.head..self.head + count]); + self.head = (self.head + count) % self.capacity(); + self.length -= count; + if self.length == 0 { + self.head = 0; + } + count + } +} + +/// Driver-owned idle anonymous mappings. The byte bound counts requested map +/// lengths; OS page padding and fixed Arc/mutex/slot metadata are separate. +/// No cache entry can contain live bytes or own a stream/Driver strongly. +pub(crate) struct MapCache { + state: Mutex, capacity: usize, + closed: AtomicBool, + #[cfg(test)] + fail_next_map: AtomicBool, + #[cfg(test)] + map_attempts: std::sync::atomic::AtomicUsize, +} + +struct MapState { + mappings: MapSlots, + retained: usize, +} + +impl MapCache { + pub(crate) fn new(capacity: usize) -> Self { + Self { + state: Mutex::new(MapState { + mappings: std::array::from_fn(|_| None), + retained: 0, + }), + capacity, + closed: AtomicBool::new(false), + #[cfg(test)] + fail_next_map: AtomicBool::new(false), + #[cfg(test)] + map_attempts: std::sync::atomic::AtomicUsize::new(0), + } + } + + fn take(&self, capacity: usize) -> Option { + if self.closed.load(Ordering::Acquire) { + return None; + } + let mut state = self.state.try_lock().ok()?; + if self.closed.load(Ordering::Acquire) { + return None; + } + let index = state.mappings.iter().position(|mapping| { + mapping + .as_ref() + .is_some_and(|mapping| mapping.capacity() == capacity) + })?; + let mapping = state.mappings[index].take()?; + state.retained -= mapping.capacity(); + Some(MappedByteRing::new(mapping)) + } + + fn acquire(&self, capacity: usize) -> Option { + if self.closed.load(Ordering::Acquire) { + return None; + } + if let Some(ring) = self.take(capacity) { + return Some(ring); + } + if self.closed.load(Ordering::Acquire) { + return None; + } + #[cfg(test)] + { + self.map_attempts.fetch_add(1, Ordering::Relaxed); + if self.fail_next_map.swap(false, Ordering::AcqRel) { + return None; + } + } + QueueMapping::new(capacity).ok().map(MappedByteRing::new) + } + + fn put(&self, ring: MappedByteRing) -> Result<(), MappedByteRing> { + let capacity = ring.capacity(); + if !ring.is_empty() + || capacity == 0 + || capacity > self.capacity + || self.closed.load(Ordering::Acquire) + { + return Err(ring); + } + let Ok(mut state) = self.state.try_lock() else { + return Err(ring); + }; + if self.closed.load(Ordering::Acquire) || state.retained > self.capacity - capacity { + return Err(ring); + } + let Some(index) = state.mappings.iter().position(Option::is_none) else { + return Err(ring); + }; + state.retained += capacity; + state.mappings[index] = Some(ring.mapping); + Ok(()) + } + + pub(crate) fn close(&self) { + self.closed.store(true, Ordering::Release); + let retired: MapSlots = { + let mut state = self + .state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.retained = 0; + std::array::from_fn(|index| state.mappings[index].take()) + }; + drop(retired); // Actual unmap only after releasing cache metadata. + } + + #[cfg(test)] + pub(crate) fn retained_for_test(&self) -> usize { + self.state.lock().unwrap().retained + } +} + +enum QueueStorage { + Vector(VecDeque), + Mapped(MappedByteRing), +} + +struct QueueState { + storage: QueueStorage, + mapping_disabled: bool, +} + +impl QueueState { + fn len(&self) -> usize { + match &self.storage { + QueueStorage::Vector(bytes) => bytes.len(), + QueueStorage::Mapped(ring) => ring.length, + } + } + fn is_empty(&self) -> bool { + self.len() == 0 + } + fn capacity(&self) -> usize { + match &self.storage { + QueueStorage::Vector(bytes) => bytes.capacity(), + QueueStorage::Mapped(ring) => ring.capacity(), + } + } + fn write(&mut self, source: &[u8], limit: usize) -> usize { + match &mut self.storage { + QueueStorage::Mapped(ring) => ring.write(source), + QueueStorage::Vector(bytes) => { + let count = source.len().min(limit - bytes.len()); + let needed = bytes.len() + count; + if needed > bytes.capacity() { + let target = needed.max(bytes.capacity().saturating_mul(2)).min(limit); + bytes.reserve_exact(target - bytes.len()); + } + bytes.extend(&source[..count]); + count + } + } + } + fn read(&mut self, target: &mut [u8]) -> usize { + match &mut self.storage { + QueueStorage::Mapped(ring) => ring.read(target), + QueueStorage::Vector(bytes) => bytes + .read(target) + .expect("reading an in-memory queue cannot fail"), + } + } +} + +/// Default RX/small queues retain `VecDeque` backing. Large application TX and +/// explicitly opted-in application RX may return an empty mapping to their +/// independent Driver-owned cache without moving live bytes. +pub(crate) struct ByteQueue { + bytes: Mutex, + capacity: usize, + map_cache: Option>, + // Advisory only; authoritative FIN/flush checks still take the queue lock. + nonempty_hint: Option, } impl ByteQueue { fn new(capacity: usize) -> Self { Self { - bytes: Mutex::new(VecDeque::new()), + bytes: Mutex::new(QueueState { + storage: QueueStorage::Vector(VecDeque::new()), + mapping_disabled: false, + }), capacity, + map_cache: None, + nonempty_hint: None, + } + } + fn new_tx(capacity: usize) -> Self { + Self { + nonempty_hint: Some(AtomicBool::new(false)), + ..Self::new(capacity) } } - fn lock(&self) -> MutexGuard<'_, VecDeque> { + // Keep publication inside the same queue lock for both storage backends. + fn publish_nonempty(&self, bytes: &MutexGuard<'_, QueueState>) { + if let Some(hint) = &self.nonempty_hint { + hint.store(!bytes.is_empty(), Ordering::Release); + } + } + + pub(crate) fn may_have_data(&self) -> bool { + self.nonempty_hint + .as_ref() + .is_none_or(|hint| hint.load(Ordering::Acquire)) + } + + fn lock(&self) -> MutexGuard<'_, QueueState> { self.bytes .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) } - pub(crate) fn write(&self, source: &[u8]) -> usize { + let cache = self.map_cache.as_ref().and_then(Weak::upgrade); let mut bytes = self.lock(); - let count = source.len().min(self.capacity - bytes.len()); - let needed = bytes.len() + count; - if needed > bytes.capacity() { - // Amortized VecDeque growth can overshoot even a power-of-two - // limit when the first write is an arbitrary-sized TCP segment. - let target = needed - .max(bytes.capacity().saturating_mul(2)) - .min(self.capacity); - let additional = target - bytes.len(); - bytes.reserve_exact(additional); + if !source.is_empty() + && bytes.is_empty() + && bytes.capacity() == 0 + && !bytes.mapping_disabled + && self.map_cache.is_some() + { + let ring = cache + .as_ref() + .and_then(|cache| cache.acquire(self.capacity)); + if let Some(ring) = ring { + bytes.storage = QueueStorage::Mapped(ring); + } else { + bytes.mapping_disabled = true; + } // Original bounded Vec path remains live. } - bytes.extend(&source[..count]); + let count = bytes.write(source, self.capacity); + self.publish_nonempty(&bytes); + drop(bytes); + drop(cache); count } - - pub(crate) fn read(&self, destination: &mut [u8]) -> usize { - self.lock() - .read(destination) - .expect("reading an in-memory queue cannot fail") + pub(crate) fn read(&self, target: &mut [u8]) -> usize { + let cache = self.map_cache.as_ref().and_then(Weak::upgrade); + let mut bytes = self.lock(); + let count = bytes.read(target); + let retired = if bytes.is_empty() && matches!(&bytes.storage, QueueStorage::Mapped(_)) { + let QueueStorage::Mapped(ring) = + std::mem::replace(&mut bytes.storage, QueueStorage::Vector(VecDeque::new())) + else { + unreachable!() + }; + match &cache { + Some(cache) => cache.put(ring).err(), + None => Some(ring), + } + } else { + None + }; + self.publish_nonempty(&bytes); + drop(bytes); + drop(retired); // Rejected mapping unmaps outside both locks. + count } - pub(crate) fn is_empty(&self) -> bool { self.lock().is_empty() } - #[cfg(test)] pub(crate) fn len(&self) -> usize { self.lock().len() } + #[cfg(test)] + pub(crate) fn mapped_lifetime_for_test(&self) -> Option> { + match &self.lock().storage { + QueueStorage::Mapped(ring) => Some(Arc::downgrade(&ring.mapping.lifetime)), + QueueStorage::Vector(_) => None, + } + } } pub(crate) struct TcpStreamHandle { @@ -252,6 +572,38 @@ pub(crate) struct TcpStreamHandle { } impl TcpStreamHandle { + pub(crate) fn with_rx_cache(self, cache: Weak) -> Self { + #[cfg(unix)] + { + let mut handle = self; + handle.app_recv.map_cache = Some(cache); + // RX keeps its authoritative lock/read/waker behavior; it never + // opts into the advisory application-TX nonempty hint. + handle + } + #[cfg(not(unix))] + { + let _ = cache; + self + } + } + + pub(crate) fn with_tx_cache(self, cache: Weak) -> Self { + #[cfg(unix)] + { + let mut handle = self; + if handle.app_send.capacity >= MAPPED_TX_MINIMUM { + handle.app_send.map_cache = Some(cache); + } + handle + } + #[cfg(not(unix))] + { + let _ = cache; + self + } + } + pub(crate) fn new( app_recv_buffer: usize, app_send_buffer: usize, @@ -259,7 +611,7 @@ impl TcpStreamHandle { ) -> Self { Self { app_recv: ByteQueue::new(app_recv_buffer), - app_send: ByteQueue::new(app_send_buffer), + app_send: ByteQueue::new_tx(app_send_buffer), recv_waker: AtomicWaker::new(), send_waker: AtomicWaker::new(), dropped: AtomicBool::new(false), @@ -290,11 +642,30 @@ impl TcpStreamHandle { pub struct TcpStream { flow: FlowKey, pub(crate) handle: Arc, + #[cfg(test)] + read_empty_probe: Option>, + #[cfg(test)] + empty_reads: usize, } impl TcpStream { pub(crate) fn new(flow: FlowKey, handle: Arc) -> Self { - Self { flow, handle } + Self { + flow, + handle, + #[cfg(test)] + read_empty_probe: None, + #[cfg(test)] + empty_reads: 0, + } + } + + #[cfg(test)] + fn after_empty_read(&mut self) { + self.empty_reads += 1; + if let Some(probe) = &mut self.read_empty_probe { + probe(self.empty_reads); + } } /// Intercepted application address, or local source of an active connection. @@ -324,6 +695,16 @@ impl TcpStream { || self.handle.write_shutdown.load(Ordering::Acquire) || self.handle.stopped.load(Ordering::Acquire) } + + fn read_ended_and_drained(&self) -> bool { + // The driver can publish its final bytes and terminal flag after an + // earlier read observed the queue empty. Observe publication first, + // then recheck the actual queue before allowing that read to be EOF. + (self.handle.read_closed.load(Ordering::Acquire) + || self.handle.socket_closed.load(Ordering::Acquire) + || self.handle.stopped.load(Ordering::Acquire)) + && self.handle.app_recv.is_empty() + } } impl std::fmt::Debug for TcpStream { @@ -352,31 +733,32 @@ impl AsyncRead for TcpStream { context: &mut Context<'_>, buffer: &mut ReadBuf<'_>, ) -> Poll> { + let this = self.get_mut(); let target = buffer.initialize_unfilled(); - let count = self.handle.app_recv.read(target); + let count = this.handle.app_recv.read(target); if count > 0 { buffer.advance(count); - self.notify_driver(); + this.notify_driver(); return Poll::Ready(Ok(())); } - if self.handle.read_closed.load(Ordering::Acquire) - || self.handle.socket_closed.load(Ordering::Acquire) - || self.handle.stopped.load(Ordering::Acquire) - { + #[cfg(test)] + this.after_empty_read(); + if this.read_ended_and_drained() { return Poll::Ready(Ok(())); } - self.handle.recv_waker.register(context.waker()); - let count = self.handle.app_recv.read(buffer.initialize_unfilled()); + this.handle.recv_waker.register(context.waker()); + let count = this.handle.app_recv.read(buffer.initialize_unfilled()); + #[cfg(test)] + if count == 0 { + this.after_empty_read(); + } if count > 0 { buffer.advance(count); - self.notify_driver(); + this.notify_driver(); Poll::Ready(Ok(())) - } else if self.handle.read_closed.load(Ordering::Acquire) - || self.handle.socket_closed.load(Ordering::Acquire) - || self.handle.stopped.load(Ordering::Acquire) - { + } else if this.read_ended_and_drained() { Poll::Ready(Ok(())) } else { Poll::Pending @@ -414,6 +796,9 @@ impl AsyncWrite for TcpStream { "netstack TCP write side is closed", ))) } else { + // The successful publication already notified the driver. Keep + // the registered waker and double-check, without a new Mac wake. + #[cfg(not(target_os = "macos"))] self.notify_driver(); Poll::Pending } @@ -438,6 +823,7 @@ impl AsyncWrite for TcpStream { "netstack TCP write side closed before buffered data was flushed", ))) } else { + #[cfg(not(target_os = "macos"))] self.notify_driver(); Poll::Pending } @@ -471,14 +857,645 @@ impl TcpListener { } } +#[cfg(test)] +#[path = "tcp_pending_notify_memory_tests.rs"] +mod pending_notify_memory_tests; + #[cfg(test)] mod tests { - use std::time::Duration; + use std::{ + sync::atomic::AtomicUsize, + task::{Wake, Waker}, + time::Duration, + }; use tokio::io::AsyncWriteExt as _; use super::*; + #[derive(Clone, Copy, Debug)] + enum ReadEnd { + PeerFin, + SocketClosed, + Stopped, + } + + impl ReadEnd { + fn publish(self, handle: &TcpStreamHandle) { + match self { + Self::PeerFin => handle.read_closed.store(true, Ordering::Release), + Self::SocketClosed => handle.socket_closed.store(true, Ordering::Release), + Self::Stopped => { + handle.mark_stopped(); + return; + } + } + handle.recv_waker.wake(); + } + } + + struct ReadWake(AtomicUsize); + impl Wake for ReadWake { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::Relaxed); + } + + fn wake_by_ref(self: &Arc) { + self.0.fetch_add(1, Ordering::Relaxed); + } + } + + fn assert_published_tail_precedes_eof( + empty_probe: usize, + ending: ReadEnd, + rx_cache: Option>, + ) { + let mut handle = TcpStreamHandle::new( + rx_cache.as_ref().map_or(1024, |cache| cache.capacity / 2), + 16, + Arc::new(Notify::new()), + ); + if let Some(cache) = &rx_cache { + handle = handle.with_rx_cache(Arc::downgrade(cache)); + } + let handle = Arc::new(handle); + let mut stream = TcpStream::new( + FlowKey { + source: "192.0.2.1:12000".parse().unwrap(), + destination: "198.51.100.1:443".parse().unwrap(), + }, + handle.clone(), + ); + // Publish exactly where the concurrent driver can deliver its final + // bytes: after a consumer observed the real queue empty, before its + // terminal-state decision. There is no global hook or scheduler race. + let publisher = handle.clone(); + let expect_map = rx_cache.is_some(); + stream.read_empty_probe = Some(Box::new(move |probe| { + if probe == empty_probe { + assert_eq!(publisher.app_recv.write(&[0x5a; 730]), 730); + assert_eq!( + publisher.app_recv.mapped_lifetime_for_test().is_some(), + expect_map + ); + ending.publish(&publisher); + } + })); + let notifications = Arc::new(ReadWake(AtomicUsize::new(0))); + let waker = Waker::from(notifications.clone()); + let mut context = Context::from_waker(&waker); + let mut bytes = [0; 1024]; + let mut buffer = ReadBuf::new(&mut bytes); + let first = Pin::new(&mut stream).poll_read(&mut context, &mut buffer); + if first.is_pending() { + assert!( + notifications.0.load(Ordering::Relaxed) > 0, + "{ending:?}: registered consumer lost the final publication wake" + ); + assert!(matches!( + Pin::new(&mut stream).poll_read(&mut context, &mut buffer), + Poll::Ready(Ok(())) + )); + } else { + assert!(matches!(first, Poll::Ready(Ok(())))); + } + assert_eq!( + buffer.filled().len(), + 730, + "{ending:?}: empty probe {empty_probe} returned EOF before its accepted tail" + ); + assert!(buffer.filled().iter().all(|byte| *byte == 0x5a)); + assert!(handle.app_recv.is_empty()); + let mut final_byte = [0]; + let mut eof = ReadBuf::new(&mut final_byte); + assert!(matches!( + Pin::new(&mut stream).poll_read(&mut context, &mut eof), + Poll::Ready(Ok(())) + )); + assert_eq!(eof.filled(), []); + if let Some(cache) = rx_cache { + assert_eq!(cache.retained_for_test(), cache.capacity / 2); + cache.close(); + } + } + + #[test] + fn tcp_read_publication_after_initial_empty_probe_drains_before_eof() { + for ending in [ReadEnd::PeerFin, ReadEnd::SocketClosed, ReadEnd::Stopped] { + assert_published_tail_precedes_eof(1, ending, None); + } + } + + #[test] + fn tcp_read_publication_after_registered_empty_probe_drains_before_eof() { + for ending in [ReadEnd::PeerFin, ReadEnd::SocketClosed, ReadEnd::Stopped] { + assert_published_tail_precedes_eof(2, ending, None); + } + } + + #[cfg(unix)] + #[test] + fn mapped_rx_publication_after_both_empty_probes_drains_before_eof() { + for total in [112 * 1024, 128 * 1024] { + for probe in [1, 2] { + for ending in [ReadEnd::PeerFin, ReadEnd::SocketClosed, ReadEnd::Stopped] { + assert_published_tail_precedes_eof( + probe, + ending, + Some(Arc::new(MapCache::new(total))), + ); + } + } + } + } + + #[cfg(unix)] + #[test] + fn mapped_rx_empty_cache_is_bounded_and_independent_from_tx() { + for (capacity, tx_total) in [(56 * 1024, 64 * 1024), (64 * 1024, 32 * 1024)] { + assert_mapped_rx_empty_cache(capacity, tx_total); + } + } + + #[cfg(unix)] + fn assert_mapped_rx_empty_cache(capacity: usize, tx_total: usize) { + let rx = Arc::new(MapCache::new(2 * capacity)); + let tx = Arc::new(MapCache::new(tx_total)); + let queues: Vec<_> = (0..3) + .map(|_| { + let handle = TcpStreamHandle::new(capacity, tx_total / 2, Arc::new(Notify::new())) + .with_tx_cache(Arc::downgrade(&tx)) + .with_rx_cache(Arc::downgrade(&rx)); + assert!(handle.app_recv.nonempty_hint.is_none()); + assert_eq!(handle.app_recv.capacity, capacity); + assert_eq!(handle.app_send.capacity, tx_total / 2); + assert!( + handle.app_send.map_cache.is_none(), + "TX threshold remains64KiB" + ); + handle.app_recv + }) + .collect(); + let payload = vec![0x5a; capacity + 1]; + let mut lifetimes = Vec::new(); + for queue in &queues { + assert_eq!(queue.write(&payload), capacity); + assert_eq!(queue.len(), capacity); + lifetimes.push(queue.mapped_lifetime_for_test().unwrap()); + assert_eq!(queue.write(b"full"), 0); + } + let mut output = vec![0; capacity]; + for queue in &queues { + assert_eq!(queue.read(&mut []), 0); + assert_eq!(queue.len(), capacity); + let retained_before = rx.retained_for_test(); + let half = capacity / 2; + assert_eq!(queue.read(&mut output[..half]), half); + assert_eq!(queue.len(), capacity - half); + assert!(queue.mapped_lifetime_for_test().is_some()); + assert_eq!(rx.retained_for_test(), retained_before); + assert_eq!(queue.read(&mut output[half..]), capacity - half); + assert!(output.iter().all(|byte| *byte == 0x5a)); + } + assert_eq!(rx.retained_for_test(), 2 * capacity); + assert_eq!(tx.retained_for_test(), 0); + assert!(lifetimes[0].upgrade().is_some()); + assert!(lifetimes[1].upgrade().is_some()); + assert!( + lifetimes[2].upgrade().is_none(), + "excess idle owner is actually destroyed" + ); + let reused = TcpStreamHandle::new(capacity, tx_total / 2, Arc::new(Notify::new())) + .with_rx_cache(Arc::downgrade(&rx)) + .app_recv; + assert_eq!(reused.write(b"new"), 3); + assert_eq!(reused.read(&mut output), 3); + assert_eq!(&output[..3], b"new"); + assert_eq!(reused.read(&mut output), 0); + rx.close(); + assert!( + lifetimes + .iter() + .all(|lifetime| lifetime.upgrade().is_none()) + ); + } + + #[cfg(unix)] + #[test] + fn mapped_rx_failure_keeps_bounded_vec_progress_without_retries() { + for (capacity, tx_total) in [(56 * 1024, 64 * 1024), (64 * 1024, 32 * 1024)] { + assert_mapped_rx_failure(capacity, tx_total); + } + } + + #[cfg(unix)] + fn assert_mapped_rx_failure(capacity: usize, tx_total: usize) { + let cache = Arc::new(MapCache::new(2 * capacity)); + cache.fail_next_map.store(true, Ordering::Release); + let queue = TcpStreamHandle::new(capacity, tx_total / 2, Arc::new(Notify::new())) + .with_rx_cache(Arc::downgrade(&cache)) + .app_recv; + let payload = vec![0x6b; capacity + 7]; + assert_eq!(queue.write(&payload), capacity); + assert!(queue.lock().mapping_disabled); + assert!(queue.mapped_lifetime_for_test().is_none()); + let mut output = vec![0; capacity]; + assert_eq!(queue.read(&mut output), capacity); + assert_eq!(output, payload[..capacity]); + for _ in 0..3 { + assert_eq!(queue.write(b"vec"), 3); + assert_eq!(queue.read(&mut output), 3); + assert_eq!(&output[..3], b"vec"); + } + assert_eq!(cache.map_attempts.load(Ordering::Relaxed), 1); + assert_eq!(cache.retained_for_test(), 0); + } + + fn mapped_queue(capacity: usize, cache: &Arc) -> ByteQueue { + TcpStreamHandle::new(16, capacity, Arc::new(Notify::new())) + .with_tx_cache(Arc::downgrade(cache)) + .app_send + } + + #[cfg(unix)] + fn map_ring(capacity: usize) -> MappedByteRing { + MappedByteRing::new(QueueMapping::new(capacity).unwrap()) + } + + #[cfg(unix)] + #[test] + fn mapped_tx_ring_wrap_partial_zero_and_full_keep_exact_order() { + let mut ring = map_ring(8); + assert_eq!(ring.write(b"abcdef"), 6); + assert_eq!(ring.read(&mut []), 0); + assert_eq!(ring.length, 6); + let mut first = [0; 2]; + assert_eq!(ring.read(&mut first), 2); + assert_eq!(&first, b"ab"); + assert_eq!(ring.write(b"WXYZextra"), 4); + assert_eq!(ring.write(b"full"), 0); + let mut output = [0; 8]; + assert_eq!(ring.read(&mut output), 6); + assert_eq!(&output[..6], b"cdefWX"); + assert_eq!(ring.length, 2); + assert_eq!(ring.read(&mut output[6..]), 2); + assert_eq!(&output, b"cdefWXYZ"); + assert_eq!(ring.head, 0); + assert!(ring.is_empty()); + assert_eq!(ring.read(&mut output), 0); + assert_eq!(ring.write(&[]), 0); + assert_eq!(ring.write(b"123456789"), 8); + assert_eq!(ring.read(&mut output), 8); + assert_eq!(&output, b"12345678"); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_only_large_send_uses_map_and_preserves_explicit_capacity() { + let capacity = MAPPED_TX_MINIMUM + 3; + let cache = Arc::new(MapCache::new(2 * capacity)); + let large = mapped_queue(capacity, &cache); + let body = vec![0x5a; capacity + 7]; + assert_eq!(large.write(&body), capacity); + assert_eq!(large.lock().capacity(), capacity); + assert!(large.mapped_lifetime_for_test().is_some()); + assert_eq!(large.write(b"full"), 0); + let mut output = vec![0; capacity]; + assert_eq!(large.read(&mut output), capacity); + assert!(output.iter().all(|byte| *byte == 0x5a)); + assert_eq!(cache.retained_for_test(), capacity); + + let small = mapped_queue(MAPPED_TX_MINIMUM - 1, &cache); + let receive = ByteQueue::new(capacity); + for queue in [&small, &receive] { + assert_eq!(queue.write(b"vec"), 3); + assert!(queue.mapped_lifetime_for_test().is_none()); + let retained = queue.lock().capacity(); + assert_eq!(queue.read(&mut [0; 3]), 3); + assert_eq!(queue.lock().capacity(), retained); + } + assert_eq!(cache.retained_for_test(), capacity); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_tail_stays_owned_and_idle_reuse_exposes_only_new_bytes() { + let capacity = MAPPED_TX_MINIMUM; + let cache = Arc::new(MapCache::new(2 * capacity)); + let first = mapped_queue(capacity, &cache); + assert_eq!(first.write(b"first-flow-secret"), 17); + let lifetime = first.mapped_lifetime_for_test().unwrap(); + let mut prefix = [0; 5]; + assert_eq!(first.read(&mut prefix), 5); + assert_eq!(&prefix, b"first"); + assert_eq!(cache.retained_for_test(), 0); + assert!(lifetime.upgrade().is_some()); + let mut tail = [0; 12]; + assert_eq!(first.read(&mut tail), 12); + assert_eq!(&tail, b"-flow-secret"); + assert_eq!(cache.retained_for_test(), capacity); + assert!(lifetime.upgrade().is_some()); + let attempts = cache.map_attempts.load(Ordering::Relaxed); + let second = mapped_queue(capacity, &cache); + assert_eq!(second.write(b"new"), 3); + assert_eq!(cache.map_attempts.load(Ordering::Relaxed), attempts); + assert_eq!(cache.retained_for_test(), 0); + let mut output = [0x7f; 32]; + assert_eq!(second.read(&mut output), 3); + assert_eq!(&output[..3], b"new"); + assert!(output[3..].iter().all(|byte| *byte == 0x7f)); + cache.close(); + assert!(lifetime.upgrade().is_none()); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_cache_rejects_nonempty_full_slots_and_excess_bytes() { + let cache = MapCache::new(8 * 4096); + let mut nonempty = map_ring(4096); + assert_eq!(nonempty.write(b"tail"), 4); + let mut rejected = cache.put(nonempty).err().unwrap(); + let mut tail = [0; 4]; + assert_eq!(rejected.read(&mut tail), 4); + assert_eq!(&tail, b"tail"); + for _ in 0..MAPPED_IDLE_SLOTS { + assert!(cache.put(map_ring(4096)).is_ok()); + } + assert_eq!(cache.retained_for_test(), MAPPED_IDLE_SLOTS * 4096); + let extra = map_ring(4096); + let lifetime = Arc::downgrade(&extra.mapping.lifetime); + let retired = cache.put(extra).err().unwrap(); + assert!(lifetime.upgrade().is_some()); + drop(retired); + assert!(lifetime.upgrade().is_none()); + let bounded = MapCache::new(4096); + assert!(bounded.put(map_ring(4096)).is_ok()); + assert!(bounded.put(map_ring(4096)).is_err()); + assert_eq!(bounded.retained_for_test(), 4096); + cache.close(); + bounded.close(); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_full_idle_budget_unmaps_a_returned_queue_backing() { + let capacity = MAPPED_TX_MINIMUM; + let cache = Arc::new(MapCache::new(capacity)); + let first = mapped_queue(capacity, &cache); + let second = mapped_queue(capacity, &cache); + assert_eq!(first.write(b"one"), 3); + assert_eq!(second.write(b"two"), 3); + let kept = first.mapped_lifetime_for_test().unwrap(); + let rejected = second.mapped_lifetime_for_test().unwrap(); + assert_eq!(first.read(&mut [0; 3]), 3); + assert_eq!(cache.retained_for_test(), capacity); + let mut output = [0; 3]; + assert_eq!(second.read(&mut output), 3); + assert_eq!(&output, b"two"); + assert!(rejected.upgrade().is_none()); + assert!(kept.upgrade().is_some()); + assert_eq!(second.lock().capacity(), 0); + cache.close(); + assert!(kept.upgrade().is_none()); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_cache_contention_unmaps_return_without_rejecting_data() { + let capacity = MAPPED_TX_MINIMUM; + let cache = Arc::new(MapCache::new(2 * capacity)); + let queue = mapped_queue(capacity, &cache); + let guard = cache.state.lock().unwrap(); + assert_eq!(queue.write(b"progress"), 8); + let lifetime = queue.mapped_lifetime_for_test().unwrap(); + let mut output = [0; 8]; + assert_eq!(queue.read(&mut output), 8); + assert_eq!(&output, b"progress"); + assert!(lifetime.upgrade().is_none()); + drop(guard); + assert_eq!(cache.retained_for_test(), 0); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_map_failure_keeps_bounded_vec_progress_without_retries() { + let capacity = MAPPED_TX_MINIMUM + 3; + let cache = Arc::new(MapCache::new(2 * capacity)); + cache.fail_next_map.store(true, Ordering::Release); + let queue = mapped_queue(capacity, &cache); + let payload = vec![0x5a; capacity + 5]; + assert_eq!(queue.write(&payload), capacity); + assert!(queue.lock().mapping_disabled); + assert!(queue.mapped_lifetime_for_test().is_none()); + assert_eq!(queue.write(b"full"), 0); + assert!(queue.lock().capacity() <= capacity); + let mut output = vec![0; capacity]; + assert_eq!(queue.read(&mut output), capacity); + assert_eq!(output, payload[..capacity]); + for _ in 0..4 { + assert_eq!(queue.write(b"still-live"), 10); + assert_eq!(queue.read(&mut output), 10); + assert_eq!(&output[..10], b"still-live"); + } + assert_eq!(cache.map_attempts.load(Ordering::Relaxed), 1); + assert_eq!(cache.retained_for_test(), 0); + assert!(queue.lock().capacity() > 0); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_close_does_not_unmap_nonempty_tail_and_late_return_cannot_revive() { + let capacity = MAPPED_TX_MINIMUM; + let cache = Arc::new(MapCache::new(2 * capacity)); + let queue = mapped_queue(capacity, &cache); + assert_eq!(queue.write(b"retained-tail"), 13); + let lifetime = queue.mapped_lifetime_for_test().unwrap(); + cache.close(); + assert!(lifetime.upgrade().is_some()); + let mut output = [0; 13]; + assert_eq!(queue.read(&mut output), 13); + assert_eq!(&output, b"retained-tail"); + assert!(lifetime.upgrade().is_none()); + assert_eq!(cache.retained_for_test(), 0); + assert_eq!(queue.write(b"late-vec"), 8); + assert!(queue.mapped_lifetime_for_test().is_none()); + assert_eq!(queue.read(&mut output), 8); + assert_eq!(&output[..8], b"late-vec"); + let expired = mapped_queue(capacity, &cache); + drop(cache); + assert!(queue.map_cache.as_ref().unwrap().upgrade().is_none()); + assert_eq!(expired.write(b"expired"), 7); + assert!(expired.mapped_lifetime_for_test().is_none()); + assert!(expired.lock().mapping_disabled); + assert_eq!(expired.read(&mut output), 7); + assert_eq!(&output[..7], b"expired"); + } + + #[cfg(unix)] + #[tokio::test] + async fn mapped_tx_stop_preserves_rx_tail_and_rejects_public_writes() { + use tokio::io::AsyncReadExt; + let capacity = MAPPED_TX_MINIMUM; + let cache = Arc::new(MapCache::new(2 * capacity)); + let handle = Arc::new( + TcpStreamHandle::new(16, capacity, Arc::new(Notify::new())) + .with_tx_cache(Arc::downgrade(&cache)), + ); + let mut stream = TcpStream::new( + FlowKey { + source: "192.0.2.1:12000".parse().unwrap(), + destination: "198.51.100.1:443".parse().unwrap(), + }, + handle.clone(), + ); + assert_eq!(handle.app_recv.write(b"accepted-tail"), 13); + assert_eq!(handle.app_send.write(b"sent"), 4); + let lifetime = handle.app_send.mapped_lifetime_for_test().unwrap(); + assert_eq!(handle.app_send.read(&mut [0; 4]), 4); + assert!(cache.retained_for_test() > 0); + cache.close(); + handle.mark_stopped(); + assert!(lifetime.upgrade().is_none()); + assert_eq!( + stream.write_all(b"late").await.unwrap_err().kind(), + ErrorKind::BrokenPipe + ); + let mut tail = [0; 13]; + stream.read_exact(&mut tail).await.unwrap(); + assert_eq!(&tail, b"accepted-tail"); + assert_eq!(stream.read(&mut [0; 1]).await.unwrap(), 0); + assert_eq!(cache.retained_for_test(), 0); + } + + #[cfg(not(unix))] + #[test] + fn non_unix_large_tx_keeps_bounded_vec_progress_without_mapping() { + let capacity = MAPPED_TX_MINIMUM + 3; + let cache = Arc::new(MapCache::new(2 * capacity)); + let queue = mapped_queue(capacity, &cache); + assert!(queue.map_cache.is_none()); + let receive = TcpStreamHandle::new(56 * 1024, 16, Arc::new(Notify::new())) + .with_rx_cache(Arc::downgrade(&cache)) + .app_recv; + assert!(receive.map_cache.is_none()); + assert_eq!(receive.write(b"rx"), 2); + assert!(receive.mapped_lifetime_for_test().is_none()); + assert_eq!( + QueueMapping::new(capacity).err().unwrap().kind(), + ErrorKind::Unsupported + ); + let payload = vec![0x5a; capacity + 1]; + assert_eq!(queue.write(&payload), capacity); + assert_eq!(queue.write(b"full"), 0); + assert!(queue.mapped_lifetime_for_test().is_none()); + assert!(queue.lock().capacity() <= capacity); + let mut output = vec![0; capacity]; + assert_eq!(queue.read(&mut output), capacity); + assert!(output.iter().all(|byte| *byte == 0x5a)); + assert!(queue.lock().capacity() > 0); + assert_eq!(queue.write(b"still-live"), 10); + assert_eq!(queue.read(&mut output), 10); + assert_eq!(&output[..10], b"still-live"); + assert_eq!(cache.map_attempts.load(Ordering::Relaxed), 0); + assert_eq!(cache.retained_for_test(), 0); + } + + #[cfg(unix)] + #[test] + fn mapped_tx_hint_preserves_partial_tail_reuse_and_vec_fallback() { + let capacity = MAPPED_TX_MINIMUM; + let cache = Arc::new(MapCache::new(2 * capacity)); + let queue = mapped_queue(capacity, &cache); + assert!(!queue.may_have_data()); + assert_eq!(queue.write(b"abcdef"), 6); + assert!(queue.may_have_data()); + assert_eq!(queue.read(&mut []), 0); + assert!(queue.may_have_data()); + let mut prefix = [0; 2]; + assert_eq!(queue.read(&mut prefix), 2); + assert_eq!(&prefix, b"ab"); + assert!(queue.may_have_data()); + assert_eq!(cache.retained_for_test(), 0); + let mut tail = [0; 4]; + assert_eq!(queue.read(&mut tail), 4); + assert_eq!(&tail, b"cdef"); + assert!(!queue.may_have_data()); + assert_eq!(cache.retained_for_test(), capacity); + let attempts = cache.map_attempts.load(Ordering::Relaxed); + assert_eq!(queue.write(b"xy"), 2); + assert!(queue.may_have_data()); + assert_eq!(cache.map_attempts.load(Ordering::Relaxed), attempts); + let lifetime = queue.mapped_lifetime_for_test().unwrap(); + cache.close(); + assert!(queue.may_have_data()); + assert_eq!(queue.read(&mut tail), 2); + assert_eq!(&tail[..2], b"xy"); + assert!(!queue.may_have_data()); + assert!(lifetime.upgrade().is_none()); + assert_eq!(queue.write(b"v"), 1); + assert!(queue.lock().mapping_disabled); + assert!(queue.mapped_lifetime_for_test().is_none()); + assert!(queue.may_have_data()); + assert_eq!(queue.read(&mut tail), 1); + assert_eq!(tail[0], b'v'); + assert!(!queue.may_have_data()); + } + + #[test] + fn tx_hint_tracks_real_tail_after_zero_and_partial_operations() { + let queue = ByteQueue::new_tx(8); + assert!(!queue.may_have_data()); + assert_eq!(queue.write(b"abcdef"), 6); + assert!(queue.may_have_data()); + assert_eq!(queue.read(&mut []), 0); + assert!(queue.may_have_data()); + let mut prefix = [0; 2]; + assert_eq!(queue.read(&mut prefix), 2); + assert_eq!(&prefix, b"ab"); + assert!(queue.may_have_data()); + assert_eq!(queue.write(b"WXYZextra"), 4); + assert_eq!(queue.write(b"full"), 0); + assert!(queue.may_have_data()); + let mut tail = [0; 8]; + let mut read = 0; + while read < tail.len() { + assert!(queue.may_have_data()); + assert_eq!(queue.len(), tail.len() - read); + let count = queue.read(&mut tail[read..]); + assert!(count > 0); + read += count; + } + assert_eq!(&tail, b"cdefWXYZ"); + assert_eq!(queue.len(), 0); + assert!(!queue.may_have_data()); + assert_eq!(queue.write(&[]), 0); + assert_eq!(queue.read(&mut []), 0); + assert!(!queue.may_have_data()); + assert_eq!(queue.write(b"next"), 4); + assert!(queue.may_have_data()); + assert_eq!(queue.read(&mut tail), 4); + assert_eq!(&tail[..4], b"next"); + assert!(!queue.may_have_data()); + } + + #[test] + fn only_application_tx_queues_opt_in_to_the_advisory_hint() { + let handle = TcpStreamHandle::new(7, 9, Arc::new(Notify::new())); + assert!(handle.app_recv.nonempty_hint.is_none()); + assert!(handle.app_recv.may_have_data()); // Unknown, not a false empty. + assert!(handle.app_send.nonempty_hint.is_some()); + assert!(!handle.app_send.may_have_data()); + assert_eq!(handle.app_recv.write(b"rx"), 2); + assert!(handle.app_recv.may_have_data()); + assert_eq!(handle.app_send.write(b"123456789x"), 9); + assert_eq!(handle.app_send.write(b"full"), 0); + assert!(handle.app_send.may_have_data()); + let mut body = [0; 9]; + assert_eq!(handle.app_send.read(&mut body), 9); + assert_eq!(&body, b"123456789"); + assert!(!handle.app_send.may_have_data()); + } + #[test] fn byte_queue_never_exceeds_capacity() { let queue = ByteQueue::new(4); diff --git a/crates/vole-netstack/src/tcp_pending_notify_memory_tests.rs b/crates/vole-netstack/src/tcp_pending_notify_memory_tests.rs new file mode 100644 index 0000000..136cc0b --- /dev/null +++ b/crates/vole-netstack/src/tcp_pending_notify_memory_tests.rs @@ -0,0 +1,54 @@ +use super::*; +use futures_util::FutureExt as _; + +#[test] +fn pending_write_and_flush_notifications_match_target_contract() { + for flush in [false, true] { + assert_pending_notification(flush); + } +} + +fn assert_pending_notification(flush: bool) { + let notify = Arc::new(Notify::new()); + let handle = Arc::new(TcpStreamHandle::new(8, 8, notify.clone())); + let mut stream = TcpStream::new( + FlowKey { + source: "192.0.2.1:12000".parse().unwrap(), + destination: "198.51.100.1:443".parse().unwrap(), + }, + handle.clone(), + ); + let mut context = Context::from_waker(std::task::Waker::noop()); + let published = matches!( + Pin::new(&mut stream).poll_write(&mut context, b"accepted"), + Poll::Ready(Ok(8)) + ); + let legitimate_permit = notify.notified().now_or_never().is_some(); + let initially_empty = notify.notified().now_or_never().is_none(); + let mut pending = [false; 4]; + let mut extra_permits = [false; 4]; + for index in 0..pending.len() { + pending[index] = if flush { + Pin::new(&mut stream).poll_flush(&mut context).is_pending() + } else { + Pin::new(&mut stream) + .poll_write(&mut context, b"later") + .is_pending() + }; + extra_permits[index] = notify.notified().now_or_never().is_some(); + } + let unchanged = handle.app_send.len() == 8; + // No task, socket or driver exists in this test. Retire the real handle + // before the semantic assertion, including the expected old-Mac failure. + handle.mark_stopped(); + drop(stream); + drop(handle); + drop(notify); + assert!(published && legitimate_permit && initially_empty && unchanged); + assert_eq!(pending, [true; 4]); + assert_eq!( + extra_permits, + [cfg!(not(target_os = "macos")); 4], + "still-Pending polls published no new state; macOS must not renotify" + ); +} diff --git a/crates/vole-netstack/tests/netstack.rs b/crates/vole-netstack/tests/netstack.rs index fc1546a..5aa29f6 100644 --- a/crates/vole-netstack/tests/netstack.rs +++ b/crates/vole-netstack/tests/netstack.rs @@ -721,17 +721,24 @@ async fn active_tcp_uses_configured_sources_and_delivers_established_duplex_stre #[tokio::test] async fn active_tcp_shutdown_drains_accepted_tail_before_fin_without_prior_acks() { - assert_active_accepted_tail(false).await; + for send_total in [32 * 1024, 128 * 1024, 256 * 1024] { + assert_active_accepted_tail(false, send_total).await; + } } #[tokio::test] async fn active_tcp_drop_drains_accepted_tail_before_fin_without_prior_acks() { - assert_active_accepted_tail(true).await; + for send_total in [32 * 1024, 128 * 1024, 256 * 1024] { + assert_active_accepted_tail(true, send_total).await; + } } -async fn assert_active_accepted_tail(drop_after_write: bool) { - let config = NetStackConfig::default(); - let payload: Vec = (0..24 * 1024) +async fn assert_active_accepted_tail(drop_after_write: bool, send_total: usize) { + let config = NetStackConfig { + tcp_send_buffer: send_total, + ..NetStackConfig::default() + }; + let payload: Vec = (0..send_total * 3 / 4) .map(|index| u8::try_from(index % 251).unwrap()) .collect(); assert!(payload.len() > config.tcp_send_buffer / 2); @@ -1357,6 +1364,8 @@ async fn asymmetric_tcp_buffers_bound_each_direction_and_stop_unblocks_writes() (4 * 1024, 16 * 1024), (16 * 1024, 4 * 1024), (32 * 1024, 64 * 1024), + (32 * 1024, 128 * 1024), + (32 * 1024, 256 * 1024), ] { for flow in [Flow::v4(13_500), Flow::v6(13_501)] { let mut parts = NetStack::start_tcp(NetStackConfig { @@ -1445,55 +1454,57 @@ async fn asymmetric_tcp_buffers_bound_each_direction_and_stop_unblocks_writes() #[tokio::test] async fn tcp_write_applies_backpressure_and_stop_unblocks_it() { - let config = NetStackConfig { - packet_queue: 1, - tcp_accept_queue: 1, - udp_queue: 1, - tcp_recv_buffer: 8 * 1024, - tcp_send_buffer: 8 * 1024, - max_poll_interval: Duration::from_millis(5), - ..NetStackConfig::default() - }; - let stack = NetStack::start(config).unwrap(); - let mut parts = stack.into_parts(); - let flow = Flow::v4(14_000); - parts - .packet_sink - .send(build_tcp(&flow, 10, 0, TcpFlags::SYN, &[])) - .await - .unwrap(); - let syn_ack = timeout_packet(&mut parts.packet_stream).await; - let server_sequence = tcp_sequence(&syn_ack); - let mut stream = parts.tcp_listener.accept().await.unwrap(); - parts - .packet_sink - .send(build_tcp( - &flow, - 11, - server_sequence.wrapping_add(1), - TcpFlags::ACK, - &[], - )) - .await - .unwrap(); - - tokio::time::sleep(Duration::from_millis(20)).await; - let payload = vec![0x5a; 128 * 1024]; - let mut write = Box::pin(stream.write_all(&payload)); - assert!( - tokio::time::timeout(Duration::from_millis(100), &mut write) + for send_total in [8 * 1024, 128 * 1024, 256 * 1024] { + let config = NetStackConfig { + packet_queue: 1, + tcp_accept_queue: 1, + udp_queue: 1, + tcp_recv_buffer: 8 * 1024, + tcp_send_buffer: send_total, + max_poll_interval: Duration::from_millis(5), + ..NetStackConfig::default() + }; + let stack = NetStack::start(config).unwrap(); + let mut parts = stack.into_parts(); + let flow = Flow::v4(14_000); + parts + .packet_sink + .send(build_tcp(&flow, 10, 0, TcpFlags::SYN, &[])) .await - .is_err(), - "write unexpectedly bypassed bounded TCP buffers" - ); + .unwrap(); + let syn_ack = timeout_packet(&mut parts.packet_stream).await; + let server_sequence = tcp_sequence(&syn_ack); + let mut stream = parts.tcp_listener.accept().await.unwrap(); + parts + .packet_sink + .send(build_tcp( + &flow, + 11, + server_sequence.wrapping_add(1), + TcpFlags::ACK, + &[], + )) + .await + .unwrap(); - parts.control.stop().await; - let write_result = tokio::time::timeout(WAIT, write) - .await - .expect("blocked TCP write was not woken by stop"); - assert!(write_result.is_err()); - assert!(stream.is_stopped()); - assert_eq!(parts.stats.snapshot().active_tcp, 0); + tokio::time::sleep(Duration::from_millis(20)).await; + let payload = vec![0x5a; (send_total * 2).max(128 * 1024)]; + let mut write = Box::pin(stream.write_all(&payload)); + assert!( + tokio::time::timeout(Duration::from_millis(100), &mut write) + .await + .is_err(), + "write unexpectedly bypassed bounded TCP buffers" + ); + + parts.control.stop().await; + let write_result = tokio::time::timeout(WAIT, write) + .await + .expect("blocked TCP write was not woken by stop"); + assert!(write_result.is_err()); + assert!(stream.is_stopped()); + assert_eq!(parts.stats.snapshot().active_tcp, 0); + } } #[tokio::test] diff --git a/docs/acceptance.md b/docs/acceptance.md index 1138150..741af7b 100644 --- a/docs/acceptance.md +++ b/docs/acceptance.md @@ -22,45 +22,28 @@ Linux RSS 不等于 Apple Network Extension physical footprint。 ## 性能采纳标准 -所有平台与构建使用统一的内存策略和 benchmark 预算,内存统一使用 MiB: +### 内存与环境 -- **1 Gbps:≤43 MiB(45,088,768 bytes)**。 -- **2 Gbps:≤45 MiB(47,185,920 bytes)**。 +- macOS 模拟记录独立 Core worker 的 `phys_footprint`。iOS 和 tvOS 真机记录整个 Network Extension 的 `phys_footprint`,包括 Core、宿主桥接和扩展运行时。Apple 验收预算统一为 **≤45 MiB(47,185,920 字节)**。 +- Linux 记录 RSS,Android、Windows 记录各自可取得的进程内存指标,均用作参考。记录测量进程、指标、启动、活动窗口、排空及停止覆盖范围。跨平台结果须按实际指标解释。 +- 真机、真实 TUN 和 Mac socketpair 模拟分别报告。物理设备的最终验收使用实际设备、权限和连接条件。 -每档使用单一内存门槛,不再区分硬上限与优化目标。 +### 压力与性能 -内存策略不按平台或编译模式切换,CLI 与 FFI 共用同一实现。 +Mac 综合模拟分别执行 JS 和原生规则加 JS 的窗口,覆盖明文 HTTP、HTTPS H1/H2、适用的 UDP 和 DNS。HTTP 准入按完整送入的请求正文确认,已准入业务的最终改写、内容归属、DNS、活动及排空窗口和资源清理分别核对。 -真实 iOS/tvOS VPN 扩展仍以整个 Network Extension 进程的 physical footprint 验收, -包含 Core、宿主桥接与扩展运行时。 -上述数值是项目按负载划分的验收预算,不声明为各设备的系统限额,也不能只计算 Rust heap。 -Linux 压力使用 RSS;Linux 结果只作优化筛选,不替代真机扩展验收。 -其他平台记录承载 Core 的整个后台进程及实际指标口径,排除独立负载客户端和原站。 -不同平台和测量指标的数值不直接混合排名。 +Linux 真实 TUN 压力按协议覆盖 TCP、UDP 和混合业务。Vole TCP 验证交付与内容,UDP 丢包按实际发送和唯一有效接收计量。吞吐按活动窗口计量,交付丢包在固定排空后计算,保留上下行原始计数。 -定速压力使用既有 Linux 原生 TUN 环境。冷启动、配置和 GeoData 更新、负载、收尾及 -Stop 都应覆盖;未执行的生命周期场景单独标明,不从一次压力结果推导。 -测试执行完成不代表达到验收门槛。 +默认目标未达标时,对匹配协议和负载使用官方 Mihomo 作为容量参考。只比较实际收发的业务字节和数据报交付比例;未发送量、CPU、RSS 和传输诊断独立记录。适用负载档位、相对性能门槛和阶段关闭证据由 benchmark 工程维护。Vole 的正确性、测量和正常停止要求独立验收。 -性能对照使用相同输入、负载和重复次数的普通 Release 构建,分别比较吞吐/QPS 中位数 -与同平台进程内存峰值。Linux 保留原压力负载和 RSS 观察逻辑,覆盖 exec 至退出/reap, -包括启动、负载、drain 和 Stop;heaptrack 等仪器开销、tracked heap 和 wait4 读数 -不能替代这一验收口径。 +### 采纳优化 + +比较相同输入、负载和测量口径的普通 Release 构建,验证受影响的组合,分别记录性能和正确性。压力报告、对照执行细则和历史结果由 benchmark 工程维护。 -- 整体验收必须满足对应负载的内存门槛,协议数据正确性、取消与资源清理必须保持;不能用吞吐或丢包改善抵消内存超限。 - 吞吐、CPU、内存和丢包率都允许渐进式改进,不要求一次修改达到全部目标、各项同步改善或单项绝对不退步,不设单次改善幅度下限。不固定指标优化顺序,按实测瓶颈和综合收益选择下一步。 - 允许指标之间的合理取舍,结合改善幅度、代价、实际完成量和运行间波动评估;综合收益为正的阶段性改进可以采纳。减少实际负载或业务未完成导致的 CPU、内存下降不能算作优化收益。 -- 当前组合和所有受影响组合均需完成相同输入、负载下的回归,不能只凭目标组合的结果采纳。涉及内存增长时仍须满足对应内存门槛;降低内存但尚未达标的阶段性改进也可采纳,超限 FAIL 保留。采纳改进与整体验收分别判断,未达标项不改签为通过。 -- Linux 压力与横向对比均覆盖纯 TCP、纯 UDP、混合 TCP/UDP 三种业务;每种业务独立记录与验收。不支持 UDP 的协议只验收纯 TCP,其他口径明确标记不适用。 -- Linux 定速压力在 **1 Gbps** 下内存须 **≤43 MiB**。性能不设独立的绝对容量轴,以实际吞吐 **≥950 Mbps**、适用的 UDP 交付丢包率 **≤1%** 作为默认参考,满足即性能通过,不再专项优化。完整性和测量独立验收:纯 TCP 要求已发送业务字节与接收字节、校验和一致,无超时、断流或未完成流;TCP 重传独立记录。期限内交付缺口不能单独归因为永久丢失或 Core 缺陷,须先区分 Core、对端与测试工具。 -- 性能对照客户端固定为 Vole 和 Mihomo。1 Gbps 未达到默认性能参考时,补测同协议组合、服务端、流量类型、输入和负载的 Mihomo;逐指标采用较容易达到的标准,达到后也认为性能通过,不再专项优化。Mihomo 与 Mihomo listener 或官方服务端存在兼容问题时,照常统计并比较吞吐、CPU、内存和丢包率,兼容问题及内容错误独立记录。官方客户端仅作源码技术参考,不作为测试对照客户端。 -- 吞吐按实际写入和读到的字节统计,包含错误内容及错误返回前的部分 I/O;内容校验失败只记录首错和累计错误,继续压力收发。数据正确性与吞吐计数分开,错误数据不计为完整、正确交付。对照须保留匹配输入、真实 TUN、实际负载窗口、进程观测、正常 Stop/join 及清理证据;缺测明确记录,不伪造数值。初期逐指标参考为吞吐下限 **min(950 Mbps, Mihomo 实测吞吐)**、UDP 丢包率上限 **max(1%, Mihomo 实测丢包率)**;CPU 继续记录。Vole 内存仍须 **≤43 MiB**,自身数据正确性、TCP 完整交付、实际窗口、DNS 与正常退出清理要求保持;不能用性能通过豁免这些门禁。旧复合负载标记包含此前吞吐目标时,不将其 false 当作实际窗口无效;使用实际活动窗和收发计数判断。历史 FAIL/ERROR、兼容问题与实际身份保留,不追溯改签。 -- 每个精确协议组合、流量类型和负载窗口优先争取达到或优于匹配 Mihomo,独立生产候选的优化尝试**最多20轮**。达到适用参考即停止该项性能优化;同一候选的重复、原版对照、纯观测及仅编译/内存测试不重复计轮。经多轮仍不能达到目标时,可记录结论提前结束;20轮是上限,不要求为凑数做满。 -- 结束上述优化阶段后,允许与匹配 Mihomo **最高相对10%差距**:吞吐下限为 **min(950 Mbps, 0.9 × Mihomo 实测吞吐)**,UDP丢包率上限为 **max(1%, min(100%, 1.1 × Mihomo 实测丢包率))**。这是相对比例,不是增加10个百分点;Mihomo丢包率为0时仍沿用1%较容易参考。必须保留独立候选及真实TUN结果的轮次证据、结束原因、严格结果与降级阶段;没有适用证据不自动放宽。内存、数据/来源、TCP完整交付、实际窗口、DNS、测量与Stop/清理门槛不放宽,历史FAIL/ERROR不重写。 -- **2 Gbps** 用于内存过载验收,内存须 **≤45 MiB**;吞吐、CPU 和丢包率只记录,不设吞吐及丢包门槛。允许通过掐连接、丢包、断连和限制队列大小等方式保护内存。仍须完成真实 TUN 的完整压力窗口,并验证已接收内容、源地址、观测有效性和退出清理;提前结束或没有实际流量不能代替压力验收。 -- UDP 交付丢包率以实际发送与唯一有效接收的数据报数计算,按上下行发送包数加权汇总,同时保留两个方向的独立计数和含错误、重复数据的原始收包数。丢包在固定收尾后统计;吞吐仅统计活动窗口,不把漏发算作丢包。iOS/tvOS 吞吐负载根据真机与链路能力校准,内存预算保持一致。 - -当前默认压力档位仅 **1 Gbps**,2 Gbps 后续单独验证。完整性、性能参考、内存、实际完成量、负载窗口、CPU、UDP loss、DNS 完成数、测量有效性及退出/join/资源清理分别记录。2 Gbps 下的超时、丢包、断连和未完成量保留原始状态,不因允许过载保护而改签为完整交付;Vole 自身的错误内容或源地址仍使验收失败。测量成功不等于业务成功,编译、配置解析或连接成功不代替压力验收。显式安排的 3 Gbps 专项沿用 **≤45 MiB** 的内存过载标准;历史结果保留当时语义,不追溯改签。 +- 公共路径改动复测受影响的已通过范围。各测量窗口保留实际完成量、错误和清理状态;旧证据仅用于其原运行身份。 +- 过载压力分别记录吞吐、CPU、丢包、实际交付与资源回收,并按声明的平台内存口径和实际窗口验收。 过载保护应遵循[运行时资源策略](runtime-resource-policy.md)的资源所有权、局部容量、取消和同步 Stop 边界。 diff --git a/docs/adr/0010-freeze-http-resources-and-private-material-per-session.md b/docs/adr/0010-freeze-http-resources-and-private-material-per-session.md index 8bcb8a4..8a92510 100644 --- a/docs/adr/0010-freeze-http-resources-and-private-material-per-session.md +++ b/docs/adr/0010-freeze-http-resources-and-private-material-per-session.md @@ -4,8 +4,10 @@ status: accepted # ADR 0010:会话固定 HTTP 资源和私密材料 -独立 HTTP 配置的资源更新只产生完整的待应用候选;运行会话固定主设置、实际 payload、编译规则和 CA 身份。显式重连先准备候选,再经过停止屏障切换;失败恢复保留的旧实际内容,不重新读取已变化的来源。普通 Stop 释放私密材料。节点选择和分流资源更新不应用待修改的 HTTP 配置。 +独立 HTTP 配置的资源更新只产生完整的待应用候选;运行会话固定主设置、实际 payload、编译规则、脚本实际源码/静态检查产物、执行顺序和 CA 身份。脚本后端的必要能力在启动准备时校验,静态配置验证不创建执行环境。显式重连先准备候选,再经过停止屏障切换;失败恢复保留的旧实际内容,不重新读取已变化的来源。普通 Stop 释放私密材料。节点选择和分流资源更新不应用待修改的 HTTP 配置。 CA 由 Invoke 的独立私密上下文提供,CLI 只传明确的私密文件路径;共享 YAML、普通缓存和可序列化启动快照不承载私钥。Windows 跨进程交付使用绑定启动身份的当前用户 DPAPI sidecar。静态校验和离线演算不获取 CA、不读取外部资源,也不初始化 VPN。 -URL、头和正文阶段始终按原始 URL 选规则。匹配正文在有界事务内累积,完整成功后才提交输出;格式或工作区不足时回放原文。共享工作区在分配前预留,许可随实际缓冲持有至发送结束;传输错误、取消和 Stop 仍作为真实失败处理。 +URL、头、正文与脚本配置选择始终按原始 URL(U0),不因修改重新匹配。原生规则与脚本共存:每个方向先执行原生阶段,再串行执行匹配脚本;脚本看到前序成功结果。原生 header/body 保留独立阶段事务;每次脚本的 URL/method/status/header/body 候选整体校验后才接受,失败回到该次调用输入,保留此前成功结果和凭据清理。请求脚本结束后才为最终目标建立业务上游;本地结果不递归进入响应处理。 + +匹配正文只接收一次,在同一个有界工作区内完成原生与脚本事务。共同收集/解码失败时回放原文;原生转换失败或单次脚本失败不撤销其它已成功阶段。共享工作区在分配前预留,许可随实际缓冲、回放前缀和发送 owner 持有至最后引用释放;传输错误、取消和 Stop 仍作为真实失败处理。JS text 与 bytes 变化分别输出 UTF-8 identity 与 binary identity,无内容变化保留当前表示。平台执行超时不得遗留仍在运行的脚本;观察到 Future 完成不能代替真实结束。 diff --git a/docs/geodata.md b/docs/geodata.md index 259fed8..726a0f5 100644 --- a/docs/geodata.md +++ b/docs/geodata.md @@ -309,8 +309,8 @@ fallible Vec 扩容、合法 protobuf 帧/长度、code、选中匹配值的 UTF MMDB metadata/图校验状态未计入。因此账本**不包含正则内部编译状态、搜索缓存、 动态 scratch、配置需求集合、allocator 开销或整个进程 footprint**。这些未计入的 内存并不是零;accounted peak 不能作为加载或运行期峰值上界。 -进程 RSS 的硬上限与默认 1 / 2 Gbps 分档压力标准统一见[验收边界](acceptance.md#性能采纳标准), -它们是压力测试标准,不是加载器保证。 +进程内存按[验收边界](acceptance.md#内存与环境)记录, +这是压力测试标准,不是加载器保证。 互通和内存/吞吐压力由独立容器测试工具维护,结果与结论统一保存在 benchmark 工程; `interop`、`stress` 和 `compare` 以 `--source vole=PATH` 显式指定被测 checkout。 diff --git a/docs/http-processing.md b/docs/http-processing.md index adecc91..7ab4253 100644 --- a/docs/http-processing.md +++ b/docs/http-processing.md @@ -2,9 +2,21 @@ 独立 HTTP 配置作用于 TUN 和 mixed-port 的业务 TCP。Core 的 DNS、provider、GeoData、节点握手及 Controller 不进入业务重写。主代理配置仍使用 Mihomo YAML。 +SOCKS5 CONNECT、普通 HTTP 代理请求、HTTP CONNECT 和 TUN TCP 使用同一处理实现。 +明文按原始目标端口与 `http-ports` 准入;普通 HTTP 不因目标端口在 `mitm.ports` 而切换为 +TLS 隧道。SOCKS5/CONNECT 的候选流先确认代理握手,再读取业务数据;未识别或未获 MITM +授权时,已读字节完整回放后继续嗅探/选路。连接沿固定 HTTP 资源代际执行,原始入口类型和 +认证身份不变。UDP/QUIC 不进入此 HTTP 处理路径。 + +主配置 sniffer 与独立 HTTP 处理分别准入。关闭 sniffer、协议端口不匹配或命中其排除项, +不会自动关闭已显式授权的 HTTP rewrite/MITM;嗅探得到域名也不能扩大 MITM 授权。 +普通 HTTP 每请求重新检查端口、执行规则并选路;离开处理端口时退役该下游此前保留的处理上游。 + +明文 H1 在改写前对原始 authority 复用主配置的嗅探准入、HTTP 端口、force/skip 与目标覆盖策略;关闭或排除时不隐式补域名,`override-destination: false` 只提供选路提示并保留已选 IP,HTTPS 仍沿固定 SNI 和逐 authority 授权。 + ## 配置与资源 -`httpConfigYaml` 使用单份 YAML 文档。未知字段、旧格式、重复键、类型错误及 `null` 冒充省略值均拒绝。四个顶层字段均可省略: +`httpConfigYaml` 使用单份 YAML 文档。未知字段、旧格式、重复键、类型错误及 `null` 冒充省略值均拒绝。五个顶层字段均可省略: ```yaml http-ports: [80, 8080] @@ -12,6 +24,9 @@ rewrite-providers: {} rewrite: enabled: false rules: [] +http-scripts: + enabled: false + scripts: [] mitm: enabled: false ports: [443] @@ -54,6 +69,58 @@ file 在显式准备时读取;http 的 interval 默认 86400 秒,0 只关闭 HTTP 处理需要编译启用 `inbound-http`。缺少该能力时,非空 HTTP 配置在静态校验时拒绝,不读取 provider 或私密 CA;省略或空输入仍表示不启用。 +## 内联 HTTP 脚本配置 + +`http-scripts.enabled` 独立于 `rewrite.enabled`,默认 false;`scripts` 默认为空列表。每项必填 `name`、`phase`、`url` 和内联 `source`;`phase` 仅 request/response,`match` 默认 regex,可为 exact/prefix,`body` 默认 none,可为 text/bytes。名称不能为空或包含控制字符。选择器使用原始规范化 URL,按声明顺序执行所有匹配项;仅脚本启用时也可进入配置的 HTTP 端口,不要求原生规则非空。 + +```yaml +http-scripts: + enabled: true + scripts: + - name: tag-request + phase: request + url: 'https://api.example/' + match: prefix + body: none + source: | + function rewrite(input) { + return { + type: "modify", + headers: [{op: "set", name: "x-vole", values: ["1"]}] + }; + } +``` + +脚本只能在本机文档中内联声明。rewrite provider 只携带原生规则。静态校验始终检查脚本 schema、选择器和 AST,包括关闭总开关时。启用脚本的实际会话准备会校验执行后端,当前后端可用性限于 Apple。初始化只处理受信任的运行库,用户脚本在命中业务请求或响应时执行。 + +脚本声明最多 64 项,名称与选择器合计不超过 64 KiB,选择器沿用每项 2 KiB 和原生正则编译预算;内联源码计入已有的 1 MiB 文档/实际资源总上限。未知字段、空值冒充省略值、无效 AST 或超限均拒绝整个候选,不截断。实际 source、声明与编译结果随 HTTP 会话候选固定,资源刷新或后续编辑不改变正在运行的脚本。 + +源码必须定义唯一同步入口 `function rewrite(input) { ... }`。当前语法支持 let/const、if/else、return、普通 for/while/do-while、无标签 break/continue、普通对象和稠密数组、成员读取/简单赋值、局部变量自增减及赋值运算、条件/逻辑表达式与原始值的有限算术比较。对象不会被隐式转换成字符串或数字。静态 AST 检查遍历最多 16,384 项、递归深度 128;未知语法明确拒绝,不用字符串过滤代替语法解析。 + +AST 解析前检查词法复杂度。局部变量使用未转义的 ASCII 标识符。 + +工具调用只开放 `String/Number/Boolean` 的单参数原始值转换,`JSON.parse/stringify`,`Object.keys/values/entries`,`Array.isArray`,`Number.isFinite/isInteger`,`Math.abs/floor/ceil/round/trunc/min/max` 和 `Uint8Array.from`。字符串可用 slice/substring/charAt/at/includes/startsWith/endsWith/indexOf/lastIndexOf/trim/toLowerCase/toUpperCase/split/replace/replaceAll;replace 的搜索参数只接受字符串,保留 JavaScript 字符串替换模板语义。数组可用 push/pop/slice/concat/join/indexOf/includes/reverse/at,Uint8Array 另支持 subarray。工具拒绝用户回调和隐式对象转换,输出在分配或导出前受大小、结构和工作预算检查。 + +不支持 import/export、额外函数或闭包、递归、async/await/Promise、class/new、try/catch/throw、正则字面量、模板字面量、解构、spread、可选链、动态函数调用和属性自增/复合赋值。不能访问 eval、constructor、prototype、原型链修改入口或内部执行工具;不提供文件、网络、KV、通知、timer、DOM 或平台对象。普通 JS JSON Number 与重复键行为不等于原生无损 JSON Patch。 + +输入含 `phase`、只读原始 URL/方法、当前 request、response 阶段的当前 response,以及本次声明选择的 body。headers 是保留同名多值顺序的 `{name,value}` 序列,不承诺 H2 的原始完整线序。none 的 body 为 not-requested;text 是严格 UTF-8 字符串,bytes 是完整解码实体的 Uint8Array,空正文与未提供正文不同。输入修改不直接提交;不能无损构造字符串 header 快照时跳过调用,不丢字段或有损替换。 + +返回值必须是普通有限数据记录:`{type:"pass"}` 保留输入,modify 可包含 url/method/status/headers/body,respond 以 status、初始 headers 和正文生成完整本地响应,`{type:"abort"}` 关闭当前 H1 交换或 reset 当前 H2 流。modify 的 headers 只能是有序 set/add/remove 操作,set/add 的 values 是非空字符串数组;respond 的 headers 是初始 `{name,value}` 序列。响应阶段不能改 URL/方法,请求阶段不能改 status。未知字段、undefined/null/Promise、accessor、自定义 toJSON、非有限数、孤立 surrogate、共享/循环结果和非法字节载荷均使整次调用失败。 + +普通请求 method 可改合法 token,但不允许涉及 HEAD/CONNECT 的方法转换;OPTIONS `*` 的请求脚本只提供 none,modify 只改普通 headers。普通完整响应 status 可在 200..599 之间变更;204/205/304/206 或带 Content-Range 的响应不变更 status,普通响应也不能改成这些特殊状态。respond 不生成 1xx/101/206 或 Content-Range;HEAD、204/205/304 不允许非空实体。framing、Host、Content-Encoding 等协议字段仍由 Core 管理;JS 另不能写代理认证字段。每次结果最多 100 个 header 操作/初始字段、100 个 set/add 值,控制字段按现有开销算法累计最多 32 KiB。 + +混用顺序固定为原生 URL → 原生 request header/body → request JS → 最终目标规划与上游转发 → 原生 response header/body → response JS → Core 校验发送;全部选择器继续使用原始 URL。JS 按声明顺序串行累计,失败只回到该次输入,保留原生和前序脚本结果;跨 origin 先清继承的 Authorization/Cookie,回退不恢复前序已清理凭据。respond/abort 终止后续链,本地响应不再递归执行 response 脚本。 + +原生与 JS 共用 256 KiB 单份实体和 4 MiB 非等待正文账本,桥接实际副本与输出也计费;没有正文需求不缓冲全文。原生正文继续使用 UTF-8 资格与事务;bytes 模式不要求 UTF-8,但保留 HEAD/无体/部分响应、流式、trailer 和原始协商排除。JS text 变化输出 UTF-8 identity,bytes 变化输出 binary identity,不自动追加 UTF-8 charset;无变化保留该次输入表示。正文不可用时跳过要求正文的脚本,none 仍可执行。 + +Apple 后端对可证明等价的闭合脚本使用静态执行计划,其余受支持的脚本使用独立 JavaScriptCore 上下文。两条分支执行相同的事务、期限与资源准入规则。调用内对输入对象的修改仍需经结果校验才能应用。 + +单次调用的期限为 100 ms(包含排队),最多 100,000 次受控 tick。请求和响应 JS 阶段各有 1 秒总期限,正文收集与传输使用各自的期限。取消及超时后的回收等待同步操作和实际执行 owner 结束;2 MiB 的累计分配工作预算约束执行工作量。正文许可随实际输入、输出、桥接副本和发送引用持有至最后一次释放。 + +## 编译期诊断 + +启用非默认构建功能 `http-diagnostics` 后,可通过 [Invoke](invoke-api.md#gethttpdiagnostics仅-http-diagnostics-构建) 读取 HTTP、脚本与 TUN 的进程级计数。活动工作、累计量与峰值分开解释。通过真实 Stop 和 owner 退出后的静止快照核对资源释放。脚本计量区分静态 Plan 与 JavaScriptCore;设备或性能验收使用实际测试窗口。 + ## URL 阶段 规则共有必填 `url`、`action`,可选 `match`、`enabled` 和展示用 `name`。`match` 为 regex(默认)、exact 或 prefix,不根据文本猜测。URL 动作为 replace、redirect302、redirect307、reject;前三者必须有 replacement,reject 不接受替换参数。 @@ -86,9 +153,9 @@ rewrite: JSON Patch 支持 RFC 6902 的 add/remove/replace/move/copy/test 和 RFC 6901 Pointer;`value` 可为真正的 null、布尔、数值、字符串、数组、对象。配置数值必须能无损转换,不能静默舍入;业务 JSON 保留数值原文并拒绝重复键。空 patch 不触发解析或重新编码。非法 JSON、Pointer 或失败的 test 导致整个正文阶段原样旁路。 -只有被正文规则选中的消息才缓冲。原始、解码、中间和最终正文各限 256 KiB;进程共享 2 MiB 正文工作区,包含 JSON 与 codec 临时空间。先预留再分配,无额度直接旁路;发送期间保留额度。未知长度最多探测上限加一字节,超限按原实体字节回放已读前缀和余下数据,不截断。传输中断、超时和取消仍是错误,不能假装完成。 +只有被正文规则选中的消息才缓冲。原始、解码、中间和最终正文各限 256 KiB;进程共享 4 MiB 正文工作区,包含 JSON 与 codec 临时空间。先预留再分配,无额度直接旁路;发送期间保留额度。未知长度最多探测上限加一字节,超限按原实体字节回放已读前缀和余下数据,不截断。传输中断、超时和取消仍是错误,不能假装完成。 -支持 identity、gzip、deflate、br;按收到的 Content-Type、charset、Content-Encoding 和原始请求 Accept-Encoding 判断资格。改写后使用 UTF-8 identity,修正长度与表示元数据并删除失效的校验/签名字段。没有实际改动时保留原始编码表示。未知编码、非法文本、压缩校验失败或预算不足均整阶段原文旁路。 +符合正文条件的消息在限额内收集一次,原生规则和脚本共用工作区。收集或解码失败时回放原始消息,传输失败按真实错误处理。发送切片保留实际缓冲区的预算占用。 HEAD、无正文状态、206/Content-Range、CONNECT、Upgrade、SSE、gRPC、multipart 及带 trailer 的消息不做正文改写,普通 header 规则仍可执行。选中正文的 H1 Expect: 100-continue 在读取前完成握手;未匹配消息保持原有流式背压、早响应和半关闭语义。H1/H2 与成功解密的 HTTPS 共用规则与预算。 @@ -111,8 +178,20 @@ MITM 支持 HTTP/1.1 与 HTTP/2。HTTP/3 MITM 暂不支持;UDP/QUIC(含 H3 只终止允许的 SNI/端口;无 SNI、ECH(含 GREASE)和未授权名称保持透明。每个原始 HTTP authority 独立授权,同一 H2 连接不扩大权限。最终上游按实际目标验证证书,使用受保护出口;不通过关闭验证处理 pinning 或客户端证书要求。 +下游 rustls 写侧缓冲使用统一 TLS 默认值 64 KiB;这是 HTTP 上下文的固定默认策略,不接收节点或低层调用者的容量覆盖。它与 TUN 发送缓冲、H2 窗口及 4 MiB 正文账本分别计量;正文许可继续持有至实际发送 owner 释放,TLS 局部容量不代表进程 physical footprint。 + H1 上游协商 HTTP/1.1,H2 下游对接实际协商的 H2 或 H1。普通 H2 CONNECT 返回 405;WebSocket 使用 H1 Upgrade。叶证书最多 32 项、材料预算 256 KiB、空闲 10 分钟,有效期不超过 24 小时或 CA。 -H2 每连接最多 8 个活动请求,流/连接接收窗口 32/64 KiB,头最多 32 KiB/100 字段,帧 16 KiB,关闭动态 HPACK 表。上游不跨请求复用。上传使用 30 秒无进展期限;上传完成后响应头另有 30 秒等待期限,提前响应仍与上传并发。取消和 Stop 覆盖上下游、正文与驱动。 +## 业务上游复用 -当前会话固定主设置、实际 payload、授权和 CA。保存/资源刷新只产生待应用候选,节点选择和分流更新继承 active。显式重连准备候选后切换,后续启动失败使用旧实际内容恢复,不重读已变化文件;普通 Stop 释放私密材料。共享入口见 [Invoke API](invoke-api.md) 与 [CLI](cli.md)。 +同一下游连接可保留一个可接收新请求的 H1 上游或 H2 会话。每个请求仍需独立授权、改写并按最终目标选路。复用要求最终 origin、资源代际、入口上下文及完整静态连接器身份一致。HTTPS 还要保持整个改写链的原 origin,并通过最终目标的证书、SNI 和 ALPN 校验。跨 origin 或 scheme 的请求建立独立上游,即使后续再次改回。 + +- **H1** 要求持久的 HTTP/1.1、空正文或固定长度请求,以及原始响应的完整 Content-Length 消费。HEAD、CONNECT、`OPTIONS *`、Expect、Upgrade、分块与 trailer 使用独立交换。早响应、未完整上传、关闭、截断或传输错误会退役上游;已发送请求的失败按原错误返回。 +- **H2** 要求实际协商 HTTP/2。空正文可随 HEADERS 发送 END_STREAM,其余上传在实际正文、trailer 和 END_STREAM 完成后才算完整。早响应、上传失败及停止可使上游退役。复用时如果在提交请求前观察到远端 GOAWAY,旧连接停止准入,当前请求沿已选路由和原连接期限拨号一次。已在途请求继续持有原 driver 至结束。已提交请求按原错误路径处理。单次路径有独立的上游所有权。 +- **H2 局部上限**为每个下游连接 8 个活动请求,流及连接接收信用各 64 KiB,头 32 KiB/100 字段,帧 16 KiB,动态 HPACK 表关闭。下游每流响应发送容量为 64 KiB,每次最多提交 16 KiB;上游发送容量为 16 KiB。上传以 30 秒无进展为限,完成后另等待响应头至多 30 秒。共享正文预算延续至最后发送引用释放。 + +固定连接器资格由实际出站图提供。动态策略组、未知上游路径、会改变安全身份的外部资源以及已停止的节点走单次路径。VLESS 的上传、下载腿分别校验其真实 TCP 或 UDP 载体;在 macOS 上,`mptcp: true` 沿用普通 TCP 路径。各协议的静态端点、安全身份和封装限制见 [出站契约](outbounds.md)、[VLESS](vless.md) 和 [XHTTP](xhttp.md)。保留的业务连接继续拥有其协议逻辑流和租约,直到退役、下游结束或 Stop。 + +## 会话边界 + +运行会话固定主设置、实际 payload、脚本、授权和 CA。保存与资源刷新产生待应用候选,节点选择和分流更新沿用运行中的 HTTP 资源。显式重连先准备候选再切换,失败恢复原会话的实际内容。普通 Stop 释放私密材料。[Invoke API](invoke-api.md#独立-http-设置与私密上下文) · [CLI](cli.md) · [离线回归](../tests/README.md#http-处理与-invoke) diff --git a/docs/inbounds.md b/docs/inbounds.md index ef1ac3f..b70dbe1 100644 --- a/docs/inbounds.md +++ b/docs/inbounds.md @@ -47,6 +47,21 @@ HTTP 每个请求重新验证,SOCKS TCP 和 UDP 授权关联保留握手身份 Mihomo 当前实现不把 SOCKS TCP 身份传给独立 UDP 接收;Vole 的授权 UDP 保留 真实握手身份。Mihomo HTTP 在无认证时也可能记录请求声称的用户,Vole 保持为空。 +## 共享嗅探与 HTTP 处理 + +SOCKS5 CONNECT、普通 HTTP、HTTP CONNECT 和 TUN TCP 共用主配置的 sniffer +策略;各入口不另设开关。全局关闭、未声明协议或目标端口不匹配时不嗅探。 +来源/目标地址排除先于读取;纯 IP 由 `parse-pure-ip` 控制,redir-host 提示由 +`force-dns-mapping` 控制,显式域名与已恢复的 fake-IP 名字须匹配 `force-domain`。 +`skip-domain` 排除识别结果,协议级 `override-destination` 决定只提供选路提示还是 +同时替换目标。普通 HTTP 使用已解析的原始 authority 应用同一策略,不为嗅探读取正文。 + +四类 TCP 入口也共用独立 [HTTP 处理](http-processing.md)。主 sniffer 的关闭、排除或 +目标覆盖不改变独立 HTTP/MITM 授权:明文按原始目标端口的 `http-ports` 准入,TLS +按 MITM 端口、SNI 允许/排除与 CA 准入。普通 HTTP 代理请求不会因为端口在 MITM +列表就变成 CONNECT。未认领的业务字节完整回放后继续原嗅探/选路;已有 HTTP +上下文的连接使用其固定代际 Dispatcher,入口类型、来源、本地端口和认证身份保留。 + ## HTTP 每个请求独立认证,缺失、错误、重复或非法 Proxy-Authorization 返回 407 并关闭, @@ -55,15 +70,13 @@ Mihomo 当前实现不把 SOCKS TCP 身份传给独立 UDP 接收;Vole 的授 ### 普通转发 HTTP/1.0 和 HTTP/1.1 使用绝对 `http://host[:port]/path?query` URI。每个请求重新 -确定目标、选路和建链,转发为 origin-form 并重建 Host,上游不跨请求复用。 -客户端可以 Keep-Alive 或顺序预发送;固定缓冲保存预读,只有上传完成且响应有明确 -边界才处理下一请求。不会把旧目标连接用于下一请求。 +确定目标和选路,转发为 origin-form 并重建 Host;默认每请求建立上游。 +客户端可 Keep-Alive 或顺序预发送,固定缓冲保存预读。只有上传完成且响应边界明确才继续处理。启用 HTTP 处理时,符合[复用条件](http-processing.md#业务上游复用)的请求可使用同一上游。 - Content-Length 精确转发;没有正文长度的普通请求视为空正文。 - chunked 按块解码并重编码;合法扩展不透传,合法 trailer 保留。 - HEAD/1xx/204/304 无正文;1xx/204 携带正文定界字段失败关闭,HEAD/304 可保留表示长度。 -- 转发 100 Continue 等临时响应;上传和响应读取并行。提前最终响应会终止上传、 - 转发响应并关闭客户端,不把余下正文误作新请求。 +- 转发 100 Continue 等临时响应,上传和响应读取并行。最终响应到达后,只有真实正文写入和 flush 完成才算上传完整;其余交换转发响应后关闭连接。 - 无长度响应由 EOF 定界并关闭;HTTP/1.0 客户端接收 chunked 响应时去块后关闭。 - 重复 Content-Length、CL/TE 并存、歧义长度、非法控制字符/分块、截断或超限均失败关闭。 认证、内部诊断、Connection 指名及逐跳字段不泄漏给目标;trailer 不能携带认证、 @@ -73,7 +86,7 @@ HTTP/1.0 和 HTTP/1.1 使用绝对 `http://host[:port]/path?query` URI。每个 ### 隧道 -CONNECT 通常在上游成功后返回 200,保留头后的预读数据。匹配 TCP 嗅探策略时先返回 200, +CONNECT 通常在上游成功后返回 200,保留头后的预读数据。匹配 TCP 嗅探策略或独立 HTTP/MITM 候选端口时先返回 200, 再读取有界业务前缀并按嗅探结果建链;此后建链失败直接关闭隧道。Upgrade 只接受无正文请求; 合法 101、Connection/Upgrade 一致且选中请求协议时才切隧道,保留双方预读和 TCP 半关闭。非 101 按普通响应处理,非法切换返回 502。 @@ -93,7 +106,7 @@ trailer 8 KiB/100 字段,每个最终响应前最多 16 个临时响应。正 仅支持 RFC 1928/1929 的 SOCKS5 CONNECT、UDP ASSOCIATE 和用户名密码协商。 不降级绕过已配置认证。精确读取握手并保留 CONNECT 后业务字节;通常在上游成功后回复成功。匹配 TCP 嗅探策略 -时先确认 CONNECT,取得业务前缀后建链,失败关闭已确认的连接。 +或独立 HTTP/MITM 候选端口时先确认 CONNECT,取得业务前缀后建链,失败关闭已确认的连接。 目标保留 IPv4、IPv6 或域名交给 Dispatcher,入站不提前解析。TCP 每方向复制 4 KiB, 保留半关闭。 @@ -117,6 +130,3 @@ wire 最大 65,507 字节,额外 sentinel 识别截断,自有 UDP socket 请 TUN 使用独立 MTU;SOCKS5 数据不计入 Controller 的 TUN 流量。 [验收边界](acceptance.md)区分容器双栈与真实 LAN/物理 IPv6,不能相互替代。 - - -显式启用独立 HTTP 配置时,mixed HTTP/CONNECT 与 TUN 共用[URL rewrite](http-processing.md)和同代 Dispatcher。规则先确定最终 URL,再选路;本地动作不连接旧目标。请求正文与 Upgrade 继续复用本文件的流式 framing/relay;入口认证和用户名语义保持。 diff --git a/docs/invoke-api.md b/docs/invoke-api.md index 1d580ab..1e3c81c 100644 --- a/docs/invoke-api.md +++ b/docs/invoke-api.md @@ -117,6 +117,20 @@ stopped -> preparing -> prepared -> starting -> running `version` 和 `buildIdentity` 中的 `coreVersion` 取自 Cargo package version。源码 commit、lockfile 和产物 hash 由发布系统记录。 +### `getHttpDiagnostics`(仅 `http-diagnostics` 构建) + +同时启用 `http-diagnostics` 与 `invoke` 时,可发送读请求: + +```json +{"method":"getHttpDiagnostics","payload":{}} +``` + +省略 `instanceId`,使用空 payload。此调用直接读取 [进程级观测](http-processing.md#编译期诊断),无需初始化。Apple 另提供本 Core 自有线程的 QoS 请求记录。累计量可比较同一进程的前后读数,峰值应按其实际覆盖范围解释。App 和 Network Extension 各自报告本进程。默认构建返回未知方法。 + +### `runHttpScriptPlanValidation`(仅 tvOS 诊断构建) + +在同时启用 `http-diagnostics`、`inbound-http` 与 `invoke` 的 tvOS 构建中,尚未初始化或创建实例的独立进程可提交 `{"method":"runHttpScriptPlanValidation","payload":{}}`。省略 `instanceId`,使用空 payload。该调用离线运行固定合成用例,比较静态 Plan 与 JavaScriptCore 的事务结果、预算及取消后的释放。结果包含实际执行的范围、用例结果和进程身份。开始验证后,后续业务须使用新进程。默认构建和其他平台返回未知方法。 + ### `initialize` 参数和幂等语义见“初始化与生命周期”。成功时返回规范化后的 `dataDir`。 @@ -637,6 +651,8 @@ updateConfig 省略 HTTP 时继承 active;同设置可继续使用 active。 method 默认 GET,response.status 必填;headers 是保留顺序与重复项的二元数组,bodyBase64 表示原始编码实体。外部资源只取同来源已准备内存候选;缺少则返回 resourcesReady false/unprepared,不伪装为未命中。总开关关闭仍可演算启用规则;没有样本只报告被选中。结果包含 U0/U1、来源索引、URL 结果、各阶段执行或旁路与样本输出,httpsReady 不宣称真实信任就绪。结果不含 CA,也不持久化正文。 +当前 `testHttp` 只演算原生规则,不执行 JS。`http-scripts.enabled: true` 且脚本列表非空时明确返回不支持错误,不静默跳过脚本后报告演算成功;脚本总开关关闭时仍做源码 AST 静态校验,然后只演算原生规则。`validateConfig` 的源码校验同样不初始化脚本后端。 + ### foreground 私密文件 可选 httpConfigPath、httpCaPath 都是明确的普通文件路径,不自动搜索、不从环境获取;HTTP 文件最多 1 MiB。私密文件格式为 `{"certificate":"...PEM...","privateKey":"...PEM..."}`,Unix 要求当前用户所有、group/other 权限全关闭,并拒绝符号链接。foreground 保留 HTTP 文件目录作为 baseDir。CLI 只传路径,读取仍归 Invoke;空路径与 `-` 拒绝。 diff --git a/docs/outbounds.md b/docs/outbounds.md index 9acdf65..4a4aef8 100644 --- a/docs/outbounds.md +++ b/docs/outbounds.md @@ -92,8 +92,9 @@ DoQ/DoH H3 的当前 DIRECT 发送预算为 IPv4 65,507、IPv6 65,527 字节, ECN 开启时传递实际发送标记和接收元数据;关闭时不发送/交付 ECN 标记。 系统无法开启 ECN 接收元数据时,保留同一受保护 socket,沿用原单包、无元数据路径。 GRO 保持关闭,接收仍使用一个有界完整包,不放大 QUIC 接收区或 socket 缓冲。 -代理 hop、HY2 的 pacer/混淆/Realm、quiche 后端以及非 Linux 平台当前保持单包且不保留 ECN; -这些路径不声称消费新元数据能力。停止时撤销物理 socket 的共同租约;保留已关闭的 QUIC +macOS 的 DIRECT QUIC 适配器可提交当前就绪的最多 4 个独立数据报、合计 8 KiB。只确认实际提交的 FIFO 前缀,保留未发送后缀。能力不可用时逐包发送,物理错误关闭原 owner。此能力适用于 Quinn 和 quiche,使用 Tokio 公共发送接口。 +代理 hop、HY2 的 pacer/混淆/Realm、quiche 后端以及非 Linux 平台仍保持独立数据报边界且不保留 ECN; +这些路径不消费上述Linux元数据能力。Linux原生路径停止时撤销物理 socket 的共同租约;保留已关闭的 QUIC 连接或写就绪 poller 不会延长物理 fd 的生命周期。GSO 的明确能力错误只关闭后续批量发送,失败批次 作为 UDP 丢失交给 Quinn 的正常 ACK/重传;不会立即重发该批次,不掩盖地址、策略或 ECN 错误。H3 的正常传输、认证、PMTUD、取消及同步 Stop 仍沿原所有者。 @@ -186,10 +187,12 @@ max-connections <= 0 时,只在 max-streams > 0 且流数 < max-streams 时复 不增加周期 QUIC keepalive。逻辑空闲回收与 QUIC 传输空闲是不同期限。 TCP 流使用原始字节,无 gRPC 帧;建立流后独立消费响应头,允许服务端等待 client-first 业务。 +H2 每条物理连接最多保留 256 个近期由本地重置的流状态,由原版 h2 使用默认期限处理途中抵达的响应帧。 udp 缺省 false,开启后使用 `_udp2` CONNECT 承载多目标数据报。 health-check 缺省 false,开启后使用 `_check` CONNECT;成功 CONNECT 响应重置 7 秒计时, 单次探测期限为7秒。两模式的UDP业务都使用可靠CONNECT流,不使用QUIC DATAGRAM。 关闭只结束当前逻辑流;节点Stop取消并join池、探测、H2/H3及QUIC驱动,释放受控上游。 +共享 quiche H3 适配器在最后一个应用句柄释放时清理被取消流的正文。底层 RESET/STOP 未结束时保留请求索引,等 QUIC 收尾后回收。兄弟请求继续使用原连接。 H3 外层无论业务 udp 是否开启,都要求受控上游提供双向至少1200字节UDP路径; QUIC payload 最大1400并取实际双向上游预算交集,PMTUD不超过该预算,不回落TCP或DIRECT。 @@ -266,6 +269,7 @@ TCP CONNECT 仍按最新 RTT 计算。两类业务保留原退避、超时上限 Stop 结束驱动并回收驱动缓存,不等待应用读取;外部仍持有流的已递交数据由读取或释放流回收。 待确认明文仍持有发送预算。物理驱动每轮最多接收8个就绪数据报、发送8个数据报, ACK 优先于该会话的批量数据,会话轮换服务;接收每8包让出一次执行机会。 +macOS 的低熵 UDP 载体可为已建立 SID 的首次 DATA 提交当前就绪的最多 4 包、8 KiB,计入原发送、拥塞与未确认预算。正完成只确认 FIFO 前缀,余下密文沿原路逐包发送。ACK、重传和控制帧使用各自路径。 Mieru UDP 向共享 Dialer 请求512 KiB物理接收缓冲;当前Linux接受时通常为1 MiB有效容量。 这是内部性能提示,OS可钳位或拒绝;保留原socket、protect、接口绑定及停止所有权, 不改变逻辑包预算,不新增配置字段,协议自有池仍管理自己的物理载体。 @@ -276,6 +280,8 @@ Mieru UDP 向共享 Dialer 请求512 KiB物理接收缓冲;当前Linux接受 低熵编码作用于数据密文,认证 tag 保持原值;按真实载体预算缩小明文分片, 不会扩大队列或接收预算。重传重新应用 nonce 与 padding,控制帧分片由物理写任务完成。 +业务 HTTP 可在单物理端口和不可变 factory/凭据/编译 traffic-pattern 下保留同 origin TCP 流:TCP 载体递归证明完整静态 TCP 图,UDP 载体仅接受固定直接 UDP 路径;端口范围、域名、动态组、未知依赖及已停止 client/Dialer 保持单次路径。现有 logical stream 不因一个 HTTP 请求结束而归还载体,所有固定 mux/握手模式沿原语义;NO_WAIT 仍先发送合并的 SOCKS 请求与首段业务数据,再在首写成功返回前验证 SOCKS 回复。协议池、随机调度、信用、可靠性、计时器和 Stop 屏障保持,见[HTTP 处理](http-processing.md)。 + ## MASQUE `type: masque` 由 `outbound-masque` 提供。缺省、空串及非 `h2`/`h3-l4proxy` @@ -297,8 +303,7 @@ PMTU 反馈按连接生效,通过包层软件分段恢复,重传由官方 sm 初始发送 MTU 取配置与真实隧道预算的交集,避免已知预算下的持续二次分段。 内部队列、capsule 和 packet 均有界,停止等待其工作任务回收。 H3 IP 的物理 UDP 请求沿原受控 dialer 携带 512 KiB 接收缓冲提示;系统可限制或忽略该提示,不构成进程 RSS 或真机内存保证。 -当底层实际报告发送预算缩小时,只反馈当前过大包,不关闭其它业务流。 -稳定路径的 MTU 下降目前不会自动触发 QUIC PMTU 重新探测。 +macOS MASQUE H3/IP 与 H3/L4 的 Direct/LazyDirect 路径可在首次发送时为同一受控 UDP socket 固定完整 peer。绑定、保护和接口检查完成后才 connect 并发布,初始化失败结束本代际。Group、Proxy 和 codec 路径仍使用各自的传输。 `network: h3-l4proxy` 使用 Cloudflare L4 HTTP/3 CONNECT,每个 TCP 目标独占请求流,共享受控 QUIC 连接; 等待 2xx 响应后才交付业务流,拒绝响应不取消其它流,节点 Stop 等待所有驱动退出。 @@ -407,7 +412,7 @@ Upgrade 的 ED 仅允许默认 Sec-WebSocket-Protocol 头(大小写不敏感 gRPC 的 HTTP authority 使用非空 SNI,否则使用 server,不包含端口;不改变物理拨号地址。 gRPC 选项与 VMess/VLESS 共用:省略或空 service-name 默认 GunService,普通名映射 /name/Tun,以 / 开头使用完整路径;省略或空 user-agent 默认 grpc-go/1.36.0。 ping-interval 为秒,0 不主动 PING,负值明确拒绝;max-connections/min-streams/max-streams 接受带符号整数,负阈值禁用相应分支。三项池阈值省略或字面全零时归一为4/0/0,Mihomo为1/0/0;显式 max-connections=1 或2保留各自策略。正 max-connections 优先于 max-streams。 -每个节点独立拥有连接池,空闲连接总是复用;复用保留原上游选择、TLS 身份和认证策略,每条逻辑流仍单独发送 Trojan 认证头。 +每个节点独立拥有连接池,空闲连接总是复用;复用保留原上游选择、TLS 身份和认证策略,每条逻辑流仍单独发送 Trojan 认证头。业务 HTTP 可在静态连接器资格有效时保留已建立的逻辑流,具体条件见[业务上游复用](http-processing.md#业务上游复用)。 Trojan 私有 gRPC 池在原绝对期限内等待 H2 SETTINGS、提交并 flush 完整认证请求, 随后允许 client-first 上传等待迟到的 HTTP 响应,不把建链期限继续套用到业务。 @@ -454,6 +459,13 @@ TLS 支持独立的 `name-cert-verify` 和成对内联 PEM 或文件路径 `cert - h2 的 authority 列表省略/空时使用 www.example.com,path 省略/空时为 /,每流选一个 authority,通过 HTTP/2 PUT body 双向传输;明文 prior knowledge、TLS h2,无 gRPC 帧。 +业务 HTTP 仅在 H2 配置恰有一个固定完整 URI、明文或普通静态 TLS、安全身份与实际物理/上游路径均 +可证明固定且节点未停止时,允许按 HTTP 处理合同保留同 origin 连接。保留的连接继续持有原 VMess +逻辑流与 H2 driver,不增加载体池,也不在每个业务请求后重新认证或归还载体。多 URI 配置保持 +每次新流选择 authority 的原行为,业务 HTTP 仍使用单次路径。 + +启用 `inbound-http` 时,HTTP 首包伪装仅在实际节点为明文安全身份、恰有一个固定 URI、每个已声明头恰有一个值(无头也固定),且完整静态上游和节点所有者均通过原门禁时,提供同 origin 业务 HTTP 复用资格。TLS 即使身份固定、多 URI 或多头值候选及其它安全模式仍为单次路径;不在资格查询时选择随机值。每条上述固定明文 HTTP 的完整 TCP 流沿原 child 绑定独立读写唤醒,绑定按固定类型决定,不因 Stop 已撤销许可而省略。父停止唤醒两个方向,后续轮询按原取消错误释放 IO;单流 Drop 不停止父或兄弟流,HTTP 父级仍负责实际缓存退役与释放。该绑定不增加任务,不改变原 raw owner、VMess AEAD/目标、整流关闭、传输、建链期限或 UDP 路径;没有 `inbound-http` 时不新增资格或绑定。 + 关闭对齐 Mihomo:TCP/WS 可保留上传 EOF 后的读取;gRPC/HTTP/H2 关闭整条逻辑流, 完整响应应在关闭前读取,不统一要求半关闭尾包。 @@ -566,6 +578,8 @@ pacer;这是混淆不是认证,错误密钥由 QUIC 拒绝,短包有界丢 官方 Hysteria 已验证版本的 4096 字节回包缓冲包含头,更大回包可能在分片前丢弃。 原生测试记录实际版本和限制,Vole 完整 4096 字节另对 Mihomo 验证,不修改第三方。 +在业务 HTTP/MITM 中,仅字面IP、固定客户端TLS身份、无跳端口/Realm且物理直接UDP出口可证明固定的 Hysteria2 节点,才可保留同origin业务TCP/TLS连接。代理UDP链和动态身份仍走原单次路径。该资格不改变上述认证会话槽、拥塞/带宽、接收窗口、队列、定时器和Stop所有权;规则与脚本仍每HTTP请求执行,边界见[HTTP处理](http-processing.md)。 + ## TUIC v5 固定 QUIC/TLS 1.3,复用官方 Quinn、rustls/ring 与共享受控数据报适配器。 @@ -584,6 +598,13 @@ Authenticate 与 Connect 没有成功 ACK;本地 open 成功不是密码通过 必须由最终拒绝和原站零业务验证。Connect 为双向 QUIC 流,不引入 HTTP/3 请求。 流关闭结束该逻辑双向通道,与 Mihomo 对齐,不影响兄弟流。 +启用业务 HTTP 处理时,固定 TLS 身份与字面物理 IP 的直接 UDP 上游可提供静态 TCP 复用证明, +包括逻辑 server/SNI 为域名但显式 ip 固定实际目标的情况。该资格适用于 native/quic/UoT 配置下的 +普通业务 TCP;文件客户端身份、动态物理目标、代理/组 UDP 上游及已停止的节点或 Dialer 不提供证明。 +已支持的外层静态 TCP 链可按原规则依赖此 TUIC 叶。HTTP 父级仍要求同 origin、路由/资源身份一致及 +实际完整上传/响应;实际保留时继续持有同一 TUIC Stream 和 lease,退役与 Stop 沿原所有者释放。 +此证明不改变 TUIC wire、流关闭、物理会话池、UDP/UoT、UNI、队列、计时器或日志;细节见业务 HTTP 契约。 + 业务 UDP 始终可用;`udp` 可省略或填 true/false,均不禁用它,组 `disable-udp` 仍生效。 外层 QUIC 始终需要有效双向至少 1200 字节的数据报路径。 未开放 DATAGRAM、预算不足、protect 失败或只支持 TCP 的上游均失败,不回退 TCP @@ -606,19 +627,24 @@ quic 收齐声明长度的报文后立即交付并释放接收流,TCP 通道 目标改写、域名目标及不同出站实例在该追踪路径保留独立关联。 未启用追踪时沿用既有路由缓存的关联复用规则。 -每节点按需复用物理会话。native 按完整来源地址(含端口)稳定分配至两个按需池, -同源 TCP/UDP 保持池亲和;UoT v2 保持原共享池。quic relay 的 TCP 与原生 UDP -各自按需使用独立池,避免逐包单向流的回包积压占用 TCP 所在连接。每池仍沿原所有者 -阈值准入、退役与释放,不增加单个连接的窗口或远端单向流信用。两个当前池不是全节点 +macOS TUN 的 quic relay(未启用 UoT v2)对已打开、目标及连接标识未变的 +缓存路由,每来源至多保留一个独立发送操作;等待 UNI 信用或流写入期间继续接收 +同关联的响应。首次路由、新目标、连接标识变化、目标改写及维护到期时沿用原发送路径。 +不增加 sender 任务或数据报队列,原发送绝对期限仍为15秒;取消和关闭先丢弃发送操作, +再结束路由/统计所有权。外部取消或超时不伪记为已完成的出站错误或上传字节。 +并发驻留的发送状态、响应及代际元数据可能增加峰值内存,不保证吞吐或内存收益。 + +每节点按需复用物理会话。native(不含 UoT v2)按完整来源地址(含端口)稳定分配 +至两个按需池,同源 TCP/UDP 保持池亲和。启用 UoT v2 时,普通 TCP 使用池0, +只有内部 UoT magic Connect 使用池1;两池分别复用自己的认证 QUIC 会话。 +quic relay(不含 UoT v2)的 TCP 与原生 UDP 各自按需使用独立池,避免逐包单向流的 +回包积压占用 TCP 所在连接。每池仍沿原所有者 +阈值准入、退役与释放,单个连接的窗口保持不变;远端单向流信用见下述模式约束。两个当前池不是全节点 总连接上限;退役会话仍由既有所有者生命周期释放。流 credit 等待沿用调用方原期限。 native 模式(不含 UoT v2)向共享 Dialer 请求512 KiB物理 UDP 接收缓冲; 这是可钳位或拒绝的性能提示,沿用同一个受保护、已绑定的 socket,不改变 QUIC 信用、 应用队列或逻辑包预算。quic relay 与 UoT v2 不请求该提示;Linux 内核缓冲与进程 RSS 分开核算。 -关联 ID 在同一物理会话 -不重用;65,536 个 ID 用尽后新业务新建会话,旧流继续,最后一个旧所有者退出即回收。 -TCP shutdown 立即完成逻辑关闭,发送所有权保留到 FIN/数据确认或最多 5 秒,防止 -退役池提前丢弃已接受的末尾上传;该等待归节点所有,Stop 直接取消并 join。 -切组不迁移已有池;故障后只有新业务可创建新池,已发送业务不自动重放。 +macOS 的 quic relay(不含 UoT v2)为直接声明的 Direct/LazyDirect 物理会话固定完整 peer,TCP 与 UDP 池均适用。首次发送在原 socket 完成绑定、保护与接口检查后 connect。Peer 变化使用新的传输代际;其余 UDP 路径沿原工厂处理。 `ip` 覆盖物理拨号地址,逻辑 server/SNI 保留。heartbeat-interval 单位毫秒,<=0 回落 10000,同时控制 QUIC keepalive 与实际 v5 HEARTBEAT,两种 UDP relay 模式均用 DATAGRAM。 @@ -627,8 +653,11 @@ recv-window-conn 实际为 stream,recv-window 实际为 connection;正值同 随后采用上述 Middle 策略,默认实际为固定 stream 4 MiB / connection 2 MiB。 窗口是信用额度,不预分配全部缓冲;显式正值不按默认窗口钳位。 -max-open-streams 控制客户端 TCP/UDP 所有者池,不扩大 Quinn 内部远端 stream 表; -远端双向流信用固定为 0,单向流为 32。0 使用100;参考客户端100阈值转换90,入池计数必须严格小于阈值,所以 +max-open-streams 控制客户端 TCP/UDP 所有者池,不把业务所有者阈值写入 Quinn 远端 stream 表; +远端双向流信用固定为0。仅macOS、quic relay且未启用UoT v2的实际UDP池1,通告独立的128条远端单向流许可; +同节点TCP池0、native、UoT v2和其它平台仍为32。实际并行入站decoder仍为32,未增加正文交付队列。 +额外最多96条尚未accept的UNI由Quinn持有,可能增加流表、未读数据和排队驻留;原连接接收信用与payload预算保持, +不预分配128份正文,也不保证进程内存不增加。max-open-streams为0使用100;参考客户端100阈值转换90,入池计数必须严格小于阈值,所以 默认89个同时所有者,其它正N为N-1;1和负值可解析但无法开启业务。饱和新建物理 会话,退役会话继续服务已有所有者,最后所有者退出回收,不重放已发送业务。 @@ -648,7 +677,8 @@ udp-over-stream-version 省略或整数2均使用v2,其余版本拒绝。首 实际错误或超时使关联失效。响应队列1项、任务归节点Stop同步回收。 UoT在可靠流中传输,有丢包导致的队头阻塞成本,不应用原生TUIC分片额度。 -连接未确认发送缓冲1 MiB;最多32个并行入站控制解码器,半条控制流最长5秒, +连接未确认发送缓冲1 MiB;最多32个并行入站控制解码器,半条控制流从decoder接纳起最多5秒, +尚未accept的UNI不在此5秒timeout内,不能宣称128条流都在首帧到达后5秒内结束;原所有者与Stop负责最终回收。 拒绝服务端主动双向业务流。空闲30秒。Stop等待认证、收发、重组、心跳及上游释放, 关闭交换最多一秒;这些是局部结构限制,不是全局业务会话额度。 @@ -689,6 +719,14 @@ TCP 使用官方 `CryptoStream` 的加解密与记录分帧,Vole 构造目标 `client-fingerprint` 仅 ShadowTLS/JLS 插件消费,其余插件不接受该字段。 插件参数只接受对应模式的字段;队列、窗口、连接池和配置范围均有界,取消/Stop 不等待远端回包。 +启用 `inbound-http` 时,三种 SS2022 cipher 的固定 `obfs` HTTP/TLS cover 可与完整静态物理路径一起提供同 origin 业务 HTTP 复用资格;实际代理端点须为字面 IP,未知路径、上游策略组、受约束或停止的依赖仍不参与。HTTP 实体完成后保留同一 SS/cover 流,不重发目标前导、首 cover 或重置 SS AEAD 状态;已关闭、EOF 或不完整的连接按原 HTTP 规则退役,失败请求不自动重放。simple-obfs TLS 仍只是报文外观,不提供标准 TLS 身份证明。 + +启用 `inbound-http` 时,`v2ray-plugin` 仅在 `tls: false`、`mux: true`、early-data 为 0、标准 WebSocket 握手且实际持有上述固定传输时,沿相同字面代理端点和完整静态上游证明提供同 origin 业务 HTTP 复用资格。保留同一完整 SS/单通道 V2Ray mux/WS 流,不按实体重发 SS 目标、mux New 或重置 AEAD;节点停止立即撤销许可。WSS、early-data、`mux: false`、HTTPUpgrade/fast-open、Gost 和 JLS 保持单次业务 HTTP 路径;不建立通用 mux 池。 + +匹配资格的 SS/插件流持有独立取消子令牌。节点停止撤销资格并唤醒读写,HTTP 父级负责释放空闲上游;单流关闭只结束自己的逻辑流。 + +实际 obfs HTTP/TLS 与上述固定 WebSocket mux 流在 SS codec 前聚合首响应密文前缀。AES128 为 59 字节,AES256/ChaCha20 为 91 字节,可跨合法 mux Data 或完整 WS Binary Message。前缀截断返回错误。此读取边界适用于各 feature 组合,HTTP 复用仍须通过上面的独立资格。 + ### ShadowTLS v3 SS 三算法的 TCP 可配置 `plugin: shadow-tls` 与完整 `plugin-opts`,不是新的代理类型。 @@ -708,6 +746,8 @@ flush 排空,关闭最多五秒,不在已切换的 SS 通道中发送 TLS cl shadow-tls-v3,精简构建可单独移除;无 feature 的插件配置在 IO 前拒绝。 v3 的额外四字节记录特征仍存在,完整认证和互通不等于不可识别。 +固定 ShadowTLS v3 cover 与完整静态物理路径,以及无 mTLS 身份或内联身份,可提供同 origin HTTP 复用资格。每条已建流持有独立取消子令牌。业务退役和 Stop 范围见[HTTP 处理](http-processing.md#业务上游复用)。 + ### UDP over TCP v2 `udp-over-tcp` 默认 false;true 要求 `udp: true`,三算法均可用于裸 SS 或 @@ -809,13 +849,34 @@ refresh-server-ip-interval 默认 0,关闭更新;非零值以秒计,新业 节点 raw 包队列和各 peer 发送队列各 32 项;每 UDP 关联响应队列 64 项。UDP 负载上限 为 MTU 减本地 IP/UDP 头,再与调用方收发预算分别取交集;双栈保守扣 48 字节,IPv4 扣 28 字节。TCP 栈输出交给已就绪 peer 时先尝试入队;Full 时只暂持当前包与原 peer -代际,释放 peer 槽位锁后,在同一次队列准入的轮询之间给一次协作调度机会,仍满则丢弃, -TCP 依赖重传。全局取消优先结束输出 pump,其次处理原 peer 取消,不把待交付包改投新代际。 -这次退让会暂缓共享输出 pump,不承诺其他 peer 零等待或固定墙钟时限。 -解密后到栈的 raw 包与 UDP 响应仍在满队列时丢当前包;业务 UDP 发送保留直接等待原 peer -发送队列的可取消路径,不经过 TCP 输出 pump。解密后校验本地目的地址、来源地址族、 +代际并释放 peer 槽位锁;单 peer 等待原队列容量,多 peer 在同一次准入轮询之间给一次 +协作调度机会,仍满则丢弃,TCP 依赖重传。全局取消优先结束输出 pump,其次处理原 peer +取消,不把待交付包改投新代际;不承诺兄弟 peer 零等待或固定墙钟时限。 +解密后的非 UDP raw 包到栈队列 Full 时,每个实际 peer 最多保留一个不超过配置 MTU 的 +pending 包,准入等待由原 peer 事件循环持有,继续处理 TX、定时器与端点更新,不在 UDP +回调内等待。pending 期间暂停外层接收,因此控制报文和业务 UDP 同样可能延迟;到下一次 +已选中的原定时器仍未准入则丢弃 pending 并恢复接收,不新增定时器或承诺 250ms 墙钟上限。 +实际替换端点/重新握手前清理 pending,同端点更新保持原状态;停止和错误释放其唯一所有者。 +32 项队列容量不增加,但每个 pending 额外驻留最多 MTU 字节 IP 负载及有限元数据, +不承诺零内存增量或无损交付。Full 且超过 MTU 的包仍丢弃,不改变栈成功接收的既有预算。 +UDP 响应仍在满队列时丢当前包;业务 UDP 发送保留直接等待原 peer 发送队列的可取消路径, +不经过 TCP 输出 pump。解密后校验本地目的地址、来源地址族、 最长前缀所属 peer 和关联端口;这些是局部结构边界,不是业务连接总数限制。 +macOS 已建立 peer 可批量发送当前就绪的 Noise type 4 数据包,每批最多 4 包、8 KiB,适用于 MTU≤2016。只确认实际发送的前缀;余下原密文沿同一路径发送。接收事件可处理首包及最多 3 个就绪外层数据报,Pending、待准入 ingress、取消或首次握手完成时停止扩展本轮。 + +Direct/LazyDirect 物理路径在首次发送时固定 peer 的完整 endpoint,沿共享 Dialer 完成保护与绑定后 connect。同一端点的 refresh 保持原传输,端点变化时创建新传输并重新握手。接收继续应用 Noise 验证、内层路由和包大小检查。Connected UDP 的来源过滤与 ICMP 错误由内核体现。 + 握手、收发、更新与重试均可取消;驱动由节点持有,调用方 future 丢弃不会丢失任务 所有权。Stop 关闭新准入,取消并等待所有 peer 与退役驱动,关闭各上游(分别最多一秒), 随后等待用户态栈退出;私有 DNS 使用弱节点引用,不延长节点生命周期。 + +业务 HTTP 的静态复用资格仅在节点完整不可变 peer 图的所有初始及适用刷新路径均可证明为 +固定字面 IP 的直接物理 UDP 路径时提供。资格使用每个实际 peer 的端点及原驱动的 +`for_server` 派生,不以代表性 address/port 或已认证的首 peer 替代完整图;动态域名、 +上游代理/策略组、未知依赖、受约束或停止的 Dialer、停止节点保持单次业务 HTTP。 +非零刷新仍须证明同一物理 Dialer/IP4P 策略产生相同实际地址和端口,不支持动态漫游。 +查询不创建栈、Noise、解析或 socket,也不查询 channel 是否健康;实际 TCP 保留原 peer +取消 token 和 HTTP 失活退役语义。业务域名及私有 DNS 的原解析路径、实际选路/资源代际、 +Noise 重键、全部队列和 Stop 所有权保持;完整 HTTP 资格与退役条件见 +[HTTP 处理](http-processing.md)。 diff --git a/docs/runtime-resource-policy.md b/docs/runtime-resource-policy.md index 1fd2a37..6cdcd16 100644 --- a/docs/runtime-resource-policy.md +++ b/docs/runtime-resource-policy.md @@ -15,10 +15,8 @@ Tokio `new_multi_thread()`,不按 TUN 分叉,不自行读取 CPU 数或设置 worker 数。 worker 数遵循 Tokio 默认行为(包括其 `TOKIO_WORKER_THREADS` 环境覆盖); 线程栈使用 Tokio / Rust 默认值,不固定为 1 MiB。 -启动准备和 `measureDelay` 保留共用的单线程执行策略,不按 TUN 分叉。 -工作线程(含阻塞任务线程)继承 Invoke 重入保护, -Apple 平台另保留线程局部日志作用域;同步停止仍等待子任务与运行时线程退出。 -Release 构建优先吞吐(`opt-level = 3`),保留 thin LTO 与现有缓冲、队列边界。 +Apple 引擎在自建 owner 及 Tokio 新线程入口尽力请求 USER_INITIATED QoS。 +宿主调用线程保持自身策略。该观测记录公开的请求等级,线程释放按实际 join 确认。 ## TUN 结构上限 @@ -30,7 +28,9 @@ Release 构建优先吞吐(`opt-level = 3`),保留 thin LTO 与现有缓 每关联 UDP 入站 64 普通 UDP 响应 256 DNS 响应 128 -每个 TUN TCP 方向缓冲区 4 KiB +TUN TCP 转发复制缓冲(每方向) 4 KiB +TUN TCP 接收总预算(每流) 32 KiB +TUN TCP 发送总预算(每流) 128 KiB TLS / 流式 XHTTP 缓冲区 64 KiB XHTTP packet-up 单批 H1/H2 64 KiB;H3 128 KiB DNS 结果总容量(每角色) 默认 4,096 项,dns.cache-max-size @@ -55,17 +55,17 @@ MTU 由 `tun.mtu` 配置,默认值和平台限制统一见 [TUN 平台层](tun ## TCP 与握手 - TCP 流按需创建任务;TUN 转发每方向缓冲区为 4 KiB。 -- netstack 的 TCP 应用队列从空分配按实际写入有界增长,保留每方向 16 KiB 逻辑上限;排空不收缩,连接释放时销毁。smoltcp 收发缓冲仍各为 16 KiB,不用进程内存或连接总数改变容量。 -- WireGuard 与 MASQUE H2/IP 的私有主动栈使用 64 KiB TCP 发送总预算: - smoltcp 32 KiB 与按需应用队列 32 KiB。接收总预算仍为 32 KiB; - MASQUE H3/IP、共享 TUN 与通用 netstack 默认值保持原样。 +- 生产 TUN 的 TCP 接收总预算默认 32 KiB,smoltcp RX 与应用接收队列各 16 KiB;发送总预算默认 128 KiB,smoltcp TX 与应用发送队列各 64 KiB。Rust `ResourceLimits::tun_tcp_send_buffer` 独立于原 `tcp_buffer_per_direction`,后者仍为 32 KiB 并用于 TUN 接收及原共享流缓冲;显式容量原样传递,不倍乘或钳制,不新增 YAML/Invoke 字段。所有平台 TUN 共用该策略。 +- 应用队列按需增长并保持原容量。Unix 发送队列达到 64 KiB 时可使用匿名映射 ring;显式 `NetStackConfig::map_tcp_recv_buffer` 可为接收队列启用独立映射,默认关闭。映射不可用或 owner 已停止时使用有界 VecDeque。 +- 每个 Driver 按方向最多缓存四个已排空的映射,缓存请求长度合计受方向预算约束,只复用相同长度。Stop 清空缓存,未读数据和活动切片继续由实际 owner 持有至释放。Apple WireGuard 和 macOS MASQUE H3/IP 私有栈启用接收映射。逻辑容量、映射末页和进程内存采用各自口径。 +- WireGuard 私有主动栈的 TCP 接收总预算为 128 KiB:smoltcp 数组与按需应用队列 + 各 64 KiB;发送总预算为 64 KiB,两部分各 32 KiB。MASQUE H2/IP 接收总预算为 96 KiB, + 发送为 64 KiB;H3/IP 接收为 128 KiB,发送与通用 netstack 默认值同为 32 KiB。 + 缩小接收预算同时缩小内层 TCP 通告窗口,较高 RTT 或应用消费停顿时可能限制吞吐; + 分配容量差不等于进程 physical footprint 的固定节省量。 节点业务与私有 DNS 的 TCP 共用该主动栈;此预算不改变内层 UDP、原始包队列或连接数量策略。 - rustls/流式 XHTTP 的配置缓冲区为 64 KiB;boring 每次应用写入最多 min(节点缓冲预算, 16 KiB),原生 TLS 记录有界,命名模板证书消息/解压输出另限 128 KiB。 -- 标准 TLS 恢复会话总预算为 4,按节点(含独立下载端点)分配;每个缓存绑定不可变的 SNI、ALPN 和证书策略,绝不跨节点复用。TLS 1.3 票据有界、一次性消费,TLS 1.2 会话占用同一额度;额度为 0 则禁用恢复。REALITY 不参与该缓存。 -- 共享 TLS 客户端的显式验证名、协议版本和 ClientHello profile 固定。内联客户端身份固定;文件身份整对校验后供新物理连接取快照,旧连接保留原身份。票据按节点和身份代隔离,换代后拒绝旧票据和旧连接晚到的票据,各代共用原节点总容量。boring 在应用层 ALPN 接受前不发布票据,失败或取消丢弃临时票据。标准 TLS 和 REALITY CloseWrite 只发送 close_notify,刷新最多5秒,保持读方向和底层传输;Drop 释放整个流。XHTTP 仍以逻辑连接整体关闭为准。 -- 半开连接、出站握手和活动会话只记录当前值和峰值,不触发资源错误。 -- 超时、取消、EOF 和协议错误负责回收;停止必须等待全部已跟踪任务结束。 -- 引导解析器最多使用四个工作线程;全部忙时在调用方既有期限内等待,不返回人为容量错误。 +- 业务 MITM 下游 rustls 写缓冲上限使用默认 64 KiB。H2 下游每响应流的发送容量为 64 KiB,上游客户端为 16 KiB。流信用、共享正文账本、生命周期和回退见 [HTTP 处理](http-processing.md)。 ### 物理 socket 初始化 @@ -128,15 +128,30 @@ Trojan UDP 接收直接读入既有的有界帧缓存,每次最多读取 2 KiB 公共 sing-mux 包装器按节点拥有独立池,只消费底层协议到约定目标的 TCP IO。 每池最多保留16条闲连接;命令/物理写队列16项、写块16 KiB。smux接收帧共享每物理连接的字节预算,单流队列槽数由该预算推导;当前默认值见[XHTTP/sing-mux](xhttp.md#通用-sing-mux)。 -h2mux每流接收窗口64 KiB、连接接收窗口512 KiB,按实际读取量释放信用。 +h2mux 专用客户端每流接收窗口 128 KiB、连接接收窗口 1 MiB。实际使用共享 H3 PacketUp +载体的 h2mux 连接窗口为 1.5 MiB。流和连接均按实际读取量释放信用。 +接收信用按收到的正文使用;各流保留 128 KiB DATA 时,八条流可用尽 1 MiB, +十二条流可用尽 1.5 MiB。 +已复制/已归还信用的数据与 TLS 等缓冲独立计量,进程 footprint 仍须实际验收。 连接额度允许少量未读取流占住各自窗口时,其他逻辑流继续接收;不预分配全部窗口。 yamux单连接累计接纳64流后退役,连接接收窗口16 MiB;活动兄弟流继续。 满足 XHTTP PacketUp 自主写条件的私有 h2mux,普通 DATA 仅在现有 h2 capacity 范围内移交驱动后接纳,16 KiB 发送缓冲不变。每逻辑流固定一个确认状态,物理 flush 列表每流至多一个弱引用登记;不按 DATA 保留 oneshot。显式 flush/END_STREAM 前仍确认 真实 supplied IO flush,首帧期限、部分写取消、来源隔离和同步 Stop 不变;不新增任务或全局额度。 +私有自主 H2Mux 的非空 DATA 写入依靠 h2 在报告容量前及缓存 DATA 前检查关闭状态, +避免每次另取连接锁查询 reset。零容量等待仍订阅原 send waiter;容量关闭/错误仍使私有 +确认失败并唤醒。空写保留 reset 查询,显式 flush/FIN 等待确认期间也保留原 reset 查询; +不改变普通 gRPC/H2、写预算、队列或 Stop。 私有 h2mux 的底层写入有正进度而 flush Pending 时,以一个布尔状态触发一次驱动重调度; 没有后续写入便不再自唤醒。重调度不分配队列或确认状态,也不把 Pending 当作 flush 完成。 +可信 VLESS PacketUp、无 Encryption/显式下载、无 padding 且 only-tcp=false 的 H3 Body +可为 h2mux/yamux 使用原单正文128KiB与两个有序响应槽。限定 Yamux carrier 另有独立的 +固定128KiB初始QUIC发送留存;不取得H2Mux的UDP升档control,也不把其channel-ready flush +当作物理IO证明。预算资格改变时隔离clone私有池,原活动租约仍由原owner收尾;其它路径 +及H2Mux初始64KiB/元数据flush后256KiB不变。上述资格均在节点发布前固定, +不需要业务HTTP静态身份或inbound-http能力;它改变同一既有认证逻辑流内的POST批次、 +响应重叠和限定physical发送留存,不新增跨路由/身份物理复用,不改变逻辑flush、FIN或Stop。 h2mux/yamux上传半关闭保留读取与lease,smux v1关闭整条逻辑流。 图只登记最终包装器;begin_shutdown同时关闭mux和底层准入,shutdown先join全部 mux驱动,再等待底层协议。provider代际与node-only测速复用此屏障,没有全局池。 @@ -207,6 +222,8 @@ UoT 写入最多暂持一帧及偏移;取消单次发送后,后续收发先 `quic-transport` 只把已有 `DatagramTransport` 适配成 Quinn/quiche 共用的受控 UDP 接口,没有内部 bind、DNS 或 DIRECT 回落。每个连接双向各最多32个排队数据报,另允许一个正在发送的包;TX满返回WouldBlock,RX满暂停读取。接收等待不会持有发送队列锁;Pending发送不会重复提交。单逻辑peer/物理peer映射和来源校验独立保留,不接受未请求的目标、GSO或源地址覆盖。物理 socket 仍只能来自 Dialer。 已打开且受保护的 UDP 路径可借出一个在途发送操作;驱动等待发送或 pacing 时继续接收,保持32包队列与一个发送中的包。首次发送仍由原路径完成初始化;上游不支持此能力时沿用原发送。停止先释放在途操作,再关闭并释放上游。 +macOS 的通用 QUIC owner 在 DIRECT 已打开的同一受保护 socket 上,可将当前就绪 FIFO 前缀按最多4包、合计8KiB提交;不等凑批,不改变逻辑分段或 pacing。批次只克隆既有 Bytes 句柄,原包仍留在32项队列作为唯一容量账本,确认正数的实际发送前缀后才消费、计数和释放容量,不增加32+4的负载容量。物理操作逐包使用 Tokio 的公开 poll_send_to(macOS MASQUE H3/IP、H3/L4及WireGuard 的固定直接物理路径使用公开 poll_send):首包 Pending 保留同一发送操作,正数前缀后的 Pending 立即返回该实际前缀,未发送后缀保留原位;不依赖私有批量 syscall ABI,也不把多包拼为单个 UDP 数据报。等待发送时接收继续推进。能力不可用或批次不足时沿原单包路径;实际错误或异常短发送不回退重放,原错误种类沿有界 close/drop/join 返回。Stop先释放批次引用与原发送租约,再关闭上游。非macOS及未提供物理批量能力的代理、codec、pacer保持原路径。 +macOS MASQUE H3/IP、H3/L4及WireGuard 的直接声明 Direct/LazyDirect 路径可准备一个新代际、单peer的connected UDP socket;仍只有共享Dialer创建socket。首次原send在bind/protect/接口策略/取消检查后连接同一socket,成功才公布原Arc;失败或初始化future取消不允许同代际再次bind/connect,不回落到send_to。所有send入口先校验完整SocketAddr;Group/Proxy/codec不携带该意图,H2及其它平台或协议保持原路径。接收仍使用原recv_from、32次就绪重查和预算加一字节检测;kernel来源过滤和ICMP错误可观察差异不被掩盖。Stop先释放原在途发送,再关闭该socket的全部原持有者,不增加任务、队列、缓存或期限。 立即就绪的读取、发送容量与发送完成检查不登记新的等待者;仅在同一状态锁内确认 Pending 后登记唤醒,保留后续数据、容量恢复、取消与 Stop 的通知。 队列通知采用边沿:TX由空变非空、RX由满变为有容量时通知驱动;已排队TX由就绪条件继续推进。 普通RX消费保持底层已有的接收等待,避免逐包取消并重建同一等待。 @@ -223,10 +240,14 @@ XHTTP 和 DoH/H3 通过 `quinn-h3-transport` 使用官方 h3/h3-quinn,共享 XHTTP packet-up 的单批 backing(含正在发送的正文)上限为 H1/H2 64 KiB、H3 128 KiB, 并与该 writer 采样的 POST 上限取较小值;按需扩容,不积累第二份正文。普通路径等待完整 POST 响应才释放写背压和确认 flush。无 Encryption、无独立下载、无 padding 且 only-tcp=false -的 VLESS h2mux,仅 H3 packet-up body/auto 上传保留最多两个未退役响应槽:发送 FIN 完成、 +的 VLESS h2mux/yamux,仅 H3 packet-up body/auto 上传保留最多两个未退役响应槽:发送 FIN 完成、 最后正文引用释放并归还唯一 Vec,且槽未满后才能复用正文;flush 仍等待连续成功响应。 -每批只有一份有界 owner 元数据,不复制正文,也不增加 QUIC 窗口、队列或停止预算。该 backing -上限不是进程 RSS 上限;HTTP/QUIC codec、发送窗口和 allocator 的共同持有峰值需实测。 +每批只有一份有界 owner 元数据,不复制正文;响应重叠本身不增加 QUIC 窗口、队列或停止预算。 +H2Mux 的 UDP 发送留存升档继续使用其独立证明;限定 Yamux 路径只设置固定128KiB初始留存, +没有自适应升档,其它路径仍64KiB。这是每physical留存的已接收应用字节界,已ACK但未释放 +的存储仍计入,较大allocation切片也可能持有更多内存;它不是等量预分配、socket队列、 +拥塞窗口或进程footprint上限。backing、HTTP/QUIC codec、发送窗口和allocator的共同持有 +峰值仍须实测,并满足原平台内存政策。 `quiche-h3-transport` 为 TrustTunnel/MASQUE 使用官方 quiche 的低层驱动,共享上述数据报适配器,不创建新的 socket。 接收时移动既有队列中的数据报,独占存储直接交给 quiche 原地解密;共享或不可变存储 @@ -240,6 +261,10 @@ TrustTunnel H3 使用 quiche 的本地发送容量比例 0.5,按当前可用 帧开始写入后必须完成;部分写入失败或被取消时关闭该来源关联,不丢弃帧尾后继续发送下一帧。 MASQUE 与其余 quiche H3 默认使用原生比例 1.0。 +共享 CONNECT 字节流允许读侧推进待发送块并继续接收。读写两侧分别登记等待者, +底层发送通知唤醒两侧;读侧完成待发送块时也通知写侧,保持各自任务的进度。 +通知不新增任务、数据队列或发送信用,停止仍释放待发送块、收发句柄与租约。 + QUIC双向可用payload至少1,200字节;endpoint必须显式把QUIC MTU限制在有效预算内。IPv4/IPv6路径MTU分别先扣除28/48字节IP+UDP头,边界和单字节不足均有定向测试。 Linux 受控物理 UDP 的收发与就绪注册可并发借用同一 socket。借用不跨 Pending 或 await, @@ -255,6 +280,10 @@ DoQ 初始及最小发送 payload 为 1200 字节,接收预算独立保留, TUIC 的独立会话、关联 ID 退役、控制流、分片负载 及交付队列边界见 [TUIC v5](outbounds.md#tuic-v5)。旧池的待建流也持有所有权, 不能在等待 credit 时被当成空闲池回收。TUIC 业务 UDP 队列使用独立观测类别。 +启用 UoT 时,普通 TCP 与内部 magic Connect 分别使用原两个当前槽;单连接的 +所有者阈值、窗口、队列与 FIN 保留不变。分池可能增加同时活动的物理连接及其状态, +退休会话仍由旧租约持有;两个当前槽不是最多两个 live 连接,也不是节点总内存上界。 + native 接收循环每处理最多 512 个就绪事件主动让出执行权,quic relay 保持 32 个; 底层异步等待和协作式调度可更早让出,不增加接收或交付队列。 @@ -393,7 +422,7 @@ Stop 的同步释放屏障完成后,Apple 通过 malloc zone、GNU/Linux 通 - 未使用 TUN 时不配置 allocator、不启动周期采样或 Stop 回收。 - 采样失败只记录一次警告,不写入 `lastError`。 -- 43/45 MiB 阈值分别对应默认 1 Gbps 与 2 Gbps 的预算,仅作诊断;Core 不推断负载档位,最终由 benchmark 按实际负载判定。这些观测不改变 prepare、start、running、stop 或 panic recovery。 +- Core 的 43/45 MiB 遥测阈值用于日志诊断。平台压力预算和进程观测范围见[验收边界](acceptance.md#内存与环境)。 - Stop 后的 allocator 回收只执行一次且尽力而为,不保证立即降低进程内存。 内存预算与真实设备范围见[验收边界](acceptance.md)。 diff --git a/docs/testing-isolation.md b/docs/testing-isolation.md index ea7f02e..4cd35ab 100644 --- a/docs/testing-isolation.md +++ b/docs/testing-isolation.md @@ -1,27 +1,25 @@ # 服务端测试隔离 -所有协议服务端、TCP/UDP/HTTP/DNS 原站、故障注入服务端和提供监听入口的对照客户端, -均在隔离容器中运行。宿主只运行待测客户端、测试驱动和观察工具。 -纯内存、编解码和离线配置测试可在宿主执行;容器不可用时报告未执行,不回退到宿主服务端。 +普通协议、原站和故障对端运行在自有隔离容器。Apple 真机测试使用显式绑定私有 LAN 地址的自有 Mac 原站,HTTP/MITM 业务经真实 Network Extension。Mac socketpair 模拟保留实际 Core/netstack,单独记录模拟包路径与容器对端。直接 LAN 对照保持 Core 和 Network Extension 停止。 + +宿主离线检查限于编解码、内存 I/O、临时文件与配置;涉及外部对端的验证使用上面的隔离环境。 编排、对端下载和压力测试由独立容器测试工具管理,执行时显式传入 `--source vole=PATH`。Vole 编译不依赖测试工具 checkout。 ## 执行要求 -1. 容器带任务所有权标记,使用 NAT/bridge 网络;不发布宿主端口,不修改宿主 VPN、 - 路由、DNS 或防火墙,也不清理其他任务的容器和网络。 +1. 容器带任务所有权标记并使用 NAT/bridge 网络。需要端口发布时只使用本次运行的自有端口和已声明的测试地址,保留宿主 VPN、路由、DNS、防火墙及其它任务资源。 2. 对端使用官方最新稳定发行二进制和官方稳定镜像,记录实际版本。保留 Mihomo 回环 保护及第三方默认 socket 行为。仅 Caddy 可按需使用官方 xcaddy 构建并注明来源。 3. 地址来自容器网络;配置、证书和凭据放临时目录,fixture 只读挂载,日志有界且脱敏。 4. 启动前登记资源所有权,成功、失败、超时和中断均停止并等待本次容器退出。 先保存文字结论,再删除本次临时容器、网络和中间产物;已验证的共享依赖缓存独立保留。 清理前复查资源归属;清理失败时保留必要现场并记录错误。 -5. 结果记录实际命令、环境、输入、流量、指标、失败、停止和清理状态。双向业务应校对内容, - 认证拒绝应确认原站未收到被拒绝的业务,客户端超时本身不能证明拒绝生效。 -6. CLI、原生 Invoke/FFI、协议、DNS、生命周期和压力的网络业务统一经过真实 TUN。 +5. 结果记录实际命令、环境、输入、流量、指标、失败、停止和清理状态。Vole 互通和业务完整性验收校验双向内容;认证拒绝由原站观测确认。Mihomo 容量参考按[实际收发口径](acceptance.md#压力与性能)计量。 +6. CLI、原生 Invoke/FFI、协议、DNS、生命周期和压力的网络验收业务统一经过真实 TUN。 使用隔离的负载网络命名空间、真实 raw-IP fd,并校验 TUN 流量和回收; - Controller 仅作管理入口。纯内存、离线和编译检查不要求 TUN。 + Controller 仅作管理入口。上述 socketpair 诊断独立记录其模拟边界;纯内存、离线和编译检查不要求 TUN。 互通、压力和设备验收分别执行,范围见 [验收边界](acceptance.md)。具体对端与用例参数 与实测结论统一由 benchmark 工程维护。 diff --git a/docs/tls-dependencies.md b/docs/tls-dependencies.md index 3746f3b..74ace05 100644 --- a/docs/tls-dependencies.md +++ b/docs/tls-dependencies.md @@ -7,6 +7,7 @@ | 用途 | 来源与约束 | | --- | --- | | 普通流 TLS、WebPKI | 官方 rustls/tokio-rustls,ring provider;rustls-native-certs 只读取可用平台根,不替换验证器 | +| HTTP/2 | 官方 registry h2;使用公开 Builder、流量控制和取消 API,保留官方编码缓冲默认值 | | Quinn QUIC | HY2、TUIC、DoQ、XHTTP H3 和 DoH/H3 使用官方 registry Quinn 0.11.12 / quinn-proto 0.11.19、rustls/ring;窗口与数据报预算通过公开 API 和 Core 包装处理;Linux DIRECT 的有限 GSO/ECN 使用同一受保护 fd 的 Linux ancillary API,不另建 socket | | Quinn HTTP/3 | HY2 认证、XHTTP 和 DoH/H3 使用 registry h3 0.0.8 + h3-quinn 0.0.10,MIT;HY2 认证与业务共用同一 Quinn 连接,XHTTP/DNS 的取消和帧预算由 Core 公开 trait 包装处理,不修改上游源码 | | quiche HTTP/3 | TrustTunnel 和 MASQUE 使用 registry quiche 0.30.0,BSD-2-Clause;自有低层驱动使用公开 API,共用同一 boring/boring-sys,不启用 quiche FFI、qlog 或另一套 TLS 来源 | diff --git a/docs/tun-platform.md b/docs/tun-platform.md index 451e46d..658d705 100644 --- a/docs/tun-platform.md +++ b/docs/tun-platform.md @@ -50,9 +50,8 @@ Linux 压测可以把 TUN 创建在客户端 namespace,再把借用 fd 交给 tvOS 首版为 17.0+、ARM64 真机和 Apple Silicon 模拟器,共用 TunIo、netstack 和 Dialer。所有平台使用统一的 TUN 内存诊断、allocator 配置和 Stop 后回收策略, -缓冲、队列和线程策略也不按平台或内存模式切换。内存按默认压力负载统一验收:1 Gbps 不超过 43 MiB, -2 Gbps 不超过 45 MiB;真实 iOS/tvOS 扩展按整个进程的 physical footprint -验收,完整口径见[验收边界](acceptance.md)。 +缓冲、队列和线程策略跨平台共享。内存验证按[验收边界](acceptance.md#内存与环境) +记录各平台的实际观测进程及指标。 Apple 公开 NEPacketTunnelFlow API 是 packetFlow 的包读写,不承诺可取得 raw fd。 Vole 的借用 fd 契约不能证明宿主 KVC 提取 fd 是稳定公开方案。真实宿主的 fd 获取/桥接、 @@ -107,16 +106,14 @@ token 归还容量。满输出保留尚未处理的 TCP 包和协议状态,低 输出端关闭则停止 Driver、释放 socket 并唤醒全部等待者。 netstack 的 TCP 接收与发送缓冲可独立配置,各方向的容量包含 smoltcp 缓冲与应用 -队列,两层上限各占一半。生产 TUN 仍使用每方向 32 KiB、合计每流 64 KiB 的数据 -容量上限。应用队列从空分配开始,按实际写入有界增长,分配请求不超过该队列的 -逻辑上限;排空后保留已分配空间直到连接释放。smoltcp 缓冲容量、背压、唤醒、 -flush 与关闭语义保持不变。该容量不包含代理 relay、包队列或 allocator 的内存, -也不保证进程 RSS 与数据容量相同。 +队列,两层上限各占一半。所有平台的生产 TUN 默认接收总预算为 32 KiB(每层 16 KiB), +发送总预算为 128 KiB(每层 64 KiB),合计每流 160 KiB。Rust `ResourceLimits` 的 +`tcp_buffer_per_direction` 与独立的 `tun_tcp_send_buffer` 分别映射到 TUN 接收与发送, +保留调用者显式容量,不倍乘或钳制;通用 netstack 默认收发仍各 32 KiB,不新增 YAML 或 +Invoke 字段。资源入口拒绝零值,netstack 启动时继续要求每方向总预算为至少 4 KiB 的偶数。 +应用队列有界并按需扩展。Unix 上的较大发送队列可使用匿名映射,分配不可用时继续使用有界 VecDeque。其缓存、停止顺序与内存覆盖范围见 [运行时资源策略](runtime-resource-policy.md#tcp-与握手)。 -Linux 目前不启用 GRO/GSO:`tun-rs` 的 Linux offload 示例通过 builder 创建并 -配置带 VNET header 的设备,而 Vole 的原生和借用路径均不启用该模式。对现有 raw-IP -设备调用 `recv_multiple` 不会自动合并读取或启用 offload。Vole 保留宿主 -MTU/格式与 fd 标志,原生 builder 只打开 raw-IP TUN,不暗中启用 offload 或改变借用接口。 +Linux 创建或借用的 raw-IP TUN 保留原 MTU、包格式及 fd 标志,GRO、GSO 与 VNET header 均关闭;`recv_multiple` 本身只使用现有设备能力。 ## Linux 自建 TUN 的系统网络 diff --git a/docs/vless.md b/docs/vless.md index 4233dc7..a2ad07c 100644 --- a/docs/vless.md +++ b/docs/vless.md @@ -57,6 +57,11 @@ TLS 1.2 和 HRR 都不能满足 JLS;失败不发伪装 HTTP 探测、不重发 连接器只包装既有 Dialer/上游交付的受控 IO,不创建 resolver、socket、后台任务 或额外连接池。建链期限、取消、ALPN 检查和同步 Stop 继承现有运行时。 +固定 JLS 腿可在 VLESS 私有可信工厂中提供业务 HTTP 静态身份:实际 Boring JLS 客户端须成功构造, +字面端点、完整静态上游图及原 Dialer 限制均须通过;XHTTP 的主/下载每腿与所有者分别检查。 +它只允许保留已经完成认证的同 origin 业务逻辑流,不提供共享安全白名单、H3 JLS 或新的物理池。 +最终 origin、路由与资源代际、完整请求/响应、flush、取消和 Stop 仍由原 HTTP 边界校验。 + JLS 继续承载 TLS 记录,CloseWrite 沿用共享 TLS 有界关闭;XHTTP 保持整流关闭。 Encryption 位于外层传输内,身份彼此独立,不能由单层成功推断组合验收。 @@ -136,15 +141,27 @@ padding 采用 Mihomo 的 `概率-下界-上界` 三元组,交替表示字节 缺省为 `100-111-1111.75-0-111.50-0-3333`,等待受原建链期限及取消控制。 所有密钥交换、AEAD 和 CTR 使用既有官方原语,AES-256-GCM / ChaCha20-Poly1305 -根据 CPU 选择,不增加用户算法选项。每节点一个恢复票据;`1rtt` 不复用, +根据 CPU 选择,不增加用户算法选项。每节点一个恢复票据;`1rtt` 不使用恢复票据, `0rtt` 在票据有效时恢复,过期改为新握手。错误票据/认证失败不会自动重发业务。 节点缓存互相隔离,旧连接失败不清除新一代票据,Stop 清空缓存且禁止再次插入。 +未停止的 Native/XorPublic/Random Client 可为同 origin 业务 HTTP 复用提供静态身份资格, +仍受完整路径、安全、依赖和 HTTP 上下文检查。Random 的双向记录头 CTR 和 Vision parser +继续由原逻辑流持有,不按 HTTP 实体或 H2 stream 重置。 +既有流继续持有自己的加密状态,票据更新/过期只影响新握手,不重置已有流或重放请求。 + 该层位于外层传输内、VLESS 请求头外;WS/HTTPUpgrade/HTTP 的 initial data 是 Encryption 握手字节,不能提前发送明文 VLESS 请求头。XHTTP 主/下载腿汇聚为 一条逻辑流后只执行一次 Encryption。普通 Encryption 关闭与 Mihomo CommonConn 一致,flush 后关闭整条逻辑流,不承诺半关闭尾包;不关闭复用池中的兄弟流。 +读写方向独立推进。读取仍先尝试发送已接受的密文;普通业务发送受阻时, +已认证明文及可用的接收记录仍可交付,已经观察到的发送错误仍使流失败关闭。 +非空 `0rtt` 恢复前导必须完整交给底层写侧后才能读取响应,部分发送沿原偏移继续, +不重发前导或重新封装已接受的记录。读取不替代调用者的显式 flush。 +底层读写、flush、半关闭及节点取消的唤醒均交给仍在等待的对应调用者; +流关闭或丢弃时释放等待者,不新增后台发送任务。 + Vision 在独立的 Encryption 记录边界切换:先排空已认证明文,再绕过 AEAD; 已有外层 TLS 保留,random 模式保留记录头 CTR,不重置计数器。 进入 direct 后,native/xorpub 继承底层 CloseWrite 并保留读取方向;random 对齐 diff --git a/docs/xhttp.md b/docs/xhttp.md index 00b3638..87c8807 100644 --- a/docs/xhttp.md +++ b/docs/xhttp.md @@ -51,7 +51,17 @@ packet-up 在发送间隔内聚合小块写入,而不是把每个 write 变成 批次缓冲按需扩容,分配容量也受该批次上限约束,避免不规则帧尺寸使倍增扩容超过预算;writer 不预分配完整批次。普通路径在 POST 确认后复用已独占的正文 backing;HTTP 尚持有引用时释放本地引用,不为回收再复制正文。每个 writer 至多保留这一批缓冲,逻辑连接关闭时释放。H3 的批次 backing 上限不等于进程 RSS 增量;HTTP/QUIC 编码及发送窗口可能同时持有其它有界数据。 -VLESS 无 Encryption、无显式下载设置,且启用无 padding 的 h2mux、only-tcp=false 时,H3 packet-up 的 body/auto 上传串行发送正文,最多保留两个尚未退役的响应槽。正文仍只有一个不超过 128 KiB 的工作区:真实发送 FIN 完成且最后一个正文引用释放后,独占归还同一 Vec,才允许复用。每批增加一个有界 owner 元数据对象,不复制正文;两个响应槽满时连第三批预填也暂停。 同一qualified H3物理连接初始发送留存仍64KiB;只有该连接上一次业务mux UDP请求的元数据成功写入并flush后,才同步升至192KiB直到退役(不是peer确认)。同physical的TCP与UDP共享升档,未见UDP的其它physical及排除路径仍64KiB;不拆池、不增加队列/task/连接,不改变FIN/Stop。200 响应及不超过 16 KiB 的响应体读取成功,才按序确认连续前缀;后到先完成的响应仍占槽,flush 不跨过缺口。等待打开请求、发送、FIN 和缓冲归还时共同推进已有响应;错误取消未完成上传,Stop 沿用节点的取消与 join。其它路径保持单响应背压。 +h2mux 接收信用为每流 128 KiB、每连接 1 MiB,帧上限 16 KiB。共享 H3 PacketUp 载体的连接信用为 1.5 MiB。连接信用由多个流共享,按实际消耗归还。业务 HTTP/2 和普通 gRPC 使用各自的窗口。 + +无 Encryption、无显式下载、无 padding 且 `only-tcp: false` 的 VLESS h2mux/yamux,H3 PacketUp 的 body/auto 上传可持有两个有序响应槽。仅使用一个最多 128 KiB 的正文工作区,真实发送 FIN 和最后正文引用释放后才复用。两个槽满时暂停,按顺序收到 200 及读完最多 16 KiB 的响应体后确认连续前缀。错误取消未完成的上传,Stop 等待所有者退出。 + +合格 h2mux 的发送留存从 64 KiB 起,在同一物理连接成功写入并 flush 首个 mux UDP 请求的元数据后升至 256 KiB。合格 yamux 固定为 128 KiB。预算资格在工厂发布前固定,不同资格使用独立池。 + +合格 Smux v1(同样无 Encryption、无显式下载、enabled、无 padding、only-tcp=false) +只共享上述 H3 packet-up body/auto 双响应 geometry:唯一 128 KiB 正文、两个有序响应槽, +省略间隔时使用 2 ms。Smux physical 仍为 64 KiB 发送留存,无 UDP 升档 control; +不借用 Yamux 的 128 KiB 或 h2mux 的 256 KiB 资格。首 UDP、显式 flush、FIN、 +取消偏移与节点 Stop 保持真实屏障,其它版本、模式和排除条件保持原路径。 body/auto 模式的 POST 共享已冻结批次的不可变 backing,不额外复制一份业务负载; 发送任务和批次所有者分别释放引用,头部/cookie 模式继续使用有界编码。 @@ -89,7 +99,7 @@ H1 请求命令队列以指针槽持有完整请求,避免底层分块队列 仅 VLESS packet-up 且存在显式 download-settings、上传和下载均为 H2 与静态普通 TLS、JLS 或 REALITY 时,可按每腿的字面 IP、固定直接上游和固定物理出口证明共享活动连接,每条最多 4 个逻辑租约。上传与显式下载腿各有独立池,不跨节点或资源代复用;单腿、stream-one/stream-up、明文和其它版本组合保持原路径。 REALITY 的公钥、short ID、SNI、指纹与混合密钥交换选项固定于各腿节点;新物理连接仍执行原生 REALITY 认证,不跨两腿或身份复用握手材料。 实际租约同时受对端 HTTP/2 并发 stream 额度约束;收到 GOAWAY 后新逻辑请求另建物理连接,现有流继续排空,不重放已发送正文。 -域名、动态组/代理上游、文件客户端证书、动态 ECH、ShadowTLS、opaque protect、DNS/source/interface binding、自动出口发现、非 dual IP-version、MPTCP 和 Windows adapter binding 保持原独立路径;请求 TCP-control 的逻辑建链也独立。它们仍受支持,不增加配置拒绝。 +域名、动态组/代理上游、文件客户端证书、动态 ECH、ShadowTLS、opaque protect、DNS/source/interface binding、自动出口发现、非 dual IP-version、非 macOS 的 `mptcp: true` 和 Windows adapter binding 保持原独立路径;请求 TCP-control 的逻辑建链也独立。它们仍受支持,不增加配置拒绝。 每次逻辑租约保留原路径预检:LazyDirect 使用字面端点 resolver,预解析 Direct 保留其端点而不新增 resolver 依赖,两者均保留 deadline/cancellation/地址族/IP4P 检查;Dialer 停机、节点 Stop、物理连接退役及原建链期限也覆盖等待池创建与命中活动连接的路径。mark、TFO、TLS 参数、HTTP 请求模板及队列预算保持原腿配置,不通过新默认 Dialer 重拨。 最后一个租约释放后立即移出候选池,并进入既有的有界传输收尾流程,不保留空闲候选。 这限制了并行连接的重复开销,不是全节点业务准入额度。 @@ -141,6 +151,8 @@ Inner 记录。它的字节单独可见,不重复计入业务 uploadTotal/down 空闲物理会话优先复用;max-connections>0 分支按连接数量与 min-streams 扩容,否则按 max-streams 阈值复用。两个 max 字段字面值均为零时 min-streams 归一为 8;归一在负阈值禁用之前执行,不把该值解释为所有调度分支的硬额度。每节点和资源代际的池独立,单流关闭不关闭兄弟流,节点 Stop 才取消和等待所有自有驱动。 +固定的无 Encryption、无显式下载腿的 VLESS H3 packet-up Body 载体,在启用无 padding、非 only-tcp、无 Brutal 的 smux v1 时,将 UDP 逻辑流放入独立的 Smux 会话候选域。TCP 保留原候选域;两域分别按同一 max-connections/min-streams/max-streams 阈值选择会话,各自串行建链,不让已有 TCP 会话的写入或 flush 占用 UDP 的 Smux writer。阈值仍不是全节点硬上限,取消退役中的旧 owner 可能短暂重叠。两域共用节点取消和任务所有者,Stop 关闭两域准入并等待全部驱动;没有新增公共配置或按目标增加物理会话。每个 source 的字面多目标 UDP 仍共享原逻辑 wire,首帧及显式 flush、FIN、正文与队列预算不变。底层 XHTTP H3 池、QUIC 连接和物理 UDP 可以继续共享,这不是物理网络隔离或进程内存上限保证。 + 物理建链、mux 请求元数据与 Brutal 控制协商沿用调用方的原绝对期限,复用不重置期限。 业务流在首个正长度 payload 写入被底层接受,或读取到合法成功状态后,结束 setup 计时; 因此纯上传可持续运行,不因对端尚未产生下行 HTTP headers 或 mux 状态而超时。 @@ -148,12 +160,12 @@ Inner 记录。它的字节单独可见,不重复计入业务 uploadTotal/down 期限结束前未建立的流关闭 IO 与租约;迟到状态不能复活。解除期限后仍完整校验状态, 拒绝、非法状态或截断照常失败;不改变单流关闭、兄弟流与节点 Stop 的所有权。 -smux v1 单流 shutdown 先等待已接受帧写入并 flush,再安排 FIN 并结束整条逻辑流。 -smux 的物理读写循环都遵守每轮 I/O 处理预算,主动让出调度。接收帧共用每连接 4 MiB 的分配预算,逐帧计入负载与管理费用,整帧释放后归还;有界单流队列的槽数由总预算推导,避免在总预算尚有余量时阻塞兄弟流。本地关闭立即释放排队数据,远端 FIN 仍在已收 DATA 排空后返回 EOF;写队列、flush 和帧顺序保持。 -VLESS XHTTP、无 VLESS Encryption 且未启用 sing-mux padding 时,smux DATA 帧的完成仅表示 -帧已完整进入自主驱动的底层 IO,不逐帧等待 POST 确认。显式 flush 仍通过同一有界命令队列 -等待真实底层 flush,shutdown 与 FIN 的顺序不变;其它路径保持逐批强 flush。 -该路径的 UDP 首帧保留原期限内的 setup flush,后续完整帧由 XHTTP 自有任务推进。 +合格的 VLESS H3 PacketUp body/auto Smux 可将已排队的显式 flush 票据合并到同一次底层 flush。每批受 16 个命令和 64 KiB 双重上限约束,保留 FIN 和控制命令的优先级。各票据在底层完成后确认。 + +Smux v1 的单流 shutdown 先写入并 flush 已接受帧,再安排 FIN 并结束逻辑流。各物理连接的接收帧共用 4 MiB 分配预算,计入负载和管理费用。释放整帧即归还预算,本地关闭立即释放排队数据,远端 FIN 在已收 DATA 排空后返回 EOF。读写调度分轮处理,队列容量受同一预算约束。 + +无 Encryption 和 sing-mux padding 的 VLESS XHTTP Smux DATA 在完整交给自主驱动的底层 I/O 后返回。显式 flush 等待实际底层 flush,首 UDP 帧在建链期限内完成 setup flush,后续完整帧由 XHTTP 任务推进。 + 最多仍保留一个待写 UDP 帧;取消后的偏移、首帧期限和 Stop 屏障保持。 VLESS 的 PacketUp XHTTP、无 VLESS Encryption 且无 sing-mux padding 时,h2mux 普通 DATA 先申请既有 h2 容量,实际移交 Connection 驱动后返回;不逐帧等待 POST 确认。 @@ -163,12 +175,15 @@ oneshot,也不增加 payload 队列。显式 flush、元数据与首 UDP 帧 该私有路径在底层实际写出字节、但强 flush 尚待完成时,主动再调度一次已有的 H2 驱动, 使已排队 DATA 继续填充同一有界 PacketUp 批次。没有新写入进度便不重复唤醒, 也不提前完成 flush 确认;显式 flush、FIN 与 Stop 仍遵守原屏障。 +私有 h2mux 在 codec 排空且底层 flush 挂起时保留当时的确认水位。旧前缀确认与后续 DATA 分别等待各自的实际 flush。有显式或强确认等待时,额外实际写入达到 128 KiB 后暂停,直到底层通知可推进。 h2mux 和 yamux 关闭上传后保留读取与租约,允许对端继续发送尾部;h2mux 的上传 数据须到达上游 IO 的 flush 边界再发送 END_STREAM。节点 Stop 或 Drop 可取消待写, 不承诺异常终止交付。 yamux 的内部资源边界是单物理连接累计分配 64 个流后退役;旧流继续,新请求另建连接,空闲即回收。该边界避免逻辑取消与库内 reset 回收不同步时误关兄弟流,不是全节点额度,详见 [资源策略](runtime-resource-policy.md)。 +业务 HTTP 可在完整内层静态身份有效且包装器仍存活时保留已建立的 mux 逻辑 TCP,继续持有原 lease。空闲 HTTP 缓存仍属于活动流,可能延后 Brutal/yamux 退役等待;原期限、单会话限制和 Stop 屏障保持,详见 [HTTP 处理](http-processing.md)。 + 同一 UDP 来源、相同具体节点且目标 IP 无需还原时,多个目标共享一条逐包地址 mux 流; Controller 仍逐目标记录与关闭业务连接。域名、fake-IP 和 QUIC 目标覆盖继续使用独立流, 避免响应地址歧义。发送至多保留一个受报文预算约束的帧及其写入进度,取消不会丢失 @@ -193,4 +208,6 @@ H3 的 QUIC 驱动、数据报适配器和后台任务归节点所有。物理 不构成远端 ACK 屏障。未完成的上传取消会 reset 当前请求,已提交 FIN 的发送不因此 reset, 兄弟流继续。shutdown 返回不代表物理驱动已退出;Stop 返回以任务回收为准,不把 Drop 或等待时间当作完成证明。 -H1/H2 原生验证优先使用官方 latest Mihomo;H3 使用官方 latest Xray。不被 Xray 直接解码的 packetaddr/sing-mux 使用明确标注的 Xray XHTTP → Mihomo VLESS 分层拓扑;mTLS 使用已批准的 xcaddy/Caddy H3 网关,后端仍是同一个 Xray handler。分层成功不改写直接对端失败。所有服务端与原站在隔离容器中,配置和私钥不入 Git;原生数据、公共入口、资源、跨平台构建和阶段签收分别记录。 +对端、拓扑和平台证据见[测试隔离](testing-isolation.md)及[验收边界](acceptance.md)。 + +业务 HTTP 保留同一已建逻辑 TCP 流与本章的 XHTTP 物理 transport 池不同。静态业务资格检查真实上传及下载每一腿的版本、security、path 和 owner 取消;H3 不能借用父 connector 的 TCP 证明。业务 HTTP 资格与物理 transport 池分别判断,不能由业务资格替代 packet-up/stream-up/stream-one 的原条件。macOS 的 `mptcp: true` 普通 TCP 标记例外也适用于私有 active-H2-pair 的每腿静态路径证明;其余资格、池及额度不变。逻辑流的发送/关闭合同和显式 reuse-settings 保持。 diff --git a/include/module.modulemap b/include/module.modulemap index 2bf7c78..396d9b2 100644 --- a/include/module.modulemap +++ b/include/module.modulemap @@ -1,5 +1,6 @@ module LibVole { header "vole.h" link "c++" + link framework "JavaScriptCore" export * } diff --git a/scripts/README.md b/scripts/README.md index 1c7d2e1..53f668b 100644 --- a/scripts/README.md +++ b/scripts/README.md @@ -65,10 +65,12 @@ CI 使用 `deps --github-env "$GITHUB_ENV"` 自动传给后续步骤。 ## 发布 [Release workflow](../.github/workflows/release.yml) 在 `vX.Y.Z` tag push 时构建并发布, -tag 必须匹配 Cargo 版本。PR 使用同一构建矩阵,全部构建成功后汇总十四个归档。 +tag 必须匹配 Cargo 版本。`main`、手动运行和标签使用完整构建矩阵,成功后汇总十四个归档。 +[PR workflow](../.github/workflows/test.yml) 运行 Linux Debug 和 Quality,并在 macOS ARM64 和 +Windows ARM64 上构建原生 CLI 和 FFI。iOS、tvOS 和 Android 按相关文件改动触发。 CI 中的 Python 均由 `actions/setup-python` 安装,选择最新稳定 Python 3;uv 仅使用系统解释器, 禁止自动下载 Python,不使用脚本安装或特定解释器发行版请求。 -CLI 构建后执行 `-h/-v/-t` 检查。Windows CLI、Wintun FFI、UWP FFI 分别使用独立的 +CLI 构建后执行 `-h/-v/-t` 检查。发布矩阵的 Windows CLI、Wintun FFI、UWP FFI 分别使用独立的 x64/ARM64 job,每个 job 的 runner、Python、工具链和验证产物必须同架构; UWP 的 COM 回归只加载当前 job 构建的 DLL。ARM64 MSVC 使用原生 `vcvarsall arm64`, 不使用 `amd64_arm64` 交叉工具链。 diff --git a/scripts/src/vole_scripts/h2_source.py b/scripts/src/vole_scripts/h2_source.py new file mode 100644 index 0000000..50d7d3e --- /dev/null +++ b/scripts/src/vole_scripts/h2_source.py @@ -0,0 +1,101 @@ +"""Audit the official h2 registry dependency and reject local source overrides.""" + +from __future__ import annotations + +import argparse +import json +import subprocess +import tomllib +from pathlib import Path + +VERSION = "0.4.20" +REGISTRY = "registry+https://github.com/rust-lang/crates.io-index" +CRATE_SHA256 = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +ROOT = Path(__file__).resolve().parents[3] + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def audit_h2_source(root, metadata): + root = Path(root).resolve(strict=True) + require( + Path(metadata["workspace_root"]).resolve() == root, "metadata root mismatch" + ) + vendor = root / "vendor" + require(not vendor.exists() and not vendor.is_symlink(), "vendor is forbidden") + manifest = tomllib.loads((root / "Cargo.toml").read_text()) + require( + manifest["dependencies"]["h2"] == VERSION, + "h2 must use its official version requirement", + ) + require( + all( + name != "h2" + and not (isinstance(spec, dict) and spec.get("package") == "h2") + for entries in manifest.get("patch", {}).values() + for name, spec in entries.items() + ) + and not any( + key.split(":", 1)[0] == "h2" for key in manifest.get("replace", {}) + ), + "h2 source overrides are forbidden", + ) + packages = [item for item in metadata["packages"] if item["name"] == "h2"] + require(len(packages) == 1, "expected one resolved h2 across the graph") + item = packages[0] + require( + item["version"] == VERSION + and item.get("source") == REGISTRY + and item.get("license") == "MIT", + "h2 must resolve to the official registry package", + ) + require( + item["id"] in {node["id"] for node in metadata["resolve"]["nodes"]} + and item["id"] not in metadata["workspace_members"], + "h2 must be a resolved external dependency", + ) + rows = [ + row + for row in tomllib.loads((root / "Cargo.lock").read_text())["package"] + if row["name"] == "h2" + ] + require( + len(rows) == 1 + and rows[0]["version"] == VERSION + and rows[0].get("source") == REGISTRY + and rows[0].get("checksum") == CRATE_SHA256, + "h2 lock must retain the official registry source and archive checksum", + ) + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--metadata", type=Path) + options = parser.parse_args() + if options.metadata: + metadata = json.loads(options.metadata.read_bytes()) + else: + metadata = json.loads( + subprocess.check_output( + [ + "cargo", + "metadata", + "--offline", + "--locked", + "--all-features", + "--format-version", + "1", + ], + cwd=ROOT, + timeout=120, + ) + ) + audit_h2_source(ROOT, metadata) + print("Official h2 registry source, archive checksum and unique graph passed") + + +if __name__ == "__main__": + main() diff --git a/scripts/tests/test_h2_source.py b/scripts/tests/test_h2_source.py new file mode 100644 index 0000000..226c718 --- /dev/null +++ b/scripts/tests/test_h2_source.py @@ -0,0 +1,88 @@ +"""Check official dependency acceptance and reject local or ambiguous sources.""" + +import tempfile +import unittest +from copy import deepcopy +from pathlib import Path + +from vole_scripts.h2_source import audit_h2_source + + +class H2SourceAuditTests(unittest.TestCase): + def setUp(self): + owner = tempfile.TemporaryDirectory() + self.addCleanup(owner.cleanup) + self.root = Path(owner.name).resolve() + self.manifest = '[dependencies]\nh2 = "0.4.20"\n' + (self.root / "Cargo.toml").write_text(self.manifest) + self.lock = ( + 'version = 4\n[[package]]\nname = "h2"\nversion = "0.4.20"\n' + 'source = "registry+https://github.com/rust-lang/crates.io-index"\n' + 'checksum = "' + "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" + '"\n' + ) + (self.root / "Cargo.lock").write_text(self.lock) + self.package = { + "id": "synthetic-official-h2", + "name": "h2", + "version": "0.4.20", + "source": "registry+https://github.com/rust-lang/crates.io-index", + "license": "MIT", + } + self.metadata = { + "workspace_root": str(self.root), + "workspace_members": [], + "packages": [self.package], + "resolve": {"nodes": [{"id": self.package["id"]}]}, + } + + def test_official_registry_package_and_lock_pass(self): + audit_h2_source(self.root, self.metadata) + + def test_vendor_directory_is_rejected(self): + (self.root / "vendor").mkdir() + with self.assertRaises(ValueError): + audit_h2_source(self.root, self.metadata) + + def test_local_git_and_duplicate_packages_are_rejected(self): + for source in (None, "git+https://example.invalid/h2", "registry+other"): + changed = deepcopy(self.metadata) + changed["packages"][0]["source"] = source + with self.subTest(source=source), self.assertRaises(ValueError): + audit_h2_source(self.root, changed) + changed = deepcopy(self.metadata) + changed["packages"].append(self.package | {"id": "second-h2"}) + with self.assertRaises(ValueError): + audit_h2_source(self.root, changed) + + def test_manifest_source_overrides_are_rejected(self): + for extra in ( + '\n[patch.crates-io]\nh2 = { path = "local-h2" }\n', + '\n[patch.crates-io]\nh2_local = { package = "h2", path = "local-h2" }\n', + '\n[replace]\n"h2:0.4.20" = { path = "local-h2" }\n', + ): + (self.root / "Cargo.toml").write_text(self.manifest + extra) + with self.subTest(extra=extra), self.assertRaises(ValueError): + audit_h2_source(self.root, self.metadata) + + def test_missing_registry_identity_or_wrong_checksum_is_rejected(self): + for text in ( + self.lock.replace( + 'source = "registry+https://github.com/rust-lang/crates.io-index"\n', "" + ), + self.lock.replace("7d290202", "00000000"), + ): + (self.root / "Cargo.lock").write_text(text) + with self.subTest(text=text), self.assertRaises(ValueError): + audit_h2_source(self.root, self.metadata) + + def test_workspace_and_unresolved_h2_are_rejected(self): + for field, value in ( + ("workspace_members", [self.package["id"]]), + ("resolve", {"nodes": []}), + ): + changed = deepcopy(self.metadata) + changed[field] = value + with self.subTest(field=field), self.assertRaises(ValueError): + audit_h2_source(self.root, changed) diff --git a/src/config/domain_regex.rs b/src/config/domain_regex.rs index 7d960f8..ec84b55 100644 --- a/src/config/domain_regex.rs +++ b/src/config/domain_regex.rs @@ -47,6 +47,8 @@ pub(crate) struct DecisionBudget { work: u64, backtracks: usize, match_time: Duration, + #[cfg(test)] + fixed_match_duration: Option, failure: Option, cancellation: Vec, deadline: Option, @@ -62,6 +64,8 @@ impl DecisionBudget { work: DECISION_WORK, backtracks: DECISION_BACKTRACKS, match_time: Duration::ZERO, + #[cfg(test)] + fixed_match_duration: None, failure: None, cancellation: Vec::new(), deadline: None, @@ -123,6 +127,8 @@ impl DecisionBudget { duration: Duration, cancel: Option<&CancellationToken>, ) -> std::result::Result<(), MatchFailure> { + #[cfg(test)] + let duration = self.fixed_match_duration.unwrap_or(duration); self.match_time = self.match_time.saturating_add(duration); if self.match_time > DECISION_MATCH_TIME { return self.fail(MatchFailure::Budget); @@ -156,6 +162,14 @@ impl PartialEq for RuleDecision { } impl Eq for RuleDecision {} impl RuleDecision { + #[cfg(test)] + pub(super) fn with_fixed_match_duration(duration: Duration) -> Self { + Self(Arc::new(std::sync::Mutex::new(DecisionBudget { + fixed_match_duration: Some(duration), + ..DecisionBudget::new() + }))) + } + pub(crate) async fn scope(&self, future: F) -> F::Output { ACTIVE_DECISION.scope(self.clone(), future).await } @@ -723,6 +737,7 @@ mod tests { use super::*; #[test] fn common_domain_expressions_compile_once_and_match() { + let decision = RuleDecision::with_fixed_match_duration(Duration::ZERO); for (pattern, domain) in [ (r"^(?!internal\.)[a-z0-9.-]+(?=\.test$)", "Api.Example.TEST"), (r"(?<=edge\.)[a-z]+(? TlsIdentityPem { + use base64::Engine as _; + let key = rcgen::KeyPair::generate().unwrap(); + let mut params = + rcgen::CertificateParams::new(vec!["client.memory.invalid".into()]).unwrap(); + params.extended_key_usages = vec![rcgen::ExtendedKeyUsagePurpose::ClientAuth]; + let certificate = params.self_signed(&key).unwrap(); + let pem = |label: &str, bytes: &[u8]| { + format!( + "-----BEGIN {label}-----\n{}\n-----END {label}-----\n", + base64::engine::general_purpose::STANDARD.encode(bytes) + ) + }; + TlsIdentityPem { + certificate: pem("CERTIFICATE", certificate.der()), + private_key: pem("PRIVATE KEY", &key.serialize_der()), + origin: None, + } + } + + fn marked_file_identity(mut identity: TlsIdentityPem) -> TlsIdentityPem { + // A marker only: the supplied PEM is already valid. No test invokes + // IdentityFiles, stamp/read, refresh, a worker or any filesystem API. + identity.origin = Some(Arc::new(IdentityFileOrigin { + certificate: PathBuf::from("/__vole_memory_identity__/certificate.pem"), + private_key: PathBuf::from("/__vole_memory_identity__/private-key.pem"), + initial: PairStamp::default(), + })); + identity + } + + #[cfg(any( + feature = "outbound-http", + feature = "outbound-socks5", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic" + ))] + fn path() -> UpstreamPath { + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + } + } + + #[cfg(feature = "outbound-tuic")] + #[test] + fn tuic_real_tls_constructor_reuses_inline_but_rejects_file_identity() { + let parsed = crate::config::Config::parse_yaml( + b"proxies: [{name: memory, type: tuic, server: 192.0.2.10, port: 443, uuid: 00000000-0000-0000-0000-000000000007, password: synthetic, sni: tuic.memory.invalid}]", + ).unwrap(); + let crate::config::ProxyProtocol::Tuic(config) = &parsed.proxies[0].protocol else { + panic!("TUIC memory configuration") + }; + let identity = identity(); + for mode in [ + crate::config::TuicUdpMode::Native, + crate::config::TuicUdpMode::Quic, + ] { + for uot in [false, true] { + let mut config = config.clone(); + config.udp_mode = mode; + config.udp_over_stream = uot; + let security = SecurityContext::new(); + for inline in [None, Some(identity.clone())] { + config.tls.identity = inline; + let node = crate::outbound::tuic::TuicOutbound::with_shared_security( + &config, + path(), + &security, + 8192, + ) + .unwrap(); + assert!(node.permits_http_tcp_reuse()); + node.begin_shutdown(); + assert!(!node.permits_http_tcp_reuse()); + } + assert!(!security.identities.has_sources()); + config.tls.identity = Some(marked_file_identity(identity.clone())); + let file = crate::outbound::tuic::TuicOutbound::with_shared_security( + &config, + path(), + &security, + 8192, + ) + .unwrap(); + assert!(security.identities.has_sources()); + assert!(!file.permits_http_tcp_reuse()); + } + } + } + + #[cfg(feature = "outbound-http")] + fn http( + identity: Option, + ech: Option, + security: &SecurityContext, + ) -> crate::outbound::http::HttpOutbound { + let config = crate::config::HttpOutboundConfig { + address: "192.0.2.10".into(), + port: 8443, + tls: Some(crate::config::TlsConfig { + server_name: "proxy.memory.invalid".into(), + alpn: vec![b"http/1.1".to_vec()], + tls13_only: false, + required_alpn: None, + certificate: Default::default(), + identity, + ech, + client_fingerprint: None, + }), + auth: None, + headers: Default::default(), + }; + crate::outbound::http::HttpOutbound::with_shared_security( + &config, + path(), + security, + 0, + 8192, + ) + .unwrap() + } + + #[cfg(feature = "outbound-socks5")] + fn socks( + server: &str, + identity: Option, + ech: Option, + security: &SecurityContext, + ) -> std::io::Result { + let config = crate::config::Socks5OutboundConfig { + address: server.into(), + port: 8443, + username: None, + password: None, + tls: Some(crate::config::TlsClientPolicy { + identity, + ech, + ..Default::default() + }), + }; + crate::outbound::Socks5Outbound::with_shared_security( + &config, + path(), + Some(security), + 0, + 8192, + ) + } + + #[cfg(feature = "outbound-http")] + #[test] + fn http_inline_identity_reuses_but_file_origin_does_not() { + let identity = identity(); + let security = SecurityContext::new(); + let inline = http(Some(identity.clone()), None, &security); + assert!(inline.permits_http_tcp_reuse()); + assert!(!security.identities.has_sources()); + let file = http(Some(marked_file_identity(identity)), None, &security); + assert!(!file.permits_http_tcp_reuse()); + assert!(security.identities.has_sources()); + } + + #[cfg(feature = "outbound-socks5")] + #[test] + fn socks5_inline_identity_reuses_but_file_origin_does_not() { + let identity = identity(); + let security = SecurityContext::new(); + let inline = socks("192.0.2.10", Some(identity.clone()), None, &security).unwrap(); + assert!(OutboundConnector::permits_http_tcp_reuse(&inline)); + assert!(!security.identities.has_sources()); + let file = socks( + "192.0.2.10", + Some(marked_file_identity(identity)), + None, + &security, + ) + .unwrap(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&file)); + assert!(security.identities.has_sources()); + } + + #[cfg(feature = "ech")] + fn dynamic_ech() -> StaticEchConfig { + let raw: super::super::ech::RawEch = + serde_yaml_ng::from_str("enable: true\nquery-server-name: ech.memory.invalid\n") + .unwrap(); + let ech = raw.normalize(false).unwrap().unwrap(); + assert!(ech.is_dynamic()); + ech + } + + #[cfg(feature = "ech")] + fn static_ech() -> StaticEchConfig { + // A public X25519 key and bounded ECHConfigList. No private + // ECH key, server, ClientHello or network operation is needed here. + let name = b"public.memory.invalid"; + let key = [9_u8; 32]; + let mut content = vec![7]; + content.extend_from_slice(&0x0020_u16.to_be_bytes()); + content.extend_from_slice(&(key.len() as u16).to_be_bytes()); + content.extend_from_slice(&key); + content.extend_from_slice(&4_u16.to_be_bytes()); + content.extend_from_slice(&1_u16.to_be_bytes()); + content.extend_from_slice(&1_u16.to_be_bytes()); + content.extend_from_slice(&[0, name.len() as u8]); + content.extend_from_slice(name); + content.extend_from_slice(&[0, 0]); + let mut list = ((content.len() + 4) as u16).to_be_bytes().to_vec(); + list.extend_from_slice(&0xfe0d_u16.to_be_bytes()); + list.extend_from_slice(&(content.len() as u16).to_be_bytes()); + list.extend_from_slice(&content); + let ech = StaticEchConfig::from_config_list_for_backend(&list, false).unwrap(); + assert!(!ech.is_dynamic()); + ech + } + + #[cfg(all(feature = "outbound-http", feature = "ech"))] + #[test] + fn http_static_ech_reuses_but_dynamic_ech_does_not() { + let security = SecurityContext::new(); + let fixed = http(None, Some(static_ech()), &security); + assert!(fixed.permits_http_tcp_reuse()); + let dynamic = http(None, Some(dynamic_ech()), &security); + assert!(!dynamic.permits_http_tcp_reuse()); + assert!(!security.identities.has_sources()); + } + + #[cfg(all(feature = "outbound-socks5", feature = "ech"))] + #[test] + fn socks5_ech_cannot_bypass_literal_endpoint_and_dns_name_requirements() { + let security = SecurityContext::new(); + for ech in [static_ech(), dynamic_ech()] { + // SOCKS TLS deliberately authenticates its configured address. + // ECH requires DNS SNI, whereas the reuse proof requires literal + // proxy addressing. The actual constructor rejects this pair. + let result = socks("192.0.2.10", None, Some(ech.clone()), &security); + assert!( + matches!(result, Err(ref error) if error.kind() == std::io::ErrorKind::InvalidInput) + ); + // A supported DNS-named ECH constructor remains keyless; it must + // not manufacture a literal endpoint or perform DNS to qualify. + let named = socks("proxy.memory.invalid", None, Some(ech), &security).unwrap(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&named)); + } + } + + #[cfg(feature = "outbound-hysteria2")] + fn hysteria2( + identity: Option, + ech: Option, + security: &SecurityContext, + ) -> crate::outbound::hysteria2::Hysteria2Outbound { + let parsed = crate::config::Config::parse_yaml( + br#"proxies: + - name: memory-hysteria2 + type: hysteria2 + server: 192.0.2.10 + port: 8443 + password: memory-only-password + sni: proxy.memory.invalid +"#, + ) + .unwrap(); + let crate::config::ProxyProtocol::Hysteria2(config) = &parsed.proxies[0].protocol else { + panic!("expected normalized Hysteria2 configuration"); + }; + let mut config = config.as_ref().clone(); + config.tls.identity = identity; + config.tls.ech = ech; + crate::outbound::hysteria2::Hysteria2Outbound::with_shared_security( + &config, + path(), + security, + 0, + 8192, + ) + .unwrap() + } + + #[cfg(feature = "outbound-hysteria2")] + #[test] + fn hysteria2_inline_identity_qualifies_but_file_storage_does_not() { + let identity = identity(); + let security = SecurityContext::new(); + let inline = hysteria2(Some(identity.clone()), None, &security); + assert!(inline.permits_http_tcp_reuse()); + assert!(!security.identities.has_sources()); + let file = hysteria2(Some(marked_file_identity(identity)), None, &security); + assert!(!file.permits_http_tcp_reuse()); + assert!(security.identities.has_sources()); + } + + #[cfg(all(feature = "outbound-hysteria2", feature = "ech"))] + #[test] + fn hysteria2_static_ech_qualifies_but_dynamic_ech_does_not() { + let security = SecurityContext::new(); + let fixed = hysteria2(None, Some(static_ech()), &security); + assert!(fixed.permits_http_tcp_reuse()); + let dynamic = hysteria2(None, Some(dynamic_ech()), &security); + assert!(!dynamic.permits_http_tcp_reuse()); + assert!(!security.identities.has_sources()); + } + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + fn stream_tls( + network: &str, + identity: Option, + ech: Option, + ) -> crate::config::SecurityConfig { + let alpn = match network { + "ws" => vec![b"http/1.1".to_vec()], + "grpc" => vec![b"h2".to_vec()], + _ => Vec::new(), + }; + crate::config::SecurityConfig::Tls(crate::config::TlsConfig { + server_name: "proxy.memory.invalid".into(), + required_alpn: alpn.first().cloned(), + alpn, + tls13_only: ech.is_some(), + certificate: Default::default(), + identity, + ech, + client_fingerprint: None, + }) + } + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + fn stream_proxies( + network: &str, + security: crate::config::SecurityConfig, + upstream: UpstreamPath, + ) -> Vec<(&'static str, Box)> { + vec![ + #[cfg(feature = "outbound-vmess")] + ( + "vmess", + Box::new( + crate::outbound::vmess::VmessOutbound::new_with_path( + &crate::config::VmessOutboundConfig { + address: "192.0.2.10".into(), + port: 8443, + id: uuid::Uuid::from_u128(7), + cipher: crate::config::VmessCipher::Aes128Gcm, + global_padding: false, + authenticated_length: false, + packet_encoding: crate::config::VmessPacketEncoding::Raw, + server_name: security.server_name().into(), + security: security.clone(), + transport: match network { + "tcp" => crate::config::VmessTransport::Tcp, + "ws" => crate::config::VmessTransport::WebSocket { + uri: "wss://proxy.memory.invalid/path".into(), + headers: Default::default(), + max_early_data: 0, + early_data_header_name: "Sec-WebSocket-Protocol".into(), + handshake: Default::default(), + }, + "grpc" => crate::config::VmessTransport::Grpc { + uri: "https://proxy.memory.invalid/GunService/Tun".into(), + options: Default::default(), + }, + _ => panic!("unsupported memory transport"), + }, + }, + upstream.clone(), + ) + .unwrap(), + ) as Box, + ), + #[cfg(feature = "outbound-trojan")] + ( + "trojan", + Box::new( + crate::outbound::trojan::TrojanOutbound::new_with_path( + &crate::config::TrojanOutboundConfig { + address: "192.0.2.10".into(), + port: 8443, + password: "memory-password".into(), + server_name: security.server_name().into(), + security: security.clone(), + transport: match network { + "tcp" => crate::config::TrojanTransport::Tcp, + "ws" => crate::config::TrojanTransport::WebSocket { + uri: "wss://proxy.memory.invalid/path".into(), + headers: Default::default(), + max_early_data: 0, + early_data_header_name: "Sec-WebSocket-Protocol".into(), + handshake: Default::default(), + }, + "grpc" => crate::config::TrojanTransport::Grpc { + uri: "https://proxy.memory.invalid/GunService/Tun".into(), + options: Default::default(), + }, + _ => panic!("unsupported memory transport"), + }, + }, + upstream.clone(), + ) + .unwrap(), + ) as Box, + ), + ] + } + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + #[test] + fn stream_proxy_static_transports_reuse_and_owner_stop_revokes_admission() { + for network in ["tcp", "ws", "grpc"] { + for (name, node) in stream_proxies(network, stream_tls(network, None, None), path()) { + assert!(node.permits_http_tcp_reuse(), "{name}/{network}"); + node.begin_shutdown(); + assert!(!node.permits_http_tcp_reuse(), "{name}/{network}"); + } + } + } + + #[cfg(feature = "outbound-vmess")] + #[test] + fn vmess_plain_tcp_keeps_static_http_proof() { + let mut config = crate::config::Config::parse_yaml( + b"proxies: [{name: memory, type: vmess, server: 192.0.2.10, port: 8443, uuid: 00000000-0000-0000-0000-000000000007, cipher: aes-128-gcm}]\nrules: ['MATCH,memory']\n", + ) + .unwrap(); + let crate::config::ProxyProtocol::Vmess(node) = config.proxies.remove(0).protocol else { + panic!("memory VMess configuration") + }; + let outbound = crate::outbound::vmess::VmessOutbound::new_with_path(&node, path()).unwrap(); + assert!(outbound.permits_http_tcp_reuse()); + outbound.begin_shutdown(); + assert!(!outbound.permits_http_tcp_reuse()); + } + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + #[test] + fn stream_proxy_inline_identity_qualifies_but_file_source_does_not() { + let identity = identity(); + for network in ["tcp", "ws", "grpc"] { + for (name, node) in stream_proxies( + network, + stream_tls(network, Some(identity.clone()), None), + path(), + ) { + assert!(node.permits_http_tcp_reuse(), "{name}/{network}"); + } + for (name, node) in stream_proxies( + network, + stream_tls(network, Some(marked_file_identity(identity.clone())), None), + path(), + ) { + assert!(!node.permits_http_tcp_reuse(), "{name}/{network}"); + } + } + } + + #[cfg(all( + feature = "ech", + any(feature = "outbound-vmess", feature = "outbound-trojan") + ))] + #[test] + fn stream_proxy_static_ech_qualifies_but_dynamic_ech_does_not() { + for network in ["tcp", "ws", "grpc"] { + for (name, node) in stream_proxies( + network, + stream_tls(network, None, Some(static_ech())), + path(), + ) { + assert!(node.permits_http_tcp_reuse(), "{name}/{network}"); + } + for (name, node) in stream_proxies( + network, + stream_tls(network, None, Some(dynamic_ech())), + path(), + ) { + assert!(!node.permits_http_tcp_reuse(), "{name}/{network}"); + } + } + } + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + #[test] + fn stream_proxy_upstream_group_remains_keyless_and_dialer_stop_propagates() { + let selection = Arc::new(crate::routing::GroupSelection::new(0)); + let group = UpstreamPath::Group { + server: crate::session::Destination::Ip("192.0.2.10:8443".parse().unwrap()), + group: Arc::new(crate::outbound::SelectUpstream::new( + selection.clone(), + vec![crate::outbound::SelectUpstreamMember::Direct], + )), + endpoint: None, + dialer: Dialer::default(), + }; + for (name, node) in stream_proxies("tcp", stream_tls("tcp", None, None), group) { + assert!(!node.permits_http_tcp_reuse(), "{name}"); + } + let dialer = Dialer::default(); + let nodes = stream_proxies( + "tcp", + stream_tls("tcp", None, None), + UpstreamPath::LazyDirect { + dialer: dialer.clone(), + }, + ); + assert!(nodes.iter().all(|(_, node)| node.permits_http_tcp_reuse())); + dialer.begin_shutdown(); + assert!(nodes.iter().all(|(_, node)| !node.permits_http_tcp_reuse())); + } + + #[cfg(any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ))] + fn constructed_tls( + identity: Option, + ech: Option, + profile: Option, + ) -> crate::security::StandardTlsClient { + let context = SecurityContext::new(); + let identity = identity.as_ref().map(|identity| { + crate::security::TlsClientIdentity::from_config(identity, &context).unwrap() + }); + crate::security::StandardTlsClient::with_options( + &context, + "proxy.memory.invalid", + crate::security::TlsClientOptions { + identity, + ech, + client_fingerprint: profile, + ..Default::default() + }, + 0, + 8192, + ) + .unwrap() + } + + #[cfg(any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ))] + #[test] + fn constructed_tls_inline_identity_qualifies_but_file_storage_does_not() { + let identity = identity(); + let profiles = [ + None, + #[cfg(feature = "tls-fingerprint")] + Some(crate::config::ClientFingerprint::Chrome133), + ]; + for profile in profiles { + let inline = constructed_tls(Some(identity.clone()), None, profile); + assert!(inline.permits_static_http_reuse()); + let file = constructed_tls(Some(marked_file_identity(identity.clone())), None, profile); + assert!(!file.permits_static_http_reuse()); + } + } + + #[cfg(all( + feature = "ech", + any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ) + ))] + #[test] + fn constructed_tls_static_ech_qualifies_but_dynamic_wrapper_does_not() { + let fixed = constructed_tls(None, Some(static_ech()), None); + assert!(fixed.permits_static_http_reuse()); + let dynamic = constructed_tls(None, Some(dynamic_ech()), None); + assert!(!dynamic.permits_static_http_reuse()); + } + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + struct OpaqueStreamDependency; + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + #[async_trait::async_trait] + impl OutboundConnector for OpaqueStreamDependency { + async fn connect_stream( + &self, + _: crate::session::StreamSession, + _: &crate::outbound::EstablishContext, + ) -> std::result::Result + { + panic!("a structural query must not open opaque IO") + } + async fn open_datagram( + &self, + _: crate::outbound::DatagramRequest, + _: &crate::outbound::EstablishContext, + ) -> std::result::Result< + Box, + crate::dispatch::DispatchError, + > { + panic!("a structural query must not open opaque datagrams") + } + } + + #[cfg(any(feature = "outbound-vmess", feature = "outbound-trojan"))] + #[test] + fn stream_proxy_opaque_dependency_never_gains_reuse_permission() { + for (name, node) in stream_proxies( + "tcp", + stream_tls("tcp", None, None), + UpstreamPath::proxy(Arc::new(OpaqueStreamDependency)), + ) { + assert!(!node.permits_http_tcp_reuse(), "{name}"); + } + } + + #[cfg(feature = "outbound-vmess")] + fn vmess_h2_config(tls: bool) -> crate::config::VmessOutboundConfig { + let security = if tls { + ", tls: true, servername: proxy.memory.invalid" + } else { + "" + }; + let yaml = format!( + "proxies: [{{name: memory, type: vmess, server: 192.0.2.10, port: 8443, uuid: 00000000-0000-0000-0000-000000000007, cipher: aes-128-gcm, network: h2, h2-opts: {{host: [proxy.memory.invalid], path: /memory}}{security}}}]\nrules: ['MATCH,memory']\n" + ); + let mut config = crate::config::Config::parse_yaml(yaml.as_bytes()).unwrap(); + let crate::config::ProxyProtocol::Vmess(node) = config.proxies.remove(0).protocol else { + panic!("memory VMess H2 configuration") + }; + node + } + + #[cfg(feature = "outbound-vmess")] + #[test] + fn vmess_h2_single_uri_plain_and_static_tls_reuse_until_owner_stop() { + for tls in [false, true] { + let config = vmess_h2_config(tls); + let crate::config::VmessTransport::H2 { uris } = &config.transport else { + panic!("memory VMess H2 transport") + }; + assert_eq!( + uris, + &[format!( + "{}://proxy.memory.invalid/memory", + if tls { "https" } else { "http" } + )] + ); + let node = VmessOutbound::new_with_path(&config, path()).unwrap(); + assert!(node.permits_http_tcp_reuse(), "tls={tls}"); + node.begin_shutdown(); + assert!(!node.permits_http_tcp_reuse(), "tls={tls}"); + } + } + + #[cfg(feature = "outbound-vmess")] + #[test] + fn vmess_h2_multiple_uris_keep_single_use_http() { + for tls in [false, true] { + let mut config = vmess_h2_config(tls); + let crate::config::VmessTransport::H2 { uris } = &mut config.transport else { + panic!("memory VMess H2 transport") + }; + uris.push(uris[0].replace("proxy.memory.invalid", "alternate.memory.invalid")); + let node = VmessOutbound::new_with_path(&config, path()).unwrap(); + assert!(!node.permits_http_tcp_reuse(), "tls={tls}"); + } + } + + #[cfg(feature = "outbound-vmess")] + #[test] + fn vmess_h2_inline_identity_qualifies_but_file_source_does_not() { + let mut config = vmess_h2_config(true); + let crate::config::SecurityConfig::Tls(tls) = &mut config.security else { + panic!("memory VMess H2 TLS") + }; + tls.identity = Some(identity()); + let inline = VmessOutbound::new_with_path(&config, path()).unwrap(); + assert!(inline.permits_http_tcp_reuse()); + let crate::config::SecurityConfig::Tls(tls) = &mut config.security else { + unreachable!() + }; + tls.identity = Some(marked_file_identity(tls.identity.take().unwrap())); + let file = VmessOutbound::new_with_path(&config, path()).unwrap(); + assert!(!file.permits_http_tcp_reuse()); + } + + #[cfg(all(feature = "outbound-vmess", feature = "ech"))] + #[test] + fn vmess_h2_static_ech_qualifies_but_dynamic_ech_does_not() { + let mut config = vmess_h2_config(true); + let crate::config::SecurityConfig::Tls(tls) = &mut config.security else { + panic!("memory VMess H2 TLS") + }; + tls.tls13_only = true; + tls.ech = Some(static_ech()); + let fixed = VmessOutbound::new_with_path(&config, path()).unwrap(); + assert!(fixed.permits_http_tcp_reuse()); + let crate::config::SecurityConfig::Tls(tls) = &mut config.security else { + unreachable!() + }; + tls.ech = Some(dynamic_ech()); + let dynamic = VmessOutbound::new_with_path(&config, path()).unwrap(); + assert!(!dynamic.permits_http_tcp_reuse()); + } + + #[cfg(feature = "outbound-vmess")] + #[test] + fn vmess_h2_keeps_upstream_and_dialer_restrictions() { + let config = vmess_h2_config(false); + let group = UpstreamPath::Group { + server: crate::session::Destination::Ip("192.0.2.10:8443".parse().unwrap()), + group: Arc::new(crate::outbound::SelectUpstream::new( + Arc::new(crate::routing::GroupSelection::new(0)), + vec![crate::outbound::SelectUpstreamMember::Direct], + )), + endpoint: None, + dialer: Dialer::default(), + }; + let egress = crate::config::EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for upstream in [ + group, + UpstreamPath::proxy(Arc::new(OpaqueStreamDependency)), + UpstreamPath::LazyDirect { + dialer: Dialer::default().with_ip_version(crate::config::IpVersion::Ipv4), + }, + UpstreamPath::LazyDirect { + dialer: Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + }, + UpstreamPath::LazyDirect { + dialer: Dialer::default().with_egress(&egress), + }, + ] { + let node = VmessOutbound::new_with_path(&config, upstream).unwrap(); + assert!(!node.permits_http_tcp_reuse()); + } + let dialer = Dialer::default(); + let node = VmessOutbound::new_with_path( + &config, + UpstreamPath::LazyDirect { + dialer: dialer.clone(), + }, + ) + .unwrap(); + assert!(node.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + assert!(!node.permits_http_tcp_reuse()); + let mut domain = config; + domain.address = "proxy.memory.invalid".into(); + let node = VmessOutbound::new_with_path(&domain, path()).unwrap(); + assert!(!node.permits_http_tcp_reuse()); + } + + #[cfg(feature = "outbound-vmess")] + #[test] + fn vmess_tls_http_camouflage_remains_outside_the_proof_scope() { + let mut config = crate::config::Config::parse_yaml( + b"proxies: [{name: memory, type: vmess, server: 192.0.2.10, port: 8443, uuid: 00000000-0000-0000-0000-000000000007, cipher: aes-128-gcm, network: http, tls: true}]\nrules: ['MATCH,memory']\n", + ) + .unwrap(); + let crate::config::ProxyProtocol::Vmess(config) = config.proxies.remove(0).protocol else { + panic!("memory VMess HTTP camouflage configuration") + }; + assert!( + matches!(&config.security, crate::config::SecurityConfig::Tls(_)), + "the HTTP camouflage negative control must normalize to real TLS" + ); + let node = VmessOutbound::new_with_path(&config, path()).unwrap(); + assert!(!node.permits_http_tcp_reuse()); + } +} diff --git a/src/config/process.rs b/src/config/process.rs index ee16d4d..01a52e6 100644 --- a/src/config/process.rs +++ b/src/config/process.rs @@ -170,8 +170,11 @@ pub(crate) fn uid_ranges(payload: &str) -> Result> { #[cfg(test)] mod tests { use super::*; + use std::time::Duration; + #[test] fn process_predicates_preserve_unicode_and_shared_budget() { + let decision = RuleDecision::with_fixed_match_duration(Duration::ZERO); for (kind, pattern, value) in [ ("PROCESS-NAME", "应用", "应用"), ("PROCESS-PATH", "/Applications/WEB", "/applications/web"), @@ -184,20 +187,20 @@ mod tests { ("PROCESS-NAME-REGEX", "(?=应用)应用$", "应用"), ("PROCESS-PATH-REGEX", "^/路径/.*$", "/路径/程序"), ] { - assert!( + assert_eq!( ProcessRule::parse(kind, pattern) .unwrap() - .matches(value, &Default::default()) - .unwrap() + .matches(value, &decision), + Ok(true), + "{kind} {pattern:?}" ); } assert!( !ProcessRule::parse("PROCESS-NAME-REGEX", ".*") .unwrap() - .matches("", &Default::default()) + .matches("", &decision) .unwrap() ); - let decision = RuleDecision::default(); let token = tokio_util::sync::CancellationToken::new(); token.cancel(); decision.set_cancellation(token); diff --git a/src/dialer.rs b/src/dialer.rs index c58bfd7..1e5b254 100644 --- a/src/dialer.rs +++ b/src/dialer.rs @@ -478,11 +478,20 @@ impl Dialer { /// Only immutable direct egress may donate a private active H2 connection. #[cfg(feature = "outbound-vless")] pub(crate) fn permits_static_h2_reuse(&self) -> bool { + self.permits_static_http_reuse() + } + #[cfg(feature = "inbound-http")] + pub(crate) fn http_reuse_cancelled(&self) -> bool { + self.initialization.cancellation.is_cancelled() + } + #[cfg(any(feature = "outbound-vless", feature = "inbound-http"))] + pub(crate) fn permits_static_http_reuse(&self) -> bool { if self.protector.is_some() || self.dns_binding.is_some() || self.source_binding.is_some() || self.egress.interface.is_some() - || self.mptcp + // macOS currently keeps this preference on ordinary TCP sockets. + || (self.mptcp && !cfg!(target_os = "macos")) || self.ip_version != crate::config::IpVersion::Dual { return false; diff --git a/src/dispatch.rs b/src/dispatch.rs index b2c3a74..62d5fd6 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -19,10 +19,148 @@ impl AsyncStream for T where T: AsyncRead + AsyncWrite + Unpin + Send {} pub type BoxStream = Box; +/// Opaque, owned equality evidence from a completed routing decision. +/// No public configuration/API field and no transport or cache owner. +#[cfg(feature = "inbound-http")] +#[doc(hidden)] +#[derive(Clone)] +pub struct HttpTcpReuseKey { + value: Arc, + equal: fn(&dyn std::any::Any, &dyn std::any::Any) -> bool, + generation: Option>, +} + +#[cfg(feature = "inbound-http")] +impl HttpTcpReuseKey { + pub(crate) fn new(value: T) -> Self { + fn equal(a: &dyn std::any::Any, b: &dyn std::any::Any) -> bool { + a.downcast_ref::() + .zip(b.downcast_ref::()) + .is_some_and(|(a, b)| a == b) + } + Self { + value: Arc::new(value), + equal: equal::, + generation: None, + } + } + pub(crate) fn with_generation(mut self, generation: Arc) -> Self { + self.generation = Some(generation); + self + } + pub(crate) fn same(&self, other: &Self) -> bool { + let generation = match (&self.generation, &other.generation) { + (None, None) => true, + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + _ => false, + }; + generation && (self.equal)(self.value.as_ref(), other.value.as_ref()) + } +} + +/// An already selected route. Opening consumes this plan, never selects twice. +#[cfg(feature = "inbound-http")] +#[doc(hidden)] +#[async_trait] +pub trait HttpTcpPlan: Send { + fn reuse_key(&self) -> Option<&HttpTcpReuseKey>; + async fn connect(self: Box) -> Result; +} + /// One owned send operation; its owner must cancel or complete it before close. pub type OwnedDatagramSend = Pin> + Send + 'static>>; +/// Opaque identity for one TUN business operation; never traffic or route text. +#[cfg(target_os = "macos")] +#[doc(hidden)] +#[derive(Clone)] +pub struct TunSendToken(Arc<()>); + +#[cfg(target_os = "macos")] +impl TunSendToken { + pub(crate) fn same(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } +} + +/// One already-open TUIC operation, distinct from a physical-path send lease. +#[cfg(target_os = "macos")] +#[doc(hidden)] +pub struct TunPendingSend { + pub(crate) operation: OwnedDatagramSend, + pub(crate) completion: TunSendToken, +} + +#[cfg(target_os = "macos")] +impl TunPendingSend { + pub(crate) fn new(operation: OwnedDatagramSend) -> Self { + Self { + operation, + completion: TunSendToken(Arc::new(())), + } + } +} + +/// Only a completed IO result may update successful/failed-send accounting. +#[cfg(target_os = "macos")] +#[doc(hidden)] +pub enum TunSendOutcome { + Completed(Result<(), DispatchError>), + TimedOut, + Cancelled, +} + +#[cfg(target_os = "macos")] +impl TunSendOutcome { + pub(crate) fn into_result(self) -> Result<(), DispatchError> { + match self { + Self::Completed(result) => result, + Self::TimedOut => Err(DispatchError::TimedOut), + Self::Cancelled => Err(DispatchError::NotAllowed), + } + } +} + +/// An already-open physical path's confirmed FIFO datagram prefix. +#[cfg(target_os = "macos")] +pub type OwnedDatagramBatchSend = + Pin> + Send + 'static>>; + +#[cfg(target_os = "macos")] +pub(crate) const DATAGRAM_SEND_BATCH_LIMIT: usize = 4; +#[cfg(target_os = "macos")] +pub(crate) const DATAGRAM_SEND_BATCH_BYTES: usize = 8 * 1024; + +/// Admission only: no resolution, socket acquisition, or IO. +#[cfg(target_os = "macos")] +pub(crate) fn datagram_batch_peer(packets: &[Datagram]) -> Option { + if !(2..=DATAGRAM_SEND_BATCH_LIMIT).contains(&packets.len()) { + return None; + } + let crate::session::Destination::Ip(peer) = &packets[0].remote else { + return None; + }; + let peer = *peer; + if peer.port() == 0 || peer.ip().is_unspecified() || peer.ip().is_multicast() { + return None; + } + let mut bytes = 0usize; + for packet in packets { + if packet.remote != crate::session::Destination::Ip(peer) + || packet.sniffed_domain.is_some() + || packet.payload.is_empty() + { + return None; + } + bytes = bytes.checked_add(packet.payload.len())?; + if bytes > DATAGRAM_SEND_BATCH_BYTES { + return None; + } + } + Some(peer) +} + #[derive(Debug, thiserror::Error)] pub enum DispatchError { #[error("connection is not allowed")] @@ -104,6 +242,44 @@ pub trait DatagramTransport: Send { Err(datagram) } + /// Lease one already-open actual Mac TUN TUIC QUIC business send. + /// Unsupported returns the untouched packet before IO or route mutation. + /// The caller retains one operation, drops it before completion/close, and + /// invokes completion exactly once, including timeout and cancellation. + #[cfg(target_os = "macos")] + #[doc(hidden)] + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + _flow_id: Option<&[u8]>, + ) -> Result { + Err(datagram) + } + + #[cfg(target_os = "macos")] + #[doc(hidden)] + async fn finish_tun_send( + &mut self, + _completion: TunSendToken, + outcome: TunSendOutcome, + ) -> Result<(), DispatchError> { + outcome.into_result() + } + + /// Optional physical send of at most four ready datagrams, totaling 8 KiB, + /// to one IP peer. + /// Unsupported paths return the untouched batch before any IO. A positive + /// completion confirms only that FIFO prefix; errors must never be replayed. + /// Drop this operation before closing the transport, as with `send_owned`. + #[cfg(target_os = "macos")] + #[doc(hidden)] + fn send_batch_owned( + &mut self, + datagrams: Vec, + ) -> Result> { + Err(datagrams) + } + /// A dedicated QUIC endpoint may initialize this same DIRECT physical /// socket through Dialer and retain a lease until endpoint retirement. /// Codecs, proxy hops and pacers do not forward this capability. @@ -164,6 +340,23 @@ pub trait DatagramTransport: Send { #[async_trait] pub trait Dispatcher: Send + Sync { + /// Structural proof of immutable egress, including every proxy dependency + /// and security identity. Opaque nodes and dynamic paths keep the default. + #[cfg(feature = "inbound-http")] + #[doc(hidden)] + fn permits_http_tcp_reuse(&self) -> bool { + false + } + /// None means this dispatcher does not implement owned planning. Errors + /// are real decision failures, never permission to select a second route. + #[cfg(feature = "inbound-http")] + #[doc(hidden)] + async fn prepare_http_tcp( + &self, + _session: StreamSession, + ) -> Result>, DispatchError> { + Ok(None) + } #[cfg(feature = "inbound-http")] #[doc(hidden)] fn http_context(&self) -> Option { @@ -211,6 +404,23 @@ impl SessionObservedDispatcher { #[async_trait] impl Dispatcher for SessionObservedDispatcher { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.inner.permits_http_tcp_reuse() + } + #[cfg(feature = "inbound-http")] + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + Ok(self.inner.prepare_http_tcp(session).await?.map(|inner| { + Box::new(ObservedHttpTcpPlan { + inner, + resource_stats: self.resource_stats.clone(), + handshake: false, + }) as Box + })) + } fn supports_udp(&self) -> bool { self.inner.supports_udp() } @@ -263,6 +473,23 @@ impl HandshakeObservedDispatcher { #[async_trait] impl Dispatcher for HandshakeObservedDispatcher { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.inner.permits_http_tcp_reuse() + } + #[cfg(feature = "inbound-http")] + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + Ok(self.inner.prepare_http_tcp(session).await?.map(|inner| { + Box::new(ObservedHttpTcpPlan { + inner, + resource_stats: self.resource_stats.clone(), + handshake: true, + }) as Box + })) + } fn supports_udp(&self) -> bool { self.inner.supports_udp() } @@ -289,6 +516,37 @@ impl Dispatcher for HandshakeObservedDispatcher { } } +#[cfg(feature = "inbound-http")] +struct ObservedHttpTcpPlan { + inner: Box, + resource_stats: RuntimeResourceStats, + handshake: bool, +} +#[cfg(feature = "inbound-http")] +#[async_trait] +impl HttpTcpPlan for ObservedHttpTcpPlan { + fn reuse_key(&self) -> Option<&HttpTcpReuseKey> { + self.inner.reuse_key() + } + async fn connect(self: Box) -> Result { + let Self { + inner, + resource_stats, + handshake, + } = *self; + if handshake { + let _activity = resource_stats.begin(ResourceActivity::Handshake); + inner.connect().await + } else { + let inner = inner.connect().await?; + Ok(Box::new(ObservedStream { + inner, + _activity: resource_stats.begin(ResourceActivity::TcpSession), + })) + } + } +} + #[must_use] pub(crate) fn observe_sessions_with_stats( inner: Arc, @@ -383,6 +641,32 @@ impl DatagramTransport for ObservedDatagramTransport { self.inner.send_owned(datagram) } + #[cfg(target_os = "macos")] + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + flow_id: Option<&[u8]>, + ) -> Result { + self.inner.try_begin_tun_send(datagram, flow_id) + } + + #[cfg(target_os = "macos")] + async fn finish_tun_send( + &mut self, + completion: TunSendToken, + outcome: TunSendOutcome, + ) -> Result<(), DispatchError> { + self.inner.finish_tun_send(completion, outcome).await + } + + #[cfg(target_os = "macos")] + fn send_batch_owned( + &mut self, + datagrams: Vec, + ) -> Result> { + self.inner.send_batch_owned(datagrams) + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { self.inner.send(datagram).await } @@ -407,6 +691,11 @@ impl DatagramTransport for ObservedDatagramTransport { // Assert object safety in normal builds rather than discovering it in an FFI adapter. const _: Option>> = None; +#[cfg(all(test, target_os = "macos"))] +pub(crate) mod tun_send_memory_test_support; +#[cfg(all(test, target_os = "macos"))] +mod tun_send_memory_tests; + #[cfg(test)] mod tests { use std::sync::{ diff --git a/src/dispatch/datagram.rs b/src/dispatch/datagram.rs index 004e8ec..22524c4 100644 --- a/src/dispatch/datagram.rs +++ b/src/dispatch/datagram.rs @@ -91,6 +91,14 @@ struct Bounded { observation: Option, } +#[cfg(all(test, target_os = "macos"))] +#[path = "datagram_tun_send_memory_tests.rs"] +mod tun_send_memory_tests; + +#[cfg(all(test, target_os = "macos"))] +#[path = "datagram_batch_memory_tests.rs"] +mod batch_memory_tests; + #[async_trait::async_trait] impl DatagramTransport for Bounded { #[cfg(all( @@ -154,6 +162,46 @@ impl DatagramTransport for Bounded { self.inner.send_owned(datagram) } + #[cfg(target_os = "macos")] + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + flow_id: Option<&[u8]>, + ) -> Result { + if self.closing + || datagram.payload.len() + > usize::from(self.payload_budget(&datagram.remote).transmit()) + { + return Err(datagram); + } + self.inner.try_begin_tun_send(datagram, flow_id) + } + + #[cfg(target_os = "macos")] + async fn finish_tun_send( + &mut self, + completion: super::TunSendToken, + outcome: super::TunSendOutcome, + ) -> Result<(), DispatchError> { + self.inner.finish_tun_send(completion, outcome).await + } + + #[cfg(target_os = "macos")] + fn send_batch_owned( + &mut self, + datagrams: Vec, + ) -> Result> { + if self.closing + || super::datagram_batch_peer(&datagrams).is_none() + || datagrams.iter().any(|packet| { + packet.payload.len() > usize::from(self.payload_budget(&packet.remote).transmit()) + }) + { + return Err(datagrams); + } + self.inner.send_batch_owned(datagrams) + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { if self.closing { return Err(DispatchError::NotAllowed); diff --git a/src/dispatch/datagram_batch_memory_tests.rs b/src/dispatch/datagram_batch_memory_tests.rs new file mode 100644 index 0000000..64ec138 --- /dev/null +++ b/src/dispatch/datagram_batch_memory_tests.rs @@ -0,0 +1,84 @@ +use super::*; +use bytes::Bytes; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +struct PhysicalBoundary { + calls: Arc, + closes: Arc, +} +#[async_trait::async_trait] +impl DatagramTransport for PhysicalBoundary { + fn supports_shared_destinations(&self) -> bool { + false + } + fn payload_budget(&self, _: &Destination) -> DatagramBudget { + DatagramBudget::new(1400, 1400) + } + fn send_batch_owned( + &mut self, + packets: Vec, + ) -> Result> { + self.calls.fetch_add(1, Ordering::Relaxed); + Ok(Box::pin(async move { Ok(packets.len()) })) + } + async fn send(&mut self, _: Datagram) -> Result<(), DispatchError> { + panic!("batch boundary only") + } + async fn receive(&mut self) -> Result { + panic!("batch boundary only") + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.closes.fetch_add(1, Ordering::Relaxed); + Ok(()) + } +} +fn packets(length: usize) -> Vec { + (0..2) + .map(|_| Datagram { + remote: "192.0.2.1:443" + .parse::() + .unwrap() + .into(), + payload: Bytes::from(vec![7; length]), + sniffed_domain: None, + }) + .collect() +} + +#[tokio::test] +async fn macos_quic_batch_memory_nested_bounds_enforce_peer_budget_and_close_before_forwarding() { + let calls = Arc::new(AtomicUsize::new(0)); + let closes = Arc::new(AtomicUsize::new(0)); + let inner = bounded( + Box::new(PhysicalBoundary { + calls: calls.clone(), + closes: closes.clone(), + }), + DatagramBudget::new(1350, 1350), + ); + let mut path = bounded(inner, DatagramBudget::new(1250, 1300)); + let oversized = path.send_batch_owned(packets(1251)).is_err(); + let mut wrong_peer = packets(1200); + wrong_peer[1].remote = "192.0.2.2:443" + .parse::() + .unwrap() + .into(); + let mismatched = path.send_batch_owned(wrong_peer).is_err(); + let rejected_calls = calls.load(Ordering::Relaxed); + let accepted = path.send_batch_owned(packets(1200)).ok(); + let count = match accepted { + Some(operation) => operation.await, + None => Err(io::ErrorKind::Unsupported.into()), + }; + path.close().await.unwrap(); + path.close().await.unwrap(); + let closed = path.send_batch_owned(packets(1200)).is_err(); + assert!(oversized && mismatched && closed); + assert_eq!(rejected_calls, 0); + assert_eq!(count.unwrap(), 2); + assert_eq!(calls.load(Ordering::Relaxed), 1); + assert_eq!(closes.load(Ordering::Relaxed), 1); +} diff --git a/src/dispatch/datagram_tun_send_memory_tests.rs b/src/dispatch/datagram_tun_send_memory_tests.rs new file mode 100644 index 0000000..231b9dc --- /dev/null +++ b/src/dispatch/datagram_tun_send_memory_tests.rs @@ -0,0 +1,59 @@ +use super::*; +use crate::dispatch::tun_send_memory_test_support::{ + Packets, Probe, assert_untouched, completion_outcomes, packet, +}; +use std::sync::{Arc, atomic::Ordering}; + +#[tokio::test] +async fn tun_owned_wrapper_preserves_both_payload_caps_and_closed_admission() { + for (outer, inner) in [(2, 4), (4, 2)] { + let probe = Arc::new(Probe::default()); + let mut packets = Packets::new(probe.clone()); + packets.budget = DatagramBudget::new(inner, inner); + let mut transport = bounded(Box::new(packets), DatagramBudget::new(outer, outer)); + let original = packet(b"big"); + let Err(returned) = transport.try_begin_tun_send(original.clone(), Some(b"opaque")) else { + panic!("oversized packet reached the inner owned seam"); + }; + assert_untouched(returned, &original); + assert_eq!(probe.begins.load(Ordering::Relaxed), 0); + } + let probe = Arc::new(Probe::default()); + let mut transport = bounded( + Box::new(Packets::new(probe.clone())), + DatagramBudget::new(4, 4), + ); + transport.close().await.unwrap(); + let original = packet(b"ok"); + let Err(returned) = transport.try_begin_tun_send(original.clone(), None) else { + panic!("closed wrapper admitted an owned send"); + }; + assert_untouched(returned, &original); + assert_eq!(probe.begins.load(Ordering::Relaxed), 0); + assert_eq!(probe.closes.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn tun_owned_bounded_wrapper_forwards_identity_flow_metadata_and_all_outcomes() { + let probe = Arc::new(Probe::default()); + let mut transport = bounded( + Box::new(Packets::new(probe.clone())), + DatagramBudget::new(4, 4), + ); + completion_outcomes(transport.as_mut(), &probe).await; +} + +#[test] +fn tun_owned_bounded_wrapper_returns_unsupported_packet_without_replay() { + let probe = Arc::new(Probe::default()); + let mut packets = Packets::new(probe.clone()); + packets.accept = false; + let mut transport = bounded(Box::new(packets), DatagramBudget::new(4, 4)); + let original = packet(b"ok"); + let Err(returned) = transport.try_begin_tun_send(original.clone(), Some(b"opaque")) else { + panic!("unsupported inner path must decline"); + }; + assert_untouched(returned, &original); + assert_eq!(probe.begins.load(Ordering::Relaxed), 1); + assert_eq!(probe.legacy.load(Ordering::Relaxed), 0); +} diff --git a/src/dispatch/tun_send_memory_test_support.rs b/src/dispatch/tun_send_memory_test_support.rs new file mode 100644 index 0000000..5af2281 --- /dev/null +++ b/src/dispatch/tun_send_memory_test_support.rs @@ -0,0 +1,134 @@ +//! Fixed typed mocks for forwarding tests; no sockets, tasks or protocol credit. +use super::{ + DatagramBudget, DatagramTransport, DispatchError, TunPendingSend, TunSendOutcome, TunSendToken, +}; +use crate::session::{Datagram, Destination}; +use async_trait::async_trait; +use std::sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, +}; + +#[derive(Default)] +pub(crate) struct Probe { + pub(crate) begins: AtomicUsize, + pub(crate) finishes: AtomicUsize, + pub(crate) legacy: AtomicUsize, + pub(crate) closes: AtomicUsize, + pub(crate) flow_id: Mutex>>, +} + +pub(crate) struct Packets { + pub(crate) probe: Arc, + pub(crate) accept: bool, + pub(crate) budget: DatagramBudget, + completion: Option, +} + +impl Packets { + pub(crate) fn new(probe: Arc) -> Self { + Self { + probe, + accept: true, + budget: DatagramBudget::new(u16::MAX, u16::MAX), + completion: None, + } + } +} + +#[async_trait] +impl DatagramTransport for Packets { + fn supports_shared_destinations(&self) -> bool { + false + } + fn payload_budget(&self, _: &Destination) -> DatagramBudget { + self.budget + } + + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + flow_id: Option<&[u8]>, + ) -> Result { + self.probe.begins.fetch_add(1, Ordering::Relaxed); + *self.probe.flow_id.lock().unwrap() = flow_id.map(<[u8]>::to_vec); + if !self.accept || self.completion.is_some() { + return Err(datagram); + } + let pending = TunPendingSend::new(Box::pin(async { Ok(()) })); + self.completion = Some(pending.completion.clone()); + Ok(pending) + } + + async fn finish_tun_send( + &mut self, + completion: TunSendToken, + outcome: TunSendOutcome, + ) -> Result<(), DispatchError> { + let expected = self.completion.take().expect("one accepted operation"); + assert!( + expected.same(&completion), + "completion identity must be forwarded" + ); + self.probe.finishes.fetch_add(1, Ordering::Relaxed); + outcome.into_result() + } + + async fn send(&mut self, _: Datagram) -> Result<(), DispatchError> { + self.probe.legacy.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + async fn receive(&mut self) -> Result { + std::future::pending().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.probe.closes.fetch_add(1, Ordering::Relaxed); + Ok(()) + } +} + +pub(crate) fn packet(payload: &'static [u8]) -> Datagram { + Datagram { + remote: Destination::Ip("192.0.2.1:443".parse().unwrap()), + payload: bytes::Bytes::from_static(payload), + sniffed_domain: Some("fixture.invalid".into()), + } +} + +pub(crate) fn assert_untouched(actual: Datagram, expected: &Datagram) { + assert_eq!(actual.remote, expected.remote); + assert_eq!(actual.sniffed_domain, expected.sniffed_domain); + assert_eq!(actual.payload.as_ptr(), expected.payload.as_ptr()); + assert_eq!(actual.payload.len(), expected.payload.len()); +} + +pub(crate) async fn completion_outcomes(transport: &mut dyn DatagramTransport, probe: &Probe) { + for case in 0..4 { + let flow_id: Option<&[u8]> = (case % 2 == 0).then_some(b"opaque"); + let Ok(TunPendingSend { + operation, + completion, + }) = transport.try_begin_tun_send(packet(b"ok"), flow_id) + else { + panic!("opened wrapper lost the owned-send capability"); + }; + assert_eq!(probe.flow_id.lock().unwrap().as_deref(), flow_id); + operation.await.unwrap(); + let outcome = match case { + 0 => TunSendOutcome::Completed(Ok(())), + 1 => TunSendOutcome::Completed(Err(DispatchError::ConnectionRefused)), + 2 => TunSendOutcome::TimedOut, + _ => TunSendOutcome::Cancelled, + }; + let result = transport.finish_tun_send(completion, outcome).await; + match case { + 0 => assert!(result.is_ok()), + 1 => assert!(matches!(result, Err(DispatchError::ConnectionRefused))), + 2 => assert!(matches!(result, Err(DispatchError::TimedOut))), + _ => assert!(matches!(result, Err(DispatchError::NotAllowed))), + } + } + assert_eq!(probe.begins.load(Ordering::Relaxed), 4); + assert_eq!(probe.finishes.load(Ordering::Relaxed), 4); + assert_eq!(probe.legacy.load(Ordering::Relaxed), 0); +} diff --git a/src/dispatch/tun_send_memory_tests.rs b/src/dispatch/tun_send_memory_tests.rs new file mode 100644 index 0000000..d4f178b --- /dev/null +++ b/src/dispatch/tun_send_memory_tests.rs @@ -0,0 +1,35 @@ +use super::tun_send_memory_test_support::{ + Packets, Probe, assert_untouched, completion_outcomes, packet, +}; +use super::*; +use std::sync::{Arc, atomic::Ordering}; + +#[tokio::test] +async fn tun_owned_observed_wrapper_forwards_identity_metadata_and_all_outcomes() { + let probe = Arc::new(Probe::default()); + let stats = RuntimeResourceStats::new("tun_owned_wrapper"); + let mut transport = ObservedDatagramTransport { + inner: Box::new(Packets::new(probe.clone())), + _activity: stats.begin(ResourceActivity::UdpAssociation), + }; + completion_outcomes(&mut transport, &probe).await; +} + +#[test] +fn tun_owned_observed_wrapper_returns_unsupported_packet_without_legacy_send() { + let probe = Arc::new(Probe::default()); + let mut packets = Packets::new(probe.clone()); + packets.accept = false; + let stats = RuntimeResourceStats::new("tun_owned_wrapper"); + let mut transport = ObservedDatagramTransport { + inner: Box::new(packets), + _activity: stats.begin(ResourceActivity::UdpAssociation), + }; + let original = packet(b"ok"); + let Err(returned) = transport.try_begin_tun_send(original.clone(), Some(b"opaque")) else { + panic!("unsupported inner path must decline"); + }; + assert_untouched(returned, &original); + assert_eq!(probe.begins.load(Ordering::Relaxed), 1); + assert_eq!(probe.legacy.load(Ordering::Relaxed), 0); +} diff --git a/src/http_processing/body.rs b/src/http_processing/body.rs index cfcd29f..b854061 100644 --- a/src/http_processing/body.rs +++ b/src/http_processing/body.rs @@ -7,9 +7,11 @@ mod json; pub(crate) use budget::{Budget, BudgetedBytes, MAX_BODY}; use super::{ + diagnostics::{self, BodyPoint, Counter}, headers::Fields, rules::{BodyOperation, Phase, Rule, RuleAction}, }; +use bytes::Bytes; use url::Url; #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -38,6 +40,7 @@ pub(crate) enum Encoding { /// Capture before request-header actions. Content negotiation must reflect the /// client that will actually receive the response, not a rewritten header. +#[derive(Clone, Copy)] pub(crate) struct OriginalRequestMeta { pub(crate) head: bool, pub(crate) connect: bool, @@ -57,6 +60,7 @@ pub(crate) struct WireBodyMeta { pub(crate) encoding: Encoding, pub(crate) length: Option, bypass: Option, + text_bypass: Option, } impl WireBodyMeta { pub(crate) fn new( @@ -90,10 +94,11 @@ impl WireBodyMeta { encoding }; let mut bypass = None; + let mut text_bypass = None; if original.head || original.connect || upgraded - || status.is_some_and(|status| status < 200 || matches!(status, 204 | 304)) + || status.is_some_and(|status| status < 200 || matches!(status, 204 | 205 | 304)) { bypass = Some(Bypass::ForbiddenBody); } else if status == Some(206) || values("content-range").next().is_some() { @@ -121,20 +126,28 @@ impl WireBodyMeta { "utf-8" | "utf8" ) { - bypass = Some(Bypass::Charset); + text_bypass = Some(Bypass::Charset); } } } if values("content-type").count() > 1 { - bypass = Some(Bypass::Charset); + text_bypass = Some(Bypass::Charset); } Self { encoding, length, bypass, + text_bypass, } } pub(crate) fn eligibility(&self) -> Result<(), Bypass> { + self.common_eligibility()?; + if let Some(reason) = self.text_bypass { + return Err(reason); + } + Ok(()) + } + pub(crate) fn common_eligibility(&self) -> Result<(), Bypass> { if let Some(reason) = self.bypass { return Err(reason); } @@ -224,6 +237,7 @@ pub(crate) struct Transaction<'a> { original: &'a Url, phase: Phase, encoding: Encoding, + text_allowed: bool, } pub(crate) struct ResultBody { pub(crate) body: BudgetedBytes, @@ -233,6 +247,7 @@ pub(crate) struct ResultBody { } impl ResultBody { pub(crate) fn rollback(&mut self, reason: Bypass) { + diagnostics::body_bypass(BodyPoint::HeaderFinalize, reason); if let Some(original) = self.original.take() { self.body = original; } @@ -262,27 +277,78 @@ impl<'a> Transaction<'a> { phase: Phase, wire: &WireBodyMeta, ) -> Result { - if !has_rules(rules, original, phase) { - return Err(Bypass::NoRules); + diagnostics::increment(Counter::CollectorNativeRequested); + let result = (|| { + if !has_rules(rules, original, phase) { + return Err(Bypass::NoRules); + } + wire.eligibility()?; + let capacity = wire.length.map_or(MAX_BODY + 1, |length| length as usize); + let raw = BudgetedBytes::new(budget, capacity).ok_or(Bypass::Budget)?; + Ok(Self { + budget: budget.clone(), + raw, + rules, + original, + phase, + encoding: wire.encoding, + text_allowed: true, + }) + })(); + match &result { + Ok(_) => diagnostics::increment(Counter::CollectorAdmitted), + Err(reason) => diagnostics::body_bypass(BodyPoint::NativeAdmission, *reason), } - wire.eligibility()?; - let capacity = wire.length.map_or(MAX_BODY + 1, |length| length as usize); - let raw = BudgetedBytes::new(budget, capacity).ok_or(Bypass::Budget)?; - Ok(Self { - budget: budget.clone(), - raw, - rules, - original, - phase, - encoding: wire.encoding, - }) + result + } + /// Shared collection admits binary scripts independently of native text + /// rules. The same collector and codec still own the wire representation. + pub(crate) fn begin_shared( + budget: &Budget, + rules: &'a [Rule], + original: &'a Url, + phase: Phase, + wire: &WireBodyMeta, + script_body: bool, + ) -> Result { + diagnostics::increment(Counter::CollectorSharedRequested); + let result = (|| { + if !script_body && !has_rules(rules, original, phase) { + return Err(Bypass::NoRules); + } + if script_body { + wire.common_eligibility()?; + } else { + wire.eligibility()?; + } + let capacity = wire.length.map_or(MAX_BODY + 1, |length| length as usize); + Ok(Self { + budget: budget.clone(), + raw: BudgetedBytes::new_shared_collector(budget, capacity, wire.length.is_some()) + .ok_or(Bypass::Budget)?, + rules, + original, + phase, + encoding: wire.encoding, + text_allowed: wire.eligibility().is_ok(), + }) + })(); + match &result { + Ok(_) => diagnostics::increment(Counter::CollectorAdmitted), + Err(reason) => diagnostics::body_bypass(BodyPoint::SharedAdmission, *reason), + } + result } pub(crate) fn remaining(&self) -> usize { self.raw.remaining() } pub(crate) fn push(&mut self, bytes: &[u8]) -> Result<(), Bypass> { - self.raw.extend(bytes).map_err(|_| Bypass::Size)?; + self.raw.extend(bytes).map_err(|_| { + diagnostics::body_bypass(BodyPoint::Collection, Bypass::Size); + Bypass::Size + })?; if self.raw.as_ref().len() > MAX_BODY { + diagnostics::body_bypass(BodyPoint::Collection, Bypass::Size); return Err(Bypass::Size); } Ok(()) @@ -291,72 +357,49 @@ impl<'a> Transaction<'a> { self.raw } pub(crate) fn finish(self, has_trailers: bool) -> ResultBody { - let fallback = |raw, reason| ResultBody { - body: raw, - changed: false, - bypass: Some(reason), - original: None, + diagnostics::increment(Counter::CollectorFinished); + let fallback = |raw, reason, point| { + diagnostics::body_bypass(point, reason); + ResultBody { + body: raw, + changed: false, + bypass: Some(reason), + original: None, + } }; if has_trailers { - return fallback(self.raw, Bypass::Trailers); + return fallback(self.raw, Bypass::Trailers, BodyPoint::NativeDecode); } if self.raw.as_ref().len() > MAX_BODY { - return fallback(self.raw, Bypass::Size); + return fallback(self.raw, Bypass::Size, BodyPoint::NativeDecode); } let decoded = match codec::decode(self.raw.as_ref(), self.encoding, &self.budget) { Ok(decoded) => decoded, - Err(reason) => return fallback(self.raw, reason), + Err(reason) => return fallback(self.raw, reason, BodyPoint::NativeDecode), }; let baseline = decoded .as_ref() .map_or(self.raw.as_ref(), |value| value.as_ref()); if std::str::from_utf8(baseline).is_err() { - return fallback(self.raw, Bypass::InvalidText); + return fallback(self.raw, Bypass::InvalidText, BodyPoint::NativeDecode); } - let mut candidate = None; - for rule in self.rules { - let RuleAction::Body { phase, operation } = &rule.action else { - continue; - }; - if *phase != self.phase || !rule.matches(self.original) { - continue; + let candidate = match apply_operations( + self.rules, + self.original, + self.phase, + baseline, + &self.budget, + ) { + Ok(candidate) => candidate, + Err(reason) => { + return ResultBody { + body: self.raw, + changed: false, + bypass: Some(reason), + original: None, + }; } - match operation { - BodyOperation::Set(value) => { - let Some(output) = BudgetedBytes::copy(&self.budget, value.as_bytes()) else { - return fallback(self.raw, Bypass::Budget); - }; - candidate = Some(output); - } - BodyOperation::Replace(search) => { - let input = candidate - .as_ref() - .map_or(baseline, |value: &BudgetedBytes| value.as_ref()); - let input = std::str::from_utf8(input).expect("body candidates stay UTF-8"); - let Some(mut output) = BudgetedBytes::new(&self.budget, MAX_BODY) else { - return fallback(self.raw, Bypass::Budget); - }; - if output - .write_text(|output| search.apply_into(input, output, MAX_BODY)) - .is_err() - { - return fallback(self.raw, Bypass::Transform); - } - candidate = Some(output); - } - BodyOperation::JsonPatch(patch) if patch.is_empty() => {} - BodyOperation::JsonPatch(patch) => { - let input = candidate - .as_ref() - .map_or(baseline, |value: &BudgetedBytes| value.as_ref()); - let input = std::str::from_utf8(input).expect("body candidates stay UTF-8"); - match json::apply(input, patch, &self.budget) { - Ok(output) => candidate = Some(output), - Err(reason) => return fallback(self.raw, reason), - } - } - } - } + }; match candidate { Some(output) if output.as_ref() != baseline => ResultBody { body: output, @@ -372,11 +415,289 @@ impl<'a> Transaction<'a> { }, } } + + /// Finish native work while retaining the decoded baseline for scripts. + /// A native failure does not invalidate a successfully decoded entity. + pub(crate) fn finish_shared(self, has_trailers: bool, fields: &mut Fields) -> Entity { + diagnostics::increment(Counter::CollectorFinished); + let decoded = if has_trailers { + Err(Bypass::Trailers) + } else if self.raw.as_ref().len() > MAX_BODY { + Err(Bypass::Size) + } else { + codec::decode(self.raw.as_ref(), self.encoding, &self.budget) + }; + let wire = self.raw.into_bytes(); + let mut entity = match decoded { + Ok(decoded) => Entity { + logical: Some(decoded.map_or_else(|| wire.clone(), BudgetedBytes::into_bytes)), + wire, + budget: self.budget.clone(), + bypass: None, + changed: false, + original_text: self.text_allowed, + }, + Err(reason) => { + diagnostics::body_bypass(BodyPoint::SharedDecode, reason); + return Entity { + wire, + logical: None, + budget: self.budget.clone(), + bypass: Some(reason), + changed: false, + original_text: self.text_allowed, + }; + } + }; + if !has_rules(self.rules, self.original, self.phase) { + return entity; + } + let baseline = entity.logical().expect("decoded entity"); + if !self.text_allowed || std::str::from_utf8(baseline).is_err() { + let reason = if self.text_allowed { + Bypass::InvalidText + } else { + Bypass::Charset + }; + diagnostics::body_bypass(BodyPoint::NativeTransform, reason); + entity.bypass = Some(reason); + return entity; + } + match apply_operations( + self.rules, + self.original, + self.phase, + baseline, + &self.budget, + ) { + Ok(Some(output)) if output.as_ref() != baseline => { + if let Err(reason) = commit_shared_body(&mut entity, fields, output) { + diagnostics::body_bypass(BodyPoint::HeaderFinalize, reason); + entity.bypass = Some(reason); + } + } + Ok(_) => {} + Err(reason) => entity.bypass = Some(reason), + } + entity + } +} + +/// A read-only body view tied to its actual Entity or BudgetedBytes owner. +/// Private fields prevent pairing arbitrary bytes with a different ledger. +#[derive(Clone, Copy)] +#[cfg_attr( + not(all(feature = "inbound-http", target_os = "tvos")), + allow(dead_code) +)] +pub(crate) struct BorrowedBody<'a> { + bytes: &'a [u8], + budget: &'a Budget, +} +#[cfg_attr( + not(all(feature = "inbound-http", target_os = "tvos")), + allow(dead_code) +)] +impl<'a> BorrowedBody<'a> { + pub(crate) fn as_bytes(&self) -> &'a [u8] { + self.bytes + } + pub(crate) fn same_ledger_as(&self, output: &BudgetedBytes) -> bool { + self.budget.same_ledger(output.budget()) + } +} +impl BudgetedBytes { + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + pub(crate) fn borrowed_body(&self) -> BorrowedBody<'_> { + BorrowedBody { + bytes: self.as_ref(), + budget: self.budget(), + } + } +} + +/// Complete wire representation and its decoded logical view. `Bytes` keeps +/// the original allocation's workspace permit through clones and send queues. +#[derive(Clone)] +pub(crate) struct Entity { + wire: Bytes, + logical: Option, + // Provenance only: the reservation still belongs to the actual Bytes owner. + budget: Budget, + pub(crate) bypass: Option, + changed: bool, + original_text: bool, +} +impl Entity { + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + pub(crate) fn identity(bytes: BudgetedBytes) -> Self { + let budget = bytes.budget().clone(); + let wire = bytes.into_bytes(); + Self { + logical: Some(wire.clone()), + wire, + budget, + bypass: None, + changed: false, + original_text: true, + } + } + pub(crate) fn wire(&self) -> &Bytes { + &self.wire + } + pub(crate) fn logical(&self) -> Option<&[u8]> { + self.logical.as_deref() + } + #[cfg_attr( + not(all(feature = "inbound-http", target_os = "tvos")), + allow(dead_code) + )] + pub(crate) fn borrowed_body(&self) -> Option> { + Some(BorrowedBody { + bytes: self.logical.as_deref()?, + budget: &self.budget, + }) + } + pub(crate) fn into_wire(self) -> Bytes { + self.wire + } + pub(crate) fn changed(&self) -> bool { + self.changed + } + pub(crate) fn original_text_allowed(&self) -> bool { + self.original_text + } + /// Reject a foreign owner before changing any part of this Entity. + pub(crate) fn replace(&mut self, bytes: BudgetedBytes) -> Result<(), BudgetedBytes> { + if !self.budget.same_ledger(bytes.budget()) { + return Err(bytes); + } + let bytes = bytes.into_bytes(); + self.wire = bytes.clone(); + self.logical = Some(bytes); + self.bypass = None; + self.changed = true; + Ok(()) + } +} + +/// Commit only after both header validation and owner provenance have passed. +fn commit_shared_body( + entity: &mut Entity, + fields: &mut Fields, + output: BudgetedBytes, +) -> Result<(), Bypass> { + let mut candidate = fields.clone(); + repair_metadata(&mut candidate, output.as_ref().len()); + super::headers::check(&candidate).map_err(|_| Bypass::Budget)?; + entity.replace(output).map_err(|_| Bypass::Budget)?; + *fields = candidate; + Ok(()) +} + +fn apply_operations( + rules: &[Rule], + original: &Url, + phase: Phase, + baseline: &[u8], + budget: &Budget, +) -> Result, Bypass> { + diagnostics::increment(Counter::NativeTransformRequested); + let result = (|| { + let mut candidate = None; + for rule in rules { + let RuleAction::Body { + phase: rule_phase, + operation, + } = &rule.action + else { + continue; + }; + if *rule_phase != phase || !rule.matches(original) { + continue; + } + match operation { + BodyOperation::Set(value) => { + candidate = + Some(BudgetedBytes::copy(budget, value.as_bytes()).ok_or(Bypass::Budget)?); + } + BodyOperation::Replace(search) => { + let input = candidate + .as_ref() + .map_or(baseline, |value: &BudgetedBytes| value.as_ref()); + let input = std::str::from_utf8(input).map_err(|_| Bypass::InvalidText)?; + let capacity = search.output_capacity(input.len(), MAX_BODY); + let mut output = + if search.ascii_literal_byte_map().is_some() && capacity == input.len() { + BudgetedBytes::new_fixed_output(budget, capacity) + } else { + BudgetedBytes::new(budget, capacity) + } + .ok_or(Bypass::Budget)?; + fill_replacement(input, search, &mut output)?; + candidate = Some(output); + } + BodyOperation::JsonPatch(patch) if patch.is_empty() => {} + BodyOperation::JsonPatch(patch) => { + let input = candidate + .as_ref() + .map_or(baseline, |value: &BudgetedBytes| value.as_ref()); + let input = std::str::from_utf8(input).map_err(|_| Bypass::InvalidText)?; + candidate = Some(json::apply(input, patch, budget)?); + } + } + } + Ok(candidate) + })(); + diagnostics::increment(Counter::NativeTransformFinished); + if let Err(reason) = &result { + diagnostics::body_bypass(BodyPoint::NativeTransform, *reason); + } + result +} + +/// Caller has validated UTF-8 and admitted the unchanged independent output. +fn fill_replacement( + input: &str, + search: &super::rules::Search, + output: &mut BudgetedBytes, +) -> Result<(), Bypass> { + if let Some((search, replacement, occurrences)) = search.ascii_literal_byte_map() { + // Admission is unchanged, including no-match/same-byte. ASCII bytes + // cannot occur within multibyte UTF-8 units. Dollar/NUL are literal data. + output + .write_initialized_output(input.len(), |output| { + if occurrences == super::rules::Occurrences::First { + output.copy_from_slice(input.as_bytes()); + if let Some(index) = input.find(char::from(search)) { + output[index] = replacement; + } + } else { + for (output, input) in output.iter_mut().zip(input.as_bytes()) { + *output = if *input == search { + replacement + } else { + *input + }; + } + } + Ok(input.len()) + }) + .map_err(|_| Bypass::Transform) + } else { + output + .write_text(|output| search.apply_into(input, output, MAX_BODY)) + .map_err(|_| Bypass::Transform) + } } /// Final representation repair follows successful content changes and therefore /// takes precedence over independently successful ordinary header actions. pub(crate) fn repair_metadata(fields: &mut Fields, length: usize) { + repair_metadata_kind(fields, length, true); +} + +pub(crate) fn repair_metadata_kind(fields: &mut Fields, length: usize, text: bool) { fields.retain(|(name, _)| { !matches!( name.to_ascii_lowercase().as_str(), @@ -391,10 +712,11 @@ pub(crate) fn repair_metadata(fields: &mut Fields, length: usize) { | "signature" | "signature-input" | "accept-ranges" + | "content-range" ) }); for (name, value) in fields.iter_mut() { - if name.eq_ignore_ascii_case("content-type") { + if text && name.eq_ignore_ascii_case("content-type") { let mut pieces = value.split(';'); let mut repaired = pieces.next().unwrap_or_default().to_owned(); for parameter in pieces { @@ -414,9 +736,447 @@ pub(crate) fn repair_metadata(fields: &mut Fields, length: usize) { fields.push(("Content-Length".into(), length.to_string())); } +#[cfg(all( + feature = "inbound-http", + feature = "http-diagnostics", + target_os = "tvos" +))] +#[path = "native_byte_map_validation.rs"] +mod native_byte_map_validation; +#[cfg(all( + feature = "inbound-http", + feature = "http-diagnostics", + target_os = "tvos" +))] +pub(crate) fn validate_native_byte_map() -> std::io::Result { + native_byte_map_validation::run() +} + #[cfg(test)] mod tests { use super::*; + + #[cfg(all(unix, feature = "inbound-http"))] + #[forbid(unsafe_code)] + mod shared_collector_mapping_tests { + include!("shared_collector_body_memory_tests.rs"); + } + + #[test] + fn borrowed_body_factories_borrow_the_same_allocation_and_actual_ledger() { + let budget = Budget::default(); + let input = BudgetedBytes::copy(&budget, b"paid\0input").unwrap(); + let local_output = BudgetedBytes::empty(&budget); + let foreign_output = BudgetedBytes::empty(&Budget::default()); + let original_charge = budget.used(); + { + let view = input.borrowed_body(); + assert_eq!(view.as_bytes().as_ptr(), input.as_ref().as_ptr()); + assert_eq!(view.as_bytes(), b"paid\0input"); + assert!(view.same_ledger_as(&local_output)); + assert!(!view.same_ledger_as(&foreign_output)); + assert_eq!(budget.used(), original_charge); + } + let entity = Entity::identity(input); + let clone = entity.clone(); + { + let view = entity.borrowed_body().unwrap(); + assert_eq!(view.as_bytes().as_ptr(), clone.logical().unwrap().as_ptr()); + assert!(view.same_ledger_as(&local_output)); + assert!(!view.same_ledger_as(&foreign_output)); + assert_eq!(budget.used(), original_charge); + } + drop(entity); + assert_eq!(budget.used(), original_charge); + drop(clone); + assert_eq!(budget.used(), 0); + } + + #[test] + fn shared_native_commit_keeps_body_and_metadata_atomic_on_foreign_owner() { + let budget = Budget::default(); + let foreign = Budget::default(); + let mut entity = Entity::identity(BudgetedBytes::copy(&budget, b"original").unwrap()); + let original_wire = entity.wire().clone(); + let mut fields = vec![ + ("Content-Length".into(), "8".into()), + ("ETag".into(), "original-tag".into()), + ("Content-Type".into(), "text/plain".into()), + ]; + let before = fields.clone(); + let output = BudgetedBytes::copy(&foreign, b"foreign-longer").unwrap(); + assert_eq!( + commit_shared_body(&mut entity, &mut fields, output), + Err(Bypass::Budget) + ); + assert_eq!(fields, before); + assert_eq!(entity.wire().as_ptr(), original_wire.as_ptr()); + assert_eq!(entity.logical().unwrap(), b"original"); + assert!(!entity.changed()); + assert_eq!(foreign.used(), 0); + + // The same production helper really commits a correctly paid owner. + let output = BudgetedBytes::copy(&budget, b"accepted-longer").unwrap(); + assert_eq!(commit_shared_body(&mut entity, &mut fields, output), Ok(())); + assert_eq!(entity.logical().unwrap(), b"accepted-longer"); + assert!(entity.changed()); + assert!( + fields + .iter() + .any(|(k, v)| k.eq_ignore_ascii_case("content-length") && v == "15") + ); + assert!(!fields.iter().any(|(k, _)| k.eq_ignore_ascii_case("etag"))); + drop(entity); + assert_eq!(budget.used(), BudgetedBytes::allocation_cost(8).unwrap()); + drop(original_wire); + assert_eq!(budget.used(), 0); + } + + #[cfg(feature = "inbound-http")] + #[tokio::test] + async fn borrowed_entity_owner_stays_charged_during_the_actual_blocked_sender() { + let budget = Budget::default(); + let entity = Entity::identity(BudgetedBytes::copy(&budget, &vec![b'x'; 4096]).unwrap()); + let cost = budget.used(); + { + let view = entity.borrowed_body().unwrap(); + assert_eq!(view.as_bytes(), &vec![b'x'; 4096]); + assert_eq!(budget.used(), cost); + } + let wire = entity.into_wire(); + let last_slice = wire.slice(17..18); + let prepared = super::super::h1_body::PreparedBody::from_bytes(wire); + let mut reader = tokio::io::BufReader::new(tokio::io::empty()); + let (mut writer, peer) = tokio::io::duplex(8); + let blocklist = std::collections::HashSet::new(); + let mut sending = Box::pin(prepared.transfer( + &mut reader, + &mut writer, + std::time::Duration::from_secs(1), + &blocklist, + false, + )); + // An 8-byte duplex cannot finish the real 4096-byte write_all. No + // spawned task needs cleanup if an assertion unwinds this test. + assert!(futures_util::poll!(sending.as_mut()).is_pending()); + assert_eq!(budget.used(), cost); + drop(sending); + drop(peer); + assert_eq!(budget.used(), cost); + assert_eq!(last_slice.as_ref(), b"x"); + drop(last_slice); + assert_eq!(budget.used(), 0); + } + + #[cfg(all(unix, feature = "inbound-http"))] + #[test] + fn native_fixed_outputs_select_backing_and_keep_source_and_sender_owners_paid() { + const SUFFIX: &[u8] = "é😀中\0$".as_bytes(); + let url = Url::parse("https://fixed-output.invalid/body").unwrap(); + for capacity in [64 * 1024 - 1, 64 * 1024, MAX_BODY] { + for occurrences in ["first", "all"] { + let budget = Budget::default(); + let mut source = BudgetedBytes::new(&budget, capacity).unwrap(); + source + .write_initialized_output(capacity, |bytes| { + bytes.fill(b'q'); + bytes[capacity - SUFFIX.len()..].copy_from_slice(SUFFIX); + Ok(capacity) + }) + .unwrap(); + assert!(!source.is_mapped_for_test()); + let mut entity = Entity::identity(source); + let original = std::str::from_utf8(entity.logical().unwrap()).unwrap(); + let expected = if occurrences == "first" { + original.replacen('q', "z", 1) + } else { + original.replace('q', "z") + }; + let selected = rules(&format!( + "- {{url: '.', action: response-body-replace, search: q, replacement: z, occurrences: {occurrences}}}" + )); + let output = apply_operations( + &selected, + &url, + Phase::Response, + entity.logical().unwrap(), + &budget, + ) + .unwrap() + .unwrap(); + assert_eq!(output.is_mapped_for_test(), capacity >= 64 * 1024); + assert_eq!(output.as_ref(), expected.as_bytes()); + assert!(std::str::from_utf8(output.as_ref()).is_ok()); + assert_ne!(output.as_ref().as_ptr(), entity.logical().unwrap().as_ptr()); + let cost = BudgetedBytes::allocation_cost(capacity).unwrap(); + assert_eq!(budget.used(), 2 * cost); + let source_sender = entity.wire().slice(..1); + let mut fields = vec![("ETag".into(), "old".into())]; + commit_shared_body(&mut entity, &mut fields, output).unwrap(); + assert!(entity.changed()); + assert_eq!(budget.used(), 2 * cost); + let sender = entity.into_wire(); + let last_output = sender.slice(capacity - 1..); + drop(sender); + assert_eq!(last_output.as_ref(), &expected.as_bytes()[capacity - 1..]); + assert_eq!(source_sender.as_ref(), b"q"); + assert_eq!(budget.used(), 2 * cost); + drop(source_sender); + assert_eq!(budget.used(), cost); + drop(last_output); + assert_eq!(budget.used(), 0); + } + } + } + + #[cfg(all(unix, feature = "inbound-http"))] + #[test] + fn native_fixed_output_keeps_noop_representation_and_whole_stage_rollback() { + let url = Url::parse("https://fixed-output.invalid/body").unwrap(); + let original = vec![b'q'; 64 * 1024]; + for (yaml, bypass) in [ + ( + "- {url: '.', action: request-body-replace, search: q, replacement: q}", + None, + ), + ( + "- {url: '.', action: request-body-replace, search: x, replacement: z}", + None, + ), + ( + "- {url: '.', action: request-body-replace, search: q, replacement: z}\n- {url: '.', action: request-body-json-patch, patch: [{op: test, path: /ok, value: false}]}", + Some(Bypass::Transform), + ), + ] { + let budget = Budget::default(); + let selected = rules(yaml); + let mut fields = vec![ + ("ETag".into(), "old".into()), + ("X-Independent".into(), "kept".into()), + ]; + let before = fields.clone(); + let request = OriginalRequestMeta::new("POST", &fields); + let wire = WireBodyMeta::new( + &fields, + &request, + Phase::Request, + None, + Some(original.len() as u64), + false, + ); + let mut transaction = + Transaction::begin_shared(&budget, &selected, &url, Phase::Request, &wire, true) + .unwrap(); + transaction.push(&original).unwrap(); + let entity = transaction.finish_shared(false, &mut fields); + assert!(!entity.changed()); + assert_eq!(entity.bypass, bypass); + assert_eq!(entity.logical().unwrap(), original.as_slice()); + assert_eq!(entity.wire().as_ref(), original.as_slice()); + assert_eq!(fields, before); + assert_eq!( + budget.used(), + BudgetedBytes::allocation_cost(original.len()).unwrap() + ); + drop(entity); + assert_eq!(budget.used(), 0); + } + } + + #[test] + fn literal_capacity_keeps_a_second_real_transaction_admissible_under_pressure() { + const LENGTH: usize = 65536; + let budget = Budget::default(); + let rules = rules("- {url: '.', action: response-body-replace, search: q, replacement: z}"); + let url = Url::parse("http://capacity.example/").unwrap(); + let request = OriginalRequestMeta::new("GET", &vec![]); + let wire = WireBodyMeta::new( + &vec![], + &request, + Phase::Response, + Some(200), + Some(LENGTH as u64), + false, + ); + let small = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let old_maximum = BudgetedBytes::allocation_cost(MAX_BODY).unwrap(); + // This fixed pressure still lets the old implementation finish the + // first real transform at its original raw + MAX allocation peak. + let pressure = budget + .reserve(budget::WORKSPACE - small - old_maximum) + .unwrap(); + let mut first = + Transaction::begin_shared(&budget, &rules, &url, Phase::Response, &wire, true).unwrap(); + first.push(&vec![b'q'; LENGTH]).unwrap(); + let first = first.finish_shared(false, &mut vec![]); + assert!(first.changed()); + // Old MAX residency leaves exactly one raw slot; the extra byte makes + // the second genuine collector fail rather than simulating a reserve. + let boundary = budget.reserve(1).unwrap(); + let mut second = + Transaction::begin_shared(&budget, &rules, &url, Phase::Response, &wire, true) + .expect("retained literal output must leave the second real collector admissible"); + second.push(&vec![b'q'; LENGTH]).unwrap(); + let second = second.finish_shared(false, &mut vec![]); + assert!(second.changed()); + assert_eq!(second.bypass, None); + assert_eq!(second.wire().as_ref(), vec![b'z'; LENGTH]); + assert_eq!( + budget.used(), + budget::WORKSPACE - small - old_maximum + 1 + 2 * small + ); + drop(second); + drop(first); + drop(boundary); + drop(pressure); + assert_eq!(budget.used(), 0); + } + + #[test] + fn literal_capacity_regex_and_growth_keep_full_capacity_and_budget_fallback() { + let url = Url::parse("http://capacity.example/").unwrap(); + for yaml in [ + "- {url: '.', action: request-body-replace, search: a, replacement: aa}", + "- {url: '.', action: request-body-replace, search: '(a)', search-mode: regex, replacement: '${1}'}", + ] { + let rules = rules(yaml); + let budget = Budget::default(); + let output = apply_operations(&rules, &url, Phase::Request, b"a", &budget) + .unwrap() + .unwrap(); + assert_eq!(output.remaining() + output.as_ref().len(), MAX_BODY); + assert_eq!( + budget.used(), + BudgetedBytes::allocation_cost(MAX_BODY).unwrap() + ); + drop(output); + let request = OriginalRequestMeta::new("POST", &vec![]); + let wire = WireBodyMeta::new(&vec![], &request, Phase::Request, None, Some(1), false); + let mut transaction = + Transaction::begin_shared(&budget, &rules, &url, Phase::Request, &wire, true) + .unwrap(); + transaction.push(b"a").unwrap(); + let pressure = budget + .reserve( + budget::WORKSPACE - budget.used() - BudgetedBytes::allocation_cost(1).unwrap(), + ) + .unwrap(); + let entity = transaction.finish_shared(false, &mut vec![]); + assert!(!entity.changed()); + assert_eq!(entity.bypass, Some(Bypass::Budget)); + assert_eq!(entity.wire().as_ref(), b"a"); + drop(entity); + drop(pressure); + assert_eq!(budget.used(), 0); + } + } + + #[test] + fn shared_native_failure_keeps_decoded_entity_and_original_compressed_wire() { + use std::io::Write; + let budget = Budget::default(); + let rules = rules( + "- {url: '.', action: request-body-json-patch, patch: [{op: test, path: /ok, value: false}]}", + ); + let fields = vec![("Content-Encoding".into(), "gzip".into())]; + let mut gzip = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default()); + gzip.write_all(br#"{"ok":true}"#).unwrap(); + let gzip = gzip.finish().unwrap(); + let meta = OriginalRequestMeta::new("POST", &fields); + let wire = WireBodyMeta::new( + &fields, + &meta, + Phase::Request, + None, + Some(gzip.len() as u64), + false, + ); + let original = Url::parse("http://example.com/").unwrap(); + let mut transaction = + Transaction::begin_shared(&budget, &rules, &original, Phase::Request, &wire, true) + .unwrap(); + transaction.push(&gzip).unwrap(); + let mut final_fields = fields.clone(); + let entity = transaction.finish_shared(false, &mut final_fields); + assert_eq!(entity.logical().unwrap(), br#"{"ok":true}"#); + assert_eq!(entity.wire().as_ref(), gzip); + assert!(!entity.changed()); + assert_eq!(final_fields, fields); + assert!(entity.bypass.is_some()); + let retained = entity.clone(); + drop(entity); + assert!(budget.used() > 0); + drop(retained); + assert_eq!(budget.used(), 0); + } + + #[test] + fn shared_binary_input_survives_native_text_exclusion_and_decode_failure_is_unavailable() { + let budget = Budget::default(); + let rules = rules("- {url: '.', action: request-body-set, value: changed}"); + let original = Url::parse("http://example.com/").unwrap(); + let fields = vec![( + "Content-Type".into(), + "application/octet-stream; charset=latin1".into(), + )]; + let meta = OriginalRequestMeta::new("POST", &fields); + let wire = WireBodyMeta::new(&fields, &meta, Phase::Request, None, Some(2), false); + assert!(matches!( + Transaction::begin(&budget, &rules, &original, Phase::Request, &wire), + Err(Bypass::Charset) + )); + let mut transaction = + Transaction::begin_shared(&budget, &rules, &original, Phase::Request, &wire, true) + .unwrap(); + transaction.push(&[0xff, 0x00]).unwrap(); + let mut final_fields = fields.clone(); + let entity = transaction.finish_shared(false, &mut final_fields); + assert_eq!(entity.logical().unwrap(), &[0xff, 0x00]); + assert!(!entity.original_text_allowed()); + drop(entity); + let fields = vec![("Content-Encoding".into(), "gzip".into())]; + let wire = WireBodyMeta::new(&fields, &meta, Phase::Request, None, Some(3), false); + let mut transaction = + Transaction::begin_shared(&budget, &[], &original, Phase::Request, &wire, true) + .unwrap(); + transaction.push(b"bad").unwrap(); + let entity = transaction.finish_shared(false, &mut vec![]); + assert!(entity.logical().is_none()); + assert_eq!(entity.wire().as_ref(), b"bad"); + drop(entity); + assert_eq!(budget.used(), 0); + } + + #[test] + fn shared_native_success_releases_old_representation_and_repairs_before_acceptance() { + let budget = Budget::default(); + let rules = rules("- {url: '.', action: request-body-set, value: changed}"); + let original = Url::parse("http://example.com/").unwrap(); + let mut fields = vec![("ETag".into(), "old".into())]; + let meta = OriginalRequestMeta::new("POST", &fields); + let wire = WireBodyMeta::new(&fields, &meta, Phase::Request, None, Some(8), false); + let mut transaction = + Transaction::begin_shared(&budget, &rules, &original, Phase::Request, &wire, true) + .unwrap(); + transaction.push(b"original").unwrap(); + let entity = transaction.finish_shared(false, &mut fields); + assert!(entity.changed()); + assert_eq!(entity.wire().as_ref(), b"changed"); + assert!( + !fields + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("etag")) + ); + assert!(budget.used() < 1024); + drop(entity); + assert_eq!(budget.used(), 0); + let no_content = + WireBodyMeta::new(&vec![], &meta, Phase::Response, Some(205), Some(0), false); + assert!(matches!( + no_content.common_eligibility(), + Err(Bypass::ForbiddenBody) + )); + } fn rules(yaml: &str) -> Vec { let raw: Vec = serde_yaml_ng::from_str(yaml).unwrap(); let mut total = 0; diff --git a/src/http_processing/body_budget.rs b/src/http_processing/body_budget.rs index 004482e..b60cfe9 100644 --- a/src/http_processing/body_budget.rs +++ b/src/http_processing/body_budget.rs @@ -9,7 +9,71 @@ use std::{ }; pub(crate) const MAX_BODY: usize = 256 * 1024; -pub(crate) const WORKSPACE: usize = 2 * 1024 * 1024; +pub(crate) const WORKSPACE: usize = 4 * 1024 * 1024; + +// A public JSC string view can own an N-byte 8-bit copy plus a 2N-byte +// UTF-16 expansion. This is bridge admission, not a VM heap bound. +#[cfg(feature = "inbound-http")] +pub(crate) const API_TEXT_VIEW: usize = 3 * MAX_BODY; + +#[cfg(all(feature = "inbound-http", test))] +pub(crate) fn bridge_workspace_cost(input: usize, text: bool) -> Option { + BridgePlan::new(input, text, MAX_BODY)?.cost() +} + +// A paid API terminator scratch byte is never a larger logical body bound. +#[cfg(feature = "inbound-http")] +pub(crate) fn output_capacity(bound: usize) -> Option { + if bound > MAX_BODY { + return None; + } + Some(if bound > 0 && bound < MAX_BODY { + bound + 1 + } else { + bound + }) +} + +/// Independent retained-input and scratch payloads. This is a conservative +/// copy ledger, not storage, a VM heap limit, or a second execution lane. +#[cfg(feature = "inbound-http")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct BridgePlan { + pub(crate) retained_input: usize, + pub(crate) view_capacity: usize, + pub(crate) input_vec_bookkeeping: usize, +} +#[cfg(feature = "inbound-http")] +impl BridgePlan { + pub(crate) fn new(input: usize, text: bool, output: usize) -> Option { + if input > MAX_BODY || output > MAX_BODY { + return None; + } + let vector = std::mem::size_of::>(); + let literal_peak = input + .checked_mul(7)? + .checked_add(vector)? + .min(API_TEXT_VIEW); + let view_capacity = output.checked_mul(3)?.max(literal_peak); + Some(Self { + retained_input: if text { input.checked_mul(2)? } else { 0 }, + view_capacity, + input_vec_bookkeeping: if text { vector } else { 0 }, + }) + } + pub(crate) fn cost(self) -> Option { + self.retained_input + .checked_add(self.view_capacity)? + .checked_add(self.input_vec_bookkeeping) + } + #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))] + pub(crate) fn allows_utf8_input(self, input: usize) -> bool { + input + .checked_mul(3) + .and_then(|n| n.checked_add(1)) + .is_some_and(|peak| peak <= self.view_capacity) + } +} #[derive(Clone)] pub(crate) struct Budget(Arc); @@ -28,13 +92,25 @@ impl Default for Budget { } impl Budget { + /// Identity of the actual shared ledger, independent of its current charge. + pub(super) fn same_ledger(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.0, &other.0) + } + pub(crate) fn reserve(&self, bytes: usize) -> Option { - self.0 + let previous = match self + .0 .used .try_update(Ordering::AcqRel, Ordering::Acquire, |used| { used.checked_add(bytes).filter(|next| *next <= self.0.limit) - }) - .ok()?; + }) { + Ok(previous) => previous, + Err(_) => { + super::diagnostics::increment(super::diagnostics::Counter::BodyReserveRejected); + return None; + } + }; + super::diagnostics::body_reserved(bytes, previous + bytes); Some(Reservation { budget: self.clone(), bytes, @@ -54,20 +130,193 @@ pub(crate) struct Reservation { impl Drop for Reservation { fn drop(&mut self) { self.budget.0.used.fetch_sub(self.bytes, Ordering::AcqRel); + super::diagnostics::body_released(self.bytes); + } +} + +impl Reservation { + /// Join reservations from one ledger without changing its admitted total. + /// Failure preserves the additional owner; no amount is silently refunded. + #[cfg(all(feature = "inbound-http", target_vendor = "apple"))] + pub(crate) fn merge(&mut self, mut additional: Self) -> Result<(), Self> { + if !Arc::ptr_eq(&self.budget.0, &additional.budget.0) { + return Err(additional); + } + let Some(bytes) = self.bytes.checked_add(additional.bytes) else { + return Err(additional); + }; + self.bytes = bytes; + additional.bytes = 0; + Ok(()) + } + + #[cfg(feature = "inbound-http")] + #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))] + pub(crate) fn covers(&self, output: &BudgetedBytes, bytes: usize) -> bool { + self.bytes >= bytes && Arc::ptr_eq(&self.budget.0, &output._reservation.budget.0) + } + + /// Divide an already admitted reservation without changing the shared total. + pub(crate) fn split(&mut self, bytes: usize) -> Option { + if bytes > self.bytes { + return None; + } + self.bytes -= bytes; + Some(Self { + budget: self.budget.clone(), + bytes, + }) } } /// A fixed-capacity allocation. Its reservation follows every Bytes slice and /// is released only when the last sender/driver has dropped the actual owner. pub(crate) struct BudgetedBytes { - bytes: Vec, + // Fields drop in declaration order. The real backing owner must finish its + // destruction (including an anonymous map's unmap Drop) before refunding. + bytes: Backing, _reservation: Reservation, } +enum Backing { + Vector(Vec), + #[cfg(all(unix, feature = "inbound-http"))] + Mapped(MappedOutput), +} + +#[cfg(all(unix, feature = "inbound-http"))] +const MAPPED_FIXED_OUTPUT_MINIMUM: usize = 64 * 1024; + +#[cfg(all(unix, feature = "inbound-http"))] +struct MappedOutput { + bytes: memmap2::MmapMut, + length: usize, + // Test-only observation runs after the real mapping destructor, before + // BudgetedBytes refunds. It does not assert OS unmap success or RSS. + #[cfg(test)] + after_unmap: Option, +} + +#[cfg(all(test, unix, feature = "inbound-http"))] +struct MappedDropWitness { + budget: Budget, + observed_used: Arc, +} + +#[cfg(all(test, unix, feature = "inbound-http"))] +impl Drop for MappedDropWitness { + fn drop(&mut self) { + self.observed_used + .store(self.budget.used(), Ordering::Release); + } +} + +impl Backing { + fn capacity(&self) -> usize { + match self { + Self::Vector(bytes) => bytes.capacity(), + #[cfg(all(unix, feature = "inbound-http"))] + Self::Mapped(mapped) => mapped.bytes.len(), + } + } + + fn initialized(&mut self, length: usize) -> &mut [u8] { + match self { + Self::Vector(bytes) => { + bytes.resize(length, 0); + bytes + } + #[cfg(all(unix, feature = "inbound-http"))] + Self::Mapped(mapped) => { + mapped.length = length; + let bytes = &mut mapped.bytes[..length]; + // Match Vec::resize even when an earlier failed callback left + // scratch contents in this still-owned, fully paid mapping. + bytes.fill(0); + bytes + } + } + } + + fn truncate(&mut self, length: usize) { + match self { + Self::Vector(bytes) => bytes.truncate(length), + #[cfg(all(unix, feature = "inbound-http"))] + Self::Mapped(mapped) => mapped.length = mapped.length.min(length), + } + } +} + +impl AsRef<[u8]> for Backing { + fn as_ref(&self) -> &[u8] { + match self { + Self::Vector(bytes) => bytes, + #[cfg(all(unix, feature = "inbound-http"))] + Self::Mapped(mapped) => &mapped.bytes[..mapped.length], + } + } +} + impl BudgetedBytes { + /// The allocation's actual ledger; borrowing this handle does not refund it. + pub(crate) fn budget(&self) -> &Budget { + &self._reservation.budget + } + + #[cfg(feature = "inbound-http")] + #[cfg_attr(not(target_vendor = "apple"), allow(dead_code))] + pub(crate) fn reserve_temporary(&self, bytes: usize) -> Option { + self._reservation.budget.reserve(bytes) + } + + /// No allocation and no body-workspace admission for a metadata-only call. + /// A backend exporting a nonempty result must call `prepare_output` first. + pub(crate) fn empty(budget: &Budget) -> Self { + Self { + bytes: Backing::Vector(Vec::new()), + _reservation: Reservation { + budget: budget.clone(), + bytes: 0, + }, + } + } + pub(crate) fn allocation_cost(capacity: usize) -> Option { + capacity.checked_add(std::mem::size_of::()) + } + pub(crate) fn new(budget: &Budget, capacity: usize) -> Option { - let bytes = capacity.checked_add(std::mem::size_of::())?; + let bytes = Self::allocation_cost(capacity)?; let reservation = budget.reserve(bytes)?; + Self::from_reserved(reservation, capacity) + } + + /// All known shared entities keep original one-shot admission/capacity. + /// Apple may map them, also with native body plus metadata-only scripts. + /// Unknown lengths keep the original MAX_BODY + 1 Vec sentinel. + pub(crate) fn new_shared_collector( + budget: &Budget, + capacity: usize, + known_length: bool, + ) -> Option { + let reservation = budget.reserve(Self::allocation_cost(capacity)?)?; + if cfg!(target_vendor = "apple") && known_length && capacity <= MAX_BODY { + Self::from_reserved_fixed_capacity(reservation, capacity) + } else { + Self::from_reserved(reservation, capacity) + } + } + + pub(crate) fn from_reserved(reservation: Reservation, capacity: usize) -> Option { + if reservation.bytes != Self::allocation_cost(capacity)? { + return None; + } + Some(Self { + bytes: Backing::Vector(Self::allocate_vector(capacity)?), + _reservation: reservation, + }) + } + + fn allocate_vector(capacity: usize) -> Option> { let mut buffer = Vec::new(); buffer.try_reserve_exact(capacity).ok()?; // Vec's allocation policy is allowed to return more than requested. @@ -75,12 +324,117 @@ impl BudgetedBytes { if buffer.capacity() > capacity { return None; } + Some(buffer) + } + + /// Independently admit a proven fixed-bound byte output before its fill. + /// Closed Plans and native ASCII byte maps use this allocation policy. + pub(crate) fn new_fixed_output(budget: &Budget, capacity: usize) -> Option { + if capacity > MAX_BODY { + return None; + } + let reservation = budget.reserve(Self::allocation_cost(capacity)?)?; + Self::from_reserved_fixed_output(reservation, capacity) + } + + /// Reuse a complete reservation for a proven fixed-bound byte output. + /// Native String/JSC outputs and the separate native-only entry keep Vec. + pub(crate) fn from_reserved_fixed_output( + reservation: Reservation, + capacity: usize, + ) -> Option { + Self::from_reserved_fixed_capacity(reservation, capacity) + } + + // Physical fixed-capacity byte backing only: this does not initialize an + // output, infer a body length, or create another workspace reservation. + fn from_reserved_fixed_capacity(reservation: Reservation, capacity: usize) -> Option { + if capacity > MAX_BODY { + return None; + } + #[cfg(all(unix, feature = "inbound-http"))] + { + Self::from_reserved_fixed_output_with( + reservation, + capacity, + memmap2::MmapMut::map_anon, + Self::allocate_vector, + ) + } + #[cfg(not(all(unix, feature = "inbound-http")))] + { + Self::from_reserved(reservation, capacity) + } + } + + #[cfg(all(unix, feature = "inbound-http"))] + fn from_reserved_fixed_output_with( + reservation: Reservation, + capacity: usize, + map: impl FnOnce(usize) -> io::Result, + vector: impl FnOnce(usize) -> Option>, + ) -> Option { + if capacity > MAX_BODY || reservation.bytes != Self::allocation_cost(capacity)? { + return None; + } + let mapping = if capacity >= MAPPED_FIXED_OUTPUT_MINIMUM { + map(capacity).ok().filter(|bytes| bytes.len() == capacity) + } else { + None + }; + let bytes = if let Some(bytes) = mapping { + Backing::Mapped(MappedOutput { + bytes, + length: 0, + #[cfg(test)] + after_unmap: None, + }) + } else { + // Mapping failure does not consume or reacquire the reservation. + // Only one successful backing allocation is ever retained. + let bytes = vector(capacity)?; + if !bytes.is_empty() || bytes.capacity() != capacity { + return None; + } + Backing::Vector(bytes) + }; Some(Self { - bytes: buffer, + bytes, _reservation: reservation, }) } + #[cfg(all(test, unix, feature = "inbound-http"))] + pub(crate) fn is_mapped_for_test(&self) -> bool { + matches!(self.bytes, Backing::Mapped(_)) + } + + /// Admit a known result before copying it out of an engine. Body-less calls + /// use an empty buffer until the backend knows that a result has a body. + #[cfg(all(feature = "inbound-http", any(test, target_vendor = "apple")))] + pub(crate) fn prepare_output(&mut self, length: usize) -> io::Result<()> { + if length > MAX_BODY { + return Err(io::Error::new( + io::ErrorKind::FileTooLarge, + "HTTP script body exceeded", + )); + } + if self.bytes.capacity() >= length { + return Ok(()); + } + let replacement = Self::new(&self._reservation.budget, length).ok_or_else(|| { + io::Error::new(io::ErrorKind::OutOfMemory, "HTTP body workspace exceeded") + })?; + if !self.bytes.as_ref().is_empty() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "HTTP script output is not empty", + )); + } + *self = replacement; + Ok(()) + } + pub(crate) fn copy(budget: &Budget, value: &[u8]) -> Option { let mut result = Self::new(budget, value.len())?; result.extend(value).ok()?; @@ -94,12 +448,56 @@ impl BudgetedBytes { "HTTP body workspace exceeded", )); } - self.bytes.extend_from_slice(value); + match &mut self.bytes { + Backing::Vector(bytes) => bytes.extend_from_slice(value), + #[cfg(all(unix, feature = "inbound-http"))] + Backing::Mapped(mapped) => { + let end = mapped.length + value.len(); + mapped.bytes[mapped.length..end].copy_from_slice(value); + mapped.length = end; + } + } Ok(()) } + /// Fill initialized bytes inside an existing, independently admitted allocation. + /// The callback returns the retained length; scratch bytes remain charged + /// through this owner's unchanged capacity and are never exposed as body. + pub(crate) fn write_initialized_output( + &mut self, + length: usize, + operation: impl FnOnce(&mut [u8]) -> io::Result, + ) -> io::Result<()> { + if !self.bytes.as_ref().is_empty() || length > MAX_BODY || length > self.remaining() { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "HTTP script output scratch is not available", + )); + } + // The capacity check above prevents resize from allocating. Every byte + // passed to the callback is initialized, including terminator scratch. + let result = operation(self.bytes.initialized(length)); + match result { + Ok(retained) if retained <= length => { + self.bytes.truncate(retained); + Ok(()) + } + Ok(_) => { + self.bytes.truncate(0); + Err(io::Error::new( + io::ErrorKind::InvalidData, + "HTTP script output scratch length is invalid", + )) + } + Err(error) => { + self.bytes.truncate(0); + Err(error) + } + } + } + pub(crate) fn remaining(&self) -> usize { - self.bytes.capacity() - self.bytes.len() + self.bytes.capacity() - self.bytes.as_ref().len() } pub(crate) fn into_bytes(self) -> Bytes { @@ -110,17 +508,30 @@ impl BudgetedBytes { &mut self, operation: impl FnOnce(&mut String) -> io::Result<()>, ) -> io::Result<()> { - let mut text = String::from_utf8(std::mem::take(&mut self.bytes)) + // Mapped backing is private to bounded byte writers/collectors. Do not + // silently allocate an unpaid String copy if that internal boundary is + // accidentally crossed; all existing String-capable constructors use Vec. + let bytes = match &mut self.bytes { + Backing::Vector(bytes) => bytes, + #[cfg(all(unix, feature = "inbound-http"))] + Backing::Mapped(_) => { + return Err(io::Error::new( + io::ErrorKind::InvalidInput, + "HTTP direct output does not use String storage", + )); + } + }; + let mut text = String::from_utf8(std::mem::take(bytes)) .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "HTTP body text is invalid"))?; let result = operation(&mut text); - self.bytes = text.into_bytes(); + *bytes = text.into_bytes(); result } } impl AsRef<[u8]> for BudgetedBytes { fn as_ref(&self) -> &[u8] { - &self.bytes + self.bytes.as_ref() } } impl io::Write for BudgetedBytes { @@ -135,7 +546,150 @@ impl io::Write for BudgetedBytes { #[cfg(test)] mod tests { + #[cfg(feature = "inbound-http")] + #[test] + fn bounded_bridge_plan_preserves_maximum_boundary_and_constructor_peaks() { + let vector = std::mem::size_of::>(); + for input in [0, 1, 4096, 65536, MAX_BODY - 1, MAX_BODY] { + let old = 2 * input + API_TEXT_VIEW + vector; + let unknown = BridgePlan::new(input, true, MAX_BODY).unwrap(); + assert_eq!(unknown.cost(), Some(old)); + for output in [0, input, MAX_BODY] { + let plan = BridgePlan::new(input, true, output).unwrap(); + assert!(plan.view_capacity >= 2 * input); + assert!(plan.view_capacity >= 3 * output); + assert!(plan.cost().unwrap() <= old); + if plan.allows_utf8_input(input) { + assert!(plan.view_capacity >= 3 * input + 1); + } + } + } + assert!( + !BridgePlan::new(MAX_BODY, true, MAX_BODY) + .unwrap() + .allows_utf8_input(MAX_BODY) + ); + assert_eq!(BridgePlan::new(MAX_BODY + 1, true, 0), None); + assert_eq!(BridgePlan::new(0, true, MAX_BODY + 1), None); + } + use super::*; + #[test] + fn ledger_identity_tracks_the_owner_not_equal_limits_or_charges() { + let left = Budget::default(); + let right = Budget::default(); + let left_alias = left.clone(); + let bytes = BudgetedBytes::copy(&left, b"same").unwrap(); + let other = BudgetedBytes::copy(&right, b"same").unwrap(); + assert_eq!(left.used(), right.used()); + assert!(bytes.budget().same_ledger(&left_alias)); + assert!(!bytes.budget().same_ledger(other.budget())); + let cost = left.used(); + let wire = bytes.into_bytes(); + let slice = wire.slice(1..2); + drop(wire); + assert_eq!(left.used(), cost); + drop(slice); + // The ledger alias itself owns no payload reservation. + assert_eq!(left.used(), 0); + drop(other); + assert_eq!(right.used(), 0); + drop(left_alias); + } + + #[cfg(feature = "inbound-http")] + #[test] + fn initialized_output_scratch_never_allocates_and_keeps_capacity_charged() { + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, 4).unwrap(); + let cost = budget.used(); + output + .write_initialized_output(4, |bytes| { + assert_eq!(bytes, &[0, 0, 0, 0]); + bytes.copy_from_slice(b"a\0b\0"); + Ok(3) + }) + .unwrap(); + assert_eq!(output.as_ref(), b"a\0b"); + assert_eq!(output.remaining(), 1); + assert_eq!(budget.used(), cost); + let retained = output.into_bytes(); + let owner = retained.slice(1..); + drop(retained); + assert_eq!(&owner[..], b"\0b"); + assert_eq!(budget.used(), cost); + drop(owner); + assert_eq!(budget.used(), 0); + } + + #[cfg(feature = "inbound-http")] + #[test] + fn initialized_output_scratch_rejects_growth_and_clears_failed_copy() { + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, 4).unwrap(); + let cost = budget.used(); + assert_eq!( + output + .write_initialized_output(5, |_| panic!("unadmitted scratch")) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert!(output.as_ref().is_empty()); + assert_eq!(budget.used(), cost); + assert_eq!( + output + .write_initialized_output(4, |_| Err(io::ErrorKind::InvalidData.into())) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + assert!(output.as_ref().is_empty()); + assert!(output.write_initialized_output(4, |_| Ok(5)).is_err()); + assert!(output.as_ref().is_empty()); + assert_eq!(budget.used(), cost); + output.extend(b"kept").unwrap(); + assert!(output.write_initialized_output(0, |_| Ok(0)).is_err()); + assert_eq!(output.as_ref(), b"kept"); + drop(output); + assert_eq!(budget.used(), 0); + } + + #[cfg(feature = "inbound-http")] + #[test] + fn bridge_api_temporary_reservations_are_separate_from_output_allocations() { + let budget = Budget::default(); + let output = BudgetedBytes::new(&budget, MAX_BODY).unwrap(); + let output_cost = budget.used(); + let view = output.reserve_temporary(API_TEXT_VIEW).unwrap(); + assert_eq!(budget.used(), output_cost + API_TEXT_VIEW); + assert!(view.covers(&output, API_TEXT_VIEW)); + assert!(!view.covers(&output, API_TEXT_VIEW + 1)); + let other = BudgetedBytes::empty(&Budget::default()); + assert!(!view.covers(&other, API_TEXT_VIEW)); + drop(output); + assert_eq!(budget.used(), API_TEXT_VIEW); + drop(view); + assert_eq!(budget.used(), 0); + } + + #[cfg(all(feature = "inbound-http", target_vendor = "apple"))] + #[test] + fn merged_reservations_keep_the_same_ledger_and_one_final_refund() { + let budget = Budget::default(); + let mut retained = budget.reserve(128).unwrap(); + assert!(retained.merge(budget.reserve(256).unwrap()).is_ok()); + assert_eq!(budget.used(), 384); + let other = Budget::default(); + let rejected = retained.merge(other.reserve(64).unwrap()).err().unwrap(); + assert_eq!(budget.used(), 384); + assert_eq!(other.used(), 64); + drop(rejected); + assert_eq!(other.used(), 0); + drop(retained); + assert_eq!(budget.used(), 0); + } + #[test] fn ownership_survives_bytes_clone_and_slice() { let budget = Budget::default(); @@ -159,3 +713,7 @@ mod tests { assert_eq!(budget.used(), 0); } } + +#[cfg(all(test, unix, feature = "inbound-http"))] +#[path = "body_budget/mapped_output_tests.rs"] +mod mapped_output_tests; diff --git a/src/http_processing/body_budget/mapped_output_tests.rs b/src/http_processing/body_budget/mapped_output_tests.rs new file mode 100644 index 0000000..50b6666 --- /dev/null +++ b/src/http_processing/body_budget/mapped_output_tests.rs @@ -0,0 +1,207 @@ +//! Pure-memory ownership regressions; actual anonymous maps, no peers. +use super::*; + +fn mapped(budget: &Budget, capacity: usize) -> BudgetedBytes { + let reservation = budget + .reserve(BudgetedBytes::allocation_cost(capacity).unwrap()) + .unwrap(); + let output = BudgetedBytes::from_reserved_fixed_output(reservation, capacity).unwrap(); + assert!(output.is_mapped_for_test()); + output +} + +fn observe_after_unmap(output: &mut BudgetedBytes) -> Arc { + let observed_used = Arc::new(AtomicUsize::new(usize::MAX)); + let Backing::Mapped(backing) = &mut output.bytes else { + panic!("expected a real anonymous mapping"); + }; + backing.after_unmap = Some(MappedDropWitness { + budget: output._reservation.budget.clone(), + observed_used: observed_used.clone(), + }); + observed_used +} + +#[test] +fn mapped_output_keeps_requested_capacity_and_unmaps_before_final_refund() { + let budget = Budget::default(); + // Non-page-multiple capacity exercises logical length separately from OS + // page rounding; the latter is not charged as logical body payload. + let capacity = MAPPED_FIXED_OUTPUT_MINIMUM + 3; + let mut output = mapped(&budget, capacity); + let cost = BudgetedBytes::allocation_cost(capacity).unwrap(); + assert_eq!(budget.used(), cost); + assert_eq!(output.remaining(), capacity); + assert!(output.as_ref().is_empty()); + let observed = observe_after_unmap(&mut output); + output + .write_initialized_output(capacity, |bytes| { + assert_eq!(bytes.len(), capacity); + assert!(bytes.iter().all(|byte| *byte == 0)); + bytes[..4].copy_from_slice(b"body"); + bytes[capacity - 1] = b'z'; + Ok(4) + }) + .unwrap(); + assert_eq!(output.as_ref(), b"body"); + assert_eq!(output.remaining(), capacity - 4); + let bytes = output.into_bytes(); + let cloned = bytes.clone(); + let tail = bytes.slice(1..3); + drop(bytes); + drop(cloned); + assert_eq!(&tail[..], b"od"); + assert_eq!(budget.used(), cost); + assert_eq!(observed.load(Ordering::Acquire), usize::MAX); + drop(tail); + // The witness runs after MmapMut's real destructor and still observes the + // paid reservation; it does not claim a successful OS unmap or RSS change. + assert_eq!(observed.load(Ordering::Acquire), cost); + assert_eq!(budget.used(), 0); +} + +#[test] +fn mapped_output_error_and_invalid_retained_length_expose_no_scratch() { + let budget = Budget::default(); + let mut output = mapped(&budget, MAPPED_FIXED_OUTPUT_MINIMUM); + let cost = budget.used(); + assert_eq!( + output + .write_initialized_output(5, |bytes| { + bytes.copy_from_slice(b"stale"); + Err(io::ErrorKind::Interrupted.into()) + }) + .unwrap_err() + .kind(), + io::ErrorKind::Interrupted + ); + assert!(output.as_ref().is_empty()); + assert_eq!(output.remaining(), MAPPED_FIXED_OUTPUT_MINIMUM); + assert_eq!(budget.used(), cost); + assert!( + output + .write_initialized_output(5, |bytes| { + assert_eq!(bytes, &[0; 5]); + bytes.copy_from_slice(b"again"); + Ok(6) + }) + .is_err() + ); + assert!(output.as_ref().is_empty()); + assert_eq!(budget.used(), cost); + output.extend(b"kept").unwrap(); + assert!( + output + .write_initialized_output(0, |_| panic!("nonempty output entered fill")) + .is_err() + ); + assert_eq!(output.as_ref(), b"kept"); + assert_eq!(budget.used(), cost); + drop(output); + assert_eq!(budget.used(), 0); +} + +#[test] +fn mapped_output_map_failure_reuses_the_same_full_ledger_for_vec() { + let budget = Budget::default(); + let capacity = MAPPED_FIXED_OUTPUT_MINIMUM; + let cost = BudgetedBytes::allocation_cost(capacity).unwrap(); + let reservation = budget.reserve(cost).unwrap(); + let held = budget.reserve(WORKSPACE - cost).unwrap(); + let mut output = BudgetedBytes::from_reserved_fixed_output_with( + reservation, + capacity, + |requested| { + assert_eq!(requested, capacity); + assert_eq!(budget.used(), WORKSPACE); + Err(io::ErrorKind::OutOfMemory.into()) + }, + |requested| { + // A second reserve would fail here; fallback must use the original + // reservation while performing the real Vec allocation. + assert_eq!(budget.used(), WORKSPACE); + BudgetedBytes::allocate_vector(requested) + }, + ) + .unwrap(); + assert!(!output.is_mapped_for_test()); + assert_eq!(output.remaining(), capacity); + output + .write_initialized_output(capacity, |bytes| { + bytes.fill(b'z'); + bytes[..8].copy_from_slice(b"fallback"); + Ok(capacity) + }) + .unwrap(); + assert_eq!(&output.as_ref()[..8], b"fallback"); + assert!(output.as_ref()[8..].iter().all(|byte| *byte == b'z')); + assert_eq!(budget.used(), WORKSPACE); + let sender = output.into_bytes(); + let last_slice = sender.slice(capacity - 1..); + drop(sender); + assert_eq!(last_slice.as_ref(), b"z"); + assert_eq!(budget.used(), WORKSPACE); + drop(last_slice); + assert_eq!(budget.used(), WORKSPACE - cost); + drop(held); + assert_eq!(budget.used(), 0); +} + +#[test] +fn mapped_output_double_allocation_failure_and_bad_reservation_refund_once() { + let budget = Budget::default(); + let capacity = MAPPED_FIXED_OUTPUT_MINIMUM; + let cost = BudgetedBytes::allocation_cost(capacity).unwrap(); + let reservation = budget.reserve(cost).unwrap(); + assert!( + BudgetedBytes::from_reserved_fixed_output_with( + reservation, + capacity, + |_| { + assert_eq!(budget.used(), cost); + Err(io::ErrorKind::OutOfMemory.into()) + }, + |_| { + assert_eq!(budget.used(), cost); + None + }, + ) + .is_none() + ); + assert_eq!(budget.used(), 0); + let short = budget.reserve(cost - 1).unwrap(); + assert!( + BudgetedBytes::from_reserved_fixed_output_with( + short, + capacity, + |_| panic!("invalid reservation reached mmap"), + |_| panic!("invalid reservation reached Vec allocation"), + ) + .is_none() + ); + assert_eq!(budget.used(), 0); +} + +#[test] +fn mapped_output_never_allocates_an_unpaid_string_copy() { + let budget = Budget::default(); + let mut output = mapped(&budget, MAPPED_FIXED_OUTPUT_MINIMUM); + let cost = budget.used(); + assert_eq!( + output + .write_text(|_| panic!("direct output entered String operation")) + .unwrap_err() + .kind(), + io::ErrorKind::InvalidInput + ); + assert!(output.as_ref().is_empty()); + assert_eq!(budget.used(), cost); + drop(output); + assert_eq!(budget.used(), 0); +} + +#[forbid(unsafe_code)] +mod collector_fallback_extend_tests { + use super::*; + include!("shared_collector_fallback_extend_memory_test.rs"); +} diff --git a/src/http_processing/body_budget/shared_collector_fallback_extend_memory_test.rs b/src/http_processing/body_budget/shared_collector_fallback_extend_memory_test.rs new file mode 100644 index 0000000..631ae18 --- /dev/null +++ b/src/http_processing/body_budget/shared_collector_fallback_extend_memory_test.rs @@ -0,0 +1,50 @@ +// Same physical allocator seam, but the real collector byte-extension API. +#[test] +fn mapped_fallback_collector_extend_keeps_reservation_and_final_slice() { + let budget = Budget::default(); + let capacity = MAPPED_FIXED_OUTPUT_MINIMUM + 3; + let cost = BudgetedBytes::allocation_cost(capacity).unwrap(); + let reservation = budget.reserve(cost).unwrap(); + let held = budget.reserve(WORKSPACE - cost).unwrap(); + let mut raw = BudgetedBytes::from_reserved_fixed_output_with( + reservation, + capacity, + |requested| { + assert_eq!(requested, capacity); + assert_eq!(budget.used(), WORKSPACE); + Err(io::ErrorKind::OutOfMemory.into()) + }, + |requested| { + assert_eq!(requested, capacity); + assert_eq!(budget.used(), WORKSPACE); + BudgetedBytes::allocate_vector(requested) + }, + ) + .unwrap(); + assert!(!raw.is_mapped_for_test()); + assert!(raw.as_ref().is_empty()); + assert_eq!(raw.remaining(), capacity); + let mut expected = vec![b'a'; capacity]; + expected[capacity - 5..].copy_from_slice(b"tail\0"); + let mut length = 0; + for chunk in expected.chunks(1021) { + raw.extend(chunk).unwrap(); + length += chunk.len(); + assert_eq!(raw.as_ref(), &expected[..length]); + assert_eq!(raw.remaining(), capacity - length); + assert_eq!(budget.used(), WORKSPACE); + } + assert!(raw.extend(b"x").is_err()); + assert_eq!(raw.as_ref(), expected); + let bytes = raw.into_bytes(); + let clone = bytes.clone(); + let last = bytes.slice(capacity - 5..); + drop(bytes); + drop(clone); + assert_eq!(budget.used(), WORKSPACE); + drop(held); + assert_eq!(last.as_ref(), b"tail\0"); + assert_eq!(budget.used(), cost); + drop(last); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/completed_post_upload_error_memory_tests.rs b/src/http_processing/completed_post_upload_error_memory_tests.rs new file mode 100644 index 0000000..4c9ca60 --- /dev/null +++ b/src/http_processing/completed_post_upload_error_memory_tests.rs @@ -0,0 +1,583 @@ +//! Completed-upload admission and retirement over actual memory IO. +//! This private exchange test uses actual Hyper/H2 framing over duplex IO. +//! The input owner is an HTTP/1 body with a declared eight-byte length which +//! really ends after one byte. It is not a synthetic completion boolean. +//! The downstream has one byte of response credit, so a valid final response +//! cannot finish before the upload error has actually propagated upstream. +use super::*; +use crate::{ + dispatch::{DatagramTransport, DispatchError, Dispatcher, HttpTcpReuseKey}, + http_processing::config::Document, + security::SecurityContext, + session::{DatagramSession, Destination, InboundKind, InboundMetadata}, +}; +use async_trait::async_trait; +use futures_util::FutureExt; +use std::{ + collections::VecDeque, + panic::AssertUnwindSafe, + sync::atomic::{AtomicUsize, Ordering}, +}; +use tokio::{io::AsyncWriteExt, task::JoinHandle}; + +const WAIT: Duration = Duration::from_secs(3); +const REPLY: &[u8] = b"origin"; + +#[derive(Clone)] +struct UploadErrorWitness { + count: Arc, + observed: Arc, +} +tokio::task_local! { + static UPLOAD_ERROR_WITNESS: UploadErrorWitness; +} +pub(super) fn observe_late_upload_error() { + let _ = UPLOAD_ERROR_WITNESS.try_with(|witness| { + witness.count.fetch_add(1, Ordering::AcqRel); + witness.observed.notify_one(); + }); +} +struct Empty; +impl hyper::body::Body for Empty { + type Data = Bytes; + type Error = std::convert::Infallible; + fn poll_frame( + self: Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> Poll, Self::Error>>> { + Poll::Ready(None) + } + fn is_end_stream(&self) -> bool { + true + } + fn size_hint(&self) -> hyper::body::SizeHint { + hyper::body::SizeHint::with_exact(0) + } +} +struct UnusedDispatcher; +#[async_trait] +impl Dispatcher for UnusedDispatcher { + async fn connect_tcp(&self, _: StreamSession) -> Result { + Err(DispatchError::NotAllowed) + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +fn session() -> StreamSession { + StreamSession { + metadata: InboundMetadata::new(443), + inbound: InboundKind::Tun, + source: "198.18.0.2:30000".parse().unwrap(), + destination: Destination::Ip("203.0.113.1:443".parse().unwrap()), + sniffed_domain: Some("a.test".into()), + } +} +fn error(_: E) -> io::Error { + failed() +} + +fn origin_pair( + stop: CancellationToken, + incomplete: Arc, + received: Arc, + phase: Arc, +) -> (BoxStream, JoinHandle>) { + let (client, peer) = tokio::io::duplex(8192); + let task = tokio::spawn(async move { + let operation = async { + phase.store(1, Ordering::Release); + let mut connection = h2::server::handshake::<_>(peer).await.map_err(error)?; + phase.store(2, Ordering::Release); + let mut exchange: Option> + Send>>> = None; + loop { + tokio::select! {biased; + result=async { exchange.as_mut().expect("guarded exchange").await },if exchange.is_some()=>{ + result?; + exchange = None; + }, + accepted=connection.accept()=>match accepted { + Some(Ok((request, mut response)))=>{ + phase.store(3, Ordering::Release); + if exchange.is_some() { return Err(failed()); } + let incomplete = incomplete.clone(); + let received = received.clone(); + let phase = phase.clone(); + exchange = Some(Box::pin(async move { + let mut input = request.into_body(); + let prefix = input.data().await.ok_or_else(failed)?.map_err(error)?; + if prefix.as_ref() != b"x" { return Err(failed()); } + received.fetch_add(prefix.len(), Ordering::AcqRel); + phase.store(4, Ordering::Release); + input.flow_control().release_capacity(prefix.len()).map_err(error)?; + let mut body = response.send_response(Response::builder().header("content-length", REPLY.len()).body(()).map_err(error)?, false).map_err(error)?; + body.send_data(Bytes::from_static(REPLY), true).map_err(error)?; + phase.store(5, Ordering::Release); + // A completed download cannot drop this upload: + // the downstream deliberately withholds credit. + // Only real truncated-source propagation ends it. + match input.data().await { + Some(Ok(_)) => return Err(failed()), + Some(Err(_)) | None => incomplete.notify_one(), + } + phase.store(6, Ordering::Release); + Ok::<_, io::Error>(()) + }) as Pin> + Send>>); + }, + Some(Err(_)) | None => return Ok(()), + } + } + } + }; + tokio::select! {biased; ()=stop.cancelled()=>Ok(()), result=operation=>result} + }); + (Box::new(client), task) +} + +#[tokio::test] +async fn completed_post_h2_upload_error_after_final_headers_preserves_reply_and_retires() { + let stop = CancellationToken::new(); + let close_source = CancellationToken::new(); + let incomplete = Arc::new(tokio::sync::Notify::new()); + let received = Arc::new(AtomicUsize::new(0)); + let opens = AtomicUsize::new(0); + let witness = UploadErrorWitness { + count: Arc::new(AtomicUsize::new(0)), + observed: Arc::new(tokio::sync::Notify::new()), + }; + let phase = AtomicUsize::new(0); + let source_driver_phase = Arc::new(AtomicUsize::new(0)); + let origin_phases: [Arc; 2] = + std::array::from_fn(|_| Arc::new(AtomicUsize::new(0))); + let mut tasks: Vec>> = Vec::new(); + let result = AssertUnwindSafe(async { + timeout(WAIT * 3, async { + phase.store(1, Ordering::Release); + let (source_client, mut source_peer) = tokio::io::duplex(8192); + let source_stop = stop.clone(); + let source_close = close_source.clone(); + tasks.push(tokio::spawn(async move { + tokio::select! {biased; + ()=source_stop.cancelled()=>Ok(()), + result=async { + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") && head.len() < 32768 { + head.push(tokio::io::AsyncReadExt::read_u8(&mut source_peer).await?); + } + source_peer.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nx").await?; + source_peer.flush().await?; + source_close.cancelled().await; + // Drop with a genuine Content-Length deficit. + Ok::<_, io::Error>(()) + }=>result, + } + })); + let (mut source_sender, source_driver) = hyper::client::conn::http1::handshake::<_, Empty>(hyper_util::rt::TokioIo::new(source_client)).await.map_err(error)?; + let source_stop = stop.clone(); + let driver_phase = source_driver_phase.clone(); + tasks.push(tokio::spawn(async move { + // Its framing failure is the explicit fault under test. + driver_phase.store(1, Ordering::Release); + tokio::select! {biased; + ()=source_stop.cancelled()=>{driver_phase.store(4, Ordering::Release);}, + result=source_driver=>{driver_phase.store(if result.is_err() {3} else {2}, Ordering::Release);} + } + Ok(()) + })); + phase.store(10, Ordering::Release); + let source_response = source_sender.send_request(Request::builder().uri("/source").body(Empty).map_err(error)?).await.map_err(error)?; + phase.store(11, Ordering::Release); + drop(source_sender); + let source = h2_body::Source::h1(source_response.into_body()); + + let mut origins = VecDeque::new(); + for origin_phase in &origin_phases { + let (io, owner) = origin_pair(stop.clone(), incomplete.clone(), received.clone(), origin_phase.clone()); + origins.push_back(io); + tasks.push(owner); + } + let (sessions, mut parent) = h2_reuse::new(); + let parent_stop = stop.clone(); + tasks.push(tokio::spawn(async move { + loop { tokio::select! {biased; ()=parent_stop.cancelled()=>return Ok(()), ()=parent.progress()=>{}} } + })); + let url = url::Url::parse("https://a.test/upload").map_err(error)?; + let identity = || h2_reuse::Identity::new(HttpTcpReuseKey::new(1_u8), &url); + let first_io = origins.pop_front().ok_or_else(failed)?; + let open_count = &opens; + phase.store(20, Ordering::Release); + let (lease, sender) = match sessions.acquire(identity(), Instant::now()+SETUP, move || async move { + open_count.fetch_add(1, Ordering::AcqRel); + Ok((first_io, Some(b"h2".to_vec()))) + }).await? { + h2_reuse::Acquired::Shared { lease, sender }=>(lease, sender), + _=>return Err(failed()), + }; + phase.store(21, Ordering::Release); + + let (down_client, down_server) = tokio::io::duplex(8192); + let mut builder = h2::client::Builder::new(); + builder.initial_window_size(1); + let (mut down_sender, down_driver) = builder.handshake::<_, Bytes>(down_client).await.map_err(error)?; + let down_stop = stop.clone(); + tasks.push(tokio::spawn(async move { + tokio::select! {biased; ()=down_stop.cancelled()=>Ok(()), result=down_driver=>result.map_err(error)} + })); + phase.store(30, Ordering::Release); + let mut down_connection = h2::server::handshake::<_>(down_server).await.map_err(error)?; + phase.store(31, Ordering::Release); + let (down_response, _) = down_sender.send_request(Request::builder().uri("https://a.test/upload").body(()).map_err(error)?, true).map_err(error)?; + phase.store(32, Ordering::Release); + let (_, response) = down_connection.accept().await.ok_or_else(failed)?.map_err(error)?; + phase.store(33, Ordering::Release); + let down_stop = stop.clone(); + tasks.push(tokio::spawn(async move { + loop { tokio::select! {biased; + ()=down_stop.cancelled()=>return Ok(()), + accepted=down_connection.accept()=>match accepted { + Some(Ok(_))=>return Err(failed()), + Some(Err(_))|None=>return Ok(()), + } + }} + })); + let response = ResponseSlot(Arc::new(Mutex::new(ResponseState { response, infos:0, final_started:false, upstream_final_received:false }))); + let policy = Document::parse("{}").map_err(error)?.compile(&std::collections::BTreeMap::new()).map_err(error)?.bind_ca(None).map_err(error)?; + let context = HttpContext::new(policy, Arc::new(UnusedDispatcher), SecurityContext::default()); + let target = Target { original:url.clone(), url:url.clone(), session:session(), logical_destination:Destination::domain("a.test",443).map_err(error)?, strip_origin_credentials:false }; + let metadata = MessageMeta { original:OriginalRequestMeta::new("POST", &vec![]), length:Some(8), asterisk:false, script:None }; + let request = Request::builder().method("POST").uri(url.as_str()).header("content-length",8).body(source).map_err(error)?; + let exchange = UPLOAD_ERROR_WITNESS.scope(witness.clone(), context.h2_exchange(UpstreamSender::Shared { lease: &lease, sender }, request, &response, target, metadata)); + phase.store(40, Ordering::Release); + let observe = async { + phase.store(41, Ordering::Release); + let response = down_response.await.map_err(error)?; + phase.store(42, Ordering::Release); + if response.status()!=StatusCode::OK { return Err(failed()); } + // This is the actual downstream receipt of final headers. + close_source.cancel(); + phase.store(43, Ordering::Release); + // Observe the actual upload-error-after-final-head branch. + // Dropping SendStream alone need not reset the request while + // its response owner remains alive; that is not a valid gate. + witness.observed.notified().await; + phase.store(44, Ordering::Release); + let mut body = response.into_body(); + let mut bytes = Vec::new(); + while let Some(frame) = body.data().await { + let frame = frame.map_err(error)?; + bytes.extend_from_slice(&frame); + body.flow_control().release_capacity(frame.len()).map_err(error)?; + } + if bytes != REPLY { return Err(failed()); } + phase.store(45, Ordering::Release); + Ok::<_, io::Error>(()) + }; + let (exchange, observed) = tokio::join!(exchange, observe); + phase.store(50, Ordering::Release); + exchange?; + observed?; + if witness.count.load(Ordering::Acquire)!=1 { return Err(io::Error::other("late upload error branch was not observed exactly once")); } + if received.load(Ordering::Acquire)!=1 { return Err(failed()); } + drop(lease); + let second_io = origins.pop_front().ok_or_else(failed)?; + let open_count = &opens; + phase.store(60, Ordering::Release); + let next = sessions.acquire(identity(), Instant::now()+SETUP, move || async move { + open_count.fetch_add(1, Ordering::AcqRel); + Ok((second_io, Some(b"h2".to_vec()))) + }).await?; + drop(next); + phase.store(61, Ordering::Release); + drop((down_sender, sessions)); + if opens.load(Ordering::Acquire)!=2 { + return Err(io::Error::other("upload failure after final headers retained admission")); + } + Ok::<_, io::Error>(()) + }).await.map_err(|_| io::Error::other(format!( + "controlled POST exchange deadline: phase={}, sourceDriver={}, originPhases={:?}, received={}, opens={}, lateUploadErrors={}", + phase.load(Ordering::Acquire), source_driver_phase.load(Ordering::Acquire), + origin_phases.each_ref().map(|value| value.load(Ordering::Acquire)), + received.load(Ordering::Acquire), opens.load(Ordering::Acquire), witness.count.load(Ordering::Acquire) + )))? + }).catch_unwind().await; + stop.cancel(); + close_source.cancel(); + let mut join_errors = Vec::new(); + for mut task in tasks { + match timeout(WAIT, &mut task).await { + Ok(Ok(Ok(()))) => {} + Ok(other) => join_errors.push(format!("owned duplex task: {other:?}")), + Err(_) => { + task.abort(); + let _ = task.await; + join_errors.push("owned duplex task required abort".into()); + } + } + } + assert!(join_errors.is_empty(), "{join_errors:?}"); + let result = match result { + Ok(result) => result, + Err(panic) => std::panic::resume_unwind(panic), + }; + assert!(result.is_ok(), "{result:?}"); +} + +// Track the physical IO owners while a sibling keeps a retired session alive. +struct DropOwnedIo { + io: tokio::io::DuplexStream, + live: Arc, +} +impl DropOwnedIo { + fn new(io: tokio::io::DuplexStream, live: &Arc) -> Self { + live.fetch_add(1, Ordering::AcqRel); + Self { + io, + live: live.clone(), + } + } +} +impl Drop for DropOwnedIo { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::AcqRel); + } +} +impl tokio::io::AsyncRead for DropOwnedIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + bytes: &mut tokio::io::ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, bytes) + } +} +impl tokio::io::AsyncWrite for DropOwnedIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, bytes) + } + fn poll_flush( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown( + mut self: Pin<&mut Self>, + cx: &mut std::task::Context<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} +fn drop_origin_pair( + stop: CancellationToken, + dropped_request_started: CancellationToken, + sibling_started: CancellationToken, + release_sibling: CancellationToken, + live: &Arc, +) -> (BoxStream, JoinHandle>) { + let (client, peer) = tokio::io::duplex(8192); + let client = DropOwnedIo::new(client, live); + let peer = DropOwnedIo::new(peer, live); + let owner = tokio::spawn(async move { + let operation = async { + let mut connection = h2::server::handshake::<_>(peer).await.map_err(error)?; + let mut exchanges = FuturesUnordered::new(); + loop { + tokio::select! {biased; + result=exchanges.next(),if !exchanges.is_empty()=>{ if let Some(result) = result { result?; } }, + accepted=connection.accept()=>match accepted { + Some(Ok((request, mut response)))=>{ + let dropped_request_started = dropped_request_started.clone(); + let sibling_started = sibling_started.clone(); + let release_sibling = release_sibling.clone(); + exchanges.push(async move { + if request.uri().path()=="/drop" { + let mut input = request.into_body(); + let prefix = input.data().await.ok_or_else(failed)?.map_err(error)?; + if prefix.as_ref()!=b"x" { return Err(failed()); } + input.flow_control().release_capacity(prefix.len()).map_err(error)?; + dropped_request_started.cancel(); + // No response and no upload EOS: the actual + // request future remains in flight until Drop. + if let Some(Ok(_)) = input.data().await { return Err(failed()); } + return Ok::<_,io::Error>(()); + } + if request.uri().path()!="/sibling" || !request.body().is_end_stream() { return Err(failed()); } + sibling_started.cancel(); + release_sibling.cancelled().await; + let mut body = response.send_response(Response::builder().header("content-length",REPLY.len()).body(()).map_err(error)?, false).map_err(error)?; + body.send_data(Bytes::from_static(REPLY),true).map_err(error)?; + Ok(()) + }); + }, + Some(Err(_))|None=>return Ok::<_,io::Error>(()), + } + } + } + }; + tokio::select! {biased; ()=stop.cancelled()=>Ok(()), result=operation=>result} + }); + (Box::new(client), owner) +} +fn drop_target(path: &str) -> io::Result { + let url = url::Url::parse(&format!("https://a.test/{path}")).map_err(error)?; + Ok(Target { + original: url.clone(), + url, + session: session(), + logical_destination: Destination::domain("a.test", 443).map_err(error)?, + strip_origin_credentials: false, + }) +} +fn drop_metadata(method: &str, length: Option) -> MessageMeta { + MessageMeta { + original: OriginalRequestMeta::new(method, &vec![]), + length, + asterisk: false, + script: None, + } +} + +#[tokio::test] +async fn completed_post_h2_dropped_exchange_retires_admission_without_cancelling_sibling() { + let stop = CancellationToken::new(); + let drop_started = CancellationToken::new(); + let sibling_started = CancellationToken::new(); + let release_sibling = CancellationToken::new(); + let live = Arc::new(AtomicUsize::new(0)); + let opens = AtomicUsize::new(0); + let phase = AtomicUsize::new(0); + let mut tasks: Vec>> = Vec::new(); + let result = AssertUnwindSafe(async { + timeout(WAIT*3, async { + let mut origins = VecDeque::new(); + for _ in 0..2 { + let (io, owner) = drop_origin_pair(stop.clone(),drop_started.clone(),sibling_started.clone(),release_sibling.clone(),&live); + origins.push_back(io); + tasks.push(owner); + } + let (sessions,mut parent) = h2_reuse::new(); + let parent_stop = stop.clone(); + tasks.push(tokio::spawn(async move { + loop { tokio::select! {biased; ()=parent_stop.cancelled()=>return Ok(()), ()=parent.progress()=>{}} } + })); + let url = url::Url::parse("https://a.test/").map_err(error)?; + let identity = || h2_reuse::Identity::new(HttpTcpReuseKey::new(2_u8),&url); + phase.store(10,Ordering::Release); + let first = sessions.acquire(identity(),Instant::now()+SETUP,|| { + opens.fetch_add(1,Ordering::AcqRel); + let io = origins.pop_front(); + async move { Ok((io.ok_or_else(failed)?,Some(b"h2".to_vec()))) } + }).await?; + let h2_reuse::Acquired::Shared { lease: first_lease, sender: first_sender } = first else {return Err(failed());}; + let sibling = sessions.acquire(identity(),Instant::now()+SETUP,|| { + opens.fetch_add(1,Ordering::AcqRel); + let io = origins.pop_front(); + async move { Ok((io.ok_or_else(failed)?,Some(b"h2".to_vec()))) } + }).await?; + let h2_reuse::Acquired::Shared { lease: sibling_lease, sender: sibling_sender } = sibling else {return Err(failed());}; + if opens.load(Ordering::Acquire)!=1 {return Err(io::Error::other("sibling did not acquire the same initial physical owner"));} + + let (client,server) = tokio::io::duplex(8192); + let (mut sender,driver) = h2::client::handshake::<_>(client).await.map_err(error)?; + let client_stop = stop.clone(); + tasks.push(tokio::spawn(async move { + tokio::select! {biased; ()=client_stop.cancelled()=>Ok(()), result=driver=>result.map_err(error)} + })); + let mut connection = h2::server::handshake::<_>(server).await.map_err(error)?; + let (first_response,mut first_input) = sender.send_request(Request::builder().method("POST").uri("https://a.test/drop").header("content-length",8).body(()).map_err(error)?,false).map_err(error)?; + first_input.send_data(Bytes::from_static(b"x"),false).map_err(error)?; + let (first_request,first_response_owner) = connection.accept().await.ok_or_else(failed)?.map_err(error)?; + let (sibling_response,_) = sender.send_request(Request::builder().uri("https://a.test/sibling").body(()).map_err(error)?,true).map_err(error)?; + let (sibling_request,sibling_response_owner) = connection.accept().await.ok_or_else(failed)?.map_err(error)?; + let server_stop = stop.clone(); + tasks.push(tokio::spawn(async move { + loop {tokio::select! {biased; + ()=server_stop.cancelled()=>return Ok(()), + accepted=connection.accept()=>match accepted {Some(Ok(_))=>return Err(failed()),Some(Err(_))|None=>return Ok(())} + }} + })); + let first_slot = ResponseSlot(Arc::new(Mutex::new(ResponseState {response:first_response_owner,infos:0,final_started:false,upstream_final_received:false}))); + let sibling_slot = ResponseSlot(Arc::new(Mutex::new(ResponseState {response:sibling_response_owner,infos:0,final_started:false,upstream_final_received:false}))); + let policy = Document::parse("{}").map_err(error)?.compile(&std::collections::BTreeMap::new()).map_err(error)?.bind_ca(None).map_err(error)?; + let context = HttpContext::new(policy,Arc::new(UnusedDispatcher),SecurityContext::default()); + let first_request = Request::builder().method("POST").uri("https://a.test/drop").header("content-length",8).body(h2_body::Source::h2(first_request.into_body())).map_err(error)?; + let sibling_request = Request::builder().uri("https://a.test/sibling").body(h2_body::Source::h2(sibling_request.into_body())).map_err(error)?; + let mut first_exchange = Box::pin(context.h2_exchange( + UpstreamSender::Shared { lease: &first_lease, sender: first_sender }, + first_request, &first_slot, drop_target("drop")?, drop_metadata("POST",Some(8)) + )); + let mut sibling_exchange = Box::pin(context.h2_exchange( + UpstreamSender::Shared { lease: &sibling_lease, sender: sibling_sender }, + sibling_request, &sibling_slot, drop_target("sibling")?, drop_metadata("GET",None) + )); + phase.store(20,Ordering::Release); + tokio::select! {biased; + _=&mut first_exchange=>return Err(io::Error::other("first exchange completed before Drop")), + _=&mut sibling_exchange=>return Err(io::Error::other("sibling completed before admission check")), + ()=async {drop_started.cancelled().await;sibling_started.cancelled().await;}=>{}, + } + // Drop just this in-flight future. Sessions, Parent, the sibling + // lease, downstream connection and normal runtime remain alive. + drop(first_exchange); + drop(first_lease); + drop((first_response,first_input,first_slot)); + phase.store(30,Ordering::Release); + let next = sessions.acquire(identity(),Instant::now()+SETUP,|| { + opens.fetch_add(1,Ordering::AcqRel); + let io = origins.pop_front(); + async move { Ok((io.ok_or_else(failed)?,Some(b"h2".to_vec()))) } + }).await?; + let changed = opens.load(Ordering::Acquire)==2; + drop(next); + phase.store(40,Ordering::Release); + release_sibling.cancel(); + let observe = async { + let response = sibling_response.await.map_err(error)?; + let mut body = response.into_body(); + let mut bytes = Vec::new(); + while let Some(frame) = body.data().await { + let frame = frame.map_err(error)?; + bytes.extend_from_slice(&frame); + body.flow_control().release_capacity(frame.len()).map_err(error)?; + } + if bytes!=REPLY {return Err(failed());} + Ok::<_,io::Error>(()) + }; + let (completed,observed) = tokio::join!(sibling_exchange,observe); + completed?; + observed?; + drop((sibling_lease,sender,sessions)); + phase.store(50,Ordering::Release); + if !changed {return Err(io::Error::other("dropped exchange retained future admission while sibling was in flight"));} + Ok::<_,io::Error>(()) + }).await.map_err(|_|io::Error::other(format!("Drop-only exchange deadline: phase={},opens={},live={}",phase.load(Ordering::Acquire),opens.load(Ordering::Acquire),live.load(Ordering::Acquire))))? + }).catch_unwind().await; + stop.cancel(); + release_sibling.cancel(); + let mut failures = Vec::new(); + for mut task in tasks { + match timeout(WAIT, &mut task).await { + Ok(Ok(Ok(()))) => {} + Ok(other) => failures.push(format!("owned Drop-only task: {other:?}")), + Err(_) => { + task.abort(); + let _ = task.await; + failures.push("Drop-only task required abort".into()); + } + } + } + assert!(failures.is_empty(), "{failures:?}"); + assert_eq!(live.load(Ordering::Acquire), 0); + let result = match result { + Ok(result) => result, + Err(panic) => std::panic::resume_unwind(panic), + }; + assert!(result.is_ok(), "{result:?}"); +} diff --git a/src/http_processing/config.rs b/src/http_processing/config.rs index 492c5c0..db467fd 100644 --- a/src/http_processing/config.rs +++ b/src/http_processing/config.rs @@ -7,6 +7,7 @@ use super::{ private_context::CaMaterial, providers::Payload, rules::{self, Rule, UrlAction}, + script_config::CompiledScript, }; #[cfg(any(test, all(windows, feature = "windows-uwp")))] use serde::Deserialize; @@ -43,6 +44,7 @@ pub(super) fn require_http_adapter() -> io::Result<()> { pub(crate) struct PolicyCandidate { pub(crate) document: Arc, pub(super) rules: Arc<[Rule]>, + pub(crate) scripts: Arc<[CompiledScript]>, pub(super) payloads: BTreeMap>, pub(super) identity: [u8; 32], pub(super) origins: Box<[SourceLocation]>, @@ -84,6 +86,7 @@ impl PolicyCandidate { material: Option<&CaMaterial>, ) -> io::Result> { require_http_adapter()?; + self.document.http_scripts.ensure_available()?; #[cfg(feature = "inbound-http")] let mitm = super::mitm::Mitm::compile(self.document.mitm.clone(), material)?; #[cfg(not(feature = "inbound-http"))] @@ -98,6 +101,7 @@ impl PolicyCandidate { identity: hash.finalize().into(), document: self.document.clone(), candidate: Some(self.clone()), + scripts_backend_ready: true, #[cfg(feature = "inbound-http")] mitm, })) @@ -188,6 +192,7 @@ pub(crate) struct Policy { identity: [u8; 32], document: Arc, candidate: Option>, + scripts_backend_ready: bool, #[cfg(feature = "inbound-http")] mitm: Option>, } @@ -196,6 +201,7 @@ impl fmt::Debug for Policy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HttpPolicy") .field("rules", &self.all_rules().len()) + .field("scripts", &self.all_scripts().len()) .field("prepared", &self.is_prepared()) .finish_non_exhaustive() } @@ -247,6 +253,7 @@ impl Policy { .map_or_else(|| document.identity(), |candidate| candidate.identity()); Self { identity, + scripts_backend_ready: !document.http_scripts.is_active(), document, candidate, #[cfg(feature = "inbound-http")] @@ -262,6 +269,7 @@ impl Policy { } pub(crate) fn is_prepared(&self) -> bool { self.candidate.is_some() + && self.scripts_backend_ready && (!self.document.mitm.enabled || { #[cfg(feature = "inbound-http")] { @@ -274,7 +282,8 @@ impl Policy { }) } pub(crate) fn plain_port(&self, port: u16) -> bool { - !self.rules().is_empty() && self.document.http_ports.contains(&port) + (!self.rules().is_empty() || !self.scripts().is_empty()) + && self.document.http_ports.contains(&port) } pub(crate) fn rules(&self) -> &[Rule] { if self.document.rewrite.enabled { @@ -288,6 +297,18 @@ impl Policy { .as_ref() .map_or(&[], |candidate| &candidate.rules) } + pub(crate) fn scripts(&self) -> &[CompiledScript] { + if self.document.http_scripts.enabled { + self.all_scripts() + } else { + &[] + } + } + pub(crate) fn all_scripts(&self) -> &[CompiledScript] { + self.candidate + .as_ref() + .map_or(&[], |candidate| &candidate.scripts) + } #[cfg(feature = "inbound-http")] pub(crate) fn body_budget(&self) -> &super::body_budget::Budget { static BUDGET: std::sync::LazyLock = diff --git a/src/http_processing/diagnostics.rs b/src/http_processing/diagnostics.rs new file mode 100644 index 0000000..0b9777f --- /dev/null +++ b/src/http_processing/diagnostics.rs @@ -0,0 +1,912 @@ +//! Fixed-size, process-lifetime HTTP diagnostics; no traffic data or reset API. +//! +//! Only `http-diagnostics` builds retain counters. Concurrent snapshots are +//! independently sampled atomics, not a transaction; use a quiescent snapshot +//! after the real stop barrier for lifecycle conservation checks. + +#[derive(Clone, Copy)] +#[cfg_attr( + not(all(feature = "http-diagnostics", target_vendor = "apple")), + allow(dead_code) +)] +pub(crate) enum Counter { + ScriptMatched, + SkipAsteriskBody, + SkipBodyUnavailable, + SkipTextUnavailable, + SkipInputUnrepresentable, + SkipCallBuffers, + CallBuffersRequested, + CallBuffersAdmitted, + CallBuffersBudgetRejected, + CallBuffersAllocationRejected, + QueueRequested, + QueueAcquired, + QueueTimeout, + QueueCancelled, + QueueFailed, + EvaluationEntered, + EvaluationSucceeded, + EvaluationTimedOut, + EvaluationCancelled, + EvaluationFailed, + BackendFatal, + OutputAccepted, + OutputRejected, + OutputTerminal, + BodyReserveSucceeded, + BodyReserveRejected, + CollectorNativeRequested, + CollectorSharedRequested, + CollectorAdmitted, + CollectorFinished, + NativeTransformRequested, + NativeTransformFinished, + ContextCreated, + ContextReleased, + BridgeInputRejected, + BridgeExportRejected, + BridgeGuardInvalid, + AsciiViewRequested, + AsciiViewAdmitted, + AsciiViewBudgetFallback, + LiteralReplaceRequested, + LiteralReplaceAdmitted, + LiteralReplaceBudgetFallback, + LiteralReplaceSemanticFallback, + LiteralReplaceApiFallback, + PlatformWarmupRequested, + PlatformWarmupStarted, + PlatformWarmupSucceeded, + PlatformWarmupFailed, + PlatformWarmupContextCreated, + PlatformWarmupContextReleased, + JscSelected, + PlanSelected, + PlanInputFallback, + PlanAstFallback, + PlanBuffersRejected, + PlanEntered, + PlanSucceeded, + PlanTimedOut, + PlanCancelled, + PlanFailed, + JscOwnerStarted, + JscOwnerJoined, + PlanOwnerStarted, + PlanOwnerJoined, + PlanFinalRecipeEntered, + PlanFinalDagEntered, + PlanInlineEntered, + PlanInlineReturned, + PlanInlinePanicked, + PlanInlineCpuUnavailable, + PlanHeaderGuardEntered, + PlanHeaderGuardTail, + PlanHeaderGuardPass, + PlanHeaderGuardAbort, + PlanFinalSingleStepEntered, + PlanOutputPendingAdmitted, + PlanOutputQueueFailed, + PlanOutputPayloadBudgetRejected, + // Platform TUN write observations share the existing diagnostic no-op. + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteSingleSendAttempts, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteSingleEnobufsErrors, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteSingleSleep1msRequests, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteSingleAcceptedPackets, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteSingleWouldBlock, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteBatchSendAttempts, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteBatchEnobufsErrors, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteBatchSleep1msRequests, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteBatchAcceptedPackets, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunWriteBatchWouldBlock, + // Read outcomes and netstack handoff are different packet boundaries. + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunIngressReadOkPackets, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunIngressReadInvalidPacketOutcomes, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunIngressMtuExceededDrops, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunIngressNetstackAcceptedPackets, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunIngressNetstackBackpressureDrops, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunIngressIpv4DeclaredLengthExceedsReadSlice, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunIngressIpv6DeclaredLengthExceedsReadSlice, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverDrivePasses, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverTcpEntryVisits, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverAppRxBytes, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverAppTxBytes, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverNoDataProgressPasses, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverWaitIngress, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverWaitNotify, + #[cfg_attr(not(feature = "tun"), allow(dead_code))] + TunNetstackDriverWaitTimer, +} + +#[derive(Clone, Copy)] +#[cfg_attr( + not(all(feature = "http-diagnostics", target_vendor = "apple")), + allow(dead_code) +)] +pub(crate) enum Timing { + Queue, + Evaluation, + ContextRelease, + FinalParse, + ScopedOwner, + JscScopedOwner, + PlanScopedOwner, + PlanInlineDispatchWall, + PlanInlineWall, + PlanInlineThreadCpu, +} + +#[derive(Clone, Copy)] +pub(crate) enum BodyPoint { + NativeAdmission, + SharedAdmission, + Collection, + NativeDecode, + SharedDecode, + NativeTransform, + HeaderFinalize, +} + +#[inline] +pub(crate) fn increment(counter: Counter) { + #[cfg(feature = "http-diagnostics")] + enabled::STATS.increment(counter); + #[cfg(not(feature = "http-diagnostics"))] + let _ = counter; +} + +#[cfg(feature = "http-diagnostics")] +#[cfg_attr(not(feature = "tun"), allow(dead_code))] +#[inline] +pub(crate) fn add_counter(counter: Counter, value: u64) { + enabled::STATS.add_counter(counter, value); +} + +// Observation only: a complete base header's declared length exceeds the +// actual read slice. This is not an IP validator or proof of transport loss. +#[inline] +#[cfg_attr(not(feature = "tun"), allow(dead_code))] +pub(crate) fn record_tun_ingress_header(packet: &[u8]) { + #[cfg(feature = "http-diagnostics")] + if let Some(counter) = tun_ingress_header_length_counter(packet) { + increment(counter); + } + #[cfg(not(feature = "http-diagnostics"))] + let _ = packet; +} + +#[cfg(feature = "http-diagnostics")] +#[cfg_attr(not(feature = "tun"), allow(dead_code))] +fn tun_ingress_header_length_counter(packet: &[u8]) -> Option { + match packet.first().map(|byte| byte >> 4) { + Some(4) if packet.len() >= 20 => { + let declared = usize::from(u16::from_be_bytes([packet[2], packet[3]])); + (declared > packet.len()) + .then_some(Counter::TunIngressIpv4DeclaredLengthExceedsReadSlice) + } + Some(6) if packet.len() >= 40 => { + let declared = 40 + usize::from(u16::from_be_bytes([packet[4], packet[5]])); + (declared > packet.len()) + .then_some(Counter::TunIngressIpv6DeclaredLengthExceedsReadSlice) + } + _ => None, + } +} + +#[inline] +pub(crate) fn body_reserved(bytes: usize, single_budget_used: usize) { + #[cfg(feature = "http-diagnostics")] + enabled::STATS.body_reserved(bytes, single_budget_used); + #[cfg(not(feature = "http-diagnostics"))] + let _ = (bytes, single_budget_used); +} + +#[inline] +pub(crate) fn body_released(bytes: usize) { + #[cfg(feature = "http-diagnostics")] + enabled::STATS + .body_current + .fetch_sub(bytes as u64, std::sync::atomic::Ordering::Relaxed); + #[cfg(not(feature = "http-diagnostics"))] + let _ = bytes; +} + +#[inline] +pub(crate) fn call_buffers_requested(input: usize, output: usize, bridge: usize) { + #[cfg(feature = "http-diagnostics")] + enabled::STATS.call_buffers_requested(input, output, bridge); + #[cfg(not(feature = "http-diagnostics"))] + let _ = (input, output, bridge); +} + +#[inline] +pub(crate) fn body_bypass(point: BodyPoint, reason: super::body::Bypass) { + #[cfg(feature = "http-diagnostics")] + enabled::STATS.body_bypass(point, reason); + #[cfg(not(feature = "http-diagnostics"))] + let _ = (point, reason); +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +#[inline] +pub(crate) fn context_created() { + #[cfg(feature = "http-diagnostics")] + { + use std::sync::atomic::Ordering; + increment(Counter::ContextCreated); + let current = enabled::STATS + .context_current + .fetch_add(1, Ordering::Relaxed) + + 1; + enabled::STATS + .context_peak + .fetch_max(current, Ordering::Relaxed); + } +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +#[inline] +pub(crate) fn context_released() { + #[cfg(feature = "http-diagnostics")] + { + increment(Counter::ContextReleased); + enabled::STATS + .context_current + .fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + } +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +pub(crate) struct QueueGuard { + #[cfg(feature = "http-diagnostics")] + started: std::time::Instant, + #[cfg(feature = "http-diagnostics")] + finished: bool, +} +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +impl QueueGuard { + #[inline] + pub(crate) fn new() -> Self { + #[cfg(feature = "http-diagnostics")] + { + use std::sync::atomic::Ordering; + increment(Counter::QueueRequested); + let current = enabled::STATS.queue_current.fetch_add(1, Ordering::Relaxed) + 1; + enabled::STATS + .queue_peak + .fetch_max(current, Ordering::Relaxed); + } + Self { + #[cfg(feature = "http-diagnostics")] + started: std::time::Instant::now(), + #[cfg(feature = "http-diagnostics")] + finished: false, + } + } + #[inline] + pub(crate) fn acquired(&mut self) { + #[cfg(feature = "http-diagnostics")] + { + self.finish(); + increment(Counter::QueueAcquired); + } + } + #[inline] + pub(crate) fn failed(&mut self, kind: std::io::ErrorKind) { + #[cfg(feature = "http-diagnostics")] + { + let counter = match kind { + std::io::ErrorKind::TimedOut => Counter::QueueTimeout, + std::io::ErrorKind::Interrupted => Counter::QueueCancelled, + _ => Counter::QueueFailed, + }; + self.finish(); + increment(counter); + } + #[cfg(not(feature = "http-diagnostics"))] + let _ = kind; + } + #[cfg(feature = "http-diagnostics")] + fn finish(&mut self) { + self.finished = true; + enabled::STATS + .queue_current + .fetch_sub(1, std::sync::atomic::Ordering::Relaxed); + enabled::STATS.timings[Timing::Queue as usize].record(self.started.elapsed().as_micros()); + } +} +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +impl Drop for QueueGuard { + fn drop(&mut self) { + #[cfg(feature = "http-diagnostics")] + if !self.finished { + self.failed(std::io::ErrorKind::Interrupted); + } + } +} + +#[cfg(all(feature = "http-diagnostics", target_vendor = "apple"))] +#[inline] +pub(crate) fn timing(kind: Timing, micros: u128) { + #[cfg(feature = "http-diagnostics")] + enabled::STATS.timings[kind as usize].record(micros); + #[cfg(not(feature = "http-diagnostics"))] + let _ = (kind, micros); +} + +#[cfg(all(feature = "http-diagnostics", target_vendor = "apple"))] +#[inline] +pub(crate) fn evaluation_finished( + stages: [u128; 6], + seen: u8, + overall: u128, + ticks: usize, + succeeded: bool, +) { + enabled::STATS.evaluation_finished(stages, seen, overall, ticks, succeeded); +} + +/// Diagnostic-build-only, process-lifetime counters. No URL, script identity, +/// configuration, headers, body, certificate or private key is retained. +#[cfg(feature = "http-diagnostics")] +pub fn snapshot() -> serde_json::Value { + let value = enabled::STATS.snapshot(); + #[cfg(all(feature = "inbound-http", target_vendor = "apple"))] + { + let mut value = value; + value["scopedScriptOwner"] = super::scripts::scoped_owner_qos_snapshot(); + value + } + #[cfg(not(all(feature = "inbound-http", target_vendor = "apple")))] + { + value + } +} + +#[cfg(feature = "http-diagnostics")] +mod enabled { + use super::{BodyPoint, Counter}; + use crate::http_processing::body::Bypass; + use serde_json::{Map, Value, json}; + use std::sync::atomic::{AtomicU64, Ordering}; + + const COUNTERS: [&str; 104] = [ + "scriptMatched", + "skipAsteriskBody", + "skipBodyUnavailable", + "skipTextUnavailable", + "skipInputUnrepresentable", + "skipCallBuffers", + "callBuffersRequested", + "callBuffersAdmitted", + "callBuffersBudgetRejected", + "callBuffersAllocationRejected", + "queueRequested", + "queueAcquired", + "queueTimeout", + "queueCancelled", + "queueFailed", + "evaluationEntered", + "evaluationSucceeded", + "evaluationTimedOut", + "evaluationCancelled", + "evaluationFailed", + "backendFatal", + "outputAccepted", + "outputRejected", + "outputTerminal", + "bodyReserveSucceeded", + "bodyReserveRejected", + "collectorNativeRequested", + "collectorSharedRequested", + "collectorAdmitted", + "collectorFinished", + "nativeTransformRequested", + "nativeTransformFinished", + "contextCreated", + "contextReleased", + "bridgeInputRejected", + "bridgeExportRejected", + "bridgeGuardInvalid", + "asciiViewRequested", + "asciiViewAdmitted", + "asciiViewBudgetFallback", + "literalReplaceRequested", + "literalReplaceAdmitted", + "literalReplaceBudgetFallback", + "literalReplaceSemanticFallback", + "literalReplaceApiFallback", + "platformWarmupRequested", + "platformWarmupStarted", + "platformWarmupSucceeded", + "platformWarmupFailed", + "platformWarmupContextCreated", + "platformWarmupContextReleased", + "jscSelected", + "planSelected", + "planInputFallback", + "planAstFallback", + "planBuffersRejected", + "planEntered", + "planSucceeded", + "planTimedOut", + "planCancelled", + "planFailed", + "jscOwnerStarted", + "jscOwnerJoined", + "planOwnerStarted", + "planOwnerJoined", + "planFinalRecipeEntered", + "planFinalDagEntered", + "planInlineEntered", + "planInlineReturned", + "planInlinePanicked", + "planInlineCpuUnavailable", + "planHeaderGuardEntered", + "planHeaderGuardTail", + "planHeaderGuardPass", + "planHeaderGuardAbort", + "planFinalSingleStepEntered", + "planOutputPendingAdmitted", + "planOutputQueueFailed", + "planOutputPayloadBudgetRejected", + "tunWriteSingleSendAttempts", + "tunWriteSingleEnobufsErrors", + "tunWriteSingleSleep1msRequests", + "tunWriteSingleAcceptedPackets", + "tunWriteSingleWouldBlock", + "tunWriteBatchSendAttempts", + "tunWriteBatchEnobufsErrors", + "tunWriteBatchSleep1msRequests", + "tunWriteBatchAcceptedPackets", + "tunWriteBatchWouldBlock", + "tunIngressReadOkPackets", + "tunIngressReadInvalidPacketOutcomes", + "tunIngressMtuExceededDrops", + "tunIngressNetstackAcceptedPackets", + "tunIngressNetstackBackpressureDrops", + "tunIngressIpv4DeclaredLengthExceedsReadSlice", + "tunIngressIpv6DeclaredLengthExceedsReadSlice", + "tunNetstackDriverDrivePasses", + "tunNetstackDriverTcpEntryVisits", + "tunNetstackDriverAppRxBytes", + "tunNetstackDriverAppTxBytes", + "tunNetstackDriverNoDataProgressPasses", + "tunNetstackDriverWaitIngress", + "tunNetstackDriverWaitNotify", + "tunNetstackDriverWaitTimer", + ]; + const TIMINGS: [&str; 10] = [ + "queue", + "evaluation", + "contextRelease", + "finalParse", + "scopedOwner", + "jscScopedOwner", + "planScopedOwner", + "planInlineDispatchWall", + "planInlineWall", + "planInlineThreadCpu", + ]; + const STAGES: [&str; 6] = [ + "contextAndCallback", + "prelude", + "program", + "input", + "invokeAndFinish", + "export", + ]; + const BODY_POINTS: [&str; 7] = [ + "nativeAdmission", + "sharedAdmission", + "collection", + "nativeDecode", + "sharedDecode", + "nativeTransform", + "headerFinalize", + ]; + const REASONS: [&str; 11] = [ + "noRules", + "forbiddenBody", + "streaming", + "trailers", + "charset", + "encoding", + "identityExcluded", + "budget", + "size", + "invalidText", + "transform", + ]; + + fn reason_index(reason: Bypass) -> usize { + match reason { + Bypass::NoRules => 0, + Bypass::ForbiddenBody => 1, + Bypass::Streaming => 2, + Bypass::Trailers => 3, + Bypass::Charset => 4, + Bypass::Encoding => 5, + Bypass::IdentityExcluded => 6, + Bypass::Budget => 7, + Bypass::Size => 8, + Bypass::InvalidText => 9, + Bypass::Transform => 10, + } + } + + // Saturation affects only telemetry and cannot wrap an accumulated time or + // byte count. Gauges instead follow balanced actual owner admission/drop. + fn add(target: &AtomicU64, value: u64) { + let _ = target.try_update(Ordering::Relaxed, Ordering::Relaxed, |old| { + Some(old.saturating_add(value)) + }); + } + fn load(target: &AtomicU64) -> u64 { + target.load(Ordering::Relaxed) + } + fn bounded(value: u128) -> u64 { + value.min(u128::from(u64::MAX)) as u64 + } + pub(super) struct Aggregate { + count: AtomicU64, + total: AtomicU64, + max: AtomicU64, + } + impl Aggregate { + const fn new() -> Self { + Self { + count: AtomicU64::new(0), + total: AtomicU64::new(0), + max: AtomicU64::new(0), + } + } + pub(super) fn record(&self, value: u128) { + add(&self.count, 1); + let value = bounded(value); + add(&self.total, value); + self.max.fetch_max(value, Ordering::Relaxed); + } + fn snapshot(&self) -> Value { + json!({"count": load(&self.count), "total": load(&self.total), "max": load(&self.max)}) + } + } + + pub(super) struct Stats { + counters: [AtomicU64; COUNTERS.len()], + pub(super) timings: [Aggregate; TIMINGS.len()], + stages: [[Aggregate; STAGES.len()]; 2], + requested: [Aggregate; 3], + ticks: Aggregate, + bypasses: [[AtomicU64; REASONS.len()]; BODY_POINTS.len()], + pub(super) body_current: AtomicU64, + body_peak: AtomicU64, + body_max_single_budget: AtomicU64, + pub(super) context_current: AtomicU64, + pub(super) context_peak: AtomicU64, + pub(super) queue_current: AtomicU64, + pub(super) queue_peak: AtomicU64, + } + impl Stats { + const fn new() -> Self { + Self { + counters: [const { AtomicU64::new(0) }; COUNTERS.len()], + timings: [const { Aggregate::new() }; TIMINGS.len()], + stages: [const { [const { Aggregate::new() }; STAGES.len()] }; 2], + requested: [const { Aggregate::new() }; 3], + ticks: Aggregate::new(), + bypasses: [const { [const { AtomicU64::new(0) }; REASONS.len()] }; + BODY_POINTS.len()], + body_current: AtomicU64::new(0), + body_peak: AtomicU64::new(0), + body_max_single_budget: AtomicU64::new(0), + context_current: AtomicU64::new(0), + context_peak: AtomicU64::new(0), + queue_current: AtomicU64::new(0), + queue_peak: AtomicU64::new(0), + } + } + pub(super) fn add_counter(&self, counter: Counter, value: u64) { + add(&self.counters[counter as usize], value); + } + pub(super) fn increment(&self, counter: Counter) { + add(&self.counters[counter as usize], 1); + } + pub(super) fn body_reserved(&self, bytes: usize, single_budget_used: usize) { + self.increment(Counter::BodyReserveSucceeded); + let current = self + .body_current + .fetch_add(bytes as u64, Ordering::Relaxed) + .saturating_add(bytes as u64); + self.body_peak.fetch_max(current, Ordering::Relaxed); + self.body_max_single_budget + .fetch_max(single_budget_used as u64, Ordering::Relaxed); + } + pub(super) fn call_buffers_requested(&self, input: usize, output: usize, bridge: usize) { + self.increment(Counter::CallBuffersRequested); + for (stat, bytes) in self.requested.iter().zip([input, output, bridge]) { + stat.record(bytes as u128); + } + } + pub(super) fn body_bypass(&self, point: BodyPoint, reason: Bypass) { + add(&self.bypasses[point as usize][reason_index(reason)], 1); + } + #[cfg(any(test, target_vendor = "apple"))] + pub(super) fn evaluation_finished( + &self, + stages: [u128; 6], + seen: u8, + overall: u128, + ticks: usize, + succeeded: bool, + ) { + self.timings[super::Timing::Evaluation as usize].record(overall); + self.ticks.record(ticks as u128); + let outcome = usize::from(!succeeded); + for (index, micros) in stages.into_iter().enumerate() { + if seen & (1 << index) != 0 { + self.stages[outcome][index].record(micros); + } + } + } + pub(super) fn snapshot(&self) -> Value { + let counters: Map = COUNTERS + .iter() + .zip(&self.counters) + .map(|(key, value)| ((*key).into(), load(value).into())) + .collect(); + let timings: Map = TIMINGS + .iter() + .zip(&self.timings) + .map(|(key, value)| ((*key).into(), value.snapshot())) + .collect(); + let stages: Map = STAGES.iter().enumerate().map(|(i, key)| ((*key).into(), json!({"succeeded": self.stages[0][i].snapshot(), "failed": self.stages[1][i].snapshot()}))).collect(); + let bypasses: Map = BODY_POINTS + .iter() + .zip(&self.bypasses) + .map(|(point, values)| { + let reasons: Map = REASONS + .iter() + .zip(values) + .map(|(reason, value)| ((*reason).into(), load(value).into())) + .collect(); + ((*point).into(), reasons.into()) + }) + .collect(); + json!({ + "scope": "process-lifetime; fixed counters; atomic fields sampled independently", + "units": {"timings": "microseconds", "stages": "microseconds", "callBuffers": "reserved bytes requested", "bodyWorkspace": "reservation bytes, not VM heap or RSS"}, + "counters": counters, + "queue": {"current": load(&self.queue_current), "peak": load(&self.queue_peak)}, + "contexts": {"current": load(&self.context_current), "peak": load(&self.context_peak), "kind": "JSGlobalContext; current implementation creates a unique group per context"}, + "timings": timings, + "stages": stages, + "ticks": self.ticks.snapshot(), + "bodyWorkspace": {"current": load(&self.body_current), "peak": load(&self.body_peak), "maxSingleBudget": load(&self.body_max_single_budget), "scope": "current/peak are process-wide shadow telemetry; transient ordering can overstate peak; maxSingleBudget uses actual successful admission"}, + "callBuffers": {"input": self.requested[0].snapshot(), "maximumOutput": self.requested[1].snapshot(), "bridgeWorkspace": self.requested[2].snapshot(), "admission": "single atomic combined reservation; failure does not identify a single component"}, + "bodyBypasses": bypasses, + }) + } + } + pub(super) static STATS: Stats = Stats::new(); + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn local_stats_preserve_components_and_combined_rejection() { + let stats = Stats::new(); + stats.call_buffers_requested(64, 256, 128); + stats.increment(Counter::CallBuffersBudgetRejected); + let value = stats.snapshot(); + assert_eq!(value["callBuffers"]["input"]["total"], 64); + assert_eq!(value["callBuffers"]["maximumOutput"]["total"], 256); + assert_eq!(value["callBuffers"]["bridgeWorkspace"]["total"], 128); + assert_eq!(value["counters"]["callBuffersBudgetRejected"], 1); + assert_eq!(value["counters"]["callBuffersAdmitted"], 0); + } + + #[test] + fn local_gauges_balance_independent_reservations_and_stage_outcomes() { + let stats = Stats::new(); + stats.body_reserved(100, 100); + stats.body_reserved(20, 120); + stats.body_current.fetch_sub(100, Ordering::Relaxed); + assert_eq!(stats.snapshot()["bodyWorkspace"]["current"], 20); + stats.body_current.fetch_sub(20, Ordering::Relaxed); + stats.evaluation_finished([2, 3, 5, 7, 11, 13], 0b11_1111, 50, 80, true); + stats.evaluation_finished([17, 19, 0, 0, 0, 0], 0b00_0011, 40, 0, false); + let value = stats.snapshot(); + assert_eq!(value["bodyWorkspace"]["current"], 0); + assert_eq!(value["bodyWorkspace"]["peak"], 120); + assert_eq!(value["stages"]["prelude"]["succeeded"]["total"], 3); + assert_eq!(value["stages"]["prelude"]["failed"]["total"], 19); + assert_eq!(value["stages"]["program"]["failed"]["count"], 0); + assert_eq!(value["timings"]["evaluation"]["total"], 90); + assert_eq!(value["ticks"]["max"], 80); + } + + #[test] + fn telemetry_saturates_without_affecting_owner_gauges() { + let total = AtomicU64::new(u64::MAX - 1); + add(&total, 3); + assert_eq!(load(&total), u64::MAX); + } + + #[test] + fn tun_ingress_ipv4_declared_length_is_observational_only() { + let mut packet = [0u8; 24]; + packet[0] = 0x45; + for declared in [0u16, 19, 20, 23, 24] { + packet[2..4].copy_from_slice(&declared.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + None + )); + } + packet[2..4].copy_from_slice(&25u16.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + Some(super::super::Counter::TunIngressIpv4DeclaredLengthExceedsReadSlice) + )); + // IHL/options validity is outside this observation. Only the complete + // twenty-byte base and version select the declared-length comparison. + packet[0] = 0x4f; + packet[2..4].copy_from_slice(&24u16.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + None + )); + packet[2..4].copy_from_slice(&25u16.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + Some(super::super::Counter::TunIngressIpv4DeclaredLengthExceedsReadSlice) + )); + } + + #[test] + fn tun_ingress_length_uses_read_slice_not_vec_capacity_or_backing() { + let mut ipv4 = Vec::with_capacity(4096); + ipv4.resize(20, 0u8); + ipv4[0] = 0x45; + ipv4[2..4].copy_from_slice(&21u16.to_be_bytes()); + assert!(ipv4.capacity() > ipv4.len()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&ipv4), + Some(super::super::Counter::TunIngressIpv4DeclaredLengthExceedsReadSlice) + )); + ipv4.resize(32, 0); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&ipv4), + None + )); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&ipv4[..20]), + Some(super::super::Counter::TunIngressIpv4DeclaredLengthExceedsReadSlice) + )); + + let mut ipv6 = Vec::with_capacity(4096); + ipv6.resize(40, 0u8); + ipv6[0] = 0x60; + ipv6[4..6].copy_from_slice(&1u16.to_be_bytes()); + assert!(ipv6.capacity() > ipv6.len()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&ipv6), + Some(super::super::Counter::TunIngressIpv6DeclaredLengthExceedsReadSlice) + )); + ipv6.resize(41, 0); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&ipv6), + None + )); + } + + #[test] + fn tun_ingress_length_requires_complete_base_headers_and_known_version() { + for len in 0..20 { + let mut packet = vec![0u8; len]; + if let Some(first) = packet.first_mut() { + *first = 0x45; + } + if len >= 4 { + packet[2..4].copy_from_slice(&u16::MAX.to_be_bytes()); + } + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + None + )); + } + for len in 0..40 { + let mut packet = vec![0u8; len]; + if let Some(first) = packet.first_mut() { + *first = 0x60; + } + if len >= 6 { + packet[4..6].copy_from_slice(&u16::MAX.to_be_bytes()); + } + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + None + )); + } + for version in [0u8, 1, 5, 7, 15] { + let mut packet = [0xffu8; 40]; + packet[0] = version << 4; + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + None + )); + } + } + + #[test] + fn tun_ingress_ipv6_declared_length_adds_base_without_u16_wrap_or_jumbo_guess() { + let mut packet = [0u8; 48]; + packet[0] = 0x60; + for payload in [0u16, 1, 7, 8] { + packet[4..6].copy_from_slice(&payload.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + None + )); + } + packet[4..6].copy_from_slice(&9u16.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + Some(super::super::Counter::TunIngressIpv6DeclaredLengthExceedsReadSlice) + )); + packet[4..6].copy_from_slice(&u16::MAX.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&packet), + Some(super::super::Counter::TunIngressIpv6DeclaredLengthExceedsReadSlice) + )); + + // Zero-filled synthetic storage; declared length is 65535 + 40 in usize, + // not u16 arithmetic. Equality and one-byte-short remain distinct. + let mut maximum = vec![0u8; usize::from(u16::MAX) + 40]; + maximum[0] = 0x60; + maximum[4..6].copy_from_slice(&u16::MAX.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&maximum), + None + )); + maximum.truncate(maximum.len() - 1); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&maximum), + Some(super::super::Counter::TunIngressIpv6DeclaredLengthExceedsReadSlice) + )); + // payload_length = 0 does not inspect or infer a Jumbo Payload option. + maximum[4..6].copy_from_slice(&0u16.to_be_bytes()); + assert!(matches!( + super::super::tun_ingress_header_length_counter(&maximum), + None + )); + } + } +} diff --git a/src/http_processing/document.rs b/src/http_processing/document.rs index ce26f37..c46d6d4 100644 --- a/src/http_processing/document.rs +++ b/src/http_processing/document.rs @@ -3,7 +3,8 @@ use super::{MAX_ADDENDUM, Policy, PolicyCandidate, SourceLocation, invalid}; use crate::http_processing::{ mitm::RawMitm, providers::{Payload, ProviderSpec}, - rules::{MAX_RULES, RawRule, Rule}, + rules::{MAX_RULES, RawRule, Rule, SelectorCompiler}, + script_config::RawScripts, }; use serde::{Deserialize, Deserializer, Serialize}; use sha2::{Digest, Sha256}; @@ -39,6 +40,8 @@ pub(crate) struct Document { #[serde(default, deserialize_with = "nonnull")] pub(crate) rewrite: Rewrite, #[serde(default, deserialize_with = "nonnull")] + pub(crate) http_scripts: RawScripts, + #[serde(default, deserialize_with = "nonnull")] pub(crate) mitm: RawMitm, #[serde(skip)] identity: [u8; 32], @@ -93,6 +96,7 @@ impl Document { validate_ports(&self.http_ports)?; validate_ports(&self.mitm.ports)?; self.mitm.validate_static()?; + self.http_scripts.compile()?; if self.providers.len() > MAX_RULES || self.rewrite.rules.len() > MAX_RULES { return Err(invalid()); } @@ -166,6 +170,7 @@ impl Document { ) -> io::Result> { let mut rules = Vec::new(); let mut text = 0; + let mut selectors = SelectorCompiler::default(); let mut payloads = BTreeMap::new(); let mut origins = Vec::new(); let mut bytes = self.input_bytes; @@ -175,7 +180,11 @@ impl Document { if rules.len() == MAX_RULES { return Err(invalid()); } - rules.push(compile_rule(rule.clone(), &mut text)?); + rules.push(Rule::compile_with_selectors( + rule.clone(), + &mut text, + &mut selectors, + )?); origins.push(SourceLocation::Local { index }); } RuleEntry::Reference(reference) if reference.enabled => { @@ -202,7 +211,11 @@ impl Document { if rules.len() == MAX_RULES { return Err(invalid()); } - rules.push(compile_rule(rule.clone(), &mut text)?); + rules.push(Rule::compile_with_selectors( + rule.clone(), + &mut text, + &mut selectors, + )?); origins.push(SourceLocation::Provider { provider: reference.rule_set.clone(), index, @@ -225,6 +238,7 @@ impl Document { Ok(Arc::new(PolicyCandidate { document: self.clone(), rules: rules.into(), + scripts: self.http_scripts.compile()?.into(), payloads, identity: hash.finalize().into(), origins: origins.into(), @@ -246,3 +260,7 @@ fn validate_ports(ports: &[u16]) -> io::Result<()> { } Ok(()) } + +#[cfg(all(test, feature = "inbound-http"))] +#[path = "selector_sharing_tests.rs"] +mod selector_sharing_tests; diff --git a/src/http_processing/document_tests.rs b/src/http_processing/document_tests.rs index 1ffbccc..b1a447e 100644 --- a/src/http_processing/document_tests.rs +++ b/src/http_processing/document_tests.rs @@ -83,3 +83,145 @@ fn external_http_payload_is_mandatory_and_never_carries_local_authority() { ); assert!(doc.is_err()); } + +#[cfg(feature = "inbound-http")] +fn inline_script_document(enabled: bool, body: &str, source: &str) -> String { + format!( + "http-scripts:\n enabled: {enabled}\n scripts:\n - name: example\n phase: request\n url: 'https://example.test/api/'\n match: prefix\n body: {body}\n source: {}\n", + serde_json::to_string(source).unwrap() + ) +} + +#[cfg(feature = "inbound-http")] +const PASS_SCRIPT: &str = "function rewrite(input) { return { type: 'pass' }; }"; + +#[cfg(feature = "inbound-http")] +#[test] +fn inline_scripts_have_independent_switch_and_static_compilation() { + use crate::http_processing::{rules::Phase, script_config::BodyMode}; + let document = Document::parse(&inline_script_document(true, "bytes", PASS_SCRIPT)).unwrap(); + let policy = document.static_policy().unwrap(); + assert!(policy.rules().is_empty()); + assert_eq!(policy.scripts().len(), 1); + assert!(policy.plain_port(80)); + assert!(!policy.plain_port(81)); + assert!(!policy.is_prepared()); + let script = &policy.scripts()[0]; + assert_eq!(script.name, "example"); + assert_eq!(script.phase, Phase::Request); + assert_eq!(script.body, BodyMode::Bytes); + assert!(script.matches(&Url::parse("https://example.test/api/item").unwrap())); + assert!(!script.matches(&Url::parse("https://example.test/other").unwrap())); + + let disabled = Policy::compile(&inline_script_document(false, "none", PASS_SCRIPT)).unwrap(); + assert!(disabled.scripts().is_empty()); + assert_eq!(disabled.all_scripts().len(), 1); + assert!(!disabled.plain_port(80)); + assert!(disabled.is_prepared()); +} + +#[cfg(feature = "inbound-http")] +#[test] +fn inline_script_schema_is_strict_even_when_disabled() { + for invalid in [ + "http-scripts: null", + "http-scripts: {enabled: null}", + "http-scripts: {scripts: null}", + "http-scripts: {scripts: [], provider: remote}", + ] { + assert!(Document::parse(invalid).is_err()); + } + let valid = inline_script_document(false, "text", PASS_SCRIPT); + for (field, invalid) in [ + ("name", serde_yaml_ng::Value::String(String::new())), + ("phase", serde_yaml_ng::Value::String("cron".into())), + ("body", serde_yaml_ng::Value::Null), + ("match", serde_yaml_ng::Value::String("automatic".into())), + ( + "source", + serde_yaml_ng::Value::String("function rewrite(".into()), + ), + ("url", serde_yaml_ng::Value::String("[".into())), + ( + "script-path", + serde_yaml_ng::Value::String("remote.js".into()), + ), + ] { + let mut value: serde_yaml_ng::Value = serde_yaml_ng::from_str(&valid).unwrap(); + value["http-scripts"]["scripts"][0][field] = invalid; + assert!( + Document::parse(&serde_yaml_ng::to_string(&value).unwrap()).is_err(), + "accepted invalid script field {field}" + ); + } + assert!( + Payload::parse( + format!( + "payload: []\n{}", + inline_script_document(true, "none", PASS_SCRIPT) + ) + .as_bytes() + ) + .is_err() + ); +} + +#[cfg(feature = "inbound-http")] +#[test] +fn inline_script_sources_are_hashed_and_frozen_in_actual_snapshots() { + let original = Document::parse(&inline_script_document(true, "none", PASS_SCRIPT)).unwrap(); + let candidate = original.compile(&BTreeMap::new()).unwrap(); + let exported = candidate.export_snapshot().unwrap(); + let restored = PolicyCandidate::import_snapshot(&exported).unwrap(); + assert_eq!(candidate.identity(), restored.identity()); + assert_eq!(restored.scripts.len(), 1); + let snapshot: serde_yaml_ng::Value = serde_yaml_ng::from_str(&exported).unwrap(); + assert_eq!( + snapshot["document"]["http-scripts"]["scripts"][0]["source"].as_str(), + Some(PASS_SCRIPT) + ); + for other in [ + inline_script_document(false, "none", PASS_SCRIPT), + inline_script_document(true, "text", PASS_SCRIPT), + inline_script_document(true, "none", &format!("{PASS_SCRIPT}\n")), + inline_script_document(true, "none", PASS_SCRIPT) + .replace("phase: request", "phase: response"), + inline_script_document(true, "none", PASS_SCRIPT).replace("match: prefix", "match: exact"), + inline_script_document(true, "none", PASS_SCRIPT).replace("name: example", "name: other"), + ] { + let changed = Document::parse(&other).unwrap(); + assert_ne!(original.identity(), changed.identity()); + assert_eq!(restored.identity(), candidate.identity()); + } +} + +#[cfg(all(feature = "inbound-http", not(target_vendor = "apple")))] +#[tokio::test] +async fn unsupported_script_backend_fails_preparation_before_external_resources() { + use crate::http_processing::providers::{SourceContext, Store}; + let input = format!( + "rewrite-providers: {{missing: {{type: file, path: missing.yaml}}}}\nrewrite: {{rules: [{{rule-set: missing}}]}}\n{}", + inline_script_document(true, "none", PASS_SCRIPT) + ); + let document = Document::parse(&input).unwrap(); + let error = Store::new() + .prepare( + document, + &SourceContext::default(), + None, + &tokio_util::sync::CancellationToken::new(), + false, + ) + .await + .err() + .unwrap(); + assert_eq!(error.kind(), io::ErrorKind::Unsupported); + let candidate = Document::parse(&inline_script_document(true, "none", PASS_SCRIPT)) + .unwrap() + .compile(&BTreeMap::new()) + .unwrap(); + assert_eq!( + candidate.bind_ca(None).err().unwrap().kind(), + io::ErrorKind::Unsupported + ); +} diff --git a/src/http_processing/h1.rs b/src/http_processing/h1.rs index f656baa..9a1c8da 100644 --- a/src/http_processing/h1.rs +++ b/src/http_processing/h1.rs @@ -79,6 +79,7 @@ impl HttpContext { let (read, mut write) = tokio::io::split(stream); let mut reader = BufReader::with_capacity(framing::COPY_BUFFER, read); let config = HttpServerConfig::processing(); + let mut upstream = None; loop { let request = timeout(config.header_timeout, async { if reader.fill_buf().await?.is_empty() { @@ -102,7 +103,8 @@ impl HttpContext { &request, session.clone(), scheme, - &config, + (&config, &cancellation), + &mut upstream, ) .await? { @@ -116,16 +118,31 @@ impl HttpContext { } } + #[allow(clippy::too_many_arguments)] pub(crate) async fn forward_h1( &self, reader: &mut R, writer: &mut W, request: &RequestHead, - session: StreamSession, + mut session: StreamSession, scheme: Scheme, - config: &HttpServerConfig, + scope: (&HttpServerConfig, &CancellationToken), + upstream: &mut Option, ) -> io::Result { + let (config, cancellation) = scope; let original = request_url(request, scheme)?; + if scheme == Scheme::Http + && let Some(plan) = self + .dispatcher() + .sniff_plan(session.source, &session.destination) + .await + .map_err(|_| io::Error::other("sniffer rule evaluation failed"))? + { + plan.with_cancellation(cancellation.clone()) + .observe_http_host(original.host_str().ok_or_else(invalid)?, &mut session) + .map_err(|_| io::Error::other("sniffer rule evaluation failed"))?; + } + let base_session = session.clone(); let asterisk = request.method == "OPTIONS" && request.target == "*"; let decision = match self.plan(original, session, scheme, !asterisk) { Ok(decision) => decision, @@ -140,7 +157,7 @@ impl HttpContext { } Err(error) => return Err(error), }; - let target = match decision { + let mut target = match decision { Decision::Reject => { framing::write_timed( writer, @@ -180,13 +197,13 @@ impl HttpContext { origin.clone(), false, )?; - let message = super::h1_body::Message { - policy: self.policy(), - original: &target.original, - request, - meta: super::body::OriginalRequestMeta::new(&request.method, &request.headers), - continued: std::sync::atomic::AtomicBool::new(false), - }; + let original_url = target.original.clone(); + let original_meta = + super::body::OriginalRequestMeta::new(&request.method, &request.headers); + let mut crossed_origin = target.strip_origin_credentials; + let mut continued = false; + let mut prepared_upload = None; + let mut script_context = None; let mut outgoing = request.clone(); if target.strip_origin_credentials { super::headers::strip_origin_credentials(&mut outgoing.headers); @@ -199,14 +216,247 @@ impl HttpContext { ); let mut plan = RequestPlan::for_target(&outgoing, target.logical_destination.clone(), origin, false)?; + let active_scripts = plan.upgrade.is_empty() + && self + .policy() + .scripts() + .iter() + .any(|s| s.matches(&original_url)); + if active_scripts { + use super::{ + body::{Transaction, WireBodyMeta}, + script_config::BodyMode, + script_message::{self, OriginalSnapshot, Outcome, RequestSnapshot}, + }; + let wants_body = self.policy().scripts().iter().any(|s| { + s.phase == super::rules::Phase::Request + && s.body != BodyMode::None + && s.matches(&original_url) + }); + let length = match plan.body { + framing::Body::Empty => Some(0), + framing::Body::Length(n) => Some(n), + _ => None, + }; + let wire = WireBodyMeta::new( + &request.headers, + &original_meta, + super::rules::Phase::Request, + None, + length, + false, + ); + let transaction = Transaction::begin_shared( + self.policy().body_budget(), + self.policy().rules(), + &original_url, + super::rules::Phase::Request, + &wire, + wants_body && !asterisk, + ) + .ok(); + if transaction.is_some() + && request + .headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("expect")) + { + framing::write_timed( + writer, + b"HTTP/1.1 100 Continue\r\n\r\n", + config.header_timeout, + ) + .await?; + framing::timeout_io( + config.header_timeout, + tokio::io::AsyncWriteExt::flush(writer), + ) + .await?; + continued = true; + outgoing + .headers + .retain(|(name, _)| !name.eq_ignore_ascii_case("expect")); + } + if target.strip_origin_credentials { + plan.trailer_blocklist.insert("cookie".into()); + } + let (mut prepared, entity) = super::h1_body::prepare_shared( + reader, + plan.body, + &plan.trailer_blocklist, + config.body_idle_timeout, + transaction, + &mut outgoing.headers, + ) + .await?; + let original = OriginalSnapshot { + url: original_url.clone(), + method: request.method.clone(), + identity_allowed: original_meta.identity_allowed, + asterisk, + }; + let mut message = script_message::Message::request( + original.clone(), + RequestSnapshot { + url: target.url.clone(), + method: outgoing.method.clone(), + headers: outgoing.headers.clone(), + }, + entity, + &request.headers, + target.strip_origin_credentials, + ); + let outcome = + match script_message::run(self.policy(), &original_url, &mut message, cancellation) + .await + { + Ok(outcome) => outcome, + Err(error) + if cancellation.is_cancelled() + || error.kind() == io::ErrorKind::Interrupted => + { + return Err(error); + } + Err(_) => { + return write_local( + writer, + script_message::LocalResponse { + status: 502, + headers: vec![("Content-Length".into(), "0".into())], + body: bytes::Bytes::new(), + }, + config.header_timeout, + ) + .await; + } + }; + match outcome { + Outcome::Abort => return Ok(false), + Outcome::Respond(local) => { + drop(message); + drop(prepared); + return write_local(writer, local, config.header_timeout).await; + } + Outcome::Forward => {} + } + crossed_origin |= message.crossed_origin; + if let Some(entity) = message.body.take() { + prepared.install_entity(entity); + } + outgoing.method = message.request.method.clone(); + outgoing.headers = message.request.headers.clone(); + target = self.final_target( + original_url.clone(), + message.request.url.clone(), + base_session, + scheme, + )?; + let mut final_origin = if asterisk { + "*".to_owned() + } else { + target.url.path().to_owned() + }; + if let Some(query) = target.url.query() { + final_origin.push('?'); + final_origin.push_str(query); + } + plan = RequestPlan::for_target( + &outgoing, + target.logical_destination.clone(), + final_origin, + false, + )?; + if message.crossed_origin { + plan.trailer_blocklist.insert("cookie".into()); + } + prepared_upload = Some(prepared); + script_context = Some(super::h1_body::ScriptContext { + original, + request: message.request, + cancellation: cancellation.clone(), + }); + } if target.strip_origin_credentials { plan.trailer_blocklist.insert("cookie".into()); } + let message = super::h1_body::Message { + policy: self.policy(), + original: &original_url, + request, + meta: original_meta, + continued: std::sync::atomic::AtomicBool::new(continued), + prepared: std::sync::Mutex::new(prepared_upload), + scripts: script_context, + }; + // The slot never leaves this downstream's fixed HttpContext. HTTPS + // additionally requires an unchanged origin throughout request actions; + // an A -> B -> A script chain must not recover reuse eligibility. + let reusable_transport = (scheme == Scheme::Http && target.url.scheme() == "http") + || (scheme == Scheme::Https + && target.url.scheme() == "https" + && !crossed_origin + && !target.strip_origin_credentials); + let eligible = reusable_transport + && !matches!(request.method.as_str(), "HEAD" | "CONNECT") + && !matches!(outgoing.method.as_str(), "HEAD" | "CONNECT") + && !asterisk + && request.version == "HTTP/1.1" + && plan.keep_alive + && plan.upgrade.is_empty() + && matches!(plan.body, framing::Body::Empty | framing::Body::Length(_)) + && !outgoing + .headers + .iter() + .any(|(n, _)| n.eq_ignore_ascii_case("expect")); let deadline = Instant::now() + config.connect_timeout; - let mut outbound = timeout_at(deadline, self.dispatcher.connect_tcp(target.session)) + let prepared = if eligible { + timeout_at( + deadline, + self.dispatcher.prepare_http_tcp(target.session.clone()), + ) .await - .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "HTTP outbound timed out"))? - .map_err(|_| io::Error::other("HTTP outbound failed"))?; + .map_err(|_| { + io::Error::new(io::ErrorKind::TimedOut, "HTTP outbound planning timed out") + })? + .map_err(|_| io::Error::other("HTTP outbound planning failed"))? + } else { + None + }; + let key = prepared.as_ref().and_then(|p| p.reuse_key()).cloned(); + let authority = target.url.origin().ascii_serialization(); + // Taking removes the slot even on errors/panic. No old IO can survive + // an uncertain exchange or be used for a rejected new route. + if let Some(mut previous) = upstream.take() + && key.as_ref().is_some_and(|k| previous.key.same(k)) + && previous.authority == authority + && previous.io.idle_healthy().await + { + drop(prepared); + let outcome = server::forward_processed_reusable( + reader, + writer, + &mut previous.io, + request, + plan, + config, + &message, + ) + .await?; + if outcome.upstream_reusable { + *upstream = Some(previous); + } + return Ok(outcome.downstream_keep_alive); + } + let mut outbound = timeout_at(deadline, async { + if let Some(prepared) = prepared { + prepared.connect().await + } else { + self.dispatcher.connect_tcp(target.session).await + } + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "HTTP outbound timed out"))? + .map_err(|_| io::Error::other("HTTP outbound failed"))?; if target.url.scheme() == "https" { let tls = StandardTlsClient::with_options( self.security(), @@ -222,16 +472,61 @@ impl HttpContext { 0, 64 * 1024, )?; - outbound = timeout_at(deadline, tls.connect(outbound)) + let (authenticated, alpn) = timeout_at(deadline, tls.connect_negotiated(outbound)) .await .map_err(|_| { io::Error::new(io::ErrorKind::TimedOut, "HTTP upstream TLS timed out") })? .map_err(|_| io::Error::other("HTTP upstream TLS failed"))?; + if alpn + .as_deref() + .is_some_and(|protocol| protocol != b"http/1.1") + { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "HTTP upstream TLS did not negotiate HTTP/1.1", + )); + } + outbound = authenticated; + } + if let Some(key) = key { + let mut io = server::UpstreamIo::new(outbound); + let outcome = server::forward_processed_reusable( + reader, writer, &mut io, request, plan, config, &message, + ) + .await?; + if outcome.upstream_reusable { + *upstream = Some(server::UpstreamSlot { authority, key, io }); + } + Ok(outcome.downstream_keep_alive) + } else { + server::forward_processed(reader, writer, outbound, request, plan, config, &message) + .await } - server::forward_processed(reader, writer, outbound, request, plan, config, &message).await } } +async fn write_local( + writer: &mut W, + local: super::script_message::LocalResponse, + idle: Duration, +) -> io::Result { + let reason = http::StatusCode::from_u16(local.status) + .ok() + .and_then(|s| s.canonical_reason()) + .unwrap_or("Response"); + let mut head = format!("HTTP/1.1 {} {}\r\n", local.status, reason); + for (name, value) in &local.headers { + head.push_str(name); + head.push_str(": "); + head.push_str(value); + head.push_str("\r\n"); + } + head.push_str("Connection: close\r\n\r\n"); + framing::write_timed(writer, head.as_bytes(), idle).await?; + framing::write_timed(writer, &local.body, idle).await?; + framing::timeout_io(idle, tokio::io::AsyncWriteExt::flush(writer)).await?; + Ok(false) +} fn request_url(request: &RequestHead, scheme: Scheme) -> io::Result { let mut hosts = request .headers diff --git a/src/http_processing/h1_body.rs b/src/http_processing/h1_body.rs index 75a1a27..3854a1f 100644 --- a/src/http_processing/h1_body.rs +++ b/src/http_processing/h1_body.rs @@ -5,25 +5,41 @@ use super::{ headers::Fields, rules::Phase, }; +use super::{ + script_config::BodyMode, + script_message::{self, OriginalSnapshot, Outcome, RequestSnapshot, ResponseSnapshot}, +}; use crate::inbound::http::{ HttpServerConfig, RequestHead, framing::{self, Body, RequestPlan, ResponseHead}, }; +use bytes::Bytes; use std::{ collections::HashSet, io, + pin::Pin, sync::atomic::{AtomicBool, Ordering}, + task::{Context, Poll}, time::Duration, }; use tokio::io::{AsyncBufRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}; +use tokio_util::sync::CancellationToken; use url::Url; +pub(crate) struct ScriptContext { + pub(crate) original: OriginalSnapshot, + pub(crate) request: RequestSnapshot, + pub(crate) cancellation: CancellationToken, +} + pub(crate) struct Message<'a> { pub(crate) policy: &'a Policy, pub(crate) original: &'a Url, pub(crate) request: &'a RequestHead, pub(crate) meta: OriginalRequestMeta, pub(crate) continued: AtomicBool, + pub(crate) prepared: std::sync::Mutex>, + pub(crate) scripts: Option, } impl Message<'_> { @@ -37,6 +53,14 @@ impl Message<'_> { plan: &mut RequestPlan, config: &HttpServerConfig, ) -> io::Result { + if let Some(prepared) = self + .prepared + .lock() + .map_err(|_| io::Error::other("HTTP upload owner poisoned"))? + .take() + { + return Ok(prepared); + } let wire = WireBodyMeta::new( &self.request.headers, &self.meta, @@ -101,7 +125,84 @@ impl Message<'_> { length(body), response.status == 101, ); + let original_fields = self.scripts.as_ref().map(|_| response.headers().clone()); self.response_headers(response)?; + if let Some(script) = &self.scripts { + let wants_body = self.policy.scripts().iter().any(|s| { + s.phase == Phase::Response && s.body != BodyMode::None && s.matches(self.original) + }); + let transaction = Transaction::begin_shared( + self.policy.body_budget(), + self.policy.rules(), + self.original, + Phase::Response, + &wire, + wants_body, + ) + .ok(); + let mut fields = response.headers().clone(); + let (mut prepared, entity) = prepare_shared( + reader, + body, + response.trailer_blocklist(), + config.body_idle_timeout, + transaction, + &mut fields, + ) + .await?; + let mut message = script_message::Message::response( + script.original.clone(), + script.request.clone(), + ResponseSnapshot { + status: response.status, + headers: fields, + }, + entity, + original_fields.as_ref().expect("script wire headers"), + ); + let outcome = match script_message::run( + self.policy, + self.original, + &mut message, + &script.cancellation, + ) + .await + { + Ok(outcome) => outcome, + Err(error) + if script.cancellation.is_cancelled() + || error.kind() == io::ErrorKind::Interrupted => + { + return Err(error); + } + Err(_) => { + response.replace(502, vec![("Content-Length".into(), "0".into())])?; + return Ok(PreparedBody::from_bytes(Bytes::new())); + } + }; + match outcome { + Outcome::Forward => { + let current = message.response.take().expect("response message"); + response.replace(current.status, current.headers)?; + if let Some(entity) = message.body { + prepared.install_entity(entity); + } + return Ok(prepared); + } + Outcome::Respond(local) => { + drop(message); + drop(prepared); + response.replace(local.status, local.headers)?; + return Ok(PreparedBody::from_bytes(local.body)); + } + Outcome::Abort => { + return Err(io::Error::new( + io::ErrorKind::ConnectionAborted, + "HTTP script aborted exchange", + )); + } + } + } let transaction = Transaction::begin( self.policy.body_budget(), self.policy.rules(), @@ -141,13 +242,68 @@ fn length(body: Body) -> Option { } } +// This wrapper belongs only to PreparedBody's body transfer, never the head. +// Both transfer paths call flush only after successful source/framing reads +// and all body/framing writes. Keep that invariant if intermediate flushes are added. +struct FinalFlushProbe<'a, W> { + writer: &'a mut W, + observed: &'a AtomicBool, + eligible: bool, +} +impl AsyncWrite for FinalFlushProbe<'_, W> { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut *self.writer).poll_write(cx, bytes) + } + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[io::IoSlice<'_>], + ) -> Poll> { + Pin::new(&mut *self.writer).poll_write_vectored(cx, bytes) + } + fn is_write_vectored(&self) -> bool { + self.writer.is_write_vectored() + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.eligible { + self.observed.store(true, Ordering::Release); + } + Pin::new(&mut *self.writer).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut *self.writer).poll_shutdown(cx) + } +} + pub(crate) struct PreparedBody { framing: Body, cursor: Option, prefix: Option, result: Option, + buffered: Option, + origin_replaced: bool, } impl PreparedBody { + pub(crate) fn from_bytes(bytes: Bytes) -> Self { + Self { + framing: Body::Length(bytes.len() as u64), + cursor: Some(Cursor::new(Body::Empty)), + prefix: None, + result: None, + buffered: Some(bytes), + origin_replaced: true, + } + } + pub(crate) fn install_entity(&mut self, entity: body::Entity) { + if entity.changed() { + self.framing = Body::Length(entity.wire().len() as u64); + } + self.buffered = Some(entity.into_wire()); + } fn finalize_headers(&mut self, fields: &mut Fields) { if let Some(mut result) = self.result.take() { result.finalize_headers(fields); @@ -163,8 +319,41 @@ impl PreparedBody { cursor: None, prefix: None, result: None, + buffered: None, + origin_replaced: false, } } + pub(crate) async fn transfer_observing_final_flush< + R: AsyncBufRead + Unpin, + W: AsyncWrite + Unpin, + >( + self, + reader: &mut R, + writer: &mut W, + idle: Duration, + blocklist: &HashSet, + dechunk: bool, + observed: &AtomicBool, + ) -> io::Result<()> { + // Cursor framing is the real source, not the rewritten output length. + // Unknown/generated sources and chunked/trailer paths gain no proof. + let fixed_source = match self.cursor.as_ref() { + Some(cursor) => matches!(cursor.body, Body::Empty | Body::Length(_)), + None => self.buffered.is_none() && self.prefix.is_none() && self.result.is_none(), + }; + let eligible = fixed_source + && !self.origin_replaced + && !dechunk + && matches!(self.framing, Body::Empty | Body::Length(_)); + let mut writer = FinalFlushProbe { + writer, + observed, + eligible, + }; + self.transfer(reader, &mut writer, idle, blocklist, dechunk) + .await + } + pub(crate) async fn transfer( self, reader: &mut R, @@ -173,11 +362,36 @@ impl PreparedBody { blocklist: &HashSet, dechunk: bool, ) -> io::Result<()> { + self.transfer_with_origin(reader, writer, idle, blocklist, dechunk) + .await + .map(|_| ()) + } + pub(crate) async fn transfer_with_origin( + self, + reader: &mut R, + writer: &mut W, + idle: Duration, + blocklist: &HashSet, + dechunk: bool, + ) -> io::Result { let Some(mut cursor) = self.cursor else { - return framing::transfer_body(reader, writer, self.framing, idle, blocklist, dechunk) - .await; + framing::transfer_body(reader, writer, self.framing, idle, blocklist, dechunk).await?; + return Ok(!self.origin_replaced && matches!(self.framing, Body::Length(_))); }; + // A later request script may have changed origin after collection. + // Recheck against the final credential blocklist before any replay. + for (name, _) in &cursor.trailers { + if framing::forbidden_trailer(name, blocklist) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "HTTP trailer became forbidden after rewriting", + )); + } + } let chunked = self.framing == Body::Chunked && !dechunk; + if let Some(bytes) = self.buffered { + send(writer, &bytes, chunked, idle).await?; + } if let Some(prefix) = self.prefix { send(writer, prefix.as_ref(), chunked, idle).await?; // Keep the reservation until write_all actually completes. @@ -191,15 +405,102 @@ impl PreparedBody { } send(writer, &bytes[..count], chunked, idle).await?; } + let consumed = + !self.origin_replaced && cursor.done && matches!(cursor.body, Body::Length(0)); if chunked { framing::write_timed(writer, b"0\r\n", idle).await?; for (name, value) in cursor.trailers { + if framing::forbidden_trailer(&name, blocklist) { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "forbidden HTTP trailer", + )); + } framing::write_timed(writer, format!("{name}: {value}\r\n").as_bytes(), idle) .await?; } framing::write_timed(writer, b"\r\n", idle).await?; } - framing::timeout_io(idle, writer.flush()).await + framing::timeout_io(idle, writer.flush()).await?; + Ok(consumed) + } +} + +/// The cursor reads the wire once and keeps every over-limit prefix for replay. +pub(crate) async fn prepare_shared( + reader: &mut R, + framing: Body, + blocklist: &HashSet, + idle: Duration, + transaction: Option>, + fields: &mut Fields, +) -> io::Result<(PreparedBody, Option)> { + let Some(mut transaction) = transaction else { + return Ok((PreparedBody::original(framing), None)); + }; + let mut cursor = Cursor::new(framing); + let mut bytes = [0u8; framing::COPY_BUFFER]; + loop { + if cursor.done || matches!(cursor.body, Body::Empty | Body::Length(0)) { + let entity = transaction.finish_shared(!cursor.trailers.is_empty(), fields); + let mut prepared = PreparedBody { + framing, + cursor: Some(cursor), + prefix: None, + result: None, + buffered: None, + origin_replaced: false, + }; + prepared.install_entity(entity.clone()); + return Ok((prepared, Some(entity))); + } + let available = transaction.remaining().min(bytes.len()); + if available == 0 { + super::diagnostics::body_bypass( + super::diagnostics::BodyPoint::Collection, + body::Bypass::Size, + ); + return Ok(( + PreparedBody { + framing, + cursor: Some(cursor), + prefix: Some(transaction.into_raw()), + result: None, + buffered: None, + origin_replaced: false, + }, + None, + )); + } + let count = cursor + .read(reader, &mut bytes[..available], idle, blocklist) + .await?; + if count == 0 { + let entity = transaction.finish_shared(!cursor.trailers.is_empty(), fields); + let mut prepared = PreparedBody { + framing, + cursor: Some(cursor), + prefix: None, + result: None, + buffered: None, + origin_replaced: false, + }; + prepared.install_entity(entity.clone()); + return Ok((prepared, Some(entity))); + } + if transaction.push(&bytes[..count]).is_err() { + return Ok(( + PreparedBody { + framing, + cursor: Some(cursor), + prefix: Some(transaction.into_raw()), + result: None, + buffered: None, + origin_replaced: false, + }, + None, + )); + } } } @@ -242,15 +543,23 @@ async fn probe( cursor: Some(cursor), prefix: None, result: Some(result), + buffered: None, + origin_replaced: false, }); } let available = transaction.remaining().min(bytes.len()); if available == 0 { + super::diagnostics::body_bypass( + super::diagnostics::BodyPoint::Collection, + body::Bypass::Size, + ); return Ok(PreparedBody { framing: body, cursor: Some(cursor), prefix: Some(transaction.into_raw()), result: None, + buffered: None, + origin_replaced: false, }); } let count = cursor @@ -263,6 +572,8 @@ async fn probe( cursor: Some(cursor), prefix: None, result: Some(result), + buffered: None, + origin_replaced: false, }); } if transaction.push(&bytes[..count]).is_err() { @@ -271,6 +582,8 @@ async fn probe( cursor: Some(cursor), prefix: Some(transaction.into_raw()), result: None, + buffered: None, + origin_replaced: false, }); } } @@ -367,6 +680,62 @@ impl Cursor { #[cfg(test)] mod tests { use super::*; + + #[cfg(all(unix, feature = "inbound-http"))] + #[forbid(unsafe_code)] + mod shared_collector_mapping_tests { + include!("shared_collector_h1_memory_tests.rs"); + } + + #[cfg(all(unix, feature = "inbound-http"))] + #[forbid(unsafe_code)] + mod shared_collector_c15_gap_tests { + include!("shared_collector_c15_cancel_metadata_memory_tests.rs"); + } + #[tokio::test] + async fn collected_cookie_trailer_cannot_cross_a_later_script_origin_change() { + let budget = body::Budget::default(); + let original = Url::parse("http://a.example/").unwrap(); + let meta = OriginalRequestMeta::new("POST", &vec![]); + let wire = WireBodyMeta::new(&vec![], &meta, Phase::Request, None, None, false); + let transaction = + Transaction::begin_shared(&budget, &[], &original, Phase::Request, &wire, true) + .unwrap(); + let mut reader = b"3\r\nold\r\n0\r\nCookie: old-secret\r\n\r\n".as_slice(); + let mut fields = vec![]; + let (prepared, entity) = prepare_shared( + &mut reader, + Body::Chunked, + &HashSet::new(), + Duration::from_secs(1), + Some(transaction), + &mut fields, + ) + .await + .unwrap(); + assert!( + entity + .as_ref() + .is_some_and(|entity| entity.logical().is_none()) + ); + let mut final_blocklist = HashSet::new(); + final_blocklist.insert("cookie".into()); + let mut sent = Vec::new(); + let error = prepared + .transfer( + &mut reader, + &mut sent, + Duration::from_secs(1), + &final_blocklist, + false, + ) + .await + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::InvalidData); + assert!(sent.is_empty()); + drop(entity); + assert_eq!(budget.used(), 0); + } fn rules() -> Vec { let value: serde_yaml_ng::Value = serde_yaml_ng::from_str("{url: '.', action: response-body-set, value: changed}") diff --git a/src/http_processing/h2.rs b/src/http_processing/h2.rs index 430364f..c94085f 100644 --- a/src/http_processing/h2.rs +++ b/src/http_processing/h2.rs @@ -1,21 +1,26 @@ //! HTTP/2 downstream owner. Every request and upstream driver is polled inline. use super::{ HttpContext, Scheme, - body::{OriginalRequestMeta, Transaction, WireBodyMeta}, + body::{Entity, OriginalRequestMeta, Transaction, WireBodyMeta}, config::checked_url, h2_body::{self, IDLE}, - h2_h1, h2_headers, headers, + h2_h1, h2_headers, h2_reuse, headers, request::{Decision, Target}, rules::Phase, + script_config::BodyMode, + script_message::{ + self, LocalResponse, Message, OriginalSnapshot, Outcome, RequestSnapshot, ResponseSnapshot, + }, }; use crate::{ - dispatch::BoxStream, + dispatch::{BoxStream, HttpTcpPlan}, security::{StandardTlsClient, TlsClientOptions}, session::StreamSession, }; use bytes::Bytes; use futures_util::{StreamExt, future::poll_fn, stream::FuturesUnordered}; use http::{HeaderValue, Method, Request, Response, StatusCode, Version}; +use hyper::body::Body as _; use std::{ future::Future, io, @@ -30,17 +35,48 @@ use tokio::{ }; use tokio_util::sync::CancellationToken; const STREAMS: usize = 8; -const SETUP: Duration = Duration::from_secs(10); +const SETUP: Duration = h2_reuse::SETUP; +enum UpstreamSender<'a> { + OneShot(h2::client::SendRequest), + Shared { + lease: &'a h2_reuse::Lease, + sender: h2::client::SendRequest, + }, +} + +// A valid response may finish before its upload, or survive a late upload +// error. Neither proves that this shared session may admit another request. +// Retire admission on every uncertain exit, including cancellation/unwind; +// the existing lease still owns this response and any sibling exchanges. +struct SharedExchangeGuard<'a> { + lease: &'a h2_reuse::Lease, + completed: bool, +} +impl Drop for SharedExchangeGuard<'_> { + fn drop(&mut self) { + if !self.completed { + self.lease.retire(); + } + } +} struct MessageMeta { original: OriginalRequestMeta, length: Option, asterisk: bool, + script: Option, +} +struct ScriptExchange { + original: OriginalSnapshot, + request: Option, + cancellation: CancellationToken, } struct BodyMessage { phase: Phase, wire: Option, expected: Option, strip_credentials: bool, + scripts: bool, + asterisk: bool, } fn failed() -> io::Error { io::Error::new(io::ErrorKind::ConnectionAborted, "HTTP proxy stream failed") @@ -56,12 +92,12 @@ impl HttpContext { let operation = async { let mut builder = h2::server::Builder::new(); builder - .initial_window_size(32 * 1024) + .initial_window_size(64 * 1024) .initial_connection_window_size(64 * 1024) .header_table_size(0) .max_header_list_size(32 * 1024) .max_frame_size(16 * 1024) - .max_send_buffer_size(16 * 1024) + .max_send_buffer_size(64 * 1024) .max_concurrent_streams(STREAMS as u32) .max_concurrent_reset_streams(16) .max_local_error_reset_streams(Some(16)); @@ -69,6 +105,7 @@ impl HttpContext { .await .map_err(|_| io::ErrorKind::TimedOut)? .map_err(|_| failed())?; + let (sessions, mut upstreams) = h2_reuse::new(); let mut requests = FuturesUnordered::new(); let idle = tokio::time::sleep(IDLE); tokio::pin!(idle); @@ -76,6 +113,9 @@ impl HttpContext { // accept also drives DATA, SETTINGS, WINDOW_UPDATE and resets. // It stays polled while all eight request slots are occupied. tokio::select! {biased; + // Also drive idle sessions and drain ready retirees before + // admitting another request/registered physical owner. + ()=upstreams.progress()=>{}, ()=&mut idle,if requests.is_empty()=>return Ok(()), result=requests.next(),if !requests.is_empty()=>{ let _=result;idle.as_mut().reset(Instant::now()+IDLE); @@ -87,7 +127,7 @@ impl HttpContext { // The ready queue also owns an empty sentinel // with the same future type. Keep its storage // small on every downstream connection. - requests.push(Box::pin(self.h2_request(request,response,session.clone()))); + requests.push(Box::pin(self.h2_request(request,response,session.clone(),cancellation.clone(),&sessions))); } }, Some(Err(_))=>return Err(failed()), @@ -104,13 +144,20 @@ impl HttpContext { request: Request, response: h2::server::SendResponse, session: StreamSession, + cancellation: CancellationToken, + sessions: &h2_reuse::Sessions, ) { let response = ResponseSlot(Arc::new(Mutex::new(ResponseState { response, infos: 0, final_started: false, + upstream_final_received: false, }))); - if self.h2_forward(request, &response, session).await.is_err() { + if self + .h2_forward(request, &response, session, cancellation, sessions) + .await + .is_err() + { response.reset(); } } @@ -119,6 +166,8 @@ impl HttpContext { request: Request, response: &ResponseSlot, session: StreamSession, + cancellation: CancellationToken, + sessions: &h2_reuse::Sessions, ) -> io::Result<()> { if request.method() == Method::CONNECT { return local(response, StatusCode::METHOD_NOT_ALLOWED, None); @@ -127,6 +176,10 @@ impl HttpContext { Ok(length) => length, Err(_) => return local(response, StatusCode::BAD_REQUEST, None), }; + let reusable_original = request.method() != Method::HEAD + && request.method() != Method::CONNECT + && (length.is_some() || request.body().is_end_stream()) + && !request.headers().contains_key("expect"); let original_fields = headers::from_map(request.headers()); let mut original_meta = OriginalRequestMeta::new( request.method().as_str(), @@ -142,7 +195,16 @@ impl HttpContext { Ok(value) => value, Err(_) => return local(response, StatusCode::BAD_REQUEST, None), }; - let target = match self.plan(original, session, Scheme::Https, !asterisk) { + let scripts_selected = self.has_scripts(&original, Phase::Request) + || self.has_scripts(&original, Phase::Response); + let original_snapshot = scripts_selected.then(|| OriginalSnapshot { + url: original.clone(), + method: request.method().as_str().to_owned(), + identity_allowed: original_meta.identity_allowed, + asterisk, + }); + let base_session = session.clone(); + let mut target = match self.plan(original, session, Scheme::Https, !asterisk) { Ok(Decision::Reject) => return local(response, StatusCode::FORBIDDEN, None), Ok(Decision::Redirect { status, url }) => { return local( @@ -175,7 +237,7 @@ impl HttpContext { Phase::Request, &mut parts.headers, ); - let (body, length) = self + let (mut body, mut length, entity) = self .prepare_body( h2_body::Source::h2(body), &target.original, @@ -185,16 +247,153 @@ impl HttpContext { wire, expected: length, strip_credentials: target.strip_origin_credentials, + scripts: original_fields.is_some(), + asterisk, }, ) .await?; + let mut final_request = scripts_selected + .then(|| headers::from_map(&parts.headers)) + .flatten() + .map(|fields| RequestSnapshot { + url: target.url.clone(), + method: parts.method.as_str().to_owned(), + headers: fields, + }); + if self.has_scripts(&target.original, Phase::Request) { + if let Some(request_snapshot) = final_request.take() { + let mut message = Message::request( + original_snapshot + .as_ref() + .expect("selected script context") + .clone(), + request_snapshot, + entity, + original_fields.as_ref().unwrap_or(&Vec::new()), + target.strip_origin_credentials, + ); + match script_message::run( + self.policy(), + &target.original, + &mut message, + &cancellation, + ) + .await + { + Ok(Outcome::Forward) => { + if let Some(entity) = message.body.take().filter(Entity::changed) { + length = Some(entity.wire().len() as u64); + body = h2_body::Source::buffered(entity.into_wire(), None); + } + parts.method = Method::from_bytes(message.request.method.as_bytes()) + .map_err(|_| failed())?; + parts.headers = + headers::to_map(message.request.headers.clone()).ok_or_else(failed)?; + let sticky = message.crossed_origin; + target = self.final_target( + target.original.clone(), + message.request.url.clone(), + base_session, + Scheme::Https, + )?; + // This flag is used for trailers, never a second ordinary + // credential cleanup after explicit script operations. + target.strip_origin_credentials |= sticky; + final_request = Some(message.request); + } + Ok(Outcome::Respond(local_response)) => { + let fully_collected = message.body.is_some(); + drop(message); + if fully_collected { + // The collector already returned the receive owner; + // only obsolete buffered wire bytes remain here. + drop(body); + return send_local(response, local_response).await; + } + // Keep the receive half alive until the final response + // has been committed; dropping it first can reset the + // stream before the client receives its local result. + let result = send_local(response, local_response).await; + drop(body); + return result; + } + Ok(Outcome::Abort) => return Err(failed()), + Err(error) if cancellation.is_cancelled() => return Err(error), + Err(_) => return local(response, StatusCode::BAD_GATEWAY, None), + } + } else { + self.skip_unrepresentable(&target.original, Phase::Request); + } + } let request = Request::from_parts(parts, body); let metadata = MessageMeta { original: original_meta, length, asterisk, + script: original_snapshot.map(|original| ScriptExchange { + original, + request: final_request, + cancellation, + }), }; - let (io, protocol) = self.http_upstream(&target).await?; + let eligible = reusable_original + && request.method() != Method::HEAD + && request.method() != Method::CONNECT + && (metadata.length.is_some() || request.body().is_end_stream()) + && !metadata.asterisk + && !request.headers().contains_key("expect") + && target.url.scheme() == "https" + && target.original.origin() == target.url.origin() + && !target.strip_origin_credentials; + let deadline = Instant::now() + SETUP; + let prepared = if eligible { + timeout_at( + deadline, + self.dispatcher().prepare_http_tcp(target.session.clone()), + ) + .await + .map_err(|_| io::ErrorKind::TimedOut)? + .map_err(|_| failed())? + } else { + None + }; + if let Some(key) = prepared.as_ref().and_then(|plan| plan.reuse_key()).cloned() { + let identity = h2_reuse::Identity::new(key, &target.url); + let acquired = sessions + .acquire(identity, deadline, || { + self.http_upstream_prepared(&target, prepared, deadline) + }) + .await?; + return match acquired { + h2_reuse::Acquired::Shared { lease, sender } => { + let result = self + .h2_exchange( + UpstreamSender::Shared { + lease: &lease, + sender, + }, + request, + response, + target, + metadata, + ) + .await; + // Retire admission on an uncertain exchange, while sibling + // leases retain their real response/driver to completion. + if result.is_err() { + lease.retire(); + } + result + } + h2_reuse::Acquired::H1(io) => { + self.h1_upstream(io, request, response, target, metadata) + .await + } + }; + } + let (io, protocol) = self + .http_upstream_prepared(&target, prepared, deadline) + .await?; if protocol.as_deref() == Some(b"h2") { self.h2_upstream(io, request, response, target, metadata) .await @@ -209,10 +408,41 @@ impl HttpContext { original: &url::Url, headers: &mut http::HeaderMap, message: BodyMessage, - ) -> io::Result<(h2_body::Source, Option)> { + ) -> io::Result<(h2_body::Source, Option, Option)> { let Some(wire) = message.wire else { - return Ok((source, message.expected)); + return Ok((source, message.expected, None)); }; + if message.scripts && self.has_scripts(original, message.phase) { + let Some(mut fields) = headers::from_map(headers) else { + return Ok((source, message.expected, None)); + }; + let script_body = !message.asterisk + && self.policy().scripts().iter().any(|script| { + script.phase == message.phase + && script.matches(original) + && script.body != BodyMode::None + }); + let Ok(transaction) = Transaction::begin_shared( + self.policy().body_budget(), + self.policy().rules(), + original, + message.phase, + &wire, + script_body, + ) else { + return Ok((source, message.expected, None)); + }; + let prepared = h2_body::prepare_shared( + source, + transaction, + message.expected, + message.strip_credentials, + &mut fields, + ) + .await?; + *headers = headers::to_map(fields).ok_or_else(failed)?; + return Ok((prepared.source, prepared.expected, prepared.entity)); + } let Ok(transaction) = Transaction::begin( self.policy().body_budget(), self.policy().rules(), @@ -220,7 +450,7 @@ impl HttpContext { message.phase, &wire, ) else { - return Ok((source, message.expected)); + return Ok((source, message.expected, None)); }; let prepared = h2_body::prepare( source, @@ -230,14 +460,139 @@ impl HttpContext { headers, ) .await?; - Ok((prepared.source, prepared.expected)) + Ok((prepared.source, prepared.expected, None)) } - async fn http_upstream(&self, target: &Target) -> io::Result<(BoxStream, Option>)> { - let deadline = Instant::now() + SETUP; - let stream = timeout_at( - deadline, - self.dispatcher().connect_tcp(target.session.clone()), - ) + fn has_scripts(&self, original: &url::Url, phase: Phase) -> bool { + self.policy() + .scripts() + .iter() + .any(|script| script.phase == phase && script.matches(original)) + } + + fn skip_unrepresentable(&self, original: &url::Url, phase: Phase) { + for script in self + .policy() + .scripts() + .iter() + .filter(|script| script.phase == phase && script.matches(original)) + { + tracing::debug!(target: "vole::http_processing::script", script = %script.name, phase = ?phase, + reason="input-unrepresentable", "HTTP script skipped"); + } + } + + #[allow(clippy::too_many_arguments)] + async fn forward_response( + &self, + mut parts: http::response::Parts, + source: h2_body::Source, + method: &Method, + target: &Target, + original_meta: &OriginalRequestMeta, + script: Option<&ScriptExchange>, + response: &ResponseSlot, + ) -> io::Result<()> { + response.received_final()?; + let expected = h2_headers::response_body(&parts.headers, parts.status, method)?; + let wire_fields = headers::from_map(&parts.headers); + let wire = wire_fields.as_ref().map(|fields| { + WireBodyMeta::new( + fields, + original_meta, + Phase::Response, + Some(parts.status.as_u16()), + expected, + false, + ) + }); + headers::apply_map( + self.policy().rules(), + &target.original, + Phase::Response, + &mut parts.headers, + ); + parts.headers = h2_headers::clean(parts.headers, false, false)?; + let (mut source, mut expected, entity) = self + .prepare_body( + source, + &target.original, + &mut parts.headers, + BodyMessage { + phase: Phase::Response, + wire, + expected, + strip_credentials: false, + scripts: script.is_some_and(|script| script.request.is_some()) + && wire_fields.is_some(), + asterisk: false, + }, + ) + .await?; + if self.has_scripts(&target.original, Phase::Response) { + let script = script.ok_or_else(failed)?; + if let (Some(request), Some(fields), Some(original_fields)) = ( + script.request.as_ref(), + headers::from_map(&parts.headers), + wire_fields.as_ref(), + ) { + let mut message = Message::response( + script.original.clone(), + request.clone(), + ResponseSnapshot { + status: parts.status.as_u16(), + headers: fields, + }, + entity, + original_fields, + ); + match script_message::run( + self.policy(), + &target.original, + &mut message, + &script.cancellation, + ) + .await + { + Ok(Outcome::Forward) => { + if let Some(entity) = message.body.take().filter(Entity::changed) { + expected = Some(entity.wire().len() as u64); + source = h2_body::Source::buffered(entity.into_wire(), None); + } + let result = message.response.take().ok_or_else(failed)?; + parts.status = StatusCode::from_u16(result.status).map_err(|_| failed())?; + parts.headers = headers::to_map(result.headers).ok_or_else(failed)?; + } + Ok(Outcome::Respond(local_response)) => { + drop(message); + drop(source); + return send_local(response, local_response).await; + } + Ok(Outcome::Abort) => return Err(failed()), + Err(error) if script.cancellation.is_cancelled() => return Err(error), + Err(_) => return local(response, StatusCode::BAD_GATEWAY, None), + } + } else { + self.skip_unrepresentable(&target.original, Phase::Response); + } + } + parts.version = Version::HTTP_2; + h2_headers::check(&parts.headers)?; + let downstream = response.final_response(Response::from_parts(parts, ()), false)?; + h2_body::relay(source, downstream, expected, false).await + } + async fn http_upstream_prepared( + &self, + target: &Target, + prepared: Option>, + deadline: Instant, + ) -> io::Result<(BoxStream, Option>)> { + let stream = timeout_at(deadline, async { + if let Some(prepared) = prepared { + prepared.connect().await + } else { + self.dispatcher().connect_tcp(target.session.clone()).await + } + }) .await .map_err(|_| io::ErrorKind::TimedOut)? .map_err(|_| failed())?; @@ -271,150 +626,158 @@ impl HttpContext { target: Target, metadata: MessageMeta, ) -> io::Result<()> { + let (sender, driver) = h2_reuse::handshake(io, Instant::now() + SETUP).await?; + inline_driver( + driver, + self.h2_exchange( + UpstreamSender::OneShot(sender), + request, + response, + target, + metadata, + ), + ) + .await + } + async fn h2_exchange( + &self, + sender: UpstreamSender<'_>, + request: Request, + response: &ResponseSlot, + target: Target, + metadata: MessageMeta, + ) -> io::Result<()> { + let mut shared = match &sender { + UpstreamSender::Shared { lease, .. } => Some(SharedExchangeGuard { + lease, + completed: false, + }), + UpstreamSender::OneShot(_) => None, + }; let MessageMeta { original: original_meta, length, asterisk, + script, } = metadata; - let mut builder = h2::client::Builder::new(); - builder - .initial_window_size(32 * 1024) - .initial_connection_window_size(64 * 1024) - .header_table_size(0) - .max_header_list_size(32 * 1024) - .max_frame_size(16 * 1024) - .max_send_buffer_size(16 * 1024) - .enable_push(false) - .max_concurrent_streams(1); - let (sender, driver) = timeout(SETUP, builder.handshake::<_, Bytes>(io)) - .await - .map_err(|_| io::ErrorKind::TimedOut)? + let (parts, body) = request.into_parts(); + let method = parts.method.clone(); + // Original credentials were removed before request-header actions. + // A second origin cleanup must not erase explicitly supplied ones. + let mut headers = h2_headers::clean(parts.headers, false, true)?; + headers.remove("expect"); + let uri = if asterisk { + http::Uri::builder() + .scheme("https") + .authority(target.logical_destination.authority()) + .path_and_query("*") + .build() + .map_err(|_| failed())? + } else { + target.url.as_str().parse().map_err(|_| failed())? + }; + let mut outgoing = Request::builder() + .method(parts.method) + .uri(uri) + .version(Version::HTTP_2) + .body(()) .map_err(|_| failed())?; - let exchange = Box::pin(async { - let (parts, body) = request.into_parts(); - let method = parts.method.clone(); - // Original credentials were removed before request-header actions. - // A second origin cleanup must not erase explicitly supplied ones. - let mut headers = h2_headers::clean(parts.headers, false, true)?; - headers.remove("expect"); - let uri = if asterisk { - http::Uri::builder() - .scheme("https") - .authority(target.logical_destination.authority()) - .path_and_query("*") - .build() - .map_err(|_| failed())? - } else { - target.url.as_str().parse().map_err(|_| failed())? - }; - let mut outgoing = Request::builder() - .method(parts.method) - .uri(uri) - .version(Version::HTTP_2) - .body(()) - .map_err(|_| failed())?; - *outgoing.headers_mut() = headers; - let mut sender = sender.ready().await.map_err(|_| failed())?; - let (mut incoming, upload) = - sender.send_request(outgoing, false).map_err(|_| failed())?; - let (upload_finished, uploaded) = tokio::sync::oneshot::channel(); - let upload = async move { - let result = - h2_body::relay(body, upload, length, target.strip_origin_credentials).await; + *outgoing.headers_mut() = headers; + let mut sender = match sender { + UpstreamSender::OneShot(sender) => sender.ready().await.map_err(|_| failed())?, + UpstreamSender::Shared { sender, .. } => sender, + }; + let (mut incoming, uploaded, upload) = h2_body::start_request( + &mut sender, + outgoing, + body, + length, + target.strip_origin_credentials, + )?; + let download = async { + let incoming = response_after_upload(uploaded, async { + let mut infos = 0; + loop { + let event = poll_fn(|cx| { + if let Poll::Ready(Some(info)) = incoming.poll_informational(cx) { + return Poll::Ready(info.map(Head::Informational)); + } + Pin::new(&mut incoming) + .poll(cx) + .map(|value| value.map(Head::Final)) + }) + .await + .map_err(|_| failed())?; + match event { + Head::Informational(info) => { + infos += 1; + if infos > 16 { + return Err(failed()); + } + if info.status() != StatusCode::CONTINUE { + let (mut parts, ()) = info.into_parts(); + parts.headers = h2_headers::clean(parts.headers, false, false)?; + response + .informational(Response::from_parts(parts, ())) + .map_err(|_| failed())?; + } + } + Head::Final(incoming) => { + response.received_final()?; + break Ok(incoming); + } + } + } + }) + .await?; + let (parts, body) = incoming.into_parts(); + self.forward_response( + parts, + h2_body::Source::h2(body), + &method, + &target, + &original_meta, + script.as_ref(), + response, + ) + .await + }; + // A complete final response ends this exchange even when the + // client has not finished uploading. Dropping the inline upload + // returns its receive owner; h2 closes that half with NO_ERROR + // after the final response, without blocking sibling streams. + let mut upload_completed = upload.ended_in_headers(); + let result = { + let uploading = async { + let result = upload.run().await; if result.is_ok() { - let _ = upload_finished.send(()); + upload_completed = true; } result }; - let download = async { - let incoming = response_after_upload(uploaded, async { - let mut infos = 0; - loop { - let event = poll_fn(|cx| { - if let Poll::Ready(Some(info)) = incoming.poll_informational(cx) { - return Poll::Ready(info.map(Head::Informational)); - } - Pin::new(&mut incoming) - .poll(cx) - .map(|value| value.map(Head::Final)) - }) - .await - .map_err(|_| failed())?; - match event { - Head::Informational(info) => { - infos += 1; - if infos > 16 { - return Err(failed()); - } - if info.status() != StatusCode::CONTINUE { - let (mut parts, ()) = info.into_parts(); - parts.headers = h2_headers::clean(parts.headers, false, false)?; - response - .informational(Response::from_parts(parts, ())) - .map_err(|_| failed())?; - } - } - Head::Final(response) => break Ok(response), - } - } - }) - .await?; - let (mut parts, body) = incoming.into_parts(); - let expected = h2_headers::response_body(&parts.headers, parts.status, &method)?; - let wire = headers::from_map(&parts.headers).map(|fields| { - WireBodyMeta::new( - &fields, - &original_meta, - Phase::Response, - Some(parts.status.as_u16()), - expected, - false, - ) - }); - headers::apply_map( - self.policy().rules(), - &target.original, - Phase::Response, - &mut parts.headers, - ); - parts.headers = h2_headers::clean(parts.headers, false, false)?; - let (body, expected) = self - .prepare_body( - h2_body::Source::h2(body), - &target.original, - &mut parts.headers, - BodyMessage { - phase: Phase::Response, - wire, - expected, - strip_credentials: false, - }, - ) - .await?; - let downstream = response - .final_response(Response::from_parts(parts, ()), false) - .map_err(|_| failed())?; - h2_body::relay(body, downstream, expected, false).await - }; - // A complete final response ends this exchange even when the - // client has not finished uploading. Dropping the inline upload - // returns its receive owner; h2 closes that half with NO_ERROR - // after the final response, without blocking sibling streams. - tokio::pin!(upload); + tokio::pin!(uploading); tokio::pin!(download); tokio::select! {biased; result=&mut download=>result, - result=&mut upload=>{ - // An early final response may reset the upstream's input - // before its nonempty response has crossed the downstream - // window. Once headers were committed, finish that bounded - // response rather than replacing it with a reset. - if result.is_err() && !response.final_started() { result?; } - download.await + result=&mut uploading=>{ + // Preserve a valid final response after a late upload + // failure, while separately retiring future admission. + #[cfg(test)] + if result.is_err() && response.upstream_final_received() { + completed_post_upload_error_memory_tests::observe_late_upload_error(); + } + if result.is_err() && !response.upstream_final_received() { + result + } else { + download.await + } } } - }); - inline_driver(driver, exchange).await + }; + if let Some(shared) = &mut shared { + shared.completed = upload_completed && result.is_ok(); + } + result } async fn h1_upstream( &self, @@ -428,6 +791,7 @@ impl HttpContext { original: original_meta, length, asterisk, + script, } = metadata; let (mut sender, driver) = timeout( SETUP, @@ -503,41 +867,17 @@ impl HttpContext { if incoming.status() == StatusCode::SWITCHING_PROTOCOLS { return Err(failed()); } - let (mut parts, body) = incoming.into_parts(); - let expected = h2_headers::response_body(&parts.headers, parts.status, &method)?; - let wire = headers::from_map(&parts.headers).map(|fields| { - WireBodyMeta::new( - &fields, - &original_meta, - Phase::Response, - Some(parts.status.as_u16()), - expected, - false, - ) - }); - headers::apply_map( - self.policy().rules(), - &target.original, - Phase::Response, - &mut parts.headers, - ); - parts.headers = h2_headers::clean(parts.headers, false, false)?; - let (body, expected) = self - .prepare_body( - h2_body::Source::h1(body), - &target.original, - &mut parts.headers, - BodyMessage { - phase: Phase::Response, - wire, - expected, - strip_credentials: false, - }, - ) - .await?; - parts.version = Version::HTTP_2; - let downstream = state.final_response(Response::from_parts(parts, ()), false)?; - h2_h1::download(body, downstream, expected).await + let (parts, body) = incoming.into_parts(); + self.forward_response( + parts, + h2_body::Source::h1(body), + &method, + &target, + &original_meta, + script.as_ref(), + &state, + ) + .await }); tokio::select! {biased;()=info_cancel.cancelled()=>Err(failed()),result=inline_driver(driver,exchange)=>result} } @@ -570,8 +910,18 @@ struct ResponseState { response: h2::server::SendResponse, infos: usize, final_started: bool, + upstream_final_received: bool, } impl ResponseSlot { + fn received_final(&self) -> io::Result<()> { + self.0.lock().map_err(|_| failed())?.upstream_final_received = true; + Ok(()) + } + fn upstream_final_received(&self) -> bool { + self.0 + .lock() + .is_ok_and(|state| state.upstream_final_received) + } fn informational(&self, response: Response<()>) -> io::Result<()> { let mut state = self.0.lock().map_err(|_| failed())?; state.infos += 1; @@ -622,6 +972,28 @@ impl ResponseSlot { } } } +async fn send_local(response: &ResponseSlot, result: LocalResponse) -> io::Result<()> { + if response.final_started() { + return Err(failed()); + } + let length = result.body.len() as u64; + let mut message = Response::builder() + .status(result.status) + .body(()) + .map_err(|_| failed())?; + *message.headers_mut() = headers::to_map(result.headers).ok_or_else(failed)?; + let downstream = response.final_response(message, length == 0)?; + if length != 0 { + h2_body::relay( + h2_body::Source::buffered(result.body, None), + downstream, + Some(length), + false, + ) + .await?; + } + Ok(()) +} async fn inline_driver(driver: D, exchange: E) -> io::Result where D: Future>, @@ -683,3 +1055,7 @@ fn original_url(request: &Request) -> io::Result<(url::Url, bool } Ok((url, asterisk)) } + +#[cfg(test)] +#[path = "completed_post_upload_error_memory_tests.rs"] +mod completed_post_upload_error_memory_tests; diff --git a/src/http_processing/h2_body.rs b/src/http_processing/h2_body.rs index 0ea1b6f..d8a2901 100644 --- a/src/http_processing/h2_body.rs +++ b/src/http_processing/h2_body.rs @@ -1,6 +1,6 @@ //! One native frame at a time, with credit returned after bounded forwarding. use super::{ - body::{Bypass, Transaction}, + body::{Bypass, Entity, Transaction}, h2_headers, headers, }; use bytes::Bytes; @@ -57,7 +57,7 @@ impl Source { pending_credit: 0, } } - fn buffered(data: Bytes, trailers: Option) -> Self { + pub(super) fn buffered(data: Bytes, trailers: Option) -> Self { Self { kind: Kind::Buffered { data: Some(data), @@ -69,6 +69,14 @@ impl Source { pending_credit: 0, } } + fn can_end_request_on_headers(&self, expected: Option) -> bool { + // No frame/trailer remains, no receive-credit release can still fail, + // and the same Length::finish check as relay already succeeds. + expected.is_none_or(|length| length == 0) + && self.credit == 0 + && self.pending_credit == 0 + && self.is_end_stream() + } fn release(&mut self) -> io::Result<()> { let credit = std::mem::take(&mut self.credit); if credit != 0 @@ -186,6 +194,73 @@ pub(super) struct Prepared { pub(super) expected: Option, } +pub(super) struct SharedPrepared { + pub(super) source: Source, + pub(super) expected: Option, + pub(super) entity: Option, +} + +pub(super) async fn prepare_shared( + mut source: Source, + mut transaction: Transaction<'_>, + expected: Option, + strip_credentials: bool, + fields: &mut headers::Fields, +) -> io::Result { + let mut length = Length::new(expected); + let mut trailers = None; + while let Some(frame) = timeout( + IDLE, + futures_util::future::poll_fn(|cx| Pin::new(&mut source).poll_frame(cx)), + ) + .await + .map_err(|_| io::ErrorKind::TimedOut)? + { + let frame = frame?; + match frame.into_data() { + Ok(mut data) => { + length.consume(data.len())?; + let count = transaction.remaining().min(data.len()); + let prefix = data.split_to(count); + let result = transaction.push(&prefix); + if result.is_err() || !data.is_empty() { + if result.is_ok() { + super::diagnostics::body_bypass( + super::diagnostics::BodyPoint::Collection, + Bypass::Size, + ); + } + source.rewind(transaction.into_raw().into_bytes(), data)?; + return Ok(SharedPrepared { + source, + expected, + entity: None, + }); + } + } + Err(frame) => { + if let Ok(headers) = frame.into_trailers() { + trailers = Some(h2_headers::trailers(headers, strip_credentials)?); + break; + } + } + } + } + length.finish()?; + let entity = transaction.finish_shared(trailers.is_some(), fields); + let expected = if entity.changed() { + Some(entity.wire().len() as u64) + } else { + expected + }; + let source = Source::buffered(entity.wire().clone(), trailers); + Ok(SharedPrepared { + source, + expected, + entity: Some(entity), + }) +} + pub(super) async fn prepare( mut source: Source, mut transaction: Transaction<'_>, @@ -210,6 +285,12 @@ pub(super) async fn prepare( let prefix = data.split_to(count); let result = transaction.push(&prefix); if result.is_err() || !data.is_empty() { + if result.is_ok() { + super::diagnostics::body_bypass( + super::diagnostics::BodyPoint::Collection, + Bypass::Size, + ); + } source.rewind(transaction.into_raw().into_bytes(), data)?; return Ok(Prepared { source, expected }); } @@ -340,9 +421,89 @@ pub(super) async fn relay( finish(&mut target, None, strip_credentials) } +struct PendingUpload { + source: Source, + target: h2::SendStream, + expected: Option, + strip_credentials: bool, + finished: tokio::sync::oneshot::Sender<()>, +} + +pub(super) struct RequestUpload(Option); +impl RequestUpload { + /// True only when start_request already committed END_STREAM in HEADERS. + pub(super) fn ended_in_headers(&self) -> bool { + self.0.is_none() + } + + pub(super) async fn run(self) -> io::Result<()> { + let Some(upload) = self.0 else { + return Ok(()); + }; + let result = relay( + upload.source, + upload.target, + upload.expected, + upload.strip_credentials, + ) + .await; + if result.is_ok() { + let _ = upload.finished.send(()); + } + result + } +} + +/// Shared by both one-shot and leased upstream H2 exchanges. Only an already +/// ended source may finish in HEADERS; all other uploads keep the old relay. +pub(super) fn start_request( + sender: &mut h2::client::SendRequest, + request: http::Request<()>, + source: Source, + expected: Option, + strip_credentials: bool, +) -> io::Result<( + h2::client::ResponseFuture, + tokio::sync::oneshot::Receiver<()>, + RequestUpload, +)> { + let end_stream = source.can_end_request_on_headers(expected); + let (response, target) = sender.send_request(request, end_stream).map_err(|_| { + io::Error::new(io::ErrorKind::ConnectionAborted, "HTTP proxy stream failed") + })?; + let (finished, uploaded) = tokio::sync::oneshot::channel(); + let pending = if end_stream { + drop(source); + drop(target); + // HEADERS already closed the upload. Start the unchanged response-head + // idle gate now, without waiting for an empty relay future to be polled. + let _ = finished.send(()); + None + } else { + Some(PendingUpload { + source, + target, + expected, + strip_credentials, + finished, + }) + }; + Ok((response, uploaded, RequestUpload(pending))) +} + +#[cfg(any(test, all(target_os = "tvos", feature = "http-diagnostics")))] +#[path = "h2_request_upload_validation.rs"] +pub(super) mod request_upload_validation; + #[cfg(test)] mod tests { use super::*; + + #[cfg(all(unix, feature = "inbound-http"))] + #[forbid(unsafe_code)] + mod shared_collector_mapping_tests { + include!("shared_collector_h2_memory_tests.rs"); + } use crate::http_processing::{ body::{Budget, MAX_BODY, OriginalRequestMeta, WireBodyMeta}, rules::{Phase, RawRule, Rule}, diff --git a/src/http_processing/h2_frame_validation.rs b/src/http_processing/h2_frame_validation.rs new file mode 100644 index 0000000..3f61fcb --- /dev/null +++ b/src/http_processing/h2_frame_validation.rs @@ -0,0 +1,499 @@ +//! Synthetic duplex wire regressions for the official h2 dependency. +//! Exercises actual frames without host peers or production diagnostics. +#![cfg(feature = "inbound-http")] +use bytes::Bytes; +use futures_util::future::poll_fn; +use http::{HeaderMap, HeaderValue, Request, Response}; +use sha2::{Digest, Sha256}; +use std::{ + io, + pin::Pin, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + task::{Context, Poll}, + time::Duration, +}; +use tokio::{ + io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf}, + task::JoinHandle, + time::timeout, +}; +use tokio_util::sync::CancellationToken; + +const LIMIT: Duration = Duration::from_secs(10); +const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; +const PROOF: &str = "x-write-buffer-proof"; +const TRAILER: &str = "x-write-buffer-trailer"; + +fn failure(message: &'static str) -> io::Error { + io::Error::other(message) +} + +#[derive(Default)] +struct Trace { + wire: Mutex>, + owners: AtomicUsize, + short_writes: AtomicUsize, + pending_writes: AtomicUsize, + pending_flushes: AtomicUsize, + completed_flushes: AtomicUsize, +} + +// One fixed non-vectored wrapper, with bounded synthetic wire recording. +struct ShortIo { + io: Arc>, + trace: Arc, + write_pending: bool, + flush_pending: bool, +} +impl ShortIo { + fn new(io: Arc>, trace: &Arc) -> Self { + trace.owners.fetch_add(1, Ordering::AcqRel); + Self { + io, + trace: trace.clone(), + write_pending: true, + flush_pending: true, + } + } +} +impl Drop for ShortIo { + fn drop(&mut self) { + self.trace.owners.fetch_sub(1, Ordering::AcqRel); + } +} +impl AsyncRead for ShortIo { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut *self.io.lock().map_err(|_| failure("IO lock poisoned"))?).poll_read(cx, buf) + } +} +impl AsyncWrite for ShortIo { + fn is_write_vectored(&self) -> bool { + false + } + + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + if bytes.is_empty() { + return Poll::Ready(Ok(0)); + } + if self.write_pending { + self.write_pending = false; + self.trace.pending_writes.fetch_add(1, Ordering::AcqRel); + cx.waker().wake_by_ref(); + return Poll::Pending; // No bytes accepted on Pending. + } + let count = bytes.len().min(37); + let result = { + let mut io = self.io.lock().map_err(|_| failure("IO lock poisoned"))?; + Pin::new(&mut *io).poll_write(cx, &bytes[..count]) + }; + match result { + Poll::Ready(Ok(written)) => { + { + let mut wire = self + .trace + .wire + .lock() + .map_err(|_| failure("wire lock poisoned"))?; + if wire.len() + written > 512 * 1024 { + return Poll::Ready(Err(failure("synthetic wire bound exceeded"))); + } + wire.extend_from_slice(&bytes[..written]); + } + self.trace + .short_writes + .fetch_add(usize::from(written < bytes.len()), Ordering::AcqRel); + self.write_pending = true; + Poll::Ready(Ok(written)) + } + other => other, + } + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if self.flush_pending { + self.flush_pending = false; + self.trace.pending_flushes.fetch_add(1, Ordering::AcqRel); + cx.waker().wake_by_ref(); + return Poll::Pending; + } + let result = { + let mut io = self.io.lock().map_err(|_| failure("IO lock poisoned"))?; + Pin::new(&mut *io).poll_flush(cx) + }; + if matches!(result, Poll::Ready(Ok(()))) { + self.trace.completed_flushes.fetch_add(1, Ordering::AcqRel); + self.flush_pending = true; + } + result + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut *self.io.lock().map_err(|_| failure("IO lock poisoned"))?).poll_shutdown(cx) + } +} + +fn check_proof(headers: &HeaderMap, name: &str, proof: &HeaderValue) -> io::Result<()> { + if headers.get(name).map(HeaderValue::as_bytes) != Some(proof.as_bytes()) { + return Err(failure("complete header/trailer value mismatch")); + } + Ok(()) +} +fn check_payload(actual: &[u8], expected: &[u8]) -> io::Result<()> { + if actual != expected || Sha256::digest(actual).to_vec() != Sha256::digest(expected).to_vec() { + return Err(failure("complete payload or SHA-256 mismatch")); + } + Ok(()) +} +async fn receive( + mut body: h2::RecvStream, + expected: &Bytes, + proof: &HeaderValue, + trailers: bool, +) -> io::Result<()> { + let mut actual = Vec::with_capacity(expected.len()); + while let Some(chunk) = body.data().await { + let chunk = chunk.map_err(io::Error::other)?; + if actual.len() + chunk.len() > expected.len() { + return Err(failure("body too long")); + } + actual.extend_from_slice(&chunk); + body.flow_control() + .release_capacity(chunk.len()) + .map_err(io::Error::other)?; + } + check_payload(&actual, expected)?; + match (trailers, body.trailers().await.map_err(io::Error::other)?) { + (true, Some(fields)) => check_proof(&fields, TRAILER, proof), + (false, None) => Ok(()), + _ => Err(failure("missing or unexpected trailers")), + } +} +async fn send( + body: &mut h2::SendStream, + mut bytes: Bytes, + proof: &HeaderValue, + trailers: bool, +) -> io::Result<()> { + if bytes.is_empty() && !trailers { + body.send_data(Bytes::new(), true) + .map_err(io::Error::other)?; + } + while !bytes.is_empty() { + body.reserve_capacity(bytes.len().min(16 * 1024)); + let available = poll_fn(|cx| body.poll_capacity(cx)) + .await + .ok_or_else(|| failure("send stream closed"))? + .map_err(io::Error::other)?; + if available == 0 { + continue; + } + let count = bytes.len().min(available).min(16 * 1024); + let eos = count == bytes.len() && !trailers; + body.send_data(bytes.split_to(count), eos) + .map_err(io::Error::other)?; + } + if trailers { + let mut fields = HeaderMap::new(); + fields.insert(TRAILER, proof.clone()); + body.send_trailers(fields).map_err(io::Error::other)?; + } + Ok(()) +} + +async fn serve( + io: ShortIo, + expected: Bytes, + proof: HeaderValue, + trailers: bool, + cancel: CancellationToken, +) -> io::Result<()> { + let builder = h2::server::Builder::new(); + let mut connection = tokio::select! { biased; + () = cancel.cancelled() => return Err(failure("server cancelled")), + result = builder.handshake::<_, Bytes>(io) => result.map_err(io::Error::other)?, + }; + let (request, mut response) = tokio::select! { biased; + () = cancel.cancelled() => return Err(failure("server cancelled")), + result = connection.accept() => result.ok_or_else(|| failure("request absent"))?.map_err(io::Error::other)?, + }; + { + let exchange = async { + check_proof(request.headers(), PROOF, &proof)?; + receive(request.into_body(), &expected, &proof, trailers).await?; + let reply = Response::builder() + .status(200) + .header(PROOF, proof.clone()) + .header("content-length", expected.len().to_string()) + .body(()) + .map_err(io::Error::other)?; + let mut upload = response + .send_response(reply, false) + .map_err(io::Error::other)?; + send(&mut upload, expected.clone(), &proof, trailers).await + }; + tokio::pin!(exchange); + tokio::select! { biased; + () = cancel.cancelled() => return Err(failure("server cancelled")), + result = &mut exchange => result?, + _ = connection.accept() => return Err(failure("extra request or early connection close")), + } + } + drop(response); + connection.graceful_shutdown(); + tokio::select! { biased; + () = cancel.cancelled() => Err(failure("server cancelled")), + result = poll_fn(|cx| connection.poll_closed(cx)) => result.map_err(io::Error::other), + } +} + +async fn join_driver( + task: Option>>, + cancel: &CancellationToken, +) -> io::Result<()> { + let Some(mut task) = task else { + return Ok(()); + }; + match timeout(LIMIT, &mut task).await { + Ok(result) => result.map_err(io::Error::other)?, + Err(_) => { + cancel.cancel(); + // Cancellation must be observed and the real future dropped before return. + if timeout(LIMIT, &mut task).await.is_err() { + task.abort(); + let _ = task.await; // Failing cleanup still joins; never detach. + } + Err(failure("driver join timed out")) + } + } +} + +// Parse actual synthetic IO bytes, including all control frames between blocks. +fn check_wire( + wire: &[u8], + client: bool, + expected: &[u8], + large: bool, + trailers: bool, +) -> io::Result<()> { + let mut wire = if client { + wire.strip_prefix(PREFACE) + .ok_or_else(|| failure("missing client preface"))? + } else { + wire + }; + let mut actual = Vec::new(); + let mut blocks = Vec::new(); // encoded bytes, frame count, first HEADERS flags + let mut pending: Option<(usize, usize, u8)> = None; + let mut data_eos = 0; + while !wire.is_empty() { + if wire.len() < 9 { + return Err(failure("partial frame header after join")); + } + let size = + (usize::from(wire[0]) << 16) | (usize::from(wire[1]) << 8) | usize::from(wire[2]); + if size > 16 * 1024 || wire.len() < 9 + size { + return Err(failure("invalid or partial frame after join")); + } + let (kind, flags) = (wire[3], wire[4]); + let id = u32::from_be_bytes([wire[5], wire[6], wire[7], wire[8]]) & 0x7fff_ffff; + let payload = &wire[9..9 + size]; + if pending.is_some() && (kind != 9 || id != 1) { + return Err(failure("interleaved CONTINUATION")); + } + if id == 1 { + match kind { + 1 | 9 => { + let mut block = if kind == 1 { + if flags & (8 | 32) != 0 { + return Err(failure("unexpected HEADERS padding/priority")); + } + (0, 0, flags) + } else { + pending + .take() + .ok_or_else(|| failure("orphan CONTINUATION"))? + }; + block.0 += size; + block.1 += 1; + if flags & 4 != 0 { + blocks.push(block); + } else { + pending = Some(block); + } + } + 0 => { + if flags & 8 != 0 { + return Err(failure("unexpected DATA padding")); + } + actual.extend_from_slice(payload); + if actual.len() > expected.len() { + return Err(failure("wire body too long")); + } + if flags & 1 != 0 { + data_eos += 1; + if actual.len() != expected.len() { + return Err(failure("early DATA EOS")); + } + } + } + _ => {} + } + } + wire = &wire[9 + size..]; + } + if pending.is_some() || blocks.len() != if trailers { 2 } else { 1 } { + return Err(failure("incomplete or unexpected header blocks")); + } + for (index, (size, count, flags)) in blocks.iter().enumerate() { + if (*size > 16 * 1024) != large + || (!large && (*size <= 2048 || *count != 1)) + || (large && *count < 2) + { + return Err(failure("actual header block/CONTINUATION fixture mismatch")); + } + if (flags & 1 != 0) != (trailers && index == 1) { + return Err(failure("HEADERS END_STREAM mismatch")); + } + } + if data_eos != usize::from(!trailers) { + return Err(failure("DATA END_STREAM count mismatch")); + } + check_payload(&actual, expected) +} + +async fn case(body_len: usize, header_len: usize, trailers: bool) -> io::Result<()> { + let expected = Bytes::from( + (0..body_len) + .map(|i| (i.wrapping_mul(131).wrapping_add(i / 251) & 255) as u8) + .collect::>(), + ); + let text = (0..header_len) + .map(|i| 33 + ((i * 73 + i / 29) % 94) as u8) + .collect::>(); + let mut proof = HeaderValue::from_bytes(&text).map_err(io::Error::other)?; + proof.set_sensitive(true); // Preserve a genuinely large encoded block on fresh connections. + let client_trace = Arc::new(Trace::default()); + let server_trace = Arc::new(Trace::default()); + let (client_io, server_io) = tokio::io::duplex(1024); + let client_io = Arc::new(Mutex::new(client_io)); + let server_io = Arc::new(Mutex::new(server_io)); + let client_weak = Arc::downgrade(&client_io); + let server_weak = Arc::downgrade(&server_io); + let cancel = CancellationToken::new(); + let server = Some(tokio::spawn(serve( + ShortIo::new(server_io.clone(), &server_trace), + expected.clone(), + proof.clone(), + trailers, + cancel.clone(), + ))); + let mut client = None; + let mut keepalive = None; + let transfer = timeout(LIMIT, async { + let builder = h2::client::Builder::new(); + let (sender, driver) = builder + .handshake::<_, Bytes>(ShortIo::new(client_io.clone(), &client_trace)) + .await + .map_err(io::Error::other)?; + let stop = cancel.clone(); + client = Some(tokio::spawn(async move { + tokio::select! { biased; + () = stop.cancelled() => Err(failure("client cancelled")), + result = driver => result.map_err(io::Error::other), + } + })); + let mut sender = sender.ready().await.map_err(io::Error::other)?; + let request = Request::builder() + .method("POST") + .uri("https://write-capacity.invalid/probe") + .header(PROOF, proof.clone()) + .header("content-length", expected.len().to_string()) + .body(()) + .map_err(io::Error::other)?; + let (response, mut upload) = sender + .send_request(request, false) + .map_err(io::Error::other)?; + send(&mut upload, expected.clone(), &proof, trailers).await?; + drop(upload); + let response = response.await.map_err(io::Error::other)?; + if response.status() != 200 { + return Err(failure("response status mismatch")); + } + check_proof(response.headers(), PROOF, &proof)?; + receive(response.into_body(), &expected, &proof, trailers).await?; + keepalive = Some(sender); + Ok(()) + }) + .await + .unwrap_or_else(|_| Err(failure("wire exchange timed out"))); + if transfer.is_err() { + cancel.cancel(); + } + let server_done = join_driver(server, &cancel).await; + if server_done.is_err() { + cancel.cancel(); + } + drop(keepalive); + let client_done = join_driver(client, &cancel).await; + cancel.cancel(); + drop(client_io); + drop(server_io); + if client_weak.upgrade().is_some() || server_weak.upgrade().is_some() { + return Err(failure("transport owner survived joined drivers")); + } + // Check every terminal owner after both actual task joins, including error paths. + if client_trace.owners.load(Ordering::Acquire) != 0 + || server_trace.owners.load(Ordering::Acquire) != 0 + { + return Err(failure("IO owner survived joined drivers")); + } + if transfer.is_err() || server_done.is_err() || client_done.is_err() { + return Err(io::Error::other(format!( + "transfer={transfer:?};server={server_done:?};client={client_done:?}" + ))); + } + for (trace, is_client) in [(&client_trace, true), (&server_trace, false)] { + if trace.short_writes.load(Ordering::Acquire) == 0 + || trace.pending_writes.load(Ordering::Acquire) == 0 + || trace.pending_flushes.load(Ordering::Acquire) == 0 + || trace.completed_flushes.load(Ordering::Acquire) == 0 + { + return Err(failure("short/Pending/write/flush path was not exercised")); + } + let wire = trace + .wire + .lock() + .map_err(|_| failure("wire lock poisoned"))?; + check_wire( + &wire, + is_client, + &expected, + header_len > 16 * 1024, + trailers, + )?; + } + Ok(()) +} + +#[tokio::test] +async fn short_pending_headers_and_data_end_stream() { + for length in [0, 64 * 1024] { + let result = case(length, 6000, false).await; + assert!(result.is_ok(), "joined wire case failed: {result:?}"); + } +} + +#[tokio::test] +async fn continuation_headers_64k_data_and_trailers() { + let result = case(64 * 1024, 30_000, true).await; + assert!(result.is_ok(), "joined wire case failed: {result:?}"); +} diff --git a/src/http_processing/h2_h1.rs b/src/http_processing/h2_h1.rs index 5374b6e..c29b0b8 100644 --- a/src/http_processing/h2_h1.rs +++ b/src/http_processing/h2_h1.rs @@ -169,10 +169,3 @@ impl Body for Upload { hint } } -pub(super) async fn download( - body: h2_body::Source, - target: h2::SendStream, - expected: Option, -) -> io::Result<()> { - h2_body::relay(body, target, expected, false).await -} diff --git a/src/http_processing/h2_headers.rs b/src/http_processing/h2_headers.rs index 3463560..ec80dae 100644 --- a/src/http_processing/h2_headers.rs +++ b/src/http_processing/h2_headers.rs @@ -69,9 +69,13 @@ pub(super) fn response_body( if (status.is_informational() || status == StatusCode::NO_CONTENT) && length.is_some() { return Err(invalid()); } + if status == StatusCode::RESET_CONTENT && length.is_some_and(|length| length != 0) { + return Err(invalid()); + } if method == Method::HEAD || status.is_informational() || status == StatusCode::NO_CONTENT + || status == StatusCode::RESET_CONTENT || status == StatusCode::NOT_MODIFIED { Ok(Some(0)) @@ -151,6 +155,29 @@ pub(super) fn trailers( mod tests { use super::*; #[test] + fn reset_content_has_no_entity_and_does_not_reject_head_representation_lengths() { + let mut headers = HeaderMap::new(); + assert_eq!( + response_body(&headers, StatusCode::RESET_CONTENT, &Method::GET).unwrap(), + Some(0) + ); + headers.insert("content-length", "0".parse().unwrap()); + assert_eq!( + response_body(&headers, StatusCode::RESET_CONTENT, &Method::GET).unwrap(), + Some(0) + ); + headers.insert("content-length", "12".parse().unwrap()); + assert!(response_body(&headers, StatusCode::RESET_CONTENT, &Method::GET).is_err()); + assert_eq!( + response_body(&headers, StatusCode::NOT_MODIFIED, &Method::GET).unwrap(), + Some(0) + ); + assert_eq!( + response_body(&headers, StatusCode::OK, &Method::HEAD).unwrap(), + Some(0) + ); + } + #[test] fn h2_headers_and_trailers_are_bounded_before_conversion() { let mut headers = HeaderMap::new(); for _ in 0..101 { diff --git a/src/http_processing/h2_receive_credit_memory_tests.rs b/src/http_processing/h2_receive_credit_memory_tests.rs new file mode 100644 index 0000000..332df41 --- /dev/null +++ b/src/http_processing/h2_receive_credit_memory_tests.rs @@ -0,0 +1,710 @@ +//! Actual Core serve_h2 receive settings and exhausted-connection controls. +//! Duplex only: no listener, TLS acceptance, benchmark qualification or retry. +use super::*; +use futures_util::future::poll_fn; +use std::{ + future::Future, + io::{self, IoSlice}, + pin::Pin, + sync::atomic::{AtomicUsize, Ordering}, + task::{Context, Poll}, +}; +use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf}; +use tokio::time::{Instant, timeout_at}; + +struct CountedIo { + inner: DuplexStream, + live: Arc, + writes: Option>>, + data: Option>, +} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +struct DataSnapshot { + bytes: [usize; 2], + end_streams: u8, +} +struct DataFrames { + preface: usize, + head: [u8; 9], + head_used: usize, + remaining: usize, + data_stream: Option, + data_length: usize, + data_end: bool, + snapshot: DataSnapshot, + error: Option<&'static str>, +} +impl DataFrames { + fn new() -> Self { + Self { + preface: 0, + head: [0; 9], + head_used: 0, + remaining: 0, + data_stream: None, + data_length: 0, + data_end: false, + snapshot: DataSnapshot::default(), + error: None, + } + } + fn record(&mut self, mut bytes: &[u8]) { + const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + while !bytes.is_empty() && self.error.is_none() { + if self.preface < PREFACE.len() { + let count = bytes.len().min(PREFACE.len() - self.preface); + if bytes[..count] != PREFACE[self.preface..self.preface + count] { + self.error = Some("unexpected synthetic client preface"); + return; + } + self.preface += count; + bytes = &bytes[count..]; + continue; + } + if self.head_used < self.head.len() { + let count = bytes.len().min(self.head.len() - self.head_used); + self.head[self.head_used..self.head_used + count].copy_from_slice(&bytes[..count]); + self.head_used += count; + bytes = &bytes[count..]; + if self.head_used != self.head.len() { + continue; + } + self.remaining = + u32::from_be_bytes([0, self.head[0], self.head[1], self.head[2]]) as usize; + if self.remaining > 16 * 1024 { + self.error = Some("synthetic client exceeded the actual peer frame bound"); + return; + } + self.data_stream = None; + self.data_length = 0; + self.data_end = false; + if self.head[3] == 0 { + let stream = + u32::from_be_bytes(self.head[5..9].try_into().unwrap()) & 0x7fff_ffff; + self.data_stream = match stream { + 1 => Some(0), + 3 => Some(1), + _ => { + self.error = Some("unexpected synthetic DATA stream"); + return; + } + }; + if self.head[4] & 8 != 0 { + self.error = Some("unexpected synthetic DATA padding"); + return; + } + self.data_length = self.remaining; + self.data_end = self.head[4] & 1 != 0; + } + } + let count = bytes.len().min(self.remaining); + self.remaining -= count; + bytes = &bytes[count..]; + if self.remaining != 0 { + continue; + } + if let Some(stream) = self.data_stream { + if self.snapshot.end_streams & (1 << stream) != 0 { + self.error = Some("synthetic DATA after original END_STREAM"); + return; + } + let Some(total) = self.snapshot.bytes[stream].checked_add(self.data_length) else { + self.error = Some("synthetic DATA counter overflow"); + return; + }; + if total > 32 * 1024 { + self.error = Some("synthetic original body exceeded its frozen length"); + return; + } + self.snapshot.bytes[stream] = total; + if self.data_end { + self.snapshot.end_streams |= 1 << stream; + } + } + self.head_used = 0; + } + } + fn snapshot(&self) -> io::Result { + self.error + .map_or(Ok(self.snapshot), |message| Err(failed(message))) + } +} +struct ClientData { + frames: Mutex, + changed: tokio::sync::Notify, +} +impl ClientData { + fn new() -> Self { + Self { + frames: Mutex::new(DataFrames::new()), + changed: tokio::sync::Notify::new(), + } + } + fn record(&self, bytes: &[u8]) { + self.frames.lock().unwrap().record(bytes); + self.changed.notify_one(); + } + async fn complete(&self) -> io::Result { + loop { + let changed = self.changed.notified(); + let actual = self.frames.lock().unwrap().snapshot()?; + if actual + == (DataSnapshot { + bytes: [32 * 1024; 2], + end_streams: 3, + }) + { + return Ok(actual); + } + changed.await; + } + } +} +struct WireWrites { + bytes: Vec, + overflow: bool, +} +impl WireWrites { + fn new() -> Self { + Self { + bytes: Vec::with_capacity(4096), + overflow: false, + } + } + fn updates(&self) -> io::Result<(usize, u32)> { + if self.overflow { + return Err(failed("bounded synthetic wire evidence overflow")); + } + let mut offset = 0; + let (mut count, mut total) = (0, 0); + while offset + 9 <= self.bytes.len() { + let head = &self.bytes[offset..offset + 9]; + let length = u32::from_be_bytes([0, head[0], head[1], head[2]]) as usize; + let end = offset + 9 + length; + if end > self.bytes.len() { + return Err(failed("partial synthetic wire evidence")); + } + let stream = u32::from_be_bytes(head[5..9].try_into().unwrap()) & 0x7fff_ffff; + if head[3] == 8 && stream == 0 && length == 4 { + count += 1; + total += u32::from_be_bytes(self.bytes[offset + 9..end].try_into().unwrap()) + & 0x7fff_ffff; + } + offset = end; + } + if offset != self.bytes.len() { + return Err(failed("partial synthetic frame header")); + } + Ok((count, total)) + } +} +impl CountedIo { + fn new(inner: DuplexStream, live: &Arc) -> Self { + live.fetch_add(1, Ordering::AcqRel); + Self { + inner, + live: live.clone(), + writes: None, + data: None, + } + } + fn record_write(&self, bytes: &[u8]) { + if let Some(evidence) = &self.writes { + let mut evidence = evidence.lock().unwrap(); + let record = bytes.len().min(4096 - evidence.bytes.len()); + evidence.bytes.extend_from_slice(&bytes[..record]); + evidence.overflow |= record != bytes.len(); + } + if let Some(data) = &self.data { + data.record(bytes); + } + } +} +impl Drop for CountedIo { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::AcqRel); + } +} +impl AsyncRead for CountedIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.inner).poll_read(cx, out) + } +} +impl AsyncWrite for CountedIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let result = Pin::new(&mut self.inner).poll_write(cx, bytes); + if let Poll::Ready(Ok(written)) = result { + self.record_write(&bytes[..written]); + } + result + } + fn is_write_vectored(&self) -> bool { + self.inner.is_write_vectored() + } + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buffers: &[IoSlice<'_>], + ) -> Poll> { + let result = Pin::new(&mut self.inner).poll_write_vectored(cx, buffers); + if let Poll::Ready(Ok(written)) = result { + let mut remaining = written; + for buffer in buffers { + let count = remaining.min(buffer.len()); + self.record_write(&buffer[..count]); + remaining -= count; + if remaining == 0 { + break; + } + } + if remaining != 0 { + return Poll::Ready(Err(failed("invalid vectored write length"))); + } + } + result + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } +} +fn failed(message: &'static str) -> io::Error { + io::Error::other(message) +} +async fn joined(mut owner: tokio::task::JoinHandle) -> Result { + match timeout(Duration::from_secs(2), &mut owner).await { + Ok(result) => result.map_err(|failure| failure.to_string()), + Err(_) => { + owner.abort(); + let _ = owner.await; + Err("owner timed out and was actually aborted/joined".into()) + } + } +} + +#[tokio::test(flavor = "current_thread")] +async fn counted_client_data_tracks_only_actual_vectored_short_write_prefixes() { + let live = Arc::new(AtomicUsize::new(0)); + let data = Arc::new(ClientData::new()); + let (client, mut peer) = tokio::io::duplex(30); + let mut client = CountedIo::new(client, &live); + client.data = Some(data.clone()); + let preface = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + let frame = raw_h2_frame(0, 1, 1, &[7; 17]); + let slices: [&[u8]; 3] = [preface, &frame[..9], &frame[9..]]; + let total: usize = slices.iter().map(|slice| slice.len()).sum(); + let result = timeout(Duration::from_secs(2), async { + let mut offset = 0; + let mut saw_short = false; + let mut premature = false; + while offset < total { + let mut skipped = offset; + let mut buffers = Vec::with_capacity(3); + for slice in slices { + let count = skipped.min(slice.len()); + skipped -= count; + if count != slice.len() { + buffers.push(IoSlice::new(&slice[count..])); + } + } + let written = client.write_vectored(&buffers).await?; + if written == 0 { + return Err(failed("synthetic vectored write made no progress")); + } + saw_short |= written < total - offset; + offset += written; + // Drain only bytes the real IO accepted, including short prefixes. + let mut drained = vec![0; written]; + peer.read_exact(&mut drained).await?; + let snapshot = data.frames.lock().unwrap().snapshot()?; + if offset < total && snapshot.bytes[0] != 0 { + premature = true; + } + } + Ok::<_, io::Error>(( + saw_short, + premature, + data.frames.lock().unwrap().snapshot()?, + )) + }) + .await; + drop(client); + drop(peer); + assert_eq!(live.load(Ordering::Acquire), 0); + let (short, premature, actual) = result.unwrap().unwrap(); + assert!(short && !premature); + assert_eq!( + actual, + DataSnapshot { + bytes: [17, 0], + end_streams: 1 + } + ); +} +#[derive(Debug, Default)] +struct Advertised { + stream: Option, + concurrent: Option, + frame: Option, +} +async fn read_advertised(client: &mut CountedIo) -> io::Result { + client + .write_all(b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") + .await?; + client.write_all(&raw_h2_frame(4, 0, 0, &[])).await?; + client.flush().await?; + let mut actual = Advertised::default(); + for _ in 0..16 { + let mut head = [0u8; 9]; + client.read_exact(&mut head).await?; + let length = u32::from_be_bytes([0, head[0], head[1], head[2]]) as usize; + if length > 16 * 1024 { + return Err(failed("unexpected initial frame length")); + } + let stream = u32::from_be_bytes(head[5..9].try_into().unwrap()) & 0x7fff_ffff; + let mut payload = vec![0; length]; + client.read_exact(&mut payload).await?; + if head[3] == 4 && head[4] & 1 == 0 && stream == 0 { + if !length.is_multiple_of(6) { + return Err(failed("invalid real SETTINGS payload")); + } + for setting in payload.chunks_exact(6) { + let id = u16::from_be_bytes(setting[..2].try_into().unwrap()); + let value = u32::from_be_bytes(setting[2..].try_into().unwrap()); + match id { + 3 => actual.concurrent = Some(value), + 4 => actual.stream = Some(value), + 5 => actual.frame = Some(value), + _ => {} + } + } + } + if actual.stream.is_some() { + return Ok(actual); + } + } + Err(failed( + "actual server did not advertise bounded receive credit", + )) +} + +#[tokio::test(flavor = "current_thread")] +async fn actual_serve_h2_advertises_64k_stream_without_requiring_initial_connection_update() { + let (context, origin) = prepared(true); + let stop = CancellationToken::new(); + let cancel = stop.clone(); + let live = Arc::new(AtomicUsize::new(0)); + let (client, server) = tokio::io::duplex(8192); + let mut client = CountedIo::new(client, &live); + let mut server = CountedIo::new(server, &live); + let owner = tokio::spawn(async move { context.serve_h2(&mut server, session(), cancel).await }); + let result = timeout(Duration::from_secs(2), read_advertised(&mut client)).await; + stop.cancel(); + drop(client); + let core = joined(owner).await; + origin.join().await; + // All failure/timeout paths have dropped and actually joined their IO owner. + assert!(core.as_ref().is_ok_and(|result| result.is_ok()), "{core:?}"); + assert_eq!(live.load(Ordering::Acquire), 0); + let actual = result + .expect("real server wire observation timed out") + .unwrap(); + assert_eq!(actual.stream, Some(65_536)); + assert_eq!(actual.concurrent, Some(8)); + assert_eq!(actual.frame, Some(16_384)); +} + +struct PendingPlan { + live: Arc, +} +impl Drop for PendingPlan { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::AcqRel); + } +} +struct HeldDispatcher { + live: Arc, + entered: AtomicUsize, + changed: tokio::sync::Notify, + release: CancellationToken, + physical_calls: AtomicUsize, +} +impl HeldDispatcher { + async fn wait_for(&self, expected: usize) { + while self.entered.load(Ordering::Acquire) < expected { + self.changed.notified().await; + } + } +} +#[async_trait] +impl Dispatcher for HeldDispatcher { + async fn prepare_http_tcp( + &self, + _: StreamSession, + ) -> Result>, DispatchError> { + self.live.fetch_add(1, Ordering::AcqRel); + let _owner = PendingPlan { + live: self.live.clone(), + }; + self.entered.fetch_add(1, Ordering::AcqRel); + self.changed.notify_one(); + self.release.cancelled().await; + Err(DispatchError::NotAllowed) + } + async fn connect_tcp(&self, _: StreamSession) -> Result { + self.physical_calls.fetch_add(1, Ordering::AcqRel); + Err(DispatchError::NotAllowed) + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + self.physical_calls.fetch_add(1, Ordering::AcqRel); + Err(DispatchError::NotAllowed) + } +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn actual_serve_h2_shared_64k_connection_credit_still_times_out_at_original_end() { + let (base, origin) = prepared(true); + let held = Arc::new(HeldDispatcher { + live: Arc::new(AtomicUsize::new(0)), + entered: AtomicUsize::new(0), + changed: tokio::sync::Notify::new(), + release: CancellationToken::new(), + physical_calls: AtomicUsize::new(0), + }); + let context = HttpContext::new(base.policy.clone(), held.clone(), base.security.clone()); + let start = Instant::now(); + let active_end = start + Duration::from_secs(60); + // Create the actual Core owner at the original tail slot, avoiding its + // unrelated 30s idle timer during this controlled one-slot experiment. + tokio::time::advance(Duration::from_nanos(59_999_000_000)).await; + let stop = CancellationToken::new(); + let cancel = stop.clone(); + let live = Arc::new(AtomicUsize::new(0)); + let (client, server) = tokio::io::duplex(256 * 1024); + let mut client = CountedIo::new(client, &live); + let data_evidence = Arc::new(ClientData::new()); + client.data = Some(data_evidence.clone()); + let mut server = CountedIo::new(server, &live); + let wire_evidence = Arc::new(Mutex::new(WireWrites::new())); + server.writes = Some(wire_evidence.clone()); + let owner = tokio::spawn(async move { context.serve_h2(&mut server, session(), cancel).await }); + let mut driver = None; + let observed = timeout_at(start + Duration::from_secs(61), async { + let (mut sender, mut connection) = wire::client::handshake(client) + .await + .map_err(|_| failed("client handshake"))?; + let mut ping = connection + .ping_pong() + .ok_or_else(|| failed("client PING handle"))?; + driver = Some(tokio::spawn(connection)); + ping.ping(wire::Ping::opaque()) + .await + .map_err(|_| failed("initial real SETTINGS/PING barrier"))?; + let mut replies = Vec::with_capacity(3); + let mut writers = Vec::with_capacity(3); + let mut submitted = 0usize; + let mut second_grants = [0usize; 2]; + let mut second_grant_count = 0; + for sequence in 0..2 { + sender = sender + .ready() + .await + .map_err(|_| failed("original request ready"))?; + let (reply, mut writer) = sender + .send_request( + Request::builder() + .method("POST") + .uri(format!("https://a.test/connection-credit/{sequence}")) + .header("content-length", 32 * 1024) + .body(()) + .unwrap(), + false, + ) + .map_err(|_| failed("original request headers"))?; + held.wait_for(sequence + 1).await; + let mut offset = 0; + while offset < 32 * 1024 { + if Instant::now() >= active_end { + return Err(failed("prefill crossed original active boundary")); + } + writer.reserve_capacity(32 * 1024 - offset); + let grant = timeout_at(active_end, poll_fn(|cx| writer.poll_capacity(cx))) + .await + .map_err(|_| failed("prefill capacity deadline"))? + .ok_or_else(|| failed("prefill stream closed"))? + .map_err(|_| failed("prefill capacity error"))?; + if grant == 0 { + continue; + } + if sequence == 1 { + if second_grant_count == second_grants.len() { + return Err(failed("unexpected second-body grant count")); + } + second_grants[second_grant_count] = grant; + second_grant_count += 1; + } + let count = grant.min(32 * 1024 - offset); + offset += count; + writer + .send_data( + Bytes::from(vec![7 + sequence as u8; count]), + offset == 32 * 1024, + ) + .map_err(|_| failed("prefill DATA"))?; + submitted += count; + } + replies.push(reply); + writers.push(writer); + } + // PING may overtake queued DATA. First observe complete DATA frames in + // successful client IO writes, then enqueue a fresh PING behind them. + let data_written = timeout_at(active_end, data_evidence.complete()) + .await + .map_err(|_| failed("original DATA wire completion deadline"))??; + timeout_at(active_end, ping.ping(wire::Ping::opaque())) + .await + .map_err(|_| failed("post-DATA PING deadline"))? + .map_err(|_| failed("post-DATA PING barrier"))?; + let updates = wire_evidence.lock().unwrap().updates()?; + sender = sender + .ready() + .await + .map_err(|_| failed("third original request ready"))?; + let (reply, mut writer) = sender + .send_request( + Request::builder() + .method("POST") + .uri("https://a.test/connection-credit/2") + .header("content-length", 65_536) + .body(()) + .unwrap(), + false, + ) + .map_err(|_| failed("third original request headers"))?; + held.wait_for(3).await; + writer.reserve_capacity(8192); + let before = writer.capacity(); + let timed_out = { + let wait = timeout_at(active_end, poll_fn(|cx| writer.poll_capacity(cx))); + tokio::pin!(wait); + let pending = poll_fn(|cx| Poll::Ready(wait.as_mut().poll(cx).is_pending())).await; + if !pending { + return Err(failed("exhausted connection unexpectedly granted DATA")); + } + tokio::time::advance(active_end.saturating_duration_since(Instant::now())).await; + // Drive the real timer wheel tick without changing the 60s deadline. + tokio::time::advance(Duration::from_millis(2)).await; + wait.await.is_err() + }; + let after = writer.capacity(); + replies.push(reply); + writers.push(writer); + let held_before_cancel = held.live.load(Ordering::Acquire); + let core_running = !owner.is_finished(); + let client_running = driver.as_ref().is_some_and(|owner| !owner.is_finished()); + let data_after_wait = data_evidence.frames.lock().unwrap().snapshot()?; + Ok::<_, io::Error>(( + submitted, + before, + after, + timed_out, + Instant::now(), + held.entered.load(Ordering::Acquire), + second_grants, + second_grant_count, + updates, + data_written, + data_after_wait, + held_before_cancel, + core_running, + client_running, + )) + }) + .await; + stop.cancel(); + let core = joined(owner).await; + held.release.cancel(); + let client = match driver { + Some(driver) => Some(joined(driver).await), + None => None, + }; + origin.join().await; + // No assertions before original request/driver/Core ownership is released. + assert!(core.as_ref().is_ok_and(|result| result.is_ok()), "{core:?}"); + assert!( + client.as_ref().is_some_and(|join| join.is_ok()), + "client owner did not join: {client:?}" + ); + // Keep the protocol result distinct: controlled Core cancellation may + // produce an H2/IO error even though the actual owner joined successfully. + let _client_protocol_result = client.unwrap().unwrap(); + assert_eq!(live.load(Ordering::Acquire), 0); + assert_eq!(held.live.load(Ordering::Acquire), 0); + assert_eq!(held.physical_calls.load(Ordering::Acquire), 0); + let ( + submitted, + before, + after, + timed_out, + finished, + entered, + second_grants, + second_grant_count, + updates, + data_written, + data_after_wait, + held_before_cancel, + core_running, + client_running, + ) = observed.unwrap().unwrap(); + assert_eq!( + data_written, + DataSnapshot { + bytes: [32 * 1024; 2], + end_streams: 3 + } + ); + assert_eq!( + data_after_wait, data_written, + "no third-stream DATA or replay" + ); + assert_eq!( + held_before_cancel, 3, + "original Sources remained held at the deadline" + ); + assert!( + core_running && client_running, + "owners must not retire before the original capacity timeout" + ); + assert_eq!(submitted, 65_536); + assert_eq!(second_grant_count, 2); + assert_eq!( + second_grants, + [32_767, 1], + "the last byte still required real connection feedback" + ); + assert_eq!(updates, (1, 1)); + assert_eq!(65_535 + updates.1, 65_536); + assert_eq!((before, after), (0, 0)); + assert!(timed_out && finished >= active_end && finished < start + Duration::from_secs(61)); + assert_eq!(entered, 3, "no request was replayed or invented"); +} + +#[cfg(all(unix, feature = "inbound-http"))] +#[forbid(unsafe_code)] +mod shared_collector_recvstream_tests { + include!("shared_collector_h2_recvstream_memory_test.rs"); +} diff --git a/src/http_processing/h2_request_upload_validation.rs b/src/http_processing/h2_request_upload_validation.rs new file mode 100644 index 0000000..2332b05 --- /dev/null +++ b/src/http_processing/h2_request_upload_validation.rs @@ -0,0 +1,394 @@ +//! Fixed real-duplex request-framing probes; no TLS authentication or sockets. +use super::*; +use crate::http_processing::body_budget::{Budget, BudgetedBytes, WORKSPACE}; +use futures_util::future::poll_fn; +use http::{Request, Response}; +use serde_json::{Value, json}; +use std::{ + future::Future, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, +}; +use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf}; + +const REQUEST: &[u8] = b"\0x\xff"; +const RESPONSE: &[u8] = b"request-framing-proof"; +struct CountedIo { + io: DuplexStream, + live: Arc, +} +impl CountedIo { + fn new(io: DuplexStream, live: &Arc) -> Self { + live.fetch_add(1, Ordering::AcqRel); + Self { + io, + live: live.clone(), + } + } +} +impl Drop for CountedIo { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::AcqRel); + } +} +impl AsyncRead for CountedIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, buf) + } +} +impl AsyncWrite for CountedIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, bytes) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} +fn error(_error: E) -> io::Error { + failed() +} +struct Pair { + sender: h2::client::SendRequest, + client: h2::client::Connection, + server: h2::server::Connection, +} +impl Pair { + async fn new(live: &Arc) -> io::Result { + let (client, server) = tokio::io::duplex(8192); + let (sender, mut client) = h2::client::handshake(CountedIo::new(client, live)) + .await + .map_err(error)?; + let mut handshake = Box::pin(h2::server::handshake(CountedIo::new(server, live))); + let server = tokio::select! {biased; + result=&mut handshake=>result.map_err(error)?, + _=&mut client=>return Err(failed()), + }; + drop(handshake); + Ok(Self { + sender, + client, + server, + }) + } + async fn accept( + &mut self, + ) -> io::Result<(Request, h2::server::SendResponse)> { + poll_fn(|cx| { + if Pin::new(&mut self.client).poll(cx).is_ready() { + return Poll::Ready(Err(failed())); + } + self.server + .poll_accept(cx) + .map(|request| request.ok_or_else(failed)?.map_err(error)) + }) + .await + } + async fn drive(&mut self, work: F) -> io::Result { + tokio::pin!(work); + poll_fn(|cx| { + if let Poll::Ready(result) = work.as_mut().poll(cx) { + return Poll::Ready(Ok(result)); + } + if Pin::new(&mut self.client).poll(cx).is_ready() + || self.server.poll_accept(cx).is_ready() + { + return Poll::Ready(Err(failed())); + } + work.as_mut().poll(cx).map(Ok) + }) + .await + } +} + +#[derive(Clone, Copy)] +enum Input { + Empty, + Data, + Trailers, + InvalidTrailers, + EndedH2, + EmptyPrefix, +} +struct Case { + id: &'static str, + input: Input, + expected: Option, + headers_eos: bool, + expected_error: Option, +} +async fn collect(mut body: h2::RecvStream, expected: &[u8]) -> io::Result> { + let mut offset = 0usize; + while let Some(data) = body.data().await { + let data = data.map_err(error)?; + let end = offset.checked_add(data.len()).ok_or_else(failed)?; + if end > expected.len() || data.as_ref() != &expected[offset..end] { + return Err(failed()); + } + offset = end; + body.flow_control() + .release_capacity(data.len()) + .map_err(error)?; + } + if offset != expected.len() { + return Err(failed()); + } + body.trailers().await.map_err(error) +} +async fn case(case: Case) -> io::Result { + let budget = Budget::default(); + let live = Arc::new(AtomicUsize::new(0)); + let mut pair = Pair::new(&live).await?; + let mut source_pair = None; + let mut source_response = None; + let mut source_reply = None; + let mut last_owner = None; + let result = async { + let source = if matches!(case.input, Input::EndedH2) { + let mut origin = Pair::new(&live).await?; + let (response, upload) = origin + .sender + .send_request( + Request::builder() + .uri("https://source.invalid/empty") + .body(()) + .map_err(error)?, + true, + ) + .map_err(error)?; + drop(upload); + let (request, reply) = origin.accept().await?; + if !request.body().is_end_stream() { + return Err(failed()); + } + source_response = Some(response); + source_reply = Some(reply); + source_pair = Some(origin); + Source::h2(request.into_body()) + } else { + let payload = if matches!(case.input, Input::Data) { + REQUEST + } else { + &[] + }; + let mut owned = + BudgetedBytes::new(&budget, payload.len()).ok_or(io::ErrorKind::OutOfMemory)?; + owned.extend(payload)?; + let bytes = owned.into_bytes(); + last_owner = Some(bytes.clone()); + let trailers = if matches!(case.input, Input::Trailers | Input::InvalidTrailers) { + let mut trailers = HeaderMap::new(); + trailers.insert("x-proof", "kept".parse().map_err(error)?); + if matches!(case.input, Input::InvalidTrailers) { + trailers.insert("authorization", "synthetic".parse().map_err(error)?); + } + Some(trailers) + } else { + None + }; + let mut source = Source::buffered(bytes, trailers); + if matches!(case.input, Input::EmptyPrefix) { + source.prefix = Some(Bytes::new()); + } + source + }; + let request = Request::builder() + .method("POST") + .uri("https://destination.invalid/submit") + .body(()) + .map_err(error)?; + let (response, mut uploaded, upload) = + start_request(&mut pair.sender, request, source, case.expected, true)?; + // Deliberately do not poll RequestUpload yet: the peer can only see + // HEADERS, never a later empty DATA submitted by the relay. + let gate_before = match uploaded.try_recv() { + Ok(()) => true, + Err(tokio::sync::oneshot::error::TryRecvError::Empty) => false, + Err(_) => return Err(failed()), + }; + let (request, mut reply) = pair.accept().await?; + let headers_eos = request.body().is_end_stream(); + if case.expected_error.is_some() { + let result = pair.drive(upload.run()).await?; + let actual_error = result.as_ref().err().map(io::Error::kind); + let gate_after = uploaded.try_recv().is_ok(); + // The real exchange exits on an upload error before a final head + // and drops its response future/receive owners; do not join a + // deliberately unclosed peer upload as if it could complete. + drop(response); + drop(request); + drop(reply); + return Ok(( + headers_eos, + gate_before, + actual_error == case.expected_error && !gate_after, + actual_error, + )); + } + let expected = if matches!(case.input, Input::Data) { + REQUEST + } else { + &[] + }; + let receiving = async { + let trailers = collect(request.into_body(), expected).await?; + let trailers_ok = if matches!(case.input, Input::Trailers) { + trailers.as_ref().is_some_and(|t| { + t.get("x-proof").is_some_and(|v| v == "kept") + && !t.contains_key("authorization") + }) + } else { + trailers.is_none() + }; + if !trailers_ok { + return Err(failed()); + } + let mut body = reply + .send_response( + Response::builder() + .status(200) + .header("content-length", RESPONSE.len()) + .body(()) + .map_err(error)?, + false, + ) + .map_err(error)?; + body.send_data(Bytes::from_static(RESPONSE), true) + .map_err(error)?; + Ok::<_, io::Error>(()) + }; + let download = async { + let response = response.await.map_err(error)?; + if response.status() != 200 { + return Err(failed()); + } + if collect(response.into_body(), RESPONSE).await?.is_some() { + return Err(failed()); + } + Ok::<_, io::Error>(()) + }; + let (upload, receiving, download) = pair + .drive(async { tokio::join!(upload.run(), receiving, download) }) + .await?; + let gate_after = if gate_before { + true + } else { + uploaded.try_recv().is_ok() + }; + let result_ok = upload.is_ok() && receiving.is_ok() && download.is_ok() && gate_after; + Ok::<_, io::Error>((headers_eos, gate_before, result_ok, None)) + } + .await; + drop(source_reply); + drop(source_response); + drop(source_pair); + drop(pair); + let io_released = live.load(Ordering::Acquire) == 0; + let last_owner_available = last_owner.is_some(); + let last_owner_paid = last_owner_available.then(|| budget.reserve(WORKSPACE).is_none()); + drop(last_owner); + let refunded = budget.reserve(WORKSPACE).is_some(); + let (headers_eos, gate_before, result_ok, actual_error) = result?; + Ok( + json!({"id":case.id,"passed":headers_eos==case.headers_eos && gate_before==case.headers_eos && result_ok && io_released && last_owner_paid.is_none_or(|paid|paid) && refunded, + "headersEndStreamBeforeUploadPolled":headers_eos,"expectedHeadersEndStream":case.headers_eos, + "uploadGateReadyBeforeUploadPolled":gate_before,"bodyTrailersOrExpectedErrorCorrect":result_ok, + "errorKind":actual_error.map(|kind|format!("{kind:?}")),"expectedErrorKind":case.expected_error.map(|kind|format!("{kind:?}")), + "ioOwnersReleased":io_released,"lastSharedBytesOwnerAvailable":last_owner_available,"lastSharedBytesOwnerStillPaid":last_owner_paid,"lastBodyOwnerRefunded":refunded}), + ) +} + +pub(in crate::http_processing) async fn probe() -> io::Result { + let cases = [ + Case { + id: "buffered-empty-unknown-length", + input: Input::Empty, + expected: None, + headers_eos: true, + expected_error: None, + }, + Case { + id: "buffered-empty-zero-length", + input: Input::Empty, + expected: Some(0), + headers_eos: true, + expected_error: None, + }, + Case { + id: "native-h2-ended", + input: Input::EndedH2, + expected: None, + headers_eos: true, + expected_error: None, + }, + Case { + id: "nonempty-binary", + input: Input::Data, + expected: Some(REQUEST.len() as u64), + headers_eos: false, + expected_error: None, + }, + Case { + id: "trailers-validation-preserved", + input: Input::Trailers, + expected: Some(0), + headers_eos: false, + expected_error: None, + }, + Case { + id: "invalid-trailers-still-fail", + input: Input::InvalidTrailers, + expected: Some(0), + headers_eos: false, + expected_error: Some(io::ErrorKind::InvalidData), + }, + Case { + id: "empty-prefix-still-relayed", + input: Input::EmptyPrefix, + expected: Some(0), + headers_eos: false, + expected_error: None, + }, + Case { + id: "truncated-length-still-fails", + input: Input::Empty, + expected: Some(1), + headers_eos: false, + expected_error: Some(io::ErrorKind::ConnectionAborted), + }, + ]; + let mut rows = Vec::with_capacity(cases.len()); + for current in cases { + rows.push(case(current).await?); + } + let passed = rows.iter().all(|row| row["passed"] == true); + Ok( + json!({"id":"h2-empty-request-headers-eos","passed":passed,"caseCount":rows.len(),"cases":rows, + "scope":"real duplex H2 and common production start_request/relay; no TLS authentication or network acceptance", + "backgroundTasksSpawned":false,"externalIO":false}), + ) +} + +#[cfg(test)] +mod tests { + #[tokio::test] + async fn ended_request_headers_eos_and_upload_gate_preserve_streaming_trailers_and_failure() { + let result = tokio::time::timeout(std::time::Duration::from_secs(5), super::probe()) + .await + .unwrap() + .unwrap(); + assert_eq!(result["passed"], true, "{result}"); + } +} diff --git a/src/http_processing/h2_reuse.rs b/src/http_processing/h2_reuse.rs new file mode 100644 index 0000000..70fbc75 --- /dev/null +++ b/src/http_processing/h2_reuse.rs @@ -0,0 +1,338 @@ +//! A downstream-local H2 admission slot. Its parent owns every I/O driver. +use crate::dispatch::{BoxStream, HttpTcpReuseKey}; +use bytes::Bytes; +use futures_util::{StreamExt, future::poll_fn, stream::FuturesUnordered}; +use std::{ + future::Future, + io, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + task::Poll, +}; +use tokio::{ + sync::{Mutex, mpsc, oneshot}, + time::{Duration, Instant, timeout_at}, +}; +use tokio_util::sync::CancellationToken; + +pub(super) const SETUP: Duration = Duration::from_secs(10); +pub(super) type Driver = Pin> + Send + 'static>>; +type OwnedDriver = Pin + Send + 'static>>; + +fn failed() -> io::Error { + io::Error::new( + io::ErrorKind::ConnectionAborted, + "HTTP upstream session failed", + ) +} + +pub(super) async fn handshake( + io: BoxStream, + deadline: Instant, +) -> io::Result<(h2::client::SendRequest, Driver)> { + let mut builder = h2::client::Builder::new(); + builder + .initial_window_size(64 * 1024) + .initial_connection_window_size(64 * 1024) + .header_table_size(0) + .max_header_list_size(32 * 1024) + .max_frame_size(16 * 1024) + .max_send_buffer_size(16 * 1024) + .enable_push(false) + // This advertises receive concurrency. Peer SETTINGS / ready() still + // govern our sends; downstream admission remains eight requests. + .max_concurrent_streams(1); + let (sender, driver) = timeout_at(deadline, builder.handshake::<_, Bytes>(io)) + .await + .map_err(|_| io::ErrorKind::TimedOut)? + .map_err(|_| failed())?; + Ok((sender, Box::pin(driver))) +} + +pub(super) struct Identity { + route: HttpTcpReuseKey, + origin: url::Origin, +} +impl Identity { + pub(super) fn new(route: HttpTcpReuseKey, url: &url::Url) -> Self { + Self { + route, + origin: url.origin(), + } + } + fn same(&self, other: &Self) -> bool { + self.route.same(&other.route) && self.origin == other.origin + } +} + +struct State { + retired: AtomicBool, + closed: AtomicBool, + leases: AtomicUsize, + retire_unleased: CancellationToken, +} +impl State { + fn new() -> Arc { + Arc::new(Self { + retired: AtomicBool::new(false), + closed: AtomicBool::new(false), + leases: AtomicUsize::new(0), + retire_unleased: CancellationToken::new(), + }) + } + fn retire(&self) { + // These two atomics form one retirement/last-lease handshake. SeqCst + // excludes both sides missing the other's write under store buffering. + self.retired.store(true, Ordering::SeqCst); + if self.leases.load(Ordering::SeqCst) == 0 { + self.retire_unleased.cancel(); + } + } + fn usable(&self) -> bool { + !self.retired.load(Ordering::SeqCst) && !self.closed.load(Ordering::SeqCst) + } + fn release_lease(&self) { + if self.leases.fetch_sub(1, Ordering::SeqCst) == 1 && self.retired.load(Ordering::SeqCst) { + self.retire_unleased.cancel(); + } + } +} + +struct Provisional(Option>); +impl Drop for Provisional { + fn drop(&mut self) { + if let Some(state) = &self.0 { + state.retire(); + } + } +} +struct DriverEnd { + driver: Option, + state: Arc, +} +impl Drop for DriverEnd { + fn drop(&mut self) { + // Also ordered when the wrapper was never polled: closed means the + // actual I/O owner was destroyed, not merely that cleanup was entered. + drop(self.driver.take()); + self.state.closed.store(true, Ordering::SeqCst); + self.state.retire(); + } +} +struct Registration { + driver: Driver, + state: Arc, + accepted: oneshot::Sender<()>, +} +struct Slot { + identity: Identity, + sender: h2::client::SendRequest, + state: Arc, +} +impl Slot { + async fn admit(&self, deadline: Instant) -> io::Result> { + let result = match timeout_at(deadline, self.sender.clone().ready()).await { + Ok(Ok(sender)) => { + return Ok(Some(Acquired::Shared { + lease: Lease::new(&self.state)?, + sender, + })); + } + // The peer can finish existing streams after GOAWAY. Retire this + // slot before leasing it and let the caller open a replacement. + Ok(Err(error)) if error.is_go_away() && error.is_remote() => Ok(None), + Ok(Err(_)) => Err(failed()), + Err(_) => Err(io::ErrorKind::TimedOut.into()), + }; + self.state.retire(); + result + } +} +impl Drop for Slot { + fn drop(&mut self) { + self.state.retire(); + } +} + +/// The lease is held through complete body relay, not merely send_request. +pub(super) struct Lease { + state: Arc, +} +impl Lease { + fn new(state: &Arc) -> io::Result { + state.leases.fetch_add(1, Ordering::SeqCst); + if !state.usable() { + state.release_lease(); + return Err(failed()); + } + Ok(Self { + state: state.clone(), + }) + } + pub(super) fn retire(&self) { + self.state.retire(); + } +} +impl Drop for Lease { + fn drop(&mut self) { + self.state.release_lease(); + } +} +pub(super) enum Acquired { + Shared { + lease: Lease, + sender: h2::client::SendRequest, + }, + H1(BoxStream), +} + +/// Never escapes this serve_h2's fixed HttpContext/security scope. +pub(super) struct Sessions { + slot: Mutex>, + registrations: mpsc::Sender, +} +/// All registered drivers remain inline in this parent, including while idle. +pub(super) struct Parent { + registrations: mpsc::Receiver, + drivers: FuturesUnordered, +} +pub(super) fn new() -> (Sessions, Parent) { + let (send, receive) = mpsc::channel(1); + ( + Sessions { + slot: Mutex::new(None), + registrations: send, + }, + Parent { + registrations: receive, + drivers: FuturesUnordered::new(), + }, + ) +} +impl Sessions { + /// `open` is the production authenticated StandardTlsClient path. It is + /// lazy: on a hit its already-selected route plan is dropped, not dialed. + pub(super) async fn acquire( + &self, + identity: Identity, + connect_deadline: Instant, + open: F, + ) -> io::Result + where + F: FnOnce() -> O, + O: Future>)>>, + { + let mut slot = timeout_at(connect_deadline, self.slot.lock()) + .await + .map_err(|_| io::ErrorKind::TimedOut)?; + if let Some(current) = slot.as_ref() + && current.identity.same(&identity) + && current.state.usable() + && let Some(acquired) = current.admit(connect_deadline).await? + { + return Ok(acquired); + } + // Drop the root sender immediately. Existing leases keep their stream + // driver until they finish; a silent peer cannot retain an empty one. + drop(slot.take()); + let (io, protocol) = timeout_at(connect_deadline, open()) + .await + .map_err(|_| io::ErrorKind::TimedOut)??; + match protocol.as_deref() { + Some(b"h2") => {} + None | Some(b"http/1.1") => return Ok(Acquired::H1(io)), + Some(_) => return Err(failed()), + } + let deadline = Instant::now() + SETUP; + let (sender, driver) = handshake(io, deadline).await?; + let state = State::new(); + let mut provisional = Provisional(Some(state.clone())); + let (accepted, acknowledgement) = oneshot::channel(); + timeout_at( + deadline, + self.registrations.send(Registration { + driver, + state: state.clone(), + accepted, + }), + ) + .await + .map_err(|_| io::ErrorKind::TimedOut)? + .map_err(|_| failed())?; + timeout_at(deadline, acknowledgement) + .await + .map_err(|_| io::ErrorKind::TimedOut)? + .map_err(|_| failed())?; + if !state.usable() { + return Err(failed()); + } + let current = Slot { + identity, + sender, + state, + }; + let acquired = current.admit(deadline).await?.ok_or_else(failed)?; + *slot = Some(current); + // Only this initial guard must be disarmed; do not mark the published + // slot retired. No fallible operation or await separates publication. + drop(provisional.0.take()); + Ok(acquired) + } +} +impl Parent { + /// Drain completed/signalled retirees before accepting a new registration. + /// This future never locks Sessions: an initializer holds that mutex while + /// waiting for this parent's acknowledgement. + pub(super) async fn progress(&mut self) { + poll_fn(|cx| { + let mut changed = false; + while let Poll::Ready(Some(())) = self.drivers.poll_next_unpin(cx) { + changed = true; + } + if let Poll::Ready(Some(registration)) = self.registrations.poll_recv(cx) { + let Registration { + driver, + state, + accepted, + } = registration; + let end = DriverEnd { + driver: Some(driver), + state: state.clone(), + }; + self.drivers.push(Box::pin(async move { + let mut end = end; + tokio::select! {biased; + ()=state.retire_unleased.cancelled()=>{}, + _=end.driver.as_mut().expect("registered driver owner")=>{}, + } + drop(end); + })); + // Ownership is in FuturesUnordered before sender publication. + let _ = accepted.send(()); + changed = true; + } + if changed { + Poll::Ready(()) + } else { + Poll::Pending + } + }) + .await; + } +} + +#[cfg(any(test, all(target_os = "tvos", feature = "http-diagnostics")))] +#[path = "h2_reuse_validation.rs"] +mod validation; + +#[cfg(all(target_os = "tvos", feature = "http-diagnostics"))] +pub(super) fn validate() -> io::Result { + validation::run() +} + +#[cfg(test)] +#[path = "https_h2_reuse_memory_tests.rs"] +mod integration_tests; diff --git a/src/http_processing/h2_reuse_validation.rs b/src/http_processing/h2_reuse_validation.rs new file mode 100644 index 0000000..017297a --- /dev/null +++ b/src/http_processing/h2_reuse_validation.rs @@ -0,0 +1,753 @@ +//! Fixed duplex-H2 ownership probes. These do not authenticate TLS. +use super::*; +use crate::http_processing::body_budget::{Budget, BudgetedBytes, WORKSPACE}; +use http::{Request, Response}; +use serde_json::{Value, json}; +use std::{sync::Mutex as StdMutex, task::Context}; +use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf}; +use tokio::time::timeout; + +const PAYLOAD: &[u8] = b"owned-h2-body"; +struct CountedIo { + io: DuplexStream, + live: Arc, +} +impl CountedIo { + fn new(io: DuplexStream, live: &Arc) -> Self { + live.fetch_add(1, Ordering::AcqRel); + Self { + io, + live: live.clone(), + } + } +} +impl Drop for CountedIo { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::AcqRel); + } +} +impl AsyncRead for CountedIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, buf) + } +} +impl AsyncWrite for CountedIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, bytes) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} +fn identity() -> Identity { + Identity::new( + HttpTcpReuseKey::new(7_u8), + &"https://memory.invalid/".parse().unwrap(), + ) +} +fn io_error(_error: E) -> io::Error { + failed() +} + +struct Fixture { + client: StdMutex>, + peer: Option, + live_io: Arc, + opens: AtomicUsize, + budget: Budget, + last_slice: Arc>>, + ping: CancellationToken, + pong: CancellationToken, +} +impl Fixture { + fn new() -> Self { + let (client, peer) = tokio::io::duplex(8192); + let live_io = Arc::new(AtomicUsize::new(0)); + Self { + client: StdMutex::new(Some(Box::new(CountedIo::new(client, &live_io)))), + peer: Some(CountedIo::new(peer, &live_io)), + live_io, + opens: AtomicUsize::new(0), + budget: Budget::default(), + last_slice: Arc::new(StdMutex::new(None)), + ping: CancellationToken::new(), + pong: CancellationToken::new(), + } + } + // Only this cfg(test/explicit tvOS suite) factory bypasses TLS. Production + // acquire's factory is StandardTlsClient::connect_negotiated, not this one. + async fn open(&self) -> io::Result<(BoxStream, Option>)> { + self.opens.fetch_add(1, Ordering::AcqRel); + let io = self + .client + .lock() + .map_err(io_error)? + .take() + .ok_or_else(failed)?; + Ok((io, Some(b"h2".to_vec()))) + } + fn peer( + &mut self, + expected: usize, + ) -> impl Future> + Send + 'static { + let io = self.peer.take().unwrap(); + let budget = self.budget.clone(); + let last_slice = self.last_slice.clone(); + let ping = self.ping.clone(); + let pong = self.pong.clone(); + async move { + let mut connection = h2::server::Builder::new() + .initial_window_size(32 * 1024) + .initial_connection_window_size(64 * 1024) + .handshake::<_, Bytes>(io) + .await + .map_err(io_error)?; + let mut pings = connection.ping_pong().ok_or_else(failed)?; + let mut sent_ping = false; + let mut got_pong = false; + let mut accepted = 0; + loop { + tokio::select! {biased; + ()=ping.cancelled(),if !sent_ping=>{ + pings.send_ping(h2::Ping::opaque()).map_err(io_error)?; + sent_ping=true; + }, + result=poll_fn(|cx|pings.poll_pong(cx)),if sent_ping && !got_pong=>{ + result.map_err(io_error)?; got_pong=true; pong.cancel(); + }, + incoming=connection.accept()=>match incoming { + Some(Ok((request,mut response)))=>{ + if request.method()!=http::Method::GET || !request.body().is_end_stream() || accepted>=expected { + return Err(failed()); + } + accepted+=1; + let mut output=BudgetedBytes::new(&budget,PAYLOAD.len()).ok_or(io::ErrorKind::OutOfMemory)?; + output.extend(PAYLOAD)?; + let bytes=output.into_bytes(); + *last_slice.lock().map_err(io_error)?=Some(bytes.slice(..)); + let mut body=response.send_response(Response::builder().header("content-length",PAYLOAD.len()).body(()).map_err(io_error)?,false).map_err(io_error)?; + body.send_data(bytes,true).map_err(io_error)?; + }, + Some(Err(_))|None=>return if accepted==expected {Ok(accepted)} else {Err(failed())}, + } + } + } + } + } +} + +async fn read_response(mut sender: h2::client::SendRequest) -> io::Result<()> { + let (response, _) = sender + .send_request( + Request::builder() + .uri("https://memory.invalid/probe") + .body(()) + .map_err(io_error)?, + true, + ) + .map_err(io_error)?; + let response = response.await.map_err(io_error)?; + if response.status() != http::StatusCode::OK { + return Err(failed()); + } + let mut body = response.into_body(); + let mut offset = 0; + while let Some(bytes) = body.data().await { + let bytes = bytes.map_err(io_error)?; + if offset + bytes.len() > PAYLOAD.len() + || bytes.as_ref() != &PAYLOAD[offset..offset + bytes.len()] + { + return Err(failed()); + } + offset += bytes.len(); + body.flow_control() + .release_capacity(bytes.len()) + .map_err(io_error)?; + } + if offset != PAYLOAD.len() { + return Err(failed()); + } + Ok(()) +} + +async fn shared_idle_retire() -> io::Result { + let mut fixture = Fixture::new(); + let mut peer = Box::pin(fixture.peer(2)); + let (sessions, mut parent) = new(); + let operation = async { + let Acquired::Shared { + lease: first, + sender, + } = sessions + .acquire(identity(), Instant::now() + SETUP, || fixture.open()) + .await? + else { + return Err(failed()); + }; + read_response(sender).await?; + let state = first.state.clone(); + drop(first); + let idle = + state.leases.load(Ordering::Acquire) == 0 && !state.closed.load(Ordering::Acquire); + fixture.ping.cancel(); + fixture.pong.cancelled().await; + let Acquired::Shared { + lease: second, + sender, + } = sessions + .acquire(identity(), Instant::now() + SETUP, || fixture.open()) + .await? + else { + return Err(failed()); + }; + let same = Arc::ptr_eq(&state, &second.state); + read_response(sender).await?; + drop(sessions.slot.lock().await.take()); + let retained = state.retired.load(Ordering::Acquire) + && !state.closed.load(Ordering::Acquire) + && state.leases.load(Ordering::Acquire) == 1 + && fixture.live_io.load(Ordering::Acquire) == 2; + drop(second); + while !state.closed.load(Ordering::Acquire) { + tokio::task::yield_now().await; + } + Ok::<_, io::Error>((idle, same, retained)) + }; + let mut operation = Box::pin(operation); + // Without parent registration polling no sender may escape acquire. + let waiting_for_ack = poll_fn(|cx| Poll::Ready(operation.as_mut().poll(cx).is_pending())).await + && parent.registrations.len() == 1; + let result = loop { + tokio::select! {biased; + ()=parent.progress()=>{}, + result=&mut operation=>break result?, + result=&mut peer=>{let _=result?;return Err(failed());}, + } + }; + drop(operation); + drop(parent); + let accepted = peer.await?; + drop(sessions); + let io_released = fixture.live_io.load(Ordering::Acquire) == 0; + let final_slice_paid = fixture.budget.reserve(WORKSPACE).is_none(); + drop(fixture.last_slice.lock().map_err(io_error)?.take()); + let refunded = fixture.budget.reserve(WORKSPACE).is_some(); + let opens = fixture.opens.load(Ordering::Acquire); + Ok( + json!({"id":"h2-parent-register-idle-retire","passed":waiting_for_ack && result.0 && result.1 && result.2 && accepted==2 && opens==1 && io_released && final_slice_paid && refunded, + "registrationAckRequired":waiting_for_ack,"sameSession":result.1,"idlePingPong":fixture.pong.is_cancelled(),"leaseRetainedAfterEviction":result.2, + "connectionsOpened":opens,"acceptedRequests":accepted,"ioOwnersReleased":io_released,"lastBodySliceStillPaid":final_slice_paid,"lastBodyOwnerRefunded":refunded}), + ) +} + +async fn cancel_active() -> io::Result { + let mut fixture = Fixture::new(); + let mut peer = Box::pin(fixture.peer(1)); + let (sessions, mut parent) = new(); + let headers = CancellationToken::new(); + let state = StdMutex::new(None::>); + let operation = async { + let Acquired::Shared { lease, mut sender } = sessions + .acquire(identity(), Instant::now() + SETUP, || fixture.open()) + .await? + else { + return Err(failed()); + }; + *state.lock().map_err(io_error)? = Some(lease.state.clone()); + let (response, _) = sender + .send_request( + Request::builder() + .uri("https://memory.invalid/cancel") + .body(()) + .map_err(io_error)?, + true, + ) + .map_err(io_error)?; + let incoming = response.await.map_err(io_error)?; + let _body = incoming.into_body(); + headers.cancel(); + // This is the actual pending request future/lease, not a drop counter + // standing in for one. Parent cancellation drops it before the driver. + std::future::pending::<()>().await; + drop(lease); + Ok::<_, io::Error>(()) + }; + let mut operation = Box::pin(operation); + loop { + tokio::select! {biased; + ()=parent.progress()=>{}, + ()=headers.cancelled()=>break, + result=&mut operation=>{result?;return Err(failed());}, + result=&mut peer=>{let _=result?;return Err(failed());}, + } + } + let active = state + .lock() + .map_err(io_error)? + .as_ref() + .is_some_and(|s| s.leases.load(Ordering::Acquire) == 1); + drop(operation); + drop(parent); + let accepted = peer.await?; + drop(sessions); + let lease_released = + state.lock().map_err(io_error)?.as_ref().is_some_and(|s| { + s.leases.load(Ordering::Acquire) == 0 && s.closed.load(Ordering::Acquire) + }); + let io_released = fixture.live_io.load(Ordering::Acquire) == 0; + let final_slice_paid = fixture.budget.reserve(WORKSPACE).is_none(); + drop(fixture.last_slice.lock().map_err(io_error)?.take()); + let refunded = fixture.budget.reserve(WORKSPACE).is_some(); + Ok( + json!({"id":"h2-parent-active-cancel","passed":active && lease_released && accepted==1 && io_released && final_slice_paid && refunded, + "realRequestPending":active,"leaseReleased":lease_released,"ioOwnersReleased":io_released,"lastBodySliceStillPaid":final_slice_paid,"lastBodyOwnerRefunded":refunded}), + ) +} + +async fn probes() -> io::Result { + let rows = vec![ + shared_idle_retire().await?, + cancel_active().await?, + cancel_before_ack().await?, + unsupported_alpn().await?, + downstream_send_capacity().await?, + super::super::h2_body::request_upload_validation::probe().await?, + ]; + let passed = rows.iter().all(|row| row["passed"] == true); + Ok( + json!({"id":"h2-upstream-owner-lifecycle","kind":"h2-memory-owner-group","passed":passed,"probeCount":rows.len(),"probes":rows, + "scope":"private fixed duplex H2 only; shared production register/ack, driver and lease code; no TLS authentication or network acceptance", + "tlsAuthenticationExercised":false,"externalIO":false,"backgroundTasksSpawned":false,"joined":true}), + ) +} +async fn cancel_before_ack() -> io::Result { + let mut fixture = Fixture::new(); + let (sessions, parent) = new(); + let mut body = + BudgetedBytes::new(&fixture.budget, PAYLOAD.len()).ok_or(io::ErrorKind::OutOfMemory)?; + body.extend(PAYLOAD)?; + let body = body.into_bytes(); + let last_slice = body.slice(..); + let operation = async { + let _body_owner = body; + let _result = sessions + .acquire(identity(), Instant::now() + SETUP, || fixture.open()) + .await?; + std::future::pending::<()>().await; + Ok::<_, io::Error>(()) + }; + let mut operation = Box::pin(operation); + let queued = poll_fn(|cx| Poll::Ready(operation.as_mut().poll(cx).is_pending())).await + && parent.registrations.len() == 1; + let body_paid = fixture.budget.reserve(WORKSPACE).is_none(); + drop(operation); + // The not-yet-polled registered driver is still a real I/O owner in the + // parent's channel. Dropping its parent closes it without publication. + drop(parent); + drop(sessions); + drop(fixture.peer.take()); + let io_released = fixture.live_io.load(Ordering::Acquire) == 0; + let last_slice_paid = fixture.budget.reserve(WORKSPACE).is_none(); + drop(last_slice); + let refunded = fixture.budget.reserve(WORKSPACE).is_some(); + Ok( + json!({"id":"h2-parent-cancel-before-register-ack","passed":queued && body_paid && io_released && last_slice_paid && refunded, + "registrationQueuedWithoutPublication":queued,"realBodyOwnerPaid":body_paid,"ioOwnersReleased":io_released,"lastBodySliceStillPaid":last_slice_paid,"lastBodyOwnerRefunded":refunded}), + ) +} +async fn unsupported_alpn() -> io::Result { + let mut fixture = Fixture::new(); + let (sessions, parent) = new(); + let result = sessions + .acquire(identity(), Instant::now() + SETUP, || async { + let (io, _) = fixture.open().await?; + Ok((io, Some(b"not-http".to_vec()))) + }) + .await; + let rejected = + matches!(result,Err(ref error) if error.kind()==io::ErrorKind::ConnectionAborted); + let never_registered = parent.registrations.is_empty() && parent.drivers.is_empty(); + drop(result); + drop(parent); + drop(sessions); + drop(fixture.peer.take()); + let released = fixture.live_io.load(Ordering::Acquire) == 0; + Ok( + json!({"id":"h2-unexpected-alpn-rejected","passed":rejected && never_registered && released,"rejected":rejected,"neverRegistered":never_registered,"ioOwnersReleased":released}), + ) +} +#[cfg(all(target_os = "tvos", feature = "http-diagnostics"))] +pub(super) fn run() -> io::Result { + if tokio::runtime::Handle::try_current().is_ok() { + return Err(io::ErrorKind::WouldBlock.into()); + } + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_time() + .build()?; + let result = runtime.block_on(async { timeout(Duration::from_secs(5), probes()).await }); + drop(runtime); + let mut result = result.map_err(|_| io::ErrorKind::TimedOut)??; + result["runtimeDropped"] = json!(true); + Ok(result) +} + +#[cfg(test)] +mod tests { + #[tokio::test] + async fn h2_reuse_parent_register_idle_ping_retire_and_cancel_keep_real_owners() { + let result = super::timeout(super::Duration::from_secs(5), super::probes()) + .await + .unwrap() + .unwrap(); + assert_eq!(result["passed"], true, "{result}"); + } +} + +// Control fixtures below use real H2 framing/credit and the unchanged business +// send helper. They never invoke TLS or introduce a production input factory. +const SEND_PROBE_BYTES: usize = 64 * 1024; +const PEER_CREDIT: u32 = 128 * 1024; +struct MeteredIo { + io: CountedIo, + activity: Arc, +} +impl AsyncRead for MeteredIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let before = buf.filled().len(); + let result = Pin::new(&mut self.io).poll_read(cx, buf); + if buf.filled().len() != before { + self.activity.fetch_add(1, Ordering::AcqRel); + } + result + } +} +impl AsyncWrite for MeteredIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + data: &[u8], + ) -> Poll> { + let result = Pin::new(&mut self.io).poll_write(cx, data); + if matches!(result,Poll::Ready(Ok(n)) if n>0) { + self.activity.fetch_add(1, Ordering::AcqRel); + } + result + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} +type ProbeClient = h2::client::Connection; +type ProbeServer = h2::server::Connection; +struct SendReceiver { + response: h2::client::ResponseFuture, + body: Option, + received: usize, + frames: usize, + max_frame: usize, + held_credit: usize, + complete: bool, +} +impl SendReceiver { + fn release_credit(&mut self) -> io::Result<()> { + if self.held_credit != 0 { + self.body + .as_mut() + .ok_or_else(failed)? + .flow_control() + .release_capacity(std::mem::take(&mut self.held_credit)) + .map_err(io_error)?; + } + Ok(()) + } + fn poll_available(&mut self, cx: &mut Context<'_>, release: bool) -> io::Result<()> { + if self.body.is_none() { + match Pin::new(&mut self.response).poll(cx) { + Poll::Ready(Ok(response)) => { + if response.status() != http::StatusCode::OK { + return Err(failed()); + } + self.body = Some(response.into_body()); + } + Poll::Ready(Err(_)) => return Err(failed()), + Poll::Pending => return Ok(()), + } + } + let body = self.body.as_mut().ok_or_else(failed)?; + if release && self.held_credit != 0 { + body.flow_control() + .release_capacity(std::mem::take(&mut self.held_credit)) + .map_err(io_error)?; + } + if self.complete { + return Ok(()); + } + loop { + match body.poll_data(cx) { + Poll::Ready(Some(Ok(bytes))) => { + if self.received + bytes.len() > SEND_PROBE_BYTES + || !bytes + .iter() + .enumerate() + .all(|(i, b)| *b == ((self.received + i) % 256) as u8) + { + return Err(failed()); + } + self.received += bytes.len(); + self.frames += 1; + self.max_frame = self.max_frame.max(bytes.len()); + if release { + body.flow_control() + .release_capacity(bytes.len()) + .map_err(io_error)?; + } else { + self.held_credit += bytes.len(); + } + } + Poll::Ready(Some(Err(_))) => return Err(failed()), + Poll::Ready(None) => { + self.complete = true; + return Ok(()); + } + Poll::Pending => return Ok(()), + } + } + } +} +fn poll_send_connections( + client: &mut ProbeClient, + server: &mut ProbeServer, + cx: &mut Context<'_>, +) -> io::Result<()> { + if Pin::new(client).poll(cx).is_ready() || server.poll_accept(cx).is_ready() { + return Err(failed()); + } + Ok(()) +} +async fn settle_send_connections( + client: &mut ProbeClient, + server: &mut ProbeServer, + receiver: &mut SendReceiver, + activity: &AtomicUsize, +) -> io::Result<()> { + // Finite in-memory quiescence passes; an explicit yield replenishes the + // runtime's cooperative budget rather than interpreting its yield as EOF. + for _ in 0..4 { + poll_fn(|cx| { + for _ in 0..32 { + let before = activity.load(Ordering::Acquire); + poll_send_connections(client, server, cx)?; + receiver.poll_available(cx, false)?; + if activity.load(Ordering::Acquire) == before { + return Poll::Ready(Ok(())); + } + } + Poll::Ready(Err(failed())) + }) + .await?; + tokio::task::yield_now().await; + } + Ok(()) +} +async fn send_capacity_case(limit: usize, initial_window: u32) -> io::Result { + let budget = Budget::default(); + let live = Arc::new(AtomicUsize::new(0)); + let activity = Arc::new(AtomicUsize::new(0)); + let (client_io, server_io) = tokio::io::duplex(8192); + let client_io = MeteredIo { + io: CountedIo::new(client_io, &live), + activity: activity.clone(), + }; + let server_io = MeteredIo { + io: CountedIo::new(server_io, &live), + activity: activity.clone(), + }; + let mut client_builder = h2::client::Builder::new(); + client_builder + .initial_window_size(initial_window) + .initial_connection_window_size(PEER_CREDIT) + .header_table_size(0) + .max_frame_size(16 * 1024); + let (sender, mut client) = client_builder + .handshake::<_, Bytes>(client_io) + .await + .map_err(io_error)?; + let mut server_builder = h2::server::Builder::new(); + server_builder + .initial_window_size(32 * 1024) + .initial_connection_window_size(64 * 1024) + .header_table_size(0) + .max_frame_size(16 * 1024) + .max_send_buffer_size(limit); + let mut handshake = Box::pin(server_builder.handshake::<_, Bytes>(server_io)); + let mut server = tokio::select! {biased; + result=&mut handshake=>result.map_err(io_error)?, + _=&mut client=>return Err(failed()), + }; + drop(handshake); + let mut sender = sender.ready().await.map_err(io_error)?; + let (response, _) = sender + .send_request( + Request::builder() + .uri("https://memory.invalid/send-credit") + .body(()) + .map_err(io_error)?, + true, + ) + .map_err(io_error)?; + let (request, mut response_sender) = tokio::select! {biased; + accepted=server.accept()=>accepted.ok_or_else(failed)?.map_err(io_error)?, + _=&mut client=>return Err(failed()), + }; + if !request.body().is_end_stream() { + return Err(failed()); + } + drop(request); + let mut target = response_sender + .send_response( + Response::builder() + .header("content-length", SEND_PROBE_BYTES) + .body(()) + .map_err(io_error)?, + false, + ) + .map_err(io_error)?; + let mut receiver = SendReceiver { + response, + body: None, + received: 0, + frames: 0, + max_frame: 0, + held_credit: 0, + complete: false, + }; + // Drain the actual initial SETTINGS / connection WINDOW_UPDATE before + // pausing this server driver. No DATA has been queued at this point. + settle_send_connections(&mut client, &mut server, &mut receiver, &activity).await?; + let mut pings = client.ping_pong().ok_or_else(failed)?; + pings.send_ping(h2::Ping::opaque()).map_err(io_error)?; + poll_fn(|cx| { + poll_send_connections(&mut client, &mut server, cx)?; + pings + .poll_pong(cx) + .map(|result| result.map(|_| ()).map_err(io_error)) + }) + .await?; + settle_send_connections(&mut client, &mut server, &mut receiver, &activity).await?; + if receiver.body.is_none() || receiver.received != 0 { + return Err(failed()); + } + let mut output = + BudgetedBytes::new(&budget, SEND_PROBE_BYTES).ok_or(io::ErrorKind::OutOfMemory)?; + let block: [u8; 256] = std::array::from_fn(|i| i as u8); + for _ in 0..SEND_PROBE_BYTES / 256 { + output.extend(&block)?; + } + let output = output.into_bytes(); + let last_slice = output.slice(..); + let mut producer = Box::pin(crate::http_processing::h2_body::send_data( + &mut target, + output, + )); + // No server/client poll in this call: only production reserve/poll/send. + let initially_ready = poll_fn(|cx| { + Poll::Ready(match producer.as_mut().poll(cx) { + Poll::Ready(result) => result.map(|_| true), + Poll::Pending => Ok(false), + }) + }) + .await?; + // Resume both real drivers, but keep the producer itself paused; received + // bytes are exactly the prefix that was queued during that one manual poll. + settle_send_connections(&mut client, &mut server, &mut receiver, &activity).await?; + let prefix = receiver.received; + let prefix_frames = receiver.frames; + let expected_prefix = (initial_window as usize).min(limit).min(SEND_PROBE_BYTES); + let ready_expected = expected_prefix == SEND_PROBE_BYTES; + let prefix_correct = + prefix == expected_prefix && prefix_frames == expected_prefix.div_ceil(16 * 1024); + // Grow low/zero credit via the real public SETTINGS path, then drain the + // same producer future and original body; there is no replay/reconstruction. + if initial_window < PEER_CREDIT { + client + .set_initial_window_size(PEER_CREDIT) + .map_err(io_error)?; + } + receiver.release_credit()?; + if !initially_ready { + poll_fn(|cx| { + poll_send_connections(&mut client, &mut server, cx)?; + receiver.poll_available(cx, true)?; + producer.as_mut().poll(cx) + }) + .await?; + } + drop(producer); + crate::http_processing::h2_body::finish(&mut target, None, false)?; + poll_fn(|cx| { + poll_send_connections(&mut client, &mut server, cx)?; + receiver.poll_available(cx, true)?; + if receiver.complete { + Poll::Ready(Ok::<_, io::Error>(())) + } else { + Poll::Pending + } + }) + .await?; + let received = receiver.received; + let max_frame = receiver.max_frame; + let full = received == SEND_PROBE_BYTES && receiver.complete && max_frame <= 16 * 1024; + drop(receiver); + drop(target); + drop(response_sender); + drop(sender); + drop(pings); + drop(server); + drop(client); + let io_released = live.load(Ordering::Acquire) == 0; + let last_paid = budget.reserve(WORKSPACE).is_none(); + drop(last_slice); + let refunded = budget.reserve(WORKSPACE).is_some(); + Ok( + json!({"sendQueueBytes":limit,"initialPeerStreamWindowBytes":initial_window,"peerConnectionWindowBytes":PEER_CREDIT, + "pausedProducerReady":initially_ready,"pausedPrefixBytes":prefix,"pausedPrefixFrames":prefix_frames,"expectedPrefixBytes":expected_prefix, + "controlPingPong":true,"fullBodyBytesVerified":received,"maxDataFrameBytes":max_frame,"maxDataFrameAtMost16KiB":max_frame<=16*1024, + "ioOwnersReleased":io_released,"lastBodySliceStillPaid":last_paid,"lastBodyOwnerRefunded":refunded, + "passed":initially_ready==ready_expected && prefix_correct && full && io_released && last_paid && refunded}), + ) +} +async fn downstream_send_capacity() -> io::Result { + let mut variants = Vec::new(); + for (limit, window) in [ + (16 * 1024, PEER_CREDIT), + (64 * 1024, PEER_CREDIT), + (64 * 1024, 0), + (64 * 1024, 8 * 1024), + ] { + variants.push(send_capacity_case(limit, window).await?); + } + let passed = variants.iter().all(|row| row["passed"] == true); + Ok( + json!({"id":"h2-downstream-send-capacity","passed":passed,"variantCount":variants.len(),"variants":variants, + "scope":"real duplex H2 control queues16/64 and production h2_body::send_data; no TLS; no production builder introspection", + "backgroundTasksSpawned":false,"joined":true}), + ) +} diff --git a/src/http_processing/h2_tests.rs b/src/http_processing/h2_tests.rs index 7ed804d..8ea2aea 100644 --- a/src/http_processing/h2_tests.rs +++ b/src/http_processing/h2_tests.rs @@ -19,6 +19,363 @@ use tokio::{ use tokio_util::sync::CancellationToken; const PAYLOAD: usize = 96 * 1024; +#[path = "h2_receive_credit_memory_tests.rs"] +mod receive_credit_memory_tests; + +#[cfg(target_vendor = "apple")] +async fn script_memory_response( + context: HttpContext, + request: Request<()>, + payload: Bytes, +) -> Response> { + let cancel = CancellationToken::new(); + let stop = cancel.clone(); + let (client, mut server) = tokio::io::duplex(8192); + let worker = tokio::spawn(async move { + context + .serve_h2(&mut server, session(), stop) + .await + .unwrap(); + }); + let (mut sender, connection) = wire::client::handshake(client).await.unwrap(); + let driver = tokio::spawn(connection); + let (response, mut upload) = sender.send_request(request, payload.is_empty()).unwrap(); + let sending = async { + if !payload.is_empty() { + super::h2_body::send_data(&mut upload, payload) + .await + .unwrap(); + upload.send_data(Bytes::new(), true).unwrap(); + } + }; + let receiving = async { + let response = response.await.unwrap(); + let (parts, mut body) = response.into_parts(); + let mut bytes = Vec::new(); + while let Some(frame) = body.data().await { + let frame = frame.unwrap(); + body.flow_control().release_capacity(frame.len()).unwrap(); + bytes.extend_from_slice(&frame); + } + Response::from_parts(parts, bytes) + }; + let (_, response) = timeout(Duration::from_secs(5), async { + tokio::join!(sending, receiving) + }) + .await + .unwrap(); + cancel.cancel(); + timeout(Duration::from_secs(1), worker) + .await + .unwrap() + .unwrap(); + drop(sender); + driver.abort(); + let _ = driver.await; + response +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn h2_scripts_only_local_response_skips_upstream_and_response_hooks() { + let scripts = r#" +http-scripts: + enabled: true + scripts: + - name: local + phase: request + url: https://a.test/local + match: exact + source: 'function rewrite(input) { return {type:"respond",status:201,headers:[{name:"Set-Cookie",value:"a=1"},{name:"Set-Cookie",value:"b=2"}],body:{kind:"bytes",data:Uint8Array.from([1,2,3])}}; }' + - name: unreachable-request + phase: request + url: https://a.test/local + match: exact + source: 'function rewrite(input) { return {type:"abort"}; }' + - name: unreachable-response + phase: response + url: https://a.test/local + match: exact + source: 'function rewrite(input) { return {type:"abort"}; }' +"#; + let (context, origin) = prepared_origin_rules(true, false, false, OriginMode::None, scripts); + let response = script_memory_response( + context, + Request::builder() + .uri("https://a.test/local") + .body(()) + .unwrap(), + Bytes::new(), + ) + .await; + assert_eq!(response.status(), StatusCode::CREATED); + assert_eq!(response.body(), &[1, 2, 3]); + assert_eq!(response.headers().get_all("set-cookie").iter().count(), 2); + assert!(origin.sessions.lock().unwrap().is_empty()); + origin.join().await; +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn h2_script_local_response_preserves_unfinished_upload_and_sibling_stream() { + let settings = r#" +http-scripts: + enabled: true + scripts: + - name: local + phase: request + url: https://a.test/local + match: exact + source: 'function rewrite(input) { return {type:"respond",status:201,body:{kind:"text",data:"local"}}; }' +"#; + let (context, origin) = prepared_origin_rules(true, false, false, OriginMode::None, settings); + let cancel = CancellationToken::new(); + let stop = cancel.clone(); + let (client, mut server) = tokio::io::duplex(8192); + let worker = tokio::spawn(async move { + context + .serve_h2(&mut server, session(), stop) + .await + .unwrap(); + }); + let (mut sender, connection) = wire::client::handshake(client).await.unwrap(); + let driver = tokio::spawn(connection); + let (first, mut unfinished) = sender + .send_request( + Request::builder() + .method("POST") + .uri("https://a.test/local") + .header("content-length", 100) + .body(()) + .unwrap(), + false, + ) + .unwrap(); + unfinished + .send_data(Bytes::from_static(b"part"), false) + .unwrap(); + for response in [Some(first), None] { + let response = if let Some(response) = response { + response + } else { + sender = sender.ready().await.unwrap(); + sender + .send_request( + Request::builder() + .uri("https://a.test/local") + .body(()) + .unwrap(), + true, + ) + .unwrap() + .0 + }; + let response = timeout(Duration::from_secs(2), response) + .await + .unwrap() + .unwrap(); + assert_eq!(response.status(), StatusCode::CREATED); + let mut body = response.into_body(); + let mut bytes = Vec::new(); + while let Some(frame) = timeout(Duration::from_secs(2), body.data()).await.unwrap() { + let frame = frame.unwrap(); + body.flow_control().release_capacity(frame.len()).unwrap(); + bytes.extend_from_slice(&frame); + } + assert_eq!(bytes, b"local"); + } + assert!(origin.sessions.lock().unwrap().is_empty()); + drop(unfinished); + cancel.cancel(); + timeout(Duration::from_secs(1), worker) + .await + .unwrap() + .unwrap(); + drop(sender); + driver.abort(); + let _ = driver.await; + origin.join().await; +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn h2_scripts_mix_native_results_u0_selection_and_per_call_rollback() { + let settings = r#" +rewrite: + enabled: true + rules: + - {url: 'https://a.test/upload', match: exact, action: replace, replacement: 'https://b.test/rewritten'} + - {url: 'https://a.test/upload', match: exact, action: request-header-set, header: X-Request, value: rewritten} + - {url: 'https://a.test/upload', match: exact, action: request-header-set, header: Authorization, value: 'Bearer explicit'} + - {url: 'https://a.test/upload', match: exact, action: request-header-set, header: Cookie, value: 'new=explicit'} + - {url: 'https://a.test/upload', match: exact, action: request-body-replace, search: old, replacement: new} + - {url: 'https://a.test/upload', match: exact, action: response-header-remove, header: Server} + - {url: 'https://a.test/upload', match: exact, action: response-body-json-patch, patch: [{op: replace, path: /token, value: native}]} +http-scripts: + enabled: true + scripts: + - name: request-view + phase: request + url: https://a.test/upload + match: exact + body: text + source: 'function rewrite(input) { if (input.request.url !== "https://b.test/rewritten" || input.body.data !== "new request") { return {type:"abort"}; } return {type:"modify",headers:[{op:"set",name:"x-js",values:["accepted"]}]}; }' + - name: invalid-request + phase: request + url: https://a.test/upload + match: exact + source: 'function rewrite(input) { return {type:"modify",url:"https://invalid host/",headers:[{op:"remove",name:"authorization"}]}; }' + - name: effective-url-is-not-selector + phase: request + url: https://b.test/rewritten + match: exact + source: 'function rewrite(input) { return {type:"abort"}; }' + - name: response-body + phase: response + url: https://a.test/upload + match: exact + body: text + source: 'function rewrite(input) { if (input.request.url !== "https://b.test/rewritten" || input.original.url !== "https://a.test/upload") { return {type:"abort"}; } let value=JSON.parse(input.body.data); if (value.token !== "native") { return {type:"abort"}; } value.token="script"; return {type:"modify",status:201,headers:[{op:"add",name:"set-cookie",values:["a=1","b=2"]}],body:{kind:"text",data:JSON.stringify(value)}}; }' + - name: invalid-response + phase: response + url: https://a.test/upload + match: exact + source: 'function rewrite(input) { return {type:"modify",status:204,headers:[{op:"remove",name:"set-cookie"}]}; }' +"#; + for upstream_h2 in [true, false] { + let (context, origin) = + prepared_origin_rules(upstream_h2, false, false, OriginMode::Rewrite, settings); + let response = script_memory_response( + context, + Request::builder() + .method("POST") + .uri("https://a.test/upload") + .header("content-length", 11) + .header("authorization", "original") + .header("cookie", "old=original") + .body(()) + .unwrap(), + Bytes::from_static(b"old request"), + ) + .await; + assert_eq!(response.status(), StatusCode::CREATED); + assert!(!response.headers().contains_key("server")); + assert_eq!(response.headers().get_all("set-cookie").iter().count(), 2); + assert_eq!( + serde_json::from_slice::(response.body()).unwrap(), + serde_json::json!({"ads":[1],"token":"script"}) + ); + assert_eq!(origin.received.lock().unwrap()[0], b"new request"); + assert_eq!( + origin.sessions.lock().unwrap()[0].destination, + Destination::domain("b.test", 443).unwrap() + ); + origin.join().await; + } +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn h2_scripts_do_not_erase_obs_text_to_make_an_input_snapshot() { + let settings = r#" +http-scripts: + enabled: true + scripts: + - name: should-skip + phase: request + url: https://a.test/upload + match: exact + source: 'function rewrite(input) { return {type:"respond",status:201}; }' + - name: response-must-also-have-representable-request + phase: response + url: https://a.test/upload + match: exact + source: 'function rewrite(input) { return {type:"abort"}; }' +"#; + let (context, origin) = prepared_origin_rules(true, false, false, OriginMode::None, settings); + let mut request = Request::builder() + .method("POST") + .uri("https://a.test/upload") + .header("content-length", PAYLOAD) + .body(()) + .unwrap(); + request + .headers_mut() + .insert("x-opaque", http::HeaderValue::from_bytes(&[0xff]).unwrap()); + let response = script_memory_response(context, request, Bytes::from(vec![7; PAYLOAD])).await; + assert_eq!(response.status(), StatusCode::OK); + assert_eq!(response.body(), &vec![9; PAYLOAD]); + assert_eq!(origin.received.lock().unwrap()[0], vec![7; PAYLOAD]); + origin.join().await; +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn h2_script_body_collection_preserves_early_response_while_upload_is_unfinished() { + let settings = r#" +http-scripts: + enabled: true + scripts: + - name: complete-response-only + phase: response + url: https://a.test/upload + match: exact + body: bytes + source: 'function rewrite(input) { if (input.body.data.length !== 98304) { return {type:"abort"}; } return {type:"modify",headers:[{op:"set",name:"x-js-complete",values:["yes"]}]}; }' +"#; + for upstream_h2 in [true, false] { + let (context, origin) = + prepared_origin_rules(upstream_h2, true, false, OriginMode::None, settings); + let cancel = CancellationToken::new(); + let stop = cancel.clone(); + let (client, mut server) = tokio::io::duplex(8192); + let worker = tokio::spawn(async move { + context + .serve_h2(&mut server, session(), stop) + .await + .unwrap(); + }); + let (mut sender, connection) = wire::client::handshake(client).await.unwrap(); + let driver = tokio::spawn(connection); + let (response, mut upload) = sender + .send_request( + Request::builder() + .method("POST") + .uri("https://a.test/upload") + .header("content-length", PAYLOAD) + .body(()) + .unwrap(), + false, + ) + .unwrap(); + upload + .send_data(Bytes::from(vec![7; PAYLOAD / 2]), false) + .unwrap(); + let response = timeout(Duration::from_secs(3), response) + .await + .unwrap() + .unwrap(); + assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE); + assert_eq!(response.headers()["x-js-complete"], "yes"); + timeout( + Duration::from_secs(3), + require_early_body(response.into_body()), + ) + .await + .unwrap(); + drop(upload); + cancel.cancel(); + timeout(Duration::from_secs(1), worker) + .await + .unwrap() + .unwrap(); + drop(sender); + driver.abort(); + let _ = driver.await; + origin.join().await; + } +} + #[tokio::test] async fn h2_rewrite_stages_use_original_url_for_h2_and_h1_origins() { let rules = r#" diff --git a/src/http_processing/https_h1_reuse_memory_tests.rs b/src/http_processing/https_h1_reuse_memory_tests.rs new file mode 100644 index 0000000..c04e881 --- /dev/null +++ b/src/http_processing/https_h1_reuse_memory_tests.rs @@ -0,0 +1,912 @@ +//! Real upstream TLS over duplex IO, entered after downstream TLS decryption. +//! These tests exercise `serve_h1(Scheme::Https)`, not the full MITM handshake. +//! All identities are generated in memory; no sockets, DNS or files are used. +#[cfg(feature = "sing-mux")] +#[path = "https_h1_sing_mux_reuse_memory_tests.rs"] +mod sing_mux_reuse; + +#[cfg(feature = "outbound-shadowsocks")] +#[path = "https_h1_ss_obfs_reuse_memory_tests.rs"] +mod ss_obfs_reuse; + +#[cfg(feature = "outbound-shadowsocks")] +#[path = "https_h1_ss_v2ray_mux_reuse_memory_tests.rs"] +mod ss_v2ray_mux_reuse; + +#[cfg(feature = "outbound-vmess")] +#[path = "https_h1_vmess_http_cover_reuse_memory_tests.rs"] +mod vmess_http_cover_reuse; + +use crate::{ + dispatch::{ + BoxStream, DatagramTransport, DispatchError, Dispatcher, HttpTcpPlan, HttpTcpReuseKey, + observe_handshakes_with_stats, observe_sessions_with_stats, + }, + http_processing::{ + HttpContext, Scheme, authority::Authority, config::Document, private_context::CaMaterial, + }, + inbound::http::{framing, parser::parse_request_head}, + resources::RuntimeResourceStats, + security::SecurityContext, + session::{DatagramSession, Destination, InboundKind, InboundMetadata, StreamSession}, +}; +use async_trait::async_trait; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +#[cfg(feature = "outbound-vmess")] +use futures_util::FutureExt; +#[cfg(feature = "outbound-vmess")] +use std::panic::AssertUnwindSafe; +use std::{ + io, + pin::Pin, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + task::{Context, Poll}, + time::Duration, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, ReadBuf}, + task::JoinHandle, + time::timeout, +}; +use tokio_util::sync::CancellationToken; + +const WAIT: Duration = Duration::from_secs(3); + +#[derive(Clone, Copy)] +enum Reply { + Persistent, + Close, + Http10, + Extra, + Chunked, + Trailer, + ContentRange, + FailSecond, + Partial, + EarlyPost, + WaitPost, +} + +struct State { + authority: Arc, + scope: Arc<()>, + alpn: Option<&'static [u8]>, + reply: Reply, + reject: AtomicBool, + prepares: AtomicUsize, + opens: AtomicUsize, + accepts: Arc, + live: Arc, + heads: Arc>>, + uploads: Arc>>>, + sni: Arc>>, + negotiated: Arc>>>>, + sessions: Mutex>, + peers: Mutex>>, + partial: Arc, + #[cfg(feature = "outbound-shadowsocks")] + obfs: Mutex>>, + #[cfg(feature = "outbound-vmess")] + vmess_http_cover: Mutex>>, +} + +#[derive(Clone)] +struct MemoryTls(Arc); + +// Equality evidence owns its scope, rather than comparing a borrowed address. +// Routing and physical-DIRECT proofs are covered by upstream_memory_tests; +// this fixture deliberately supplies one immutable physical in-memory leaf. +struct Identity { + scope: Arc<()>, + session: StreamSession, +} +impl PartialEq for Identity { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.scope, &other.scope) && self.session == other.session + } +} +impl Eq for Identity {} + +struct Plan { + origin: MemoryTls, + session: StreamSession, + key: HttpTcpReuseKey, +} +#[async_trait] +impl HttpTcpPlan for Plan { + fn reuse_key(&self) -> Option<&HttpTcpReuseKey> { + Some(&self.key) + } + async fn connect(self: Box) -> Result { + let Self { + origin, session, .. + } = *self; + origin.open(session).await + } +} + +struct OwnedClient { + io: BoxStream, + live: Arc, +} +impl Drop for OwnedClient { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::SeqCst); + } +} +impl AsyncRead for OwnedClient { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buffer: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, buffer) + } +} +impl AsyncWrite for OwnedClient { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, bytes) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} + +#[async_trait] +impl Dispatcher for MemoryTls { + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + self.0.prepares.fetch_add(1, Ordering::SeqCst); + if self.0.reject.load(Ordering::SeqCst) { + return Err(DispatchError::NotAllowed); + } + let key = HttpTcpReuseKey::new(Identity { + scope: self.0.scope.clone(), + session: session.clone(), + }); + Ok(Some(Box::new(Plan { + origin: self.clone(), + session, + key, + }))) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.open(session).await + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +type AcceptedMemoryPeer = Pin> + Send>>; + +fn plain_memory_pair() -> (BoxStream, AcceptedMemoryPeer) { + let (client, peer) = tokio::io::duplex(8192); + ( + Box::new(client), + Box::pin(async move { Ok(Box::new(peer) as BoxStream) }), + ) +} + +impl MemoryTls { + async fn open(&self, session: StreamSession) -> Result { + let name = match &session.destination { + Destination::Domain { host, .. } => host.clone(), + Destination::Ip(_) => session + .sniffed_domain + .clone() + .expect("the selected original IP must retain its own SNI"), + }; + // This fixture maps only rewritten port 80 to cleartext; 443 and 444 + // are real TLS peers. It never resolves the symbolic destination. + let secure = session.destination.port() != 80; + let config = if secure { + let mut config = (*self.0.authority.server_config(&name).unwrap()).clone(); + config.alpn_protocols = self.0.alpn.map_or_else(Vec::new, |p| vec![p.to_vec()]); + Some(Arc::new(config)) + } else { + None + }; + self.0.sessions.lock().unwrap().push(session.clone()); + self.0.opens.fetch_add(1, Ordering::SeqCst); + #[cfg(feature = "outbound-shadowsocks")] + let factory = self.0.obfs.lock().unwrap().clone(); + #[cfg(feature = "outbound-vmess")] + let vmess = self.0.vmess_http_cover.lock().unwrap().clone(); + #[cfg(all(feature = "outbound-shadowsocks", feature = "outbound-vmess"))] + if factory.is_some() && vmess.is_some() { + return Err(DispatchError::NotAllowed); + } + let fallback = async { + #[cfg(feature = "outbound-shadowsocks")] + if let Some(factory) = factory { + return factory.open(session.destination.clone()).await; + } + Ok::<_, io::Error>(plain_memory_pair()) + }; + #[cfg(feature = "outbound-vmess")] + let (client, peer) = match vmess { + Some(factory) => factory.open(session.destination.clone()).await?, + None => fallback.await?, + }; + #[cfg(not(feature = "outbound-vmess"))] + let (client, peer) = fallback.await?; + self.0.live.fetch_add(1, Ordering::SeqCst); + let accepts = self.0.accepts.clone(); + let sni = self.0.sni.clone(); + let negotiated = self.0.negotiated.clone(); + let heads = self.0.heads.clone(); + let uploads = self.0.uploads.clone(); + let partial = self.0.partial.clone(); + let reply = self.0.reply; + self.0.peers.lock().unwrap().push(tokio::spawn(async move { + // The real SS handshake must await client TLS bytes, after open returns. + let peer = peer.await.expect("memory carrier handshake and exact target"); + let stream: BoxStream = if let Some(config) = config { + let tls = tokio_rustls::TlsAcceptor::from(config) + .accept(peer) + .await + .expect("the in-memory upstream TLS handshake must really succeed"); + accepts.fetch_add(1, Ordering::SeqCst); + sni.lock() + .unwrap() + .push(tls.get_ref().1.server_name().unwrap().to_owned()); + negotiated + .lock() + .unwrap() + .push(tls.get_ref().1.alpn_protocol().map(<[u8]>::to_vec)); + Box::new(tls) + } else { + peer + }; + let mut reader = BufReader::new(stream); + let mut sequence = 0; + loop { + let bytes = match framing::read_head(&mut reader, 32768).await { + Ok(bytes) => bytes, + Err(_) => break, // EOF/cancellation releases this real peer. + }; + let request = parse_request_head(&bytes, Vec::new()).unwrap(); + assert!(matches!(request.method.as_str(), "GET" | "POST")); + let text = String::from_utf8(bytes).unwrap(); + heads.lock().unwrap().push(text.clone()); + sequence += 1; + if matches!(reply, Reply::FailSecond) && sequence == 2 { + break; // The second request head was received, never replay it. + } + if request.method == "POST" { + let expected = request.headers.iter().find_map(|(name, value)| { + name.eq_ignore_ascii_case("content-length") + .then(|| value.parse::().unwrap()) + }).expect("the fixed POST fixture requires Content-Length"); + assert!(expected <= 65536); + let mut body = vec![0; if matches!(reply, Reply::EarlyPost | Reply::WaitPost) { + expected.min(1) + } else { expected }]; + if reader.read_exact(&mut body).await.is_err() { + break; + } + uploads.lock().unwrap().push(body); + if matches!(reply, Reply::EarlyPost | Reply::WaitPost) { + partial.notify_one(); + } + if matches!(reply, Reply::WaitPost) { + // An unfinished upload is released by Core cancellation, + // rather than by a fixture-side timer or detached task. + let mut tail = Vec::new(); + let _ = reader.read_to_end(&mut tail).await; + break; + } + } + let wire: &[u8] = match reply { + Reply::Close => b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\nConnection: close\r\n\r\norigin", + Reply::Http10 => b"HTTP/1.0 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\n\r\norigin", + Reply::Extra => b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\n\r\noriginunsolicited", + Reply::Chunked => b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n6\r\norigin\r\n0\r\n\r\n", + Reply::Trailer => b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\nTrailer: X-Safe\r\n\r\n6\r\norigin\r\n0\r\nX-Safe: value\r\n\r\n", + Reply::ContentRange => b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\nContent-Range: bytes 0-5/12\r\n\r\norigin", + Reply::Partial => b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 12\r\n\r\norigin", + _ => b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\n\r\norigin", + }; + if reader.get_mut().write_all(wire).await.is_err() + || reader.get_mut().flush().await.is_err() + { + break; + } + if matches!(reply, Reply::Partial) { + partial.notify_one(); + } + if matches!(reply, Reply::EarlyPost) { + let mut tail = Vec::new(); + let _ = reader.read_to_end(&mut tail).await; + break; + } + if matches!(reply, Reply::Close | Reply::Http10) + || text.to_ascii_lowercase().contains("connection: close") + { + break; + } + } + })); + Ok(Box::new(OwnedClient { + io: client, + live: self.0.live.clone(), + })) + } + fn count(&self, value: &AtomicUsize) -> usize { + value.load(Ordering::SeqCst) + } +} + +struct Fixture { + context: HttpContext, + origin: MemoryTls, + stats: RuntimeResourceStats, +} +fn pem(label: &str, bytes: &[u8]) -> String { + format!( + "-----BEGIN {label}-----\n{}\n-----END {label}-----\n", + STANDARD.encode(bytes) + ) +} +fn fixture(alpn: Option<&'static [u8]>, reply: Reply, rewrite_body: bool, extra: &str) -> Fixture { + let mut params = rcgen::CertificateParams::default(); + params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign]; + let key = rcgen::KeyPair::generate().unwrap(); + let cert = params.self_signed(&key).unwrap(); + let certificate = pem("CERTIFICATE", cert.der()); + let private_key = pem("PRIVATE KEY", &key.serialize_der()); + let authority = Authority::load(&certificate, &private_key).unwrap(); + let source = format!( + "mitm:\n enabled: true\n domains: [{{pattern: a.test}}, {{pattern: b.test}}]\nrewrite:\n enabled: true\n rules:\n - {{url: '.', action: response-header-set, header: X-Native-Proof, value: memory-tls}}\n{}{}", + if rewrite_body { + " - {url: '.', action: response-body-set, value: changed}\n" + } else { + "" + }, + extra + ); + let candidate = Document::parse(&source) + .unwrap() + .compile(&std::collections::BTreeMap::new()) + .unwrap(); + let policy = candidate + .bind_ca(Some(&CaMaterial { + certificate, + private_key: zeroize::Zeroizing::new(private_key), + })) + .unwrap(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(cert.der().clone()).unwrap(); + let origin = MemoryTls(Arc::new(State { + authority, + scope: Arc::new(()), + alpn, + reply, + reject: AtomicBool::new(false), + prepares: AtomicUsize::new(0), + opens: AtomicUsize::new(0), + accepts: Arc::new(AtomicUsize::new(0)), + live: Arc::new(AtomicUsize::new(0)), + heads: Arc::default(), + uploads: Arc::default(), + sni: Arc::default(), + negotiated: Arc::default(), + sessions: Mutex::new(Vec::new()), + peers: Mutex::new(Vec::new()), + partial: Arc::new(tokio::sync::Notify::new()), + #[cfg(feature = "outbound-shadowsocks")] + obfs: Mutex::new(None), + #[cfg(feature = "outbound-vmess")] + vmess_http_cover: Mutex::new(None), + })); + let stats = RuntimeResourceStats::new("https_h1_reuse_memory"); + let dispatcher = observe_sessions_with_stats( + observe_handshakes_with_stats(Arc::new(origin.clone()), stats.clone()), + stats.clone(), + ); + Fixture { + context: HttpContext::new(policy, dispatcher, SecurityContext::with_tls_roots(roots)), + origin, + stats, + } +} + +struct Running { + client: BufReader, + cancellation: CancellationToken, + serving: JoinHandle>, +} +fn start(fixture: &Fixture) -> Running { + let (client, mut peer) = tokio::io::duplex(8192); + let cancellation = CancellationToken::new(); + let stop = cancellation.clone(); + let context = fixture.context.clone(); + let serving = tokio::spawn(async move { + context + .serve_h1( + &mut peer, + StreamSession { + metadata: InboundMetadata::new(443), + inbound: InboundKind::Tun, + source: "198.18.0.2:30000".parse().unwrap(), + destination: Destination::Ip("203.0.113.1:443".parse().unwrap()), + sniffed_domain: Some("a.test".into()), + }, + Scheme::Https, + stop, + ) + .await + }); + Running { + client: BufReader::new(client), + cancellation, + serving, + } +} +async fn joined(mut task: JoinHandle) -> Result { + match timeout(WAIT, &mut task).await { + Ok(result) => result.map_err(|error| error.to_string()), + Err(_) => { + task.abort(); + let _ = task.await; + Err("the real memory task did not join before the deadline".into()) + } + } +} +async fn finish(running: Running, fixture: &Fixture) -> io::Result<()> { + // Keep the downstream open until serving has actually joined. EOF must not + // be the only reason an idle or partly consumed TLS owner gets released. + running.cancellation.cancel(); + let result = joined(running.serving).await; + let mut failures = Vec::new(); + if let Err(error) = &result { + failures.push(error.clone()); + } + #[cfg(feature = "outbound-vmess")] + { + let factory = fixture + .origin + .0 + .vmess_http_cover + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(factory) = factory { + if AssertUnwindSafe(factory.shutdown()) + .catch_unwind() + .await + .is_err() + { + failures.push("actual VMess HTTP-cover owner shutdown panicked".into()); + } + } + } + let peers = std::mem::take(&mut *fixture.origin.0.peers.lock().unwrap()); + for peer in peers { + if let Err(error) = joined(peer).await { + failures.push(error); + } + } + drop(running.client); + assert!( + failures.is_empty(), + "all real owners must join: {failures:?}" + ); + assert_eq!(fixture.origin.count(&fixture.origin.0.live), 0); + assert_eq!(fixture.stats.snapshot().tcp_current, 0); + assert_eq!(fixture.stats.snapshot().handshake_current, 0); + result.unwrap() +} +async fn request( + running: &mut Running, + authority: &str, + path: &str, +) -> io::Result<(String, Vec)> { + request_fields(running, authority, path, "").await +} +async fn request_fields( + running: &mut Running, + authority: &str, + path: &str, + fields: &str, +) -> io::Result<(String, Vec)> { + timeout(WAIT, async { + running + .client + .get_mut() + .write_all( + format!("GET {path} HTTP/1.1\r\nHost: {authority}\r\n{fields}\r\n").as_bytes(), + ) + .await?; + let head = framing::read_head(&mut running.client, 32768).await?; + let response = framing::ResponseHead::parse(&head)?; + let mut body = Vec::new(); + framing::transfer_body( + &mut running.client, + &mut body, + response.body("GET"), + WAIT, + response.trailer_blocklist(), + true, + ) + .await?; + Ok((String::from_utf8(head).unwrap(), body)) + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "memory response timed out"))? +} +fn native_response(result: io::Result<(String, Vec)>, body: &[u8]) { + let (head, actual) = result.unwrap(); + assert!(head.starts_with("HTTP/1.1 200")); + assert!( + head.to_ascii_lowercase() + .contains("x-native-proof: memory-tls") + ); + assert_eq!(actual, body); +} + +async fn fixed_post( + running: &mut Running, + path: &str, + body: &[u8], +) -> io::Result<(String, Vec)> { + timeout(WAIT, async { + running.client.get_mut().write_all(format!( + "POST {path} HTTP/1.1\r\nHost: a.test\r\nContent-Type: text/plain\r\nContent-Length: {}\r\n\r\n", body.len() + ).as_bytes()).await?; + running.client.get_mut().write_all(body).await?; + running.client.get_mut().flush().await?; + let head = framing::read_head(&mut running.client, 32768).await?; + let response = framing::ResponseHead::parse(&head)?; + let mut received = Vec::new(); + framing::transfer_body(&mut running.client, &mut received, response.body("POST"), WAIT, response.trailer_blocklist(), true).await?; + Ok((String::from_utf8(head).unwrap(), received)) + }).await.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "fixed POST response timed out"))? +} + +#[tokio::test] +async fn completed_post_h1_reuses_only_after_full_fixed_upload_and_response() { + for native in [false, true] { + let extra = if native { + " - {url: '.', action: request-body-set, value: transformed}\n" + } else { + "" + }; + let fixture = fixture(Some(b"http/1.1"), Reply::Persistent, false, extra); + let mut running = start(&fixture); + let first = fixed_post(&mut running, "/one", b"original").await; + let second = fixed_post(&mut running, "/two", b"original").await; + let finished = finish(running, &fixture).await; + native_response(first, b"origin"); + native_response(second, b"origin"); + finished.unwrap(); + assert_eq!(fixture.origin.count(&fixture.origin.0.prepares), 2); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 1); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), 1); + let expected = if native { + b"transformed".as_slice() + } else { + b"original".as_slice() + }; + assert_eq!( + *fixture.origin.0.uploads.lock().unwrap(), + vec![expected.to_vec(), expected.to_vec()] + ); + assert!( + fixture + .origin + .0 + .heads + .lock() + .unwrap() + .iter() + .all(|head| head.to_ascii_lowercase().contains("connection: keep-alive")) + ); + } +} + +#[tokio::test] +async fn completed_post_h1_sent_second_request_is_never_replayed() { + let fixture = fixture(Some(b"http/1.1"), Reply::FailSecond, false, ""); + let mut running = start(&fixture); + let first = fixed_post(&mut running, "/one", b"original").await; + let second = fixed_post(&mut running, "/two", b"original").await; + let finished = finish(running, &fixture).await; + native_response(first, b"origin"); + if let Ok((head, body)) = second { + // The ordinary H1 forwarder can frame the upstream failure before + // propagating its IO error. A gateway error is not a replayed response. + let response = framing::ResponseHead::parse(head.as_bytes()).unwrap(); + assert!(matches!(response.status, 400 | 502)); + assert!(body.is_empty()); + } + assert!(finished.is_err()); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 1); + assert_eq!(fixture.origin.0.heads.lock().unwrap().len(), 2); + assert_eq!(fixture.origin.0.uploads.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn completed_post_h1_partial_upload_early_final_closes_both_owners() { + let fixture = fixture(Some(b"http/1.1"), Reply::EarlyPost, false, ""); + let mut running = start(&fixture); + let result = timeout(WAIT, async { + running + .client + .get_mut() + .write_all(b"POST /early HTTP/1.1\r\nHost: a.test\r\nContent-Length: 65536\r\n\r\nx") + .await?; + let head = framing::read_head(&mut running.client, 32768).await?; + let response = framing::ResponseHead::parse(&head)?; + let mut body = Vec::new(); + framing::transfer_body( + &mut running.client, + &mut body, + response.body("POST"), + WAIT, + response.trailer_blocklist(), + false, + ) + .await?; + let mut tail = [0; 1]; + let eof = running.client.read(&mut tail).await?; + Ok::<_, io::Error>((head, body, eof)) + }) + .await; + let finished = finish(running, &fixture).await; + let (head, body, eof) = result.unwrap().unwrap(); + finished.unwrap(); + assert!( + String::from_utf8(head) + .unwrap() + .to_ascii_lowercase() + .contains("connection: close") + ); + assert_eq!(body, b"origin"); + assert_eq!(eof, 0); + assert_eq!( + *fixture.origin.0.uploads.lock().unwrap(), + vec![b"x".to_vec()] + ); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 1); +} + +#[tokio::test] +async fn completed_post_h1_cancellation_joins_an_unfinished_upload() { + let fixture = fixture(Some(b"http/1.1"), Reply::WaitPost, false, ""); + let mut running = start(&fixture); + let started = timeout(WAIT, async { + running + .client + .get_mut() + .write_all(b"POST /cancel HTTP/1.1\r\nHost: a.test\r\nContent-Length: 65536\r\n\r\nx") + .await?; + fixture.origin.0.partial.notified().await; + Ok::<_, io::Error>(()) + }) + .await; + let finished = finish(running, &fixture).await; + started.unwrap().unwrap(); + finished.unwrap(); + assert_eq!( + *fixture.origin.0.uploads.lock().unwrap(), + vec![b"x".to_vec()] + ); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 1); +} + +#[tokio::test] +async fn https_h1_actual_h1_or_no_alpn_reuses_one_tls_owner_for_two_native_responses() { + for alpn in [Some(b"http/1.1".as_slice()), None] { + let fixture = fixture(alpn, Reply::Persistent, true, ""); + let mut running = start(&fixture); + let first = request(&mut running, "a.test", "/one").await; + let second = request(&mut running, "a.test", "/two").await; + let active = fixture.stats.snapshot(); + finish(running, &fixture).await.unwrap(); + native_response(first, b"changed"); + native_response(second, b"changed"); + assert_eq!(fixture.origin.count(&fixture.origin.0.prepares), 2); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 1); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), 1); + assert_eq!(fixture.origin.0.heads.lock().unwrap().len(), 2); + assert_eq!( + *fixture.origin.0.sni.lock().unwrap(), + vec!["a.test".to_owned()] + ); + assert_eq!( + *fixture.origin.0.negotiated.lock().unwrap(), + vec![alpn.map(<[u8]>::to_vec)] + ); + assert_eq!(active.tcp_current, 1); + assert_eq!(active.handshake_current, 0); + } +} + +#[tokio::test] +async fn https_h1_request_close_retires_a_previously_cached_tls_owner() { + let fixture = fixture(Some(b"http/1.1"), Reply::Persistent, false, ""); + let mut running = start(&fixture); + let first = request(&mut running, "a.test", "/one").await; + let second = request_fields(&mut running, "a.test", "/closing", "Connection: close\r\n").await; + let serving = finish(running, &fixture).await; + native_response(first, b"origin"); + native_response(second, b"origin"); + serving.unwrap(); + assert_eq!(fixture.origin.count(&fixture.origin.0.prepares), 1); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 2); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), 2); + let heads = fixture.origin.0.heads.lock().unwrap(); + assert_eq!(heads.len(), 2); + assert!( + heads[0] + .to_ascii_lowercase() + .contains("connection: keep-alive") + ); + assert!(heads[1].to_ascii_lowercase().contains("connection: close")); +} + +#[tokio::test] +async fn https_h1_original_wire_retirement_cases_require_two_real_tls_accepts() { + for reply in [ + Reply::Close, + Reply::Http10, + Reply::Extra, + Reply::Chunked, + Reply::Trailer, + Reply::ContentRange, + ] { + let fixture = fixture(Some(b"http/1.1"), reply, false, ""); + let mut running = start(&fixture); + let first = request(&mut running, "a.test", "/one").await; + let second = request(&mut running, "a.test", "/two").await; + finish(running, &fixture).await.unwrap(); + native_response(first, b"origin"); + native_response(second, b"origin"); + assert_eq!(fixture.origin.count(&fixture.origin.0.prepares), 2); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 2); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), 2); + assert_eq!(fixture.origin.0.heads.lock().unwrap().len(), 2); + } +} + +#[tokio::test] +async fn https_h1_host_port_and_scheme_rewrites_keep_one_shot_and_final_sni() { + for (replacement, name, port, accepts) in [ + ("https://b.test/final", "b.test", 443, 2), + ("https://a.test:444/final", "a.test", 444, 2), + ("http://a.test/final", "a.test", 80, 0), + ] { + let extra = format!( + " - {{url: '^https://a\\.test/rewrite', action: replace, replacement-mode: url, replacement: '{replacement}'}}\n" + ); + let fixture = fixture(Some(b"http/1.1"), Reply::Persistent, false, &extra); + let mut running = start(&fixture); + let first = request(&mut running, "a.test", "/rewrite-one").await; + let second = request(&mut running, "a.test", "/rewrite-two").await; + finish(running, &fixture).await.unwrap(); + native_response(first, b"origin"); + native_response(second, b"origin"); + assert_eq!(fixture.origin.count(&fixture.origin.0.prepares), 0); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 2); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), accepts); + let sessions = fixture.origin.0.sessions.lock().unwrap(); + assert!(sessions.iter().all(|s| { + s.destination == Destination::domain(name, port).unwrap() && s.sniffed_domain.is_none() + })); + let expected: Vec = (0..accepts).map(|_| name.to_owned()).collect(); + assert_eq!(*fixture.origin.0.sni.lock().unwrap(), expected); + assert!(fixture.origin.0.heads.lock().unwrap().iter().all(|head| { + head.starts_with("GET /final HTTP/1.1\r\n") + && head.to_ascii_lowercase().contains("connection: close") + })); + } +} + +#[tokio::test] +async fn https_h1_unauthorized_original_authority_is_rejected_before_rewrite_or_reuse() { + let extra = " - {url: '^https://denied\\.test/', action: replace, replacement-mode: url, replacement: 'https://a.test/allowed'}\n"; + let fixture = fixture(Some(b"http/1.1"), Reply::Persistent, false, extra); + let mut running = start(&fixture); + let first = request(&mut running, "a.test", "/one").await; + let _second = request(&mut running, "denied.test", "/two").await; + let serving = finish(running, &fixture).await; + native_response(first, b"origin"); + assert!(serving.is_err()); + assert_eq!(fixture.origin.count(&fixture.origin.0.prepares), 1); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 1); + assert_eq!(fixture.origin.0.heads.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn https_h1_idle_and_partial_response_cancel_join_actual_tls_owners() { + for reply in [Reply::Persistent, Reply::Partial] { + let fixture = fixture(Some(b"http/1.1"), reply, false, ""); + let mut running = start(&fixture); + let initial = async { + if matches!(reply, Reply::Partial) { + running + .client + .get_mut() + .write_all(b"GET /partial HTTP/1.1\r\nHost: a.test\r\n\r\n") + .await?; + timeout(WAIT, fixture.origin.0.partial.notified()) + .await + .map_err(|_| { + io::Error::new(io::ErrorKind::TimedOut, "missing partial TLS response") + })?; + Ok::<_, io::Error>(None) + } else { + request(&mut running, "a.test", "/idle").await.map(Some) + } + } + .await; + let live = fixture.origin.count(&fixture.origin.0.live); + let active = fixture.stats.snapshot().tcp_current; + let finished = finish(running, &fixture).await; + if let Some(response) = initial.unwrap() { + native_response(Ok(response), b"origin"); + } + finished.unwrap(); + assert_eq!(live, 1); + assert_eq!(active, 1); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), 1); + } +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn https_h1_native_then_real_js_a_b_a_does_not_recover_reuse_eligibility() { + let extra = r#" - {url: '^https://a\.test/', action: replace, replacement-mode: url, replacement: 'https://b.test/middle'} +http-scripts: + enabled: true + scripts: + - name: return-to-original + phase: request + url: '^https://a\.test/' + source: | + function rewrite(input) { + if (input.request.url !== "https://b.test/middle") return {type:"abort"}; + return {type:"modify",url:"https://a.test/final",headers:[{op:"set",name:"X-Round-Trip",values:["real-jsc"]}]}; + } +"#; + let fixture = fixture(Some(b"http/1.1"), Reply::Persistent, false, extra); + let mut running = start(&fixture); + let first = request(&mut running, "a.test", "/one").await; + let second = request(&mut running, "a.test", "/two").await; + finish(running, &fixture).await.unwrap(); + native_response(first, b"origin"); + native_response(second, b"origin"); + assert_eq!(fixture.origin.count(&fixture.origin.0.prepares), 0); + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 2); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), 2); + assert_eq!( + *fixture.origin.0.sni.lock().unwrap(), + vec!["a.test".to_owned(), "a.test".to_owned()] + ); + let heads = fixture.origin.0.heads.lock().unwrap(); + assert_eq!(heads.len(), 2); + assert!(heads.iter().all(|head| { + let lower = head.to_ascii_lowercase(); + head.starts_with("GET /final HTTP/1.1\r\n") + && lower.contains("x-round-trip: real-jsc") + && lower.contains("connection: close") + })); +} diff --git a/src/http_processing/https_h1_sing_mux_reuse_memory_tests.rs b/src/http_processing/https_h1_sing_mux_reuse_memory_tests.rs new file mode 100644 index 0000000..05a1907 --- /dev/null +++ b/src/http_processing/https_h1_sing_mux_reuse_memory_tests.rs @@ -0,0 +1,299 @@ +//! Real sing-mux carrier plus the existing in-memory HTTPS/H1 origin. +use super::*; +use crate::{ + config::{SingMuxConfig, SingMuxProtocol}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, SingMuxConnector, + }, + resources::observation::{ResourceKind, ResourceProbe}, +}; +use sha2::{Digest as _, Sha256}; +use tokio_util::compat::{FuturesAsyncReadCompatExt, TokioAsyncReadCompatExt}; + +struct Carrier { + origin: MemoryTls, + proven: bool, + physical: AtomicUsize, + logical: Arc, + tasks: Mutex>>, + relays: Arc>>>, + probe: ResourceProbe, +} +#[async_trait] +impl OutboundConnector for Carrier { + fn permits_http_tcp_reuse(&self) -> bool { + self.proven + } + + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + self.physical.fetch_add(1, Ordering::SeqCst); + let effective_peer = session.destination.clone(); + let (client, mut peer) = tokio::io::duplex(65536); + let origin = self.origin.clone(); + let logical = self.logical.clone(); + let relays = self.relays.clone(); + self.tasks.lock().unwrap().push(tokio::spawn(async move { + let mut prefix = [0; 2]; + peer.read_exact(&mut prefix).await.unwrap(); + assert_eq!(prefix, [0, 1], "real sing-mux yamux bootstrap"); + let mut connection = yamux::Connection::new( + peer.compat(), + yamux::Config::default(), + yamux::Mode::Server, + ); + while let Some(next) = std::future::poll_fn(|cx| connection.poll_next_inbound(cx)).await + { + let stream = match next { + Ok(stream) => stream, + Err(_) => break, // Owned physical cancellation closes its streams. + }; + logical.fetch_add(1, Ordering::SeqCst); + let origin = origin.clone(); + let mut target_session = session.clone(); + relays.lock().unwrap().push(tokio::spawn(async move { + let mut stream = stream.compat(); + // This fixed test target is IPv4; decode its real wire + // address with the production codec rather than inventing it. + let mut request = [0; 9]; + stream.read_exact(&mut request).await.unwrap(); + assert_eq!(&request[..2], &[0, 0]); + let (target, consumed) = crate::socks5::decode_address(&request[2..]).unwrap(); + assert_eq!(consumed, 7); + assert_eq!(target, Destination::Ip("203.0.113.1:443".parse().unwrap())); + target_session.destination = target; + target_session.sniffed_domain = Some("a.test".into()); + stream.write_all(&[0]).await.unwrap(); + stream.flush().await.unwrap(); + let mut tls_peer = origin.open(target_session).await.unwrap(); + let _ = tokio::io::copy_bidirectional(&mut stream, &mut tls_peer).await; + })); + } + // The shared registry keeps relay handles through parent cancellation. + drop(connection); + })); + Ok(ConnectedStream { + io: Box::new(client), + effective_peer, + }) + } + + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } + + async fn shutdown(&self) { + let mux_driver_finished = self.probe.snapshot().current(ResourceKind::Task) == 0; + let owners = std::mem::take(&mut *self.tasks.lock().unwrap()); + let mut failures = Vec::new(); + for owner in owners { + if let Err(error) = joined(owner).await { + failures.push(error); + } + } + let relays = std::mem::take(&mut *self.relays.lock().unwrap()); + for relay in relays { + if let Err(error) = joined(relay).await { + failures.push(error); + } + } + let tls_peers = std::mem::take(&mut *self.origin.0.peers.lock().unwrap()); + for peer in tls_peers { + if let Err(error) = joined(peer).await { + failures.push(error); + } + } + assert!( + failures.is_empty(), + "real mux peers did not join: {failures:?}" + ); + assert!( + mux_driver_finished, + "inner shutdown preceded the actual mux driver" + ); + } +} + +struct RoutedMux { + node: Arc, + scope: Arc<()>, + probe: ResourceProbe, +} +struct MuxPlan { + node: Arc, + session: StreamSession, + key: Option, + probe: ResourceProbe, +} +#[async_trait] +impl HttpTcpPlan for MuxPlan { + fn reuse_key(&self) -> Option<&HttpTcpReuseKey> { + self.key.as_ref() + } + async fn connect(self: Box) -> Result { + let Self { + node, + session, + probe, + .. + } = *self; + probe + .scope(node.connect_stream(session, &EstablishContext::default())) + .await + .map(|stream| stream.io) + } +} +#[async_trait] +impl Dispatcher for RoutedMux { + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + let key = self.node.permits_http_tcp_reuse().then(|| { + HttpTcpReuseKey::new(Identity { + scope: self.scope.clone(), + session: session.clone(), + }) + }); + Ok(Some(Box::new(MuxPlan { + node: self.node.clone(), + session, + key, + probe: self.probe.clone(), + }))) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.node + .connect_stream(session, &EstablishContext::default()) + .await + .map(|stream| stream.io) + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +#[tokio::test] +async fn proven_sing_mux_keeps_one_real_logical_tls_stream_for_two_http_requests() { + let probe = ResourceProbe::default(); + probe + .scope(async { + let mut fixture = fixture(Some(b"http/1.1"), Reply::Persistent, false, ""); + let carrier = Arc::new(Carrier { + origin: fixture.origin.clone(), + proven: true, + physical: AtomicUsize::new(0), + logical: Arc::new(AtomicUsize::new(0)), + tasks: Mutex::new(Vec::new()), + relays: Arc::new(Mutex::new(Vec::new())), + probe: probe.clone(), + }); + let node = Arc::new(SingMuxConnector::new( + carrier.clone(), + SingMuxConfig { + enabled: true, + protocol: SingMuxProtocol::Yamux, + max_connections: 1, + ..Default::default() + }, + )); + let route = Arc::new(RoutedMux { + node: node.clone(), + scope: fixture.origin.0.scope.clone(), + probe: probe.clone(), + }); + fixture.context.dispatcher = observe_sessions_with_stats( + observe_handshakes_with_stats(route, fixture.stats.clone()), + fixture.stats.clone(), + ); + let mut running = start(&fixture); + let first = request(&mut running, "a.test", "/one").await; + let second = request(&mut running, "a.test", "/two").await; + let hashes: Vec<_> = [&first, &second] + .into_iter() + .map(|response| { + response + .as_ref() + .ok() + .map(|(_, body)| Sha256::digest(body).to_vec()) + }) + .collect(); + let physical = carrier.physical.load(Ordering::SeqCst); + let logical = carrier.logical.load(Ordering::SeqCst); + let tls_opens = fixture.origin.count(&fixture.origin.0.opens); + let tls_accepts = fixture.origin.count(&fixture.origin.0.accepts); + let idle_live = fixture.origin.count(&fixture.origin.0.live); + let idle_tcp = fixture.stats.snapshot().tcp_current; + let idle_pool = probe.snapshot().current(ResourceKind::Pool); + let idle_tasks = probe.snapshot().current(ResourceKind::Task); + // Keep the downstream open: cancellation, rather than client EOF, + // must destroy the retained TLS/logical lease before node Stop joins. + running.cancellation.cancel(); + let serving = joined(running.serving).await; + node.shutdown().await; + let cancelled_proof = node.permits_http_tcp_reuse(); + let peers = std::mem::take(&mut *fixture.origin.0.peers.lock().unwrap()); + let mut failures = Vec::new(); + for peer in peers { + if let Err(error) = joined(peer).await { + failures.push(error); + } + } + drop(running.client); + let heads = fixture.origin.0.heads.lock().unwrap().clone(); + let live = fixture.origin.count(&fixture.origin.0.live); + let stats = fixture.stats.snapshot(); + let idle = probe.snapshot().is_idle(); + // A cancelled outer owner and an unproven inner owner must both deny + // the capability. These controls create no additional wire owners. + let denied = SingMuxConnector::new( + Arc::new(Carrier { + origin: fixture.origin.clone(), + proven: false, + physical: AtomicUsize::new(0), + logical: Arc::new(AtomicUsize::new(0)), + tasks: Mutex::new(Vec::new()), + relays: Arc::new(Mutex::new(Vec::new())), + probe: probe.clone(), + }), + SingMuxConfig { + enabled: true, + ..Default::default() + }, + ); + let inner_denied = !denied.permits_http_tcp_reuse(); + drop(denied); + + assert!( + failures.is_empty(), + "real TLS peers failed to join: {failures:?}" + ); + serving.unwrap().unwrap(); + native_response(first, b"origin"); + native_response(second, b"origin"); + assert_eq!(hashes, vec![Some(Sha256::digest(b"origin").to_vec()); 2]); + assert_eq!(heads.len(), 2); + assert!(heads[0].starts_with("GET /one ")); + assert!(heads[1].starts_with("GET /two ")); + assert_eq!(physical, 1); + assert_eq!(logical, 1, "HTTP reopened a real mux logical stream"); + assert_eq!((tls_opens, tls_accepts), (1, 1), "HTTP repeated origin TLS"); + assert_eq!((idle_live, idle_tcp, idle_pool, idle_tasks), (1, 1, 1, 1)); + assert!(!cancelled_proof && inner_denied); + assert_eq!(live, 0); + assert_eq!(stats.tcp_current, 0); + assert_eq!(stats.handshake_current, 0); + assert!(idle); + }) + .await; +} diff --git a/src/http_processing/https_h1_ss_obfs_reuse_memory_tests.rs b/src/http_processing/https_h1_ss_obfs_reuse_memory_tests.rs new file mode 100644 index 0000000..6bed62a --- /dev/null +++ b/src/http_processing/https_h1_ss_obfs_reuse_memory_tests.rs @@ -0,0 +1,289 @@ +//! Genuine obfs/SS under the original authenticated TLS and H1 cache. +use super::*; +use crate::{ + config::ShadowsocksCipher, + outbound::{MemoryObfsFactory, MemoryObfsReceipt}, +}; +use futures_util::FutureExt; +use std::panic::AssertUnwindSafe; + +const CIPHERS: [ShadowsocksCipher; 3] = [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, +]; + +struct Closed { + serving: Result, String>, + failures: Vec, + receipt: MemoryObfsReceipt, +} + +async fn close(running: Running, fixture: &Fixture, factory: &MemoryObfsFactory) -> Closed { + // Keep downstream open until the actual HTTP parent has dropped its cache. + running.cancellation.cancel(); + let serving = joined(running.serving).await; + let mut failures = Vec::new(); + if AssertUnwindSafe(factory.shutdown()) + .catch_unwind() + .await + .is_err() + { + failures.push("actual obfs owner shutdown panicked".into()); + } + let peers = std::mem::take( + &mut *fixture + .origin + .0 + .peers + .lock() + .unwrap_or_else(|error| error.into_inner()), + ); + for peer in peers { + if let Err(error) = joined(peer).await { + failures.push(error); + } + } + drop(running.client); + Closed { + serving, + failures, + receipt: factory.snapshot(), + } +} + +fn closed_witness(closed: &Closed, fixture: &Fixture) { + assert!( + closed.serving.is_ok(), + "HTTP parent did not join: {:?}", + closed.serving + ); + assert!( + closed.failures.is_empty(), + "peer owners did not join: {:?}", + closed.failures + ); + assert_eq!(fixture.origin.count(&fixture.origin.0.live), 0); + assert_eq!(fixture.stats.snapshot().tcp_current, 0); + assert_eq!(fixture.stats.snapshot().handshake_current, 0); + let r = &closed.receipt; + assert_eq!(r.owners, 1, "{r:?}"); + assert_eq!(r.opens, 1, "{r:?}"); + assert_eq!(r.target_handshakes, 1, "{r:?}"); + assert_eq!(r.cover_requests, 1, "{r:?}"); + assert_eq!(r.cover_responses, 1, "{r:?}"); + assert_eq!( + r.client_drops, 1, + "actual SS client IO survived parent join: {r:?}" + ); + assert_eq!( + r.peer_drops, 1, + "actual SS peer IO survived peer join: {r:?}" + ); + assert_eq!(r.owner_cancelled, 1, "{r:?}"); + assert_eq!(r.owner_closed, 1, "{r:?}"); + assert_eq!(r.owner_wait_returned, 1, "{r:?}"); +} + +async fn run(cipher: ShadowsocksCipher, tls: bool, reply: Reply) { + run_with_factory(MemoryObfsFactory::new(cipher, tls, 4096), reply).await; +} + +pub(super) async fn run_with_factory(factory: Arc, reply: Reply) { + run_with_factory_options(factory, reply, "", false).await; +} + +#[cfg(target_vendor = "apple")] +pub(super) async fn run_scripted_with_factory(factory: Arc, extra: &str) { + run_with_factory_options(factory, Reply::Persistent, extra, true).await; +} + +fn response_witness(result: io::Result<(String, Vec)>, scripted: bool) { + if scripted { + let (head, _) = result.as_ref().expect("scripted response must complete"); + assert!( + head.to_ascii_lowercase() + .contains("x-js-response: native-then-js"), + "actual response script witness missing" + ); + } + let expected: &[u8] = if scripted { b"Changed" } else { b"origin" }; + native_response(result, expected); +} + +async fn run_with_factory_options( + factory: Arc, + reply: Reply, + extra: &str, + scripted: bool, +) { + let fixture = fixture(Some(b"http/1.1"), reply, scripted, extra); + *fixture.origin.0.obfs.lock().unwrap() = Some(factory.clone()); + let mut running = start(&fixture); + let result = AssertUnwindSafe(async { + timeout(WAIT * 3, async { + match reply { + Reply::Persistent | Reply::FailSecond => { + let first = fixed_post(&mut running, "/one", b"original").await; + response_witness(first, scripted); + let second = fixed_post(&mut running, "/two", b"original").await; + if matches!(reply, Reply::FailSecond) { + if let Ok((head, body)) = second { + let response = framing::ResponseHead::parse(head.as_bytes())?; + assert!(matches!(response.status, 400 | 502)); + assert!(body.is_empty()); + } + } else { + response_witness(second, scripted); + // Stop a genuinely idle carrier while downstream stays open. + factory.begin_shutdown(); + } + } + Reply::WaitPost | Reply::EarlyPost => { + running.client.get_mut().write_all( + b"POST /partial HTTP/1.1\r\nHost: a.test\r\nContent-Length: 65536\r\n\r\nx" + ).await?; + if matches!(reply, Reply::WaitPost) { + timeout(WAIT, fixture.origin.0.partial.notified()) + .await + .map_err(|_| { + io::Error::new(io::ErrorKind::TimedOut, "actual partial upload") + })?; + factory.begin_shutdown(); + } else { + let head = framing::read_head(&mut running.client, 32768).await?; + let response = framing::ResponseHead::parse(&head)?; + let mut body = Vec::new(); + framing::transfer_body( + &mut running.client, + &mut body, + response.body("POST"), + WAIT, + response.trailer_blocklist(), + false, + ) + .await?; + let mut tail = [0; 1]; + assert_eq!(running.client.read(&mut tail).await?, 0); + assert_eq!(body, b"origin"); + assert!( + String::from_utf8(head) + .unwrap() + .to_ascii_lowercase() + .contains("connection: close") + ); + } + } + _ => unreachable!("R4 uses the original completed/partial POST modes"), + } + Ok::<_, io::Error>(()) + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "whole SS/H1 memory exchange"))? + }) + .catch_unwind() + .await; + // Handshake/content/assertion errors and panics all reach the same cleanup. + let closed = close(running, &fixture, &factory).await; + closed_witness(&closed, &fixture); + match result { + Ok(result) => result.unwrap(), + Err(panic) => std::panic::resume_unwind(panic), + } + assert_eq!(fixture.origin.count(&fixture.origin.0.opens), 1); + assert_eq!(fixture.origin.count(&fixture.origin.0.accepts), 1); + assert_eq!( + *fixture.origin.0.sni.lock().unwrap(), + vec!["a.test".to_owned()] + ); + assert_eq!( + *fixture.origin.0.negotiated.lock().unwrap(), + vec![Some(b"http/1.1".to_vec())] + ); + let expected_heads = if matches!(reply, Reply::Persistent | Reply::FailSecond) { + 2 + } else { + 1 + }; + assert_eq!( + fixture.origin.count(&fixture.origin.0.prepares), + expected_heads + ); + let heads = fixture.origin.0.heads.lock().unwrap(); + assert_eq!(heads.len(), expected_heads); + assert!( + heads + .iter() + .all(|head| head.to_ascii_lowercase().contains("connection: keep-alive")) + ); + if scripted { + assert!( + heads.iter().all(|head| { + head.to_ascii_lowercase() + .contains("x-js-request: transformed") + }), + "actual request script witness missing at origin" + ); + } + let uploads = fixture.origin.0.uploads.lock().unwrap(); + let complete_body: &[u8] = if scripted { + b"transformed" + } else { + b"original" + }; + let expected = match reply { + Reply::Persistent => vec![complete_body.to_vec(), complete_body.to_vec()], + Reply::FailSecond => vec![complete_body.to_vec()], + _ => vec![b"x".to_vec()], + }; + assert_eq!(*uploads, expected); + match reply { + Reply::FailSecond => assert!( + closed.serving.unwrap().is_err(), + "submitted second POST did not reach its fault" + ), + Reply::WaitPost => { + if let Err(error) = closed.serving.unwrap() { + assert_eq!( + error.kind(), + io::ErrorKind::ConnectionAborted, + "partial upload must finish normally or observe the explicit node cancellation" + ); + } + } + _ => closed.serving.unwrap().expect("normal HTTP parent failed"), + } +} + +#[tokio::test] +async fn ss_obfs_https_h1_two_posts_share_one_authenticated_carrier() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, Reply::Persistent).await; + } + } +} +#[tokio::test] +async fn ss_obfs_https_h1_submitted_second_post_is_not_replayed() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, Reply::FailSecond).await; + } + } +} +#[tokio::test] +async fn ss_obfs_https_h1_active_stop_drops_partial_upload() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, Reply::WaitPost).await; + } + } +} +#[tokio::test] +async fn ss_obfs_https_h1_early_final_retires_partial_upload() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, Reply::EarlyPost).await; + } + } +} diff --git a/src/http_processing/https_h1_ss_v2ray_mux_reuse_memory_tests.rs b/src/http_processing/https_h1_ss_v2ray_mux_reuse_memory_tests.rs new file mode 100644 index 0000000..34473f1 --- /dev/null +++ b/src/http_processing/https_h1_ss_v2ray_mux_reuse_memory_tests.rs @@ -0,0 +1,105 @@ +//! Real SS2022/plain WS mux beneath the original authenticated TLS/HTTP cache. +//! Pure memory only; no official Go server, sockets or throughput claims. +use super::*; +use crate::{config::ShadowsocksCipher, outbound::MemoryObfsFactory}; +async fn exercise(mode: Reply) { + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let factory = MemoryObfsFactory::new_v2ray_mux(cipher, 4096); + let weak = Arc::downgrade(&factory); + super::ss_obfs_reuse::run_with_factory(factory.clone(), mode).await; + let receipt = factory.snapshot(); + assert!(receipt.owners > 0, "actual mux factory was not entered"); + assert_eq!( + receipt.mux_new, receipt.owners, + "one New per actual WS/SS carrier: {receipt:?}" + ); + drop(factory); + assert!( + weak.upgrade().is_none(), + "HTTP parent retained the carrier factory" + ); + } +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h1_two_posts_share_one_authenticated_carrier() { + exercise(Reply::Persistent).await; +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h1_submitted_second_post_is_not_replayed() { + exercise(Reply::FailSecond).await; +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h1_active_stop_drops_partial_upload() { + exercise(Reply::WaitPost).await; +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h1_early_final_retires_uncertain_upload() { + exercise(Reply::EarlyPost).await; +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn ss_v2ray_mux_https_h1_native_then_js_reuses_one_authenticated_carrier() { + // Native sets the request header and response body first. Each script + // checks that stage; a failure/rollback leaves bytes or headers that fail + // the existing HTTP and independent origin-upload witnesses. + const SCRIPTS: &str = r#" - {url: 'https://a.test/', match: prefix, action: request-header-set, header: x-native-request, value: before-js} +http-scripts: + enabled: true + scripts: + - name: actual-request-body + phase: request + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.request.headers.length; i++) { + let header = input.request.headers[i]; + if (header.name === "x-native-request" && header.value === "before-js") found = true; + } + if (!found || input.body.data !== "original") return {type:"abort"}; + return {type:"modify",headers:[{op:"set",name:"x-js-request",values:["transformed"]}],body:{kind:"text",data:"transformed"}}; + } + - name: actual-response-body + phase: response + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.response.headers.length; i++) { + let header = input.response.headers[i]; + if (header.name === "x-native-proof" && header.value === "memory-tls") found = true; + } + if (!found || input.body.data !== "changed") return {type:"abort"}; + return {type:"modify",headers:[{op:"set",name:"x-js-response",values:["native-then-js"]}],body:{kind:"text",data:"Changed"}}; + } +"#; + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let factory = MemoryObfsFactory::new_v2ray_mux(cipher, 4096); + let weak = Arc::downgrade(&factory); + super::ss_obfs_reuse::run_scripted_with_factory(factory.clone(), SCRIPTS).await; + let receipt = factory.snapshot(); + assert_eq!((receipt.owners, receipt.mux_new), (1, 1), "{receipt:?}"); + drop(factory); + assert!( + weak.upgrade().is_none(), + "scripted HTTP parent retained factory" + ); + } +} diff --git a/src/http_processing/https_h1_vmess_http_cover_reuse_memory_tests.rs b/src/http_processing/https_h1_vmess_http_cover_reuse_memory_tests.rs new file mode 100644 index 0000000..38618ff --- /dev/null +++ b/src/http_processing/https_h1_vmess_http_cover_reuse_memory_tests.rs @@ -0,0 +1,367 @@ +//! Actual plain VMess HTTP cover under the original TLS/H1 cache. +//! Pure memory model; no official peer, downstream MITM or performance claim. +use super::*; +use crate::outbound::{ + MemoryVmessHttpCoverFactory, MemoryVmessHttpCoverReceipt, vmess::BodyCipher, +}; +use futures_util::FutureExt; +use std::panic::AssertUnwindSafe; + +const CIPHERS: [BodyCipher; 4] = [ + BodyCipher::Auto, + BodyCipher::None, + BodyCipher::Aes128Gcm, + BodyCipher::Chacha20Poly1305, +]; + +struct Closed { + serving: Result, String>, + failures: Vec, + receipt: MemoryVmessHttpCoverReceipt, +} + +async fn close( + running: Running, + fixture: &Fixture, + factory: &MemoryVmessHttpCoverFactory, +) -> Closed { + // Keep downstream open until the actual HTTP parent has dropped its cache. + running.cancellation.cancel(); + let serving = joined(running.serving).await; + let mut failures = Vec::new(); + if AssertUnwindSafe(factory.shutdown()) + .catch_unwind() + .await + .is_err() + { + failures.push("actual VMess HTTP-cover owner shutdown panicked".into()); + } + let peers = std::mem::take( + &mut *fixture + .origin + .0 + .peers + .lock() + .unwrap_or_else(|error| error.into_inner()), + ); + for peer in peers { + if let Err(error) = joined(peer).await { + failures.push(error); + } + } + drop(running.client); + Closed { + serving, + failures, + receipt: factory.snapshot(), + } +} + +struct Observed { + live: usize, + tcp: usize, + handshake: usize, + opens: usize, + accepts: usize, + prepares: usize, + heads: Vec, + uploads: Vec>, + sni: Vec, + negotiated: Vec>>, +} +impl Observed { + fn take(fixture: &Fixture) -> Self { + let stats = fixture.stats.snapshot(); + Self { + live: fixture.origin.count(&fixture.origin.0.live), + tcp: stats.tcp_current, + handshake: stats.handshake_current, + opens: fixture.origin.count(&fixture.origin.0.opens), + accepts: fixture.origin.count(&fixture.origin.0.accepts), + prepares: fixture.origin.count(&fixture.origin.0.prepares), + heads: fixture + .origin + .0 + .heads + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(), + uploads: fixture + .origin + .0 + .uploads + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(), + sni: fixture + .origin + .0 + .sni + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(), + negotiated: fixture + .origin + .0 + .negotiated + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(), + } + } +} + +fn closed_witness(closed: &Closed, observed: &Observed) { + assert!( + closed.serving.is_ok(), + "HTTP parent did not join: {:?}", + closed.serving + ); + assert!( + closed.failures.is_empty(), + "peer owners did not join: {:?}", + closed.failures + ); + assert_eq!(observed.live, 0); + assert_eq!(observed.tcp, 0); + assert_eq!(observed.handshake, 0); + let r = &closed.receipt; + assert_eq!(r.owners, 1, "{r:?}"); + assert_eq!(r.opens, 1, "{r:?}"); + assert_eq!(r.target_handshakes, 1, "{r:?}"); + assert_eq!(r.cover_requests, 1, "{r:?}"); + assert_eq!(r.cover_responses, 1, "{r:?}"); + assert_eq!( + r.client_drops, 1, + "actual VMess client IO survived parent join: {r:?}" + ); + assert_eq!( + r.peer_drops, 1, + "actual VMess peer IO survived peer join: {r:?}" + ); + assert_eq!(r.owner_cancelled, 1, "{r:?}"); + assert_eq!(r.owner_closed, 1, "{r:?}"); + assert_eq!(r.owner_wait_returned, 1, "{r:?}"); + assert_eq!(r.owner_tasks_empty, 1, "{r:?}"); + assert_eq!(r.auth_failures, 0, "{r:?}"); +} + +fn response_witness(result: io::Result<(String, Vec)>, scripted: bool) { + if scripted { + let (head, _) = result.as_ref().expect("scripted response must complete"); + assert!( + head.to_ascii_lowercase() + .contains("x-js-response: native-then-js"), + "actual response script witness missing" + ); + } + let expected: &[u8] = if scripted { b"Changed" } else { b"origin" }; + native_response(result, expected); +} + +async fn run(cipher: BodyCipher, reply: Reply, extra: &str, scripted: bool) { + let factory = MemoryVmessHttpCoverFactory::new(cipher, 4096); + let weak = Arc::downgrade(&factory); + let fixture = fixture(Some(b"http/1.1"), reply, scripted, extra); + *fixture.origin.0.vmess_http_cover.lock().unwrap() = Some(factory.clone()); + let mut running = start(&fixture); + let result = AssertUnwindSafe(async { + timeout(WAIT * 3, async { + match reply { + Reply::Persistent | Reply::FailSecond => { + let first = fixed_post(&mut running, "/one", b"original").await; + response_witness(first, scripted); + let second = fixed_post(&mut running, "/two", b"original").await; + if matches!(reply, Reply::FailSecond) { + if let Ok((head, body)) = second { + let response = framing::ResponseHead::parse(head.as_bytes())?; + assert!(matches!(response.status, 400 | 502)); + assert!(body.is_empty()); + } + } else { + response_witness(second, scripted); + // Stop a genuinely idle carrier while downstream stays open. + factory.begin_shutdown(); + } + } + Reply::WaitPost | Reply::EarlyPost => { + running.client.get_mut().write_all( + b"POST /partial HTTP/1.1\r\nHost: a.test\r\nContent-Length: 65536\r\n\r\nx" + ).await?; + if matches!(reply, Reply::WaitPost) { + timeout(WAIT, fixture.origin.0.partial.notified()) + .await + .map_err(|_| { + io::Error::new(io::ErrorKind::TimedOut, "actual partial upload") + })?; + factory.begin_shutdown(); + } else { + let head = framing::read_head(&mut running.client, 32768).await?; + let response = framing::ResponseHead::parse(&head)?; + let mut body = Vec::new(); + framing::transfer_body( + &mut running.client, + &mut body, + response.body("POST"), + WAIT, + response.trailer_blocklist(), + false, + ) + .await?; + let mut tail = [0; 1]; + assert_eq!(running.client.read(&mut tail).await?, 0); + assert_eq!(body, b"origin"); + assert!( + String::from_utf8(head) + .unwrap() + .to_ascii_lowercase() + .contains("connection: close") + ); + } + } + _ => unreachable!("R4 uses the original completed/partial POST modes"), + } + Ok::<_, io::Error>(()) + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "whole VMess/H1 memory exchange"))? + }) + .catch_unwind() + .await; + // Handshake/content/assertion errors and panics all reach the same cleanup. + let closed = close(running, &fixture, &factory).await; + let observed = Observed::take(&fixture); + drop(fixture); + drop(factory); + assert!( + weak.upgrade().is_none(), + "HTTP parent retained the actual VMess factory" + ); + closed_witness(&closed, &observed); + match result { + Ok(result) => result.unwrap(), + Err(panic) => std::panic::resume_unwind(panic), + } + assert_eq!(observed.opens, 1); + assert_eq!(observed.accepts, 1); + assert_eq!(observed.sni, vec!["a.test".to_owned()]); + assert_eq!(observed.negotiated, vec![Some(b"http/1.1".to_vec())]); + let expected_heads = if matches!(reply, Reply::Persistent | Reply::FailSecond) { + 2 + } else { + 1 + }; + assert_eq!(observed.prepares, expected_heads); + let heads = &observed.heads; + assert_eq!(heads.len(), expected_heads); + assert!( + heads + .iter() + .all(|head| head.to_ascii_lowercase().contains("connection: keep-alive")) + ); + if scripted { + assert!( + heads.iter().all(|head| { + head.to_ascii_lowercase() + .contains("x-js-request: transformed") + }), + "actual request script witness missing at origin" + ); + } + let uploads = &observed.uploads; + let complete_body: &[u8] = if scripted { + b"transformed" + } else { + b"original" + }; + let expected = match reply { + Reply::Persistent => vec![complete_body.to_vec(), complete_body.to_vec()], + Reply::FailSecond => vec![complete_body.to_vec()], + _ => vec![b"x".to_vec()], + }; + assert_eq!(*uploads, expected); + match reply { + Reply::FailSecond => assert!( + closed.serving.unwrap().is_err(), + "submitted second POST did not reach its fault" + ), + Reply::WaitPost => { + if let Err(error) = closed.serving.unwrap() { + assert_eq!( + error.kind(), + io::ErrorKind::ConnectionAborted, + "partial upload must finish normally or observe the explicit node cancellation" + ); + } + } + _ => closed.serving.unwrap().expect("normal HTTP parent failed"), + } +} + +#[tokio::test] +async fn vmess_http_cover_https_h1_two_posts_share_one_authenticated_carrier() { + for cipher in CIPHERS { + run(cipher, Reply::Persistent, "", false).await; + } +} +#[tokio::test] +async fn vmess_http_cover_https_h1_submitted_second_post_is_not_replayed() { + for cipher in CIPHERS { + run(cipher, Reply::FailSecond, "", false).await; + } +} +#[tokio::test] +async fn vmess_http_cover_https_h1_active_stop_drops_partial_upload() { + for cipher in CIPHERS { + run(cipher, Reply::WaitPost, "", false).await; + } +} +#[tokio::test] +async fn vmess_http_cover_https_h1_early_final_retires_uncertain_upload() { + for cipher in CIPHERS { + run(cipher, Reply::EarlyPost, "", false).await; + } +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn vmess_http_cover_https_h1_native_then_js_reuses_one_authenticated_carrier() { + const SCRIPTS: &str = r#" - {url: 'https://a.test/', match: prefix, action: request-header-set, header: x-native-request, value: before-js} +http-scripts: + enabled: true + scripts: + - name: actual-request-body + phase: request + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.request.headers.length; i++) { + let header = input.request.headers[i]; + if (header.name === "x-native-request" && header.value === "before-js") found = true; + } + if (!found || input.body.data !== "original") return {type:"abort"}; + return {type:"modify",headers:[{op:"set",name:"x-js-request",values:["transformed"]}],body:{kind:"text",data:"transformed"}}; + } + - name: actual-response-body + phase: response + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.response.headers.length; i++) { + let header = input.response.headers[i]; + if (header.name === "x-native-proof" && header.value === "memory-tls") found = true; + } + if (!found || input.body.data !== "changed") return {type:"abort"}; + return {type:"modify",headers:[{op:"set",name:"x-js-response",values:["native-then-js"]}],body:{kind:"text",data:"Changed"}}; + } +"#; + for cipher in CIPHERS { + run(cipher, Reply::Persistent, SCRIPTS, true).await; + } +} diff --git a/src/http_processing/https_h2_reuse_memory_tests.rs b/src/http_processing/https_h2_reuse_memory_tests.rs new file mode 100644 index 0000000..984709c --- /dev/null +++ b/src/http_processing/https_h2_reuse_memory_tests.rs @@ -0,0 +1,1003 @@ +//! Real TLS/H2 and ALPN-H1 over duplex; no listener, DNS or file material. +#[cfg(feature = "outbound-shadowsocks")] +#[path = "https_h2_ss_obfs_reuse_memory_tests.rs"] +mod ss_obfs_reuse; + +#[cfg(feature = "outbound-shadowsocks")] +#[path = "https_h2_ss_v2ray_mux_reuse_memory_tests.rs"] +mod ss_v2ray_mux_reuse; + +#[cfg(feature = "outbound-vmess")] +#[path = "https_h2_vmess_http_cover_reuse_memory_tests.rs"] +mod vmess_http_cover_reuse; + +use crate::{ + dispatch::{ + BoxStream, DatagramTransport, DispatchError, Dispatcher, HttpTcpPlan, HttpTcpReuseKey, + }, + http_processing::{ + HttpContext, authority::Authority, config::Document, private_context::CaMaterial, + }, + security::SecurityContext, + session::{DatagramSession, Destination, InboundKind, InboundMetadata, StreamSession}, +}; +use async_trait::async_trait; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use bytes::Bytes; +use futures_util::{FutureExt, StreamExt, stream::FuturesUnordered}; +use http::{Request, Response, StatusCode}; +use std::panic::AssertUnwindSafe; +use std::{ + pin::Pin, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + task::{Context, Poll}, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf}, + task::JoinHandle, + time::{Duration, timeout}, +}; +use tokio_util::sync::CancellationToken; + +const WAIT: Duration = Duration::from_secs(3); +const PAYLOAD: &[u8] = b"from-origin"; +#[derive(Clone, Copy, Default)] +enum PostReply { + #[default] + Complete, + Early, + Wait, + FailSecond, +} +#[derive(Default)] +struct GoAwayProbe { + observed: CancellationToken, + release_response: CancellationToken, + requests: Mutex>, +} + +#[derive(Clone)] +struct Origin(Arc); +struct Inner { + authority: Arc, + h2: bool, + scope: Arc<()>, + key: AtomicUsize, + reusable: AtomicBool, + prepares: AtomicUsize, + opens: AtomicUsize, + accepts: Arc, + live: Arc, + sni: Arc>>, + tasks: Mutex>>, + post_reply: PostReply, + uploads: Arc>>>, + post_heads: Arc, + post_started: Arc, + go_away: Option>, + #[cfg(feature = "outbound-shadowsocks")] + obfs: Mutex>>, + #[cfg(feature = "outbound-vmess")] + vmess_http_cover: Mutex>>, +} +struct Key { + scope: Arc<()>, + version: usize, + session: StreamSession, +} +impl PartialEq for Key { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.scope, &other.scope) + && self.version == other.version + && self.session == other.session + } +} +impl Eq for Key {} +struct Plan { + origin: Origin, + session: StreamSession, + key: Option, +} +#[async_trait] +impl HttpTcpPlan for Plan { + fn reuse_key(&self) -> Option<&HttpTcpReuseKey> { + self.key.as_ref() + } + async fn connect(self: Box) -> Result { + self.origin.open(self.session).await + } +} +struct Io { + io: T, + live: Arc, +} +impl Io { + fn new(io: T, live: &Arc) -> Self { + live.fetch_add(1, Ordering::AcqRel); + Self { + io, + live: live.clone(), + } + } +} +impl Drop for Io { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::AcqRel); + } +} +impl AsyncRead for Io { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, buf) + } +} +impl AsyncWrite for Io { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, bytes) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} +#[async_trait] +impl Dispatcher for Origin { + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + self.0.prepares.fetch_add(1, Ordering::AcqRel); + let key = self.0.reusable.load(Ordering::Acquire).then(|| { + HttpTcpReuseKey::new(Key { + scope: self.0.scope.clone(), + version: self.0.key.load(Ordering::Acquire), + session: session.clone(), + }) + }); + Ok(Some(Box::new(Plan { + origin: self.clone(), + session, + key, + }))) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.open(session).await + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +type AcceptedMemoryPeer = + Pin> + Send>>; + +fn plain_memory_pair(live: &Arc) -> (BoxStream, AcceptedMemoryPeer) { + let (client, peer) = tokio::io::duplex(8192); + let peer = Io::new(peer, live); + ( + Box::new(client), + Box::pin(async move { Ok(Box::new(peer) as BoxStream) }), + ) +} + +impl Origin { + async fn open(&self, session: StreamSession) -> Result { + let connection_index = self.0.opens.fetch_add(1, Ordering::AcqRel) + 1; + let name = match &session.destination { + Destination::Domain { host, .. } => host.clone(), + _ => session.sniffed_domain.clone().unwrap(), + }; + let mut config = (*self.0.authority.server_config(&name).unwrap()).clone(); + config.alpn_protocols = vec![if self.0.h2 { + b"h2".to_vec() + } else { + b"http/1.1".to_vec() + }]; + #[cfg(feature = "outbound-shadowsocks")] + let factory = self.0.obfs.lock().unwrap().clone(); + #[cfg(feature = "outbound-vmess")] + let vmess = self.0.vmess_http_cover.lock().unwrap().clone(); + #[cfg(all(feature = "outbound-shadowsocks", feature = "outbound-vmess"))] + if factory.is_some() && vmess.is_some() { + return Err(DispatchError::NotAllowed); + } + let fallback = async { + #[cfg(feature = "outbound-shadowsocks")] + if let Some(factory) = factory { + let (client, peer) = factory.open(session.destination.clone()).await?; + let live = self.0.live.clone(); + return Ok::<_, std::io::Error>(( + client, + Box::pin(async move { + peer.await + .map(|io| Box::new(Io::new(io, &live)) as BoxStream) + }) as AcceptedMemoryPeer, + )); + } + Ok::<_, std::io::Error>(plain_memory_pair(&self.0.live)) + }; + #[cfg(feature = "outbound-vmess")] + let (client, peer): (BoxStream, AcceptedMemoryPeer) = match vmess { + Some(factory) => { + let (client, peer) = factory.open(session.destination.clone()).await?; + let live = self.0.live.clone(); + ( + client, + Box::pin(async move { + peer.await + .map(|io| Box::new(Io::new(io, &live)) as BoxStream) + }), + ) + } + None => fallback.await?, + }; + #[cfg(not(feature = "outbound-vmess"))] + let (client, peer) = fallback.await?; + let accepts = self.0.accepts.clone(); + let sni = self.0.sni.clone(); + let h2 = self.0.h2; + let post_reply = self.0.post_reply; + let uploads = self.0.uploads.clone(); + let post_heads = self.0.post_heads.clone(); + let post_started = self.0.post_started.clone(); + let go_away = self.0.go_away.clone(); + let task = tokio::spawn(async move { + let peer = peer + .await + .expect("memory carrier handshake and exact target"); + let Ok(mut tls) = tokio_rustls::TlsAcceptor::from(Arc::new(config)) + .accept(peer) + .await + else { + return; + }; + accepts.fetch_add(1, Ordering::AcqRel); + sni.lock() + .unwrap() + .push(tls.get_ref().1.server_name().unwrap_or_default().to_owned()); + if h2 { + let mut connection = h2::server::Builder::new() + .handshake::<_, Bytes>(tls) + .await + .unwrap(); + let mut exchanges = FuturesUnordered::new(); + let mut sequence = 0; + let mut go_away_ping: Option = None; + loop { + tokio::select! {biased; + _=exchanges.next(),if !exchanges.is_empty()=>{}, + pong=std::future::poll_fn(|cx| { + go_away_ping.as_mut().unwrap().poll_pong(cx) + }),if go_away_ping.is_some()=>{ + pong.expect("upstream PING after GOAWAY acknowledged"); + go_away_ping = None; + go_away.as_ref().unwrap().observed.cancel(); + }, + accepted=connection.accept()=>{ + let Some(Ok((request, mut response))) = accepted else { break; }; + sequence += 1; + assert_eq!(request.headers()["x-request"], "native"); + if let Some(probe) = &go_away { + probe.requests.lock().unwrap().push((connection_index, request.uri().path().to_owned())); + } + let held = go_away.clone().filter(|_| connection_index == 1 && sequence == 1); + if held.is_some() { + connection.graceful_shutdown(); + // h2 queues its NO_ERROR GOAWAY before sending PING. + // The peer's PONG proves the ordered frame was processed. + let mut ping = connection.ping_pong().unwrap(); + ping.send_ping(h2::Ping::opaque()).unwrap(); + go_away_ping = Some(ping); + } + let uploads = uploads.clone(); + let post_heads = post_heads.clone(); + let post_started = post_started.clone(); + exchanges.push(async move { + if request.method() == http::Method::POST { + post_heads.fetch_add(1, Ordering::AcqRel); + if matches!(post_reply, PostReply::FailSecond) && sequence == 2 { + response.send_reset(h2::Reason::INTERNAL_ERROR); + return; + } + let expected = request.headers()["content-length"].to_str().unwrap().parse::().unwrap(); + assert!(expected <= 65536); + let mut input = request.into_body(); + let mut bytes = Vec::new(); + while let Some(frame) = input.data().await { + let Ok(frame) = frame else { return; }; + bytes.extend_from_slice(&frame); + assert!(bytes.len() <= expected); + if input.flow_control().release_capacity(frame.len()).is_err() { return; } + if matches!(post_reply, PostReply::Early | PostReply::Wait) { + uploads.lock().unwrap().push(bytes); + post_started.notify_one(); + if matches!(post_reply, PostReply::Wait) { + while input.data().await.is_some() {} + return; + } + let Ok(mut body) = response.send_response(Response::builder().header("content-length", PAYLOAD.len()).header("content-type", "text/plain").body(()).unwrap(), false) else { return; }; + let _ = body.send_data(Bytes::from_static(PAYLOAD), true); + // Return the unread receive owner only after committing + // a complete final response on the same real stream. + return; + } + } + assert_eq!(bytes.len(), expected); + assert!(input.trailers().await.unwrap().is_none()); + uploads.lock().unwrap().push(bytes); + } else { + assert!(request.body().is_end_stream()); + } + if let Some(probe) = held { + probe.release_response.cancelled().await; + } + let Ok(mut body) = response.send_response(Response::builder().header("content-length", PAYLOAD.len()).header("content-type", "text/plain").body(()).unwrap(), false) else { return; }; + let _ = body.send_data(Bytes::from_static(PAYLOAD), true); + }); + } + } + } + } else { + let mut head = Vec::new(); + while head.len() < 32768 && !head.ends_with(b"\r\n\r\n") { + let Ok(byte) = tls.read_u8().await else { + return; + }; + head.push(byte); + } + assert!( + String::from_utf8(head) + .unwrap() + .to_ascii_lowercase() + .contains("x-request: native\r\n") + ); + tls.write_all(format!("HTTP/1.1 200 OK\r\nContent-Length: {}\r\nContent-Type: text/plain\r\nConnection: close\r\n\r\n",PAYLOAD.len()).as_bytes()).await.unwrap(); + tls.write_all(PAYLOAD).await.unwrap(); + let _ = tls.shutdown().await; + } + }); + self.0.tasks.lock().unwrap().push(task); + Ok(Box::new(Io::new(client, &self.0.live))) + } + async fn join(&self) -> Result<(), String> { + let tasks = std::mem::take( + &mut *self + .0 + .tasks + .lock() + .unwrap_or_else(|error| error.into_inner()), + ); + let mut errors = Vec::new(); + for task in tasks { + if let Err(error) = join_owned(task).await { + errors.push(error); + } + } + if self.0.live.load(Ordering::Acquire) != 0 { + errors.push("origin I/O owners remain".into()); + } + if errors.is_empty() { + Ok(()) + } else { + Err(errors.join("; ")) + } + } +} +#[cfg(feature = "outbound-shadowsocks")] +fn begin_obfs_owner_shutdown(origin: &Origin) { + let factory = origin + .0 + .obfs + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(factory) = factory { + factory.begin_shutdown(); + } +} + +#[cfg(feature = "outbound-vmess")] +fn begin_vmess_owner_shutdown(origin: &Origin) { + let factory = origin + .0 + .vmess_http_cover + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + if let Some(factory) = factory { + factory.begin_shutdown(); + } +} + +#[cfg(feature = "outbound-vmess")] +async fn shutdown_vmess_owner(origin: &Origin) -> Result<(), &'static str> { + let factory = origin + .0 + .vmess_http_cover + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + match factory { + Some(factory) => AssertUnwindSafe(factory.shutdown()) + .catch_unwind() + .await + .map_err(|_| "actual VMess HTTP-cover owner shutdown panicked"), + None => Ok(()), + } +} + +fn pem(label: &str, bytes: &[u8]) -> String { + format!( + "-----BEGIN {label}-----\n{}\n-----END {label}-----\n", + STANDARD.encode(bytes) + ) +} +fn fixture(h2: bool, extra: &str) -> (HttpContext, Origin) { + fixture_post(h2, extra, PostReply::Complete) +} +fn fixture_post(h2: bool, extra: &str, post_reply: PostReply) -> (HttpContext, Origin) { + fixture_with_probe(h2, extra, post_reply, None) +} + +fn fixture_with_probe( + h2: bool, + extra: &str, + post_reply: PostReply, + go_away: Option>, +) -> (HttpContext, Origin) { + let mut params = rcgen::CertificateParams::default(); + params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + params.key_usages = vec![rcgen::KeyUsagePurpose::KeyCertSign]; + let key = rcgen::KeyPair::generate().unwrap(); + let cert = params.self_signed(&key).unwrap(); + let cert_pem = pem("CERTIFICATE", cert.der()); + let key_pem = pem("PRIVATE KEY", &key.serialize_der()); + let authority = Authority::load(&cert_pem, &key_pem).unwrap(); + let document=Document::parse(&format!("mitm:\n enabled: true\n domains: [{{pattern: a.test}}, {{pattern: b.test}}]\nrewrite:\n enabled: true\n rules:\n - {{url: 'https://a.test/', match: prefix, action: request-header-set, header: x-request, value: native}}\n - {{url: 'https://a.test/', match: prefix, action: response-header-set, header: x-proof, value: native}}\n - {{url: 'https://a.test/', match: prefix, action: response-body-replace, search: '-', replacement: '_'}}\n{extra}")).unwrap(); + let candidate = document + .compile(&std::collections::BTreeMap::new()) + .unwrap(); + let material = CaMaterial { + certificate: cert_pem, + private_key: zeroize::Zeroizing::new(key_pem), + }; + let policy = candidate.bind_ca(Some(&material)).unwrap(); + let mut roots = rustls::RootCertStore::empty(); + roots.add(cert.der().clone()).unwrap(); + let origin = Origin(Arc::new(Inner { + authority, + h2, + scope: Arc::new(()), + key: AtomicUsize::new(1), + reusable: AtomicBool::new(true), + prepares: AtomicUsize::new(0), + opens: AtomicUsize::new(0), + accepts: Arc::new(AtomicUsize::new(0)), + live: Arc::new(AtomicUsize::new(0)), + sni: Arc::new(Mutex::new(Vec::new())), + tasks: Mutex::new(Vec::new()), + post_reply, + uploads: Arc::default(), + post_heads: Arc::default(), + post_started: Arc::new(tokio::sync::Notify::new()), + go_away, + #[cfg(feature = "outbound-shadowsocks")] + obfs: Mutex::new(None), + #[cfg(feature = "outbound-vmess")] + vmess_http_cover: Mutex::new(None), + })); + ( + HttpContext::new( + policy, + Arc::new(origin.clone()), + SecurityContext::with_tls_roots(roots), + ), + origin, + ) +} +fn session() -> StreamSession { + StreamSession { + metadata: InboundMetadata::new(443), + inbound: InboundKind::Tun, + source: "198.18.0.2:30000".parse().unwrap(), + destination: Destination::Ip("203.0.113.1:443".parse().unwrap()), + sniffed_domain: Some("a.test".into()), + } +} +async fn join_owned(mut task: JoinHandle) -> Result { + match timeout(WAIT, &mut task).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(format!("memory owner join: {error}")), + Err(_) => { + task.abort(); + let _ = task.await; + Err("memory owner required abort after join timeout".into()) + } + } +} +async fn reply(sender: h2::client::SendRequest, path: &str) -> Result, String> { + timeout(WAIT, async { + let mut sender = sender + .ready() + .await + .map_err(|_| "downstream sender not ready")?; + let request = Request::builder() + .uri(format!("https://a.test/{path}")) + .header("accept-encoding", "identity") + .body(()) + .map_err(|_| "request construction")?; + let (response, _) = sender + .send_request(request, true) + .map_err(|_| "downstream request failed")?; + let response = response.await.map_err(|_| "response head failed")?; + if response.status() != StatusCode::OK + || response + .headers() + .get("x-proof") + .map(|value| value.as_bytes()) + != Some(b"native".as_slice()) + { + return Err("rewritten response head differs".into()); + } + let mut body = response.into_body(); + let mut bytes = Vec::new(); + while let Some(frame) = body.data().await { + let frame = frame.map_err(|_| "response body failed")?; + bytes.extend_from_slice(&frame); + body.flow_control() + .release_capacity(frame.len()) + .map_err(|_| "receive credit release failed")?; + } + Ok::<_, String>(bytes) + }) + .await + .map_err(|_| "complete H2 reply deadline".to_owned())? +} +async fn exercise(h2: bool, concurrent: bool, change_key: bool, keyless: bool) { + let (context, origin) = fixture(h2, ""); + origin.0.reusable.store(!keyless, Ordering::Release); + let stop = CancellationToken::new(); + let cancel = stop.clone(); + let (client, mut server) = tokio::io::duplex(8192); + let owner = tokio::spawn(async move { context.serve_h2(&mut server, session(), cancel).await }); + let mut sender_owner = None; + let mut driver_owner = None; + let result = AssertUnwindSafe(async { + timeout(WAIT * 3, async { + let (sender, driver) = h2::client::handshake(client) + .await + .map_err(|_| "downstream handshake failed")?; + sender_owner = Some(sender); + driver_owner = Some(tokio::spawn(driver)); + let sender = sender_owner.as_ref().ok_or("missing downstream sender")?; + if concurrent { + let (a, b) = + tokio::join!(reply(sender.clone(), "one"), reply(sender.clone(), "two")); + if a? != b"from_origin" || b? != b"from_origin" { + return Err("concurrent full rewritten bytes differ".into()); + } + } else { + if reply(sender.clone(), "one").await? != b"from_origin" { + return Err("first full rewritten bytes differ".into()); + } + if change_key { + origin.0.key.store(2, Ordering::Release); + } + if reply(sender.clone(), "two").await? != b"from_origin" { + return Err("second full rewritten bytes differ".into()); + } + } + let expected = if h2 && !change_key && !keyless { 1 } else { 2 }; + if origin.0.prepares.load(Ordering::Acquire) != 2 + || origin.0.opens.load(Ordering::Acquire) != expected + || origin.0.accepts.load(Ordering::Acquire) != expected + { + return Err("fresh-route / physical-open / TLS-accept counts differ".into()); + } + if !origin + .0 + .sni + .lock() + .map_err(|_| "SNI witness poisoned")? + .iter() + .all(|name| name == "a.test") + { + return Err("authenticated upstream SNI differs".into()); + } + Ok::<_, String>(()) + }) + .await + .map_err(|_| "whole memory exchange deadline".to_owned())? + }) + .catch_unwind() + .await; + // Always close and actually await every owned task before propagating any + // mismatch, timeout or panic. A timeout abort is itself a test failure. + #[cfg(feature = "outbound-vmess")] + begin_vmess_owner_shutdown(&origin); + stop.cancel(); + let owner_join = join_owned(owner).await; + drop(sender_owner.take()); + let driver_join = if let Some(driver) = driver_owner.take() { + join_owned(driver).await.map(|_| ()) + } else { + Ok(()) + }; + #[cfg(feature = "outbound-shadowsocks")] + let carrier_shutdown = { + let factory = origin + .0 + .obfs + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + match factory { + Some(factory) => AssertUnwindSafe(factory.shutdown()) + .catch_unwind() + .await + .map_err(|_| "actual obfs owner shutdown panicked"), + None => Ok(()), + } + }; + #[cfg(feature = "outbound-vmess")] + let vmess_shutdown = shutdown_vmess_owner(&origin).await; + let peers_join = origin.join().await; + let result = match result { + Ok(result) => result, + Err(panic) => std::panic::resume_unwind(panic), + }; + assert!(result.is_ok(), "{result:?}"); + assert!(matches!(&owner_join, Ok(Ok(()))), "{owner_join:?}"); + assert!(driver_join.is_ok(), "{driver_join:?}"); + assert!(peers_join.is_ok(), "{peers_join:?}"); + #[cfg(feature = "outbound-shadowsocks")] + assert!(carrier_shutdown.is_ok(), "{carrier_shutdown:?}"); + #[cfg(feature = "outbound-vmess")] + assert!(vmess_shutdown.is_ok(), "{vmess_shutdown:?}"); +} +#[tokio::test] +async fn h2_tls_sequential_and_concurrent_gets_reuse_one_authenticated_origin() { + exercise(true, false, false, false).await; + exercise(true, true, false, false).await; +} +#[tokio::test] +async fn h2_tls_changed_route_key_and_keyless_plan_do_not_reuse() { + exercise(true, false, true, false).await; + exercise(true, false, false, true).await; +} +#[tokio::test] +async fn h2_actual_h1_alpn_uses_original_connected_io_once_per_exchange() { + exercise(false, false, false, false).await; +} + +async fn post_response( + response: h2::client::ResponseFuture, + early: bool, +) -> Result, String> { + let response = response + .await + .map_err(|error| format!("POST response head: {error}"))?; + if response.status() != StatusCode::OK + || response.headers().get("x-proof").map(|h| h.as_bytes()) != Some(b"native".as_slice()) + { + return Err("POST response head was not fully processed".into()); + } + let mut body = response.into_body(); + let mut received = Vec::new(); + while let Some(frame) = body.data().await { + match frame { + Ok(frame) => { + received.extend_from_slice(&frame); + body.flow_control() + .release_capacity(frame.len()) + .map_err(|_| "POST response credit")?; + } + // A complete early final may close the unread upload with NO_ERROR; + // it cannot excuse a single missing or changed response byte. + Err(error) + if early + && error.reason() == Some(h2::Reason::NO_ERROR) + && received == b"from_origin" => + { + break; + } + Err(error) => return Err(format!("POST response body: {error}")), + } + } + if received != b"from_origin" { + return Err("POST final response bytes differ".into()); + } + Ok(received) +} + +async fn send_post(sender: h2::client::SendRequest, path: &str) -> Result, String> { + let mut sender = sender.ready().await.map_err(|_| "POST sender readiness")?; + let request = Request::builder() + .method("POST") + .uri(format!("https://a.test/{path}")) + .header("content-type", "text/plain") + .header("content-length", 8) + .body(()) + .map_err(|_| "POST request construction")?; + let (response, mut upload) = sender + .send_request(request, false) + .map_err(|_| "POST send head")?; + upload + .send_data(Bytes::from_static(b"original"), true) + .map_err(|_| "POST send body")?; + post_response(response, false).await +} + +#[tokio::test] +async fn h2_remote_goaway_moves_unsent_post_to_fresh_origin_without_interrupting_inflight_get() { + let probe = Arc::new(GoAwayProbe::default()); + let (context, origin) = fixture_with_probe(true, "", PostReply::Complete, Some(probe.clone())); + let stop = CancellationToken::new(); + let cancel = stop.clone(); + let (client, mut server) = tokio::io::duplex(8192); + let owner = tokio::spawn(async move { context.serve_h2(&mut server, session(), cancel).await }); + let mut driver_owner = None; + let result = AssertUnwindSafe(timeout(WAIT * 3, async { + let (sender, driver) = h2::client::handshake(client) + .await + .map_err(|error| error.to_string())?; + driver_owner = Some(tokio::spawn(driver)); + let first = reply(sender.clone(), "held"); + tokio::pin!(first); + tokio::select! { + () = probe.observed.cancelled() => {}, + result = &mut first => return Err(format!("first response ended before GOAWAY was acknowledged: {result:?}")), + } + if origin.0.live.load(Ordering::Acquire) != 2 { + return Err("original upstream closed before the replacement request".into()); + } + send_post(sender, "replacement").await?; + if origin.0.live.load(Ordering::Acquire) != 4 { + return Err("original and replacement upstream were not both live".into()); + } + probe.release_response.cancel(); + if first.await? != b"from_origin" { + return Err("original response bytes differ after GOAWAY".into()); + } + Ok::<_, String>(()) + })) + .catch_unwind() + .await; + probe.release_response.cancel(); + stop.cancel(); + let owner_join = join_owned(owner).await; + let driver_join = match driver_owner { + Some(driver) => join_owned(driver).await.map(|_| ()), + None => Err("downstream driver never started".into()), + }; + let peers_join = origin.join().await; + match result { + Ok(result) => result.expect("GOAWAY exchange deadline").unwrap(), + Err(panic) => std::panic::resume_unwind(panic), + } + assert!(matches!(owner_join, Ok(Ok(()))), "{owner_join:?}"); + assert!(driver_join.is_ok(), "{driver_join:?}"); + assert!(peers_join.is_ok(), "{peers_join:?}"); + assert_eq!(origin.0.prepares.load(Ordering::Acquire), 2); + assert_eq!(origin.0.opens.load(Ordering::Acquire), 2); + assert_eq!(origin.0.accepts.load(Ordering::Acquire), 2); + assert_eq!(origin.0.post_heads.load(Ordering::Acquire), 1); + assert_eq!(*origin.0.uploads.lock().unwrap(), [b"original".to_vec()]); + assert_eq!( + *probe.requests.lock().unwrap(), + [(1, "/held".to_owned()), (2, "/replacement".to_owned())] + ); +} + +async fn wait_post_released(origin: &Origin) -> Result<(), String> { + timeout(WAIT, async { + while origin.0.live.load(Ordering::Acquire) != 0 { + tokio::task::yield_now().await; + } + }) + .await + .map_err(|_| "uncertain POST retained its physical owner".to_owned()) +} + +async fn exercise_post(mode: PostReply, native: bool, change_key: bool) { + let extra = if native { + " - {url: 'https://a.test/', match: prefix, action: request-body-set, value: transformed}\n" + } else { + "" + }; + let (context, origin) = fixture_post(true, extra, mode); + exercise_post_fixture(mode, native, change_key, context, origin).await; +} + +async fn exercise_post_fixture( + mode: PostReply, + native: bool, + change_key: bool, + context: HttpContext, + origin: Origin, +) { + let stop = CancellationToken::new(); + let cancel = stop.clone(); + let (client, mut server) = tokio::io::duplex(8192); + let owner = tokio::spawn(async move { context.serve_h2(&mut server, session(), cancel).await }); + let mut sender_owner = None; + let mut driver_owner = None; + let result = AssertUnwindSafe(async { + timeout(WAIT * 3, async { + let (sender, driver) = h2::client::handshake(client) + .await + .map_err(|_| "POST downstream handshake")?; + sender_owner = Some(sender); + driver_owner = Some(tokio::spawn(driver)); + let sender = sender_owner.as_ref().ok_or("missing POST sender")?; + if matches!(mode, PostReply::Early | PostReply::Wait) { + let mut ready = sender + .clone() + .ready() + .await + .map_err(|_| "partial POST readiness")?; + let request = Request::builder() + .method("POST") + .uri("https://a.test/unfinished") + .header("content-length", 65536) + .body(()) + .map_err(|_| "partial POST construction")?; + let (response, mut upload) = ready + .send_request(request, false) + .map_err(|_| "partial POST send")?; + upload + .send_data(Bytes::from_static(b"x"), false) + .map_err(|_| "partial POST prefix")?; + origin.0.post_started.notified().await; + if matches!(mode, PostReply::Wait) { + // Keep both the downstream upload and response owners alive + // while cancelling the actual serve_h2 parent. + #[cfg(feature = "outbound-shadowsocks")] + begin_obfs_owner_shutdown(&origin); + #[cfg(feature = "outbound-vmess")] + begin_vmess_owner_shutdown(&origin); + stop.cancel(); + drop((upload, response)); + } else { + post_response(response, true).await?; + // The physical connection must retire despite a complete + // valid final response: its upload never reached EOS. + wait_post_released(&origin).await?; + drop(upload); + if reply(sender.clone(), "after-early").await? != b"from_origin" { + return Err("post-retirement GET differs".into()); + } + if origin.0.opens.load(Ordering::Acquire) != 2 { + return Err("early POST physical connection was reused".into()); + } + } + if *origin.0.uploads.lock().unwrap() != vec![b"x".to_vec()] { + return Err("partial POST input differs".into()); + } + } else { + send_post(sender.clone(), "one").await?; + if change_key { + origin.0.key.store(2, Ordering::Release); + } + let second = send_post(sender.clone(), "two").await; + if matches!(mode, PostReply::FailSecond) { + if second.is_ok() { + return Err( + "second submitted POST was replayed or did not reach the fault".into(), + ); + } + wait_post_released(&origin).await?; + } else { + second?; + } + let expected_opens = if change_key { 2 } else { 1 }; + if origin.0.prepares.load(Ordering::Acquire) != 2 + || origin.0.opens.load(Ordering::Acquire) != expected_opens + || origin.0.accepts.load(Ordering::Acquire) != expected_opens + || origin.0.post_heads.load(Ordering::Acquire) != 2 + { + return Err("completed POST route/open/TLS/request counts differ".into()); + } + let body = if native { + b"transformed".as_slice() + } else { + b"original".as_slice() + }; + let count = if matches!(mode, PostReply::FailSecond) { + 1 + } else { + 2 + }; + if *origin.0.uploads.lock().unwrap() != vec![body.to_vec(); count] { + return Err("fully consumed POST payloads differ".into()); + } + } + Ok::<_, String>(()) + }) + .await + .map_err(|_| "whole POST memory exchange deadline".to_owned())? + }) + .catch_unwind() + .await; + // The regression stays red without leaking owners, including on assertion, + // handshake, content, timeout and early-response failures. + #[cfg(feature = "outbound-shadowsocks")] + begin_obfs_owner_shutdown(&origin); + #[cfg(feature = "outbound-vmess")] + begin_vmess_owner_shutdown(&origin); + stop.cancel(); + let owner_join = join_owned(owner).await; + drop(sender_owner.take()); + let driver_join = if let Some(driver) = driver_owner.take() { + join_owned(driver).await.map(|_| ()) + } else { + Ok(()) + }; + #[cfg(feature = "outbound-shadowsocks")] + let carrier_shutdown = { + let factory = origin + .0 + .obfs + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + match factory { + Some(factory) => AssertUnwindSafe(factory.shutdown()) + .catch_unwind() + .await + .map_err(|_| "actual obfs owner shutdown panicked"), + None => Ok(()), + } + }; + #[cfg(feature = "outbound-vmess")] + let vmess_shutdown = shutdown_vmess_owner(&origin).await; + let peers_join = origin.join().await; + let result = match result { + Ok(result) => result, + Err(panic) => std::panic::resume_unwind(panic), + }; + assert!(result.is_ok(), "{result:?}"); + assert!(matches!(&owner_join, Ok(Ok(()))), "{owner_join:?}"); + assert!(driver_join.is_ok(), "{driver_join:?}"); + assert!(peers_join.is_ok(), "{peers_join:?}"); + #[cfg(feature = "outbound-shadowsocks")] + assert!(carrier_shutdown.is_ok(), "{carrier_shutdown:?}"); + #[cfg(feature = "outbound-vmess")] + assert!(vmess_shutdown.is_ok(), "{vmess_shutdown:?}"); +} + +#[tokio::test] +async fn completed_post_h2_reuses_after_full_body_and_checks_fresh_route() { + exercise_post(PostReply::Complete, false, false).await; + exercise_post(PostReply::Complete, true, false).await; + exercise_post(PostReply::Complete, false, true).await; +} + +#[tokio::test] +async fn completed_post_h2_sent_second_stream_is_never_replayed() { + exercise_post(PostReply::FailSecond, false, false).await; +} + +#[tokio::test] +async fn completed_post_h2_partial_upload_early_final_retires_physical_owner() { + exercise_post(PostReply::Early, false, false).await; +} + +#[tokio::test] +async fn completed_post_h2_cancel_joins_partial_upload_and_driver() { + exercise_post(PostReply::Wait, false, false).await; +} diff --git a/src/http_processing/https_h2_ss_obfs_reuse_memory_tests.rs b/src/http_processing/https_h2_ss_obfs_reuse_memory_tests.rs new file mode 100644 index 0000000..4b68b76 --- /dev/null +++ b/src/http_processing/https_h2_ss_obfs_reuse_memory_tests.rs @@ -0,0 +1,99 @@ +//! Actual SS/obfs beneath the existing authenticated H2 POST/cache fixture. +use super::*; +use crate::{config::ShadowsocksCipher, outbound::MemoryObfsFactory}; + +const CIPHERS: [ShadowsocksCipher; 3] = [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, +]; + +async fn run(cipher: ShadowsocksCipher, tls: bool, mode: PostReply) { + run_with_factory(MemoryObfsFactory::new(cipher, tls, 4096), mode).await; +} + +pub(super) async fn run_with_factory(factory: Arc, mode: PostReply) { + run_with_factory_options(factory, mode, "", false).await; +} + +#[cfg(target_vendor = "apple")] +pub(super) async fn run_scripted_with_factory(factory: Arc, extra: &str) { + run_with_factory_options(factory, PostReply::Complete, extra, true).await; +} + +async fn run_with_factory_options( + factory: Arc, + mode: PostReply, + extra: &str, + scripted: bool, +) { + let (context, origin) = fixture_post(true, extra, mode); + *origin.0.obfs.lock().unwrap() = Some(factory.clone()); + // The original helper drives real complete/partial POSTs and cleanup on + // content error, timeout or panic. It does not replace the H2 session/cache. + exercise_post_fixture(mode, scripted, false, context, origin.clone()).await; + let r = factory.snapshot(); + // The original early-final helper retires the uncertain carrier and then + // verifies a new GET on a second authenticated connection. + let expected = if matches!(mode, PostReply::Early) { + 2 + } else { + 1 + }; + assert_eq!(r.owners, expected, "{r:?}"); + assert_eq!(r.opens, expected, "{r:?}"); + assert_eq!(r.target_handshakes, expected, "{r:?}"); + assert_eq!(r.cover_requests, expected, "{r:?}"); + assert_eq!(r.cover_responses, expected, "{r:?}"); + assert_eq!( + r.client_drops, expected, + "actual client IO survived H2 parent join: {r:?}" + ); + assert_eq!( + r.peer_drops, expected, + "actual peer IO survived TLS peer join: {r:?}" + ); + assert_eq!(r.owner_cancelled, expected, "{r:?}"); + assert_eq!(r.owner_closed, expected, "{r:?}"); + assert_eq!(r.owner_wait_returned, expected, "{r:?}"); + assert_eq!(origin.0.opens.load(Ordering::Acquire), expected); + assert_eq!(origin.0.accepts.load(Ordering::Acquire), expected); + assert_eq!( + *origin.0.sni.lock().unwrap(), + vec!["a.test".to_owned(); expected] + ); + assert_eq!(origin.0.live.load(Ordering::Acquire), 0); +} + +#[tokio::test] +async fn ss_obfs_https_h2_two_posts_share_one_authenticated_carrier() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, PostReply::Complete).await; + } + } +} +#[tokio::test] +async fn ss_obfs_https_h2_submitted_second_post_is_not_replayed() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, PostReply::FailSecond).await; + } + } +} +#[tokio::test] +async fn ss_obfs_https_h2_active_stop_drops_partial_upload() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, PostReply::Wait).await; + } + } +} +#[tokio::test] +async fn ss_obfs_https_h2_early_final_retires_partial_upload() { + for cipher in CIPHERS { + for tls in [false, true] { + run(cipher, tls, PostReply::Early).await; + } + } +} diff --git a/src/http_processing/https_h2_ss_v2ray_mux_reuse_memory_tests.rs b/src/http_processing/https_h2_ss_v2ray_mux_reuse_memory_tests.rs new file mode 100644 index 0000000..697a318 --- /dev/null +++ b/src/http_processing/https_h2_ss_v2ray_mux_reuse_memory_tests.rs @@ -0,0 +1,105 @@ +//! Real SS2022/plain WS mux beneath the original authenticated TLS/HTTP cache. +//! Pure memory only; no official Go server, sockets or throughput claims. +use super::*; +use crate::{config::ShadowsocksCipher, outbound::MemoryObfsFactory}; +async fn exercise(mode: PostReply) { + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let factory = MemoryObfsFactory::new_v2ray_mux(cipher, 4096); + let weak = Arc::downgrade(&factory); + super::ss_obfs_reuse::run_with_factory(factory.clone(), mode).await; + let receipt = factory.snapshot(); + assert!(receipt.owners > 0, "actual mux factory was not entered"); + assert_eq!( + receipt.mux_new, receipt.owners, + "one New per actual WS/SS carrier: {receipt:?}" + ); + drop(factory); + assert!( + weak.upgrade().is_none(), + "HTTP parent retained the carrier factory" + ); + } +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h2_two_posts_share_one_authenticated_carrier() { + exercise(PostReply::Complete).await; +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h2_submitted_second_post_is_not_replayed() { + exercise(PostReply::FailSecond).await; +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h2_active_stop_drops_partial_upload() { + exercise(PostReply::Wait).await; +} + +#[tokio::test] +async fn ss_v2ray_mux_https_h2_early_final_retires_uncertain_upload() { + exercise(PostReply::Early).await; +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn ss_v2ray_mux_https_h2_native_then_js_reuses_one_authenticated_carrier() { + // The extra native header is deliberately unacceptable to post_response. + // Only the response script restores its required value after checking the + // native body; request-script output is independently read by the origin. + const SCRIPTS: &str = r#" - {url: 'https://a.test/', match: prefix, action: response-header-set, header: x-proof, value: before-js} +http-scripts: + enabled: true + scripts: + - name: actual-request-body + phase: request + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.request.headers.length; i++) { + let header = input.request.headers[i]; + if (header.name === "x-request" && header.value === "native") found = true; + } + if (!found || input.body.data !== "original") return {type:"abort"}; + return {type:"modify",body:{kind:"text",data:"transformed"}}; + } + - name: actual-response-proof + phase: response + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.response.headers.length; i++) { + let header = input.response.headers[i]; + if (header.name === "x-proof" && header.value === "before-js") found = true; + } + if (!found || input.body.data !== "from_origin") return {type:"abort"}; + return {type:"modify",headers:[{op:"set",name:"x-proof",values:["native"]}],body:{kind:"text",data:input.body.data}}; + } +"#; + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let factory = MemoryObfsFactory::new_v2ray_mux(cipher, 4096); + let weak = Arc::downgrade(&factory); + super::ss_obfs_reuse::run_scripted_with_factory(factory.clone(), SCRIPTS).await; + let receipt = factory.snapshot(); + assert_eq!((receipt.owners, receipt.mux_new), (1, 1), "{receipt:?}"); + drop(factory); + assert!( + weak.upgrade().is_none(), + "scripted HTTP parent retained factory" + ); + } +} diff --git a/src/http_processing/https_h2_vmess_http_cover_reuse_memory_tests.rs b/src/http_processing/https_h2_vmess_http_cover_reuse_memory_tests.rs new file mode 100644 index 0000000..ebdc732 --- /dev/null +++ b/src/http_processing/https_h2_vmess_http_cover_reuse_memory_tests.rs @@ -0,0 +1,144 @@ +//! Actual plain VMess HTTP cover beneath the unchanged TLS/H2 POST parent. +//! Memory peer model only; no official server, full downstream MITM or performance claim. +use super::*; +use crate::outbound::{MemoryVmessHttpCoverFactory, vmess::BodyCipher}; + +const CIPHERS: [BodyCipher; 4] = [ + BodyCipher::Auto, + BodyCipher::None, + BodyCipher::Aes128Gcm, + BodyCipher::Chacha20Poly1305, +]; + +async fn run(cipher: BodyCipher, mode: PostReply, extra: &str, scripted: bool) { + let factory = MemoryVmessHttpCoverFactory::new(cipher, 4096); + let weak = Arc::downgrade(&factory); + let (context, origin) = fixture_post(true, extra, mode); + *origin.0.vmess_http_cover.lock().unwrap() = Some(factory.clone()); + // The original helper retains its upload/response/no-replay/early-final + // checks and really joins every parent, driver and peer on all exits. + let result = AssertUnwindSafe(exercise_post_fixture( + mode, + scripted, + false, + context, + origin.clone(), + )) + .catch_unwind() + .await; + let r = factory.snapshot(); + let opens = origin.0.opens.load(Ordering::Acquire); + let accepts = origin.0.accepts.load(Ordering::Acquire); + let sni = origin + .0 + .sni + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + let live = origin.0.live.load(Ordering::Acquire); + drop(origin); + drop(factory); + // No fixture-held Arc or guard is permitted to conceal the real release. + assert!( + weak.upgrade().is_none(), + "HTTP parent retained the actual VMess factory" + ); + let expected = if matches!(mode, PostReply::Early) { + 2 + } else { + 1 + }; + assert_eq!(r.owners, expected, "{r:?}"); + assert_eq!(r.opens, expected, "{r:?}"); + assert_eq!(r.target_handshakes, expected, "{r:?}"); + assert_eq!(r.cover_requests, expected, "{r:?}"); + assert_eq!(r.cover_responses, expected, "{r:?}"); + assert_eq!( + r.client_drops, expected, + "actual client IO survived H2 parent join: {r:?}" + ); + assert_eq!( + r.peer_drops, expected, + "actual peer IO survived TLS peer join: {r:?}" + ); + assert_eq!(r.owner_cancelled, expected, "{r:?}"); + assert_eq!(r.owner_closed, expected, "{r:?}"); + assert_eq!(r.owner_wait_returned, expected, "{r:?}"); + assert_eq!(r.owner_tasks_empty, expected, "{r:?}"); + assert_eq!(r.auth_failures, 0, "{r:?}"); + assert_eq!(opens, expected); + assert_eq!(accepts, expected); + assert_eq!(sni, vec!["a.test".to_owned(); expected]); + assert_eq!(live, 0); + if let Err(panic) = result { + std::panic::resume_unwind(panic); + } +} + +#[tokio::test] +async fn vmess_http_cover_https_h2_two_posts_share_one_authenticated_carrier() { + for cipher in CIPHERS { + run(cipher, PostReply::Complete, "", false).await; + } +} +#[tokio::test] +async fn vmess_http_cover_https_h2_submitted_second_post_is_not_replayed() { + for cipher in CIPHERS { + run(cipher, PostReply::FailSecond, "", false).await; + } +} +#[tokio::test] +async fn vmess_http_cover_https_h2_active_stop_drops_partial_upload() { + for cipher in CIPHERS { + run(cipher, PostReply::Wait, "", false).await; + } +} +#[tokio::test] +async fn vmess_http_cover_https_h2_early_final_retires_uncertain_upload() { + for cipher in CIPHERS { + run(cipher, PostReply::Early, "", false).await; + } +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn vmess_http_cover_https_h2_native_then_js_reuses_one_authenticated_carrier() { + const SCRIPTS: &str = r#" - {url: 'https://a.test/', match: prefix, action: response-header-set, header: x-proof, value: before-js} +http-scripts: + enabled: true + scripts: + - name: actual-request-body + phase: request + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.request.headers.length; i++) { + let header = input.request.headers[i]; + if (header.name === "x-request" && header.value === "native") found = true; + } + if (!found || input.body.data !== "original") return {type:"abort"}; + return {type:"modify",body:{kind:"text",data:"transformed"}}; + } + - name: actual-response-proof + phase: response + url: https://a.test/ + match: prefix + body: text + source: | + function rewrite(input) { + let found = false; + for (let i = 0; i < input.response.headers.length; i++) { + let header = input.response.headers[i]; + if (header.name === "x-proof" && header.value === "before-js") found = true; + } + if (!found || input.body.data !== "from_origin") return {type:"abort"}; + return {type:"modify",headers:[{op:"set",name:"x-proof",values:["native"]}],body:{kind:"text",data:input.body.data}}; + } +"#; + for cipher in CIPHERS { + run(cipher, PostReply::Complete, SCRIPTS, true).await; + } +} diff --git a/src/http_processing/ingress_memory_tests.rs b/src/http_processing/ingress_memory_tests.rs new file mode 100644 index 0000000..b42b7b7 --- /dev/null +++ b/src/http_processing/ingress_memory_tests.rs @@ -0,0 +1,425 @@ +//! Real mixed HTTP entry and bounded memory origins; no sockets or VM backend. +use super::*; +use crate::{ + dispatch::{HttpTcpPlan, HttpTcpReuseKey}, + inbound::http::{HttpBasicAuth, HttpServerConfig, framing, server}, + routing::EmptyGeoMatcher, +}; +use std::{ + net::SocketAddr, + pin::Pin, + sync::atomic::{AtomicUsize, Ordering}, + task::{Context as TaskContext, Poll}, +}; +use tokio::io::{AsyncRead, AsyncWrite, BufReader, DuplexStream, ReadBuf}; + +#[derive(Default)] +struct Recorded { + sessions: Mutex>, + heads: Mutex>, + live_at_connect: Mutex>, + live: Arc, + tasks: Mutex>>, +} + +#[derive(Clone, Default)] +struct FixedOrigin { + recorded: Arc, + sniff: Option>, +} + +struct StreamOwner { + io: DuplexStream, + live: Arc, +} +impl Drop for StreamOwner { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::SeqCst); + } +} +impl AsyncRead for StreamOwner { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut TaskContext<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, buf) + } +} +impl AsyncWrite for StreamOwner { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut TaskContext<'_>, + buf: &[u8], + ) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, buf) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown( + mut self: Pin<&mut Self>, + cx: &mut TaskContext<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} + +struct FixedPlan { + origin: FixedOrigin, + session: StreamSession, + key: HttpTcpReuseKey, +} +#[async_trait] +impl HttpTcpPlan for FixedPlan { + fn reuse_key(&self) -> Option<&HttpTcpReuseKey> { + Some(&self.key) + } + async fn connect(self: Box) -> Result { + self.origin.connect_tcp(self.session).await + } +} + +#[async_trait] +impl Dispatcher for FixedOrigin { + async fn sniff_plan( + &self, + source: SocketAddr, + destination: &Destination, + ) -> Result, DispatchError> { + let host = match destination { + Destination::Domain { host, .. } => Some(host.as_str()), + Destination::Ip(_) => None, + }; + self.sniff + .as_ref() + .map(|policy| policy.plan(source, destination, host, false)) + .transpose() + .map_err(DispatchError::from) + } + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + Ok(Some(Box::new(FixedPlan { + origin: self.clone(), + session, + // The test origin has one immutable route. Production's key proof + // is tested separately; this exercises the actual HTTP slot owner. + key: HttpTcpReuseKey::new(1_u8), + }))) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.recorded + .live_at_connect + .lock() + .unwrap() + .push(self.recorded.live.load(Ordering::SeqCst)); + self.recorded.sessions.lock().unwrap().push(session); + self.recorded.live.fetch_add(1, Ordering::SeqCst); + let (client, peer) = tokio::io::duplex(8192); + let recorded = self.recorded.clone(); + let task = tokio::spawn(async move { + let mut peer = BufReader::new(peer); + loop { + let Ok(head) = framing::read_head(&mut peer, 32768).await else { + break; + }; + let head = String::from_utf8(head).unwrap(); + let close = head.to_ascii_lowercase().contains("connection: close\r\n"); + recorded.heads.lock().unwrap().push(head); + if peer + .get_mut() + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok") + .await + .is_err() + { + break; + } + if close { + break; + } + } + }); + self.recorded.tasks.lock().unwrap().push(task); + Ok(Box::new(StreamOwner { + io: client, + live: self.recorded.live.clone(), + })) + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +async fn join_owned(mut task: tokio::task::JoinHandle) -> Result { + match timeout(Duration::from_secs(5), &mut task).await { + Ok(Ok(result)) => Ok(result), + Ok(Err(error)) => Err(error.to_string()), + Err(_) => { + task.abort(); + let _ = task.await; + Err("memory owner did not join".into()) + } + } +} + +fn start( + origin: &FixedOrigin, + policy: &str, + auth: bool, +) -> ( + BufReader, + CancellationToken, + tokio::task::JoinHandle>, +) { + start_with_policy(origin, Policy::compile(policy).unwrap(), auth) +} + +fn start_with_policy( + origin: &FixedOrigin, + policy: Arc, + auth: bool, +) -> ( + BufReader, + CancellationToken, + tokio::task::JoinHandle>, +) { + let fixed: Arc = Arc::new(origin.clone()); + // Entry::connect_tcp deliberately panics: fallback must retain this fixed + // HttpContext dispatcher rather than return to the outer dynamic entry. + let entry: Arc = Arc::new(Entry(HttpContext::new( + policy, + fixed, + SecurityContext::new(), + ))); + let (client, peer) = tokio::io::duplex(8192); + let cancel = CancellationToken::new(); + let child = cancel.clone(); + let mut config = HttpServerConfig::processing(); + if auth { + config.auth = Some(HttpBasicAuth::new("user", "pass").unwrap()); + } + let task = tokio::spawn(async move { + server::handle_connection_with_deadline( + peer, + "127.0.0.1:30000".parse().unwrap(), + "127.0.0.1:1080".parse().unwrap(), + entry, + config, + child, + Instant::now() + Duration::from_secs(5), + ) + .await + }); + (BufReader::new(client), cancel, task) +} + +async fn finish( + client: BufReader, + cancel: CancellationToken, + task: tokio::task::JoinHandle>, + origin: &FixedOrigin, +) { + cancel.cancel(); + drop(client); + let server = join_owned(task).await; + let tasks = std::mem::take(&mut *origin.recorded.tasks.lock().unwrap()); + let mut peers = Vec::new(); + for task in tasks { + peers.push(join_owned(task).await); + } + assert_eq!(origin.recorded.live.load(Ordering::SeqCst), 0); + server.unwrap().unwrap(); + for peer in peers { + peer.unwrap(); + } +} + +async fn response(client: &mut BufReader) -> std::io::Result { + let head = framing::read_head(client, 32768).await?; + let mut body = [0; 2]; + client.read_exact(&mut body).await?; + if body != *b"ok" { + return Err(std::io::ErrorKind::InvalidData.into()); + } + Ok(String::from_utf8(head).unwrap()) +} + +const REWRITE: &str = "http-ports: [80]\nrewrite:\n enabled: true\n rules:\n - {url: '.', action: response-header-set, header: X-Rewrite, value: active}\n - {url: '.', action: replace, replacement-mode: url, replacement: 'http://first.invalid/rewritten'}\n"; + +#[tokio::test] +async fn ordinary_http_on_mitm_only_port_stays_plain_forwarding() { + let material = super::super::private_context::test_material(); + let yaml = format!( + "{REWRITE}\nmitm:\n enabled: true\n ports: [443]\n domains: [{{pattern: first.invalid}}]\n" + ); + let policy = super::super::config::Document::parse(&yaml) + .unwrap() + .compile(&Default::default()) + .unwrap() + .bind_ca(Some(&material)) + .unwrap(); + let origin = FixedOrigin::default(); + let (mut client, cancel, task) = start_with_policy(&origin, policy, false); + let exchange = timeout(Duration::from_secs(5), async { + client.get_mut().write_all(b"GET http://first.invalid:443/original HTTP/1.1\r\nHost: first.invalid:443\r\nConnection: close\r\n\r\n").await?; + response(&mut client).await + }).await; + finish(client, cancel, task, &origin).await; + let response = exchange.unwrap().unwrap(); + assert!(response.starts_with("HTTP/1.1 200 OK\r\n")); + assert!(!response.to_ascii_lowercase().contains("x-rewrite:")); + let sessions = origin.recorded.sessions.lock().unwrap(); + assert_eq!(sessions.len(), 1); + assert_eq!( + sessions[0].destination, + Destination::domain("first.invalid", 443).unwrap() + ); + assert_eq!(sessions[0].inbound, InboundKind::Http); + assert!(origin.recorded.heads.lock().unwrap()[0].starts_with("GET /original HTTP/1.1\r\n")); +} + +#[tokio::test] +async fn candidate_then_noncandidate_retires_cached_upstream_and_keeps_request_identity() { + let origin = FixedOrigin::default(); + let (mut client, cancel, task) = start(&origin, REWRITE, true); + let exchange = timeout(Duration::from_secs(5), async { + let mut responses = Vec::new(); + let mut retained_first_owner = false; + for (authority, connection) in [("first.invalid", "X-Hop"), ("first.invalid:8081", "close, X-Hop")] { + client.get_mut().write_all(format!("GET http://{authority}/original HTTP/1.1\r\nHost: {authority}\r\nProxy-Authorization: Basic dXNlcjpwYXNz\r\nProxy-Connection: keep-alive\r\nConnection: {connection}\r\nX-Hop: private\r\n\r\n").as_bytes()).await?; + responses.push(response(&mut client).await?); + if responses.len() == 1 { + retained_first_owner = origin.recorded.live.load(Ordering::SeqCst) == 1; + } + } + Ok::<_, std::io::Error>((responses, retained_first_owner)) + }).await; + finish(client, cancel, task, &origin).await; + let (responses, retained_first_owner) = exchange.unwrap().unwrap(); + assert!( + retained_first_owner, + "the first persistent response must retain its actual upstream owner" + ); + assert!( + responses[0] + .to_ascii_lowercase() + .contains("x-rewrite: active\r\n") + ); + assert!(!responses[1].to_ascii_lowercase().contains("x-rewrite:")); + let sessions = origin.recorded.sessions.lock().unwrap(); + assert_eq!(sessions.len(), 2); + for (session, port) in sessions.iter().zip([80, 8081]) { + assert_eq!( + session.destination, + Destination::domain("first.invalid", port).unwrap() + ); + assert_eq!(session.inbound, InboundKind::Http); + assert_eq!(session.metadata.user.as_deref(), Some("user")); + assert_eq!(session.metadata.local_port, 1080); + assert_eq!( + session.metadata.local_address, + Some("127.0.0.1:1080".parse().unwrap()) + ); + } + assert_eq!( + *origin.recorded.live_at_connect.lock().unwrap(), + [0, 0], + "the cached first owner must drop before the second dial" + ); + let heads = origin.recorded.heads.lock().unwrap(); + assert_eq!(heads.len(), 2); + assert!(heads[0].starts_with("GET /rewritten HTTP/1.1\r\n")); + assert!(heads[1].starts_with("GET /original HTTP/1.1\r\n")); + assert!( + heads[0] + .lines() + .any(|line| line.eq_ignore_ascii_case("connection: keep-alive")), + "the first response must have qualified for a live upstream slot" + ); + for head in heads.iter() { + let lower = head.to_ascii_lowercase(); + for forbidden in ["proxy-authorization:", "proxy-connection:", "x-hop:"] { + assert!(!lower.contains(forbidden), "{forbidden} leaked"); + } + } +} + +#[tokio::test] +async fn ordinary_http_and_connect_share_force_skip_and_override_false_sniff_policy() { + let base = "sniffer:\n enable: true\n parse-pure-ip: false\n force-domain: [target.invalid]\n override-destination: false\n sniff:\n HTTP: {ports: [8081]}\n"; + for (main, accepted) in [ + (base.to_owned(), true), + ( + base.replace("force-domain: [target.invalid]", "force-domain: []"), + false, + ), + ( + base.replace( + " sniff:", + " skip-domain: [target.invalid, observed.invalid]\n sniff:", + ), + false, + ), + (base.replace("ports: [8081]", "ports: [8082]"), false), + ] { + for connect in [false, true] { + let config = crate::config::Config::parse_yaml(main.as_bytes()).unwrap(); + let origin = FixedOrigin { + recorded: Arc::default(), + sniff: Some(crate::sniffing::Policy::new( + Arc::new(config.sniffer), + Arc::new(EmptyGeoMatcher), + )), + }; + let (mut client, cancel, task) = start(&origin, REWRITE, false); + let exchange = timeout(Duration::from_secs(5), async { + if connect { + client.get_mut().write_all(b"CONNECT target.invalid:8081 HTTP/1.1\r\nHost: target.invalid:8081\r\n\r\n").await?; + let head = framing::read_head(&mut client, 32768).await?; + if !head.starts_with(b"HTTP/1.1 200 ") { return Err(std::io::ErrorKind::InvalidData.into()); } + client.get_mut().write_all(b"GET /inside HTTP/1.1\r\nHost: observed.invalid\r\nConnection: close\r\n\r\n").await?; + } else { + client.get_mut().write_all(b"GET http://target.invalid:8081/outside HTTP/1.1\r\nHost: target.invalid:8081\r\nConnection: close\r\n\r\n").await?; + } + response(&mut client).await + }).await; + finish(client, cancel, task, &origin).await; + assert!( + exchange + .unwrap() + .unwrap() + .starts_with("HTTP/1.1 200 OK\r\n") + ); + let sessions = origin.recorded.sessions.lock().unwrap(); + assert_eq!(sessions.len(), 1); + assert_eq!( + sessions[0].destination, + Destination::domain("target.invalid", 8081).unwrap(), + "override false must retain the original target" + ); + assert_eq!( + sessions[0].inbound, + if connect { + InboundKind::Https + } else { + InboundKind::Http + } + ); + let expected = accepted.then_some(if connect { + "observed.invalid" + } else { + "target.invalid" + }); + assert_eq!( + sessions[0].sniffed_domain.as_deref(), + expected, + "{main}; CONNECT={connect}" + ); + } + } +} diff --git a/src/http_processing/mitm.rs b/src/http_processing/mitm.rs index 284ee6d..7f62f68 100644 --- a/src/http_processing/mitm.rs +++ b/src/http_processing/mitm.rs @@ -233,7 +233,9 @@ mod enabled { let mut tls = tokio::time::timeout( Duration::from_secs(10), tokio_rustls::TlsAcceptor::from(config).accept_with(replay, |connection| { - connection.set_buffer_limit(Some(32 * 1024)) + connection.set_buffer_limit(Some( + crate::limits::ResourceLimits::default().tls_buffer_limit, + )) }), ) .await diff --git a/src/http_processing/mod.rs b/src/http_processing/mod.rs index 5e17069..b5e58db 100644 --- a/src/http_processing/mod.rs +++ b/src/http_processing/mod.rs @@ -4,12 +4,21 @@ mod authority; pub(crate) mod body; mod body_budget; pub(crate) mod config; +#[cfg(feature = "http-diagnostics")] +#[doc(hidden)] +pub mod diagnostics; +#[cfg(not(feature = "http-diagnostics"))] +pub(crate) mod diagnostics; pub(crate) mod headers; mod mitm; mod numeric_input; pub(crate) mod private_context; pub(crate) mod providers; pub(crate) mod rules; +pub(crate) mod script_config; +#[cfg(feature = "inbound-http")] +pub(crate) mod script_message; +pub(crate) mod scripts; pub(crate) use config::{MAX_ADDENDUM, Policy}; #[cfg(feature = "inbound-http")] mod h1; @@ -23,6 +32,8 @@ mod h2_body; mod h2_h1; #[cfg(feature = "inbound-http")] mod h2_headers; +#[cfg(feature = "inbound-http")] +mod h2_reuse; #[cfg(all(test, feature = "inbound-http"))] mod h2_tests; #[cfg(feature = "inbound-http")] @@ -67,8 +78,11 @@ impl HttpContext { pub(super) fn security(&self) -> &SecurityContext { &self.security } - pub(crate) fn candidate_port(&self, port: u16) -> bool { + pub(crate) fn plain_port(&self, port: u16) -> bool { self.policy.plain_port(port) + } + pub(crate) fn candidate_port(&self, port: u16) -> bool { + self.plain_port(port) || self .policy .mitm() @@ -100,3 +114,6 @@ pub(crate) enum Intercept { mod h1_boundary_tests; #[cfg(all(test, feature = "inbound-http"))] mod tests; + +#[cfg(test)] +mod h2_frame_validation; diff --git a/src/http_processing/native_byte_map_validation.rs b/src/http_processing/native_byte_map_validation.rs new file mode 100644 index 0000000..c3207de --- /dev/null +++ b/src/http_processing/native_byte_map_validation.rs @@ -0,0 +1,518 @@ +//! Fixed tvOS-only native differential group in the existing active suite. +//! No caller data, sockets, VM, new runtime, source logging or host-only tests. +use super::*; +use crate::http_processing::rules::{ + ActionKind, MatchKind, Occurrences, RawRule, Search, SearchMode, +}; +use serde_json::{Value, json}; +use std::{io, time::Instant}; + +const URL: &str = "https://native-validation.invalid/body"; +const N: usize = 65536; +const ASCII_CASES: usize = 128 * 128 * 2; +const EXPECTED: usize = ASCII_CASES + 24 + 10 + 6 + 3 + 8; + +fn invalid() -> io::Error { + io::ErrorKind::InvalidData.into() +} +fn compiled( + search: &str, + replacement: &str, + mode: SearchMode, + occurrences: Occurrences, +) -> io::Result { + let raw = RawRule { + url: URL.into(), + match_kind: MatchKind::Exact, + action: ActionKind::ResponseBodyReplace, + enabled: true, + name: None, + replacement: Some(replacement.into()), + replacement_mode: None, + header: None, + value: None, + search: Some(search.into()), + search_mode: Some(mode), + occurrences: Some(occurrences), + patch: None, + }; + Rule::compile(raw, &mut 0) +} +fn search(rule: &Rule) -> io::Result<&Search> { + match &rule.action { + RuleAction::Body { + operation: BodyOperation::Replace(value), + .. + } => Ok(value), + _ => Err(invalid()), + } +} +fn repeated(budget: &Budget, byte: u8, length: usize) -> io::Result { + // Producer scratch is fixed1KiB, not an uncharged retained body-sized copy. + let mut value = BudgetedBytes::new(budget, length).ok_or(io::ErrorKind::OutOfMemory)?; + let chunk = [byte; 1024]; + while value.as_ref().len() < length { + let count = (length - value.as_ref().len()).min(chunk.len()); + value.extend(&chunk[..count])?; + } + Ok(value) +} +fn fingerprint(bytes: &[u8]) -> u64 { + bytes.iter().fold(0xcbf29ce484222325, |sum, byte| { + (sum ^ u64::from(*byte)).wrapping_mul(0x100000001b3) + }) +} +fn compare( + rule: &Rule, + input: &BudgetedBytes, + budget: &Budget, + eligible: bool, +) -> io::Result { + let query = search(rule)?; + let text = std::str::from_utf8(input.as_ref()).map_err(io::Error::other)?; + let capacity = query.output_capacity(text.len(), MAX_BODY); + let before = fingerprint(input.as_ref()); + let mut legacy = BudgetedBytes::new(budget, capacity).ok_or(io::ErrorKind::OutOfMemory)?; + // This reference is the unchanged match_indices/captures/template helper, + // also still used by headers, with its actual independently paid Vec. + let old = legacy.write_text(|out| query.apply_into(text, out, MAX_BODY)); + let url = Url::parse(URL).map_err(io::Error::other)?; + let actual = apply_operations( + std::slice::from_ref(rule), + &url, + Phase::Response, + input.as_ref(), + budget, + ); + let same = match (&old, &actual) { + (Ok(()), Ok(Some(value))) => { + value.as_ref() == legacy.as_ref() + && value.as_ref().len() + value.remaining() == capacity + && std::str::from_utf8(value.as_ref()).is_ok() + && (value.as_ref().is_empty() || value.as_ref().as_ptr() != input.as_ref().as_ptr()) + } + (Err(_), Err(Bypass::Transform)) => true, + _ => false, + }; + Ok(same + && (query.ascii_literal_byte_map().is_some() == eligible) + && before == fingerprint(input.as_ref())) +} +struct Group { + count: usize, + failures: usize, + details: Value, +} +impl Group { + fn new() -> Self { + Self { + count: 0, + failures: 0, + details: json!({}), + } + } + fn check(&mut self, passed: bool) { + self.count += 1; + self.failures += usize::from(!passed); + } +} +fn ascii_pairs(budget: &Budget) -> io::Result { + const SUFFIX: &[u8] = "é😀中".as_bytes(); + let mut input = + BudgetedBytes::new(budget, 256 + SUFFIX.len()).ok_or(io::ErrorKind::OutOfMemory)?; + input.write_initialized_output(256 + SUFFIX.len(), |out| { + for (index, byte) in out[..256].iter_mut().enumerate() { + *byte = (index % 128) as u8; + } + out[256..].copy_from_slice(SUFFIX); + Ok(out.len()) + })?; + let mut group = Group::new(); + for from in 0u8..128 { + for to in 0u8..128 { + for occurrences in [Occurrences::First, Occurrences::All] { + let rule = compiled( + &char::from(from).to_string(), + &char::from(to).to_string(), + SearchMode::Literal, + occurrences, + )?; + group.check(compare(&rule, &input, budget, true)?); + } + } + } + group.details = json!({"all128SearchAndReplacementBytes":true,"occurrencePolicies":2,"unicodeNulDollarInput":true,"independentlyPaidReferenceAndOutput":true}); + Ok(group) +} +fn boundaries(budget: &Budget) -> io::Result { + let mut group = Group::new(); + for length in [0, 1, 255, 256, 257, 4095, 4096, N, MAX_BODY, MAX_BODY + 1] { + let input = repeated(budget, b'q', length)?; + for occurrences in [Occurrences::First, Occurrences::All] { + group.check(compare( + &compiled("q", "z", SearchMode::Literal, occurrences)?, + &input, + budget, + true, + )?); + } + } + for bytes in ["q:é:q:😀:q:中".as_bytes(), "no target é😀\0$".as_bytes()] { + let input = BudgetedBytes::copy(budget, bytes).ok_or(io::ErrorKind::OutOfMemory)?; + for occurrences in [Occurrences::First, Occurrences::All] { + group.check(compare( + &compiled("q", "z", SearchMode::Literal, occurrences)?, + &input, + budget, + true, + )?); + } + } + Ok(group) +} +fn fallback(budget: &Budget) -> io::Result { + let mut group = Group::new(); + for (input, from, to, mode, occurrences) in [ + ("éaé", "é", "x", SearchMode::Literal, Occurrences::All), + ( + "ab--abab", + "ab", + "$1", + SearchMode::Literal, + Occurrences::First, + ), + ("aa😀a", "a", "", SearchMode::Literal, Occurrences::All), + ("aéa", "a", "aa", SearchMode::Literal, Occurrences::All), + ( + "a ab", + "(?Pa)(b)?", + "${letter}-$2-$$", + SearchMode::Regex, + Occurrences::First, + ), + ("aéa", "(a)", "${1}", SearchMode::Regex, Occurrences::All), + ("aa", "a", "$$", SearchMode::Regex, Occurrences::All), + ("ab", "", "x", SearchMode::Regex, Occurrences::All), + ] { + let input = + BudgetedBytes::copy(budget, input.as_bytes()).ok_or(io::ErrorKind::OutOfMemory)?; + group.check(compare( + &compiled(from, to, mode, occurrences)?, + &input, + budget, + false, + )?); + } + group.check( + Search::compile( + String::new(), + "x".into(), + SearchMode::Literal, + Occurrences::All, + ) + .is_err(), + ); + let input = BudgetedBytes::copy(budget, &[0xff, b'q']).ok_or(io::ErrorKind::OutOfMemory)?; + let rules = [compiled("q", "z", SearchMode::Literal, Occurrences::All)?]; + let url = Url::parse(URL).map_err(io::Error::other)?; + group.check(matches!( + apply_operations(&rules, &url, Phase::Response, input.as_ref(), budget), + Err(Bypass::InvalidText) + )); + Ok(group) +} +fn push_repeat(transaction: &mut Transaction<'_>, byte: u8, length: usize) -> io::Result<()> { + let chunk = [byte; 1024]; + for offset in (0..length).step_by(chunk.len()) { + transaction + .push(&chunk[..(length - offset).min(chunk.len())]) + .map_err(|_| invalid())?; + } + Ok(()) +} +fn entity_budget(budget: &Budget) -> io::Result { + let mut group = Group::new(); + let cost = BudgetedBytes::allocation_cost(N).ok_or(io::ErrorKind::OutOfMemory)?; + for (from, to, changes) in [("q", "z", true), ("q", "q", false), ("x", "z", false)] { + for missing in [0usize, 1] { + let pressure_bytes = budget::WORKSPACE - 2 * cost + missing; + let pressure = budget + .reserve(pressure_bytes) + .ok_or(io::ErrorKind::OutOfMemory)?; + let rules = [compiled(from, to, SearchMode::Literal, Occurrences::All)?]; + let url = Url::parse(URL).map_err(io::Error::other)?; + let request = OriginalRequestMeta::new("GET", &vec![]); + let wire = WireBodyMeta::new( + &vec![], + &request, + Phase::Response, + Some(200), + Some(N as u64), + false, + ); + let mut transaction = + Transaction::begin_shared(budget, &rules, &url, Phase::Response, &wire, true) + .map_err(|_| invalid())?; + push_repeat(&mut transaction, b'q', N)?; + let old_ptr = transaction.raw.as_ref().as_ptr(); + let mut fields = vec![ + ("x-independent".into(), "kept".into()), + ("etag".into(), "synthetic".into()), + ]; + let before = fields.clone(); + let entity = transaction.finish_shared(false, &mut fields); + let changed = missing == 0 && changes; + let expected = if changed { b'z' } else { b'q' }; + let body = entity.changed() == changed + && entity.wire().len() == N + && entity.wire().iter().all(|b| *b == expected) + && entity + .logical() + .is_some_and(|bytes| bytes.iter().all(|b| *b == expected)); + let fallback = entity.bypass + == if missing == 1 { + Some(Bypass::Budget) + } else { + None + }; + let metadata = if changed { + !fields + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("etag")) + && fields.iter().any(|(name, value)| { + name.eq_ignore_ascii_case("content-length") && value == &N.to_string() + }) + && fields + .iter() + .any(|(name, value)| name == "x-independent" && value == "kept") + } else { + fields == before && entity.wire().as_ptr() == old_ptr + }; + let remaining = budget::WORKSPACE - pressure_bytes - cost; + let only_one_owner = + budget.reserve(remaining).is_some() && budget.reserve(remaining + 1).is_none(); + let sent = entity.into_wire(); + let final_slice = sent.slice(17..18); + drop(sent); + let still_paid = budget.reserve(remaining + 1).is_none() + && final_slice.as_ref() == [expected].as_slice(); + drop(final_slice); + let source_refunded = budget.reserve(budget::WORKSPACE - pressure_bytes).is_some(); + drop(pressure); + group.check( + body && fallback && metadata && only_one_owner && still_paid && source_refunded, + ); + } + } + group.details = json!({"actualSharedCollectorEntity":true,"exactAndOneByteShort":true,"sameByteAndNoMatchStillAdmit":true,"actualFinalBytesSliceRetainsCredit":true}); + Ok(group) +} +fn rollback(budget: &Budget) -> io::Result { + let mut group = Group::new(); + let url = Url::parse(URL).map_err(io::Error::other)?; + let old = br#"{"key":"qq","number":1}"#; + let mut rules = vec![compiled("q", "$", SearchMode::Literal, Occurrences::All)?]; + let patch: RawRule = serde_json::from_value(json!({"url":URL,"match":"exact","action":"response-body-json-patch","patch":[{"op":"test","path":"/key","value":"other"}]})).map_err(io::Error::other)?; + rules.push(Rule::compile(patch, &mut 0)?); + let request = OriginalRequestMeta::new("GET", &vec![]); + let wire = WireBodyMeta::new( + &vec![], + &request, + Phase::Response, + Some(200), + Some(old.len() as u64), + false, + ); + let mut transaction = + Transaction::begin_shared(budget, &rules, &url, Phase::Response, &wire, true) + .map_err(|_| invalid())?; + transaction.push(old).map_err(|_| invalid())?; + let mut fields = vec![ + ("x-independent".into(), "kept".into()), + ("etag".into(), "synthetic".into()), + ]; + let before = fields.clone(); + let old_ptr = transaction.raw.as_ref().as_ptr(); + let entity = transaction.finish_shared(false, &mut fields); + group.check( + !entity.changed() + && entity.bypass == Some(Bypass::Transform) + && fields == before + && entity.wire().as_ref() == old + && entity.wire().as_ptr() == old_ptr + && entity.logical() == Some(old.as_slice()), + ); + drop(entity); + + let rules = [compiled("q", "z", SearchMode::Literal, Occurrences::All)?]; + let wire = WireBodyMeta::new( + &vec![], + &request, + Phase::Response, + Some(200), + Some(8), + false, + ); + let mut transaction = + Transaction::begin_shared(budget, &rules, &url, Phase::Response, &wire, true) + .map_err(|_| invalid())?; + transaction.push(b"qqsource").map_err(|_| invalid())?; + let old_ptr = transaction.raw.as_ref().as_ptr(); + let mut fields = vec![( + "x-pad".into(), + "a".repeat(super::super::headers::MAX_BYTES - 32 - 5), + )]; + let before = fields.clone(); + let entity = transaction.finish_shared(false, &mut fields); + group.check( + !entity.changed() + && entity.bypass == Some(Bypass::Budget) + && fields == before + && entity.wire().as_ref() == b"qqsource" + && entity.wire().as_ptr() == old_ptr, + ); + drop(entity); + + let mut entity = Entity::identity( + BudgetedBytes::copy(budget, b"qqsource").ok_or(io::ErrorKind::OutOfMemory)?, + ); + let before_wire = entity.wire().clone(); + let mut fields = vec![("etag".into(), "synthetic".into())]; + let before = fields.clone(); + let foreign = Budget::default(); + let output = apply_operations( + &rules, + &url, + Phase::Response, + entity.logical().ok_or_else(invalid)?, + &foreign, + ) + .map_err(|_| invalid())? + .ok_or_else(invalid)?; + let mapped = output.as_ref() == b"zzsource"; + let refused = commit_shared_body(&mut entity, &mut fields, output) == Err(Bypass::Budget); + group.check( + mapped + && refused + && fields == before + && entity.wire().as_ptr() == before_wire.as_ptr() + && entity.wire().as_ref() == b"qqsource" + && foreign.reserve(budget::WORKSPACE).is_some(), + ); + drop((entity, before_wire)); + group.details = json!({"laterOperationRollsBackWholeNativeStage":true,"headerFinalizeFailureAtomic":true,"foreignLedgerActualMappedOutputRejected":true}); + Ok(group) +} + +fn cpu() -> Option { + let mut time = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: same public current-thread clock used by scoped_qos; initialized + // writable timespec, tvOS-only diagnostics, no QoS setter or private API. + let rc = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) }; + (rc == 0 && time.tv_sec >= 0 && (0..1_000_000_000).contains(&time.tv_nsec)) + .then(|| (time.tv_sec as u128) * 1_000_000_000 + time.tv_nsec as u128) +} +fn measured(operation: impl FnOnce() -> T) -> (T, Value) { + let start_cpu = cpu(); + let start = Instant::now(); + let value = operation(); + let elapsed = start.elapsed().as_micros(); + let cpu_us = cpu() + .zip(start_cpu) + .and_then(|(end, start)| end.checked_sub(start)) + .map(|value| value / 1000); + ( + value, + json!({"sampleCount":1,"wallUs":elapsed,"threadCpuUs":cpu_us,"threadCpuAvailable":cpu_us.is_some()}), + ) +} +fn timing(budget: &Budget) -> io::Result { + let mut group = Group::new(); + let mut samples = Vec::new(); + for dense in [true, false] { + let mut input = BudgetedBytes::new(budget, N).ok_or(io::ErrorKind::OutOfMemory)?; + input.write_initialized_output(N, |bytes| { + bytes.fill(if dense { b'q' } else { b'x' }); + if !dense { + bytes[17] = b'q'; + bytes[N - 17] = b'q'; + } + Ok(N) + })?; + for occurrences in [Occurrences::First, Occurrences::All] { + let rule = compiled("q", "z", SearchMode::Literal, occurrences)?; + let query = search(&rule)?; + let text = std::str::from_utf8(input.as_ref()).map_err(io::Error::other)?; + for iteration in 0..2 { + let mut old = BudgetedBytes::new(budget, N).ok_or(io::ErrorKind::OutOfMemory)?; + let mut new = BudgetedBytes::new(budget, N).ok_or(io::ErrorKind::OutOfMemory)?; + let legacy = |out: &mut BudgetedBytes| { + out.write_text(|out| query.apply_into(text, out, MAX_BODY)) + .map_err(|_| Bypass::Transform) + }; + let (old_result, old_time, new_result, new_time) = if iteration == 0 { + let (a, ta) = measured(|| legacy(&mut old)); + let (b, tb) = measured(|| fill_replacement(text, query, &mut new)); + (a, ta, b, tb) + } else { + let (b, tb) = measured(|| fill_replacement(text, query, &mut new)); + let (a, ta) = measured(|| legacy(&mut old)); + (a, ta, b, tb) + }; + let same = old_result.is_ok() + && new_result.is_ok() + && old.as_ref() == new.as_ref() + && old.as_ref().len() == N + && new.as_ref().len() + new.remaining() == N; + group.check(same); + samples.push(json!({"shape":if dense{"dense"}else{"sparse-two-matches"},"policy":if occurrences==Occurrences::First{"first"}else{"all"},"iteration":iteration, + "order":if iteration==0{"legacy-then-new"}else{"new-then-legacy"},"bytes":N,"equal":same,"legacy":old_time,"candidate":new_time})); + } + } + } + group.details = json!({"scope":"real helper operations on separately pre-admitted equal-capacity outputs; excludes source construction, output allocation and final owner drop; new helper includes zero initialization, legacy includes Vec/String handoff; native has no JS tick/100ms limit added", + "processID":std::process::id(),"threadScope":"same diagnostic caller thread, no QoS setter or worker selection", "notWholeNeProfile":true,"noTimingThreshold":true,"samples":samples}); + Ok(group) +} + +pub(super) fn run() -> io::Result { + let mut groups = Vec::new(); + for (id, expected, function) in [ + ( + "all-ascii-pairs", + ASCII_CASES, + ascii_pairs as fn(&Budget) -> io::Result, + ), + ("body-boundaries", 24, boundaries), + ("legacy-fallback", 10, fallback), + ("entity-budget-last-slice", 6, entity_budget), + ("body-metadata-rollback", 3, rollback), + ("dense-sparse-helper-cost", 8, timing), + ] { + let budget = Budget::default(); + let result = function(&budget); + let refunded = budget.reserve(budget::WORKSPACE).is_some(); + let row = match result { + Ok(group) => { + json!({"id":id,"passed":group.count==expected && group.failures==0 && refunded,"caseCount":group.count,"expectedCaseCount":expected,"mismatchCount":group.failures,"budgetFullyRefunded":refunded,"details":group.details}) + } + Err(error) => { + json!({"id":id,"passed":false,"caseCount":0,"expectedCaseCount":expected,"harnessErrorKind":format!("{:?}",error.kind()),"budgetFullyRefunded":refunded}) + } + }; + groups.push(row); + } + let count: u64 = groups + .iter() + .filter_map(|row| row["caseCount"].as_u64()) + .sum(); + let mismatches = groups.iter().filter(|row| row["passed"] != true).count(); + let passed = count == EXPECTED as u64 && groups.len() == 6 && mismatches == 0; + Ok( + json!({"id":"native-byte-map-differential","kind":"native-differential","passed":passed,"caseCount":count,"expectedCaseCount":EXPECTED,"groupCount":groups.len(),"mismatchGroupCount":mismatches,"groups":groups, + "realCompiledRulesAndBodyOperations":true,"legacySearchReferenceRetained":true,"noJscEquivalenceClaim":true,"performanceAcceptance":false,"scope":"fixed active tvOS native helper/Entity/ledger evidence, not a network or process-memory qualification"}), + ) +} diff --git a/src/http_processing/providers_store.rs b/src/http_processing/providers_store.rs index 4f29fbf..500dd22 100644 --- a/src/http_processing/providers_store.rs +++ b/src/http_processing/providers_store.rs @@ -168,6 +168,8 @@ impl Store { cancellation: &CancellationToken, force_refresh: bool, ) -> io::Result> { + check_cancel(cancellation)?; + document.http_scripts.prepare_platform(cancellation)?; check_cancel(cancellation)?; let paths = resolve_paths(&document, context, true)?; if force_refresh { diff --git a/src/http_processing/providers_store_tests.rs b/src/http_processing/providers_store_tests.rs index a8e8cd9..e92a6d5 100644 --- a/src/http_processing/providers_store_tests.rs +++ b/src/http_processing/providers_store_tests.rs @@ -412,3 +412,55 @@ async fn disabled_sources_skip_fifo_and_unresolvable_cache_parent_without_io() { assert!(candidate.payloads.is_empty()); assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 2); } + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +#[tokio::test] +async fn platform_warmup_is_requested_only_by_active_actual_preparation() { + use crate::http_processing::{config::Policy, scripts}; + // An infinite user program is valid finite-language source; actual prepare + // must not execute it, nor load the trusted prelude as a substitute. + let active_yaml = "http-scripts:\n enabled: true\n scripts:\n - name: warmup-path\n phase: response\n url: 'http://example.test/'\n match: prefix\n source: 'function rewrite(input){while(true){}}'\n"; + let requests = scripts::platform_prepare_requests_for_test(); + scripts::validate_source("function rewrite(input){return {type:'pass'};}").unwrap(); + let active = Document::parse(active_yaml).unwrap(); + Policy::compile(active_yaml).unwrap(); + active.http_scripts.ensure_available().unwrap(); + assert_eq!(scripts::platform_prepare_requests_for_test(), requests); + + let disabled = + Document::parse(&active_yaml.replace("enabled: true", "enabled: false")).unwrap(); + let empty = Document::parse("http-scripts: {enabled: true, scripts: []}\n").unwrap(); + let context = SourceContext::default(); + let mut store = Store::new(); + for document in [disabled, empty] { + store + .prepare(document, &context, None, &CancellationToken::new(), false) + .await + .unwrap(); + } + let cancelled = CancellationToken::new(); + cancelled.cancel(); + assert_eq!( + store + .prepare(active.clone(), &context, None, &cancelled, false) + .await + .err() + .unwrap() + .kind(), + io::ErrorKind::Interrupted + ); + assert_eq!(scripts::platform_prepare_requests_for_test(), requests); + for expected in [requests + 1, requests + 2] { + store + .prepare( + active.clone(), + &context, + None, + &CancellationToken::new(), + false, + ) + .await + .unwrap(); + assert_eq!(scripts::platform_prepare_requests_for_test(), expected); + } +} diff --git a/src/http_processing/request.rs b/src/http_processing/request.rs index f822dd6..775e927 100644 --- a/src/http_processing/request.rs +++ b/src/http_processing/request.rs @@ -20,7 +20,7 @@ impl HttpContext { pub(super) fn plan( &self, original: Url, - mut session: StreamSession, + session: StreamSession, scheme: Scheme, apply_url_actions: bool, ) -> io::Result { @@ -32,17 +32,6 @@ impl HttpContext { "HTTPS authority is not permitted", )); } - let original_matches_tls = scheme != Scheme::Https - || (session.sniffed_domain.as_deref().is_some_and(|sni| { - original - .host_str() - .is_some_and(|host| host.eq_ignore_ascii_case(sni)) - }) && original.port_or_known_default() == Some(session.destination.port())); - let origin = ( - original.scheme() == "https", - original.host_str().unwrap_or_default().to_owned(), - original.port_or_known_default(), - ); let action = if apply_url_actions { self.policy().evaluate(original.clone())? } else { @@ -53,9 +42,28 @@ impl HttpContext { Action::Redirect { status, url } => return Ok(Decision::Redirect { status, url }), Action::Forward(url) => url, }; - let strip_origin_credentials = origin.0 != (url.scheme() == "https") - || origin.1 != url.host_str().unwrap_or_default() - || origin.2 != url.port_or_known_default(); + self.final_target(original, url, session, scheme) + .map(|target| Decision::Forward(Box::new(target))) + } + + /// Rebuild only the final physical target, without re-running URL rules. + /// Callers already performed credential cleaning at each accepted origin. + pub(super) fn final_target( + &self, + original: Url, + url: Url, + mut session: StreamSession, + scheme: Scheme, + ) -> io::Result { + let original_matches_tls = scheme != Scheme::Https + || (session.sniffed_domain.as_deref().is_some_and(|sni| { + original + .host_str() + .is_some_and(|host| host.eq_ignore_ascii_case(sni)) + }) && original.port_or_known_default() == Some(session.destination.port())); + let strip_origin_credentials = original.scheme() != url.scheme() + || original.host_str() != url.host_str() + || original.port_or_known_default() != url.port_or_known_default(); let host = url.host_str().ok_or_else(invalid)?.trim_matches(['[', ']']); let port = url.port_or_known_default().ok_or_else(invalid)?; let destination = match host.parse::() { @@ -72,13 +80,13 @@ impl HttpContext { // Retain the fixed SNI's selected IP only for its own authority. session.sniffed_domain = Some(host.to_owned()); } - Ok(Decision::Forward(Box::new(Target { + Ok(Target { original, url, session, logical_destination: destination, strip_origin_credentials, - }))) + }) } } fn invalid() -> io::Error { diff --git a/src/http_processing/rule_search.rs b/src/http_processing/rule_search.rs index f5ddb72..30fb355 100644 --- a/src/http_processing/rule_search.rs +++ b/src/http_processing/rule_search.rs @@ -57,6 +57,43 @@ impl Search { }) } + /// Preallocate the actual body owner at a proven byte upper bound. + /// Literal matches are nonempty and nonoverlapping, so replacing each with + /// no more bytes cannot increase any output prefix beyond the input size. + /// Regex/templates and potentially growing literals retain the full limit. + pub(crate) fn output_capacity(&self, input_bytes: usize, limit: usize) -> usize { + match &self.pattern { + Pattern::Literal { + search, + replacement, + } if replacement.len() <= search.len() => input_bytes.min(limit), + _ => limit, + } + } + + /// A read-only shape proof for a separately admitted body output. + /// Literal NUL and dollar are data; regex replacement templates stay out. + pub(crate) fn ascii_literal_byte_map(&self) -> Option<(u8, u8, Occurrences)> { + let Pattern::Literal { + search, + replacement, + } = &self.pattern + else { + return None; + }; + let [search] = search.as_bytes() else { + return None; + }; + let [replacement] = replacement.as_bytes() else { + return None; + }; + (search.is_ascii() && replacement.is_ascii()).then_some(( + *search, + *replacement, + self.occurrences, + )) + } + /// The caller owns the input and output workspace permits. Allocation is /// checked before every append, including unmatched portions and captures. pub(crate) fn apply(&self, input: &str, limit: usize) -> io::Result { diff --git a/src/http_processing/rules.rs b/src/http_processing/rules.rs index 10387f0..69fc17e 100644 --- a/src/http_processing/rules.rs +++ b/src/http_processing/rules.rs @@ -1,6 +1,6 @@ //! The common flat HTTP rule schema and pure, bounded rule compiler. use regex::{Regex, RegexBuilder}; -use std::io; +use std::{collections::BTreeMap, io, sync::Arc}; use url::Url; #[path = "rule_schema.rs"] @@ -35,7 +35,28 @@ pub(crate) struct Rule { pub(crate) enum Matcher { Exact(Box), Prefix(Box), - Regex(Regex), + Regex(Arc), +} + +/// One native-selector builder profile, scoped to one candidate compilation. +#[derive(Default)] +pub(crate) struct SelectorCompiler { + regexes: BTreeMap, Arc>, +} + +impl SelectorCompiler { + fn regex(&mut self, pattern: &str) -> io::Result> { + if let Some(regex) = self.regexes.get(pattern) { + return Ok(Arc::clone(regex)); + } + if self.regexes.len() == MAX_RULES { + return Err(invalid()); + } + // Exact pattern bytes plus this fixed builder profile form the key. + let regex = Arc::new(bounded_regex(pattern)?); + self.regexes.insert(pattern.into(), Arc::clone(®ex)); + Ok(regex) + } } pub(crate) enum RuleAction { @@ -150,7 +171,15 @@ impl RawRule { } impl Rule { - pub(crate) fn compile(mut raw: RawRule, total_text: &mut usize) -> io::Result { + pub(crate) fn compile(raw: RawRule, total_text: &mut usize) -> io::Result { + Self::compile_with_selectors(raw, total_text, &mut SelectorCompiler::default()) + } + + pub(crate) fn compile_with_selectors( + mut raw: RawRule, + total_text: &mut usize, + selectors: &mut SelectorCompiler, + ) -> io::Result { let next_text = total_text .checked_add(raw.text_size()?) .ok_or_else(invalid)?; @@ -172,7 +201,7 @@ impl Rule { return Err(invalid()); } let selector = match raw.match_kind { - MatchKind::Regex => Matcher::Regex(bounded_regex(&raw.url)?), + MatchKind::Regex => Matcher::Regex(selectors.regex(&raw.url)?), MatchKind::Exact => Matcher::Exact(checked_url(&raw.url)?.as_str().into()), MatchKind::Prefix => Matcher::Prefix(checked_url(&raw.url)?.as_str().into()), }; diff --git a/src/http_processing/script_config.rs b/src/http_processing/script_config.rs new file mode 100644 index 0000000..ccb22f9 --- /dev/null +++ b/src/http_processing/script_config.rs @@ -0,0 +1,316 @@ +//! Inline script declarations and pure compilation of their URL selectors. +use super::{ + config::{invalid, nonnull}, + rules::{MAX_PATTERN, MAX_RULE_TEXT, MAX_RULES, MatchKind, Phase, checked_url}, + scripts::{self, CompiledSource}, +}; +use regex::{Regex, RegexBuilder}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use std::io; +use url::Url; + +#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub(crate) enum BodyMode { + #[default] + None, + Text, + Bytes, +} + +#[derive(Clone, Default, Deserialize, Serialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct RawScripts { + #[serde(default)] + pub(crate) enabled: bool, + #[serde(default, deserialize_with = "nonnull")] + scripts: Vec, +} + +#[derive(Clone, Deserialize, Serialize)] +#[serde(deny_unknown_fields, rename_all = "kebab-case")] +struct RawScript { + name: String, + #[serde(deserialize_with = "phase", serialize_with = "serialize_phase")] + phase: Phase, + url: String, + #[serde(default, rename = "match")] + match_kind: MatchKind, + #[serde(default)] + body: BodyMode, + source: String, +} + +#[derive(Clone, Copy, Deserialize, Serialize)] +#[serde(rename_all = "lowercase")] +enum RawPhase { + Request, + Response, +} + +fn phase<'de, D: Deserializer<'de>>(deserializer: D) -> Result { + RawPhase::deserialize(deserializer).map(|phase| match phase { + RawPhase::Request => Phase::Request, + RawPhase::Response => Phase::Response, + }) +} + +fn serialize_phase(phase: &Phase, serializer: S) -> Result { + match phase { + Phase::Request => RawPhase::Request, + Phase::Response => RawPhase::Response, + } + .serialize(serializer) +} + +#[derive(Clone)] +enum Matcher { + Exact(String), + Prefix(String), + Regex(Regex), +} + +#[derive(Clone)] +pub(crate) struct CompiledScript { + pub(crate) name: String, + pub(crate) phase: Phase, + pub(crate) body: BodyMode, + pub(crate) compiled: CompiledSource, + matcher: Matcher, +} + +impl CompiledScript { + pub(crate) fn matches(&self, url: &Url) -> bool { + match &self.matcher { + Matcher::Exact(value) => url.as_str() == value, + Matcher::Prefix(value) => url.as_str().starts_with(value), + Matcher::Regex(regex) => regex.is_match(url.as_str()), + } + } + + fn needs_jsc_for_business(&self) -> bool { + self.compiled.needs_jsc_for_business(self.body, self.phase) + } +} + +impl RawScripts { + pub(crate) fn is_active(&self) -> bool { + self.enabled && !self.scripts.is_empty() + } + + /// Platform admission belongs to actual preparation, never YAML validation. + pub(crate) fn ensure_available(&self) -> io::Result<()> { + if self.is_active() { + scripts::ensure_available()?; + } + Ok(()) + } + + /// Initialize trusted platform state only from actual resource preparation. + pub(crate) fn prepare_platform( + &self, + cancellation: &tokio_util::sync::CancellationToken, + ) -> io::Result<()> { + if self.is_active() { + // Preparation still requires the supported platform even when a + // closed Plan proves that business input cannot select JSC. + scripts::ensure_available()?; + if cancellation.is_cancelled() { + return Err(io::ErrorKind::Interrupted.into()); + } + // Compile the whole immutable declaration list before deciding; + // a total prefix must not hide an unchecked or JSC-only suffix. + let needs_jsc = { + let compiled = self.compile()?; + compiled.iter().any(CompiledScript::needs_jsc_for_business) + }; + if cancellation.is_cancelled() { + return Err(io::ErrorKind::Interrupted.into()); + } + if needs_jsc { + scripts::prepare_platform(cancellation)?; + } + } + Ok(()) + } + + /// Disabled declarations are validated too; enabling cannot expose a + /// previously unchecked source or selector. + pub(crate) fn compile(&self) -> io::Result> { + if self.scripts.len() > MAX_RULES { + return Err(invalid()); + } + let mut text = 0usize; + self.scripts + .iter() + .map(|script| { + text = text + .checked_add(script.name.len()) + .and_then(|size| size.checked_add(script.url.len())) + .filter(|size| *size <= MAX_RULE_TEXT) + .ok_or_else(invalid)?; + if script.name.trim().is_empty() + || script.name.chars().any(char::is_control) + || script.url.len() > MAX_PATTERN + { + return Err(invalid()); + } + let matcher = match script.match_kind { + MatchKind::Exact => Matcher::Exact(checked_url(&script.url)?.to_string()), + MatchKind::Prefix => Matcher::Prefix(checked_url(&script.url)?.to_string()), + MatchKind::Regex => Matcher::Regex( + RegexBuilder::new(&script.url) + .size_limit(128 * 1024) + .dfa_size_limit(64 * 1024) + .build() + .map_err(|_| invalid())?, + ), + }; + Ok(CompiledScript { + name: script.name.clone(), + phase: script.phase, + body: script.body, + compiled: scripts::validate_source(&script.source)?, + matcher, + }) + }) + .collect() + } +} + +#[cfg(all(test, feature = "inbound-http"))] +mod tests { + use super::*; + + const CLOSED: &str = "function rewrite(input){const text=input.body.data.replaceAll('a','b');return {type:'modify',body:{kind:'text',data:text}};}"; + const REQUEST_GUARD: &str = "function rewrite(input){let found=false;for(let i=0;i RawScript { + RawScript { + name: "coverage-proof".into(), + phase, + url: "https://example.test/".into(), + match_kind: MatchKind::Exact, + body, + source: source.into(), + } + } + + fn active(source: &str, body: BodyMode, phase: Phase) -> RawScripts { + RawScripts { + enabled: true, + scripts: vec![declaration(source, body, phase)], + } + } + + #[test] + fn jsc_preparation_proof_uses_the_actual_body_and_phase_declaration() { + for phase in [Phase::Request, Phase::Response] { + let compiled = active(CLOSED, BodyMode::Text, phase).compile().unwrap(); + assert_eq!( + compiled[0].needs_jsc_for_business(), + !cfg!(target_vendor = "apple") + ); + for body in [BodyMode::None, BodyMode::Bytes] { + let compiled = active(CLOSED, body, phase).compile().unwrap(); + assert!(compiled[0].needs_jsc_for_business()); + } + } + } + + #[test] + fn guard_coverage_uses_the_actual_business_phase_and_body_declaration() { + for (source, phase, covered) in [ + (REQUEST_GUARD, Phase::Request, true), + (REQUEST_GUARD, Phase::Response, true), + (RESPONSE_GUARD, Phase::Response, true), + (RESPONSE_GUARD, Phase::Request, false), + ] { + let compiled = active(source, BodyMode::Text, phase).compile().unwrap(); + assert_eq!( + compiled[0].needs_jsc_for_business(), + !cfg!(target_vendor = "apple") || !covered + ); + for body in [BodyMode::None, BodyMode::Bytes] { + let compiled = active(source, body, phase).compile().unwrap(); + assert!(compiled[0].needs_jsc_for_business()); + } + } + } + + #[test] + fn disabled_sources_still_receive_the_complete_frontend_validation() { + let mut valid = active(UNUSED_UNKNOWN, BodyMode::Text, Phase::Response); + valid.enabled = false; + assert!(valid.compile().is_ok()); + valid.scripts[0].source = "function rewrite(input){return async () => 1;}".into(); + assert!(valid.compile().is_err()); + } + + #[cfg(target_vendor = "apple")] + #[test] + fn only_a_complete_total_list_skips_the_platform_prepare_request() { + use tokio_util::sync::CancellationToken; + + let requested = scripts::platform_prepare_requests_for_test(); + let mut total = active(CLOSED, BodyMode::Text, Phase::Response); + total.scripts.extend([ + declaration(CLOSED, BodyMode::Text, Phase::Request), + declaration(REQUEST_GUARD, BodyMode::Text, Phase::Request), + declaration(REQUEST_GUARD, BodyMode::Text, Phase::Response), + declaration(RESPONSE_GUARD, BodyMode::Text, Phase::Response), + ]); + total.compile().unwrap(); + total.ensure_available().unwrap(); + assert_eq!(scripts::platform_prepare_requests_for_test(), requested); + total.prepare_platform(&CancellationToken::new()).unwrap(); + assert_eq!(scripts::platform_prepare_requests_for_test(), requested); + + let cancelled = CancellationToken::new(); + cancelled.cancel(); + assert_eq!( + total.prepare_platform(&cancelled).unwrap_err().kind(), + io::ErrorKind::Interrupted + ); + assert_eq!(scripts::platform_prepare_requests_for_test(), requested); + + let mut disabled = active(RESPONSE_GUARD, BodyMode::Text, Phase::Request); + disabled.enabled = false; + disabled + .prepare_platform(&CancellationToken::new()) + .unwrap(); + RawScripts { + enabled: true, + scripts: Vec::new(), + } + .prepare_platform(&CancellationToken::new()) + .unwrap(); + assert_eq!(scripts::platform_prepare_requests_for_test(), requested); + + let mut mixed = total; + mixed + .scripts + .push(declaration(RESPONSE_GUARD, BodyMode::Text, Phase::Request)); + mixed.prepare_platform(&CancellationToken::new()).unwrap(); + assert_eq!(scripts::platform_prepare_requests_for_test(), requested + 1); + // A second actual preparation requests the existing process-global + // initializer again; its own shared success/retry policy is unchanged. + mixed.prepare_platform(&CancellationToken::new()).unwrap(); + assert_eq!(scripts::platform_prepare_requests_for_test(), requested + 2); + } + + #[cfg(not(target_vendor = "apple"))] + #[test] + fn total_source_does_not_expand_platform_availability() { + let total = active(CLOSED, BodyMode::Text, Phase::Request); + assert_eq!( + total + .prepare_platform(&tokio_util::sync::CancellationToken::new()) + .unwrap_err() + .kind(), + io::ErrorKind::Unsupported + ); + } +} diff --git a/src/http_processing/script_h1_tests.rs b/src/http_processing/script_h1_tests.rs new file mode 100644 index 0000000..6b324f0 --- /dev/null +++ b/src/http_processing/script_h1_tests.rs @@ -0,0 +1,134 @@ +//! Real H1 framing + actual system JSC, with only in-memory peer I/O. +use super::*; + +async fn exchange(yaml: &str, request: &[u8]) -> (String, Arc) { + let origin = Arc::new(Origin::default()); + let context = HttpContext::new( + Policy::compile(yaml).unwrap(), + origin.clone(), + SecurityContext::new(), + ); + let (mut client, mut server) = tokio::io::duplex(16 * 1024); + let task = tokio::spawn(async move { + context + .serve_h1( + &mut server, + session(), + Scheme::Http, + CancellationToken::new(), + ) + .await + .unwrap(); + }); + client.write_all(request).await.unwrap(); + let mut response = String::new(); + timeout(Duration::from_secs(5), client.read_to_string(&mut response)) + .await + .unwrap() + .unwrap(); + task.await.unwrap(); + origin.join().await; + (response, origin) +} + +#[tokio::test] +async fn request_script_sees_native_headers_and_responds_without_upstream() { + let (response,origin)=exchange(r#" +rewrite: + enabled: true + rules: + - {url: 'http://old.invalid/', match: prefix, action: request-header-set, header: X-Native, value: ready} +http-scripts: + enabled: true + scripts: + - name: local + phase: request + url: 'http://old.invalid/' + match: prefix + source: | + function rewrite(input) { + let found = false; + for (let i=0;i, + pub(crate) body: Option, + /// Sticky: original trailers must not restore credentials after A→B→A. + pub(crate) crossed_origin: bool, + protected: BTreeSet, + partial_response: bool, +} + +pub(crate) struct LocalResponse { + pub(crate) status: u16, + pub(crate) headers: Fields, + pub(crate) body: Bytes, +} + +pub(crate) enum Outcome { + Forward, + Respond(LocalResponse), + Abort, +} + +#[derive(Clone, Copy, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "lowercase")] +pub(crate) enum BodyKind { + Text, + Bytes, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct BodyOutput { + pub(crate) kind: BodyKind, +} + +fn present<'de, D: Deserializer<'de>, T: Deserialize<'de>>(d: D) -> Result, D::Error> { + Option::::deserialize(d)? + .map(Some) + .ok_or_else(|| serde::de::Error::custom("null is not an omitted script field")) +} + +#[derive(Deserialize)] +#[serde(tag = "op", rename_all = "lowercase", deny_unknown_fields)] +pub(crate) enum HeaderOp { + Set { name: String, values: Vec }, + Add { name: String, values: Vec }, + Remove { name: String }, +} + +#[derive(Deserialize)] +#[serde(deny_unknown_fields)] +pub(crate) struct HeaderField { + name: String, + value: String, +} + +#[derive(Deserialize)] +#[serde(tag = "type", rename_all = "lowercase", deny_unknown_fields)] +pub(crate) enum ScriptOutput { + Pass {}, + Modify { + #[serde(default, deserialize_with = "present")] + url: Option, + #[serde(default, deserialize_with = "present")] + method: Option, + #[serde(default, deserialize_with = "present")] + status: Option, + #[serde(default, deserialize_with = "present")] + headers: Option>, + #[serde(default, deserialize_with = "present")] + body: Option, + }, + Respond { + status: u16, + #[serde(default, deserialize_with = "present")] + headers: Option>, + #[serde(default, deserialize_with = "present")] + body: Option, + }, + Abort {}, +} + +fn invalid() -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, "invalid HTTP script result") +} +fn exhausted() -> io::Error { + io::Error::new( + io::ErrorKind::OutOfMemory, + "HTTP script body workspace exceeded", + ) +} + +pub(crate) fn same_origin(a: &Url, b: &Url) -> bool { + a.scheme() == b.scheme() + && a.host_str() == b.host_str() + && a.port_or_known_default() == b.port_or_known_default() +} + +impl Message { + pub(crate) fn request( + original: OriginalSnapshot, + mut request: RequestSnapshot, + body: Option, + wire_headers: &Fields, + crossed_origin: bool, + ) -> Self { + update_host(&mut request.headers, &request.url); + Self { + original, + request, + response: None, + body, + crossed_origin, + protected: nominated(wire_headers), + partial_response: false, + } + } + + pub(crate) fn response( + original: OriginalSnapshot, + mut request: RequestSnapshot, + response: ResponseSnapshot, + body: Option, + wire_headers: &Fields, + ) -> Self { + let partial_response = response.status == 206 + || wire_headers + .iter() + .any(|(name, _)| name.eq_ignore_ascii_case("content-range")); + update_host(&mut request.headers, &request.url); + Self { + original, + request, + response: Some(response), + body, + crossed_origin: false, + protected: nominated(wire_headers), + partial_response, + } + } + + pub(crate) fn phase(&self) -> Phase { + if self.response.is_some() { + Phase::Response + } else { + Phase::Request + } + } + + fn fields(&self) -> &Fields { + self.response + .as_ref() + .map_or(&self.request.headers, |r| &r.headers) + } + + fn metadata(&self, mode: BodyMode) -> io::Result { + headers::check(&self.request.headers)?; + headers::check(self.fields())?; + let snapshot = |fields: &Fields| -> Value { + fields + .iter() + .map(|(name, value)| json!({"name":name.to_ascii_lowercase(),"value":value})) + .collect() + }; + let mut input = json!({ + "phase": if self.phase() == Phase::Request { "request" } else { "response" }, + "original": {"url":self.original.url.as_str(),"method":self.original.method}, + "request": {"url":self.request.url.as_str(),"method":self.request.method, + "headers":null}, + "body": {"kind":match mode { BodyMode::None=>"not-requested",BodyMode::Text=>"text",BodyMode::Bytes=>"bytes"}}, + }); + *input + .get_mut("request") + .and_then(|request| request.get_mut("headers")) + .expect("request header slot is constructed above") = snapshot(&self.request.headers); + if let Some(response) = &self.response { + input["response"] = json!({"status":response.status,"headers":null}); + *input + .get_mut("response") + .and_then(|response| response.get_mut("headers")) + .expect("response header slot is constructed above") = snapshot(&response.headers); + } + Ok(input) + } + + fn check_header(&self, name: &str) -> io::Result<()> { + rules::validate_header_name(name)?; + if self.protected.contains(&name.to_ascii_lowercase()) + || matches!( + name.to_ascii_lowercase().as_str(), + "proxy-authorization" | "proxy-authenticate" | "content-range" + ) + { + return Err(invalid()); + } + Ok(()) + } + + /// Validation and representation repair happen before replacing any input. + pub(crate) fn apply( + &mut self, + output: ScriptOutput, + output_body: BudgetedBytes, + mode: BodyMode, + ) -> io::Result { + match output { + ScriptOutput::Pass {} => { + if !output_body.as_ref().is_empty() { + return Err(invalid()); + } + Ok(Outcome::Forward) + } + ScriptOutput::Abort {} => { + if !output_body.as_ref().is_empty() { + return Err(invalid()); + } + Ok(Outcome::Abort) + } + ScriptOutput::Modify { + url, + method, + status, + headers: operations, + body: result_body, + } => { + let request_phase = self.response.is_none(); + if (request_phase && status.is_some()) + || (!request_phase && (url.is_some() || method.is_some())) + { + return Err(invalid()); + } + if request_phase + && self.original.asterisk + && (url.is_some() || method.is_some() || result_body.is_some()) + { + return Err(invalid()); + } + let next_url = url.as_deref().map(rules::checked_url).transpose()?; + let origin_changed = next_url + .as_ref() + .is_some_and(|url| !same_origin(&self.request.url, url)); + if let Some(method) = &method { + http::Method::from_bytes(method.as_bytes()).map_err(|_| invalid())?; + if method.len() > headers::MAX_BYTES + || (method != &self.request.method + && (matches!(method.as_str(), "HEAD" | "CONNECT") + || matches!(self.request.method.as_str(), "HEAD" | "CONNECT"))) + { + return Err(invalid()); + } + } + if let Some(status) = status { + let old = self.response.as_ref().ok_or_else(invalid)?.status; + if !(200..=599).contains(&status) + || (status != old + && (self.partial_response + || special_status(old) + || special_status(status))) + { + return Err(invalid()); + } + } + let mut fields = self.fields().clone(); + if origin_changed { + headers::strip_origin_credentials(&mut fields); + } + if let Some(url) = &next_url { + update_host(&mut fields, url); + } + if let Some(operations) = operations { + self.apply_headers(&mut fields, operations)?; + } + let mut replacement = None; + if let Some(body) = result_body { + if mode == BodyMode::None { + return Err(invalid()); + } + let baseline = self + .body + .as_ref() + .and_then(Entity::logical) + .ok_or_else(invalid)?; + validate_body(&output_body, body.kind)?; + if output_body.as_ref() != baseline { + body::repair_metadata_kind( + &mut fields, + output_body.as_ref().len(), + body.kind == BodyKind::Text, + ); + replacement = Some(output_body); + } + } else if !output_body.as_ref().is_empty() { + return Err(invalid()); + } + headers::check(&fields)?; + // This is the first commit. Every validation above is complete; + // rejecting a foreign owner leaves body and metadata intact. + if let Some(bytes) = replacement { + self.body + .as_mut() + .expect("validated body input") + .replace(bytes) + .map_err(|_| invalid())?; + } + if let Some(response) = &mut self.response { + response.headers = fields; + if let Some(status) = status { + response.status = status; + } + } else { + self.request.headers = fields; + if let Some(url) = next_url { + self.request.url = url; + } + if let Some(method) = method { + self.request.method = method; + } + self.crossed_origin |= origin_changed; + } + Ok(Outcome::Forward) + } + ScriptOutput::Respond { + status, + headers: initial, + body: result_body, + } => { + if !(200..=599).contains(&status) || status == 206 { + return Err(invalid()); + } + let mut fields = Vec::new(); + for field in initial.unwrap_or_default() { + self.check_header(&field.name)?; + rules::validate_header_value(&field.value)?; + fields.push((field.name.to_ascii_lowercase(), field.value)); + } + headers::check(&fields)?; + let length = output_body.as_ref().len(); + if result_body.is_none() && length != 0 { + return Err(invalid()); + } + if let Some(body) = &result_body { + validate_body(&output_body, body.kind)?; + } + let no_body = self.original.method == "HEAD" || matches!(status, 204 | 205 | 304); + if length != 0 && (no_body || !self.original.identity_allowed) { + return Err(invalid()); + } + if result_body + .as_ref() + .is_some_and(|body| body.kind == BodyKind::Text) + { + repair_charset(&mut fields); + } + if !no_body || (status == 205 && self.original.method != "HEAD") { + fields.push(("content-length".into(), length.to_string())); + } + headers::check(&fields)?; + let body = if result_body.is_some() && length != 0 { + output_body.into_bytes() + } else { + Bytes::new() + }; + Ok(Outcome::Respond(LocalResponse { + status, + headers: fields, + body, + })) + } + } + } + + fn apply_headers(&self, fields: &mut Fields, operations: Vec) -> io::Result<()> { + if operations.len() > headers::MAX_FIELDS { + return Err(invalid()); + } + let mut records = 0usize; + let mut values_total = 0usize; + for operation in operations { + let (name, values, set) = match operation { + HeaderOp::Set { name, values } => (name, Some(values), true), + HeaderOp::Add { name, values } => (name, Some(values), false), + HeaderOp::Remove { name } => (name, None, true), + }; + self.check_header(&name)?; + let name = name.to_ascii_lowercase(); + if set { + fields.retain(|(old, _)| !old.eq_ignore_ascii_case(&name)); + } + if let Some(values) = values { + if values.is_empty() { + return Err(invalid()); + } + values_total = values_total.checked_add(values.len()).ok_or_else(invalid)?; + if values_total > headers::MAX_FIELDS { + return Err(invalid()); + } + for value in values { + rules::validate_header_value(&value)?; + records = records + .checked_add(name.len() + value.len() + 32) + .ok_or_else(invalid)?; + if records > headers::MAX_BYTES { + return Err(invalid()); + } + fields.push((name.clone(), value)); + } + } else { + records = records.checked_add(name.len() + 32).ok_or_else(invalid)?; + if records > headers::MAX_BYTES { + return Err(invalid()); + } + } + } + Ok(()) + } +} + +fn special_status(status: u16) -> bool { + matches!(status, 204 | 205 | 304 | 206) +} +fn update_host(fields: &mut Fields, url: &Url) { + for (name, value) in fields { + if name.eq_ignore_ascii_case("host") { + *value = url[url::Position::BeforeHost..url::Position::AfterPort].to_owned(); + } + } +} +fn nominated(fields: &Fields) -> BTreeSet { + fields + .iter() + .filter(|(name, _)| name.eq_ignore_ascii_case("connection")) + .flat_map(|(_, value)| value.split(',')) + .map(|value| value.trim().to_ascii_lowercase()) + .collect() +} +fn validate_body(body: &BudgetedBytes, kind: BodyKind) -> io::Result<()> { + if body.as_ref().len() > MAX_BODY + || (kind == BodyKind::Text && std::str::from_utf8(body.as_ref()).is_err()) + { + return Err(invalid()); + } + Ok(()) +} +fn repair_charset(fields: &mut Fields) { + for (name, value) in fields { + if name.eq_ignore_ascii_case("content-type") { + let mut pieces = value.split(';'); + let mut result = pieces.next().unwrap_or_default().to_owned(); + for piece in pieces { + if piece + .split_once('=') + .is_some_and(|(name, _)| name.trim().eq_ignore_ascii_case("charset")) + { + continue; + } + result.push(';'); + result.push_str(piece); + } + result.push_str("; charset=utf-8"); + *value = result; + } + } +} +fn readable_text(fields: &Fields, bytes: &[u8]) -> bool { + if std::str::from_utf8(bytes).is_err() { + return false; + } + let mut content_types = fields + .iter() + .filter(|(name, _)| name.eq_ignore_ascii_case("content-type")); + let Some((_, value)) = content_types.next() else { + return true; + }; + if content_types.next().is_some() { + return false; + } + value.split(';').skip(1).all(|piece| { + !piece.split_once('=').is_some_and(|(name, value)| { + name.trim().eq_ignore_ascii_case("charset") + && !matches!( + value.trim().trim_matches('"').to_ascii_lowercase().as_str(), + "utf-8" | "utf8" + ) + }) + }) +} + +// Preserve the existing per-invocation output-owner charge while queued; +// only its not-yet-allocated payload is deferred until the same lane is held. +#[cfg(target_vendor = "apple")] +struct PendingPlanOutput<'a> { + budget: &'a Budget, + reservation: super::body_budget::Reservation, + bound: usize, +} +#[cfg(target_vendor = "apple")] +const _: () = assert!( + std::mem::size_of::>() <= std::mem::size_of::() +); +#[cfg(target_vendor = "apple")] +impl<'a> PendingPlanOutput<'a> { + fn new( + budget: &'a Budget, + bytes: Option<&[u8]>, + mode: BodyMode, + backend: super::scripts::Backend<'_>, + ) -> io::Result { + let bound = backend.output_bound(bytes.map_or(0, <[u8]>::len)); + if !backend.is_plan() + || mode != BodyMode::Text + || bytes.is_none_or(|bytes| bytes.len() > MAX_BODY) + || bound > MAX_BODY + { + return Err(invalid()); + } + let output_cost = BudgetedBytes::allocation_cost(bound).ok_or_else(exhausted)?; + let bookkeeping = BudgetedBytes::allocation_cost(0).ok_or_else(exhausted)?; + super::diagnostics::call_buffers_requested(0, output_cost, 0); + let reservation = budget.reserve(bookkeeping).ok_or_else(|| { + super::diagnostics::increment(super::diagnostics::Counter::CallBuffersBudgetRejected); + exhausted() + })?; + super::diagnostics::increment(super::diagnostics::Counter::PlanOutputPendingAdmitted); + Ok(Self { + budget, + reservation, + bound, + }) + } + // The caller already owns InvocationLane. No wait and no second queue. + fn materialize(mut self) -> io::Result { + let payload = self.budget.reserve(self.bound).ok_or_else(|| { + super::diagnostics::increment( + super::diagnostics::Counter::PlanOutputPayloadBudgetRejected, + ); + super::diagnostics::increment(super::diagnostics::Counter::CallBuffersBudgetRejected); + exhausted() + })?; + self.reservation.merge(payload).map_err(|_| invalid())?; + let output = BudgetedBytes::from_reserved_fixed_output(self.reservation, self.bound) + .ok_or_else(|| { + super::diagnostics::increment( + super::diagnostics::Counter::CallBuffersAllocationRejected, + ); + exhausted() + })?; + super::diagnostics::increment(super::diagnostics::Counter::CallBuffersAdmitted); + Ok(CallBuffers { + output, + bridge_workspace: None, + }) + } +} + +struct CallBuffers { + output: BudgetedBytes, + bridge_workspace: Option, +} +impl CallBuffers { + fn for_backend( + budget: &Budget, + bytes: Option<&[u8]>, + mode: BodyMode, + backend: super::scripts::Backend<'_>, + ) -> io::Result { + let bound = backend.output_bound(bytes.map_or(0, <[u8]>::len)); + if !backend.is_plan() { + return Self::with_output_bound(budget, bytes, mode, bound); + } + // Selection is final: a refusal skips this invocation, never JSC. + if mode != BodyMode::Text + || bytes.is_none_or(|bytes| bytes.len() > MAX_BODY) + || bound > MAX_BODY + { + return Err(invalid()); + } + let output_cost = BudgetedBytes::allocation_cost(bound).ok_or_else(exhausted)?; + super::diagnostics::call_buffers_requested(0, output_cost, 0); + let permit = budget.reserve(output_cost).ok_or_else(|| { + super::diagnostics::increment(super::diagnostics::Counter::CallBuffersBudgetRejected); + exhausted() + })?; + let output = BudgetedBytes::from_reserved(permit, bound).ok_or_else(|| { + super::diagnostics::increment( + super::diagnostics::Counter::CallBuffersAllocationRejected, + ); + exhausted() + })?; + super::diagnostics::increment(super::diagnostics::Counter::CallBuffersAdmitted); + Ok(Self { + output, + bridge_workspace: None, + }) + } + #[cfg(test)] + fn new(budget: &Budget, bytes: Option<&[u8]>, mode: BodyMode) -> io::Result { + Self::with_output_bound(budget, bytes, mode, MAX_BODY) + } + fn with_output_bound( + budget: &Budget, + bytes: Option<&[u8]>, + mode: BodyMode, + output_bound: usize, + ) -> io::Result { + let Some(bytes) = bytes else { + super::diagnostics::call_buffers_requested(0, 0, 0); + super::diagnostics::increment(super::diagnostics::Counter::CallBuffersAdmitted); + return Ok(Self { + output: BudgetedBytes::empty(budget), + bridge_workspace: None, + }); + }; + if bytes.len() > MAX_BODY || output_bound > MAX_BODY { + return Err(invalid()); + } + // The immutable Entity remains borrowed through the real owner join. + // JSC still creates its independently paid string/typed-array copy. + // One prepaid terminator byte preserves the ASCII public export API. + // Actual result bytes remain limited by output_bound in the adapter. + let output_capacity = + super::body_budget::output_capacity(output_bound).ok_or_else(exhausted)?; + let output_cost = BudgetedBytes::allocation_cost(output_capacity).ok_or_else(exhausted)?; + let bridge_cost = + super::body_budget::BridgePlan::new(bytes.len(), mode == BodyMode::Text, output_bound) + .and_then(super::body_budget::BridgePlan::cost) + .ok_or_else(exhausted)?; + super::diagnostics::call_buffers_requested(0, output_cost, bridge_cost); + let mut all = budget + .reserve(output_cost.checked_add(bridge_cost).ok_or_else(exhausted)?) + .ok_or_else(|| { + super::diagnostics::increment( + super::diagnostics::Counter::CallBuffersBudgetRejected, + ); + exhausted() + })?; + let bridge_workspace = Some(all.split(bridge_cost).ok_or_else(exhausted)?); + let allocation_failed = || { + super::diagnostics::increment( + super::diagnostics::Counter::CallBuffersAllocationRejected, + ); + exhausted() + }; + let output = + BudgetedBytes::from_reserved(all, output_capacity).ok_or_else(allocation_failed)?; + super::diagnostics::increment(super::diagnostics::Counter::CallBuffersAdmitted); + Ok(Self { + output, + bridge_workspace, + }) + } +} + +pub(crate) async fn run( + policy: &Policy, + original: &Url, + message: &mut Message, + cancellation: &CancellationToken, +) -> io::Result { + run_until( + policy, + original, + message, + cancellation, + Instant::now() + Duration::from_secs(1), + ) + .await +} + +fn report_backend_error(error: io::Error, script_name: &str, phase: Phase) -> io::Result<()> { + if matches!( + error.kind(), + io::ErrorKind::BrokenPipe + | io::ErrorKind::ConnectionAborted + | io::ErrorKind::ConnectionReset + | io::ErrorKind::NotConnected + | io::ErrorKind::Unsupported + ) { + super::diagnostics::increment(super::diagnostics::Counter::BackendFatal); + tracing::warn!(target: "vole::http_processing::script", script = %script_name, phase = ?phase, error_kind = ?error.kind(), error = %error, "HTTP script backend failed"); + Err(error) + } else { + tracing::warn!(target: "vole::http_processing::script", script = %script_name, phase = ?phase, error_kind = ?error.kind(), error = %error, "HTTP script failed"); + Ok(()) + } +} + +fn check_stage(cancellation: &CancellationToken, deadline: Instant) -> io::Result<()> { + if cancellation.is_cancelled() { + return Err(io::ErrorKind::Interrupted.into()); + } + if Instant::now() >= deadline { + return Err(io::ErrorKind::TimedOut.into()); + } + Ok(()) +} + +async fn run_until( + policy: &Policy, + original: &Url, + message: &mut Message, + cancellation: &CancellationToken, + deadline: Instant, +) -> io::Result { + if &message.original.url != original { + return Err(invalid()); + } + check_stage(cancellation, deadline)?; + let phase = message.phase(); + for script in policy + .scripts() + .iter() + .filter(|script| script.phase == phase && script.matches(original)) + { + check_stage(cancellation, deadline)?; + super::diagnostics::increment(super::diagnostics::Counter::ScriptMatched); + if message.phase() == Phase::Request + && message.original.asterisk + && script.body != BodyMode::None + { + super::diagnostics::increment(super::diagnostics::Counter::SkipAsteriskBody); + tracing::debug!(target: "vole::http_processing::script", script = %script.name, phase = ?phase, reason = "asterisk-body", "HTTP script skipped"); + continue; + } + let bytes = if script.body == BodyMode::None { + None + } else { + let Some(bytes) = message.body.as_ref().and_then(Entity::logical) else { + super::diagnostics::increment(super::diagnostics::Counter::SkipBodyUnavailable); + tracing::debug!(target: "vole::http_processing::script", script = %script.name, phase = ?phase, reason = "body-unavailable", "HTTP script skipped"); + continue; + }; + let text_readable = message.body.as_ref().is_some_and(|body| { + if body.changed() { + readable_text(message.fields(), bytes) + } else { + body.original_text_allowed() && std::str::from_utf8(bytes).is_ok() + } + }); + if script.body == BodyMode::Text && !text_readable { + super::diagnostics::increment(super::diagnostics::Counter::SkipTextUnavailable); + tracing::debug!(target: "vole::http_processing::script", script = %script.name, phase = ?phase, reason = "text-unavailable", "HTTP script skipped"); + continue; + } + Some(bytes) + }; + let Ok(metadata) = message.metadata(script.body) else { + super::diagnostics::increment(super::diagnostics::Counter::SkipInputUnrepresentable); + tracing::debug!(target: "vole::http_processing::script", script = %script.name, phase = ?phase, reason = "input-unrepresentable", "HTTP script skipped"); + continue; + }; + // Both references borrow the same immutable Entity owner. The witness + // adds ledger identity, never another input copy or reservation. + let borrowed = bytes.and_then(|_| message.body.as_ref().and_then(Entity::borrowed_body)); + let backend = script.compiled.backend(&metadata, borrowed); + #[cfg(target_vendor = "apple")] + let mut acquired_lane = None; + let prepared_buffers = { + #[cfg(target_vendor = "apple")] + if backend.is_plan() { + match PendingPlanOutput::new(policy.body_budget(), bytes, script.body, backend) { + Err(error) => Err(error), + Ok(pending) => { + let lane = + match super::scripts::InvocationLane::acquire(cancellation, deadline) + .await + { + Ok(lane) => lane, + Err(error) => { + super::diagnostics::increment( + super::diagnostics::Counter::PlanOutputQueueFailed, + ); + check_stage(cancellation, deadline)?; + report_backend_error(error, &script.name, phase)?; + continue; + } + }; + acquired_lane = Some(lane); + pending.materialize() + } + } + } else { + CallBuffers::for_backend(policy.body_budget(), bytes, script.body, backend) + } + #[cfg(not(target_vendor = "apple"))] + { + CallBuffers::for_backend(policy.body_budget(), bytes, script.body, backend) + } + }; + let Ok(mut buffers) = prepared_buffers else { + if backend.is_plan() { + super::diagnostics::increment(super::diagnostics::Counter::PlanBuffersRejected); + } + super::diagnostics::increment(super::diagnostics::Counter::SkipCallBuffers); + tracing::debug!(target: "vole::http_processing::script", script = %script.name, phase = ?phase, reason = "body-budget", "HTTP script skipped"); + continue; + }; + let result = { + #[cfg(target_vendor = "apple")] + if let Some(lane) = acquired_lane { + if super::scripts::plan_can_run_direct() { + // Keep this exact paid output and acquired lane/deadline. + // One scheduling opportunity, not an IO-poll guarantee. + tokio::task::yield_now().await; + } + super::scripts::evaluate_plan_in_lane( + backend, + &metadata, + borrowed, + &mut buffers.output, + cancellation, + lane, + ) + } else { + super::scripts::evaluate_backend_until( + backend, + &metadata, + // The typed witness borrows the actual sender-owned Bytes, through + // the same actual backend owner/TLS join. No raw slice retagging. + borrowed, + &mut buffers.output, + buffers.bridge_workspace.as_ref(), + cancellation, + deadline, + ) + .await + } + #[cfg(not(target_vendor = "apple"))] + { + super::scripts::evaluate_backend_until( + backend, + &metadata, + // The typed witness borrows the actual sender-owned Bytes, through + // the same actual backend owner/TLS join. No raw slice retagging. + borrowed, + &mut buffers.output, + buffers.bridge_workspace.as_ref(), + cancellation, + deadline, + ) + .await + } + }; + drop(buffers.bridge_workspace.take()); + check_stage(cancellation, deadline)?; + let metadata = match result { + Ok(metadata) => metadata, + Err(error) => { + report_backend_error(error, &script.name, phase)?; + continue; + } + }; + let result = serde_json::from_value::(metadata) + .map_err(|_| invalid()) + .and_then(|output| message.apply(output, buffers.output, script.body)); + check_stage(cancellation, deadline)?; + match result { + Ok(Outcome::Forward) => { + super::diagnostics::increment(super::diagnostics::Counter::OutputAccepted); + } + Ok(terminal) => { + super::diagnostics::increment(super::diagnostics::Counter::OutputTerminal); + return Ok(terminal); + } + Err(error) => { + super::diagnostics::increment(super::diagnostics::Counter::OutputRejected); + tracing::warn!(target: "vole::http_processing::script", script = %script.name, phase = ?phase, error_kind = ?error.kind(), error = %error, "HTTP script result rejected") + } + } + } + check_stage(cancellation, deadline)?; + Ok(Outcome::Forward) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn request(budget: &Budget) -> Message { + let url = Url::parse("https://a.example/path").unwrap(); + let fields = vec![ + ("Authorization".into(), "old-secret".into()), + ("Cookie".into(), "a=1".into()), + ]; + Message::request( + OriginalSnapshot { + url: url.clone(), + method: "GET".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url, + method: "GET".into(), + headers: fields.clone(), + }, + Some(Entity::identity( + BudgetedBytes::copy(budget, b"original").unwrap(), + )), + &fields, + false, + ) + } + fn output(value: Value) -> ScriptOutput { + serde_json::from_value(value).unwrap() + } + fn apply( + message: &mut Message, + budget: &Budget, + value: Value, + bytes: &[u8], + mode: BodyMode, + ) -> io::Result { + message.apply( + output(value), + BudgetedBytes::copy(budget, bytes).unwrap(), + mode, + ) + } + + #[test] + fn candidate_failure_preserves_url_credentials_body_and_prior_success() { + let budget = Budget::default(); + let mut message = request(&budget); + apply(&mut message, &budget, json!({"type":"modify","headers":[{"op":"add","name":"x-first","values":["accepted"]}]}), b"", BodyMode::None).unwrap(); + assert!(apply(&mut message, &budget, json!({"type":"modify","url":"https://b.example/","headers":[{"op":"set","name":"x-bad","values":["bad\r\nvalue"]}],"body":{"kind":"text"}}), b"changed", BodyMode::Text).is_err()); + assert_eq!(message.request.url.host_str(), Some("a.example")); + assert_eq!( + message.body.as_ref().unwrap().logical().unwrap(), + b"original" + ); + assert!( + message + .request + .headers + .iter() + .any(|(n, v)| n == "Authorization" && v == "old-secret") + ); + assert!( + message + .request + .headers + .iter() + .any(|(n, v)| n == "x-first" && v == "accepted") + ); + assert!(!message.crossed_origin); + drop(message); + assert_eq!(budget.used(), 0); + } + + #[test] + fn each_origin_transition_cleans_inherited_values_but_accepts_explicit_values() { + let budget = Budget::default(); + let mut message = request(&budget); + apply(&mut message,&budget,json!({"type":"modify","url":"https://b.example/","headers":[{"op":"set","name":"authorization","values":["b-secret"]}]}),b"",BodyMode::None).unwrap(); + assert_eq!( + message.request.headers, + vec![("authorization".into(), "b-secret".into())] + ); + apply( + &mut message, + &budget, + json!({"type":"modify","url":"https://a.example/"}), + b"", + BodyMode::None, + ) + .unwrap(); + assert!(message.request.headers.is_empty()); + assert!(message.crossed_origin); + apply(&mut message,&budget,json!({"type":"modify","url":"https://a.example:443/new","headers":[{"op":"add","name":"cookie","values":["a=new"]}]}),b"",BodyMode::None).unwrap(); + apply( + &mut message, + &budget, + json!({"type":"modify","url":"https://a.example/path"}), + b"", + BodyMode::None, + ) + .unwrap(); + assert_eq!( + message.request.headers, + vec![("cookie".into(), "a=new".into())] + ); + } + + #[test] + fn repeated_header_values_and_control_record_limits_are_distinct() { + let budget = Budget::default(); + let mut message = request(&budget); + apply(&mut message,&budget,json!({"type":"modify","headers":[{"op":"set","name":"x-values","values":["1","2"]},{"op":"add","name":"X-Values","values":["3"]}]}),b"",BodyMode::None).unwrap(); + let values: Vec<_> = message + .request + .headers + .iter() + .filter(|(n, _)| n == "x-values") + .map(|(_, v)| v.as_str()) + .collect(); + assert_eq!(values, ["1", "2", "3"]); + let operations: Vec<_> = (0..101) + .map(|_| json!({"op":"set","name":"x-values","values":["one"]})) + .collect(); + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","headers":operations}), + b"", + BodyMode::None + ) + .is_err() + ); + assert_eq!( + message + .request + .headers + .iter() + .filter(|(n, _)| n == "x-values") + .count(), + 3 + ); + } + + #[test] + fn protected_and_connection_nominated_fields_never_become_writable() { + let budget = Budget::default(); + let mut message = request(&budget); + message.protected = nominated(&vec![("Connection".into(), "X-Hop".into())]); + for name in [ + "Host", + "content-length", + "Proxy-Authorization", + "content-range", + "X-Hop", + ] { + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","headers":[{"op":"remove","name":name}]}), + b"", + BodyMode::None + ) + .is_err(), + "{name}" + ); + } + } + + #[test] + fn request_host_snapshot_tracks_current_url_and_response_sees_final_request() { + let budget = Budget::default(); + let mut message = request(&budget); + message + .request + .headers + .push(("Host".into(), "a.example".into())); + apply( + &mut message, + &budget, + json!({"type":"modify","url":"https://b.example:8443/final"}), + b"", + BodyMode::None, + ) + .unwrap(); + assert!( + message + .request + .headers + .iter() + .any(|(name, value)| name == "Host" && value == "b.example:8443") + ); + let mut response = Message::response( + message.original.clone(), + message.request.clone(), + ResponseSnapshot { + status: 200, + headers: vec![], + }, + None, + &vec![], + ); + let input = response.metadata(BodyMode::None).unwrap(); + assert_eq!(input["original"]["url"], "https://a.example/path"); + assert_eq!(input["request"]["url"], "https://b.example:8443/final"); + assert_eq!( + input["request"]["headers"], + json!([{"name":"host","value":"b.example:8443"}]) + ); + assert_eq!(input["body"], json!({"kind":"not-requested"})); + assert!( + apply( + &mut response, + &budget, + json!({"type":"modify","url":"https://a.example/"}), + b"", + BodyMode::None + ) + .is_err() + ); + assert_eq!( + response.request.url.as_str(), + "https://b.example:8443/final" + ); + } + + #[test] + fn method_status_and_phase_rules_cannot_change_http_message_classes() { + let budget = Budget::default(); + let mut message = request(&budget); + for method in ["HEAD", "CONNECT", "bad method", ""] { + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","method":method}), + b"", + BodyMode::None + ) + .is_err() + ); + } + apply( + &mut message, + &budget, + json!({"type":"modify","method":"PATCH"}), + b"", + BodyMode::None, + ) + .unwrap(); + assert_eq!(message.request.method, "PATCH"); + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","status":201}), + b"", + BodyMode::None + ) + .is_err() + ); + message.response = Some(ResponseSnapshot { + status: 200, + headers: vec![], + }); + for status in [101, 204, 205, 206, 304, 600] { + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","status":status}), + b"", + BodyMode::None + ) + .is_err() + ); + } + apply( + &mut message, + &budget, + json!({"type":"modify","status":201}), + b"", + BodyMode::None, + ) + .unwrap(); + message.response.as_mut().unwrap().status = 204; + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","status":304}), + b"", + BodyMode::None + ) + .is_err() + ); + apply( + &mut message, + &budget, + json!({"type":"modify","status":204}), + b"", + BodyMode::None, + ) + .unwrap(); + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","url":"https://b.example/"}), + b"", + BodyMode::None + ) + .is_err() + ); + } + + #[test] + fn local_results_respect_identity_head_status_and_duplicate_cookie_values() { + let budget = Budget::default(); + let mut message = request(&budget); + message.original.identity_allowed = false; + assert!( + apply( + &mut message, + &budget, + json!({"type":"respond","status":200,"body":{"kind":"bytes"}}), + b"new", + BodyMode::None + ) + .is_err() + ); + message.original.identity_allowed = true; + for status in [204, 205, 304, 206] { + assert!( + apply( + &mut message, + &budget, + json!({"type":"respond","status":status,"body":{"kind":"text"}}), + b"new", + BodyMode::None + ) + .is_err() + ); + } + let Outcome::Respond(response)=apply(&mut message,&budget,json!({"type":"respond","status":200,"headers":[{"name":"Set-Cookie","value":"a=1"},{"name":"Set-Cookie","value":"b=2"}],"body":{"kind":"text"}}),b"new",BodyMode::None).unwrap() else { panic!("local response") }; + assert_eq!(response.body, b"new".as_slice()); + assert_eq!( + response + .headers + .iter() + .filter(|(n, _)| n == "set-cookie") + .count(), + 2 + ); + message.original.method = "HEAD".into(); + assert!( + apply( + &mut message, + &budget, + json!({"type":"respond","status":200,"body":{"kind":"bytes"}}), + b"new", + BodyMode::None + ) + .is_err() + ); + let Outcome::Respond(response) = apply( + &mut message, + &budget, + json!({"type":"respond","status":200}), + b"", + BodyMode::None, + ) + .unwrap() else { + panic!("local HEAD") + }; + assert!(!response.headers.iter().any(|(n, _)| n == "content-length")); + } + + #[test] + fn binary_repair_does_not_guess_charset_and_metadata_failure_rolls_back() { + let budget = Budget::default(); + let mut message = request(&budget); + message.request.headers = vec![ + ( + "content-type".into(), + "application/octet-stream; charset=latin1".into(), + ), + ("etag".into(), "old".into()), + ("content-encoding".into(), "gzip".into()), + ]; + apply( + &mut message, + &budget, + json!({"type":"modify","body":{"kind":"bytes"}}), + &[0xff, 0x00], + BodyMode::Bytes, + ) + .unwrap(); + assert!( + message + .request + .headers + .iter() + .any(|(n, v)| n == "content-type" && v.ends_with("latin1")) + ); + assert!( + !message + .request + .headers + .iter() + .any(|(n, _)| n == "etag" || n == "content-encoding") + ); + assert!(!readable_text( + &message.request.headers, + message.body.as_ref().unwrap().logical().unwrap() + )); + apply( + &mut message, + &budget, + json!({"type":"modify","body":{"kind":"text"}}), + b"UTF-8", + BodyMode::Bytes, + ) + .unwrap(); + assert!(readable_text( + &message.request.headers, + message.body.as_ref().unwrap().logical().unwrap() + )); + message.request.headers = (0..100) + .map(|n| (format!("x-{n}"), "value".into())) + .collect(); + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","body":{"kind":"text"}}), + b"must-rollback", + BodyMode::Text + ) + .is_err() + ); + assert_eq!(message.body.as_ref().unwrap().logical().unwrap(), b"UTF-8"); + } + + #[test] + fn null_unknown_union_and_body_mode_fail_closed() { + for value in [ + json!(null), + json!({"type":"pass","body":{}}), + json!({"type":"abort","url":"https://example.com/"}), + json!({"type":"modify","url":null}), + json!({"type":"modify","body":{"kind":"not-requested"}}), + json!({"type":"modify","headers":[{"op":"remove","name":"x","values":[]}]}), + json!({"type":"respond","status":200.5}), + ] { + assert!(serde_json::from_value::(value).is_err()); + } + let budget = Budget::default(); + let mut message = request(&budget); + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","body":{"kind":"bytes"}}), + b"", + BodyMode::None + ) + .is_err() + ); + message.original.asterisk = true; + assert!( + apply( + &mut message, + &budget, + json!({"type":"modify","method":"GET"}), + b"", + BodyMode::None + ) + .is_err() + ); + } + + #[cfg(target_vendor = "apple")] + #[tokio::test(flavor = "current_thread")] + async fn bounded_output_arena_production_run_rolls_back_one_call_and_runs_the_next() { + let policy=Policy::compile(r#"http-scripts: + enabled: true + scripts: + - name: reject-protected-header + phase: request + match: exact + url: https://a.example/path + body: text + source: 'function rewrite(input){return {type:"modify",headers:[{op:"set",name:"host",values:["invalid.example"]}],body:{kind:"text",data:"bad"}};}' + - name: accepted-after-rollback + phase: request + match: exact + url: https://a.example/path + body: text + source: 'function rewrite(input){return {type:"modify",headers:[{op:"add",name:"x-bridge",values:["done"]}],body:{kind:"text",data:input.body.data.replaceAll("i","I")}};}' +"#).unwrap(); + let budget = policy.body_budget(); + let mut message = request(budget); + let original = message.original.url.clone(); + // Old input/MAX-output/3MAX bridge admission skips both calls here. + // Bounded copies fit, while total ledger and production lane stay fixed. + let held = budget + .reserve(super::super::body_budget::WORKSPACE - budget.used() - 2048) + .unwrap(); + assert!(matches!( + run(&policy, &original, &mut message, &CancellationToken::new()) + .await + .unwrap(), + Outcome::Forward + )); + assert_eq!( + message.body.as_ref().unwrap().logical().unwrap(), + b"orIgInal" + ); + assert!( + message + .request + .headers + .iter() + .any(|(name, value)| name == "x-bridge" && value == "done") + ); + assert!( + !message + .request + .headers + .iter() + .any(|(name, value)| name == "host" && value == "invalid.example") + ); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + assert!( + matches!(run(&policy,&original,&mut message,&cancelled).await,Err(error) if error.kind()==io::ErrorKind::Interrupted) + ); + assert_eq!( + message.body.as_ref().unwrap().logical().unwrap(), + b"orIgInal" + ); + drop(held); + drop(message); + assert_eq!(budget.used(), 0); + } + + #[test] + fn metadata_only_calls_run_even_when_the_entire_body_workspace_is_held() { + let budget = Budget::default(); + let url = Url::parse("https://a.example/").unwrap(); + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "GET".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url, + method: "GET".into(), + headers: vec![], + }, + None, + &vec![], + false, + ); + let held = budget + .reserve(super::super::body_budget::WORKSPACE) + .unwrap(); + let buffers = CallBuffers::new(&budget, None, BodyMode::None).unwrap(); + message.apply(output(json!({"type":"modify","headers":[{"op":"set","name":"x-meta","values":["yes"]}]})), buffers.output, BodyMode::None).unwrap(); + assert_eq!( + message.request.headers, + vec![("x-meta".into(), "yes".into())] + ); + assert!( + CallBuffers::new(&budget, None, BodyMode::None) + .unwrap() + .output + .prepare_output(1) + .is_err() + ); + drop(held); + assert_eq!(budget.used(), 0); + } + + #[test] + fn generated_205_has_explicit_zero_length_unless_head_semantics_take_precedence() { + let budget = Budget::default(); + let mut message = request(&budget); + let Outcome::Respond(response) = apply( + &mut message, + &budget, + json!({"type":"respond","status":205}), + b"", + BodyMode::None, + ) + .unwrap() else { + panic!("205 response") + }; + assert_eq!( + response.headers, + vec![("content-length".into(), "0".into())] + ); + message.original.method = "HEAD".into(); + let Outcome::Respond(response) = apply( + &mut message, + &budget, + json!({"type":"respond","status":205}), + b"", + BodyMode::None, + ) + .unwrap() else { + panic!("HEAD response") + }; + assert!(response.headers.is_empty()); + } + + #[tokio::test] + async fn expired_stage_never_enters_backend_or_accepts_a_terminal_result() { + let policy = Policy::compile( + r#"http-scripts: + enabled: true + scripts: + - name: must-not-execute + phase: request + url: https://a.example/path + match: exact + source: 'function rewrite(input) { return {type:"abort"}; }' +"#, + ) + .unwrap(); + let budget = Budget::default(); + let mut message = request(&budget); + let original = message.original.url.clone(); + let result = run_until( + &policy, + &original, + &mut message, + &CancellationToken::new(), + Instant::now() - Duration::from_millis(1), + ) + .await; + assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::TimedOut)); + assert_eq!(message.request.url, original); + assert_eq!( + message.body.as_ref().unwrap().logical().unwrap(), + b"original" + ); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + let result = run_until( + &policy, + &original, + &mut message, + &cancelled, + Instant::now() - Duration::from_millis(1), + ) + .await; + assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::Interrupted)); + } +} + +#[cfg(test)] +#[path = "script_message/borrowed_input_tests.rs"] +mod borrowed_input_tests; + +#[cfg(all(test, target_vendor = "apple"))] +#[path = "script_message/guard_coverage_tests.rs"] +mod guard_coverage_tests; + +#[cfg(all(test, unix))] +#[path = "script_message/mapped_output_tests.rs"] +mod mapped_output_tests; + +#[cfg(all(test, target_vendor = "apple"))] +#[path = "script_message/plan_yield_tests.rs"] +mod plan_yield_tests; diff --git a/src/http_processing/script_message/borrowed_input_tests.rs b/src/http_processing/script_message/borrowed_input_tests.rs new file mode 100644 index 0000000..ae63d5f --- /dev/null +++ b/src/http_processing/script_message/borrowed_input_tests.rs @@ -0,0 +1,203 @@ +//! Unexecuted memory-only candidate regressions. No sockets or peers. +use super::*; + +#[test] +fn borrowed_input_admits_at_the_same_budget_where_a_real_input_copy_cannot() { + const LENGTH: usize = 65536; + let budget = Budget::default(); + let original = BudgetedBytes::copy(&budget, &vec![b'a'; LENGTH]) + .unwrap() + .into_bytes(); + let original_slice = original.slice(1..2); + let original_cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let output_cost = + BudgetedBytes::allocation_cost(super::super::body_budget::output_capacity(LENGTH).unwrap()) + .unwrap(); + let bridge_cost = super::super::body_budget::BridgePlan::new(LENGTH, true, LENGTH) + .unwrap() + .cost() + .unwrap(); + let borrowed_cost = output_cost + bridge_cost; + let copied_cost = original_cost + borrowed_cost; + let occupied = budget + .reserve(super::super::body_budget::WORKSPACE - original_cost - copied_cost + 1) + .unwrap(); + let before = budget.used(); + + // Materialize the removed copy, rather than merely comparing formulas. + // With that actual owner retained, the unchanged output+bridge cannot fit. + let copied_input = BudgetedBytes::copy(&budget, &original).unwrap(); + assert!( + CallBuffers::with_output_bound(&budget, Some(&original), BodyMode::Text, LENGTH).is_err() + ); + drop(copied_input); + assert_eq!(budget.used(), before); + + // The old production CallBuffers also fails this assertion: available + // budget is exactly one byte short of its combined copied-input charge. + let mut buffers = + CallBuffers::with_output_bound(&budget, Some(&original), BodyMode::Text, LENGTH) + .expect("an already charged immutable input needs no second Rust copy"); + assert_eq!(budget.used(), before + borrowed_cost); + buffers.output.extend(&vec![b'b'; LENGTH]).unwrap(); + let CallBuffers { + output, + bridge_workspace, + .. + } = buffers; + drop(bridge_workspace); + let output = output.into_bytes(); + let output_slice = output.slice(1..2); + drop(occupied); + assert_eq!(budget.used(), original_cost + output_cost); + drop(original); + assert_eq!(budget.used(), original_cost + output_cost); + drop(original_slice); + assert_eq!(budget.used(), output_cost); + drop(output); + assert_eq!(budget.used(), output_cost); + assert_eq!(output_slice.as_ref(), b"b"); + drop(output_slice); + assert_eq!(budget.used(), 0); +} + +#[cfg(target_vendor = "apple")] +#[tokio::test(flavor = "current_thread")] +async fn borrowed_input_production_text_unicode_nul_and_writable_bytes_stay_isolated() { + let cases: &[(BodyMode, &str, &[u8], &[u8])] = &[ + ( + BodyMode::Text, + "function rewrite(input){input.body.data='after\\u0000caf\\u00e9\\ud83d\\ude00';return {type:'modify',body:{kind:'text',data:input.body.data}};}", + "before\0café😀".as_bytes(), + "after\0café😀".as_bytes(), + ), + ( + BodyMode::Bytes, + "function rewrite(input){input.body.data[1]=90;return {type:'modify',body:{kind:'bytes',data:input.body.data}};}", + &[0, 1, 255, 0, 2], + &[0, 90, 255, 0, 2], + ), + ]; + for &(mode, source, input, expected) in cases { + let mode_name = match mode { + BodyMode::Text => "text", + BodyMode::Bytes => "bytes", + BodyMode::None => unreachable!(), + }; + let policy = Policy::compile(&format!( + "http-scripts:\n enabled: true\n scripts:\n - name: owned-input\n phase: request\n match: exact\n url: https://borrowed.example/path\n body: {mode_name}\n source: {}\n", + serde_json::to_string(source).unwrap(), + )) + .unwrap(); + let url = Url::parse("https://borrowed.example/path").unwrap(); + let entity = Entity::identity(BudgetedBytes::copy(policy.body_budget(), input).unwrap()); + let original_owner = entity.wire().clone(); + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: vec![], + }, + Some(entity), + &vec![], + false, + ); + assert!(matches!( + run(&policy, &url, &mut message, &CancellationToken::new()) + .await + .unwrap(), + Outcome::Forward + )); + assert_eq!(original_owner.as_ref(), input); + assert_eq!(message.body.as_ref().unwrap().logical().unwrap(), expected); + assert_ne!( + original_owner.as_ptr(), + message.body.as_ref().unwrap().wire().as_ptr() + ); + } +} + +#[cfg(target_vendor = "apple")] +#[tokio::test(flavor = "current_thread")] +async fn borrowed_input_mutation_then_invalid_result_keeps_the_original_entity() { + let policy = Policy::compile( + r#"http-scripts: + enabled: true + scripts: + - name: reject-after-input-mutation + phase: request + match: exact + url: https://borrowed.example/path + body: bytes + source: 'function rewrite(input){input.body.data[0]=90;return {type:"modify",headers:[{op:"set",name:"host",values:["rejected.example"]}],body:{kind:"bytes",data:input.body.data}};}' +"#, + ) + .unwrap(); + let url = Url::parse("https://borrowed.example/path").unwrap(); + let input = [1, 2, 255, 0]; + let entity = Entity::identity(BudgetedBytes::copy(policy.body_budget(), &input).unwrap()); + let original_owner = entity.wire().clone(); + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: vec![], + }, + Some(entity), + &vec![], + false, + ); + let original_headers = message.request.headers.clone(); + assert!(matches!( + run(&policy, &url, &mut message, &CancellationToken::new()) + .await + .unwrap(), + Outcome::Forward + )); + assert_eq!(message.body.as_ref().unwrap().logical().unwrap(), input); + assert_eq!( + message.body.as_ref().unwrap().wire().as_ptr(), + original_owner.as_ptr() + ); + assert_eq!(message.request.headers, original_headers); + assert_eq!(original_owner.as_ref(), input); +} + +#[cfg(target_vendor = "apple")] +#[test] +fn static_plan_admission_pays_real_output_without_a_jsc_bridge() { + const LENGTH: usize = 65536; + let budget = Budget::default(); + let entity = Entity::identity(BudgetedBytes::copy(&budget, &vec![b'-'; LENGTH]).unwrap()); + let source = super::super::scripts::validate_source("function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('-', '_')}};}").unwrap(); + let metadata = json!({"body":{"kind":"text"}}); + let backend = source.backend(&metadata, entity.borrowed_body()); + assert!(backend.is_plan()); + let input_cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let output_cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let blocker = budget + .reserve(super::super::body_budget::WORKSPACE - input_cost - output_cost) + .unwrap(); + assert!( + CallBuffers::with_output_bound(&budget, entity.logical(), BodyMode::Text, LENGTH).is_err() + ); + let buffers = + CallBuffers::for_backend(&budget, entity.logical(), BodyMode::Text, backend).unwrap(); + assert!(buffers.bridge_workspace.is_none()); + assert_eq!(buffers.output.remaining(), LENGTH); + assert_eq!(budget.used(), super::super::body_budget::WORKSPACE); + drop((buffers, blocker, entity)); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/script_message/guard_coverage_tests.rs b/src/http_processing/script_message/guard_coverage_tests.rs new file mode 100644 index 0000000..dd686ac --- /dev/null +++ b/src/http_processing/script_message/guard_coverage_tests.rs @@ -0,0 +1,254 @@ +//! Actual Message metadata is the business guard proof boundary, not arbitrary JSON. +use super::*; +use crate::http_processing::{ + body_budget::{BridgePlan, output_capacity}, + scripts, +}; + +fn source(array: &str) -> String { + format!( + "function rewrite(input){{let found=false;for(let i=0;i Message { + let url = Url::parse("https://guard.example/path").unwrap(); + let original = OriginalSnapshot { + url: url.clone(), + method: "GET".into(), + identity_allowed: true, + asterisk: false, + }; + let request = RequestSnapshot { + url, + method: "GET".into(), + headers: request, + }; + let body = Some(Entity::identity( + BudgetedBytes::copy(budget, "中文-😀".as_bytes()).unwrap(), + )); + match phase { + Phase::Request => Message::request(original, request, body, &vec![], false), + Phase::Response => Message::response( + original, + request, + ResponseSnapshot { + status: 200, + headers: response, + }, + body, + &vec![], + ), + } +} + +fn selected(compiled: &scripts::CompiledSource, message: &Message) -> bool { + let metadata = message.metadata(BodyMode::Text).unwrap(); + compiled + .backend( + &metadata, + message.body.as_ref().and_then(Entity::borrowed_body), + ) + .is_plan() +} + +async fn compare_actual_jsc( + compiled: &scripts::CompiledSource, + message: &Message, + budget: &Budget, +) -> (Value, Vec) { + let metadata = message.metadata(BodyMode::Text).unwrap(); + let entity = message.body.as_ref().unwrap(); + let input = entity.logical().unwrap(); + let original_owner = entity.wire().clone(); + let ledger = message.body.as_ref().unwrap().borrowed_body().unwrap(); + let local_budget = Budget::default(); + // The reference uses a separately witnessed owner/ledger; business input + // remains unchanged and no owner is relabelled or refunded early. + let reference = BudgetedBytes::copy(&local_budget, input).unwrap(); + let bound = compiled.maximum_output_bytes(input.len()); + let mut jsc_body = BudgetedBytes::new(&local_budget, output_capacity(bound).unwrap()).unwrap(); + let bridge = local_budget + .reserve( + BridgePlan::new(input.len(), true, bound) + .unwrap() + .cost() + .unwrap(), + ) + .unwrap(); + scripts::prepare_platform(&CancellationToken::new()).unwrap(); + let jsc = scripts::evaluate_until( + compiled, + &metadata, + Some(reference.as_ref()), + &mut jsc_body, + Some(&bridge), + &CancellationToken::new(), + Instant::now() + Duration::from_secs(1), + ) + .await + .unwrap(); + let expected = jsc_body.as_ref().to_vec(); + drop((reference, jsc_body, bridge)); + assert_eq!(local_budget.used(), 0); + + // A real Message's current body carries this exact ledger provenance. + let metadata = message.metadata(BodyMode::Text).unwrap(); + let mut plan_body = BudgetedBytes::new(budget, output_capacity(bound).unwrap()).unwrap(); + let backend = compiled.backend(&metadata, Some(ledger)); + assert!(backend.is_plan()); + let plan = scripts::evaluate_backend_until( + backend, + &metadata, + Some(ledger), + &mut plan_body, + None, + &CancellationToken::new(), + Instant::now() + Duration::from_secs(1), + ) + .await + .unwrap(); + assert_eq!(plan, jsc); + assert_eq!(plan_body.as_ref(), expected); + assert_eq!( + message.body.as_ref().unwrap().wire().as_ptr(), + original_owner.as_ptr() + ); + (plan, expected) +} + +#[tokio::test(flavor = "current_thread")] +async fn canonical_message_guards_cover_both_request_domains_and_response_domain() { + for (phase, array) in [ + (Phase::Request, "request"), + (Phase::Response, "request"), + (Phase::Response, "response"), + ] { + let budget = Budget::default(); + let fields = vec![ + ("X-Check".into(), "other".into()), + ("x-check".into(), "中文😀".into()), + ]; + let message = message(phase, fields.clone(), fields, &budget); + let compiled = scripts::validate_source(&source(array)).unwrap(); + assert!(!compiled.needs_jsc_for_business(BodyMode::Text, phase)); + assert!(selected(&compiled, &message)); + let (output, bytes) = compare_actual_jsc(&compiled, &message, &budget).await; + assert_eq!(output["type"], "modify"); + assert_eq!(bytes, "中文_😀".as_bytes()); + } + for (phase, array) in [ + (Phase::Request, "request"), + (Phase::Response, "request"), + (Phase::Response, "response"), + ] { + let budget = Budget::default(); + let message = message(phase, vec![], vec![], &budget); + let compiled = scripts::validate_source(&source(array)).unwrap(); + assert!(selected(&compiled, &message)); + let (output, bytes) = compare_actual_jsc(&compiled, &message, &budget).await; + assert_eq!(output["type"], "pass"); + assert!(bytes.is_empty()); + } +} + +#[test] +fn metadata_byte_boundary_is_checked_before_a_guard_can_execute() { + let budget = Budget::default(); + let value = "v".repeat(headers::MAX_BYTES - "x-limit".len() - 32); + let mut message = message( + Phase::Response, + vec![], + vec![("X-Limit".into(), value)], + &budget, + ); + let compiled = scripts::validate_source(&source("response")).unwrap(); + assert!(selected(&compiled, &message)); + message + .response + .as_mut() + .unwrap() + .headers + .push(("x-extra".into(), String::new())); + assert!(message.metadata(BodyMode::Text).is_err()); +} + +#[tokio::test(flavor = "current_thread")] +async fn guard_reads_the_current_native_and_previous_script_header_snapshot() { + let budget = Budget::default(); + let mut message = message(Phase::Response, vec![], vec![], &budget); + let url = message.original.url.clone(); + let raw: rules::RawRule = serde_json::from_value( + json!({"url":".","action":"response-header-add","header":"X-Check","value":"other"}), + ) + .unwrap(); + let rule = rules::Rule::compile(raw, &mut 0).unwrap(); + assert_eq!( + headers::apply( + &[rule], + &url, + Phase::Response, + &mut message.response.as_mut().unwrap().headers + ), + headers::Outcome::Changed + ); + let compiled = scripts::validate_source(&source("response")).unwrap(); + let (output, _) = compare_actual_jsc(&compiled, &message, &budget).await; + assert_eq!(output["type"], "pass"); + let output: ScriptOutput = serde_json::from_value( + json!({"type":"modify","headers":[{"op":"set","name":"X-Check","values":["中文😀"]}]}), + ) + .unwrap(); + assert!(matches!( + message + .apply(output, BudgetedBytes::empty(&budget), BodyMode::Text) + .unwrap(), + Outcome::Forward + )); + let (output, bytes) = compare_actual_jsc(&compiled, &message, &budget).await; + assert_eq!(output["type"], "modify"); + assert_eq!(bytes, "中文_😀".as_bytes()); +} + +#[tokio::test(flavor = "current_thread")] +async fn request_phase_response_guard_keeps_the_actual_jsc_exception() { + let budget = Budget::default(); + let message = message(Phase::Request, vec![], vec![], &budget); + let compiled = scripts::validate_source(&source("response")).unwrap(); + assert!(compiled.needs_jsc_for_business(BodyMode::Text, Phase::Request)); + let metadata = message.metadata(BodyMode::Text).unwrap(); + let entity = message.body.as_ref().unwrap(); + let input = entity.borrowed_body().unwrap(); + let before = entity.wire().clone(); + let bound = compiled.maximum_output_bytes(input.as_bytes().len()); + let mut output = BudgetedBytes::new(&budget, output_capacity(bound).unwrap()).unwrap(); + let bridge = budget + .reserve( + BridgePlan::new(input.as_bytes().len(), true, bound) + .unwrap() + .cost() + .unwrap(), + ) + .unwrap(); + scripts::prepare_platform(&CancellationToken::new()).unwrap(); + let backend = compiled.backend(&metadata, Some(input)); + assert!(!backend.is_plan()); + assert!( + scripts::evaluate_backend_until( + backend, + &metadata, + Some(input), + &mut output, + Some(&bridge), + &CancellationToken::new(), + Instant::now() + Duration::from_secs(1) + ) + .await + .is_err() + ); + assert!(output.as_ref().is_empty()); + assert_eq!( + message.body.as_ref().unwrap().wire().as_ptr(), + before.as_ptr() + ); +} diff --git a/src/http_processing/script_message/mapped_output_tests.rs b/src/http_processing/script_message/mapped_output_tests.rs new file mode 100644 index 0000000..419a75c --- /dev/null +++ b/src/http_processing/script_message/mapped_output_tests.rs @@ -0,0 +1,179 @@ +//! Memory-only mapped script-output ownership and transaction regressions. +use super::*; + +const LENGTH: usize = 64 * 1024; + +fn mapped(budget: &Budget, value: &[u8]) -> BudgetedBytes { + assert_eq!(value.len(), LENGTH); + let cost = BudgetedBytes::allocation_cost(value.len()).unwrap(); + let reservation = budget.reserve(cost).unwrap(); + let mut output = BudgetedBytes::from_reserved_fixed_output(reservation, value.len()).unwrap(); + assert!( + output.is_mapped_for_test(), + "must test actual mapped storage" + ); + output + .write_initialized_output(value.len(), |target| { + target.copy_from_slice(value); + Ok(value.len()) + }) + .unwrap(); + output +} + +fn request_with(body: BudgetedBytes) -> Message { + let url = Url::parse("https://a.example/path").unwrap(); + let fields = vec![ + ("authorization".into(), "old-secret".into()), + ("cookie".into(), "a=1".into()), + ]; + Message::request( + OriginalSnapshot { + url: url.clone(), + method: "GET".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url, + method: "GET".into(), + headers: fields.clone(), + }, + Some(Entity::identity(body)), + &fields, + false, + ) +} + +fn output(value: Value) -> ScriptOutput { + serde_json::from_value(value).unwrap() +} + +#[test] +fn rejected_mapped_text_preserves_prior_body_headers_origin_and_owner() { + let budget = Budget::default(); + let mut message = request_with(BudgetedBytes::copy(&budget, b"original").unwrap()); + let accepted = vec![b'a'; LENGTH]; + assert!(matches!( + message + .apply( + output(json!({ + "type": "modify", + "headers": [{"op": "set", "name": "x-first", "values": ["accepted"]}], + "body": {"kind": "text"} + })), + mapped(&budget, &accepted), + BodyMode::Text, + ) + .unwrap(), + Outcome::Forward + )); + let headers = message.request.headers.clone(); + let owner = message.body.as_ref().unwrap().wire().slice(0..1); + let pointer = message.body.as_ref().unwrap().wire().as_ptr(); + let cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + assert_eq!(budget.used(), cost); + + // URL cleanup and header changes are valid candidates; strict text body + // validation rejects this already-filled, independently owned mapping. + // None of that invocation's metadata may commit before body validation. + let mut invalid_text = vec![b'b'; LENGTH]; + invalid_text[0] = 0xff; + let candidate = mapped(&budget, &invalid_text); + assert_eq!(budget.used(), 2 * cost); + assert!( + message + .apply( + output(json!({ + "type": "modify", + "url": "https://b.example/changed", + "headers": [{"op": "set", "name": "x-second", "values": ["uncommitted"]}], + "body": {"kind": "text"} + })), + candidate, + BodyMode::Text, + ) + .is_err() + ); + assert_eq!(message.request.url.as_str(), "https://a.example/path"); + assert_eq!(message.request.headers, headers); + assert!(!message.crossed_origin); + assert_eq!(message.body.as_ref().unwrap().logical().unwrap(), accepted); + assert_eq!(message.body.as_ref().unwrap().wire().as_ptr(), pointer); + assert_eq!(budget.used(), cost, "rejected candidate alone is refunded"); + drop(message); + assert_eq!( + budget.used(), + cost, + "actual Bytes slice still owns the mapping" + ); + assert_eq!(owner.as_ref(), b"a"); + drop(owner); + assert_eq!(budget.used(), 0); +} + +#[cfg(target_vendor = "apple")] +#[tokio::test(flavor = "current_thread")] +async fn later_real_plan_reads_mapped_entity_and_preserves_sender_ownership() { + const SOURCE: &str = "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('a','b')}};}"; + let policy = Policy::compile(&format!( + "http-scripts:\n enabled: true\n scripts:\n - name: read-owned-body\n phase: request\n match: exact\n url: https://a.example/path\n body: text\n source: {}\n", + serde_json::to_string(SOURCE).unwrap(), + )) + .unwrap(); + let budget = policy.body_budget(); + let initial = vec![b'a'; LENGTH]; + let mut message = request_with(mapped(budget, &initial)); + let original_owner = message.body.as_ref().unwrap().wire().clone(); + let url = message.original.url.clone(); + let metadata = message.metadata(BodyMode::Text).unwrap(); + let compiled = super::super::scripts::validate_source(SOURCE).unwrap(); + assert!( + compiled + .backend( + &metadata, + message.body.as_ref().and_then(Entity::borrowed_body) + ) + .is_plan(), + "the later invocation must read the actual mapped Entity through its ledger witness" + ); + drop(compiled); + + assert!(matches!( + run(&policy, &url, &mut message, &CancellationToken::new()) + .await + .unwrap(), + Outcome::Forward + )); + assert_eq!(original_owner.as_ref(), initial); + assert_eq!( + message.body.as_ref().unwrap().logical().unwrap(), + vec![b'b'; LENGTH] + ); + assert_ne!( + original_owner.as_ptr(), + message.body.as_ref().unwrap().wire().as_ptr() + ); + let cancelled = CancellationToken::new(); + cancelled.cancel(); + let pointer = message.body.as_ref().unwrap().wire().as_ptr(); + assert!(matches!( + run(&policy, &url, &mut message, &cancelled).await, + Err(error) if error.kind() == io::ErrorKind::Interrupted + )); + assert_eq!(message.body.as_ref().unwrap().wire().as_ptr(), pointer); + assert_eq!( + message.body.as_ref().unwrap().logical().unwrap(), + vec![b'b'; LENGTH] + ); + let final_owner = message.body.as_ref().unwrap().wire().slice(0..1); + let cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + assert_eq!(budget.used(), 2 * cost); + drop(message); + assert_eq!(budget.used(), 2 * cost); + drop(original_owner); + assert_eq!(budget.used(), cost); + assert_eq!(final_owner.as_ref(), b"b"); + drop(final_owner); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/script_message/plan_yield_tests.rs b/src/http_processing/script_message/plan_yield_tests.rs new file mode 100644 index 0000000..8db24ee --- /dev/null +++ b/src/http_processing/script_message/plan_yield_tests.rs @@ -0,0 +1,258 @@ +//! Actual Message futures, without a test hook or a mirrored yield predicate. +use super::*; +use std::{ + future::{Future, poll_fn}, + pin::Pin, + task::Poll, +}; +use tokio::runtime::{Builder, Runtime}; + +const LENGTH: usize = 65536; +const SOURCE: &str = "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('a','b')}};}"; +fn runtime() -> Runtime { + // Test capability fixture only; no production/benchmark worker override. + let runtime = Builder::new_multi_thread() + .worker_threads(2) + .enable_all() + .build() + .unwrap(); + assert_eq!(runtime.handle().metrics().num_workers(), 2); + runtime +} +fn policy() -> std::sync::Arc { + Policy::compile(&format!( + "http-scripts:\n enabled: true\n scripts:\n - name: yield-owner\n phase: request\n match: exact\n url: https://a.example/path\n body: text\n source: {}\n", + serde_json::to_string(SOURCE).unwrap(), + )).unwrap() +} +fn message(policy: &Policy) -> (Message, Bytes, Fields) { + let url = Url::parse("https://a.example/path").unwrap(); + let body = + Entity::identity(BudgetedBytes::copy(policy.body_budget(), &vec![b'a'; LENGTH]).unwrap()); + let last = body.wire().slice(0..1); + let fields = vec![("authorization".into(), "original-secret".into())]; + let message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url, + method: "POST".into(), + headers: fields.clone(), + }, + Some(body), + &fields, + false, + ); + let compiled = super::super::scripts::validate_source(SOURCE).unwrap(); + assert!( + compiled + .backend( + &message.metadata(BodyMode::Text).unwrap(), + message.body.as_ref().and_then(Entity::borrowed_body), + ) + .is_plan(), + "fixture must select the actual closed Plan" + ); + let headers = message.request.headers.clone(); + (message, last, headers) +} +async fn suspend_with_paid_output( + mut future: Pin<&mut impl Future>>, + budget: &Budget, + expected: usize, +) { + // Queue contention may first yield with only Q. Stop only at a real Pending + // after the full output owner is charged, before synchronous Plan starts. + poll_fn(|cx| match future.as_mut().poll(cx) { + Poll::Pending if budget.used() == expected => Poll::Ready(()), + Poll::Pending => Poll::Pending, + Poll::Ready(_) => panic!("Message did not suspend with its paid output"), + }) + .await; +} +fn unchanged(message: &Message, headers: &Fields, pointer: *const u8) { + assert_eq!(message.request.url.as_str(), "https://a.example/path"); + assert_eq!(message.original.url, message.request.url); + assert_eq!(message.request.method, "POST"); + assert_eq!(&message.request.headers, headers); + assert!(!message.crossed_origin); + let body = message.body.as_ref().unwrap(); + assert_eq!(body.wire().as_ptr(), pointer); + assert_eq!(body.logical().unwrap().len(), LENGTH); + assert!(body.logical().unwrap().iter().all(|byte| *byte == b'a')); +} + +#[test] +fn direct_plan_yield_drop_keeps_same_lane_and_refunds_actual_output() { + let runtime = runtime(); + runtime.block_on(async { + let policy = policy(); + let budget = policy.body_budget(); + let cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let q = BudgetedBytes::allocation_cost(0).unwrap(); + let (mut first, first_last, first_headers) = message(&policy); + let (mut second, second_last, second_headers) = message(&policy); + let first_pointer = first.body.as_ref().unwrap().wire().as_ptr(); + let second_pointer = second.body.as_ref().unwrap().wire().as_ptr(); + let url = first.original.url.clone(); + let cancellation = CancellationToken::new(); + let deadline = Instant::now() + Duration::from_secs(1); + let mut running = Box::pin(run_until( + &policy, + &url, + &mut first, + &cancellation, + deadline, + )); + suspend_with_paid_output(running.as_mut(), budget, 3 * cost).await; + let mut waiting = Box::pin(run_until( + &policy, + &url, + &mut second, + &cancellation, + deadline, + )); + let queued = poll_fn(|cx| Poll::Ready(waiting.as_mut().poll(cx))).await; + assert!(matches!(queued, Poll::Pending)); + assert_eq!( + budget.used(), + 3 * cost + q, + "second actual Message cannot acquire the same lane/output" + ); + drop(waiting); + assert_eq!(budget.used(), 3 * cost); + unchanged(&second, &second_headers, second_pointer); + drop(running); + assert_eq!( + budget.used(), + 2 * cost, + "dropped future refunds its real output owner" + ); + unchanged(&first, &first_headers, first_pointer); + // A new actual invocation must be healthy: the dropped future released + // the real permit, rather than only decreasing an accounting number. + assert!(matches!( + run_until(&policy, &url, &mut second, &cancellation, deadline) + .await + .unwrap(), + Outcome::Forward + )); + assert_eq!(second.request.url.as_str(), "https://a.example/path"); + assert!( + second + .body + .as_ref() + .unwrap() + .logical() + .unwrap() + .iter() + .all(|byte| *byte == b'b') + ); + drop((first, second)); + assert_eq!( + budget.used(), + 2 * cost, + "both real original last slices still retain credit" + ); + assert_eq!(first_last.as_ref(), b"a"); + assert_eq!(second_last.as_ref(), b"a"); + drop(first_last); + assert_eq!(budget.used(), cost); + drop(second_last); + assert_eq!(budget.used(), 0); + }); + drop(runtime); // Actual normal Runtime drop joins its workers. +} + +#[test] +fn direct_plan_yield_cancel_or_original_phase_deadline_rolls_back_before_execution() { + let runtime = runtime(); + runtime.block_on(async { + let policy = policy(); + for cancel in [true, false] { + let budget = policy.body_budget(); + let cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let (mut value, last, headers) = message(&policy); + let pointer = value.body.as_ref().unwrap().wire().as_ptr(); + let url = value.original.url.clone(); + let token = CancellationToken::new(); + let phase_deadline = Instant::now() + + if cancel { + Duration::from_secs(1) + } else { + Duration::from_millis(10) + }; + let mut running = + Box::pin(run_until(&policy, &url, &mut value, &token, phase_deadline)); + suspend_with_paid_output(running.as_mut(), budget, 2 * cost).await; + if cancel { + token.cancel(); + assert_eq!( + budget.used(), + 2 * cost, + "cancellation signal is not owner completion" + ); + } else { + // Original phase clock, not a replacement deadline after yield. + tokio::time::sleep_until(tokio::time::Instant::from_std(phase_deadline)).await; + } + let result = running.as_mut().await; + drop(running); + let expected = if cancel { + io::ErrorKind::Interrupted + } else { + io::ErrorKind::TimedOut + }; + assert!(matches!(result, Err(error) if error.kind() == expected)); + assert_eq!(budget.used(), cost); + unchanged(&value, &headers, pointer); + drop(value); + assert_eq!(budget.used(), cost); + assert_eq!(last.as_ref(), b"a"); + drop(last); + assert_eq!(budget.used(), 0); + } + }); + drop(runtime); +} + +#[test] +fn direct_plan_yield_preserves_invocation_expiry_while_original_phase_is_live() { + let runtime = runtime(); + runtime.block_on(async { + let policy = policy(); + let budget = policy.body_budget(); + let cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let (mut value, last, headers) = message(&policy); + let pointer = value.body.as_ref().unwrap().wire().as_ptr(); + let url = value.original.url.clone(); + let token = CancellationToken::new(); + let phase_deadline = Instant::now() + Duration::from_secs(1); + let mut running = Box::pin(run_until(&policy, &url, &mut value, &token, phase_deadline)); + suspend_with_paid_output(running.as_mut(), budget, 2 * cost).await; + // The original invocation started before this real suspension. Waiting + // 110ms here exceeds its 100ms bound without expiring the 1s phase. + tokio::time::sleep(Duration::from_millis(110)).await; + assert!( + Instant::now() < phase_deadline, + "setup no longer isolates invocation expiry" + ); + assert_eq!(budget.used(), 2 * cost, "sleeping is not owner completion"); + let result = running.as_mut().await; + drop(running); + // Invocation timeout is recoverable; phase timeout would be Err. + assert!(matches!(result, Ok(Outcome::Forward))); + unchanged(&value, &headers, pointer); + assert_eq!(budget.used(), cost); + drop(value); + assert_eq!(budget.used(), cost); + assert_eq!(last.as_ref(), b"a"); + drop(last); + assert_eq!(budget.used(), 0); + }); + drop(runtime); +} diff --git a/src/http_processing/scripts/apple.rs b/src/http_processing/scripts/apple.rs new file mode 100644 index 0000000..c45862f --- /dev/null +++ b/src/http_processing/scripts/apple.rs @@ -0,0 +1,1545 @@ +//! System JavaScriptCore C API. No private execution-time or heap APIs. +use super::CompiledSource; +use crate::http_processing::{ + body_budget::{API_TEXT_VIEW, BridgePlan, Budget, BudgetedBytes, Reservation}, + diagnostics::{self, Counter}, +}; +use std::{ + cell::RefCell, + ffi::{CString, c_char, c_void}, + io, ptr, slice, + time::Instant, +}; +use tokio_util::sync::CancellationToken; + +type Context = *const c_void; +type Object = *mut c_void; +type Value = *const c_void; +type JsString = *mut c_void; +type Callback = + unsafe extern "C" fn(Context, Object, Object, usize, *const Value, *mut Value) -> Value; + +#[link(name = "JavaScriptCore", kind = "framework")] +unsafe extern "C" { + fn JSGlobalContextCreate(class: *const c_void) -> Context; + fn JSGlobalContextRelease(ctx: Context); + fn JSContextGetGlobalObject(ctx: Context) -> Object; + fn JSStringCreateWithUTF8CString(text: *const c_char) -> JsString; + fn JSStringCreateWithCharacters(text: *const u16, length: usize) -> JsString; + fn JSStringRelease(string: JsString); + fn JSStringGetLength(string: JsString) -> usize; + fn JSStringGetCharactersPtr(string: JsString) -> *const u16; + fn JSStringGetUTF8CString(string: JsString, buffer: *mut c_char, size: usize) -> usize; + fn JSValueMakeUndefined(ctx: Context) -> Value; + fn JSValueMakeBoolean(ctx: Context, value: bool) -> Value; + fn JSValueMakeString(ctx: Context, value: JsString) -> Value; + fn JSValueMakeFromJSONString(ctx: Context, value: JsString) -> Value; + fn JSValueCreateJSONString( + ctx: Context, + value: Value, + indent: u32, + exception: *mut Value, + ) -> JsString; + fn JSValueToStringCopy(ctx: Context, value: Value, exception: *mut Value) -> JsString; + fn JSValueToObject(ctx: Context, value: Value, exception: *mut Value) -> Object; + fn JSValueIsString(ctx: Context, value: Value) -> bool; + fn JSValueIsNumber(ctx: Context, value: Value) -> bool; + fn JSValueToNumber(ctx: Context, value: Value, exception: *mut Value) -> f64; + fn JSValueIsUndefined(ctx: Context, value: Value) -> bool; + fn JSValueProtect(ctx: Context, value: Value); + fn JSValueUnprotect(ctx: Context, value: Value); + fn JSObjectMakeFunctionWithCallback( + ctx: Context, + name: JsString, + callback: Option, + ) -> Object; + fn JSObjectGetProperty( + ctx: Context, + object: Object, + name: JsString, + exception: *mut Value, + ) -> Value; + fn JSObjectSetProperty( + ctx: Context, + object: Object, + name: JsString, + value: Value, + attributes: u32, + exception: *mut Value, + ); + fn JSObjectDeleteProperty( + ctx: Context, + object: Object, + name: JsString, + exception: *mut Value, + ) -> bool; + fn JSObjectCallAsFunction( + ctx: Context, + object: Object, + receiver: Object, + count: usize, + args: *const Value, + exception: *mut Value, + ) -> Value; + fn JSEvaluateScript( + ctx: Context, + source: JsString, + this: Object, + url: JsString, + line: i32, + exception: *mut Value, + ) -> Value; + fn JSObjectMakeTypedArray( + ctx: Context, + kind: u32, + length: usize, + exception: *mut Value, + ) -> Object; + fn JSObjectGetTypedArrayByteLength( + ctx: Context, + object: Object, + exception: *mut Value, + ) -> usize; + fn JSObjectGetTypedArrayByteOffset( + ctx: Context, + object: Object, + exception: *mut Value, + ) -> usize; + fn JSObjectGetTypedArrayBuffer(ctx: Context, object: Object, exception: *mut Value) -> Object; + fn JSObjectGetArrayBufferByteLength( + ctx: Context, + object: Object, + exception: *mut Value, + ) -> usize; + fn JSObjectGetArrayBufferBytesPtr( + ctx: Context, + object: Object, + exception: *mut Value, + ) -> *mut c_void; + fn JSValueGetTypedArrayType(ctx: Context, value: Value, exception: *mut Value) -> u32; +} + +struct StringRef(JsString); +impl StringRef { + fn new(value: &str) -> io::Result { + let bytes = CString::new(value).map_err(|_| invalid("embedded NUL in control string"))?; + let value = unsafe { JSStringCreateWithUTF8CString(bytes.as_ptr()) }; + if value.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + Ok(Self(value)) + } + fn text(value: &str, allow_utf8: bool) -> io::Result { + #[cfg(test)] + if FORCE_UTF16_INPUT_FOR_TEST.with(std::cell::Cell::get) { + return Self::text_utf16(value); + } + if allow_utf8 && !value.is_empty() && value.bytes().all(|byte| byte.is_ascii() && byte != 0) + { + // Keep the original fallible, exact-capacity body allocation rule. + // Admission separately pays retained API2I and Vec bookkeeping; + // this branch requires view >= 3I+1 for CString+possible decoder. + #[cfg(test)] + bridge_event(BridgeEvent::InputUtf8Start); + let length = value + .len() + .checked_add(1) + .ok_or(io::ErrorKind::OutOfMemory)?; + let mut utf8 = Vec::new(); + utf8.try_reserve_exact(length) + .map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?; + if utf8.capacity() > length { + return Err(io::ErrorKind::OutOfMemory.into()); + } + utf8.extend_from_slice(value.as_bytes()); + utf8.push(0); + let value = unsafe { JSStringCreateWithUTF8CString(utf8.as_ptr().cast()) }; + if value.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + return Ok(Self(value)); + } + Self::text_utf16(value) + } + fn text_utf16(value: &str) -> io::Result { + #[cfg(test)] + bridge_event(BridgeEvent::InputUtf16Start); + let length = value.encode_utf16().count(); + let mut utf16 = Vec::new(); + utf16 + .try_reserve_exact(length) + .map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?; + if utf16.capacity() > length { + return Err(io::ErrorKind::OutOfMemory.into()); + } + utf16.extend(value.encode_utf16()); + let value = unsafe { JSStringCreateWithCharacters(utf16.as_ptr(), utf16.len()) }; + if value.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + Ok(Self(value)) + } + fn units(&self) -> &[u16] { + let length = unsafe { JSStringGetLength(self.0) }; + if length == 0 { + return &[]; + } + unsafe { slice::from_raw_parts(JSStringGetCharactersPtr(self.0), length) } + } + fn to_string_checked(&self, limit: usize) -> io::Result { + let length = utf8_length(self.units(), limit)?; + let mut result = String::new(); + result + .try_reserve_exact(length) + .map_err(|_| io::Error::from(io::ErrorKind::OutOfMemory))?; + for ch in char::decode_utf16(self.units().iter().copied()) { + result.push(ch.map_err(|_| invalid("invalid UTF-16"))?); + } + Ok(result) + } +} +impl Drop for StringRef { + fn drop(&mut self) { + if !self.0.is_null() { + unsafe { JSStringRelease(self.0) }; + } + } +} +/// Initialize trusted platform/prelude state on a joined owner thread. No user +/// source is evaluated. No prelude, callback, execution TLS, body view or VM +/// survives this function; the process only retains the joined Ready marker. +pub(super) fn initialize_platform() -> io::Result<()> { + struct PlatformContext(Context); + impl Drop for PlatformContext { + fn drop(&mut self) { + unsafe { JSGlobalContextRelease(self.0) }; + diagnostics::increment(Counter::PlatformWarmupContextReleased); + } + } + let raw = unsafe { JSGlobalContextCreate(ptr::null()) }; + if raw.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + diagnostics::increment(Counter::PlatformWarmupContextCreated); + let context = PlatformContext(raw); + let global = unsafe { JSContextGetGlobalObject(context.0) }; + if global.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + // These callbacks exist only in this disposable, trusted context. They do + // not inspect args, touch EXECUTION, acquire body credit or count business + // ticks. Known small constants bound every prelude path exercised below. + for name in ["__voleTick", "__voleIsASCII", "__voleReplaceASCIIAll"] { + let key = StringRef::new(name)?; + let function = unsafe { + JSObjectMakeFunctionWithCallback(context.0, key.0, Some(platform_warmup_noop)) + }; + if function.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + set(context.0, global, name, function.cast_const())?; + } + if script(context.0, include_str!("runtime.js"))?.is_null() + || script(context.0, PLATFORM_TRUSTED_WARMUP)?.is_null() + { + return Err(io::ErrorKind::OutOfMemory.into()); + } + drop(context); + Ok(()) +} + +unsafe extern "C" fn platform_warmup_noop( + ctx: Context, + _: Object, + _: Object, + _: usize, + _: *const Value, + _: *mut Value, +) -> Value { + unsafe { JSValueMakeUndefined(ctx) } +} + +// Fixed trusted code, not generated from configuration or passed user source. +// No source enumeration, callback arguments, network, metadata/body input or +// rewrite() invocation is available here. Each helper receives only the small +// constants below, and both synthetic results die with PlatformContext. +const PLATFORM_TRUSTED_WARMUP: &str = r#" +(function () { + const input = {body: {data: "warmup:text:text"}}; + const text = __voleGet(__voleGet(input, "body"), "data"); + const changed = __voleCall(text, "replaceAll", [":", "_"]); + if (changed !== "warmup_text_text") throw new Error("trusted warmup mismatch"); + __voleFinish(__voleValue({ + type: "modify", + headers: __voleValue([__voleValue({ + op: "set", name: "x-vole-warmup", values: __voleValue(["ready"]) + })]), + body: __voleValue({kind: "text", data: changed}) + })); + __voleExportTextUnits(changed); + const bytes = __voleCall(Uint8Array, "from", [[0, 1, 127, 255]]); + __voleFinish(__voleValue({ + type: "modify", body: __voleValue({kind: "bytes", data: bytes}) + })); +})(); +"#; + +struct ContextRef(Context); +impl Drop for ContextRef { + fn drop(&mut self) { + #[cfg(feature = "http-diagnostics")] + execution_phase("context-release"); + #[cfg(feature = "http-diagnostics")] + let started = Instant::now(); + unsafe { JSGlobalContextRelease(self.0) }; + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + VALIDATION_TRACE.with(|slot| { + if let Some(trace) = slot.borrow_mut().as_mut() { + trace.context_released = true; + } + }); + #[cfg(test)] + CONTEXT_RELEASE_FOR_TEST.with(|slot| { + if let Some(observer) = slot.borrow_mut().take() { + observer(); + } + }); + #[cfg(feature = "http-diagnostics")] + super::super::diagnostics::timing( + super::super::diagnostics::Timing::ContextRelease, + started.elapsed().as_micros(), + ); + if !self.0.is_null() { + super::super::diagnostics::context_released(); + } + } +} +struct Rooted { + ctx: Context, + value: Value, +} +impl Rooted { + fn new(ctx: Context, value: Value) -> io::Result { + if value.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + unsafe { JSValueProtect(ctx, value) }; + Ok(Self { ctx, value }) + } +} +impl Drop for Rooted { + fn drop(&mut self) { + unsafe { JSValueUnprotect(self.ctx, self.value) }; + } +} + +struct Execution { + deadline: Instant, + cancellation: CancellationToken, + ascii_view_budget: Budget, + prepaid_view_capacity: usize, + // Final body egress3O can never be consumed by retained outputs. + prepaid_export_floor: usize, + // Disjoint portions of that slot retained by native API output strings. + // Never includes the separately paid 2I input backing or Rust output Vec. + retained_borrowed: usize, + // Extra native-output backing outside borrowed prepaid slices. The + // complete prepaid bridge owner and this cumulative extra owner both + // outlive the actual JSGlobalContextRelease, even after JS overwrites it. + literal_output_backing: Option, + ticks: usize, + exception: Value, + started: Instant, + entry_remaining_us: u128, + phase: &'static str, + phase_start_us: u128, + stage_us: [u128; 6], + #[cfg(feature = "http-diagnostics")] + stages_seen: u8, + first_stop: Option, +} +#[derive(Clone, Copy)] +struct StopEvidence { + cause: &'static str, + phase: &'static str, + ticks: usize, + elapsed_us: u128, + phase_elapsed_us: u128, +} +thread_local! { static EXECUTION: RefCell> = const { RefCell::new(None) }; } +#[cfg(test)] +thread_local! { + static LAST_TICKS_FOR_TEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} +#[cfg(test)] +thread_local! { + static FORCE_UTF16_INPUT_FOR_TEST: std::cell::Cell = const { std::cell::Cell::new(false) }; +} +#[cfg(test)] +pub(super) struct InputConstructorControl(bool); +#[cfg(test)] +impl Drop for InputConstructorControl { + fn drop(&mut self) { + FORCE_UTF16_INPUT_FOR_TEST.with(|slot| slot.set(self.0)); + } +} +#[cfg(test)] +pub(super) fn force_utf16_input_for_test() -> InputConstructorControl { + // These differential tests deliberately execute on the test's current + // thread, where the same real adapter reads this test-only override. + assert_eq!( + tokio::runtime::Handle::current().runtime_flavor(), + tokio::runtime::RuntimeFlavor::CurrentThread + ); + InputConstructorControl(FORCE_UTF16_INPUT_FOR_TEST.with(|slot| slot.replace(true))) +} +#[cfg(test)] +pub(super) fn last_ticks_for_test() -> Option { + LAST_TICKS_FOR_TEST.with(std::cell::Cell::get) +} +#[cfg(test)] +thread_local! { + static FIRST_TICK_FOR_TEST: RefCell>> = const { RefCell::new(None) }; +} +#[cfg(test)] +pub(super) fn on_first_tick_for_test(hook: impl FnOnce() + 'static) { + FIRST_TICK_FOR_TEST.with(|slot| { + *slot.borrow_mut() = Some(Box::new(hook)); + }); +} +#[cfg(test)] +thread_local! { + static CONTEXT_RELEASE_FOR_TEST: RefCell>> = const { RefCell::new(None) }; +} +#[cfg(test)] +pub(super) fn on_context_release_for_test(observer: impl FnOnce() + 'static) { + CONTEXT_RELEASE_FOR_TEST.with(|slot| { + *slot.borrow_mut() = Some(Box::new(observer)); + }); +} +struct ExecutionGuard { + #[cfg(feature = "http-diagnostics")] + succeeded: bool, +} +impl Drop for ExecutionGuard { + fn drop(&mut self) { + EXECUTION.with(|s| { + #[cfg(feature = "http-diagnostics")] + if let Some(state) = s.borrow_mut().as_mut() { + let elapsed = state.started.elapsed().as_micros(); + let mut stages = state.stage_us; + if let Some(slot) = stage_slot(state.phase) { + stages[slot] = + stages[slot].saturating_add(elapsed.saturating_sub(state.phase_start_us)); + } + super::super::diagnostics::evaluation_finished( + stages, + state.stages_seen, + elapsed, + state.ticks, + self.succeeded, + ); + } + #[cfg(test)] + LAST_TICKS_FOR_TEST.with(|ticks| { + ticks.set(s.borrow().as_ref().map(|state| state.ticks)); + }); + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + VALIDATION_TRACE.with(|slot| { + if let (Some(trace), Some(state)) = + (slot.borrow_mut().as_mut(), s.borrow().as_ref()) + { + trace.ticks = Some(state.ticks); + } + }); + s.replace(None); + }); + } +} + +unsafe extern "C" fn tick( + ctx: Context, + _: Object, + _: Object, + _: usize, + _: *const Value, + exception: *mut Value, +) -> Value { + #[cfg(test)] + FIRST_TICK_FOR_TEST.with(|slot| { + let hook = slot.borrow_mut().take(); + if let Some(hook) = hook { + hook(); + } + }); + let error = EXECUTION.with(|cell| { + let mut state = cell.borrow_mut(); + let state = state.as_mut()?; + state.ticks += 1; + // Preserve the existing short-circuit order and one clock read on + // a healthy tick. Evidence and its clock read exist only on failure. + let cause = if state.cancellation.is_cancelled() { + Some("cancel") + } else if state.ticks > 100_000 { + Some("ticks") + } else if Instant::now() >= state.deadline { + Some("deadline") + } else { + None + }; + if let Some(cause) = cause { + if state.first_stop.is_none() { + let elapsed_us = state.started.elapsed().as_micros(); + state.first_stop = Some(StopEvidence { + cause, + phase: state.phase, + ticks: state.ticks, + elapsed_us, + phase_elapsed_us: elapsed_us.saturating_sub(state.phase_start_us), + }); + } + Some(state.exception) + } else { + None + } + }); + if let Some(error) = error { + // The exception is allocated and rooted before running user code, so + // cancellation itself cannot fail because a new string needs memory. + unsafe { *exception = error }; + } + unsafe { JSValueMakeUndefined(ctx) } +} + +// Private trusted-prelude ABI: (primitive string, that same string's length). +// The frontend cannot name this helper and strings cannot change between the +// two argument evaluations. Return undefined to retain the original regex +// predicate whenever additional bridge payload cannot be admitted or viewed. +unsafe extern "C" fn is_ascii( + ctx: Context, + _: Object, + _: Object, + count: usize, + args: *const Value, + _: *mut Value, +) -> Value { + let unavailable = || unsafe { JSValueMakeUndefined(ctx) }; + if count != 2 || args.is_null() { + return unavailable(); + } + let value = unsafe { *args }; + let declared_length = unsafe { *args.add(1) }; + if value.is_null() + || declared_length.is_null() + || !unsafe { JSValueIsString(ctx, value) } + || !unsafe { JSValueIsNumber(ctx, declared_length) } + { + return unavailable(); + } + let mut conversion_exception = ptr::null(); + let declared_length = + unsafe { JSValueToNumber(ctx, declared_length, &mut conversion_exception) }; + if !conversion_exception.is_null() + || !declared_length.is_finite() + || declared_length < 0.0 + || declared_length.fract() != 0.0 + || declared_length > super::super::body_budget::MAX_BODY as f64 + { + return unavailable(); + } + let length = declared_length as usize; + let Some(payload) = length.checked_mul(3) else { + return unavailable(); + }; + let reservation = EXECUTION.with(|cell| { + let state = cell.borrow(); + let state = state.as_ref()?; + use super::super::diagnostics::{Counter, increment}; + increment(Counter::AsciiViewRequested); + let extra = payload.saturating_sub(state.available_view()); + if extra == 0 { + increment(Counter::AsciiViewAdmitted); + return Some(None); + } + match state.ascii_view_budget.reserve(extra) { + Some(reservation) => { + increment(Counter::AsciiViewAdmitted); + Some(Some(reservation)) + } + None => { + increment(Counter::AsciiViewBudgetFallback); + None + } + } + }); + // Any extra guard is declared before StringRef: release the API copy + // and expansion first. The prepaid slot remains held by the caller and + // is reused sequentially by export, never by retained input backing. + let Some(_reservation) = reservation else { + return unavailable(); + }; + #[cfg(test)] + let _owner_observer = AsciiOwnerObserver; + #[cfg(test)] + bridge_event(BridgeEvent::AsciiCopyStart); + let text = StringRef(unsafe { JSValueToStringCopy(ctx, value, &mut conversion_exception) }); + if !conversion_exception.is_null() || text.0.is_null() { + return unavailable(); + } + if unsafe { JSStringGetLength(text.0) } != length { + return unavailable(); + } + if length == 0 { + return unsafe { JSValueMakeBoolean(ctx, true) }; + } + let units = unsafe { JSStringGetCharactersPtr(text.0) }; + if units.is_null() { + return unavailable(); + } + // Public JSC can copy N bytes and expand 2N more for an 8-bit source. + // The separate view slot or extra reservation covers character payload, + // not VM heap/metadata. The retained 2I input allocation is never reused. + let ascii = unsafe { slice::from_raw_parts(units, length) } + .iter() + .all(|unit| *unit <= 0x7f); + unsafe { JSValueMakeBoolean(ctx, ascii) } +} + +// Private trusted-prelude ABI: (primitive string, that string's length, +// ASCII search code unit, ASCII replacement code unit). No value conversion +// can invoke user code. Return undefined to keep the original JS operation. +unsafe extern "C" fn replace_ascii_literal_all( + ctx: Context, + _: Object, + _: Object, + count: usize, + args: *const Value, + _: *mut Value, +) -> Value { + let unavailable = || unsafe { JSValueMakeUndefined(ctx) }; + if count != 4 || args.is_null() { + return unavailable(); + } + let value = unsafe { *args }; + if value.is_null() || !unsafe { JSValueIsString(ctx, value) } { + return unavailable(); + } + let mut numbers = [0usize; 3]; + for (index, maximum) in [super::super::body_budget::MAX_BODY, 127, 127] + .into_iter() + .enumerate() + { + let argument = unsafe { *args.add(index + 1) }; + if argument.is_null() || !unsafe { JSValueIsNumber(ctx, argument) } { + return unavailable(); + } + let mut exception = ptr::null(); + let number = unsafe { JSValueToNumber(ctx, argument, &mut exception) }; + if !exception.is_null() + || !number.is_finite() + || number < 0.0 + || number.fract() != 0.0 + || number > maximum as f64 + { + return unavailable(); + } + numbers[index] = number as usize; + } + let [length, search, replacement] = numbers; + if length < 4096 || replacement == usize::from(b'$') { + return unavailable(); + } + diagnostics::increment(Counter::LiteralReplaceRequested); + let Some(temporary_payload) = length + .checked_mul(5) + .and_then(|bytes| bytes.checked_add(std::mem::size_of::>())) + else { + return unavailable(); + }; + let Some(retained_payload) = length.checked_mul(2) else { + return unavailable(); + }; + let admission = EXECUTION.with(|cell| { + let state = cell.borrow(); + let state = state.as_ref()?; + // Retained and temporary slices must fit simultaneously. Reservation + // failures occur before any API copy. No primitive API here reenters JS. + let borrowed_retained = retained_payload.min(state.available_retained_view()); + let temporary_extra = + temporary_payload.saturating_sub(state.available_view() - borrowed_retained); + let retained_extra = retained_payload - borrowed_retained; + let temporary = if temporary_extra == 0 { + None + } else { + Some(state.ascii_view_budget.reserve(temporary_extra)?) + }; + let retained = if retained_extra == 0 { + None + } else { + Some(state.ascii_view_budget.reserve(retained_extra)?) + }; + Some((temporary, retained, borrowed_retained)) + }); + // Both guards precede every API copy and the host UTF-16 Vec. Any API + // owner and Vec are dropped before the temporary guard on every exit. + let Some((_temporary, retained, borrowed_retained)) = admission else { + diagnostics::increment(Counter::LiteralReplaceBudgetFallback); + return unavailable(); + }; + #[cfg(test)] + let _temporary_owner_observer = NativeOwnerObserver; + #[cfg(test)] + bridge_event(BridgeEvent::NativeCopyStart); + let mut conversion_exception = ptr::null(); + let text = StringRef(unsafe { JSValueToStringCopy(ctx, value, &mut conversion_exception) }); + if !conversion_exception.is_null() + || text.0.is_null() + || unsafe { JSStringGetLength(text.0) } != length + { + diagnostics::increment(Counter::LiteralReplaceApiFallback); + return unavailable(); + } + let units = unsafe { JSStringGetCharactersPtr(text.0) }; + if units.is_null() { + diagnostics::increment(Counter::LiteralReplaceApiFallback); + return unavailable(); + } + // The slice is used only while its StringRef owner remains in this scope. + // All input is checked before allocating or exposing a replacement value. + let units = unsafe { slice::from_raw_parts(units, length) }; + let mut matches = 0usize; + for unit in units { + if *unit > 0x7f { + diagnostics::increment(Counter::LiteralReplaceSemanticFallback); + return unavailable(); + } + matches += usize::from(usize::from(*unit) == search); + } + // Sparse/no-match input keeps JSC's very cheap native string intrinsic. + // This is an eligibility threshold, not a measured crossover claim. + if matches < length.div_ceil(16) { + diagnostics::increment(Counter::LiteralReplaceSemanticFallback); + return unavailable(); + } + let mut output_units = Vec::new(); + if output_units.try_reserve_exact(length).is_err() || output_units.capacity() != length { + diagnostics::increment(Counter::LiteralReplaceApiFallback); + return unavailable(); + } + output_units.extend(units.iter().map(|unit| { + if usize::from(*unit) == search { + replacement as u16 + } else { + *unit + } + })); + // The last units read has completed. End the 3N input API view before + // creating output API2N and any JSValueMakeString VM isolated copy2N. + // Peak is then max(3N+Vec2N, Vec2N+API2N+VM2N) <= T5N+R2N. + drop(text); + #[cfg(test)] + bridge_event(BridgeEvent::NativeInputOwnerDropped); + // Commit only at the actual output API allocation boundary. Earlier + // semantic/copy fallbacks refund this unused retained plan. From here on, + // even allocation failure keeps borrowed and extra payload until ctx drop. + let committed = EXECUTION.with(|cell| { + let mut state = cell.borrow_mut(); + let Some(state) = state.as_mut() else { + return false; + }; + if borrowed_retained > state.available_retained_view() { + return false; + } + if let Some(retained) = retained { + if let Some(previous) = state.literal_output_backing.as_mut() { + if previous.merge(retained).is_err() { + return false; + } + } else { + state.literal_output_backing = Some(retained); + } + } + state.retained_borrowed += borrowed_retained; + true + }); + if !committed { + diagnostics::increment(Counter::LiteralReplaceApiFallback); + return unavailable(); + } + #[cfg(test)] + bridge_event(BridgeEvent::NativeRetainedCommitted); + let output = StringRef(unsafe { + JSStringCreateWithCharacters(output_units.as_ptr(), output_units.len()) + }); + if output.0.is_null() { + // The conservative retained reservation still expires at context + // release, including this allocation-failure path. + diagnostics::increment(Counter::LiteralReplaceApiFallback); + return unavailable(); + } + let result = unsafe { JSValueMakeString(ctx, output.0) }; + if result.is_null() { + diagnostics::increment(Counter::LiteralReplaceApiFallback); + return unavailable(); + } + diagnostics::increment(Counter::LiteralReplaceAdmitted); + result +} + +// Successful evaluations emit no diagnostics. A check-based classification +// is kept distinct from the first native callback that requested a stop. +fn execution_error( + state: &Execution, + kind: io::ErrorKind, + origin: &'static str, + classification: &'static str, +) -> io::Error { + let elapsed_us = state.started.elapsed().as_micros(); + let first = state.first_stop.unwrap_or(StopEvidence { + cause: classification, + phase: state.phase, + ticks: state.ticks, + elapsed_us, + phase_elapsed_us: elapsed_us.saturating_sub(state.phase_start_us), + }); + let first_trigger = if state.first_stop.is_some() { + "callback" + } else { + origin + }; + let stages = state.stage_us.map(diagnostic_us); + io::Error::new( + kind, + format!( + "js f={first_trigger} c={} p={} t={} e={} pe={} o={origin} k={classification} a={} r={} stage_us={},{},{},{},{},{}", + first.cause, + first.phase, + first.ticks, + diagnostic_us(first.elapsed_us), + diagnostic_us(first.phase_elapsed_us), + diagnostic_us(elapsed_us), + diagnostic_us(state.entry_remaining_us), + stages[0], + stages[1], + stages[2], + stages[3], + stages[4], + stages[5], + ), + ) +} +// Presentation-only saturation keeps every diagnostic below the host's +// 256-byte UTF-8 message cap. Execution clocks and limits remain unchanged. +fn diagnostic_us(value: u128) -> u32 { + value.min(u128::from(u32::MAX)) as u32 +} +fn stage_slot(phase: &str) -> Option { + match phase { + "context" => Some(0), + "prelude" => Some(1), + "program" => Some(2), + "input" => Some(3), + "invoke" => Some(4), + "export" => Some(5), + _ => None, + } +} +fn execution_phase(phase: &'static str) { + EXECUTION.with(|cell| { + if let Some(state) = cell.borrow_mut().as_mut() { + // Reuse the phase transition's existing clock reading. The fixed + // array holds completed context/prelude/program/input/invoke/export. + let elapsed_us = state.started.elapsed().as_micros(); + let slot = stage_slot(state.phase); + if let Some(slot) = slot { + state.stage_us[slot] = state.stage_us[slot] + .saturating_add(elapsed_us.saturating_sub(state.phase_start_us)); + } + state.phase = phase; + state.phase_start_us = elapsed_us; + #[cfg(feature = "http-diagnostics")] + if let Some(slot) = stage_slot(phase) { + state.stages_seen |= 1 << slot; + } + } + }); +} +fn stopped(kind: io::ErrorKind, origin: &'static str, cause: &'static str) -> io::Error { + EXECUTION.with(|cell| { + let state = cell.borrow(); + state.as_ref().map_or_else( + || io::Error::from(kind), + |s| execution_error(s, kind, origin, cause), + ) + }) +} + +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} +fn utf8_length(units: &[u16], limit: usize) -> io::Result { + let mut length = 0usize; + for ch in char::decode_utf16(units.iter().copied()) { + length = length + .checked_add(ch.map_err(|_| invalid("invalid UTF-16"))?.len_utf8()) + .filter(|v| *v <= limit) + .ok_or_else(|| invalid("script result is too large"))?; + } + Ok(length) +} +fn check(exception: Value) -> io::Result<()> { + if exception.is_null() { + return Ok(()); + } + EXECUTION.with(|cell| { + let state = cell.borrow(); + let Some(state) = state.as_ref() else { + return Err(invalid("JavaScript evaluation failed")); + }; + if state.cancellation.is_cancelled() { + Err(execution_error( + state, + io::ErrorKind::Interrupted, + "exception-check", + "cancel", + )) + } else if state.ticks > 100_000 { + Err(execution_error( + state, + io::ErrorKind::TimedOut, + "exception-check", + "ticks", + )) + } else if Instant::now() >= state.deadline { + // This says when the exception was classified, not that the + // exception itself was necessarily thrown by the tick callback. + Err(execution_error( + state, + io::ErrorKind::TimedOut, + "exception-check", + "deadline", + )) + } else { + Err(invalid("JavaScript evaluation failed")) + } + }) +} +fn property(ctx: Context, object: Object, name: &str) -> io::Result { + let key = StringRef::new(name)?; + let mut exception = ptr::null(); + let value = unsafe { JSObjectGetProperty(ctx, object, key.0, &mut exception) }; + check(exception)?; + Ok(value) +} +fn object(ctx: Context, value: Value) -> io::Result { + let mut exception = ptr::null(); + let value = unsafe { JSValueToObject(ctx, value, &mut exception) }; + check(exception)?; + if value.is_null() { + return Err(invalid("object required")); + } + Ok(value) +} +fn set(ctx: Context, object: Object, name: &str, value: Value) -> io::Result<()> { + let _value = Rooted::new(ctx, value)?; + let key = StringRef::new(name)?; + let mut exception = ptr::null(); + unsafe { JSObjectSetProperty(ctx, object, key.0, value, 0, &mut exception) }; + check(exception) +} +fn script(ctx: Context, source: &str) -> io::Result { + let source = StringRef::new(source)?; + let mut exception = ptr::null(); + let result = unsafe { + JSEvaluateScript( + ctx, + source.0, + ptr::null_mut(), + ptr::null_mut(), + 1, + &mut exception, + ) + }; + check(exception)?; + Ok(result) +} +fn call(ctx: Context, global: Object, name: &str, input: Value) -> io::Result { + let _input = Rooted::new(ctx, input)?; + let function = object(ctx, property(ctx, global, name)?)?; + let mut exception = ptr::null(); + let result = unsafe { + JSObjectCallAsFunction(ctx, function, ptr::null_mut(), 1, &input, &mut exception) + }; + check(exception)?; + Rooted::new(ctx, result) +} + +pub(super) fn evaluate( + program: &CompiledSource, + metadata: &serde_json::Value, + input: Option<&[u8]>, + output: &mut BudgetedBytes, + bridge_workspace: Option<&Reservation>, + cancellation: &CancellationToken, + deadline: Instant, +) -> io::Result { + if cancellation.is_cancelled() { + return Err(io::Error::new( + io::ErrorKind::Interrupted, + "js f=entry-check c=cancel p=context t=0 e=0 pe=0 o=entry-check k=cancel a=0 r=0 stage_us=0,0,0,0,0,0", + )); + } + // This guard is declared before the context and therefore remains held + // through JSGlobalContextRelease. Direct adapter tests use the same ledger + // as production CallBuffers; they cannot omit bridge admission. + let output_bound = program.maximum_output_bytes(input.map_or(0, <[u8]>::len)); + let plan = input + .map(|bytes| { + BridgePlan::new( + bytes.len(), + metadata["body"]["kind"] == "text", + output_bound, + ) + .ok_or_else(|| invalid("invalid bridge input")) + }) + .transpose()?; + let required = plan.and_then(BridgePlan::cost); + let local_bridge = if let Some(prepaid) = bridge_workspace { + if !prepaid.covers(output, required.unwrap_or(0)) { + diagnostics::increment(Counter::BridgeGuardInvalid); + return Err(invalid("invalid bridge reservation")); + } + None + } else if let Some(required) = required { + Some(output.reserve_temporary(required).ok_or_else(|| { + diagnostics::increment(Counter::BridgeInputRejected); + io::Error::new( + io::ErrorKind::OutOfMemory, + "HTTP script bridge workspace exceeded", + ) + })?) + } else { + None + }; + // This owner remains declared before ExecutionGuard and ContextRef. Its + // complete slot (including borrowed retained slices) outlives actual ctx. + let _bridge_workspace = bridge_workspace.or(local_bridge.as_ref()); + let started = Instant::now(); + EXECUTION.with(|s| { + s.replace(Some(Execution { + deadline, + cancellation: cancellation.clone(), + ascii_view_budget: output.budget().clone(), + prepaid_view_capacity: plan.map_or(0, |plan| plan.view_capacity), + prepaid_export_floor: plan.map_or(0, |_| 3 * output_bound), + retained_borrowed: 0, + literal_output_backing: None, + ticks: 0, + exception: ptr::null(), + started, + entry_remaining_us: deadline.saturating_duration_since(started).as_micros(), + phase: "context", + phase_start_us: 0, + stage_us: [0; 6], + #[cfg(feature = "http-diagnostics")] + stages_seen: 1, + first_stop: None, + })); + }); + #[cfg(feature = "http-diagnostics")] + let mut _execution = ExecutionGuard { succeeded: false }; + #[cfg(not(feature = "http-diagnostics"))] + let _execution = ExecutionGuard {}; + let ctx = ContextRef(unsafe { JSGlobalContextCreate(ptr::null()) }); + if ctx.0.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + super::super::diagnostics::context_created(); + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + let _validation_context = ValidationContextProbe(ctx.0); + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + VALIDATION_TRACE.with(|slot| { + if let Some(trace) = slot.borrow_mut().as_mut() { + trace.context_created = true; + } + }); + let failure = StringRef::new("script execution cancelled or budget exceeded")?; + let failure = Rooted::new(ctx.0, unsafe { JSValueMakeString(ctx.0, failure.0) })?; + EXECUTION.with(|s| { + if let Some(state) = s.borrow_mut().as_mut() { + state.exception = failure.value; + } + }); + let global = unsafe { JSContextGetGlobalObject(ctx.0) }; + let name = StringRef::new("__voleTick")?; + let function = unsafe { JSObjectMakeFunctionWithCallback(ctx.0, name.0, Some(tick)) }; + set(ctx.0, global, "__voleTick", function.cast_const())?; + let name = StringRef::new("__voleIsASCII")?; + let function = unsafe { JSObjectMakeFunctionWithCallback(ctx.0, name.0, Some(is_ascii)) }; + if function.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + set(ctx.0, global, "__voleIsASCII", function.cast_const())?; + let name = StringRef::new("__voleReplaceASCIIAll")?; + let function = + unsafe { JSObjectMakeFunctionWithCallback(ctx.0, name.0, Some(replace_ascii_literal_all)) }; + if function.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + set( + ctx.0, + global, + "__voleReplaceASCIIAll", + function.cast_const(), + )?; + execution_phase("prelude"); + script(ctx.0, include_str!("runtime.js"))?; + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + VALIDATION_TRACE.with(|slot| { + if let Some(trace) = slot.borrow_mut().as_mut() { + trace.prelude_loaded = true; + } + }); + execution_phase("program"); + script(ctx.0, &program.code)?; + execution_phase("input"); + let json = serde_json::to_string(metadata).map_err(|_| invalid("invalid script metadata"))?; + if json.len() > 1024 * 1024 { + return Err(invalid("script metadata limit")); + } + let json = StringRef::new(&json)?; + let input_value = unsafe { JSValueMakeFromJSONString(ctx.0, json.0) }; + if input_value.is_null() { + return Err(invalid("invalid script input")); + } + let input_root = Rooted::new(ctx.0, input_value)?; + let input_object = object(ctx.0, input_value)?; + if let Some(input) = input { + let body = object(ctx.0, property(ctx.0, input_object, "body")?)?; + let value = if metadata["body"]["kind"] == "text" { + let text = std::str::from_utf8(input).map_err(|_| invalid("body is not UTF-8"))?; + let plan = plan.ok_or_else(|| invalid("missing input bridge plan"))?; + // UTF8 worst-case extra is CString(I+1)+decoder Vec(2I). + // MAX uses UTF16 rather than borrowing the separately paid input2I. + let text = StringRef::text(text, plan.allows_utf8_input(input.len()))?; + unsafe { JSValueMakeString(ctx.0, text.0) } + } else { + let mut exception = ptr::null(); + // JSTypedArrayType Uint8Array = 3 in the public SDK enum. + let array = unsafe { JSObjectMakeTypedArray(ctx.0, 3, input.len(), &mut exception) }; + check(exception)?; + if array.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + let array_root = Rooted::new(ctx.0, array.cast_const())?; + let buffer = unsafe { JSObjectGetTypedArrayBuffer(ctx.0, array, &mut exception) }; + check(exception)?; + let data = unsafe { JSObjectGetArrayBufferBytesPtr(ctx.0, buffer, &mut exception) }; + check(exception)?; + if !input.is_empty() { + if data.is_null() { + return Err(invalid("invalid typed array allocation")); + } + unsafe { ptr::copy_nonoverlapping(input.as_ptr(), data.cast::(), input.len()) }; + } + set(ctx.0, body, "data", array.cast_const())?; + drop(array_root); + array.cast_const() + }; + set(ctx.0, body, "data", value)?; + } + execution_phase("invoke"); + let rewritten = call(ctx.0, global, "rewrite", input_value)?; + let result_root = call(ctx.0, global, "__voleFinish", rewritten.value)?; + execution_phase("export"); + drop(rewritten); + drop(input_root); + let result = result_root.value; + let record = object(ctx.0, result)?; + if let Some(kind) = output_kind(ctx.0, record)? { + let body = object(ctx.0, property(ctx.0, record, "body")?)?; + let data = property(ctx.0, body, "data")?; + export_body(ctx.0, kind.as_str(), data, output, output_bound)?; + let key = StringRef::new("data")?; + let mut exception = ptr::null(); + if !unsafe { JSObjectDeleteProperty(ctx.0, body, key.0, &mut exception) } { + return Err(invalid("body data is not exportable")); + } + check(exception)?; + } + let mut exception = ptr::null(); + let encoded = StringRef(unsafe { JSValueCreateJSONString(ctx.0, result, 0, &mut exception) }); + check(exception)?; + if encoded.0.is_null() { + return Err(invalid("invalid result encoding")); + } + let encoded = encoded.to_string_checked(256 * 1024)?; + execution_phase("final-check"); + if cancellation.is_cancelled() { + return Err(stopped(io::ErrorKind::Interrupted, "final-check", "cancel")); + } + if Instant::now() >= deadline { + return Err(stopped(io::ErrorKind::TimedOut, "final-check", "deadline")); + } + #[cfg(feature = "http-diagnostics")] + let parse_started = Instant::now(); + let result = serde_json::from_str(&encoded).map_err(|_| invalid("invalid result encoding")); + #[cfg(feature = "http-diagnostics")] + { + super::super::diagnostics::timing( + super::super::diagnostics::Timing::FinalParse, + parse_started.elapsed().as_micros(), + ); + _execution.succeeded = result.is_ok(); + } + result +} + +fn output_kind(ctx: Context, record: Object) -> io::Result> { + let value = property(ctx, record, "body")?; + if unsafe { JSValueIsUndefined(ctx, value) } { + return Ok(None); + } + let mut exception = ptr::null(); + let body = object(ctx, value)?; + let kind = property(ctx, body, "kind")?; + if !unsafe { JSValueIsString(ctx, kind) } { + return Err(invalid("invalid body kind")); + } + let kind = StringRef(unsafe { JSValueToStringCopy(ctx, kind, &mut exception) }); + check(exception)?; + if kind.0.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + let kind = kind.to_string_checked(16)?; + if kind != "text" && kind != "bytes" { + return Err(invalid("invalid body kind")); + } + Ok(Some(kind)) +} + +impl Execution { + fn available_view(&self) -> usize { + self.prepaid_view_capacity - self.retained_borrowed + } + fn available_retained_view(&self) -> usize { + self.available_view() + .saturating_sub(self.prepaid_export_floor) + } +} +// Primitive-string APIs do not call user code; no borrowed temporary view can +// overlap another callback. Retained slices are deducted permanently below. +fn reserve_view(payload: usize) -> Option> { + EXECUTION.with(|cell| { + let state = cell.borrow(); + let state = state.as_ref()?; + let extra = payload.saturating_sub(state.available_view()); + if extra == 0 { + Some(None) + } else { + state.ascii_view_budget.reserve(extra).map(Some) + } + }) +} +#[cfg(test)] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(super) enum BridgeEvent { + InputUtf8Start, + InputUtf16Start, + AsciiCopyStart, + AsciiOwnerDropped, + NativeCopyStart, + NativeInputOwnerDropped, + NativeRetainedCommitted, + NativeOwnersDropped, + ExportCopyStart, + ExportOwnerDropped, +} +#[cfg(test)] +thread_local! { static BRIDGE_EVENT: RefCell>> = const { RefCell::new(None) }; } +#[cfg(test)] +pub(super) fn observe_bridge_for_test(observer: impl FnMut(BridgeEvent) + 'static) { + BRIDGE_EVENT.with(|slot| *slot.borrow_mut() = Some(Box::new(observer))); +} +#[cfg(test)] +fn bridge_event(event: BridgeEvent) { + BRIDGE_EVENT.with(|slot| { + if let Some(observer) = slot.borrow_mut().as_mut() { + observer(event); + } + }); +} +#[cfg(test)] +pub(super) fn bridge_view_for_test() -> (usize, usize) { + EXECUTION.with(|cell| { + let state = cell.borrow(); + let state = state.as_ref().unwrap(); + (state.prepaid_view_capacity, state.retained_borrowed) + }) +} +#[cfg(test)] +struct AsciiOwnerObserver; +#[cfg(test)] +impl Drop for AsciiOwnerObserver { + fn drop(&mut self) { + bridge_event(BridgeEvent::AsciiOwnerDropped); + } +} +#[cfg(test)] +struct NativeOwnerObserver; +#[cfg(test)] +impl Drop for NativeOwnerObserver { + fn drop(&mut self) { + bridge_event(BridgeEvent::NativeOwnersDropped); + } +} +#[cfg(test)] +struct ExportOwnerObserver; +#[cfg(test)] +impl Drop for ExportOwnerObserver { + fn drop(&mut self) { + bridge_event(BridgeEvent::ExportOwnerDropped); + } +} +// Called only after trusted Finish. Native rechecks the primitive types; +// no String object/ToPrimitive conversion or API character copy precedes 3N. +fn export_text_units(ctx: Context, data: Value) -> io::Result { + if !unsafe { JSValueIsString(ctx, data) } { + return Err(invalid("text body required")); + } + let global = unsafe { JSContextGetGlobalObject(ctx) }; + let length = call(ctx, global, "__voleExportTextUnits", data)?; + if !unsafe { JSValueIsNumber(ctx, length.value) } { + return Err(invalid("invalid text unit count")); + } + let mut exception = ptr::null(); + let length = unsafe { JSValueToNumber(ctx, length.value, &mut exception) }; + check(exception)?; + if !length.is_finite() + || length < 0.0 + || length.fract() != 0.0 + || length > super::super::body_budget::MAX_BODY as f64 + { + return Err(invalid("invalid text unit count")); + } + Ok(length as usize) +} + +fn export_body( + ctx: Context, + kind: &str, + data: Value, + output: &mut BudgetedBytes, + output_bound: usize, +) -> io::Result<()> { + let mut exception = ptr::null(); + if kind == "text" { + let expected_units = export_text_units(ctx, data)?; + if expected_units > output_bound { + return Err(invalid("text exceeded proven output bound")); + } + if expected_units == 0 { + output.prepare_output(0)?; + return Ok(()); + } + let payload = expected_units + .checked_mul(3) + .filter(|n| *n <= API_TEXT_VIEW) + .ok_or_else(|| invalid("invalid text view payload"))?; + let _view_reservation = reserve_view(payload).ok_or_else(|| { + diagnostics::increment(Counter::BridgeExportRejected); + io::Error::new( + io::ErrorKind::OutOfMemory, + "HTTP script bridge workspace exceeded", + ) + })?; + #[cfg(test)] + let _owner_observer = ExportOwnerObserver; + #[cfg(test)] + bridge_event(BridgeEvent::ExportCopyStart); + // Declared after the permit: all exits release the API owner first. + let text = StringRef(unsafe { JSValueToStringCopy(ctx, data, &mut exception) }); + check(exception)?; + if text.0.is_null() { + return Err(io::ErrorKind::OutOfMemory.into()); + } + if unsafe { JSStringGetLength(text.0) } != expected_units { + return Err(invalid("text unit count changed before export")); + } + let units = text.units(); + let length = units.len(); + if length < super::super::body_budget::MAX_BODY + && output.as_ref().is_empty() + && output.remaining() > length + && units.iter().all(|unit| (1..=0x7f).contains(unit)) + { + // ASCII excludes every surrogate. Reserve no extra storage: the + // public API's trailing NUL fits in already admitted capacity. + // Embedded NUL and MAX_BODY stay on the strict original path. + output.write_initialized_output(length + 1, |buffer| { + let written = unsafe { + JSStringGetUTF8CString(text.0, buffer.as_mut_ptr().cast(), buffer.len()) + }; + if written != buffer.len() || buffer[length] != 0 { + return Err(invalid("incomplete ASCII body export")); + } + Ok(length) + })?; + return Ok(()); + } + let length = utf8_length(units, output_bound)?; + output.prepare_output(length)?; + for ch in char::decode_utf16(units.iter().copied()) { + let mut bytes = [0u8; 4]; + output.extend( + ch.map_err(|_| invalid("invalid body text"))? + .encode_utf8(&mut bytes) + .as_bytes(), + )?; + } + } else { + let kind = unsafe { JSValueGetTypedArrayType(ctx, data, &mut exception) }; + check(exception)?; + // The public SDK has Uint8Array=3 and ArrayBuffer=9. + if kind != 3 && kind != 9 { + return Err(invalid("Uint8Array or ArrayBuffer required")); + } + let array = object(ctx, data)?; + let (buffer, offset, length) = if kind == 3 { + let length = unsafe { JSObjectGetTypedArrayByteLength(ctx, array, &mut exception) }; + check(exception)?; + let offset = unsafe { JSObjectGetTypedArrayByteOffset(ctx, array, &mut exception) }; + check(exception)?; + let buffer = unsafe { JSObjectGetTypedArrayBuffer(ctx, array, &mut exception) }; + check(exception)?; + (buffer, offset, length) + } else { + let length = unsafe { JSObjectGetArrayBufferByteLength(ctx, array, &mut exception) }; + check(exception)?; + (array, 0, length) + }; + if length > output_bound { + return Err(invalid("bytes exceeded proven output bound")); + } + output.prepare_output(length)?; + let capacity = unsafe { JSObjectGetArrayBufferByteLength(ctx, buffer, &mut exception) }; + check(exception)?; + if offset.checked_add(length).is_none_or(|end| end > capacity) { + return Err(invalid("invalid bytes view")); + } + let bytes = unsafe { JSObjectGetArrayBufferBytesPtr(ctx, buffer, &mut exception) }; + check(exception)?; + if length != 0 { + if bytes.is_null() { + return Err(invalid("invalid bytes backing")); + } + output + .extend(unsafe { slice::from_raw_parts(bytes.cast::().add(offset), length) })?; + } + } + Ok(()) +} + +// Explicit tvOS diagnostic only. Normal evaluations never evaluate this probe. +#[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] +#[derive(Default, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub(super) struct ValidationTrace { + pub(super) ticks: Option, + pub(super) allocation_work: Option, + pub(super) context_created: bool, + pub(super) prelude_loaded: bool, + pub(super) context_released: bool, +} +#[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] +thread_local! { + static VALIDATION_TRACE: RefCell> = const { RefCell::new(None) }; +} +#[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] +struct ValidationContextProbe(Context); +#[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] +impl Drop for ValidationContextProbe { + fn drop(&mut self) { + if std::thread::panicking() { + return; + } + let enabled = VALIDATION_TRACE.with(|slot| { + slot.borrow() + .as_ref() + .is_some_and(|trace| trace.prelude_loaded) + }); + if !enabled { + return; + } + // __voleAllocated is a trusted global lexical, not a global-object + // property. No tick/Charge/user source runs; probe errors never replace + // the original result. Missing/failed reads remain explicitly None. + let work = (|| -> Option { + let value = script(self.0, "__voleAllocated").ok()?; + if !unsafe { JSValueIsNumber(self.0, value) } { + return None; + } + let mut exception = ptr::null(); + let number = unsafe { JSValueToNumber(self.0, value, &mut exception) }; + if !exception.is_null() + || !number.is_finite() + || number.fract() != 0.0 + || !(0.0..=2097152.0).contains(&number) + { + return None; + } + Some(number as usize) + })(); + VALIDATION_TRACE.with(|slot| { + if let Some(trace) = slot.borrow_mut().as_mut() { + trace.allocation_work = work; + } + }); + } +} +#[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] +pub(super) fn evaluate_for_validation( + program: &CompiledSource, + metadata: &serde_json::Value, + input: Option<&[u8]>, + output: &mut BudgetedBytes, + bridge: Option<&Reservation>, + cancellation: &CancellationToken, + deadline: Instant, +) -> (io::Result, ValidationTrace) { + struct Capture; + impl Drop for Capture { + fn drop(&mut self) { + VALIDATION_TRACE.with(|slot| { + slot.borrow_mut().take(); + }); + } + } + let occupied = VALIDATION_TRACE.with(|slot| { + let occupied = slot.borrow().is_some(); + if !occupied { + slot.replace(Some(ValidationTrace::default())); + } + occupied + }); + if occupied { + return ( + Err(io::ErrorKind::WouldBlock.into()), + ValidationTrace::default(), + ); + } + let _capture = Capture; + let result = evaluate( + program, + metadata, + input, + output, + bridge, + cancellation, + deadline, + ); + let trace = VALIDATION_TRACE + .with(|slot| slot.borrow_mut().take()) + .unwrap_or_default(); + (result, trace) +} diff --git a/src/http_processing/scripts/borrowed_input_owner_tests.rs b/src/http_processing/scripts/borrowed_input_owner_tests.rs new file mode 100644 index 0000000..a90710e --- /dev/null +++ b/src/http_processing/scripts/borrowed_input_owner_tests.rs @@ -0,0 +1,127 @@ +//! Actual fresh-JSC/scoped-thread/TLS teardown test; never a detached worker. +use super::*; +use crate::http_processing::{ + body::BudgetedBytes, + body_budget::{BridgePlan, Budget, MAX_BODY, WORKSPACE}, +}; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc, +}; +use std::time::{Duration, Instant}; +use tokio_util::sync::CancellationToken; + +struct TlsGate { + entered: mpsc::Sender<()>, + release: mpsc::Receiver<()>, + exited: Arc, + released_normally: Arc, +} +impl Drop for TlsGate { + fn drop(&mut self) { + let _ = self.entered.send(()); + self.released_normally.store( + self.release.recv_timeout(Duration::from_secs(5)).is_ok(), + Ordering::Release, + ); + self.exited.store(true, Ordering::Release); + } +} +thread_local! { + static TLS_GATE: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn borrowed_input_cancel_keeps_source_and_bridge_until_real_tls_join() { + let code = validate_source("function rewrite(input){while(true){}}").unwrap(); + let budget = Budget::default(); + let original = BudgetedBytes::copy(&budget, &vec![b'a'; 4096]) + .unwrap() + .into_bytes(); + let last_slice = original.slice(0..1); + let original_cost = budget.used(); + let mut output = BudgetedBytes::new(&budget, MAX_BODY).unwrap(); + let bridge_cost = BridgePlan::new(original.len(), true, MAX_BODY) + .unwrap() + .cost() + .unwrap(); + let bridge = budget.reserve(bridge_cost).unwrap(); + let pressure = budget.reserve(WORKSPACE - budget.used()).unwrap(); + let cancellation = CancellationToken::new(); + let exited = Arc::new(AtomicBool::new(false)); + let released_normally = Arc::new(AtomicBool::new(false)); + let returned = Arc::new(AtomicBool::new(false)); + let (entered_tx, entered_rx) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::channel(); + + // The controller always releases the TLS gate before any assertions. + // A watchdog failure is reported only after the real worker has joined. + let (result, proof) = tokio::task::block_in_place(|| { + std::thread::scope(|scope| { + let observed_budget = budget.clone(); + let observed_returned = returned.clone(); + let observed_exited = exited.clone(); + let controller = scope.spawn(move || { + let entered = entered_rx.recv_timeout(Duration::from_secs(5)).is_ok(); + let still_full = observed_budget.reserve(1).is_none(); + let prematurely_returned = observed_returned.load(Ordering::Acquire); + let prematurely_exited = observed_exited.load(Ordering::Acquire); + let released = release_tx.send(()).is_ok(); + ( + entered, + still_full, + prematurely_returned, + prematurely_exited, + released, + ) + }); + let source = original.as_ref(); + let token = cancellation.clone(); + let exited = exited.clone(); + let released_normally = released_normally.clone(); + let result = run_on_scoped_thread(|| { + TLS_GATE.with(|slot| { + *slot.borrow_mut() = Some(TlsGate { + entered: entered_tx, + release: release_rx, + exited, + released_normally, + }); + }); + let cancel_at_tick = token.clone(); + // No assertion or panic crosses the extern-C tick callback. + apple::on_first_tick_for_test(move || cancel_at_tick.cancel()); + apple::evaluate( + &code, + &serde_json::json!({"phase":"request","body":{"kind":"text"}}), + Some(source), + &mut output, + Some(&bridge), + &token, + Instant::now() + Duration::from_millis(100), + ) + }); + returned.store(true, Ordering::Release); + let proof = controller + .join() + .expect("controller panicked after gate release"); + (result, proof) + }) + }); + assert_eq!(proof, (true, true, false, false, true)); + assert_eq!(result.unwrap_err().kind(), std::io::ErrorKind::Interrupted); + assert!(exited.load(Ordering::Acquire)); + assert!(released_normally.load(Ordering::Acquire)); + assert!(output.as_ref().is_empty()); + assert_eq!(budget.used(), WORKSPACE); + drop(pressure); + drop(bridge); + drop(output); + assert_eq!(budget.used(), original_cost); + drop(original); + assert_eq!(budget.used(), original_cost); + assert_eq!(last_slice.as_ref(), b"a"); + drop(last_slice); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/scripts/frontend.rs b/src/http_processing/scripts/frontend.rs new file mode 100644 index 0000000..f5c2cac --- /dev/null +++ b/src/http_processing/scripts/frontend.rs @@ -0,0 +1,1108 @@ +//! Parse real JavaScript syntax and emit the explicitly supported subset. +//! No unvalidated source fragments are copied into the generated program. +use oxc_allocator::Allocator; +use oxc_ast::ast::*; +use oxc_parser::Parser; +use oxc_span::SourceType; +use std::{collections::BTreeMap, io}; + +const MAX_NODES: usize = 16_384; +const MAX_DEPTH: usize = 128; +const MAX_GENERATED: usize = super::super::config::MAX_ADDENDUM * 8; +const MAX_LEX_WORK: usize = 8 * 1024 * 1024; +const MAX_LEX_BRANCHES: usize = 256; + +fn invalid() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidInput, + "unsupported HTTP script syntax", + ) +} + +mod output_bound; + +#[cfg(test)] +pub(super) fn compile(source: &str) -> io::Result { + compile_with_output_bound(source).map(|(code, _)| code) +} + +#[cfg(test)] +pub(super) fn compile_with_output_bound(source: &str) -> io::Result<(String, super::OutputBound)> { + let prepared = compile_prepared(source)?; + Ok((prepared.code, prepared.output_bound)) +} + +pub(super) struct PreparedSource { + pub(super) code: String, + pub(super) output_bound: super::OutputBound, + #[cfg(target_vendor = "apple")] + pub(super) plan: Option, +} + +pub(super) fn compile_prepared(source: &str) -> io::Result { + if source.len() > super::super::config::MAX_ADDENDUM { + return Err(invalid()); + } + lexical_budget(source)?; + let allocator = Allocator::default(); + let parsed = Parser::new(&allocator, source, SourceType::script()).parse(); + if !parsed.diagnostics.is_empty() + || parsed.fatal_error + || parsed.program.hashbang.is_some() + || !parsed.program.directives.is_empty() + || parsed.program.body.len() != 1 + { + return Err(invalid()); + } + let Statement::FunctionDeclaration(function) = &parsed.program.body[0] else { + return Err(invalid()); + }; + if function.r#async + || function.generator + || function.id.as_ref().is_none_or(|id| id.name != "rewrite") + || function.params.rest.is_some() + || function.params.items.len() != 1 + { + return Err(invalid()); + } + let parameter = &function.params.items[0]; + let BindingPattern::BindingIdentifier(parameter_name) = ¶meter.pattern else { + return Err(invalid()); + }; + if parameter_name.name != "input" || parameter.initializer.is_some() { + return Err(invalid()); + } + let body = function.body.as_ref().ok_or_else(invalid)?; + if !body.directives.is_empty() { + return Err(invalid()); + } + let mut emitter = Emitter { + nodes: 0, + depth: 0, + loops: 0, + temporaries: 0, + scopes: vec![BTreeMap::from([("input".to_owned(), false)])], + }; + let mut body_output = String::new(); + for statement in &body.statements { + body_output.push_str(&emitter.statement(statement)?); + if body_output.len() > MAX_GENERATED { + return Err(invalid()); + } + } + let mut output = String::from("function rewrite(input){\"use strict\";__voleTick();"); + if emitter.temporaries > 0 { + output.push_str("let "); + for index in 0..emitter.temporaries { + if index != 0 { + output.push(','); + } + output.push_str(&format!("__voleTmp{index}")); + } + output.push(';'); + } + output.push_str(&body_output); + output.push('}'); + let code = emitter.bounded(output)?; + // Analyze the same already accepted AST. An inconclusive/capped proof + // returns Maximum and never changes JavaScript or public acceptance. + Ok(PreparedSource { + code, + output_bound: output_bound::analyze(function), + #[cfg(target_vendor = "apple")] + plan: super::static_literal_plan::analyze(function), + }) +} + +struct Emitter { + nodes: usize, + depth: usize, + loops: usize, + temporaries: usize, + scopes: Vec>, +} + +impl Emitter { + fn enter(&mut self) -> io::Result<()> { + self.nodes += 1; + self.depth += 1; + if self.nodes > MAX_NODES || self.depth > MAX_DEPTH { + return Err(invalid()); + } + Ok(()) + } + + fn bounded(&self, output: String) -> io::Result { + if output.len() > MAX_GENERATED { + return Err(invalid()); + } + Ok(output) + } + + fn statement(&mut self, statement: &Statement<'_>) -> io::Result { + self.enter()?; + let output = self.statement_inner(statement); + self.depth -= 1; + self.bounded(output?) + } + + fn statement_inner(&mut self, statement: &Statement<'_>) -> io::Result { + Ok(match statement { + Statement::BlockStatement(block) => { + self.scopes.push(BTreeMap::new()); + let mut output = String::from("{"); + for statement in &block.body { + output.push_str(&self.statement(statement)?); + if output.len() > MAX_GENERATED { + return Err(invalid()); + } + } + self.scopes.pop(); + output.push('}'); + output + } + Statement::EmptyStatement(_) => ";".into(), + Statement::VariableDeclaration(declaration) => { + format!("{};", self.declaration(declaration)?) + } + Statement::ExpressionStatement(statement) => { + format!("{};", self.expression(&statement.expression)?) + } + Statement::ReturnStatement(statement) => match &statement.argument { + Some(argument) => format!("return {};", self.expression(argument)?), + None => "return;".into(), + }, + Statement::IfStatement(statement) => { + let test = self.expression(&statement.test)?; + let consequent = self.statement(&statement.consequent)?; + let alternate = statement + .alternate + .as_ref() + .map(|statement| { + self.statement(statement) + .map(|output| format!("else{{{output}}}")) + }) + .transpose()? + .unwrap_or_default(); + format!("if({test}){{{consequent}}}{alternate}") + } + Statement::WhileStatement(statement) => { + let test = self.expression(&statement.test)?; + self.loops += 1; + let body = self.statement(&statement.body)?; + self.loops -= 1; + format!("while({test}){{__voleTick();{body}}}") + } + Statement::DoWhileStatement(statement) => { + self.loops += 1; + let body = self.statement(&statement.body)?; + self.loops -= 1; + let test = self.expression(&statement.test)?; + format!("do{{__voleTick();{body}}}while({test});") + } + Statement::ForStatement(statement) => { + self.scopes.push(BTreeMap::new()); + let init = match &statement.init { + Some(ForStatementInit::VariableDeclaration(declaration)) => { + self.declaration(declaration)? + } + Some(init) => self.expression(init.as_expression().ok_or_else(invalid)?)?, + None => String::new(), + }; + let test = statement + .test + .as_ref() + .map(|value| self.expression(value)) + .transpose()? + .unwrap_or_default(); + let update = statement + .update + .as_ref() + .map(|value| self.expression(value)) + .transpose()? + .unwrap_or_default(); + self.loops += 1; + let body = self.statement(&statement.body)?; + self.loops -= 1; + self.scopes.pop(); + format!("for({init};{test};{update}){{__voleTick();{body}}}") + } + Statement::BreakStatement(statement) if self.loops > 0 && statement.label.is_none() => { + "break;".into() + } + Statement::ContinueStatement(statement) + if self.loops > 0 && statement.label.is_none() => + { + "continue;".into() + } + _ => return Err(invalid()), + }) + } + + fn declaration(&mut self, declaration: &VariableDeclaration<'_>) -> io::Result { + let (kind, mutable) = match declaration.kind { + VariableDeclarationKind::Let => ("let", true), + VariableDeclarationKind::Const => ("const", false), + _ => return Err(invalid()), + }; + let mut output = Vec::new(); + for binding in &declaration.declarations { + self.nodes += 1; + if self.nodes > MAX_NODES { + return Err(invalid()); + } + let BindingPattern::BindingIdentifier(identifier) = &binding.id else { + return Err(invalid()); + }; + let name = identifier.name.as_str(); + validate_binding(name)?; + let init = binding + .init + .as_ref() + .map(|value| self.expression(value)) + .transpose()?; + if !mutable && init.is_none() { + return Err(invalid()); + } + if self + .scopes + .last_mut() + .ok_or_else(invalid)? + .insert(name.to_owned(), mutable) + .is_some() + { + return Err(invalid()); + } + output.push(match init { + Some(init) => format!("{name}={init}"), + None => name.to_owned(), + }); + } + self.bounded(format!("{kind} {}", output.join(","))) + } + + fn variable(&self, name: &str, write: bool) -> io::Result { + if name == "undefined" && !write { + return Ok(name.to_owned()); + } + let mutable = self + .scopes + .iter() + .rev() + .find_map(|scope| scope.get(name)) + .ok_or_else(invalid)?; + if write && !mutable { + return Err(invalid()); + } + Ok(name.to_owned()) + } + + fn expression(&mut self, expression: &Expression<'_>) -> io::Result { + self.enter()?; + let output = self.expression_inner(expression); + self.depth -= 1; + self.bounded(output?) + } + + fn expression_inner(&mut self, expression: &Expression<'_>) -> io::Result { + Ok(match expression { + Expression::BooleanLiteral(value) => value.value.to_string(), + Expression::NullLiteral(_) => "null".into(), + Expression::NumericLiteral(value) if value.value.is_finite() => { + serde_json::to_string(&value.value).map_err(|_| invalid())? + } + Expression::StringLiteral(value) => quoted(value.value.as_str().ok_or_else(invalid)?)?, + Expression::Identifier(identifier) => self.variable(identifier.name.as_str(), false)?, + Expression::ParenthesizedExpression(value) => { + format!("({})", self.expression(&value.expression)?) + } + Expression::ArrayExpression(array) => { + let mut elements = Vec::new(); + for element in &array.elements { + elements.push(self.expression(element.as_expression().ok_or_else(invalid)?)?); + } + format!("__voleValue([{}])", elements.join(",")) + } + Expression::ObjectExpression(object) => { + let mut properties = Vec::new(); + for property in &object.properties { + self.nodes += 1; + if self.nodes > MAX_NODES { + return Err(invalid()); + } + let ObjectPropertyKind::ObjectProperty(property) = property else { + return Err(invalid()); + }; + if property.kind != PropertyKind::Init || property.method || property.computed { + return Err(invalid()); + } + let key = match &property.key { + PropertyKey::StaticIdentifier(key) => key.name.as_str().to_owned(), + PropertyKey::StringLiteral(key) => { + key.value.as_str().ok_or_else(invalid)?.to_owned() + } + PropertyKey::NumericLiteral(key) if key.value.is_finite() => { + key.value.to_string() + } + _ => return Err(invalid()), + }; + validate_key(&key)?; + properties.push(format!( + "{}:{}", + quoted(&key)?, + self.expression(&property.value)? + )); + } + format!("__voleValue({{{}}})", properties.join(",")) + } + Expression::StaticMemberExpression(member) if !member.optional => { + validate_key(member.property.name.as_str())?; + format!( + "__voleGet({},{})", + self.expression(&member.object)?, + quoted(member.property.name.as_str())? + ) + } + Expression::ComputedMemberExpression(member) if !member.optional => { + let object = self.expression(&member.object)?; + let key = self.key_expression(&member.expression)?; + format!("__voleGet({object},{key})") + } + Expression::BinaryExpression(binary) => { + let operator = binary.operator.as_str(); + let left = self.expression(&binary.left)?; + let right = self.expression(&binary.right)?; + if operator == "+" { + format!("__voleAdd({left},{right})") + } else if matches!(operator, "===" | "!==") { + format!("({left}{operator}{right})") + } else if matches!( + operator, + "-" | "*" + | "/" + | "%" + | "<" + | "<=" + | ">" + | ">=" + | "==" + | "!=" + | "===" + | "!==" + | "|" + | "&" + | "^" + | "<<" + | ">>" + | ">>>" + ) { + format!("__voleBinary({},{left},{right})", quoted(operator)?) + } else { + return Err(invalid()); + } + } + Expression::LogicalExpression(logical) => format!( + "({}{}{})", + self.expression(&logical.left)?, + logical.operator.as_str(), + self.expression(&logical.right)? + ), + Expression::ConditionalExpression(conditional) => format!( + "({}?{}:{})", + self.expression(&conditional.test)?, + self.expression(&conditional.consequent)?, + self.expression(&conditional.alternate)? + ), + Expression::UnaryExpression(unary) + if matches!( + unary.operator.as_str(), + "+" | "-" | "!" | "~" | "typeof" | "void" + ) => + { + let argument = self.expression(&unary.argument)?; + let operator = unary.operator.as_str(); + if matches!(operator, "+" | "-" | "~") { + format!("__voleUnary({},{argument})", quoted(operator)?) + } else { + format!("({operator} {argument})") + } + } + Expression::AssignmentExpression(assignment) => self.assignment(assignment)?, + Expression::UpdateExpression(update) => { + let SimpleAssignmentTarget::AssignmentTargetIdentifier(identifier) = + &update.argument + else { + return Err(invalid()); + }; + let name = self.variable(identifier.name.as_str(), true)?; + let change = if update.operator.as_str() == "++" { + "1" + } else { + "-1" + }; + if update.prefix { + format!("({name}=__voleAdd(__voleUnary(\"+\",{name}),{change}))") + } else { + let temporary = self.temporaries; + self.temporaries += 1; + format!( + "(__voleTmp{temporary}=__voleUnary(\"+\",{name}),{name}=__voleAdd(__voleTmp{temporary},{change}),__voleTmp{temporary})" + ) + } + } + Expression::CallExpression(call) => self.call(call)?, + _ => return Err(invalid()), + }) + } + + fn key_expression(&mut self, expression: &Expression<'_>) -> io::Result { + if let Expression::StringLiteral(literal) = expression { + validate_key(literal.value.as_str().ok_or_else(invalid)?)?; + } + self.expression(expression) + } + + fn assignment(&mut self, assignment: &AssignmentExpression<'_>) -> io::Result { + let operator = assignment.operator.as_str(); + match &assignment.left { + AssignmentTarget::AssignmentTargetIdentifier(identifier) => { + let name = self.variable(identifier.name.as_str(), true)?; + let value = self.expression(&assignment.right)?; + if operator == "+=" { + Ok(format!("({name}=__voleAdd({name},{value}))")) + } else if operator == "=" { + Ok(format!("({name}={value})")) + } else if matches!( + operator, + "-=" | "*=" | "/=" | "%=" | "|=" | "&=" | "^=" | "<<=" | ">>=" | ">>>=" + ) { + Ok(format!( + "({name}=__voleBinary({},{name},{value}))", + quoted(&operator[..operator.len() - 1])? + )) + } else { + Err(invalid()) + } + } + AssignmentTarget::StaticMemberExpression(member) + if operator == "=" && !member.optional => + { + validate_key(member.property.name.as_str())?; + Ok(format!( + "__voleSet({},{},{})", + self.expression(&member.object)?, + quoted(member.property.name.as_str())?, + self.expression(&assignment.right)? + )) + } + AssignmentTarget::ComputedMemberExpression(member) + if operator == "=" && !member.optional => + { + Ok(format!( + "__voleSet({},{},{})", + self.expression(&member.object)?, + self.key_expression(&member.expression)?, + self.expression(&assignment.right)? + )) + } + _ => Err(invalid()), + } + } + + fn call(&mut self, call: &CallExpression<'_>) -> io::Result { + if call.optional { + return Err(invalid()); + } + let mut arguments = Vec::new(); + for argument in &call.arguments { + arguments.push(self.expression(argument.as_expression().ok_or_else(invalid)?)?); + } + if let Expression::Identifier(identifier) = &call.callee { + let name = identifier.name.as_str(); + if matches!(name, "String" | "Number" | "Boolean") && arguments.len() == 1 { + return Ok(format!( + "__voleConvert({}, {})", + quoted(name)?, + arguments[0] + )); + } + return Err(invalid()); + } + let Expression::StaticMemberExpression(member) = &call.callee else { + return Err(invalid()); + }; + if member.optional { + return Err(invalid()); + } + let name = member.property.name.as_str(); + validate_key(name)?; + let receiver = if let Expression::Identifier(identifier) = &member.object { + let global = identifier.name.as_str(); + if matches!( + global, + "JSON" | "Object" | "Array" | "Number" | "Math" | "Uint8Array" + ) { + if !global_method(global, name) { + return Err(invalid()); + } + global.to_owned() + } else { + if !value_method(name) { + return Err(invalid()); + } + self.expression(&member.object)? + } + } else { + if !value_method(name) { + return Err(invalid()); + } + self.expression(&member.object)? + }; + Ok(format!( + "__voleCall({receiver},{},[{}])", + quoted(name)?, + arguments.join(",") + )) + } +} + +fn quoted(value: &str) -> io::Result { + serde_json::to_string(value).map_err(|_| invalid()) +} + +fn validate_key(key: &str) -> io::Result<()> { + if matches!(key, "constructor" | "prototype" | "__proto__") || key.starts_with("__vole") { + return Err(invalid()); + } + Ok(()) +} + +fn validate_binding(name: &str) -> io::Result<()> { + validate_key(name)?; + if name.is_empty() + || !name.bytes().enumerate().all(|(index, byte)| { + byte.is_ascii_alphabetic() + || byte == b'_' + || byte == b'$' + || (index > 0 && byte.is_ascii_digit()) + }) + || matches!( + name, + "input" + | "rewrite" + | "undefined" + | "JSON" + | "Object" + | "Array" + | "Math" + | "Uint8Array" + | "String" + | "Number" + | "Boolean" + | "eval" + | "arguments" + | "yield" + | "await" + | "implements" + | "interface" + | "package" + | "private" + | "protected" + | "public" + | "static" + | "let" + | "enum" + ) + { + return Err(invalid()); + } + Ok(()) +} + +#[derive(Clone, Default)] +struct LexicalState { + offset: usize, + brackets: Vec, + operators: usize, + controls: usize, + colons: usize, +} + +/// This is only parser admission. Real syntax and every executable construct +/// still go through Oxc and the AST emitter. In particular, do not guess the +/// RegExp/Division lexical goal from preceding text: explore both possible +/// slash interpretations and conservatively enforce the resource bounds. +fn lexical_budget(source: &str) -> io::Result<()> { + let bytes = source.as_bytes(); + let mut pending = vec![LexicalState::default()]; + let mut visited: BTreeMap<(usize, Vec), (usize, usize, usize)> = BTreeMap::new(); + let mut work = 0usize; + let mut branches = 0usize; + while let Some(mut state) = pending.pop() { + while state.offset < bytes.len() { + let key = (state.offset, state.brackets.clone()); + if let Some(counts) = visited.get_mut(&key) { + if counts.0 >= state.operators + && counts.1 >= state.controls + && counts.2 >= state.colons + { + break; + } + state.operators = state.operators.max(counts.0); + state.controls = state.controls.max(counts.1); + state.colons = state.colons.max(counts.2); + *counts = (state.operators, state.controls, state.colons); + } else { + if visited.len() >= MAX_NODES * 4 { + return Err(invalid()); + } + visited.insert(key, (state.operators, state.controls, state.colons)); + } + lex_work(&mut work, 1)?; + let i = state.offset; + match bytes[i] { + b'\'' | b'"' => { + let quote = bytes[i]; + let mut end = i + 1; + while end < bytes.len() { + lex_work(&mut work, 1)?; + if bytes[end] == b'\\' { + end += 1; + if end >= bytes.len() { + break; + } + if bytes[end] == b'\r' && bytes.get(end + 1) == Some(&b'\n') { + end += 1; + } + } else if bytes[end] == quote { + end += 1; + break; + } else if matches!(bytes[end], b'\n' | b'\r') { + break; + } + end += 1; + } + // An impossible lexical alternative must not reject a + // valid division expression. At a malformed line ending, + // keep scanning subsequent source for parser recovery; + // Oxc remains responsible for reporting the string error. + state.offset = end; + } + b'/' if bytes.get(i + 1) == Some(&b'/') => { + let mut end = i + 2; + while end < bytes.len() && !lex_line_end(bytes, end) { + lex_work(&mut work, 1)?; + end += 1; + } + state.offset = end; + } + b'/' if bytes.get(i + 1) == Some(&b'*') => { + let mut end = i + 2; + while end + 1 < bytes.len() && &bytes[end..end + 2] != b"*/" { + lex_work(&mut work, 1)?; + end += 1; + } + state.offset = (end + 2).min(bytes.len()); + } + b'/' => { + if let Some(end) = possible_regexp_end(bytes, i + 1, &mut work)? { + branches += 1; + if branches > MAX_LEX_BRANCHES { + return Err(invalid()); + } + let mut alternative = state.clone(); + alternative.offset = end; + pending.push(alternative); + } + state.operators += 1; + state.offset += 1; + } + b'(' | b'[' | b'{' => { + state.brackets.push(bytes[i]); + state.offset += 1; + if bytes[i] == b'{' { + state.colons = 0; + } + } + b')' | b']' | b'}' => { + let expected = match bytes[i] { + b')' => b'(', + b']' => b'[', + _ => b'{', + }; + if state.brackets.last() == Some(&expected) { + state.brackets.pop(); + } + if bytes[i] == b'}' { + state.colons = 0; + } + state.offset += 1; + } + b':' => { + state.colons += 1; + state.offset += 1; + } + b',' | b';' => { + state.colons = 0; + state.offset += 1; + } + b'!' | b'~' | b'+' | b'-' | b'*' | b'%' | b'<' | b'>' | b'=' | b'&' | b'|' + | b'^' | b'?' => { + state.operators += 1; + state.offset += 1; + } + b'`' | b'\\' => return Err(invalid()), + byte if byte.is_ascii_alphabetic() || matches!(byte, b'_' | b'$') => { + let mut end = i + 1; + while end < bytes.len() + && (bytes[end].is_ascii_alphanumeric() || matches!(bytes[end], b'_' | b'$')) + { + lex_work(&mut work, 1)?; + end += 1; + } + if matches!( + &bytes[i..end], + b"if" + | b"else" + | b"for" + | b"while" + | b"do" + | b"function" + | b"class" + | b"switch" + | b"try" + | b"catch" + | b"finally" + | b"with" + ) { + state.controls += 1; + } + state.offset = end; + } + byte if byte.is_ascii_whitespace() => { + state.offset += 1; + while state.offset < bytes.len() && bytes[state.offset].is_ascii_whitespace() { + lex_work(&mut work, 1)?; + state.offset += 1; + } + } + _ => state.offset += 1, + } + if state.brackets.len() > MAX_DEPTH + || state.operators > MAX_DEPTH + || state.controls > MAX_DEPTH + || state.colons > MAX_DEPTH + { + return Err(invalid()); + } + } + } + Ok(()) +} + +fn lex_work(work: &mut usize, amount: usize) -> io::Result<()> { + *work = work + .checked_add(amount) + .filter(|n| *n <= MAX_LEX_WORK) + .ok_or_else(invalid)?; + Ok(()) +} + +fn possible_regexp_end(bytes: &[u8], start: usize, work: &mut usize) -> io::Result> { + let mut i = start; + let mut class = false; + while i < bytes.len() { + lex_work(work, 1)?; + if lex_line_end(bytes, i) { + return Ok(None); + } + match bytes[i] { + b'\n' | b'\r' => return Ok(None), + b'\\' => { + i += 1; + if i >= bytes.len() || lex_line_end(bytes, i) { + return Ok(None); + } + } + b'[' => class = true, + b']' => class = false, + b'/' if !class => return Ok(Some(i + 1)), + _ => {} + } + i += 1; + } + Ok(None) +} + +fn lex_line_end(bytes: &[u8], offset: usize) -> bool { + matches!(bytes[offset], b'\n' | b'\r') + || bytes[offset..].starts_with(&[0xE2, 0x80, 0xA8]) + || bytes[offset..].starts_with(&[0xE2, 0x80, 0xA9]) +} + +fn global_method(receiver: &str, name: &str) -> bool { + match receiver { + "JSON" => matches!(name, "parse" | "stringify"), + "Object" => matches!(name, "keys" | "values" | "entries"), + "Array" => name == "isArray", + "Number" => matches!(name, "isFinite" | "isInteger"), + "Math" => matches!( + name, + "abs" | "floor" | "ceil" | "round" | "trunc" | "min" | "max" + ), + "Uint8Array" => name == "from", + _ => false, + } +} + +fn value_method(name: &str) -> bool { + matches!( + name, + "slice" + | "subarray" + | "substring" + | "charAt" + | "at" + | "includes" + | "startsWith" + | "endsWith" + | "indexOf" + | "lastIndexOf" + | "trim" + | "toLowerCase" + | "toUpperCase" + | "split" + | "replace" + | "replaceAll" + | "push" + | "pop" + | "concat" + | "join" + | "reverse" + ) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rewrites_all_growth_and_member_paths_from_the_ast() { + let output = compile("function rewrite(input) { let s = input.body.data; const a = []; for(let i=0;i<3;i++){s += 'x'; a.push(s);} a[0] = s + 'y'; return {type:'modify',body:{kind:'text',data:a.join(',')}}; }").unwrap(); + assert_eq!(output.matches("__voleTick();").count(), 2); + assert!(output.contains("__voleAdd(s,\"x\")")); + assert!(output.contains("__voleSet(a,0.0,__voleAdd(s,\"y\"))")); + assert!(output.contains("__voleGet(__voleGet(input,\"body\"),\"data\")")); + assert!(output.contains("__voleCall(a,\"push\",[s])")); + assert!(output.contains("__voleValue({")); + } + + #[test] + fn rejects_escape_syntax_and_uninstrumented_invocation_paths() { + for source in [ + "function rewrite(input){return eval('1');}", + "function rewrite(input){return input.constructor;}", + "function rewrite(input){return input['__proto__'];}", + "function rewrite(input){return __voleGet(input,'x');}", + "function rewrite(input){return [].map(x=>x);}", + "function rewrite(input){const f=JSON.parse;return f('{}');}", + "function rewrite(input){return JSON['parse']('{}');}", + "function rewrite(input){return new Uint8Array(10);}", + "function rewrite(input){try{return input;}catch(e){return input;}}", + "function rewrite(input){function f(){return 1;}return f();}", + "async function rewrite(input){return input;}", + "function rewrite(input){return {get x(){return 1;}};}", + "function rewrite(input){return {['__proto__']:input};}", + "function rewrite(input){let JSON={};return JSON.parse('{}');}", + "function rewrite(input){return /x/.test('x');}", + "function rewrite(input){return '\\ud800';}", + "function rewrite(input){return input;} rewrite({});", + "function rewrite(other){return other;}", + "function rewrite(input){const a=1;a=2;return a;}", + ] { + assert!(compile(source).is_err(), "accepted {source}"); + } + } + + #[test] + fn all_loop_forms_tick_even_when_the_body_is_empty_or_continues() { + let output = compile("function rewrite(input){let i=0;while(i<2){i++;continue;}do{i--;}while(i>0);for(;;);return {type:'pass'};}").unwrap(); + assert_eq!(output.matches("__voleTick();").count(), 4); + } + + #[test] + fn approved_tools_remain_explicit_calls_without_function_values() { + let output = compile("function rewrite(input){const a=JSON.parse(input.body.data);const b=Object.keys(a);const c=Uint8Array.from([1,2]);return {type:'respond',status:Number('200'),body:{kind:'text',data:JSON.stringify(b)}};}").unwrap(); + assert!(output.contains("__voleCall(JSON,\"parse\",")); + assert!(output.contains("__voleCall(Uint8Array,\"from\",")); + assert!(output.contains("__voleConvert(\"Number\", \"200\")")); + } + + #[test] + fn typed_array_views_are_routed_through_the_controlled_method() { + let output = compile("function rewrite(input){return {type:'modify',body:{kind:'bytes',data:input.body.data.subarray(1,3)}};}").unwrap(); + assert!(output.contains( + "__voleCall(__voleGet(__voleGet(input,\"body\"),\"data\"),\"subarray\",[1.0,3.0])" + )); + } +} + +#[cfg(test)] +mod lexical_tests { + use super::*; + + #[test] + fn parser_admission_rejects_deep_expressions_and_unbraced_control_flow() { + let cases = [ + format!( + "function rewrite(input){{return {}0{};}}", + "(".repeat(20_000), + ")".repeat(20_000) + ), + format!( + "function rewrite(input){{return {}true;}}", + "!".repeat(20_000) + ), + format!( + "function rewrite(input){{{}return {{type:'pass'}};}}", + "if(true) ".repeat(20_000) + ), + format!("function rewrite(input){{let a;{}0;}}", "a=".repeat(20_000)), + format!( + "function rewrite(input){{{}return {{type:'pass'}};}}", + "label:".repeat(20_000) + ), + ]; + for source in cases { + assert!(compile(&source).is_err()); + } + } + + #[test] + fn lexical_admission_skips_data_and_covers_regexp_quote_ambiguity() { + let data = "if ((( ! ".repeat(1000); + let source = format!( + "function rewrite(input){{/* {data} */let s={};return {{type:'pass'}};}}", + serde_json::to_string(&data).unwrap() + ); + assert!(compile(&source).is_ok()); + assert!(compile("function rewrite(input){let n=8 / 2;const url='https://example.test/';return {type:'pass'};}").is_ok()); + let source = format!( + "function rewrite(input){{let r=/\"/;{}0{};}}", + "(".repeat(20_000), + ")".repeat(20_000) + ); + assert!(compile(&source).is_err()); + let source = format!( + "function rewrite(input){{// comment\u{2028}{}0{};}}", + "(".repeat(20_000), + ")".repeat(20_000) + ); + assert!(compile(&source).is_err()); + } +} + +#[cfg(all(test, target_vendor = "apple"))] +mod prelude_tests { + use crate::http_processing::{ + body_budget::{Budget, BudgetedBytes}, + scripts, + }; + use serde_json::{Value, json}; + use std::io; + use tokio_util::sync::CancellationToken; + + async fn run(source: &str, input: Option<&[u8]>) -> io::Result<(Value, Vec)> { + let program = scripts::validate_source(source)?; + let metadata = json!({"phase":"response","original":{"url":"https://example.test/","method":"GET"}, + "request":{"url":"https://example.test/","method":"GET","headers":[]}, + "response":{"status":200,"headers":[]},"body":{"kind":if input.is_some(){"text"}else{"not-requested"}}}); + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, 0).unwrap(); + let result = scripts::evaluate( + &program, + &metadata, + input, + &mut output, + &CancellationToken::new(), + ) + .await?; + Ok((result, output.as_ref().to_vec())) + } + + #[tokio::test] + async fn coercive_operations_cannot_expand_nested_arrays_implicitly() { + for expression in ["a+1", "a-1", "+a", "a<1", "Math.abs(a)", "Number(a)"] { + let source = format!( + "function rewrite(input){{let a=['x'];for(let i=0;i<20;i++){{a=[a,a];}}const n={expression};return {{type:'pass'}};}}" + ); + assert!(run(&source, None).await.is_err(), "accepted {expression}"); + } + assert!( + run( + "function rewrite(input){let n=[['x']];n++;return {type:'pass'};}", + None + ) + .await + .is_err() + ); + } + + #[tokio::test] + async fn array_growth_join_and_split_fail_before_large_native_results() { + for source in [ + "function rewrite(input){const a=[];a[262143]=0;return {type:'pass'};}", + "function rewrite(input){let a=['x'];for(let i=0;i<20;i++){a=[a,a];}const s=a.join('');return {type:'pass'};}", + ] { + assert!(run(source, None).await.is_err()); + } + assert!( + run( + "function rewrite(input){const a=input.body.data.split('');return {type:'pass'};}", + Some(&vec![b'x'; 100_000]) + ) + .await + .is_err() + ); + } + + #[tokio::test] + async fn text_growth_is_limited_in_utf8_bytes() { + let input = "中".repeat(50_000); + assert!(run("function rewrite(input){const a=input.body.data+input.body.data;return {type:'pass'};}",Some(input.as_bytes())).await.is_err()); + } + + #[tokio::test] + async fn replacement_templates_keep_js_semantics_and_preflight_expansion() { + let (_, body) = run("function rewrite(input){return {type:'respond',status:200,body:{kind:'text',data:'aaa'.replaceAll('a','$`')}};}",None).await.unwrap(); + assert_eq!(body, b"aaa"); + assert!(run("function rewrite(input){const s=input.body.data.replaceAll('a',\"$'\");return {type:'pass'};}",Some(&vec![b'a';4096])).await.is_err()); + } + + #[tokio::test] + async fn result_export_checks_header_records_and_utf8_totals() { + assert!(run("function rewrite(input){const h=[];for(let i=0;i<101;i++){h.push({op:'set',name:'x-test',values:['x']});}return {type:'modify',headers:h};}",None).await.is_err()); + let input = "中".repeat(6000); + assert!(run("function rewrite(input){return {type:'modify',headers:[{op:'set',name:'x-test',values:[input.body.data,input.body.data]}]};}",Some(input.as_bytes())).await.is_err()); + for source in [ + "function rewrite(input){return {type:'pass',url:'https://example.test/'};}", + "function rewrite(input){return {type:'modify',headers:[{op:'remove',name:'x-test',values:['x']}]};}", + "function rewrite(input){return {type:'modify',headers:[{op:'add',name:'proxy-authorization',values:['x']}]};}", + ] { + assert!(run(source, None).await.is_err()); + } + } + + #[tokio::test] + async fn json_tools_reject_deep_or_shared_structures_without_exporting_them() { + let deep = format!("{}0{}", "[".repeat(70), "]".repeat(70)); + assert!(run("function rewrite(input){const x=JSON.parse(input.body.data);return {type:'pass'};}",Some(deep.as_bytes())).await.is_err()); + assert!(run("function rewrite(input){let a=['x'];for(let i=0;i<20;i++){a=[a,a];}const s=JSON.stringify(a);return {type:'pass'};}",None).await.is_err()); + } + + #[tokio::test] + async fn postfix_and_prefix_updates_preserve_their_numeric_results() { + let (_,body)=run("function rewrite(input){let i='1';const a=i++;const b=++i;return {type:'respond',status:200,body:{kind:'text',data:JSON.stringify([a,b,i])}};}",None).await.unwrap(); + assert_eq!(body, b"[1,3,3]"); + } +} diff --git a/src/http_processing/scripts/frontend/output_bound.rs b/src/http_processing/scripts/frontend/output_bound.rs new file mode 100644 index 0000000..5f5a098 --- /dev/null +++ b/src/http_processing/scripts/frontend/output_bound.rs @@ -0,0 +1,889 @@ +//! Optional size proof over an already accepted AST. This emits no code and +//! never turns a supported JavaScript program into a configuration error. +use oxc_ast::ast::*; +use std::collections::{BTreeMap, BTreeSet}; + +use super::super::OutputBound; + +const MAX_PROOF_NODES: usize = 4096; +const MAX_PROOF_BINDINGS: usize = 128; +const MAX_PROOF_DEPENDENCIES: usize = 32; + +#[derive(Clone)] +struct StringProof { + literal_bytes: usize, + original_input: bool, + dependencies: BTreeSet, +} + +pub(super) fn analyze(function: &Function<'_>) -> OutputBound { + let Some(parameter) = function.params.items.first() else { + return OutputBound::Maximum; + }; + let BindingPattern::BindingIdentifier(parameter) = ¶meter.pattern else { + return OutputBound::Maximum; + }; + let Some(body) = function.body.as_ref() else { + return OutputBound::Maximum; + }; + let mut analysis = Analysis { + parameter: parameter.name.as_str().to_owned(), + safe: true, + nodes: 0, + declared: BTreeSet::new(), + bindings: BTreeMap::new(), + writes: BTreeSet::new(), + root_strings: BTreeSet::new(), + audited_writes: BTreeSet::new(), + other_writes: BTreeSet::new(), + returns: Vec::new(), + }; + let always_returns = analysis.statements(&body.statements, true); + if !analysis.safe || !always_returns || analysis.returns.is_empty() { + return OutputBound::Maximum; + } + let mut maximum_literal_bytes = 0; + for proof in &analysis.returns { + if proof.dependencies.iter().any(|name| { + analysis.writes.contains(name) + && (!analysis.audited_writes.contains(name) || analysis.other_writes.contains(name)) + }) { + return OutputBound::Maximum; + } + maximum_literal_bytes = maximum_literal_bytes.max(proof.literal_bytes); + } + if maximum_literal_bytes > super::super::super::body_budget::MAX_BODY { + return OutputBound::Maximum; + } + OutputBound::InputOrConstant { + maximum_literal_bytes, + } +} + +struct Analysis { + parameter: String, + safe: bool, + nodes: usize, + declared: BTreeSet, + bindings: BTreeMap, + writes: BTreeSet, + root_strings: BTreeSet, + audited_writes: BTreeSet, + other_writes: BTreeSet, + returns: Vec, +} + +impl Analysis { + fn enter(&mut self) -> bool { + self.nodes += 1; + self.safe &= self.nodes <= MAX_PROOF_NODES; + self.safe + } + + fn statements(&mut self, statements: &[Statement<'_>], root: bool) -> bool { + let mut always_returns = false; + for statement in statements { + // Do not prune dead/unreachable statements: their unknown effects + // must also force the whole optional proof back to Maximum. + always_returns |= self.statement(statement, root); + } + always_returns + } + + fn statement(&mut self, statement: &Statement<'_>, root: bool) -> bool { + if !self.enter() { + return false; + } + match statement { + Statement::BlockStatement(block) => self.statements(&block.body, false), + Statement::EmptyStatement(_) => false, + Statement::VariableDeclaration(declaration) => { + self.declaration(declaration, root); + false + } + Statement::ExpressionStatement(statement) => { + self.expression_at(&statement.expression, root); + false + } + Statement::ReturnStatement(statement) => { + if let Some(argument) = &statement.argument { + self.expression(argument); + if !self.safe { + return true; + } + if let Some(proof) = self.return_proof(argument) { + self.returns.push(proof); + } else { + self.safe = false; + } + } else { + self.safe = false; + } + true + } + Statement::IfStatement(statement) => { + self.expression(&statement.test); + let consequent = self.statement(&statement.consequent, false); + let alternate = statement + .alternate + .as_ref() + .is_some_and(|s| self.statement(s, false)); + consequent && alternate + } + Statement::WhileStatement(statement) => { + self.expression(&statement.test); + self.statement(&statement.body, false); + false + } + Statement::DoWhileStatement(statement) => { + self.statement(&statement.body, false); + self.expression(&statement.test); + false + } + Statement::ForStatement(statement) => { + if let Some(init) = &statement.init { + match init { + ForStatementInit::VariableDeclaration(declaration) => { + self.declaration(declaration, false) + } + _ => match init.as_expression() { + Some(expression) => self.expression(expression), + None => self.safe = false, + }, + } + } + if let Some(test) = &statement.test { + self.expression(test); + } + if let Some(update) = &statement.update { + self.expression(update); + } + self.statement(&statement.body, false); + false + } + Statement::BreakStatement(statement) if statement.label.is_none() => false, + Statement::ContinueStatement(statement) if statement.label.is_none() => false, + _ => { + self.safe = false; + false + } + } + } + + fn declaration(&mut self, declaration: &VariableDeclaration<'_>, root: bool) { + for binding in &declaration.declarations { + let BindingPattern::BindingIdentifier(identifier) = &binding.id else { + self.safe = false; + return; + }; + let name = identifier.name.as_str(); + if name == self.parameter + || !self.declared.insert(name.to_owned()) + || self.declared.len() > MAX_PROOF_BINDINGS + { + self.safe = false; + return; + } + if let Some(init) = &binding.init { + self.expression(init); + if !self.safe { + return; + } + if let Some(proof) = self.string_proof(init) { + if root && matches!(declaration.kind, VariableDeclarationKind::Let) { + self.root_strings.insert(name.to_owned()); + } + self.bindings.insert(name.to_owned(), proof); + } + } + } + } + + fn expression(&mut self, expression: &Expression<'_>) { + self.expression_at(expression, false); + } + + fn expression_at(&mut self, expression: &Expression<'_>, root_statement: bool) { + if !self.enter() { + return; + } + match expression { + Expression::BooleanLiteral(_) + | Expression::NullLiteral(_) + | Expression::NumericLiteral(_) + | Expression::StringLiteral(_) + | Expression::Identifier(_) => {} + Expression::ParenthesizedExpression(value) => self.expression(&value.expression), + Expression::ArrayExpression(array) => { + for element in &array.elements { + match element.as_expression() { + Some(value) => self.expression(value), + None => self.safe = false, + } + } + } + Expression::ObjectExpression(object) => { + for property in &object.properties { + let ObjectPropertyKind::ObjectProperty(property) = property else { + self.safe = false; + return; + }; + if property.kind != PropertyKind::Init || property.method || property.computed { + self.safe = false; + } + self.expression(&property.value); + } + } + Expression::StaticMemberExpression(member) if !member.optional => { + self.expression(&member.object) + } + Expression::ComputedMemberExpression(member) if !member.optional => { + self.expression(&member.object); + self.expression(&member.expression); + } + Expression::BinaryExpression(value) => { + self.expression(&value.left); + self.expression(&value.right); + } + Expression::LogicalExpression(value) => { + self.expression(&value.left); + self.expression(&value.right); + } + Expression::ConditionalExpression(value) => { + self.expression(&value.test); + self.expression(&value.consequent); + self.expression(&value.alternate); + } + Expression::UnaryExpression(value) => self.expression(&value.argument), + Expression::AssignmentExpression(value) => { + match &value.left { + AssignmentTarget::AssignmentTargetIdentifier(identifier) => { + let name = identifier.name.as_str(); + let audited = root_statement + && self.root_strings.contains(name) + && ascii_self_assignment(value, name); + self.record_write(name, audited); + } + // Includes writes through aliases, computed keys, argument + // expressions and unreachable branches. + _ => self.safe = false, + } + self.expression(&value.right); + } + Expression::UpdateExpression(value) => match &value.argument { + SimpleAssignmentTarget::AssignmentTargetIdentifier(identifier) => { + let name = identifier.name.as_str(); + self.record_write(name, false); + } + _ => self.safe = false, + }, + Expression::CallExpression(call) if !call.optional => { + self.safe &= safe_call(call); + if let Expression::StaticMemberExpression(member) = &call.callee { + self.expression(&member.object); + } + for argument in &call.arguments { + match argument.as_expression() { + Some(value) => self.expression(value), + None => self.safe = false, + } + } + } + _ => self.safe = false, + } + } + + fn record_write(&mut self, name: &str, audited: bool) { + self.writes.insert(name.to_owned()); + if audited { + self.audited_writes.insert(name.to_owned()); + } else { + self.other_writes.insert(name.to_owned()); + } + self.safe &= name != self.parameter + && self.writes.len() <= MAX_PROOF_BINDINGS + && self.audited_writes.len() <= MAX_PROOF_BINDINGS + && self.other_writes.len() <= MAX_PROOF_BINDINGS; + } + + fn return_proof(&self, expression: &Expression<'_>) -> Option { + let fields = object_fields(expression)?; + if fields.keys().any(|key| { + !matches!( + key.as_str(), + "type" | "url" | "method" | "status" | "headers" | "body" + ) + }) { + return None; + } + let kind = literal(fields.get("type")?)?; + if !matches!(kind, "pass" | "abort" | "modify" | "respond") { + return None; + } + let Some(body) = fields.get("body") else { + return Some(constant_proof(0)); + }; + if matches!(kind, "pass" | "abort") { + return None; + } + let body = object_fields(body)?; + if body.len() != 2 || literal(body.get("kind")?)? != "text" { + return None; + } + self.string_proof(body.get("data")?) + } + + fn string_proof(&self, expression: &Expression<'_>) -> Option { + match unparenthesized(expression) { + Expression::StringLiteral(value) => Some(constant_proof(value.value.as_str()?.len())), + Expression::Identifier(identifier) => { + let name = identifier.name.as_str(); + let mut proof = self.bindings.get(name)?.clone(); + proof.dependencies.insert(name.to_owned()); + (proof.dependencies.len() <= MAX_PROOF_DEPENDENCIES).then_some(proof) + } + value if original_data(value, &self.parameter) => Some(StringProof { + literal_bytes: 0, + original_input: true, + dependencies: BTreeSet::new(), + }), + Expression::CallExpression(call) if !call.optional && call.arguments.len() == 2 => { + let Expression::StaticMemberExpression(member) = &call.callee else { + return None; + }; + if member.optional || member.property.name != "replaceAll" { + return None; + } + let receiver = self.string_proof(&member.object)?; + if !receiver.original_input { + return None; + } + let search = literal(call.arguments[0].as_expression()?)?; + let replacement = literal(call.arguments[1].as_expression()?)?; + if search.len() != 1 + || replacement.len() != 1 + || !search.is_ascii() + || !replacement.is_ascii() + || replacement == "$" + { + return None; + } + Some(receiver) + } + _ => None, + } + } +} + +// A constant-size syntax check inside the existing counted AST walk. The +// initial proof is never replaced: every successful string version has the +// same byte bound, including aliases and returns before a later assignment. +fn ascii_self_assignment(assignment: &AssignmentExpression<'_>, name: &str) -> bool { + if assignment.operator.as_str() != "=" { + return false; + } + let Expression::CallExpression(call) = &assignment.right else { + return false; + }; + let Expression::StaticMemberExpression(member) = &call.callee else { + return false; + }; + if call.optional + || member.optional + || member.property.name != "replaceAll" + || call.arguments.len() != 2 + || !matches!(&member.object, Expression::Identifier(receiver) if receiver.name == name) + { + return false; + } + let Some(Expression::StringLiteral(search)) = call.arguments[0].as_expression() else { + return false; + }; + let Some(Expression::StringLiteral(replacement)) = call.arguments[1].as_expression() else { + return false; + }; + let (Some(search), Some(replacement)) = (search.value.as_str(), replacement.value.as_str()) + else { + return false; + }; + search.len() == 1 + && search.is_ascii() + && replacement.len() == 1 + && replacement.is_ascii() + && replacement != "$" +} + +fn constant_proof(literal_bytes: usize) -> StringProof { + StringProof { + literal_bytes, + original_input: false, + dependencies: BTreeSet::new(), + } +} + +fn unparenthesized<'a, 'b>(mut expression: &'b Expression<'a>) -> &'b Expression<'a> { + while let Expression::ParenthesizedExpression(value) = expression { + expression = &value.expression; + } + expression +} + +fn literal<'a, 'b>(expression: &'b Expression<'a>) -> Option<&'b str> { + let Expression::StringLiteral(value) = unparenthesized(expression) else { + return None; + }; + value.value.as_str() +} + +fn object_fields<'a, 'b>( + expression: &'b Expression<'a>, +) -> Option>> { + let Expression::ObjectExpression(object) = unparenthesized(expression) else { + return None; + }; + let mut fields = BTreeMap::new(); + for property in &object.properties { + let ObjectPropertyKind::ObjectProperty(property) = property else { + return None; + }; + if property.kind != PropertyKind::Init || property.method || property.computed { + return None; + } + let key = match &property.key { + PropertyKey::StaticIdentifier(key) => key.name.as_str(), + PropertyKey::StringLiteral(key) => key.value.as_str()?, + _ => return None, + }; + if fields.insert(key.to_owned(), &property.value).is_some() { + return None; + } + } + Some(fields) +} + +fn original_data(expression: &Expression<'_>, parameter: &str) -> bool { + fn member<'a, 'b>(expression: &'b Expression<'a>, name: &str) -> Option<&'b Expression<'a>> { + match unparenthesized(expression) { + Expression::StaticMemberExpression(value) + if !value.optional && value.property.name == name => + { + Some(&value.object) + } + Expression::ComputedMemberExpression(value) + if !value.optional && literal(&value.expression) == Some(name) => + { + Some(&value.object) + } + _ => None, + } + } + let Some(body) = member(expression, "data").and_then(|value| member(value, "body")) else { + return false; + }; + matches!(unparenthesized(body), Expression::Identifier(value) if value.name == parameter) +} + +// Audited independently of frontend's allowlist: any future method addition +// remains Maximum until its effects are reviewed. Primitive conversions reject +// objects; no callbacks/accessors are expressible. Array mutators only change +// array indices/length (or fixed-size typed-array elements), never the fresh +// plain input.body record's data property. Member writes are forbidden above. +fn safe_call(call: &CallExpression<'_>) -> bool { + match &call.callee { + Expression::Identifier(identifier) => { + matches!(identifier.name.as_str(), "String" | "Number" | "Boolean") + } + Expression::StaticMemberExpression(member) if !member.optional => { + let name = member.property.name.as_str(); + if let Expression::Identifier(receiver) = &member.object { + match receiver.name.as_str() { + "JSON" => return matches!(name, "parse" | "stringify"), + "Object" => return matches!(name, "keys" | "values" | "entries"), + "Array" => return name == "isArray", + "Number" => return matches!(name, "isFinite" | "isInteger"), + "Math" => { + return matches!( + name, + "abs" | "floor" | "ceil" | "round" | "trunc" | "min" | "max" + ); + } + "Uint8Array" => return name == "from", + _ => {} + } + } + matches!( + name, + "slice" + | "subarray" + | "substring" + | "charAt" + | "at" + | "includes" + | "startsWith" + | "endsWith" + | "indexOf" + | "lastIndexOf" + | "trim" + | "toLowerCase" + | "toUpperCase" + | "split" + | "replace" + | "replaceAll" + | "push" + | "pop" + | "concat" + | "join" + | "reverse" + ) + } + _ => false, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn hint(source: &str) -> OutputBound { + super::super::compile_with_output_bound(source).unwrap().1 + } + + #[test] + fn top_level_ascii_self_assignment_bounds_output_without_changing_emitted_js() { + let source = "function rewrite(input){let payload=input.body.data;payload=payload.replaceAll('q','z');return {type:'modify',body:{kind:'text',data:payload}};}"; + let prepared = super::super::compile_prepared(source).unwrap(); + assert_eq!( + prepared.code, + r#"function rewrite(input){"use strict";__voleTick();let payload=__voleGet(__voleGet(input,"body"),"data");(payload=__voleCall(payload,"replaceAll",["q","z"]));return __voleValue({"type":"modify","body":__voleValue({"kind":"text","data":payload})});}"# + ); + #[cfg(target_vendor = "apple")] + assert!( + prepared.plan.is_some(), + "the independent closed Plan proof now accepts this source" + ); + assert_eq!( + prepared.output_bound, + OutputBound::InputOrConstant { + maximum_literal_bytes: 0 + } + ); + } + + #[test] + fn frozen_guarded_pressure_sources_keep_input_sized_output_and_closed_plans() { + // Freeze the actual pure/request and mixed/response source shapes. + // No guard, witness, assignment or body workload is simplified here. + for source in [ + r#"function rewrite(input) { if (!input.body || input.body.kind !== "text" || typeof input.body.data !== "string" || input.body.data.length !== 65536) { return {type: "abort"}; } let data = input.body.data; data = data.replaceAll("a", "c"); return {type: "modify", headers: [{op: "set", name: "X-Benchmark-Request-JS", values: ["js-v1"]}], body: {kind: "text", data: data}}; }"#, + r#"function rewrite(input) { let found = false; for (let i = 0; i < input.response.headers.length; i++) { if (input.response.headers[i].name === "x-benchmark-native" && input.response.headers[i].value === "native-v1") { found = true; } } if (!found) { return {type: "abort"}; } if (!input.body || input.body.kind !== "text" || typeof input.body.data !== "string" || input.body.data.length !== 65536) { return {type: "abort"}; } let data = input.body.data; data = data.replaceAll("b", "c"); return {type: "modify", headers: [{op: "set", name: "X-Benchmark-JS", values: ["native-v1>js-v1"]}], body: {kind: "text", data: data}}; }"#, + ] { + let prepared = super::super::compile_prepared(source).unwrap(); + #[cfg(target_vendor = "apple")] + assert!( + prepared.plan.is_some(), + "complete guard and tail proof required" + ); + assert_eq!( + prepared.output_bound, + OutputBound::InputOrConstant { + maximum_literal_bytes: 0 + }, + "self assignment lost a complete output bound for {source}" + ); + } + } + + #[test] + fn audited_self_writes_are_generic_in_names_and_decoded_ascii_literals() { + for name in ["result", "_copy9", "$payload", "a"] { + for (search, replacement) in [("q", "z"), ("A", "B"), ("\0", "\x7f"), ("$", "!")] { + let source = format!( + "function rewrite(input){{let {name}=input.body.data;{name}={name}.replaceAll({},{});return {{type:'modify',body:{{kind:'text',data:{name}}}}};}}", + serde_json::to_string(search).unwrap(), + serde_json::to_string(replacement).unwrap(), + ); + let prepared = super::super::compile_prepared(&source).unwrap(); + #[cfg(target_vendor = "apple")] + assert!(prepared.plan.is_some()); + assert_eq!( + prepared.output_bound, + OutputBound::InputOrConstant { + maximum_literal_bytes: 0 + } + ); + } + } + } + + #[test] + fn all_string_versions_aliases_and_early_returns_keep_the_initial_bound() { + for (index, source) in [ + "function rewrite(input){let s=input.body.data;const old=s;s=s.replaceAll('a','b');s=s.replaceAll('b','c');return {type:'modify',body:{kind:'text',data:old}};}", + "function rewrite(input){let s=input.body.data;s=s.replaceAll('a','c');const after=s;return {type:'modify',body:{kind:'text',data:after}};}", + "function rewrite(input){let s=input.body.data;if(input.phase==='request')return {type:'modify',body:{kind:'text',data:s}};s=s.replaceAll('a','c');return {type:'modify',body:{kind:'text',data:s}};}", + "function rewrite(input){let s=input.body.data;return {type:'modify',body:{kind:'text',data:s}};s=s.replaceAll('a','c');}", + "function rewrite(input){let a=input.body.data;a=a.replaceAll('a','b');let s=a;s=s.replaceAll('b','c');return {type:'modify',body:{kind:'text',data:s}};}", + "function rewrite(input){const initial=input.body.data;let s=initial;s=s.replaceAll('a','c');return {type:'modify',body:{kind:'text',data:s}};}", + ] + .into_iter() + .enumerate() + { + let prepared = super::super::compile_prepared(source).unwrap(); + #[cfg(target_vendor = "apple")] + assert_eq!( + prepared.plan.is_some(), + !matches!(index, 2 | 3), + "arbitrary branches and statements after return remain unproved" + ); + assert_eq!( + prepared.output_bound, + OutputBound::InputOrConstant { + maximum_literal_bytes: 0 + }, + "{source}" + ); + } + // ASCII substitution preserves UTF-8 bytes even in a Unicode/NUL + // literal. The proof retains the full initial bound at every return. + assert_eq!( + hint( + "function rewrite(input){let s='é😀\\u0000';s=s.replaceAll('\\u0000','!');return {type:'modify',body:{kind:'text',data:s}};}" + ), + OutputBound::InputOrConstant { + maximum_literal_bytes: 7 + } + ); + } + + #[test] + fn an_audited_write_never_hides_other_contexts_shapes_or_effects() { + for mutation in [ + "s='EXPANDED';", + "s+='EXPANDED';", + "s++;", + "if(false)s=s.replaceAll('b','c');", + "while(false){s=s.replaceAll('b','c');}", + "do{s=s.replaceAll('b','c');}while(false);", + "for(s=s.replaceAll('b','c');false;){}", + "for(let i=0;i<0;s=s.replaceAll('b','c')){}", + "{s=s.replaceAll('b','c');}", + "false&&(s=s.replaceAll('b','c'));", + "false?(s=s.replaceAll('b','c')):s;", + "String(s=s.replaceAll('b','c'));", + "(s=s.replaceAll('b','c'));", + "s=input.body.data.replaceAll('b','c');", + "s=s.replaceAll('b','c').replaceAll('c','d');", + "s=s.replaceAll('b','cc');", + "s=s.replaceAll('bb','cc');", + "s=s.replaceAll('é','c');", + "s=s.replaceAll('b','界');", + "s=s.replaceAll('b','$');", + "s=s.replaceAll('b','$&');", + "s=s.replaceAll('','c');", + "let replacement='c';s=s.replaceAll('b',replacement);", + "input.body.data='EXPANDED';", + "if(false)input.body['data']='EXPANDED';", + "const body=input.body;body.data='EXPANDED';", + "{let s='EXPANDED';}", + ] { + let source = format!( + "function rewrite(input){{let s=input.body.data;s=s.replaceAll('a','b');{mutation}return {{type:'modify',body:{{kind:'text',data:s}}}};}}" + ); + assert_eq!(hint(&source), OutputBound::Maximum, "{mutation}"); + } + } + + #[test] + fn audited_locals_keep_all_initial_dependencies_and_unreachable_writes() { + for source in [ + "function rewrite(input){let a=input.body.data;a='EXPANDED';let s=a;s=s.replaceAll('x','y');return {type:'modify',body:{kind:'text',data:s}};}", + "function rewrite(input){let a=input.body.data;let s=a;a='EXPANDED';s=s.replaceAll('x','y');return {type:'modify',body:{kind:'text',data:s}};}", + "function rewrite(input){let a=input.body.data;let s=a;a=a.replaceAll('a','b');a='EXPANDED';s=s.replaceAll('x','y');return {type:'modify',body:{kind:'text',data:s}};}", + "function rewrite(input){let s=input.body.data;let alias=s;s=s.replaceAll('a','b');alias='EXPANDED';return {type:'modify',body:{kind:'text',data:alias}};}", + "function rewrite(input){let s=input.body.data;s=s.replaceAll('a','b');return {type:'modify',body:{kind:'text',data:s}};s='EXPANDED';}", + "function rewrite(input){let s;s=s.replaceAll('a','b');return {type:'modify',body:{kind:'text',data:s}};}", + "function rewrite(input){let s=3;s=s.replaceAll('a','b');return {type:'modify',body:{kind:'text',data:s}};}", + ] { + assert_eq!(hint(source), OutputBound::Maximum, "{source}"); + } + } + + #[test] + fn audited_writes_cannot_bypass_binding_node_or_dependency_caps() { + let mut bindings = String::from("function rewrite(input){let s=input.body.data;"); + for index in 0..MAX_PROOF_BINDINGS { + bindings.push_str(&format!("let unused{index};")); + } + bindings + .push_str("s=s.replaceAll('a','c');return {type:'modify',body:{kind:'text',data:s}};}"); + assert_eq!(hint(&bindings), OutputBound::Maximum); + + let mut nodes = String::from( + "function rewrite(input){let s=input.body.data;s=s.replaceAll('a','c');return {type:'modify',body:{kind:'text',data:s}};", + ); + for _ in 0..=MAX_PROOF_NODES / 2 { + nodes.push_str("0;"); + } + nodes.push('}'); + assert_eq!(hint(&nodes), OutputBound::Maximum); + + let mut dependencies = String::from("function rewrite(input){let seed=input.body.data;"); + let mut previous = "seed".to_owned(); + for index in 0..=MAX_PROOF_DEPENDENCIES { + let name = format!("alias{index}"); + dependencies.push_str(&format!("let {name}={previous};")); + previous = name; + } + dependencies.push_str(&format!("{previous}={previous}.replaceAll('a','c');return {{type:'modify',body:{{kind:'text',data:{previous}}}}};}}")); + assert_eq!(hint(&dependencies), OutputBound::Maximum); + } + + #[test] + fn readonly_aliases_are_independent_of_local_names_and_ascii_values() { + for name in ["result", "_copy9", "$payload", "a"] { + for (search, replacement) in [("q", "z"), ("A", "B"), ("\0", "\x7f"), ("$", "!")] { + let source = format!( + "function rewrite(input){{const original=input['body']['data'];let {name}=original.replaceAll({},{});return {{type:'modify',body:{{kind:'text',data:{name}}}}};}}", + serde_json::to_string(search).unwrap(), + serde_json::to_string(replacement).unwrap(), + ); + assert_eq!( + hint(&source), + OutputBound::InputOrConstant { + maximum_literal_bytes: 0 + } + ); + } + } + } + + #[test] + fn fresh_return_paths_join_decoded_utf8_literal_bounds() { + let text = "é😀\0"; + let source = format!( + "function rewrite(input){{if(input.phase==='request')return {{type:'pass'}};if(input.response.status===201)return {{type:'modify',body:{{kind:'text',data:'cat'}}}};return {{type:'respond',status:200,body:{{kind:'text',data:{}}}}};}}", + serde_json::to_string(text).unwrap() + ); + assert_eq!( + hint(&source), + OutputBound::InputOrConstant { + maximum_literal_bytes: text.len() + } + ); + let code = crate::http_processing::scripts::validate_source(&source).unwrap(); + assert_eq!(code.maximum_output_bytes(0), 7); + assert_eq!(code.maximum_output_bytes(4096), 4096); + } + + #[test] + fn read_only_metadata_loops_and_array_mutators_do_not_change_plain_body_data() { + let source = "function rewrite(input){let found=false;for(let index=0;index, + #[cfg_attr(not(feature = "inbound-http"), allow(dead_code))] + pub(crate) output_bound: OutputBound, + #[cfg(all(feature = "inbound-http", target_vendor = "apple"))] + plan: Option>, +} + +impl CompiledSource { + /// Only a complete proof for this actual business declaration can remove + /// eager JSC preparation. Source acceptance and platform availability are + /// separate; unknown source, body modes and metadata keep the JSC path. + pub(crate) fn needs_jsc_for_business( + &self, + body: super::script_config::BodyMode, + phase: super::rules::Phase, + ) -> bool { + #[cfg(all(feature = "inbound-http", target_vendor = "apple"))] + { + body != super::script_config::BodyMode::Text + || !self + .plan + .as_ref() + .is_some_and(|plan| plan.covers_business_text_phase(phase)) + } + #[cfg(not(all(feature = "inbound-http", target_vendor = "apple")))] + { + let _ = (self, body, phase); + true + } + } +} + +#[cfg(feature = "inbound-http")] +impl CompiledSource { + // This proof bounds the Rust result; independent API/input owners remain. + // This hint + // never pays for API input/view copies or a retained engine backing. + pub(crate) fn maximum_output_bytes(&self, input_bytes: usize) -> usize { + let maximum = super::body_budget::MAX_BODY; + match self.output_bound { + OutputBound::Maximum => maximum, + OutputBound::InputOrConstant { + maximum_literal_bytes, + } => input_bytes.max(maximum_literal_bytes).min(maximum), + } + } +} + +pub(crate) fn validate_source(source: &str) -> io::Result { + #[cfg(feature = "inbound-http")] + { + let prepared = frontend::compile_prepared(source)?; + Ok(CompiledSource { + code: prepared.code.into(), + output_bound: prepared.output_bound, + #[cfg(target_vendor = "apple")] + plan: prepared.plan.map(Arc::new), + }) + } + #[cfg(not(feature = "inbound-http"))] + { + let _ = source; + Err(unsupported()) + } +} + +#[cfg(feature = "inbound-http")] +#[derive(Clone, Copy)] +pub(crate) enum Backend<'a> { + Jsc(&'a CompiledSource), + #[cfg(target_vendor = "apple")] + Plan(&'a static_literal_plan::Plan), +} +#[cfg(feature = "inbound-http")] +impl CompiledSource { + pub(crate) fn backend( + &self, + metadata: &serde_json::Value, + input: Option>, + ) -> Backend<'_> { + #[cfg(target_vendor = "apple")] + if let Some(plan) = &self.plan { + if plan.accepts_input(metadata, input) { + super::diagnostics::increment(super::diagnostics::Counter::PlanSelected); + return Backend::Plan(plan); + } + super::diagnostics::increment(super::diagnostics::Counter::PlanInputFallback); + } else { + super::diagnostics::increment(super::diagnostics::Counter::PlanAstFallback); + } + #[cfg(not(target_vendor = "apple"))] + let _ = (metadata, input); + super::diagnostics::increment(super::diagnostics::Counter::JscSelected); + Backend::Jsc(self) + } +} +#[cfg(feature = "inbound-http")] +impl Backend<'_> { + pub(crate) fn is_plan(self) -> bool { + match self { + Self::Jsc(_) => false, + #[cfg(target_vendor = "apple")] + Self::Plan(_) => true, + } + } + pub(crate) fn output_bound(self, input: usize) -> usize { + match self { + Self::Jsc(program) => program.maximum_output_bytes(input), + #[cfg(target_vendor = "apple")] + Self::Plan(plan) => plan + .maximum_output_bytes(input) + .unwrap_or(super::body_budget::MAX_BODY), + } + } +} +#[cfg(feature = "inbound-http")] +#[derive(Clone, Copy)] +#[cfg_attr(not(target_vendor = "apple"), allow(dead_code))] +enum InvocationInput<'a> { + #[cfg_attr(not(test), allow(dead_code))] + JscOnly(Option<&'a [u8]>), + Borrowed(Option>), +} +#[cfg(feature = "inbound-http")] +impl<'a> InvocationInput<'a> { + #[cfg(target_vendor = "apple")] + fn bytes(self) -> Option<&'a [u8]> { + match self { + Self::JscOnly(bytes) => bytes, + Self::Borrowed(body) => body.map(|body| body.as_bytes()), + } + } + #[cfg(target_vendor = "apple")] + fn witness(self) -> Option> { + match self { + Self::JscOnly(_) => None, + Self::Borrowed(body) => body, + } + } +} + +fn unsupported() -> io::Error { + io::Error::new( + io::ErrorKind::Unsupported, + "HTTP JavaScript execution backend is unavailable", + ) +} + +pub(crate) fn ensure_available() -> io::Result<()> { + if cfg!(all(feature = "inbound-http", target_vendor = "apple")) { + Ok(()) + } else { + Err(unsupported()) + } +} + +/// Actual resource preparation only; source validation and capability checks +/// must not call this. The process retains only successful initialization state. +pub(crate) fn prepare_platform( + cancellation: &tokio_util::sync::CancellationToken, +) -> io::Result<()> { + ensure_available()?; + #[cfg(all(feature = "inbound-http", target_vendor = "apple"))] + { + use super::diagnostics::{Counter, increment}; + static INITIALIZATION: platform_init::Initialization = platform_init::Initialization::new(); + if cancellation.is_cancelled() { + return Err(io::ErrorKind::Interrupted.into()); + } + increment(Counter::PlatformWarmupRequested); + #[cfg(test)] + PLATFORM_PREPARE_REQUESTS.with(|count| count.set(count.get() + 1)); + INITIALIZATION.ensure(cancellation, || { + // Count thread-creation errors and unwinding as failed attempts too. + struct Attempt(bool); + impl Drop for Attempt { + fn drop(&mut self) { + if !self.0 { + increment(Counter::PlatformWarmupFailed); + } + } + } + increment(Counter::PlatformWarmupStarted); + let mut attempt = Attempt(false); + let result = + run_on_scoped_thread_named("vole-http-js-init", apple::initialize_platform); + if result.is_ok() { + increment(Counter::PlatformWarmupSucceeded); + attempt.0 = true; + } + result + }) + } + #[cfg(not(all(feature = "inbound-http", target_vendor = "apple")))] + { + let _ = cancellation; + Err(unsupported()) + } +} + +#[cfg(all(test, feature = "inbound-http", target_vendor = "apple"))] +std::thread_local! { + // A current-thread prepare-path witness; independent of process-global + // diagnostic counters and other tests' initialization order. + static PLATFORM_PREPARE_REQUESTS: std::cell::Cell = const { std::cell::Cell::new(0) }; +} + +#[cfg(all(test, feature = "inbound-http", target_vendor = "apple"))] +pub(crate) fn platform_prepare_requests_for_test() -> usize { + PLATFORM_PREPARE_REQUESTS.with(std::cell::Cell::get) +} + +#[cfg(all(test, feature = "inbound-http"))] +pub(crate) async fn evaluate( + program: &CompiledSource, + metadata: &serde_json::Value, + input_body: Option<&[u8]>, + output_body: &mut super::body_budget::BudgetedBytes, + cancellation: &tokio_util::sync::CancellationToken, +) -> io::Result { + evaluate_until( + program, + metadata, + input_body, + output_body, + None, + cancellation, + std::time::Instant::now() + std::time::Duration::from_millis(100), + ) + .await +} + +// Explicit JSC-only reference seam for existing direct-adapter tests/validation. +#[cfg(feature = "inbound-http")] +#[cfg_attr(not(test), allow(dead_code))] +pub(crate) async fn evaluate_until( + program: &CompiledSource, + metadata: &serde_json::Value, + input_body: Option<&[u8]>, + output_body: &mut super::body_budget::BudgetedBytes, + bridge_workspace: Option<&super::body_budget::Reservation>, + cancellation: &tokio_util::sync::CancellationToken, + phase_deadline: std::time::Instant, +) -> io::Result { + evaluate_internal( + Backend::Jsc(program), + metadata, + InvocationInput::JscOnly(input_body), + output_body, + bridge_workspace, + cancellation, + phase_deadline, + ) + .await +} + +#[cfg(feature = "inbound-http")] +pub(crate) async fn evaluate_backend_until( + backend: Backend<'_>, + metadata: &serde_json::Value, + input_body: Option>, + output_body: &mut super::body_budget::BudgetedBytes, + bridge_workspace: Option<&super::body_budget::Reservation>, + cancellation: &tokio_util::sync::CancellationToken, + phase_deadline: std::time::Instant, +) -> io::Result { + evaluate_internal( + backend, + metadata, + InvocationInput::Borrowed(input_body), + output_body, + bridge_workspace, + cancellation, + phase_deadline, + ) + .await +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +pub(crate) struct InvocationLane { + _permit: tokio::sync::SemaphorePermit<'static>, + deadline: std::time::Instant, +} +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +impl InvocationLane { + // Only cancellation and the original phase bound enter this future. No + // mutable message/output is held by the lane acquisition helper. + pub(crate) async fn acquire( + cancellation: &tokio_util::sync::CancellationToken, + phase_deadline: std::time::Instant, + ) -> io::Result { + // This is an execution lane, not a limit on HTTP connections. Waiting + // inherits this invocation's deadline and never runs on a TUN callback. + let started = std::time::Instant::now(); + let mut queue = super::diagnostics::QueueGuard::new(); + let deadline = phase_deadline.min(started + std::time::Duration::from_millis(100)); + let mut lane_error = |kind, cause| { + queue.failed(kind); + let elapsed_us = started.elapsed().as_micros().min(u128::from(u32::MAX)); + let remaining_us = deadline + .saturating_duration_since(started) + .as_micros() + .min(u128::from(u32::MAX)); + io::Error::new( + kind, + format!( + "js f=lane-acquire c={cause} p=queue t=0 e={elapsed_us} pe={elapsed_us} o=lane-acquire k={cause} a={elapsed_us} r={remaining_us} stage_us=0,0,0,0,0,0", + ), + ) + }; + if std::time::Instant::now() >= deadline { + return Err(lane_error(io::ErrorKind::TimedOut, "deadline")); + } + let permit = tokio::select! { + biased; + () = cancellation.cancelled() => return Err(lane_error(io::ErrorKind::Interrupted, "cancel")), + permit = tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), EXECUTION_LANE.acquire()) => { + permit.map_err(|_| lane_error(io::ErrorKind::TimedOut, "deadline"))? + .map_err(|_| lane_error(io::ErrorKind::BrokenPipe, "closed"))? + } + }; + queue.acquired(); + Ok(Self { + _permit: permit, + deadline, + }) + } +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +pub(crate) fn evaluate_plan_in_lane( + backend: Backend<'_>, + metadata: &serde_json::Value, + input_body: Option>, + output_body: &mut super::body_budget::BudgetedBytes, + cancellation: &tokio_util::sync::CancellationToken, + lane: InvocationLane, +) -> io::Result { + if !backend.is_plan() { + return Err(io::ErrorKind::InvalidInput.into()); + } + evaluate_acquired( + backend, + metadata, + InvocationInput::Borrowed(input_body), + output_body, + None, + cancellation, + lane, + ) +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +fn evaluate_acquired( + backend: Backend<'_>, + metadata: &serde_json::Value, + input_body: InvocationInput<'_>, + output_body: &mut super::body_budget::BudgetedBytes, + bridge_workspace: Option<&super::body_budget::Reservation>, + cancellation: &tokio_util::sync::CancellationToken, + lane: InvocationLane, +) -> io::Result { + let deadline = lane.deadline; + let _lane = lane; // Keep the exact permit through real return/unwind/join. + let mut operation = || match backend { + Backend::Jsc(program) => { + super::diagnostics::increment(super::diagnostics::Counter::EvaluationEntered); + let result = apple::evaluate( + program, + metadata, + input_body.bytes(), + output_body, + bridge_workspace, + cancellation, + deadline, + ); + let counter = match result.as_ref().map_err(io::Error::kind) { + Ok(_) => super::diagnostics::Counter::EvaluationSucceeded, + Err(io::ErrorKind::TimedOut) => super::diagnostics::Counter::EvaluationTimedOut, + Err(io::ErrorKind::Interrupted) => super::diagnostics::Counter::EvaluationCancelled, + Err(_) => super::diagnostics::Counter::EvaluationFailed, + }; + super::diagnostics::increment(counter); + result + } + Backend::Plan(plan) => { + super::diagnostics::increment(super::diagnostics::Counter::PlanEntered); + let result = match plan.try_execute( + metadata, + input_body.witness(), + output_body, + cancellation, + deadline, + ) { + Some(attempt) => { + tracing::trace!(target: "vole::http_processing::script", backend = attempt.backend, ticks = attempt.ticks, allocation_work = attempt.allocation_work, "HTTP script backend completed"); + attempt.result + } + // Selection was already fixed before any output admission. + // A failed invariant is a rollback, never another backend. + None => Err(io::ErrorKind::InvalidInput.into()), + }; + let counter = match result.as_ref().map_err(io::Error::kind) { + Ok(_) => super::diagnostics::Counter::PlanSucceeded, + Err(io::ErrorKind::TimedOut) => super::diagnostics::Counter::PlanTimedOut, + Err(io::ErrorKind::Interrupted) => super::diagnostics::Counter::PlanCancelled, + Err(_) => super::diagnostics::Counter::PlanFailed, + }; + super::diagnostics::increment(counter); + result + } + }; + if tokio::runtime::Handle::current().runtime_flavor() + == tokio::runtime::RuntimeFlavor::MultiThread + { + if backend.is_plan() { + run_plan_inline(operation) + } else { + // JSC still lives only on its fresh scoped owner, with its + // original QoS request, context/TLS teardown and actual join. + tokio::task::block_in_place(|| run_on_script_thread(OwnerBackend::Jsc, operation)) + } + } else { + operation() + } +} + +#[cfg(feature = "inbound-http")] +async fn evaluate_internal( + backend: Backend<'_>, + metadata: &serde_json::Value, + input_body: InvocationInput<'_>, + output_body: &mut super::body_budget::BudgetedBytes, + bridge_workspace: Option<&super::body_budget::Reservation>, + cancellation: &tokio_util::sync::CancellationToken, + phase_deadline: std::time::Instant, +) -> io::Result { + #[cfg(target_vendor = "apple")] + { + let lane = InvocationLane::acquire(cancellation, phase_deadline).await?; + evaluate_acquired( + backend, + metadata, + input_body, + output_body, + bridge_workspace, + cancellation, + lane, + ) + } + #[cfg(not(target_vendor = "apple"))] + { + let _ = ( + backend, + metadata, + input_body, + output_body, + bridge_workspace, + cancellation, + phase_deadline, + ); + Err(unsupported()) + } +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +#[derive(Clone, Copy)] +enum OwnerBackend { + Jsc, + #[cfg_attr( + not(any(test, all(feature = "http-diagnostics", target_os = "tvos"))), + allow(dead_code) + )] + Plan, +} + +#[cfg(all( + feature = "inbound-http", + target_vendor = "apple", + any(test, all(feature = "http-diagnostics", target_os = "tvos")) +))] +fn run_on_scoped_thread( + operation: impl FnOnce() -> io::Result + Send, +) -> io::Result { + run_on_script_thread(OwnerBackend::Jsc, operation) +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +fn run_on_script_thread( + owner: OwnerBackend, + operation: impl FnOnce() -> io::Result + Send, +) -> io::Result { + #[cfg(feature = "http-diagnostics")] + let started = std::sync::atomic::AtomicBool::new(false); + #[cfg(feature = "http-diagnostics")] + struct ParentWall<'a> { + begin: std::time::Instant, + started: &'a std::sync::atomic::AtomicBool, + owner: OwnerBackend, + } + #[cfg(feature = "http-diagnostics")] + impl Drop for ParentWall<'_> { + fn drop(&mut self) { + use super::diagnostics::{Counter, Timing, increment, timing}; + let elapsed = self.begin.elapsed().as_micros(); + timing(Timing::ScopedOwner, elapsed); + timing( + match self.owner { + OwnerBackend::Jsc => Timing::JscScopedOwner, + OwnerBackend::Plan => Timing::PlanScopedOwner, + }, + elapsed, + ); + if self.started.load(std::sync::atomic::Ordering::Acquire) { + increment(match self.owner { + OwnerBackend::Jsc => Counter::JscOwnerJoined, + OwnerBackend::Plan => Counter::PlanOwnerJoined, + }); + } + } + } + // This guard encloses named-helper return/unwind and therefore actual + // thread/TLS join. A failed spawn never claims an owner started or joined. + #[cfg(feature = "http-diagnostics")] + let _parent_wall = ParentWall { + begin: std::time::Instant::now(), + started: &started, + owner, + }; + #[cfg(feature = "http-diagnostics")] + let started = &started; + let name = match owner { + OwnerBackend::Jsc => "vole-http-js", + OwnerBackend::Plan => "vole-http-plan", + }; + run_on_scoped_thread_named(name, move || { + #[cfg(feature = "http-diagnostics")] + { + started.store(true, std::sync::atomic::Ordering::Release); + super::diagnostics::increment(match owner { + OwnerBackend::Jsc => super::diagnostics::Counter::JscOwnerStarted, + OwnerBackend::Plan => super::diagnostics::Counter::PlanOwnerStarted, + }); + } + // Same public QoS request and real scoped owner for both backends. + scoped_qos::run(operation) + }) +} + +#[cfg(all( + feature = "inbound-http", + feature = "http-diagnostics", + target_vendor = "apple" +))] +pub(crate) fn scoped_owner_qos_snapshot() -> serde_json::Value { + scoped_qos::snapshot() +} + +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +fn run_on_scoped_thread_named( + name: &str, + operation: impl FnOnce() -> io::Result + Send, +) -> io::Result { + // Keep backend state on its owner and join before releasing borrowed + // buffers or the execution lane. Capture tracing in the blocking parent. + let dispatch = tracing::dispatcher::get_default(Clone::clone); + let span = tracing::Span::current(); + std::thread::scope(|scope| { + let worker = std::thread::Builder::new() + .name(name.into()) + .spawn_scoped(scope, move || { + tracing::dispatcher::with_default(&dispatch, || span.in_scope(operation)) + })?; + match worker.join() { + Ok(result) => result, + Err(payload) => std::panic::resume_unwind(payload), + } + }) +} + +#[cfg(all(test, feature = "inbound-http", target_vendor = "apple"))] +mod borrowed_input_owner_tests; + +/// Same capability check for the Message yield and synchronous Plan policy. +/// A query only: no worker/CPU/affinity override or availability guarantee. +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +pub(crate) fn plan_can_run_direct() -> bool { + tokio::runtime::Handle::try_current().is_ok_and(|handle| { + handle.runtime_flavor() == tokio::runtime::RuntimeFlavor::MultiThread + && handle.metrics().num_workers() > 1 + }) +} + +/// Multi-thread Plan only, on the same caller stack and held lane/borrows. +/// Multiple configured workers allow direct execution; one retains BIP. +/// No JSC object, scoped owner, QoS setter, detached Future or new deadline. +#[cfg(all(feature = "inbound-http", target_vendor = "apple"))] +fn run_plan_inline(operation: impl FnOnce() -> io::Result) -> io::Result { + #[cfg(feature = "http-diagnostics")] + struct DispatchWall(std::time::Instant); + #[cfg(feature = "http-diagnostics")] + impl Drop for DispatchWall { + fn drop(&mut self) { + super::diagnostics::timing( + super::diagnostics::Timing::PlanInlineDispatchWall, + self.0.elapsed().as_micros(), + ); + } + } + #[cfg(feature = "http-diagnostics")] + struct Operation { + clock: scoped_qos::OperationClock, + } + #[cfg(feature = "http-diagnostics")] + impl Operation { + fn enter() -> Self { + super::diagnostics::increment(super::diagnostics::Counter::PlanInlineEntered); + Self { + clock: scoped_qos::OperationClock::start(), + } + } + } + #[cfg(feature = "http-diagnostics")] + impl Drop for Operation { + fn drop(&mut self) { + use super::diagnostics::{Counter, Timing, increment, timing}; + let (wall, cpu) = self.clock.elapsed(); + timing(Timing::PlanInlineWall, wall); + if let Some(cpu) = cpu { + timing(Timing::PlanInlineThreadCpu, u128::from(cpu)); + } else { + increment(Counter::PlanInlineCpuUnavailable); + } + increment(if std::thread::panicking() { + Counter::PlanInlinePanicked + } else { + Counter::PlanInlineReturned + }); + } + } + #[cfg(feature = "http-diagnostics")] + let _dispatch = DispatchWall(std::time::Instant::now()); + let operation = || { + #[cfg(feature = "http-diagnostics")] + let _operation = Operation::enter(); + operation() + }; + if plan_can_run_direct() { + operation() + } else { + tokio::task::block_in_place(operation) + } +} + +#[cfg(all(test, feature = "inbound-http", target_vendor = "apple"))] +mod multi_worker_plan_tests; diff --git a/src/http_processing/scripts/multi_worker_plan_tests.rs b/src/http_processing/scripts/multi_worker_plan_tests.rs new file mode 100644 index 0000000..08458d1 --- /dev/null +++ b/src/http_processing/scripts/multi_worker_plan_tests.rs @@ -0,0 +1,298 @@ +//! Actual Plan/owner/lane probes; worker_threads(1/2) are only test fixtures. +use super::*; +use crate::http_processing::{ + body::Entity, + body_budget::{Budget, BudgetedBytes}, +}; +use std::{ + future::Future, + sync::{Mutex, mpsc}, + time::{Duration, Instant}, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + runtime::{Builder, Runtime}, +}; +use tokio_util::sync::CancellationToken; + +const N: usize = 65536; +const CLEANUP: Duration = Duration::from_secs(5); +#[derive(Clone, Copy, Debug)] +struct Seen { + error: Option, + length: usize, + correct: bool, +} +struct Release(mpsc::SyncSender<()>); +impl Release { + fn now(&self) { + let _ = self.0.try_send(()); + } +} +impl Drop for Release { + fn drop(&mut self) { + self.now(); + } +} +struct Probe { + task: tokio::task::JoinHandle<()>, + entered: mpsc::Receiver, + waiting: mpsc::Receiver<()>, + release: Release, + cancel: CancellationToken, + seen: Arc>>, + budget: Budget, + last: Option, + cost: usize, +} +fn runtime(workers: usize) -> Runtime { + let runtime = Builder::new_multi_thread() + .worker_threads(workers) + .enable_all() + .build() + .unwrap(); + assert_eq!( + runtime.handle().runtime_flavor(), + tokio::runtime::RuntimeFlavor::MultiThread + ); + assert_eq!(runtime.handle().metrics().num_workers(), workers); + runtime +} +impl Probe { + fn spawn(runtime: &Runtime, panic_after_release: bool) -> Self { + let budget = Budget::default(); + let source = Entity::identity(BudgetedBytes::copy(&budget, &vec![b'a'; N]).unwrap()); + let last = Some(source.wire().slice(0..1)); + let mut output = BudgetedBytes::new_fixed_output(&budget, N).unwrap(); + let cost = BudgetedBytes::allocation_cost(N).unwrap(); + assert_eq!(budget.used(), 2 * cost); + let (entered_tx, entered) = mpsc::channel(); + let (waiting_tx, waiting) = mpsc::channel(); + let (release_tx, release_rx) = mpsc::sync_channel(1); + let cancel = CancellationToken::new(); + let token = cancel.clone(); + let seen = Arc::new(Mutex::new(None)); + let observed = seen.clone(); + let workers = runtime.handle().metrics().num_workers(); + let task = runtime.spawn(async move { + assert_eq!(tokio::runtime::Handle::current().metrics().num_workers(), workers); + let plan = static_literal_plan::compile( + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('a','b').replaceAll('b','c')}};}" + ).unwrap(); + let acquire = InvocationLane::acquire(&token, Instant::now() + Duration::from_secs(1)); + tokio::pin!(acquire); + let mut waiting_tx = Some(waiting_tx); + let lane = std::future::poll_fn(|cx| { + let result = acquire.as_mut().poll(cx); + if result.is_pending() + && let Some(sender) = waiting_tx.take() + { + let _ = sender.send(()); + } + result + }) + .await + .unwrap(); + let deadline = lane.deadline; // Original 100ms limit, never replaced by CLEANUP. + let _lane = lane; + let mut entered_tx = Some(entered_tx); + let mut hook = move |filled| { + if filled == 256 { + if let Some(sender) = entered_tx.take() { let _ = sender.send(deadline); } + assert!(release_rx.recv_timeout(CLEANUP).is_ok(), "cleanup watchdog released no gate"); + assert!(!panic_after_release, "fixed actual Plan unwind"); + } + }; + let attempt = run_plan_inline(|| { + plan.try_execute_for_validation( + &serde_json::json!({"body":{"kind":"text"}}), + source.borrowed_body(), &mut output, &token, deadline, + static_literal_plan::Validation { force_dag: false, after_chunk: Some(&mut hook) }, + ).ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + }).unwrap(); + let expected = serde_json::json!({"type":"modify","body":{"kind":"text"}}); + let correct = attempt.result.as_ref().is_ok_and(|value| value == &expected) + && output.as_ref().len() == N && output.as_ref().iter().all(|byte| *byte == b'c'); + *observed.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(Seen { + error: attempt.result.as_ref().err().map(io::Error::kind), + length: output.as_ref().len(), correct, + }); + // Source/output/Workspace and the actual permit end with this poll. + }); + Self { + task, + entered, + waiting, + release: Release(release_tx), + cancel, + seen, + budget, + last, + cost, + } + } + fn seen(&self) -> Option { + *self + .seen + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } + fn held(&self) -> bool { + !self.task.is_finished() && self.seen().is_none() + && self.budget.used() > 2 * self.cost // Actual Plan Workspace is still owned. + && EXECUTION_LANE.try_acquire().is_err() + } + fn refunded(&mut self) { + assert!(self.task.is_finished()); + assert_eq!( + self.budget.used(), + self.cost, + "actual last source slice retains its charge" + ); + assert_eq!(self.last.as_ref().unwrap().as_ref(), b"a"); + drop(self.last.take()); + assert_eq!(self.budget.used(), 0); + } +} + +fn check_plan_progress(workers: usize) { + let runtime = runtime(workers); + let (mut reader, mut writer) = tokio::io::duplex(1); + let (io_tx, io_rx) = mpsc::channel(); + let (start_tx, start_rx) = tokio::sync::oneshot::channel(); + let read = runtime.spawn(async move { + let mut value = [0; 4]; + reader.read_exact(&mut value).await.unwrap(); + let _ = io_tx.send(value); + }); + let write = runtime.spawn(async move { + start_rx.await.unwrap(); + tokio::time::sleep(Duration::from_millis(1)).await; + writer.write_all(b"flow").await.unwrap(); + }); + let mut first = Probe::spawn(&runtime, false); + let deadline = first.entered.recv_timeout(CLEANUP).unwrap(); + let mut second = Probe::spawn(&runtime, false); + // This gate is ready only after the second real task acquires the same lane. + second.release.now(); + let waiting = second.waiting.recv_timeout(CLEANUP).is_ok(); + let _ = start_tx.send(()); + let progress = io_rx.recv_timeout(deadline.saturating_duration_since(Instant::now())); + let lane_and_owners = first.held(); + let second_blocked = second.entered.try_recv().is_err() + && second.seen().is_none() + && second.budget.used() == 2 * second.cost; + first.release.now(); // Always release before assertions or runtime joins. + let (a, b, r, w) = runtime.block_on(async { + ( + (&mut first.task).await, + (&mut second.task).await, + read.await, + write.await, + ) + }); + drop(runtime); // Normal drop joins workers, not shutdown_timeout/background. + assert!(waiting && lane_and_owners && second_blocked); + assert_eq!(progress.unwrap(), *b"flow"); + assert!(a.is_ok() && b.is_ok() && r.is_ok() && w.is_ok()); + assert!(first.seen().unwrap().correct && second.seen().unwrap().correct); + first.refunded(); + second.refunded(); +} + +#[test] +fn multi_worker_plan_keeps_same_lane_and_allows_real_timer_and_duplex_progress() { + check_plan_progress(2); +} + +#[test] +fn single_worker_plan_bip_keeps_same_lane_and_allows_real_timer_and_duplex_progress() { + check_plan_progress(1); +} + +#[test] +fn multi_worker_plan_abort_cancel_and_panic_keep_real_owners_until_completion() { + for (abort, cancel, panic) in [ + (true, false, false), + (true, true, false), + (false, false, true), + ] { + let runtime = runtime(2); + let mut probe = Probe::spawn(&runtime, panic); + let entered = probe.entered.recv_timeout(CLEANUP).is_ok(); + if abort { + probe.task.abort(); + } + if cancel { + probe.cancel.cancel(); + } + let held = entered && probe.held(); + probe.release.now(); + let result = runtime.block_on(&mut probe.task); + drop(runtime); + assert!(held); + if panic { + assert!(result.as_ref().is_err_and(tokio::task::JoinError::is_panic)); + assert!(probe.seen().is_none()); + } else { + assert!( + result.is_ok() + || result + .as_ref() + .is_err_and(tokio::task::JoinError::is_cancelled) + ); + let actual = probe.seen().unwrap(); + if cancel { + assert_eq!(actual.error, Some(io::ErrorKind::Interrupted)); + assert_eq!( + actual.length, 0, + "partial scratch is not a committed result" + ); + } else { + assert!(actual.correct); + } + } + probe.refunded(); + } +} + +#[test] +fn multi_worker_plan_runtime_drop_is_a_real_owner_and_lane_barrier() { + let runtime = runtime(2); + let mut probe = Probe::spawn(&runtime, false); + let entered = probe.entered.recv_timeout(CLEANUP).is_ok(); + let (started_tx, started_rx) = mpsc::sync_channel(1); + let (done_tx, done_rx) = mpsc::sync_channel(1); + let (started, returned_early, held, joined) = std::thread::scope(|scope| { + let dropper = scope.spawn(move || { + // About-to-drop signal, not proof the destructor was scheduled yet. + let _ = started_tx.send(()); + drop(runtime); + let _ = done_tx.send(()); + }); + let started = started_rx.recv_timeout(CLEANUP).is_ok(); + let early = done_rx.recv_timeout(Duration::from_millis(2)).is_ok(); + let held = probe.held(); + probe.release.now(); + (started, early, held, dropper.join().is_ok()) + }); + let mut context = std::task::Context::from_waker(std::task::Waker::noop()); + let result = match std::pin::Pin::new(&mut probe.task).poll(&mut context) { + std::task::Poll::Ready(result) => Some(result), + std::task::Poll::Pending => None, + }; + assert!(entered && started && !returned_early && held && joined); + assert!( + result.is_some(), + "normal Runtime drop must finish the actual task" + ); + let result = result.unwrap(); + assert!( + result.is_ok() + || result + .as_ref() + .is_err_and(tokio::task::JoinError::is_cancelled) + ); + assert!(probe.seen().unwrap().correct); + probe.refunded(); +} diff --git a/src/http_processing/scripts/plan_validation.rs b/src/http_processing/scripts/plan_validation.rs new file mode 100644 index 0000000..eeaaf74 --- /dev/null +++ b/src/http_processing/scripts/plan_validation.rs @@ -0,0 +1,2294 @@ +//! Fixed, active tvOS diagnostic. No caller-supplied source, body or resources. +//! Requires Invoke's irreversible dedicated-process admission; never pressure. +use super::{CompiledSource, apple, static_literal_plan}; +use crate::http_processing::{ + Policy, + body::Entity, + body_budget::{BridgePlan, Budget, BudgetedBytes, WORKSPACE, output_capacity}, + diagnostics, + script_config::BodyMode, + script_message::{self, Message, OriginalSnapshot, Outcome, RequestSnapshot, ScriptOutput}, +}; +use serde_json::{Value, json}; +use std::{ + io, + time::{Duration, Instant, SystemTime, UNIX_EPOCH}, +}; +use tokio_util::sync::CancellationToken; + +const INVOCATION_LIMIT: Duration = Duration::from_millis(100); +enum Input { + Small(&'static [u8]), + Repeat(u8, usize), + Alphabet, + None, +} +struct Case { + id: &'static str, + source: String, + input: Input, + kind: &'static str, + selection: &'static str, +} +struct Observation { + result: io::Result, + ticks: Option, + work: Option, + backend: &'static str, + trace: Value, +} +fn body(expression: &str) -> String { + format!( + "function rewrite(input){{return {{type:'modify',body:{{kind:'text',data:{expression}}}}};}}" + ) +} +fn cases() -> Vec { + let replace = "input.body.data.replaceAll('-', '_')"; + let mut cases = vec![ + Case { id: "empty", source: body("input.body.data"), input: Input::Small(b""), kind: "text", selection: "plan" }, + Case { id: "renamed-local", source: "function rewrite(input){const renamedPayload=input.body.data;const independentlyNamed=renamedPayload.replaceAll('-', '_');return {type:'modify',body:{kind:'text',data:independentlyNamed}};}".into(), input: Input::Small(b"p-q--$\0"), kind: "text", selection: "plan" }, + Case { id: "first-only", source: body("input.body.data.replace('-', '_')"), input: Input::Small(b"---$\0"), kind: "text", selection: "plan" }, + Case { id: "nested-replace", source: body("input.body.data.replaceAll('-', '_').replace('_', '+')"), input: Input::Small(b"---x"), kind: "text", selection: "plan" }, + Case { id: "literal-nul-dollar", source: body(r"'Q\u0000$-'.replace('-', '_')"), input: Input::Small(b"ignored"), kind: "text", selection: "plan" }, + Case { id: "nul-search", source: body(r"input.body.data.replaceAll('\u0000', '!')"), input: Input::Small(b"a\0-\0$"), kind: "text", selection: "plan" }, + Case { id: "dollar-search", source: body("input.body.data.replaceAll('$', '#')"), input: Input::Small(b"$-$\0"), kind: "text", selection: "plan" }, + Case { id: "static-headers", source: r#"function rewrite(input){return {headers:[{op:'set',name:'X-Trace',values:['a\t\"b']},{op:'add',name:'X-Trace',values:['']},{op:'remove',name:'X-Old'}],body:{data:input.body.data.replaceAll('-', '_'),kind:'text'},type:'modify'};}"#.into(), input: Input::Small(b"--\0"), kind: "text", selection: "plan" }, + Case { id: "ascii-4095", source: body(replace), input: Input::Repeat(b'-', 4095), kind: "text", selection: "plan" }, + Case { id: "ascii-4096", source: body(replace), input: Input::Repeat(b'-', 4096), kind: "text", selection: "plan" }, + Case { id: "ascii-64k", source: body(replace), input: Input::Repeat(b'-', 65536), kind: "text", selection: "plan" }, + Case { id: "ascii-no-match-64k", source: body(replace), input: Input::Repeat(b'x', 65536), kind: "text", selection: "plan" }, + Case { id: "unicode-input", source: body(replace), input: Input::Small("é-😀\0$".as_bytes()), kind: "text", selection: "plan" }, + Case { id: "unicode-literal", source: body("input.body.data.replaceAll('é', 'e')"), input: Input::Small("é-é".as_bytes()), kind: "text", selection: "ast-fallback" }, + Case { id: "dollar-replacement", source: body("input.body.data.replaceAll('-', '$')"), input: Input::Small(b"x--"), kind: "text", selection: "ast-fallback" }, + Case { id: "template-match", source: body("input.body.data.replaceAll('-', '$&')"), input: Input::Small(b"x--"), kind: "text", selection: "ast-fallback" }, + Case { id: "empty-search", source: body("input.body.data.replaceAll('', 'x')"), input: Input::Small(b"q"), kind: "text", selection: "ast-fallback" }, + Case { id: "unknown-loop", source: "function rewrite(input){let found=false;for(let i=0;i(); + cases.push(Case { id, source: format!("function rewrite(input){{{declarations}return {{type:'modify',body:{{kind:'text',data:input.body.data}}}};}}"), input: Input::Repeat(b'-', 65536), kind: "text", selection: "plan" }); + } + cases +} +fn extra_semantic_cases() -> Vec { + let mut cases = Vec::new(); + for (id, length) in [ + ("identity-1", 1), + ("identity-255", 255), + ("identity-256", 256), + ("identity-max", 262144), + ] { + cases.push(Case { + id, + source: body("input.body.data"), + input: Input::Repeat(b'Q', length), + kind: "text", + selection: "plan", + }); + } + cases.push(Case { + id: "identical-replacement", + source: body("input.body.data.replaceAll('a', 'a')"), + input: Input::Small(b"aa-a\0$"), + kind: "text", + selection: "plan", + }); + cases.push(Case { + id: "del-search-and-replacement", + source: body(r"input.body.data.replaceAll('\u007f', '!').replace('!', '\u007f')"), + input: Input::Small(b"a\x7fb\x7f"), + kind: "text", + selection: "plan", + }); + // The value is 4097 ASCII code units. Header validation uses the unquoted + // shortcut; metadata Measure must still run 17 quoted-string tick points. + let mut long_value = "q".repeat(4094); + long_value.push_str("\t\\\""); + let long_value = serde_json::to_string(&long_value).unwrap(); + let allowed = serde_json::to_string("\t !~\"\\").unwrap(); + cases.push(Case { + id: "quoted-long-header-order-and-values", + source: format!( + "function rewrite(input){{return {{body:{{data:input.body.data,kind:'text'}},headers:[{{values:[{long_value}],name:'X-Quoted',op:'set'}},{{name:'X-Order',values:['',{allowed}],op:'add'}},{{name:'X-Old',op:'remove'}}],type:'modify'}};}}" + ), + input: Input::Small(b"x\0"), + kind: "text", + selection: "plan", + }); + cases.push(Case { + id: "duplicate-body-key-ast-fallback", + source: "function rewrite(input){return {type:'modify',body:{kind:'text',data:'discarded',data:input.body.data}};}".into(), + input: Input::Small(b"last-key-wins"), + kind: "text", + selection: "ast-fallback", + }); + cases.push(Case { + id: "let-assignment-ast-fallback", + source: "function rewrite(input){let named=input.body.data;named='changed';return {type:'modify',body:{kind:'text',data:named}};}".into(), + input: Input::Small(b"original"), + kind: "text", + selection: "ast-fallback", + }); + cases +} + +fn materialization_cases() -> Vec { + let input = b"aabbcc--za\0$"; + let mut cases = vec![ + Case { id:"writer-transitive", source:body("input.body.data.replaceAll('a','b').replaceAll('b','c')"), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-reversed", source:body("input.body.data.replaceAll('b','c').replaceAll('a','b')"), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-cycle", source:body("input.body.data.replaceAll('a','b').replaceAll('b','a')"), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-alias-branch", source:"function rewrite(input){const original=input.body.data;const unused=original.replaceAll('z','q');const chosen=original.replaceAll('a','b');const other=chosen.replaceAll('c','z');return {type:'modify',body:{kind:'text',data:chosen.replaceAll('b','c')}};}".into(), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-renamed-local", source:"function rewrite(input){const renamed=input.body.data;const independentlyNamed=renamed.replaceAll('a','b');return {body:{data:independentlyNamed.replaceAll('b','c'),kind:'text'},headers:[{values:['static'],op:'set',name:'X-Proof'}],type:'modify'};}".into(), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-literal-base", source:body(r"'a-\u0000aa$'.replaceAll('a','b').replaceAll('b','c')"), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-unused-first", source:"function rewrite(input){const ignored=input.body.data.replace('a','z');return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('a','b').replaceAll('b','c')}};}".into(), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-first-ancestor", source:body("input.body.data.replace('a','b').replaceAll('b','c')"), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-all-first-all", source:body("input.body.data.replaceAll('a','b').replace('b','c').replaceAll('c','d')"), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-ascii-alphabet", source:body(r"input.body.data.replaceAll('\u0000','\u007f').replaceAll('\u007f','!')"), input:Input::Alphabet, kind:"text", selection:"plan" }, + Case { id:"writer-no-match", source:body("input.body.data.replaceAll('x','y').replaceAll('y','z')"), input:Input::Small(input), kind:"text", selection:"plan" }, + Case { id:"writer-equal-byte", source:body("input.body.data.replaceAll('a','a').replaceAll('b','b')"), input:Input::Small(input), kind:"text", selection:"plan" }, + ]; + for (id, length) in [ + ("writer-chunk-0", 0), + ("writer-chunk-1", 1), + ("writer-chunk-255", 255), + ("writer-chunk-256", 256), + ("writer-chunk-257", 257), + ("writer-chunk-64k", 65536), + ] { + cases.push(Case { + id, + source: body("input.body.data.replaceAll('a','b').replaceAll('b','c')"), + input: Input::Repeat(b'a', length), + kind: "text", + selection: "plan", + }); + } + for (id, count) in [ + ("writer-unused-literal-15", 15), + ("writer-unused-literal-16", 16), + ] { + let declarations = (0..count) + .map(|i| format!("const unused{i}=input.body.data.replaceAll('a','b');")) + .collect::(); + cases.push(Case { id, source:format!("function rewrite(input){{{declarations}return {{type:'modify',body:{{kind:'text',data:'constant\\u0000$'}}}};}}"), input:Input::Repeat(b'a',65536), kind:"text", selection:"plan" }); + } + cases +} + +fn single_step_cases() -> Vec { + vec![ + Case { + id: "single-empty", + source: body("input.body.data.replaceAll('a','z')"), + input: Input::Small(b""), + kind: "text", + selection: "plan", + }, + Case { + id: "single-ascii-nul-del", + source: body(r"input.body.data.replaceAll('\u0000','\u007f')"), + input: Input::Alphabet, + kind: "text", + selection: "plan", + }, + Case { + id: "single-cross-chunk-tail", + source: body("input.body.data.replaceAll('a','z')"), + input: Input::Repeat(b'a', 257), + kind: "text", + selection: "plan", + }, + Case { + id: "single-literal-source", + source: body(r"'a\u0000-\u007fa'.replaceAll('a','z')"), + input: Input::Small(b"ignored"), + kind: "text", + selection: "plan", + }, + ] +} + +struct GuardCase { + case: Case, + metadata: Value, + canary: Option<(usize, usize, &'static str)>, +} +fn guarded_source( + path: &str, + flag: &str, + index: &str, + predicate: &str, + early: &str, + prefix: bool, +) -> String { + let update = if prefix { + format!("++{index}") + } else { + format!("{index}++") + }; + format!( + "function rewrite(input){{let {flag}=false;for(let {index}=0;{index} Value { + let mut metadata = json!({"body":{"kind":"text"}}); + metadata[path] = json!({"headers":rows}); + metadata +} +fn guard_case( + id: &'static str, + source: String, + metadata: Value, + selection: &'static str, + canary: Option<(usize, usize, &'static str)>, +) -> GuardCase { + GuardCase { + case: Case { + id, + source, + input: Input::Small(b"--source"), + kind: "text", + selection, + }, + metadata, + canary, + } +} +fn guard_cases() -> Vec { + let name = "input.response.headers[row].name === 'x-probe'"; + let value = "input.response.headers[row].value === 'ok'"; + let source = |predicate: &str, early: &str| { + guarded_source("response", "seen", "row", predicate, early, false) + }; + let rows = |value: Value| guard_metadata("response", value); + let matched = rows(json!([{"name":"x-probe","value":"ok"}])); + let other = rows(json!([{"name":"x-other","value":"no"}])); + let empty = rows(json!([])); + let mut cases = vec![ + guard_case( + "guard-empty-pass", + source(name, "pass"), + empty.clone(), + "plan", + Some((14, 142, "pass")), + ), + guard_case( + "guard-empty-abort", + source(name, "abort"), + empty, + "plan", + Some((14, 144, "abort")), + ), + guard_case( + "guard-one-false-pass", + source(name, "pass"), + other.clone(), + "plan", + Some((34, 158, "pass")), + ), + guard_case( + "guard-and-short-false", + source(&format!("{name} && {value}"), "pass"), + other.clone(), + "plan", + Some((34, 158, "pass")), + ), + guard_case( + "guard-and-second-false", + source(&format!("{name} && {value}"), "pass"), + rows(json!([{"name":"x-probe","value":"no"}])), + "plan", + Some((42, 158, "pass")), + ), + guard_case( + "guard-or-all-false", + source(&format!("{name} || {value}"), "abort"), + other.clone(), + "plan", + Some((42, 160, "abort")), + ), + guard_case( + "guard-not-equal-literal-left", + source("'x-other' !== input.response.headers[row].name", "pass"), + matched.clone(), + "plan", + None, + ), + guard_case( + "guard-unicode-value", + source("input.response.headers[row].value === 'café😀'", "pass"), + rows(json!([{"name":"x-probe","value":"café😀"}])), + "plan", + None, + ), + guard_case( + "guard-name-case-sensitive", + source("input.response.headers[row].name === 'X-Probe'", "pass"), + matched.clone(), + "plan", + Some((34, 158, "pass")), + ), + guard_case( + "guard-duplicates-empty-values", + source(&format!("{name} && {value}"), "pass"), + rows(json!([{"name":"x-probe","value":""},{"name":"x-probe","value":"ok"}])), + "plan", + None, + ), + guard_case( + "guard-empty-value-match", + source("input.response.headers[row].value === ''", "pass"), + rows(json!([{"name":"x-probe","value":""}])), + "plan", + None, + ), + guard_case( + "guard-nul-quoted-value", + source( + &format!( + "input.response.headers[row].value === {}", + serde_json::to_string("a\0\"\\b").unwrap() + ), + "pass", + ), + rows(json!([{"name":"x-probe","value":"a\0\"\\b"}])), + "plan", + None, + ), + guard_case( + "guard-prefix-increment", + guarded_source( + "response", + "differentFlag", + "cursor", + "input.response.headers[cursor].name === 'x-probe'", + "pass", + true, + ), + matched.clone(), + "plan", + None, + ), + guard_case( + "guard-request-path", + guarded_source( + "request", + "ready", + "position", + "input.request.headers[position].value === 'ok'", + "abort", + false, + ), + guard_metadata("request", json!([{"name":"x-probe","value":"ok"}])), + "plan", + None, + ), + guard_case( + "guard-missing-response", + source(name, "pass"), + json!({"body":{"kind":"text"}}), + "input-fallback", + None, + ), + guard_case( + "guard-nonarray-headers", + source(name, "pass"), + rows(json!({"length":0})), + "input-fallback", + None, + ), + guard_case( + "guard-shortcircuited-missing-value", + source(&format!("{name} || {value}"), "pass"), + rows(json!([{"name":"x-probe"}])), + "input-fallback", + None, + ), + guard_case( + "guard-extra-row-field", + source(name, "pass"), + rows(json!([{"name":"x-probe","value":"ok","extra":true}])), + "input-fallback", + None, + ), + guard_case( + "guard-string-row", + source(name, "pass"), + rows(json!(["primitive"])), + "input-fallback", + None, + ), + guard_case( + "guard-row-count-bound", + source(name, "pass"), + rows(Value::Array( + (0..101) + .map(|_| json!({"name":"x-other","value":"no"})) + .collect(), + )), + "input-fallback", + None, + ), + guard_case( + "guard-row-byte-bound", + source(name, "pass"), + rows(json!([{"name":"x-probe","value":"x".repeat(32768)}])), + "input-fallback", + None, + ), + guard_case( + "guard-unknown-while", + source(name, "pass").replace("let seen=false;", "let seen=false;while(false){}"), + matched.clone(), + "ast-fallback", + None, + ), + guard_case( + "guard-flag-write-false", + source(name, "pass").replace("seen=true;", "seen=false;"), + matched.clone(), + "ast-fallback", + None, + ), + guard_case( + "guard-extra-break", + source(name, "pass").replace("seen=true;", "seen=true;break;"), + matched.clone(), + "ast-fallback", + None, + ), + guard_case( + "guard-alternate-update", + source(name, "pass").replace("row++", "row+=1"), + matched.clone(), + "ast-fallback", + None, + ), + guard_case( + "guard-wrong-index", + source("input.response.headers[0].name === 'x-probe'", "pass"), + matched.clone(), + "ast-fallback", + None, + ), + guard_case( + "guard-unused-flag-alias", + source(name, "pass").replace( + "const mappedBody=", + "const unusedAlias=seen;const mappedBody=", + ), + matched.clone(), + "ast-fallback", + None, + ), + ]; + for (id, predicate, metadata, canary) in [ + ( + "guard-one-true-64k", + name.to_owned(), + matched.clone(), + Some((52, 131488, "modify")), + ), + ( + "guard-or-short-true", + format!("{name} || {value}"), + matched.clone(), + Some((52, 131488, "modify")), + ), + ( + "guard-or-second-true", + format!("{name} || {value}"), + rows(json!([{"name":"x-other","value":"ok"}])), + Some((60, 131488, "modify")), + ), + ( + "guard-and-both-true", + format!("{name} && {value}"), + matched.clone(), + Some((60, 131488, "modify")), + ), + ( + "guard-found-first-reads-all", + name.to_owned(), + rows( + json!([{"name":"x-probe","value":"ok"},{"name":"x-other","value":"later"},{"name":"x-last","value":"later"}]), + ), + Some((92, 131520, "modify")), + ), + ( + "guard-found-last-reads-all", + name.to_owned(), + rows( + json!([{"name":"x-other","value":"first"},{"name":"x-next","value":"middle"},{"name":"x-probe","value":"ok"}]), + ), + Some((92, 131520, "modify")), + ), + ] { + let mut case = guard_case(id, source(&predicate, "pass"), metadata, "plan", canary); + case.case.input = Input::Repeat(b'-', 65536); + cases.push(case); + } + cases.push(guard_case( + "guard-static-header-tail", + source(name, "pass").replace( + "return {type:'modify',body:", + "return {headers:[{op:'set',name:'X-Proof',values:['static']}],type:'modify',body:", + ), + matched.clone(), + "plan", + None, + )); + for (id, count, canary) in [ + ("guard-unused-quota-15", 15, (210, 1966944, "modify")), + ( + "guard-unused-quota-16", + 16, + (204, 1966576, "error:InvalidData"), + ), + ] { + let declarations = (0..count) + .map(|i| format!("const unused{i}=input.body.data.replaceAll('-', '_');")) + .collect::(); + let final_tail = format!( + "{declarations}return {{type:'modify',body:{{kind:'text',data:input.body.data}}}};" + ); + let mut case=guard_case(id,source(name,"pass").replace("const mappedBody=input.body.data.replaceAll('-', '_');return {type:'modify',body:{kind:'text',data:mappedBody}};",&final_tail),matched.clone(),"plan",Some(canary)); + case.case.input = Input::Repeat(b'-', 65536); + cases.push(case); + } + cases +} +fn compare_guard(case: &GuardCase, budget: &Budget) -> io::Result { + let mut row = compare_metadata(&case.case, budget, Some(&case.metadata))?; + let canary = case.canary.is_none_or(|(ticks, work, kind)| { + let result = if let Some(error) = kind.strip_prefix("error:") { + row["baseline"]["errorKind"] == error + } else { + row["baseline"]["resultType"] == kind + }; + row["baseline"]["ticks"] == ticks && row["baseline"]["allocationWork"] == work && result + }); + let early_empty = if matches!( + row["candidate"]["resultType"].as_str(), + Some("pass" | "abort") + ) { + row["candidate"]["outputBytes"] == 0 + } else { + true + }; + row["guardCanaryMet"] = json!(canary); + row["earlyOutputEmpty"] = json!(early_empty); + if !canary || !early_empty { + row["passed"] = json!(false); + } + Ok(row) +} + +fn output(budget: &Budget, bound: usize, body: bool) -> io::Result { + if !body { + return Ok(BudgetedBytes::empty(budget)); + } + BudgetedBytes::new( + budget, + output_capacity(bound).ok_or(io::ErrorKind::FileTooLarge)?, + ) + .ok_or_else(|| io::ErrorKind::OutOfMemory.into()) +} +fn fixture(budget: &Budget, input: &Input) -> io::Result> { + match input { + Input::None => Ok(None), + Input::Small(bytes) => BudgetedBytes::copy(budget, bytes) + .map(Some) + .ok_or_else(|| io::ErrorKind::OutOfMemory.into()), + Input::Alphabet => { + let mut value = BudgetedBytes::new(budget, 128).ok_or(io::ErrorKind::OutOfMemory)?; + value.write_initialized_output(128, |bytes| { + for (index, byte) in bytes.iter_mut().enumerate() { + *byte = index as u8; + } + Ok(128) + })?; + Ok(Some(value)) + } + Input::Repeat(byte, length) => { + let mut value = + BudgetedBytes::new(budget, *length).ok_or(io::ErrorKind::OutOfMemory)?; + value.write_initialized_output(*length, |bytes| { + bytes.fill(*byte); + Ok(*length) + })?; + Ok(Some(value)) + } + } +} +fn run_jsc( + program: &CompiledSource, + metadata: &Value, + input: Option<&BudgetedBytes>, + output: &mut BudgetedBytes, + budget: &Budget, +) -> io::Result { + // This guard stays live through ContextRelease and the actual scoped join. + let bridge = input + .map(|input| { + let plan = BridgePlan::new( + input.as_ref().len(), + metadata["body"]["kind"] == "text", + program.maximum_output_bytes(input.as_ref().len()), + ) + .ok_or(io::ErrorKind::InvalidInput)?; + budget + .reserve(plan.cost().ok_or(io::ErrorKind::OutOfMemory)?) + .ok_or(io::ErrorKind::OutOfMemory) + }) + .transpose()?; + let cancellation = CancellationToken::new(); + let deadline = Instant::now() + INVOCATION_LIMIT; + let (result, trace) = super::run_on_scoped_thread(|| { + Ok(apple::evaluate_for_validation( + program, + metadata, + input.map(AsRef::as_ref), + output, + bridge.as_ref(), + &cancellation, + deadline, + )) + })?; + // Reaching here proves the owner/TLS really joined, independently of ctx. + let ticks = trace.ticks; + let work = trace.allocation_work; + Ok(Observation { + result, + ticks, + work, + backend: "javascriptcore", + trace: serde_json::to_value(trace).map_err(io::Error::other)?, + }) +} +fn outcome(observation: &Observation, bytes: usize) -> Value { + json!({"backend": observation.backend, "succeeded": observation.result.is_ok(), + "errorKind": observation.result.as_ref().err().map(|error| format!("{:?}", error.kind())), + "ticks": observation.ticks, "allocationWork": observation.work, "outputBytes": bytes, + "ownerJoined": true, "resultType":observation.result.as_ref().ok().and_then(|v|v["type"].as_str()), "trace": observation.trace}) +} +fn compare(case: &Case, budget: &Budget) -> io::Result { + compare_metadata(case, budget, None) +} +fn compare_metadata( + case: &Case, + budget: &Budget, + metadata_override: Option<&Value>, +) -> io::Result { + let program = super::validate_source(&case.source)?; + let plan = static_literal_plan::compile(&case.source); + let input = fixture(budget, &case.input)?; + let length = input.as_ref().map_or(0, |input| input.as_ref().len()); + let default_metadata = json!({"body":{"kind":case.kind}, "response":{"status":200,"headers":[{"name":"X-Unused","values":["fixture"]}]}}); + let metadata = metadata_override.unwrap_or(&default_metadata); + let mut baseline_output = output( + budget, + program.maximum_output_bytes(length), + input.is_some(), + )?; + let baseline = run_jsc( + &program, + metadata, + input.as_ref(), + &mut baseline_output, + budget, + )?; + let bound = plan + .as_ref() + .and_then(|plan| plan.maximum_output_bytes(length)) + .unwrap_or_else(|| program.maximum_output_bytes(length)); + let mut candidate_output = output(budget, bound, input.is_some())?; + // No JSC bridge is created or retained for a selected Plan invocation. + let attempted = if let Some(plan) = &plan { + let cancellation = CancellationToken::new(); + let deadline = Instant::now() + INVOCATION_LIMIT; + super::run_on_script_thread(super::OwnerBackend::Plan, || { + Ok(plan.try_execute( + metadata, + input.as_ref().map(BudgetedBytes::borrowed_body), + &mut candidate_output, + &cancellation, + deadline, + )) + })? + } else { + None + }; + let (selection, actual) = if let Some(attempt) = attempted { + // Some(Err), including selected t=0 OOM, never reruns JavaScriptCore. + ( + "plan", + Observation { + result: attempt.result, + ticks: Some(attempt.ticks), + work: Some(attempt.allocation_work), + backend: attempt.backend, + trace: json!({"kind":"plan-counters","contextCreated":false}), + }, + ) + } else { + let selection = if plan.is_some() { + "input-fallback" + } else { + "ast-fallback" + }; + ( + selection, + run_jsc( + &program, + metadata, + input.as_ref(), + &mut candidate_output, + budget, + )?, + ) + }; + + // A third independently paid output runs the untouched DAG materializer. + // The JSC bridge/owner has already really ended in run_jsc above. + let dag_reference = if selection == "plan" { + let plan = plan.as_ref().ok_or(io::ErrorKind::InvalidInput)?; + let mut dag_output = BudgetedBytes::new(budget, bound).ok_or(io::ErrorKind::OutOfMemory)?; + let cancellation = CancellationToken::new(); + let deadline = Instant::now() + INVOCATION_LIMIT; + let attempt = super::run_on_script_thread(super::OwnerBackend::Plan, || { + plan.try_execute_for_validation( + metadata, + input.as_ref().map(BudgetedBytes::borrowed_body), + &mut dag_output, + &cancellation, + deadline, + static_literal_plan::Validation { + force_dag: true, + after_chunk: None, + }, + ) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + })?; + Some(( + Observation { + result: attempt.result, + ticks: Some(attempt.ticks), + work: Some(attempt.allocation_work), + backend: attempt.backend, + trace: json!({"kind":"original-dag-reference","contextCreated":false}), + }, + dag_output, + )) + } else { + None + }; + let dag_equal = dag_reference.as_ref().map(|(reference, bytes)| { + let result_equal = match (&reference.result, &actual.result) { + (Ok(a), Ok(b)) => a == b, + (Err(a), Err(b)) => a.kind() == b.kind(), + _ => false, + }; + result_equal + && reference.ticks == actual.ticks + && reference.work == actual.work + && bytes.as_ref() == candidate_output.as_ref() + }); + let materializer = plan + .as_ref() + .filter(|_| selection == "plan") + .map(|p| p.materializer_kind()); + let expected_materializer = if selection == "plan" { + Some(match case.id { + "first-only" + | "nested-replace" + | "literal-nul-dollar" + | "del-search-and-replacement" + | "writer-first-ancestor" + | "writer-all-first-all" => "dag", + _ => "recipe", + }) + } else { + None + }; + let materializer_expected = materializer == expected_materializer; + + let result_equal = match (&baseline.result, &actual.result) { + (Ok(a), Ok(b)) => a == b, + (Err(a), Err(b)) => a.kind() == b.kind(), + _ => false, + }; + let bytes_equal = baseline_output.as_ref() == candidate_output.as_ref(); + let ticks_equal = baseline.ticks.is_some() && baseline.ticks == actual.ticks; + let work_equal = baseline.work.is_some() && baseline.work == actual.work; + let trace_complete = baseline.trace["contextReleased"] == true + && baseline.trace["preludeLoaded"] == true + && (selection == "plan" + || (actual.trace["contextReleased"] == true && actual.trace["preludeLoaded"] == true)); + // Independent fixed boundary canaries prevent two unavailable/incorrect + // observations from being mistaken for a successful differential. + let boundary_expected = match case.id { + "ascii-64k" => { + baseline.result.is_ok() && baseline.ticks == Some(25) && baseline.work == Some(131472) + } + "unused-work-limit-16" => { + baseline + .result + .as_ref() + .is_err_and(|error| error.kind() == io::ErrorKind::InvalidData) + && baseline.work == Some(1966560) + } + _ => true, + }; + let passed = boundary_expected + && selection == case.selection + && result_equal + && bytes_equal + && ticks_equal + && work_equal + && trace_complete + && dag_equal != Some(false) + && materializer_expected; + Ok( + json!({"id":case.id,"passed":passed,"inputBytes":length,"planCompiled":plan.is_some(), + "expectedSelection":case.selection,"selection":selection,"resultEqual":result_equal,"compiledHeaderGuard":plan.as_ref().is_some_and(|p|p.has_header_guard()), + "bytesEqual":bytes_equal,"ticksEqual":ticks_equal,"allocationWorkEqual":work_equal,"traceComplete":trace_complete,"boundaryExpected":boundary_expected, + "compiledFinalMaterializer":materializer,"expectedCompiledFinalMaterializer":expected_materializer,"materializerExpected":materializer_expected,"originalDagEqual":dag_equal, + "dagReference":dag_reference.as_ref().map(|(o,b)|outcome(o,b.as_ref().len())), + "baseline":outcome(&baseline,baseline_output.as_ref().len()),"candidate":outcome(&actual,candidate_output.as_ref().len())}), + ) +} +// Operational ownership/transaction checks are separate from the real JSC +// semantic differential: Rust Plan owns no fictional JSC bridge copies. +const OPERATIONAL_IDS: [&str; 7] = [ + "typed-foreign-ledger", + "selected-state-oom", + "selected-expired", + "selected-cancelled-expired", + "last-owner-refund", + "invalid-metadata", + "message-atomic-rollback", +]; +fn operational(id: &str, budget: &Budget) -> io::Result { + let source = body("input.body.data.replaceAll('-', '_')"); + let plan = static_literal_plan::compile(&source).ok_or(io::ErrorKind::InvalidData)?; + let input = BudgetedBytes::copy(budget, b"---source").ok_or(io::ErrorKind::OutOfMemory)?; + let metadata = json!({"body":{"kind":"text"}}); + let mut target = + BudgetedBytes::new(budget, input.as_ref().len()).ok_or(io::ErrorKind::OutOfMemory)?; + let cancellation = CancellationToken::new(); + let invoke = |target: &mut BudgetedBytes, metadata: &Value, deadline| { + super::run_on_script_thread(super::OwnerBackend::Plan, || { + plan.try_execute( + metadata, + Some(input.borrowed_body()), + target, + &cancellation, + deadline, + ) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + }) + }; + let healthy = || Instant::now() + INVOCATION_LIMIT; + let mut flags = json!({"scope":"direct typed Plan or Message operational check; not a second execution lane"}); + let passed = match id { + "typed-foreign-ledger" => { + let other = Budget::default(); + let mut foreign = BudgetedBytes::new(&other, input.as_ref().len()) + .ok_or(io::ErrorKind::OutOfMemory)?; + let attempt = invoke(&mut foreign, &metadata, healthy())?; + let passed = attempt + .result + .as_ref() + .is_err_and(|e| e.kind() == io::ErrorKind::InvalidInput) + && attempt.ticks == 0 + && attempt.allocation_work == 0 + && foreign.as_ref().is_empty(); + drop(foreign); + passed && other.reserve(WORKSPACE).is_some() + } + "selected-state-oom" => { + let charged = BudgetedBytes::allocation_cost(input.as_ref().len()) + .ok_or(io::ErrorKind::OutOfMemory)? + .checked_mul(2) + .ok_or(io::ErrorKind::OutOfMemory)?; + let blocker = budget + .reserve(WORKSPACE - charged) + .ok_or(io::ErrorKind::OutOfMemory)?; + let attempt = invoke(&mut target, &metadata, healthy())?; + let passed = attempt + .result + .as_ref() + .is_err_and(|e| e.kind() == io::ErrorKind::OutOfMemory) + && attempt.ticks == 0 + && attempt.allocation_work == 0 + && target.as_ref().is_empty(); + drop(blocker); + passed + } + "selected-expired" | "selected-cancelled-expired" => { + if id == "selected-cancelled-expired" { + cancellation.cancel(); + } + let attempt = invoke( + &mut target, + &metadata, + Instant::now() - Duration::from_millis(1), + )?; + let expected = if cancellation.is_cancelled() { + io::ErrorKind::Interrupted + } else { + io::ErrorKind::TimedOut + }; + attempt.result.as_ref().is_err_and(|e| e.kind() == expected) + && attempt.ticks == 0 + && attempt.allocation_work == 0 + && target.as_ref().is_empty() + } + "last-owner-refund" => { + drop((input, target)); + let entity = Entity::identity( + BudgetedBytes::copy(budget, b"---source").ok_or(io::ErrorKind::OutOfMemory)?, + ); + let old = entity.wire().clone(); + let old_slice = old.slice(0..1); + let mut output = + BudgetedBytes::new(budget, old.len()).ok_or(io::ErrorKind::OutOfMemory)?; + let attempt = super::run_on_script_thread(super::OwnerBackend::Plan, || { + plan.try_execute( + &metadata, + entity.borrowed_body(), + &mut output, + &cancellation, + healthy(), + ) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + })?; + let correct = attempt.result.is_ok() && output.as_ref() == b"___source"; + drop(entity); + let output_cost = + BudgetedBytes::allocation_cost(old.len()).ok_or(io::ErrorKind::OutOfMemory)?; + let source_held = budget.reserve(WORKSPACE - output_cost).is_none(); + drop(old); + let source_slice_held = budget.reserve(WORKSPACE - output_cost).is_none(); + drop(old_slice); + let source_refunded = budget.reserve(WORKSPACE - output_cost).is_some(); + let sent = output.into_bytes(); + let sent_slice = sent.slice(0..1); + drop(sent); + let output_slice_held = budget.reserve(WORKSPACE).is_none() + && budget.reserve(WORKSPACE - output_cost).is_some(); + drop(sent_slice); + flags["ownerJoined"] = json!(true); + flags["sourceRefundedAfterLastSlice"] = json!(source_refunded); + flags["lastSourceSliceHeldPermit"] = json!(source_slice_held); + flags["lastOutputSliceHeldPermit"] = json!(output_slice_held); + return Ok( + json!({"id":id,"kind":"operational","passed":correct && source_held && source_slice_held && source_refunded && output_slice_held && budget.reserve(WORKSPACE).is_some(),"checks":flags}), + ); + } + "invalid-metadata" => { + let oversized = json!({"body":{"kind":"text"},"padding":"x".repeat(1024 * 1024)}); + let attempt = invoke(&mut target, &oversized, healthy())?; + let compiled = super::validate_source(&source)?; + let baseline = run_jsc(&compiled, &oversized, Some(&input), &mut target, budget)?; + attempt + .result + .as_ref() + .is_err_and(|e| e.kind() == io::ErrorKind::InvalidData) + && baseline + .result + .as_ref() + .is_err_and(|e| e.kind() == io::ErrorKind::InvalidData) + && attempt.ticks == 0 + && attempt.allocation_work == 0 + && target.as_ref().is_empty() + } + "message-atomic-rollback" => { + drop((input, target)); + let url = + url::Url::parse("https://fixture.invalid/original").map_err(io::Error::other)?; + let entity = Entity::identity( + BudgetedBytes::copy(budget, b"before").ok_or(io::ErrorKind::OutOfMemory)?, + ); + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: vec![("authorization".into(), "fixture".into())], + }, + Some(entity), + &vec![], + false, + ); + let headers = message.request.headers.clone(); + let old_owner = message + .body + .as_ref() + .ok_or(io::ErrorKind::InvalidData)? + .wire() + .clone(); + let other = Budget::default(); + let foreign = + BudgetedBytes::copy(&other, b"after").ok_or(io::ErrorKind::OutOfMemory)?; + let result: ScriptOutput = serde_json::from_value(json!({"type":"modify","url":"https://elsewhere.invalid/changed","method":"PUT","headers":[{"op":"set","name":"X-Changed","values":["yes"]}],"body":{"kind":"text"}})).map_err(io::Error::other)?; + let rejected = message.apply(result, foreign, BodyMode::Text).is_err(); + let unchanged = message.request.url == url + && message.request.method == "POST" + && message.request.headers == headers + && !message.crossed_origin + && message.body.as_ref().is_some_and(|b| { + b.wire().as_ptr() == old_owner.as_ptr() + && b.logical() == Some(b"before".as_slice()) + }); + let invalid_header: ScriptOutput = serde_json::from_value(json!({"type":"modify","headers":[{"op":"set","name":"host","values":["rejected.invalid"]}],"body":{"kind":"text"}})).map_err(io::Error::other)?; + let same = BudgetedBytes::copy(budget, b"after").ok_or(io::ErrorKind::OutOfMemory)?; + let validation_rejected = message.apply(invalid_header, same, BodyMode::Text).is_err(); + let still_unchanged = message.request.headers == headers + && message.request.url == url + && message + .body + .as_ref() + .is_some_and(|b| b.wire().as_ptr() == old_owner.as_ptr()); + drop((message, old_owner)); + return Ok( + json!({"id":id,"kind":"operational","passed":rejected && unchanged && validation_rejected && still_unchanged && other.reserve(WORKSPACE).is_some() && budget.reserve(WORKSPACE).is_some(),"checks":flags}), + ); + } + _ => return Err(io::ErrorKind::InvalidInput.into()), + }; + drop((input, target)); + flags["ownerJoined"] = json!(true); + Ok(json!({"id":id,"kind":"operational","passed":passed,"checks":flags})) +} + +const MATERIALIZATION_OPERATIONAL_IDS: [&str; 6] = [ + "writer-cancel-after-first-chunk", + "writer-expire-after-first-chunk", + "writer-cancel-after-full-chunk", + "writer-materialized-header-rollback", + "single-writer-cancel-after-first-chunk", + "single-writer-cancel-after-full-chunk", +]; +fn materialization_operational(id: &str, budget: &Budget) -> io::Result { + if id == "writer-materialized-header-rollback" { + let source = "function rewrite(input){return {type:'modify',headers:[{op:'set',name:'X-Proof',values:['static']}],body:{kind:'text',data:input.body.data.replaceAll('-', '_')}};}"; + let plan = static_literal_plan::compile(source).ok_or(io::ErrorKind::InvalidData)?; + let url = url::Url::parse("https://fixture.invalid/original").map_err(io::Error::other)?; + let fields = vec![ + ("connection".into(), "x-proof".into()), + ("authorization".into(), "fixture".into()), + ]; + let entity = Entity::identity( + BudgetedBytes::copy(budget, b"--source").ok_or(io::ErrorKind::OutOfMemory)?, + ); + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: fields.clone(), + }, + Some(entity), + &fields, + true, + ); + let before_headers = message.request.headers.clone(); + let before = message + .body + .as_ref() + .ok_or(io::ErrorKind::InvalidData)? + .wire() + .clone(); + let mut output = + BudgetedBytes::new(budget, before.len()).ok_or(io::ErrorKind::OutOfMemory)?; + let cancellation = CancellationToken::new(); + let deadline = Instant::now() + INVOCATION_LIMIT; + let attempt = super::run_on_script_thread(super::OwnerBackend::Plan, || { + plan.try_execute( + &json!({"body":{"kind":"text"}}), + message.body.as_ref().and_then(Entity::borrowed_body), + &mut output, + &cancellation, + deadline, + ) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + })?; + let materialized = output.as_ref() == b"__source"; + let result: ScriptOutput = + serde_json::from_value(attempt.result?).map_err(io::Error::other)?; + let rejected = message + .apply(result, output, BodyMode::Text) + .is_err_and(|error| error.kind() == io::ErrorKind::InvalidData); + let unchanged = message.request.url == url + && message.request.method == "POST" + && message.request.headers == before_headers + && message.crossed_origin + && message.body.as_ref().is_some_and(|body| { + body.wire().as_ptr() == before.as_ptr() + && body.logical() == Some(b"--source".as_slice()) + }); + drop((message, before)); + return Ok( + json!({"id":id,"kind":"materialization-operational","passed":materialized && rejected && unchanged && budget.reserve(WORKSPACE).is_some(), + "materializedAsExpected":materialized,"dynamicProtectedHeaderRejected":rejected,"transactionUnchanged":unchanged,"ownerJoined":true}), + ); + } + let length = if matches!( + id, + "writer-cancel-after-full-chunk" | "single-writer-cancel-after-full-chunk" + ) { + 256 + } else { + 257 + }; + let input = + fixture(budget, &Input::Repeat(b'a', length))?.ok_or(io::ErrorKind::InvalidInput)?; + let expression = if id.starts_with("single-writer-") { + "input.body.data.replaceAll('a','c')" + } else { + "input.body.data.replaceAll('a','b').replaceAll('b','c')" + }; + let plan = static_literal_plan::compile(&body(expression)).ok_or(io::ErrorKind::InvalidData)?; + let mut output = BudgetedBytes::new(budget, length).ok_or(io::ErrorKind::OutOfMemory)?; + let cancellation = CancellationToken::new(); + let deadline = Instant::now() + INVOCATION_LIMIT; + let mut completed_chunks = 0; + let mut filled_bytes = 0; + let attempt = { + let mut hook = |filled| { + completed_chunks += 1; + filled_bytes = filled; + if id == "writer-expire-after-first-chunk" { + // Only a finite diagnostic synchronization hook waits. It does + // not restart or extend the existing absolute100ms deadline. + while Instant::now() < deadline { + std::thread::yield_now(); + } + } else { + cancellation.cancel(); + } + }; + super::run_on_script_thread(super::OwnerBackend::Plan, || { + plan.try_execute_for_validation( + &json!({"body":{"kind":"text"}}), + Some(input.borrowed_body()), + &mut output, + &cancellation, + deadline, + static_literal_plan::Validation { + force_dag: false, + after_chunk: Some(&mut hook), + }, + ) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + })? + }; + let expected_error = if id == "writer-expire-after-first-chunk" { + io::ErrorKind::TimedOut + } else { + io::ErrorKind::Interrupted + }; + let error_matches = attempt + .result + .as_ref() + .is_err_and(|error| error.kind() == expected_error); + let output_expected = if length == 256 { + output.as_ref().len() == 256 && output.as_ref().iter().all(|b| *b == b'c') + } else { + output.as_ref().is_empty() + }; + let input_unchanged = input.as_ref().iter().all(|b| *b == b'a'); + let input_cost = BudgetedBytes::allocation_cost(length).ok_or(io::ErrorKind::OutOfMemory)?; + let output_cost = input_cost; + let output_still_paid = budget.reserve(WORKSPACE - input_cost).is_none(); + let state_refunded = budget + .reserve(WORKSPACE - input_cost - output_cost) + .is_some(); + drop((input, output)); + Ok( + json!({"id":id,"kind":"materialization-operational","passed":error_matches && output_expected && input_unchanged && completed_chunks==1 && filled_bytes==256 && output_still_paid && state_refunded && budget.reserve(WORKSPACE).is_some(), + "errorKind":attempt.result.as_ref().err().map(|error|format!("{:?}",error.kind())),"expectedErrorKind":format!("{:?}",expected_error),"errorMatches":error_matches,"completedChunks":completed_chunks,"filledBytesBeforeFailure":filled_bytes, + "outputStateMatchesExistingErrorBoundary":output_expected,"sourceUnchanged":input_unchanged,"outputCapacityStillPaid":output_still_paid,"stateRefundedAfterRealJoin":state_refunded, + "scope":"direct fill boundary; no Message commit is attempted on Err; no JSC replay","ownerJoined":true}), + ) +} + +// Run only AFTER the outer diagnostic permit has actually been released. +// These exercise the unchanged production lane/CallBuffers/Message path; +// direct adapter comparisons above deliberately do not claim that coverage. +async fn production_case( + id: &str, + input: &[u8], + expected: &[u8], + selected_plan: bool, +) -> io::Result { + let source = "function rewrite(input){const payload=input.body.data.replaceAll('-', '_');return {headers:[{op:'set',name:'X-Proof',values:['ok']}],type:'modify',body:{kind:'text',data:payload}};}"; + let policy = Policy::compile(&format!( + "http-scripts:\n enabled: true\n scripts:\n - name: diagnostic-transaction\n phase: request\n match: exact\n url: https://fixture.invalid/original\n body: text\n source: {}\n", + serde_json::to_string(source).map_err(io::Error::other)? + ))?; + let budget = policy.body_budget().clone(); + let url = url::Url::parse("https://fixture.invalid/original").map_err(io::Error::other)?; + let entity = + Entity::identity(BudgetedBytes::copy(&budget, input).ok_or(io::ErrorKind::OutOfMemory)?); + let old = entity.wire().clone(); + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: vec![], + }, + Some(entity), + &vec![], + false, + ); + let before = diagnostics::snapshot(); + let result = script_message::run(&policy, &url, &mut message, &CancellationToken::new()).await; + let after = diagnostics::snapshot(); + let delta = |key: &str| { + after["counters"][key] + .as_u64()? + .checked_sub(before["counters"][key].as_u64()?) + }; + let changed = message + .body + .as_ref() + .is_some_and(|body| body.logical() == Some(expected)); + let header = message + .request + .headers + .iter() + .any(|(k, v)| k == "x-proof" && v == "ok"); + let before_untouched = old.as_ref() == input; + let accepted = delta("outputAccepted") == Some(1); + let qos_unchanged = ["completedOwners", "setSucceeded", "setFailed"] + .into_iter() + .all(|key| { + before["scopedScriptOwner"][key] + .as_u64() + .zip(after["scopedScriptOwner"][key].as_u64()) + .is_some_and(|(a, b)| a == b) + }); + let backend_observed = if selected_plan { + delta("planSelected") == Some(1) + && delta("planOutputPendingAdmitted") == Some(1) + && delta("planOutputQueueFailed") == Some(0) + && delta("planOutputPayloadBudgetRejected") == Some(0) + && delta("planEntered") == Some(1) + && delta("planSucceeded") == Some(1) + && delta("evaluationEntered") == Some(0) + && delta("contextCreated") == Some(0) + && delta("contextReleased") == Some(0) + && delta("jscOwnerStarted") == Some(0) + && delta("jscOwnerJoined") == Some(0) + && delta("planFinalSingleStepEntered") == Some(1) + && delta("planFinalRecipeEntered") == Some(1) + && delta("planFinalDagEntered") == Some(0) + && delta("planOwnerStarted") == Some(0) + && delta("planOwnerJoined") == Some(0) + && delta("planInlineEntered") == Some(1) + && delta("planInlineReturned") == Some(1) + && delta("planInlinePanicked") == Some(0) + && qos_unchanged + } else { + delta("planOutputPendingAdmitted") == Some(0) + && delta("planOutputQueueFailed") == Some(0) + && delta("planOutputPayloadBudgetRejected") == Some(0) + && delta("planFinalSingleStepEntered") == Some(0) + && delta("planFinalRecipeEntered") == Some(0) + && delta("planFinalDagEntered") == Some(0) + && delta("planInputFallback") == Some(1) + && delta("jscSelected") == Some(1) + && delta("planEntered") == Some(0) + && delta("planOwnerStarted") == Some(0) + && delta("planOwnerJoined") == Some(0) + && delta("evaluationEntered") == Some(1) + && delta("evaluationSucceeded") == Some(1) + && delta("contextCreated") == Some(1) + && delta("contextReleased") == Some(1) + && delta("jscOwnerStarted") == Some(1) + && delta("jscOwnerJoined") == Some(1) + && delta("planInlineEntered") == Some(0) + && delta("planInlineReturned") == Some(0) + && delta("planInlinePanicked") == Some(0) + }; + let lane_observed = delta("queueRequested") == Some(1) + && delta("queueAcquired") == Some(1) + && delta("queueTimeout") == Some(0) + && delta("queueCancelled") == Some(0); + let forwarded = matches!(result, Ok(Outcome::Forward)); + drop((old, message, policy)); + let refunded = budget.reserve(WORKSPACE).is_some(); + Ok( + json!({"id":id,"kind":"production-default-lane","passed":forwarded && changed && header && before_untouched && accepted && backend_observed && lane_observed && refunded, + "expectedBackend":if selected_plan{"plan"}else{"javascriptcore"},"bodyChangedAsExpected":changed,"staticHeaderCommitted":header, + "originalOwnerUnchanged":before_untouched,"outputAcceptedObserved":accepted,"backendCountersObserved":backend_observed, + "scopedQoSUnchanged":qos_unchanged,"defaultLaneObserved":lane_observed,"budgetFullyRefunded":refunded,"timeoutIsNeverSuccess":true}), + ) +} +const GUARD_OPERATIONAL_IDS: [&str; 2] = ["guard-selected-pre-cancel", "guard-selected-state-oom"]; +fn guard_operational(id: &str, budget: &Budget) -> io::Result { + let source = guarded_source( + "response", + "seen", + "row", + "input.response.headers[row].name === 'x-probe'", + "pass", + false, + ); + let metadata = guard_metadata("response", json!([])); + let plan = static_literal_plan::compile(&source).ok_or(io::ErrorKind::InvalidInput)?; + let input = BudgetedBytes::copy(budget, b"--source").ok_or(io::ErrorKind::OutOfMemory)?; + let mut output = + BudgetedBytes::new(budget, input.as_ref().len()).ok_or(io::ErrorKind::OutOfMemory)?; + let eligible = plan.accepts_input(&metadata, Some(input.borrowed_body())); + let cancellation = CancellationToken::new(); + let blocker = if id == "guard-selected-state-oom" { + let cost = BudgetedBytes::allocation_cost(input.as_ref().len()) + .ok_or(io::ErrorKind::OutOfMemory)? + * 2; + Some( + budget + .reserve(WORKSPACE - cost) + .ok_or(io::ErrorKind::OutOfMemory)?, + ) + } else { + cancellation.cancel(); + None + }; + let deadline = Instant::now() + INVOCATION_LIMIT; + let attempt = super::run_on_script_thread(super::OwnerBackend::Plan, || { + plan.try_execute( + &metadata, + Some(input.borrowed_body()), + &mut output, + &cancellation, + deadline, + ) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + })?; + let expected = if id == "guard-selected-state-oom" { + io::ErrorKind::OutOfMemory + } else { + io::ErrorKind::Interrupted + }; + let refused = attempt + .result + .as_ref() + .is_err_and(|error| error.kind() == expected); + let unchanged = input.as_ref() == b"--source" && output.as_ref().is_empty(); + let passed = + eligible && refused && attempt.ticks == 0 && attempt.allocation_work == 0 && unchanged; + let actual_error = attempt + .result + .as_ref() + .err() + .map(|error| format!("{:?}", error.kind())); + drop((blocker, input, output)); + Ok( + json!({"id":id,"kind":"guard-operational","passed":passed && budget.reserve(WORKSPACE).is_some(),"eligibleBeforeExecution":eligible, + "errorKind":actual_error,"expectedErrorKind":format!("{:?}",expected),"ticks":attempt.ticks,"allocationWork":attempt.allocation_work, + "sourceAndEmptyOutputUnchanged":unchanged,"ownerJoined":true,"scope":"chosen Plan error is terminal; never rerun JSC"}), + ) +} + +async fn production_guard_case(early: &str, found: bool) -> io::Result { + let id = if found { + "production-guard-tail" + } else if early == "pass" { + "production-guard-pass" + } else { + "production-guard-abort" + }; + let source = guarded_source( + "request", + "seen", + "row", + "input.request.headers[row].name === 'x-probe'", + early, + false, + ) + .replace( + "return {type:'modify',body:", + "return {headers:[{op:'set',name:'X-Proof',values:['ok']}],type:'modify',body:", + ); + let policy = Policy::compile(&format!( + "http-scripts:\n enabled: true\n scripts:\n - name: diagnostic-guard-transaction\n phase: request\n match: exact\n url: https://fixture.invalid/original\n body: text\n source: {}\n", + serde_json::to_string(&source).map_err(io::Error::other)? + ))?; + let budget = policy.body_budget().clone(); + let url = url::Url::parse("https://fixture.invalid/original").map_err(io::Error::other)?; + let entity = Entity::identity( + BudgetedBytes::copy(&budget, b"--source").ok_or(io::ErrorKind::OutOfMemory)?, + ); + let old = entity.wire().clone(); + let fields = if found { + vec![("x-probe".into(), "ok".into())] + } else { + vec![] + }; + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: fields.clone(), + }, + Some(entity), + &fields, + false, + ); + let before = diagnostics::snapshot(); + let result = script_message::run(&policy, &url, &mut message, &CancellationToken::new()).await; + let after = diagnostics::snapshot(); + let delta = |key: &str| { + after["counters"][key] + .as_u64()? + .checked_sub(before["counters"][key].as_u64()?) + }; + let outcome = if found || early == "pass" { + matches!(result, Ok(Outcome::Forward)) + } else { + matches!(result, Ok(Outcome::Abort)) + }; + let correct_body = message.body.as_ref().is_some_and(|body| { + body.logical() + == Some(if found { + b"__source".as_slice() + } else { + b"--source".as_slice() + }) + }); + let correct_headers = if found { + message + .request + .headers + .iter() + .any(|(k, v)| k == "x-proof" && v == "ok") + } else { + message.request.headers == fields + }; + let unchanged_owner = old.as_ref() == b"--source" + && (found + || message + .body + .as_ref() + .is_some_and(|body| body.wire().as_ptr() == old.as_ptr())); + let qos_unchanged = ["completedOwners", "setSucceeded", "setFailed"] + .into_iter() + .all(|key| { + before["scopedScriptOwner"][key] + .as_u64() + .zip(after["scopedScriptOwner"][key].as_u64()) + .is_some_and(|(a, b)| a == b) + }); + let guard = delta("planHeaderGuardEntered") == Some(1) + && delta("planHeaderGuardTail") == Some(u64::from(found)) + && delta("planHeaderGuardPass") == Some(u64::from(!found && early == "pass")) + && delta("planHeaderGuardAbort") == Some(u64::from(!found && early == "abort")); + let backend = delta("planSelected") == Some(1) + && delta("planOutputPendingAdmitted") == Some(1) + && delta("planOutputQueueFailed") == Some(0) + && delta("planOutputPayloadBudgetRejected") == Some(0) + && delta("planEntered") == Some(1) + && delta("planSucceeded") == Some(1) + && delta("contextCreated") == Some(0) + && delta("contextReleased") == Some(0) + && delta("evaluationEntered") == Some(0) + && delta("jscOwnerStarted") == Some(0) + && delta("jscOwnerJoined") == Some(0) + && delta("planOwnerStarted") == Some(0) + && delta("planOwnerJoined") == Some(0) + && delta("planInlineEntered") == Some(1) + && delta("planInlineReturned") == Some(1) + && delta("planInlinePanicked") == Some(0) + && qos_unchanged + && delta("planFinalSingleStepEntered") == Some(u64::from(found)) + && delta("planFinalRecipeEntered") == Some(u64::from(found)) + && delta("planFinalDagEntered") == Some(0); + let lane = delta("queueRequested") == Some(1) + && delta("queueAcquired") == Some(1) + && delta("queueTimeout") == Some(0); + let commit = delta("outputAccepted") == Some(u64::from(found || early == "pass")) + && delta("outputTerminal") == Some(u64::from(!found && early == "abort")); + drop((old, message, policy)); + let refund = budget.reserve(WORKSPACE).is_some(); + Ok( + json!({"id":id,"kind":"production-guard-default-lane","passed":outcome && correct_body && correct_headers && unchanged_owner && guard && backend && lane && commit && refund, + "correctOutcome":outcome,"bodyAndHeadersCorrect":correct_body && correct_headers,"originalOwnerUnchanged":unchanged_owner, + "guardCountersObserved":guard,"backendCountersObserved":backend,"scopedQoSUnchanged":qos_unchanged,"defaultLaneObserved":lane,"commitCountersObserved":commit,"budgetFullyRefunded":refund}), + ) +} + +fn production_cases() -> io::Result> { + // Invoke is synchronous and admitted only in an otherwise uninitialized, + // permanently diagnostic-only process. Do not nest a runtime accidentally. + if tokio::runtime::Handle::try_current().is_ok() { + return Err(io::ErrorKind::WouldBlock.into()); + } + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_time() + .build()?; + let rows = runtime.block_on(async { + let mut rows = Vec::new(); + for (id, input, expected, selected_plan) in [ + ("production-plan-default-lane", b"--source".as_slice(), b"__source".as_slice(), true), + ("production-unicode-plan-default-lane", "-é".as_bytes(), "_é".as_bytes(), true), + ] { + rows.push(production_case(id,input,expected,selected_plan).await.unwrap_or_else(|error| json!({"id":id,"kind":"production-default-lane","passed":false,"harnessErrorKind":format!("{:?}",error.kind())}))); + } + for (early,found) in [("pass",true),("pass",false),("abort",false)] { + rows.push(production_guard_case(early,found).await.unwrap_or_else(|error|json!({"id":"production-guard-setup","passed":false,"harnessErrorKind":format!("{:?}",error.kind())}))); + } + for (id,mode) in [ + ("plan-output-queued-bookkeeping-only",PlanAdmissionProbe::ReleaseThenRun), + ("plan-output-queue-timeout-refund",PlanAdmissionProbe::QueueTimeout), + ("plan-output-queue-cancel-refund",PlanAdmissionProbe::QueueCancel), + ("plan-output-post-lane-budget-refusal",PlanAdmissionProbe::PayloadReject), + ] { + rows.push(plan_admission_case(id,mode).await.unwrap_or_else(|error|json!({"id":id,"kind":"plan-output-admission","passed":false,"harnessErrorKind":format!("{:?}",error.kind())}))); + } + for (id, mode) in [ + ("inline-abort-ownership", InlineProbe::Abort), + ("inline-cancel-abort-ownership", InlineProbe::CancelAbort), + ("inline-panic-unwind", InlineProbe::Panic), + ] { + rows.push(inline_lifecycle_case(id,mode).await.unwrap_or_else(|error| json!({"id":id,"kind":"inline-lifecycle","passed":false,"harnessErrorKind":format!("{:?}",error.kind())}))); + } + rows + }); + // No detached future or shutdown_timeout: Runtime::drop really joins its + // transient workers/blocking tasks before the suite can claim completion. + drop(runtime); + Ok(rows) +} + +fn unix() -> u128 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis() +} + +pub(crate) fn run() -> io::Result { + // Direct adapters hold the existing lane, then release it before async + // production Message regressions reacquire that very same default lane. + let lane = super::EXECUTION_LANE + .try_acquire() + .map_err(|_| io::ErrorKind::WouldBlock)?; + let started = Instant::now(); + let start_unix = unix(); + let before = diagnostics::snapshot(); + let cancellation = CancellationToken::new(); + let warmup_started = Instant::now(); + let warmup = super::prepare_platform(&cancellation); + let warmup_us = warmup_started.elapsed().as_micros(); + let mut results = Vec::new(); + if warmup.is_ok() { + for case in cases() + .into_iter() + .chain(extra_semantic_cases()) + .chain(materialization_cases()) + .chain(single_step_cases()) + { + let budget = Budget::default(); + let result = compare(&case, &budget); + // No testcase introspection/reset: a fresh entire-ledger owner + // proves all body/API/state owners were actually released. + let refunded = budget.reserve(WORKSPACE).is_some(); + let mut row = result.unwrap_or_else(|error| json!({"id":case.id,"passed":false,"harnessErrorKind":format!("{:?}",error.kind())})); + row["budgetFullyRefunded"] = json!(refunded); + if !refunded { + row["passed"] = json!(false); + } + results.push(row); + } + } + if warmup.is_ok() { + for id in OPERATIONAL_IDS { + let budget = Budget::default(); + let result = operational(id, &budget); + let refunded = budget.reserve(WORKSPACE).is_some(); + let mut row = result.unwrap_or_else(|error| json!({"id":id,"passed":false,"harnessErrorKind":format!("{:?}",error.kind())})); + row["budgetFullyRefunded"] = json!(refunded); + if !refunded { + row["passed"] = json!(false); + } + results.push(row); + } + } + if warmup.is_ok() { + for id in MATERIALIZATION_OPERATIONAL_IDS { + let budget = Budget::default(); + let result = materialization_operational(id, &budget); + let refunded = budget.reserve(WORKSPACE).is_some(); + let mut row=result.unwrap_or_else(|error|json!({"id":id,"passed":false,"harnessErrorKind":format!("{:?}",error.kind())})); + row["budgetFullyRefunded"] = json!(refunded); + if !refunded { + row["passed"] = json!(false); + } + results.push(row); + } + } + if warmup.is_ok() { + for case in guard_cases() { + let budget = Budget::default(); + let result = compare_guard(&case, &budget); + let refunded = budget.reserve(WORKSPACE).is_some(); + let mut row=result.unwrap_or_else(|error|json!({"id":case.case.id,"passed":false,"harnessErrorKind":format!("{:?}",error.kind())})); + row["budgetFullyRefunded"] = json!(refunded); + if !refunded { + row["passed"] = json!(false); + } + results.push(row); + } + for id in GUARD_OPERATIONAL_IDS { + let budget = Budget::default(); + let result = guard_operational(id, &budget); + let refunded = budget.reserve(WORKSPACE).is_some(); + let mut row=result.unwrap_or_else(|error|json!({"id":id,"passed":false,"harnessErrorKind":format!("{:?}",error.kind())})); + row["budgetFullyRefunded"] = json!(refunded); + if !refunded { + row["passed"] = json!(false); + } + results.push(row); + } + } + if warmup.is_ok() { + results.push(crate::http_processing::body::validate_native_byte_map() + .unwrap_or_else(|error| json!({"id":"native-byte-map-differential","kind":"native-differential","passed":false,"harnessErrorKind":format!("{:?}",error.kind())}))); + } + drop(lane); + let mut production_runtime_joined = false; + if warmup.is_ok() { + match production_cases() { + Ok(rows) => { results.extend(rows); production_runtime_joined = true; } + Err(error) => results.push(json!({"id":"production-default-lane-setup","passed":false,"harnessErrorKind":format!("{:?}",error.kind())})), + } + } + if warmup.is_ok() { + results.push(inline_runtime_drop_case().unwrap_or_else(|error| json!({"id":"inline-runtime-drop-barrier","kind":"inline-lifecycle","passed":false,"harnessErrorKind":format!("{:?}",error.kind())}))); + } + if warmup.is_ok() { + results.push(crate::http_processing::h2_reuse::validate() + .unwrap_or_else(|error| json!({"id":"h2-upstream-owner-lifecycle","kind":"h2-memory-owner-group","passed":false,"harnessErrorKind":format!("{:?}",error.kind())}))); + } + let mismatches = results.iter().filter(|row| row["passed"] != true).count(); + let passed = warmup.is_ok() + && results.len() + == 91 + + OPERATIONAL_IDS.len() + + MATERIALIZATION_OPERATIONAL_IDS.len() + + GUARD_OPERATIONAL_IDS.len() + + 5 + + 4 + + 4 + + 1 + + 1 + && production_runtime_joined + && mismatches == 0; + Ok( + json!({"schemaVersion":1,"suite":"static-literal-plan-v1","started":true,"ended":true,"joined":true, + "processID":std::process::id(),"startUnixMilliseconds":start_unix,"endUnixMilliseconds":unix(),"wallUs":started.elapsed().as_micros(), + "passed":passed,"status":if passed{"PASS"}else{"FAIL"},"cases":results,"caseCount":results.len(),"mismatchCount":mismatches, + "warmup":{"succeeded":warmup.is_ok(),"wallUs":warmup_us,"joined":true,"errorKind":warmup.err().map(|error|format!("{:?}",error.kind()))}, + "limits":{"invocationMilliseconds":100,"ticks":100000,"bodyBytes":262144,"workspaceBytes":WORKSPACE,"lanes":1}, + "processMustExitBeforePressure":true,"diagnosticCountersContainSuite":true, + "counterScope":"fixed direct adapter comparisons, five production Message regressions, four real production output-admission probes, four labelled private shared-BIP lifecycle probes and one grouped native body differential/cost probe and one fixed duplex-H2 owner group (not TLS authentication); never pressure evidence", + "expectedCaseCount":121,"semanticCaseCount":91,"operationalCaseCount":15,"productionCaseCount":5,"inlineLifecycleCaseCount":4,"planAdmissionCaseCount":4,"nativeBodyGroupCount":1,"h2OwnerGroupCount":1, + "compiledRecipeStorageBytes":static_literal_plan::Plan::recipe_storage_bytes(),"recipeMaxSteps":64, + "outerLaneReleasedBeforeProduction":true,"productionRuntimeJoined":production_runtime_joined, + "diagnosticsBefore":before,"diagnosticsAfter":diagnostics::snapshot()}), + ) +} + +// Private active diagnostics. No global hooks or production input can enable +// them. The target is a real running Tokio task, blocked inside the same BIP +// policy helper used by production Plan, while owning real input/output/state. +const INLINE_PROBE_BYTES: usize = 65536; +#[derive(Clone, Copy, PartialEq, Eq)] +enum InlineProbe { + Abort, + CancelAbort, + Panic, + RuntimeDrop, +} +struct DropMark(std::sync::Arc); +impl Drop for DropMark { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::Release); + } +} +struct Tracked { + // Field drop order matters: the actual owner is dropped before the witness. + value: T, + _mark: DropMark, +} +struct InlineFixture { + source: Tracked, + output: Tracked, + last_source: bytes::Bytes, + source_dropped: std::sync::Arc, + output_dropped: std::sync::Arc, + source_cost: usize, + output_cost: usize, +} +#[derive(Clone, Copy, Default)] +struct InlineObserved { + gate_entered: bool, + gate_released: bool, + operation_returned: bool, + succeeded: bool, + error: Option, + output_bytes: usize, + output_matches: bool, +} +type SharedInlineObserved = std::sync::Arc>; +fn observed(slot: &SharedInlineObserved) -> InlineObserved { + *slot + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) +} +fn inline_fixture(budget: &Budget) -> io::Result { + use std::sync::{Arc, atomic::AtomicBool}; + let source = Entity::identity( + fixture(budget, &Input::Repeat(b'a', INLINE_PROBE_BYTES))? + .ok_or(io::ErrorKind::OutOfMemory)?, + ); + let last_source = source.wire().slice(0..1); + let output = + BudgetedBytes::new(budget, INLINE_PROBE_BYTES).ok_or(io::ErrorKind::OutOfMemory)?; + let source_dropped = Arc::new(AtomicBool::new(false)); + let output_dropped = Arc::new(AtomicBool::new(false)); + let cost = + BudgetedBytes::allocation_cost(INLINE_PROBE_BYTES).ok_or(io::ErrorKind::OutOfMemory)?; + Ok(InlineFixture { + source: Tracked { + value: source, + _mark: DropMark(source_dropped.clone()), + }, + output: Tracked { + value: output, + _mark: DropMark(output_dropped.clone()), + }, + last_source, + source_dropped, + output_dropped, + source_cost: cost, + output_cost: cost, + }) +} +async fn inline_probe_task( + owners: (Tracked, Tracked), + mode: InlineProbe, + cancellation: CancellationToken, + deadline: Instant, + entered: tokio::sync::oneshot::Sender<()>, + release: std::sync::mpsc::Receiver<()>, + state: SharedInlineObserved, +) -> io::Result<()> { + let (source, mut output) = owners; + let plan = static_literal_plan::compile(&body( + "input.body.data.replaceAll('a','b').replaceAll('b','c')", + )) + .ok_or(io::ErrorKind::InvalidData)?; + let _permit = tokio::time::timeout_at( + tokio::time::Instant::from_std(deadline), + super::EXECUTION_LANE.acquire(), + ) + .await + .map_err(|_| io::ErrorKind::TimedOut)? + .map_err(|_| io::ErrorKind::BrokenPipe)?; + let hook_state = state.clone(); + let mut entered = Some(entered); + // Move Receiver into the hook: it is Send, not Sync, and must not be + // captured through a shared borrowed reference by a Send callback. + let mut hook = move |filled| { + if filled != 256 { + return; + } + hook_state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .gate_entered = true; + if let Some(sender) = entered.take() { + let _ = sender.send(()); + } + let released = release + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .is_ok(); + hook_state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .gate_released = released; + if mode == InlineProbe::Panic && released { + panic!("fixed inline diagnostic unwind"); + } + }; + let attempt = super::run_plan_inline(|| { + plan.try_execute_for_validation( + &json!({"body":{"kind":"text"}}), + source.value.borrowed_body(), + &mut output.value, + &cancellation, + deadline, + static_literal_plan::Validation { + force_dag: false, + after_chunk: Some(&mut hook), + }, + ) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput)) + })?; + { + let mut state = state + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + state.operation_returned = true; + state.succeeded = attempt.result.is_ok(); + state.error = attempt.result.as_ref().err().map(io::Error::kind); + state.output_bytes = output.value.as_ref().len(); + state.output_matches = output.value.as_ref().len() == INLINE_PROBE_BYTES + && output.value.as_ref().iter().all(|byte| *byte == b'c'); + } + attempt.result.map(|_| ()) +} +fn join_disposition(result: &Result, tokio::task::JoinError>) -> &'static str { + match result { + Ok(Ok(())) => "ready-ok", + Ok(Err(_)) => "ready-error", + Err(error) if error.is_cancelled() => "cancelled", + Err(error) if error.is_panic() => "panic", + Err(_) => "other-join-error", + } +} +fn inline_counter_delta(before: &Value, after: &Value, key: &str) -> Option { + after["counters"][key] + .as_u64()? + .checked_sub(before["counters"][key].as_u64()?) +} +async fn inline_lifecycle_case(id: &'static str, mode: InlineProbe) -> io::Result { + use std::sync::{Arc, atomic::Ordering}; + let budget = Budget::default(); + let setup = inline_fixture(&budget)?; + let state = Arc::new(std::sync::Mutex::new(InlineObserved::default())); + let (entered_tx, entered_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = std::sync::mpsc::sync_channel(1); + let cancellation = CancellationToken::new(); + let deadline = Instant::now() + INVOCATION_LIMIT; + let before = diagnostics::snapshot(); + let task = tokio::spawn(inline_probe_task( + (setup.source, setup.output), + mode, + cancellation.clone(), + deadline, + entered_tx, + release_rx, + state.clone(), + )); + let abort = task.abort_handle(); + let source_drop = setup.source_dropped.clone(); + let output_drop = setup.output_dropped.clone(); + let watched = state.clone(); + let observer_budget = budget.clone(); + let base_cost = setup.source_cost + setup.output_cost; + // This is another actual task on a one-worker runtime. BIP must allow it + // and its timer to progress while the target's synchronous poll is gated. + let controller = tokio::spawn(async move { + let entered = matches!( + tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), entered_rx).await, + Ok(Ok(())) + ); + if mode == InlineProbe::Abort || mode == InlineProbe::CancelAbort { + abort.abort(); + } + if mode == InlineProbe::CancelAbort { + cancellation.cancel(); + } + tokio::time::sleep(Duration::from_millis(1)).await; + let source_live = !source_drop.load(Ordering::Acquire); + let output_live = !output_drop.load(Ordering::Acquire); + let not_returned = !observed(&watched).operation_returned && !abort.is_finished(); + let lane_held = super::EXECUTION_LANE.try_acquire().is_err(); + // Both real body owners plus Workspace must still be charged. No + // synthetic pressure reservation or test-only Budget.used is needed. + let owners_and_state_paid = observer_budget.reserve(WORKSPACE - base_cost).is_none(); + let released = release_tx.send(()).is_ok(); + ( + entered, + source_live, + output_live, + not_returned, + lane_held, + owners_and_state_paid, + released, + ) + }); + // Always observe the actual target completion, including a controller + // panic. The hook has the original absolute deadline as its watchdog. + let proof_result = controller.await; + let result = task.await; + let proof = proof_result.map_err(io::Error::other)?; + let after = diagnostics::snapshot(); + let actual = observed(&state); + let panic_result = result.as_ref().is_err_and(|error| error.is_panic()); + // Abort of a running poll may still resolve Ready. Only explicit business + // cancellation requires Interrupted from the actual Plan operation. + let operation_expected = if mode == InlineProbe::Panic { + panic_result && !actual.operation_returned + } else if mode == InlineProbe::CancelAbort { + actual.operation_returned + && actual.error == Some(io::ErrorKind::Interrupted) + && actual.output_bytes == 0 + } else { + actual.operation_returned && actual.succeeded && actual.output_matches + }; + let join_expected = if mode == InlineProbe::Panic { + panic_result + } else { + result.is_ok() || result.as_ref().is_err_and(|error| error.is_cancelled()) + }; + let counter_expected = inline_counter_delta(&before, &after, "planInlineEntered") == Some(1) + && inline_counter_delta(&before, &after, "planInlineReturned") + == Some(u64::from(mode != InlineProbe::Panic)) + && inline_counter_delta(&before, &after, "planInlinePanicked") + == Some(u64::from(mode == InlineProbe::Panic)) + && inline_counter_delta(&before, &after, "planOwnerStarted") == Some(0) + && inline_counter_delta(&before, &after, "planOwnerJoined") == Some(0); + let dropped = setup.source_dropped.load(Ordering::Acquire) + && setup.output_dropped.load(Ordering::Acquire); + let source_slice_held = budget.reserve(WORKSPACE).is_none() + && budget.reserve(WORKSPACE - setup.source_cost).is_some() + && setup.last_source.as_ref() == b"a"; + drop(setup.last_source); + let refunded = budget.reserve(WORKSPACE).is_some(); + let proof_ok = proof.0 && proof.1 && proof.2 && proof.3 && proof.4 && proof.5 && proof.6; + Ok( + json!({"id":id,"kind":"inline-lifecycle","passed":proof_ok && actual.gate_entered && actual.gate_released && operation_expected && join_expected && counter_expected && dropped && source_slice_held && refunded, + "targetGateEntered":proof.0,"sourceLiveDuringAbort":proof.1,"outputLiveDuringAbort":proof.2, + "pollNotReturnedBeforeRelease":proof.3,"sameLaneHeldDuringAbort":proof.4,"ownersAndWorkspaceStillPaid":proof.5, + "controllerAndTimerProgressed":proof.6,"operationReturned":actual.operation_returned,"operationSucceeded":actual.succeeded,"outputMatchesExpected":actual.output_matches, + "actualErrorKind":actual.error.map(|kind|format!("{:?}",kind)),"joinDisposition":join_disposition(&result), + "panicObserved":panic_result,"inlineCountersObserved":counter_expected,"ownersDroppedAfterCompletion":dropped, + "lastSourceSliceHeldCredit":source_slice_held,"budgetFullyRefunded":refunded,"abortOnlyMayReturnReady":true, + "scope":"real one-worker task abort/cancel/unwind during the shared BIP helper; no Message commit attempted"}), + ) +} + +fn inline_runtime_drop_case() -> io::Result { + use std::future::Future; + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + let budget = Budget::default(); + let setup = inline_fixture(&budget)?; + let state = Arc::new(std::sync::Mutex::new(InlineObserved::default())); + let (entered_tx, entered_rx) = tokio::sync::oneshot::channel(); + let (release_tx, release_rx) = std::sync::mpsc::sync_channel(1); + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(1) + .enable_time() + .build()?; + let deadline = Instant::now() + INVOCATION_LIMIT; + let before = diagnostics::snapshot(); + let mut task = runtime.spawn(inline_probe_task( + (setup.source, setup.output), + InlineProbe::RuntimeDrop, + CancellationToken::new(), + deadline, + entered_tx, + release_rx, + state.clone(), + )); + let entered = matches!( + runtime.block_on(async { + tokio::time::timeout_at(tokio::time::Instant::from_std(deadline), entered_rx).await + }), + Ok(Ok(())) + ); + let finished = Arc::new(AtomicBool::new(false)); + let drop_finished = finished.clone(); + let (drop_started_tx, drop_started_rx) = std::sync::mpsc::sync_channel(1); + let (drop_done_tx, drop_done_rx) = std::sync::mpsc::sync_channel(1); + let base_cost = setup.source_cost + setup.output_cost; + let (drop_started, returned_early, owners_held, paid, lane_held, released, drop_thread_joined) = + std::thread::scope(|scope| { + let dropper = scope.spawn(move || { + // This signal is before calling Drop: a2ms non-return observation + // requires that this controller is subsequently scheduled. It + // does not prove the destructor has already been entered. + let _ = drop_started_tx.send(()); + // Actual normal Runtime drop, never shutdown_timeout/background. + drop(runtime); + drop_finished.store(true, Ordering::Release); + let _ = drop_done_tx.send(()); + }); + let started = drop_started_rx.recv_timeout(INVOCATION_LIMIT).is_ok(); + let returned_early = drop_done_rx.recv_timeout(Duration::from_millis(2)).is_ok(); + let held = !setup.source_dropped.load(Ordering::Acquire) + && !setup.output_dropped.load(Ordering::Acquire) + && !observed(&state).operation_returned + && !task.is_finished(); + let paid = budget.reserve(WORKSPACE - base_cost).is_none(); + let lane = super::EXECUTION_LANE.try_acquire().is_err(); + let released = release_tx.send(()).is_ok(); + let joined = dropper.join().is_ok(); + (started, returned_early, held, paid, lane, released, joined) + }); + let context = &mut std::task::Context::from_waker(std::task::Waker::noop()); + let join = match std::pin::Pin::new(&mut task).poll(context) { + std::task::Poll::Ready(result) => Some(result), + std::task::Poll::Pending => None, + }; + let after = diagnostics::snapshot(); + let actual = observed(&state); + let counters = inline_counter_delta(&before, &after, "planInlineEntered") == Some(1) + && inline_counter_delta(&before, &after, "planInlineReturned") == Some(1) + && inline_counter_delta(&before, &after, "planInlinePanicked") == Some(0) + && inline_counter_delta(&before, &after, "planOwnerStarted") == Some(0) + && inline_counter_delta(&before, &after, "planOwnerJoined") == Some(0); + let owners_dropped = setup.source_dropped.load(Ordering::Acquire) + && setup.output_dropped.load(Ordering::Acquire); + let slice_held = budget.reserve(WORKSPACE).is_none() + && budget.reserve(WORKSPACE - setup.source_cost).is_some(); + drop(setup.last_source); + let refunded = budget.reserve(WORKSPACE).is_some(); + let joined = finished.load(Ordering::Acquire) && drop_thread_joined && join.is_some(); + Ok( + json!({"id":"inline-runtime-drop-barrier","kind":"inline-lifecycle","passed":entered && drop_started && !returned_early && owners_held && paid && lane_held && released && joined && actual.gate_released && actual.operation_returned && actual.succeeded && actual.output_matches && counters && owners_dropped && slice_held && refunded, + "targetGateEntered":entered,"runtimeDropAboutToStart":drop_started,"runtimeReturnedBeforeGateRelease":returned_early, + "ownersLiveWhileRuntimeDropping":owners_held,"ownersAndWorkspaceStillPaid":paid,"sameLaneHeld":lane_held, + "runtimeActuallyDroppedAndJoined":joined,"joinDisposition":join.as_ref().map(join_disposition), + "inlineCountersObserved":counters,"ownersDroppedAfterCompletion":owners_dropped,"lastSourceSliceHeldCredit":slice_held, + "budgetFullyRefunded":refunded,"scope":"actual normal Runtime::drop on an owned scoped controller; no timeout shutdown or abandoned task"}), + ) +} + +// Dedicated, real production Message regressions for output payload admission. +// Existing direct comparisons and the original 109 rows remain separate. +#[derive(Clone, Copy, PartialEq, Eq)] +enum PlanAdmissionProbe { + ReleaseThenRun, + QueueTimeout, + QueueCancel, + PayloadReject, +} +async fn plan_admission_case(id: &'static str, mode: PlanAdmissionProbe) -> io::Result { + const LENGTH: usize = 65536; + let source = "function rewrite(input){const payload=input.body.data.replaceAll('-', '_');return {headers:[{op:'set',name:'X-Proof',values:['ok']}],type:'modify',body:{kind:'text',data:payload}};}"; + let policy = Policy::compile(&format!( + "http-scripts:\n enabled: true\n scripts:\n - name: diagnostic-admission\n phase: request\n match: exact\n url: https://fixture.invalid/original\n body: text\n source: {}\n", + serde_json::to_string(source).map_err(io::Error::other)? + ))?; + let budget = policy.body_budget().clone(); + let url = url::Url::parse("https://fixture.invalid/original").map_err(io::Error::other)?; + let entity = Entity::identity( + fixture(&budget, &Input::Repeat(b'-', LENGTH))?.ok_or(io::ErrorKind::OutOfMemory)?, + ); + let old = entity.wire().clone(); + let input_cost = BudgetedBytes::allocation_cost(LENGTH).ok_or(io::ErrorKind::OutOfMemory)?; + let bookkeeping = BudgetedBytes::allocation_cost(0).ok_or(io::ErrorKind::OutOfMemory)?; + // Exactly the existing output-owner bookkeeping remains available. A full + // output cannot be allocated until this pressure is actually released. + let mut pressure = Some( + budget + .reserve(WORKSPACE - input_cost - bookkeeping) + .ok_or(io::ErrorKind::OutOfMemory)?, + ); + let mut held_lane = if mode == PlanAdmissionProbe::PayloadReject { + None + } else { + Some( + super::EXECUTION_LANE + .acquire() + .await + .map_err(|_| io::ErrorKind::BrokenPipe)?, + ) + }; + let cancellation = CancellationToken::new(); + let target_cancellation = cancellation.clone(); + let before = diagnostics::snapshot(); + let mut task = tokio::spawn(async move { + let mut message = Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: true, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: vec![], + }, + Some(entity), + &vec![], + false, + ); + let initial_headers = message.request.headers.clone(); + let result = script_message::run(&policy, &url, &mut message, &target_cancellation).await; + (result, message, initial_headers) + }); + let mut queued_without_payload = false; + if mode != PlanAdmissionProbe::PayloadReject { + let observation_deadline = Instant::now() + INVOCATION_LIMIT; + let seen = loop { + if inline_counter_delta(&before, &diagnostics::snapshot(), "queueRequested") == Some(1) + { + break true; + } + if task.is_finished() || Instant::now() >= observation_deadline { + break false; + } + tokio::task::yield_now().await; + }; + let waiting = diagnostics::snapshot(); + queued_without_payload = seen + && !task.is_finished() + && inline_counter_delta(&before, &waiting, "planOutputPendingAdmitted") == Some(1) + && inline_counter_delta(&before, &waiting, "callBuffersAdmitted") == Some(0) + && inline_counter_delta(&before, &waiting, "planEntered") == Some(0) + && budget.reserve(1).is_none(); + if mode == PlanAdmissionProbe::ReleaseThenRun { + drop(pressure.take()); + drop(held_lane.take()); + } else if mode == PlanAdmissionProbe::QueueCancel { + cancellation.cancel(); + } + } + // Never detach the target on a harness watchdog. Cancellation plus release + // is followed by its actual JoinHandle completion before any owner proof. + let completed_within_watchdog = + tokio::time::timeout(Duration::from_millis(200), &mut task).await; + let watchdog_observed = completed_within_watchdog.is_ok(); + let completed = match completed_within_watchdog { + Ok(result) => result, + Err(_) => { + cancellation.cancel(); + drop(held_lane.take()); + drop(pressure.take()); + task.await + } + }; + let after = diagnostics::snapshot(); + let (result, message, initial_headers) = completed.map_err(io::Error::other)?; + let delta = |key| inline_counter_delta(&before, &after, key); + let success = mode == PlanAdmissionProbe::ReleaseThenRun; + let payload_rejected = mode == PlanAdmissionProbe::PayloadReject; + let queue_failed = matches!( + mode, + PlanAdmissionProbe::QueueTimeout | PlanAdmissionProbe::QueueCancel + ); + let outcome = if mode == PlanAdmissionProbe::QueueCancel { + result + .as_ref() + .is_err_and(|error| error.kind() == io::ErrorKind::Interrupted) + } else { + matches!(&result, Ok(Outcome::Forward)) + }; + let expected_byte = if success { b'_' } else { b'-' }; + let body_correct = message + .body + .as_ref() + .and_then(Entity::logical) + .is_some_and(|bytes| { + bytes.len() == LENGTH && bytes.iter().all(|byte| *byte == expected_byte) + }); + let header_correct = if success { + message + .request + .headers + .iter() + .any(|(name, value)| name == "x-proof" && value == "ok") + } else { + message.request.headers == initial_headers + }; + let counters = delta("planSelected") == Some(1) + && delta("planFinalSingleStepEntered") == Some(u64::from(success)) + && delta("planOutputPayloadBudgetRejected") == Some(u64::from(payload_rejected)) + && delta("planOutputPendingAdmitted") == Some(1) + && delta("planOutputQueueFailed") == Some(u64::from(queue_failed)) + && delta("callBuffersRequested") == Some(1) + && delta("callBuffersAdmitted") == Some(u64::from(success)) + && delta("callBuffersBudgetRejected") == Some(u64::from(payload_rejected)) + && delta("planBuffersRejected") == Some(u64::from(payload_rejected)) + && delta("skipCallBuffers") == Some(u64::from(payload_rejected)) + && delta("queueRequested") == Some(1) + && delta("queueAcquired") == Some(u64::from(!queue_failed)) + && delta("queueTimeout") == Some(u64::from(mode == PlanAdmissionProbe::QueueTimeout)) + && delta("queueCancelled") == Some(u64::from(mode == PlanAdmissionProbe::QueueCancel)) + && delta("planEntered") == Some(u64::from(success)) + && delta("planSucceeded") == Some(u64::from(success)) + && delta("planInlineEntered") == Some(u64::from(success)) + && delta("planInlineReturned") == Some(u64::from(success)) + && delta("planInlinePanicked") == Some(0) + && delta("evaluationEntered") == Some(0) + && delta("contextCreated") == Some(0) + && delta("contextReleased") == Some(0) + && delta("jscOwnerStarted") == Some(0) + && delta("jscOwnerJoined") == Some(0) + && delta("planOwnerStarted") == Some(0) + && delta("planOwnerJoined") == Some(0) + && delta("outputAccepted") == Some(u64::from(success)); + // For queued failures and payload refusal, only the original input and + // controller pressure may remain. The per-call Q must already be refunded. + let pending_refunded = if success { + None + } else { + Some(budget.reserve(bookkeeping).is_some()) + }; + let bookkeeping_resolved = if success { + delta("callBuffersAdmitted") == Some(1) + } else { + pending_refunded == Some(true) + }; + drop(held_lane.take()); + let lane_returned = super::EXECUTION_LANE.try_acquire().is_ok(); + drop(pressure.take()); + let original_unchanged = old.len() == LENGTH && old.iter().all(|byte| *byte == b'-'); + drop(message); + let last_source = old.slice(0..1); + drop(old); + let last_slice_paid = + budget.reserve(WORKSPACE).is_none() && budget.reserve(WORKSPACE - input_cost).is_some(); + drop(last_source); + let refunded = budget.reserve(WORKSPACE).is_some(); + Ok( + json!({"id":id,"kind":"plan-output-admission","passed":(mode==PlanAdmissionProbe::PayloadReject || queued_without_payload) && watchdog_observed && outcome && body_correct && header_correct && counters && bookkeeping_resolved && lane_returned && original_unchanged && last_slice_paid && refunded, + "queueProbeApplicable":mode!=PlanAdmissionProbe::PayloadReject,"queuedWithOnlyOwnerBookkeeping":if mode==PlanAdmissionProbe::PayloadReject{None}else{Some(queued_without_payload)},"actualTargetJoined":true,"completedWithinHarnessWatchdog":watchdog_observed, + "outcomeMatches":outcome,"bodyAndHeaderMatch":body_correct && header_correct,"admissionCountersMatch":counters, + "actualErrorKind":result.as_ref().err().map(|error|format!("{:?}",error.kind())), + "pendingBookkeepingRefunded":pending_refunded,"pendingOwnerDisposition":if success{"promoted-to-real-output"}else{"refunded"},"sameLaneReturned":lane_returned,"originalOwnerUnchanged":original_unchanged, + "lastSourceSliceStillPaid":last_slice_paid,"budgetFullyRefunded":refunded, + "scope":"actual Message.run/default lane; full output payload cannot coexist with held exact pressure; no JSC replay"}), + ) +} diff --git a/src/http_processing/scripts/platform_init.rs b/src/http_processing/scripts/platform_init.rs new file mode 100644 index 0000000..f1dfec6 --- /dev/null +++ b/src/http_processing/scripts/platform_init.rs @@ -0,0 +1,317 @@ +//! Process state only: neither this owner nor Ready retains a JSC object. +use std::{ + io, + sync::{Condvar, Mutex, MutexGuard}, +}; +use tokio_util::sync::CancellationToken; + +#[derive(Clone, Copy)] +enum State { + Cold, + Initializing, + Ready, +} + +pub(super) struct Initialization { + state: Mutex, + changed: Condvar, + #[cfg(test)] + waiting: std::sync::atomic::AtomicUsize, +} + +impl Initialization { + pub(super) const fn new() -> Self { + Self { + state: Mutex::new(State::Cold), + changed: Condvar::new(), + #[cfg(test)] + waiting: std::sync::atomic::AtomicUsize::new(0), + } + } + + fn lock(&self) -> MutexGuard<'_, State> { + // Only this private enum is protected. Never permanently cache a + // poisoned initialization failure or hold this lock across platform API. + self.state.lock().unwrap_or_else(|error| error.into_inner()) + } + + pub(super) fn ensure( + &self, + cancellation: &CancellationToken, + initialize: impl FnOnce() -> io::Result<()>, + ) -> io::Result<()> { + let mut state = self.lock(); + // An initially cancelled caller never joins an attempt. Once a caller + // has observed Initializing, spurious wakes must not let it escape the + // real initializer's joined completion barrier. + if cancellation.is_cancelled() { + return Err(io::ErrorKind::Interrupted.into()); + } + loop { + match *state { + State::Ready | State::Cold => { + if cancellation.is_cancelled() { + return Err(io::ErrorKind::Interrupted.into()); + } + if matches!(*state, State::Ready) { + return Ok(()); + } + *state = State::Initializing; + break; + } + State::Initializing => { + // An in-flight platform API cannot be interrupted. Wait + // for its actual joined end before observing cancellation. + #[cfg(test)] + self.waiting + .fetch_add(1, std::sync::atomic::Ordering::SeqCst); + state = self + .changed + .wait(state) + .unwrap_or_else(|error| error.into_inner()); + #[cfg(test)] + self.waiting + .fetch_sub(1, std::sync::atomic::Ordering::SeqCst); + } + } + } + drop(state); + let mut attempt = Attempt { + owner: self, + finished: false, + }; + let result = initialize(); + attempt.finish(result.is_ok()); + // Successful platform initialization remains Ready even if its caller + // was cancelled while the thread was running. No user VM is retained. + if cancellation.is_cancelled() { + Err(io::ErrorKind::Interrupted.into()) + } else { + result + } + } +} + +struct Attempt<'a> { + owner: &'a Initialization, + finished: bool, +} +impl Attempt<'_> { + fn finish(&mut self, successful: bool) { + *self.owner.lock() = if successful { + State::Ready + } else { + State::Cold + }; + self.finished = true; + self.owner.changed.notify_all(); + } +} +impl Drop for Attempt<'_> { + fn drop(&mut self) { + if !self.finished { + // The scoped worker has already joined before unwinding reaches + // this guard; a later preparation may retry a failed attempt. + self.finish(false); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::sync::{ + Arc, Barrier, + atomic::{AtomicUsize, Ordering}, + mpsc, + }; + + #[test] + fn platform_initialization_cancelled_waiter_survives_spurious_wake_until_join() { + let initialization = Arc::new(Initialization::new()); + let entered = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + let owner = { + let initialization = initialization.clone(); + let entered = entered.clone(); + let release = release.clone(); + std::thread::spawn(move || { + initialization.ensure(&CancellationToken::new(), || { + entered.wait(); + release.wait(); + Ok(()) + }) + }) + }; + entered.wait(); + let cancellation = CancellationToken::new(); + let (finished, finishes) = mpsc::channel(); + let waiter = { + let initialization = initialization.clone(); + let cancellation = cancellation.clone(); + std::thread::spawn(move || { + let result = initialization.ensure(&cancellation, || panic!("second initializer")); + finished.send(result.map_err(|error| error.kind())).unwrap(); + }) + }; + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while initialization.waiting.load(Ordering::SeqCst) == 0 + && std::time::Instant::now() < deadline + { + std::thread::yield_now(); + } + let observed_waiter = initialization.waiting.load(Ordering::SeqCst) > 0; + { + // Lock acquisition also waits for the waiter to enter its real + // Condvar wait and release this mutex; the wake cannot be missed. + let _state = initialization.lock(); + cancellation.cancel(); + initialization.changed.notify_all(); + } + let premature = finishes.recv_timeout(std::time::Duration::from_millis(100)); + release.wait(); + owner.join().unwrap().unwrap(); + let final_result = match premature { + Ok(value) => value, + Err(_) => finishes + .recv_timeout(std::time::Duration::from_secs(2)) + .unwrap(), + }; + waiter.join().unwrap(); + assert!( + observed_waiter, + "fixture did not enter the actual waiter path" + ); + assert!( + premature.is_err(), + "cancelled waiter escaped before owner join" + ); + assert_eq!(final_result, Err(io::ErrorKind::Interrupted)); + } + + #[test] + fn success_is_process_state_only_and_error_can_retry() { + let initialization = Initialization::new(); + let cancellation = CancellationToken::new(); + assert_eq!( + initialization + .ensure(&cancellation, || Err(io::ErrorKind::OutOfMemory.into())) + .unwrap_err() + .kind(), + io::ErrorKind::OutOfMemory + ); + let calls = AtomicUsize::new(0); + initialization + .ensure(&cancellation, || { + calls.fetch_add(1, Ordering::SeqCst); + Ok(()) + }) + .unwrap(); + initialization + .ensure(&cancellation, || { + panic!("successful initialization repeated") + }) + .unwrap(); + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn panic_resets_state_for_retry() { + let initialization = Initialization::new(); + let cancellation = CancellationToken::new(); + let panic = std::panic::catch_unwind(|| { + let _ = initialization.ensure(&cancellation, || panic!("initialization fixture")); + }); + assert!(panic.is_err()); + initialization.ensure(&cancellation, || Ok(())).unwrap(); + } + + #[test] + fn concurrent_preparation_has_one_initializer_and_no_abandoned_worker() { + let initialization = Arc::new(Initialization::new()); + let entered = Arc::new(Barrier::new(2)); + let release = Arc::new(Barrier::new(2)); + let calls = Arc::new(AtomicUsize::new(0)); + let owner = { + let initialization = initialization.clone(); + let entered = entered.clone(); + let release = release.clone(); + let calls = calls.clone(); + std::thread::spawn(move || { + initialization.ensure(&CancellationToken::new(), || { + calls.fetch_add(1, Ordering::SeqCst); + entered.wait(); + release.wait(); + Ok(()) + }) + }) + }; + entered.wait(); + let (starting, starts) = mpsc::channel(); + let (finished, finishes) = mpsc::channel(); + let waiters: Vec<_> = (0..4) + .map(|_| { + let initialization = initialization.clone(); + let starting = starting.clone(); + let finished = finished.clone(); + std::thread::spawn(move || { + starting.send(()).unwrap(); + initialization + .ensure(&CancellationToken::new(), || { + panic!("concurrent second initializer") + }) + .unwrap(); + finished.send(()).unwrap(); + }) + }) + .collect(); + for _ in 0..4 { + starts.recv().unwrap(); + } + assert!(matches!( + finishes.try_recv(), + Err(mpsc::TryRecvError::Empty) + )); + release.wait(); + owner.join().unwrap().unwrap(); + for waiter in waiters { + waiter.join().unwrap(); + } + assert_eq!(calls.load(Ordering::SeqCst), 1); + } + + #[test] + fn cancelled_cold_preparation_does_not_start_initialization() { + let initialization = Initialization::new(); + let cancellation = CancellationToken::new(); + cancellation.cancel(); + assert_eq!( + initialization + .ensure(&cancellation, || panic!("cancelled initialization started")) + .unwrap_err() + .kind(), + io::ErrorKind::Interrupted + ); + initialization + .ensure(&CancellationToken::new(), || Ok(())) + .unwrap(); + } + + #[cfg(target_vendor = "apple")] + #[test] + fn real_platform_context_is_released_on_a_joined_owner_thread() { + let initialization = Initialization::new(); + let parent = std::thread::current().id(); + initialization + .ensure(&CancellationToken::new(), || { + super::super::run_on_scoped_thread_named("vole-http-js-init-test", || { + assert_ne!(std::thread::current().id(), parent); + super::super::apple::initialize_platform() + }) + }) + .unwrap(); + initialization + .ensure(&CancellationToken::new(), || panic!("real warmup repeated")) + .unwrap(); + } +} diff --git a/src/http_processing/scripts/runtime.js b/src/http_processing/scripts/runtime.js new file mode 100644 index 0000000..8637236 --- /dev/null +++ b/src/http_processing/scripts/runtime.js @@ -0,0 +1,488 @@ +"use strict"; +// Trusted prelude. The AST frontend cannot name these helpers, introduce +// functions/accessors or call anything outside its explicit method allowlist. +const __voleLimit = 262144; +let __voleAllocated = 0; +function __voleCharge(n) { + __voleTick(); + if (!Number.isSafeInteger(n) || n < 0 || n > 2097152 - __voleAllocated) + throw new Error("script allocation work exceeded"); + __voleAllocated += n; +} +function __voleTextSize(s, quoted) { + if (typeof s !== "string" || s.length > __voleLimit) throw new Error("invalid string"); + // Unquoted ASCII has one UTF-8 byte per code unit. Keep short strings and + // quoted/Unicode validation on the existing path; check the deadline after + // the bounded native scan before accepting its result. + if (!quoted && s.length >= 4096) { + const ascii = __voleIsASCII(s, s.length); + if (ascii === true || (ascii === undefined && !/[^\x00-\x7f]/.test(s))) { + __voleTick(); + return s.length; + } + } + let n = quoted ? 2 : 0; + for (let i = 0; i < s.length; i++) { + if ((i & 255) === 0) __voleTick(); + const c = s.charCodeAt(i); + if (c >= 0xD800 && c <= 0xDBFF) { + if (++i >= s.length || s.charCodeAt(i) < 0xDC00 || s.charCodeAt(i) > 0xDFFF) + throw new Error("isolated surrogate"); + n += 4; + } else if (c >= 0xDC00 && c <= 0xDFFF) { + throw new Error("isolated surrogate"); + } else if (quoted && (c === 34 || c === 92)) n += 2; + else if (quoted && c < 32) n += [8,9,10,12,13].includes(c) ? 2 : 6; + else n += c < 128 ? 1 : c < 2048 ? 2 : 3; + if (n > __voleLimit) throw new Error("string byte limit"); + } + return n; +} +function __volePrimitive(v) { + if (v !== null && !["undefined","boolean","number","string"].includes(typeof v)) + throw new Error("implicit object conversion"); + if (typeof v === "number" && !Number.isFinite(v)) throw new Error("nonfinite number"); + return v; +} +function __voleConvert(name,v) { + __voleTick(); __volePrimitive(v); + if (name === "String") return __voleValue(String(v)); + if (name === "Number") return __voleValue(Number(v)); + if (name === "Boolean") return Boolean(v); + throw new Error("unsupported conversion"); +} +function __voleKey(k) { + if (typeof k !== "string" && typeof k !== "number") throw new Error("invalid property key"); + __volePrimitive(k); k = String(k); + __voleTextSize(k,false); + if (k === "constructor" || k === "prototype" || k === "__proto__" || + k === "toJSON" || k.startsWith("__vole")) + throw new Error("unsupported property"); + return k; +} +function __voleValue(v) { + if (typeof v === "string") { + __voleTextSize(v,false); __voleCharge(v.length * 2 + 16); + } else if (typeof v === "number") { + if (!Number.isFinite(v)) throw new Error("nonfinite number"); + __voleCharge(8); + } else if (Array.isArray(v)) { + if (v.length > __voleLimit) throw new Error("array limit"); + __voleCharge(v.length * 24 + 32); + } else if (v instanceof Uint8Array) { + __voleCharge(__voleBinarySize(v) + 32); + } else if (v !== null && typeof v === "object") { + __voleCharge(Object.keys(v).length * 48 + 32); + } + return v; +} +function __voleAdd(a,b) { + __voleTick(); __volePrimitive(a); __volePrimitive(b); + if (typeof a === "string" || typeof b === "string") { + a = String(a); b = String(b); + if (__voleTextSize(a,false) + __voleTextSize(b,false) > __voleLimit) + throw new Error("string byte limit"); + __voleCharge((a.length+b.length)*2+16); + return a+b; + } + return __voleValue(a+b); +} +function __voleUnary(op,a) { + __voleTick(); __volePrimitive(a); + if (op === "+") return __voleValue(+a); + if (op === "-") return __voleValue(-a); + if (op === "~") return ~a; + throw new Error("unsupported unary operation"); +} +function __voleBinary(op,a,b) { + __voleTick(); __volePrimitive(a); __volePrimitive(b); + switch(op) { + case "-": return __voleValue(a-b); + case "*": return __voleValue(a*b); + case "/": return __voleValue(a/b); + case "%": return __voleValue(a%b); + case "<": return a": return a>b; + case ">=": return a>=b; + case "==": return a==b; + case "!=": return a!=b; + case "|": return a|b; + case "&": return a&b; + case "^": return a^b; + case "<<": return a<>": return a>>b; + case ">>>": return a>>>b; + } + throw new Error("unsupported binary operation"); +} +function __voleGet(o,k) { + __voleTick(); k = __voleKey(k); + if (o === null || o === undefined) throw new Error("null member access"); + const v = o[k]; + if (typeof v === "function" || typeof v === "symbol" || + (typeof v === "number" && !Number.isFinite(v))) + throw new Error("unsupported member value"); + return v; +} +function __voleSet(o,k,v) { + __voleTick(); k = __voleKey(k); + if (o === null || typeof o !== "object") throw new Error("invalid assignment"); + if (Array.isArray(o) || o instanceof Uint8Array) { + if (k === "length" || !/^(0|[1-9][0-9]*)$/.test(k) || Number(k) >= __voleLimit) + throw new Error("array index limit"); + const index = Number(k); + if (o instanceof Uint8Array) { + if (index >= o.length || typeof v !== "number" || !Number.isFinite(v)) + throw new Error("invalid byte assignment"); + } + __voleCharge(32 + Math.max(0,index+1-o.length)*24); + } else { + const p = Object.getPrototypeOf(o); + if (p !== Object.prototype && p !== null) throw new Error("invalid assignment target"); + __voleCharge(32+__voleTextSize(k,false)*2); + } + if (typeof v === "function" || typeof v === "symbol") throw new Error("invalid assigned value"); + o[k] = v; + return v; +} +function __voleBinarySize(v) { + let buffer, n; + if (v instanceof Uint8Array) { buffer=v.buffer; n=v.byteLength; } + else if (v instanceof ArrayBuffer) { buffer=v; n=v.byteLength; } + else throw new Error("byte buffer required"); + if (!(buffer instanceof ArrayBuffer) || buffer.resizable === true || n > __voleLimit) + throw new Error("unsupported byte buffer"); + // Unlike a detached view's length, this operation cannot turn detachment + // into an apparently valid zero-length body. No entity bytes are copied. + ArrayBuffer.prototype.slice.call(buffer,0,0); + return n; +} +function __voleMeasure(v,binary,skipBody) { + let visited=0; + const seen = new Set(); + function walk(v,depth) { + __voleTick(); + if (++visited > 32768 || depth > 64) throw new Error("result structure limit"); + if (v===null) return 4; + if (typeof v==="boolean") return v ? 4 : 5; + if (typeof v==="number") { + if (!Number.isFinite(v)) throw new Error("nonfinite number"); + return String(v).length; + } + if (typeof v==="string") return __voleTextSize(v,true); + if (binary && (v instanceof Uint8Array || v instanceof ArrayBuffer)) { + __voleBinarySize(v); return 0; + } + if (!v || typeof v!=="object" || seen.has(v)) throw new Error("invalid or shared result value"); + seen.add(v); + const p=Object.getPrototypeOf(v), array=Array.isArray(v); + if (p!==Object.prototype && p!==Array.prototype && p!==null) + throw new Error("invalid result prototype"); + const keys=Object.getOwnPropertyNames(v); + if (Object.getOwnPropertySymbols(v).length || keys.length>32768) throw new Error("result property limit"); + let size=2, count=0; + if (array && (v.length>32768 || keys.length!==v.length+1)) throw new Error("sparse result array"); + for (const k of keys) { + if (array && k==="length") continue; + const d=Object.getOwnPropertyDescriptor(v,k); + if (!d || !d.enumerable || d.get || d.set || k==="toJSON") throw new Error("result accessor"); + if (v===skipBody && k==="data") continue; + if (array && !/^(0|[1-9][0-9]*)$/.test(k)) throw new Error("invalid array property"); + size += (count++ ? 1 : 0) + (array ? 0 : __voleTextSize(k,true)+1) + walk(d.value,depth+1); + if (size>__voleLimit) throw new Error("encoded JSON limit"); + } + return size; + } + return walk(v,0); +} +function __voleJSONInput(s) { + __voleTextSize(s,false); + let depth=0, nodes=0, string=false, escaped=false; + for (let i=0;i32768)throw new Error("JSON node limit"); } + else if (c===91 || c===123) { + if (++depth>64 || ++nodes>32768) throw new Error("JSON structure limit"); + } else if (c===93 || c===125) depth--; + else if (c===44 && ++nodes>32768) throw new Error("JSON node limit"); + } +} +function __voleRangeBytes(s,start,end) { + let n=0; + for(let i=start;i=0xD800 && c<=0xDBFF) { + if(++i>=end || s.charCodeAt(i)<0xDC00 || s.charCodeAt(i)>0xDFFF)throw new Error("isolated surrogate"); + n+=4; + } else if(c>=0xDC00 && c<=0xDFFF)throw new Error("isolated surrogate"); + else n+=c<128 ? 1 : c<2048 ? 2 : 3; + } + return n; +} +function __voleReplacementSize(s,search,replacement,all) { + const original=__voleTextSize(s,false), matched=__voleTextSize(search,false); + __voleTextSize(replacement,false); + // A literal ASCII substitution replaces one UTF-8 byte with one byte and + // cannot split a validated surrogate pair, regardless of the match count. + if(search.length===1 && replacement.length===1 && replacement!=="$" && + search.charCodeAt(0)<128 && replacement.charCodeAt(0)<128)return original; + let fixed=0, prefix=0, suffix=0, match=0; + for(let i=0;i=0xD800 && c<=0xDBFF){fixed+=4;i++;} + else fixed+=c<128 ? 1 : c<2048 ? 2 : 3; + } + if(search==="" && fixed===0 && prefix===0 && suffix===0)return original; + let size=original, at=0, previous=0, before=0; + while(at<=s.length) { + __voleTick(); + const found=search==="" ? at : s.indexOf(search,at); + if(found<0)break; + before+=__voleRangeBytes(s,previous,found); previous=found; + size+=fixed+match*matched+prefix*before+suffix*(original-before-matched)-matched; + if(size>__voleLimit)throw new Error("replacement size limit"); + if(!all)break; + at=found+(search.length || 1); + } + return size; +} +function __voleCall(o,k,args) { + __voleTick(); k=__voleKey(k); + if (args.length>8) throw new Error("too many arguments"); + if (o===JSON && (k==="parse" || k==="stringify")) { + if(args.length!==1)throw new Error("JSON callback unsupported"); + if(k==="parse") { + if(typeof args[0]!=="string")throw new Error("JSON string required"); + __voleJSONInput(args[0]); __voleCharge(args[0].length*8+32); + const result=JSON.parse(args[0]); + __voleMeasure(result,false,null); + return result; + } + const size=__voleMeasure(args[0],false,null); + __voleCharge(size*2+32); + return JSON.stringify(args[0]); + } + if(o===Object && ["keys","values","entries"].includes(k)) { + if(args.length!==1 || args[0]===null || typeof args[0]!=="object")throw new Error("Object argument"); + const n=(Array.isArray(args[0]) || args[0] instanceof Uint8Array) + ? args[0].length : Object.getOwnPropertyNames(args[0]).length; + if(n>32768)throw new Error("Object result limit"); + __voleCharge(n*(k==="entries" ? 96 : 24)+32); + return Object[k](args[0]); + } + if(o===Array && k==="isArray") { + if(args.length!==1)throw new Error("invalid Array call"); + return Array.isArray(args[0]); + } + if(o===Number && ["isFinite","isInteger"].includes(k)) { + if(args.length!==1)throw new Error("invalid Number call"); + return Number[k](args[0]); + } + if(o===Math && ["abs","floor","ceil","round","trunc","min","max"].includes(k)) { + for(const a of args)__volePrimitive(a); + return __voleValue(Math[k](...args)); + } + if(o===Uint8Array && k==="from") { + if(args.length!==1 || !Array.isArray(args[0]) || args[0].length>__voleLimit)throw new Error("invalid bytes"); + for(const n of args[0]) { + __voleTick(); + if(typeof n!=="number" || !Number.isFinite(n))throw new Error("invalid byte value"); + } + __voleCharge(args[0].length+32); + return Uint8Array.from(args[0]); + } + if(typeof o==="string") { + if(!["slice","substring","charAt","at","includes","startsWith","endsWith","indexOf","lastIndexOf","trim","toLowerCase","toUpperCase","split","replace","replaceAll"].includes(k)) + throw new Error("unsupported string method"); + __voleTextSize(o,false); + for(const a of args)__volePrimitive(a); + if(k==="split") { + if(args.length>2 || (args[0]!==undefined && typeof args[0]!=="string"))throw new Error("literal separator required"); + let limit=__voleLimit, parts=0; + if(args[1]!==undefined) { + if(!Number.isSafeInteger(args[1]) || args[1]<0 || args[1]>__voleLimit)throw new Error("split limit"); + limit=args[1]; + } + const sep=args[0]; + if(limit===0)parts=0; + else if(sep===undefined)parts=1; + else if(sep==="")parts=Math.min(o.length,limit); + else { + parts=1; let at=0; + while(parts__voleLimit)throw new Error("split result limit"); + __voleCharge(parts*24+o.length*2+32); + return o.split(sep,limit); + } + if(k==="replace" || k==="replaceAll") { + if(args.length!==2 || typeof args[0]!=="string" || typeof args[1]!=="string") + throw new Error("literal replacement required"); + const search=args[0], replacement=args[1]; + if(search==="" && replacement==="")return o; + const bytes=__voleReplacementSize(o,search,replacement,k==="replaceAll"); + __voleCharge(bytes*2+32); + // Only a bounded dense ASCII single-code-unit replaceAll is eligible. + // Keep the same size/work preflight and every existing tick boundary. + // Undefined leaves Unicode, templates, sparse input and failed bridge + // admission on the original intrinsic, with the same allocation charge. + if(k==="replaceAll" && o.length>=4096 && search.length===1 && + replacement.length===1 && replacement!=="$" && + search.charCodeAt(0)<128 && replacement.charCodeAt(0)<128) { + const native=__voleReplaceASCIIAll(o,o.length,search.charCodeAt(0),replacement.charCodeAt(0)); + if(native!==undefined)return native; + } + return k==="replace" ? o.replace(search,replacement) : o.replaceAll(search,replacement); + } + __voleCharge(o.length*6+32); + return __voleValue(String.prototype[k].apply(o,args)); + } + if(Array.isArray(o) || o instanceof Uint8Array) { + if(!["push","pop","slice","subarray","concat","join","indexOf","includes","reverse","at"].includes(k)) + throw new Error("unsupported array method"); + if(k==="join") { + if(args.length>1 || (args[0]!==undefined && typeof args[0]!=="string"))throw new Error("join separator"); + const sep=args[0]===undefined ? "," : args[0]; + let size=Math.max(0,o.length-1)*__voleTextSize(sep,false); + for(const item of o) { + __voleTick(); __volePrimitive(item); + if(item!==null && item!==undefined)size+=__voleTextSize(String(item),false); + if(size>__voleLimit)throw new Error("join result limit"); + } + __voleCharge(size*2+32); + return o.join(sep); + } + if(k==="push") { + if(!Array.isArray(o) || o.length+args.length>__voleLimit)throw new Error("push result limit"); + __voleCharge(args.length*24+32); + return o.push(...args); + } + if(k==="concat") { + if(!Array.isArray(o))throw new Error("unsupported typed array method"); + let n=o.length; + for(const a of args)n+=Array.isArray(a) ? a.length : 1; + if(n>__voleLimit)throw new Error("array size limit"); + __voleCharge(n*24+32); return o.concat(...args); + } + for(let i=0;iallowed.length)throw new Error("unknown field"); + for(const key of keys) { + const d=Object.getOwnPropertyDescriptor(v,key); + if(!allowed.includes(key) || !d || !d.enumerable || d.get || d.set || d.value===undefined) + throw new Error("invalid data field"); + } +} +function __voleHeaderName(name) { + if(typeof name!=="string" || !/^[!#$%&'*+.^_\x60|~0-9A-Za-z-]+$/.test(name))throw new Error("invalid header name"); + const key=name.toLowerCase(); + if(["host","content-length","transfer-encoding","content-encoding","connection","upgrade","expect","trailer","te","http2-settings","keep-alive","proxy-connection","proxy-authorization","proxy-authenticate","content-range"].includes(key)) + throw new Error("protected header"); + return __voleTextSize(name,false); +} +function __voleHeaderValue(value) { + if(typeof value!=="string" || /[\x00-\x08\x0a-\x1f\x7f]/.test(value))throw new Error("invalid header value"); + return __voleTextSize(value,false); +} +function __voleHeaders(headers,operations) { + if(!Array.isArray(headers) || headers.length>100)throw new Error("header count limit"); + let bytes=0, values=0; + for(const header of headers) { + __voleTick(); + if(!operations) { + __voleRecord(header,["name","value"]); + bytes+=__voleHeaderName(header.name)+__voleHeaderValue(header.value)+32; + values++; + } else { + __voleRecord(header,["op","name","values"]); + const name=__voleHeaderName(header.name); + if(header.op==="remove") { + if(Object.hasOwn(header,"values"))throw new Error("remove values"); + bytes+=name+32; + } else if(header.op==="set" || header.op==="add") { + if(!Array.isArray(header.values) || header.values.length===0 || header.values.length>100-values) + throw new Error("header value count"); + for(const value of header.values) { + bytes+=name+__voleHeaderValue(value)+32; values++; + if(bytes>32768)throw new Error("header byte limit"); + } + } else throw new Error("invalid header operation"); + } + if(bytes>32768 || values>100)throw new Error("header limit"); + } +} +// Private adapter ABI after Finish; primitive .length creates no API copy. +// No new controlled ticks or user ToPrimitive calls. +function __voleExportTextUnits(s) { + if(typeof s!=="string" || s.length>__voleLimit)throw new Error("invalid export text"); + return s.length; +} +function __voleFinish(v) { + if(!v || typeof v!=="object")throw new Error("invalid result"); + // Inspect descriptors before reading type, so a rejected accessor never runs. + __voleRecord(v,["type","url","method","status","headers","body"]); + const type=v.type; + if(type==="pass" || type==="abort")__voleRecord(v,["type"]); + else if(type==="modify")__voleRecord(v,["type","url","method","status","headers","body"]); + else if(type==="respond")__voleRecord(v,["type","status","headers","body"]); + else throw new Error("invalid result type"); + if(Object.hasOwn(v,"url")) { + if(typeof v.url!=="string" || __voleTextSize(v.url,false)>8192)throw new Error("URL limit"); + } + if(Object.hasOwn(v,"method")) { + if(typeof v.method!=="string" || !/^[!#$%&'*+.^_\x60|~0-9A-Za-z-]+$/.test(v.method) || __voleTextSize(v.method,false)>32768) + throw new Error("invalid method"); + } + if(Object.hasOwn(v,"status") || type==="respond") { + if(!Number.isInteger(v.status) || v.status<200 || v.status>599 || (type==="respond" && v.status===206)) + throw new Error("invalid status"); + } + if(Object.hasOwn(v,"headers"))__voleHeaders(v.headers,type==="modify"); + let body=null; + if(Object.hasOwn(v,"body")) { + body=v.body; __voleRecord(body,["kind","data"]); + if(!Object.hasOwn(body,"data"))throw new Error("missing body data"); + if(body.kind==="text")__voleTextSize(body.data,false); + else if(body.kind==="bytes")__voleBinarySize(body.data); + else throw new Error("invalid body kind"); + } + // The native adapter exports body.data as a separate bounded byte payload. + // Its remaining JSON metadata must fit before native JSON serialization. + __voleCharge(__voleMeasure(v,true,body)*2+32); + return v; +} diff --git a/src/http_processing/scripts/scoped_qos.rs b/src/http_processing/scripts/scoped_qos.rs new file mode 100644 index 0000000..08322c8 --- /dev/null +++ b/src/http_processing/scripts/scoped_qos.rs @@ -0,0 +1,393 @@ +//! Public Apple QoS request confined to the disposable scoped script owner. +use libc::{c_int, c_uint}; + +// AppleTVOS SDK sys/qos.h: qos_class_t is unsigned int; USER_INITIATED=0x19. +// pthread/qos.h declares both functions public since macOS10.10/iOS8. +// libc0.2.191 supplies pthread_t/pthread_self but not these QoS declarations. +const USER_INITIATED: c_uint = 0x19; +unsafe extern "C" { + fn pthread_set_qos_class_self_np(class: c_uint, relative_priority: c_int) -> c_int; + #[cfg(any(test, feature = "http-diagnostics"))] + fn pthread_get_qos_class_np( + thread: libc::pthread_t, + class: *mut c_uint, + relative_priority: *mut c_int, + ) -> c_int; +} + +pub(super) fn run(operation: impl FnOnce() -> T) -> T { + run_with_request( + || { + // SAFETY: public current-thread API, valid SDK class/relative0. + // Its production caller wraps only the user-execution operation + // on the new scoped owner, never warmup or a persistent worker. + unsafe { pthread_set_qos_class_self_np(USER_INITIATED, 0) } + }, + operation, + ) +} + +fn run_with_request(request: impl FnOnce() -> c_int, operation: impl FnOnce() -> T) -> T { + #[cfg(feature = "http-diagnostics")] + let start = diagnostic::Start::new(); + // A failed scheduling request does not change JavaScript error/fallback + // semantics. The return value itself is errno, not last_os_error(). + let return_code = request(); + #[cfg(test)] + LAST_REQUEST.with(|slot| slot.set(Some(return_code))); + #[cfg(feature = "http-diagnostics")] + let _guard = diagnostic::Guard::new(start, return_code); + #[cfg(not(any(test, feature = "http-diagnostics")))] + let _ = return_code; + operation() +} + +#[cfg(any(test, feature = "http-diagnostics"))] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Requested { + return_code: c_int, + value: Option<(c_uint, c_int)>, +} + +#[cfg(any(test, feature = "http-diagnostics"))] +fn requested() -> Requested { + let mut class = 0; + let mut relative = 0; + // SAFETY: pthread_self supplies this live owner; the output pointers are + // valid initialized scalar storage. Failed queries never expose values. + let return_code = + unsafe { pthread_get_qos_class_np(libc::pthread_self(), &mut class, &mut relative) }; + Requested { + return_code, + value: (return_code == 0).then_some((class, relative)), + } +} + +#[cfg(test)] +thread_local! { + static LAST_REQUEST: std::cell::Cell> = const { std::cell::Cell::new(None) }; +} + +#[cfg(feature = "http-diagnostics")] +pub(super) fn snapshot() -> serde_json::Value { + diagnostic::snapshot() +} + +#[cfg(feature = "http-diagnostics")] +mod diagnostic { + use super::{Requested, USER_INITIATED, c_int, requested}; + use serde_json::{Value, json}; + use std::{ + sync::{ + Mutex, + atomic::{AtomicU64, Ordering}, + }, + time::Instant, + }; + + #[derive(Clone, Copy)] + pub(super) struct Cpu { + return_code: c_int, + nanoseconds: Option, + } + + pub(super) fn cpu_sample() -> Cpu { + let mut time = libc::timespec { + tv_sec: 0, + tv_nsec: 0, + }; + // SAFETY: public per-current-thread clock and a valid writable timespec. + let return_code = unsafe { libc::clock_gettime(libc::CLOCK_THREAD_CPUTIME_ID, &mut time) }; + let nanoseconds = + if return_code == 0 && time.tv_sec >= 0 && (0..1_000_000_000).contains(&time.tv_nsec) { + (time.tv_sec as u128) + .checked_mul(1_000_000_000) + .and_then(|seconds| seconds.checked_add(time.tv_nsec as u128)) + } else { + None + }; + Cpu { + return_code, + nanoseconds, + } + } + + pub(super) fn elapsed_cpu(before: Cpu, after: Cpu) -> Option { + let nanoseconds = after.nanoseconds?.checked_sub(before.nanoseconds?)?; + Some((nanoseconds / 1000).min(u128::from(u64::MAX)) as u64) + } + + pub(super) struct Start { + wall: Instant, + cpu: Cpu, + before: Requested, + } + impl Start { + pub(super) fn new() -> Self { + let wall = Instant::now(); + let cpu = cpu_sample(); + let before = requested(); + Self { wall, cpu, before } + } + } + + pub(super) struct Guard { + start: Start, + return_code: c_int, + after_request: Requested, + } + impl Guard { + pub(super) fn new(start: Start, return_code: c_int) -> Self { + Self { + start, + return_code, + after_request: requested(), + } + } + } + + #[derive(Clone, Copy)] + struct Record { + before: Requested, + set_return_code: c_int, + after_request: Requested, + after_operation: Requested, + cpu_before_return_code: c_int, + cpu_after_return_code: c_int, + cpu_microseconds: Option, + wall_microseconds: u64, + panicking: bool, + } + + fn add(counter: &AtomicU64, value: u64) { + let _ = counter.try_update(Ordering::Relaxed, Ordering::Relaxed, |old| { + Some(old.saturating_add(value)) + }); + } + + struct Aggregate { + count: AtomicU64, + total: AtomicU64, + maximum: AtomicU64, + } + impl Aggregate { + const fn new() -> Self { + Self { + count: AtomicU64::new(0), + total: AtomicU64::new(0), + maximum: AtomicU64::new(0), + } + } + fn record(&self, value: u64) { + add(&self.count, 1); + add(&self.total, value); + self.maximum.fetch_max(value, Ordering::Relaxed); + } + fn snapshot(&self) -> Value { + json!({"count": self.count.load(Ordering::Relaxed), "total": self.total.load(Ordering::Relaxed), "max": self.maximum.load(Ordering::Relaxed)}) + } + } + + struct Stats { + completed: AtomicU64, + set_succeeded: AtomicU64, + set_failed: AtomicU64, + before_query_failed: AtomicU64, + after_query_failed: AtomicU64, + exit_query_failed: AtomicU64, + verified_after_request: AtomicU64, + cpu_unavailable: AtomicU64, + panicked: AtomicU64, + last_busy_skipped: AtomicU64, + wall: Aggregate, + cpu: Aggregate, + last: Mutex>, + } + static STATS: Stats = Stats { + completed: AtomicU64::new(0), + set_succeeded: AtomicU64::new(0), + set_failed: AtomicU64::new(0), + before_query_failed: AtomicU64::new(0), + after_query_failed: AtomicU64::new(0), + exit_query_failed: AtomicU64::new(0), + verified_after_request: AtomicU64::new(0), + cpu_unavailable: AtomicU64::new(0), + panicked: AtomicU64::new(0), + last_busy_skipped: AtomicU64::new(0), + wall: Aggregate::new(), + cpu: Aggregate::new(), + last: Mutex::new(None), + }; + + impl Drop for Guard { + fn drop(&mut self) { + // No formatting, body buffers, assertion, API failure propagation or + // QoS restoration on this normal/error/panic cleanup path. The + // fresh owner retains the requested class through its TLS exit. + let after_operation = requested(); + let cpu = cpu_sample(); + let record = Record { + before: self.start.before, + set_return_code: self.return_code, + after_request: self.after_request, + after_operation, + cpu_before_return_code: self.start.cpu.return_code, + cpu_after_return_code: cpu.return_code, + cpu_microseconds: elapsed_cpu(self.start.cpu, cpu), + wall_microseconds: self + .start + .wall + .elapsed() + .as_micros() + .min(u128::from(u64::MAX)) as u64, + panicking: std::thread::panicking(), + }; + add(&STATS.completed, 1); + add( + if record.set_return_code == 0 { + &STATS.set_succeeded + } else { + &STATS.set_failed + }, + 1, + ); + if record.before.return_code != 0 { + add(&STATS.before_query_failed, 1); + } + if record.after_request.return_code != 0 { + add(&STATS.after_query_failed, 1); + } + if record.after_operation.return_code != 0 { + add(&STATS.exit_query_failed, 1); + } + if record.set_return_code == 0 + && record.after_request.value == Some((USER_INITIATED, 0)) + { + add(&STATS.verified_after_request, 1); + } + STATS.wall.record(record.wall_microseconds); + if let Some(cpu) = record.cpu_microseconds { + STATS.cpu.record(cpu); + } else { + add(&STATS.cpu_unavailable, 1); + } + if record.panicking { + add(&STATS.panicked, 1); + } + // Snapshot collection can never block this owner or its unwind. + match STATS.last.try_lock() { + Ok(mut last) => *last = Some(record), + Err(std::sync::TryLockError::Poisoned(error)) => *error.into_inner() = Some(record), + Err(std::sync::TryLockError::WouldBlock) => add(&STATS.last_busy_skipped, 1), + } + } + } + + fn requested_value(value: Requested) -> Value { + json!({"queryReturnCode": value.return_code, + "requestedClass": value.value.map(|(class, _)| class), + "requestedRelativePriority": value.value.map(|(_, relative)| relative)}) + } + fn record_value(record: Record) -> Value { + json!({"before": requested_value(record.before), "setReturnCode": record.set_return_code, + "afterRequest": requested_value(record.after_request), "afterOperation": requested_value(record.after_operation), + "threadCpuBeforeReturnCode": record.cpu_before_return_code, + "threadCpuAfterReturnCode": record.cpu_after_return_code, + "threadCpuAvailable": record.cpu_microseconds.is_some(), "threadCpuMicroseconds": record.cpu_microseconds, + "wallMicroseconds": record.wall_microseconds, "panicking": record.panicking}) + } + pub(super) fn snapshot() -> Value { + // Copy fixed scalars and release the lock before JSON allocation. + let last = match STATS.last.try_lock() { + Ok(last) => *last, + Err(std::sync::TryLockError::Poisoned(error)) => *error.into_inner(), + Err(std::sync::TryLockError::WouldBlock) => None, + }; + json!({"scope": "disposable user-script owner (JSC or static plan) after tracing entry through operation cleanup; excludes warmup, inline execution, spawn, tracing entry/exit, TLS destructors and parent join; process-lifetime fixed aggregates", + "targetRequestedClass": USER_INITIATED, "targetRequestedRelativePriority": 0, + "effectiveClassAvailable": false, "effectiveClass": null, + "effectiveClassScope": "public getter reports requested class, not priority overrides or process scheduling limits", + "completedOwners": STATS.completed.load(Ordering::Relaxed), + "setSucceeded": STATS.set_succeeded.load(Ordering::Relaxed), "setFailed": STATS.set_failed.load(Ordering::Relaxed), + "beforeQueryFailed": STATS.before_query_failed.load(Ordering::Relaxed), + "afterQueryFailed": STATS.after_query_failed.load(Ordering::Relaxed), + "exitQueryFailed": STATS.exit_query_failed.load(Ordering::Relaxed), + "verifiedRequestedAfterSet": STATS.verified_after_request.load(Ordering::Relaxed), + "threadCpuUnavailable": STATS.cpu_unavailable.load(Ordering::Relaxed), "panickedOwners": STATS.panicked.load(Ordering::Relaxed), + "lastBusySkipped": STATS.last_busy_skipped.load(Ordering::Relaxed), + "units": "microseconds; count/total/max are not quantiles", + "ownerWallAvailable": STATS.wall.count.load(Ordering::Relaxed) > 0, + "ownerThreadCpuAvailable": STATS.cpu.count.load(Ordering::Relaxed) > 0, + "ownerWall": STATS.wall.snapshot(), "ownerThreadCpu": STATS.cpu.snapshot(), + "last": last.map(record_value)}) + } + + #[cfg(test)] + mod tests { + use super::*; + + #[test] + fn failed_query_and_nonmonotonic_cpu_remain_unavailable_not_zero() { + let value = requested_value(Requested { + return_code: libc::EPERM, + value: None, + }); + assert!(value["requestedClass"].is_null()); + assert!(value["requestedRelativePriority"].is_null()); + assert_eq!(value["queryReturnCode"], libc::EPERM); + assert_eq!( + elapsed_cpu( + Cpu { + return_code: -1, + nanoseconds: None + }, + Cpu { + return_code: 0, + nanoseconds: Some(2) + } + ), + None + ); + assert_eq!( + elapsed_cpu( + Cpu { + return_code: 0, + nanoseconds: Some(3) + }, + Cpu { + return_code: 0, + nanoseconds: Some(2) + } + ), + None + ); + } + } +} + +#[cfg(test)] +mod tests; + +// A synchronous, same-thread operation clock. This never requests or queries +// QoS and never contributes to disposable scoped-owner/setter statistics. +#[cfg(feature = "http-diagnostics")] +pub(super) struct OperationClock { + wall: std::time::Instant, + cpu: diagnostic::Cpu, +} +#[cfg(feature = "http-diagnostics")] +impl OperationClock { + pub(super) fn start() -> Self { + Self { + wall: std::time::Instant::now(), + cpu: diagnostic::cpu_sample(), + } + } + pub(super) fn elapsed(&self) -> (u128, Option) { + let cpu = diagnostic::cpu_sample(); + ( + self.wall.elapsed().as_micros(), + diagnostic::elapsed_cpu(self.cpu, cpu), + ) + } +} diff --git a/src/http_processing/scripts/scoped_qos/tests.rs b/src/http_processing/scripts/scoped_qos/tests.rs new file mode 100644 index 0000000..2fcd6d6 --- /dev/null +++ b/src/http_processing/scripts/scoped_qos/tests.rs @@ -0,0 +1,140 @@ +use super::*; +use crate::http_processing::{ + body_budget::{Budget, BudgetedBytes}, + scripts, +}; +use std::{ + io, + sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }, +}; +use tokio_util::sync::CancellationToken; + +#[test] +fn failed_qos_request_preserves_original_success_and_error_results() { + LAST_REQUEST.with(|slot| slot.set(None)); + let success = run_with_request(|| libc::EPERM, || Ok::<_, io::Error>(37)); + assert_eq!(success.unwrap(), 37); + assert_eq!(LAST_REQUEST.with(std::cell::Cell::take), Some(libc::EPERM)); + let failure = run_with_request( + || libc::EINVAL, + || Err::<(), _>(io::Error::from(io::ErrorKind::InvalidData)), + ); + assert_eq!(failure.unwrap_err().kind(), io::ErrorKind::InvalidData); + assert_eq!(LAST_REQUEST.with(std::cell::Cell::take), Some(libc::EINVAL)); +} + +#[test] +fn real_qos_request_is_on_disposable_owner_without_changing_parent_requested_class() { + LAST_REQUEST.with(|slot| slot.set(None)); + let parent_thread = std::thread::current().id(); + let parent_before = requested(); + let (owner_thread, name, return_code, after_request) = scripts::run_on_scoped_thread(|| { + Ok(( + std::thread::current().id(), + std::thread::current().name().map(str::to_owned), + LAST_REQUEST.with(std::cell::Cell::get), + requested(), + )) + }) + .unwrap(); + let parent_after = requested(); + assert_ne!(owner_thread, parent_thread); + assert_eq!(name.as_deref(), Some("vole-http-js")); + let return_code = + return_code.expect("the real disposable owner must request QoS before operation"); + if return_code == 0 && after_request.return_code == 0 { + assert_eq!(after_request.value, Some((USER_INITIATED, 0))); + } + // A nonzero return remains observable, rather than inventing a successful + // effective class; candidate admission does not depend on OS policy. + if parent_before.return_code == 0 && parent_after.return_code == 0 { + assert_eq!(parent_before.value, parent_after.value); + } + assert_eq!(LAST_REQUEST.with(std::cell::Cell::take), None); +} + +#[test] +fn scoped_qos_owner_still_joins_tls_destructors_and_preserves_panic_payload() { + struct AtExit(Arc); + impl Drop for AtExit { + fn drop(&mut self) { + self.0.store(true, Ordering::SeqCst); + } + } + thread_local! { static EXIT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; } + let exited = Arc::new(AtomicBool::new(false)); + let observed = exited.clone(); + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + scripts::run_on_scoped_thread::<()>(move || { + EXIT.with(|slot| *slot.borrow_mut() = Some(AtExit(observed))); + assert!(LAST_REQUEST.with(std::cell::Cell::get).is_some()); + std::panic::panic_any(812_u32); + }) + })) + .expect_err("scoped panic must reach the original caller"); + assert_eq!( + *panic + .downcast::() + .expect("panic payload must remain unchanged"), + 812 + ); + assert!( + exited.load(Ordering::SeqCst), + "actual TLS destructors must finish before join returns" + ); +} + +#[test] +fn warmup_named_scoped_owner_does_not_request_qos() { + LAST_REQUEST.with(|slot| slot.set(None)); + let parent = std::thread::current().id(); + let before = requested(); + // Actual platform preparation uses this same named helper, not the + // user-execution wrapper. This test performs no JSC initialization. + let (owner, name, request) = scripts::run_on_scoped_thread_named("vole-http-js-init", || { + Ok(( + std::thread::current().id(), + std::thread::current().name().map(str::to_owned), + LAST_REQUEST.with(std::cell::Cell::get), + )) + }) + .unwrap(); + assert_ne!(owner, parent); + assert_eq!(name.as_deref(), Some("vole-http-js-init")); + assert_eq!(request, None); + assert_eq!(LAST_REQUEST.with(std::cell::Cell::take), None); + let after = requested(); + if before.return_code == 0 && after.return_code == 0 { + assert_eq!(before.value, after.value); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn inline_jsc_keeps_its_thread_without_any_qos_request() { + LAST_REQUEST.with(|slot| slot.set(None)); + let first_tick = Arc::new(AtomicBool::new(false)); + let tick_seen = first_tick.clone(); + scripts::apple::on_first_tick_for_test(move || tick_seen.store(true, Ordering::SeqCst)); + let source = + scripts::validate_source("function rewrite(input){return {type:'pass'};}").unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::empty(&budget); + let result = scripts::evaluate( + &source, + &serde_json::json!({}), + None, + &mut output, + &CancellationToken::new(), + ) + .await; + assert_eq!(result.unwrap(), serde_json::json!({"type":"pass"})); + assert!( + first_tick.load(Ordering::SeqCst), + "JSC must remain on the current thread's hook" + ); + assert_eq!(LAST_REQUEST.with(std::cell::Cell::take), None); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/scripts/static_literal_plan.rs b/src/http_processing/scripts/static_literal_plan.rs new file mode 100644 index 0000000..27d1f80 --- /dev/null +++ b/src/http_processing/scripts/static_literal_plan.rs @@ -0,0 +1,1113 @@ +//! Closed ASCII-substitution lowering over complete UTF-8 text inputs. +//! Header equality separately permits complete Unicode in a read-only prefix. +//! Unsupported source or input falls back to JSC before Plan execution. +use oxc_ast::ast::*; +use serde_json::Value; +use std::{collections::BTreeMap, io, sync::Arc, time::Instant}; +use tokio_util::sync::CancellationToken; + +use super::super::{ + body::BorrowedBody, + body_budget::{BudgetedBytes, MAX_BODY, Reservation}, + rules::Phase, +}; + +mod body_guard; +mod header_guard; + +const MAX_NODES: usize = 128; +const MAX_DEPTH: usize = 64; +const MAX_WORK: usize = 2 * 1024 * 1024; +const MAX_TICKS: usize = 100_000; + +#[derive(Clone)] +enum Node { + Input, + Literal(Arc), + Replace { + parent: usize, + search: u8, + replacement: u8, + all: bool, + }, +} +#[derive(Clone, Copy)] +enum Action { + Define(usize), + Ticks(usize), + Charge(usize), + Size(usize), +} +enum Tree { + Literal(String), + Data, + Array(Vec), + Object { + fields: Vec<(String, Tree)>, + body: bool, + }, +} + +pub(crate) struct Plan { + nodes: Vec, + actions: Vec, + result: usize, + metadata: Value, + materialization: Option, + header_guard: Option, + body_guard: Option, +} +// Immutable compiled metadata, never a body copy or invocation allocation. +// Steps are stored in base-to-result source order, not as a simultaneous map. +#[derive(Clone, Copy)] +struct Step { + search: u8, + replacement: u8, +} +struct Recipe { + base: usize, + steps: [Step; MAX_DEPTH], + length: usize, +} +impl Recipe { + fn compile(nodes: &[Node], result: usize) -> Option { + let mut recipe = Self { + base: result, + steps: [Step { + search: 0, + replacement: 0, + }; MAX_DEPTH], + length: 0, + }; + loop { + match nodes.get(recipe.base)? { + Node::Input | Node::Literal(_) => { + recipe.steps[..recipe.length].reverse(); + return Some(recipe); + } + Node::Replace { + parent, + search, + replacement, + all: true, + } => { + if recipe.length == MAX_DEPTH { + return None; + } + recipe.steps[recipe.length] = Step { + search: *search, + replacement: *replacement, + }; + recipe.length += 1; + recipe.base = *parent; + } + // A First in the final ancestry keeps the complete old DAG. + Node::Replace { all: false, .. } => return None, + } + } + } + fn source<'a>(&self, nodes: &'a [Node], input: &'a [u8]) -> io::Result<&'a [u8]> { + match nodes.get(self.base) { + Some(Node::Input) => Ok(input), + Some(Node::Literal(value)) => Ok(value.as_bytes()), + _ => Err(io::ErrorKind::InvalidInput.into()), + } + } +} + +#[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] +#[derive(Default)] +pub(super) struct Validation<'a> { + pub(super) force_dag: bool, + // Runs after a complete recipe chunk only; the original DAG loop is untouched. + pub(super) after_chunk: Option<&'a mut (dyn FnMut(usize) + Send)>, +} +pub(super) struct Attempt { + pub(super) result: io::Result, + pub(super) ticks: usize, + pub(super) allocation_work: usize, + pub(super) backend: &'static str, +} +struct Builder { + nodes: Vec, + depths: Vec, + actions: Vec, + bindings: BTreeMap, + result: Option, +} +#[derive(Clone, Copy)] +struct Binding { + node: usize, + mutable: bool, +} + +/// Optional proof only. Original frontend rejection/acceptance is unchanged. +/// Diagnostic/test convenience uses the same accepted frontend AST as production. +#[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] +pub(super) fn compile(source: &str) -> Option { + super::frontend::compile_prepared(source).ok()?.plan +} + +pub(super) fn analyze(function: &Function<'_>) -> Option { + let body = function.body.as_ref()?; + let mut b = Builder { + nodes: Vec::new(), + depths: Vec::new(), + actions: vec![Action::Ticks(1)], + bindings: BTreeMap::new(), + result: None, + }; + let (last, declarations) = body.statements.split_last()?; + let (header_guard, declarations) = + if let Some((guard, consumed)) = header_guard::compile_prefix(declarations) { + (Some(guard), declarations.get(consumed..)?) + } else { + (None, declarations) + }; + let (body_guard, declarations) = + if let Some((guard, consumed)) = body_guard::compile_prefix(declarations) { + (Some(guard), declarations.get(consumed..)?) + } else { + (None, declarations) + }; + for statement in declarations { + if let Statement::ExpressionStatement(expression) = statement { + b.rebind(&expression.expression)?; + continue; + } + let Statement::VariableDeclaration(declaration) = statement else { + return None; + }; + if !matches!( + declaration.kind, + VariableDeclarationKind::Let | VariableDeclarationKind::Const + ) { + return None; + } + let mutable = declaration.kind == VariableDeclarationKind::Let; + for declaration in &declaration.declarations { + let BindingPattern::BindingIdentifier(name) = &declaration.id else { + return None; + }; + if name.name == "input" + || b.bindings.contains_key(name.name.as_str()) + || header_guard + .as_ref() + .is_some_and(|guard| guard.conflicts_binding(name.name.as_str())) + { + return None; + } + let value = b.string(declaration.init.as_ref()?, 0)?; + b.bindings.insert( + name.name.as_str().to_owned(), + Binding { + node: value, + mutable, + }, + ); + if b.bindings.len() > MAX_NODES { + return None; + } + } + } + let Statement::ReturnStatement(last) = last else { + return None; + }; + let fields = properties(last.argument.as_ref()?)?; + if fields.len() < 2 + || fields.len() > 3 + || !fields + .iter() + .all(|(k, _)| matches!(*k, "type" | "body" | "headers")) + { + return None; + } + let mut tree = Vec::new(); + for (key, value) in fields { + let value = match key { + "type" if literal(value)? == "modify" => Tree::Literal("modify".into()), + "body" => b.body(value)?, + "headers" => b.static_tree(value, 0)?, + _ => return None, + }; + tree.push((key.to_owned(), value)); + } + if !tree.iter().any(|(k, _)| k == "type") || !tree.iter().any(|(k, _)| k == "body") { + return None; + } + b.actions.push(Action::Charge(tree.len() * 48 + 32)); + if let Some((_, headers)) = tree.iter().find(|(k, _)| k == "headers") { + b.headers(headers)?; + } + let result = b.result?; + b.actions.push(Action::Size(result)); // __voleFinish body text check. + let tree = Tree::Object { + fields: tree, + body: false, + }; + let encoded = b.measure(&tree, 0)?; + if encoded > MAX_BODY { + return None; + } + b.actions + .push(Action::Charge(encoded.checked_mul(2)?.checked_add(32)?)); + let guard_nodes = header_guard.as_ref().map_or(0, |guard| guard.node_count()) + + body_guard.as_ref().map_or(0, |guard| guard.node_count()); + if guard_nodes + b.nodes.len() > MAX_NODES { + return None; + } + let materialization = Recipe::compile(&b.nodes, result); + Some(Plan { + header_guard, + body_guard, + materialization, + nodes: b.nodes, + actions: b.actions, + result, + metadata: metadata(&tree)?, + }) +} + +impl Builder { + // Only a standalone top-level assignment to this mutable String binding + // is proved. The old node remains immutable for every prior alias, and + // the new call contributes its ordinary Define/tick/work actions. + fn rebind(&mut self, value: &Expression<'_>) -> Option<()> { + let Expression::AssignmentExpression(assignment) = value else { + return None; + }; + let AssignmentTarget::AssignmentTargetIdentifier(target) = &assignment.left else { + return None; + }; + if assignment.operator.as_str() != "=" || !self.bindings.get(target.name.as_str())?.mutable + { + return None; + } + let Expression::CallExpression(call) = &assignment.right else { + return None; + }; + let Expression::StaticMemberExpression(method) = &call.callee else { + return None; + }; + let Expression::Identifier(receiver) = &method.object else { + return None; + }; + if receiver.name != target.name || method.property.name != "replaceAll" { + return None; + } + // string() proves non-optional calls, arity and both single ASCII + // literals, excluding the replacement-template dollar character. + let node = self.string(&assignment.right, 0)?; + self.bindings.get_mut(target.name.as_str())?.node = node; + Some(()) + } + + fn node(&mut self, node: Node, depth: usize) -> Option { + if self.nodes.len() >= MAX_NODES || depth > MAX_DEPTH { + return None; + } + let index = self.nodes.len(); + self.nodes.push(node); + self.depths.push(depth); + self.actions.push(Action::Define(index)); + Some(index) + } + fn string(&mut self, value: &Expression<'_>, depth: usize) -> Option { + if depth > MAX_DEPTH { + return None; + } + match value { + Expression::Identifier(name) => self.bindings.get(name.name.as_str()).map(|v| v.node), + Expression::StringLiteral(_) => self.node(Node::Literal(literal(value)?.into()), 0), + Expression::StaticMemberExpression(data) + if !data.optional && data.property.name == "data" => + { + let Expression::StaticMemberExpression(body) = &data.object else { + return None; + }; + if body.optional || body.property.name != "body" { + return None; + } + let Expression::Identifier(input) = &body.object else { + return None; + }; + if input.name != "input" { + return None; + } + self.node(Node::Input, 0) + } + Expression::CallExpression(call) if !call.optional && call.arguments.len() == 2 => { + let Expression::StaticMemberExpression(method) = &call.callee else { + return None; + }; + if method.optional + || !matches!(method.property.name.as_str(), "replace" | "replaceAll") + { + return None; + } + let search = literal(call.arguments[0].as_expression()?)?; + let replacement = literal(call.arguments[1].as_expression()?)?; + if search.len() != 1 || replacement.len() != 1 || replacement == "$" { + return None; + } + let parent = self.string(&method.object, depth + 1)?; + self.node( + Node::Replace { + parent, + search: search.as_bytes()[0], + replacement: replacement.as_bytes()[0], + all: method.property.name == "replaceAll", + }, + self.depths[parent] + 1, + ) + } + _ => None, + } + } + fn body(&mut self, value: &Expression<'_>) -> Option { + let fields = properties(value)?; + if fields.len() != 2 { + return None; + } + let mut result = Vec::new(); + for (key, value) in fields { + result.push(( + key.to_owned(), + match key { + "kind" if literal(value)? == "text" => Tree::Literal("text".into()), + "data" => { + self.result = Some(self.string(value, 0)?); + Tree::Data + } + _ => return None, + }, + )); + } + if !result.iter().any(|(k, _)| k == "kind") || !result.iter().any(|(k, _)| k == "data") { + return None; + } + self.actions.push(Action::Charge(128)); + Some(Tree::Object { + fields: result, + body: true, + }) + } + fn static_tree(&mut self, value: &Expression<'_>, depth: usize) -> Option { + if depth > MAX_DEPTH { + return None; + } + match value { + Expression::StringLiteral(_) => Some(Tree::Literal(literal(value)?.to_owned())), + Expression::ArrayExpression(array) if array.elements.len() <= 100 => { + let mut values = Vec::new(); + for value in &array.elements { + values.push(self.static_tree(value.as_expression()?, depth + 1)?); + } + self.actions.push(Action::Charge(values.len() * 24 + 32)); + Some(Tree::Array(values)) + } + Expression::ObjectExpression(_) => { + let mut fields = Vec::new(); + for (key, value) in properties(value)? { + fields.push((key.to_owned(), self.static_tree(value, depth + 1)?)); + } + self.actions.push(Action::Charge(fields.len() * 48 + 32)); + Some(Tree::Object { + fields, + body: false, + }) + } + _ => None, + } + } + fn text(&mut self, text: &str, quoted: bool) -> Option { + let bytes = if quoted { + text.bytes().try_fold(2usize, |n, byte| { + n.checked_add(match byte { + b'"' | b'\\' => 2, + 8 | 9 | 10 | 12 | 13 => 2, + 0..=31 => 6, + _ => 1, + }) + })? + } else { + text.len() + }; + if bytes > MAX_BODY { + return None; + } + self.actions + .push(Action::Ticks(text_ticks(text.len(), quoted))); + Some(bytes) + } + fn headers(&mut self, value: &Tree) -> Option<()> { + let Tree::Array(rows) = value else { + return None; + }; + let mut bytes = 0usize; + let mut values = 0usize; + for row in rows { + let Tree::Object { fields, .. } = row else { + return None; + }; + if !fields + .iter() + .all(|(k, _)| matches!(k.as_str(), "op" | "name" | "values")) + { + return None; + } + let op = tree_literal(field(fields, "op")?)?; + let name = tree_literal(field(fields, "name")?)?; + if !header_name(name) { + return None; + } + self.actions.push(Action::Ticks(1)); + self.text(name, false)?; + match op { + "remove" if fields.len() == 2 => bytes += name.len() + 32, + "set" | "add" if fields.len() == 3 => { + let Tree::Array(items) = field(fields, "values")? else { + return None; + }; + if items.is_empty() { + return None; + } + for value in items { + let value = tree_literal(value)?; + if value + .bytes() + .any(|b| b <= 8 || (10..=31).contains(&b) || b == 127) + { + return None; + } + self.text(value, false)?; + bytes += name.len() + value.len() + 32; + values += 1; + if bytes > 32768 || values > 100 { + return None; + } + } + } + _ => return None, + } + if bytes > 32768 { + return None; + } + } + Some(()) + } + fn measure(&mut self, tree: &Tree, depth: usize) -> Option { + if depth > MAX_DEPTH { + return None; + } + self.actions.push(Action::Ticks(1)); + let size = match tree { + Tree::Literal(text) => self.text(text, true)?, + Tree::Array(values) => { + let mut size = 2 + values.len().saturating_sub(1); + for value in values { + size += self.measure(value, depth + 1)?; + } + size + } + Tree::Object { fields, body } => { + let mut size = 2; + let mut count = 0; + for (key, value) in fields { + if *body && key == "data" { + continue; + } + size += usize::from(count > 0) + + self.text(key, true)? + + 1 + + self.measure(value, depth + 1)?; + count += 1; + } + size + } + Tree::Data => return None, + }; + (size <= MAX_BODY).then_some(size) + } +} + +fn literal<'a>(value: &'a Expression<'_>) -> Option<&'a str> { + let Expression::StringLiteral(value) = value else { + return None; + }; + let value = value.value.as_str()?; + (value.is_ascii() && value.len() <= MAX_BODY).then_some(value) +} +fn properties<'a, 'b>(value: &'b Expression<'a>) -> Option)>> { + let Expression::ObjectExpression(object) = value else { + return None; + }; + if object.properties.len() > 100 { + return None; + } + let mut fields = Vec::new(); + for property in &object.properties { + let ObjectPropertyKind::ObjectProperty(property) = property else { + return None; + }; + if property.kind != PropertyKind::Init || property.method || property.computed { + return None; + } + let key = match &property.key { + PropertyKey::StaticIdentifier(key) => key.name.as_str(), + PropertyKey::StringLiteral(key) => key.value.as_str()?, + _ => return None, + }; + if !key.is_ascii() || fields.iter().any(|(previous, _)| *previous == key) { + return None; + } + fields.push((key, &property.value)); + } + Some(fields) +} +fn field<'a>(fields: &'a [(String, Tree)], key: &str) -> Option<&'a Tree> { + fields.iter().find(|(name, _)| name == key).map(|(_, v)| v) +} +fn tree_literal(value: &Tree) -> Option<&str> { + if let Tree::Literal(value) = value { + Some(value) + } else { + None + } +} +fn header_name(name: &str) -> bool { + !name.is_empty() + && name + .bytes() + .all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+.^_`|~-".contains(&b)) + && !matches!( + name.to_ascii_lowercase().as_str(), + "host" + | "content-length" + | "transfer-encoding" + | "content-encoding" + | "connection" + | "upgrade" + | "expect" + | "trailer" + | "te" + | "http2-settings" + | "keep-alive" + | "proxy-connection" + | "proxy-authorization" + | "proxy-authenticate" + | "content-range" + ) +} +fn metadata(tree: &Tree) -> Option { + Some(match tree { + Tree::Literal(value) => Value::String(value.clone()), + Tree::Array(values) => Value::Array(values.iter().map(metadata).collect::>()?), + Tree::Object { fields, body } => Value::Object( + fields + .iter() + .filter(|(k, _)| !*body || k != "data") + .map(|(k, v)| Some((k.clone(), metadata(v)?))) + .collect::>()?, + ), + Tree::Data => return None, + }) +} +fn text_ticks(length: usize, quoted: bool) -> usize { + if !quoted && length >= 4096 { + 1 + } else { + length.div_ceil(256) + } +} + +// Mirrors runtime.js TextSize's UTF-16 loop, including its skipped low +// surrogate at a 256-unit boundary. ASCII substitutions preserve this shape. +fn utf8_text_ticks(text: &str, work: &Work<'_>) -> io::Result { + if text.is_ascii() { + return Ok(text_ticks(text.len(), false)); + } + let mut units = 0usize; + let mut ticks = 0usize; + let mut next_check = 0usize; + for (offset, character) in text.char_indices() { + if offset >= next_check { + work.check()?; + next_check = offset + 256; + } + ticks += usize::from(units.is_multiple_of(256)); + units += character.len_utf16(); + } + work.check()?; + Ok(ticks) +} + +// Runtime values are immutable views, not uncharged body copies. Every source +// declaration/call still executes its original preflight/tick/work actions. +// These views do not fuse calls or remove unused declarations. +struct TextState { + length: usize, + first: Option, +} +struct Workspace { + values: Vec, + _reservation: Reservation, +} +struct Work<'a> { + ticks: usize, + allocated: usize, + cancellation: &'a CancellationToken, + deadline: Instant, +} +impl Work<'_> { + fn check(&self) -> io::Result<()> { + if self.cancellation.is_cancelled() { + Err(io::ErrorKind::Interrupted.into()) + } else if self.ticks > MAX_TICKS || Instant::now() >= self.deadline { + Err(io::ErrorKind::TimedOut.into()) + } else { + Ok(()) + } + } + fn tick(&mut self) -> io::Result<()> { + self.ticks += 1; + self.check() + } + fn ticks(&mut self, count: usize) -> io::Result<()> { + for _ in 0..count { + self.tick()?; + } + Ok(()) + } + fn charge(&mut self, bytes: usize) -> io::Result<()> { + self.tick()?; + self.allocated = self + .allocated + .checked_add(bytes) + .filter(|n| *n <= MAX_WORK) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?; + Ok(()) + } +} + +impl std::fmt::Debug for Plan { + fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + formatter + .debug_struct("StaticLiteralPlan") + .field("nodes", &self.nodes.len()) + .field("actions", &self.actions.len()) + .finish_non_exhaustive() + } +} + +impl Plan { + pub(super) fn accepts_input(&self, metadata: &Value, input: Option>) -> bool { + metadata["body"]["kind"] == "text" + && input.is_some_and(|body| std::str::from_utf8(body.as_bytes()).is_ok()) + && self + .header_guard + .as_ref() + .is_none_or(|guard| guard.rows(metadata).is_some()) + && self + .body_guard + .as_ref() + .is_none_or(|guard| guard.accepts_metadata(metadata)) + } + // Only actual Text declarations with the same production Message phase + // may use this proof. Message::metadata owns normalized header snapshots; + // arbitrary diagnostic JSON retains accepts_input/Guard::rows validation. + pub(super) fn covers_business_text_phase(&self, phase: Phase) -> bool { + self.header_guard + .as_ref() + .is_none_or(|guard| guard.covers_business_phase(phase)) + } + + /// Call ONLY inside the existing lane and selected synchronous adapter, + /// with its original + /// absolute deadline and actual borrowed input/output owners. No JSC bridge + /// copies exist on this backend, so no phantom JSC reservation is required. + /// The input witness borrows the real Entity/Bytes owner; no Rust input copy. + /// No queue/thread/VM here. + /// None means unsupported input, not a budget rejection. After selection, + /// every failure is Some(Err) and MUST NOT rerun JSC, including t=0 OOM. + pub(super) fn try_execute( + &self, + metadata: &Value, + input: Option>, + output: &mut BudgetedBytes, + cancellation: &CancellationToken, + deadline: Instant, + ) -> Option { + self.execute( + metadata, + input, + output, + cancellation, + deadline, + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + Validation::default(), + ) + } + // Existing per-call validation hook: unit tests or explicit tvOS diagnostics. + // Source/business callers cannot request it; no process-global state. + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + pub(super) fn try_execute_for_validation( + &self, + metadata: &Value, + input: Option>, + output: &mut BudgetedBytes, + cancellation: &CancellationToken, + deadline: Instant, + validation: Validation<'_>, + ) -> Option { + self.execute(metadata, input, output, cancellation, deadline, validation) + } + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + pub(super) fn has_header_guard(&self) -> bool { + self.header_guard.is_some() + } + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + pub(super) fn materializer_kind(&self) -> &'static str { + if self.materialization.is_some() { + "recipe" + } else { + "dag" + } + } + #[cfg(all(feature = "http-diagnostics", target_os = "tvos"))] + pub(super) fn recipe_storage_bytes() -> usize { + std::mem::size_of::>() + } + fn execute( + &self, + metadata: &Value, + input: Option>, + output: &mut BudgetedBytes, + cancellation: &CancellationToken, + deadline: Instant, + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + mut validation: Validation<'_>, + ) -> Option { + let input = input?; + let witness = input; + let input = input.as_bytes(); + if metadata["body"]["kind"] != "text" { + return None; + } + let text = std::str::from_utf8(input).ok()?; + // Unsupported metadata is discovered before any Plan execution. It + // cannot turn a skipped JS read into a synthetic Plan exception. + let guard_rows = match &self.header_guard { + Some(guard) => Some(guard.rows(metadata)?), + None => None, + }; + let guard_input = match &self.body_guard { + Some(guard) => Some(guard.input(metadata, text)?), + None => None, + }; + if cancellation.is_cancelled() { + return refused(io::ErrorKind::Interrupted); + } + if Instant::now() >= deadline { + return refused(io::ErrorKind::TimedOut); + } + if input.len() > MAX_BODY { + return refused(io::ErrorKind::FileTooLarge); + } + if !output.as_ref().is_empty() { + return refused(io::ErrorKind::InvalidInput); + } + if !witness.same_ledger_as(output) { + return refused(io::ErrorKind::InvalidInput); + } + let result_length = self.length(self.result, input.len()); + if result_length > MAX_BODY || result_length > output.remaining() { + return refused(io::ErrorKind::FileTooLarge); + } + let Some(bytes) = self + .nodes + .len() + .checked_mul(std::mem::size_of::()) + .and_then(|n| n.checked_add(std::mem::size_of::>())) + else { + return refused(io::ErrorKind::OutOfMemory); + }; + let Some(reservation) = output.reserve_temporary(bytes) else { + return refused(io::ErrorKind::OutOfMemory); + }; + let mut values = Vec::new(); + if values.try_reserve_exact(self.nodes.len()).is_err() + || values.capacity() > self.nodes.len() + { + return refused(io::ErrorKind::OutOfMemory); + } + let mut workspace = Workspace { + values, + _reservation: reservation, + }; + let mut work = Work { + ticks: 0, + allocated: 0, + cancellation, + deadline, + }; + let mut input_sizing_ticks = None; + let result = (|| { + work.check()?; + let mut size = MetadataSize(0); + serde_json::to_writer(&mut size, metadata) + .map_err(|_| io::Error::from(io::ErrorKind::InvalidData))?; + let guarded = self.header_guard.is_some() || self.body_guard.is_some(); + if guarded { + work.ticks(1)?; // Exactly one whole-function entry, before guards. + } + if let (Some(guard), Some(rows)) = (&self.header_guard, guard_rows) { + super::super::diagnostics::increment( + super::super::diagnostics::Counter::PlanHeaderGuardEntered, + ); + if !guard.run(rows, &mut work)? { + let result = guard.early(&mut work)?; + work.check()?; + let counter = match result["type"].as_str() { + Some("pass") => super::super::diagnostics::Counter::PlanHeaderGuardPass, + Some("abort") => super::super::diagnostics::Counter::PlanHeaderGuardAbort, + _ => return Err(io::ErrorKind::InvalidInput.into()), + }; + super::super::diagnostics::increment(counter); + return Ok(result); // No tail action or body write occurs. + } + super::super::diagnostics::increment( + super::super::diagnostics::Counter::PlanHeaderGuardTail, + ); + } + if let (Some(guard), Some(input)) = (&self.body_guard, guard_input) + && guard.run(input, &mut work)? + { + return guard.early(&mut work); // No tail action or body write. + } + let actions = if guarded { + &self.actions[1..] // Tail includes the old entry; do not repeat it. + } else { + &self.actions[..] + }; + for action in actions { + match *action { + Action::Ticks(count) => work.ticks(count)?, + Action::Charge(bytes) => work.charge(bytes)?, + Action::Size(node) => { + let ticks = + self.body_text_ticks(node, text, &mut input_sizing_ticks, &work)?; + work.ticks(ticks)? + } + Action::Define(index) => { + let (length, first) = match &self.nodes[index] { + Node::Input => { + work.ticks(4)?; + (input.len(), None) + } + Node::Literal(value) => (value.len(), None), + Node::Replace { + parent, + search, + all, + .. + } => { + let length = workspace.values[*parent].length; + work.ticks(2)?; // __voleCall + method key text. + let sizing_ticks = self.body_text_ticks( + *parent, + text, + &mut input_sizing_ticks, + &work, + )?; + work.ticks(sizing_ticks)?; + work.ticks(sizing_ticks)?; + work.ticks(2)?; // search/replacement text size. + work.charge(length * 2 + 32)?; + let mut first = None; + if !all { + for offset in 0..length { + if offset & 255 == 0 { + work.check()?; + } + if self.byte(*parent, offset, input, &workspace.values) + == *search + { + first = Some(offset); + break; + } + } + } + (length, first) + } + }; + workspace.values.push(TextState { length, first }); + } + } + } + work.check()?; + output.write_initialized_output(result_length, |target| { + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + let recipe = self + .materialization + .as_ref() + .filter(|_| !validation.force_dag); + #[cfg(not(any(test, all(feature = "http-diagnostics", target_os = "tvos"))))] + let recipe = self.materialization.as_ref(); + if let Some(recipe) = recipe { + super::super::diagnostics::increment( + super::super::diagnostics::Counter::PlanFinalRecipeEntered, + ); + let source = recipe.source(&self.nodes, input)?; + if source.len() != target.len() { + return Err(io::ErrorKind::InvalidInput.into()); + } + // Only a generic one-step All recipe uses the single + // source→independent-output pass. Other recipes are exact + // original copy+ordered-step loops, including zero steps. + let single = if recipe.length == 1 { + super::super::diagnostics::increment( + super::super::diagnostics::Counter::PlanFinalSingleStepEntered, + ); + Some(recipe.steps[0]) + } else { + None + }; + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + let mut filled = 0; + for (source, target) in source.chunks(256).zip(target.chunks_mut(256)) { + work.check()?; + if let Some(step) = single { + for (target, source) in target.iter_mut().zip(source.iter().copied()) { + *target = if source == step.search { + step.replacement + } else { + source + }; + } + } else { + target.copy_from_slice(source); + for step in &recipe.steps[..recipe.length] { + for byte in target.iter_mut() { + if *byte == step.search { + *byte = step.replacement; + } + } + } + } + #[cfg(any(test, all(feature = "http-diagnostics", target_os = "tvos")))] + { + filled += target.len(); + if let Some(hook) = validation.after_chunk.as_mut() { + hook(filled); + } + } + } + } else { + super::super::diagnostics::increment( + super::super::diagnostics::Counter::PlanFinalDagEntered, + ); + for (offset, value) in target.iter_mut().enumerate() { + if offset & 255 == 0 { + work.check()?; + } + *value = self.byte(self.result, offset, input, &workspace.values); + } + } + Ok(result_length) + })?; + work.check()?; + let result = self.metadata.clone(); + work.check()?; + Ok(result) + })(); + Some(Attempt { + result, + ticks: work.ticks, + allocation_work: work.allocated, + backend: "static-ascii-literal-prototype", + }) + } + // Every permitted replacement preserves its base's UTF-16 scalar starts. + // Cache only the input summary, and only at a real TextSize action; unused + // body aliases do not acquire a new payload scan or per-node heap state. + fn body_text_ticks( + &self, + mut node: usize, + input: &str, + cached: &mut Option, + work: &Work<'_>, + ) -> io::Result { + for _ in 0..=MAX_DEPTH { + match self.nodes.get(node).ok_or(io::ErrorKind::InvalidData)? { + Node::Input => { + if let Some(ticks) = *cached { + return Ok(ticks); + } + let ticks = utf8_text_ticks(input, work)?; + *cached = Some(ticks); + return Ok(ticks); + } + Node::Literal(value) => return Ok(text_ticks(value.len(), false)), + Node::Replace { parent, .. } => node = *parent, + } + } + Err(io::ErrorKind::InvalidData.into()) + } + pub(super) fn maximum_output_bytes(&self, input: usize) -> Option { + let size = self.length(self.result, input); + (input <= MAX_BODY && size <= MAX_BODY).then_some(size) + } + fn length(&self, node: usize, input: usize) -> usize { + match &self.nodes[node] { + Node::Input => input, + Node::Literal(value) => value.len(), + Node::Replace { parent, .. } => self.length(*parent, input), + } + } + fn byte(&self, node: usize, offset: usize, input: &[u8], states: &[TextState]) -> u8 { + match &self.nodes[node] { + Node::Input => input[offset], + Node::Literal(value) => value.as_bytes()[offset], + Node::Replace { + parent, + search, + replacement, + all, + } => { + let byte = self.byte(*parent, offset, input, states); + if byte == *search && (*all || states[node].first == Some(offset)) { + *replacement + } else { + byte + } + } + } + } +} +fn refused(kind: io::ErrorKind) -> Option { + Some(Attempt { + result: Err(kind.into()), + ticks: 0, + allocation_work: 0, + backend: "static-ascii-literal-prototype", + }) +} +struct MetadataSize(usize); +impl io::Write for MetadataSize { + fn write(&mut self, bytes: &[u8]) -> io::Result { + self.0 = self + .0 + .checked_add(bytes.len()) + .filter(|n| *n <= 1024 * 1024) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?; + Ok(bytes.len()) + } + fn flush(&mut self) -> io::Result<()> { + Ok(()) + } +} + +#[cfg(all(test, target_vendor = "apple"))] +#[path = "static_literal_plan_tests.rs"] +mod tests; diff --git a/src/http_processing/scripts/static_literal_plan/body_guard.rs b/src/http_processing/scripts/static_literal_plan/body_guard.rs new file mode 100644 index 0000000..9c36ca7 --- /dev/null +++ b/src/http_processing/scripts/static_literal_plan/body_guard.rs @@ -0,0 +1,359 @@ +//! A complete read-only text-input guard before the immutable String tail. +//! Unsupported predicates keep the whole invocation on JavaScriptCore. +use oxc_ast::ast::*; +use serde_json::{Value, json}; +use std::io; + +use super::{MAX_DEPTH, MAX_NODES, Work}; + +const CONTROL_NODES: usize = 2; // The if and its fresh early-return record. + +enum TextField { + Kind, + DataType, +} +enum Predicate { + Body, + Text { + field: TextField, + literal: String, + equal: bool, + }, + Length { + literal: f64, + equal: bool, + }, + Not(usize), + And(usize, usize), + Or(usize, usize), +} +#[derive(Clone, Copy)] +enum Early { + Pass, + Abort, +} + +pub(super) struct Guard { + predicates: Vec, + root: usize, + early: Early, +} +// The actual backend injects this borrowed UTF-8 text as body.data. Any data +// property in diagnostic metadata is overwritten by that same construction. +pub(super) struct Input<'a> { + kind: &'a str, + text: &'a str, + units: Option, +} + +pub(super) fn compile_prefix(statements: &[Statement<'_>]) -> Option<(Guard, usize)> { + let Statement::IfStatement(statement) = statements.first()? else { + return None; + }; + if statement.alternate.is_some() { + return None; + } + let Statement::ReturnStatement(early) = single(&statement.consequent)? else { + return None; + }; + let (record, _) = peel(early.argument.as_ref()?, 0)?; + let fields = super::properties(record)?; + if fields.len() != 1 || fields[0].0 != "type" { + return None; + } + let early = match literal(fields[0].1, 0)? { + "pass" => Early::Pass, + "abort" => Early::Abort, + _ => return None, + }; + let mut predicates = Vec::new(); + let root = predicate(&statement.test, 0, &mut predicates)?; + Some(( + Guard { + predicates, + root, + early, + }, + 1, + )) +} + +impl Guard { + pub(super) fn node_count(&self) -> usize { + CONTROL_NODES + self.predicates.len() + } + + pub(super) fn accepts_metadata(&self, metadata: &Value) -> bool { + text_kind(metadata).is_some() + } + + pub(super) fn input<'a>(&self, metadata: &'a Value, text: &'a str) -> Option> { + Some(Input { + kind: text_kind(metadata)?, + text, + units: None, + }) + } + + // Only the branch's truthiness escapes; every recognized leaf is either + // boolean or the qualified body object. Logical short-circuit order is + // preserved without evaluating a skipped length or synthesizing Gets. + pub(super) fn run(&self, mut input: Input<'_>, work: &mut Work<'_>) -> io::Result { + self.evaluate(self.root, &mut input, work) + } + + pub(super) fn early(&self, work: &mut Work<'_>) -> io::Result { + work.charge(80)?; + work.ticks(4)?; + work.charge(match self.early { + Early::Pass => 62, + Early::Abort => 64, + })?; + work.check()?; + let value = + json!({"type": match self.early { Early::Pass => "pass", Early::Abort => "abort" }}); + work.check()?; + Ok(value) + } + + fn evaluate( + &self, + index: usize, + input: &mut Input<'_>, + work: &mut Work<'_>, + ) -> io::Result { + match self + .predicates + .get(index) + .ok_or(io::ErrorKind::InvalidInput)? + { + Predicate::Body => { + work.ticks(2)?; // Get(input,"body") plus its key TextSize. + Ok(true) + } + Predicate::Text { + field, + literal, + equal, + } => { + work.ticks(4)?; // Two static Gets, each with key TextSize. + let value = match field { + TextField::Kind => input.kind, + TextField::DataType => "string", + }; + Ok((value == literal.as_str()) == *equal) + } + Predicate::Length { literal, equal } => { + work.ticks(6)?; // body, data and length Gets, no numeric helper. + Ok(((input.length(work)? as f64) == *literal) == *equal) + } + Predicate::Not(child) => Ok(!self.evaluate(*child, input, work)?), + Predicate::And(left, right) => { + if !self.evaluate(*left, input, work)? { + return Ok(false); + } + self.evaluate(*right, input, work) + } + Predicate::Or(left, right) => { + if self.evaluate(*left, input, work)? { + return Ok(true); + } + self.evaluate(*right, input, work) + } + } + } +} + +impl Input<'_> { + fn length(&mut self, work: &Work<'_>) -> io::Result { + if let Some(units) = self.units { + return Ok(units); + } + work.check()?; + let units = if self.text.is_ascii() { + self.text.len() + } else { + let mut units = 0usize; + let mut next_check = 0usize; + for (offset, character) in self.text.char_indices() { + if offset >= next_check { + work.check()?; + next_check = offset + 256; + } + units += character.len_utf16(); + } + units + }; + work.check()?; + self.units = Some(units); + Ok(units) + } +} + +fn text_kind(metadata: &Value) -> Option<&str> { + let kind = metadata + .as_object()? + .get("body")? + .as_object()? + .get("kind")? + .as_str()?; + (kind == "text").then_some(kind) +} + +fn peel<'a, 'b>( + mut value: &'b Expression<'a>, + mut depth: usize, +) -> Option<(&'b Expression<'a>, usize)> { + loop { + if depth > MAX_DEPTH { + return None; + } + match value { + Expression::ParenthesizedExpression(inner) => { + value = &inner.expression; + depth += 1; + } + _ => return Some((value, depth)), + } + } +} + +fn single<'a, 'b>(mut statement: &'b Statement<'a>) -> Option<&'b Statement<'a>> { + for _ in 0..=MAX_DEPTH { + match statement { + Statement::BlockStatement(block) if block.body.len() == 1 => { + statement = &block.body[0]; + } + Statement::BlockStatement(_) => return None, + _ => return Some(statement), + } + } + None +} + +fn member<'a, 'b>( + value: &'b Expression<'a>, + name: &str, + depth: usize, +) -> Option<(&'b Expression<'a>, usize)> { + let (value, depth) = peel(value, depth)?; + let Expression::StaticMemberExpression(value) = value else { + return None; + }; + (!value.optional && value.property.name == name).then_some((&value.object, depth + 1)) +} + +fn body(value: &Expression<'_>, depth: usize) -> Option<()> { + let (value, depth) = member(value, "body", depth)?; + let Expression::Identifier(value) = peel(value, depth)?.0 else { + return None; + }; + (value.name == "input").then_some(()) +} + +fn data(value: &Expression<'_>, depth: usize) -> Option<()> { + let (value, depth) = member(value, "data", depth)?; + body(value, depth) +} + +fn field(value: &Expression<'_>, depth: usize) -> Option { + let (value, depth) = peel(value, depth)?; + if let Some((value, depth)) = member(value, "kind", depth) { + body(value, depth)?; + return Some(TextField::Kind); + } + let Expression::UnaryExpression(unary) = value else { + return None; + }; + if unary.operator.as_str() != "typeof" { + return None; + } + data(&unary.argument, depth + 1)?; + Some(TextField::DataType) +} + +fn length(value: &Expression<'_>, depth: usize) -> Option<()> { + let (value, depth) = member(value, "length", depth)?; + data(value, depth) +} + +fn literal<'a, 'b>(value: &'b Expression<'a>, depth: usize) -> Option<&'b str> { + let Expression::StringLiteral(value) = peel(value, depth)?.0 else { + return None; + }; + value.value.as_str() +} + +fn number(value: &Expression<'_>, depth: usize) -> Option { + let Expression::NumericLiteral(value) = peel(value, depth)?.0 else { + return None; + }; + value.value.is_finite().then_some(value.value) +} + +fn predicate(value: &Expression<'_>, depth: usize, nodes: &mut Vec) -> Option { + let (value, depth) = peel(value, depth)?; + let node = match value { + Expression::LogicalExpression(logical) => { + let operator = logical.operator.as_str(); + if !matches!(operator, "&&" | "||") { + return None; + } + let left = predicate(&logical.left, depth + 1, nodes)?; + let right = predicate(&logical.right, depth + 1, nodes)?; + if operator == "&&" { + Predicate::And(left, right) + } else { + Predicate::Or(left, right) + } + } + Expression::UnaryExpression(unary) if unary.operator.as_str() == "!" => { + Predicate::Not(predicate(&unary.argument, depth + 1, nodes)?) + } + Expression::BinaryExpression(binary) => { + let equal = match binary.operator.as_str() { + "===" => true, + "!==" => false, + _ => return None, + }; + if let (Some(field), Some(literal)) = ( + field(&binary.left, depth + 1), + literal(&binary.right, depth + 1), + ) { + Predicate::Text { + field, + literal: literal.to_owned(), + equal, + } + } else if let (Some(literal), Some(field)) = ( + literal(&binary.left, depth + 1), + field(&binary.right, depth + 1), + ) { + Predicate::Text { + field, + literal: literal.to_owned(), + equal, + } + } else if let (Some(()), Some(literal)) = ( + length(&binary.left, depth + 1), + number(&binary.right, depth + 1), + ) { + Predicate::Length { literal, equal } + } else { + let literal = number(&binary.left, depth + 1)?; + length(&binary.right, depth + 1)?; + Predicate::Length { literal, equal } + } + } + _ => { + body(value, depth)?; + Predicate::Body + } + }; + if nodes.len().checked_add(CONTROL_NODES)? >= MAX_NODES { + return None; + } + let index = nodes.len(); + nodes.push(node); + Some(index) +} diff --git a/src/http_processing/scripts/static_literal_plan/header_guard.rs b/src/http_processing/scripts/static_literal_plan/header_guard.rs new file mode 100644 index 0000000..417d75b --- /dev/null +++ b/src/http_processing/scripts/static_literal_plan/header_guard.rs @@ -0,0 +1,507 @@ +//! Optional, complete three-statement read-only header guard prefix. +//! Called only after the original frontend has validated the entire function. +//! Compilation owns bounded metadata; execution borrows the actual rows. +use oxc_ast::ast::*; +use serde_json::{Value, json}; +use std::io; + +use super::{MAX_DEPTH, MAX_NODES, Work}; +use crate::http_processing::{ + headers::{MAX_BYTES, MAX_FIELDS}, + rules::Phase, +}; + +// These four lowered control nodes are included in the parent's combined +// optional-plan cap: flag binding, index binding, loop, and early return. +const CONTROL_NODES: usize = 4; + +#[derive(Clone, Copy, PartialEq, Eq)] +enum HeaderArray { + Request, + Response, +} +impl HeaderArray { + fn key(self) -> &'static str { + match self { + Self::Request => "request", + Self::Response => "response", + } + } +} +#[derive(Clone, Copy)] +enum Field { + Name, + Value, +} +enum Predicate { + Compare { + field: Field, + literal: String, + equal: bool, + }, + And { + left: usize, + right: usize, + }, + Or { + left: usize, + right: usize, + }, +} +#[derive(Clone, Copy)] +enum Early { + Pass, + Abort, +} + +pub(super) struct Guard { + flag: String, + index: String, + source: HeaderArray, + predicates: Vec, + root: usize, + early: Early, +} +// No arbitrary slice/string factory is exposed. The values are qualified in +// Guard::rows before backend selection, without collecting or copying headers. +pub(super) struct Rows<'a> { + values: &'a [Value], + source: HeaderArray, +} + +/// Recognize exactly three complete statements; the caller must still prove +/// the entire remaining tail, including binding conflicts, or retain JSC. +pub(super) fn compile_prefix<'a, 'b>(statements: &'b [Statement<'a>]) -> Option<(Guard, usize)> { + let Statement::VariableDeclaration(flag_declaration) = statements.first()? else { + return None; + }; + let (flag, initial_flag) = binding(flag_declaration)?; + if flag == "input" + || !matches!(peel(initial_flag, 0)?.0, Expression::BooleanLiteral(value) if !value.value) + { + return None; + } + + let Statement::ForStatement(loop_statement) = statements.get(1)? else { + return None; + }; + let Some(ForStatementInit::VariableDeclaration(index_declaration)) = &loop_statement.init + else { + return None; + }; + let (index, initial_index) = binding(index_declaration)?; + if index == "input" + || index == flag + || !matches!(peel(initial_index, 0)?.0, Expression::NumericLiteral(value) if value.value == 0.0) + { + return None; + } + + let (test, depth) = peel(loop_statement.test.as_ref()?, 0)?; + let Expression::BinaryExpression(test) = test else { + return None; + }; + if test.operator.as_str() != "<" || identifier(&test.left, depth + 1)? != index { + return None; + } + let (length, depth) = peel(&test.right, depth + 1)?; + let Expression::StaticMemberExpression(length) = length else { + return None; + }; + if length.optional || length.property.name != "length" { + return None; + } + let source = header_array(&length.object, depth + 1)?; + + let (update, _) = peel(loop_statement.update.as_ref()?, 0)?; + let Expression::UpdateExpression(update) = update else { + return None; + }; + let SimpleAssignmentTarget::AssignmentTargetIdentifier(updated) = &update.argument else { + return None; + }; + // Both prefix and postfix have identical discarded-result traces here. + if update.operator.as_str() != "++" || updated.name != index { + return None; + } + + let Statement::IfStatement(condition) = single(&loop_statement.body)? else { + return None; + }; + if condition.alternate.is_some() { + return None; + } + let Statement::ExpressionStatement(set_flag) = single(&condition.consequent)? else { + return None; + }; + let (set_flag, _) = peel(&set_flag.expression, 0)?; + let Expression::AssignmentExpression(set_flag) = set_flag else { + return None; + }; + let AssignmentTarget::AssignmentTargetIdentifier(assigned) = &set_flag.left else { + return None; + }; + if set_flag.operator.as_str() != "=" + || assigned.name != flag + || !matches!(peel(&set_flag.right, 0)?.0, Expression::BooleanLiteral(value) if value.value) + { + return None; + } + + let Statement::IfStatement(early_statement) = statements.get(2)? else { + return None; + }; + if early_statement.alternate.is_some() { + return None; + } + let (negation, depth) = peel(&early_statement.test, 0)?; + let Expression::UnaryExpression(negation) = negation else { + return None; + }; + if negation.operator.as_str() != "!" || identifier(&negation.argument, depth + 1)? != flag { + return None; + } + let Statement::ReturnStatement(early_return) = single(&early_statement.consequent)? else { + return None; + }; + let early = early_record(early_return.argument.as_ref()?)?; + + let mut predicates = Vec::new(); + let root = predicate(&condition.test, source, index, 0, &mut predicates)?; + Some(( + Guard { + flag: flag.to_owned(), + index: index.to_owned(), + source, + predicates, + root, + early, + }, + 3, + )) +} + +impl Guard { + /// Coverage is limited to production Message::metadata: request headers + /// exist in both phases, and response headers only in the response phase. + /// That private constructor checks the same field/byte bounds and emits + /// exact name/value string rows. This never qualifies arbitrary JSON; + /// rows() still validates each actual invocation before Plan selection. + pub(super) fn covers_business_phase(&self, phase: Phase) -> bool { + match self.source { + HeaderArray::Request => matches!(phase, Phase::Request | Phase::Response), + HeaderArray::Response => matches!(phase, Phase::Response), + } + } + + pub(super) fn conflicts_binding(&self, name: &str) -> bool { + name == self.flag.as_str() || name == self.index.as_str() + } + pub(super) fn node_count(&self) -> usize { + CONTROL_NODES + self.predicates.len() + } + + pub(super) fn rows<'a>(&self, metadata: &'a Value) -> Option> { + let rows = metadata + .as_object()? + .get(self.source.key())? + .as_object()? + .get("headers")? + .as_array()?; + if rows.len() > MAX_FIELDS { + return None; + } + let mut bytes = 0usize; + for row in rows { + let row = row.as_object()?; + if row.len() != 2 { + return None; + } + let name = row.get("name")?.as_str()?; + let value = row.get("value")?.as_str()?; + bytes = bytes + .checked_add(name.len())? + .checked_add(value.len())? + .checked_add(32) + .filter(|size| *size <= MAX_BYTES)?; + } + Some(Rows { + values: rows, + source: self.source, + }) + } + + /// Excludes the unique function-entry tick, which the parent executes once. + pub(super) fn run(&self, rows: Rows<'_>, work: &mut Work<'_>) -> io::Result { + if rows.source != self.source { + return Err(io::ErrorKind::InvalidInput.into()); + } + let mut found = false; + for row in rows.values { + work.ticks(7)?; // Three static Gets plus numeric '<'. + work.tick()?; // Entering this loop iteration. + if self.evaluate(self.root, row, work)? { + found = true; + } + // INDEX++/++INDEX: __voleUnary('+') then __voleAdd(...,1). + // Each helper ticks, then successful numeric __voleValue charges8. + work.tick()?; + work.charge(8)?; + work.tick()?; + work.charge(8)?; + } + work.ticks(7)?; // The final failed loop test still executes. + Ok(found) + } + + /// A fresh one-field pass/abort record and its complete Finish trace. + pub(super) fn early(&self, work: &mut Work<'_>) -> io::Result { + work.charge(80)?; + work.ticks(4)?; + work.charge(match self.early { + Early::Pass => 62, + Early::Abort => 64, + })?; + work.check()?; + let value = + json!({"type": match self.early { Early::Pass => "pass", Early::Abort => "abort" }}); + work.check()?; + Ok(value) + } + + fn evaluate(&self, index: usize, row: &Value, work: &mut Work<'_>) -> io::Result { + match self + .predicates + .get(index) + .ok_or(io::ErrorKind::InvalidInput)? + { + Predicate::Compare { + field, + literal, + equal, + } => { + // Request/response, headers, numeric index and name/value each + // execute Get plus short property-key TextSize. No value sizing. + work.ticks(8)?; + let key = match field { + Field::Name => "name", + Field::Value => "value", + }; + let value = row + .as_object() + .and_then(|row| row.get(key)) + .and_then(Value::as_str) + .ok_or(io::ErrorKind::InvalidInput)?; + Ok((value == literal.as_str()) == *equal) + } + Predicate::And { left, right } => { + if !self.evaluate(*left, row, work)? { + return Ok(false); + } + self.evaluate(*right, row, work) + } + Predicate::Or { left, right } => { + if self.evaluate(*left, row, work)? { + return Ok(true); + } + self.evaluate(*right, row, work) + } + } + } +} + +fn binding<'a, 'b>( + declaration: &'b VariableDeclaration<'a>, +) -> Option<(&'b str, &'b Expression<'a>)> { + if declaration.kind != VariableDeclarationKind::Let || declaration.declarations.len() != 1 { + return None; + } + let declaration = &declaration.declarations[0]; + let BindingPattern::BindingIdentifier(name) = &declaration.id else { + return None; + }; + Some((name.name.as_str(), declaration.init.as_ref()?)) +} + +fn peel<'a, 'b>( + mut value: &'b Expression<'a>, + mut depth: usize, +) -> Option<(&'b Expression<'a>, usize)> { + loop { + if depth > MAX_DEPTH { + return None; + } + match value { + Expression::ParenthesizedExpression(inner) => { + value = &inner.expression; + depth += 1; + } + _ => return Some((value, depth)), + } + } +} + +fn single<'a, 'b>(mut statement: &'b Statement<'a>) -> Option<&'b Statement<'a>> { + for _ in 0..=MAX_DEPTH { + match statement { + Statement::BlockStatement(block) if block.body.len() == 1 => { + statement = &block.body[0]; + } + Statement::BlockStatement(_) => return None, + _ => return Some(statement), + } + } + None +} + +fn identifier<'a, 'b>(value: &'b Expression<'a>, depth: usize) -> Option<&'b str> { + let Expression::Identifier(value) = peel(value, depth)?.0 else { + return None; + }; + Some(value.name.as_str()) +} + +fn header_array(value: &Expression<'_>, depth: usize) -> Option { + let (value, depth) = peel(value, depth)?; + let Expression::StaticMemberExpression(headers) = value else { + return None; + }; + if headers.optional || headers.property.name != "headers" { + return None; + } + let (value, depth) = peel(&headers.object, depth + 1)?; + let Expression::StaticMemberExpression(source) = value else { + return None; + }; + if source.optional || identifier(&source.object, depth + 1)? != "input" { + return None; + } + match source.property.name.as_str() { + "request" => Some(HeaderArray::Request), + "response" => Some(HeaderArray::Response), + _ => None, + } +} + +fn header_field( + value: &Expression<'_>, + source: HeaderArray, + index: &str, + depth: usize, +) -> Option { + let (value, depth) = peel(value, depth)?; + let Expression::StaticMemberExpression(field) = value else { + return None; + }; + if field.optional { + return None; + } + let field_kind = match field.property.name.as_str() { + "name" => Field::Name, + "value" => Field::Value, + _ => return None, + }; + let (value, depth) = peel(&field.object, depth + 1)?; + let Expression::ComputedMemberExpression(row) = value else { + return None; + }; + if row.optional + || identifier(&row.expression, depth + 1)? != index + || header_array(&row.object, depth + 1)? != source + { + return None; + } + Some(field_kind) +} + +fn literal<'a, 'b>(value: &'b Expression<'a>, depth: usize) -> Option<&'b str> { + let Expression::StringLiteral(value) = peel(value, depth)?.0 else { + return None; + }; + // as_str refuses incomplete UTF-16 (the original frontend also refuses it). + // Unlike body-transform literals, guard equality permits complete Unicode. + value.value.as_str() +} + +fn predicate( + value: &Expression<'_>, + source: HeaderArray, + index: &str, + depth: usize, + nodes: &mut Vec, +) -> Option { + let (value, depth) = peel(value, depth)?; + let node = match value { + Expression::LogicalExpression(logical) => { + let operator = logical.operator.as_str(); + if !matches!(operator, "&&" | "||") { + return None; + } + let left = predicate(&logical.left, source, index, depth + 1, nodes)?; + let right = predicate(&logical.right, source, index, depth + 1, nodes)?; + if operator == "&&" { + Predicate::And { left, right } + } else { + Predicate::Or { left, right } + } + } + Expression::BinaryExpression(binary) => { + let equal = match binary.operator.as_str() { + "===" => true, + "!==" => false, + _ => return None, + }; + let (field, text) = if let (Some(field), Some(text)) = ( + header_field(&binary.left, source, index, depth + 1), + literal(&binary.right, depth + 1), + ) { + (field, text) + } else { + ( + header_field(&binary.right, source, index, depth + 1)?, + literal(&binary.left, depth + 1)?, + ) + }; + Predicate::Compare { + field, + literal: text.to_owned(), + equal, + } + } + _ => return None, + }; + if nodes.len().checked_add(CONTROL_NODES)? >= MAX_NODES { + return None; + } + let index = nodes.len(); + nodes.push(node); + Some(index) +} + +fn early_record(value: &Expression<'_>) -> Option { + let Expression::ObjectExpression(record) = peel(value, 0)?.0 else { + return None; + }; + if record.properties.len() != 1 { + return None; + } + let ObjectPropertyKind::ObjectProperty(property) = &record.properties[0] else { + return None; + }; + if property.kind != PropertyKind::Init || property.method || property.computed { + return None; + } + let key = match &property.key { + PropertyKey::StaticIdentifier(key) => key.name.as_str(), + PropertyKey::StringLiteral(key) => key.value.as_str()?, + _ => return None, + }; + if key != "type" { + return None; + } + match literal(&property.value, 0)? { + "pass" => Some(Early::Pass), + "abort" => Some(Early::Abort), + _ => None, + } +} diff --git a/src/http_processing/scripts/static_literal_plan_tests.rs b/src/http_processing/scripts/static_literal_plan_tests.rs new file mode 100644 index 0000000..2154194 --- /dev/null +++ b/src/http_processing/scripts/static_literal_plan_tests.rs @@ -0,0 +1,599 @@ +//! Memory/Apple semantic regressions. New integration changes are unexecuted. +//! Physical tvOS validation is owned by the explicit diagnostic suite. +use super::*; +use crate::http_processing::{ + body_budget::{BridgePlan, Budget, output_capacity}, + scripts::{apple, validate_source}, +}; +use serde_json::json; +use std::time::Duration; + +const BODY_ONLY: &str = "function rewrite(input){const text=input.body.data.replaceAll('-', '_');return {type:'modify',body:{kind:'text',data:text}};}"; + +fn input_metadata() -> Value { + json!({"body":{"kind":"text"}}) +} +fn buffers( + budget: &Budget, + input: &[u8], + bound: usize, +) -> (BudgetedBytes, BudgetedBytes, Reservation) { + let input = BudgetedBytes::copy(budget, input).unwrap(); + let output = BudgetedBytes::new(budget, output_capacity(bound).unwrap()).unwrap(); + let bridge = budget + .reserve( + BridgePlan::new(input.as_ref().len(), true, bound) + .unwrap() + .cost() + .unwrap(), + ) + .unwrap(); + (input, output, bridge) +} + +fn compare_jsc(source: &str, input: &[u8]) { + let compiled = validate_source(source).unwrap(); + let bound = compiled.maximum_output_bytes(input.len()); + let budget = Budget::default(); + let (source_input, mut output, bridge) = buffers(&budget, input, bound); + let jsc = apple::evaluate( + &compiled, + &input_metadata(), + Some(source_input.as_ref()), + &mut output, + Some(&bridge), + &CancellationToken::new(), + Instant::now() + Duration::from_millis(100), + ); + let jsc_ticks = apple::last_ticks_for_test().expect("actual JSC owner ended"); + let jsc_bytes = output.as_ref().to_vec(); + drop((source_input, output, bridge)); + assert_eq!(budget.used(), 0); + + let (source_input, mut output, bridge) = buffers(&budget, input, bound); + let result = compile(source) + .expect("closed AST subset") + .try_execute( + &input_metadata(), + Some(source_input.borrowed_body()), + &mut output, + &CancellationToken::new(), + Instant::now() + Duration::from_millis(100), + ) + .expect("UTF-8 text pre-execution eligibility"); + match (jsc, result.result) { + (Ok(jsc), Ok(native)) => { + assert_eq!(native, jsc); + assert_eq!(output.as_ref(), jsc_bytes); + } + (Err(jsc), Err(native)) => assert_eq!(native.kind(), jsc.kind()), + other => panic!("backend result mismatch: {other:?}"), + } + assert_eq!(result.ticks, jsc_ticks, "controlled healthy/quota trace"); + assert_eq!(result.backend, "static-ascii-literal-prototype"); + drop((source_input, output, bridge)); + assert_eq!(budget.used(), 0); +} + +#[test] +#[ignore = "unbuilt isolated prototype; actual Apple JSC differential required"] +fn static_literal_closed_ast_never_ignores_other_statements() { + for source in [ + "function rewrite(input){while(true){}return {type:'modify',body:{kind:'text',data:input.body.data}};}", + "function rewrite(input){const a=input.body.data; a='x';return {type:'modify',body:{kind:'text',data:a}};}", + "function rewrite(input){const a=input.body.data; a[0]=1;return {type:'modify',body:{kind:'text',data:a}};}", + "function rewrite(input){if(true){return {type:'modify',body:{kind:'text',data:input.body.data}};}return {type:'modify',body:{kind:'text',data:input.body.data}};}", + "function rewrite(input){const h=[];h.push('x');return {type:'modify',headers:h,body:{kind:'text',data:input.body.data}};}", + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('', 'x')}};}", + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('-', '$')}};}", + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('é', '_')}};}", + "function rewrite(input){return {type:'modify',type:'modify',body:{kind:'text',data:input.body.data}};}", + ] { + assert!(compile(source).is_none(), "must keep JSC: {source}"); + } + // The complete generic guard is proved, never removed or assumed true. + // Extra unknown statements still force the whole invocation to JSC. + let mixed = "function rewrite(input){let found=false;for(let i=0;i 0); + drop(last); + assert_eq!(budget.used(), 0); +} + +#[test] +fn utf8_literal_plan_matches_actual_jsc_for_all_text_shapes_and_first_all_chains() { + let boundary = format!("{}😀{}-", "a".repeat(255), "a".repeat(255)); + let long_unicode = format!("{}-", "中文😀e\u{301}".repeat(800)); + for input in [ + "中文--结尾\0$", + "😀-😀--", + "e\u{301}-é--", + "\0-\0$", + &boundary, + &long_unicode, + ] { + for expression in [ + "input.body.data", + "input.body.data.replace('-', '_')", + "input.body.data.replaceAll('-', '_')", + "input.body.data.replaceAll('-', '_').replace('_', '+')", + "input.body.data.replace('-', '_').replaceAll('_', '+')", + ] { + let source = format!( + "function rewrite(input){{const unused=input.body.data.replaceAll('a','b');return {{type:'modify',body:{{kind:'text',data:{expression}}}}};}}" + ); + compare_jsc(&source, input.as_bytes()); + } + } +} + +#[test] +fn utf8_text_size_fuel_counts_scalar_starts_in_utf16_not_utf8_or_rounded_units() { + let cancellation = CancellationToken::new(); + let work = Work { + ticks: 0, + allocated: 0, + cancellation: &cancellation, + deadline: Instant::now() + Duration::from_millis(100), + }; + assert_eq!(utf8_text_ticks(&"é".repeat(256), &work).unwrap(), 1); + let boundary = format!("{}😀{}", "a".repeat(255), "a".repeat(255)); + assert_eq!(boundary.encode_utf16().count(), 512); + assert_eq!(utf8_text_ticks(&boundary, &work).unwrap(), 1); + assert_eq!(utf8_text_ticks(&"a".repeat(4095), &work).unwrap(), 16); + assert_eq!(utf8_text_ticks(&"a".repeat(4096), &work).unwrap(), 1); + compare_jsc(BODY_ONLY, boundary.as_bytes()); +} + +fn guarded_plan_source(length: usize, early: &str, tail: &str) -> String { + format!( + "function rewrite(input){{if(!input.body||input.body.kind!=='text'||typeof input.body.data!=='string'||input.body.data.length!=={length}){{return {{type:'{early}'}};}}{tail}}}" + ) +} + +// Mac exposes the real JSC tick count, but its numeric allocation-work probe +// is tvOS-only. Work below uses independent canaries and actual JSC quota +// outcomes; it must not be reported as a direct numeric JSC-work observation. +fn guarded_plan_compare( + source: &str, + input: &[u8], + metadata: &Value, +) -> (Result, Vec, usize, usize) { + let compiled = validate_source(source).expect("accepted public JS subset"); + let budget = Budget::default(); + let (owned_input, mut output, bridge) = + buffers(&budget, input, compiled.maximum_output_bytes(input.len())); + let jsc = apple::evaluate( + &compiled, + metadata, + Some(owned_input.as_ref()), + &mut output, + Some(&bridge), + &CancellationToken::new(), + Instant::now() + Duration::from_millis(100), + ) + .map_err(|error| error.kind()); + let jsc_ticks = apple::last_ticks_for_test().expect("actual JSC context ended"); + let jsc_bytes = output.as_ref().to_vec(); + drop((owned_input, output, bridge)); + assert_eq!(budget.used(), 0); + + let plan = compile(source).expect("complete generic guard and immutable string versions"); + let owned_input = BudgetedBytes::copy(&budget, input).unwrap(); + let bound = plan.maximum_output_bytes(input.len()).unwrap(); + let mut output = BudgetedBytes::new(&budget, bound).unwrap(); + let attempt = plan + .try_execute( + metadata, + Some(owned_input.borrowed_body()), + &mut output, + &CancellationToken::new(), + Instant::now() + Duration::from_millis(100), + ) + .expect("qualified text input selected before execution"); + let result = attempt.result.map_err(|error| error.kind()); + assert_eq!(result, jsc, "actual backend outcome"); + assert_eq!(attempt.ticks, jsc_ticks, "actual controlled tick trace"); + assert_eq!(output.as_ref(), jsc_bytes, "actual complete body output"); + let bytes = output.as_ref().to_vec(); + drop((owned_input, output)); + assert_eq!(budget.used(), 0, "all actual body owners released"); + (result, bytes, attempt.ticks, attempt.allocation_work) +} + +#[test] +fn guarded_plan_generic_text_checks_use_utf16_and_versioned_let_bindings() { + for (name, search, replacement, input, expected) in [ + ("payload", "-", "_", "😀-\0", "😀_\0"), + ("renamedText", "x", "y", "x\0😀", "y\0😀"), + ("emptyText", "-", "_", "", ""), + ] { + let tail = format!( + "let {name}=input.body.data;{name}={name}.replaceAll('{search}','{replacement}');return {{type:'modify',body:{{kind:'text',data:{name}}}}};" + ); + let source = guarded_plan_source(input.encode_utf16().count(), "abort", &tail); + let (result, bytes, _, work) = + guarded_plan_compare(&source, input.as_bytes(), &input_metadata()); + assert_eq!( + result.unwrap(), + json!({"type":"modify","body":{"kind":"text"}}) + ); + assert_eq!(bytes, expected.as_bytes()); + assert_eq!( + work, + input.len() * 2 + 400, + "one replacement plus complete Finish" + ); + } + let input = "😀-\0"; + for early in ["pass", "abort"] { + // Six UTF-8 bytes are four JS code units: this must take the early + // branch, not silently use a UTF-8 length or execute the tail. + let source = guarded_plan_source( + input.len(), + early, + "let s=input.body.data;s=s.replaceAll('-','_');return {type:'modify',body:{kind:'text',data:s}};", + ); + let (result, bytes, ticks, work) = + guarded_plan_compare(&source, input.as_bytes(), &input_metadata()); + assert_eq!(result.unwrap(), json!({"type":early})); + assert!(bytes.is_empty()); + assert_eq!(ticks, 23); + assert_eq!(work, if early == "pass" { 142 } else { 144 }); + } +} + +#[test] +fn guarded_plan_header_early_return_skips_the_body_guard_and_tail() { + let input = "😀\0-".repeat(1024); + for early in ["pass", "abort"] { + let body = guarded_plan_source( + 1, + "abort", + "let changed=input.body.data;changed=changed.replaceAll('-','_');return {type:'modify',body:{kind:'text',data:changed}};", + ); + let prefix = format!( + "let present=false;for(let cursor=0;cursor serde_json::Value { + json!({"phase":"response","original":{"url":"https://example.com/","method":"GET"}, + "request":{"url":"https://example.com/","method":"GET","headers":[]}, + "response":{"status":200,"headers":[]},"body":{"kind":kind}}) +} + +#[tokio::test] +async fn bridge_api_direct_input_reserves_before_materialization_and_releases_on_error() { + let pass = validate_source("function rewrite(input){return {type:'pass'};}").unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::empty(&budget); + let occupied = budget + .reserve(super::super::body_budget::WORKSPACE - 64 * 1024) + .unwrap(); + for kind in ["text", "bytes"] { + let error = evaluate( + &pass, + &input(kind), + Some(&vec![b'a'; 64 * 1024]), + &mut output, + &CancellationToken::new(), + ) + .await + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::OutOfMemory); + assert!(output.as_ref().is_empty()); + assert_eq!( + budget.used(), + super::super::body_budget::WORKSPACE - 64 * 1024 + ); + } + drop(occupied); + assert_eq!(budget.used(), 0); +} + +#[tokio::test] +async fn bridge_api_prepaid_workspace_is_validated_and_reused_without_double_reserving() { + let code = validate_source( + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data}};}", + ) + .unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, super::super::body_budget::MAX_BODY).unwrap(); + let required = + super::super::body_budget::BridgePlan::new(1, true, code.maximum_output_bytes(1)) + .unwrap() + .cost() + .unwrap(); + let prepaid = budget.reserve(required).unwrap(); + let occupied = budget + .reserve(super::super::body_budget::WORKSPACE - budget.used()) + .unwrap(); + assert_eq!( + evaluate_until( + &code, + &input("text"), + Some(b"x"), + &mut output, + Some(&prepaid), + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_millis(100), + ) + .await + .unwrap(), + json!({"type":"modify","body":{"kind":"text"}}) + ); + assert_eq!(output.as_ref(), b"x"); + assert_eq!(budget.used(), super::super::body_budget::WORKSPACE); + drop(occupied); + drop(prepaid); + drop(output); + assert_eq!(budget.used(), 0); + + for foreign in [false, true] { + let budget = Budget::default(); + let mut output = BudgetedBytes::empty(&budget); + let other = Budget::default(); + let invalid = if foreign { + other.reserve(required).unwrap() + } else { + budget.reserve(required - 1).unwrap() + }; + assert_eq!( + evaluate_until( + &code, + &input("text"), + Some(b"x"), + &mut output, + Some(&invalid), + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_millis(100), + ) + .await + .unwrap_err() + .kind(), + io::ErrorKind::InvalidData + ); + assert!(output.as_ref().is_empty()); + drop(invalid); + assert_eq!(budget.used(), 0); + assert_eq!(other.used(), 0); + } +} + +#[tokio::test] +async fn apple_executes_json_rewrite_and_exports_body_separately() { + let code = validate_source( + r#"function rewrite(input) { + let document = JSON.parse(input.body.data); + document.enabled = true; + return {type:"modify",body:{kind:"text",data:JSON.stringify(document)}}; + }"#, + ) + .unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, 0).unwrap(); + let result = evaluate( + &code, + &input("text"), + Some(br#"{"enabled":false,"n":2}"#), + &mut output, + &CancellationToken::new(), + ) + .await + .unwrap(); + assert_eq!(result, json!({"type":"modify","body":{"kind":"text"}})); + let body: serde_json::Value = serde_json::from_slice(output.as_ref()).unwrap(); + assert_eq!(body, json!({"enabled":true,"n":2})); + drop(output); + assert_eq!(budget.used(), 0); +} + +#[tokio::test] +async fn apple_bytes_are_isolated_and_export_the_exact_view() { + let code = validate_source( + r#"function rewrite(input) { + input.body.data[1] = 9; + return {type:"modify",body:{kind:"bytes",data:input.body.data.subarray(1,3)}}; + }"#, + ) + .unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, 0).unwrap(); + let source = [1, 2, 3, 4]; + let result = evaluate( + &code, + &input("bytes"), + Some(&source), + &mut output, + &CancellationToken::new(), + ) + .await + .unwrap(); + assert_eq!(result, json!({"type":"modify","body":{"kind":"bytes"}})); + assert_eq!(source, [1, 2, 3, 4]); + assert_eq!(output.as_ref(), [9, 3]); +} + +#[tokio::test] +async fn apple_finite_loop_stops_before_the_next_evaluation() { + let infinite = validate_source("function rewrite(input) { while (true) {} }").unwrap(); + let healthy = validate_source("function rewrite(input) { return {type:'pass'}; }").unwrap(); + let budget = Budget::default(); + let start = std::time::Instant::now(); + let mut output = BudgetedBytes::new(&budget, 0).unwrap(); + assert!( + evaluate( + &infinite, + &input("not-requested"), + None, + &mut output, + &CancellationToken::new() + ) + .await + .is_err() + ); + assert!(start.elapsed() < std::time::Duration::from_secs(2)); + assert_eq!( + evaluate( + &healthy, + &input("not-requested"), + None, + &mut output, + &CancellationToken::new() + ) + .await + .unwrap(), + json!({"type":"pass"}) + ); +} + +#[tokio::test] +async fn apple_rejects_undefined_before_json_can_erase_it() { + // An uninitialized local is ordinary JavaScript undefined, even though + // explicit globals and arbitrary dynamic calls are not in the subset. + let code = validate_source( + "function rewrite(input) { let method; return {type:'modify',method:method}; }", + ) + .unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, 0).unwrap(); + assert!( + evaluate( + &code, + &input("not-requested"), + None, + &mut output, + &CancellationToken::new() + ) + .await + .is_err() + ); +} + +async fn evaluate_text( + source: &str, + body: &[u8], + metadata: serde_json::Value, +) -> io::Result<(serde_json::Value, Vec)> { + let code = validate_source(source)?; + evaluate_compiled_text(&code, body, metadata).await +} + +async fn evaluate_compiled_text( + code: &CompiledSource, + body: &[u8], + metadata: serde_json::Value, +) -> io::Result<(serde_json::Value, Vec)> { + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, 0).unwrap(); + let result = evaluate( + code, + &metadata, + Some(body), + &mut output, + &CancellationToken::new(), + ) + .await; + let body = output.as_ref().to_vec(); + drop(output); + assert_eq!(budget.used(), 0); + result.map(|metadata| (metadata, body)) +} + +async fn replace_text( + body: &str, + search: &str, + replacement: &str, + all: bool, +) -> io::Result> { + let source = format!( + "function rewrite(input){{return {{type:'modify',body:{{kind:'text',data:input.body.data.{}({},{})}}}};}}", + if all { "replaceAll" } else { "replace" }, + serde_json::to_string(search).unwrap(), + serde_json::to_string(replacement).unwrap(), + ); + let (metadata, body) = evaluate_text(&source, body.as_bytes(), input("text")).await?; + assert_eq!(metadata, json!({"type":"modify","body":{"kind":"text"}})); + Ok(body) +} + +#[tokio::test] +async fn apple_ascii_replace_all_rewrites_dense_64k_js_and_mixed_bodies() { + let mut original = vec![b'a'; 65536]; + original[..14].copy_from_slice(b"flow:00000000\n"); + let expected: Vec<_> = original + .iter() + .map(|b| if *b == b'a' { b'c' } else { *b }) + .collect(); + for mixed in [false, true] { + let body: Vec<_> = original + .iter() + .map(|b| if mixed && *b == b'a' { b'b' } else { *b }) + .collect(); + let guard = if mixed { + "let found=false; for(let i=0;i); +impl Drop for ScopedThreadExit { + fn drop(&mut self) { + self.0.store(true, std::sync::atomic::Ordering::Release); + } +} +thread_local! { + static SCOPED_THREAD_EXIT: std::cell::RefCell> = const { std::cell::RefCell::new(None) }; +} +fn observe_scoped_exit(flag: std::sync::Arc) { + SCOPED_THREAD_EXIT.with(|slot| { + *slot.borrow_mut() = Some(ScopedThreadExit(flag)); + }); +} + +#[derive(Debug)] +struct ScopedDispatchProbe; +impl tracing::Subscriber for ScopedDispatchProbe { + fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { + true + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn event(&self, _: &tracing::Event<'_>) {} + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn scoped_jsc_worker_joins_tls_and_preserves_dispatch_and_panic() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + let exited = Arc::new(AtomicBool::new(false)); + let observed = exited.clone(); + let caller = std::thread::current().id(); + let mut borrowed = 0; + let dispatch = tracing::Dispatch::new(ScopedDispatchProbe); + let worker = tracing::dispatcher::with_default(&dispatch, || { + tokio::task::block_in_place(|| { + run_on_scoped_thread(|| { + observe_scoped_exit(observed); + assert!(tracing::dispatcher::get_default(|d| d + .downcast_ref::() + .is_some())); + borrowed = 7; + Ok(std::thread::current().id()) + }) + }) + }) + .unwrap(); + assert_ne!(caller, worker); + assert_eq!(borrowed, 7); + // A TLS destructor runs on actual thread exit, after the job returns. + assert!(exited.load(Ordering::Acquire)); + + let exited = Arc::new(AtomicBool::new(false)); + let observed = exited.clone(); + let marker = Arc::new(()); + let expected = marker.clone(); + let panic = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + tokio::task::block_in_place(|| { + run_on_scoped_thread::<()>(move || { + observe_scoped_exit(observed); + std::panic::panic_any(marker); + }) + }) + })) + .expect_err("worker panic must reach its caller"); + let marker = panic + .downcast::>() + .unwrap_or_else(|_| panic!("panic payload changed")); + assert!(Arc::ptr_eq(marker.as_ref(), &expected)); + assert!(exited.load(Ordering::Acquire)); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn scoped_jsc_cancellation_joins_and_next_public_evaluation_is_healthy() { + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + mpsc, + }; + use std::time::{Duration, Instant}; + let code = validate_source("function rewrite(input){while(true){}}").unwrap(); + let body = vec![b'a'; 4096]; + let budget = Budget::default(); + let mut output = BudgetedBytes::empty(&budget); + let cancellation = CancellationToken::new(); + let controller_token = cancellation.clone(); + let worker_token = cancellation.clone(); + let exited = Arc::new(AtomicBool::new(false)); + let observed = exited.clone(); + let (ready_tx, ready_rx) = mpsc::channel(); + let (resume_tx, resume_rx) = mpsc::channel(); + let body_ref = body.as_slice(); + let (result, handshake) = tokio::task::block_in_place(|| { + std::thread::scope(|scope| { + let controller = scope.spawn(move || { + let entered = ready_rx.recv_timeout(Duration::from_secs(5)).is_ok(); + controller_token.cancel(); + let released = resume_tx.send(()).is_ok(); + (entered, released) + }); + let output_ref = &mut output; + let result = run_on_scoped_thread(move || { + observe_scoped_exit(observed); + let fail_safe = worker_token.clone(); + // No assertions/panics in the extern-C callback. The bounded + // timeout is only a failed-test watchdog, not an exit heuristic. + apple::on_first_tick_for_test(move || { + let _ = ready_tx.send(()); + if resume_rx.recv_timeout(Duration::from_secs(5)).is_err() { + fail_safe.cancel(); + } + }); + apple::evaluate( + &code, + &input("text"), + Some(body_ref), + output_ref, + None, + &worker_token, + Instant::now() + Duration::from_millis(100), + ) + }); + ( + result, + controller.join().expect("cancellation controller panicked"), + ) + }) + }); + assert_eq!(handshake, (true, true)); + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::Interrupted); + assert!(exited.load(Ordering::Acquire)); + assert!(output.as_ref().is_empty()); + assert_eq!(budget.used(), 0); + let healthy = validate_source( + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data}};}", + ) + .unwrap(); + let result = evaluate( + &healthy, + &input("text"), + Some(&body), + &mut output, + &CancellationToken::new(), + ) + .await + .unwrap(); + assert_eq!(result, json!({"type":"modify","body":{"kind":"text"}})); + assert_eq!(output.as_ref(), body); + drop(output); + assert_eq!(budget.used(), 0); +} + +#[tokio::test] +async fn apple_native_literal_replace_preserves_generic_ascii_and_fallback_semantics() { + // Dense controls, NUL, DEL and regexp metacharacters are ordinary ASCII + // code units; no benchmark-specific character or payload is recognized. + for (search, replacement) in [ + ('q', 'z'), + ('\0', '\x7f'), + ('\x7f', '\0'), + ('$', '!'), + ('\\', '"'), + ('.', '\n'), + ('\t', '\r'), + ('q', 'q'), + ] { + let body: String = [search, search, 'x', search] + .into_iter() + .cycle() + .take(4096) + .collect(); + let expected: String = body + .chars() + .map(|c| if c == search { replacement } else { c }) + .collect(); + assert_eq!( + replace_text(&body, &search.to_string(), &replacement.to_string(), true) + .await + .unwrap(), + expected.as_bytes() + ); + } + // Each vector deliberately misses a native eligibility rule. Original + // replaceAll still owns Unicode, templates, sparse/short and multi-unit. + for (body, search, replacement, expected) in [ + ("q".repeat(4095), "q", "z", "z".repeat(4095)), + ( + format!("{}q", "x".repeat(4095)), + "q", + "z", + format!("{}z", "x".repeat(4095)), + ), + ("éq".repeat(2048), "q", "z", "éz".repeat(2048)), + ("😀q".repeat(2048), "q", "z", "😀z".repeat(2048)), + ("q".repeat(4096), "q", "$", "$".repeat(4096)), + ("q".repeat(4096), "q", "$$", "$".repeat(4096)), + ("q".repeat(4096), "q", "$&", "q".repeat(4096)), + ("q".repeat(4096), "q", "$1", "$1".repeat(4096)), + ("q".repeat(4096), "q", "", String::new()), + ("qr".repeat(2048), "qr", "z", "z".repeat(2048)), + ] { + assert_eq!( + replace_text(&body, search, replacement, true) + .await + .unwrap(), + expected.as_bytes() + ); + } +} + +#[test] +fn native_literal_replace_helper_remains_private() { + for source in [ + "function rewrite(input){return __voleReplaceASCIIAll('q',1,113,122);}", + "function rewrite(input){let __voleReplaceASCIIAll=1;return {type:'pass'};}", + "function rewrite(input){return input.__voleReplaceASCIIAll;}", + "function rewrite(input){return input['__voleReplaceASCIIAll'];}", + "function rewrite(input){return {__voleReplaceASCIIAll:1};}", + ] { + assert!(validate_source(source).is_err(), "accepted {source}"); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn apple_native_literal_replace_retains_each_output_until_real_context_release() { + use crate::http_processing::body_budget::{MAX_BODY, WORKSPACE, bridge_workspace_cost}; + use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, + }; + const LENGTH: usize = 4096; + let code = CompiledSource { code: "function rewrite(input){let flags='';for(let i=0;i<3;i++){const value=__voleReplaceASCIIAll(input.body.data,input.body.data.length,113,122);flags+=value===undefined?'0':'1';}return {type:'modify',headers:[{op:'set',name:'x-native',values:[flags]}]};}".into(), ..Default::default() }; + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, MAX_BODY).unwrap(); + let prepaid = budget + .reserve(bridge_workspace_cost(LENGTH, true).unwrap()) + .unwrap(); + let occupied = budget + .reserve(WORKSPACE - budget.used() - 4 * LENGTH) + .unwrap(); + let before = budget.used(); + let observed = Arc::new(AtomicBool::new(false)); + let after_release = observed.clone(); + let at_release = budget.clone(); + apple::on_context_release_for_test(move || { + // Called immediately after JSGlobalContextRelease returns, while + // ExecutionGuard still owns both successful 2O reservations. + after_release.store(at_release.used() == WORKSPACE, Ordering::Release); + }); + let actual = evaluate_until( + &code, + &input("text"), + Some(&vec![b'q'; LENGTH]), + &mut output, + Some(&prepaid), + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_millis(100), + ) + .await + .unwrap(); + assert_eq!( + actual, + json!({"type":"modify","headers":[{"op":"set","name":"x-native","values":["110"]}]}) + ); + assert!(observed.load(Ordering::Acquire)); + assert_eq!(budget.used(), before); + drop(occupied); + drop(prepaid); + drop(output); + assert_eq!(budget.used(), 0); +} + +#[tokio::test] +async fn apple_native_literal_replace_keeps_dense_allocation_work_and_error_refund() { + let body = vec![b'q'; 65536]; + for (calls, accepted) in [(3, true), (4, false)] { + let source = format!( + "function rewrite(input){{let reserve=[0];for(let i=0;i<15;i++){{reserve=reserve.concat(reserve);}}let data=input.body.data;for(let i=0;i<{calls};i++){{data=data.replaceAll('q','q');}}return {{type:'pass'}};}}" + ); + assert_eq!( + evaluate_text(&source, &body, input("text")).await.is_ok(), + accepted + ); + } + let code = validate_source("function rewrite(input){const text=input.body.data.replaceAll('q','z');return {type:'modify',status:0,body:{kind:'text',data:text}};}").unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::empty(&budget); + assert!( + evaluate( + &code, + &input("text"), + Some(&body), + &mut output, + &CancellationToken::new() + ) + .await + .is_err() + ); + assert_eq!(budget.used(), 0); +} + +async fn ascii_utf8_input_observation( + code: &CompiledSource, + body: &str, + force_utf16: bool, + fill_workspace: bool, +) -> (Result, Vec, usize) { + let _constructor = force_utf16.then(apple::force_utf16_input_for_test); + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, super::super::body_budget::MAX_BODY).unwrap(); + let prepaid = budget + .reserve(super::super::body_budget::bridge_workspace_cost(body.len(), true).unwrap()) + .unwrap(); + let occupied = fill_workspace.then(|| { + budget + .reserve(super::super::body_budget::WORKSPACE - budget.used()) + .unwrap() + }); + let admitted = budget.used(); + let metadata = evaluate_until( + code, + &input("text"), + Some(body.as_bytes()), + &mut output, + Some(&prepaid), + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_millis(100), + ) + .await + .map_err(|error| error.kind()); + let ticks = apple::last_ticks_for_test().unwrap(); + // API-view and literal-output guards must have ended with the real context. + assert_eq!(budget.used(), admitted); + let bytes = output.as_ref().to_vec(); + drop(occupied); + drop(prepaid); + drop(output); + assert_eq!(budget.used(), 0); + (metadata, bytes, ticks) +} + +#[tokio::test(flavor = "current_thread")] +async fn apple_ascii_utf8_input_matches_utf16_data_methods_templates_and_fuel() { + let controls: String = (1u8..=127).map(char::from).collect::().repeat(32); + let bodies = [ + String::new(), + "q".into(), + controls, + "q".repeat(4095), + "q".repeat(4096), + "q".repeat(64 * 1024), + "q".repeat(super::super::body_budget::MAX_BODY), + "\0q\0".into(), + format!("{}\0q", "q".repeat(4096)), + format!("{}é😀q", "q".repeat(4096)), + ]; + for replacement in ["z", "$&"] { + let code = validate_source(&format!( + "function rewrite(input){{const text=input.body.data;return {{type:'modify',headers:[{{op:'set',name:'x-units',values:[String(text.length)]}}],body:{{kind:'text',data:text.replaceAll('q',{})}}}};}}", + serde_json::to_string(replacement).unwrap(), + )).unwrap(); + for body in &bodies { + let optimized = ascii_utf8_input_observation(&code, body, false, false).await; + let original = ascii_utf8_input_observation(&code, body, true, false).await; + assert_eq!( + optimized, + original, + "constructor changed result or fuel for length {}", + body.len() + ); + if replacement == "$&" && body.len() == super::super::body_budget::MAX_BODY { + // The original template scan consumes one tick per match. + // Constructor selection must preserve its real fuel failure. + assert_eq!(optimized.0, Err(io::ErrorKind::TimedOut)); + assert_eq!(optimized.2, 100_001); + assert!(optimized.1.is_empty()); + continue; + } + let expected = if replacement == "$&" { + body.clone() + } else { + body.replace('q', "z") + }; + assert_eq!(optimized.1, expected.as_bytes()); + assert_eq!( + optimized.0.as_ref().unwrap()["headers"][0]["values"][0], + body.encode_utf16().count().to_string() + ); + } + } +} + +#[tokio::test(flavor = "current_thread")] +async fn apple_ascii_utf8_input_keeps_full_workspace_and_cancel_deadline_boundaries() { + let code = validate_source( + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data}};}", + ) + .unwrap(); + for body in [ + "q".repeat(64 * 1024), + "q".repeat(super::super::body_budget::MAX_BODY), + "q\0é😀".into(), + ] { + let optimized = ascii_utf8_input_observation(&code, &body, false, true).await; + let original = ascii_utf8_input_observation(&code, &body, true, true).await; + assert_eq!(optimized, original); + assert!(optimized.0.is_ok()); + assert_eq!(optimized.1, body.as_bytes()); + } + for force_utf16 in [false, true] { + let _constructor = force_utf16.then(apple::force_utf16_input_for_test); + let budget = Budget::default(); + let mut output = BudgetedBytes::empty(&budget); + let body = vec![b'q'; 65536]; + let cancelled = CancellationToken::new(); + cancelled.cancel(); + let error = evaluate(&code, &input("text"), Some(&body), &mut output, &cancelled) + .await + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::Interrupted); + let error = evaluate_until( + &code, + &input("text"), + Some(&body), + &mut output, + None, + &CancellationToken::new(), + std::time::Instant::now() - std::time::Duration::from_millis(1), + ) + .await + .unwrap_err(); + assert_eq!(error.kind(), io::ErrorKind::TimedOut); + assert!(output.as_ref().is_empty()); + assert_eq!(budget.used(), 0); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn apple_bounded_bridge_matches_maximum_on_text_unicode_nul_bytes_none_and_max() { + use crate::http_processing::body_budget::{BridgePlan, MAX_BODY, WORKSPACE}; + let identity = + "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data}};}"; + let replace = "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('q','z')}};}"; + let literal = + "function rewrite(input){return {type:'modify',body:{kind:'text',data:'é😀\\u0000q'}};}"; + let cases = vec![ + (identity, "text", Some(vec![])), + (identity, "text", Some(vec![b'q'; MAX_BODY])), + (replace, "text", Some(vec![b'q'; 65536])), + (replace, "text", Some("qé😀\0".repeat(4096).into_bytes())), + (literal, "bytes", Some(vec![0xff; 32])), + (literal, "not-requested", None), + ]; + for (source, kind, bytes) in cases { + let mut observations = Vec::new(); + for maximum in [false, true] { + let mut code = validate_source(source).unwrap(); + if maximum { + code.output_bound = OutputBound::Maximum; + } + let budget = Budget::default(); + let output_bound = code.maximum_output_bytes(bytes.as_ref().map_or(0, Vec::len)); + let mut output = if bytes.is_some() { + BudgetedBytes::new( + &budget, + super::super::body_budget::output_capacity(output_bound).unwrap(), + ) + .unwrap() + } else { + BudgetedBytes::empty(&budget) + }; + let prepaid = bytes.as_ref().map(|bytes| { + budget + .reserve( + BridgePlan::new(bytes.len(), kind == "text", output_bound) + .unwrap() + .cost() + .unwrap(), + ) + .unwrap() + }); + // Same old pre-candidate occupancy: do not fill the newly saved + // bytes and accidentally manufacture a late export failure. + let old_cost = bytes.as_ref().map_or(0, |bytes| { + BudgetedBytes::allocation_cost(MAX_BODY).unwrap() + + super::super::body_budget::bridge_workspace_cost(bytes.len(), kind == "text") + .unwrap() + }); + let occupied = if bytes.is_some() { + Some(budget.reserve(WORKSPACE - old_cost).unwrap()) + } else { + None + }; + let before = budget.used(); + let result = apple::evaluate( + &code, + &input(kind), + bytes.as_deref(), + &mut output, + prepaid.as_ref(), + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_secs(5), + ) + .map_err(|e| e.kind()); + assert!(result.is_ok(), "{kind}, maximum={maximum}, {result:?}"); + if bytes.is_some() { + assert_eq!(budget.used(), before); + } + assert!(output.as_ref().len() <= output_bound); + observations.push(( + result, + output.as_ref().to_vec(), + apple::last_ticks_for_test(), + )); + drop(occupied); + drop(prepaid); + drop(output); + assert_eq!(budget.used(), 0); + } + assert_eq!( + observations[0], observations[1], + "source={source},kind={kind}" + ); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn apple_bounded_bridge_retained_slices_and_extra_live_through_actual_context_release() { + use crate::http_processing::body_budget::{BridgePlan, WORKSPACE}; + use std::{cell::RefCell, rc::Rc}; + let length = 4096; + // Trusted ABI-only vector forces four outputs past the small slot. The + // production proof does not come from this raw initializer. + let code=CompiledSource{code:"function rewrite(input){let flags='';for(let i=0;i<5;i++){const v=__voleReplaceASCIIAll(input.body.data,input.body.data.length,113,122);flags+=v===undefined?'0':'1';}return {type:'modify',headers:[{op:'set',name:'x-native',values:[flags]}],body:{kind:'text',data:input.body.data}};}".into(),output_bound:OutputBound::InputOrConstant{maximum_literal_bytes:0},..Default::default()}; + let plan = BridgePlan::new(length, true, length).unwrap(); + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, length).unwrap(); + let prepaid = budget.reserve(plan.cost().unwrap()).unwrap(); + let occupied = budget + .reserve(WORKSPACE - budget.used() - 6 * length) + .unwrap(); + let before = budget.used(); + let seen = Rc::new(RefCell::new(Vec::new())); + let copy = seen.clone(); + let at_event = budget.clone(); + apple::observe_bridge_for_test(move |event| { + copy.borrow_mut() + .push((event, at_event.used(), apple::bridge_view_for_test())) + }); + let released = Rc::new(RefCell::new(None)); + let copy = released.clone(); + let at_release = budget.clone(); + apple::on_context_release_for_test(move || { + *copy.borrow_mut() = Some((at_release.used(), apple::bridge_view_for_test())) + }); + let result = apple::evaluate( + &code, + &input("text"), + Some(&vec![b'q'; length]), + &mut output, + Some(&prepaid), + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_secs(5), + ) + .unwrap(); + apple::observe_bridge_for_test(|_| {}); + assert_eq!(result["headers"][0]["values"][0], "11110"); + let retained_capacity = plan.view_capacity - 3 * length; + let extra_retained = 8 * length - retained_capacity; + assert_eq!( + *released.borrow(), + Some(( + before + extra_retained, + (plan.view_capacity, retained_capacity) + )) + ); + assert_eq!(budget.used(), before); + assert_eq!(output.as_ref(), vec![b'q'; length]); + let seen = seen.borrow(); + assert!( + seen.iter() + .any(|entry| entry.0 == apple::BridgeEvent::ExportCopyStart + && entry.1 == before + extra_retained) + ); + let starts: Vec<_> = seen + .iter() + .filter(|e| e.0 == apple::BridgeEvent::NativeCopyStart) + .collect(); + let commits: Vec<_> = seen + .iter() + .filter(|e| e.0 == apple::BridgeEvent::NativeRetainedCommitted) + .collect(); + let drops: Vec<_> = seen + .iter() + .filter(|e| e.0 == apple::BridgeEvent::NativeOwnersDropped) + .collect(); + assert_eq!((starts.len(), commits.len(), drops.len()), (4, 4, 4)); + let sequence: Vec<_> = seen + .iter() + .filter_map(|entry| match entry.0 { + apple::BridgeEvent::NativeInputOwnerDropped => Some(false), + apple::BridgeEvent::NativeRetainedCommitted => Some(true), + _ => None, + }) + .collect(); + assert_eq!( + sequence, + vec![false, true, false, true, false, true, false, true] + ); + for ((start, commit), dropped) in starts.iter().zip(commits).zip(drops) { + let available = plan.view_capacity - start.2.1; + let needed_extra = (7 * length + std::mem::size_of::>()).saturating_sub(available); + assert!(start.1 >= before + needed_extra); + assert!(commit.2.1 >= start.2.1); + // Runs after native API refs and Vec dropped but before temporary guard. + assert_eq!(dropped.1, commit.1); + } + drop(seen); + drop(occupied); + drop(prepaid); + drop(output); + assert_eq!(budget.used(), 0); +} + +#[tokio::test(flavor = "current_thread")] +async fn apple_bounded_bridge_export_reserves_before_copy_and_refunds_after_owner() { + use crate::http_processing::body_budget::WORKSPACE; + use std::{cell::RefCell, rc::Rc}; + let text = "é😀\0"; + let units = text.encode_utf16().count(); + let code=validate_source("function rewrite(input){return {type:'respond',status:200,body:{kind:'text',data:'é😀\\u0000'}};}").unwrap(); + for free in [3 * units - 1, 3 * units] { + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, text.len()).unwrap(); + let occupied = budget.reserve(WORKSPACE - budget.used() - free).unwrap(); + let before = budget.used(); + let events = Rc::new(RefCell::new(Vec::new())); + let copy = events.clone(); + let ledger = budget.clone(); + apple::observe_bridge_for_test(move |event| copy.borrow_mut().push((event, ledger.used()))); + let result = apple::evaluate( + &code, + &input("not-requested"), + None, + &mut output, + None, + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_secs(5), + ); + apple::observe_bridge_for_test(|_| {}); + if free < 3 * units { + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::OutOfMemory); + assert!(events.borrow().is_empty()); + assert!(output.as_ref().is_empty()); + } else { + assert!(result.is_ok()); + assert_eq!(output.as_ref(), text.as_bytes()); + assert_eq!( + &*events.borrow(), + &[ + (apple::BridgeEvent::ExportCopyStart, before + 3 * units), + (apple::BridgeEvent::ExportOwnerDropped, before + 3 * units) + ] + ); + } + assert_eq!(budget.used(), before); + drop(occupied); + drop(output); + assert_eq!(budget.used(), 0); + } +} + +#[tokio::test(flavor = "current_thread")] +async fn apple_bounded_bridge_accounts_for_intermediate_strings_larger_than_input_and_bound() { + use crate::http_processing::body_budget::{BridgePlan, WORKSPACE, output_capacity}; + use std::{cell::RefCell, rc::Rc}; + let body = "qxxx".repeat(16384); + let length = body.len(); + let wide_length = 3 * length; + for statement in [ + "const unused=wide.includes('z');", + "const unused=wide.replaceAll('q','z');", + ] { + let source = format!( + "function rewrite(input){{const wide=input.body.data+input.body.data+input.body.data;{statement}return {{type:'modify',body:{{kind:'text',data:input.body.data}}}};}}" + ); + let code = validate_source(&source).unwrap(); + assert_eq!(code.maximum_output_bytes(length), length); + let plan = BridgePlan::new(length, true, length).unwrap(); + let mut observations = Vec::new(); + for fill in [false, true] { + let budget = Budget::default(); + let mut output = BudgetedBytes::new(&budget, output_capacity(length).unwrap()).unwrap(); + let prepaid = budget.reserve(plan.cost().unwrap()).unwrap(); + let occupied = fill.then(|| budget.reserve(WORKSPACE - budget.used()).unwrap()); + let before = budget.used(); + let events = Rc::new(RefCell::new(Vec::new())); + let copy = events.clone(); + let ledger = budget.clone(); + apple::observe_bridge_for_test(move |event| { + copy.borrow_mut().push((event, ledger.used())) + }); + let result = apple::evaluate( + &code, + &input("text"), + Some(body.as_bytes()), + &mut output, + Some(&prepaid), + &CancellationToken::new(), + std::time::Instant::now() + std::time::Duration::from_secs(5), + ) + .map_err(|e| e.kind()); + apple::observe_bridge_for_test(|_| {}); + assert!(result.is_ok(), "{statement} fill={fill} {result:?}"); + assert_eq!(output.as_ref(), body.as_bytes()); + assert_eq!(budget.used(), before); + let events = events.borrow(); + if !fill { + let (kind, extra) = if statement.contains("replaceAll") { + ( + apple::BridgeEvent::NativeCopyStart, + 7 * wide_length + std::mem::size_of::>() - plan.view_capacity, + ) + } else { + ( + apple::BridgeEvent::AsciiCopyStart, + 3 * wide_length - plan.view_capacity, + ) + }; + assert!( + events + .iter() + .any(|(event, used)| *event == kind && *used >= before + extra) + ); + } else { + assert!(events.iter().all(|(_, used)| *used == before)); + assert!( + !events + .iter() + .any(|(e, _)| *e == apple::BridgeEvent::NativeCopyStart) + ); + } + observations.push((result, apple::last_ticks_for_test())); + drop(events); + drop(occupied); + drop(prepaid); + drop(output); + assert_eq!(budget.used(), 0); + } + assert_eq!(observations[0], observations[1], "{statement}"); + } +} diff --git a/src/http_processing/selector_sharing_tests.rs b/src/http_processing/selector_sharing_tests.rs new file mode 100644 index 0000000..7c53e09 --- /dev/null +++ b/src/http_processing/selector_sharing_tests.rs @@ -0,0 +1,257 @@ +//! Real document/rule compiler controls; no listeners, peers or user scripts. +use super::*; +use crate::http_processing::rules::{ + MAX_PATTERN, MAX_RULE_TEXT, Matcher, Phase, RuleAction, SelectorCompiler, UrlAction, +}; +use regex::Regex; +use serde_json::{Value, json}; + +const UP: &str = r"^https://example\.test/up/(?P[0-9]+)$"; +const DOWN: &str = r"^https://example\.test/down/(?P[0-9]+)$"; + +fn document(value: Value) -> Arc { + Document::parse(&serde_yaml_ng::to_string(&value).unwrap()).unwrap() +} + +fn payload(value: Value) -> Arc { + Arc::new(Payload::parse(serde_yaml_ng::to_string(&value).unwrap().as_bytes()).unwrap()) +} + +fn raw(value: Value) -> RawRule { + serde_yaml_ng::from_str(&serde_yaml_ng::to_string(&value).unwrap()).unwrap() +} + +fn selector(rule: &Rule) -> &Arc { + let Matcher::Regex(regex) = &rule.selector else { + panic!("expected a native regex selector"); + }; + regex +} + +fn target(rule: &Rule, input: &str) -> String { + let Some(UrlAction::Forward(url)) = + rule.evaluate_url(&url::Url::parse(input).unwrap()).unwrap() + else { + panic!("expected an actual URL replacement"); + }; + url.to_string() +} + +fn source_inputs() -> (Arc, BTreeMap>) { + let document = document(json!({ + "rewrite-providers": {"inside": {"type": "file", "path": "rules.yaml"}}, + "rewrite": { + "enabled": true, + "rules": [ + { + "url": UP, "action": "request-header-set", + "header": "X-Proof", "value": "one" + }, + {"rule-set": "inside"}, + { + "url": DOWN, "action": "replace", + "replacement": "https://two.test/$1" + } + ] + } + })); + let payload = payload(json!({"payload": [ + { + "url": DOWN, "action": "response-body-replace", + "search": "a", "replacement": "b" + }, + { + "url": UP, "action": "replace", + "replacement": "https://one.test/${id}" + } + ]})); + (document, BTreeMap::from([("inside".to_owned(), payload)])) +} + +#[test] +fn native_selectors_share_within_candidate_without_merging_origins_or_captures() { + let (document, contents) = source_inputs(); + let candidate = document.compile(&contents).unwrap(); + assert_eq!(candidate.rules.len(), 4); + assert!(Arc::ptr_eq( + selector(&candidate.rules[0]), + selector(&candidate.rules[2]), + )); + assert!(Arc::ptr_eq( + selector(&candidate.rules[1]), + selector(&candidate.rules[3]), + )); + assert!(!Arc::ptr_eq( + selector(&candidate.rules[0]), + selector(&candidate.rules[1]), + )); + assert!(matches!( + &candidate.rules[0].action, + RuleAction::Header { + phase: Phase::Request, + .. + } + )); + assert!(matches!( + &candidate.rules[1].action, + RuleAction::Body { + phase: Phase::Response, + .. + } + )); + assert!(matches!( + candidate.origin(0), + Some(SourceLocation::Local { index: 0 }) + )); + assert!(matches!( + candidate.origin(1), + Some(SourceLocation::Provider { provider, index: 0 }) if provider == "inside" + )); + assert!(matches!( + candidate.origin(2), + Some(SourceLocation::Provider { provider, index: 1 }) if provider == "inside" + )); + assert!(matches!( + candidate.origin(3), + Some(SourceLocation::Local { index: 2 }) + )); + assert_eq!( + target(&candidate.rules[2], "https://example.test/up/17"), + "https://one.test/17" + ); + assert_eq!( + target(&candidate.rules[3], "https://example.test/down/23"), + "https://two.test/23" + ); +} + +#[test] +fn native_selector_owners_are_generation_local_and_release_after_last_policy_owner() { + let (document, contents) = source_inputs(); + let first = document.compile(&contents).unwrap(); + let second = document.compile(&contents).unwrap(); + assert_eq!(first.identity(), second.identity()); + assert!(!Arc::ptr_eq( + selector(&first.rules[0]), + selector(&second.rules[0]), + )); + let weak = Arc::downgrade(selector(&first.rules[0])); + let policy = first.bind_ca(None).unwrap(); + let last_owner = Arc::clone(&first); + drop(first); + assert!(weak.upgrade().is_some()); + drop(policy); + assert!(weak.upgrade().is_some()); + drop(last_owner); + assert!(weak.upgrade().is_none()); + assert!(second.rules[0].matches(&url::Url::parse("https://example.test/up/17").unwrap())); +} + +#[test] +fn native_selector_sharing_keeps_rule_text_pattern_and_disabled_boundaries() { + let reject = json!({"url": ".", "action": "reject"}); + let full = document(json!({"rewrite": { + "enabled": true, "rules": vec![reject.clone(); MAX_RULES] + }})) + .compile(&BTreeMap::new()) + .unwrap(); + assert_eq!(full.rules.len(), MAX_RULES); + assert!( + full.rules + .iter() + .all(|rule| Arc::ptr_eq(selector(rule), selector(&full.rules[0]))) + ); + let expanded = |count| { + let document = document(json!({ + "rewrite-providers": {"inside": {"type": "file", "path": "rules.yaml"}}, + "rewrite": {"rules": [reject.clone(), {"rule-set": "inside"}]} + })); + let contents = BTreeMap::from([( + "inside".to_owned(), + payload(json!({"payload": vec![reject.clone(); count]})), + )]); + document.compile(&contents) + }; + assert_eq!(expanded(MAX_RULES - 1).unwrap().rules.len(), MAX_RULES); + assert!(expanded(MAX_RULES).is_err()); + + // The comment keeps the regex NFA tiny while charging exact raw pattern bytes. + let pattern = format!("(?x)#{}", "a".repeat(MAX_PATTERN - 5)); + assert_eq!(pattern.len(), MAX_PATTERN); + let mut selectors = SelectorCompiler::default(); + let mut text = 0; + let mut first = None; + for _ in 0..MAX_RULE_TEXT / MAX_PATTERN { + let rule = Rule::compile_with_selectors( + raw(json!({"url": pattern, "action": "reject"})), + &mut text, + &mut selectors, + ) + .unwrap(); + if let Some(first) = &first { + assert!(Arc::ptr_eq(selector(first), selector(&rule))); + } else { + first = Some(rule); + } + } + assert_eq!(text, MAX_RULE_TEXT); + assert!( + Rule::compile_with_selectors( + raw(json!({"url": pattern, "action": "reject"})), + &mut text, + &mut selectors, + ) + .is_err() + ); + assert_eq!(text, MAX_RULE_TEXT); + + let mut selectors = SelectorCompiler::default(); + let mut text = 0; + let enabled = Rule::compile_with_selectors(raw(reject), &mut text, &mut selectors).unwrap(); + let disabled = Rule::compile_with_selectors( + raw(json!({"url": ".", "action": "reject", "enabled": false})), + &mut text, + &mut selectors, + ) + .unwrap(); + assert!(Arc::ptr_eq(selector(&enabled), selector(&disabled))); + assert_eq!(text, 2); + assert!(!disabled.matches(&url::Url::parse("https://example.test/").unwrap())); + for pattern in [ + "(".to_owned(), + format!("(?x)#{}", "a".repeat(MAX_PATTERN - 4)), + ] { + assert!( + Rule::compile_with_selectors( + raw(json!({"url": pattern, "action": "reject", "enabled": false})), + &mut text, + &mut selectors, + ) + .is_err() + ); + assert_eq!(text, 2); + } + let disabled_reference = document(json!({ + "rewrite-providers": {"missing": {"type": "file", "path": "never-read.yaml"}}, + "rewrite": {"rules": [{"rule-set": "missing", "enabled": false}]} + })); + assert_eq!(disabled_reference.unresolved_count(), 0); + assert!( + disabled_reference + .compile(&BTreeMap::new()) + .unwrap() + .rules + .is_empty() + ); + assert!( + Document::parse( + &serde_yaml_ng::to_string(&json!({ + "rewrite": {"enabled": false, "rules": [ + {"url": "(", "action": "reject", "enabled": false} + ]} + })) + .unwrap() + ) + .is_err() + ); +} diff --git a/src/http_processing/shared_collector_body_memory_tests.rs b/src/http_processing/shared_collector_body_memory_tests.rs new file mode 100644 index 0000000..3c16a02 --- /dev/null +++ b/src/http_processing/shared_collector_body_memory_tests.rs @@ -0,0 +1,148 @@ +// Tests only: the real Transaction::begin_shared selector and original ledger. +use super::*; + +fn shared_selector_meta(length: Option, fields: &Fields) -> WireBodyMeta { + let meta = OriginalRequestMeta::new("POST", fields); + WireBodyMeta::new(fields, &meta, Phase::Request, None, length, false) +} + +#[cfg(target_vendor = "apple")] +#[test] +#[ignore = "physical Apple map fixture only; legal mmap fallback is not a semantic failure"] +fn apple_shared_collector_mapping_path_fixture() { + let url = Url::parse("https://shared-collector.invalid/body").unwrap(); + let native = rules("- {url: '.', action: request-body-replace, search: a, replacement: a}"); + for length in [65536, 65537, MAX_BODY] { + for script_body in [false, true] { + let budget = Budget::default(); + let control = BudgetedBytes::new_fixed_output(&budget, length).unwrap(); + assert!( + control.is_mapped_for_test(), + "physical map fixture unavailable" + ); + drop(control); + let wire = shared_selector_meta(Some(length as u64), &vec![]); + let selected = if script_body { + &[][..] + } else { + native.as_slice() + }; + let transaction = Transaction::begin_shared( + &budget, + selected, + &url, + Phase::Request, + &wire, + script_body, + ) + .unwrap(); + let raw = transaction.into_raw(); + let actual = raw.is_mapped_for_test(); + drop(raw); + assert_eq!(budget.used(), 0); + // Failure is meaningful only after the owner confirms mmap did + // not legitimately fail between the control and selector calls. + assert!( + actual, + "shared selector unmapped: inspect legal fallback vs old wiring" + ); + } + } +} + +#[test] +fn shared_unknown_sentinel_and_native_entry_keep_vector_and_original_limit() { + let budget = Budget::default(); + let url = Url::parse("https://shared-collector.invalid/body").unwrap(); + let native = rules("- {url: '.', action: request-body-replace, search: a, replacement: a}"); + let wire = shared_selector_meta(Some(65536), &vec![]); + let native_only = Transaction::begin(&budget, &native, &url, Phase::Request, &wire).unwrap(); + assert!(!native_only.raw.is_mapped_for_test()); + drop(native_only); + let unknown = shared_selector_meta(None, &vec![]); + let mut transaction = + Transaction::begin_shared(&budget, &[], &url, Phase::Request, &unknown, true).unwrap(); + assert!(!transaction.raw.is_mapped_for_test()); + assert_eq!(transaction.remaining(), MAX_BODY + 1); + let cost = BudgetedBytes::allocation_cost(MAX_BODY + 1).unwrap(); + assert_eq!(budget.used(), cost); + assert_eq!( + transaction.push(&vec![b'a'; MAX_BODY + 1]), + Err(Bypass::Size) + ); + let raw = transaction.into_raw(); + assert_eq!(raw.as_ref().len(), MAX_BODY + 1); + assert_eq!(raw.remaining(), 0); + assert!(!raw.is_mapped_for_test()); + drop(raw); + let oversized = shared_selector_meta(Some(MAX_BODY as u64 + 1), &vec![]); + assert!(matches!( + Transaction::begin_shared(&budget, &[], &url, Phase::Request, &oversized, true), + Err(Bypass::Size) + )); + assert!(matches!( + Transaction::begin_shared(&budget, &[], &url, Phase::Request, &wire, false), + Err(Bypass::NoRules) + )); + assert_eq!(budget.used(), 0); +} + +#[test] +fn large_shared_native_failure_and_header_failure_keep_original_raw() { + let original = vec![b'a'; 65536]; + let url = Url::parse("https://shared-collector.invalid/body").unwrap(); + for header_failure in [false, true] { + let selected = rules(if header_failure { + "- {url: '.', action: request-body-replace, search: a, replacement: b}" + } else { + "- {url: '.', action: request-body-replace, search: a, replacement: b}\n- {url: '.', action: request-body-json-patch, patch: [{op: test, path: /ok, value: false}]}" + }); + let budget = Budget::default(); + let mut fields: Fields = vec![ + ("Content-Length".into(), "65536".into()), + ("Content-Type".into(), "text/plain".into()), + ("X-Independent".into(), "kept".into()), + ]; + if header_failure { + let used = fields + .iter() + .map(|(n, v)| n.len() + v.len() + 32) + .sum::(); + fields.push(( + "X-Pad".into(), + "p".repeat(crate::http_processing::headers::MAX_BYTES - used - 5 - 32), + )); + } + crate::http_processing::headers::check(&fields).unwrap(); + let before = fields.clone(); + let wire = shared_selector_meta(Some(original.len() as u64), &fields); + // false represents a native body plus metadata-only JS shared caller. + let mut transaction = + Transaction::begin_shared(&budget, &selected, &url, Phase::Request, &wire, false) + .unwrap(); + transaction.push(&original).unwrap(); + let source_pointer = transaction.raw.as_ref().as_ptr(); + let entity = transaction.finish_shared(false, &mut fields); + assert!(!entity.changed()); + assert_eq!( + entity.bypass, + Some(if header_failure { + Bypass::Budget + } else { + Bypass::Transform + }) + ); + assert_eq!(entity.wire().as_ptr(), source_pointer); + assert_eq!(entity.logical().unwrap(), original); + assert_eq!(fields, before); + let last = entity.wire().slice(65535..); + drop(entity); + assert_eq!(last.as_ref(), b"a"); + assert_eq!( + budget.used(), + BudgetedBytes::allocation_cost(65536).unwrap() + ); + drop(last); + assert_eq!(budget.used(), 0); + } +} diff --git a/src/http_processing/shared_collector_c15_cancel_metadata_memory_tests.rs b/src/http_processing/shared_collector_c15_cancel_metadata_memory_tests.rs new file mode 100644 index 0000000..1af7955 --- /dev/null +++ b/src/http_processing/shared_collector_c15_cancel_metadata_memory_tests.rs @@ -0,0 +1,265 @@ +// Memory-only shared collector cancellation and metadata script controls. +// Real shared collection, cancellation, script backend and final Bytes owner. +use super::*; +use std::sync::{Arc, atomic::AtomicUsize}; +use tokio::io::{AsyncRead, BufReader, ReadBuf}; +use tokio::sync::Notify; +use tokio::time::timeout; + +// Observe actual source reads without retaining a payload or changing reads. +struct SourceProgress { + inner: R, + read: Arc, + changed: Arc, +} +impl AsyncRead for SourceProgress { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + buffer: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + let before = buffer.filled().len(); + let result = Pin::new(&mut this.inner).poll_read(cx, buffer); + if matches!(&result, Poll::Ready(Ok(()))) { + let count = buffer.filled().len() - before; + if count != 0 { + this.read.fetch_add(count, Ordering::AcqRel); + this.changed.notify_one(); + } + } + result + } +} + +#[tokio::test(flavor = "current_thread")] +async fn known_h1_shared_collection_cancels_after_64k_and_joins_before_refund() { + const LENGTH: usize = 128 * 1024; + const PREFIX: usize = 64 * 1024; + let budget = body::Budget::default(); + let cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + let read = Arc::new(AtomicUsize::new(0)); + let changed = Arc::new(Notify::new()); + let stop = CancellationToken::new(); + let child_stop = stop.clone(); + let child_budget = budget.clone(); + let child_read = read.clone(); + let child_changed = changed.clone(); + let (mut writer, source) = tokio::io::duplex(4096); + let mut owner = tokio::spawn(async move { + let mut reader = BufReader::new(SourceProgress { + inner: source, + read: child_read.clone(), + changed: child_changed, + }); + let url = Url::parse("https://shared-cancel.invalid/body").unwrap(); + let mut fields = vec![ + ("Content-Length".into(), LENGTH.to_string()), + ("X-Independent".into(), "kept".into()), + ]; + let before = fields.clone(); + let meta = OriginalRequestMeta::new("GET", &fields); + let wire = WireBodyMeta::new( + &fields, + &meta, + Phase::Response, + Some(200), + Some(LENGTH as u64), + false, + ); + let transaction = + Transaction::begin_shared(&child_budget, &[], &url, Phase::Response, &wire, true) + .unwrap(); + let blocklist = HashSet::new(); + // Pending collection owns the actual complete known-capacity backing. + // The original collector deadline is unchanged by the observer. + let outcome = tokio::select! { biased; + () = child_stop.cancelled() => Err(io::Error::from(io::ErrorKind::Interrupted)), + result = prepare_shared( + &mut reader, Body::Length(LENGTH as u64), &blocklist, + Duration::from_secs(1), Some(transaction), &mut fields, + ) => result.map(|_| ()), + }; + // The selected future has dropped its real Transaction before these facts. + let facts = ( + outcome.map_err(|error| error.kind()), + fields == before, + child_read.load(Ordering::Acquire), + reader.buffer().len(), + ); + drop(reader); + facts + }); + // No assertion before cleanup: timeout/error must still cancel and join. + let observed = timeout(Duration::from_secs(5), async { + writer.write_all(&vec![b'a'; PREFIX]).await?; + loop { + let change = changed.notified(); + if read.load(Ordering::Acquire) >= PREFIX { + break; + } + change.await; + } + Ok::<_, io::Error>((!owner.is_finished(), budget.used())) + }) + .await; + stop.cancel(); + drop(writer); + let joined = match timeout(Duration::from_secs(2), &mut owner).await { + Ok(result) => result.map_err(|error| error.to_string()), + Err(_) => { + owner.abort(); + let _ = owner.await; + Err("collector owner needed fallback abort and was actually joined".into()) + } + }; + let remaining = budget.used(); + let (pending, charged) = observed + .expect("fixed memory harness deadline") + .expect("real source prefix delivery"); + let (result, unchanged, source_reads, buffered) = joined.expect("collector actually joined"); + assert!(pending, "an incomplete known body must still be collecting"); + assert_eq!(charged, cost); + assert_eq!(result, Err(io::ErrorKind::Interrupted)); + assert!(unchanged, "incomplete collection must not commit headers"); + assert_eq!(source_reads, PREFIX); + assert_eq!( + buffered, 0, + "the observed source prefix was consumed by the collector" + ); + assert_eq!( + remaining, 0, + "real collector/IO owner must drop before final refund" + ); +} + +#[cfg(target_vendor = "apple")] +#[tokio::test(flavor = "current_thread")] +async fn shared_native_64k_then_real_metadata_script_keeps_body_owner_through_send() { + const LENGTH: usize = 64 * 1024; + let policy = Policy::compile(r#"rewrite: + enabled: true + rules: + - {url: 'https://shared-meta.invalid/body', match: exact, action: request-body-replace, search: a, replacement: b} +http-scripts: + enabled: true + scripts: + - name: real-metadata-after-native + phase: request + match: exact + url: https://shared-meta.invalid/body + body: none + source: 'function rewrite(input){if(!input.body || input.body.kind !== "not-requested"){return {type:"abort"};}return {type:"modify",headers:[{op:"set",name:"x-meta",values:["after-native"]}]};}' +"#).unwrap(); + let budget = policy.body_budget(); + let url = Url::parse("https://shared-meta.invalid/body").unwrap(); + let original_fields = vec![ + ("Content-Type".into(), "text/plain".into()), + ("Content-Length".into(), LENGTH.to_string()), + ]; + let mut fields = original_fields.clone(); + let meta = OriginalRequestMeta::new("POST", &original_fields); + let wire = WireBodyMeta::new( + &original_fields, + &meta, + Phase::Request, + None, + Some(LENGTH as u64), + false, + ); + // This is the real false+native admission used with body:none scripts. + assert!( + policy + .scripts() + .iter() + .all(|script| script.body == BodyMode::None) + ); + let transaction = + Transaction::begin_shared(budget, policy.rules(), &url, Phase::Request, &wire, false) + .unwrap(); + let mut input = vec![b'a'; LENGTH]; + input.extend_from_slice(b"NEXT"); + let mut reader = input.as_slice(); + let (mut prepared, entity) = prepare_shared( + &mut reader, + Body::Length(LENGTH as u64), + &HashSet::new(), + Duration::from_secs(1), + Some(transaction), + &mut fields, + ) + .await + .unwrap(); + let entity = entity.expect("actual native shared collection completed"); + assert!(entity.changed() && entity.bypass.is_none()); + assert_eq!(entity.logical().unwrap(), vec![b'b'; LENGTH]); + assert_eq!(reader, b"NEXT"); + let native_owner = entity.wire().clone(); + let native_pointer = native_owner.as_ptr(); + let cost = BudgetedBytes::allocation_cost(LENGTH).unwrap(); + assert_eq!(budget.used(), cost); + let mut message = script_message::Message::request( + OriginalSnapshot { + url: url.clone(), + method: "POST".into(), + identity_allowed: meta.identity_allowed, + asterisk: false, + }, + RequestSnapshot { + url: url.clone(), + method: "POST".into(), + headers: fields, + }, + Some(entity), + &original_fields, + false, + ); + let outcome = script_message::run(&policy, &url, &mut message, &CancellationToken::new()) + .await + .unwrap(); + assert!(matches!(outcome, Outcome::Forward)); + assert!( + message.request.headers.iter().any(|(name, value)| { + name.eq_ignore_ascii_case("x-meta") && value == "after-native" + }), + "the real body:none backend must have changed the ordinary header" + ); + let final_entity = message + .body + .take() + .expect("metadata script preserved native body"); + assert_eq!(final_entity.wire().as_ptr(), native_pointer); + assert_eq!(final_entity.logical().unwrap(), vec![b'b'; LENGTH]); + assert_eq!( + budget.used(), + cost, + "metadata-only execution must not retain another body" + ); + let last = final_entity.wire().slice(LENGTH - 1..); + prepared.install_entity(final_entity); + drop(message); + let mut sent = Vec::new(); + prepared + .transfer( + &mut reader, + &mut sent, + Duration::from_secs(1), + &HashSet::new(), + false, + ) + .await + .unwrap(); + assert_eq!(sent, vec![b'b'; LENGTH]); + assert_eq!(reader, b"NEXT"); + assert_eq!(native_owner.as_ref(), sent); + assert_eq!(budget.used(), cost); + drop(native_owner); + assert_eq!(last.as_ref(), b"b"); + assert_eq!( + budget.used(), + cost, + "the final real slice still owns the full charge" + ); + drop(last); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/shared_collector_h1_memory_tests.rs b/src/http_processing/shared_collector_h1_memory_tests.rs new file mode 100644 index 0000000..8cba50e --- /dev/null +++ b/src/http_processing/shared_collector_h1_memory_tests.rs @@ -0,0 +1,182 @@ +// The real shared H1 Cursor/collector; no sockets or background owners. +use super::*; + +fn shared_h1_native_noop() -> Vec { + let raw: crate::http_processing::rules::RawRule = serde_yaml_ng::from_str( + "{url: '.', action: response-body-replace, search: a, replacement: a}", + ) + .unwrap(); + vec![crate::http_processing::rules::Rule::compile(raw, &mut 0).unwrap()] +} + +#[tokio::test] +async fn shared_h1_known_64k_keeps_next_request_and_final_slice_owner() { + let url = Url::parse("https://shared-h1.invalid/body").unwrap(); + let native = shared_h1_native_noop(); + let payload = vec![b'a'; 65536]; + for script_body in [false, true] { + let budget = body::Budget::default(); + let mut fields = vec![("Content-Length".into(), "65536".into())]; + let before = fields.clone(); + let meta = OriginalRequestMeta::new("GET", &fields); + let wire = WireBodyMeta::new( + &fields, + &meta, + Phase::Response, + Some(200), + Some(65536), + false, + ); + let selected = if script_body { + &[][..] + } else { + native.as_slice() + }; + let transaction = + Transaction::begin_shared(&budget, selected, &url, Phase::Response, &wire, script_body) + .unwrap(); + let mut wire_bytes = payload.clone(); + wire_bytes.extend_from_slice(b"NEXT"); + let mut reader = wire_bytes.as_slice(); + let (prepared, entity) = prepare_shared( + &mut reader, + Body::Length(65536), + &HashSet::new(), + Duration::from_secs(1), + Some(transaction), + &mut fields, + ) + .await + .unwrap(); + assert_eq!(wire_bytes.len() - reader.len(), 65536); + assert_eq!(reader, b"NEXT"); + assert_eq!(fields, before); + let entity = entity.expect("shared completed entity"); + assert_eq!(entity.wire().as_ref(), payload); + let last = entity.wire().slice(65535..); + drop(entity); + let mut sent = Vec::new(); + prepared + .transfer( + &mut reader, + &mut sent, + Duration::from_secs(1), + &HashSet::new(), + false, + ) + .await + .unwrap(); + assert_eq!(sent, payload); + assert_eq!(reader, b"NEXT"); + assert_eq!(last.as_ref(), b"a"); + assert_eq!( + budget.used(), + body::BudgetedBytes::allocation_cost(65536).unwrap() + ); + drop(last); + assert_eq!(budget.used(), 0); + } +} + +#[tokio::test] +async fn shared_h1_declared_64k_partial_eof_never_commits() { + let budget = body::Budget::default(); + let url = Url::parse("https://shared-h1.invalid/body").unwrap(); + let mut fields = vec![ + ("Content-Length".into(), "65536".into()), + ("X-Independent".into(), "kept".into()), + ]; + let before = fields.clone(); + let meta = OriginalRequestMeta::new("GET", &fields); + let wire = WireBodyMeta::new( + &fields, + &meta, + Phase::Response, + Some(200), + Some(65536), + false, + ); + let transaction = + Transaction::begin_shared(&budget, &[], &url, Phase::Response, &wire, true).unwrap(); + let bytes = vec![b'a'; 65535]; + let mut reader = bytes.as_slice(); + let error = prepare_shared( + &mut reader, + Body::Length(65536), + &HashSet::new(), + Duration::from_secs(1), + Some(transaction), + &mut fields, + ) + .await + .err() + .expect("real cursor must observe the partial EOF"); + assert_eq!(error.kind(), io::ErrorKind::UnexpectedEof); + assert!(reader.is_empty()); + assert_eq!(fields, before); + assert_eq!(budget.used(), 0); +} + +#[tokio::test] +async fn shared_h1_unknown_overflow_keeps_full_sentinel_trailers_and_next() { + let budget = body::Budget::default(); + let url = Url::parse("https://shared-h1.invalid/body").unwrap(); + let meta = OriginalRequestMeta::new("GET", &vec![]); + let wire = WireBodyMeta::new(&vec![], &meta, Phase::Response, Some(200), None, false); + let transaction = + Transaction::begin_shared(&budget, &[], &url, Phase::Response, &wire, true).unwrap(); + let payload = vec![b'a'; body::MAX_BODY + 123]; + let mut wire_bytes = format!("{:x}\r\n", payload.len()).into_bytes(); + wire_bytes.extend_from_slice(&payload); + wire_bytes.extend_from_slice(b"\r\n0\r\nX-End: kept\r\n\r\nNEXT"); + let mut reader = wire_bytes.as_slice(); + let mut fields = vec![("X-Independent".into(), "kept".into())]; + let before = fields.clone(); + let (prepared, entity) = prepare_shared( + &mut reader, + Body::Chunked, + &HashSet::new(), + Duration::from_secs(1), + Some(transaction), + &mut fields, + ) + .await + .unwrap(); + assert!(entity.is_none()); + let prefix = prepared.prefix.as_ref().expect("original overflow prefix"); + assert_eq!(prefix.as_ref().len(), body::MAX_BODY + 1); + assert!(!prefix.is_mapped_for_test()); + assert_eq!(fields, before); + assert_eq!( + budget.used(), + body::BudgetedBytes::allocation_cost(body::MAX_BODY + 1).unwrap() + ); + let mut sent = Vec::new(); + prepared + .transfer( + &mut reader, + &mut sent, + Duration::from_secs(1), + &HashSet::new(), + false, + ) + .await + .unwrap(); + assert_eq!(reader, b"NEXT"); + assert!(sent.ends_with(b"0\r\nX-End: kept\r\n\r\n")); + let mut replay = sent.as_slice(); + let mut dechunked = Vec::new(); + framing::transfer_body( + &mut replay, + &mut dechunked, + Body::Chunked, + Duration::from_secs(1), + &HashSet::new(), + true, + ) + .await + .unwrap(); + assert_eq!(dechunked, payload); + assert!(replay.is_empty()); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/shared_collector_h2_memory_tests.rs b/src/http_processing/shared_collector_h2_memory_tests.rs new file mode 100644 index 0000000..319e138 --- /dev/null +++ b/src/http_processing/shared_collector_h2_memory_tests.rs @@ -0,0 +1,97 @@ +// Real shared collector and Length/frame handling through Source::Buffered. +// This is not a wire/RecvStream flow-credit test; that boundary stays explicit. +use super::*; + +fn shared_h2_wire(length: Option) -> WireBodyMeta { + let meta = OriginalRequestMeta::new("GET", &vec![]); + WireBodyMeta::new(&vec![], &meta, Phase::Response, Some(200), length, false) +} + +#[tokio::test] +async fn shared_h2_64k_length_completion_and_errors_preserve_atomicity() { + let url = Url::parse("https://shared-h2.invalid/body").unwrap(); + for actual in [65535, 65536, 65537] { + let budget = Budget::default(); + let wire = shared_h2_wire(Some(65536)); + let transaction = + Transaction::begin_shared(&budget, &[], &url, Phase::Response, &wire, true).unwrap(); + let mut fields = vec![ + ("Content-Length".into(), "65536".into()), + ("X-Independent".into(), "kept".into()), + ]; + let before = fields.clone(); + let result = prepare_shared( + Source::buffered(Bytes::from(vec![b'a'; actual]), None), + transaction, + Some(65536), + false, + &mut fields, + ) + .await; + assert_eq!(fields, before); + if actual == 65536 { + let prepared = result.expect("exact complete shared frame body"); + assert_eq!(prepared.expected, Some(65536)); + let entity = prepared.entity.expect("actual collected entity"); + assert_eq!(entity.logical().unwrap(), vec![b'a'; 65536]); + let last = entity.wire().slice(65535..); + drop(entity); + let (body, trailers) = drain(prepared.source).await; + assert_eq!(body, vec![b'a'; 65536]); + assert!(trailers.is_none()); + assert_eq!(last.as_ref(), b"a"); + assert_eq!( + budget.used(), + crate::http_processing::body::BudgetedBytes::allocation_cost(65536).unwrap() + ); + drop(last); + } else { + let error = result + .err() + .expect("real Length rejects short/oversized body"); + assert_eq!(error.kind(), io::ErrorKind::ConnectionAborted); + } + assert_eq!(budget.used(), 0); + } +} + +#[tokio::test] +async fn shared_h2_unknown_overflow_replays_prefix_remaining_frame_and_trailers() { + let budget = Budget::default(); + let url = Url::parse("https://shared-h2.invalid/body").unwrap(); + let wire = shared_h2_wire(None); + let transaction = + Transaction::begin_shared(&budget, &[], &url, Phase::Response, &wire, true).unwrap(); + let payload = Bytes::from(vec![b'a'; MAX_BODY + 123]); + let mut trailers = HeaderMap::new(); + trailers.insert("x-final", "kept".parse().unwrap()); + let mut fields = vec![("X-Independent".into(), "kept".into())]; + let before = fields.clone(); + let prepared = prepare_shared( + Source::buffered(payload.clone(), Some(trailers)), + transaction, + None, + false, + &mut fields, + ) + .await + .unwrap(); + assert!(prepared.entity.is_none()); + assert_eq!(prepared.expected, None); + assert_eq!(fields, before); + let prefix = prepared + .source + .prefix + .as_ref() + .expect("collected MAX_BODY+1 sentinel"); + assert_eq!(prefix.len(), MAX_BODY + 1); + assert_eq!(prepared.source.pending.as_ref().unwrap().len(), 122); + assert_eq!( + budget.used(), + crate::http_processing::body::BudgetedBytes::allocation_cost(MAX_BODY + 1).unwrap() + ); + let (replayed, trailers) = drain(prepared.source).await; + assert_eq!(replayed, payload); + assert_eq!(trailers.unwrap()["x-final"], "kept"); + assert_eq!(budget.used(), 0); +} diff --git a/src/http_processing/shared_collector_h2_recvstream_memory_test.rs b/src/http_processing/shared_collector_h2_recvstream_memory_test.rs new file mode 100644 index 0000000..43f31d9 --- /dev/null +++ b/src/http_processing/shared_collector_h2_recvstream_memory_test.rs @@ -0,0 +1,192 @@ +// Real H2 RecvStream + shared collector. No TLS/backend or host sockets. +use super::*; + +#[tokio::test(flavor = "current_thread")] +async fn actual_shared_recvstream_returns_credit_replays_overflow_and_joins() { + use crate::http_processing::{ + body::{Budget, BudgetedBytes, MAX_BODY, OriginalRequestMeta, Transaction, WireBodyMeta}, + h2_body::{Source, finish, prepare_shared, send_data}, + rules::Phase, + }; + use hyper::body::Body as _; + use url::Url; + + for known in [true, false] { + let length = if known { 128 * 1024 } else { MAX_BODY + 123 }; + let expected_length = known.then_some(length as u64); + let capacity = if known { length } else { MAX_BODY + 1 }; + let budget = Budget::default(); + let live = Arc::new(AtomicUsize::new(0)); + let stop = CancellationToken::new(); + let mut client_owner = None; + let mut server_owner = None; + let (client, server) = tokio::io::duplex(8192); + let client = CountedIo::new(client, &live); + let server = CountedIo::new(server, &live); + let observed = timeout(Duration::from_secs(5), async { + let (mut sender, connection) = ::h2::client::handshake(client) + .await + .map_err(|_| failed("real H2 client handshake"))?; + let client_stop = stop.clone(); + client_owner = Some(tokio::spawn(async move { + tokio::select! { biased; + _ = client_stop.cancelled() => Ok::<_, io::Error>("cancelled"), + result = connection => result.map(|_| "protocol-ended") + .map_err(|_| failed("real H2 client protocol")), + } + })); + let mut connection = ::h2::server::Builder::new() + .initial_window_size(32 * 1024) + .initial_connection_window_size(64 * 1024) + .handshake::<_, Bytes>(server) + .await + .map_err(|_| failed("real H2 server handshake"))?; + sender = sender + .ready() + .await + .map_err(|_| failed("real H2 request ready"))?; + let mut request = http::Request::builder() + .method("POST") + .uri("https://shared-collector.invalid/body"); + if known { + request = request.header("content-length", length); + } + let request = request.body(()).map_err(|_| failed("real H2 request"))?; + let (response, mut upload) = sender + .send_request(request, false) + .map_err(|_| failed("real H2 request headers"))?; + let (request, mut reply) = connection + .accept() + .await + .ok_or_else(|| failed("real H2 request missing"))? + .map_err(|_| failed("real H2 accept"))?; + let server_stop = stop.clone(); + server_owner = Some(tokio::spawn(async move { + loop { + tokio::select! { biased; + _ = server_stop.cancelled() => return Ok::<_, io::Error>("cancelled"), + request = connection.accept() => match request { + None => return Ok("protocol-ended"), + Some(Err(_)) => return Err(failed("real H2 server protocol")), + Some(Ok(_)) => return Err(failed("unexpected sibling request")), + }, + } + } + })); + let sending = async { + send_data(&mut upload, Bytes::from(vec![b'a'; length])).await?; + let trailers = if known { + None + } else { + let mut fields = http::HeaderMap::new(); + fields.insert("x-final", "kept".parse().map_err(|_| failed("trailer"))?); + Some(fields) + }; + finish(&mut upload, trailers, false)?; + drop(upload); + let response = response.await.map_err(|_| failed("response missing"))?; + if response.status() != http::StatusCode::OK || !response.body().is_end_stream() { + return Err(failed("response not complete")); + } + Ok::<_, io::Error>(()) + }; + let collecting = async { + let mut fields = vec![("X-Independent".into(), "kept".into())]; + if known { + fields.push(("Content-Length".into(), length.to_string())); + } + let before = fields.clone(); + let meta = OriginalRequestMeta::new("POST", &fields); + let wire = + WireBodyMeta::new(&fields, &meta, Phase::Request, None, expected_length, false); + let url = Url::parse("https://shared-collector.invalid/body") + .map_err(|_| failed("test URL"))?; + let transaction = + Transaction::begin_shared(&budget, &[], &url, Phase::Request, &wire, true) + .map_err(|_| failed("actual shared collector admission"))?; + let prepared = prepare_shared( + Source::h2(request.into_body()), + transaction, + expected_length, + false, + &mut fields, + ) + .await?; + let entity_present = prepared.entity.is_some(); + let expected_preserved = prepared.expected == expected_length; + drop(prepared.entity); + let mut source = prepared.source; + let mut received = 0; + let mut data_correct = true; + let mut trailer_present = false; + let mut last_slice = None; + while let Some(frame) = poll_fn(|cx| Pin::new(&mut source).poll_frame(cx)).await { + let frame = frame?; + match frame.into_data() { + Ok(data) => { + received += data.len(); + data_correct &= data.iter().all(|byte| *byte == b'a'); + if last_slice.is_none() && !data.is_empty() { + last_slice = Some(data.slice(..1)); + } + } + Err(frame) => { + if let Ok(fields) = frame.into_trailers() { + trailer_present = + fields.get("x-final").is_some_and(|value| value == "kept"); + } + } + } + } + drop(source); + reply + .send_response(http::Response::new(()), true) + .map_err(|_| failed("response headers"))?; + Ok::<_, io::Error>(( + entity_present, + expected_preserved, + fields == before, + received, + data_correct, + trailer_present, + last_slice, + )) + }; + let (_, facts) = tokio::try_join!(sending, collecting)?; + drop(sender); + Ok::<_, io::Error>(facts) + }) + .await; + + // All paths cancel and actually join both H2/duplex owners first. + // The retained Bytes below owns only paid body backing, not protocol IO. + stop.cancel(); + let server_join = match server_owner { + Some(owner) => Some(joined(owner).await), + None => None, + }; + let client_join = match client_owner { + Some(owner) => Some(joined(owner).await), + None => None, + }; + assert!(matches!(&server_join, Some(Ok(Ok(_)))), "{server_join:?}"); + assert!(matches!(&client_join, Some(Ok(Ok(_)))), "{client_join:?}"); + assert_eq!(live.load(Ordering::Acquire), 0); + let facts = observed + .expect("fixed memory harness deadline") + .expect("actual shared collection and wire transfer"); + let (entity, expected, fields, received, data, trailers, last) = facts; + assert_eq!(entity, known); + assert!(expected && fields && data); + assert_eq!(received, length); + assert_eq!(trailers, !known); + let last = last.expect("real source DATA retains a paid raw slice"); + assert_eq!(last.as_ref(), b"a"); + assert_eq!( + budget.used(), + BudgetedBytes::allocation_cost(capacity).unwrap() + ); + drop(last); + assert_eq!(budget.used(), 0); + } +} diff --git a/src/http_processing/sniffing_tests.rs b/src/http_processing/sniffing_tests.rs new file mode 100644 index 0000000..83b5462 --- /dev/null +++ b/src/http_processing/sniffing_tests.rs @@ -0,0 +1,173 @@ +//! Configured routing hints in the real HTTP adapter, using only memory peers. +use super::*; +use crate::{ + config::Config, + routing::{GeoMatcher, RoutingContext}, +}; +use std::net::{IpAddr, SocketAddr}; + +struct ExampleGeo; +impl GeoMatcher for ExampleGeo { + fn matches_geosite(&self, code: &str, domain: &str) -> bool { + code == "cn" && domain == "allowed.example" + } + fn matches_geoip(&self, _: &str, _: IpAddr) -> bool { + false + } +} + +struct SniffingOrigin { + origin: Arc, + policy: Arc, +} +#[async_trait] +impl Dispatcher for SniffingOrigin { + async fn sniff_plan( + &self, + source: SocketAddr, + destination: &Destination, + ) -> Result, DispatchError> { + let host = match destination { + Destination::Domain { host, .. } => Some(host.as_str()), + Destination::Ip(_) => None, + }; + Ok(Some(self.policy.plan(source, destination, host, false)?)) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.origin.connect_tcp(session).await + } + async fn open_datagram( + &self, + session: DatagramSession, + ) -> Result, DispatchError> { + self.origin.open_datagram(session).await + } +} + +const NATIVE_HEADER: &str = "rewrite:\n enabled: true\n rules:\n - {url: '.', action: response-header-set, header: X-Native, value: kept}\n"; +const MAIN: &str = "sniffer:\n enable: true\n parse-pure-ip: true\n override-destination: false\n sniff:\n HTTP: {ports: [80]}\nrules: ['GEOSITE,cn,DIRECT','MATCH,REJECT']\n"; + +async fn exchange(main: &str, http: &str, host: &str) -> (String, StreamSession) { + let config = Config::parse_yaml(main.as_bytes()).unwrap(); + let origin = Arc::new(Origin::default()); + let dispatcher = Arc::new(SniffingOrigin { + origin: origin.clone(), + policy: crate::sniffing::Policy::new(Arc::new(config.sniffer), Arc::new(ExampleGeo)), + }); + let context = HttpContext::new( + Policy::compile(http).unwrap(), + dispatcher, + SecurityContext::new(), + ); + let (mut client, mut server) = tokio::io::duplex(8192); + let mut initial = session(); + initial.sniffed_domain = None; + let task = tokio::spawn(async move { + assert!(matches!( + context + .try_intercept(&mut server, initial, CancellationToken::new()) + .await + .unwrap(), + Intercept::Handled + )); + }); + client + .write_all( + format!("GET /original HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await + .unwrap(); + let mut response = String::new(); + timeout(Duration::from_secs(5), client.read_to_string(&mut response)) + .await + .unwrap() + .unwrap(); + task.await.unwrap(); + origin.join().await; + let selected = origin.sessions.lock().unwrap(); + assert_eq!(selected.len(), 1); + (response, selected[0].clone()) +} + +#[tokio::test] +async fn plain_h1_preserves_configured_geosite_hint_and_selected_ip() { + let (response, selected) = exchange(MAIN, NATIVE_HEADER, "allowed.example").await; + assert!(response.to_ascii_lowercase().contains("x-native: kept\r\n")); + assert_eq!(selected.destination, session().destination); + assert_eq!(selected.sniffed_domain.as_deref(), Some("allowed.example")); + let main = Config::parse_yaml(MAIN.as_bytes()).unwrap(); + let routing = RoutingContext::with_domain_hint( + crate::config::Network::Tcp, + &selected.destination, + selected.sniffed_domain.as_deref(), + ) + .unwrap(); + assert!(crate::routing::matches_rule(&main.rules[0], &routing, &ExampleGeo).unwrap()); + assert_eq!( + selected.metadata.original.as_ref().unwrap().destination, + session().destination + ); +} + +#[tokio::test] +async fn plain_h1_does_not_enable_excluded_or_unconfigured_http_sniffing() { + let configurations = [ + MAIN.replace("enable: true", "enable: false"), + MAIN.replace("parse-pure-ip: true", "parse-pure-ip: false"), + MAIN.replace("ports: [80]", "ports: [8080]"), + MAIN.replace("HTTP:", "TLS:"), + MAIN.replace(" sniff:", " skip-domain: [allowed.example]\n sniff:"), + MAIN.replace(" sniff:", " skip-src-address: [198.18.0.0/16]\n sniff:"), + MAIN.replace(" sniff:", " skip-dst-address: [203.0.113.0/24]\n sniff:"), + ]; + for main in configurations { + let (_, selected) = exchange(&main, NATIVE_HEADER, "allowed.example").await; + assert_eq!(selected.destination, session().destination, "{main}"); + assert_eq!(selected.sniffed_domain, None, "{main}"); + } + let (_, selected) = exchange(MAIN, NATIVE_HEADER, "203.0.113.1").await; + assert_eq!(selected.sniffed_domain, None); +} + +#[tokio::test] +async fn plain_h1_honors_explicit_override_and_discards_old_hint_on_origin_change() { + let main = MAIN.replace("override-destination: false", "override-destination: true"); + let (_, selected) = exchange(&main, NATIVE_HEADER, "allowed.example").await; + assert_eq!( + selected.destination, + Destination::domain("allowed.example", 80).unwrap() + ); + assert_eq!(selected.sniffed_domain.as_deref(), Some("allowed.example")); + assert_eq!( + selected.metadata.original.as_ref().unwrap().destination, + session().destination + ); + let (_, selected) = exchange( + MAIN, + "rewrite:\n enabled: true\n rules:\n - {url: 'http://allowed.example/', match: prefix, action: replace, replacement: 'http://final.example/'}\n", + "allowed.example", + ) + .await; + assert_eq!( + selected.destination, + Destination::domain("final.example", 80).unwrap() + ); + assert_eq!(selected.sniffed_domain, None); +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn request_script_sees_the_sniffed_base_then_final_origin_replaces_its_hint() { + let (_, selected) = exchange( + MAIN, + "http-scripts:\n enabled: true\n scripts:\n - name: final-target\n phase: request\n url: 'http://allowed.example/'\n match: prefix\n source: 'function rewrite(input) { return {type:\"modify\",url:\"http://script-final.example/\"}; }'\n", + "allowed.example", + ) + .await; + assert_eq!( + selected.destination, + Destination::domain("script-final.example", 80).unwrap() + ); + assert_eq!(selected.sniffed_domain, None); +} diff --git a/src/http_processing/tests.rs b/src/http_processing/tests.rs index 0c2ffd8..dfa47d6 100644 --- a/src/http_processing/tests.rs +++ b/src/http_processing/tests.rs @@ -1,4 +1,13 @@ //! No sockets or host peers: adapters use duplex IO and a recording dispatcher. +#[path = "https_h1_reuse_memory_tests.rs"] +mod https_h1_reuse_memory_tests; +#[path = "ingress_memory_tests.rs"] +mod ingress_memory_tests; +#[cfg(target_vendor = "apple")] +#[path = "script_h1_tests.rs"] +mod script_h1_tests; +#[path = "sniffing_tests.rs"] +mod sniffing_tests; use super::*; use crate::{ dispatch::{BoxStream, DatagramTransport, DispatchError}, diff --git a/src/inbound/http/final_flush_repoll_memory_tests.rs b/src/inbound/http/final_flush_repoll_memory_tests.rs new file mode 100644 index 0000000..2e8782e --- /dev/null +++ b/src/inbound/http/final_flush_repoll_memory_tests.rs @@ -0,0 +1,306 @@ +// Real H1 body/flush/response ordering; no new production witness is referenced. +use super::*; +use futures_util::task::AtomicWaker; +use std::{ + pin::Pin, + sync::atomic::{AtomicU8, AtomicUsize, Ordering}, + task::{Context, Poll}, +}; +use tokio::{ + io::{AsyncReadExt, DuplexStream, ReadBuf}, + sync::oneshot, +}; + +const BODY_BYTES: usize = 65536; +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Case { + Ready, + Pending, + Error, + MissingSource, + LastWritePending, +} +#[derive(Default)] +struct Control { + mode: AtomicU8, + tail_polls: AtomicUsize, + body_written: AtomicUsize, + body_write_polls: AtomicUsize, + source_read_polls: AtomicUsize, + wake: AtomicWaker, +} +struct SourceIo { + io: DuplexStream, + control: Arc, +} +impl AsyncRead for SourceIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + self.control + .source_read_polls + .fetch_add(1, Ordering::Release); + Pin::new(&mut self.io).poll_read(cx, out) + } +} +struct TailIo { + io: DuplexStream, + control: Arc, + head_flushed: bool, + block_last: bool, + first_tail: Option>, +} +impl AsyncRead for TailIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, out) + } +} +impl AsyncWrite for TailIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + data: &[u8], + ) -> Poll> { + let body = self.head_flushed; + if body { + self.control + .body_write_polls + .fetch_add(1, Ordering::Release); + } + let written = self.control.body_written.load(Ordering::Acquire); + let data = if body && self.block_last && !data.is_empty() { + self.control.wake.register(cx.waker()); + let remaining = (BODY_BYTES - 1).saturating_sub(written); + if remaining == 0 { + return Poll::Pending; + } + &data[..data.len().min(remaining)] + } else { + data + }; + let result = Pin::new(&mut self.io).poll_write(cx, data); + if body && let Poll::Ready(Ok(count)) = &result { + self.control + .body_written + .fetch_add(*count, Ordering::Release); + } + result + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + if !self.head_flushed { + let result = Pin::new(&mut self.io).poll_flush(cx); + if matches!(&result, Poll::Ready(Ok(()))) { + self.head_flushed = true; + } + return result; + } + self.control.tail_polls.fetch_add(1, Ordering::Release); + self.control.wake.register(cx.waker()); + if let Some(first) = self.first_tail.take() { + let _ = first.send(()); + } + match self.control.mode.load(Ordering::Acquire) { + 0 => Poll::Pending, + 1 => Pin::new(&mut self.io).poll_flush(cx), + _ => Poll::Ready(Err(io::ErrorKind::ConnectionReset.into())), + } + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} + +async fn exercise(case: Case) -> (bool, bool, Vec, usize) { + let (source, source_reader) = tokio::io::duplex(128 * 1024); + let (source_release, release_source) = oneshot::channel(); + let supplied = if case == Case::MissingSource { + BODY_BYTES - 1 + } else { + BODY_BYTES + }; + let source_owner = tokio::spawn(tokio::task::unconstrained(async move { + let mut source = source; + let result = source.write_all(&vec![b'a'; supplied]).await; + let _ = release_source.await; + result + })); + let (upstream_io, peer) = tokio::io::duplex(128 * 1024); + let control = Arc::new(Control::default()); + let (first_tail, tail_entered) = oneshot::channel(); + let peer_control = control.clone(); + let peer_owner = tokio::spawn(tokio::task::unconstrained(async move { + let mut peer = BufReader::new(peer); + let head = read_head(&mut peer, 16384).await?; + let prefix = if matches!(case, Case::MissingSource | Case::LastWritePending) { + BODY_BYTES - 1 + } else { + BODY_BYTES + }; + let mut body = vec![0; prefix]; + peer.read_exact(&mut body).await?; + if prefix == BODY_BYTES { + tail_entered + .await + .map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe))?; + } + // Make final flush Ready/error and response head Ready in the same + // peer poll. The real parent select remains biased response-first. + let polls_before_response = ( + peer_control.source_read_polls.load(Ordering::Acquire), + peer_control.body_write_polls.load(Ordering::Acquire), + ); + peer_control.mode.store( + match case { + Case::Ready => 1, + Case::Error => 2, + _ => 0, + }, + Ordering::Release, + ); + peer_control.wake.wake(); + peer.get_mut() + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: keep-alive\r\n\r\nack") + .await?; + let mut trailing = Vec::new(); + peer.read_to_end(&mut trailing).await?; + Ok::<_, io::Error>((head, body, trailing, polls_before_response)) + })); + let request = parse_request_head( + b"POST http://origin.test/upload HTTP/1.1\r\nHost: origin.test\r\nContent-Length: 65536\r\nConnection: keep-alive", + Vec::new(), + ).unwrap(); + let plan = RequestPlan::new(&request).unwrap(); + let config = HttpServerConfig::processing(); + let mut input = BufReader::new(SourceIo { + io: source_reader, + control: control.clone(), + }); + let mut response = Vec::new(); + let mut upstream = UpstreamIo::new(Box::new(TailIo { + io: upstream_io, + control: control.clone(), + head_flushed: false, + block_last: case == Case::LastWritePending, + first_tail: Some(first_tail), + })); + let began = Instant::now(); + let outcome = timeout( + Duration::from_secs(2), + tokio::task::unconstrained(forward_on_stream( + &mut input, + &mut response, + &mut upstream, + &request, + plan, + &config, + None, + true, + )), + ) + .await; + let elapsed = began.elapsed(); + let tail_polls = control.tail_polls.load(Ordering::Acquire); + let body_written = control.body_written.load(Ordering::Acquire); + let polls_after_response = ( + control.source_read_polls.load(Ordering::Acquire), + control.body_write_polls.load(Ordering::Acquire), + ); + drop(upstream); + drop(input); + let _ = source_release.send(()); + // Both exact owned tasks finish before even the expected old-code red. + let source_result = source_owner.await; + let peer_result = peer_owner.await; + assert!( + source_result.is_ok(), + "source owner did not join: {source_result:?}" + ); + source_result.unwrap().unwrap(); + let (head, body, trailing, polls_before_response) = peer_result.unwrap().unwrap(); + assert_eq!( + polls_after_response, polls_before_response, + "candidate polled source/body write after final head: {case:?}" + ); + assert_eq!( + elapsed, + Duration::ZERO, + "one-poll candidate awaited a Pending tail or reset a deadline: {case:?}" + ); + assert!(head.starts_with(b"POST /upload HTTP/1.1\r\n")); + assert_eq!( + body.len(), + if matches!(case, Case::MissingSource | Case::LastWritePending) { + BODY_BYTES - 1 + } else { + BODY_BYTES + } + ); + assert!(body.iter().all(|byte| *byte == b'a')); + assert!( + trailing.is_empty(), + "candidate replayed or sent more body after final: {case:?}" + ); + assert_eq!(body_written, body.len()); + assert!(response.starts_with(b"HTTP/1.1 200 OK\r\n") && response.ends_with(b"\r\n\r\nack")); + let outcome = outcome + .expect("forward owner hit fixture fail-safe") + .unwrap(); + ( + outcome.downstream_keep_alive, + outcome.upstream_reusable, + response, + tail_polls, + ) +} + +#[tokio::test(start_paused = true)] +async fn final_response_repolls_an_already_ready_real_tail_flush_once() { + let (downstream, upstream, response, polls) = exercise(Case::Ready).await; + assert!(polls >= 1, "real upload never reached its final flush"); + // Old behavior reaches this assertion only after all bytes, response and joins. + assert!( + downstream && upstream, + "response-first selection hid the completed upload flush" + ); + assert!( + response + .windows(b"Connection: keep-alive".len()) + .any(|bytes| bytes == b"Connection: keep-alive") + ); +} + +#[tokio::test(start_paused = true)] +async fn pending_error_missing_source_and_last_write_keep_the_original_close() { + for case in [ + Case::Pending, + Case::Error, + Case::MissingSource, + Case::LastWritePending, + ] { + let (downstream, upstream, response, polls) = exercise(case).await; + assert!(!downstream && !upstream, "unsafe reuse after {case:?}"); + assert!( + response + .windows(b"Connection: close".len()) + .any(|bytes| bytes == b"Connection: close") + ); + if matches!(case, Case::MissingSource | Case::LastWritePending) { + assert_eq!( + polls, 0, + "incomplete read/write reached a final-flush witness" + ); + } else { + assert!(polls >= 1); + } + } +} + +mod prepared_cases { + include!("final_flush_repoll_prepared_memory_tests.rs"); +} diff --git a/src/inbound/http/final_flush_repoll_prepared_memory_tests.rs b/src/inbound/http/final_flush_repoll_prepared_memory_tests.rs new file mode 100644 index 0000000..b173235 --- /dev/null +++ b/src/inbound/http/final_flush_repoll_prepared_memory_tests.rs @@ -0,0 +1,375 @@ +// Actual shared collection/native rewrite, Message forwarding and paid owners. +use super::*; +use crate::http_processing::{ + Policy, body, + h1_body::{self, Message}, + rules::Phase, +}; +use std::sync::Mutex; +use url::Url; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +enum Native { + Replace, + Shorten, + Rejected, +} +struct CountSource { + io: SourceIo, + bytes: Arc, +} +impl AsyncRead for CountSource { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let before = out.filled().len(); + let result = Pin::new(&mut self.io).poll_read(cx, out); + self.bytes + .fetch_add(out.filled().len() - before, Ordering::Release); + result + } +} +struct LimitLast { + io: TailIo, + bytes: usize, + block: bool, +} +impl AsyncRead for LimitLast { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, out) + } +} +impl AsyncWrite for LimitLast { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + data: &[u8], + ) -> Poll> { + let data = if self.block && self.io.head_flushed && !data.is_empty() { + let remaining = self + .bytes + .saturating_sub(1) + .saturating_sub(self.io.control.body_written.load(Ordering::Acquire)); + if remaining == 0 { + self.io + .control + .body_write_polls + .fetch_add(1, Ordering::Release); + self.io.control.wake.register(cx.waker()); + return Poll::Pending; + } + &data[..data.len().min(remaining)] + } else { + data + }; + Pin::new(&mut self.io).poll_write(cx, data) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} + +async fn shared(native: Native, case: Case) -> (bool, bool, usize) { + let policy = Policy::compile(if native == Native::Shorten { + "rewrite:\n enabled: true\n rules:\n - {url: '.', action: request-body-replace, search: aa, replacement: b}\n" + } else { + "rewrite:\n enabled: true\n rules:\n - {url: '.', action: request-body-replace, search: a, replacement: b}\n" + }).unwrap(); + let original = Url::parse("http://origin.test/upload").unwrap(); + let request = parse_request_head( + b"POST http://origin.test/upload HTTP/1.1\r\nHost: origin.test\r\nContent-Type: text/plain\r\nContent-Length: 65536\r\nConnection: keep-alive", + Vec::new(), + ).unwrap(); + let original_plan = RequestPlan::new(&request).unwrap(); + let original_meta = body::OriginalRequestMeta::new(&request.method, &request.headers); + let wire = body::WireBodyMeta::new( + &request.headers, + &original_meta, + Phase::Request, + None, + Some(BODY_BYTES as u64), + false, + ); + let config = HttpServerConfig::processing(); + let budget = body::Budget::default(); + // Reserve the actual independent ledger to refusal, without duplicating its limit. + let mut blockers = Vec::new(); + if native == Native::Rejected { + for _ in 0..64 { + match budget.reserve(body::MAX_BODY) { + Some(owner) => blockers.push(owner), + None => break, + } + } + } + let transaction = body::Transaction::begin_shared( + &budget, + policy.rules(), + &original, + Phase::Request, + &wire, + true, + ); + let rejected = matches!(&transaction, Err(body::Bypass::Budget)); + let (mut source, source_reader) = tokio::io::duplex(128 * 1024); + let (release, source_released) = oneshot::channel(); + let supplied = if case == Case::MissingSource { + BODY_BYTES - 1 + } else { + BODY_BYTES + }; + let source_owner = tokio::spawn(tokio::task::unconstrained(async move { + let result = source.write_all(&vec![b'a'; supplied]).await; + let _ = source_released.await; + result + })); + let control = Arc::new(Control::default()); + let source_bytes = Arc::new(AtomicUsize::new(0)); + let mut input = BufReader::new(CountSource { + io: SourceIo { + io: source_reader, + control: control.clone(), + }, + bytes: source_bytes.clone(), + }); + let mut outgoing = request.clone(); + let collected = timeout( + Duration::from_secs(2), + tokio::task::unconstrained(h1_body::prepare_shared( + &mut input, + original_plan.body, + &original_plan.trailer_blocklist, + config.body_idle_timeout, + transaction.ok(), + &mut outgoing.headers, + )), + ) + .await; + let (prepared, entity) = match collected { + Ok(Ok(value)) => value, + error => { + drop(input); + let _ = release.send(()); + let joined = source_owner.await; + drop(blockers); + panic!( + "real shared collection did not complete: timeout/error={}, source={joined:?}", + error.is_err() + ); + } + }; + let source_after_collection = source_bytes.load(Ordering::Acquire); + let entity_changed = entity + .as_ref() + .is_some_and(|entity| entity.changed() && entity.bypass.is_none()); + let entity_length = entity.as_ref().map(|entity| entity.wire().len()); + // A real slice shares the paid allocation; no synthetic identity/proof is built. + let retained = entity.map(|entity| entity.into_wire().slice(1..)); + let charge = budget.used(); + let plan = match RequestPlan::new(&outgoing) { + Ok(plan) => plan, + Err(error) => { + drop(prepared); + drop(retained); + drop(input); + let _ = release.send(()); + let joined = source_owner.await; + drop(blockers); + panic!("real processed framing invalid: {error}; source={joined:?}"); + } + }; + let output_bytes = match plan.body { + Body::Length(bytes) => bytes as usize, + _ => 0, + }; + let (upstream_io, peer) = tokio::io::duplex(128 * 1024); + let (first_tail, tail_entered) = oneshot::channel(); + let peer_control = control.clone(); + let peer_owner = tokio::spawn(tokio::task::unconstrained(async move { + let mut peer = BufReader::new(peer); + let head = read_head(&mut peer, 16384).await?; + let prefix = if matches!(case, Case::MissingSource | Case::LastWritePending) { + output_bytes.saturating_sub(1) + } else { + output_bytes + }; + let mut body = vec![0; prefix]; + peer.read_exact(&mut body).await?; + if prefix == output_bytes { + tail_entered + .await + .map_err(|_| io::Error::from(io::ErrorKind::BrokenPipe))?; + } + let polls = ( + peer_control.source_read_polls.load(Ordering::Acquire), + peer_control.body_write_polls.load(Ordering::Acquire), + ); + peer_control + .mode + .store(if case == Case::Ready { 1 } else { 0 }, Ordering::Release); + peer_control.wake.wake(); + peer.get_mut() + .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 3\r\nConnection: keep-alive\r\n\r\nack") + .await?; + let mut trailing = Vec::new(); + peer.read_to_end(&mut trailing).await?; + Ok::<_, io::Error>((head, body, trailing, polls)) + })); + let message = Message { + policy: &policy, + original: &original, + request: &request, + meta: original_meta, + continued: std::sync::atomic::AtomicBool::new(false), + prepared: Mutex::new(Some(prepared)), + scripts: None, + }; + let mut upstream = UpstreamIo::new(Box::new(LimitLast { + io: TailIo { + io: upstream_io, + control: control.clone(), + head_flushed: false, + block_last: false, + first_tail: Some(first_tail), + }, + bytes: output_bytes, + block: case == Case::LastWritePending, + })); + let mut response = Vec::new(); + let began = Instant::now(); + let outcome = timeout( + Duration::from_secs(2), + tokio::task::unconstrained(forward_on_stream( + &mut input, + &mut response, + &mut upstream, + &request, + plan, + &config, + Some(&message), + true, + )), + ) + .await; + let elapsed = began.elapsed(); + let polls = ( + control.source_read_polls.load(Ordering::Acquire), + control.body_write_polls.load(Ordering::Acquire), + ); + let source_after_forward = source_bytes.load(Ordering::Acquire); + let written = control.body_written.load(Ordering::Acquire); + let tail_polls = control.tail_polls.load(Ordering::Acquire); + drop(upstream); + drop(message); + drop(input); + let _ = release.send(()); + let source_result = source_owner.await; + let peer_result = peer_owner.await; + let retained_charge = budget.used(); + drop(retained); + drop(blockers); + let refunded = budget.used(); + // All IO/task/body owners have been released before any behavior assertion. + source_result.unwrap().unwrap(); + let (head, body, trailing, before) = peer_result.unwrap().unwrap(); + assert_eq!( + elapsed, + Duration::ZERO, + "unexpected wait: {native:?}/{case:?}" + ); + assert_eq!( + polls, before, + "extra source/write poll after final response" + ); + assert!(head.starts_with(b"POST /upload HTTP/1.1\r\n")); + let wire_head = parse_request_head(&head, Vec::new()).unwrap(); + let wire_lengths: Vec<_> = wire_head + .headers + .iter() + .filter(|(name, _)| name.eq_ignore_ascii_case("content-length")) + .map(|(_, value)| value.parse::().ok()) + .collect(); + assert_eq!( + wire_lengths, + vec![Some(output_bytes)], + "real output header/framing disagree" + ); + assert!(response.starts_with(b"HTTP/1.1 200 OK\r\n") && response.ends_with(b"\r\n\r\nack")); + assert!(trailing.is_empty()); + assert_eq!(written, body.len()); + assert_eq!(refunded, 0, "real paid allocation outlived its last owner"); + assert!( + charge > 0 && retained_charge == charge, + "last real alias/blocker did not retain its ledger charge" + ); + if native == Native::Rejected { + assert!(rejected && !entity_changed && entity_length.is_none()); + assert_eq!(source_after_collection, 0); + assert_eq!(source_after_forward, BODY_BYTES - 1); + assert_eq!(body, vec![b'a'; BODY_BYTES - 1]); + } else { + assert!(!rejected && entity_changed); + let expected = if native == Native::Shorten { + BODY_BYTES / 2 + } else { + BODY_BYTES + }; + assert_eq!(entity_length, Some(expected)); + assert_eq!(output_bytes, expected); + assert_eq!(source_after_collection, BODY_BYTES); + assert_eq!(source_after_forward, BODY_BYTES); + assert_eq!( + body, + vec![b'b'; expected - usize::from(case == Case::LastWritePending)] + ); + } + let outcome = outcome.expect("forward fixture fail-safe expired").unwrap(); + ( + outcome.downstream_keep_alive, + outcome.upstream_reusable, + tail_polls, + ) +} + +#[tokio::test(start_paused = true)] +async fn shared_native_64k_real_message_repolls_and_refunds_the_last_owner() { + let (downstream, upstream, polls) = shared(Native::Replace, Case::Ready).await; + assert!(polls >= 1); + assert!( + downstream && upstream, + "real precollected Message lost already-ready upload completion" + ); +} +#[tokio::test(start_paused = true)] +async fn shorter_output_keeps_the_complete_original_source_identity() { + let (downstream, upstream, polls) = shared(Native::Shorten, Case::Ready).await; + assert!(polls >= 1); + assert!( + downstream && upstream, + "changed wire length replaced the real source proof" + ); +} +#[tokio::test(start_paused = true)] +async fn precollected_shorter_output_last_write_pending_still_closes() { + let (downstream, upstream, polls) = shared(Native::Shorten, Case::LastWritePending).await; + assert!(!downstream && !upstream); + assert_eq!( + polls, 0, + "source completion alone was treated as final flush" + ); +} +#[tokio::test(start_paused = true)] +async fn real_budget_refusal_does_not_complete_an_incomplete_streaming_source() { + let (downstream, upstream, polls) = shared(Native::Rejected, Case::MissingSource).await; + assert!(!downstream && !upstream); + assert_eq!(polls, 0); +} diff --git a/src/inbound/http/framing.rs b/src/inbound/http/framing.rs index 6346e1d..ec5cd9b 100644 --- a/src/inbound/http/framing.rs +++ b/src/inbound/http/framing.rs @@ -31,6 +31,25 @@ pub(crate) struct RequestPlan { } impl RequestPlan { + /// Called after request processing; downstream persistence is independent. + pub(crate) fn enable_origin_persistence(&mut self) -> io::Result<()> { + if !matches!(self.body, Body::Empty | Body::Length(_)) + || !self.upgrade.is_empty() + || !self.keep_alive + { + return Err(invalid("request is not eligible for origin persistence")); + } + let suffix = b"Connection: close\r\n\r\n"; + let prefix = self + .head + .strip_suffix(suffix) + .ok_or_else(|| invalid("invalid generated persistence field"))?; + let length = prefix.len(); + self.head.truncate(length); + self.head + .extend_from_slice(b"Connection: keep-alive\r\n\r\n"); + Ok(()) + } pub(crate) fn edit_headers( &mut self, edit: impl FnOnce(&mut Vec<(String, String)>), @@ -125,9 +144,36 @@ pub(crate) struct ResponseHead { line: String, headers: Vec<(String, String)>, framing: Framing, + wire_http11: bool, + wire_close: bool, + wire_body: Body, + wire_reusable_status: bool, + wire_trailers: bool, } impl ResponseHead { + pub(crate) fn replace( + &mut self, + status: u16, + headers: Vec<(String, String)>, + ) -> io::Result<()> { + let status_code = + http::StatusCode::from_u16(status).map_err(|_| invalid("invalid response status"))?; + let framing = Framing::parse(&headers)?; + if (status < 200 || status == 204) && framing.body.is_some() + || status == 205 && !matches!(framing.body, None | Some(Body::Empty | Body::Length(0))) + { + return Err(invalid("body framing is forbidden for this response")); + } + self.status = status; + self.line = format!( + "HTTP/1.1 {status} {}", + status_code.canonical_reason().unwrap_or("Response") + ); + self.headers = headers; + self.framing = framing; + Ok(()) + } pub(crate) fn headers(&self) -> &Vec<(String, String)> { &self.headers } @@ -178,16 +224,38 @@ impl ResponseHead { if (status < 200 || status == 204) && framing.body.is_some() { return Err(invalid("body framing is forbidden for this response")); } + if status == 205 && !matches!(framing.body, None | Some(Body::Empty | Body::Length(0))) { + return Err(invalid("205 response must have an empty entity")); + } + let wire_reusable_status = status >= 200 + && !matches!(status, 204 | 205 | 206 | 304) + && !headers + .iter() + .any(|(n, _)| n.eq_ignore_ascii_case("content-range")); Ok(Self { status, line: format!("HTTP/1.1 {} {}", status, reason), headers, + wire_http11: version == "HTTP/1.1", + wire_close: framing.connection.contains("close"), + wire_body: framing.body.unwrap_or(Body::UntilEof), + wire_reusable_status, + wire_trailers: !framing.trailers.is_empty(), framing, }) } + pub(crate) fn origin_reusable(&self, method: &str) -> bool { + !matches!(method, "HEAD" | "CONNECT") + && self.wire_http11 + && !self.wire_close + && self.wire_reusable_status + && !self.wire_trailers + && matches!(self.wire_body, Body::Length(_)) + } + pub fn body(&self, method: &str) -> Body { - if method == "HEAD" || self.status < 200 || matches!(self.status, 204 | 304) { + if method == "HEAD" || self.status < 200 || matches!(self.status, 204 | 205 | 304) { Body::Empty } else { self.framing.body.unwrap_or(Body::UntilEof) @@ -684,6 +752,37 @@ fn invalid(message: &'static str) -> io::Error { #[cfg(test)] mod tests { + #[test] + fn reset_content_never_advertises_an_unsent_entity() { + use super::*; + let empty = + ResponseHead::parse(b"HTTP/1.1 205 Reset Content\r\nContent-Length: 0").unwrap(); + assert_eq!(empty.body("GET"), Body::Empty); + assert!(ResponseHead::parse(b"HTTP/1.1 205 Reset Content\r\nContent-Length: 12").is_err()); + assert!( + ResponseHead::parse(b"HTTP/1.1 205 Reset Content\r\nTransfer-Encoding: chunked") + .is_err() + ); + let mut ordinary = ResponseHead::parse(b"HTTP/1.1 200 OK\r\nContent-Length: 2").unwrap(); + assert!( + ordinary + .replace(205, vec![("Content-Length".into(), "2".into())]) + .is_err() + ); + ordinary + .replace(205, vec![("Content-Length".into(), "0".into())]) + .unwrap(); + assert_eq!(ordinary.body("GET"), Body::Empty); + let cached = + ResponseHead::parse(b"HTTP/1.1 304 Not Modified\r\nContent-Length: 20").unwrap(); + assert_eq!(cached.body("GET"), Body::Empty); + assert!( + cached + .encode(false, false, false) + .windows(18) + .any(|w| w == b"Content-Length: 20") + ); + } use super::*; use tokio::io::BufReader; diff --git a/src/inbound/http/server.rs b/src/inbound/http/server.rs index 1099437..4a87b08 100644 --- a/src/inbound/http/server.rs +++ b/src/inbound/http/server.rs @@ -243,6 +243,10 @@ where { let (mut deadline, cancellation) = scope; let http = dispatcher.http_context(); + // HTTP processing and transparent fallback retain the same routing/DNS + // generation, including requests outside the configured processing ports. + let dispatcher = http.as_ref().map_or(dispatcher, |http| http.dispatcher()); + let mut upstream = None; loop { let request = timeout_at(deadline, async { if reader.fill_buf().await?.is_empty() { @@ -285,10 +289,15 @@ where let forward = if request.is_connect() { framing::validate_connect(&request) .and_then(|()| request.connect_destination().map(|target| (target, None))) - } else if http.is_some() { - request - .forward_target() - .map(|(destination, _)| (destination, None)) + } else if let Some(http) = &http { + request.forward_target().and_then(|(destination, origin)| { + if http.plain_port(destination.port()) { + Ok((destination, None)) + } else { + RequestPlan::for_target(&request, destination, origin, false) + .map(|plan| (plan.destination.clone(), Some(plan))) + } + }) } else { RequestPlan::new(&request).map(|plan| (plan.destination.clone(), Some(plan))) }; @@ -315,8 +324,13 @@ where destination, sniffed_domain: None, }; + // CONNECT takes ownership of this downstream for its whole tunnel + // lifetime. Its previous ordinary HTTP slot must not live alongside it. + if request.is_connect() { + drop(upstream.take()); + } if let Some(http) = &http { - if !request.is_connect() { + if !request.is_connect() && http.plain_port(session.destination.port()) { if !http .forward_h1( reader, @@ -324,7 +338,8 @@ where &request, session, crate::http_processing::Scheme::Http, - config, + (config, cancellation), + &mut upstream, ) .await? { @@ -333,7 +348,7 @@ where deadline = Instant::now() + config.header_timeout; continue; } - if http.candidate_port(session.destination.port()) { + if request.is_connect() && http.candidate_port(session.destination.port()) { write_timed( writer, b"HTTP/1.1 200 Connection Established\r\n\r\n", @@ -365,8 +380,10 @@ where }; } } + // A request that leaves the processing path must retire its previous + // processed upstream before connecting through ordinary forwarding. + drop(upstream.take()); if request.is_connect() { - let dispatcher = http.as_ref().map_or(dispatcher, |http| http.dispatcher()); return forward_tunnel( reader, writer, @@ -495,16 +512,99 @@ pub(crate) async fn forward_processed>, + write: tokio::io::WriteHalf, +} +impl UpstreamIo { + pub(crate) fn new(stream: BoxStream) -> Self { + let (read, write) = tokio::io::split(stream); + Self { + read: BufReader::with_capacity(framing::COPY_BUFFER, read), + write, + } + } + // One nonblocking buffered poll, before sending any new request bytes. + // EOF/error/unsolicited bytes retire the owner, never trigger HTTP replay. + pub(crate) async fn idle_healthy(&mut self) -> bool { + std::future::poll_fn(|cx| { + use std::{pin::Pin, task::Poll}; + match tokio::io::AsyncBufRead::poll_fill_buf(Pin::new(&mut self.read), cx) { + Poll::Pending => Poll::Ready(true), + Poll::Ready(_) => Poll::Ready(false), + } + }) + .await + } +} +pub(crate) struct UpstreamSlot { + pub(crate) authority: String, + pub(crate) key: crate::dispatch::HttpTcpReuseKey, + pub(crate) io: UpstreamIo, +} +pub(crate) struct ForwardOutcome { + pub(crate) downstream_keep_alive: bool, + pub(crate) upstream_reusable: bool, +} + #[allow(clippy::too_many_arguments)] async fn forward_request_inner( reader: &mut R, writer: &mut W, - mut outbound: BoxStream, + outbound: BoxStream, + request: &RequestHead, + plan: RequestPlan, + config: &HttpServerConfig, + processing: Option<&crate::http_processing::h1_body::Message<'_>>, +) -> io::Result { + let mut upstream = UpstreamIo::new(outbound); + forward_on_stream( + reader, + writer, + &mut upstream, + request, + plan, + config, + processing, + false, + ) + .await + .map(|outcome| outcome.downstream_keep_alive) +} +#[allow(clippy::too_many_arguments)] +pub(crate) async fn forward_processed_reusable( + reader: &mut R, + writer: &mut W, + upstream: &mut UpstreamIo, + request: &RequestHead, + plan: RequestPlan, + config: &HttpServerConfig, + processing: &crate::http_processing::h1_body::Message<'_>, +) -> io::Result { + forward_on_stream( + reader, + writer, + upstream, + request, + plan, + config, + Some(processing), + true, + ) + .await +} + +#[allow(clippy::too_many_arguments)] +async fn forward_on_stream( + reader: &mut R, + writer: &mut W, + upstream: &mut UpstreamIo, request: &RequestHead, mut plan: RequestPlan, config: &HttpServerConfig, processing: Option<&crate::http_processing::h1_body::Message<'_>>, -) -> io::Result { + enable_reuse: bool, +) -> io::Result { let upload = match processing { Some(processing) => { processing @@ -513,18 +613,33 @@ async fn forward_request_inner( } None => crate::http_processing::h1_body::PreparedBody::original(plan.body), }; - write_timed(&mut outbound, &plan.head, config.connect_timeout).await?; + // Processing may rebuild request framing. Persistence is enabled only now. + let origin_requested = enable_reuse + && !matches!(request.method.as_str(), "HEAD" | "CONNECT") + && plan.keep_alive + && plan.upgrade.is_empty() + && matches!(plan.body, Body::Empty | Body::Length(_)) + && !request + .headers + .iter() + .any(|(n, _)| n.eq_ignore_ascii_case("expect")); + if origin_requested { + plan.enable_origin_persistence()?; + } + let mut remote_read = &mut upstream.read; + let mut remote_write = &mut upstream.write; + write_timed(&mut remote_write, &plan.head, config.connect_timeout).await?; // Some protocol transports accept the head into an internal frame. Empty // requests never poll the body sender, so publish the head before reading. - timeout_io(config.connect_timeout, outbound.flush()).await?; - let (remote_read, mut remote_write) = tokio::io::split(outbound); - let mut remote_read = BufReader::with_capacity(framing::COPY_BUFFER, remote_read); - let mut uploading = Box::pin(upload.transfer( + timeout_io(config.connect_timeout, remote_write.flush()).await?; + let final_flush_only = std::sync::atomic::AtomicBool::new(false); + let mut uploading = Box::pin(upload.transfer_observing_final_flush( reader, &mut remote_write, config.body_idle_timeout, &plan.trailer_blocklist, false, + &final_flush_only, )); // Empty bodies are already complete. Reading a ready 101 first must not // turn an otherwise valid Upgrade into an apparent early response. @@ -612,8 +727,24 @@ async fn forward_request_inner( } break response; }; - // An early final response cancels the upload and closes this client - // connection. Unread request bytes can never become a second request. + if !uploaded + && origin_requested + && response.status >= 200 + && final_flush_only.load(std::sync::atomic::Ordering::Acquire) + { + // The real body transfer has reached its final flush. Recheck that same + // future once in case response-first selection hid an already-ready + // completion. Never await Pending or read/write another body byte. + let result = std::future::poll_fn(|cx| { + std::task::Poll::Ready(std::future::Future::poll(uploading.as_mut(), cx)) + }) + .await; + if matches!(result, std::task::Poll::Ready(Ok(()))) { + uploaded = true; + } + } + // Genuine early/Pending/error final responses keep the original close path. + // Unread request bytes can never become a second request. drop(uploading); if response.status == 101 { if !uploaded || !response.valid_upgrade(&plan.upgrade).unwrap_or(false) { @@ -634,8 +765,12 @@ async fn forward_request_inner( .await?; timeout_io(config.header_timeout, writer.flush()).await?; relay(reader, writer, &mut remote_read, &mut remote_write).await?; - return Ok(false); + return Ok(ForwardOutcome { + downstream_keep_alive: false, + upstream_reusable: false, + }); } + let origin_reusable = origin_requested && response.origin_reusable(&request.method); let body = response.body(&request.method); let download = match processing { Some(processing) => { @@ -654,8 +789,8 @@ async fn forward_request_inner( config.header_timeout, ) .await?; - download - .transfer( + let consumed = download + .transfer_with_origin( &mut remote_read, writer, config.body_idle_timeout, @@ -663,7 +798,13 @@ async fn forward_request_inner( dechunk, ) .await?; - Ok(keep_alive) + Ok(ForwardOutcome { + downstream_keep_alive: keep_alive, + upstream_reusable: keep_alive + && origin_reusable + && consumed + && remote_read.buffer().is_empty(), + }) } async fn relay( @@ -1477,3 +1618,13 @@ mod response_deadline_memory_tests { } } } + +#[cfg(test)] +mod upstream_memory_tests { + include!("upstream_memory_tests.rs"); +} + +#[cfg(test)] +mod final_flush_repoll_memory_tests { + include!("final_flush_repoll_memory_tests.rs"); +} diff --git a/src/inbound/http/upstream_connect_memory_tests.rs b/src/inbound/http/upstream_connect_memory_tests.rs new file mode 100644 index 0000000..32471e1 --- /dev/null +++ b/src/inbound/http/upstream_connect_memory_tests.rs @@ -0,0 +1,237 @@ +// Mixed CONNECT interception and final HTTPS target exclusions use memory streams. +struct ConnectMemoryRecordingLeaf { + origin: Arc, + sessions: Arc>>, +} + +#[async_trait] +impl Dispatcher for ConnectMemoryRecordingLeaf { + fn permits_http_tcp_reuse(&self) -> bool { + self.origin.permits_http_tcp_reuse() + } + + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.sessions.lock().unwrap().push(session.clone()); + self.origin.connect_tcp(session).await + } + + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +async fn connect_memory_read_response( + client: &mut BufReader, +) -> io::Result<(Vec, Vec)> { + let head = framing::read_head(client, 32768).await?; + let response = framing::ResponseHead::parse(&head)?; + let mut body = Vec::new(); + framing::transfer_body( + client, + &mut body, + response.body("GET"), + Duration::from_secs(1), + response.trailer_blocklist(), + true, + ) + .await?; + Ok((head, body)) +} + +#[tokio::test] +async fn upstream_reuse_connect_http_port_intercepts_two_gets_on_one_origin_and_joins() { + let origin = MemoryOrigin::new(Reply::Persistent); + let sessions = Arc::new(Mutex::new(Vec::new())); + let leaf: Arc = Arc::new(ConnectMemoryRecordingLeaf { + origin: origin.clone(), + sessions: sessions.clone(), + }); + // A wrong HTTP/TUN identity fails routing on either request. The second + // request must therefore retain CONNECT's HTTPS identity when preparing + // its own route, as well as using the physical stream opened by the first. + let config = crate::config::Config::parse_yaml( + b"rules: ['IN-TYPE,HTTPS,DIRECT', 'MATCH,REJECT']\n", + ) + .unwrap(); + let router = Arc::new(RoutingDispatcher::new( + ProxyDispatchers::new(Vec::new()).unwrap(), + leaf, + None, + RuleSet::compile(config.rules).unwrap(), + Arc::new(EmptyGeoMatcher), + )); + let stats = crate::resources::RuntimeResourceStats::new("http_connect_inner_h1_memory"); + let observed = observe_sessions_with_stats( + observe_handshakes_with_stats(router.clone(), stats.clone()), + stats.clone(), + ); + let context = HttpContext::new( + Policy::compile( + "http-ports: [80]\nrewrite:\n enabled: true\n rules:\n - {url: '.', action: response-header-set, header: X-Connect-Proof, value: intercepted}\n", + ) + .unwrap(), + observed, + SecurityContext::new(), + ); + let dispatcher: Arc = Arc::new(MixedEntry { context, router }); + let cancel = CancellationToken::new(); + let serving_cancel = cancel.clone(); + let (client, stream) = tokio::io::duplex(8192); + let task = tokio::spawn(async move { + let (read, mut write) = tokio::io::split(stream); + let mut reader = BufReader::new(read); + let config = HttpServerConfig::processing(); + serve_requests( + &mut reader, + &mut write, + "127.0.0.1:12345".parse().unwrap(), + "127.0.0.1:1080".parse().unwrap(), + &dispatcher, + &config, + ( + Instant::now() + Duration::from_secs(10), + &serving_cancel, + ), + ) + .await + }); + let mut client = BufReader::new(client); + // Capture all assertions until after cleanup. Even the baseline's two + // accepts, a bad response, or a timeout must not abandon serving/peer tasks. + let exchange = tokio::time::timeout(Duration::from_secs(3), async { + client + .get_mut() + .write_all(b"CONNECT 203.0.113.1:80 HTTP/1.1\r\nHost: 203.0.113.1:80\r\n\r\n") + .await?; + let connect_head = framing::read_head(&mut client, 32768).await?; + let mut responses = Vec::new(); + for path in ["one", "two"] { + client + .get_mut() + .write_all( + format!("GET /{path} HTTP/1.1\r\nHost: 203.0.113.1\r\n\r\n").as_bytes(), + ) + .await?; + responses.push(connect_memory_read_response(&mut client).await?); + } + Ok::<_, io::Error>((connect_head, responses)) + }) + .await; + let opened = origin.opened.load(Ordering::SeqCst); + let active = stats.snapshot(); + let heads = origin.heads.lock().unwrap().clone(); + let bodies = origin.bodies.lock().unwrap().clone(); + let recorded_sessions = sessions.lock().unwrap().clone(); + + // Keep the downstream open while Stop is joined: downstream EOF must not + // accidentally supply the only reason the cached origin owner is released. + cancel.cancel(); + let serving = joined(task).await; + origin.join().await; + drop(client); + + serving.unwrap().unwrap(); + let (connect_head, responses) = exchange.unwrap().unwrap(); + assert!(connect_head.starts_with(b"HTTP/1.1 200 Connection Established")); + assert_eq!(opened, 1, "two inner H1 requests must share one physical accept"); + assert_eq!(heads.len(), 2, "the origin must receive both real request heads"); + assert!(heads[0].starts_with("GET /one HTTP/1.1\r\n")); + assert!(heads[1].starts_with("GET /two HTTP/1.1\r\n")); + assert!(heads.iter().all(|head| head.to_ascii_lowercase().contains("connection: keep-alive"))); + assert_eq!(bodies, vec![Vec::::new(), Vec::::new()]); + assert_eq!(responses.len(), 2); + for (head, body) in responses { + assert!(head.starts_with(b"HTTP/1.1 200")); + assert!(String::from_utf8(head).unwrap().to_ascii_lowercase().contains("x-connect-proof: intercepted"), + "a raw CONNECT relay would miss the real HTTP-processing marker"); + assert_eq!(body, b"ok"); + } + assert_eq!(recorded_sessions.len(), 1); + assert_eq!(recorded_sessions[0].inbound, InboundKind::Https); + assert_eq!(recorded_sessions[0].metadata.local_port, 1080); + assert_eq!(recorded_sessions[0].destination, Destination::Ip("203.0.113.1:80".parse().unwrap())); + assert_eq!(active.tcp_current, 1); + assert_eq!(active.handshake_current, 0); + assert_eq!(stats.snapshot().tcp_current, 0); + assert_eq!(stats.snapshot().handshake_current, 0); + assert_eq!(origin.live.load(Ordering::SeqCst), 0); +} + +#[derive(Default)] +struct FinalHttpsNoReuseProbe { + prepares: AtomicUsize, + connects: AtomicUsize, + destinations: Mutex>, +} + +#[async_trait] +impl Dispatcher for FinalHttpsNoReuseProbe { + fn permits_http_tcp_reuse(&self) -> bool { + true + } + + async fn prepare_http_tcp( + &self, + _: StreamSession, + ) -> Result>, DispatchError> { + self.prepares.fetch_add(1, Ordering::SeqCst); + Err(DispatchError::NotAllowed) + } + + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.connects.fetch_add(1, Ordering::SeqCst); + self.destinations.lock().unwrap().push(session.destination); + // Deliberately stop before TLS construction or IO. No certificates, + // private keys, socket, TLS peer, or synthetic TLS success is involved. + Err(DispatchError::NotAllowed) + } + + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +#[tokio::test] +async fn upstream_reuse_final_https_target_never_prepares_a_reuse_plan_without_tls_io() { + let probe = Arc::new(FinalHttpsNoReuseProbe::default()); + let context = HttpContext::new( + Policy::compile( + "http-ports: [80]\nrewrite:\n enabled: true\n rules:\n - {url: '.', action: replace, replacement-mode: url, replacement: 'https://203.0.113.1/final'}\n", + ) + .unwrap(), + probe.clone(), + SecurityContext::new(), + ); + let (client, mut stream) = tokio::io::duplex(8192); + let task = tokio::spawn(async move { + context + .try_intercept(&mut stream, ingress(), CancellationToken::new()) + .await + }); + let mut client = client; + let exchange = tokio::time::timeout(Duration::from_secs(1), async { + client + .write_all(b"GET /secure HTTP/1.1\r\nHost: 203.0.113.1\r\n\r\n") + .await?; + let mut response = Vec::new(); + client.read_to_end(&mut response).await?; + Ok::<_, io::Error>(response) + }) + .await; + let serving = joined(task).await; + drop(client); + + exchange.unwrap().unwrap(); + assert!(serving.unwrap().is_err(), "the deliberate pre-TLS connect failure must remain a failure"); + assert_eq!(probe.prepares.load(Ordering::SeqCst), 0, + "an HTTPS final target must stay out of the HTTP reuse-plan path"); + assert_eq!(probe.connects.load(Ordering::SeqCst), 1); + assert_eq!(*probe.destinations.lock().unwrap(), + vec![Destination::Ip("203.0.113.1:443".parse().unwrap())]); +} diff --git a/src/inbound/http/upstream_memory_tests.rs b/src/inbound/http/upstream_memory_tests.rs new file mode 100644 index 0000000..ef6548a --- /dev/null +++ b/src/inbound/http/upstream_memory_tests.rs @@ -0,0 +1,538 @@ +// Real in-memory origins and the production routing/HTTP loops; no sockets. +include!("upstream_connect_memory_tests.rs"); +use super::*; +use crate::{ + dispatch::{DatagramTransport, observe_handshakes_with_stats, observe_sessions_with_stats}, + http_processing::{HttpContext, Intercept, Policy}, + routing::{EmptyGeoMatcher, GeoMatcher, ProxyDispatchers, RoutingDispatcher, RuleSet}, + security::SecurityContext, + session::{DatagramSession, Destination}, +}; +use async_trait::async_trait; +use std::{ + pin::Pin, + sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, + }, + task::{Context, Poll}, +}; +use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, ReadBuf}; + +#[derive(Clone, Copy)] +enum Reply { + Persistent, + Close, + Http10, + Extra, + Chunked, + Trailer, + ContentRange, + BadLength, + Truncated, + FailSecond, + Pending, +} +struct MemoryOrigin { + reply: Reply, + opened: AtomicUsize, + live: Arc, + heads: Arc>>, + bodies: Arc>>>, + tasks: Mutex>>, + partial: Arc, +} +struct OwnedMemoryStream { + io: tokio::io::DuplexStream, + live: Arc, +} +impl Drop for OwnedMemoryStream { + fn drop(&mut self) { + self.live.fetch_sub(1, Ordering::SeqCst); + } +} +impl AsyncRead for OwnedMemoryStream { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + b: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.io).poll_read(cx, b) + } +} +impl AsyncWrite for OwnedMemoryStream { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + b: &[u8], + ) -> Poll> { + Pin::new(&mut self.io).poll_write(cx, b) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } +} +async fn joined(mut task: tokio::task::JoinHandle) -> Result { + match tokio::time::timeout(Duration::from_secs(1), &mut task).await { + Ok(Ok(value)) => Ok(value), + Ok(Err(error)) => Err(error.to_string()), + Err(_) => { + task.abort(); + let _ = task.await; + Err("memory peer did not join".into()) + } + } +} +impl MemoryOrigin { + fn new(reply: Reply) -> Arc { + Arc::new(Self { + reply, + opened: AtomicUsize::new(0), + live: Arc::new(AtomicUsize::new(0)), + heads: Arc::default(), + bodies: Arc::default(), + tasks: Mutex::new(Vec::new()), + partial: Arc::new(tokio::sync::Notify::new()), + }) + } + async fn join(&self) { + let tasks = std::mem::take(&mut *self.tasks.lock().unwrap()); + let mut failure = None; + for task in tasks { + if let Err(error) = joined(task).await { + failure = Some(error); + } + } + assert_eq!(self.live.load(Ordering::SeqCst), 0); + assert!(failure.is_none(), "{failure:?}"); + } +} +#[async_trait] +impl Dispatcher for MemoryOrigin { + fn permits_http_tcp_reuse(&self) -> bool { + true + } + async fn connect_tcp(&self, _: StreamSession) -> Result { + self.opened.fetch_add(1, Ordering::SeqCst); + self.live.fetch_add(1, Ordering::SeqCst); + let (client, server) = tokio::io::duplex(8192); + let (reply, heads, bodies, partial) = ( + self.reply, + self.heads.clone(), + self.bodies.clone(), + self.partial.clone(), + ); + self.tasks.lock().unwrap().push(tokio::spawn(async move { + let mut server = BufReader::new(server); + let mut sequence=0; + loop { + let bytes = match framing::read_head(&mut server,32768).await { Ok(b)=>b, Err(_)=>break }; + let text=String::from_utf8(bytes.clone()).unwrap(); + let request=crate::inbound::http::parser::parse_request_head(&bytes,Vec::new()).unwrap(); + let plan=framing::RequestPlan::for_target(&request,Destination::Ip("203.0.113.1:80".parse().unwrap()),"/".into(),false).unwrap(); + let mut body=Vec::new(); + framing::transfer_body(&mut server,&mut body,plan.body,Duration::from_secs(1),&plan.trailer_blocklist,true).await.unwrap(); + heads.lock().unwrap().push(text.clone()); bodies.lock().unwrap().push(body); sequence+=1; + if matches!(reply,Reply::FailSecond) && sequence==2 { break; } + let wire: &[u8] = match reply { + Reply::Close => b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok", + Reply::Http10 => b"HTTP/1.0 200 OK\r\nContent-Length: 2\r\n\r\nok", + Reply::Extra => b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nokunsolicited", + Reply::Chunked => b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nok\r\n0\r\n\r\n", + Reply::Trailer => b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\nTrailer: X-Safe\r\n\r\n2\r\nok\r\n0\r\nX-Safe: v\r\n\r\n", + Reply::ContentRange => b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Range: bytes 0-1/4\r\n\r\nok", + Reply::BadLength => b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\nContent-Length: 3\r\n\r\nok", + Reply::Truncated|Reply::Pending => b"HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nok", + _ => b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok", + }; + if server.get_mut().write_all(wire).await.is_err() { break; } + if matches!(reply,Reply::Pending) { partial.notify_one(); } + if matches!(reply,Reply::Truncated) { break; } + if text.to_ascii_lowercase().contains("connection: close") || matches!(reply,Reply::Close|Reply::Http10) { break; } + } + })); + Ok(Box::new(OwnedMemoryStream { + io: client, + live: self.live.clone(), + })) + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +fn ingress() -> StreamSession { + StreamSession { + metadata: crate::session::InboundMetadata::new(80), + inbound: InboundKind::Tun, + source: "198.18.0.2:12345".parse().unwrap(), + destination: Destination::Ip("203.0.113.1:80".parse().unwrap()), + sniffed_domain: Some("origin.invalid".into()), + } +} +fn router(origin: Arc, geo: Arc) -> Arc { + let config = + crate::config::Config::parse_yaml(b"rules: [\"GEOSITE,flip,REJECT\",\"MATCH,DIRECT\"]\n") + .unwrap(); + Arc::new(RoutingDispatcher::new( + ProxyDispatchers::new(Vec::new()).unwrap(), + origin, + None, + RuleSet::compile(config.rules).unwrap(), + geo, + )) +} +fn context( + origin: Arc, + geo: Arc, + extra: &str, +) -> (HttpContext, crate::resources::RuntimeResourceStats) { + let stats = crate::resources::RuntimeResourceStats::new("http_upstream_reuse_memory_test"); + let dispatcher = observe_sessions_with_stats( + observe_handshakes_with_stats(router(origin, geo), stats.clone()), + stats.clone(), + ); + let policy=Policy::compile(&format!("http-ports: [80]\nrewrite:\n enabled: true\n rules:\n - {{url: '.', action: response-header-set, header: X-Test, value: value}}\n{extra}")).unwrap(); + ( + HttpContext::new(policy, dispatcher, SecurityContext::new()), + stats, + ) +} +async fn read_response(client: &mut BufReader) -> io::Result> { + let head = framing::read_head(client, 32768).await?; + let response = framing::ResponseHead::parse(&head)?; + let mut body = Vec::new(); + framing::transfer_body( + client, + &mut body, + response.body("GET"), + Duration::from_secs(1), + response.trailer_blocklist(), + true, + ) + .await?; + Ok(body) +} +async fn send(client: &mut BufReader, path: &str) { + client.get_mut().write_all(format!("GET /{path} HTTP/1.1\r\nHost: origin.invalid\r\nContent-Type: text/plain; charset=utf-8\r\n\r\n").as_bytes()).await.unwrap(); +} +fn start( + context: HttpContext, + cancel: CancellationToken, +) -> ( + BufReader, + tokio::task::JoinHandle>, +) { + let (client, mut stream) = tokio::io::duplex(8192); + let task = + tokio::spawn(async move { context.try_intercept(&mut stream, ingress(), cancel).await }); + (BufReader::new(client), task) +} +async fn end( + mut client: BufReader, + task: tokio::task::JoinHandle>, + origin: &MemoryOrigin, +) { + client.get_mut().shutdown().await.unwrap(); + let result = joined(task).await; + origin.join().await; + result.unwrap().unwrap(); +} + +#[tokio::test] +async fn upstream_reuse_two_real_requests_one_connection_and_stop_releases_owners() { + let origin = MemoryOrigin::new(Reply::Persistent); + let (context, stats) = context(origin.clone(), Arc::new(EmptyGeoMatcher), ""); + let (mut client, task) = start(context, CancellationToken::new()); + for path in ["one", "two"] { + send(&mut client, path).await; + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + } + let opened = origin.opened.load(Ordering::SeqCst); + let active = stats.snapshot(); + let heads = origin.heads.lock().unwrap().len(); + end(client, task, &origin).await; + assert_eq!(opened, 1); + assert_eq!(active.tcp_current, 1); + assert_eq!(active.handshake_current, 0); + assert_eq!(heads, 2); + assert_eq!(stats.snapshot().tcp_current, 0); +} +#[tokio::test] +async fn upstream_reuse_original_wire_close_version_extra_and_chunks_retire() { + for reply in [ + Reply::Close, + Reply::Http10, + Reply::Extra, + Reply::Chunked, + Reply::Trailer, + Reply::ContentRange, + ] { + let origin = MemoryOrigin::new(reply); + let (context, _) = context(origin.clone(), Arc::new(EmptyGeoMatcher), ""); + let (mut client, task) = start(context, CancellationToken::new()); + for path in ["one", "two"] { + send(&mut client, path).await; + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + } + assert_eq!(origin.opened.load(Ordering::SeqCst), 2); + end(client, task, &origin).await; + } +} +#[tokio::test] +async fn upstream_reuse_truncated_body_remains_error_and_is_never_replayed() { + let origin = MemoryOrigin::new(Reply::Truncated); + let (context, _) = context(origin.clone(), Arc::new(EmptyGeoMatcher), ""); + let (mut client, task) = start(context, CancellationToken::new()); + send(&mut client, "one").await; + assert!(read_response(&mut client).await.is_err()); + assert!(joined(task).await.unwrap().is_err()); + origin.join().await; + assert_eq!(origin.opened.load(Ordering::SeqCst), 1); + assert_eq!(origin.heads.lock().unwrap().len(), 1); +} +#[tokio::test] +async fn upstream_reuse_sent_second_request_failure_does_not_reconnect_or_replay() { + let origin = MemoryOrigin::new(Reply::FailSecond); + let (context, _) = context(origin.clone(), Arc::new(EmptyGeoMatcher), ""); + let (mut client, task) = start(context, CancellationToken::new()); + send(&mut client, "one").await; + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + send(&mut client, "two").await; + // The ordinary error may be rendered as a local empty 502, then the owner fails. + let _ = read_response(&mut client).await; + assert!(joined(task).await.unwrap().is_err()); + origin.join().await; + assert_eq!(origin.opened.load(Ordering::SeqCst), 1); + assert_eq!(origin.heads.lock().unwrap().len(), 2); +} +#[derive(Default)] +struct FlipGeo(AtomicUsize); +impl GeoMatcher for FlipGeo { + fn matches_geosite(&self, _: &str, _: &str) -> bool { + self.0.fetch_add(1, Ordering::SeqCst) > 0 + } + fn matches_geoip(&self, _: &str, _: std::net::IpAddr) -> bool { + false + } +} +#[tokio::test] +async fn upstream_reuse_new_request_rechecks_reject_before_using_cached_stream() { + let origin = MemoryOrigin::new(Reply::Persistent); + let geo = Arc::new(FlipGeo::default()); + let (context, _) = context(origin.clone(), geo.clone(), ""); + let (mut client, task) = start(context, CancellationToken::new()); + send(&mut client, "one").await; + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + send(&mut client, "two").await; + let _ = read_response(&mut client).await; + assert!(joined(task).await.unwrap().is_err()); + origin.join().await; + assert_eq!(geo.0.load(Ordering::SeqCst), 2); + assert_eq!(origin.opened.load(Ordering::SeqCst), 1); + assert_eq!(origin.heads.lock().unwrap().len(), 1); +} +#[tokio::test] +async fn upstream_reuse_idle_and_partial_response_cancellation_drop_actual_streams() { + for reply in [Reply::Persistent, Reply::Pending] { + let origin = MemoryOrigin::new(reply); + let cancel = CancellationToken::new(); + let (context, stats) = context(origin.clone(), Arc::new(EmptyGeoMatcher), ""); + let (mut client, task) = start(context, cancel.clone()); + send(&mut client, "one").await; + if matches!(reply, Reply::Pending) { + origin.partial.notified().await; + } else { + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + } + cancel.cancel(); + joined(task).await.unwrap().unwrap(); + origin.join().await; + assert_eq!(stats.snapshot().tcp_current, 0); + assert_eq!(stats.snapshot().handshake_current, 0); + } +} + +#[tokio::test] +async fn upstream_reuse_same_ip_different_authority_never_coalesces() { + let origin = MemoryOrigin::new(Reply::Persistent); + let (context, _) = context(origin.clone(), Arc::new(EmptyGeoMatcher), ""); + let (mut client, task) = start(context, CancellationToken::new()); + send(&mut client, "one").await; + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + client + .get_mut() + .write_all(b"GET /two HTTP/1.1\r\nHost: other.invalid\r\n\r\n") + .await + .unwrap(); + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + assert_eq!(origin.opened.load(Ordering::SeqCst), 2); + end(client, task, &origin).await; +} +#[tokio::test] +async fn upstream_reuse_native_request_body_set_reuses_after_complete_upload() { + let origin = MemoryOrigin::new(Reply::Persistent); + let (context, _) = context( + origin.clone(), + Arc::new(EmptyGeoMatcher), + " - {url: '.', action: request-body-set, value: x}\n", + ); + let (mut client, task) = start(context, CancellationToken::new()); + for path in ["one", "two"] { + send(&mut client, path).await; + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + } + end(client, task, &origin).await; + assert_eq!(origin.opened.load(Ordering::SeqCst), 1); + assert_eq!( + *origin.bodies.lock().unwrap(), + vec![b"x".to_vec(), b"x".to_vec()] + ); + assert!( + origin + .heads + .lock() + .unwrap() + .iter() + .all(|h| h.to_ascii_lowercase().contains("connection: keep-alive")) + ); +} +#[tokio::test] +async fn upstream_reuse_ambiguous_upstream_framing_remains_failure() { + let origin = MemoryOrigin::new(Reply::BadLength); + let (context, _) = context(origin.clone(), Arc::new(EmptyGeoMatcher), ""); + let (mut client, task) = start(context, CancellationToken::new()); + send(&mut client, "one").await; + let _ = read_response(&mut client).await; + assert!(joined(task).await.unwrap().is_err()); + origin.join().await; + assert_eq!(origin.opened.load(Ordering::SeqCst), 1); +} +struct OpaqueDirect(Arc); +#[async_trait] +impl Dispatcher for OpaqueDirect { + async fn connect_tcp(&self, s: StreamSession) -> Result { + self.0.connect_tcp(s).await + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +#[tokio::test] +async fn upstream_reuse_route_named_direct_is_insufficient_without_physical_proof() { + let origin = MemoryOrigin::new(Reply::Persistent); + let opaque = Arc::new(OpaqueDirect(origin.clone())); + let context=HttpContext::new(Policy::compile("http-ports: [80]\nrewrite: {enabled: true, rules: [{url: '.', action: response-header-set, header: X-Test, value: value}]}\n").unwrap(),router(opaque,Arc::new(EmptyGeoMatcher)),SecurityContext::new()); + let (mut client, task) = start(context, CancellationToken::new()); + for path in ["one", "two"] { + send(&mut client, path).await; + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + } + assert_eq!(origin.opened.load(Ordering::SeqCst), 2); + end(client, task, &origin).await; +} +#[test] +fn upstream_reuse_builtin_direct_rejects_mutable_or_special_egress() { + let dialer = crate::dialer::Dialer::default(); + let plain = crate::outbound::DirectOutbound::new(dialer.clone()); + assert!(plain.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + assert!(!plain.permits_http_tcp_reuse()); + let mptcp = + crate::outbound::DirectOutbound::new(crate::dialer::Dialer::default().with_mptcp(true)); + assert_eq!(mptcp.permits_http_tcp_reuse(), cfg!(target_os = "macos")); +} +#[tokio::test] +async fn upstream_reuse_collected_rewritten_body_proves_original_wire_completion() { + let origin = MemoryOrigin::new(Reply::Persistent); + let (context, _) = context( + origin.clone(), + Arc::new(EmptyGeoMatcher), + " - {url: '.', action: response-body-set, value: changed}\n", + ); + let (mut client, task) = start(context, CancellationToken::new()); + for path in ["one", "two"] { + send(&mut client, path).await; + assert_eq!(read_response(&mut client).await.unwrap(), b"changed"); + } + let opened = origin.opened.load(Ordering::SeqCst); + end(client, task, &origin).await; + assert_eq!(opened, 1); +} + +struct MixedEntry { + context: HttpContext, + router: Arc, +} +#[async_trait] +impl Dispatcher for MixedEntry { + fn http_context(&self) -> Option { + Some(self.context.clone()) + } + async fn connect_tcp(&self, s: StreamSession) -> Result { + self.router.connect_tcp(s).await + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +#[tokio::test] +async fn upstream_reuse_mixed_connect_releases_the_old_slot_before_tunnel() { + let origin = MemoryOrigin::new(Reply::Persistent); + let router = router(origin.clone(), Arc::new(EmptyGeoMatcher)); + let context=HttpContext::new(Policy::compile("http-ports: [80]\nrewrite: {enabled: true, rules: [{url: '.', action: response-header-set, header: X-Test, value: value}]}\n").unwrap(),router.clone(),SecurityContext::new()); + let dispatcher: Arc = Arc::new(MixedEntry { context, router }); + let (client, stream) = tokio::io::duplex(8192); + let task = tokio::spawn(async move { + let (read, mut write) = tokio::io::split(stream); + let mut reader = BufReader::new(read); + let config = HttpServerConfig::processing(); + serve_requests( + &mut reader, + &mut write, + "127.0.0.1:12345".parse().unwrap(), + "127.0.0.1:8080".parse().unwrap(), + &dispatcher, + &config, + ( + Instant::now() + Duration::from_secs(10), + &CancellationToken::new(), + ), + ) + .await + }); + let mut client = BufReader::new(client); + client + .get_mut() + .write_all(b"GET http://203.0.113.1/one HTTP/1.1\r\nHost: 203.0.113.1\r\n\r\n") + .await + .unwrap(); + assert_eq!(read_response(&mut client).await.unwrap(), b"ok"); + assert_eq!(origin.opened.load(Ordering::SeqCst), 1); + client + .get_mut() + .write_all(b"CONNECT 203.0.113.1:443 HTTP/1.1\r\nHost: 203.0.113.1:443\r\n\r\n") + .await + .unwrap(); + let head = framing::read_head(&mut client, 32768).await.unwrap(); + let during = origin.live.load(Ordering::SeqCst); + let opened = origin.opened.load(Ordering::SeqCst); + client.get_mut().shutdown().await.unwrap(); + let result = joined(task).await; + origin.join().await; + result.unwrap().unwrap(); + assert!(head.starts_with(b"HTTP/1.1 200")); + assert_eq!(opened, 2); + assert_eq!(during, 1); +} diff --git a/src/inbound/socks5/http_processing_memory_tests.rs b/src/inbound/socks5/http_processing_memory_tests.rs new file mode 100644 index 0000000..0f21b5e --- /dev/null +++ b/src/inbound/socks5/http_processing_memory_tests.rs @@ -0,0 +1,664 @@ +//! Real SOCKS5 handshakes, HTTP framing and TLS over duplex IO; no sockets. +//! Filter: inbound::socks5::server::http_processing_memory_tests:: +use super::Socks5Handler; +use crate::{ + config::{ProxyAccess, ProxyCredentials, Socks5InboundConfig}, + dispatch::{BoxStream, DatagramTransport, DispatchError, Dispatcher}, + http_processing::{HttpContext, Policy, config::Document, private_context::test_material}, + inbound::http::{framing, parser}, + security::SecurityContext, + session::{DatagramSession, Destination, InboundKind, StreamSession}, +}; +use async_trait::async_trait; +use rustls::pki_types::{CertificateDer, PrivatePkcs8KeyDer, ServerName, pem::PemObject}; +use std::{ + io, + sync::{ + Arc, Mutex, + atomic::{AtomicUsize, Ordering}, + }, + time::Duration, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, DuplexStream}, + task::JoinHandle, + time::{Instant, timeout}, +}; +use tokio_util::sync::CancellationToken; + +const WAIT: Duration = Duration::from_secs(5); +const REQUEST: &[u8] = b"POST /path HTTP/1.1\r\nHost: target.test\r\nContent-Type: text/plain\r\nContent-Length: 3\r\nConnection: close\r\n\r\nold"; +const NATIVE: &str = r#" +http-ports: [80] +rewrite: + enabled: true + rules: + - {url: '.', action: request-header-set, header: X-Request-Native, value: yes} + - {url: '.', action: request-body-set, value: native-request} + - {url: '.', action: response-header-set, header: X-Response-Native, value: yes} + - {url: '.', action: response-body-set, value: native-response} +"#; + +#[derive(Clone)] +enum PeerMode { + Http, + Echo, + SniffingEcho, + BufferedSniffingEcho, + Tls(Arc), + Refused, +} +type RequestLog = Arc, Vec)>>>; +struct Origin { + mode: PeerMode, + sessions: Mutex>, + requests: RequestLog, + tasks: Mutex>>>, + live: Arc, + cancellation: CancellationToken, +} +struct Live(Arc); +impl Drop for Live { + fn drop(&mut self) { + self.0.fetch_sub(1, Ordering::SeqCst); + } +} + +async fn http_origin( + stream: S, + destination: Destination, + requests: RequestLog, +) -> io::Result<()> { + let mut reader = BufReader::new(stream); + let head = framing::read_head(&mut reader, 32768).await?; + let request = parser::parse_request_head(&head, Vec::new())?; + let plan = framing::RequestPlan::for_target(&request, destination, "/".into(), false)?; + let mut body = Vec::new(); + framing::transfer_body( + &mut reader, + &mut body, + plan.body, + WAIT, + &plan.trailer_blocklist, + true, + ) + .await?; + requests.lock().unwrap().push((head, body)); + reader.get_mut().write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: 6\r\nConnection: close\r\n\r\norigin").await?; + reader.get_mut().shutdown().await +} + +#[async_trait] +impl Dispatcher for Origin { + async fn sniff_plan( + &self, + source: std::net::SocketAddr, + destination: &Destination, + ) -> Result, DispatchError> { + if !matches!( + self.mode, + PeerMode::SniffingEcho | PeerMode::BufferedSniffingEcho + ) { + return Ok(None); + } + let config = crate::config::Config::parse_yaml( + b"sniffer:\n enable: true\n force-domain: [target.test]\n sniff:\n HTTP: {ports: [80]}\n", + ).unwrap(); + let policy = crate::sniffing::Policy::new( + Arc::new(config.sniffer), + Arc::new(crate::routing::EmptyGeoMatcher), + ); + let host = match destination { + Destination::Domain { host, .. } => Some(host.as_str()), + Destination::Ip(_) => None, + }; + Ok(Some(policy.plan(source, destination, host, false)?)) + } + + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.sessions.lock().unwrap().push(session.clone()); + if matches!(self.mode, PeerMode::Refused) { + return Err(DispatchError::ConnectionRefused); + } + let (client, mut peer) = tokio::io::duplex(16384); + let mode = self.mode.clone(); + let requests = self.requests.clone(); + let cancellation = self.cancellation.clone(); + self.live.fetch_add(1, Ordering::SeqCst); + let live = Live(self.live.clone()); + self.tasks.lock().unwrap().push(tokio::spawn(async move { + let _live = live; + let operation = async { + match mode { + PeerMode::Http => http_origin(peer, session.destination, requests).await, + PeerMode::Tls(config) => { + let tls = tokio_rustls::TlsAcceptor::from(config).accept(peer).await?; + http_origin(tls, session.destination, requests).await + } + PeerMode::Echo | PeerMode::SniffingEcho => { + let mut bytes = Vec::new(); + peer.read_to_end(&mut bytes).await?; + requests.lock().unwrap().push((bytes.clone(), Vec::new())); + peer.write_all(&bytes).await?; + peer.shutdown().await + } + PeerMode::BufferedSniffingEcho => { + let mut bytes = [0_u8; 1024]; + loop { + let count = peer.read(&mut bytes).await?; + if count == 0 { + return peer.shutdown().await; + } + peer.write_all(&bytes[..count]).await?; + } + } + PeerMode::Refused => unreachable!(), + } + }; + tokio::select! { + biased; + () = cancellation.cancelled() => Ok(()), + result = operation => result, + } + })); + if matches!(self.mode, PeerMode::BufferedSniffingEcho) { + Ok(Box::new(tokio::io::BufWriter::new(client))) + } else { + Ok(Box::new(client)) + } + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +impl Origin { + fn new(mode: PeerMode) -> Arc { + Arc::new(Self { + mode, + sessions: Mutex::new(Vec::new()), + requests: Arc::default(), + tasks: Mutex::new(Vec::new()), + live: Arc::default(), + cancellation: CancellationToken::new(), + }) + } + async fn join(&self) -> io::Result<()> { + self.cancellation.cancel(); + let tasks = std::mem::take(&mut *self.tasks.lock().unwrap()); + let mut failure = None; + for task in tasks { + if let Err(error) = join(task).await { + failure = Some(error); + } + } + if self.live.load(Ordering::SeqCst) != 0 { + return Err(io::Error::other("memory origin owner remains alive")); + } + failure.map_or(Ok(()), Err) + } +} + +struct Entry { + context: Option, + origin: Arc, + outer_connects: Arc, +} +#[async_trait] +impl Dispatcher for Entry { + fn http_context(&self) -> Option { + self.context.clone() + } + async fn sniff_plan( + &self, + source: std::net::SocketAddr, + destination: &Destination, + ) -> Result, DispatchError> { + self.origin.sniff_plan(source, destination).await + } + async fn connect_tcp(&self, session: StreamSession) -> Result { + self.outer_connects.fetch_add(1, Ordering::SeqCst); + self.origin.connect_tcp(session).await + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +struct Fixture { + client: DuplexStream, + worker: JoinHandle>, + cancellation: CancellationToken, + outer_connects: Arc, +} +impl Fixture { + fn new(context: Option, origin: Arc, authenticated: bool) -> Self { + let outer_connects = Arc::new(AtomicUsize::new(0)); + let entry = Arc::new(Entry { + context, + origin, + outer_connects: outer_connects.clone(), + }); + let handler = Socks5Handler::new( + Socks5InboundConfig { + tag: "memory-socks".into(), + port: 1080, + access: ProxyAccess { + bind_address: None, + allow_lan: false, + ipv6: false, + }, + auth: authenticated.then(|| ProxyCredentials::new("fixture", "password").unwrap()), + }, + entry, + ); + let (client, server) = tokio::io::duplex(16384); + let cancellation = CancellationToken::new(); + let stop = cancellation.clone(); + let worker = tokio::spawn(async move { + // Same cancellation owner as the production accept loop. No test + // listener, fake HTTP adapter or independently detached relay. + tokio::select! { + biased; + () = stop.cancelled() => Ok(()), + result = handler.handle_connection( + server, "198.51.100.2:34567".parse().unwrap(), + "127.0.0.1:1080".parse().unwrap(), None, stop.clone(), Instant::now() + WAIT, + ) => result, + } + }); + Self { + client, + worker, + cancellation, + outer_connects, + } + } + async fn finish(self, origin: &Origin) -> io::Result<()> { + self.cancellation.cancel(); + drop(self.client); + let worker = join(self.worker).await; + let peers = origin.join().await; + worker.and(peers) + } +} +async fn join(mut task: JoinHandle>) -> io::Result<()> { + match timeout(WAIT, &mut task).await { + Ok(result) => result.map_err(io::Error::other)?, + Err(_) => { + task.abort(); + let _ = task.await; + Err(io::Error::new( + io::ErrorKind::TimedOut, + "memory owner did not join", + )) + } + } +} +fn context(yaml: &str, origin: Arc) -> HttpContext { + HttpContext::new( + Policy::compile(yaml).unwrap(), + origin, + SecurityContext::new(), + ) +} +async fn exact(client: &mut DuplexStream, expected: &[u8]) -> io::Result<()> { + let mut bytes = vec![0; expected.len()]; + client.read_exact(&mut bytes).await?; + if bytes != expected { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "unexpected SOCKS reply", + )); + } + Ok(()) +} +async fn handshake(client: &mut DuplexStream, port: u16, authenticated: bool) -> io::Result<()> { + if authenticated { + client.write_all(&[5, 1, 2]).await?; + exact(client, &[5, 2]).await?; + client.write_all(b"\x01\x07fixture\x08password").await?; + exact(client, &[1, 0]).await?; + } else { + client.write_all(&[5, 1, 0]).await?; + exact(client, &[5, 0]).await?; + } + let mut command = vec![5, 1, 0]; + crate::socks5::encode_address(&Destination::domain("target.test", port)?, &mut command)?; + client.write_all(&command).await?; + // No HTTP/TLS bytes are sent until the real CONNECT success is received. + exact(client, &[5, 0, 0, 1, 0, 0, 0, 0, 0, 0]).await +} + +#[tokio::test] +async fn socks_http_native_request_response_and_authenticated_identity() { + let origin = Origin::new(PeerMode::Http); + let mut fixture = Fixture::new(Some(context(NATIVE, origin.clone())), origin.clone(), true); + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, 80, true).await?; + fixture.client.write_all(REQUEST).await?; + let mut response = String::new(); + fixture.client.read_to_string(&mut response).await?; + Ok::<_, io::Error>(response) + }) + .await; + let outer = fixture.outer_connects.load(Ordering::SeqCst); + let cleanup = fixture.finish(&origin).await; + cleanup.unwrap(); + let response = exchange.unwrap().unwrap(); + assert!(response.starts_with("HTTP/1.1 200"), "{response}"); + assert!( + response + .to_ascii_lowercase() + .contains("x-response-native: yes\r\n") + ); + assert!(response.ends_with("\r\n\r\nnative-response")); + assert_eq!(outer, 0); + let requests = origin.requests.lock().unwrap(); + assert_eq!(requests.len(), 1); + assert!( + String::from_utf8_lossy(&requests[0].0) + .to_ascii_lowercase() + .contains("x-request-native: yes\r\n") + ); + assert_eq!(requests[0].1, b"native-request"); + let sessions = origin.sessions.lock().unwrap(); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0].inbound, InboundKind::Socks5); + assert_eq!(sessions[0].metadata.user.as_deref(), Some("fixture")); + assert_eq!(sessions[0].metadata.local_port, 1080); + let original = sessions[0].metadata.original.as_ref().unwrap(); + assert_eq!(original.inbound, InboundKind::Socks5); + assert_eq!(original.user.as_deref(), Some("fixture")); + assert_eq!( + original.destination, + Destination::domain("target.test", 80).unwrap() + ); +} + +#[tokio::test] +async fn socks_http_transparent_boundaries_preserve_bytes_and_fixed_context() { + for (yaml, port, candidate) in [ + (None, 80, false), + ( + Some( + "http-ports: [80]\nrewrite: {enabled: false, rules: [{url: '.', action: response-body-set, value: changed}]}\n", + ), + 80, + false, + ), + (Some(NATIVE), 81, false), + (Some(NATIVE), 80, true), + ] { + let origin = Origin::new(if candidate { + PeerMode::SniffingEcho + } else { + PeerMode::Echo + }); + let pinned = yaml.is_some(); + let http = yaml.map(|yaml| context(yaml, origin.clone())); + let mut fixture = Fixture::new(http, origin.clone(), false); + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, port, false).await?; + let before_payload = origin.sessions.lock().unwrap().len(); + let payload = b"PING\0opaque\r\n\xfftail"; + fixture.client.write_all(payload).await?; + fixture.client.shutdown().await?; + let mut response = Vec::new(); + fixture.client.read_to_end(&mut response).await?; + Ok::<_, io::Error>((before_payload, response, payload.to_vec())) + }) + .await; + let outer = fixture.outer_connects.load(Ordering::SeqCst); + let cleanup = fixture.finish(&origin).await; + cleanup.unwrap(); + let (before, response, payload) = exchange.unwrap().unwrap(); + assert_eq!( + before, + usize::from(!candidate), + "raw ports must connect before acknowledging" + ); + assert_eq!(outer, usize::from(!pinned)); + assert_eq!( + response, payload, + "consumed prefix or a duplicate SOCKS reply leaked" + ); + assert_eq!(origin.requests.lock().unwrap()[0].0, payload); + } +} + +#[tokio::test] +async fn socks_sniffed_prefix_is_flushed_before_the_client_sends_more() { + let origin = Origin::new(PeerMode::BufferedSniffingEcho); + let mut fixture = Fixture::new(None, origin.clone(), false); + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, 80, false).await?; + fixture.client.write_all(REQUEST).await?; + let mut response = vec![0; REQUEST.len()]; + // The client deliberately keeps its write half open and sends no + // second flight until the buffered outbound has replied. + fixture.client.read_exact(&mut response).await?; + Ok::<_, io::Error>(response) + }) + .await; + let cleanup = fixture.finish(&origin).await; + cleanup.unwrap(); + assert_eq!(exchange.unwrap().unwrap(), REQUEST); + assert_eq!( + origin.sessions.lock().unwrap()[0].sniffed_domain.as_deref(), + Some("target.test") + ); +} + +#[tokio::test] +async fn socks_http_transparent_connect_failure_never_sends_a_second_socks_reply() { + let origin = Origin::new(PeerMode::Refused); + let mut fixture = Fixture::new(Some(context(NATIVE, origin.clone())), origin.clone(), false); + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, 80, false).await?; + fixture.client.write_all(b"\0opaque").await?; + let mut response = Vec::new(); + fixture.client.read_to_end(&mut response).await?; + Ok::<_, io::Error>(response) + }) + .await; + let outer = fixture.outer_connects.load(Ordering::SeqCst); + let cleanup = fixture.finish(&origin).await; + assert!(cleanup.is_err()); + assert!(exchange.unwrap().unwrap().is_empty()); + assert_eq!(outer, 0); + assert_eq!(origin.sessions.lock().unwrap().len(), 1); +} + +#[tokio::test] +async fn socks_http_cancel_pending_candidate_joins_without_origin() { + let origin = Origin::new(PeerMode::Http); + let mut fixture = Fixture::new(Some(context(NATIVE, origin.clone())), origin.clone(), false); + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, 80, false).await?; + fixture.client.write_all(b"GE").await + }) + .await; + let cleanup = fixture.finish(&origin).await; + cleanup.unwrap(); + exchange.unwrap().unwrap(); + assert!(origin.sessions.lock().unwrap().is_empty()); + assert_eq!(origin.live.load(Ordering::SeqCst), 0); +} + +#[tokio::test] +async fn socks_https_mitm_allowed_and_excluded_use_real_tls_and_correct_identity() { + for excluded in [false, true] { + let material = test_material(); + let identity = + rcgen::generate_simple_self_signed(vec!["allowed.test".into(), "excluded.test".into()]) + .unwrap(); + let origin_certificate = identity.cert.der().clone(); + let mut server = rustls::ServerConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_no_client_auth() + .with_single_cert( + vec![origin_certificate.clone()], + PrivatePkcs8KeyDer::from(identity.signing_key.serialize_der()).into(), + ) + .unwrap(); + server.alpn_protocols = vec![b"http/1.1".to_vec()]; + let origin = Origin::new(PeerMode::Tls(Arc::new(server))); + let yaml = "mitm:\n enabled: true\n ports: [443]\n domains: [{pattern: allowed.test}, {pattern: excluded.test}]\n exclude-domains: [{pattern: excluded.test}]\nrewrite:\n enabled: true\n rules:\n - {url: '.', action: response-header-set, header: X-Mitm, value: yes}\n - {url: '.', action: response-body-set, value: decrypted}\n"; + let policy = Document::parse(yaml) + .unwrap() + .compile(&Default::default()) + .unwrap() + .bind_ca(Some(&material)) + .unwrap(); + let mut upstream_roots = rustls::RootCertStore::empty(); + upstream_roots.add(origin_certificate.clone()).unwrap(); + let http = HttpContext::new( + policy, + origin.clone(), + SecurityContext::with_tls_roots(upstream_roots), + ); + let mut roots = rustls::RootCertStore::empty(); + roots + .add(if excluded { + origin_certificate.clone() + } else { + CertificateDer::from_pem_slice(material.certificate.as_bytes()).unwrap() + }) + .unwrap(); + let mut client_config = rustls::ClientConfig::builder_with_provider(Arc::new( + rustls::crypto::ring::default_provider(), + )) + .with_safe_default_protocol_versions() + .unwrap() + .with_root_certificates(roots) + .with_no_client_auth(); + client_config.alpn_protocols = vec![b"http/1.1".to_vec()]; + let mut fixture = Fixture::new(Some(http), origin.clone(), true); + let name = if excluded { + "excluded.test" + } else { + "allowed.test" + }; + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, 443, true).await?; + let mut tls = tokio_rustls::TlsConnector::from(Arc::new(client_config)) + .connect(ServerName::try_from(name).unwrap(), &mut fixture.client) + .await?; + let certificate = tls.get_ref().1.peer_certificates().unwrap()[0].clone(); + tls.write_all( + format!("GET /tls HTTP/1.1\r\nHost: {name}\r\nConnection: close\r\n\r\n") + .as_bytes(), + ) + .await?; + let mut reader = BufReader::new(tls); + let head = framing::read_head(&mut reader, 32768).await?; + let parsed = framing::ResponseHead::parse(&head)?; + let mut body = Vec::new(); + framing::transfer_body( + &mut reader, + &mut body, + parsed.body("GET"), + WAIT, + parsed.trailer_blocklist(), + true, + ) + .await?; + let head = String::from_utf8(head).map_err(io::Error::other)?; + Ok::<_, io::Error>((certificate, head, body)) + }) + .await; + let outer = fixture.outer_connects.load(Ordering::SeqCst); + let cleanup = fixture.finish(&origin).await; + cleanup.unwrap(); + let (certificate, head, body) = exchange.unwrap().unwrap(); + assert_eq!(certificate == origin_certificate, excluded); + assert!(head.starts_with("HTTP/1.1 200")); + assert_eq!( + head.lines() + .any(|line| line.eq_ignore_ascii_case("x-mitm: yes")), + !excluded + ); + assert_eq!( + body, + if excluded { + b"origin".as_slice() + } else { + b"decrypted".as_slice() + } + ); + assert_eq!( + outer, 0, + "transparent TLS must retain the HTTP resource generation" + ); + let sessions = origin.sessions.lock().unwrap(); + assert_eq!(sessions.len(), 1); + assert_eq!(sessions[0].inbound, InboundKind::Socks5); + assert_eq!(sessions[0].metadata.user.as_deref(), Some("fixture")); + } +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn socks_http_jsc_request_and_response_follow_native_stages() { + let yaml = format!( + "{NATIVE}\nhttp-scripts:\n enabled: true\n scripts:\n - name: request\n phase: request\n url: '.'\n body: text\n source: 'function rewrite(input) {{return {{type: \"modify\", body: {{kind: \"text\", data: input.body.data + \":js\"}}}};}}'\n - name: response\n phase: response\n url: '.'\n body: text\n source: 'function rewrite(input) {{return {{type: \"modify\", body: {{kind: \"text\", data: input.body.data + \":js\"}}}};}}'\n" + ); + let origin = Origin::new(PeerMode::Http); + let mut fixture = Fixture::new(Some(context(&yaml, origin.clone())), origin.clone(), false); + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, 80, false).await?; + fixture.client.write_all(REQUEST).await?; + let mut response = String::new(); + fixture.client.read_to_string(&mut response).await?; + Ok::<_, io::Error>(response) + }) + .await; + let cleanup = fixture.finish(&origin).await; + cleanup.unwrap(); + assert!( + exchange + .unwrap() + .unwrap() + .ends_with("\r\n\r\nnative-response:js") + ); + assert_eq!(origin.requests.lock().unwrap()[0].1, b"native-request:js"); +} + +#[cfg(target_vendor = "apple")] +#[tokio::test] +async fn socks_http_jsc_local_response_never_opens_upstream() { + let origin = Origin::new(PeerMode::Http); + let yaml = r#"http-ports: [80] +http-scripts: + enabled: true + scripts: + - name: local + phase: request + url: '.' + source: 'function rewrite(input) {return {type:"respond",status:201,body:{kind:"text",data:"local-jsc"}};}' +"#; + let mut fixture = Fixture::new(Some(context(yaml, origin.clone())), origin.clone(), false); + let exchange = timeout(WAIT, async { + handshake(&mut fixture.client, 80, false).await?; + fixture.client.write_all(REQUEST).await?; + let mut response = String::new(); + fixture.client.read_to_string(&mut response).await?; + Ok::<_, io::Error>(response) + }) + .await; + let cleanup = fixture.finish(&origin).await; + cleanup.unwrap(); + let response = exchange.unwrap().unwrap(); + assert!(response.starts_with("HTTP/1.1 201")); + assert!(response.ends_with("\r\n\r\nlocal-jsc")); + assert!(origin.sessions.lock().unwrap().is_empty()); +} diff --git a/src/inbound/socks5/server.rs b/src/inbound/socks5/server.rs index ae9d391..6a2f481 100644 --- a/src/inbound/socks5/server.rs +++ b/src/inbound/socks5/server.rs @@ -181,7 +181,7 @@ impl Socks5Handler { deadline: Instant, ) -> io::Result<()> where - S: AsyncRead + AsyncWrite + Unpin, + S: AsyncRead + AsyncWrite + Unpin + Send, { let config = &self.config; let dispatcher = self.dispatcher.clone(); @@ -215,14 +215,47 @@ impl Socks5Handler { destination, sniffed_domain: None, }; + let mut acknowledged = false; + #[cfg(feature = "inbound-http")] + let (mut stream, dispatcher) = { + let mut selected = dispatcher; + let mut prefix = Vec::new(); + if let Some(http) = selected.http_context() { + // Pin this connection even when its port is not a + // candidate; interception and fallback use one generation. + selected = http.dispatcher().clone(); + if http.candidate_port(session.destination.port()) { + // The client must receive CONNECT success before + // sending HTTP or its TLS ClientHello. Later failures + // close it instead of writing a second SOCKS reply. + timed(handshake::reply(&mut stream, 0, None)).await?; + acknowledged = true; + match http + .try_intercept(&mut stream, session.clone(), cancellation.clone()) + .await? + { + crate::http_processing::Intercept::Handled => return Ok(()), + crate::http_processing::Intercept::Transparent { prefix: bytes } => { + prefix = bytes; + } + } + } + } + ( + crate::http_processing::io::Replay::new(prefix, stream), + selected, + ) + }; let sniff = dispatcher .sniff_plan(peer, &session.destination) .await .map_err(|_| io::Error::other("sniffer rule evaluation failed"))? .filter(|plan| plan.tcp_enabled()); - let acknowledged = sniff.is_some(); let prefix = if let Some(plan) = sniff { - timed(handshake::reply(&mut stream, 0, None)).await?; + if !acknowledged { + timed(handshake::reply(&mut stream, 0, None)).await?; + acknowledged = true; + } plan.sniff(&mut stream, &mut session) .await .map_err(|_| io::Error::other("sniffer rule evaluation failed"))? @@ -238,7 +271,11 @@ impl Socks5Handler { timed(handshake::reply(&mut stream, 0, None)).await?; } if !prefix.is_empty() { - timed(upstream.write_all(&prefix)).await?; + timed(async { + upstream.write_all(&prefix).await?; + upstream.flush().await + }) + .await?; } copy_bidirectional_with_sizes( &mut stream, @@ -304,6 +341,10 @@ impl Socks5Handler { } } +#[cfg(all(test, feature = "inbound-http"))] +#[path = "http_processing_memory_tests.rs"] +mod http_processing_memory_tests; + async fn read_control(stream: &mut S) -> io::Result<()> { let mut buffer = [0; 1024]; while stream.read(&mut buffer).await? != 0 {} diff --git a/src/invoke/http_diagnostics_tests.rs b/src/invoke/http_diagnostics_tests.rs new file mode 100644 index 0000000..6e89406 --- /dev/null +++ b/src/invoke/http_diagnostics_tests.rs @@ -0,0 +1,125 @@ +// Included inside invoke::tests so the existing lifecycle test lock is shared. +// These tests read JSON and atomics only; they never initialize or start Core. + +const HTTP_DIAGNOSTICS_REQUEST: &[u8] = + br#"{"method":"getHttpDiagnostics","payload":{}}"#; + +fn http_diagnostics_response(request: &[u8], owned: bool) -> Value { + let bytes = if owned { + super::invoke_owned_bytes(request.to_vec()) + } else { + super::invoke_bytes(request) + }; + serde_json::from_slice(&bytes).unwrap() +} + +#[cfg(not(feature = "http-diagnostics"))] +#[test] +fn http_diagnostics_is_unknown_without_the_feature() { + let _guard = TEST_LOCK.lock().unwrap(); + let registry_before = super::REGISTRY.get().map(std::ptr::from_ref); + for owned in [false, true] { + let response = http_diagnostics_response(HTTP_DIAGNOSTICS_REQUEST, owned); + assert_failure(&response); + assert!(response["error"].as_str().unwrap().contains( + "unknown method `getHttpDiagnostics`" + )); + } + assert_eq!(super::REGISTRY.get().map(std::ptr::from_ref), registry_before); +} + +#[test] +fn http_diagnostics_cannot_reenter_from_a_runtime_thread() { + // Both builds must preserve the shared admission rule, even for reads. + let _runtime_thread = super::RuntimeThreadGuard::enter(); + for owned in [false, true] { + let bytes = if owned { + super::invoke_owned_bytes(HTTP_DIAGNOSTICS_REQUEST.to_vec()) + } else { + super::invoke_bytes(HTTP_DIAGNOSTICS_REQUEST) + }; + assert_eq!(bytes, super::runtime_thread_response()); + } +} + +#[cfg(feature = "http-diagnostics")] +fn http_diagnostics_registry_state() -> Option<(usize, bool, Option, u64)> { + super::REGISTRY.get().map(|registry| { + ( + std::ptr::from_ref(registry) as usize, + super::lock(®istry.runtime_data).is_some(), + super::lock(®istry.inner).instance.as_ref().map(|value| value.id), + registry.next_id.load(Ordering::Relaxed), + ) + }) +} + +#[cfg(feature = "http-diagnostics")] +#[test] +fn http_diagnostics_reads_without_initialization_or_resources() { + use crate::resources::observation::ResourceProbe; + + let _guard = TEST_LOCK.lock().unwrap(); + let registry_before = http_diagnostics_registry_state(); + let probe = ResourceProbe::default(); + let resources_before = probe.snapshot(); + let queues_before = probe.queues(); + for owned in [false, true] { + let response = probe.scope_sync(|| { + http_diagnostics_response(HTTP_DIAGNOSTICS_REQUEST, owned) + }); + assert_eq!(response.as_object().unwrap().len(), 3); + assert_eq!(response["success"], true); + assert_eq!(response["error"], ""); + let data = &response["data"]; + assert!(data["scope"].as_str().unwrap().contains("process-lifetime")); + for name in ["counters", "timings", "stages", "callBuffers", "bodyBypasses"] { + assert!(data[name].is_object(), "missing aggregate {name}"); + } + for counter in ["callBuffersBudgetRejected", "queueTimeout", "evaluationEntered"] { + assert!(data["counters"][counter].is_u64(), "missing counter {counter}"); + } + for stage in ["contextAndCallback", "prelude", "program", "input", "invokeAndFinish", "export"] { + for outcome in ["succeeded", "failed"] { + for aggregate in ["count", "total", "max"] { + assert!(data["stages"][stage][outcome][aggregate].is_u64()); + } + } + } + assert!(data["bodyWorkspace"]["current"].is_u64()); + assert!(data["contexts"]["current"].is_u64()); + assert!(data["queue"]["current"].is_u64()); + assert!(data.get("instanceId").is_none()); + // Fixed aggregate data cannot become per-request retained observations. + assert!(serde_json::to_vec(&response).unwrap().len() < 64 * 1024); + } + assert_eq!(http_diagnostics_registry_state(), registry_before); + assert_eq!(probe.snapshot(), resources_before); + assert_eq!(probe.queues(), queues_before); +} + +#[cfg(feature = "http-diagnostics")] +#[test] +fn http_diagnostics_rejects_instance_reset_and_unknown_envelope_or_payload() { + let _guard = TEST_LOCK.lock().unwrap(); + let registry_before = http_diagnostics_registry_state(); + for request in [ + r#"{"method":"getHttpDiagnostics","instanceId":"1","payload":{}}"#, + r#"{"method":"getHttpDiagnostics","instanceId":"","payload":{}}"#, + r#"{"method":"getHttpDiagnostics","instanceId":null,"payload":{}}"#, + r#"{"method":"getHttpDiagnostics","payload":{"reset":true}}"#, + r#"{"method":"getHttpDiagnostics","payload":{"windowID":"test"}}"#, + r#"{"method":"getHttpDiagnostics","payload":{},"revision":1}"#, + r#"{"method":"getHttpDiagnostics","payload":null}"#, + r#"{"method":"getHttpDiagnostics","payload":[]}"#, + r#"{"method":"getHttpDiagnostics","payload":""}"#, + r#"{"method":"getHttpDiagnostics"}"#, + r#"{"method":"getHttpDiagnostics","payload":{},"payload":{}}"#, + ] { + let borrowed = http_diagnostics_response(request.as_bytes(), false); + let owned = http_diagnostics_response(request.as_bytes(), true); + assert_failure(&borrowed); + assert_eq!(borrowed, owned); + } + assert_eq!(http_diagnostics_registry_state(), registry_before); +} diff --git a/src/invoke/http_test.rs b/src/invoke/http_test.rs index 3ab98a2..90ea0a4 100644 --- a/src/invoke/http_test.rs +++ b/src/invoke/http_test.rs @@ -41,6 +41,13 @@ struct ResponseSample { pub(crate) fn evaluate(payload: TestPayload) -> Result { let document = Document::parse(&payload.http_config_yaml) .map_err(|_| InvokeFailure::new("invalid HTTP processing configuration"))?; + if document.http_scripts.is_active() { + return Err(io::Error::new( + io::ErrorKind::Unsupported, + "testHttp does not execute enabled HTTP scripts", + ) + .into()); + } let (base, ca) = payload .http_context .map_or((None, None), |input| (input.base_dir, input.ca)); @@ -289,4 +296,22 @@ mod tests { assert_eq!(result["resourcesReady"], false); assert_eq!(result["outcome"], "unprepared"); } + + #[test] + fn offline_http_rejects_enabled_scripts_before_resource_lookup() { + let input = json!({"httpConfigYaml": "rewrite-providers: {missing: {type: file, path: no-io.yaml}}\nrewrite: {rules: [{rule-set: missing}]}\nhttp-scripts:\n enabled: true\n scripts:\n - {name: example, phase: request, url: '.', source: \"function rewrite(input) { return {type:'pass'}; }\"}\n", "url":"https://example.com/"}); + let failure = evaluate(serde_json::from_value(input).unwrap()).unwrap_err(); + assert_eq!( + failure.message, + "testHttp does not execute enabled HTTP scripts" + ); + } + + #[test] + fn offline_http_keeps_native_evaluation_with_disabled_scripts() { + let input = json!({"httpConfigYaml": "rewrite: {rules: [{url: '.', action: reject}]}\nhttp-scripts:\n enabled: false\n scripts:\n - {name: example, phase: request, url: '.', source: \"function rewrite(input) { while(true) {} }\"}\n", "url":"https://example.com/"}); + let result = run(input); + assert_eq!(result["url"]["outcome"], "reject"); + assert_eq!(result["url"]["status"], 403); + } } diff --git a/src/invoke/mod.rs b/src/invoke/mod.rs index 8f5514f..4a1f7fb 100644 --- a/src/invoke/mod.rs +++ b/src/invoke/mod.rs @@ -79,6 +79,12 @@ thread_local! { struct RegistryInner { instance: Option>, idle_http_refresh: bool, + #[cfg(all( + feature = "http-diagnostics", + feature = "inbound-http", + target_os = "tvos" + ))] + script_plan_validation_process: bool, } #[derive(Default)] @@ -283,11 +289,17 @@ thread_local! { pub(crate) fn engine_runtime_builder() -> tokio::runtime::Builder { let dispatch = tracing::dispatcher::get_default(Clone::clone); let mut builder = tokio::runtime::Builder::new_multi_thread(); + #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "macos"))] + builder.event_interval(16); builder .on_thread_start(move || { RUNTIME_WORKER_SCOPE.with(|scope| { *scope.borrow_mut() = Some(RuntimeWorkerScope::enter(&dispatch)); }); + #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "macos"))] + crate::platform::apple_runtime_qos::request( + crate::platform::apple_runtime_qos::Role::Tokio, + ); }) .on_thread_stop(|| { let scope = RUNTIME_WORKER_SCOPE.with(|scope| scope.borrow_mut().take()); @@ -535,6 +547,16 @@ impl RuntimeRegistry { } fn create_instance(&self) -> Result, InvokeFailure> { let mut inner = lock(&self.inner); + #[cfg(all( + feature = "http-diagnostics", + feature = "inbound-http", + target_os = "tvos" + ))] + if inner.script_plan_validation_process { + return Err(InvokeFailure::invalid_state( + "JS plan validation requires this process to exit before any business instance", + )); + } if inner.idle_http_refresh { return Err(InvokeFailure::invalid_state( "HTTP resource preparation is busy", @@ -1131,6 +1153,48 @@ fn dispatch_request(request: DecodedRequest) -> Result { + require_instance_omitted(&envelope)?; + let _: EmptyPayload = decode_payload(envelope.payload)?; + { + let mut inner = lock(®istry().inner); + if inner.instance.is_some() + || inner.idle_http_refresh + || inner.script_plan_validation_process + { + return Err(InvokeFailure::invalid_state( + "JS plan validation requires a fresh, idle, dedicated process", + )); + } + if lock(®istry().runtime_data).is_some() { + return Err(InvokeFailure::invalid_state( + "JS plan validation must precede Core initialization", + )); + } + // Irreversible even on panic/failure: subsequent createInstance + // (also foreground) fails under this same registry lock. + inner.script_plan_validation_process = true; + } + crate::http_processing::scripts::plan_validation::run()? + } + #[cfg(feature = "http-diagnostics")] + "getHttpDiagnostics" => { + require_instance_omitted(&envelope)?; + let _: EmptyPayload = decode_payload(envelope.payload)?; + #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "macos"))] + { + let mut snapshot = crate::http_processing::diagnostics::snapshot(); + snapshot["runtimeThreadQoS"] = crate::platform::apple_runtime_qos::snapshot(); + snapshot + } + #[cfg(not(any(target_os = "ios", target_os = "tvos", target_os = "macos")))] + crate::http_processing::diagnostics::snapshot() + } "version" => { require_instance_omitted(&envelope)?; let _: EmptyPayload = decode_payload(envelope.payload)?; @@ -1458,6 +1522,10 @@ impl CoreController { let _logging = tracing::dispatcher::set_default(&dispatch); let _completion = EngineCompletion(completed_tx); let _runtime_thread = RuntimeThreadGuard::enter(); + #[cfg(any(target_os = "ios", target_os = "tvos", target_os = "macos"))] + crate::platform::apple_runtime_qos::request( + crate::platform::apple_runtime_qos::Role::EngineOwner, + ); run_engine(context, prepared.core, tun, dialer, stop_rx, startup_tx) })); let runtime_thread = match spawned { @@ -2058,6 +2126,8 @@ mod tests { static TEST_LOCK: Mutex<()> = Mutex::new(()); + include!("http_diagnostics_tests.rs"); + #[test] fn allocator_relief_requires_tun() { assert!(TunAllocatorRelief::new(false).is_none()); diff --git a/src/lib.rs b/src/lib.rs index 89660fa..a90a56d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -99,6 +99,12 @@ pub mod transport; ) ))] mod tun_runtime; +#[cfg(all(feature = "tun", feature = "interop-test", unix))] +#[doc(hidden)] +pub use tun_runtime::interop::{ + InteropTunRoutingRegistry, InteropTunUdpReplies, InteropTunUdpTask, interop_tracked_tun_router, + interop_tun_udp_association, +}; #[cfg(any(feature = "tun", feature = "inbound-socks5", test))] mod udp_sniffing; #[cfg(all(windows, feature = "windows-uwp"))] diff --git a/src/limits.rs b/src/limits.rs index a4e5892..ca0e972 100644 --- a/src/limits.rs +++ b/src/limits.rs @@ -38,8 +38,10 @@ pub const XHTTP_H3_UNI_STREAMS: usize = 8; pub const XHTTP_H3_STREAM_WINDOW: usize = 64 * 1024; pub const XHTTP_H3_CONNECTION_WINDOW: usize = 128 * 1024; pub const XHTTP_H3_SEND_WINDOW: usize = 64 * 1024; +/// Fixed initial retained writes for the qualified VLESS/Yamux H3 carrier. +pub const XHTTP_H3_YAMUX_SEND_WINDOW: usize = 128 * 1024; /// Retained writes after a qualified physical connection's first local mux UDP association. -pub const XHTTP_H3_UDP_SEND_WINDOW: usize = 192 * 1024; +pub const XHTTP_H3_UDP_SEND_WINDOW: usize = 256 * 1024; pub const SING_MUX_IDLE_CONNECTIONS: usize = 16; pub const SING_MUX_COMMAND_QUEUE: usize = 16; pub const SING_MUX_CHUNK: usize = 16 * 1024; @@ -107,7 +109,10 @@ pub struct ResourceLimits { pub max_datagram_size: usize, /// Maximum raw IP packet accepted by a TUN netstack. pub tun_max_datagram_size: usize, + /// Shared stream buffer budget and TUN TCP receive total per flow. pub tcp_buffer_per_direction: usize, + /// TUN TCP send total per flow, split equally between smoltcp and its app queue. + pub tun_tcp_send_buffer: usize, /// Explicit low-level DNS constructor override. Production sessions use /// dns.cache-max-size for the shared typed/opaque result capacity instead. pub dns_address_cache_entries: usize, @@ -134,6 +139,7 @@ impl Default for ResourceLimits { max_datagram_size: 65_535, tun_max_datagram_size: 1_500, tcp_buffer_per_direction: 32 * 1024, + tun_tcp_send_buffer: 128 * 1024, dns_address_cache_entries: 256, dns_redir_host_entries: 256, tun_udp_association_queue_capacity: 64, @@ -154,6 +160,7 @@ impl ResourceLimits { ("max_datagram_size", self.max_datagram_size), ("tun_max_datagram_size", self.tun_max_datagram_size), ("tcp_buffer_per_direction", self.tcp_buffer_per_direction), + ("tun_tcp_send_buffer", self.tun_tcp_send_buffer), ("dns_address_cache_entries", self.dns_address_cache_entries), ("dns_redir_host_entries", self.dns_redir_host_entries), ( @@ -202,6 +209,10 @@ mod tests { tcp_buffer_per_direction: 0, ..ResourceLimits::default() }, + ResourceLimits { + tun_tcp_send_buffer: 0, + ..ResourceLimits::default() + }, ResourceLimits { dns_address_cache_entries: 0, ..ResourceLimits::default() @@ -246,6 +257,7 @@ mod tests { assert_eq!(limits.max_datagram_size, 65_535); assert_eq!(limits.tun_max_datagram_size, 1_500); assert_eq!(limits.tcp_buffer_per_direction, 32 * 1024); + assert_eq!(limits.tun_tcp_send_buffer, 128 * 1024); assert_eq!(limits.dns_address_cache_entries, 256); assert_eq!(limits.dns_redir_host_entries, 256); assert_eq!(limits.tun_udp_association_queue_capacity, 64); diff --git a/src/outbound/connector.rs b/src/outbound/connector.rs index 3752b86..5bcbadc 100644 --- a/src/outbound/connector.rs +++ b/src/outbound/connector.rs @@ -582,6 +582,15 @@ impl DatagramRequest { /// protocols adjust their upstream response budget. #[async_trait] pub trait OutboundConnector: Send + Sync { + /// Structural proof that the complete configured TCP path and security + /// identity are immutable. This query neither selects a group nor opens IO. + /// Unknown connectors and dynamic dependencies remain one-shot HTTP paths. + #[cfg(feature = "inbound-http")] + #[doc(hidden)] + fn permits_http_tcp_reuse(&self) -> bool { + false + } + async fn connect_stream( &self, session: StreamSession, @@ -750,6 +759,61 @@ impl std::fmt::Debug for UpstreamPath { } impl UpstreamPath { + /// A retained HTTP stream must not hide a new physical path selection. + /// Only exact literal endpoints and recursively proven connectors qualify; + /// groups are rejected even when their current member happens to be DIRECT. + #[cfg(feature = "inbound-http")] + pub(crate) fn permits_static_http_reuse(&self, server: &Destination) -> bool { + let Destination::Ip(address) = server else { + return false; + }; + let dialer = match self { + Self::LazyDirect { dialer } => dialer, + Self::Direct { endpoint, dialer } + if endpoint.port == address.port() + && endpoint.logical_host.parse::().ok() == Some(address.ip()) + && endpoint.addresses.as_slice() == std::slice::from_ref(address) => + { + dialer + } + Self::Proxy(connector) => return connector.permits_http_tcp_reuse(), + _ => return false, + }; + dialer.permits_static_http_reuse() && !dialer.http_reuse_cancelled() + } + + /// A UDP carrier may retain a business TCP stream only on a proven + /// physical first hop. A proxy's TCP proof says nothing about its datagram + /// relay, so Proxy and Group never inherit permission here. + #[cfg(all( + feature = "inbound-http", + any( + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless", + feature = "outbound-mieru", + feature = "outbound-wireguard", + feature = "outbound-masque" + ) + ))] + pub(crate) fn permits_static_direct_http_reuse(&self, server: &Destination) -> bool { + let Destination::Ip(address) = server else { + return false; + }; + let dialer = match self { + Self::LazyDirect { dialer } => dialer, + Self::Direct { endpoint, dialer } + if endpoint.port == address.port() + && endpoint.logical_host.parse::().ok() == Some(address.ip()) + && endpoint.addresses.as_slice() == std::slice::from_ref(address) => + { + dialer + } + _ => return false, + }; + dialer.permits_static_http_reuse() && !dialer.http_reuse_cancelled() + } + /// A multi-endpoint node shares the declared graph, while each /// physical peer has its own server and may refresh a previously pinned IP. #[cfg(any( @@ -909,6 +973,30 @@ impl UpstreamPath { } } + /// Only directly declared physical paths may prepare one immutable UDP peer. + /// Groups and codecs keep their original selection and datagram behavior. + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + pub(crate) async fn open_fixed_peer_datagram( + &self, + request: DatagramRequest, + peer: SocketAddr, + context: &EstablishContext, + ) -> Result, DispatchError> { + match self { + Self::Direct { dialer, .. } | Self::LazyDirect { dialer } => { + DirectOutbound::new(dialer.clone()).open_fixed_datagram(request, peer) + } + Self::Group { .. } | Self::Proxy(_) => self.open_datagram(request, context).await, + } + } + /// Pins a native UDP server using the node resolver when first needed. /// Resolving here and opening IO below share the context's group snapshot. #[cfg(any( @@ -1021,6 +1109,11 @@ pub(crate) struct IpVersionConnector { } #[async_trait] impl OutboundConnector for IpVersionConnector { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.version == crate::config::IpVersion::Dual && self.inner.permits_http_tcp_reuse() + } + async fn connect_stream( &self, session: StreamSession, @@ -1138,6 +1231,11 @@ impl ConnectorDispatcher { #[async_trait] impl Dispatcher for ConnectorDispatcher { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.inner.permits_http_tcp_reuse() + } + fn supports_udp(&self) -> bool { self.allow_udp } @@ -1165,6 +1263,14 @@ impl Dispatcher for ConnectorDispatcher { } } +#[cfg(all(test, feature = "inbound-http"))] +#[path = "http_reuse_memory_tests.rs"] +mod http_reuse_memory_tests; + +#[cfg(all(test, feature = "inbound-http", feature = "outbound-hysteria2"))] +#[path = "hysteria2_http_reuse_memory_tests.rs"] +mod hysteria2_http_reuse_memory_tests; + #[cfg(test)] mod tests { use crate::session::{Datagram, InboundKind}; @@ -1330,6 +1436,87 @@ mod tests { } } + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + #[tokio::test] + async fn fixed_udp_memory_upstream_scope_keeps_groups_proxies_and_snapshots_original() { + let peer = "192.0.2.1:443".parse().unwrap(); + for path in [ + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }, + UpstreamPath::Direct { + endpoint: ResolvedEndpoint { + logical_host: "192.0.2.1".to_owned(), + port: 443, + addresses: vec![peer], + }, + dialer: Dialer::default(), + }, + ] { + let context = EstablishContext::default(); + let mut ordinary = path.open_datagram(test_request(), &context).await.unwrap(); + assert!(ordinary.supports_shared_destinations()); + ordinary.close().await.unwrap(); + let mut fixed = path + .open_fixed_peer_datagram(test_request(), peer, &context) + .await + .unwrap(); + assert!(!fixed.supports_shared_destinations()); + assert_eq!(fixed.payload_budget(&Destination::Ip(peer)).receive(), 1714); + fixed.close().await.unwrap(); + } + let proxy = Arc::new(MarkedConnector { + marker: 17, + ..Default::default() + }); + let path = UpstreamPath::Proxy(proxy.clone()); + let mut transport = path + .open_fixed_peer_datagram(test_request(), peer, &EstablishContext::default()) + .await + .unwrap(); + assert_eq!(transport.receive().await.unwrap().payload[0], 17); + assert_eq!(*proxy.budgets.lock().unwrap(), [1714]); + transport.close().await.unwrap(); + + let selection = Arc::new(GroupSelection::new(0)); + let path = selected_path( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + ); + let context = EstablishContext::default(); + let mut first = path + .open_fixed_peer_datagram(test_request(), peer, &context) + .await + .unwrap(); + assert!( + first.supports_shared_destinations(), + "a group currently choosing DIRECT must stay unconnected" + ); + first.close().await.unwrap(); + selection.store(1, Ordering::Release); + let mut pinned = path + .open_fixed_peer_datagram(test_request(), peer, &context) + .await + .unwrap(); + assert!( + pinned.supports_shared_destinations(), + "same context keeps its original group snapshot" + ); + pinned.close().await.unwrap(); + assert!(matches!( + path.open_fixed_peer_datagram(test_request(), peer, &EstablishContext::default()) + .await, + Err(DispatchError::NotAllowed) + )); + } + #[tokio::test] async fn ingress_sticky_upstream_keeps_source_ip_and_authenticated_user_precedence() { struct Carrier(UpstreamPath); diff --git a/src/outbound/direct.rs b/src/outbound/direct.rs index 8c27788..9eb647a 100644 --- a/src/outbound/direct.rs +++ b/src/outbound/direct.rs @@ -17,6 +17,21 @@ use crate::{ use super::{ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector}; +#[cfg(target_os = "macos")] +#[path = "direct_macos_batch.rs"] +mod macos_batch; + +#[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) +))] +#[path = "direct_fixed_peer.rs"] +mod fixed_peer; + /// Built-in DIRECT action. Domain destinations must be resolved and pinned by /// the routing layer before they reach this dispatcher. #[derive(Debug, Clone)] @@ -29,10 +44,40 @@ impl DirectOutbound { pub const fn new(dialer: Dialer) -> Self { Self { dialer } } + + /// Prepare one dedicated fixed-peer UDP path, without opening a socket. + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + pub(super) fn open_fixed_datagram( + &self, + request: DatagramRequest, + peer: SocketAddr, + ) -> Result, DispatchError> { + let mut transport = DirectDatagramTransport::new( + self.dialer.clone(), + usize::from(request.max_response_payload_size()), + request.udp_socket_options(), + ); + transport.fixed_peer = Some(fixed_peer::Path::new(peer)?); + Ok(crate::dispatch::bound_datagram( + Box::new(transport), + request.budget(), + )) + } } #[async_trait] impl Dispatcher for DirectOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.dialer.permits_static_http_reuse() && !self.dialer.http_reuse_cancelled() + } async fn connect_tcp(&self, session: StreamSession) -> Result { OutboundConnector::connect_stream(self, session, &EstablishContext::default()) .await @@ -95,6 +140,15 @@ struct DirectDatagramTransport { socket_options: crate::dialer::UdpSocketOptions, receive_buffer: Vec, receive_cursor: usize, + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + fixed_peer: Option>, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -116,6 +170,15 @@ impl DirectDatagramTransport { socket_options, receive_buffer: Vec::new(), receive_cursor: 0, + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + fixed_peer: None, } } @@ -145,11 +208,27 @@ impl DirectDatagramTransport { payload: &[u8], address: SocketAddr, ) -> Result<(), DispatchError> { - let written = socket - .send_to(payload, address) - .await - .map_err(DispatchError::from)?; - if written != payload.len() { + Self::finish_send(payload.len(), socket.send_to(payload, address)).await + } + + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + async fn send_connected(socket: &UdpSocket, payload: &[u8]) -> Result<(), DispatchError> { + Self::finish_send(payload.len(), socket.send(payload)).await + } + + async fn finish_send( + expected: usize, + send: impl std::future::Future>, + ) -> Result<(), DispatchError> { + let written = send.await.map_err(DispatchError::from)?; + if written != expected { return Err(DispatchError::Other( "direct UDP socket truncated a datagram".to_owned(), )); @@ -212,6 +291,17 @@ impl DirectDatagramTransport { #[async_trait] impl DatagramTransport for DirectDatagramTransport { fn supports_shared_destinations(&self) -> bool { + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + if self.fixed_peer.is_some() { + return false; + } // Unconnected sockets preserve each send target and actual reply source. true } @@ -256,6 +346,22 @@ impl DatagramTransport for DirectDatagramTransport { return Err(datagram); }; let address = *address; + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + if let Some(path) = &self.fixed_peer { + let Ok(Some(socket)) = path.ready(address) else { + return Err(datagram); + }; + return Ok(Box::pin(async move { + Self::send_connected(&socket, &datagram.payload).await + })); + } let class = UdpSocketClass { ipv6: address.is_ipv6(), loopback: address.ip().is_loopback(), @@ -270,10 +376,81 @@ impl DatagramTransport for DirectDatagramTransport { })) } + #[cfg(target_os = "macos")] + fn send_batch_owned( + &mut self, + datagrams: Vec, + ) -> Result> { + let Some(peer) = crate::dispatch::datagram_batch_peer(&datagrams) else { + return Err(datagrams); + }; + #[cfg(any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ))] + if let Some(path) = &self.fixed_peer { + let Ok(Some(socket)) = path.ready(peer) else { + return Err(datagrams); + }; + return macos_batch::send_connected_owned(socket, peer, datagrams); + } + let class = UdpSocketClass { + ipv6: peer.is_ipv6(), + loopback: peer.ip().is_loopback(), + }; + let Some((_, socket)) = self.sockets.iter().find(|(key, _)| *key == class) else { + // Only the existing ordinary first send may initialize protected IO. + return Err(datagrams); + }; + macos_batch::send_owned(socket.clone(), datagrams) + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { let Destination::Ip(address) = datagram.remote else { return Err(DispatchError::HostUnreachable); }; + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + if let Some(path) = &mut self.fixed_peer { + let dialer = self.dialer.clone(); + let options = self.socket_options; + let socket = path + .initialize_with( + address, + move |peer| async move { + // This existing Dialer call completes bind, protect, + // interface policy and its cancellation checks first. + dialer + .bind_udp_for_with_options(peer, options) + .await + .map_err(DispatchError::from) + }, + |socket, peer| async move { + socket.connect(peer).await.map_err(DispatchError::from)?; + Ok(socket) + }, + ) + .await?; + if self.sockets.is_empty() { + // Retain the original recv_from path and its source/oversize + // checks on this exact connected, protected socket. + self.sockets.push(( + UdpSocketClass { + ipv6: address.is_ipv6(), + loopback: address.ip().is_loopback(), + }, + socket.clone(), + )); + } + return Self::send_connected(&socket, &datagram.payload).await; + } let socket = self.socket_for(address).await?; Self::send_on(socket, &datagram.payload, address).await } @@ -310,6 +487,17 @@ impl DatagramTransport for DirectDatagramTransport { } async fn close(&mut self) -> Result<(), DispatchError> { + #[cfg(all( + target_os = "macos", + any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" + ) + ))] + if let Some(path) = &mut self.fixed_peer { + path.close(); + } self.sockets.clear(); Ok(()) } diff --git a/src/outbound/direct_fixed_peer.rs b/src/outbound/direct_fixed_peer.rs new file mode 100644 index 0000000..ae05b7f --- /dev/null +++ b/src/outbound/direct_fixed_peer.rs @@ -0,0 +1,367 @@ +//! One immutable peer on a fresh protected DIRECT path; no socket factory. +use crate::dispatch::DispatchError; +use std::{future::Future, net::SocketAddr, sync::Arc}; + +pub(super) struct Path { + peer: SocketAddr, + attempted: bool, + closed: bool, + socket: Option>, +} + +impl Path { + pub(super) fn new(peer: SocketAddr) -> Result { + if peer.port() == 0 || peer.ip().is_unspecified() || peer.ip().is_multicast() { + return Err(DispatchError::NotAllowed); + } + Ok(Self { + peer, + attempted: false, + closed: false, + socket: None, + }) + } + + pub(super) fn ready(&self, peer: SocketAddr) -> Result>, DispatchError> { + if self.closed || peer != self.peer { + return Err(DispatchError::NotAllowed); + } + Ok(self.socket.clone()) + } + + pub(super) async fn initialize_with( + &mut self, + peer: SocketAddr, + prepare: B, + connect: C, + ) -> Result, DispatchError> + where + B: FnOnce(SocketAddr) -> BF, + BF: Future>, + C: FnOnce(S, SocketAddr) -> CF, + CF: Future>, + { + if let Some(socket) = self.ready(peer)? { + return Ok(socket); + } + if self.attempted { + return Err(DispatchError::NotAllowed); + } + // Reserve one attempt before any await. Failure or cancellation never + // permits another bind/connect on this physical generation. + self.attempted = true; + let socket = prepare(self.peer).await?; + let socket = connect(socket, self.peer).await?; + // Only the successful, original prepared socket is published. + let socket = Arc::new(socket); + self.socket = Some(socket.clone()); + Ok(socket) + } + + pub(super) fn close(&mut self) { + self.closed = true; + self.socket.take(); + } +} + +#[cfg(test)] +mod tests { + use super::super::DirectDatagramTransport; + use super::*; + use crate::{ + dialer::Dialer, + dispatch::DatagramTransport, + session::{Datagram, Destination}, + }; + use bytes::Bytes; + use std::sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, + }; + + #[derive(Debug)] + struct Lease { + token: usize, + drops: Arc, + } + impl Drop for Lease { + fn drop(&mut self) { + self.drops.fetch_add(1, Ordering::Relaxed); + } + } + fn peer() -> SocketAddr { + SocketAddr::V6(std::net::SocketAddrV6::new( + "fe80::1".parse().unwrap(), + 443, + 123, + 7, + )) + } + fn packet(remote: Destination) -> Datagram { + Datagram { + remote, + payload: Bytes::from_static(b"whole"), + sniffed_domain: None, + } + } + + #[tokio::test] + async fn fixed_udp_memory_prepared_owner_connects_once_and_publishes_only_success() { + let peer = peer(); + let events = Arc::new(Mutex::new(Vec::new())); + let drops = Arc::new(AtomicUsize::new(0)); + let mut path = Path::::new(peer).unwrap(); + assert!(path.ready(peer).unwrap().is_none()); + let prepared = events.clone(); + let connected = events.clone(); + let owned_drops = drops.clone(); + let socket = path + .initialize_with( + peer, + move |actual| async move { + assert_eq!(actual, peer); + prepared + .lock() + .unwrap() + .push("protected-preparation-returned"); + Ok(Lease { + token: 17, + drops: owned_drops, + }) + }, + move |socket, actual| async move { + assert_eq!(actual, peer); + assert_eq!(socket.token, 17); + connected.lock().unwrap().push("connect-original-owner"); + Ok(socket) + }, + ) + .await + .unwrap(); + assert_eq!( + *events.lock().unwrap(), + ["protected-preparation-returned", "connect-original-owner"] + ); + assert!(Arc::ptr_eq(&socket, &path.ready(peer).unwrap().unwrap())); + let again = path + .initialize_with( + peer, + |_| async { panic!("a connected generation must not prepare again") }, + |_, _| async { panic!("a connected generation must not connect again") }, + ) + .await + .unwrap(); + assert!(Arc::ptr_eq(&socket, &again)); + drop(again); + path.close(); + assert!(path.ready(peer).is_err()); + assert_eq!( + drops.load(Ordering::Relaxed), + 0, + "the returned owned lease remains real" + ); + drop(socket); + assert_eq!(drops.load(Ordering::Relaxed), 1); + } + + #[tokio::test] + async fn fixed_udp_memory_preparation_refusal_never_connects_or_retries() { + let peer = peer(); + let calls = Arc::new(AtomicUsize::new(0)); + let connect_calls = calls.clone(); + let mut path = Path::::new(peer).unwrap(); + let result = path + .initialize_with( + peer, + |_| async { Err(DispatchError::NotAllowed) }, + move |socket, _| async move { + connect_calls.fetch_add(1, Ordering::Relaxed); + Ok(socket) + }, + ) + .await; + assert!(matches!(result, Err(DispatchError::NotAllowed))); + assert_eq!(calls.load(Ordering::Relaxed), 0); + assert!(path.ready(peer).unwrap().is_none()); + let retry = path + .initialize_with( + peer, + |_| async { panic!("failed protected preparation cannot rebind") }, + |_, _| async { panic!("failed protected preparation cannot connect") }, + ) + .await; + assert!(matches!(retry, Err(DispatchError::NotAllowed))); + path.close(); + } + + #[tokio::test] + async fn fixed_udp_memory_connect_error_preserves_error_and_drops_unpublished_owner() { + let peer = peer(); + let drops = Arc::new(AtomicUsize::new(0)); + let owned_drops = drops.clone(); + let mut path = Path::::new(peer).unwrap(); + let result = path + .initialize_with( + peer, + move |_| async move { + Ok(Lease { + token: 17, + drops: owned_drops, + }) + }, + |socket, _| async move { + assert_eq!(socket.token, 17); + Err(DispatchError::Other("original-connect-error".to_owned())) + }, + ) + .await; + assert!( + matches!(result, Err(DispatchError::Other(value)) if value == "original-connect-error") + ); + assert_eq!(drops.load(Ordering::Relaxed), 1); + assert!(path.ready(peer).unwrap().is_none()); + assert!(matches!( + path.initialize_with( + peer, + |_| async { panic!("connect failure must not allocate a replacement") }, + |_, _| async { panic!("connect failure must not reconnect") }, + ) + .await, + Err(DispatchError::NotAllowed) + )); + } + + #[tokio::test] + async fn fixed_udp_memory_cancelled_preparation_or_connect_releases_owner_without_reconnect() { + for pending_connect in [false, true] { + let peer = peer(); + let drops = Arc::new(AtomicUsize::new(0)); + let owned_drops = drops.clone(); + let mut path = Path::::new(peer).unwrap(); + let mut initializing = Box::pin(path.initialize_with( + peer, + move |_| async move { + let socket = Lease { + token: 17, + drops: owned_drops, + }; + if !pending_connect { + let _held = socket; + return std::future::pending::>().await; + } + Ok(socket) + }, + |socket, _| async move { + let _held = socket; + std::future::pending::>().await + }, + )); + assert!(futures_util::poll!(initializing.as_mut()).is_pending()); + assert_eq!(drops.load(Ordering::Relaxed), 0); + drop(initializing); + assert_eq!(drops.load(Ordering::Relaxed), 1); + assert!(path.ready(peer).unwrap().is_none()); + assert!(matches!( + path.initialize_with( + peer, + |_| async { panic!("cancelled initialization must not prepare again") }, + |_, _| async { panic!("cancelled initialization must not reconnect") }, + ) + .await, + Err(DispatchError::NotAllowed) + )); + path.close(); + } + } + + #[tokio::test] + async fn fixed_udp_memory_all_direct_send_guards_reject_wrong_peer_without_io() { + let peer = peer(); + let mut transport = + DirectDatagramTransport::new(Dialer::default(), 1400, Default::default()); + transport.fixed_peer = Some(Path::new(peer).unwrap()); + assert!(!transport.supports_shared_destinations()); + let mut peers = vec!["192.0.2.1:443".parse().unwrap()]; + for (port, flow, scope) in [(444, 123, 7), (443, 124, 7), (443, 123, 8)] { + peers.push(SocketAddr::V6(std::net::SocketAddrV6::new( + "fe80::1".parse().unwrap(), + port, + flow, + scope, + ))); + } + for other in peers { + assert!(matches!( + transport.send(packet(other.into())).await, + Err(DispatchError::NotAllowed) + )); + let returned = transport.send_owned(packet(other.into())).err().unwrap(); + assert_eq!(returned.remote, Destination::Ip(other)); + let batch = vec![packet(other.into()), packet(other.into())]; + let returned = transport.send_batch_owned(batch).err().unwrap(); + assert_eq!(returned.len(), 2); + assert!( + returned + .iter() + .all(|packet| packet.remote == Destination::Ip(other)) + ); + } + assert!( + transport + .send(packet(Destination::domain("other.invalid", 443).unwrap())) + .await + .is_err() + ); + assert!( + transport.send_owned(packet(peer.into())).is_err(), + "first exact peer is still unopened" + ); + assert!( + transport + .send_batch_owned(vec![packet(peer.into()), packet(peer.into())]) + .is_err() + ); + assert!( + transport.sockets.is_empty(), + "none of these guards may open a socket" + ); + transport.close().await.unwrap(); + assert!(matches!( + transport.send(packet(peer.into())).await, + Err(DispatchError::NotAllowed) + )); + assert!(transport.sockets.is_empty()); + } + + #[tokio::test] + async fn fixed_udp_memory_whole_datagram_helper_keeps_short_fatal_and_pending_drop() { + for actual in [0, 4, 6] { + let result = DirectDatagramTransport::finish_send(5, async { Ok(actual) }).await; + assert!( + matches!(result, Err(DispatchError::Other(value)) if value == "direct UDP socket truncated a datagram") + ); + } + DirectDatagramTransport::finish_send(5, async { Ok(5) }) + .await + .unwrap(); + assert!(matches!( + DirectDatagramTransport::finish_send(5, async { + Err(std::io::Error::from(std::io::ErrorKind::PermissionDenied)) + }) + .await, + Err(DispatchError::NotAllowed) + )); + let drops = Arc::new(AtomicUsize::new(0)); + let held = Lease { + token: 17, + drops: drops.clone(), + }; + let mut send = Box::pin(DirectDatagramTransport::finish_send(5, async move { + let _held = held; + std::future::pending::>().await + })); + assert!(futures_util::poll!(send.as_mut()).is_pending()); + drop(send); + assert_eq!(drops.load(Ordering::Relaxed), 1); + } +} diff --git a/src/outbound/direct_macos_batch.rs b/src/outbound/direct_macos_batch.rs new file mode 100644 index 0000000..9bebe95 --- /dev/null +++ b/src/outbound/direct_macos_batch.rs @@ -0,0 +1,80 @@ +//! Bounded ready UDP prefixes on an already protected socket. +use crate::session::Datagram; +use std::{ + io, + net::SocketAddr, + sync::Arc, + task::{Context, Poll}, +}; + +pub(super) fn send_owned( + socket: Arc, + packets: Vec, +) -> Result> { + send_with(packets, move |cx, payload, peer| { + // Tokio owns nonblocking readiness and cooperative-budget handling. + // This capture retains the original protected socket until operation Drop. + socket.poll_send_to(cx, payload, peer) + }) +} + +#[cfg(any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" +))] +pub(super) fn send_connected_owned( + socket: Arc, + peer: SocketAddr, + packets: Vec, +) -> Result> { + send_connected_with(packets, peer, move |cx, payload| { + socket.poll_send(cx, payload) + }) +} + +#[cfg(any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" +))] +fn send_connected_with( + packets: Vec, + peer: SocketAddr, + mut send: impl FnMut(&mut Context<'_>, &[u8]) -> Poll> + Send + 'static, +) -> Result> { + if crate::dispatch::datagram_batch_peer(&packets) != Some(peer) { + return Err(packets); + } + send_with(packets, move |cx, payload, _| send(cx, payload)) +} + +fn send_with( + packets: Vec, + mut send: impl FnMut(&mut Context<'_>, &[u8], SocketAddr) -> Poll> + + Send + + 'static, +) -> Result> { + let Some(peer) = crate::dispatch::datagram_batch_peer(&packets) else { + return Err(packets); + }; + Ok(Box::pin(std::future::poll_fn(move |cx| { + let mut accepted = 0; + // Admission bounds this poll to four complete packets and 8 KiB. + // The parent retains its FIFO until this exact positive prefix completes. + for packet in &packets { + match send(cx, &packet.payload, peer) { + Poll::Ready(Ok(length)) if length == packet.payload.len() => accepted += 1, + Poll::Ready(Ok(_)) => return Poll::Ready(Err(io::ErrorKind::InvalidData.into())), + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending if accepted != 0 => return Poll::Ready(Ok(accepted)), + Poll::Pending => return Poll::Pending, + } + } + Poll::Ready(Ok(accepted)) + }))) +} + +#[cfg(test)] +#[path = "direct_macos_batch_memory_tests.rs"] +mod tests; diff --git a/src/outbound/direct_macos_batch_memory_tests.rs b/src/outbound/direct_macos_batch_memory_tests.rs new file mode 100644 index 0000000..1ed06f5 --- /dev/null +++ b/src/outbound/direct_macos_batch_memory_tests.rs @@ -0,0 +1,426 @@ +use super::*; +use bytes::Bytes; +use std::{ + collections::VecDeque, + sync::{ + Mutex, + atomic::{AtomicUsize, Ordering}, + }, + task::Waker, +}; + +#[derive(Clone, Copy)] +enum Step { + Accept, + Pending, + Error(io::ErrorKind), + Short(usize), +} +#[derive(Default)] +struct Boundary { + steps: VecDeque, + attempts: Vec<(SocketAddr, usize, usize)>, + emitted: Vec, + waiter: Option, +} +fn packets(peer: SocketAddr) -> Vec { + (1..=4) + .map(|marker| Datagram { + remote: peer.into(), + payload: Bytes::from(vec![marker; 1200]), + sniffed_domain: None, + }) + .collect() +} +fn operation( + packets: Vec, + boundary: Arc>, +) -> crate::dispatch::OwnedDatagramBatchSend { + send_with(packets, move |cx, payload, peer| { + let mut boundary = boundary.lock().unwrap(); + boundary + .attempts + .push((peer, payload.as_ptr() as usize, payload.len())); + match boundary.steps.pop_front().unwrap_or(Step::Accept) { + Step::Accept => { + boundary.emitted.push(payload[0]); + Poll::Ready(Ok(payload.len())) + } + Step::Pending => { + boundary.waiter = Some(cx.waker().clone()); + Poll::Pending + } + Step::Error(kind) => Poll::Ready(Err(kind.into())), + Step::Short(length) => Poll::Ready(Ok(length)), + } + }) + .unwrap_or_else(|_| panic!("valid production-seam batch refused")) +} +fn poll(operation: &mut crate::dispatch::OwnedDatagramBatchSend) -> Poll> { + operation + .as_mut() + .poll(&mut Context::from_waker(Waker::noop())) +} + +#[test] +fn macos_public_send_memory_full_four_keep_whole_payloads_and_ipv6_scope() { + for peer in [ + "192.0.2.1:443".parse().unwrap(), + SocketAddr::V6(std::net::SocketAddrV6::new( + "fe80::1".parse().unwrap(), + 443, + 123, + 7, + )), + ] { + let packets = packets(peer); + let expected: Vec<_> = packets + .iter() + .map(|packet| (peer, packet.payload.as_ptr() as usize, packet.payload.len())) + .collect(); + let boundary = Arc::new(Mutex::new(Boundary::default())); + let mut operation = operation(packets, boundary.clone()); + assert!(matches!(poll(&mut operation), Poll::Ready(Ok(4)))); + drop(operation); + let state = boundary.lock().unwrap(); + assert_eq!(state.attempts, expected); + assert_eq!(state.emitted, [1, 2, 3, 4]); + } +} + +#[test] +fn macos_public_send_memory_zero_prefix_pending_keeps_waker_and_never_replays() { + let boundary = Arc::new(Mutex::new(Boundary { + steps: [Step::Pending, Step::Pending].into(), + ..Default::default() + })); + let mut operation = operation(packets("192.0.2.1:443".parse().unwrap()), boundary.clone()); + for _ in 0..2 { + assert!(poll(&mut operation).is_pending()); + let state = boundary.lock().unwrap(); + assert!(state.emitted.is_empty()); + assert!(state.waiter.is_some()); + state.waiter.as_ref().unwrap().wake_by_ref(); + } + assert!(matches!(poll(&mut operation), Poll::Ready(Ok(4)))); + drop(operation); + let state = boundary.lock().unwrap(); + assert_eq!(state.attempts.len(), 6); + assert_eq!(state.emitted, [1, 2, 3, 4]); +} + +#[test] +fn macos_public_send_memory_positive_prefix_returns_before_pending_and_preserves_suffix() { + for prefix in [1, 2] { + let mut packets = packets("192.0.2.1:443".parse().unwrap()); + let mut steps = VecDeque::new(); + steps.extend(std::iter::repeat_n(Step::Accept, prefix)); + steps.push_back(Step::Pending); + let boundary = Arc::new(Mutex::new(Boundary { + steps, + ..Default::default() + })); + let mut first = operation(packets.clone(), boundary.clone()); + assert!(matches!(poll(&mut first), Poll::Ready(Ok(actual)) if actual == prefix)); + drop(first); + assert_eq!(boundary.lock().unwrap().emitted.len(), prefix); + drop(packets.drain(..prefix)); + let mut suffix = operation(packets, boundary.clone()); + assert!(matches!(poll(&mut suffix), Poll::Ready(Ok(actual)) if actual == 4 - prefix)); + drop(suffix); + assert_eq!(boundary.lock().unwrap().emitted, [1, 2, 3, 4]); + } +} + +#[test] +fn macos_public_send_memory_fatal_or_short_after_a_prefix_never_replays_or_hides_error() { + for prefix in [0, 1, 2] { + for last in [ + Step::Error(io::ErrorKind::Interrupted), + Step::Error(io::ErrorKind::PermissionDenied), + Step::Error(io::ErrorKind::ConnectionReset), + Step::Short(0), + Step::Short(1199), + Step::Short(1201), + ] { + let mut steps = VecDeque::new(); + steps.extend(std::iter::repeat_n(Step::Accept, prefix)); + steps.push_back(last); + let boundary = Arc::new(Mutex::new(Boundary { + steps, + ..Default::default() + })); + let mut operation = + operation(packets("192.0.2.1:443".parse().unwrap()), boundary.clone()); + let Poll::Ready(Err(error)) = poll(&mut operation) else { + panic!("a real fatal/short boundary must remain a terminal error"); + }; + let expected = match last { + Step::Error(kind) => kind, + _ => io::ErrorKind::InvalidData, + }; + assert_eq!(error.kind(), expected); + drop(operation); + let state = boundary.lock().unwrap(); + assert_eq!(state.attempts.len(), prefix + 1); + assert_eq!(state.emitted.len(), prefix); + } + } +} + +struct CaptureLease(Arc); +impl Drop for CaptureLease { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::Relaxed); + } +} +#[test] +fn macos_public_send_memory_pending_drop_releases_owned_capture_without_more_io() { + let drops = Arc::new(AtomicUsize::new(0)); + let calls = Arc::new(AtomicUsize::new(0)); + let lease = CaptureLease(drops.clone()); + let observed_calls = calls.clone(); + let mut operation = send_with(packets("192.0.2.1:443".parse().unwrap()), move |_, _, _| { + let _held = &lease; + observed_calls.fetch_add(1, Ordering::Relaxed); + Poll::Pending + }) + .unwrap_or_else(|_| panic!("valid production-seam batch refused")); + assert_eq!(drops.load(Ordering::Relaxed), 0); + assert!(poll(&mut operation).is_pending()); + drop(operation); + assert_eq!(calls.load(Ordering::Relaxed), 1); + assert_eq!(drops.load(Ordering::Relaxed), 1); +} + +#[test] +fn macos_public_send_memory_invalid_admission_returns_untouched_packets_without_io() { + let peer = "192.0.2.1:443".parse().unwrap(); + let mut cases = vec![Vec::new(), packets(peer).into_iter().take(1).collect()]; + let mut mixed = packets(peer); + mixed[1].remote = "192.0.2.2:443".parse::().unwrap().into(); + cases.push(mixed); + let mut oversized = packets(peer); + oversized[0].payload = Bytes::from(vec![0; 8193]); + cases.push(oversized); + let mut too_many = packets(peer); + too_many.push(packets(peer).remove(0)); + cases.push(too_many); + let mut empty = packets(peer); + empty[0].payload = Bytes::new(); + cases.push(empty); + let mut sniffed = packets(peer); + sniffed[0].sniffed_domain = Some("invalid.example".into()); + cases.push(sniffed); + cases.push(packets("0.0.0.0:443".parse().unwrap())); + cases.push(packets("192.0.2.1:0".parse().unwrap())); + cases.push(packets("224.0.0.1:443".parse().unwrap())); + let calls = Arc::new(AtomicUsize::new(0)); + for batch in cases { + let expected: Vec<_> = batch + .iter() + .map(|packet| { + ( + packet.remote.clone(), + packet.payload.as_ptr(), + packet.payload.len(), + ) + }) + .collect(); + let observed = calls.clone(); + let Err(returned) = send_with(batch, move |_, _, _| { + observed.fetch_add(1, Ordering::Relaxed); + Poll::Ready(Ok(1200)) + }) else { + panic!("invalid batch reached a physical operation"); + }; + let actual: Vec<_> = returned + .iter() + .map(|packet| { + ( + packet.remote.clone(), + packet.payload.as_ptr(), + packet.payload.len(), + ) + }) + .collect(); + assert_eq!(actual, expected); + } + assert_eq!(calls.load(Ordering::Relaxed), 0); +} + +#[cfg(any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" +))] +fn connected_operation( + packets: Vec, + peer: SocketAddr, + boundary: Arc>, +) -> crate::dispatch::OwnedDatagramBatchSend { + send_connected_with(packets, peer, move |cx, payload| { + let mut boundary = boundary.lock().unwrap(); + boundary + .attempts + .push((peer, payload.as_ptr() as usize, payload.len())); + match boundary.steps.pop_front().unwrap_or(Step::Accept) { + Step::Accept => { + boundary.emitted.push(payload[0]); + Poll::Ready(Ok(payload.len())) + } + Step::Pending => { + boundary.waiter = Some(cx.waker().clone()); + Poll::Pending + } + Step::Error(kind) => Poll::Ready(Err(kind.into())), + Step::Short(length) => Poll::Ready(Ok(length)), + } + }) + .unwrap_or_else(|_| panic!("valid connected production batch refused")) +} + +#[cfg(any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" +))] +#[test] +fn macos_public_send_memory_connected_prefix_whole_payload_and_terminal_errors() { + for peer in [ + "192.0.2.1:443".parse().unwrap(), + SocketAddr::V6(std::net::SocketAddrV6::new( + "fe80::1".parse().unwrap(), + 443, + 123, + 7, + )), + ] { + for prefix in 0..4 { + for last in [ + Step::Pending, + Step::Error(io::ErrorKind::PermissionDenied), + Step::Short(1199), + ] { + let batch = packets(peer); + let expected: Vec<_> = batch + .iter() + .take(prefix + 1) + .map(|packet| (peer, packet.payload.as_ptr() as usize, packet.payload.len())) + .collect(); + let mut steps = VecDeque::new(); + steps.extend(std::iter::repeat_n(Step::Accept, prefix)); + steps.push_back(last); + let boundary = Arc::new(Mutex::new(Boundary { + steps, + ..Default::default() + })); + let mut operation = connected_operation(batch.clone(), peer, boundary.clone()); + match last { + Step::Pending if prefix == 0 => { + assert!(poll(&mut operation).is_pending()); + assert!(boundary.lock().unwrap().waiter.is_some()); + } + Step::Pending => assert!( + matches!(poll(&mut operation), Poll::Ready(Ok(actual)) if actual == prefix) + ), + Step::Error(kind) => assert!( + matches!(poll(&mut operation), Poll::Ready(Err(error)) if error.kind() == kind) + ), + Step::Short(_) => assert!( + matches!(poll(&mut operation), Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::InvalidData) + ), + Step::Accept => unreachable!(), + } + { + let state = boundary.lock().unwrap(); + assert_eq!(state.attempts, expected); + assert_eq!(state.emitted.len(), prefix); + } + drop(operation); + if matches!(last, Step::Pending) { + let mut suffix = batch; + drop(suffix.drain(..prefix)); + if suffix.len() == 1 { + let original_pointer = suffix[0].payload.as_ptr(); + let returned = send_connected_with(suffix, peer, |_, _| { + panic!( + "the generic owner must send a singleton through its original path" + ) + }) + .err() + .unwrap(); + assert_eq!(returned[0].payload.as_ptr(), original_pointer); + assert_eq!(boundary.lock().unwrap().emitted, [1, 2, 3]); + } else { + let mut operation = connected_operation(suffix, peer, boundary.clone()); + assert!( + matches!(poll(&mut operation), Poll::Ready(Ok(actual)) if actual == 4 - prefix) + ); + drop(operation); + assert_eq!(boundary.lock().unwrap().emitted, [1, 2, 3, 4]); + } + } + } + } + } +} + +#[cfg(any( + feature = "outbound-masque", + feature = "outbound-wireguard", + feature = "outbound-tuic" +))] +#[test] +fn macos_public_send_memory_connected_peer_rejection_and_pending_capture_drop() { + let peer = SocketAddr::V6(std::net::SocketAddrV6::new( + "fe80::1".parse().unwrap(), + 443, + 123, + 7, + )); + let calls = Arc::new(AtomicUsize::new(0)); + for other in [ + "192.0.2.1:443".parse().unwrap(), + SocketAddr::V6(std::net::SocketAddrV6::new( + "fe80::1".parse().unwrap(), + 443, + 123, + 8, + )), + SocketAddr::V6(std::net::SocketAddrV6::new( + "fe80::1".parse().unwrap(), + 443, + 124, + 7, + )), + ] { + let batch = packets(other); + let pointers: Vec<_> = batch.iter().map(|packet| packet.payload.as_ptr()).collect(); + let observed = calls.clone(); + let Err(returned) = send_connected_with(batch, peer, move |_, _| { + observed.fetch_add(1, Ordering::Relaxed); + Poll::Ready(Ok(1200)) + }) else { + panic!("mismatched connected peer reached IO"); + }; + assert_eq!( + returned + .iter() + .map(|packet| packet.payload.as_ptr()) + .collect::>(), + pointers + ); + } + assert_eq!(calls.load(Ordering::Relaxed), 0); + let drops = Arc::new(AtomicUsize::new(0)); + let held = CaptureLease(drops.clone()); + let mut operation = send_connected_with(packets(peer), peer, move |_, _| { + let _held = &held; + Poll::Pending + }) + .unwrap_or_else(|_| panic!("valid connected batch refused")); + assert!(poll(&mut operation).is_pending()); + drop(operation); + assert_eq!(drops.load(Ordering::Relaxed), 1); +} diff --git a/src/outbound/http.rs b/src/outbound/http.rs index 60a5ac9..706b8a3 100644 --- a/src/outbound/http.rs +++ b/src/outbound/http.rs @@ -18,6 +18,8 @@ pub struct HttpOutbound { tls: Option, headers: BTreeMap, authorization: Option, + #[cfg(feature = "inbound-http")] + http_reuse_security_static: bool, } impl HttpOutbound { pub(crate) fn with_shared_security( @@ -58,6 +60,13 @@ impl HttpOutbound { .auth .as_ref() .map(|auth| auth.authorization_header_value()), + #[cfg(feature = "inbound-http")] + http_reuse_security_static: config.tls.as_ref().is_none_or(|tls| { + tls.identity + .as_ref() + .is_none_or(|identity| identity.origin.is_none()) + && tls.ech.as_ref().is_none_or(|ech| !ech.is_dynamic()) + }), }) } } @@ -123,6 +132,11 @@ async fn handshake( } #[async_trait] impl OutboundConnector for HttpOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.http_reuse_security_static && self.upstream.permits_static_http_reuse(&self.server) + } + async fn connect_stream( &self, session: StreamSession, diff --git a/src/outbound/http_reuse_memory_tests.rs b/src/outbound/http_reuse_memory_tests.rs new file mode 100644 index 0000000..2d09e92 --- /dev/null +++ b/src/outbound/http_reuse_memory_tests.rs @@ -0,0 +1,878 @@ +//! Structural HTTP reuse proofs only: no socket, resolver, file or runtime. +use super::*; +use crate::config::{EgressOptions, IpVersion}; + +fn server() -> Destination { + Destination::Ip("192.0.2.10:8443".parse().unwrap()) +} + +fn endpoint() -> ResolvedEndpoint { + ResolvedEndpoint { + logical_host: "192.0.2.10".into(), + port: 8443, + addresses: vec!["192.0.2.10:8443".parse().unwrap()], + } +} + +struct Opaque; +#[async_trait] +impl OutboundConnector for Opaque { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("a structural proof must not open a stream") + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("a structural proof must not open a datagram path") + } +} + +#[test] +fn static_http_path_requires_exact_literal_endpoint() { + assert!( + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + } + .permits_static_http_reuse(&server()) + ); + assert!( + UpstreamPath::direct(endpoint(), Dialer::default()).permits_static_http_reuse(&server()) + ); + let domain = Destination::domain("proxy.invalid", 8443).unwrap(); + assert!( + !UpstreamPath::LazyDirect { + dialer: Dialer::default(), + } + .permits_static_http_reuse(&domain) + ); + for changed in 0..5 { + let mut endpoint = endpoint(); + match changed { + 0 => endpoint.logical_host = "proxy.invalid".into(), + 1 => endpoint.port += 1, + 2 => endpoint.addresses.clear(), + 3 => endpoint.addresses.push("192.0.2.11:8443".parse().unwrap()), + _ => endpoint.addresses[0] = "192.0.2.11:8443".parse().unwrap(), + } + assert!( + !UpstreamPath::direct(endpoint, Dialer::default()).permits_static_http_reuse(&server()) + ); + } + assert!(!Opaque.permits_http_tcp_reuse()); + assert!(!UpstreamPath::proxy(Arc::new(Opaque)).permits_static_http_reuse(&server())); +} + +struct MustNotProtect; +impl crate::dialer::SocketProtector for MustNotProtect { + fn protect(&self, _: i32) -> io::Result<()> { + panic!("a structural proof must not create a physical socket") + } +} + +#[test] +fn static_http_path_preserves_physical_restrictions_and_stop() { + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for dialer in [ + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + ] { + assert!( + !UpstreamPath::direct(endpoint(), dialer.clone()).permits_static_http_reuse(&server()) + ); + assert!(!UpstreamPath::LazyDirect { dialer }.permits_static_http_reuse(&server())); + } + let dialer = Dialer::default(); + let path = UpstreamPath::direct(endpoint(), dialer.clone()); + assert!(path.permits_static_http_reuse(&server())); + dialer.begin_shutdown(); + assert!(!path.permits_static_http_reuse(&server())); +} + +#[test] +fn static_http_path_never_samples_an_upstream_group() { + let selection = Arc::new(GroupSelection::new(0)); + let path = UpstreamPath::Group { + server: server(), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + }; + assert!(!path.permits_static_http_reuse(&server())); + selection.store(1, std::sync::atomic::Ordering::Release); + assert!(!path.permits_static_http_reuse(&server())); +} + +#[cfg(feature = "outbound-http")] +fn http(upstream: UpstreamPath, tls: bool) -> Arc { + use crate::{ + config::HttpOutboundConfig, outbound::http::HttpOutbound, security::SecurityContext, + }; + let config = HttpOutboundConfig { + address: "192.0.2.10".into(), + port: 8443, + tls: tls.then(|| crate::config::TlsConfig { + server_name: "proxy.invalid".into(), + alpn: vec![b"http/1.1".to_vec()], + tls13_only: false, + required_alpn: None, + ech: None, + client_fingerprint: None, + certificate: Default::default(), + identity: None, + }), + auth: None, + headers: Default::default(), + }; + Arc::new( + HttpOutbound::with_shared_security(&config, upstream, &SecurityContext::new(), 0, 8192) + .unwrap(), + ) +} + +#[cfg(feature = "outbound-http")] +#[test] +fn static_http_proxy_recursion_preserves_opaque_path_and_stop() { + let dialer = Dialer::default(); + let inner = http(UpstreamPath::direct(endpoint(), dialer.clone()), true); + let middle = http(UpstreamPath::proxy(inner.clone()), false); + let outer = http(UpstreamPath::proxy(middle), true); + assert!(outer.permits_http_tcp_reuse()); + assert!(ConnectorDispatcher::new(outer.clone()).permits_http_tcp_reuse()); + assert!( + IpVersionConnector { + inner: outer.clone(), + version: IpVersion::Dual, + } + .permits_http_tcp_reuse() + ); + for version in [ + IpVersion::Ipv4, + IpVersion::Ipv6, + IpVersion::Ipv4Prefer, + IpVersion::Ipv6Prefer, + ] { + assert!( + !IpVersionConnector { + inner: outer.clone(), + version, + } + .permits_http_tcp_reuse() + ); + } + assert!(!http(UpstreamPath::proxy(Arc::new(Opaque)), false).permits_http_tcp_reuse()); + let domain = Destination::domain("proxy.invalid", 8443).unwrap(); + assert!(!UpstreamPath::proxy(inner).permits_static_http_reuse(&domain)); + dialer.begin_shutdown(); + assert!(!outer.permits_http_tcp_reuse()); +} + +#[cfg(feature = "outbound-socks5")] +#[test] +fn static_socks5_plain_and_tls_share_the_connector_proof() { + use crate::{config::Socks5OutboundConfig, outbound::Socks5Outbound}; + for tls in [false, true] { + let config = Socks5OutboundConfig { + address: "192.0.2.10".into(), + port: 8443, + username: Some("memory-user".into()), + password: Some("memory-password".into()), + tls: tls.then(Default::default), + }; + let dialer = Dialer::default(); + let outbound = Socks5Outbound::new_with_path( + &config, + UpstreamPath::direct(endpoint(), dialer.clone()), + ) + .unwrap(); + assert!(OutboundConnector::permits_http_tcp_reuse(&outbound)); + assert!(Dispatcher::permits_http_tcp_reuse(&outbound)); + dialer.begin_shutdown(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + } +} + +#[cfg(feature = "outbound-shadowsocks")] +#[test] +fn static_shadowsocks_all_ciphers_preserve_obfs_path_and_stop_guards() { + use crate::{ + config::{ShadowsocksCipher, ShadowsocksOutboundConfig, ShadowsocksPlugin}, + outbound::ShadowsocksOutbound, + }; + use base64::{Engine as _, engine::general_purpose::STANDARD}; + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let mut config = ShadowsocksOutboundConfig { + address: "192.0.2.10".into(), + port: 8443, + cipher, + password: STANDARD.encode(vec![7; cipher.key_len()]), + plugin: None, + udp_over_tcp: false, + }; + let dialer = Dialer::default(); + let outbound = ShadowsocksOutbound::new_with_path( + &config, + UpstreamPath::direct(endpoint(), dialer.clone()), + ) + .unwrap(); + assert!(OutboundConnector::permits_http_tcp_reuse(&outbound)); + assert!(Dispatcher::permits_http_tcp_reuse(&outbound)); + config.plugin = Some(ShadowsocksPlugin::Obfs { + tls: false, + host: "cover.invalid".into(), + }); + let plugin = ShadowsocksOutbound::new_with_path( + &config, + UpstreamPath::direct(endpoint(), Dialer::default()), + ) + .unwrap(); + assert!(OutboundConnector::permits_http_tcp_reuse(&plugin)); + assert!(Dispatcher::permits_http_tcp_reuse(&plugin)); + OutboundConnector::begin_shutdown(&plugin); + assert!(!OutboundConnector::permits_http_tcp_reuse(&plugin)); + dialer.begin_shutdown(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + } +} + +#[test] +fn macos_mptcp_preference_only_removes_its_own_static_path_restriction() { + let dialer = Dialer::default().with_mptcp(true); + assert_eq!( + UpstreamPath::direct(endpoint(), dialer.clone()).permits_static_http_reuse(&server()), + cfg!(target_os = "macos") + ); + assert_eq!( + UpstreamPath::LazyDirect { dialer }.permits_static_http_reuse(&server()), + cfg!(target_os = "macos") + ); + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for restricted in [ + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + ] { + let dialer = restricted.with_mptcp(true); + assert!( + !UpstreamPath::direct(endpoint(), dialer.clone()).permits_static_http_reuse(&server()) + ); + assert!(!UpstreamPath::LazyDirect { dialer }.permits_static_http_reuse(&server())); + } +} + +#[cfg(all(feature = "outbound-shadowsocks", feature = "shadow-tls-v3"))] +#[test] +fn static_ss2022_actual_shadowtls_v3_plugin_qualifies_and_stop_revokes_without_stopping_dependency() +{ + use crate::{ + config::{ + ShadowTlsConfig, ShadowsocksCipher, ShadowsocksOutboundConfig, ShadowsocksPlugin, + }, + outbound::ShadowsocksOutbound, + }; + use base64::{Engine as _, engine::general_purpose::STANDARD}; + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let config = ShadowsocksOutboundConfig { + address: "192.0.2.10".into(), + port: 8443, + cipher, + password: STANDARD.encode(vec![7; cipher.key_len()]), + plugin: Some(ShadowsocksPlugin::ShadowTls(ShadowTlsConfig { + server_name: "cover.invalid".into(), + password: "synthetic-relay".into(), + alpn: vec![], + required_alpn: None, + identity: None, + certificate: Default::default(), + client_fingerprint: None, + })), + udp_over_tcp: false, + }; + let path = UpstreamPath::direct(endpoint(), Dialer::default()); + let outbound = ShadowsocksOutbound::new_with_path(&config, path.clone()).unwrap(); + let direct = OutboundConnector::permits_http_tcp_reuse(&outbound); + let dispatch = Dispatcher::permits_http_tcp_reuse(&outbound); + OutboundConnector::begin_shutdown(&outbound); + let revoked = !OutboundConnector::permits_http_tcp_reuse(&outbound) + && !Dispatcher::permits_http_tcp_reuse(&outbound); + let dependency_open = path.permits_static_http_reuse(&server()); + drop(outbound); + drop(path); + // Actual construction and post-stop/dependency controls precede the + // desired-positive assertion. This is policy qualification, not IO. + assert!(revoked && dependency_open); + assert!( + direct && dispatch, + "actual fixed ShadowTLS-v3 plugin was excluded" + ); + } +} + +#[cfg(feature = "outbound-shadowsocks")] +#[test] +fn static_ss2022_obfs_actual_config_requires_owned_http_reuse() { + use crate::{ + config::{Config, ProxyProtocol, ShadowsocksCipher}, + outbound::ShadowsocksOutbound, + }; + use base64::{Engine as _, engine::general_purpose::STANDARD}; + + let mut qualifications = Vec::new(); + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + for mode in ["http", "tls"] { + let value = serde_json::json!({ + "proxies": [{ + "name": "obfs", "type": "ss", "server": "192.0.2.10", "port": 8443, + "cipher": cipher.as_str(), "password": STANDARD.encode(vec![7; cipher.key_len()]), + "plugin": "obfs", "plugin-opts": {"mode": mode, "host": "cover.invalid"} + }], + "rules": ["MATCH,obfs"] + }); + let parsed = Config::parse_yaml(&serde_json::to_vec(&value).unwrap()).unwrap(); + let ProxyProtocol::Shadowsocks(config) = &parsed.proxies[0].protocol else { + panic!("real SS configuration expected") + }; + let path = UpstreamPath::direct(endpoint(), Dialer::default()); + let outbound = ShadowsocksOutbound::new_with_path(config, path.clone()).unwrap(); + qualifications.push(( + cipher, + mode, + OutboundConnector::permits_http_tcp_reuse(&outbound), + Dispatcher::permits_http_tcp_reuse(&outbound), + )); + OutboundConnector::begin_shutdown(&outbound); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + assert!(!Dispatcher::permits_http_tcp_reuse(&outbound)); + assert!( + path.permits_static_http_reuse(&server()), + "node Stop must not stop its dependency" + ); + drop(outbound); + drop(path); + + let mut domain = config.clone(); + domain.address = "proxy.invalid".into(); + let outbound = ShadowsocksOutbound::new_with_path( + &domain, + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }, + ) + .unwrap(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + drop(outbound); + + let mut mismatch = endpoint(); + mismatch.addresses.push("192.0.2.11:8443".parse().unwrap()); + let group = UpstreamPath::Group { + server: server(), + group: Arc::new(SelectUpstream::new( + Arc::new(GroupSelection::new(0)), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + }; + for path in [ + UpstreamPath::direct(mismatch, Dialer::default()), + UpstreamPath::proxy(Arc::new(Opaque)), + group, + ] { + let outbound = ShadowsocksOutbound::new_with_path(config, path).unwrap(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + } + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for dialer in [ + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + ] { + let outbound = ShadowsocksOutbound::new_with_path( + config, + UpstreamPath::direct(endpoint(), dialer), + ) + .unwrap(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + } + let dialer = Dialer::default(); + let outbound = ShadowsocksOutbound::new_with_path( + config, + UpstreamPath::direct(endpoint(), dialer.clone()), + ) + .unwrap(); + dialer.begin_shutdown(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + drop(outbound); + } + } + // All real constructions, negative controls and Stop/dependency checks run + // before the expected RED on the old blanket plugin exclusion. + assert_eq!(qualifications.len(), 6); + assert!( + qualifications + .iter() + .all(|(_, _, connector, dispatcher)| *connector && *dispatcher), + "actual Config/SS/Dispatcher obfs qualification: {qualifications:?}", + ); +} + +#[cfg(feature = "outbound-shadowsocks")] +fn ss2022_v2ray_mux_memory_config( + cipher: crate::config::ShadowsocksCipher, + plugin: &str, + options: serde_json::Value, +) -> crate::config::ShadowsocksOutboundConfig { + use crate::config::{Config, ProxyProtocol}; + use base64::{Engine as _, engine::general_purpose::STANDARD}; + let input = serde_json::json!({ + "proxies": [{ + "name": "mux", "type": "ss", "server": "192.0.2.10", "port": 8443, + "cipher": cipher.as_str(), "password": STANDARD.encode(vec![7; cipher.key_len()]), + "plugin": plugin, "plugin-opts": options + }], + "rules": ["MATCH,mux"] + }); + let parsed = Config::parse_yaml(&serde_json::to_vec(&input).unwrap()).unwrap(); + let ProxyProtocol::Shadowsocks(config) = &parsed.proxies[0].protocol else { + panic!("real SS configuration expected") + }; + config.clone() +} + +#[cfg(feature = "outbound-shadowsocks")] +#[test] +fn static_ss2022_v2ray_mux_plain_actual_config_requires_owned_http_reuse() { + use crate::{config::ShadowsocksCipher, outbound::ShadowsocksOutbound}; + let mut qualifications = Vec::new(); + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let config = ss2022_v2ray_mux_memory_config( + cipher, + "v2ray-plugin", + serde_json::json!({ + "mode": "websocket", "host": "cover.invalid", "path": "/mux", + "headers": {"X-Memory-Test": "fixed"}, "mux": true, "tls": false + }), + ); + let path = UpstreamPath::direct(endpoint(), Dialer::default()); + let outbound = ShadowsocksOutbound::new_with_path(&config, path.clone()).unwrap(); + qualifications.push(( + cipher, + OutboundConnector::permits_http_tcp_reuse(&outbound), + Dispatcher::permits_http_tcp_reuse(&outbound), + )); + OutboundConnector::begin_shutdown(&outbound); + assert!(!OutboundConnector::permits_http_tcp_reuse(&outbound)); + assert!(!Dispatcher::permits_http_tcp_reuse(&outbound)); + assert!( + path.permits_static_http_reuse(&server()), + "node Stop stopped its dependency" + ); + drop(outbound); + drop(path); + + let denied = |config: &crate::config::ShadowsocksOutboundConfig, path: UpstreamPath| { + let node = ShadowsocksOutbound::new_with_path(config, path).unwrap(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&node)); + assert!(!Dispatcher::permits_http_tcp_reuse(&node)); + }; + let mut domain = config.clone(); + domain.address = "proxy.invalid".into(); + denied( + &domain, + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }, + ); + let mut mismatch = endpoint(); + mismatch.addresses.push("192.0.2.11:8443".parse().unwrap()); + denied(&config, UpstreamPath::direct(mismatch, Dialer::default())); + denied(&config, UpstreamPath::proxy(Arc::new(Opaque))); + let selection = Arc::new(GroupSelection::new(0)); + let group = UpstreamPath::Group { + server: server(), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + }; + denied(&config, group.clone()); + selection.store(1, std::sync::atomic::Ordering::Release); + denied(&config, group); + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for dialer in [ + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + ] { + denied(&config, UpstreamPath::direct(endpoint(), dialer)); + } + let dialer = Dialer::default(); + let node = ShadowsocksOutbound::new_with_path( + &config, + UpstreamPath::direct(endpoint(), dialer.clone()), + ) + .unwrap(); + dialer.begin_shutdown(); + assert!(!OutboundConnector::permits_http_tcp_reuse(&node)); + assert!(!Dispatcher::permits_http_tcp_reuse(&node)); + } + // Every actual construction and negative/Stop control runs before the + // desired positive assertion; constructor/visibility failures are not RED. + assert_eq!(qualifications.len(), 3); + assert!( + qualifications + .iter() + .all(|(_, connector, dispatcher)| *connector && *dispatcher), + "actual Config/SS/Dispatcher plain v2ray mux qualification: {qualifications:?}" + ); +} + +#[cfg(feature = "outbound-shadowsocks")] +#[test] +fn static_ss2022_v2ray_mux_unqualified_variants_keep_one_shot() { + use crate::{config::ShadowsocksCipher, outbound::ShadowsocksOutbound}; + let mut checked = 0; + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + for (plugin, options) in [ + ( + "v2ray-plugin", + serde_json::json!({"mode":"websocket", "mux":true, "tls":true}), + ), + ( + "gost-plugin", + serde_json::json!({"mode":"websocket", "mux":true, "tls":false}), + ), + ( + "v2ray-plugin", + serde_json::json!({"mode":"websocket", "mux":false, "tls":false}), + ), + ( + "v2ray-plugin", + serde_json::json!({"mode":"websocket", "mux":true, + "v2ray-http-upgrade":true}), + ), + ( + "v2ray-plugin", + serde_json::json!({"mode":"websocket", "mux":true, + "v2ray-http-upgrade":true, "v2ray-http-upgrade-fast-open":true}), + ), + ] { + let config = ss2022_v2ray_mux_memory_config(cipher, plugin, options); + let node = ShadowsocksOutbound::new_with_path( + &config, + UpstreamPath::direct(endpoint(), Dialer::default()), + ) + .unwrap(); + assert!( + !OutboundConnector::permits_http_tcp_reuse(&node), + "{cipher:?}/{plugin}" + ); + assert!( + !Dispatcher::permits_http_tcp_reuse(&node), + "{cipher:?}/{plugin}" + ); + checked += 1; + } + } + assert_eq!(checked, 15); +} + +#[cfg(feature = "outbound-shadowsocks")] +#[test] +fn static_ss2022_v2ray_mux_actual_early_data_path_keeps_one_shot() { + use crate::{ + config::{ShadowsocksCipher, ShadowsocksPlugin, StreamTransport}, + outbound::ShadowsocksOutbound, + }; + let mut observations = Vec::new(); + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + let config = ss2022_v2ray_mux_memory_config( + cipher, + "v2ray-plugin", + serde_json::json!({"mode":"websocket", "mux":true, "tls":false, + "path":"/memory-mux/?ed=128"}), + ); + assert!( + matches!( + config.plugin.as_ref(), + Some(ShadowsocksPlugin::WebSocket { + transport: StreamTransport::WebSocket { + max_early_data: 128, + .. + }, + .. + }) + ), + "actual Config must normalize early data instead of rejecting it" + ); + let node = ShadowsocksOutbound::new_with_path( + &config, + UpstreamPath::direct(endpoint(), Dialer::default()), + ) + .unwrap(); + observations.push(( + cipher, + OutboundConnector::permits_http_tcp_reuse(&node), + Dispatcher::permits_http_tcp_reuse(&node), + )); + } + assert!( + observations + .iter() + .all(|(_, connector, dispatcher)| !connector && !dispatcher), + "unproven early-data factory must remain one-shot: {observations:?}" + ); +} + +#[cfg(feature = "outbound-vmess")] +fn vmess_http_cover_memory_config( + cipher: &str, + options: serde_json::Value, + tls: bool, +) -> crate::config::VmessOutboundConfig { + use crate::config::{Config, ProxyProtocol}; + let value = serde_json::json!({ + "proxies": [{"name": "cover", "type": "vmess", "server": "192.0.2.10", + "port": 8443, "uuid": "07070707-0707-0707-0707-070707070707", + "cipher": cipher, "network": "http", "tls": tls, "http-opts": options}], + "rules": ["MATCH,cover"] + }); + let mut parsed = Config::parse_yaml(&serde_json::to_vec(&value).unwrap()).unwrap(); + let ProxyProtocol::Vmess(config) = parsed.proxies.remove(0).protocol else { + panic!("actual normalized VMess configuration expected") + }; + config +} + +#[cfg(feature = "outbound-vmess")] +fn vmess_http_cover_memory_node( + config: &crate::config::VmessOutboundConfig, + path: UpstreamPath, +) -> Arc { + Arc::new(crate::outbound::vmess::VmessOutbound::new_with_path(config, path).unwrap()) +} + +#[cfg(feature = "outbound-vmess")] +fn vmess_http_cover_memory_dispatch(node: &Arc) -> bool { + Dispatcher::permits_http_tcp_reuse(&ConnectorDispatcher::new(node.clone())) +} + +#[cfg(feature = "outbound-vmess")] +#[test] +fn static_vmess_http_cover_plain_singleton_actual_config_requires_reuse() { + use crate::config::VmessTransport; + let mut qualifications = Vec::new(); + for cipher in ["auto", "none", "aes-128-gcm", "chacha20-poly1305"] { + for headers in [ + serde_json::json!({}), + serde_json::json!({ + "Host": ["cover.memory.invalid"], "X-Memory": ["fixed"] + }), + ] { + let config = vmess_http_cover_memory_config( + cipher, + serde_json::json!({"method":"GET", "path":["/memory-cover"], "headers": headers}), + false, + ); + let VmessTransport::Http { + method, + uris, + headers, + } = &config.transport + else { + panic!("normalization must produce real HTTP cover") + }; + assert_eq!(method, "GET"); + assert_eq!(uris, &["http://192.0.2.10:8443/memory-cover".to_owned()]); + assert!(headers.values().all(|values| values.len() == 1)); + assert!(matches!( + &config.security, + crate::config::SecurityConfig::None + )); + let path = UpstreamPath::direct(endpoint(), Dialer::default()); + let node = vmess_http_cover_memory_node(&config, path.clone()); + qualifications.push(( + cipher, + headers.is_empty(), + OutboundConnector::permits_http_tcp_reuse(node.as_ref()), + vmess_http_cover_memory_dispatch(&node), + )); + OutboundConnector::begin_shutdown(node.as_ref()); + assert!(!OutboundConnector::permits_http_tcp_reuse(node.as_ref())); + assert!(!vmess_http_cover_memory_dispatch(&node)); + assert!( + path.permits_static_http_reuse(&server()), + "node Stop must leave dependency open" + ); + drop(node); + } + } + // Collect every actual construction and run Stop controls before the + // desired-positive assertion. A parser/build error is not the intended RED. + assert_eq!(qualifications.len(), 8); + assert!( + qualifications + .iter() + .all(|(_, _, connector, dispatcher)| *connector && *dispatcher), + "plain singleton actual Config/VMess/Dispatcher qualifications: {qualifications:?}" + ); +} + +#[cfg(feature = "outbound-vmess")] +#[test] +fn static_vmess_http_cover_keeps_tls_choice_and_complete_path_exclusions() { + use crate::config::VmessTransport; + let fixed = + serde_json::json!({"path":["/memory-cover"], "headers":{"Host":["cover.memory.invalid"]}}); + let config = vmess_http_cover_memory_config("aes-128-gcm", fixed.clone(), false); + // Existing positive path control must not depend on the new permission. + let mut tcp = config.clone(); + tcp.transport = VmessTransport::Tcp; + let control = + vmess_http_cover_memory_node(&tcp, UpstreamPath::direct(endpoint(), Dialer::default())); + assert!(OutboundConnector::permits_http_tcp_reuse(control.as_ref())); + assert!(vmess_http_cover_memory_dispatch(&control)); + drop(control); + for (tls, options) in [ + (true, fixed), + ( + false, + serde_json::json!({"path":["/one","/two"], "headers":{"Host":["cover.memory.invalid"]}}), + ), + ( + false, + serde_json::json!({"path":["/one"], "headers":{"Host":["one.memory.invalid","two.memory.invalid"]}}), + ), + ( + false, + serde_json::json!({"path":["/one"], "headers":{"Host":["cover.memory.invalid"],"X-Memory":["one","two"]}}), + ), + ] { + let config = vmess_http_cover_memory_config("aes-128-gcm", options, tls); + let node = vmess_http_cover_memory_node( + &config, + UpstreamPath::direct(endpoint(), Dialer::default()), + ); + assert!(!OutboundConnector::permits_http_tcp_reuse(node.as_ref())); + assert!(!vmess_http_cover_memory_dispatch(&node)); + } + for changed in 0..5 { + let mut mismatch = endpoint(); + match changed { + 0 => mismatch.logical_host = "proxy.memory.invalid".into(), + 1 => mismatch.port += 1, + 2 => mismatch.addresses.clear(), + 3 => mismatch.addresses.push("192.0.2.11:8443".parse().unwrap()), + _ => mismatch.addresses[0] = "192.0.2.11:8443".parse().unwrap(), + } + let node = vmess_http_cover_memory_node( + &config, + UpstreamPath::direct(mismatch, Dialer::default()), + ); + assert!(!OutboundConnector::permits_http_tcp_reuse(node.as_ref())); + assert!(!vmess_http_cover_memory_dispatch(&node)); + } + let group = UpstreamPath::Group { + server: server(), + group: Arc::new(SelectUpstream::new( + Arc::new(GroupSelection::new(0)), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + }; + for path in [group, UpstreamPath::proxy(Arc::new(Opaque))] { + let node = vmess_http_cover_memory_node(&config, path); + assert!(!OutboundConnector::permits_http_tcp_reuse(node.as_ref())); + assert!(!vmess_http_cover_memory_dispatch(&node)); + } + let mut domain = config.clone(); + domain.address = "proxy.memory.invalid".into(); + let node = vmess_http_cover_memory_node( + &domain, + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }, + ); + assert!(!OutboundConnector::permits_http_tcp_reuse(node.as_ref())); + assert!(!vmess_http_cover_memory_dispatch(&node)); + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for dialer in [ + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + ] { + let node = vmess_http_cover_memory_node(&config, UpstreamPath::direct(endpoint(), dialer)); + assert!(!OutboundConnector::permits_http_tcp_reuse(node.as_ref())); + assert!(!vmess_http_cover_memory_dispatch(&node)); + } + let dialer = Dialer::default(); + let node = + vmess_http_cover_memory_node(&config, UpstreamPath::direct(endpoint(), dialer.clone())); + dialer.begin_shutdown(); + assert!(!OutboundConnector::permits_http_tcp_reuse(node.as_ref())); + assert!(!vmess_http_cover_memory_dispatch(&node)); +} diff --git a/src/outbound/hysteria2/outbound.rs b/src/outbound/hysteria2/outbound.rs index d6b138b..abefb1c 100644 --- a/src/outbound/hysteria2/outbound.rs +++ b/src/outbound/hysteria2/outbound.rs @@ -332,6 +332,15 @@ impl Hysteria2Outbound { #[async_trait] impl OutboundConnector for Hysteria2Outbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + !self.cancel.is_cancelled() + && self.config.hopping.is_none() + && self.config.realm.is_none() + && self.tls.permits_static_http_reuse() + && self.upstream.permits_static_direct_http_reuse(&self.server) + } + async fn connect_stream( &self, session: StreamSession, diff --git a/src/outbound/hysteria2_http_reuse_memory_tests.rs b/src/outbound/hysteria2_http_reuse_memory_tests.rs new file mode 100644 index 0000000..f530c91 --- /dev/null +++ b/src/outbound/hysteria2_http_reuse_memory_tests.rs @@ -0,0 +1,240 @@ +//! Construct production Hysteria2 outbounds and query proofs without opening IO. +//! Synthetic PEM is generated in memory; no socket, resolver or identity file. +use super::*; +use crate::config::{Config, EgressOptions, IpVersion}; + +fn server() -> Destination { + Destination::Ip("192.0.2.10:443".parse().unwrap()) +} + +fn endpoint() -> ResolvedEndpoint { + ResolvedEndpoint { + logical_host: "192.0.2.10".into(), + port: 443, + addresses: vec!["192.0.2.10:443".parse().unwrap()], + } +} + +fn direct() -> UpstreamPath { + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + } +} + +// A positive TCP capability deliberately does not prove this connector's UDP +// relay. Any attempted IO makes the structural fixture fail immediately. +struct TcpOnly; +#[async_trait] +impl OutboundConnector for TcpOnly { + fn permits_http_tcp_reuse(&self) -> bool { + true + } + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("a structural query must not open a stream") + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("a TCP proof must not authorize a UDP carrier") + } +} + +struct UnknownUpstream; +#[async_trait] +impl OutboundConnector for UnknownUpstream { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("a static query must not invoke an unknown stream connector") + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("a static query must not invoke an unknown datagram connector") + } +} + +fn group() -> UpstreamPath { + UpstreamPath::Group { + server: server(), + group: Arc::new(SelectUpstream::new( + Arc::new(GroupSelection::new(0)), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + } +} + +#[test] +fn static_direct_http_carrier_requires_the_exact_literal_physical_endpoint() { + assert!(direct().permits_static_direct_http_reuse(&server())); + assert!( + UpstreamPath::direct(endpoint(), Dialer::default()) + .permits_static_direct_http_reuse(&server()) + ); + assert!( + !direct() + .permits_static_direct_http_reuse(&Destination::domain("quic.invalid", 443).unwrap()) + ); + for changed in 0..5 { + let mut peer = endpoint(); + match changed { + 0 => peer.logical_host = "quic.invalid".into(), + 1 => peer.port += 1, + 2 => peer.addresses.clear(), + 3 => peer.addresses.push("192.0.2.11:443".parse().unwrap()), + _ => peer.addresses[0] = "192.0.2.11:443".parse().unwrap(), + } + assert!( + !UpstreamPath::direct(peer, Dialer::default()) + .permits_static_direct_http_reuse(&server()) + ); + } + let proxy = UpstreamPath::proxy(Arc::new(TcpOnly)); + assert!(proxy.permits_static_http_reuse(&server())); + assert!(!proxy.permits_static_direct_http_reuse(&server())); + assert!(!group().permits_static_direct_http_reuse(&server())); +} + +struct MustNotProtect; +impl crate::dialer::SocketProtector for MustNotProtect { + fn protect(&self, _: i32) -> io::Result<()> { + panic!("a structural query must not allocate a physical socket") + } +} + +#[test] +fn static_direct_http_carrier_preserves_dialer_restrictions_and_stop() { + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for dialer in [ + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + ] { + assert!( + !UpstreamPath::direct(endpoint(), dialer.clone()) + .permits_static_direct_http_reuse(&server()) + ); + assert!(!UpstreamPath::LazyDirect { dialer }.permits_static_direct_http_reuse(&server())); + } + let dialer = Dialer::default(); + let path = UpstreamPath::direct(endpoint(), dialer.clone()); + assert!(path.permits_static_direct_http_reuse(&server())); + dialer.begin_shutdown(); + assert!(!path.permits_static_direct_http_reuse(&server())); +} + +fn inline_identity() -> crate::config::TlsIdentityPem { + use base64::{Engine as _, engine::general_purpose::STANDARD}; + let generated = + rcgen::generate_simple_self_signed(vec!["memory-client.invalid".into()]).unwrap(); + crate::config::TlsIdentityPem { + certificate: format!( + "-----BEGIN CERTIFICATE-----\n{}\n-----END CERTIFICATE-----\n", + STANDARD.encode(generated.cert.der()) + ), + private_key: format!( + "-----BEGIN PRIVATE KEY-----\n{}\n-----END PRIVATE KEY-----\n", + STANDARD.encode(generated.signing_key.serialize_der()) + ), + origin: None, + } +} + +#[cfg(feature = "outbound-hysteria2")] +fn hysteria2_config(fields: &str) -> crate::config::Hysteria2OutboundConfig { + let config = Config::parse_yaml( + format!( + "proxies:\n - name: quic\n type: hysteria2\n server: 192.0.2.10\n port: 443\n password: synthetic\n sni: quic.invalid\n{fields}" + ) + .as_bytes(), + ) + .unwrap(); + let crate::config::ProxyProtocol::Hysteria2(config) = &config.proxies[0].protocol else { + panic!("Hysteria2 fixture configuration") + }; + config.as_ref().clone() +} + +#[cfg(feature = "outbound-hysteria2")] +fn hysteria2( + config: &crate::config::Hysteria2OutboundConfig, + upstream: UpstreamPath, +) -> super::super::hysteria2::Hysteria2Outbound { + super::super::hysteria2::Hysteria2Outbound::new_with_path(config, upstream).unwrap() +} + +#[cfg(feature = "outbound-hysteria2")] +#[test] +fn hysteria2_static_http_reuse_uses_the_real_constructor_and_node_stop() { + for fields in [ + "", + " up: 2000\n down: 2000\n", + " up: 2000\n down: 2000\n obfs: salamander\n obfs-password: synthetic-obfs\n", + ] { + let config = hysteria2_config(fields); + for upstream in [ + direct(), + UpstreamPath::direct(endpoint(), Dialer::default()), + ] { + let outbound = hysteria2(&config, upstream); + assert!(outbound.permits_http_tcp_reuse()); + outbound.begin_shutdown(); + assert!(!outbound.permits_http_tcp_reuse()); + } + } + let mut config = hysteria2_config(""); + config.tls.identity = Some(inline_identity()); + assert!(hysteria2(&config, direct()).permits_http_tcp_reuse()); +} + +#[cfg(feature = "outbound-hysteria2")] +#[test] +fn hysteria2_static_http_reuse_rejects_dynamic_discovery_and_dependencies() { + for fields in [ + " ports: '443,8443'\n", + " realm-opts: {enable: true, server-url: 'http://control.invalid', realm-id: synthetic, stun-servers: ['192.0.2.30:3478']}\n", + " ech-opts: {enable: true}\n", + ] { + assert!(!hysteria2(&hysteria2_config(fields), direct()).permits_http_tcp_reuse()); + } + let mut domain = hysteria2_config(""); + domain.address = "quic.invalid".into(); + assert!(!hysteria2(&domain, direct()).permits_http_tcp_reuse()); + let config = hysteria2_config(""); + assert!(!UnknownUpstream.permits_http_tcp_reuse()); + for upstream in [ + UpstreamPath::proxy(Arc::new(TcpOnly)), + UpstreamPath::proxy(Arc::new(UnknownUpstream)), + group(), + ] { + assert!(!hysteria2(&config, upstream).permits_http_tcp_reuse()); + } + let dialer = Dialer::default(); + let outbound = hysteria2( + &config, + UpstreamPath::LazyDirect { + dialer: dialer.clone(), + }, + ); + assert!(outbound.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + assert!(!outbound.permits_http_tcp_reuse()); +} diff --git a/src/outbound/masque/http_reuse_memory_tests.rs b/src/outbound/masque/http_reuse_memory_tests.rs new file mode 100644 index 0000000..d88e0b6 --- /dev/null +++ b/src/outbound/masque/http_reuse_memory_tests.rs @@ -0,0 +1,314 @@ +//! Real MASQUE constructor proofs only; never starts an IP engine or carrier. +use super::*; +use crate::{ + config::Config, + dialer::{Dialer, ResolvedEndpoint, SocketProtector}, + outbound::{SelectUpstream, SelectUpstreamMember}, + routing::GroupSelection, +}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; + +fn config(network: MasqueNetwork) -> MasqueOutboundConfig { + let group = boring::ec::EcGroup::from_curve_name(boring::nid::Nid::X9_62_PRIME256V1).unwrap(); + let client = boring::ec::EcKey::generate(&group).unwrap(); + let peer = + boring::pkey::PKey::from_ec_key(boring::ec::EcKey::generate(&group).unwrap()).unwrap(); + let parsed = Config::parse_yaml( + &serde_json::to_vec(&serde_json::json!({ + "proxies": [{ + "name": "memory", "type": "masque", "server": "192.0.2.10", "port": 443, + "private-key": STANDARD.encode(client.private_key_to_der().unwrap()), + "public-key": STANDARD.encode(peer.public_key_to_der().unwrap()), + "sni": "proxy.memory.invalid", "ip": "192.0.2.2", "udp": true, + "uri": "https://tunnel.memory.invalid/connection?policy=fixed", + "remote-dns-resolve": true, "dns": ["tcp://192.0.2.53"], + "network": match network { + MasqueNetwork::H2 => "h2", + MasqueNetwork::Quic => "quic", + MasqueNetwork::H3L4Proxy => "h3-l4proxy", + } + }] + })) + .unwrap(), + ) + .unwrap(); + let crate::config::ProxyProtocol::Masque(config) = &parsed.proxies[0].protocol else { + panic!("MASQUE memory configuration") + }; + config.clone() +} + +fn direct(dialer: Dialer) -> UpstreamPath { + UpstreamPath::LazyDirect { dialer } +} + +fn node(config: &MasqueOutboundConfig, path: UpstreamPath) -> MasqueOutbound { + MasqueOutbound::with_shared_security(config, path, &SecurityContext::new()).unwrap() +} + +fn modes() -> [MasqueNetwork; 3] { + [ + MasqueNetwork::H2, + MasqueNetwork::Quic, + MasqueNetwork::H3L4Proxy, + ] +} + +#[test] +fn masque_static_http_reuse_keeps_parsed_identity_and_frozen_config() { + for network in modes() { + let mut config = config(network); + let expected_uri = config.uri.clone(); + let expected_sni = config.server_name.clone(); + let expected_dns = config.dns.clone(); + let expected_prefixes = config.local_prefixes; + let expected_skip = config.skip_cert_verify; + let outbound = node(&config, direct(Dialer::default())); + assert!(outbound.current.try_lock().unwrap().is_none()); + assert!(outbound.remote.get().is_none()); + config.private_key.clear(); + config.public_key.clear(); + config.uri = "https://changed.memory.invalid/path".into(); + config.server_name = "changed.memory.invalid".into(); + config.local_prefixes = [None, None]; + config.remote_dns_resolve = false; + config.dns.clear(); + config.skip_cert_verify = !expected_skip; + assert_eq!(outbound.config.uri, expected_uri); + assert_eq!(outbound.connection.server_name, expected_sni); + assert_eq!(outbound.config.dns, expected_dns); + assert_eq!(outbound.config.local_prefixes, expected_prefixes); + assert_eq!(outbound.config.skip_cert_verify, expected_skip); + assert!(outbound.config.remote_dns_resolve); + assert!(outbound.connection.tls.config(false).is_ok()); + assert!(outbound.connection.tls.quiche_config(expected_sni).is_ok()); + assert!(outbound.permits_http_tcp_reuse()); + assert!( + MasqueOutbound::with_shared_security( + &config, + direct(Dialer::default()), + &SecurityContext::new(), + ) + .is_err() + ); + outbound.begin_shutdown(); + assert!(!outbound.permits_http_tcp_reuse()); + assert!(outbound.current.try_lock().unwrap().is_none()); + assert!(outbound.remote.get().is_none()); + } +} + +#[test] +fn masque_static_http_reuse_rejects_domains_and_nonexact_prepared_endpoints() { + for network in modes() { + let mut config = config(network); + config.address = "proxy.memory.invalid".into(); + let outbound = node(&config, direct(Dialer::default())); + assert!(!outbound.permits_http_tcp_reuse()); + config.address = "192.0.2.10".into(); + for changed in 0..7 { + let mut endpoint = ResolvedEndpoint { + logical_host: config.address.clone(), + port: config.port, + addresses: vec!["192.0.2.10:443".parse().unwrap()], + }; + match changed { + 0 => endpoint.logical_host = "other.memory.invalid".into(), + 1 => endpoint.port += 1, + 2 => endpoint.addresses.push("192.0.2.11:443".parse().unwrap()), + 3 => endpoint.addresses.clear(), + 4 => endpoint.addresses[0] = "192.0.2.11:443".parse().unwrap(), + 5 => endpoint.addresses[0] = "192.0.2.10:444".parse().unwrap(), + _ => endpoint.logical_host = "192.0.2.11".into(), + } + let outbound = node(&config, UpstreamPath::direct(endpoint, Dialer::default())); + assert!(!outbound.permits_http_tcp_reuse()); + } + let exact = ResolvedEndpoint { + logical_host: config.address.clone(), + port: config.port, + addresses: vec!["192.0.2.10:443".parse().unwrap()], + }; + let outbound = node(&config, UpstreamPath::direct(exact, Dialer::default())); + assert!(outbound.permits_http_tcp_reuse()); + } +} + +#[test] +fn masque_static_http_reuse_observes_dependency_stop_and_constraints() { + for network in modes() { + let config = config(network); + let dialer = Dialer::default(); + let outbound = node(&config, direct(dialer.clone())); + assert!(outbound.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + assert!(!outbound.permits_http_tcp_reuse()); + for dialer in [ + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_ip_version(crate::config::IpVersion::Ipv4), + Dialer::default().with_ip_version(crate::config::IpVersion::Ipv6), + Dialer::default().with_egress(&crate::config::EgressOptions { + interface: Some("memory-interface".into()), + routing_mark: 0, + }), + Dialer::default().with_protector(Arc::new(UncalledProtector)), + ] { + let outbound = node(&config, direct(dialer)); + assert!(!outbound.permits_http_tcp_reuse()); + } + } +} + +struct UncalledProtector; +impl SocketProtector for UncalledProtector { + fn protect(&self, _: i32) -> io::Result<()> { + panic!("static MASQUE proof must not protect or open a socket") + } +} + +#[test] +fn masque_static_http_reuse_never_samples_an_upstream_group() { + for network in modes() { + let config = config(network); + let selection = Arc::new(GroupSelection::new(0)); + let upstream = UpstreamPath::Group { + server: Destination::Ip("192.0.2.10:443".parse().unwrap()), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: None, + dialer: Dialer::default(), + }; + let outbound = node(&config, upstream); + assert!(!outbound.permits_http_tcp_reuse()); + selection.store(1, std::sync::atomic::Ordering::Release); + assert!(!outbound.permits_http_tcp_reuse()); + selection.store(0, std::sync::atomic::Ordering::Release); + assert!(!outbound.permits_http_tcp_reuse()); + } +} + +struct Opaque; +#[async_trait::async_trait] +impl OutboundConnector for Opaque { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("proof queries must not acquire opaque TCP") + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("proof queries must not acquire opaque UDP") + } +} + +#[test] +fn masque_static_http_reuse_keeps_unknown_upstreams_keyless() { + for network in modes() { + let outbound = node(&config(network), UpstreamPath::proxy(Arc::new(Opaque))); + assert!(!outbound.permits_http_tcp_reuse()); + } +} + +#[cfg(feature = "outbound-http")] +#[test] +fn masque_static_http_reuse_never_applies_tcp_proxy_proof_to_h3_udp() { + let proxy_config = crate::config::HttpOutboundConfig { + address: "192.0.2.11".into(), + port: 8080, + tls: None, + auth: None, + headers: Default::default(), + }; + let dialer = Dialer::default(); + let proxy = Arc::new( + crate::outbound::http::HttpOutbound::with_shared_security( + &proxy_config, + direct(dialer.clone()), + &SecurityContext::new(), + 0, + 8192, + ) + .unwrap(), + ); + assert!(proxy.permits_http_tcp_reuse()); + for network in modes() { + let outbound = node(&config(network), UpstreamPath::proxy(proxy.clone())); + assert_eq!( + outbound.permits_http_tcp_reuse(), + network == MasqueNetwork::H2 + ); + } + // HTTP is stateless: its default hook does not stop the physical owner. + proxy.begin_shutdown(); + assert!(proxy.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + let outbound = node(&config(MasqueNetwork::H2), UpstreamPath::proxy(proxy)); + assert!(!outbound.permits_http_tcp_reuse()); +} + +#[test] +fn masque_static_http_reuse_covers_ipv6_literal_without_resolution() { + for network in modes() { + let mut config = config(network); + config.address = "2001:db8::10".into(); + let endpoint = ResolvedEndpoint { + logical_host: config.address.clone(), + port: config.port, + addresses: vec!["[2001:db8::10]:443".parse().unwrap()], + }; + let outbound = node(&config, UpstreamPath::direct(endpoint, Dialer::default())); + assert!(outbound.permits_http_tcp_reuse()); + assert!(outbound.current.try_lock().unwrap().is_none()); + } +} + +#[test] +fn masque_static_http_reuse_recurses_real_fixed_nodes_and_observes_child_stop() { + for inner_network in modes() { + let child = Arc::new(node(&config(inner_network), direct(Dialer::default()))); + let parent = node( + &config(MasqueNetwork::H2), + UpstreamPath::proxy(child.clone()), + ); + assert!(parent.permits_http_tcp_reuse()); + for outer_network in [MasqueNetwork::Quic, MasqueNetwork::H3L4Proxy] { + let udp_parent = node(&config(outer_network), UpstreamPath::proxy(child.clone())); + assert!(!udp_parent.permits_http_tcp_reuse()); + } + child.begin_shutdown(); + assert!(!parent.permits_http_tcp_reuse()); + assert!(child.current.try_lock().unwrap().is_none()); + assert!(parent.current.try_lock().unwrap().is_none()); + } +} + +#[test] +fn masque_static_http_reuse_accepts_each_configured_immutable_pin_policy() { + for network in modes() { + for skip in [false, true] { + let mut config = config(network); + config.skip_cert_verify = skip; + let outbound = node(&config, direct(Dialer::default())); + assert!(outbound.permits_http_tcp_reuse()); + assert_eq!(outbound.config.skip_cert_verify, skip); + // No file/dynamic ECH field exists in this typed security factory. + assert!(outbound.connection.tls.config(false).is_ok()); + assert!( + outbound + .connection + .tls + .quiche_config("proxy.memory.invalid") + .is_ok() + ); + } + } +} diff --git a/src/outbound/masque/ip.rs b/src/outbound/masque/ip.rs index 6e9cb1e..7c4bbf7 100644 --- a/src/outbound/masque/ip.rs +++ b/src/outbound/masque/ip.rs @@ -86,6 +86,13 @@ impl Engine { NetStackConfig { mtu, packet_queue: 32, + tcp_recv_buffer: if config.network == MasqueNetwork::H2 { + 96 * 1024 + } else { + 128 * 1024 + }, + map_tcp_recv_buffer: cfg!(target_os = "macos") + && config.network == MasqueNetwork::Quic, tcp_send_buffer: if config.network == MasqueNetwork::H2 { 64 * 1024 } else { @@ -295,7 +302,14 @@ async fn run( let request = request(&config.uri)?; let mut tunnel = pool .open_ip_connect(request, context.deadline(), move || async move { - factory.connect(session, &setup).await + #[cfg(target_os = "macos")] + { + factory.connect_ip(session, &setup).await + } + #[cfg(not(target_os = "macos"))] + { + factory.connect(session, &setup).await + } }) .await?; tunnel.capsules.write_all(&routes()?).await?; diff --git a/src/outbound/masque/mod.rs b/src/outbound/masque/mod.rs index b9cde3e..3e4ec7c 100644 --- a/src/outbound/masque/mod.rs +++ b/src/outbound/masque/mod.rs @@ -30,6 +30,18 @@ pub(super) struct ConnectionFactory { udp_receive_buffer_size: Option, } impl ConnectionFactory { + /// This concrete factory owns parsed immutable SPKI/client ECDSA material. + /// Prove the actual carrier: H2 TCP graph or H3 physical UDP first hop. + #[cfg(feature = "inbound-http")] + fn permits_static_http_reuse(&self, network: MasqueNetwork) -> bool { + match network { + MasqueNetwork::H2 => self.upstream.permits_static_http_reuse(&self.server), + MasqueNetwork::Quic | MasqueNetwork::H3L4Proxy => { + self.upstream.permits_static_direct_http_reuse(&self.server) + } + } + } + pub(super) async fn connect_h2( &self, session: StreamSession, @@ -61,6 +73,23 @@ impl ConnectionFactory { &self, session: StreamSession, context: &EstablishContext, + ) -> io::Result { + self.connect_inner(session, context, cfg!(target_os = "macos")) + .await + } + #[cfg(target_os = "macos")] + pub(super) async fn connect_ip( + &self, + session: StreamSession, + context: &EstablishContext, + ) -> io::Result { + self.connect_inner(session, context, true).await + } + async fn connect_inner( + &self, + session: StreamSession, + context: &EstablishContext, + fixed_peer: bool, ) -> io::Result { let tls = self.tls.quiche_config(self.server_name.clone())?; let server = self @@ -82,11 +111,20 @@ impl ConnectionFactory { } else { request }; - let transport = self - .upstream - .open_datagram(request, context) - .await - .map_err(io::Error::other)?; + #[cfg(target_os = "macos")] + let transport = if fixed_peer { + self.upstream + .open_fixed_peer_datagram(request, peer, context) + .await + } else { + self.upstream.open_datagram(request, context).await + }; + #[cfg(not(target_os = "macos"))] + let transport = { + let _ = fixed_peer; + self.upstream.open_datagram(request, context).await + }; + let transport = transport.map_err(io::Error::other)?; Ok(h3_connect::QuicTransport { transport, peer, @@ -243,6 +281,14 @@ fn connect_request(target: &Destination) -> io::Result> { #[async_trait] impl OutboundConnector for MasqueOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + !self.cancel.is_cancelled() + && self + .connection + .permits_static_http_reuse(self.config.network) + } + async fn connect_stream( &self, session: StreamSession, @@ -354,6 +400,9 @@ impl Drop for MasqueOutbound { } } +#[cfg(all(test, feature = "inbound-http"))] +mod http_reuse_memory_tests; + #[cfg(test)] mod tests { use super::*; @@ -520,6 +569,194 @@ mod tests { assert!(outbound.current.lock().await.is_none()); } } + #[cfg(target_os = "macos")] + fn fixed_factory_memory_outbound( + network: MasqueNetwork, + upstream: UpstreamPath, + peer: std::net::SocketAddr, + ) -> MasqueOutbound { + let mut outbound = outbound_network(0, Arc::new(PendingUpstream::default()), network); + let factory = Arc::get_mut(&mut outbound.connection).unwrap(); + factory.server = Destination::Ip(peer); + factory.upstream = upstream; + outbound + } + + #[cfg(target_os = "macos")] + #[tokio::test] + async fn masque_h3_fixed_factory_memory_l4_acquires_direct_and_lazy_fixed_peers() { + use crate::{ + dialer::{Dialer, ResolvedEndpoint}, + session::Datagram, + }; + use bytes::Bytes; + use std::net::{SocketAddr, SocketAddrV6}; + + let ipv6 = SocketAddr::V6(SocketAddrV6::new("fe80::10".parse().unwrap(), 443, 123, 7)); + for peer in ["192.0.2.10:443".parse().unwrap(), ipv6] { + for prepared in [false, true] { + let path = if prepared { + UpstreamPath::direct( + ResolvedEndpoint { + logical_host: peer.ip().to_string(), + port: peer.port(), + addresses: vec![peer], + }, + Dialer::default(), + ) + } else { + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + } + }; + let outbound = fixed_factory_memory_outbound(MasqueNetwork::H3L4Proxy, path, peer); + let mut acquired = outbound + .connection + .connect(session(), &EstablishContext::default()) + .await + .unwrap(); + assert_eq!(acquired.peer, peer); + assert_eq!(acquired.budget, DatagramBudget::new(1400, 1400)); + assert_eq!( + acquired.transport.payload_budget(&Destination::Ip(peer)), + DatagramBudget::new(1400, 1400) + ); + // This observes the real returned transport before any send. + // The old unconnected factory fails here without opening IO. + assert!( + !acquired.transport.supports_shared_destinations(), + "H3 L4 must acquire one fixed physical peer" + ); + let packet = |remote| Datagram { + remote: Destination::Ip(remote), + payload: Bytes::from_static(b"whole"), + sniffed_domain: None, + }; + let mut other = peer; + other.set_port(444); + let mut rejected = vec![other]; + if let SocketAddr::V6(address) = peer { + let mut flow = address; + flow.set_flowinfo(address.flowinfo() + 1); + rejected.push(SocketAddr::V6(flow)); + let mut scope = address; + scope.set_scope_id(address.scope_id() + 1); + rejected.push(SocketAddr::V6(scope)); + } + for other in rejected { + assert!(matches!( + acquired.transport.send(packet(other)).await, + Err(DispatchError::NotAllowed) + )); + let returned = acquired.transport.send_owned(packet(other)).err().unwrap(); + assert_eq!(returned.remote, Destination::Ip(other)); + assert_eq!(returned.payload, Bytes::from_static(b"whole")); + let returned = acquired + .transport + .send_batch_owned(vec![packet(other), packet(other)]) + .err() + .unwrap(); + assert_eq!(returned.len(), 2); + assert!(returned.iter().all(|item| { + item.remote == Destination::Ip(other) + && item.payload == Bytes::from_static(b"whole") + })); + } + assert!( + acquired.transport.send_owned(packet(peer)).is_err(), + "factory acquisition must leave the exact peer unopened" + ); + acquired.transport.close().await.unwrap(); + assert!(matches!( + acquired.transport.send(packet(peer)).await, + Err(DispatchError::NotAllowed) + )); + drop(acquired); + outbound.shutdown().await; + assert!(outbound.current.lock().await.is_none()); + assert!(outbound.remote.get().is_none()); + } + } + } + + #[cfg(target_os = "macos")] + #[tokio::test] + async fn masque_h3_fixed_factory_memory_preserves_ip_group_snapshot_and_proxy() { + use crate::{ + dialer::Dialer, + outbound::{SelectUpstream, SelectUpstreamMember}, + routing::GroupSelection, + }; + + let peer = "192.0.2.10:443".parse().unwrap(); + let ip = fixed_factory_memory_outbound( + MasqueNetwork::Quic, + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }, + peer, + ); + let mut acquired = ip + .connection + .connect_ip(session(), &EstablishContext::default()) + .await + .unwrap(); + assert_eq!(acquired.peer, peer); + assert!(!acquired.transport.supports_shared_destinations()); + acquired.transport.close().await.unwrap(); + drop(acquired); + ip.shutdown().await; + + let selection = Arc::new(GroupSelection::new(0)); + let group = fixed_factory_memory_outbound( + MasqueNetwork::H3L4Proxy, + UpstreamPath::Group { + server: Destination::Ip(peer), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: None, + dialer: Dialer::default(), + }, + peer, + ); + let context = EstablishContext::default(); + let mut first = group.connection.connect(session(), &context).await.unwrap(); + assert!(first.transport.supports_shared_destinations()); + selection.store(1, Ordering::Release); + let mut pinned = group.connection.connect(session(), &context).await.unwrap(); + assert!(pinned.transport.supports_shared_destinations()); + assert!( + group + .connection + .connect(session(), &EstablishContext::default()) + .await + .is_err() + ); + first.transport.close().await.unwrap(); + pinned.transport.close().await.unwrap(); + drop((first, pinned)); + group.shutdown().await; + + let upstream = Arc::new(PendingUpstream::default()); + let mut proxy = outbound_network(0, upstream.clone(), MasqueNetwork::H3L4Proxy); + Arc::get_mut(&mut proxy.connection).unwrap().server = Destination::Ip(peer); + assert!( + proxy + .connection + .connect(session(), &EstablishContext::default()) + .await + .is_err() + ); + assert_eq!(upstream.calls.load(Ordering::Relaxed), 1); + assert_eq!( + *upstream.datagram_requests.lock().unwrap(), + vec![(DatagramBudget::new(1400, 1400), None)] + ); + proxy.shutdown().await; + } + #[test] fn masque_handshake_duration_wrap_is_expired_not_a_new_schema_rejection() { let context = EstablishContext::with_timeout(Duration::from_millis(1)); diff --git a/src/outbound/mieru/http_reuse_memory_tests.rs b/src/outbound/mieru/http_reuse_memory_tests.rs new file mode 100644 index 0000000..c0808b4 --- /dev/null +++ b/src/outbound/mieru/http_reuse_memory_tests.rs @@ -0,0 +1,175 @@ +//! Query real Mieru constructors without opening a carrier, socket or resolver. +use super::*; +use crate::{ + config::{Config, EgressOptions, IpVersion, MieruHandshake, MieruMultiplexing}, + dialer::{Dialer, ResolvedEndpoint}, + outbound::{SelectUpstream, SelectUpstreamMember}, + routing::GroupSelection, +}; +use std::sync::Arc; + +fn server() -> Destination { + Destination::Ip("192.0.2.10:443".parse().unwrap()) +} +fn direct(dialer: Dialer) -> UpstreamPath { + UpstreamPath::LazyDirect { dialer } +} +fn endpoint() -> ResolvedEndpoint { + ResolvedEndpoint { + logical_host: "192.0.2.10".into(), + port: 443, + addresses: vec!["192.0.2.10:443".parse().unwrap()], + } +} +fn config(transport: &str) -> MieruOutboundConfig { + let parsed = Config::parse_yaml( + format!( + "proxies:\n - name: memory\n type: mieru\n server: 192.0.2.10\n port: 443\n username: synthetic-user\n password: synthetic-password\n transport: {transport}\n udp: true\n" + ).as_bytes(), + ).unwrap(); + let crate::config::ProxyProtocol::Mieru(config) = &parsed.proxies[0].protocol else { + panic!("Mieru memory configuration") + }; + config.clone() +} +fn outbound(config: &MieruOutboundConfig, path: UpstreamPath) -> MieruOutbound { + MieruOutbound::new(config, path, 32 * 1024).unwrap() +} + +#[test] +fn mieru_real_factory_static_path_keeps_fixed_pattern_and_mode_identity() { + // Mux policy controls carrier allocation; a held business stream retains + // the same factory, target and cancellation owner in every mode. + for transport in ["TCP", "UDP"] { + for multiplexing in [ + MieruMultiplexing::Off, + MieruMultiplexing::Low, + MieruMultiplexing::Middle, + MieruMultiplexing::High, + ] { + for handshake in [MieruHandshake::Standard, MieruHandshake::NoWait] { + for pattern in [None, Some("CAc=".to_owned())] { + let mut config = config(transport); + config.multiplexing = multiplexing; + config.handshake_mode = handshake; + config.traffic_pattern = pattern; + let node = outbound(&config, direct(Dialer::default())); + assert!(node.permits_http_tcp_reuse()); + node.begin_shutdown(); + assert!(!node.permits_http_tcp_reuse()); + } + } + } + assert!( + outbound( + &config(transport), + UpstreamPath::direct(endpoint(), Dialer::default()) + ) + .permits_http_tcp_reuse() + ); + } +} + +struct Opaque; +#[async_trait] +impl OutboundConnector for Opaque { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("structural proof must not open opaque IO") + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("structural proof must not open opaque datagrams") + } +} + +struct MustNotProtect; +impl crate::dialer::SocketProtector for MustNotProtect { + fn protect(&self, _: i32) -> io::Result<()> { + panic!("structural proof must not allocate a physical socket") + } +} + +#[test] +fn mieru_factory_rejects_endpoint_selection_groups_and_stopped_dependencies() { + for transport in ["TCP", "UDP"] { + let baseline = config(transport); + let mut range = baseline.clone(); + range.port_end += 1; + assert!(!outbound(&range, direct(Dialer::default())).permits_http_tcp_reuse()); + let mut named = baseline.clone(); + named.address = "dynamic.memory.invalid".into(); + assert!(!outbound(&named, direct(Dialer::default())).permits_http_tcp_reuse()); + let mut mismatch = endpoint(); + mismatch.addresses.push("192.0.2.11:443".parse().unwrap()); + assert!( + !outbound(&baseline, UpstreamPath::direct(mismatch, Dialer::default())) + .permits_http_tcp_reuse() + ); + let selection = Arc::new(GroupSelection::new(0)); + let group = UpstreamPath::Group { + server: server(), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + }; + let grouped = outbound(&baseline, group); + assert!(!grouped.permits_http_tcp_reuse()); + selection.store(1, std::sync::atomic::Ordering::Release); + assert!(!grouped.permits_http_tcp_reuse()); + assert!( + !outbound(&baseline, UpstreamPath::proxy(Arc::new(Opaque))).permits_http_tcp_reuse() + ); + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for dialer in [ + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + ] { + assert!(!outbound(&baseline, direct(dialer)).permits_http_tcp_reuse()); + } + let dialer = Dialer::default(); + let node = outbound(&baseline, direct(dialer.clone())); + assert!(node.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + assert!(!node.permits_http_tcp_reuse()); + } +} + +#[cfg(feature = "outbound-socks5")] +#[test] +fn mieru_tcp_graph_proof_does_not_authorize_the_same_proxied_udp_carrier() { + let parsed = Config::parse_yaml( + b"proxies: [{name: upstream, type: socks5, server: 192.0.2.20, port: 1080, udp: true}]", + ) + .unwrap(); + let crate::config::ProxyProtocol::Socks5(config) = &parsed.proxies[0].protocol else { + panic!("SOCKS5 memory upstream") + }; + let upstream = Arc::new( + crate::outbound::Socks5Outbound::new_with_path(config, direct(Dialer::default())).unwrap(), + ); + assert!(OutboundConnector::permits_http_tcp_reuse(upstream.as_ref())); + assert!( + outbound(&self::config("TCP"), UpstreamPath::proxy(upstream.clone())) + .permits_http_tcp_reuse() + ); + assert!( + !outbound(&self::config("UDP"), UpstreamPath::proxy(upstream)).permits_http_tcp_reuse() + ); +} diff --git a/src/outbound/mieru/mod.rs b/src/outbound/mieru/mod.rs index 72a2c62..661c354 100644 --- a/src/outbound/mieru/mod.rs +++ b/src/outbound/mieru/mod.rs @@ -70,6 +70,11 @@ impl MieruOutbound { } #[async_trait] impl OutboundConnector for MieruOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.client.permits_http_tcp_reuse() + } + async fn connect_stream( &self, session: StreamSession, @@ -135,6 +140,8 @@ impl OutboundConnector for MieruOutbound { self.client.shutdown().await; } } +#[cfg(all(test, feature = "inbound-http"))] +mod http_reuse_memory_tests; #[cfg(test)] mod packet_routing_tests; #[cfg(test)] diff --git a/src/outbound/mieru/tcp.rs b/src/outbound/mieru/tcp.rs index f5b4be9..7e0f447 100644 --- a/src/outbound/mieru/tcp.rs +++ b/src/outbound/mieru/tcp.rs @@ -324,6 +324,27 @@ impl Client { idle, }) } + /// The factory owns immutable credentials and compiled traffic policy. + /// Mux/handshake modes govern new logical streams, never the identity or + /// target of a retained stream. Only endpoint selection may be dynamic. + #[cfg(feature = "inbound-http")] + pub(super) fn permits_http_tcp_reuse(&self) -> bool { + let config = &self.factory.config; + if self.cancel.is_cancelled() || config.port == 0 || config.port != config.port_end { + return false; + } + let Ok(server) = server_destination(&config.address, config.port) else { + return false; + }; + match config.transport { + MieruTransport::Tcp => self.factory.upstream.permits_static_http_reuse(&server), + MieruTransport::Udp => self + .factory + .upstream + .permits_static_direct_http_reuse(&server), + } + } + pub(super) fn queues_datagrams(&self) -> bool { self.factory.config.transport == MieruTransport::Udp } diff --git a/src/outbound/mieru/udp.rs b/src/outbound/mieru/udp.rs index 631009d..c37b8ed 100644 --- a/src/outbound/mieru/udp.rs +++ b/src/outbound/mieru/udp.rs @@ -790,6 +790,140 @@ async fn send( shared.count_output(output.len()); Ok(()) } + +#[cfg(target_os = "macos")] +fn accept_ready_data( + state: &mut Reliable, + metadata: Metadata, + wire_len: usize, + shared: &Shared, + pattern: &mut PacketPattern<'_>, +) { + // Only a known successful physical prefix consumes the original FIFO. + pattern.remaining -= 1; + shared.count_output(wire_len); + let mut segment = state + .pending + .pop_front() + .expect("prepared DATA remains pending"); + segment.metadata = metadata; + segment.sent = Some(Instant::now()); + state.heartbeat = segment.sent.unwrap() + state.heartbeat_interval; + segment.tx_count = 1; + if state.state.business == super::tcp::Business::UdpAssociate { + segment.timeout_nanos = state.rtt.retransmit_delay(1).as_nanos() as u64; + } + if let Metadata::Data(meta) = metadata { + state.last_window = meta.window; + } + if let Some(lease) = &segment.lease { + lease.sent(); + } + if state.outstanding.is_empty() { + state.first_check = Some(Instant::now() + FIRST_CHECK); + } + state.outstanding.insert(sequence(metadata), segment); +} + +#[cfg(target_os = "macos")] +#[allow(clippy::too_many_arguments)] +async fn output_ready_data( + transport: &mut dyn DatagramTransport, + peer: &Destination, + encoder: &mut PacketEncoder, + username: &str, + shared: &Shared, + pattern: &mut PacketPattern<'_>, + state: &mut Reliable, + partial_available: bool, + available: u32, + buffer: &mut Vec, +) -> io::Result { + // Preparation never admits another command or removes its byte lease. + let limit = crate::dispatch::DATAGRAM_SEND_BATCH_LIMIT + .min(crate::dispatch::DATAGRAM_SEND_BATCH_BYTES / pattern.wire_budget.max(1)) + .min(pattern.remaining) + .min(available as usize) + .min((SEGMENTS - 1).saturating_sub(state.outstanding.len())); + let count = state.pending.iter().take(limit).take_while(|segment| { + matches!(segment.metadata, Metadata::Data(meta) if meta.kind == DataKind::ClientData) + }).count(); + if count < 2 { + return Ok(0); + } + let mut packets = Vec::with_capacity(count); + let mut wire_bytes = 0usize; + for segment in state.pending.iter().take(count) { + if shared.cancel.is_cancelled() { + return Err(closed()); + } + let mut metadata = segment.metadata; + if let Metadata::Data(ref mut meta) = metadata { + meta.unack_sequence = state.state.next_receive.load(Ordering::Acquire); + meta.window = state.window(partial_available); + } + let mut nonce = rand::random(); + pattern + .pattern + .rewrite_nonce(&mut pattern.nonce, &mut nonce, MieruTransport::Udp); + let nonce = crypto::make_client_nonce(username, nonce); + let prepared = pattern.pattern.prepare_frame( + metadata, + segment.payload.len(), + MieruTransport::Udp, + pattern.wire_budget, + )?; + encoder.encode_frame( + metadata, + &segment.payload, + prepared.encoding(), + nonce, + super::tcp::now()?, + buffer, + )?; + wire_bytes = wire_bytes + .checked_add(buffer.len()) + .filter(|size| *size <= crate::dispatch::DATAGRAM_SEND_BATCH_BYTES) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidData))?; + packets.push(( + metadata, + Datagram { + remote: peer.clone(), + payload: Bytes::copy_from_slice(buffer), + sniffed_domain: None, + }, + )); + } + // Keep original ciphertext; the lease clones only Bytes handles. + let owned = packets.iter().map(|(_, packet)| packet.clone()).collect(); + if let Ok(operation) = transport.send_batch_owned(owned) { + let accepted = tokio::select! {biased; + () = shared.cancel.cancelled() => return Err(closed()), + result = tokio::time::timeout(Duration::from_secs(10), operation) => { + result.map_err(|_| io::ErrorKind::TimedOut)?.map_err(|_| closed())? + } + }; + if accepted == 0 || accepted > packets.len() { + return Err(io::Error::from(io::ErrorKind::InvalidData)); + } + for (metadata, packet) in packets.drain(..accepted) { + accept_ready_data(state, metadata, packet.payload.len(), shared, pattern); + } + } + // Capability refusal did no IO. A positive partial leaves only this exact + // ciphertext suffix; future errors/cancellation above never fall back here. + for (metadata, packet) in packets { + let wire_len = packet.payload.len(); + tokio::select! {biased; + () = shared.cancel.cancelled() => return Err(closed()), + result = tokio::time::timeout(Duration::from_secs(10), transport.send(packet)) => { + result.map_err(|_| io::ErrorKind::TimedOut)?.map_err(|_| closed())? + } + } + accept_ready_data(state, metadata, wire_len, shared, pattern); + } + Ok(count as u32) +} #[allow(clippy::too_many_arguments)] async fn output( transport: &mut dyn DatagramTransport, @@ -929,6 +1063,26 @@ async fn output( pattern.truncated = true; break; } + #[cfg(target_os = "macos")] + if state.established && pattern.pattern.low_entropy_enabled() { + let sent = output_ready_data( + transport, + peer, + encoder, + username, + shared, + pattern, + state, + partial_available, + available - new_sent, + buffer, + ) + .await?; + if sent != 0 { + new_sent += sent; + continue; + } + } let mut segment = state.pending.pop_front().unwrap(); if let Metadata::Data(ref mut meta) = segment.metadata { meta.unack_sequence = state.state.next_receive.load(Ordering::Acquire); @@ -1412,6 +1566,8 @@ mod tests { }; use tokio_util::{sync::CancellationToken, task::TaskTracker}; include!("udp_upload_shutdown_tests.rs"); + #[cfg(target_os = "macos")] + include!("udp_ready_batch_client_stop_memory_tests.rs"); #[derive(Default)] struct ReceiveCalls { @@ -1437,6 +1593,8 @@ mod tests { nonces: Mutex>, transmit_limit: u16, received: Mutex>, + #[cfg(target_os = "macos")] + ready_batch_stop_gate: Option>, } struct Memory { polled_receive: bool, @@ -1447,6 +1605,8 @@ mod tests { task: Option>, budget: DatagramBudget, quiet_close: Option<(Arc, PacketDecoder)>, + #[cfg(target_os = "macos")] + ready_batch_stop_gate: Option>, } impl Memory { fn quiet_close_input(&self) -> bool { @@ -1498,6 +1658,16 @@ mod tests { fn payload_budget(&self, _: &Destination) -> DatagramBudget { self.budget } + #[cfg(target_os = "macos")] + fn send_batch_owned( + &mut self, + packets: Vec, + ) -> Result> { + let Some(gate) = &self.ready_batch_stop_gate else { + return Err(packets); + }; + gate.send_owned(packets) + } async fn send(&mut self, packet: Datagram) -> Result<(), DispatchError> { let close = if let Some((upload, decoder)) = &mut self.quiet_close { let frame = decoder @@ -1537,10 +1707,20 @@ mod tests { Ok(packet) } async fn close(&mut self) -> Result<(), DispatchError> { + #[cfg(target_os = "macos")] + if let Some(gate) = &self.ready_batch_stop_gate { + gate.closes.fetch_add(1, Ordering::AcqRel); + gate.close_with_owner + .fetch_or(gate.active.load(Ordering::Acquire) != 0, Ordering::AcqRel); + } self.cancel.cancel(); if let Some(task) = self.task.take() { let _ = task.await; } + #[cfg(target_os = "macos")] + if let Some(gate) = &self.ready_batch_stop_gate { + gate.memory_joined.fetch_add(1, Ordering::AcqRel); + } Ok(()) } } @@ -1575,6 +1755,8 @@ mod tests { nonces: Mutex::new(Vec::new()), transmit_limit: MTU, received: Mutex::new(Vec::new()), + #[cfg(target_os = "macos")] + ready_batch_stop_gate: None, }) } async fn stop(&self) { @@ -1630,6 +1812,8 @@ mod tests { task: Some(task), budget: DatagramBudget::new(self.transmit_limit, MTU), quiet_close, + #[cfg(target_os = "macos")] + ready_batch_stop_gate: self.ready_batch_stop_gate.clone(), })) } } @@ -4060,3 +4244,7 @@ include!("udp_split_receive_tests.rs"); #[cfg(test)] include!("udp_balanced_driver_tests.rs"); + +#[cfg(all(test, target_os = "macos"))] +#[path = "udp_ready_batch_memory_tests.rs"] +mod ready_batch_memory_tests; diff --git a/src/outbound/mieru/udp_ready_batch_client_stop_memory_tests.rs b/src/outbound/mieru/udp_ready_batch_client_stop_memory_tests.rs new file mode 100644 index 0000000..4342457 --- /dev/null +++ b/src/outbound/mieru/udp_ready_batch_client_stop_memory_tests.rs @@ -0,0 +1,223 @@ +// Included only in the existing udp::tests module on macOS. Peer/Memory/serve +// remain the actual real-client factory; no production seam is replaced. +struct ReadyBatchStopGate { + armed: AtomicBool, + entered: AtomicUsize, + active: AtomicUsize, + retained_bytes: AtomicUsize, + dropped: AtomicUsize, + submitted: AtomicUsize, + authenticated_data: AtomicUsize, + invalid: AtomicBool, + closes: AtomicUsize, + close_with_owner: AtomicBool, + memory_joined: AtomicUsize, + entered_notify: tokio::sync::Notify, + decoder: Mutex, +} +impl ReadyBatchStopGate { + fn new() -> Arc { + let key = crypto::derive_packet_key( + "vole", "fixture-password", super::super::tcp::now().unwrap(), + ); + Arc::new(Self { + armed: AtomicBool::new(false), entered: AtomicUsize::new(0), + active: AtomicUsize::new(0), retained_bytes: AtomicUsize::new(0), + dropped: AtomicUsize::new(0), submitted: AtomicUsize::new(0), + authenticated_data: AtomicUsize::new(0), invalid: AtomicBool::new(false), + closes: AtomicUsize::new(0), close_with_owner: AtomicBool::new(false), + memory_joined: AtomicUsize::new(0), entered_notify: tokio::sync::Notify::new(), + decoder: Mutex::new(PacketDecoder::new(&key, true).unwrap()), + }) + } + fn send_owned( + self: &Arc, + packets: Vec, + ) -> Result> { + if !self.armed.load(Ordering::Acquire) { + return Err(packets); + } + if crate::dispatch::datagram_batch_peer(&packets).is_none() { + self.invalid.store(true, Ordering::Release); + return Err(packets); + } + let bytes = packets.iter().map(|packet| packet.payload.len()).sum(); + self.active.fetch_add(1, Ordering::AcqRel); + self.retained_bytes.fetch_add(bytes, Ordering::AcqRel); + let held = ReadyBatchStopOwned { packets, bytes, gate: self.clone() }; + Ok(Box::pin(async move { + // Authentication observes attempted DATA preparation, not physical + // acceptance. The controlled physical future never returns Ready. + let mut sid = None; + let mut authenticated = 0; + for packet in &held.packets { + let decoded = super::super::tcp::now().and_then(|now| { + held.gate.decoder.lock().unwrap().decode_frame(packet.payload.clone(), now) + }); + match decoded { + Ok(Frame { metadata: Metadata::Data(meta), .. }) + if meta.kind == DataKind::ClientData + && sid.is_none_or(|sid| sid == meta.session_id) => + { + sid = Some(meta.session_id); + authenticated += 1; + } + _ => held.gate.invalid.store(true, Ordering::Release), + } + } + held.gate.submitted.store(held.packets.len(), Ordering::Release); + held.gate.authenticated_data.store(authenticated, Ordering::Release); + held.gate.entered.fetch_add(1, Ordering::AcqRel); + held.gate.entered_notify.notify_one(); + let result = std::future::pending::>().await; + drop(held); + result + })) + } + async fn wait_entered(&self) { + loop { + let notified = self.entered_notify.notified(); + if self.entered.load(Ordering::Acquire) != 0 { + return; + } + notified.await; + } + } +} +struct ReadyBatchStopOwned { + packets: Vec, + bytes: usize, + gate: Arc, +} +impl Drop for ReadyBatchStopOwned { + fn drop(&mut self) { + self.gate.retained_bytes.fetch_sub(self.bytes, Ordering::AcqRel); + self.gate.active.fetch_sub(1, Ordering::AcqRel); + self.gate.dropped.fetch_add(1, Ordering::AcqRel); + } +} + +#[tokio::test(start_paused = true)] +async fn mieru_udp_pattern_ready_batch_real_client_stop_joins_active_owned_send() { + for polled in [false, true] { + let probe = ResourceProbe::default(); + let outcome = probe.scope(async { + let gate = ReadyBatchStopGate::new(); + let weak_gate = Arc::downgrade(&gate); + let mut peer = Peer::new(false, false); + { + let exclusive = Arc::get_mut(&mut peer).unwrap(); + exclusive.polled_receive = polled; + exclusive.ready_batch_stop_gate = Some(gate.clone()); + } + let weak_peer = Arc::downgrade(&peer); + let mut configuration = config(); + configuration.handshake_mode = crate::config::MieruHandshake::Standard; + configuration.traffic_pattern = Some( + "CAAaBAgAEAAiEAgDEAEYACAAKgZhYWJiY2MqBAgAEAAyBAgBEAA=".into(), + ); + let node = super::super::MieruOutbound::new( + &configuration, UpstreamPath::proxy(Arc::new(peer.clone())), 32768, + ).unwrap(); + // Keep the optional gate unarmed through ordinary OPEN, real SOCKS + // CONNECT and an authenticated business roundtrip on the same peer. + let setup = tokio::time::timeout(Duration::from_secs(5), async { + let context = EstablishContext::with_timeout(Duration::from_secs(5)); + let mut stream = node.connect_stream(super::super::tests::session(), &context) + .await.map_err(|_| closed())?.io; + stream.write_all(b"ready").await?; + let mut echo = [0; 5]; + stream.read_exact(&mut echo).await?; + if &echo != b"ready" { + return Err(io::Error::new(io::ErrorKind::InvalidData, "warmup echo differs")); + } + Ok::<_, io::Error>(stream) + }).await; + let mut stream = match setup { + Ok(Ok(stream)) => Some(stream), + _ => None, + }; + let setup_ok = stream.is_some(); + let opens_before_arm = peer.opens.load(Ordering::Acquire); + let mut entered = false; + let mut write_pending = false; + let mut held_stop = false; + let mut writer_rejected = false; + let mut active_before_stop = 0; + let mut bytes_before_stop = 0; + if let Some(stream) = stream.as_mut() { + gate.armed.store(true, Ordering::Release); + let payload = vec![0x61; 32768]; + let mut writing = Box::pin(stream.write_all(&payload)); + // This bounded wait is a GREEN integration prerequisite, not + // an old-source RED. Every branch rejoins owners before assert. + let first = tokio::time::timeout(Duration::from_secs(2), async { + tokio::select! { biased; + () = gate.wait_entered() => None, + result = &mut writing => Some(result.is_err()), + } + }).await; + let mut early_write = match first { + Ok(None) => { entered = true; None } + Ok(Some(rejected)) => Some(rejected), + Err(_) => None, + }; + if entered && early_write.is_none() { + // Use the actual caller Context: no noop waker, fabricated + // readiness or mirrored write-completion state. + match std::future::poll_fn(|cx| std::task::Poll::Ready( + std::future::Future::poll(writing.as_mut(), cx), + )).await { + std::task::Poll::Pending => write_pending = true, + std::task::Poll::Ready(result) => early_write = Some(result.is_err()), + } + } + active_before_stop = gate.active.load(Ordering::Acquire); + bytes_before_stop = gate.retained_bytes.load(Ordering::Acquire); + node.begin_shutdown(); + // Both the actual boxed Stream/RawStream and its write waiter + // remain alive while real Client::shutdown waits its TaskTracker. + held_stop = tokio::time::timeout(Duration::from_secs(2), node.shutdown()).await.is_ok(); + writer_rejected = if let Some(rejected) = early_write { + rejected + } else { + matches!(tokio::time::timeout(Duration::from_secs(2), writing.as_mut()).await, Ok(Err(_))) + }; + drop(writing); + } + drop(stream); + // Even a failed bounded observation/held-stop takes this final real + // join after releasing caller-held IO; it is never skipped by assert. + node.begin_shutdown(); + node.shutdown().await; + drop(node); + peer.stop().await; + let peer_joined = peer.tasks.is_empty(); + let receipt = ( + gate.entered.load(Ordering::Acquire), gate.dropped.load(Ordering::Acquire), + gate.active.load(Ordering::Acquire), gate.retained_bytes.load(Ordering::Acquire), + gate.submitted.load(Ordering::Acquire), gate.authenticated_data.load(Ordering::Acquire), + gate.invalid.load(Ordering::Acquire), gate.closes.load(Ordering::Acquire), + gate.close_with_owner.load(Ordering::Acquire), gate.memory_joined.load(Ordering::Acquire), + ); + drop((peer, gate)); + (setup_ok, opens_before_arm, entered, write_pending, held_stop, writer_rejected, + active_before_stop, bytes_before_stop, peer_joined, receipt, weak_peer, weak_gate) + }).await; + // All assertions follow real node/peer joins and owner release. + assert!(probe.snapshot().is_idle()); + let (setup_ok, opens, entered, pending, stopped, rejected, active, bytes, + peer_joined, receipt, weak_peer, weak_gate) = outcome; + assert!(weak_peer.upgrade().is_none() && weak_gate.upgrade().is_none()); + assert!(setup_ok && opens > 0 && peer_joined); + assert!(entered && pending && stopped && rejected); + assert_eq!(active, 1); + assert!(bytes > 0); + let (entered, dropped, active, bytes, submitted, authenticated, invalid, closes, close_with_owner, joined) = receipt; + assert_eq!((entered, dropped, active, bytes), (1, 1, 0, 0)); + assert!((2..=4).contains(&submitted)); + assert_eq!(authenticated, submitted); + assert!(!invalid && !close_with_owner); + assert_eq!((closes, joined), (1, 1)); + } +} diff --git a/src/outbound/mieru/udp_ready_batch_memory_tests.rs b/src/outbound/mieru/udp_ready_batch_memory_tests.rs new file mode 100644 index 0000000..754ffd3 --- /dev/null +++ b/src/outbound/mieru/udp_ready_batch_memory_tests.rs @@ -0,0 +1,759 @@ +//! Real old-API output/reliability tests; no socket, helper mirror or new production API. +use super::*; +use crate::{dispatch::DispatchError, resources::observation::ResourceProbe}; +use async_trait::async_trait; +use std::{future::Future, task::Poll}; +use tokio_util::sync::CancellationToken; + +// Existing independently encoded MODE32 pattern: no frame padding or control +// fragmentation, fixed UDP nonce prefix. Compile it through the real policy. +const PATTERN: &str = "CAAaBAgAEAAiEAgDEAEYACAAKgZhYWJiY2MqBAgAEAAyBAgBEAA="; +const CREDIT: usize = 32768; +type Business = super::super::tcp::Business; + +#[derive(Clone, Copy)] +enum Action { + Full, + PrefixOne, + Unsupported, + Fatal, + Zero, + Overflow, + Pending, +} + +#[derive(Default)] +struct Owner { + active: AtomicUsize, + entered: AtomicUsize, + dropped: AtomicUsize, +} +struct Held { + packets: Vec, + owner: Arc, +} +impl Drop for Held { + fn drop(&mut self) { + self.owner.active.fetch_sub(1, Ordering::AcqRel); + self.owner.dropped.fetch_add(1, Ordering::AcqRel); + } +} +#[derive(Clone)] +struct Accepted { + wire: Bytes, + metadata: Metadata, + payload: Bytes, +} +struct Log { + decoder: PacketDecoder, + completion: Arc>>>, + batches: Vec>, + singles: Vec, + accepted: Vec, + early_completion: bool, + invalid_admission: bool, + closed_with_owner: bool, + closes: usize, +} +impl Log { + fn accept(&mut self, packet: &Datagram) -> io::Result<()> { + // A fragmented application write cannot complete before its last + // physical Ready-OK. No assertion interrupts the owner's cleanup. + if !matches!( + self.completion.lock().unwrap().try_recv(), + Err(oneshot::error::TryRecvError::Empty) + ) { + self.early_completion = true; + } + let frame = self + .decoder + .decode_frame(packet.payload.clone(), super::super::tcp::now()?)?; + self.accepted.push(Accepted { + wire: packet.payload.clone(), + metadata: frame.metadata, + payload: frame.payload, + }); + Ok(()) + } +} +struct Memory { + log: Arc>, + owner: Arc, + action: Action, + first_batch: bool, + fail_single: Option, +} +#[async_trait] +impl DatagramTransport for Memory { + fn supports_shared_destinations(&self) -> bool { + false + } + fn payload_budget(&self, _: &Destination) -> DatagramBudget { + DatagramBudget::new(MTU, MTU) + } + fn send_batch_owned( + &mut self, + packets: Vec, + ) -> Result> { + let mut log = self.log.lock().unwrap(); + log.batches.push( + packets + .iter() + .map(|packet| packet.payload.clone()) + .collect(), + ); + if crate::dispatch::datagram_batch_peer(&packets).is_none() + || packets + .iter() + .any(|packet| packet.payload.len() > usize::from(MTU)) + { + log.invalid_admission = true; + return Err(packets); + } + let action = if self.first_batch { + self.first_batch = false; + self.action + } else { + Action::Full + }; + if matches!(action, Action::Unsupported) { + return Err(packets); // Admission rejection: no physical acceptance. + } + drop(log); + self.owner.active.fetch_add(1, Ordering::AcqRel); + let held = Held { + packets, + owner: self.owner.clone(), + }; + let log = self.log.clone(); + Ok(Box::pin(async move { + held.owner.entered.fetch_add(1, Ordering::AcqRel); + let count = match action { + Action::Full => held.packets.len(), + Action::PrefixOne => 1, + Action::Fatal => return Err(io::ErrorKind::PermissionDenied.into()), + Action::Zero => return Ok(0), + Action::Overflow => return Ok(held.packets.len() + 1), + Action::Pending => std::future::pending::().await, + Action::Unsupported => unreachable!("rejected before owned IO"), + }; + for packet in &held.packets[..count] { + log.lock().unwrap().accept(packet)?; + } + drop(held); + Ok(count) + })) + } + async fn send(&mut self, packet: Datagram) -> Result<(), DispatchError> { + let mut log = self.log.lock().unwrap(); + log.singles.push(packet.payload.clone()); + if self.fail_single == Some(log.singles.len()) { + return Err(DispatchError::ConnectionRefused); + } + log.accept(&packet).map_err(DispatchError::from) + } + async fn receive(&mut self) -> Result { + std::future::pending().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + let mut log = self.log.lock().unwrap(); + log.closes += 1; + log.closed_with_owner |= self.owner.active.load(Ordering::Acquire) != 0; + Ok(()) + } +} + +struct Fixture { + shared: Arc, + state: Arc, + reliable: Reliable, + credit: Arc, + completion: Arc>>>, + encoder: PacketEncoder, + ack_encoder: PacketEncoder, + ack_decoder: PacketDecoder, + pattern: EffectivePattern, + memory: Memory, + expected: Vec, + remaining: usize, + buffer: Vec, +} +struct View { + batches: Vec>, + singles: Vec, + accepted: Vec, + pending: usize, + outstanding: Vec<(u32, u32, bool, u64)>, + remaining: usize, + first_check: bool, + credit: usize, + completion: u8, + early_completion: bool, + invalid_admission: bool, +} +struct Cleanup { + closed: bool, + closed_with_owner: bool, + closes: usize, + active: usize, + entered: usize, + dropped: usize, + credit: usize, + completion: u8, +} +fn completion_status(receiver: &Mutex>>) -> u8 { + match receiver.lock().unwrap().try_recv() { + Err(oneshot::error::TryRecvError::Empty) => 0, + Ok(Ok(())) => 1, + Ok(Err(_)) => 2, + Err(oneshot::error::TryRecvError::Closed) => 3, + } +} +impl Fixture { + fn new(business: Business, low: bool, fragments: usize, action: Action) -> Self { + let pattern = EffectivePattern::compile( + low.then_some(PATTERN), + super::super::pattern::HostProfile::capture(), + "vole", + ) + .unwrap(); + let chunk = pattern + .plaintext_fragment_limit(MieruTransport::Udp, MTU.into()) + .unwrap(); + let expected: Vec<_> = (0..chunk * fragments) + .map(|index| b'A' + (index / chunk) as u8) + .collect(); + let shared = Shared::output_test_shared(CancellationToken::new()); + let state = + State::new_for_business(7, CREDIT, business, &shared.cancel, shared.activity.clone()); + state.opened.store(true, Ordering::Release); + shared.sessions.lock().unwrap().insert(7, state.clone()); + let credit = Arc::new(Semaphore::new(CREDIT)); + let (done, completion) = oneshot::channel(); + let completion = Arc::new(Mutex::new(completion)); + let command = WriterCommand { + state: state.clone(), + data: Bytes::copy_from_slice(&expected), + piggyback: false, + done, + _bytes: credit + .clone() + .try_acquire_many_owned(expected.len() as u32) + .unwrap(), + }; + let mut reliable = Reliable::new(state.clone(), 1312); + reliable.established = true; + reliable.heartbeat_interval = Duration::from_secs(30); + reliable.heartbeat = Instant::now() + reliable.heartbeat_interval; + reliable.enqueue(command, chunk, false); + let key = crypto::derive_packet_key( + "vole", + "fixture-password", + super::super::tcp::now().unwrap(), + ); + let log = Arc::new(Mutex::new(Log { + decoder: PacketDecoder::new(&key, low).unwrap(), + completion: completion.clone(), + batches: Vec::new(), + singles: Vec::new(), + accepted: Vec::new(), + early_completion: false, + invalid_admission: false, + closed_with_owner: false, + closes: 0, + })); + Self { + shared, + state, + reliable, + credit, + completion, + encoder: PacketEncoder::new(&key, false).unwrap(), + ack_encoder: PacketEncoder::new(&key, false).unwrap(), + ack_decoder: PacketDecoder::new(&key, low).unwrap(), + pattern, + memory: Memory { + log, + owner: Arc::default(), + action, + first_batch: true, + fail_single: None, + }, + expected, + remaining: OUTPUT_QUANTUM, + buffer: Vec::new(), + } + } + async fn output(&mut self) -> io::Result { + let mut pattern = PacketPattern { + pattern: &self.pattern, + nonce: NonceState::new(), + wire_budget: MTU.into(), + remaining: self.remaining, + truncated: false, + }; + let result = output( + &mut self.memory, + &Destination::Ip("192.0.2.1:2000".parse().unwrap()), + &mut self.encoder, + "vole", + &self.shared, + &mut pattern, + &mut self.reliable, + true, + &mut self.buffer, + ) + .await; + self.remaining = pattern.remaining; + result + } + fn view(&self) -> View { + let log = self.memory.log.lock().unwrap(); + View { + batches: log.batches.clone(), + singles: log.singles.clone(), + accepted: log.accepted.clone(), + pending: self.reliable.pending.len(), + outstanding: self + .reliable + .outstanding + .iter() + .map(|(sequence, segment)| { + ( + *sequence, + segment.tx_count, + segment.sent.is_some(), + segment.timeout_nanos, + ) + }) + .collect(), + remaining: self.remaining, + first_check: self.reliable.first_check.is_some(), + credit: self.credit.available_permits(), + completion: completion_status(&self.completion), + early_completion: log.early_completion, + invalid_admission: log.invalid_admission, + } + } + fn ack(&mut self, unack: u32) { + let mut wire = Vec::new(); + self.ack_encoder + .encode_frame( + Metadata::Data(DataMetadata { + kind: DataKind::ServerAck, + session_id: 7, + sequence: 0, + unack_sequence: unack, + window: 16, + fragment: 0, + }), + &[], + super::super::wire::Padding::default(), + rand::random(), + super::super::tcp::now().unwrap(), + &mut wire, + ) + .unwrap(); + let frame = self + .ack_decoder + .decode_frame(Bytes::from(wire), super::super::tcp::now().unwrap()) + .unwrap(); + self.reliable.input(frame, Instant::now(), &mut None); + } + async fn cleanup(self) -> Cleanup { + let Self { + shared, + state, + reliable, + credit, + completion, + mut memory, + encoder, + ack_encoder, + ack_decoder, + pattern, + expected, + buffer, + .. + } = self; + shared.cancel.cancel(); + let closed = memory.close().await.is_ok(); + state.close(); + drop(reliable); + shared.sessions.lock().unwrap().clear(); + drop(( + state, + shared, + encoder, + ack_encoder, + ack_decoder, + pattern, + expected, + buffer, + )); + let log = memory.log.lock().unwrap(); + let result = Cleanup { + closed, + closed_with_owner: log.closed_with_owner, + closes: log.closes, + active: memory.owner.active.load(Ordering::Acquire), + entered: memory.owner.entered.load(Ordering::Acquire), + dropped: memory.owner.dropped.load(Ordering::Acquire), + credit: credit.available_permits(), + completion: completion_status(&completion), + }; + drop(log); + drop((memory, completion, credit)); + result + } +} +fn assert_cleanup(cleanup: &Cleanup) { + assert!(cleanup.closed && !cleanup.closed_with_owner); + assert_eq!( + (cleanup.closes, cleanup.active, cleanup.credit), + (1, 0, CREDIT) + ); + assert_eq!(cleanup.entered, cleanup.dropped); +} +fn assert_data(view: &View, expected: &[u8], fragments: usize, udp: bool) { + assert!(!view.early_completion && !view.invalid_admission); + assert_eq!( + (view.accepted.len(), view.pending, view.outstanding.len()), + (fragments, 0, fragments) + ); + let mut payload = Vec::new(); + for (index, accepted) in view.accepted.iter().enumerate() { + assert!(matches!(accepted.metadata, Metadata::Data(meta) + if meta.kind == DataKind::ClientData && meta.session_id == 7 + && meta.sequence == index as u32 && meta.fragment as usize == fragments - index - 1)); + payload.extend_from_slice(&accepted.payload); + assert!(accepted.wire.len() <= usize::from(MTU)); + } + assert_eq!(payload, expected); + for (index, entry) in view.outstanding.iter().enumerate() { + assert_eq!((entry.0, entry.1, entry.2), (index as u32, 1, true)); + assert_eq!( + entry.3 != 0, + udp, + "saved RTO is qualified by each State's business" + ); + } + assert!(view.first_check); + assert_eq!(view.completion, 1); + assert_eq!( + view.credit, + CREDIT - expected.len(), + "first-send is not an ACK refund" + ); +} + +#[tokio::test(start_paused = true)] +async fn mieru_udp_pattern_ready_batch_real_output_eight_fragments_both_businesses() { + let probe = ResourceProbe::default(); + let cases = probe + .scope(async { + let mut cases = Vec::new(); + for business in [Business::UdpAssociate, Business::TcpConnect] { + let mut fixture = Fixture::new(business, true, 8, Action::Full); + let expected = fixture.expected.clone(); + let result = fixture.output().await; + let view = fixture.view(); + fixture.ack(8); + let ack_credit = fixture.credit.available_permits(); + let outstanding_after_ack = fixture.reliable.outstanding.len(); + let cleanup = fixture.cleanup().await; + cases.push(( + business, + expected, + result, + view, + ack_credit, + outstanding_after_ack, + cleanup, + )); + } + cases + }) + .await; + assert!(probe.snapshot().is_idle()); + for (business, expected, result, view, ack_credit, outstanding_after_ack, cleanup) in cases { + assert_cleanup(&cleanup); + assert!(matches!(result, Ok(true))); + assert_data( + &view, + &expected, + 8, + matches!(business, Business::UdpAssociate), + ); + assert_eq!((ack_credit, outstanding_after_ack), (CREDIT, 0)); + assert_eq!(view.remaining, 0); + // Old 5de naturally finishes eight ordinary sends and all cleanup above; + // it then fails this batch-use policy assertion, never a gate timeout. + assert_eq!( + view.batches.iter().map(Vec::len).collect::>(), + [4, 4] + ); + assert!(view.singles.is_empty()); + } +} + +#[tokio::test(start_paused = true)] +async fn mieru_udp_pattern_ready_batch_partial_preserves_ciphertext_and_real_ack_credit() { + let probe = ResourceProbe::default(); + let cases = probe + .scope(async { + let mut cases = Vec::new(); + for business in [Business::UdpAssociate, Business::TcpConnect] { + let mut fixture = Fixture::new(business, true, 4, Action::PrefixOne); + let expected = fixture.expected.clone(); + let result = fixture.output().await; + let view = fixture.view(); + fixture.ack(1); + let partial_credit = fixture.credit.available_permits(); + fixture.ack(4); + let full_credit = fixture.credit.available_permits(); + let cleanup = fixture.cleanup().await; + cases.push(( + business, + expected, + result, + view, + partial_credit, + full_credit, + cleanup, + )); + } + cases + }) + .await; + assert!(probe.snapshot().is_idle()); + for (business, expected, result, view, partial_credit, full_credit, cleanup) in cases { + assert_cleanup(&cleanup); + assert!(matches!(result, Ok(true))); + assert_data( + &view, + &expected, + 4, + matches!(business, Business::UdpAssociate), + ); + assert_eq!( + (partial_credit, full_credit), + (CREDIT - expected.len(), CREDIT) + ); + assert_eq!(view.remaining, 4); + assert_eq!(view.batches.len(), 1); + assert_eq!(view.batches[0].len(), 4); + assert_eq!(view.singles, view.batches[0][1..]); + for (single, original) in view.singles.iter().zip(&view.batches[0][1..]) { + assert_eq!( + single.as_ptr(), + original.as_ptr(), + "suffix keeps its original encoded allocation" + ); + } + } +} + +#[tokio::test(start_paused = true)] +async fn mieru_udp_pattern_ready_batch_errors_and_partial_suffix_failure_do_not_replay() { + let probe = ResourceProbe::default(); + let (errors, suffix) = probe + .scope(async { + let mut errors = Vec::new(); + for action in [Action::Fatal, Action::Zero, Action::Overflow] { + let mut fixture = Fixture::new(Business::UdpAssociate, true, 4, action); + let result = fixture.output().await; + let view = fixture.view(); + let cleanup = fixture.cleanup().await; + errors.push((result, view, cleanup)); + } + let mut fixture = Fixture::new(Business::UdpAssociate, true, 4, Action::PrefixOne); + fixture.memory.fail_single = Some(2); + let result = fixture.output().await; + let view = fixture.view(); + fixture.ack(2); + let credit_after_prefix_ack = fixture.credit.available_permits(); + let cleanup = fixture.cleanup().await; + (errors, (result, view, credit_after_prefix_ack, cleanup)) + }) + .await; + assert!(probe.snapshot().is_idle()); + for (result, view, cleanup) in errors { + assert_cleanup(&cleanup); + assert!(result.is_err()); + assert_eq!( + (view.batches.len(), view.singles.len(), view.accepted.len()), + (1, 0, 0) + ); + assert_eq!( + ( + view.pending, + view.outstanding.len(), + view.remaining, + view.completion + ), + (4, 0, 8, 0) + ); + assert!(!view.first_check && !view.early_completion); + assert_eq!( + cleanup.completion, 2, + "terminal drop rejects the unconfirmed write" + ); + } + let (result, view, credit_after_prefix_ack, cleanup) = suffix; + assert_cleanup(&cleanup); + assert!(result.is_err()); + assert_eq!( + (view.batches.len(), view.singles.len(), view.accepted.len()), + (1, 2, 2) + ); + assert_eq!(view.singles, view.batches[0][1..3]); + assert_eq!( + ( + view.pending, + view.outstanding.len(), + view.remaining, + view.completion + ), + (2, 2, 6, 0) + ); + assert!( + view.outstanding + .iter() + .all(|entry| entry.1 == 1 && entry.2 && entry.3 != 0) + ); + assert_eq!( + view.accepted + .iter() + .map(|frame| sequence(frame.metadata)) + .collect::>(), + [0, 1] + ); + assert_eq!( + credit_after_prefix_ack, view.credit, + "unconfirmed fragments retain the shared write lease" + ); + assert_eq!(cleanup.completion, 2); +} + +#[tokio::test(start_paused = true)] +async fn mieru_udp_pattern_ready_batch_pending_cancel_and_timeout_drop_before_close() { + let probe = ResourceProbe::default(); + let cases = probe + .scope(async { + let mut cases = Vec::new(); + for timeout in [false, true] { + let mut fixture = Fixture::new(Business::UdpAssociate, true, 4, Action::Pending); + let cancel = fixture.shared.cancel.clone(); + let mut operation = Box::pin(fixture.output()); + // Poll the real output exactly once with the caller's real Context. + // Old ordinary output may finish immediately; never wait for a + // batch-entered event which old production cannot produce. + let first = + std::future::poll_fn(|cx| Poll::Ready(operation.as_mut().poll(cx))).await; + let was_pending = first.is_pending(); + let result = match first { + Poll::Ready(result) => result, + Poll::Pending => { + if timeout { + tokio::time::advance(Duration::from_secs(10)).await; + } else { + cancel.cancel(); + } + operation.as_mut().await + } + }; + drop(operation); + let view = fixture.view(); + let cleanup = fixture.cleanup().await; + cases.push((timeout, was_pending, result, view, cleanup)); + } + cases + }) + .await; + assert!(probe.snapshot().is_idle()); + for (timeout, was_pending, result, view, cleanup) in cases { + assert_cleanup(&cleanup); + assert!(was_pending && result.is_err()); + if timeout { + assert_eq!(result.unwrap_err().kind(), io::ErrorKind::TimedOut); + } + assert_eq!((cleanup.entered, cleanup.dropped), (1, 1)); + assert_eq!( + (view.batches.len(), view.singles.len(), view.accepted.len()), + (1, 0, 0) + ); + assert_eq!( + ( + view.pending, + view.outstanding.len(), + view.remaining, + view.completion + ), + (4, 0, 8, 0) + ); + assert_eq!(cleanup.completion, 2); + } +} + +#[tokio::test(start_paused = true)] +async fn mieru_udp_pattern_ready_batch_fallback_scope_and_original_window_quantum() { + let probe = ResourceProbe::default(); + let cases = probe + .scope(async { + let mut cases = Vec::new(); + // Capability rejection preserves already encoded ciphertext. The other + // controls exercise actual eligibility through existing output. + for case in 0..6 { + let mut fixture = Fixture::new( + Business::UdpAssociate, + case != 1, + if case == 2 { 1 } else { 4 }, + if case == 0 { + Action::Unsupported + } else { + Action::Full + }, + ); + if case == 3 { + fixture.reliable.established = false; + } + if case == 4 { + fixture.reliable.remote_window = 1; + } + if case == 5 { + fixture.remaining = 1; + } + let result = fixture.output().await; + let view = fixture.view(); + let cleanup = fixture.cleanup().await; + cases.push((case, result, view, cleanup)); + } + cases + }) + .await; + assert!(probe.snapshot().is_idle()); + for (case, result, view, cleanup) in cases { + assert_cleanup(&cleanup); + assert!(matches!(result, Ok(true))); + assert!(!view.early_completion && !view.invalid_admission); + if case == 0 { + assert_eq!(view.batches.len(), 1); + assert_eq!(view.singles, view.batches[0]); + for (single, original) in view.singles.iter().zip(&view.batches[0]) { + assert_eq!(single.as_ptr(), original.as_ptr()); + } + } else { + assert!(view.batches.is_empty()); + } + let accepted = match case { + 0 | 1 => 4, + 3 => 0, + _ => 1, + }; + assert_eq!( + (view.singles.len(), view.accepted.len()), + (accepted, accepted) + ); + } +} diff --git a/src/outbound/mod.rs b/src/outbound/mod.rs index 0e0a04a..a33de59 100644 --- a/src/outbound/mod.rs +++ b/src/outbound/mod.rs @@ -35,6 +35,11 @@ mod shadowsocks; mod uot; #[cfg(feature = "outbound-shadowsocks")] pub use shadowsocks::ShadowsocksOutbound; + +#[cfg(all(test, feature = "outbound-shadowsocks", feature = "shadow-tls-v3"))] +pub(crate) use shadowsocks::memory_test_ss_stack_stream; +#[cfg(all(test, feature = "inbound-http", feature = "outbound-shadowsocks"))] +pub(crate) use shadowsocks::testing::{MemoryObfsFactory, MemoryObfsReceipt}; mod direct; mod dns; mod named_direct; @@ -89,3 +94,8 @@ pub mod hysteria2; mod owned_stream; #[cfg(feature = "outbound-tuic")] pub mod tuic; + +#[cfg(all(test, feature = "inbound-http", feature = "outbound-vmess"))] +pub(crate) use vmess::{ + MemoryVmessAcceptedPeer, MemoryVmessHttpCoverFactory, MemoryVmessHttpCoverReceipt, +}; diff --git a/src/outbound/shadowsocks/mod.rs b/src/outbound/shadowsocks/mod.rs index 385208c..d06447b 100644 --- a/src/outbound/shadowsocks/mod.rs +++ b/src/outbound/shadowsocks/mod.rs @@ -18,6 +18,7 @@ mod datagram_codec; mod packet_io; mod packet_window; mod plugin; +mod response_header; mod stream; mod uot; @@ -105,6 +106,14 @@ impl ShadowsocksOutbound { #[async_trait] impl OutboundConnector for ShadowsocksOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.plugin + .as_ref() + .is_none_or(|owner| owner.permits_http_tcp_reuse()) + && self.upstream.permits_static_http_reuse(&self.server) + } + async fn connect_stream( &self, session: StreamSession, @@ -121,10 +130,19 @@ impl OutboundConnector for ShadowsocksOutbound { .await? .io }; + let io = match &self.plugin { + Some(owner) => owner.prepare_ss_response(io, self.config.method())?, + None => io, + }; let stream = stream::SsStream::new(self.context.clone(), io, &self.config, address(&target)); + let stream: BoxStream = Box::new(stream); + let stream = match &self.plugin { + Some(owner) => owner.bind_stream(stream), + None => stream, + }; Ok(ConnectedStream { - io: Box::new(stream), + io: stream, effective_peer: target, }) } @@ -187,6 +205,11 @@ impl OutboundConnector for ShadowsocksOutbound { #[async_trait] impl Dispatcher for ShadowsocksOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + OutboundConnector::permits_http_tcp_reuse(self) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { OutboundConnector::connect_stream(self, session, &EstablishContext::default()) .await @@ -233,3 +256,20 @@ fn safe_io(error: io::Error) -> io::Error { #[cfg(test)] mod tests; + +#[cfg(all(test, feature = "inbound-http"))] +pub(super) mod testing; + +#[cfg(all(test, feature = "shadow-tls-v3"))] +pub(crate) fn memory_test_ss_stack_stream( + io: BoxStream, + config: &ServerConfig, + target: &Destination, +) -> BoxStream { + Box::new(stream::SsStream::new( + Context::new_shared(ServerType::Local), + io, + config, + address(target), + )) +} diff --git a/src/outbound/shadowsocks/obfs_reuse_owner_memory_tests.rs b/src/outbound/shadowsocks/obfs_reuse_owner_memory_tests.rs new file mode 100644 index 0000000..5e9e6c6 --- /dev/null +++ b/src/outbound/shadowsocks/obfs_reuse_owner_memory_tests.rs @@ -0,0 +1,406 @@ +//! Complete SS2022 stream ownership through the actual plugin binding. +use super::super::{address, stream::SsStream}; +use super::*; +use crate::config::{Config, ProxyProtocol, ShadowsocksCipher, ShadowsocksOutboundConfig}; +use ::shadowsocks::{ServerConfig, config::ServerType, context::Context as SsContext}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use std::sync::atomic::{AtomicUsize, Ordering}; + +#[derive(Default)] +struct State { + read_waker: Option, + write_waker: Option, + polls: usize, + dropped: bool, +} +struct Raw(Arc>); +impl Drop for Raw { + fn drop(&mut self) { + let mut state = self.0.lock().unwrap(); + state.dropped = true; + state.read_waker = None; + state.write_waker = None; + } +} +impl AsyncRead for Raw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + _: &mut ReadBuf<'_>, + ) -> Poll> { + let mut state = self.0.lock().unwrap(); + state.polls += 1; + state.read_waker = Some(cx.waker().clone()); + Poll::Pending + } +} +impl Raw { + fn pending_write(&self, cx: &mut Context<'_>) { + let mut state = self.0.lock().unwrap(); + state.polls += 1; + state.write_waker = Some(cx.waker().clone()); + } +} +impl AsyncWrite for Raw { + fn poll_write(self: Pin<&mut Self>, cx: &mut Context<'_>, _: &[u8]) -> Poll> { + self.pending_write(cx); + Poll::Pending + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.pending_write(cx); + Poll::Pending + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.pending_write(cx); + Poll::Pending + } +} +#[derive(Default)] +struct Count(AtomicUsize); +impl Wake for Count { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } + fn wake_by_ref(self: &Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} +fn ciphers() -> [ShadowsocksCipher; 3] { + [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] +} +fn obfs_config(cipher: ShadowsocksCipher, tls: bool) -> ShadowsocksOutboundConfig { + let input = serde_json::json!({ + "proxies": [{ + "name": "obfs", "type": "ss", "server": "192.0.2.10", "port": 8443, + "cipher": cipher.as_str(), "password": STANDARD.encode(vec![7; cipher.key_len()]), + "plugin": "obfs", "plugin-opts": {"mode": if tls { "tls" } else { "http" }, "host": "cover.invalid"} + }], + "rules": ["MATCH,obfs"] + }); + let parsed = Config::parse_yaml(&serde_json::to_vec(&input).unwrap()).unwrap(); + let ProxyProtocol::Shadowsocks(config) = &parsed.proxies[0].protocol else { + panic!("real SS configuration expected") + }; + config.clone() +} + +#[derive(Clone, Copy, Debug)] +pub(super) enum Carrier { + ObfsHttp, + ObfsTls, + V2rayMux, +} + +fn mux_config(cipher: ShadowsocksCipher) -> ShadowsocksOutboundConfig { + let input = serde_json::json!({ + "proxies": [{"name":"mux", "type":"ss", "server":"192.0.2.10", "port":8443, + "cipher":cipher.as_str(), "password":STANDARD.encode(vec![7; cipher.key_len()]), + "plugin":"v2ray-plugin", "plugin-opts":{"mode":"websocket", "host":"cover.invalid", + "path":"/mux", "mux":true, "tls":false}}], + "rules":["MATCH,mux"] + }); + let parsed = Config::parse_yaml(&serde_json::to_vec(&input).unwrap()).unwrap(); + let ProxyProtocol::Shadowsocks(config) = &parsed.proxies[0].protocol else { + panic!("real SS configuration expected") + }; + config.clone() +} + +impl Carrier { + fn config(self, cipher: ShadowsocksCipher) -> ShadowsocksOutboundConfig { + match self { + Self::ObfsHttp => obfs_config(cipher, false), + Self::ObfsTls => obfs_config(cipher, true), + Self::V2rayMux => mux_config(cipher), + } + } +} +fn owner(config: &ShadowsocksOutboundConfig) -> Owner { + Owner::new( + config.plugin.as_ref().unwrap(), + &SecurityContext::new(), + 0, + 16_384, + config.port, + ) + .unwrap() +} +fn unbound(config: &ShadowsocksOutboundConfig) -> (BoxStream, Arc>) { + let server = ServerConfig::new( + (config.address.clone(), config.port), + config.password.clone(), + config.cipher.as_str().parse().unwrap(), + ) + .unwrap(); + let state = Arc::new(Mutex::new(State::default())); + let stream = SsStream::new( + SsContext::new_shared(ServerType::Local), + Box::new(Raw(state.clone())), + &server, + address(&Destination::domain("origin.invalid", 443).unwrap()), + ); + (Box::new(stream), state) +} +fn write_operation(stream: &mut BoxStream, waker: &Waker, operation: &str) -> Poll> { + let mut cx = Context::from_waker(waker); + match operation { + "write" => Pin::new(&mut **stream) + .poll_write(&mut cx, b"next") + .map(|result| result.map(|_| ())), + "flush" => Pin::new(&mut **stream).poll_flush(&mut cx), + "shutdown" => Pin::new(&mut **stream).poll_shutdown(&mut cx), + _ => unreachable!(), + } +} +#[derive(Debug)] +struct StopObservation { + parent_stopped: bool, + woke_reader: bool, + woke_writer: bool, + read_aborted: bool, + write_aborted: bool, + raw_not_repolled: bool, + released_by_cancel_poll: bool, +} +impl StopObservation { + fn passed(&self) -> bool { + self.parent_stopped + && self.woke_reader + && self.woke_writer + && self.read_aborted + && self.write_aborted + && self.raw_not_repolled + && self.released_by_cancel_poll + } +} +async fn pending_stop( + cipher: ShadowsocksCipher, + carrier: Carrier, + operation: &str, +) -> StopObservation { + let config = carrier.config(cipher); + let owner = owner(&config); + let (stream, state) = unbound(&config); + let weak_state = Arc::downgrade(&state); + let mut stream = owner.bind_stream(stream); + let a = Arc::new(Count::default()); + let b = Arc::new(Count::default()); + let weak_a = Arc::downgrade(&a); + let weak_b = Arc::downgrade(&b); + let wa = Waker::from(a.clone()); + let wb = Waker::from(b.clone()); + let payload = b"accepted-first-ss-payload"; + let primed = matches!(Pin::new(&mut *stream).poll_write(&mut Context::from_waker(&wb), payload), + Poll::Ready(Ok(n)) if n == payload.len()); + let read_pending = Pin::new(&mut *stream) + .poll_read(&mut Context::from_waker(&wa), &mut ReadBuf::new(&mut [0])) + .is_pending(); + let write_pending = write_operation(&mut stream, &wb, operation).is_pending(); + let (raw_both, raw_polls) = { + let state = state.lock().unwrap(); + ( + state.read_waker.is_some() && state.write_waker.is_some(), + state.polls, + ) + }; + let before_a = a.0.load(Ordering::SeqCst); + let before_b = b.0.load(Ordering::SeqCst); + owner.begin_shutdown(); + let woke_reader = a.0.load(Ordering::SeqCst) > before_a; + let woke_writer = b.0.load(Ordering::SeqCst) > before_b; + let read_aborted = matches!(Pin::new(&mut *stream).poll_read( + &mut Context::from_waker(&wa), &mut ReadBuf::new(&mut [0])), + Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::ConnectionAborted); + let write_aborted = matches!(write_operation(&mut stream, &wb, operation), + Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::ConnectionAborted); + let (raw_not_repolled, released_by_cancel_poll) = { + let state = state.lock().unwrap(); + (state.polls == raw_polls, state.dropped) + }; + let parent_stopped = owner.cancel.is_cancelled() && !owner.permits_http_tcp_reuse(); + // Non-Gost WS has no plugin driver. The real tracker barrier does not + // substitute for the separately observed actual IO Drop above. + owner.shutdown().await; + drop(stream); + drop(owner); + drop(wa); + drop(wb); + drop(a); + drop(b); + let released = { + let state = state.lock().unwrap(); + state.dropped && state.read_waker.is_none() && state.write_waker.is_none() + }; + drop(state); + assert!( + released + && weak_state.upgrade().is_none() + && weak_a.upgrade().is_none() + && weak_b.upgrade().is_none() + ); + assert!( + primed && read_pending && write_pending && raw_both, + "real SS fixture premise: {cipher:?}/{operation} primed={primed} pending={read_pending}/{write_pending} raw={raw_both}" + ); + StopObservation { + parent_stopped, + woke_reader, + woke_writer, + read_aborted, + write_aborted, + raw_not_repolled, + released_by_cancel_poll, + } +} + +pub(super) async fn assert_pending_stop(carrier: Carrier) { + for cipher in ciphers() { + for operation in ["write", "flush", "shutdown"] { + let observed = pending_stop(cipher, carrier, operation).await; + assert!( + observed.passed(), + "{carrier:?}/{cipher:?}/{operation}: {observed:?}" + ); + } + } +} + +pub(super) async fn assert_stop_before_bind(carrier: Carrier) { + let mut observed = Vec::new(); + for cipher in ciphers() { + let config = carrier.config(cipher); + let owner = owner(&config); + let (stream, state) = unbound(&config); + let weak_state = Arc::downgrade(&state); + owner.begin_shutdown(); + let mut stream = owner.bind_stream(stream); + let count = Arc::new(Count::default()); + let weak_count = Arc::downgrade(&count); + let waker = Waker::from(count.clone()); + let read_aborted = matches!(Pin::new(&mut *stream).poll_read( + &mut Context::from_waker(&waker), &mut ReadBuf::new(&mut [0])), + Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::ConnectionAborted); + let write_aborted = ["write", "flush", "shutdown"].map(|operation| { + matches!(write_operation(&mut stream, &waker, operation), + Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::ConnectionAborted) + }); + let all_write_aborted = write_aborted.into_iter().all(|aborted| aborted); + let untouched_and_released = { + let state = state.lock().unwrap(); + state.polls == 0 && state.dropped + }; + owner.shutdown().await; + drop(stream); + drop(owner); + drop(waker); + drop(count); + assert!(state.lock().unwrap().dropped); + drop(state); + assert!(weak_state.upgrade().is_none() && weak_count.upgrade().is_none()); + observed.push(( + cipher, + read_aborted && all_write_aborted, + untouched_and_released, + )); + } + assert_eq!(observed.len(), 3); + assert!( + observed + .iter() + .all(|(_, aborted, untouched)| *aborted && *untouched), + "{carrier:?}: Stop-before-bind complete SS observations: {observed:?}" + ); +} + +pub(super) async fn assert_sibling_drop(carrier: Carrier) { + let mut observed = Vec::new(); + for cipher in ciphers() { + let config = carrier.config(cipher); + let owner = owner(&config); + let (first, first_state) = unbound(&config); + let (second, second_state) = unbound(&config); + let first_weak = Arc::downgrade(&first_state); + let second_weak = Arc::downgrade(&second_state); + let first = owner.bind_stream(first); + let mut second = owner.bind_stream(second); + drop(first); + let first_closed = { + let state = first_state.lock().unwrap(); + state.dropped && state.polls == 0 + }; + let parent_open = !owner.cancel.is_cancelled() && !*owner.closed.lock().unwrap(); + let count = Arc::new(Count::default()); + let weak_count = Arc::downgrade(&count); + let waker = Waker::from(count.clone()); + let payload = b"sibling-first-ss-payload"; + let accepts = matches!(Pin::new(&mut *second).poll_write(&mut Context::from_waker(&waker), payload), + Poll::Ready(Ok(n)) if n == payload.len()); + let pending = Pin::new(&mut *second) + .poll_read( + &mut Context::from_waker(&waker), + &mut ReadBuf::new(&mut [0]), + ) + .is_pending(); + let before = count.0.load(Ordering::SeqCst); + let raw_before = second_state.lock().unwrap().polls; + owner.begin_shutdown(); + let woke = count.0.load(Ordering::SeqCst) > before; + let aborted = matches!(Pin::new(&mut *second).poll_read(&mut Context::from_waker(&waker), + &mut ReadBuf::new(&mut [0])), Poll::Ready(Err(error)) + if error.kind() == io::ErrorKind::ConnectionAborted); + let released_without_repoll = { + let state = second_state.lock().unwrap(); + state.dropped && state.polls == raw_before + }; + owner.shutdown().await; + drop(second); + drop(owner); + drop(waker); + drop(count); + assert!(first_state.lock().unwrap().dropped && second_state.lock().unwrap().dropped); + drop(first_state); + drop(second_state); + assert!( + first_weak.upgrade().is_none() + && second_weak.upgrade().is_none() + && weak_count.upgrade().is_none() + ); + observed.push(( + cipher, + first_closed && parent_open && accepts && pending, + woke && aborted && released_without_repoll, + )); + } + assert_eq!(observed.len(), 3); + assert!( + observed + .iter() + .all(|(_, independent, stopped)| *independent && *stopped), + "{carrier:?}: complete SS child/sibling observations: {observed:?}" + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn obfs_owned_complete_ss_stream_stop_wakes_independent_pending_operations() { + for carrier in [Carrier::ObfsHttp, Carrier::ObfsTls] { + assert_pending_stop(carrier).await; + } +} + +#[tokio::test(flavor = "current_thread")] +async fn obfs_owned_stop_before_bind_rejects_complete_ss_without_touching_raw() { + for carrier in [Carrier::ObfsHttp, Carrier::ObfsTls] { + assert_stop_before_bind(carrier).await; + } +} + +#[tokio::test(flavor = "current_thread")] +async fn obfs_owned_child_drop_preserves_parent_and_sibling_until_parent_stop() { + for carrier in [Carrier::ObfsHttp, Carrier::ObfsTls] { + assert_sibling_drop(carrier).await; + } +} diff --git a/src/outbound/shadowsocks/plugin.rs b/src/outbound/shadowsocks/plugin.rs index 1f09db8..7289755 100644 --- a/src/outbound/shadowsocks/plugin.rs +++ b/src/outbound/shadowsocks/plugin.rs @@ -7,10 +7,19 @@ use crate::{ session::{Destination, StreamSession}, transport::{self, ss_framed}, }; -use std::{io, sync::Mutex}; +use futures_util::task::AtomicWaker; +use shadowsocks::crypto::CipherKind; +use std::{ + io, + pin::Pin, + sync::{Arc, Mutex}, + task::{Context, Poll, Wake, Waker}, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use tokio_util::{sync::CancellationToken, task::TaskTracker}; enum Kind { Security(SecurityClient), + ShadowTls(SecurityClient), Obfs { tls: bool, host: String, @@ -39,7 +48,7 @@ impl Owner { ) -> io::Result { let kind = match config { ShadowsocksPlugin::ShadowTls(config) => { - Kind::Security(SecurityClient::from_security_with_context( + Kind::ShadowTls(SecurityClient::from_security_with_context( &SecurityConfig::ShadowTls(config.clone()), context, 0, @@ -88,6 +97,66 @@ impl Owner { closed: Mutex::new(false), }) } + // Immutable factory shapes, independent of HTTP features and liveness. + // Binding must still use the same shape after a Stop race. + fn has_static_obfs_kind(&self) -> bool { + matches!(&self.kind, Kind::Obfs { .. }) + } + + fn has_static_v2ray_mux_kind(&self) -> bool { + matches!( + &self.kind, + Kind::WebSocket { + security: None, + transport: StreamTransport::WebSocket { + handshake: crate::config::WebSocketHandshake::WebSocket, + max_early_data: 0, + .. + }, + gost: false, + mux: true, + } + ) + } + + #[cfg(feature = "inbound-http")] + pub(super) fn permits_http_tcp_reuse(&self) -> bool { + !self.cancel.is_cancelled() + && !*self.closed.lock().unwrap() + && (self.has_static_obfs_kind() + || self.has_static_v2ray_mux_kind() + || matches!(&self.kind, Kind::ShadowTls(client) + if client.permits_ss_shadowtls_http_reuse())) + } + + pub(super) fn bind_stream(&self, stream: BoxStream) -> BoxStream { + if matches!(&self.kind, Kind::ShadowTls(_)) + || (cfg!(feature = "inbound-http") + && (self.has_static_obfs_kind() || self.has_static_v2ray_mux_kind())) + { + Box::new(ShadowTlsOwned::new(stream, self.cancel.child_token())) + } else { + stream + } + } + + // These exact carrier shapes need the official codec's complete first + // response prefix even across mux Data or WS Message boundaries. This is + // protocol I/O in every feature combination, separate from HTTP reuse. + pub(super) fn prepare_ss_response( + &self, + raw: BoxStream, + method: CipherKind, + ) -> io::Result { + if self.has_static_obfs_kind() || self.has_static_v2ray_mux_kind() { + Ok(Box::new(super::response_header::HeaderIo::new( + raw, method, + )?)) + } else { + Ok(raw) + } + } + pub(super) async fn open( &self, upstream: &UpstreamPath, @@ -100,7 +169,7 @@ impl Owner { result=async { let raw=upstream.connect_server(session,server,context).await?.io; match &self.kind { - Kind::Security(security)=>context.run_io("Shadowsocks plugin identity",security.connect_with_context(raw,context)).await, + Kind::Security(security)|Kind::ShadowTls(security)=>context.run_io("Shadowsocks plugin identity",security.connect_with_context(raw,context)).await, Kind::Obfs {tls,host,port}=>Ok(ss_framed::wrap(raw,if *tls{ss_framed::Kind::Tls {host:host.clone()}}else{ss_framed::Kind::Http {host:host.clone(),port:*port}})), Kind::WebSocket {security,transport,gost,mux}=>{ let raw=if let Some(security)=security {context.run_io("Shadowsocks plugin TLS",security.connect_with_context(raw,context)).await?}else{raw}; @@ -136,3 +205,359 @@ impl Owner { self.tasks.wait().await; } } + +// A ShadowTLS owner cancels a child per established SS stream. All underlying +// operations use one stable wake, preserving independently pending read/write +// callers even when OwnedStream's cancellation future records a newer poll. +struct ShadowTlsWake { + reader: AtomicWaker, + writer: AtomicWaker, +} +impl ShadowTlsWake { + fn wake_all(&self) { + self.reader.wake(); + self.writer.wake(); + } +} +impl Wake for ShadowTlsWake { + fn wake(self: Arc) { + self.wake_all(); + } + fn wake_by_ref(self: &Arc) { + self.wake_all(); + } +} +struct ShadowTlsOwned { + inner: OwnedStream, + wake: Arc, +} +impl ShadowTlsOwned { + fn new(stream: BoxStream, child: CancellationToken) -> Self { + Self { + inner: OwnedStream::new(stream, child), + wake: Arc::new(ShadowTlsWake { + reader: AtomicWaker::new(), + writer: AtomicWaker::new(), + }), + } + } + fn poll_io( + &mut self, + cx: &mut Context<'_>, + reader: bool, + operation: impl FnOnce(Pin<&mut OwnedStream>, &mut Context<'_>) -> Poll>, + ) -> Poll> { + let slot = if reader { + &self.wake.reader + } else { + &self.wake.writer + }; + slot.register(cx.waker()); + let waker = Waker::from(self.wake.clone()); + let result = operation(Pin::new(&mut self.inner), &mut Context::from_waker(&waker)); + if result.is_ready() { + drop(slot.take()); + } + result + } +} +impl AsyncRead for ShadowTlsOwned { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + self.get_mut() + .poll_io(cx, true, |inner, cx| inner.poll_read(cx, out)) + } +} +impl AsyncWrite for ShadowTlsOwned { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + self.get_mut() + .poll_io(cx, false, |inner, cx| inner.poll_write(cx, bytes)) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.get_mut() + .poll_io(cx, false, |inner, cx| inner.poll_flush(cx)) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.get_mut() + .poll_io(cx, false, |inner, cx| inner.poll_shutdown(cx)) + } +} +impl Drop for ShadowTlsOwned { + fn drop(&mut self) { + self.wake.wake_all(); + } +} + +#[cfg(all(test, feature = "inbound-http", feature = "shadow-tls-v3"))] +mod shadowtls_reuse_owner_tests { + use super::*; + use std::sync::atomic::{AtomicUsize, Ordering}; + #[derive(Default)] + struct State { + ready_read: bool, + block_write: bool, + dropped: bool, + read_waker: Option, + write_waker: Option, + } + struct Raw(Arc>); + impl Drop for Raw { + fn drop(&mut self) { + let mut s = self.0.lock().unwrap(); + s.read_waker.take(); + s.write_waker.take(); + s.dropped = true; + } + } + impl AsyncRead for Raw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + if out.remaining() == 0 { + return Poll::Ready(Ok(())); + } + let mut s = self.0.lock().unwrap(); + if s.ready_read { + out.put_slice(&[42]); + Poll::Ready(Ok(())) + } else { + s.read_waker = Some(cx.waker().clone()); + Poll::Pending + } + } + } + impl AsyncWrite for Raw { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let mut s = self.0.lock().unwrap(); + if s.block_write { + s.write_waker = Some(cx.waker().clone()); + Poll::Pending + } else { + Poll::Ready(Ok(bytes.len())) + } + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let mut s = self.0.lock().unwrap(); + if s.block_write { + s.write_waker = Some(cx.waker().clone()); + Poll::Pending + } else { + Poll::Ready(Ok(())) + } + } + fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + } + struct Count(AtomicUsize); + impl Wake for Count { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } + fn wake_by_ref(self: &Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } + } + fn owner() -> Owner { + Owner::new( + &ShadowsocksPlugin::ShadowTls(crate::config::ShadowTlsConfig { + server_name: "cover.invalid".into(), + password: "synthetic-relay".into(), + alpn: vec![], + required_alpn: None, + identity: None, + certificate: Default::default(), + client_fingerprint: None, + }), + &SecurityContext::new(), + 0, + 16384, + 443, + ) + .unwrap() + } + #[test] + fn shadowtls_owner_stop_wakes_independent_pending_callers_across_raw_operations() { + // 0: flush pending then read ready; 1/2: read pending then raw + // flush/shutdown ready; 3: read AND actual write pending under + // distinct outer wakers; 4: read pending then actual write ready. + // No raw event is externally fired in any case. + for operation in 0..5 { + let owner = owner(); + let state = Arc::new(Mutex::new(State { + ready_read: operation == 0, + block_write: operation == 0 || operation == 3, + ..Default::default() + })); + let raw_weak = Arc::downgrade(&state); + let mut io = owner.bind_stream(Box::new(Raw(state.clone()))); + let a = Arc::new(Count(AtomicUsize::new(0))); + let b = Arc::new(Count(AtomicUsize::new(0))); + let a_weak = Arc::downgrade(&a); + let b_weak = Arc::downgrade(&b); + let wa = Waker::from(a.clone()); + let wb = Waker::from(b.clone()); + let mut bytes = [0]; + let pending = if operation == 0 { + Pin::new(&mut *io) + .poll_flush(&mut Context::from_waker(&wa)) + .is_pending() + } else { + let mut out = ReadBuf::new(&mut bytes); + Pin::new(&mut *io) + .poll_read(&mut Context::from_waker(&wa), &mut out) + .is_pending() + && out.filled().is_empty() + }; + let independent_callers = !wa.will_wake(&wb); + let payload = b"guard-write"; + let other_operation_ok = if operation == 0 { + let mut out = ReadBuf::new(&mut bytes); + matches!( + Pin::new(&mut *io).poll_read(&mut Context::from_waker(&wb), &mut out), + Poll::Ready(Ok(())) + ) && out.filled() == &[42] + } else if operation == 1 { + matches!( + Pin::new(&mut *io).poll_flush(&mut Context::from_waker(&wb)), + Poll::Ready(Ok(())) + ) + } else if operation == 2 { + matches!( + Pin::new(&mut *io).poll_shutdown(&mut Context::from_waker(&wb)), + Poll::Ready(Ok(())) + ) + } else if operation == 3 { + Pin::new(&mut *io) + .poll_write(&mut Context::from_waker(&wb), payload) + .is_pending() + } else { + matches!(Pin::new(&mut *io).poll_write(&mut Context::from_waker(&wb), payload), + Poll::Ready(Ok(count)) if count == payload.len()) + }; + let raw_both_registered = { + let s = state.lock().unwrap(); + s.read_waker.is_some() && s.write_waker.is_some() + }; + let before_b = b.0.load(Ordering::SeqCst); + let before = a.0.load(Ordering::SeqCst); + owner.begin_shutdown(); + // Snapshot cancellation BEFORE stream Drop can wake waiter slots. + let at_cancel = a.0.load(Ordering::SeqCst); + let b_at_cancel = b.0.load(Ordering::SeqCst); + let parent_cancelled = owner.cancel.is_cancelled(); + let revoked = !owner.permits_http_tcp_reuse(); + let stopped = if operation == 0 { + Pin::new(&mut *io).poll_flush(&mut Context::from_waker(&wa)) + } else { + Pin::new(&mut *io) + .poll_read(&mut Context::from_waker(&wa), &mut ReadBuf::new(&mut bytes)) + }; + let aborted = matches!(&stopped, Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::ConnectionAborted); + let other_aborted = operation != 3 + || matches!( + Pin::new(&mut *io).poll_write(&mut Context::from_waker(&wb), payload), + Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::ConnectionAborted); + drop(io); + drop(owner); + drop(wa); + drop(wb); + drop(a); + drop(b); + let raw_closed = { + let s = state.lock().unwrap(); + s.dropped && s.read_waker.is_none() && s.write_waker.is_none() + }; + drop(state); + let all_closed = raw_weak.upgrade().is_none() + && a_weak.upgrade().is_none() + && b_weak.upgrade().is_none(); + assert!(raw_closed && all_closed); + assert!( + independent_callers + && pending + && other_operation_ok + && parent_cancelled + && revoked + && aborted + && other_aborted + ); + if operation == 3 { + assert!(raw_both_registered); + assert_eq!(before_b, 0); + assert!(b_at_cancel > before_b, "stop stranded the pending writer"); + } + assert_eq!(before, 0, "prerequisite caller was already notified"); + assert!( + at_cancel > before, + "parent stop stranded an independent pending caller" + ); + } + } + #[test] + fn shadowtls_stream_drop_cancels_only_its_child_and_parent_stop_retires_sibling() { + let owner = owner(); + let first = Arc::new(Mutex::new(State::default())); + let second = Arc::new(Mutex::new(State::default())); + let first_weak = Arc::downgrade(&first); + let second_weak = Arc::downgrade(&second); + let a = Arc::new(Count(AtomicUsize::new(0))); + let a_weak = Arc::downgrade(&a); + let wa = Waker::from(a.clone()); + let first_io = owner.bind_stream(Box::new(Raw(first.clone()))); + let mut second_io = owner.bind_stream(Box::new(Raw(second.clone()))); + drop(first_io); + let owner_open = !owner.cancel.is_cancelled() && owner.permits_http_tcp_reuse(); + let mut bytes = [0]; + let pending = Pin::new(&mut *second_io) + .poll_read(&mut Context::from_waker(&wa), &mut ReadBuf::new(&mut bytes)) + .is_pending(); + let before = a.0.load(Ordering::SeqCst); + owner.begin_shutdown(); + let at_cancel = a.0.load(Ordering::SeqCst); + let stopped = Pin::new(&mut *second_io) + .poll_read(&mut Context::from_waker(&wa), &mut ReadBuf::new(&mut bytes)); + let aborted = matches!(&stopped, Poll::Ready(Err(error)) if error.kind() == io::ErrorKind::ConnectionAborted); + let revoked = !owner.permits_http_tcp_reuse(); + drop(second_io); + drop(owner); + drop(wa); + drop(a); + let raw_closed = first.lock().unwrap().dropped && second.lock().unwrap().dropped; + drop(first); + drop(second); + let all_closed = first_weak.upgrade().is_none() + && second_weak.upgrade().is_none() + && a_weak.upgrade().is_none(); + assert!(raw_closed && all_closed); + assert!(owner_open && pending && revoked && aborted); + assert_eq!(before, 0); + assert!(at_cancel > before); + } +} + +#[cfg(all(test, feature = "inbound-http"))] +#[path = "obfs_reuse_owner_memory_tests.rs"] +mod obfs_reuse_owner_memory_tests; + +#[cfg(all(test, feature = "inbound-http"))] +pub(super) mod obfs_reuse_memory_tests; + +#[cfg(all(test, feature = "inbound-http"))] +mod v2ray_mux_reuse_owner_memory_tests; + +#[cfg(all(test, feature = "inbound-http"))] +pub(super) mod v2ray_mux_reuse_memory_tests; diff --git a/src/outbound/shadowsocks/plugin/obfs_reuse_memory_tests.rs b/src/outbound/shadowsocks/plugin/obfs_reuse_memory_tests.rs new file mode 100644 index 0000000..9344d08 --- /dev/null +++ b/src/outbound/shadowsocks/plugin/obfs_reuse_memory_tests.rs @@ -0,0 +1,1105 @@ +//! Memory-only SS2022 plus simple-obfs continuity. The cover peer is a finite +//! Rust model, not an execution of the official C or Go peer. Its fields follow +//! shadowsocks/simple-obfs src/obfs_tls.c and MetaCubeX/mihomo's +//! transport/simple-obfs/{http_server,tls_server}.go. SS authentication and the +//! destination prelude are decoded by the official Rust ProxyServerStream. +//! The injected upstream supplies IO only and provides no static-reuse proof. +use super::Owner; +use crate::{ + config::{ShadowsocksCipher, ShadowsocksPlugin}, + dispatch::{BoxStream, DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, UpstreamPath, + }, + security::SecurityContext, + session::{Destination, InboundKind, StreamSession}, +}; +use async_trait::async_trait; +use base64::{ + Engine as _, + engine::general_purpose::{STANDARD, URL_SAFE}, +}; +use bytes::{Buf, Bytes}; +use futures_util::FutureExt; +use shadowsocks::{ + ServerConfig, config::ServerType, context::Context as SsContext, + relay::tcprelay::proxy_stream::ProxyServerStream, +}; +use std::{ + future::{Future, poll_fn}, + io, + panic::AssertUnwindSafe, + pin::Pin, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + task::{Context, Poll, ready}, + time::Duration, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, DuplexStream, ReadBuf}, + sync::oneshot, + time::timeout, +}; + +const ENTITY: usize = 64 * 1024; +const COVER_HOST: &str = "cover.invalid"; +const PEER_CHUNK: usize = 1024; +const CLIENT_CHUNK: usize = 16 * 1024; +const WAIT: Duration = Duration::from_secs(20); + +pub(in crate::outbound::shadowsocks) type Accept = + Pin> + Send + 'static>>; +fn invalid(message: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, message) +} +fn check(value: bool, message: &'static str) -> io::Result<()> { + if value { Ok(()) } else { Err(invalid(message)) } +} +// Fixed operation labels and ErrorKind only: never format the underlying +// official-codec error, a key, nonce, payload, or arbitrary peer data. +fn stage(name: &'static str, result: io::Result) -> io::Result { + result.map_err(|error| { + io::Error::new( + error.kind(), + format!("stage={name}; kind={:?}", error.kind()), + ) + }) +} +fn require_pending(result: Poll>, message: &'static str) -> io::Result<()> { + match result { + Poll::Pending => Ok(()), + Poll::Ready(Err(error)) => Err(error), + Poll::Ready(Ok(_)) => Err(invalid(message)), + } +} +#[derive(Default)] +struct Counts { + opens: AtomicUsize, + target_handshakes: AtomicUsize, + cover_requests: AtomicUsize, + cover_responses: AtomicUsize, + client_drops: AtomicUsize, + peer_drops: AtomicUsize, + client_write_pending: AtomicUsize, + peer_write_pending: AtomicUsize, + partial_writes: AtomicUsize, +} +#[derive(Clone, Copy, Debug)] +pub(in crate::outbound::shadowsocks) struct ObfsMemoryReceipt { + pub(in crate::outbound::shadowsocks) opens: usize, + pub(in crate::outbound::shadowsocks) target_handshakes: usize, + pub(in crate::outbound::shadowsocks) cover_requests: usize, + pub(in crate::outbound::shadowsocks) cover_responses: usize, + pub(in crate::outbound::shadowsocks) client_drops: usize, + pub(in crate::outbound::shadowsocks) peer_drops: usize, + pub(in crate::outbound::shadowsocks) client_write_pending: usize, + pub(in crate::outbound::shadowsocks) peer_write_pending: usize, + pub(in crate::outbound::shadowsocks) partial_writes: usize, + pub(in crate::outbound::shadowsocks) owner_cancelled: bool, + pub(in crate::outbound::shadowsocks) owner_closed: bool, + pub(in crate::outbound::shadowsocks) owner_wait_returned: bool, +} +pub(in crate::outbound::shadowsocks) struct ObfsMemoryGuard { + owner: Arc, + counts: Arc, + waited: AtomicBool, +} +impl ObfsMemoryGuard { + pub(in crate::outbound::shadowsocks) fn begin_shutdown(&self) { + self.owner.begin_shutdown(); + } + pub(in crate::outbound::shadowsocks) async fn shutdown(&self) { + self.owner.shutdown().await; + self.waited.store(true, Ordering::SeqCst); + } + pub(in crate::outbound::shadowsocks) fn receipt(&self) -> ObfsMemoryReceipt { + let load = |value: &AtomicUsize| value.load(Ordering::SeqCst); + ObfsMemoryReceipt { + opens: load(&self.counts.opens), + target_handshakes: load(&self.counts.target_handshakes), + cover_requests: load(&self.counts.cover_requests), + cover_responses: load(&self.counts.cover_responses), + client_drops: load(&self.counts.client_drops), + peer_drops: load(&self.counts.peer_drops), + client_write_pending: load(&self.counts.client_write_pending), + peer_write_pending: load(&self.counts.peer_write_pending), + partial_writes: load(&self.counts.partial_writes), + owner_cancelled: self.owner.cancel.is_cancelled(), + owner_closed: *self.owner.closed.lock().unwrap(), + owner_wait_returned: self.waited.load(Ordering::SeqCst), + } + } +} +impl Drop for ObfsMemoryGuard { + fn drop(&mut self) { + self.owner.begin_shutdown(); + } +} +pub(in crate::outbound::shadowsocks) struct MemoryCarrier { + pub(in crate::outbound::shadowsocks) client: BoxStream, + pub(in crate::outbound::shadowsocks) accept: Accept, + pub(in crate::outbound::shadowsocks) guard: ObfsMemoryGuard, + pub(in crate::outbound::shadowsocks) peer_write_blocked: oneshot::Receiver<()>, +} + +struct Raw { + io: DuplexStream, + counts: Arc, +} +impl Drop for Raw { + fn drop(&mut self) { + self.counts.client_drops.fetch_add(1, Ordering::SeqCst); + } +} +impl AsyncRead for Raw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_read(cx, out) + } +} +impl AsyncWrite for Raw { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let this = self.get_mut(); + let result = Pin::new(&mut this.io).poll_write(cx, bytes); + match &result { + Poll::Pending => { + this.counts + .client_write_pending + .fetch_add(1, Ordering::SeqCst); + } + Poll::Ready(Ok(n)) if *n < bytes.len() => { + this.counts.partial_writes.fetch_add(1, Ordering::SeqCst); + } + _ => {} + } + result + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_shutdown(cx) + } +} +struct MemoryUpstream { + io: Mutex>, + server: Destination, + counts: Arc, +} +#[async_trait] +impl OutboundConnector for MemoryUpstream { + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + if session.destination != self.server { + return Err(DispatchError::NotAllowed); + } + let io = self + .io + .lock() + .unwrap() + .take() + .ok_or(DispatchError::NotAllowed)?; + self.counts.opens.fetch_add(1, Ordering::SeqCst); + Ok(ConnectedStream { + io, + effective_peer: self.server.clone(), + }) + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +// A bounded cover decoder/encoder. Collect the first declared cover payload +// before exposing it to the official SS codec's existing first-read probe. +// Subsequent bytes are transparent HTTP data or bounded TLS-shaped records. +struct CoverPeer { + io: DuplexStream, + tls: bool, + counts: Arc, + first_read: bool, + head: Vec, + initial_head: Option, + initial_length: usize, + payload: Bytes, + remaining: usize, + first_write: bool, + pending: Bytes, + write_blocked: Option>, +} +impl Drop for CoverPeer { + fn drop(&mut self) { + self.counts.peer_drops.fetch_add(1, Ordering::SeqCst); + } +} +impl CoverPeer { + fn fill(&mut self, cx: &mut Context<'_>, target: usize) -> Poll> { + if target > CLIENT_CHUNK + 512 { + return Poll::Ready(Err(invalid("cover head bound"))); + } + for _ in 0..64 { + if self.head.len() >= target { + return Poll::Ready(Ok(true)); + } + let mut bytes = [0; 64]; + let amount = (target - self.head.len()).min(bytes.len()); + let mut read = ReadBuf::new(&mut bytes[..amount]); + ready!(Pin::new(&mut self.io).poll_read(cx, &mut read))?; + if read.filled().is_empty() { + return if self.head.is_empty() { + Poll::Ready(Ok(false)) + } else { + Poll::Ready(Err(invalid("truncated cover"))) + }; + } + self.head.extend_from_slice(read.filled()); + } + cx.waker().wake_by_ref(); + Poll::Pending + } + fn initial(&mut self, cx: &mut Context<'_>) -> Poll> { + if self.initial_head.is_none() { + if self.tls { + check(ready!(self.fill(cx, 5))?, "missing ClientHello")?; + check(self.head[..3] == [22, 3, 1], "ClientHello record")?; + self.initial_length = usize::from(u16::from_be_bytes([self.head[3], self.head[4]])); + self.initial_head = Some(5); + } else { + for _ in 0..256 { + let target = self.head.len() + 1; + check(ready!(self.fill(cx, target))?, "missing HTTP cover")?; + if self.head.ends_with(b"\r\n\r\n") { + self.initial_length = http_length(&self.head)?; + self.initial_head = Some(self.head.len()); + break; + } + } + if self.initial_head.is_none() { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + } + } + let head = self.initial_head.expect("initialized cover prefix"); + check( + ready!(self.fill(cx, head + self.initial_length))?, + "missing initial cover payload", + )?; + self.payload = if self.tls { + tls_ticket(&self.head[head..])? + } else { + Bytes::copy_from_slice(&self.head[head..]) + }; + self.head.clear(); + self.first_read = false; + self.counts.cover_requests.fetch_add(1, Ordering::SeqCst); + Poll::Ready(Ok(())) + } + fn drain(&mut self, cx: &mut Context<'_>) -> Poll> { + for _ in 0..64 { + if self.pending.is_empty() { + return Poll::Ready(Ok(())); + } + let result = Pin::new(&mut self.io).poll_write(cx, &self.pending); + if result.is_pending() { + self.counts + .peer_write_pending + .fetch_add(1, Ordering::SeqCst); + if let Some(signal) = self.write_blocked.take() { + let _ = signal.send(()); + } + } + let count = ready!(result)?; + if count == 0 { + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); + } + if count < self.pending.len() { + self.counts.partial_writes.fetch_add(1, Ordering::SeqCst); + } + self.pending.advance(count); + } + cx.waker().wake_by_ref(); + Poll::Pending + } +} +fn http_length(head: &[u8]) -> io::Result { + let text = std::str::from_utf8(head).map_err(|_| invalid("HTTP cover text"))?; + let mut lines = text.split("\r\n"); + check(lines.next() == Some("GET / HTTP/1.1"), "HTTP request line")?; + let mut length = None; + let mut host = false; + let mut key = false; + let mut connection_upgrade = false; + let mut websocket_upgrade = false; + for line in lines.filter(|line| !line.is_empty()) { + let (name, value) = line.split_once(':').ok_or_else(|| invalid("HTTP field"))?; + let value = value.trim(); + if name.eq_ignore_ascii_case("host") { + host = value == "cover.invalid:443"; + } + if name.eq_ignore_ascii_case("content-length") { + check(length.is_none(), "duplicate length")?; + length = Some(value.parse::().map_err(|_| invalid("HTTP length"))?); + } + if name.eq_ignore_ascii_case("connection") { + connection_upgrade = value + .split(',') + .any(|token| token.trim().eq_ignore_ascii_case("upgrade")); + } + if name.eq_ignore_ascii_case("upgrade") { + websocket_upgrade = value.eq_ignore_ascii_case("websocket"); + } + if name.eq_ignore_ascii_case("sec-websocket-key") { + key = URL_SAFE.decode(value).is_ok_and(|nonce| nonce.len() == 16); + } + } + let length = length.ok_or_else(|| invalid("missing HTTP length"))?; + check( + host && key + && connection_upgrade + && websocket_upgrade + && length > 0 + && length <= CLIENT_CHUNK, + "HTTP cover metadata", + )?; + Ok(length) +} +fn tls_ticket(hello: &[u8]) -> io::Result { + check( + hello.len() >= 137 && hello[..1] == [1] && hello[4..6] == [3, 3], + "ClientHello shape", + )?; + let length = + (usize::from(hello[1]) << 16) | (usize::from(hello[2]) << 8) | usize::from(hello[3]); + check( + length + 4 == hello.len() + && hello[38] == 32 + && hello[71..73] == [0, 56] + && hello[129..131] == [1, 0], + "ClientHello fixed fields", + )?; + let extensions = usize::from(u16::from_be_bytes([hello[131], hello[132]])); + check( + extensions == hello.len() - 133, + "ClientHello extensions length", + )?; + let mut position = 133; + let mut ticket = None; + let mut sni = false; + while position < hello.len() { + check(hello.len() - position >= 4, "short extension")?; + let kind = u16::from_be_bytes([hello[position], hello[position + 1]]); + let size = usize::from(u16::from_be_bytes([ + hello[position + 2], + hello[position + 3], + ])); + position += 4; + check(size <= hello.len() - position, "extension bound")?; + let value = &hello[position..position + size]; + if kind == 35 { + check( + ticket.is_none() && !value.is_empty() && value.len() <= CLIENT_CHUNK, + "ticket bound", + )?; + ticket = Some(Bytes::copy_from_slice(value)); + } else if kind == 0 { + check(value.len() >= 5 && value[2] == 0, "SNI shape")?; + let list = usize::from(u16::from_be_bytes([value[0], value[1]])); + let name = usize::from(u16::from_be_bytes([value[3], value[4]])); + sni = list + 2 == value.len() + && name + 5 == value.len() + && &value[5..] == COVER_HOST.as_bytes(); + } + position += size; + } + check(sni, "cover SNI")?; + ticket.ok_or_else(|| invalid("missing session ticket")) +} +fn server_hello(length: usize) -> Vec { + // The 96-byte ServerHello + 6-byte CCS + 5-byte encrypted-handshake + // prefix follows simple-obfs/Mihomo. Nonces are finite synthetic cover + // bytes; only the official SS codec below authenticates this test data. + let mut head = vec![22, 3, 1, 0, 91, 2, 0, 0, 87, 3, 3]; + head.extend_from_slice(&[0; 32]); + head.push(32); + head.extend_from_slice(&[0; 32]); + head.extend_from_slice(&[ + 0xcc, 0xa8, 0, 0, 0, 0xff, 1, 0, 1, 0, 0, 0x17, 0, 0, 0, 0x0b, 0, 2, 1, 0, + ]); + head.extend_from_slice(&[20, 3, 3, 0, 1, 1, 22, 3, 3]); + head.extend_from_slice(&(length as u16).to_be_bytes()); + head +} +impl AsyncRead for CoverPeer { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if out.remaining() == 0 { + return Poll::Ready(Ok(())); + } + if let Poll::Ready(result) = this.drain(cx) { + result?; + } + if this.first_read { + ready!(this.initial(cx))?; + } + if !this.payload.is_empty() { + let count = this.payload.len().min(out.remaining()); + out.put_slice(&this.payload[..count]); + this.payload.advance(count); + return Poll::Ready(Ok(())); + } + if !this.tls { + return Pin::new(&mut this.io).poll_read(cx, out); + } + if this.remaining == 0 { + if !ready!(this.fill(cx, 5))? { + return Poll::Ready(Ok(())); + } + check(this.head[..3] == [23, 3, 3], "subsequent TLS record")?; + this.remaining = usize::from(u16::from_be_bytes([this.head[3], this.head[4]])); + check( + this.remaining > 0 && this.remaining <= CLIENT_CHUNK, + "TLS record payload bound", + )?; + this.head.clear(); + } + let count = this.remaining.min(out.remaining()); + let mut part = ReadBuf::new(out.initialize_unfilled_to(count)); + ready!(Pin::new(&mut this.io).poll_read(cx, &mut part))?; + let count = part.filled().len(); + check(count > 0, "truncated TLS data")?; + out.advance(count); + this.remaining -= count; + Poll::Ready(Ok(())) + } +} +impl AsyncWrite for CoverPeer { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + let this = self.get_mut(); + ready!(this.drain(cx))?; + if input.is_empty() { + return Poll::Ready(Ok(0)); + } + let count = input.len().min(PEER_CHUNK); + let mut bytes = if this.first_write { + this.counts.cover_responses.fetch_add(1, Ordering::SeqCst); + if this.tls { + server_hello(count) + } else { + b"HTTP/1.1 101 Switching Protocols\r\nConnection: Upgrade\r\nUpgrade: websocket\r\n\r\n".to_vec() + } + } else if this.tls { + let mut prefix = vec![23, 3, 3]; + prefix.extend_from_slice(&(count as u16).to_be_bytes()); + prefix + } else { + Vec::new() + }; + bytes.extend_from_slice(&input[..count]); + this.first_write = false; + this.pending = bytes.into(); + if let Poll::Ready(result) = this.drain(cx) { + result?; + } + Poll::Ready(Ok(count)) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + ready!(this.drain(cx))?; + Pin::new(&mut this.io).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + ready!(this.drain(cx))?; + Pin::new(&mut this.io).poll_shutdown(cx) + } +} + +pub(in crate::outbound::shadowsocks) async fn memory_carrier( + cipher: ShadowsocksCipher, + tls: bool, + target: Destination, + capacity: usize, +) -> io::Result { + check( + (1..=4096).contains(&capacity), + "bounded memory carrier capacity", + )?; + let key = vec![7; cipher.key_len()]; + let method = cipher + .as_str() + .parse() + .map_err(|_| invalid("test cipher"))?; + let config = ServerConfig::new(("127.0.0.1", 12345), STANDARD.encode(&key), method) + .map_err(|_| invalid("test server configuration"))?; + let counts = Arc::new(Counts::default()); + let owner = Arc::new(Owner::new( + &ShadowsocksPlugin::Obfs { + tls, + host: COVER_HOST.into(), + }, + &SecurityContext::new(), + 0, + 16 * 1024, + 443, + )?); + let guard = ObfsMemoryGuard { + owner: owner.clone(), + counts: counts.clone(), + waited: AtomicBool::new(false), + }; + let server: Destination = Destination::Ip("127.0.0.1:12345".parse().unwrap()); + let (client, peer) = tokio::io::duplex(capacity); + let upstream = UpstreamPath::Proxy(Arc::new(MemoryUpstream { + io: Mutex::new(Some(Box::new(Raw { + io: client, + counts: counts.clone(), + }))), + server: server.clone(), + counts: counts.clone(), + })); + let session = StreamSession { + metadata: Default::default(), + inbound: InboundKind::Http, + source: "127.0.0.1:10000".parse().unwrap(), + destination: target.clone(), + sniffed_domain: None, + }; + let raw = match owner + .open(&upstream, &server, session, &EstablishContext::default()) + .await + { + Ok(raw) => raw, + Err(_) => { + guard.shutdown().await; + return Err(invalid("actual plugin open failed")); + } + }; + // Use the actual production Obfs preparation exactly once, including R4. + let raw = match owner.prepare_ss_response(raw, method) { + Ok(raw) => raw, + Err(error) => { + guard.shutdown().await; + return Err(error); + } + }; + let target = super::super::address(&target); + let stream = super::super::stream::SsStream::new( + SsContext::new_shared(ServerType::Local), + raw, + &config, + target.clone(), + ); + let client = owner.bind_stream(Box::new(stream)); + let (signal, peer_write_blocked) = oneshot::channel(); + let peer = CoverPeer { + io: peer, + tls, + counts: counts.clone(), + first_read: true, + head: Vec::new(), + initial_head: None, + initial_length: 0, + payload: Bytes::new(), + remaining: 0, + first_write: true, + pending: Bytes::new(), + write_blocked: Some(signal), + }; + let mut peer = ProxyServerStream::from_stream( + SsContext::new_shared(ServerType::Server), + peer, + method, + &key, + ); + let authenticated = counts.clone(); + let accept = Box::pin(async move { + let observed = stage( + "peer.official-handshake", + peer.handshake().await.map_err(Into::into), + )?; + check(observed == target, "official SS target mismatch")?; + authenticated + .target_handshakes + .fetch_add(1, Ordering::SeqCst); + Ok(Box::new(peer) as BoxStream) + }); + Ok(MemoryCarrier { + client, + accept, + guard, + peer_write_blocked, + }) +} + +async fn entity( + io: &mut (impl AsyncRead + Unpin), + expected: u8, + name: &'static str, +) -> io::Result<()> { + let mut bytes = vec![0; ENTITY]; + stage(name, io.read_exact(&mut bytes).await)?; + if bytes.iter().all(|byte| *byte == expected) { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::InvalidData, + format!("stage={name}; kind=InvalidData; expected-synthetic-byte={expected:#04x}"), + )) + } +} + +async fn exchange_io( + client: BoxStream, + accept: Accept, + peer_write_blocked: oneshot::Receiver<()>, + counts: Arc, +) -> io::Result<((), ())> { + let (allow, allowed) = oneshot::channel(); + tokio::try_join!( + async move { + let (mut read, mut write) = tokio::io::split(client); + stage("client.marker.write", write.write_all(b"!").await)?; + stage("client.marker.flush", write.flush().await)?; + let before = counts.client_write_pending.load(Ordering::SeqCst); + let mut payload = vec![0x31; ENTITY]; + payload.extend_from_slice(&vec![0x32; ENTITY]); + let mut upload = Box::pin(async { + stage("client.upload.write", write.write_all(&payload).await)?; + stage("client.upload.flush", write.flush().await) + }); + require_pending( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))).await, + "duplex must block real SS upload", + )?; + check( + counts.client_write_pending.load(Ordering::SeqCst) > before, + "upload must hit actual raw backpressure", + )?; + peer_write_blocked + .await + .map_err(|_| invalid("peer never hit real TX backpressure"))?; + entity(&mut read, 0x91, "client.response-one.read").await?; + require_pending( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))).await, + "RX must finish while TX remains blocked", + )?; + let mut second = Box::pin(entity(&mut read, 0x92, "client.response-two.read")); + require_pending( + poll_fn(|cx| Poll::Ready(second.as_mut().poll(cx))).await, + "second entity must await upload", + )?; + allow + .send(()) + .map_err(|_| invalid("peer upload gate lost"))?; + tokio::try_join!(upload.as_mut(), second.as_mut())?; + drop((upload, second)); + stage("client.shutdown", write.shutdown().await)?; + let mut extra = [0]; + check( + stage("client.response-eof.read", read.read(&mut extra).await)? == 0, + "extra response bytes", + )?; + Ok::<_, io::Error>(()) + }, + async move { + let mut peer = accept.await?; + let mut begin = [0]; + stage("peer.marker.read", peer.read_exact(&mut begin).await)?; + check(begin == [b'!'], "SS initial payload")?; + stage( + "peer.response-one.write", + peer.write_all(&vec![0x91; ENTITY]).await, + )?; + stage("peer.response-one.flush", peer.flush().await)?; + allowed + .await + .map_err(|_| invalid("client did not release RX gate"))?; + entity(&mut peer, 0x31, "peer.upload-one.read").await?; + entity(&mut peer, 0x32, "peer.upload-two.read").await?; + stage( + "peer.response-two.write", + peer.write_all(&vec![0x92; ENTITY]).await, + )?; + stage("peer.response-two.flush", peer.flush().await)?; + let mut extra = [0]; + check( + stage("peer.upload-eof.read", peer.read(&mut extra).await)? == 0, + "duplicate target or upload bytes", + )?; + stage("peer.shutdown", peer.shutdown().await)?; + Ok::<_, io::Error>(()) + } + ) +} + +async fn exchange(cipher: ShadowsocksCipher, tls: bool) { + let MemoryCarrier { + client, + accept, + guard, + peer_write_blocked, + } = memory_carrier( + cipher, + tls, + Destination::domain("memory-obfs.invalid", 443).unwrap(), + 64, + ) + .await + .unwrap(); + let counts = guard.counts.clone(); + let outcome = AssertUnwindSafe(timeout( + WAIT, + exchange_io(client, accept, peer_write_blocked, counts), + )) + .catch_unwind() + .await; + let owner_cancelled_before_cleanup = guard.owner.cancel.is_cancelled(); + guard.shutdown().await; + let receipt = guard.receipt(); + drop(guard); + match outcome { + Err(panic) => std::panic::resume_unwind(panic), + Ok(Err(_)) => panic!("{cipher:?}/tls={tls}: memory exchange deadline; {receipt:?}"), + Ok(Ok(Err(error))) => panic!( + "{cipher:?}/tls={tls}: {error}; owner_cancelled_before_cleanup={owner_cancelled_before_cleanup}; {receipt:?}" + ), + Ok(Ok(Ok(_))) => {} + } + assert_eq!( + ( + receipt.opens, + receipt.target_handshakes, + receipt.cover_requests, + receipt.cover_responses + ), + (1, 1, 1, 1) + ); + assert_eq!((receipt.client_drops, receipt.peer_drops), (1, 1)); + assert!( + receipt.client_write_pending > 0 + && receipt.peer_write_pending > 0 + && receipt.partial_writes > 0 + ); + assert!(receipt.owner_cancelled && receipt.owner_closed && receipt.owner_wait_returned); +} + +#[tokio::test] +async fn header_probe_covered_ss_all_ciphers_and_modes_preserves_actual_owned_pipeline() { + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + for tls in [false, true] { + exchange(cipher, tls).await; + } + } +} + +// The accept future owns the real peer before its first poll. Cancellation is +// observable independently of either endpoint drop and of the owner wait. +#[tokio::test] +async fn unpolled_memory_accept_drop_is_counted_separately_from_owner_shutdown() { + for tls in [false, true] { + let MemoryCarrier { + client, + accept, + guard, + peer_write_blocked, + } = memory_carrier( + ShadowsocksCipher::Aes128Gcm, + tls, + Destination::domain("memory-obfs.invalid", 443).unwrap(), + 64, + ) + .await + .unwrap(); + guard.begin_shutdown(); + let cancelled = guard.receipt(); + drop((client, accept, peer_write_blocked)); + guard.shutdown().await; + let receipt = guard.receipt(); + drop(guard); + assert!( + cancelled.owner_cancelled && cancelled.owner_closed && !cancelled.owner_wait_returned + ); + assert_eq!( + ( + cancelled.client_drops, + cancelled.peer_drops, + cancelled.target_handshakes + ), + (0, 0, 0) + ); + assert_eq!( + (receipt.opens, receipt.client_drops, receipt.peer_drops), + (1, 1, 1) + ); + assert_eq!( + ( + receipt.target_handshakes, + receipt.cover_requests, + receipt.cover_responses + ), + (0, 0, 0) + ); + assert!(receipt.owner_cancelled && receipt.owner_closed && receipt.owner_wait_returned); + } +} + +// Actual UoT factory gate: this raw adapter never buffers or frames. It only +// counts calls and delegates to the memory duplex, so an accidental empty SS +// initialization would be observed as a write and nonempty peer bytes. +#[derive(Default)] +struct NeverSentCounts { + reads: AtomicUsize, + writes: AtomicUsize, + flushes: AtomicUsize, + shutdowns: AtomicUsize, + drops: AtomicUsize, +} +#[derive(Clone, Copy, Debug)] +struct NeverSentSnapshot { + reads: usize, + writes: usize, + flushes: usize, + shutdowns: usize, + drops: usize, +} +impl NeverSentCounts { + fn snapshot(&self) -> NeverSentSnapshot { + NeverSentSnapshot { + reads: self.reads.load(Ordering::SeqCst), + writes: self.writes.load(Ordering::SeqCst), + flushes: self.flushes.load(Ordering::SeqCst), + shutdowns: self.shutdowns.load(Ordering::SeqCst), + drops: self.drops.load(Ordering::SeqCst), + } + } +} +struct NeverSentRaw { + io: DuplexStream, + counts: Arc, +} +impl Drop for NeverSentRaw { + fn drop(&mut self) { + self.counts.drops.fetch_add(1, Ordering::SeqCst); + } +} +impl AsyncRead for NeverSentRaw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + this.counts.reads.fetch_add(1, Ordering::SeqCst); + Pin::new(&mut this.io).poll_read(cx, out) + } +} +impl AsyncWrite for NeverSentRaw { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let this = self.get_mut(); + this.counts.writes.fetch_add(1, Ordering::SeqCst); + Pin::new(&mut this.io).poll_write(cx, bytes) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + this.counts.flushes.fetch_add(1, Ordering::SeqCst); + Pin::new(&mut this.io).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + this.counts.shutdowns.fetch_add(1, Ordering::SeqCst); + Pin::new(&mut this.io).poll_shutdown(cx) + } +} + +#[tokio::test(flavor = "current_thread")] +async fn obfs_uot_never_sent_actual_factory_close_drop_and_retained_stop_join_without_raw_io() { + use crate::{ + config::{Config, ProxyProtocol}, + outbound::ShadowsocksOutbound, + session::DatagramSession, + }; + let request = || { + DatagramRequest::new(DatagramSession::new( + InboundKind::Socks5, + "127.0.0.1:1234".parse().unwrap(), + )) + }; + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + for tls in [false, true] { + for ending in ["close", "drop", "stop"] { + // Same public UoT v2 construction as the existing standalone + // never-sent regression, with actual Obfs added to the node. + let input = serde_json::json!({ + "mixed-port": 1080, + "proxies": [{ + "name": "obfs-uot", "type": "ss", "server": "127.0.0.1", "port": 12345, + "cipher": cipher.as_str(), "password": STANDARD.encode(vec![7; cipher.key_len()]), + "udp": true, "udp-over-tcp": true, "udp-over-tcp-version": 2, + "plugin": "obfs", "plugin-opts": {"mode": if tls {"tls"} else {"http"}, "host": COVER_HOST}, + }], + "rules": ["MATCH,obfs-uot"], + }); + let parsed = Config::parse_yaml(&serde_json::to_vec(&input).unwrap()).unwrap(); + let ProxyProtocol::Shadowsocks(config) = &parsed.proxies[0].protocol else { + panic!("actual SS configuration expected") + }; + let counts = Arc::new(NeverSentCounts::default()); + let opens = Arc::new(Counts::default()); + let (raw, mut peer) = tokio::io::duplex(64); + let raw_weak = Arc::downgrade(&counts); + let upstream = UpstreamPath::Proxy(Arc::new(MemoryUpstream { + io: Mutex::new(Some(Box::new(NeverSentRaw { + io: raw, + counts: counts.clone(), + }))), + server: Destination::Ip("127.0.0.1:12345".parse().unwrap()), + counts: opens.clone(), + })); + let outbound = ShadowsocksOutbound::new_with_path(config, upstream).unwrap(); + let mut association: Option> = None; + let outcome = AssertUnwindSafe(timeout(WAIT, async { + association = Some( + OutboundConnector::open_datagram( + &outbound, + request(), + &EstablishContext::default(), + ) + .await + .map_err(|_| invalid("uot.actual-open-datagram"))?, + ); + let shared = association.as_ref().unwrap().supports_shared_destinations(); + // Give the actual registered UoT reader opportunities to + // poll its FirstWrite gate; no synthetic reader is used. + for _ in 0..16 { + tokio::task::yield_now().await; + } + let before = counts.snapshot(); + match ending { + "close" => association + .as_mut() + .unwrap() + .close() + .await + .map_err(|_| invalid("uot.never-sent-close"))?, + "drop" => drop(association.take()), + "stop" => OutboundConnector::shutdown(&outbound).await, + _ => unreachable!(), + } + Ok::<_, io::Error>((before, shared)) + })) + .catch_unwind() + .await; + // The actual node barrier joins both its plugin and UoT owner. + // It runs even after open/close error, timeout or caught panic. + OutboundConnector::shutdown(&outbound).await; + let after_join = counts.snapshot(); + let retained_after_join = association.is_some(); + let open_count = opens.opens.load(Ordering::SeqCst); + // Retained Stop must have released raw before this Drop. Then + // release all remaining external handles on every outcome. + drop(association.take()); + OutboundConnector::shutdown(&outbound).await; + let mut wire = Vec::new(); + let eof = timeout(Duration::from_secs(1), peer.read_to_end(&mut wire)).await; + let eof_clean = matches!(eof, Ok(Ok(0))); + let wire_length = wire.len(); + drop(peer); + drop(outbound); + drop(opens); + let final_snapshot = counts.snapshot(); + drop(counts); + let raw_owner_released = raw_weak.upgrade().is_none(); + let (before, shared) = match outcome { + Err(panic) => std::panic::resume_unwind(panic), + Ok(Err(_)) => panic!( + "{cipher:?}/tls={tls}/ending={ending}: UoT gate deadline; after_join={after_join:?}; final={final_snapshot:?}" + ), + Ok(Ok(Err(error))) => panic!( + "{cipher:?}/tls={tls}/ending={ending}: {error}; after_join={after_join:?}; final={final_snapshot:?}" + ), + Ok(Ok(Ok(value))) => value, + }; + // Every assertion is after actual shutdown/join, both endpoint + // Drops and the peer EOF observation; no token-only receipt. + assert!( + shared && raw_owner_released && eof_clean && wire_length == 0, + "{cipher:?}/tls={tls}/ending={ending}: opens={open_count}; before={before:?}; after_join={after_join:?}; final={final_snapshot:?}; eof_clean={eof_clean}; wire_length={wire_length}" + ); + assert_eq!(open_count, 1); + assert_eq!( + ( + before.reads, + before.writes, + before.flushes, + before.shutdowns, + before.drops + ), + (0, 0, 0, 0, 0) + ); + assert_eq!( + ( + after_join.reads, + after_join.writes, + after_join.flushes, + after_join.shutdowns, + after_join.drops + ), + (0, 0, 0, 0, 1) + ); + assert_eq!( + ( + final_snapshot.reads, + final_snapshot.writes, + final_snapshot.flushes, + final_snapshot.shutdowns, + final_snapshot.drops + ), + (0, 0, 0, 0, 1) + ); + if ending == "stop" { + assert!( + retained_after_join, + "Stop proof lost its retained association" + ); + } + } + } + } +} diff --git a/src/outbound/shadowsocks/plugin/v2ray_mux_reuse_memory_tests.rs b/src/outbound/shadowsocks/plugin/v2ray_mux_reuse_memory_tests.rs new file mode 100644 index 0000000..7b6b295 --- /dev/null +++ b/src/outbound/shadowsocks/plugin/v2ray_mux_reuse_memory_tests.rs @@ -0,0 +1,1187 @@ +//! Memory WS/mux/SS continuity, with independent logical Data and WS Message +//! boundaries. The mux peer is a finite model of official frame.go/writer.go; +//! WS handshake/frame validation and SS authentication use the actual libraries. +//! It is not execution of an official Go server or static qualification proof. +use super::Owner; +use crate::{ + config::{Config, ProxyProtocol, ShadowsocksCipher}, + dispatch::{BoxStream, DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, UpstreamPath, + }, + security::SecurityContext, + session::{Destination, InboundKind, StreamSession}, +}; +use async_trait::async_trait; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use bytes::{Buf, Bytes}; +use futures_util::{FutureExt, Sink, Stream}; +use shadowsocks::{ + ServerConfig, config::ServerType, context::Context as SsContext, crypto::CipherKind, + relay::tcprelay::proxy_stream::ProxyServerStream, +}; +use std::{ + collections::VecDeque, + future::{Future, poll_fn}, + io, + panic::AssertUnwindSafe, + pin::Pin, + sync::{ + Arc, Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + task::{Context, Poll, ready}, + time::Duration, +}; +use tokio::{ + io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, DuplexStream, ReadBuf}, + sync::oneshot, + time::timeout, +}; +use tokio_tungstenite::{ + WebSocketStream, accept_hdr_async_with_config, + tungstenite::{ + Message, + handshake::server::{ErrorResponse, Request, Response}, + protocol::WebSocketConfig, + }, +}; + +const ENTITY: usize = 64 * 1024; +const WAIT: Duration = Duration::from_secs(20); +const DATA_BOUND: usize = 8 * 1024; +const WS_MESSAGE_BOUND: usize = 16 * 1024; +const META_BOUND: usize = 512; +const MAX_QUEUED_MESSAGES: usize = 3; +type Accept = Pin> + Send + 'static>>; +#[derive(Debug)] +struct StageError { + name: &'static str, + kind: io::ErrorKind, + expected_synthetic_byte: Option, +} +impl std::fmt::Display for StageError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "stage={}; kind={:?}; expected-synthetic-byte={:?}", + self.name, self.kind, self.expected_synthetic_byte + ) + } +} +impl std::error::Error for StageError {} +fn invalid(message: &'static str) -> io::Error { + io::Error::new( + io::ErrorKind::InvalidData, + StageError { + name: message, + kind: io::ErrorKind::InvalidData, + expected_synthetic_byte: None, + }, + ) +} +fn check(value: bool, message: &'static str) -> io::Result<()> { + if value { Ok(()) } else { Err(invalid(message)) } +} +fn stage(name: &'static str, result: io::Result) -> io::Result { + result.map_err(|error| { + io::Error::new( + error.kind(), + StageError { + name, + kind: error.kind(), + expected_synthetic_byte: None, + }, + ) + }) +} +fn require_pending(result: Poll>, message: &'static str) -> io::Result<()> { + match result { + Poll::Pending => Ok(()), + Poll::Ready(Err(error)) => Err(error), + Poll::Ready(Ok(_)) => Err(invalid(message)), + } +} +#[derive(Clone, Copy, Debug)] +enum FirstBoundary { + Whole, + DataSplit, + MessageSplit, +} +#[derive(Default, Debug)] +struct Counts { + opens: AtomicUsize, + ws_accepts: AtomicUsize, + targets: AtomicUsize, + client_new: AtomicUsize, + client_end: AtomicUsize, + server_end_built: AtomicUsize, + server_keepalive_built: AtomicUsize, + server_binary_messages_started: AtomicUsize, + server_close_started: AtomicUsize, + first_data_length: AtomicUsize, + first_cipher_message_part: AtomicUsize, + client_write_pending: AtomicUsize, + peer_write_pending: AtomicUsize, + partial_writes: AtomicUsize, + client_drops: AtomicUsize, + peer_drops: AtomicUsize, + response_phase: AtomicBool, +} +#[derive(Clone, Copy, Debug)] +struct Snapshot { + opens: usize, + ws_accepts: usize, + targets: usize, + client_new: usize, + client_end: usize, + server_end_built: usize, + server_keepalive_built: usize, + server_binary_messages_started: usize, + server_close_started: usize, + first_data_length: usize, + first_cipher_message_part: usize, + client_write_pending: usize, + peer_write_pending: usize, + partial_writes: usize, + client_drops: usize, + peer_drops: usize, + response_phase: bool, +} +impl Counts { + fn snapshot(&self) -> Snapshot { + let load = |n: &AtomicUsize| n.load(Ordering::SeqCst); + Snapshot { + opens: load(&self.opens), + ws_accepts: load(&self.ws_accepts), + targets: load(&self.targets), + client_new: load(&self.client_new), + client_end: load(&self.client_end), + server_end_built: load(&self.server_end_built), + server_keepalive_built: load(&self.server_keepalive_built), + server_binary_messages_started: load(&self.server_binary_messages_started), + server_close_started: load(&self.server_close_started), + first_data_length: load(&self.first_data_length), + first_cipher_message_part: load(&self.first_cipher_message_part), + client_write_pending: load(&self.client_write_pending), + peer_write_pending: load(&self.peer_write_pending), + partial_writes: load(&self.partial_writes), + client_drops: load(&self.client_drops), + peer_drops: load(&self.peer_drops), + response_phase: self.response_phase.load(Ordering::SeqCst), + } + } +} +#[derive(Clone, Copy, Debug)] +struct CleanupReceipt { + shutdown_returned: bool, + owner_cancelled: bool, + owner_closed: bool, + tracker_closed: bool, + tracker_empty: bool, + client_drops: usize, + peer_drops: usize, + counter_weak_released: bool, +} +impl CleanupReceipt { + fn complete(self) -> bool { + self.shutdown_returned + && self.owner_cancelled + && self.owner_closed + && self.tracker_closed + && self.tracker_empty + && self.client_drops == 1 + && self.peer_drops == 1 + && self.counter_weak_released + } +} +#[derive(Clone, Copy, Debug)] +enum FailureClass { + Io, + Deadline, + Unwind, + Invariant, +} +#[derive(Debug)] +struct CaseFailure { + class: FailureClass, + stage: &'static str, + kind: Option, + expected_synthetic_byte: Option, + cancelled_before_cleanup: bool, + cleanup: CleanupReceipt, + counts: Snapshot, +} +impl std::fmt::Display for CaseFailure { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "class={:?}; stage={}; kind={:?}; expected-synthetic-byte={:?}; cancelled-before-cleanup={}; cleanup={:?}; counts={:?}", + self.class, + self.stage, + self.kind, + self.expected_synthetic_byte, + self.cancelled_before_cleanup, + self.cleanup, + self.counts + ) + } +} +fn io_label(error: &io::Error) -> (&'static str, io::ErrorKind, Option) { + match error + .get_ref() + .and_then(|inner| inner.downcast_ref::()) + { + Some(label) => (label.name, label.kind, label.expected_synthetic_byte), + None => ("unlabelled-io", error.kind(), None), + } +} + +struct Raw { + io: DuplexStream, + counts: Arc, + server: bool, + blocked: Option>, +} +impl Drop for Raw { + fn drop(&mut self) { + let counter = if self.server { + &self.counts.peer_drops + } else { + &self.counts.client_drops + }; + counter.fetch_add(1, Ordering::SeqCst); + } +} +impl AsyncRead for Raw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_read(cx, out) + } +} +impl AsyncWrite for Raw { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + let this = self.get_mut(); + let limit = if this.server { + input.len().min(31) + } else { + input.len() + }; + let result = Pin::new(&mut this.io).poll_write(cx, &input[..limit]); + match &result { + Poll::Pending if this.server => { + this.counts + .peer_write_pending + .fetch_add(1, Ordering::SeqCst); + // Upgrade backpressure must not satisfy the response-body gate. + if this.counts.response_phase.load(Ordering::SeqCst) { + if let Some(signal) = this.blocked.take() { + let _ = signal.send(()); + } + } + } + Poll::Pending => { + this.counts + .client_write_pending + .fetch_add(1, Ordering::SeqCst); + } + Poll::Ready(Ok(n)) if *n < input.len() => { + this.counts.partial_writes.fetch_add(1, Ordering::SeqCst); + } + _ => {} + } + result + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_shutdown(cx) + } +} +struct MemoryUpstream { + io: Mutex>, + counts: Arc, + server: Destination, +} +#[async_trait] +impl OutboundConnector for MemoryUpstream { + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + if session.destination != self.server { + return Err(DispatchError::NotAllowed); + } + let io = self + .io + .lock() + .unwrap() + .take() + .ok_or(DispatchError::NotAllowed)?; + self.counts.opens.fetch_add(1, Ordering::SeqCst); + Ok(ConnectedStream { + io, + effective_peer: self.server.clone(), + }) + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} + +// This model only serves the one channel the actual client opens. It consumes +// real WS Messages as a byte stream, independently of TCP read fragmentation. +struct MuxPeer { + ws: WebSocketStream, + incoming: Bytes, + meta: Vec, + remaining: usize, + got_new: bool, + channel_end: bool, + transport_end: bool, + outgoing: VecDeque, + prefix: Vec, + first_length: usize, + first_done: bool, + ending: bool, + boundary: FirstBoundary, + counts: Arc, +} +impl MuxPeer { + fn poll_messages(&mut self, cx: &mut Context<'_>) -> Poll> { + for _ in 0..crate::limits::IO_POLL_BUDGET { + if self.outgoing.is_empty() { + return Pin::new(&mut self.ws) + .poll_flush(cx) + .map_err(|_| invalid("mux.peer.ws.flush")); + } + ready!(Pin::new(&mut self.ws).poll_ready(cx)) + .map_err(|_| invalid("mux.peer.ws.ready"))?; + let message = self.outgoing.pop_front().expect("bounded message present"); + match &message { + Message::Binary(_) => { + self.counts + .server_binary_messages_started + .fetch_add(1, Ordering::SeqCst); + } + Message::Close(_) => { + self.counts + .server_close_started + .fetch_add(1, Ordering::SeqCst); + } + _ => return Poll::Ready(Err(invalid("unexpected model output"))), + } + Pin::new(&mut self.ws) + .start_send(message) + .map_err(|_| invalid("mux.peer.ws.start"))?; + } + cx.waker().wake_by_ref(); + Poll::Pending + } + fn poll_ws_read( + &mut self, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + for _ in 0..crate::limits::IO_POLL_BUDGET { + if !self.incoming.is_empty() { + let amount = out.remaining().min(self.incoming.len()); + out.put_slice(&self.incoming[..amount]); + self.incoming.advance(amount); + return Poll::Ready(Ok(())); + } + if self.transport_end { + return Poll::Ready(Ok(())); + } + match ready!(Pin::new(&mut self.ws).poll_next(cx)) { + Some(Ok(Message::Binary(bytes))) => { + check(bytes.len() <= WS_MESSAGE_BOUND, "client WS message bound")?; + self.incoming = bytes; + } + Some(Ok(Message::Ping(_) | Message::Pong(_))) => {} + Some(Ok(Message::Close(_))) | None => { + self.transport_end = true; + } + Some(Ok(Message::Text(_) | Message::Frame(_))) | Some(Err(_)) => { + return Poll::Ready(Err(invalid("mux.peer.ws.read"))); + } + } + } + cx.waker().wake_by_ref(); + Poll::Pending + } + fn fill(&mut self, cx: &mut Context<'_>, target: usize) -> Poll> { + check(target <= META_BOUND + 4, "mux metadata bound")?; + for _ in 0..crate::limits::IO_POLL_BUDGET { + if self.meta.len() >= target { + return Poll::Ready(Ok(true)); + } + let mut bytes = [0; 64]; + let amount = (target - self.meta.len()).min(bytes.len()); + let mut read = ReadBuf::new(&mut bytes[..amount]); + ready!(self.poll_ws_read(cx, &mut read))?; + if read.filled().is_empty() { + return if self.meta.is_empty() { + Poll::Ready(Ok(false)) + } else { + Poll::Ready(Err(invalid("truncated client mux metadata"))) + }; + } + self.meta.extend_from_slice(read.filled()); + } + cx.waker().wake_by_ref(); + Poll::Pending + } + fn queue_binary(&mut self, bytes: Vec) -> io::Result<()> { + check( + bytes.len() <= WS_MESSAGE_BOUND && self.outgoing.len() < MAX_QUEUED_MESSAGES, + "bounded model WS queue", + )?; + self.outgoing.push_back(Message::Binary(bytes.into())); + Ok(()) + } + fn first_messages(&mut self) -> io::Result<()> { + check( + self.prefix.len() == self.first_length, + "complete synthetic server framing prefix", + )?; + self.counts.response_phase.store(true, Ordering::SeqCst); + // A real non-data KeepAlive precedes the first response Keep/Data. + self.queue_binary(vec![0, 4, 0, 0, 4, 0])?; + self.counts + .server_keepalive_built + .fetch_add(1, Ordering::SeqCst); + let prefix = std::mem::take(&mut self.prefix); + match self.boundary { + FirstBoundary::Whole => { + self.counts + .first_data_length + .store(prefix.len(), Ordering::SeqCst); + self.counts + .first_cipher_message_part + .store(prefix.len(), Ordering::SeqCst); + self.queue_binary(keep_data(&prefix)?)?; + } + FirstBoundary::DataSplit => { + let cut = prefix.len() - 1; + self.counts.first_data_length.store(cut, Ordering::SeqCst); + // Two legal Data records in ONE actual Binary Message. + self.counts + .first_cipher_message_part + .store(prefix.len(), Ordering::SeqCst); + let mut bytes = keep_data(&prefix[..cut])?; + bytes.extend_from_slice(&keep_data(&prefix[cut..])?); + self.queue_binary(bytes)?; + } + FirstBoundary::MessageSplit => { + self.counts + .first_data_length + .store(prefix.len(), Ordering::SeqCst); + self.counts + .first_cipher_message_part + .store(prefix.len() - 1, Ordering::SeqCst); + let bytes = keep_data(&prefix)?; + let cut = 8 + prefix.len() - 1; + // ONE legal Data record split across TWO Binary Messages, + // not a raw TCP fragment or an unfinished WS continuation. + self.queue_binary(bytes[..cut].to_vec())?; + self.queue_binary(bytes[cut..].to_vec())?; + } + } + self.first_done = true; + Ok(()) + } +} +fn keep_data(payload: &[u8]) -> io::Result> { + check( + !payload.is_empty() && payload.len() <= DATA_BOUND, + "server mux Data bound", + )?; + let mut bytes = vec![0, 4, 0, 0, 2, 1]; + bytes.extend_from_slice(&(payload.len() as u16).to_be_bytes()); + bytes.extend_from_slice(payload); + Ok(bytes) +} +impl AsyncRead for MuxPeer { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if out.remaining() == 0 { + return Poll::Ready(Ok(())); + } + if let Poll::Ready(result) = this.poll_messages(cx) { + result?; + } + for _ in 0..crate::limits::IO_POLL_BUDGET { + if this.remaining != 0 { + let amount = this.remaining.min(out.remaining()); + let mut limited = ReadBuf::new(out.initialize_unfilled_to(amount)); + ready!(this.poll_ws_read(cx, &mut limited))?; + let amount = limited.filled().len(); + check(amount != 0, "truncated client mux Data")?; + out.advance(amount); + this.remaining -= amount; + return Poll::Ready(Ok(())); + } + if this.channel_end { + return Poll::Ready(Ok(())); + } + check(ready!(this.fill(cx, 2))?, "client WS closed before mux End")?; + let metadata = usize::from(u16::from_be_bytes([this.meta[0], this.meta[1]])); + check( + (4..=META_BOUND).contains(&metadata), + "client mux metadata length", + )?; + check( + ready!(this.fill(cx, 2 + metadata))?, + "client mux metadata EOF", + )?; + check(this.meta[2..4] == [0, 0], "single channel0")?; + let status = this.meta[4]; + let flags = this.meta[5]; + check(flags & !3 == 0, "client mux flags")?; + if flags & 1 != 0 { + check( + ready!(this.fill(cx, 4 + metadata))?, + "client mux Data length EOF", + )?; + } + match status { + 1 => { + check( + !this.got_new + && metadata == 12 + && this.meta[2..14] == [0, 0, 1, 0, 1, 0, 0, 1, 127, 0, 0, 1], + "one exact client TCP New", + )?; + this.got_new = true; + this.counts.client_new.fetch_add(1, Ordering::SeqCst); + } + 2 => { + check( + this.got_new && metadata == 4 && flags == 1, + "client Keep/Data shape", + )?; + } + 3 => { + check( + this.got_new && metadata == 4 && flags == 0, + "clean client End shape", + )?; + this.channel_end = true; + this.counts.client_end.fetch_add(1, Ordering::SeqCst); + } + 4 => { + check(metadata == 4 && flags == 0, "client KeepAlive shape")?; + } + _ => return Poll::Ready(Err(invalid("client mux status"))), + } + if flags & 1 != 0 { + this.remaining = usize::from(u16::from_be_bytes([ + this.meta[2 + metadata], + this.meta[3 + metadata], + ])); + check(this.remaining <= 16 * 1024, "client mux Data body bound")?; + } + this.meta.clear(); + } + cx.waker().wake_by_ref(); + Poll::Pending + } +} +impl AsyncWrite for MuxPeer { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + let this = self.get_mut(); + check(!this.ending, "server write after End")?; + ready!(this.poll_messages(cx))?; + if input.is_empty() { + return Poll::Ready(Ok(0)); + } + let amount = if !this.first_done { + let amount = input.len().min(this.first_length - this.prefix.len()); + this.prefix.extend_from_slice(&input[..amount]); + if this.prefix.len() == this.first_length { + this.first_messages()?; + } + amount + } else { + let amount = input.len().min(DATA_BOUND); + this.queue_binary(keep_data(&input[..amount])?)?; + amount + }; + if let Poll::Ready(result) = this.poll_messages(cx) { + result?; + } + Poll::Ready(Ok(amount)) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + check( + this.first_done || this.prefix.is_empty(), + "partial server SS prefix on flush", + )?; + this.poll_messages(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + ready!(this.poll_messages(cx))?; + if !this.ending { + check(this.first_done, "server End before response")?; + this.queue_binary(vec![0, 4, 0, 0, 3, 0])?; + this.outgoing.push_back(Message::Close(None)); + this.counts.server_end_built.fetch_add(1, Ordering::SeqCst); + this.ending = true; + } + ready!(this.poll_messages(cx))?; + // Flush a real WS Close without waiting for an acknowledgement from a + // proxy client whose normal shutdown half-closes the raw write side. + Pin::new(this.ws.get_mut()).poll_shutdown(cx) + } +} + +async fn carrier( + owner: &Owner, + cipher: ShadowsocksCipher, + boundary: FirstBoundary, + counts: Arc, +) -> io::Result<(BoxStream, Accept, oneshot::Receiver<()>)> { + carrier_to( + owner, + cipher, + boundary, + counts, + Destination::domain("memory-mux.invalid", 443).unwrap(), + 64, + ) + .await +} + +async fn carrier_to( + owner: &Owner, + cipher: ShadowsocksCipher, + boundary: FirstBoundary, + counts: Arc, + target: Destination, + capacity: usize, +) -> io::Result<(BoxStream, Accept, oneshot::Receiver<()>)> { + let method: CipherKind = cipher + .as_str() + .parse() + .map_err(|_| invalid("test cipher"))?; + let key = vec![7; cipher.key_len()]; + let config = ServerConfig::new(("192.0.2.10", 8443), STANDARD.encode(&key), method) + .map_err(|_| invalid("test SS server config"))?; + let first_length = method.salt_len() * 2 + 1 + 8 + 2 + method.tag_len(); + check( + (59..=91).contains(&first_length), + "actual first response bound", + )?; + let server = Destination::Ip("192.0.2.10:8443".parse().unwrap()); + let (client, peer) = tokio::io::duplex(capacity); + let (signal, blocked) = oneshot::channel(); + let upstream = UpstreamPath::Proxy(Arc::new(MemoryUpstream { + io: Mutex::new(Some(Box::new(Raw { + io: client, + counts: counts.clone(), + server: false, + blocked: None, + }))), + counts: counts.clone(), + server: server.clone(), + })); + let peer = Raw { + io: peer, + counts: counts.clone(), + server: true, + blocked: Some(signal), + }; + let session = StreamSession { + metadata: Default::default(), + inbound: InboundKind::Http, + source: "127.0.0.1:10000".parse().unwrap(), + destination: target.clone(), + sniffed_domain: None, + }; + let mut ws_config = WebSocketConfig::default(); + ws_config.write_buffer_size = 0; + ws_config.max_write_buffer_size = 64 * 1024; + ws_config.max_message_size = Some(WS_MESSAGE_BOUND); + ws_config.max_frame_size = Some(WS_MESSAGE_BOUND); + let accept_ws = async { + accept_hdr_async_with_config( + peer, + |request: &Request, response: Response| -> Result { + if request.uri().path() != "/mux" + || request.headers().get("host").and_then(|v| v.to_str().ok()) + != Some("cover.invalid") + || request + .headers() + .get("x-memory-test") + .and_then(|v| v.to_str().ok()) + != Some("fixed") + { + let mut error = ErrorResponse::new(Some("synthetic WS field mismatch".into())); + *error.status_mut() = http::StatusCode::BAD_REQUEST; + return Err(error); + } + Ok(response) + }, + Some(ws_config), + ) + .await + .map_err(|_| invalid("actual server WS handshake")) + }; + let context = EstablishContext::default(); + let open = async { + owner + .open(&upstream, &server, session, &context) + .await + .map_err(|_| invalid("actual mux Owner.open")) + }; + let (raw, ws) = tokio::try_join!(open, accept_ws)?; + counts.ws_accepts.fetch_add(1, Ordering::SeqCst); + let raw = owner.prepare_ss_response(raw, method)?; + let destination = super::super::address(&target); + let stream = super::super::stream::SsStream::new( + SsContext::new_shared(ServerType::Local), + raw, + &config, + destination.clone(), + ); + let client = owner.bind_stream(Box::new(stream)); + let peer = MuxPeer { + ws, + incoming: Bytes::new(), + meta: Vec::new(), + remaining: 0, + got_new: false, + channel_end: false, + transport_end: false, + outgoing: VecDeque::new(), + prefix: Vec::with_capacity(first_length), + first_length, + first_done: false, + ending: false, + boundary, + counts: counts.clone(), + }; + let mut peer = ProxyServerStream::from_stream( + SsContext::new_shared(ServerType::Server), + peer, + method, + &key, + ); + let accept = Box::pin(async move { + let target = stage( + "peer.official-handshake", + peer.handshake().await.map_err(Into::into), + )?; + check(target == destination, "official SS target mismatch")?; + counts.targets.fetch_add(1, Ordering::SeqCst); + Ok(Box::new(peer) as BoxStream) + }); + Ok((client, accept, blocked)) +} + +fn carrier_config( + cipher: ShadowsocksCipher, +) -> io::Result { + let input = serde_json::json!({"proxies":[{"name":"mux","type":"ss","server":"192.0.2.10","port":8443, + "cipher":cipher.as_str(),"password":STANDARD.encode(vec![7;cipher.key_len()]),"plugin":"v2ray-plugin", + "plugin-opts":{"mode":"websocket","host":"cover.invalid","path":"/mux","mux":true,"tls":false, + "headers":{"Host":"cover.invalid","X-Memory-Test":"fixed"}}}],"rules":["MATCH,mux"]}); + let parsed = Config::parse_yaml(&serde_json::to_vec(&input).unwrap()) + .map_err(|_| invalid("actual memory SS mux configuration"))?; + let ProxyProtocol::Shadowsocks(config) = &parsed.proxies[0].protocol else { + return Err(invalid("actual SS config expected")); + }; + Ok(config.clone()) +} + +pub(in crate::outbound::shadowsocks) struct MuxMemoryGuard { + owner: Arc, + counts: Arc, + waited: AtomicBool, +} +impl MuxMemoryGuard { + pub(in crate::outbound::shadowsocks) fn begin_shutdown(&self) { + self.owner.begin_shutdown(); + } + pub(in crate::outbound::shadowsocks) async fn shutdown(&self) { + self.owner.shutdown().await; + self.waited.store(true, Ordering::SeqCst); + } + pub(in crate::outbound::shadowsocks) fn client_new(&self) -> usize { + self.counts.client_new.load(Ordering::SeqCst) + } + pub(in crate::outbound::shadowsocks) fn receipt( + &self, + ) -> super::obfs_reuse_memory_tests::ObfsMemoryReceipt { + let load = |value: &AtomicUsize| value.load(Ordering::SeqCst); + super::obfs_reuse_memory_tests::ObfsMemoryReceipt { + opens: load(&self.counts.opens), + target_handshakes: load(&self.counts.targets), + cover_requests: load(&self.counts.ws_accepts), + cover_responses: load(&self.counts.ws_accepts), + client_drops: load(&self.counts.client_drops), + peer_drops: load(&self.counts.peer_drops), + client_write_pending: load(&self.counts.client_write_pending), + peer_write_pending: load(&self.counts.peer_write_pending), + partial_writes: load(&self.counts.partial_writes), + owner_cancelled: self.owner.cancel.is_cancelled(), + owner_closed: *self.owner.closed.lock().unwrap(), + owner_wait_returned: self.waited.load(Ordering::SeqCst), + } + } +} +impl Drop for MuxMemoryGuard { + fn drop(&mut self) { + self.owner.begin_shutdown(); + } +} +pub(in crate::outbound::shadowsocks) struct MuxMemoryCarrier { + pub(in crate::outbound::shadowsocks) client: BoxStream, + pub(in crate::outbound::shadowsocks) accept: Accept, + pub(in crate::outbound::shadowsocks) guard: MuxMemoryGuard, +} + +pub(in crate::outbound::shadowsocks) async fn memory_mux_carrier( + cipher: ShadowsocksCipher, + target: Destination, + capacity: usize, +) -> io::Result { + let config = carrier_config(cipher)?; + let owner = Arc::new(Owner::new( + config.plugin.as_ref().unwrap(), + &SecurityContext::new(), + 0, + 16 * 1024, + config.port, + )?); + let guard = MuxMemoryGuard { + owner: owner.clone(), + counts: Arc::new(Counts::default()), + waited: AtomicBool::new(false), + }; + let opened = carrier_to( + &owner, + cipher, + FirstBoundary::Whole, + guard.counts.clone(), + target, + capacity, + ) + .await; + match opened { + Ok((client, accept, blocked)) => { + // HTTP/TLS peers drive their own original future, not this R3-only notification. + drop(blocked); + Ok(MuxMemoryCarrier { + client, + accept, + guard, + }) + } + Err(error) => { + guard.shutdown().await; + Err(error) + } + } +} + +async fn entity( + io: &mut (impl AsyncRead + Unpin), + expected: u8, + name: &'static str, +) -> io::Result<()> { + let mut bytes = vec![0; ENTITY]; + stage(name, io.read_exact(&mut bytes).await)?; + if bytes.iter().all(|byte| *byte == expected) { + Ok(()) + } else { + Err(io::Error::new( + io::ErrorKind::InvalidData, + StageError { + name, + kind: io::ErrorKind::InvalidData, + expected_synthetic_byte: Some(expected), + }, + )) + } +} + +// All covered and plain controls execute this identical gate/payload sequence. +async fn exchange_io( + client: BoxStream, + accept: Accept, + peer_write_blocked: oneshot::Receiver<()>, + counts: Arc, +) -> io::Result<((), ())> { + let (allow, allowed) = oneshot::channel(); + tokio::try_join!( + async move { + let (mut read, mut write) = tokio::io::split(client); + stage("client.marker.write", write.write_all(b"!").await)?; + stage("client.marker.flush", write.flush().await)?; + let before = counts.client_write_pending.load(Ordering::SeqCst); + let mut payload = vec![0x31; ENTITY]; + payload.extend_from_slice(&vec![0x32; ENTITY]); + let mut upload = Box::pin(async { + stage("client.upload.write", write.write_all(&payload).await)?; + stage("client.upload.flush", write.flush().await) + }); + require_pending( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))).await, + "duplex must block real SS upload", + )?; + check( + counts.client_write_pending.load(Ordering::SeqCst) > before, + "upload must hit actual raw backpressure", + )?; + peer_write_blocked + .await + .map_err(|_| invalid("peer never hit real TX backpressure"))?; + entity(&mut read, 0x91, "client.response-one.read").await?; + require_pending( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))).await, + "RX must finish while TX remains blocked", + )?; + let mut second = Box::pin(entity(&mut read, 0x92, "client.response-two.read")); + require_pending( + poll_fn(|cx| Poll::Ready(second.as_mut().poll(cx))).await, + "second entity must await upload", + )?; + allow + .send(()) + .map_err(|_| invalid("peer upload gate lost"))?; + tokio::try_join!(upload.as_mut(), second.as_mut())?; + drop((upload, second)); + stage("client.shutdown", write.shutdown().await)?; + let mut extra = [0]; + check( + stage("client.response-eof.read", read.read(&mut extra).await)? == 0, + "extra response bytes", + )?; + Ok::<_, io::Error>(()) + }, + async move { + let mut peer = accept.await?; + let mut begin = [0]; + stage("peer.marker.read", peer.read_exact(&mut begin).await)?; + check(begin == [b'!'], "SS initial payload")?; + stage( + "peer.response-one.write", + peer.write_all(&vec![0x91; ENTITY]).await, + )?; + stage("peer.response-one.flush", peer.flush().await)?; + allowed + .await + .map_err(|_| invalid("client did not release RX gate"))?; + entity(&mut peer, 0x31, "peer.upload-one.read").await?; + entity(&mut peer, 0x32, "peer.upload-two.read").await?; + stage( + "peer.response-two.write", + peer.write_all(&vec![0x92; ENTITY]).await, + )?; + stage("peer.response-two.flush", peer.flush().await)?; + let mut extra = [0]; + check( + stage("peer.upload-eof.read", peer.read(&mut extra).await)? == 0, + "duplicate target or upload bytes", + )?; + stage("peer.shutdown", peer.shutdown().await)?; + Ok::<_, io::Error>(()) + } + ) +} + +async fn run(cipher: ShadowsocksCipher, boundary: FirstBoundary) -> Result<(), CaseFailure> { + let config = carrier_config(cipher).unwrap(); + let owner = Owner::new( + config.plugin.as_ref().unwrap(), + &SecurityContext::new(), + 0, + 16 * 1024, + config.port, + ) + .unwrap(); + let counts = Arc::new(Counts::default()); + // This Weak tracks the same allocation held by both real raw endpoints, + // the mux peer and all inline operations. Cancellation cannot clear it. + let counters_weak = Arc::downgrade(&counts); + let outcome = AssertUnwindSafe(timeout(WAIT, async { + let (client, accept, blocked) = carrier(&owner, cipher, boundary, counts.clone()).await?; + exchange_io(client, accept, blocked, counts.clone()).await + })) + .catch_unwind() + .await; + let cancelled_before_cleanup = owner.cancel.is_cancelled(); + // The completed/cancelled try_join future has dropped every endpoint and + // accept future before this real tracker barrier, on ALL outcomes. + owner.shutdown().await; + let owner_cancelled = owner.cancel.is_cancelled(); + let owner_closed = *owner.closed.lock().unwrap(); + let tracker_closed = owner.tasks.is_closed(); + let tracker_empty = owner.tasks.len() == 0; + drop(owner); + let snapshot = counts.snapshot(); + drop(counts); + let cleanup = CleanupReceipt { + shutdown_returned: true, + owner_cancelled, + owner_closed, + tracker_closed, + tracker_empty, + client_drops: snapshot.client_drops, + peer_drops: snapshot.peer_drops, + counter_weak_released: counters_weak.upgrade().is_none(), + }; + // Extract only typed labels for a combined cleanup failure; never format + // an arbitrary IO error or caught panic payload. + let original_io = outcome + .as_ref() + .ok() + .and_then(|timer| timer.as_ref().ok()) + .and_then(|result| result.as_ref().err()) + .map(io_label); + let original_unwind = outcome.is_err(); + let original_deadline = outcome.as_ref().is_ok_and(|timer| timer.is_err()); + // This strict independent assertion precedes error/deadline/unwind + // classification, so an expected header RED also proves actual release. + assert!( + cleanup.complete(), + "{cipher:?}/{boundary:?}: cleanup failed; original_io={original_io:?}; original_deadline={original_deadline}; original_unwind={original_unwind}; cleanup={cleanup:?}; counts={snapshot:?}" + ); + let fail = |class, stage, kind, expected_synthetic_byte| CaseFailure { + class, + stage, + kind, + expected_synthetic_byte, + cancelled_before_cleanup, + cleanup, + counts: snapshot, + }; + match outcome { + Err(_panic_payload) => { + return Err(fail(FailureClass::Unwind, "exchange-unwind", None, None)); + } + Ok(Err(_)) => { + return Err(fail( + FailureClass::Deadline, + "exchange-deadline", + Some(io::ErrorKind::TimedOut), + None, + )); + } + Ok(Ok(Err(error))) => { + let (stage, kind, expected) = io_label(&error); + return Err(fail(FailureClass::Io, stage, Some(kind), expected)); + } + Ok(Ok(Ok(_))) => {} + } + let method: CipherKind = cipher.as_str().parse().unwrap(); + let required = method.salt_len() * 2 + 1 + 8 + 2 + method.tag_len(); + let expected_data = match boundary { + FirstBoundary::DataSplit => required - 1, + _ => required, + }; + let expected_message_part = match boundary { + FirstBoundary::MessageSplit => required - 1, + _ => required, + }; + let invariant = if ( + snapshot.first_data_length, + snapshot.first_cipher_message_part, + ) != (expected_data, expected_message_part) + { + Some("exact-first-boundary-witness") + } else if cancelled_before_cleanup { + Some("unexpected-parent-cancellation") + } else if ( + snapshot.opens, + snapshot.ws_accepts, + snapshot.targets, + snapshot.client_new, + snapshot.client_end, + ) != (1, 1, 1, 1, 1) + { + Some("one-open-ws-target-new-end") + } else if ( + snapshot.server_end_built, + snapshot.server_close_started, + snapshot.server_keepalive_built, + ) != (1, 1, 1) + { + Some("normal-peer-end-close-keepalive") + } else if !snapshot.response_phase + || snapshot.server_binary_messages_started < 3 + || snapshot.client_write_pending == 0 + || snapshot.peer_write_pending == 0 + || snapshot.partial_writes == 0 + { + Some("real-cross-direction-backpressure") + } else { + None + }; + if let Some(name) = invariant { + return Err(fail(FailureClass::Invariant, name, None, None)); + } + Ok(()) +} +async fn run_all(boundary: FirstBoundary) { + let mut outcomes = Vec::new(); + for cipher in [ + ShadowsocksCipher::Aes128Gcm, + ShadowsocksCipher::Aes256Gcm, + ShadowsocksCipher::Chacha20Poly1305, + ] { + outcomes.push((cipher, run(cipher, boundary).await)); + } + assert_eq!(outcomes.len(), 3); + let failures: Vec<_> = outcomes + .iter() + .filter_map(|(cipher, result)| { + result + .as_ref() + .err() + .map(|failure| (*cipher, failure.to_string())) + }) + .collect(); + assert!( + failures.is_empty(), + "{boundary:?}: failures after all three actual cipher cases={failures:?}" + ); +} + +#[tokio::test] +async fn v2ray_mux_whole_response_header_real_ws_ss_three_ciphers_cross_direction_control() { + run_all(FirstBoundary::Whole).await; +} +#[tokio::test] +async fn v2ray_mux_legal_split_data_records_require_complete_response_header() { + run_all(FirstBoundary::DataSplit).await; +} +#[tokio::test] +async fn v2ray_mux_legal_split_ws_messages_require_complete_response_header() { + run_all(FirstBoundary::MessageSplit).await; +} diff --git a/src/outbound/shadowsocks/plugin/v2ray_mux_reuse_owner_memory_tests.rs b/src/outbound/shadowsocks/plugin/v2ray_mux_reuse_owner_memory_tests.rs new file mode 100644 index 0000000..d3989d5 --- /dev/null +++ b/src/outbound/shadowsocks/plugin/v2ray_mux_reuse_owner_memory_tests.rs @@ -0,0 +1,19 @@ +//! Run the complete SS owner checks through the plain WS mux binding. +use super::obfs_reuse_owner_memory_tests::{ + Carrier, assert_pending_stop, assert_sibling_drop, assert_stop_before_bind, +}; + +#[tokio::test(flavor = "current_thread")] +async fn v2ray_mux_owned_complete_ss_stop_wakes_independent_pending_operations() { + assert_pending_stop(Carrier::V2rayMux).await; +} + +#[tokio::test(flavor = "current_thread")] +async fn v2ray_mux_owned_stop_before_bind_rejects_complete_ss_without_touching_raw() { + assert_stop_before_bind(Carrier::V2rayMux).await; +} + +#[tokio::test(flavor = "current_thread")] +async fn v2ray_mux_owned_child_drop_preserves_parent_and_sibling_until_parent_stop() { + assert_sibling_drop(Carrier::V2rayMux).await; +} diff --git a/src/outbound/shadowsocks/response_header.rs b/src/outbound/shadowsocks/response_header.rs new file mode 100644 index 0000000..bc5140f --- /dev/null +++ b/src/outbound/shadowsocks/response_header.rs @@ -0,0 +1,316 @@ +//! Exact first SS2022 response ciphertext prefix for limited stream carriers. +//! Installed only by actual simple-obfs or plain standard WebSocket/non-Gost +//! single-mux factories without early data, independently of HTTP reuse features. +//! This bounded adapter neither decrypts nor authenticates. Bare SS, WSS, +//! non-mux WS, early data, HTTPUpgrade, Gost, JLS and ShadowTLS keep original reads. +use shadowsocks::crypto::CipherKind; +use std::{ + io, + pin::Pin, + task::{Context, Poll, ready}, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; + +const MAX_RESPONSE_PREFIX: usize = 91; +pub(super) struct HeaderIo { + inner: S, + prefix: [u8; MAX_RESPONSE_PREFIX], + target: usize, + filled: usize, + emitted: usize, + eof: bool, + truncated: bool, +} +impl HeaderIo { + pub(super) fn new(inner: S, method: CipherKind) -> io::Result { + if !method.is_aead_2022() { + return Err(io::ErrorKind::InvalidInput.into()); + } + // Official aead_2022::poll_read_header for StreamType::Client: + // salt + type + timestamp + request salt + length + authentication tag. + let salt = method.salt_len(); + let target = salt + .checked_mul(2) + .and_then(|n| n.checked_add(1 + 8 + 2)) + .and_then(|n| n.checked_add(method.tag_len())) + .filter(|n| *n != 0 && *n <= MAX_RESPONSE_PREFIX) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + Ok(Self { + inner, + prefix: [0; MAX_RESPONSE_PREFIX], + target, + filled: 0, + emitted: 0, + eof: false, + truncated: false, + }) + } +} +impl AsyncRead for HeaderIo { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if out.remaining() == 0 || this.eof { + return Poll::Ready(Ok(())); + } + if this.truncated { + return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); + } + if this.emitted == this.target { + return Pin::new(&mut this.inner).poll_read(cx, out); + } + for _ in 0..crate::limits::IO_POLL_BUDGET { + if this.filled == this.target { + break; + } + // The slice is exactly the missing prefix, so no ciphertext body + // byte is over-read. Progress survives a real inner Pending. + let amount = { + let mut read = ReadBuf::new(&mut this.prefix[this.filled..this.target]); + ready!(Pin::new(&mut this.inner).poll_read(cx, &mut read))?; + read.filled().len() + }; + if amount == 0 { + if this.filled == 0 { + this.eof = true; + return Poll::Ready(Ok(())); + } + this.truncated = true; + return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); + } + this.filled += amount; + } + if this.filled != this.target { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + let amount = (this.target - this.emitted).min(out.remaining()); + out.put_slice(&this.prefix[this.emitted..this.emitted + amount]); + this.emitted += amount; + Poll::Ready(Ok(())) + } +} +impl AsyncWrite for HeaderIo { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_write(cx, input) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().inner).poll_shutdown(cx) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use futures_util::task::noop_waker_ref; + struct Source { + bytes: Vec, + position: usize, + chunk: usize, + pending_each: bool, + pending: bool, + reads: Vec<(usize, usize)>, + writes: usize, + flushes: usize, + shutdowns: usize, + } + impl Source { + fn new(bytes: Vec, chunk: usize, pending_each: bool) -> Self { + Self { + bytes, + position: 0, + chunk, + pending_each, + pending: pending_each, + reads: Vec::new(), + writes: 0, + flushes: 0, + shutdowns: 0, + } + } + } + impl AsyncRead for Source { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + this.reads.push((this.position, out.remaining())); + if this.pending { + this.pending = false; + cx.waker().wake_by_ref(); + return Poll::Pending; + } + let amount = (this.bytes.len() - this.position) + .min(this.chunk) + .min(out.remaining()); + out.put_slice(&this.bytes[this.position..this.position + amount]); + this.position += amount; + this.pending = this.pending_each; + Poll::Ready(Ok(())) + } + } + impl AsyncWrite for Source { + fn poll_write( + self: Pin<&mut Self>, + _: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + self.get_mut().writes += 1; + Poll::Ready(Ok(bytes.len())) + } + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + self.get_mut().flushes += 1; + Poll::Ready(Ok(())) + } + fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + self.get_mut().shutdowns += 1; + Poll::Ready(Ok(())) + } + } + fn methods() -> [(CipherKind, usize); 3] { + [ + ("2022-blake3-aes-128-gcm".parse().unwrap(), 59), + ("2022-blake3-aes-256-gcm".parse().unwrap(), 91), + ("2022-blake3-chacha20-poly1305".parse().unwrap(), 91), + ] + } + #[test] + fn header_probe_exact_prefix_survives_pending_and_never_reads_a_body_byte() { + for (method, expected) in methods() { + let mut bytes = vec![0x51; expected]; + bytes.push(0x52); + let mut io = HeaderIo::new(Source::new(bytes, 7, true), method).unwrap(); + assert_eq!(io.target, expected); + let mut output = [0; MAX_RESPONSE_PREFIX]; + let mut cx = Context::from_waker(noop_waker_ref()); + let mut complete = false; + for _ in 0..(MAX_RESPONSE_PREFIX * 2) { + let mut read = ReadBuf::new(&mut output); + match Pin::new(&mut io).poll_read(&mut cx, &mut read) { + Poll::Pending => assert!(read.filled().is_empty()), + Poll::Ready(Ok(())) => { + assert_eq!(read.filled(), &vec![0x51; expected]); + complete = true; + break; + } + Poll::Ready(Err(error)) => panic!("synthetic prefix kind={:?}", error.kind()), + } + } + assert!(complete); + assert_eq!(io.inner.position, expected); + assert!( + io.inner + .reads + .iter() + .all(|(position, limit)| position + limit == expected) + ); + let mut last = [0]; + let mut body_complete = false; + for _ in 0..(MAX_RESPONSE_PREFIX * 2) { + let mut read = ReadBuf::new(&mut last); + match Pin::new(&mut io).poll_read(&mut cx, &mut read) { + Poll::Pending => {} + Poll::Ready(Ok(())) => { + assert_eq!(read.filled(), &[0x52]); + body_complete = true; + break; + } + Poll::Ready(Err(error)) => panic!("synthetic body kind={:?}", error.kind()), + } + } + assert!(body_complete); + } + } + #[test] + fn header_probe_clean_and_partial_eof_are_distinct_and_writes_stay_direct() { + for (method, expected) in methods() { + for amount in [0, expected - 1] { + let mut io = + HeaderIo::new(Source::new(vec![0x53; amount], 7, true), method).unwrap(); + let mut cx = Context::from_waker(noop_waker_ref()); + let mut output = [0; MAX_RESPONSE_PREFIX]; + let mut completed = false; + for _ in 0..(MAX_RESPONSE_PREFIX * 2) { + let mut read = ReadBuf::new(&mut output); + match Pin::new(&mut io).poll_read(&mut cx, &mut read) { + Poll::Pending => {} + Poll::Ready(result) => { + assert_eq!( + result.err().map(|e| e.kind()), + (amount != 0).then_some(io::ErrorKind::UnexpectedEof) + ); + assert!(read.filled().is_empty()); + completed = true; + break; + } + } + } + assert!(completed); + let reads = io.inner.reads.len(); + let _ = Pin::new(&mut io).poll_read(&mut cx, &mut ReadBuf::new(&mut output)); + assert_eq!(io.inner.reads.len(), reads); + } + let mut io = HeaderIo::new(Source::new(vec![0x54; expected], 1, true), method).unwrap(); + let mut cx = Context::from_waker(noop_waker_ref()); + assert!( + Pin::new(&mut io) + .poll_read(&mut cx, &mut ReadBuf::new(&mut [0; MAX_RESPONSE_PREFIX])) + .is_pending() + ); + assert!(matches!( + Pin::new(&mut io).poll_write(&mut cx, &[0x55]), + Poll::Ready(Ok(1)) + )); + assert!(matches!( + Pin::new(&mut io).poll_flush(&mut cx), + Poll::Ready(Ok(())) + )); + assert!(matches!( + Pin::new(&mut io).poll_shutdown(&mut cx), + Poll::Ready(Ok(())) + )); + assert_eq!( + (io.inner.writes, io.inner.flushes, io.inner.shutdowns), + (1, 1, 1) + ); + } + } + #[test] + fn header_probe_each_poll_obeys_the_existing_io_budget() { + for (method, expected) in methods() { + let mut io = + HeaderIo::new(Source::new(vec![0x56; expected], 1, false), method).unwrap(); + let mut cx = Context::from_waker(noop_waker_ref()); + let mut output = [0; MAX_RESPONSE_PREFIX]; + let mut completed = false; + for _ in 0..MAX_RESPONSE_PREFIX { + let before = io.inner.reads.len(); + let mut read = ReadBuf::new(&mut output); + let result = Pin::new(&mut io).poll_read(&mut cx, &mut read); + assert!(io.inner.reads.len() - before <= crate::limits::IO_POLL_BUDGET); + match result { + Poll::Pending => assert!(read.filled().is_empty()), + Poll::Ready(Ok(())) => { + assert_eq!(read.filled().len(), expected); + completed = true; + break; + } + Poll::Ready(Err(error)) => panic!("synthetic budget kind={:?}", error.kind()), + } + } + assert!(completed); + } + } +} diff --git a/src/outbound/shadowsocks/testing.rs b/src/outbound/shadowsocks/testing.rs new file mode 100644 index 0000000..5b88283 --- /dev/null +++ b/src/outbound/shadowsocks/testing.rs @@ -0,0 +1,171 @@ +//! Test-only bridge to actual SS carriers; no sockets, routes or cache. +use super::plugin::obfs_reuse_memory_tests::{ObfsMemoryGuard, memory_carrier}; +use super::plugin::v2ray_mux_reuse_memory_tests::{MuxMemoryGuard, memory_mux_carrier}; +use crate::{config::ShadowsocksCipher, dispatch::BoxStream, session::Destination}; +use std::{ + future::Future, + io, + pin::Pin, + sync::{Arc, Mutex}, +}; + +pub(crate) type AcceptedPeer = + Pin> + Send + 'static>>; + +pub(crate) struct MemoryObfsFactory { + cipher: ShadowsocksCipher, + kind: CarrierKind, + capacity: usize, + guards: Mutex>>, +} + +#[derive(Clone, Copy)] +enum CarrierKind { + Obfs { tls: bool }, + V2rayMux, +} +enum CarrierGuard { + Obfs(ObfsMemoryGuard), + V2rayMux(MuxMemoryGuard), +} +impl CarrierGuard { + fn begin_shutdown(&self) { + match self { + Self::Obfs(guard) => guard.begin_shutdown(), + Self::V2rayMux(guard) => guard.begin_shutdown(), + } + } + async fn shutdown(&self) { + match self { + Self::Obfs(guard) => guard.shutdown().await, + Self::V2rayMux(guard) => guard.shutdown().await, + } + } + fn receipt(&self) -> super::plugin::obfs_reuse_memory_tests::ObfsMemoryReceipt { + match self { + Self::Obfs(guard) => guard.receipt(), + Self::V2rayMux(guard) => guard.receipt(), + } + } + fn mux_new(&self) -> usize { + match self { + Self::Obfs(_) => 0, + Self::V2rayMux(guard) => guard.client_new(), + } + } +} + +#[derive(Debug, Default)] +pub(crate) struct MemoryObfsReceipt { + pub(crate) owners: usize, + pub(crate) opens: usize, + pub(crate) target_handshakes: usize, + pub(crate) cover_requests: usize, + pub(crate) cover_responses: usize, + pub(crate) client_drops: usize, + pub(crate) peer_drops: usize, + pub(crate) owner_cancelled: usize, + pub(crate) owner_closed: usize, + pub(crate) owner_wait_returned: usize, + pub(crate) mux_new: usize, +} + +impl MemoryObfsFactory { + pub(crate) fn new(cipher: ShadowsocksCipher, tls: bool, capacity: usize) -> Arc { + Self::with_kind(cipher, CarrierKind::Obfs { tls }, capacity) + } + + pub(crate) fn new_v2ray_mux(cipher: ShadowsocksCipher, capacity: usize) -> Arc { + Self::with_kind(cipher, CarrierKind::V2rayMux, capacity) + } + + fn with_kind(cipher: ShadowsocksCipher, kind: CarrierKind, capacity: usize) -> Arc { + Arc::new(Self { + cipher, + kind, + capacity, + guards: Mutex::new(Vec::new()), + }) + } + + pub(crate) async fn open(&self, target: Destination) -> io::Result<(BoxStream, AcceptedPeer)> { + let (client, accept, guard) = match self.kind { + CarrierKind::Obfs { tls } => { + let carrier = memory_carrier(self.cipher, tls, target, self.capacity).await?; + drop(carrier.peer_write_blocked); + ( + carrier.client, + carrier.accept, + CarrierGuard::Obfs(carrier.guard), + ) + } + CarrierKind::V2rayMux => { + let carrier = memory_mux_carrier(self.cipher, target, self.capacity).await?; + ( + carrier.client, + carrier.accept, + CarrierGuard::V2rayMux(carrier.guard), + ) + } + }; + self.guards + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(Arc::new(guard)); + // This notification belongs to the lower-layer backpressure test; R4 + // owns the original peer future and does not wait for a synthetic event. + Ok((client, accept)) + } + + pub(crate) fn begin_shutdown(&self) { + for guard in self + .guards + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + { + guard.begin_shutdown(); + } + } + + pub(crate) async fn shutdown(&self) { + let guards = self + .guards + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + for guard in &guards { + guard.begin_shutdown(); + } + // Never hold the registry lock across an owner wait. These guards do + // not join external HTTP/TLS I/O; the real fixture parent does that. + for guard in guards { + guard.shutdown().await; + } + } + + pub(crate) fn snapshot(&self) -> MemoryObfsReceipt { + let guards = self + .guards + .lock() + .unwrap_or_else(|error| error.into_inner()); + let mut total = MemoryObfsReceipt { + owners: guards.len(), + ..Default::default() + }; + for guard in guards.iter() { + let receipt = guard.receipt(); + total.opens += receipt.opens; + total.target_handshakes += receipt.target_handshakes; + total.cover_requests += receipt.cover_requests; + total.cover_responses += receipt.cover_responses; + total.client_drops += receipt.client_drops; + total.peer_drops += receipt.peer_drops; + total.owner_cancelled += usize::from(receipt.owner_cancelled); + total.owner_closed += usize::from(receipt.owner_closed); + total.owner_wait_returned += usize::from(receipt.owner_wait_returned); + total.mux_new += guard.mux_new(); + } + total + } +} diff --git a/src/outbound/sing_mux.rs b/src/outbound/sing_mux.rs index a602242..b65d83f 100644 --- a/src/outbound/sing_mux.rs +++ b/src/outbound/sing_mux.rs @@ -56,6 +56,18 @@ impl SingMuxConnector { if config.xhttp().is_some_and(|xhttp| xhttp.mode == crate::config::XHttpMode::PacketUp) ); self.pool.set_autonomous_writes(enabled, h2_packet_up); + let h3_packet_body = enabled + && matches!( + &proxy.protocol, + crate::config::ProxyProtocol::Vless(config) + if config.xhttp().is_some_and(|xhttp| + xhttp.http_version == crate::config::XHttpVersion::Http3 + && xhttp.mode == crate::config::XHttpMode::PacketUp + && xhttp.download.is_none() + && matches!(&xhttp.request.data, crate::config::xhttp::DataPlacement::Body)) + ); + self.pool.set_h3_queued_flush_coalescing(h3_packet_body); + self.pool.set_h3_udp_lane(h3_packet_body); self } #[cfg(target_os = "linux")] @@ -176,6 +188,11 @@ fn exclusive_tcp(proxy: &crate::config::ProxyConfig) -> bool { } #[async_trait] impl OutboundConnector for SingMuxConnector { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + !self.cancellation.is_cancelled() && self.inner.permits_http_tcp_reuse() + } + async fn connect_stream( &self, session: StreamSession, @@ -309,6 +326,9 @@ mod tests { }); let node = SingMuxConnector::new(inner, proxy.smux.as_ref().unwrap().clone()) .with_autonomous_xhttp(proxy); + if protocol == "yamux" { + assert!(!node.pool.captures_h3_udp()); + } assert_eq!( node.pool.autonomous_writes(), expected, @@ -742,3 +762,423 @@ mod tests { ); } } + +#[cfg(all(test, feature = "outbound-vless"))] +mod h3_udp_lane_memory_tests { + use super::*; + use crate::{ + dispatch::{BoxStream, DatagramBudget}, + resources::observation::ResourceProbe, + session::{Datagram, DatagramSession, InboundKind}, + }; + use bytes::Bytes; + use futures_util::{FutureExt, task::AtomicWaker}; + use std::{ + collections::HashMap, + panic::{AssertUnwindSafe, resume_unwind}, + pin::Pin, + sync::{ + Mutex, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + task::{Context, Poll}, + time::Duration, + }; + use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, DuplexStream, ReadBuf}; + use tokio::sync::Notify; + + const TCP_PAYLOAD: &[u8] = b"tcp-owned-lane"; + const UDP_PAYLOAD: &[u8] = b"udp-first-strong-frame"; + + #[derive(Default)] + struct FlushGate { + blocked: AtomicBool, + reached: AtomicBool, + writer: AtomicWaker, + changed: Notify, + } + impl FlushGate { + fn release(&self) { + self.blocked.store(false, Ordering::Release); + self.writer.wake(); + } + async fn wait_reached(&self) { + loop { + let changed = self.changed.notified(); + if self.reached.load(Ordering::Acquire) { + return; + } + changed.await; + } + } + } + struct GatedIo { + raw: DuplexStream, + gate: Arc, + } + impl AsyncRead for GatedIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.raw).poll_read(cx, out) + } + } + impl AsyncWrite for GatedIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + Pin::new(&mut self.raw).poll_write(cx, bytes) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.gate.writer.register(cx.waker()); + if self.gate.blocked.load(Ordering::Acquire) { + self.gate.reached.store(true, Ordering::Release); + self.gate.changed.notify_waiters(); + if self.gate.blocked.load(Ordering::Acquire) { + return Poll::Pending; + } + } + Pin::new(&mut self.raw).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.raw).poll_shutdown(cx) + } + } + #[derive(Default)] + struct Carriers { + opened: AtomicUsize, + peers: Mutex>, + tcp_gate: Arc, + } + #[async_trait] + impl OutboundConnector for Carriers { + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + let index = self.opened.fetch_add(1, Ordering::AcqRel); + let (raw, peer) = tokio::io::duplex(65536); + self.peers.lock().unwrap().push(peer); + let io: BoxStream = if index == 0 { + Box::new(GatedIo { + raw, + gate: self.tcp_gate.clone(), + }) + } else { + Box::new(raw) + }; + Ok(ConnectedStream { + io, + effective_peer: session.destination, + }) + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("Smux UDP must use the supplied stream carrier") + } + async fn shutdown(&self) {} + } + fn proxy(mode: &str) -> crate::config::ProxyConfig { + let raw = serde_json::json!({ + "proxies":[{"name":"memory", "type":"vless", "server":"192.0.2.1", "port":443, + "uuid":"00000000-0000-0000-0000-000000000001", "tls":true, "alpn":["h3"], + "network":"xhttp", "xhttp-opts":{"path":"/x", "mode":mode}, + "smux":{"enabled":true,"protocol":"smux","max-connections":1, + "padding":false,"only-tcp":false}}], + "rules":["MATCH,DIRECT"] + }); + crate::config::Config::parse_yaml(raw.to_string().as_bytes()) + .unwrap() + .proxies + .remove(0) + } + // Decode actual Smux wire bytes after the gate opens. Reading to each FIN + // also proves that logical closure can reach the peer before node Stop. + async fn read_peer(mut peer: DuplexStream, expected_fins: usize) -> (usize, usize) { + let mut preface = [0; 2]; + peer.read_exact(&mut preface).await.unwrap(); + assert_eq!(preface, [0, 0]); + let mut streams = HashMap::new(); + let (mut fins, mut tcp, mut udp) = (0, 0, 0); + while fins < expected_fins { + let mut header = [0; 8]; + peer.read_exact(&mut header).await.unwrap(); + assert_eq!(header[0], 1); + let command = header[1]; + let length = u16::from_le_bytes(header[2..4].try_into().unwrap()) as usize; + let id = u32::from_le_bytes(header[4..8].try_into().unwrap()); + let mut body = vec![0; length]; + peer.read_exact(&mut body).await.unwrap(); + match command { + 0 => { + assert!(streams.insert(id, None::).is_none()); + } + 1 => { + assert!(streams.contains_key(&id)); + fins += 1; + } + 2 => { + let kind = streams.get_mut(&id).expect("SYN before DATA"); + if let Some(kind) = *kind { + if kind == 0 { + assert_eq!(body, TCP_PAYLOAD); + tcp += 1; + } else { + assert_eq!(kind, 3); + let remote = + crate::session::Destination::Ip("192.0.2.9:25001".parse().unwrap()); + let mut expected = Vec::new(); + crate::socks5::encode_address(&remote, &mut expected).unwrap(); + expected.extend_from_slice(&(UDP_PAYLOAD.len() as u16).to_be_bytes()); + expected.extend_from_slice(UDP_PAYLOAD); + assert_eq!(body, expected); + udp += 1; + } + } else { + assert!(body.len() >= 3); + let flags = u16::from_be_bytes(body[..2].try_into().unwrap()); + assert!(matches!(flags, 0 | 3)); + *kind = Some(flags); + } + } + _ => panic!("unexpected Smux memory peer control frame"), + } + } + (tcp, udp) + } + async fn observe(mode: &str) -> (bool, usize) { + let probe = ResourceProbe::default(); + probe + .scope(async { + let carrier = Arc::new(Carriers::default()); + let proxy = proxy(mode); + // Only old-source APIs are used: this test must compile before the fix. + let node = SingMuxConnector::new(carrier.clone(), proxy.smux.clone().unwrap()) + .with_autonomous_xhttp(&proxy); + let result = + AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(3), async { + let context = EstablishContext::default(); + let mut tcp = node + .connect_stream( + StreamSession { + metadata: Default::default(), + inbound: InboundKind::Tun, + source: "192.0.2.3:40001".parse().unwrap(), + destination: crate::session::Destination::Ip( + "192.0.2.9:443".parse().unwrap(), + ), + sniffed_domain: None, + }, + &context, + ) + .await + .unwrap(); + tcp.io.write_all(TCP_PAYLOAD).await.unwrap(); + // Await the actual autonomous DATA receipt without a strong flush. + assert_eq!(tcp.io.write(&[]).await.unwrap(), 0); + carrier.tcp_gate.blocked.store(true, Ordering::Release); + let mut flushing = Box::pin(tcp.io.flush()); + assert!(futures_util::poll!(flushing.as_mut()).is_pending()); + carrier.tcp_gate.wait_reached().await; + let udp = async { + let request = DatagramRequest::new(DatagramSession::new( + InboundKind::Tun, + "192.0.2.3:40002".parse().unwrap(), + )) + .with_budget(DatagramBudget::new(1400, 1400)); + let mut transport = + node.open_datagram(request, &context).await.unwrap(); + transport + .send(Datagram { + remote: crate::session::Destination::Ip( + "192.0.2.9:25001".parse().unwrap(), + ), + payload: Bytes::from_static(UDP_PAYLOAD), + sniffed_domain: None, + }) + .await + .unwrap(); + transport.close().await.unwrap(); + }; + let mut udp = Box::pin(udp); + // Retain the original future on timeout; do not cancel/retry Open. + let early = tokio::time::timeout(Duration::from_millis(40), udp.as_mut()) + .await + .is_ok(); + carrier.tcp_gate.release(); + flushing.as_mut().await.unwrap(); + drop(flushing); + if !early { + udp.as_mut().await; + } + drop(udp); + tcp.io.shutdown().await.unwrap(); + drop(tcp); + let physical = carrier.opened.load(Ordering::Acquire); + assert!(matches!(physical, 1 | 2)); + let peers = std::mem::take(&mut *carrier.peers.lock().unwrap()); + assert_eq!(peers.len(), physical); + let (mut tcp_frames, mut udp_frames) = (0, 0); + for peer in peers { + let (a, b) = read_peer(peer, if physical == 1 { 2 } else { 1 }).await; + tcp_frames += a; + udp_frames += b; + } + assert_eq!((tcp_frames, udp_frames), (1, 1)); + (early, physical) + })) + .catch_unwind() + .await; + // Semantic RED is asserted by the caller only after all real Core + // drivers Stop/join. A panic/timeout also releases the gate first. + carrier.tcp_gate.release(); + node.shutdown().await; + drop(node); + carrier.peers.lock().unwrap().clear(); + assert!(probe.snapshot().is_idle()); + match result { + Ok(result) => result.expect("owned Smux memory fixture timed out"), + Err(panic) => resume_unwind(panic), + } + }) + .await + } + #[tokio::test] + async fn qualified_h3_udp_first_frame_progresses_while_tcp_flush_is_pending() { + let (early, physical) = observe("packet-up").await; + assert!(early, "UDP waited for the unrelated TCP strong flush"); + assert_eq!(physical, 2, "qualified TCP and UDP shared a Smux writer"); + } + #[tokio::test] + async fn excluded_h3_stream_up_keeps_the_original_shared_smux_writer() { + let (early, physical) = observe("stream-up").await; + assert!(!early, "excluded factory acquired a private UDP writer"); + assert_eq!(physical, 1); + } + #[tokio::test] + async fn active_tcp_flush_and_udp_receive_stop_before_gate_or_lease_release() { + let probe = ResourceProbe::default(); + probe + .scope(async { + let carrier = Arc::new(Carriers::default()); + let proxy = proxy("packet-up"); + let node = SingMuxConnector::new(carrier.clone(), proxy.smux.clone().unwrap()) + .with_autonomous_xhttp(&proxy); + let outcome = + AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(3), async { + let context = EstablishContext::default(); + let mut tcp = node + .connect_stream( + StreamSession { + metadata: Default::default(), + inbound: InboundKind::Tun, + source: "192.0.2.3:40003".parse().unwrap(), + destination: crate::session::Destination::Ip( + "192.0.2.9:443".parse().unwrap(), + ), + sniffed_domain: None, + }, + &context, + ) + .await + .unwrap(); + tcp.io.write_all(TCP_PAYLOAD).await.unwrap(); + assert_eq!(tcp.io.write(&[]).await.unwrap(), 0); + let request = DatagramRequest::new(DatagramSession::new( + InboundKind::Tun, + "192.0.2.3:40004".parse().unwrap(), + )) + .with_budget(DatagramBudget::new(1400, 1400)); + let mut udp = node.open_datagram(request, &context).await.unwrap(); + // The actual first strong UDP flush succeeds before TCP is gated. + udp.send(Datagram { + remote: crate::session::Destination::Ip( + "192.0.2.9:25001".parse().unwrap(), + ), + payload: Bytes::from_static(UDP_PAYLOAD), + sniffed_domain: None, + }) + .await + .unwrap(); + let physical = carrier.opened.load(Ordering::Acquire); + assert!(matches!(physical, 1 | 2)); + assert_eq!(carrier.peers.lock().unwrap().len(), physical); + carrier.tcp_gate.blocked.store(true, Ordering::Release); + let mut flushing = Box::pin(tcp.io.flush()); + assert!(futures_util::poll!(flushing.as_mut()).is_pending()); + carrier.tcp_gate.wait_reached().await; + // No peer response/status is supplied: this polls the real + // DatagramIo/ResponseStream/Smux read path to Pending. + let mut receiving = Box::pin(udp.receive()); + assert!(futures_util::poll!(receiving.as_mut()).is_pending()); + // Keep both client leases and every peer endpoint alive. Stop + // must cancel/join; EOF or an opened flush gate cannot rescue it. + let stopped = tokio::time::timeout(Duration::from_secs(1), node.shutdown()) + .await + .is_ok(); + let gate_was_blocked = carrier.tcp_gate.blocked.load(Ordering::Acquire); + let peers_held = carrier.peers.lock().unwrap().len() == physical; + if !stopped { + carrier.tcp_gate.release(); + node.shutdown().await; + } + let task_count = probe + .snapshot() + .current(crate::resources::observation::ResourceKind::Task); + let tcp_failed = flushing.as_mut().await.is_err(); + let udp_failed = receiving.as_mut().await.is_err(); + drop(flushing); + drop(receiving); + // Actual application handles release only after Stop and both + // pending waiters have observed their cancellation/failure. + drop((tcp, udp)); + ( + stopped, + gate_was_blocked, + peers_held, + task_count, + tcp_failed, + udp_failed, + ) + })) + .catch_unwind() + .await; + // Failure cleanup is exact and occurs before any semantic assertion. + carrier.tcp_gate.release(); + node.shutdown().await; + drop(node); + carrier.peers.lock().unwrap().clear(); + assert!(probe.snapshot().is_idle()); + let observed = match outcome { + Ok(result) => result.expect("active Smux Stop fixture timed out"), + Err(panic) => resume_unwind(panic), + }; + assert!( + observed.0, + "Stop waited for a gated TCP flush or a held lease" + ); + assert!( + observed.1, + "the raw flush gate was released before Stop completed" + ); + assert!( + observed.2, + "a peer endpoint was dropped before Stop completed" + ); + assert_eq!(observed.3, 0, "Stop returned before its owned tasks joined"); + assert!( + observed.4 && observed.5, + "a pending waiter survived or succeeded after Stop" + ); + }) + .await; + } +} diff --git a/src/outbound/socks5.rs b/src/outbound/socks5.rs index 4d4c5c3..cce996b 100644 --- a/src/outbound/socks5.rs +++ b/src/outbound/socks5.rs @@ -66,6 +66,8 @@ pub struct Socks5Outbound { auth: Option, upstream: UpstreamPath, tls: Option, + #[cfg(feature = "inbound-http")] + http_reuse_security_static: bool, } impl std::fmt::Debug for Socks5Outbound { @@ -134,6 +136,13 @@ impl Socks5Outbound { server: server_destination(&config.address, config.port)?, auth, upstream, + #[cfg(feature = "inbound-http")] + http_reuse_security_static: config.tls.as_ref().is_none_or(|tls| { + tls.identity + .as_ref() + .is_none_or(|identity| identity.origin.is_none()) + && tls.ech.as_ref().is_none_or(|ech| !ech.is_dynamic()) + }), tls: config .tls .as_ref() @@ -259,6 +268,11 @@ impl Socks5Outbound { #[async_trait] impl OutboundConnector for Socks5Outbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.http_reuse_security_static && self.upstream.permits_static_http_reuse(&self.server) + } + async fn connect_stream( &self, session: StreamSession, @@ -278,6 +292,11 @@ impl OutboundConnector for Socks5Outbound { #[async_trait] impl Dispatcher for Socks5Outbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + OutboundConnector::permits_http_tcp_reuse(self) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { OutboundConnector::connect_stream(self, session, &EstablishContext::default()) .await diff --git a/src/outbound/trojan/outbound.rs b/src/outbound/trojan/outbound.rs index bb5f635..f0e3d95 100644 --- a/src/outbound/trojan/outbound.rs +++ b/src/outbound/trojan/outbound.rs @@ -149,6 +149,13 @@ impl TrojanOutbound { #[async_trait] impl OutboundConnector for TrojanOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + !self.cancellation.is_cancelled() + && self.security.permits_static_http_reuse() + && self.upstream.permits_static_http_reuse(&self.server) + } + async fn connect_stream( &self, session: StreamSession, diff --git a/src/outbound/tuic/datagram.rs b/src/outbound/tuic/datagram.rs index 007b99d..f583659 100644 --- a/src/outbound/tuic/datagram.rs +++ b/src/outbound/tuic/datagram.rs @@ -107,6 +107,7 @@ impl Registry { runtime: Arc, budget: DatagramBudget, lease: super::activity::Lease, + _tun_owned_send: bool, ) -> Result>, DispatchError> { let mut state = self.state.lock().unwrap(); if state.closed || cancel.is_cancelled() { @@ -140,6 +141,8 @@ impl Registry { sent: false, closed: false, closing: None, + #[cfg(target_os = "macos")] + tun_owned_send: _tun_owned_send, }))) } pub fn exhausted(&self) -> bool { @@ -193,6 +196,8 @@ struct Transport { sent: bool, closed: bool, closing: Option>, + #[cfg(target_os = "macos")] + tun_owned_send: bool, } impl Transport { @@ -240,6 +245,34 @@ impl Transport { TuicUdpMode::Quic => u16::MAX as usize + 10 + 259, } } + + fn prepare_send(&mut self, datagram: Datagram) -> Result, DispatchError> { + if self.closed || self.cancel.is_cancelled() { + return Err(DispatchError::NotAllowed); + } + let address_len = wire::address_len(&datagram.remote)?; + let message_limit = self.message_limit(); + let budget = self + .registry + .payload_budget(address_len, message_limit) + .intersect(self.budget); + if datagram.payload.len() > budget.transmit() as usize { + return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); + } + let packets = wire::packets_with_payload_limit( + self.id, + self.packet, + &datagram.remote, + &datagram.payload, + message_limit, + self.registry + .payload_limit(address_len, datagram.payload.len(), message_limit), + )?; + // The next logical ID is consumed before any operation can be polled. + self.packet = self.packet.wrapping_add(1); + self.sent = true; + Ok(packets) + } } impl Drop for Transport { fn drop(&mut self) { @@ -266,53 +299,25 @@ impl DatagramTransport for Transport { budget.intersect(self.budget) } async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { - if self.closed || self.cancel.is_cancelled() { - return Err(DispatchError::NotAllowed); + let packets = self.prepare_send(datagram)?; + send_packets(&self.connection, &self.cancel, self.registry.mode, packets).await + } + + #[cfg(target_os = "macos")] + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + _flow_id: Option<&[u8]>, + ) -> Result { + if !self.tun_owned_send || self.registry.mode != TuicUdpMode::Quic { + return Err(datagram); } - let address_len = wire::address_len(&datagram.remote)?; - // Snapshot this logical send once; Quinn still validates the current - // path when each fragment is sent. Never cache the limit across sends. - let message_limit = self.message_limit(); - let budget = self - .registry - .payload_budget(address_len, message_limit) - .intersect(self.budget); - if datagram.payload.len() > budget.transmit() as usize { - return Err(io::Error::from(io::ErrorKind::InvalidInput).into()); - } - let packets = wire::packets_with_payload_limit( - self.id, - self.packet, - &datagram.remote, - &datagram.payload, - message_limit, - self.registry - .payload_limit(address_len, datagram.payload.len(), message_limit), - )?; - // Consume the ID before the first await: cancelling a partial send - // never reuses that unfinished packet or replays its business bytes. - self.packet = self.packet.wrapping_add(1); - self.sent = true; - for (index, packet) in packets.into_iter().enumerate() { - tokio::select! { biased; - ()=self.cancel.cancelled()=>return Err(DispatchError::NotAllowed), - result=async { - match self.registry.mode { - TuicUdpMode::Native=>self.connection.send_datagram_wait(packet).await.map_err(super::failure), - TuicUdpMode::Quic=>{ - let stream=self.connection.open_uni().await.map_err(super::failure)?; - let mut stream=UniSend(Some(stream)); - AsyncWriteExt::write_all(stream.0.as_mut().unwrap(),&packet).await.map_err(super::failure)?; - stream.0.take().unwrap().finish().map_err(super::failure) - } - } - } => result?, - } - if (index + 1) % crate::limits::IO_POLL_BUDGET == 0 { - tokio::task::yield_now().await; - } - } - Ok(()) + let packets = self.prepare_send(datagram); + let connection = self.connection.clone(); + let cancel = self.cancel.clone(); + Ok(crate::dispatch::TunPendingSend::new(Box::pin(async move { + send_packets(&connection, &cancel, TuicUdpMode::Quic, packets?).await + }))) } async fn receive(&mut self) -> Result { if self.closed { @@ -332,6 +337,33 @@ impl DatagramTransport for Transport { Ok(()) } } +async fn send_packets( + connection: &quinn::Connection, + cancel: &CancellationToken, + mode: TuicUdpMode, + packets: Vec, +) -> Result<(), DispatchError> { + for (index, packet) in packets.into_iter().enumerate() { + tokio::select! { biased; + ()=cancel.cancelled()=>return Err(DispatchError::NotAllowed), + result=async { + match mode { + TuicUdpMode::Native=>connection.send_datagram_wait(packet).await.map_err(super::failure), + TuicUdpMode::Quic=>{ + let stream=connection.open_uni().await.map_err(super::failure)?; + let mut stream=UniSend(Some(stream)); + AsyncWriteExt::write_all(stream.0.as_mut().unwrap(),&packet).await.map_err(super::failure)?; + stream.0.take().unwrap().finish().map_err(super::failure) + } + } + } => result?, + } + if (index + 1) % crate::limits::IO_POLL_BUDGET == 0 { + tokio::task::yield_now().await; + } + } + Ok(()) +} struct UniSend(Option); impl Drop for UniSend { fn drop(&mut self) { diff --git a/src/outbound/tuic/http_reuse_memory_tests.rs b/src/outbound/tuic/http_reuse_memory_tests.rs new file mode 100644 index 0000000..84aeb4e --- /dev/null +++ b/src/outbound/tuic/http_reuse_memory_tests.rs @@ -0,0 +1,250 @@ +//! Real TUIC constructors and immutable factory proofs, without opening IO. +use super::TuicOutbound; +use crate::{ + config::{Config, EgressOptions, IpVersion, TuicOutboundConfig}, + dialer::{Dialer, ResolvedEndpoint}, + dispatch::{DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, SelectUpstream, + SelectUpstreamMember, UpstreamPath, + }, + routing::GroupSelection, + session::{Destination, StreamSession}, +}; +use async_trait::async_trait; +use std::{ + io, + sync::{Arc, atomic::Ordering}, +}; + +fn config(mode: &str, uot: bool) -> TuicOutboundConfig { + let parsed = Config::parse_yaml( + format!( + "proxies:\n - name: memory\n type: tuic\n server: 192.0.2.10\n port: 443\n uuid: 00000000-0000-0000-0000-000000000007\n password: synthetic\n sni: tuic.memory.invalid\n udp-relay-mode: {mode}\n udp-over-stream: {uot}\n" + ).as_bytes(), + ).unwrap(); + let crate::config::ProxyProtocol::Tuic(config) = &parsed.proxies[0].protocol else { + panic!("TUIC memory configuration") + }; + config.clone() +} + +fn endpoint() -> ResolvedEndpoint { + ResolvedEndpoint { + logical_host: "192.0.2.10".into(), + port: 443, + addresses: vec!["192.0.2.10:443".parse().unwrap()], + } +} + +fn lazy(dialer: Dialer) -> UpstreamPath { + UpstreamPath::LazyDirect { dialer } +} + +fn node(config: &TuicOutboundConfig, upstream: UpstreamPath) -> TuicOutbound { + TuicOutbound::new_with_path(config, upstream).unwrap() +} + +#[test] +fn tuic_real_constructor_proves_literal_and_explicit_ip_for_all_udp_modes() { + for mode in ["native", "quic"] { + for uot in [false, true] { + for explicit_ip in [false, true] { + let mut config = config(mode, uot); + if explicit_ip { + config.address = "logical.memory.invalid".into(); + config.ip = Some("192.0.2.10".into()); + } + for upstream in [ + lazy(Dialer::default()), + UpstreamPath::direct(endpoint(), Dialer::default()), + ] { + let outbound = node(&config, upstream); + assert!( + outbound.permits_http_tcp_reuse(), + "{mode}/{uot}/{explicit_ip}" + ); + outbound.begin_shutdown(); + assert!(!outbound.permits_http_tcp_reuse()); + } + } + let mut ipv6 = config(mode, uot); + ipv6.address = "2001:db8::10".into(); + assert!(node(&ipv6, lazy(Dialer::default())).permits_http_tcp_reuse()); + } + } +} + +#[test] +fn tuic_real_constructor_rejects_dynamic_or_mismatched_physical_endpoints() { + for mode in ["native", "quic"] { + for uot in [false, true] { + let baseline = config(mode, uot); + let mut domain = baseline.clone(); + domain.address = "dynamic.memory.invalid".into(); + assert!(!node(&domain, lazy(Dialer::default())).permits_http_tcp_reuse()); + for changed in 0..5 { + let mut peer = endpoint(); + match changed { + 0 => peer.logical_host = "dynamic.memory.invalid".into(), + 1 => peer.port += 1, + 2 => peer.addresses.clear(), + 3 => peer.addresses.push("192.0.2.11:443".parse().unwrap()), + _ => peer.addresses[0] = "192.0.2.11:443".parse().unwrap(), + } + assert!( + !node(&baseline, UpstreamPath::direct(peer, Dialer::default())) + .permits_http_tcp_reuse() + ); + } + } + } +} + +// This unknown dependency supplies no capability. Neither method may be called +// by the structural query; no test substitutes a true connector/TLS proof. +struct Opaque; +#[async_trait] +impl OutboundConnector for Opaque { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("structural TUIC proof must not open an upstream stream") + } + + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("structural TUIC proof must not open an upstream datagram") + } +} + +#[test] +fn tuic_groups_and_even_a_real_static_tcp_proxy_do_not_prove_direct_udp() { + for mode in ["native", "quic"] { + for uot in [false, true] { + let config = config(mode, uot); + let selection = Arc::new(GroupSelection::new(0)); + let group = UpstreamPath::Group { + server: Destination::Ip("192.0.2.10:443".parse().unwrap()), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + }; + let grouped = node(&config, group); + assert!(!grouped.permits_http_tcp_reuse()); + selection.store(1, Ordering::Release); + assert!(!grouped.permits_http_tcp_reuse()); + assert!(!Opaque.permits_http_tcp_reuse()); + assert!(!node(&config, UpstreamPath::proxy(Arc::new(Opaque))).permits_http_tcp_reuse()); + + let inner = Arc::new(node(&config, lazy(Dialer::default()))); + assert!(inner.permits_http_tcp_reuse()); + // A real, eligible TUIC TCP connector still cannot donate proof + // about the Proxy variant's physical UDP factory. + assert!(!node(&config, UpstreamPath::proxy(inner)).permits_http_tcp_reuse()); + } + } +} + +struct MustNotProtect; +impl crate::dialer::SocketProtector for MustNotProtect { + fn protect(&self, _: i32) -> io::Result<()> { + panic!("structural TUIC proof must not allocate a socket") + } +} + +#[test] +fn tuic_preserves_actual_dialer_protection_binding_family_and_stop() { + let egress = EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }; + for mode in ["native", "quic"] { + for uot in [false, true] { + let config = config(mode, uot); + for dialer in [ + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_ip_version(IpVersion::Ipv6), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_protector(Arc::new(MustNotProtect)), + Dialer::default().with_egress(&egress), + #[cfg(any(target_os = "linux", target_os = "macos"))] + Dialer::default() + .for_dns_source( + crate::dns::source::DnsBinding { + interface: Arc::from("memory-interface"), + interface_index: None, + }, + "192.0.2.10:443".parse().unwrap(), + ) + .unwrap(), + ] { + assert!(!node(&config, lazy(dialer.clone())).permits_http_tcp_reuse()); + assert!( + !node(&config, UpstreamPath::direct(endpoint(), dialer)) + .permits_http_tcp_reuse() + ); + } + let dialer = Dialer::default(); + let first = node(&config, lazy(dialer.clone())); + let second = node(&config, UpstreamPath::direct(endpoint(), dialer.clone())); + assert!(first.permits_http_tcp_reuse() && second.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + assert!(!first.permits_http_tcp_reuse() && !second.permits_http_tcp_reuse()); + assert!(!node(&config, lazy(dialer)).permits_http_tcp_reuse()); + } + } +} + +#[test] +fn tuic_keeps_the_existing_macos_mptcp_preference_rule() { + for mode in ["native", "quic"] { + for uot in [false, true] { + let config = config(mode, uot); + let dialer = Dialer::default().with_mptcp(true); + for upstream in [ + lazy(dialer.clone()), + UpstreamPath::direct(endpoint(), dialer), + ] { + assert_eq!( + node(&config, upstream).permits_http_tcp_reuse(), + cfg!(target_os = "macos") + ); + } + } + } +} + +#[cfg(feature = "outbound-socks5")] +#[test] +fn an_actual_static_tcp_chain_inherits_tuic_proof_and_stop_revokes_it() { + let parsed = Config::parse_yaml( + b"proxies: [{name: memory, type: socks5, server: 192.0.2.20, port: 1080}]", + ) + .unwrap(); + let crate::config::ProxyProtocol::Socks5(socks) = &parsed.proxies[0].protocol else { + panic!("SOCKS5 memory configuration") + }; + for mode in ["native", "quic"] { + for uot in [false, true] { + let inner = Arc::new(node(&config(mode, uot), lazy(Dialer::default()))); + let outer = crate::outbound::Socks5Outbound::new_with_path( + socks, + UpstreamPath::proxy(inner.clone()), + ) + .unwrap(); + assert!(inner.permits_http_tcp_reuse()); + assert!(outer.permits_http_tcp_reuse()); + inner.begin_shutdown(); + assert!(!outer.permits_http_tcp_reuse()); + } + } +} diff --git a/src/outbound/tuic/mod.rs b/src/outbound/tuic/mod.rs index a309e49..90d1f57 100644 --- a/src/outbound/tuic/mod.rs +++ b/src/outbound/tuic/mod.rs @@ -6,6 +6,9 @@ mod stream; mod wire; pub use outbound::TuicOutbound; +#[cfg(all(test, feature = "inbound-http"))] +mod http_reuse_memory_tests; + fn failure(_: E) -> std::io::Error { // Peer close reasons and TLS errors may carry identities or destinations. std::io::Error::other("TUIC exchange failed") diff --git a/src/outbound/tuic/outbound.rs b/src/outbound/tuic/outbound.rs index 439f260..99dda5c 100644 --- a/src/outbound/tuic/outbound.rs +++ b/src/outbound/tuic/outbound.rs @@ -35,8 +35,8 @@ pub struct TuicOutbound { server: Destination, upstream: UpstreamPath, tls: StandardTlsClient, - // Lazy native source stripes, or isolated quic TCP/UDP business lanes. - // UoT keeps the original shared lane. + // Lazy native source stripes, or private TCP/UDP business lanes. + // UoT enters the UDP lane only through its internal magic stream. current: AsyncMutex<[Option>; 2]>, cancel: CancellationToken, admission: Mutex<()>, @@ -96,8 +96,7 @@ impl TuicOutbound { fn datagram_lane(&self) -> usize { usize::from( - self.config.udp_mode == crate::config::TuicUdpMode::Quic - && !self.config.udp_over_stream, + self.config.udp_mode == crate::config::TuicUdpMode::Quic || self.config.udp_over_stream, ) } @@ -228,7 +227,7 @@ impl TuicOutbound { let task = observation::track(ResourceKind::Task); self.tasks.spawn(observation::bind(async move { let _task = task; - drive(config, upstream, server, tls, datagram, context, cancel, ready).await; + drive(config, upstream, server, tls, datagram, datagram_business, context, cancel, ready).await; })); } let session = reply.await.map_err(|_|DispatchError::ConnectionRefused)??; @@ -239,21 +238,19 @@ impl TuicOutbound { }) => result, } } -} -#[async_trait] -impl OutboundConnector for TuicOutbound { - async fn connect_stream( + async fn connect_stream_in_lane( &self, session: StreamSession, context: &EstablishContext, + datagram_business: bool, ) -> Result { let header = wire::connect(&session.destination)?; let (shared, lease) = self .session( DatagramSession::new(session.inbound, session.source), context, - false, + datagram_business, ) .await?; tokio::select! { biased; @@ -267,6 +264,24 @@ impl OutboundConnector for TuicOutbound { }) => result, } } +} + +#[async_trait] +impl OutboundConnector for TuicOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + !self.cancel.is_cancelled() + && self.tls.permits_static_http_reuse() + && self.upstream.permits_static_direct_http_reuse(&self.server) + } + + async fn connect_stream( + &self, + session: StreamSession, + context: &EstablishContext, + ) -> Result { + self.connect_stream_in_lane(session, context, false).await + } async fn open_datagram( &self, @@ -275,7 +290,7 @@ impl OutboundConnector for TuicOutbound { ) -> Result, DispatchError> { if self.config.udp_over_stream { let connected = self - .connect_stream( + .connect_stream_in_lane( StreamSession { metadata: request.session.metadata.clone(), inbound: request.session.inbound, @@ -284,6 +299,7 @@ impl OutboundConnector for TuicOutbound { sniffed_domain: None, }, context, + true, ) .await?; let _admission = self.admission.lock().unwrap(); @@ -294,7 +310,7 @@ impl OutboundConnector for TuicOutbound { return Ok(crate::dispatch::bound_datagram( Box::new( crate::outbound::uot::UotTransport::new( - reader, + uot_receive_reader(reader), writer, request.max_response_payload_size(), self.cancel.clone(), @@ -313,6 +329,12 @@ impl OutboundConnector for TuicOutbound { shared.runtime.clone(), request.budget(), lease, + tun_pending_send_enabled( + cfg!(target_os = "macos"), + request.session.inbound, + self.config.udp_mode, + self.config.udp_over_stream, + ), )? { return Ok(transport); } @@ -347,6 +369,7 @@ async fn drive( server: Destination, tls: StandardTlsClient, datagram: DatagramSession, + datagram_business: bool, context: EstablishContext, cancel: CancellationToken, ready: oneshot::Sender, DispatchError>>, @@ -377,6 +400,18 @@ async fn drive( } else { request }; + #[cfg(target_os = "macos")] + let raw = if config.udp_mode == crate::config::TuicUdpMode::Quic && !config.udp_over_stream + { + // Both business lanes keep this one authenticated physical peer. + // Groups and proxy codecs retain the original datagram factory. + upstream + .open_fixed_peer_datagram(request, peer, &context) + .await? + } else { + upstream.open_datagram(request, &context).await? + }; + #[cfg(not(target_os = "macos"))] let raw = upstream.open_datagram(request, &context).await?; let (socket, owned) = quic::attach_quinn(raw, peer, budget).await?; driver = Some(owned); @@ -397,14 +432,25 @@ async fn drive( Some(discovery) }; let initial_mtu = if discovery.is_some() { 1200 } else { mtu }; + // Only the actual UDP business lane receives per-packet remote UNI + // streams. This permission is separate from the 32 active decoders. + let advertised_uni_credit = if cfg!(target_os = "macos") + && datagram_business + && config.udp_mode == crate::config::TuicUdpMode::Quic + && !config.udp_over_stream + { + 128_u32 + } else { + crate::limits::TUIC_CONTROL_READERS as u32 + }; limits .initial_mtu(initial_mtu) .min_mtu(1200) .mtu_discovery_config(discovery) // Business owner thresholds never flow into Quinn's eager maps. - // The decoder already bounds concurrent remote uni streams to 32. + // The receive loop still bounds active decoders to 32. .max_concurrent_bidi_streams(0_u8.into()) - .max_concurrent_uni_streams((crate::limits::TUIC_CONTROL_READERS as u32).into()) + .max_concurrent_uni_streams(advertised_uni_credit.into()) .send_window(crate::limits::TUIC_SEND_WINDOW as u64) .datagram_receive_buffer_size(Some(crate::limits::TUIC_DATAGRAM_BUFFER)) .datagram_send_buffer_size(crate::limits::TUIC_DATAGRAM_BUFFER) @@ -506,6 +552,35 @@ async fn drive( } } +fn tun_pending_send_enabled( + macos: bool, + inbound: crate::session::InboundKind, + mode: crate::config::TuicUdpMode, + uot: bool, +) -> bool { + macos + && inbound == crate::session::InboundKind::Tun + && mode == crate::config::TuicUdpMode::Quic + && !uot +} + +#[cfg(test)] +#[path = "tun_send_selector_tests.rs"] +mod tun_send_selector_tests; + +// Only actual TUIC UoT associations retain this bounded read-ahead buffer. +// Coalesce their small frame-header reads before acquiring the shared QUIC IO. +fn uot_receive_reader(reader: R) -> impl tokio::io::AsyncRead + Unpin + Send + 'static +where + R: tokio::io::AsyncRead + Unpin + Send + 'static, +{ + tokio::io::BufReader::with_capacity(8 * 1024, reader) +} + +#[cfg(test)] +#[path = "uot_read_memory_tests.rs"] +mod uot_read_memory_tests; + fn current_tls( tls: &StandardTlsClient, disable_sni: bool, diff --git a/src/outbound/tuic/tun_send_selector_tests.rs b/src/outbound/tuic/tun_send_selector_tests.rs new file mode 100644 index 0000000..e252ec5 --- /dev/null +++ b/src/outbound/tuic/tun_send_selector_tests.rs @@ -0,0 +1,45 @@ +use super::tun_pending_send_enabled; +use crate::{config::TuicUdpMode, session::InboundKind}; + +#[test] +fn tun_pending_send_requires_actual_mac_tun_quic_without_uot() { + assert!(tun_pending_send_enabled( + true, + InboundKind::Tun, + TuicUdpMode::Quic, + false + )); + assert!(!tun_pending_send_enabled( + false, + InboundKind::Tun, + TuicUdpMode::Quic, + false + )); + assert!(!tun_pending_send_enabled( + true, + InboundKind::Tun, + TuicUdpMode::Native, + false + )); + assert!(!tun_pending_send_enabled( + true, + InboundKind::Tun, + TuicUdpMode::Quic, + true + )); + for inbound in [ + InboundKind::Socks5, + InboundKind::Http, + InboundKind::Https, + InboundKind::InternalDns, + InboundKind::InternalGeoData, + InboundKind::InternalMeasure, + ] { + assert!(!tun_pending_send_enabled( + true, + inbound, + TuicUdpMode::Quic, + false + )); + } +} diff --git a/src/outbound/tuic/uot_read_memory_tests.rs b/src/outbound/tuic/uot_read_memory_tests.rs new file mode 100644 index 0000000..7648dba --- /dev/null +++ b/src/outbound/tuic/uot_read_memory_tests.rs @@ -0,0 +1,381 @@ +//! Real UoT codec and owned reader tests over in-memory duplex IO only. +//! The coalescing requirement deliberately fails the pass-through baseline; +//! it models the observed per-field read/lock amplification, not throughput. +use super::uot_receive_reader; +use crate::{ + dispatch::{DatagramTransport, DispatchError}, + outbound::uot::UotTransport, + session::{Datagram, Destination}, +}; +use std::{ + io, + net::{Ipv4Addr, SocketAddr}, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, + }, + task::{Context, Poll}, + time::Duration, +}; +use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, DuplexStream, ReadBuf}; +use tokio_util::{sync::CancellationToken, task::TaskTracker}; + +const TEST_TIMEOUT: Duration = Duration::from_secs(2); +#[derive(Default)] +struct Counts { + read_polls: AtomicUsize, + nonempty_reads: AtomicUsize, + read_bytes: AtomicUsize, + reader_drops: AtomicUsize, + io_drops: AtomicUsize, +} +struct CountingReader { + inner: R, + counts: Arc, +} +impl Drop for CountingReader { + fn drop(&mut self) { + self.counts.reader_drops.fetch_add(1, Ordering::Relaxed); + } +} +impl AsyncRead for CountingReader { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + let before = buf.filled().len(); + self.counts.read_polls.fetch_add(1, Ordering::Relaxed); + let result = Pin::new(&mut self.inner).poll_read(cx, buf); + let bytes = buf.filled().len() - before; + self.counts.read_bytes.fetch_add(bytes, Ordering::Relaxed); + if bytes != 0 { + self.counts.nonempty_reads.fetch_add(1, Ordering::Relaxed); + } + result + } +} +struct OwnedMemoryIo { + inner: DuplexStream, + counts: Arc, +} +impl Drop for OwnedMemoryIo { + fn drop(&mut self) { + self.counts.io_drops.fetch_add(1, Ordering::Relaxed); + } +} +impl AsyncRead for OwnedMemoryIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.inner).poll_read(cx, buf) + } +} +impl AsyncWrite for OwnedMemoryIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + data: &[u8], + ) -> Poll> { + Pin::new(&mut self.inner).poll_write(cx, data) + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } +} +fn association( + parent: CancellationToken, +) -> (UotTransport, DuplexStream, TaskTracker, Arc) { + let counts = Arc::new(Counts::default()); + let (io, peer) = tokio::io::duplex(32 * 1024); + let io = OwnedMemoryIo { + inner: io, + counts: counts.clone(), + }; + let (reader, writer) = tokio::io::split(io); + let tracker = TaskTracker::new(); + let reader = CountingReader { + inner: reader, + counts: counts.clone(), + }; + let transport = UotTransport::new(uot_receive_reader(reader), writer, 1200, parent, &tracker) + .with_initial_deadline(tokio::time::Instant::now() + Duration::from_secs(10)); + (transport, peer, tracker, counts) +} +// An independent v2 datagram-mode response. Do not use Vole's encoder. +fn frame(port: u16, payload: &[u8]) -> Vec { + let length = u16::try_from(payload.len()).expect("bounded memory fixture"); + let mut wire = vec![0, 192, 0, 2, 10]; + wire.extend_from_slice(&port.to_be_bytes()); + wire.extend_from_slice(&length.to_be_bytes()); + wire.extend_from_slice(payload); + wire +} +fn assert_datagram(datagram: &Datagram, port: u16, payload: &[u8]) { + assert_eq!( + datagram.remote, + Destination::Ip(SocketAddr::new(Ipv4Addr::new(192, 0, 2, 10).into(), port)) + ); + assert_eq!(datagram.payload.as_ref(), payload); +} +async fn finish( + mut transport: UotTransport, + peer: DuplexStream, + tracker: TaskTracker, + counts: &Counts, +) { + let closed = tokio::time::timeout(TEST_TIMEOUT, transport.close()).await; + drop(transport); + drop(peer); + tracker.close(); + let joined = tokio::time::timeout(TEST_TIMEOUT, tracker.wait()).await; + assert!(joined.is_ok(), "actual UoT reader task did not join"); + assert!(tracker.is_empty()); + assert!( + matches!(closed, Ok(Ok(()))), + "memory transport close failed: {closed:?}" + ); + assert_eq!(counts.reader_drops.load(Ordering::Relaxed), 1); + assert_eq!(counts.io_drops.load(Ordering::Relaxed), 1); +} + +#[tokio::test(flavor = "current_thread")] +async fn tuic_uot_factory_coalesces_already_available_response_frames() { + let (mut transport, mut peer, tracker, counts) = association(CancellationToken::new()); + let payloads: Vec<_> = (0..8).map(|index| vec![0x40 + index; 1200]).collect(); + let wire: Vec<_> = payloads + .iter() + .enumerate() + .flat_map(|(index, payload)| frame(5300 + index as u16, payload)) + .collect(); + // Queue the entire independent batch before the reader is first scheduled. + let wrote = peer.write_all(&wire).await; + let received = tokio::time::timeout(TEST_TIMEOUT, async { + let mut packets = Vec::new(); + for _ in &payloads { + packets.push(transport.receive().await?); + } + Ok::<_, DispatchError>(packets) + }) + .await; + finish(transport, peer, tracker, &counts).await; + wrote.expect("memory peer write"); + let received = received + .expect("batch receive timed out") + .expect("batch decode failed"); + for (index, packet) in received.iter().enumerate() { + assert_datagram(packet, 5300 + index as u16, &payloads[index]); + } + assert_eq!(counts.read_bytes.load(Ordering::Relaxed), wire.len()); + let raw_reads = counts.nonempty_reads.load(Ordering::Relaxed); + assert!( + raw_reads <= payloads.len() / 2, + "TUIC UoT factory amplified an already available batch into {raw_reads} nonempty raw reads for {} packets ({} total polls)", + payloads.len(), + counts.read_polls.load(Ordering::Relaxed) + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn tuic_uot_receive_cancellation_keeps_partial_frame_and_next_frame() { + let (mut transport, mut peer, tracker, counts) = association(CancellationToken::new()); + let first_payload = vec![0x55; 1200]; + let second_payload = vec![0xa3; 777]; + let first = frame(5301, &first_payload); + let second = frame(5302, &second_payload); + let split = 9 + 301; + let received = tokio::time::timeout(TEST_TIMEOUT, async { + peer.write_all(&first[..split]) + .await + .map_err(DispatchError::from)?; + while counts.read_bytes.load(Ordering::Relaxed) < split { + tokio::task::yield_now().await; + } + let was_pending = { + let waker = futures_util::task::noop_waker(); + let mut cx = Context::from_waker(&waker); + let mut waiting = transport.receive(); + std::future::Future::poll(waiting.as_mut(), &mut cx).is_pending() + }; // Drop only the public receive future, not its owned parser. + let mut remainder = first[split..].to_vec(); + remainder.extend_from_slice(&second); + peer.write_all(&remainder) + .await + .map_err(DispatchError::from)?; + let first = transport.receive().await?; + let second = transport.receive().await?; + Ok::<_, DispatchError>((was_pending, first, second)) + }) + .await; + finish(transport, peer, tracker, &counts).await; + let (was_pending, first_packet, second_packet) = received + .expect("partial frame timed out") + .expect("partial frame decode failed"); + assert!(was_pending); + assert_datagram(&first_packet, 5301, &first_payload); + assert_datagram(&second_packet, 5302, &second_payload); + assert_eq!( + counts.read_bytes.load(Ordering::Relaxed), + first.len() + second.len() + ); +} + +#[tokio::test(flavor = "current_thread")] +async fn tuic_uot_oversize_response_drains_before_next_valid_packet() { + let (mut transport, mut peer, tracker, counts) = association(CancellationToken::new()); + let oversized = frame(5301, &vec![0x63; 4000]); + let payload = vec![0x27; 411]; + let mut wire = oversized; + wire.extend_from_slice(&frame(5302, &payload)); + let received = tokio::time::timeout(TEST_TIMEOUT, async { + peer.write_all(&wire).await.map_err(DispatchError::from)?; + transport.receive().await + }) + .await; + finish(transport, peer, tracker, &counts).await; + let packet = received + .expect("oversize drain timed out") + .expect("oversize drain failed"); + assert_datagram(&packet, 5302, &payload); + assert_eq!(counts.read_bytes.load(Ordering::Relaxed), wire.len()); +} + +#[tokio::test(flavor = "current_thread")] +async fn tuic_uot_close_joins_reader_before_releasing_complete_io() { + let (mut transport, peer, tracker, counts) = association(CancellationToken::new()); + let closed = tokio::time::timeout(TEST_TIMEOUT, transport.close()).await; + let readers_after_close = counts.reader_drops.load(Ordering::Relaxed); + let io_after_close = counts.io_drops.load(Ordering::Relaxed); + finish(transport, peer, tracker, &counts).await; + assert!(matches!(closed, Ok(Ok(())))); + assert_eq!(readers_after_close, 1); + // The original writer half remains owned until transport Drop. + assert_eq!(io_after_close, 0); +} + +#[tokio::test(flavor = "current_thread")] +async fn tuic_uot_parent_cancel_joins_actual_reader_task() { + let parent = CancellationToken::new(); + let (transport, peer, tracker, counts) = association(parent.clone()); + parent.cancel(); + tracker.close(); + let joined = tokio::time::timeout(TEST_TIMEOUT, tracker.wait()).await; + let readers_after_cancel = counts.reader_drops.load(Ordering::Relaxed); + finish(transport, peer, tracker, &counts).await; + assert!(joined.is_ok()); + assert_eq!(readers_after_cancel, 1); +} + +#[tokio::test(flavor = "current_thread")] +async fn tuic_uot_drop_joins_actual_reader_and_releases_both_io_halves() { + let (transport, peer, tracker, counts) = association(CancellationToken::new()); + drop(transport); + drop(peer); + tracker.close(); + let joined = tokio::time::timeout(TEST_TIMEOUT, tracker.wait()).await; + assert!(joined.is_ok()); + assert!(tracker.is_empty()); + assert_eq!(counts.reader_drops.load(Ordering::Relaxed), 1); + assert_eq!(counts.io_drops.load(Ordering::Relaxed), 1); +} + +#[tokio::test(flavor = "current_thread")] +async fn tuic_uot_parent_cancel_discards_prefetched_frames_behind_full_response_queue() { + let parent = CancellationToken::new(); + let raw_counts = Arc::new(Counts::default()); + let parsed_counts = Arc::new(Counts::default()); + let (io, mut peer) = tokio::io::duplex(32 * 1024); + let io = OwnedMemoryIo { + inner: io, + counts: raw_counts.clone(), + }; + let (reader, writer) = tokio::io::split(io); + let raw_reader = CountingReader { + inner: reader, + counts: raw_counts.clone(), + }; + // Observe both sides of the real production factory. The outer reader + // measures bytes consumed by the real parser, not speculative prefetch. + let parsed_reader = CountingReader { + inner: uot_receive_reader(raw_reader), + counts: parsed_counts.clone(), + }; + let tracker = TaskTracker::new(); + let mut transport = UotTransport::new(parsed_reader, writer, 1200, parent.clone(), &tracker) + .with_initial_deadline(tokio::time::Instant::now() + Duration::from_secs(10)); + let payloads: Vec<_> = (0..4).map(|index| vec![0x60 + index; 1200]).collect(); + let frames: Vec<_> = payloads + .iter() + .enumerate() + .map(|(index, payload)| frame(5400 + index as u16, payload)) + .collect(); + let wire: Vec<_> = frames + .iter() + .flat_map(|frame| frame.iter().copied()) + .collect(); + let parsed_two = frames[0].len() + frames[1].len(); + let ready = tokio::time::timeout(TEST_TIMEOUT, async { + peer.write_all(&wire).await?; + while parsed_counts.read_bytes.load(Ordering::Relaxed) < parsed_two { + tokio::task::yield_now().await; + } + Ok::<_, io::Error>(()) + }) + .await; + let parsed_before_cancel = parsed_counts.read_bytes.load(Ordering::Relaxed); + let raw_before_cancel = raw_counts.read_bytes.load(Ordering::Relaxed); + // No public receive has run. Two complete frames consumed by the real + // read_loop mean the first occupies its one-response queue and the second + // is waiting for admission. Raw bytes beyond both frames remain in the + // factory's read-ahead buffer, including at least one further whole frame. + parent.cancel(); + tracker.close(); + let joined = tokio::time::timeout(TEST_TIMEOUT, tracker.wait()).await; + let parsed_after_join = parsed_counts.read_bytes.load(Ordering::Relaxed); + let reader_drops_after_join = raw_counts.reader_drops.load(Ordering::Relaxed); + let parsed_reader_drops_after_join = parsed_counts.reader_drops.load(Ordering::Relaxed); + let io_drops_before_transport_drop = raw_counts.io_drops.load(Ordering::Relaxed); + let after_cancel = tokio::time::timeout(TEST_TIMEOUT, transport.receive()).await; + finish(transport, peer, tracker, &raw_counts).await; + + assert!( + matches!(ready, Ok(Ok(()))), + "real parser did not reach queue backpressure: {ready:?}" + ); + assert_eq!( + parsed_before_cancel, parsed_two, + "the real response queue was not full before cancellation" + ); + assert!( + raw_before_cancel >= parsed_two + frames[2].len(), + "the production reader had not prefetched a complete next frame" + ); + assert!(raw_before_cancel <= wire.len()); + assert!( + joined.is_ok(), + "parent cancellation did not join the real reader" + ); + assert_eq!( + parsed_after_join, parsed_before_cancel, + "cancellation consumed another prefetched frame" + ); + assert_eq!(reader_drops_after_join, 1); + assert_eq!(parsed_reader_drops_after_join, 1); + assert_eq!( + io_drops_before_transport_drop, 0, + "the original writer half was released before transport Drop" + ); + assert!( + matches!(after_cancel, Ok(Err(_))), + "a queued or prefetched packet escaped parent cancellation" + ); + assert_eq!(parsed_counts.reader_drops.load(Ordering::Relaxed), 1); + assert_eq!(raw_counts.reader_drops.load(Ordering::Relaxed), 1); + assert_eq!(raw_counts.io_drops.load(Ordering::Relaxed), 1); +} diff --git a/src/outbound/vless/encryption/mod.rs b/src/outbound/vless/encryption/mod.rs index 963472e..4beaf3e 100644 --- a/src/outbound/vless/encryption/mod.rs +++ b/src/outbound/vless/encryption/mod.rs @@ -45,6 +45,17 @@ impl Client { Handshake::start(&self.settings, self.cache.clone(), self.suite) } + #[cfg(feature = "inbound-http")] + pub(crate) fn permits_http_tcp_reuse(&self) -> bool { + !self.cache.cancellation.is_cancelled() + && matches!( + self.settings.appearance, + config::Appearance::Native + | config::Appearance::XorPublic + | config::Appearance::Random + ) + } + /// Exercise the non-AES hardware branch against an independent peer. /// Never compiled into production, and never a public YAML cipher option. #[cfg(feature = "interop-test")] diff --git a/src/outbound/vless/encryption/records.rs b/src/outbound/vless/encryption/records.rs index ea168fa..7cb7d9e 100644 --- a/src/outbound/vless/encryption/records.rs +++ b/src/outbound/vless/encryption/records.rs @@ -3,11 +3,12 @@ use super::crypto::{Aead, Ctr, Suite, failure}; use super::header_xor::HeaderXor; use crate::dispatch::BoxStream; use crate::security::vision::{SpliceControl, SpliceStats}; +use futures_util::task::AtomicWaker; use std::sync::Arc; use std::{ io, pin::Pin, - task::{Context, Poll, ready}, + task::{Context, Poll, Wake, Waker, ready}, }; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use zeroize::{Zeroize, Zeroizing}; @@ -22,6 +23,8 @@ pub(super) struct Records { rx_ctr: Option, pending: Vec, sent: usize, + prefix_pending: bool, + io_wake: Arc, input: Vec, filled: usize, reading: Reading, @@ -38,6 +41,42 @@ pub(super) struct Records { direct_rx: HeaderXor, } +// Raw IO and its cancellation guard can share one latest-waker slot. Keep +// both Records owners behind the same stable waker for every raw operation. +struct IoWake { + reader: AtomicWaker, + writer: AtomicWaker, +} + +impl IoWake { + fn new() -> Self { + Self { + reader: AtomicWaker::new(), + writer: AtomicWaker::new(), + } + } + + fn wake_all(&self) { + self.reader.wake(); + self.writer.wake(); + } +} + +impl Wake for IoWake { + fn wake(self: Arc) { + self.wake_all(); + } + + fn wake_by_ref(self: &Arc) { + self.wake_all(); + } +} + +enum DrainSide { + Read, + Write, +} + enum Reading { Random, Padding, @@ -70,6 +109,8 @@ impl Records { rx_ctr, pending: Vec::new(), sent: 0, + prefix_pending: false, + io_wake: Arc::new(IoWake::new()), input: vec![0; padding], filled: 0, reading: Reading::Padding, @@ -99,6 +140,7 @@ impl Records { cache: Arc, ticket: Arc, ) -> Self { + let prefix_pending = !prefix.is_empty(); Self { raw: Some(raw), key, @@ -109,6 +151,8 @@ impl Records { rx_ctr: None, pending: prefix, sent: 0, + prefix_pending, + io_wake: Arc::new(IoWake::new()), input: vec![0; 16], filled: 0, reading: Reading::Random, @@ -153,17 +197,23 @@ impl Records { self.key.zeroize(); self.plain.zeroize(); self.pending.clear(); + self.prefix_pending = false; self.input.clear(); + self.io_wake.wake_all(); error } - fn drain(&mut self, cx: &mut Context<'_>) -> Poll> { + fn drain(&mut self, side: DrainSide) -> Poll> { if let Err(error) = self.open() { return Poll::Ready(Err(self.fail(error))); } + let had_pending = self.sent < self.pending.len(); + let waker = Waker::from(self.io_wake.clone()); + let mut io_cx = Context::from_waker(&waker); while self.sent < self.pending.len() { let result = ready!( - Pin::new(self.raw.as_mut().unwrap()).poll_write(cx, &self.pending[self.sent..]) + Pin::new(self.raw.as_mut().unwrap()) + .poll_write(&mut io_cx, &self.pending[self.sent..]) ); let count = match result { Ok(0) => { @@ -182,15 +232,30 @@ impl Records { } self.pending.clear(); self.sent = 0; + self.prefix_pending = false; + if had_pending { + // Another owner can be parked on the exact frame just completed. + match side { + DrainSide::Read => self.io_wake.writer.wake(), + DrainSide::Write => self.io_wake.reader.wake(), + } + } Poll::Ready(Ok(())) } fn receive(&mut self, cx: &mut Context<'_>, output: &mut ReadBuf<'_>) -> Poll> { self.open()?; + self.io_wake.reader.register(cx.waker()); if output.remaining() == 0 { return Poll::Ready(Ok(())); } - ready!(self.drain(cx))?; + match self.drain(DrainSide::Read) { + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending if self.prefix_pending => return Poll::Pending, + Poll::Pending | Poll::Ready(Ok(())) => {} + } + let waker = Waker::from(self.io_wake.clone()); + let mut io_cx = Context::from_waker(&waker); loop { if self.consumed < self.plain.len() { let count = output.remaining().min(self.plain.len() - self.consumed); @@ -208,7 +273,7 @@ impl Records { return Poll::Ready(Err(failure())); } let before = output.filled().len(); - ready!(Pin::new(self.raw.as_mut().unwrap()).poll_read(cx, output))?; + ready!(Pin::new(self.raw.as_mut().unwrap()).poll_read(&mut io_cx, output))?; if let Some(ctr) = &mut self.rx_ctr { self.direct_rx .apply(ctr, &mut output.filled_mut()[before..], true)?; @@ -221,7 +286,7 @@ impl Records { } while self.filled < self.input.len() { let mut buf = ReadBuf::new(&mut self.input[self.filled..]); - ready!(Pin::new(self.raw.as_mut().unwrap()).poll_read(cx, &mut buf))?; + ready!(Pin::new(self.raw.as_mut().unwrap()).poll_read(&mut io_cx, &mut buf))?; let count = buf.filled().len(); if count == 0 { if self.filled == 0 && matches!(self.reading, Reading::Header) { @@ -292,10 +357,14 @@ impl AsyncRead for Records { cx: &mut Context<'_>, output: &mut ReadBuf<'_>, ) -> Poll> { - match self.receive(cx, output) { + let result = match self.receive(cx, output) { Poll::Ready(Err(error)) => Poll::Ready(Err(self.fail(error))), result => result, + }; + if result.is_ready() { + drop(self.io_wake.reader.take()); } + result } } @@ -305,105 +374,141 @@ impl AsyncWrite for Records { cx: &mut Context<'_>, input: &[u8], ) -> Poll> { - ready!(self.drain(cx))?; - if self.write_closed { - return Poll::Ready(Err(io::Error::new( - io::ErrorKind::BrokenPipe, - "VLESS Encryption write side closed", - ))); - } - if input.is_empty() { - return Poll::Ready(Ok(0)); - } - let count = input.len().min(8192); - if self - .vision - .as_ref() - .is_some_and(|(control, _)| control.writing_direct()) - { - if !self.direct_write { - let result = ready!(Pin::new(self.raw.as_mut().unwrap()).poll_flush(cx)); - if let Err(error) = result { - return Poll::Ready(Err(self.fail(error))); - } - self.direct_write = true; - } - self.pending.extend_from_slice(&input[..count]); - let this = &mut *self; - if let Some(ctr) = &mut this.tx_ctr - && let Err(error) = this.direct_tx.apply(ctr, &mut this.pending, false) - { - return Poll::Ready(Err(this.fail(error))); - } - self.pending_direct = true; - return Poll::Ready(Ok(count)); - } - let length = (count + 16) as u16; - let mut header = [23, 3, 3, (length >> 8) as u8, length as u8]; - let rekey = self.tx.exhausted(); + self.io_wake.writer.register(cx.waker()); + let waker = Waker::from(self.io_wake.clone()); + let mut io_cx = Context::from_waker(&waker); let result = (|| { - let sealed = self.tx.seal(&input[..count], &header, None)?; - if rekey { - let mut context = header.to_vec(); - context.extend_from_slice(&sealed); - self.tx = Aead::new(&context, self.key.as_ref(), self.suite)?; + ready!(self.drain(DrainSide::Write))?; + if self.write_closed { + return Poll::Ready(Err(io::Error::new( + io::ErrorKind::BrokenPipe, + "VLESS Encryption write side closed", + ))); } - if let Some(ctr) = self.tx_ctr.as_mut() { - ctr.apply(&mut header)?; + if input.is_empty() { + return Poll::Ready(Ok(0)); } - self.pending.extend_from_slice(&header); - self.pending.extend_from_slice(&sealed); - Ok(count) + let count = input.len().min(8192); + if self + .vision + .as_ref() + .is_some_and(|(control, _)| control.writing_direct()) + { + if !self.direct_write { + let result = + ready!(Pin::new(self.raw.as_mut().unwrap()).poll_flush(&mut io_cx)); + if let Err(error) = result { + return Poll::Ready(Err(self.fail(error))); + } + self.direct_write = true; + } + self.pending.extend_from_slice(&input[..count]); + let this = &mut *self; + if let Some(ctr) = &mut this.tx_ctr + && let Err(error) = this.direct_tx.apply(ctr, &mut this.pending, false) + { + return Poll::Ready(Err(this.fail(error))); + } + self.pending_direct = true; + return Poll::Ready(Ok(count)); + } + let length = (count + 16) as u16; + let mut header = [23, 3, 3, (length >> 8) as u8, length as u8]; + let rekey = self.tx.exhausted(); + let result = (|| { + let sealed = self.tx.seal(&input[..count], &header, None)?; + if rekey { + let mut context = header.to_vec(); + context.extend_from_slice(&sealed); + self.tx = Aead::new(&context, self.key.as_ref(), self.suite)?; + } + if let Some(ctr) = self.tx_ctr.as_mut() { + ctr.apply(&mut header)?; + } + self.pending.extend_from_slice(&header); + self.pending.extend_from_slice(&sealed); + Ok(count) + })(); + Poll::Ready(result.map_err(|error| self.fail(error))) })(); - Poll::Ready(result.map_err(|error| self.fail(error))) + if result.is_ready() { + drop(self.io_wake.writer.take()); + } + result } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - ready!(self.drain(cx))?; - match Pin::new(self.raw.as_mut().unwrap()).poll_flush(cx) { - Poll::Ready(Err(error)) => Poll::Ready(Err(self.fail(error))), - result => result, + self.io_wake.writer.register(cx.waker()); + let waker = Waker::from(self.io_wake.clone()); + let mut io_cx = Context::from_waker(&waker); + let result = (|| { + ready!(self.drain(DrainSide::Write))?; + match Pin::new(self.raw.as_mut().unwrap()).poll_flush(&mut io_cx) { + Poll::Ready(Err(error)) => Poll::Ready(Err(self.fail(error))), + result => result, + } + })(); + if result.is_ready() { + drop(self.io_wake.writer.take()); } + result } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - if self.write_closed { - return Poll::Ready(Ok(())); - } - ready!(self.drain(cx))?; - if self.tx_ctr.is_none() - && self - .vision - .as_ref() - .is_some_and(|(control, _)| control.writing_direct() || control.reading_direct()) - { - // Vision exposes the underlying transport after direct switching. - // Native/xorpub therefore inherit its CloseWrite (TCP FIN or TLS - // close_notify). Random's XorConn is not replaceable in Mihomo and - // still has whole-connection close semantics. - return match Pin::new(self.raw.as_mut().unwrap()).poll_shutdown(cx) { + self.io_wake.writer.register(cx.waker()); + let waker = Waker::from(self.io_wake.clone()); + let mut io_cx = Context::from_waker(&waker); + let result = (|| { + if self.write_closed { + return Poll::Ready(Ok(())); + } + ready!(self.drain(DrainSide::Write))?; + if self.tx_ctr.is_none() + && self.vision.as_ref().is_some_and(|(control, _)| { + control.writing_direct() || control.reading_direct() + }) + { + // Vision exposes the underlying transport after direct switching. + // Native/xorpub therefore inherit its CloseWrite (TCP FIN or TLS + // close_notify). Random's XorConn is not replaceable in Mihomo and + // still has whole-connection close semantics. + return match Pin::new(self.raw.as_mut().unwrap()).poll_shutdown(&mut io_cx) { + Poll::Ready(Ok(())) => { + self.write_closed = true; + Poll::Ready(Ok(())) + } + Poll::Ready(Err(error)) => Poll::Ready(Err(self.fail(error))), + result => result, + }; + } + // Mihomo CommonConn does not expose CloseWrite/replaceable upstream. + // Flush pending records then release this whole logical transport. + // A normal close must not invalidate a reusable node-local ticket. + match Pin::new(self.raw.as_mut().unwrap()).poll_flush(&mut io_cx) { Poll::Ready(Ok(())) => { self.write_closed = true; + self.raw.take(); + self.key.zeroize(); + self.plain.zeroize(); + self.io_wake.wake_all(); Poll::Ready(Ok(())) } Poll::Ready(Err(error)) => Poll::Ready(Err(self.fail(error))), result => result, - }; - } - // Mihomo CommonConn does not expose CloseWrite/replaceable upstream. - // Flush pending records then release this whole logical transport. - // A normal close must not invalidate a reusable node-local ticket. - match Pin::new(self.raw.as_mut().unwrap()).poll_flush(cx) { - Poll::Ready(Ok(())) => { - self.write_closed = true; - self.raw.take(); - self.key.zeroize(); - self.plain.zeroize(); - Poll::Ready(Ok(())) } - Poll::Ready(Err(error)) => Poll::Ready(Err(self.fail(error))), - result => result, + })(); + if result.is_ready() { + drop(self.io_wake.writer.take()); } + result + } +} + +impl Drop for Records { + fn drop(&mut self) { + // Raw transports can retain the fanout waker after their last poll. + // Release task references even when an owner cancels without repolling. + self.io_wake.wake_all(); } } @@ -746,6 +851,8 @@ mod tests { } } + include!("records_duplex_memory_tests.rs"); + struct DropProbe(Arc); impl Drop for DropProbe { fn drop(&mut self) { diff --git a/src/outbound/vless/encryption/records_duplex_memory_tests.rs b/src/outbound/vless/encryption/records_duplex_memory_tests.rs new file mode 100644 index 0000000..6dfe1d2 --- /dev/null +++ b/src/outbound/vless/encryption/records_duplex_memory_tests.rs @@ -0,0 +1,1366 @@ +// Synthetic full-1rtt Records handoff; no resumption or direct mode. The +// existing Go KDF/cipher vector is a control, not a new nonce4/5 Go vector. +#[derive(Default)] +struct NativeDuplexState { + block_writes: bool, + write_allowance: Option, + write_error: Option, + block_reads: bool, + pending_read_polls: usize, + first_read_output_len: Option, + raw_write_pulses: usize, + read_waker: Option, + output: Vec, + read_polls: usize, + pending_write_polls: usize, + flush_polls: usize, + shutdown_polls: usize, + remaining_input: usize, + write_waker: Option, + dropped: bool, +} +struct NativeDuplexRaw { + input: Vec, + read: usize, + state: Arc>, +} +impl Drop for NativeDuplexRaw { + fn drop(&mut self) { + let mut state = self.state.lock().unwrap(); + state.write_waker.take(); + state.read_waker.take(); + state.dropped = true; + } +} +impl AsyncRead for NativeDuplexRaw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + output: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + let mut state = this.state.lock().unwrap(); + state.read_polls += 1; + if state.first_read_output_len.is_none() { + state.first_read_output_len = Some(state.output.len()); + } + if state.block_reads { + state.pending_read_polls += 1; + state.read_waker = Some(cx.waker().clone()); + return Poll::Pending; + } + let count = output.remaining().min(this.input.len() - this.read); + output.put_slice(&this.input[this.read..this.read + count]); + this.read += count; + state.remaining_input = this.input.len() - this.read; + Poll::Ready(Ok(())) + } +} +impl AsyncWrite for NativeDuplexRaw { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + let mut state = self.state.lock().unwrap(); + if let Some(kind) = state.write_error { + return Poll::Ready(Err(io::Error::from(kind))); + } + if state.block_writes || state.write_allowance == Some(0) { + state.pending_write_polls += 1; + state.write_waker = Some(cx.waker().clone()); + return Poll::Pending; + } + let count = state + .write_allowance + .unwrap_or(input.len()) + .min(input.len()); + state.output.extend_from_slice(&input[..count]); + if let Some(allowance) = &mut state.write_allowance { + *allowance -= count; + } + Poll::Ready(Ok(count)) + } + fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + self.state.lock().unwrap().flush_polls += 1; + Poll::Ready(Ok(())) + } + fn poll_shutdown(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll> { + self.state.lock().unwrap().shutdown_polls += 1; + Poll::Ready(Ok(())) + } +} +struct NativeDuplexReport { + vector_ok: bool, + bootstrap_ok: bool, + metadata_accepted: bool, + metadata_flushed: bool, + metadata_wire_ok: bool, + response_header_ok: bool, + native_header_state: bool, + rx_available_before: bool, + app_accepted: bool, + tx_flush_pending: bool, + raw_tx_pending: bool, + tx_unchanged: bool, + raw_dropped: bool, + waker_released: bool, + read_polls_before: usize, + read_polls_after: usize, + read: Poll>, + actual: Vec, + expected: Vec, +} +fn native_duplex_frame(peer: &mut Aead, plain: &[u8]) -> io::Result> { + let length = u16::try_from(plain.len() + 16).map_err(|_| failure())?; + let header = [23, 3, 3, (length >> 8) as u8, length as u8]; + let mut wire = header.to_vec(); + wire.extend_from_slice(&peer.seal(plain, &header, None)?); + Ok(wire) +} +struct NativeDuplexFixture { + stream: Records, + state: Arc>, + metadata: bytes::Bytes, + expected_metadata_wire: Vec, + expected: Vec, + vector_ok: bool, + bootstrap_ok: bool, +} +fn native_duplex_fixture( + v: &serde_json::Value, + buffered_plain: bool, +) -> io::Result { + let material: [u8; 96] = bytes(&v["key"]).try_into().map_err(|_| failure())?; + let rx_context = bytes(&v["context"]); + let tx_context = b"native-full1rtt-duplex-upload-context"; + let suite = if v["cipher"] == "aes256gcm" { + Suite::Aes + } else { + Suite::ChaCha + }; + let expected = bytes(&v["plaintext"]); + let mut known = Aead::new(&rx_context, &material, suite)?; + let nonce = bytes(&v["nonce"]).try_into().map_err(|_| failure())?; + let vector_ok = + known.seal(&expected, &bytes(&v["aad"]), Some(nonce))? == bytes(&v["ciphertext"]); + + // Mirror Handshake::finish's authenticated RX handoff: ticket nonce1, + // length nonce2, then Records::new consumes padding nonce3. New DATA + // starts at nonce4. Never seed/set a nonce or use Records::resumed. + let mut peer_tx = Aead::new(&rx_context, &material, suite)?; + let ticket = [0_u8; 16]; // Zero lifetime, uncached1rtt. + let ticket_wire = peer_tx.seal(&ticket, &[], None)?; + let padding = [0_u8; 1]; + let padding_size = u16::try_from(padding.len() + 16).map_err(|_| failure())?; + let length_wire = peer_tx.seal(&padding_size.to_be_bytes(), &[], None)?; + let padding_wire = peer_tx.seal(&padding, &[], None)?; + let mut rx = Aead::new(&rx_context, &material, suite)?; + let decoded_ticket = rx.open(&ticket_wire, &[], None)?; + let decoded_length = rx.open(&length_wire, &[], None)?; + let bootstrap_ok = decoded_ticket == ticket + && decoded_length == padding_size.to_be_bytes() + && padding_wire.len() == usize::from(padding_size); + let mut first_plain = vec![0, 0]; // Ordinary VLESS response, no addons. + if buffered_plain { + first_plain.extend_from_slice(&expected); + } + let mut input = padding_wire; + input.extend_from_slice(&native_duplex_frame(&mut peer_tx, &first_plain)?); + if !buffered_plain { + input.extend_from_slice(&native_duplex_frame(&mut peer_tx, &expected)?); + } + let target = crate::session::Destination::Ip("192.0.2.9:443".parse().unwrap()); + let metadata = crate::outbound::vless::codec::encode_request_header( + uuid::Uuid::from_bytes([7; 16]), + crate::outbound::vless::codec::VlessCommand::Tcp, + Some(&target), + )?; + let mut peer_rx = Aead::new(tx_context, &material, suite)?; + let expected_metadata_wire = native_duplex_frame(&mut peer_rx, &metadata)?; + let state = Arc::new(Mutex::new(NativeDuplexState { + remaining_input: input.len(), + ..Default::default() + })); + let stream = Records::new( + Box::new(NativeDuplexRaw { + input, + read: 0, + state: state.clone(), + }), + Zeroizing::new(material), + suite, + Aead::new(tx_context, &material, suite)?, + rx, + None, + None, + usize::from(padding_size), + Arc::new(Cache::default()), + None, + ); + Ok(NativeDuplexFixture { + stream, + state, + metadata, + expected_metadata_wire, + expected, + vector_ok, + bootstrap_ok, + }) +} +fn native_duplex_case( + v: &serde_json::Value, + buffered_plain: bool, +) -> io::Result { + let NativeDuplexFixture { + mut stream, + state, + metadata, + expected_metadata_wire, + expected, + vector_ok, + bootstrap_ok, + } = native_duplex_fixture(v, buffered_plain)?; + let mut cx = Context::from_waker(std::task::Waker::noop()); + let metadata_accepted = matches!( + Pin::new(&mut stream).poll_write(&mut cx, &metadata), + Poll::Ready(Ok(count)) if count == metadata.len() + ); + let metadata_flushed = matches!( + Pin::new(&mut stream).poll_flush(&mut cx), + Poll::Ready(Ok(())) + ); + let metadata_wire_ok = state.lock().unwrap().output == expected_metadata_wire; + let mut response_header = [255_u8; 2]; + let response_header_poll = { + let mut output = ReadBuf::new(&mut response_header); + let result = Pin::new(&mut stream).poll_read(&mut cx, &mut output); + matches!(result, Poll::Ready(Ok(()))) && output.filled().len() == 2 + }; + let response_header_ok = response_header_poll && response_header == [0, 0]; + let native_header_state = matches!(stream.reading, Reading::Header) + && stream.filled == 0 + && stream.input.len() == 5 + && stream.rx.is_some() + && stream.tx_ctr.is_none() + && stream.rx_ctr.is_none() + && stream.ticket.is_none(); + let rx_available_before = if buffered_plain { + stream.plain[stream.consumed..] == expected + } else { + stream.plain.len() == stream.consumed + && state.lock().unwrap().remaining_input == expected.len() + 21 + }; + state.lock().unwrap().block_writes = true; + let app = b"queued app TX must not gate readable RX"; + let app_accepted = matches!( + Pin::new(&mut stream).poll_write(&mut cx, app), + Poll::Ready(Ok(count)) if count == app.len() + ); + let tx_flush_pending = Pin::new(&mut stream).poll_flush(&mut cx).is_pending(); + let raw_tx_pending = { + let state = state.lock().unwrap(); + state.pending_write_polls > 0 && state.write_waker.is_some() + }; + let pending_before = stream.pending.clone(); + let sent_before = stream.sent; + let read_polls_before = state.lock().unwrap().read_polls; + let mut buffer = vec![0; expected.len()]; + let (read, actual) = { + let mut output = ReadBuf::new(&mut buffer); + let result = Pin::new(&mut stream).poll_read(&mut cx, &mut output); + (result, output.filled().to_vec()) + }; + let tx_unchanged = pending_before.len() == app.len() + 21 + && sent_before == 0 + && stream.pending == pending_before + && stream.sent == sent_before + && state.lock().unwrap().output == expected_metadata_wire; + let read_polls_after = state.lock().unwrap().read_polls; + // No future, socket, background owner or real-time wait exists here. + // Drop Records/raw and release its registered waker BEFORE any verdict. + drop(stream); + let (raw_dropped, waker_released) = { + let state = state.lock().unwrap(); + ( + state.dropped, + state.write_waker.is_none() && state.read_waker.is_none(), + ) + }; + drop(state); + Ok(NativeDuplexReport { + vector_ok, + bootstrap_ok, + metadata_accepted, + metadata_flushed, + metadata_wire_ok, + response_header_ok, + native_header_state, + rx_available_before, + app_accepted, + tx_flush_pending, + raw_tx_pending, + tx_unchanged, + raw_dropped, + waker_released, + read_polls_before, + read_polls_after, + read, + actual, + expected, + }) +} +fn native_duplex_controls(report: &NativeDuplexReport) { + assert!(report.raw_dropped && report.waker_released); + assert!(report.vector_ok && report.bootstrap_ok); + assert!(report.metadata_accepted && report.metadata_flushed && report.metadata_wire_ok); + assert!(report.response_header_ok && report.native_header_state); + assert!(report.rx_available_before && report.app_accepted); + assert!(report.tx_flush_pending && report.raw_tx_pending && report.tx_unchanged); +} +#[test] +fn native_full1rtt_authenticated_plain_remainder_progresses_with_tx_blocked() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let report = native_duplex_case(&group[0], true)?; + native_duplex_controls(&report); + // Old production must pass every control above and fail this actual + // single-poll liveness assertion, never a missing field/API. + assert!( + matches!(&report.read, Poll::Ready(Ok(()))), + "authenticated plaintext was held behind unrelated pending TX" + ); + assert_eq!(report.actual, report.expected); + assert_eq!(report.read_polls_after, report.read_polls_before); + } + Ok(()) +} +#[test] +fn native_full1rtt_ready_ciphertext_progresses_with_tx_blocked() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let report = native_duplex_case(&group[0], false)?; + native_duplex_controls(&report); + assert!( + matches!(&report.read, Poll::Ready(Ok(()))), + "ready authenticated peer direction was held behind unrelated pending TX" + ); + assert_eq!(report.actual, report.expected); + assert!(report.read_polls_after > report.read_polls_before); + } + Ok(()) +} + +struct NativeCallerWake(std::sync::atomic::AtomicUsize); +impl std::task::Wake for NativeCallerWake { + fn wake(self: Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } + fn wake_by_ref(self: &Arc) { + self.0.fetch_add(1, Ordering::SeqCst); + } +} +struct NativeCallers { + a: Arc, + b: Arc, + wa: std::task::Waker, + wb: std::task::Waker, +} +impl NativeCallers { + fn new() -> Self { + let a = Arc::new(NativeCallerWake(std::sync::atomic::AtomicUsize::new(0))); + let b = Arc::new(NativeCallerWake(std::sync::atomic::AtomicUsize::new(0))); + Self { + wa: std::task::Waker::from(a.clone()), + wb: std::task::Waker::from(b.clone()), + a, + b, + } + } + fn counts(&self) -> [usize; 2] { + [ + self.a.0.load(Ordering::SeqCst), + self.b.0.load(Ordering::SeqCst), + ] + } +} +fn native_raw_write_ready(state: &Arc>, notify: bool) -> bool { + let wake = { + let mut state = state.lock().unwrap(); + state.block_writes = false; + if notify { + let wake = state.write_waker.take(); + if wake.is_some() { + state.raw_write_pulses += 1; + } + wake + } else { + None + } + }; + if let Some(wake) = wake { + wake.wake(); + true + } else { + false + } +} +fn native_wake_close( + stream: Records, + state: Arc>, + callers: NativeCallers, +) -> (bool, bool) { + let raw_weak = Arc::downgrade(&state); + let a_weak = Arc::downgrade(&callers.a); + let b_weak = Arc::downgrade(&callers.b); + drop(stream); + let raw_closed = { + let state = state.lock().unwrap(); + state.dropped && state.write_waker.is_none() && state.read_waker.is_none() + }; + drop(state); + drop(callers); + let weak_closed = + raw_weak.upgrade().is_none() && a_weak.upgrade().is_none() && b_weak.upgrade().is_none(); + (raw_closed, weak_closed) +} +fn native_wake_fixture( + v: &serde_json::Value, + buffered_plain: bool, + drain_payload: bool, +) -> io::Result<(NativeDuplexFixture, bool)> { + native_warm_fixture(native_duplex_fixture(v, buffered_plain)?, drain_payload) +} +fn native_warm_fixture( + mut fixture: NativeDuplexFixture, + drain_payload: bool, +) -> io::Result<(NativeDuplexFixture, bool)> { + let mut cx = Context::from_waker(std::task::Waker::noop()); + let accepted = matches!( + Pin::new(&mut fixture.stream).poll_write(&mut cx, &fixture.metadata), + Poll::Ready(Ok(count)) if count == fixture.metadata.len() + ); + let flushed = matches!( + Pin::new(&mut fixture.stream).poll_flush(&mut cx), + Poll::Ready(Ok(())) + ); + let mut header = [255_u8; 2]; + let header_ok = { + let mut output = ReadBuf::new(&mut header); + let read = Pin::new(&mut fixture.stream).poll_read(&mut cx, &mut output); + matches!(read, Poll::Ready(Ok(()))) && output.filled().len() == 2 + }; + let payload_ok = if drain_payload { + let mut bytes = vec![0; fixture.expected.len()]; + let mut output = ReadBuf::new(&mut bytes); + let read = Pin::new(&mut fixture.stream).poll_read(&mut cx, &mut output); + matches!(read, Poll::Ready(Ok(()))) && output.filled() == fixture.expected.as_slice() + } else { + true + }; + let warm = fixture.vector_ok + && fixture.bootstrap_ok + && accepted + && flushed + && header_ok + && header == [0, 0] + && payload_ok + && fixture.state.lock().unwrap().output == fixture.expected_metadata_wire + && fixture.stream.pending.is_empty() + && fixture.stream.sent == 0 + && fixture.stream.rx.is_some() + && matches!(fixture.stream.reading, Reading::Header); + Ok((fixture, warm)) +} + +#[test] +fn native_full1rtt_raw_tx_ready_wakes_both_independent_pending_callers() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let (mut fixture, warm) = native_wake_fixture(&group[0], false, true)?; + let callers = NativeCallers::new(); + let app = b"queued writer A business bytes"; + { + let mut state = fixture.state.lock().unwrap(); + state.block_writes = true; + state.block_reads = true; + } + let accepted = matches!( + Pin::new(&mut fixture.stream).poll_write(&mut Context::from_waker(&callers.wa), app), + Poll::Ready(Ok(count)) if count == app.len() + ); + let writer_pending = Pin::new(&mut fixture.stream) + .poll_flush(&mut Context::from_waker(&callers.wa)) + .is_pending(); + let pending_cipher = fixture.stream.pending.clone(); + let mut bytes = [0_u8; 1]; + let (reader_pending, no_plain) = { + let mut output = ReadBuf::new(&mut bytes); + let read = Pin::new(&mut fixture.stream) + .poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read.is_pending(), output.filled().is_empty()) + }; + let before_pulse = callers.counts(); + let control = { + let state = fixture.state.lock().unwrap(); + state.block_reads + && state.remaining_input == 0 + && state.pending_write_polls > 0 + && state.write_waker.is_some() + }; + let fired = native_raw_write_ready(&fixture.state, true); + // Capture the READY event now. Drop's wake cannot satisfy liveness. + let at_pulse = callers.counts(); + let read_pending_polls = fixture.state.lock().unwrap().pending_read_polls; + let untouched = fixture.stream.pending == pending_cipher + && fixture.stream.sent == 0 + && fixture.state.lock().unwrap().output == fixture.expected_metadata_wire; + let NativeDuplexFixture { stream, state, .. } = fixture; + let closed = native_wake_close(stream, state, callers); + assert!(closed.0 && closed.1); + assert!(warm && accepted && writer_pending && reader_pending && no_plain && control); + assert_eq!(before_pulse, [0, 0]); + assert!(fired && untouched); + assert!( + at_pulse[0] > 0 && at_pulse[1] > 0, + "one raw TX readiness event stranded an independently pending caller" + ); + assert!(read_pending_polls > 0); + } + Ok(()) +} + +#[test] +fn native_full1rtt_read_assisted_drain_wakes_writer_without_raw_event() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let (mut fixture, warm) = native_wake_fixture(&group[0], true, false)?; + let callers = NativeCallers::new(); + fixture.state.lock().unwrap().block_writes = true; + let app = b"writer A waits while reader B can assist"; + let accepted = matches!( + Pin::new(&mut fixture.stream).poll_write(&mut Context::from_waker(&callers.wa), app), + Poll::Ready(Ok(count)) if count == app.len() + ); + let writer_pending = Pin::new(&mut fixture.stream) + .poll_flush(&mut Context::from_waker(&callers.wa)) + .is_pending(); + let pending_cipher = fixture.stream.pending.clone(); + let raw_waiting = fixture.state.lock().unwrap().write_waker.is_some(); + let no_pulse = !native_raw_write_ready(&fixture.state, false); + let before_assist = callers.counts(); + let mut bytes = vec![0_u8; fixture.expected.len()]; + let (read, actual) = { + let mut output = ReadBuf::new(&mut bytes); + let read = Pin::new(&mut fixture.stream) + .poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read, output.filled().to_vec()) + }; + // Snapshot BEFORE Drop, which is permitted to wake both slots. + let at_assist = callers.counts(); + let expected_wire = [fixture.expected_metadata_wire.clone(), pending_cipher].concat(); + let drained = fixture.stream.pending.is_empty() + && fixture.stream.sent == 0 + && fixture.state.lock().unwrap().output == expected_wire; + let raw_pulses = fixture.state.lock().unwrap().raw_write_pulses; + let expected = fixture.expected.clone(); + let NativeDuplexFixture { stream, state, .. } = fixture; + let closed = native_wake_close(stream, state, callers); + assert!(closed.0 && closed.1); + assert!(warm && accepted && writer_pending && raw_waiting && no_pulse); + assert_eq!(before_assist, [0, 0]); + assert_eq!(raw_pulses, 0); + assert!(matches!(&read, Poll::Ready(Ok(()))) && drained); + assert_eq!(actual, expected); + assert!( + at_assist[0] > 0, + "read completed the queued TX without waking its pending writer" + ); + } + Ok(()) +} + +#[test] +fn resumed_opaque_prefix_blocks_rx_until_sent_then_business_tx_is_duplex() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let v = &group[0]; + let key: [u8; 96] = bytes(&v["key"]).try_into().map_err(|_| failure())?; + let suite = if v["cipher"] == "aes256gcm" { + Suite::Aes + } else { + Suite::ChaCha + }; + let context = bytes(&v["context"]); + let expected_first = bytes(&v["plaintext"]); + let expected_second = bytes(&group[1]["plaintext"]); + let prefix = b"opaque-owned-resumption-prefix-not-a-handshake-vector".to_vec(); + let input = [context.clone(), wire(v), wire(&group[1])].concat(); + let state = Arc::new(Mutex::new(NativeDuplexState { + block_writes: true, + remaining_input: input.len(), + ..Default::default() + })); + let mut stream = Records::resumed( + Box::new(NativeDuplexRaw { + input, + read: 0, + state: state.clone(), + }), + Zeroizing::new(key), + suite, + Aead::new(&context, &key, suite)?, + None, + false, + prefix.clone(), + Arc::new(Cache::default()), + Arc::new(Ticket { + pfs: Zeroizing::new([0; 64]), + bytes: Zeroizing::new([0; 16]), + expires: tokio::time::Instant::now() + std::time::Duration::from_secs(60), + }), + ); + let callers = NativeCallers::new(); + let prefix_flush_pending = Pin::new(&mut stream) + .poll_flush(&mut Context::from_waker(&callers.wa)) + .is_pending(); + let mut first = vec![0_u8; expected_first.len()]; + let (prefix_read_pending, no_early_plain) = { + let mut output = ReadBuf::new(&mut first); + let read = + Pin::new(&mut stream).poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read.is_pending(), output.filled().is_empty()) + }; + let prefix_held = { + let state = state.lock().unwrap(); + state.read_polls == 0 + && state.first_read_output_len.is_none() + && state.remaining_input > 0 + && state.output.is_empty() + && stream.pending == prefix + && stream.sent == 0 + && stream.rx.is_none() + }; + let prefix_ready_fired = native_raw_write_ready(&state, true); + let (first_read, first_actual) = { + let mut output = ReadBuf::new(&mut first); + let read = + Pin::new(&mut stream).poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read, output.filled().to_vec()) + }; + let prefix_sent_once = { + let state = state.lock().unwrap(); + state.output == prefix + && state.first_read_output_len == Some(prefix.len()) + && stream.pending.is_empty() + && stream.sent == 0 + && stream.rx.is_some() + }; + state.lock().unwrap().block_writes = true; + let app = b"ordinary accepted business record after the prefix"; + let accepted = matches!( + Pin::new(&mut stream).poll_write(&mut Context::from_waker(&callers.wa), app), + Poll::Ready(Ok(count)) if count == app.len() + ); + let business_flush_pending = Pin::new(&mut stream) + .poll_flush(&mut Context::from_waker(&callers.wa)) + .is_pending(); + let business_cipher = stream.pending.clone(); + let ready_cipher = state.lock().unwrap().remaining_input == wire(&group[1]).len(); + let mut second = vec![0_u8; expected_second.len()]; + let (second_read, second_actual) = { + let mut output = ReadBuf::new(&mut second); + let read = + Pin::new(&mut stream).poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read, output.filled().to_vec()) + }; + let business_unchanged = stream.pending == business_cipher + && stream.sent == 0 + && state.lock().unwrap().output == prefix; + let closed = native_wake_close(stream, state, callers); + assert!(closed.0 && closed.1); + // Opaque prefix tests only ownership/order, not a complete0rtt handshake. + assert!(prefix_flush_pending && prefix_read_pending && no_early_plain && prefix_held); + assert!(prefix_ready_fired && prefix_sent_once); + assert!(matches!(&first_read, Poll::Ready(Ok(())))); + assert_eq!(first_actual, expected_first); + assert!(accepted && business_flush_pending && ready_cipher && business_unchanged); + assert!( + matches!(&second_read, Poll::Ready(Ok(()))), + "established resumed RX still waited for unrelated business TX" + ); + assert_eq!(second_actual, expected_second); + } + Ok(()) +} + +#[test] +fn resumed_partial_opaque_prefix_survives_cancelled_flush_and_read_assist() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let v = &group[0]; + let key: [u8; 96] = bytes(&v["key"]).try_into().map_err(|_| failure())?; + let suite = if v["cipher"] == "aes256gcm" { + Suite::Aes + } else { + Suite::ChaCha + }; + let context = bytes(&v["context"]); + let expected_first = bytes(&v["plaintext"]); + let expected_second = bytes(&group[1]["plaintext"]); + let prefix = b"opaque-partial-resumption-prefix-owned-by-test".to_vec(); + let input = [context.clone(), wire(v), wire(&group[1])].concat(); + let state = Arc::new(Mutex::new(NativeDuplexState { + write_allowance: Some(7), + remaining_input: input.len(), + ..Default::default() + })); + let mut stream = Records::resumed( + Box::new(NativeDuplexRaw { + input, + read: 0, + state: state.clone(), + }), + Zeroizing::new(key), + suite, + Aead::new(&context, &key, suite)?, + None, + false, + prefix.clone(), + Arc::new(Cache::default()), + Arc::new(Ticket { + pfs: Zeroizing::new([0; 64]), + bytes: Zeroizing::new([0; 16]), + expires: tokio::time::Instant::now() + std::time::Duration::from_secs(60), + }), + ); + let callers = NativeCallers::new(); + let cancelled_flush_pending = { + let mut flush = Box::pin(stream.flush()); + let pending = + std::future::Future::poll(flush.as_mut(), &mut Context::from_waker(&callers.wa)) + .is_pending(); + // Cancel only this borrow/future, preserving the Records owner. + drop(flush); + pending + }; + let mut first = vec![0_u8; expected_first.len()]; + let prefix_read_pending = { + let mut output = ReadBuf::new(&mut first); + let read = + Pin::new(&mut stream).poll_read(&mut Context::from_waker(&callers.wb), &mut output); + read.is_pending() && output.filled().is_empty() + }; + let partial_held = { + let raw = state.lock().unwrap(); + raw.output.as_slice() == &prefix[..7] + && raw.read_polls == 0 + && raw.first_read_output_len.is_none() + && raw.remaining_input > 0 + && stream.pending == prefix + && stream.sent == 7 + && stream.rx.is_none() + }; + state.lock().unwrap().write_allowance = None; + // No raw wake/event: the reader itself must resume the exact offset. + let no_raw_pulse = !native_raw_write_ready(&state, false); + let (first_read, first_actual) = { + let mut output = ReadBuf::new(&mut first); + let read = + Pin::new(&mut stream).poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read, output.filled().to_vec()) + }; + let prefix_sent_once = { + let raw = state.lock().unwrap(); + raw.output == prefix + && raw.first_read_output_len == Some(prefix.len()) + && stream.pending.is_empty() + && stream.sent == 0 + && stream.rx.is_some() + }; + state.lock().unwrap().block_writes = true; + let app = b"ordinary business TX after a partially sent prefix"; + let accepted = matches!( + Pin::new(&mut stream).poll_write(&mut Context::from_waker(&callers.wa), app), + Poll::Ready(Ok(count)) if count == app.len() + ); + let business_flush_pending = Pin::new(&mut stream) + .poll_flush(&mut Context::from_waker(&callers.wa)) + .is_pending(); + let business_cipher = stream.pending.clone(); + let ready_cipher = state.lock().unwrap().remaining_input == wire(&group[1]).len(); + let mut second = vec![0_u8; expected_second.len()]; + let (second_read, second_actual) = { + let mut output = ReadBuf::new(&mut second); + let read = + Pin::new(&mut stream).poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read, output.filled().to_vec()) + }; + let business_unchanged = stream.pending == business_cipher + && stream.sent == 0 + && state.lock().unwrap().output == prefix; + let closed = native_wake_close(stream, state, callers); + // Opaque prefix is an ownership/order seam, not a full0rtt handshake. + assert!(closed.0 && closed.1); + assert!(cancelled_flush_pending && prefix_read_pending && partial_held); + assert!(no_raw_pulse && prefix_sent_once); + assert!(matches!(&first_read, Poll::Ready(Ok(())))); + assert_eq!(first_actual, expected_first); + assert!(accepted && business_flush_pending && ready_cipher && business_unchanged); + assert!( + matches!(&second_read, Poll::Ready(Ok(()))), + "partial prefix left an established stream permanently RX-blocked" + ); + assert_eq!(second_actual, expected_second); + } + Ok(()) +} + +#[test] +fn native_full1rtt_ready_tx_error_precedes_buffered_plain_and_preserves_new_ticket() +-> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let fixture = native_duplex_fixture(&group[0], true)?; + let (fixture, warm) = native_warm_fixture(fixture, false)?; + let NativeDuplexFixture { + mut stream, + state, + expected, + expected_metadata_wire, + .. + } = fixture; + let cache = stream.cache.clone(); + // The real authenticated-body path has no live stream ticket here. + // Do not manufacture buffered plaintext plus an unconsumed ticket. + let authenticated_cache_open = stream.ticket.is_none() + && cache.lookup()?.is_none() + && !cache.cancellation.is_cancelled(); + let buffered_authenticated_plain = stream.plain.get(stream.consumed..) + == Some(expected.as_slice()) + && state.lock().unwrap().remaining_input == 0; + let newer = Arc::new(Ticket { + pfs: Zeroizing::new([0; 64]), + bytes: Zeroizing::new([1; 16]), + expires: tokio::time::Instant::now() + std::time::Duration::from_secs(60), + }); + cache.publish(newer.clone())?; + let callers = NativeCallers::new(); + let app = b"accepted business TX must report its ready transport error"; + let accepted = matches!( + Pin::new(&mut stream).poll_write(&mut Context::from_waker(&callers.wa), app), + Poll::Ready(Ok(count)) if count == app.len() + ); + let pending_business = !stream.pending.is_empty() && stream.sent == 0; + state.lock().unwrap().write_error = Some(io::ErrorKind::ConnectionReset); + let mut bytes = vec![0_u8; expected.len()]; + let (read, leaked) = { + let mut output = ReadBuf::new(&mut bytes); + let read = + Pin::new(&mut stream).poll_read(&mut Context::from_waker(&callers.wb), &mut output); + (read, output.filled().to_vec()) + }; + let error_kind = match &read { + Poll::Ready(Err(error)) => Some(error.kind()), + _ => None, + }; + let failure_closed_raw = stream.raw.is_none() + && stream.pending.is_empty() + && stream.input.is_empty() + && state.lock().unwrap().dropped; + let exact_wire = state.lock().unwrap().output == expected_metadata_wire; + let newer_retained = cache + .lookup()? + .is_some_and(|current| Arc::ptr_eq(¤t, &newer)); + let newer_weak = Arc::downgrade(&newer); + let closed = native_wake_close(stream, state, callers); + drop(cache); + drop(newer); + let tickets_closed = newer_weak.upgrade().is_none(); + assert!(closed.0 && closed.1 && tickets_closed); + assert!( + warm && buffered_authenticated_plain + && authenticated_cache_open + && accepted + && pending_business + ); + assert_eq!( + error_kind, + Some(io::ErrorKind::ConnectionReset), + "ready TX error was hidden behind authenticated buffered plaintext" + ); + assert!(leaked.is_empty() && failure_closed_raw && exact_wire && newer_retained); + } + Ok(()) +} + +#[derive(Clone, Copy, Debug)] +enum NativeCancelOperation { + ReadReady, + FlushReady, + HalfShutdownReady, +} +#[derive(Debug)] +struct NativeCancelReport { + controls: bool, + before_cancel: [usize; 2], + at_cancel: [usize; 2], + raw_pulses: usize, + closed: (bool, bool), +} +fn native_guarded_cancel_case( + v: &serde_json::Value, + operation: NativeCancelOperation, +) -> io::Result { + let mut fixture = native_duplex_fixture(v, false)?; + let cache = fixture.stream.cache.clone(); + let raw = fixture.stream.raw.take().ok_or_else(failure)?; + // The actual handshake guard uses a CHILD token: dropping one stream + // must not cancel its node/siblings. Install it before metadata/RX setup. + fixture.stream.raw = Some(Box::new(crate::outbound::owned_stream::OwnedStream::new( + raw, + cache.cancellation.child_token(), + ))); + let drain_payload = !matches!(operation, NativeCancelOperation::ReadReady); + let (fixture, warm) = native_warm_fixture(fixture, drain_payload)?; + let NativeDuplexFixture { + mut stream, + state, + expected, + .. + } = fixture; + let callers = NativeCallers::new(); + let operation_ok = match operation { + NativeCancelOperation::ReadReady => { + state.lock().unwrap().block_writes = true; + let app = b"writer A waits while completed reader B overwrites cancel context"; + let accepted = matches!( + Pin::new(&mut stream).poll_write(&mut Context::from_waker(&callers.wa), app), + Poll::Ready(Ok(count)) if count == app.len() + ); + let writer_pending = Pin::new(&mut stream) + .poll_flush(&mut Context::from_waker(&callers.wa)) + .is_pending(); + let read_before = state.lock().unwrap().read_polls; + let mut bytes = vec![0; expected.len()]; + let read_ready = { + let mut output = ReadBuf::new(&mut bytes); + let read = Pin::new(&mut stream) + .poll_read(&mut Context::from_waker(&callers.wb), &mut output); + matches!(read, Poll::Ready(Ok(()))) && output.filled() == expected.as_slice() + }; // Completed reader/context is gone; it is never polled again. + let raw = state.lock().unwrap(); + accepted + && writer_pending + && read_ready + && raw.read_polls > read_before + && raw.block_writes + && raw.pending_write_polls > 0 + } + NativeCancelOperation::FlushReady | NativeCancelOperation::HalfShutdownReady => { + if matches!(operation, NativeCancelOperation::HalfShutdownReady) { + let control = SpliceControl::default(); + control.write_direct(); + stream = stream.with_vision(Some((control, Arc::default()))); + } + state.lock().unwrap().block_reads = true; + let mut bytes = [0_u8; 1]; + let reader_pending = { + let mut output = ReadBuf::new(&mut bytes); + let read = Pin::new(&mut stream) + .poll_read(&mut Context::from_waker(&callers.wa), &mut output); + read.is_pending() && output.filled().is_empty() + }; + let (flush_before, shutdown_before) = { + let raw = state.lock().unwrap(); + (raw.flush_polls, raw.shutdown_polls) + }; + let ready = if matches!(operation, NativeCancelOperation::FlushReady) { + Pin::new(&mut stream).poll_flush(&mut Context::from_waker(&callers.wb)) + } else { + Pin::new(&mut stream).poll_shutdown(&mut Context::from_waker(&callers.wb)) + }; + let raw = state.lock().unwrap(); + let raw_operation = if matches!(operation, NativeCancelOperation::FlushReady) { + raw.flush_polls > flush_before && !stream.write_closed + } else { + raw.shutdown_polls > shutdown_before && stream.write_closed + }; + reader_pending + && matches!(ready, Poll::Ready(Ok(()))) + && raw_operation + && raw.pending_read_polls > 0 + && stream.pending.is_empty() + && stream.raw.is_some() + && !raw.dropped + } + }; + let before_cancel = callers.counts(); + let cache_open = !cache.cancellation.is_cancelled(); + cache.close(); + // This immutable snapshot is the cancel event, BEFORE Records/IO Drop. + // Drop may wake both waiter slots, so postmortem counts are never proof. + let at_cancel = callers.counts(); + let raw_pulses = state.lock().unwrap().raw_write_pulses; + let closed = native_wake_close(stream, state, callers); + drop(cache); + Ok(NativeCancelReport { + controls: warm && operation_ok && cache_open, + before_cancel, + at_cancel, + raw_pulses, + closed, + }) +} +fn native_guarded_cancel_verdict(report: &NativeCancelReport) { + assert!(report.closed.0 && report.closed.1, "owners: {report:?}"); + assert!( + report.controls, + "invalid cancellation prerequisite: {report:?}" + ); + assert_eq!(report.raw_pulses, 0); + // A was still awaiting IO, with no earlier wake in lieu of this event. + assert_eq!( + report.before_cancel[0], 0, + "already-notified control: {report:?}" + ); + assert!( + report.at_cancel[0] > report.before_cancel[0], + "node cancellation stranded the pending caller: {report:?}" + ); +} +#[test] +fn native_full1rtt_owned_raw_rx_ready_preserves_writer_cancel_wake() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let report = native_guarded_cancel_case(&group[0], NativeCancelOperation::ReadReady)?; + native_guarded_cancel_verdict(&report); + } + Ok(()) +} +#[test] +fn native_full1rtt_owned_raw_flush_ready_preserves_reader_cancel_wake() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let report = native_guarded_cancel_case(&group[0], NativeCancelOperation::FlushReady)?; + native_guarded_cancel_verdict(&report); + } + Ok(()) +} +#[test] +fn native_full1rtt_owned_raw_half_shutdown_preserves_reader_cancel_wake() -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + let report = + native_guarded_cancel_case(&group[0], NativeCancelOperation::HalfShutdownReady)?; + native_guarded_cancel_verdict(&report); + } + Ok(()) +} + +// Real H2 framing/flow-control over paired record layers, NOT a KEM/VLESS handshake. +mod native_h2_duplex_memory { + use super::*; + use futures_util::{StreamExt as _, stream::FuturesUnordered}; + use tokio::io::DuplexStream; + #[derive(Default)] + struct Counts { + incoming: [usize; 2], + read: [usize; 2], + pending: usize, + witness: usize, + live: usize, + underflow: bool, + active: bool, + } + struct Raw { + io: DuplexStream, + side: usize, + counts: Arc>, + } + impl Drop for Raw { + fn drop(&mut self) { + self.counts.lock().unwrap().live -= 1; + } + } + impl AsyncRead for Raw { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let before = out.filled().len(); + let result = Pin::new(&mut self.io).poll_read(cx, out); + let read = out.filled().len() - before; + let mut counts = self.counts.lock().unwrap(); + counts.read[self.side] += read; + if let Some(left) = counts.incoming[self.side].checked_sub(read) { + counts.incoming[self.side] = left; + } else { + counts.underflow = true; + } + result + } + } + impl AsyncWrite for Raw { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let result = Pin::new(&mut self.io).poll_write(cx, bytes); + let mut counts = self.counts.lock().unwrap(); + match &result { + Poll::Ready(Ok(written)) => counts.incoming[1 - self.side] += *written, + Poll::Pending => { + counts.pending += 1; + if counts.active + && counts.read[self.side] >= 16 + && counts.incoming[self.side] != 0 + { + counts.witness += 1; + } + } + _ => {} + } + result + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.io).poll_shutdown(cx) + } + } + fn err(error: impl std::fmt::Display) -> String { + error.to_string() + } + async fn receive(mut body: h2::RecvStream, expected: u8) -> Result<(), String> { + let mut total = 0; + while let Some(data) = body.data().await { + let data = data.map_err(err)?; + total += data.len(); + if total > 65536 || data.iter().any(|byte| *byte != expected) { + return Err("incorrect synthetic H2 entity".into()); + } + body.flow_control() + .release_capacity(data.len()) + .map_err(err)?; + } + if total != 65536 || body.trailers().await.map_err(err)?.is_some() { + return Err("incomplete or unexpected H2 entity trailers".into()); + } + Ok(()) + } + async fn serve( + raw: Records, + mut client_done: tokio::sync::oneshot::Receiver<()>, + ) -> Result<(), String> { + let mut connection = h2::server::handshake(raw).await.map_err(err)?; + let mut work = FuturesUnordered::new(); + let (mut accepted, mut completed, mut responses_received) = (0, 0, false); + let mut connection_open = true; + while completed != 4 || !responses_received { + tokio::select! { + done = &mut client_done, if !responses_received => { + done.map_err(err)?; + responses_received = true; + } + done = work.next(), if accepted == 4 && !work.is_empty() => { + done.ok_or_else(|| "missing request owner".to_string())??; + completed += 1; + } + next = connection.accept(), if connection_open => { + let Some(next) = next else { + if accepted != 4 { return Err("H2 server closed before four requests".into()); } + // All streams may close before their ready body/done owners + // are polled. Continue checking those owners after EOF. + connection_open = false; + continue; + }; + let (request, mut response) = next.map_err(err)?; + let id = request.uri().path().trim_start_matches('/').parse::().map_err(err)?; + accepted += 1; + if id >= 4 || accepted > 4 { return Err("unexpected synthetic request".into()); } + let reply = http::Response::builder().status(200).body(()).map_err(err)?; + let mut body = response.send_response(reply, false).map_err(err)?; + body.send_data(bytes::Bytes::from(vec![id + 16; 65536]), true).map_err(err)?; + work.push(async move { receive(request.into_body(), id).await }); + } + } + } + Ok(()) + } + struct Report { + vector: bool, + transfer: Result<(), String>, + server: Result<(), String>, + live: usize, + pending: usize, + witness: usize, + underflow: bool, + weak_closed: bool, + random_state: bool, + } + async fn case(v: &serde_json::Value, capacity: usize) -> io::Result { + case_with_random_headers(v, capacity, false).await + } + async fn case_with_random_headers( + v: &serde_json::Value, + capacity: usize, + random_headers: bool, + ) -> io::Result { + let key: [u8; 96] = bytes(&v["key"]).try_into().map_err(|_| failure())?; + let contexts = [bytes(&v["context"]), vec![0x42; 16]]; + let suite = if v["cipher"] == "aes256gcm" { + Suite::Aes + } else { + Suite::ChaCha + }; + let mut known = Aead::new(&contexts[0], &key, suite)?; + let nonce = bytes(&v["nonce"]).try_into().map_err(|_| failure())?; + let vector = known.seal(&bytes(&v["plaintext"]), &bytes(&v["aad"]), Some(nonce))? + == bytes(&v["ciphertext"]); + let counts = Arc::new(Mutex::new(Counts { + live: 2, + ..Default::default() + })); + let weak = Arc::downgrade(&counts); + let (left, right) = tokio::io::duplex(capacity); + let mut left = Raw { + io: left, + side: 0, + counts: counts.clone(), + }; + let mut right = Raw { + io: right, + side: 1, + counts: counts.clone(), + }; + // Each peer's context is physically queued before Records owns that raw IO. + left.write_all(&contexts[0]).await?; + right.write_all(&contexts[1]).await?; + let record = |raw: Raw, context: &[u8]| -> io::Result { + let tx_ctr = if random_headers { + let iv: &[u8; 16] = context.try_into().map_err(|_| failure())?; + Some(Ctr::new(&key, iv)?) + } else { + None + }; + Ok(Records::resumed( + Box::new(raw), + Zeroizing::new(key), + suite, + Aead::new(context, &key, suite)?, + tx_ctr, + random_headers, + Vec::new(), + Arc::new(Cache::default()), + Arc::new(Ticket { + pfs: Zeroizing::new([0; 64]), + bytes: Zeroizing::new([0; 16]), + expires: tokio::time::Instant::now() + std::time::Duration::from_secs(60), + }), + )) + }; + let left = record(left, &contexts[0])?; + let right = record(right, &contexts[1])?; + let random_state = left.tx_ctr.is_some() && right.tx_ctr.is_some() + && left.random_headers && right.random_headers; + let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(3); + let (done_tx, done_rx) = tokio::sync::oneshot::channel(); + let mut server = tokio::spawn(serve(right, done_rx)); + let mut driver = None; + let transfer = tokio::time::timeout_at(deadline, async { + let (mut sender, connection) = h2::client::handshake(left).await.map_err(err)?; + driver = Some(tokio::spawn(connection)); + let mut work = FuturesUnordered::new(); + for id in 0_u8..4 { + sender = sender.ready().await.map_err(err)?; + let request = http::Request::builder() + .method("POST") + .uri(format!("https://records.invalid/{id}")) + .body(()) + .map_err(err)?; + let (response, mut body) = sender.send_request(request, false).map_err(err)?; + body.send_data(bytes::Bytes::from(vec![id; 65536]), true) + .map_err(err)?; + counts.lock().unwrap().active = true; + work.push(async move { + let response = response.await.map_err(err)?; + if response.status() != 200 { + return Err("unexpected H2 response status".into()); + } + receive(response.into_body(), id + 16).await + }); + } + drop(sender); + while let Some(done) = work.next().await { + done?; + } + done_tx + .send(()) + .map_err(|_| "server owner closed before all responses".to_string())?; + Ok::<_, String>(()) + }) + .await + .unwrap_or_else(|_| Err("bounded H2 progress guard expired".into())); + // The timed-out transfer future (and all request futures) is dropped above. + // Always abort AND await every remaining task before returning any verdict. + let server_result = match tokio::time::timeout_at(deadline, &mut server).await { + Ok(result) => result.map_err(err).and_then(|result| result), + Err(_) => { + server.abort(); + let _ = server.await; + Err("server guard expired; aborted/joined".into()) + } + }; + if let Some(driver) = driver { + driver.abort(); + let _ = driver.await; + } + let (live, pending, witness, underflow) = { + let c = counts.lock().unwrap(); + (c.live, c.pending, c.witness, c.underflow) + }; + drop(counts); + Ok(Report { + vector, + transfer, + server: server_result, + live, + pending, + witness, + underflow, + weak_closed: weak.upgrade().is_none(), + random_state, + }) + } + #[tokio::test(flavor = "current_thread")] + async fn paired_records_real_h2_four_bidirectional_entities_progress_with_buffered_rx() + -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + for capacity in [64, 256] { + let report = case(&group[0], capacity).await?; + assert_eq!(report.live, 0, "raw owner survived cleanup"); + assert!(report.weak_closed && !report.underflow && report.vector); + assert!( + report.pending > 0 && report.witness > 0, + "invalid seam: no observed raw TX Pending with peer RX bytes buffered" + ); + assert!(report.transfer.is_ok(), "transfer: {:?}", report.transfer); + assert!(report.server.is_ok(), "server: {:?}", report.server); + } + } + Ok(()) + } + #[tokio::test(flavor = "current_thread")] + async fn random_normal_records_real_h2_four_bidirectional_entities_preserve_ctr_under_backpressure() + -> io::Result<()> { + for group in vectors()["records"].as_array().unwrap().as_chunks::<3>().0 { + for capacity in [64, 256] { + let report = case_with_random_headers(&group[0], capacity, true).await?; + assert_eq!(report.live, 0, "raw owner survived cleanup"); + assert!(report.weak_closed && !report.underflow && report.vector); + assert!(report.random_state, "invalid Random CTR construction control"); + assert!( + report.pending > 0 && report.witness > 0, + "invalid seam: no observed raw TX Pending with peer RX bytes buffered" + ); + assert!(report.transfer.is_ok(), "Random transfer: {:?}", report.transfer); + assert!(report.server.is_ok(), "Random server: {:?}", report.server); + } + } + Ok(()) + } +} diff --git a/src/outbound/vless/http_reuse_memory_tests.rs b/src/outbound/vless/http_reuse_memory_tests.rs new file mode 100644 index 0000000..7d7b108 --- /dev/null +++ b/src/outbound/vless/http_reuse_memory_tests.rs @@ -0,0 +1,849 @@ +//! Actual VLESS constructors and static proofs only; never open a stream. +use super::*; +use crate::{ + config::{Config, IpVersion, ProxyProtocol, XHttpVersion}, + routing::GroupSelection, + session::Destination, +}; +use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD}; +use serde_json::{Value, json}; + +fn base() -> Value { + json!({"name":"memory-vless","type":"vless","server":"192.0.2.10","port":443, + "uuid":"09090909-0909-0909-0909-090909090909"}) +} + +fn reality(mut node: Value) -> Value { + node["tls"] = json!(true); + node["servername"] = json!("proxy.invalid"); + node["client-fingerprint"] = json!("chrome"); + // Synthetic public bytes only, never an actual server's identity. + node["reality-opts"] = json!({"public-key":URL_SAFE_NO_PAD.encode([9_u8;32]), + "short-id":"01020304"}); + node +} + +fn jls(mut node: Value) -> Value { + node["tls"] = json!(true); + node["servername"] = json!("proxy.invalid"); + node["client-fingerprint"] = json!("chrome"); + node["jls-opts"] = json!({"username":"memory-user","password":"memory-password"}); + node +} + +fn vision() -> Value { + let mut node = reality(base()); + node["flow"] = json!("xtls-rprx-vision"); + node +} + +fn xhttp(reality_security: bool, version: &str, mode: &str) -> Value { + let mut node = if reality_security { + reality(base()) + } else { + base() + }; + node["tls"] = json!(true); + node["servername"] = json!("proxy.invalid"); + node["network"] = json!("xhttp"); + node["alpn"] = json!([version]); + node["xhttp-opts"] = json!({"mode":mode,"path":"/memory/"}); + node +} + +fn config(node: Value) -> VlessOutboundConfig { + let config = Config::parse_yaml(json!({"proxies":[node]}).to_string().as_bytes()).unwrap(); + let ProxyProtocol::Vless(config) = &config.proxies[0].protocol else { + panic!("expected normalized VLESS configuration"); + }; + config.clone() +} + +fn path(dialer: Dialer) -> UpstreamPath { + UpstreamPath::direct( + ResolvedEndpoint { + logical_host: "192.0.2.10".into(), + port: 443, + addresses: vec!["192.0.2.10:443".parse().unwrap()], + }, + dialer, + ) +} + +fn node(raw: Value, upstream: UpstreamPath) -> VlessOutbound { + VlessOutbound::new_with_path(&config(raw), upstream).unwrap() +} + +fn capable(node: &VlessOutbound) -> bool { + OutboundConnector::permits_http_tcp_reuse(node) +} + +struct Unknown; +#[async_trait] +impl OutboundConnector for Unknown { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("static VLESS HTTP proof must not open a stream") + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("static VLESS HTTP proof must not open a datagram transport") + } +} + +#[test] +fn static_vless_actual_constructors_cover_three_matrix_paths_and_stop() { + for raw in [ + vision(), + xhttp(true, "h2", "stream-one"), + xhttp(false, "h3", "stream-one"), + ] { + let config = config(raw); + let node = VlessOutbound::new_with_shared_security( + &config, + path(Dialer::default()), + None, + &SecurityContext::new(), + 0, + VlessResourceLimits::new(65536, 16384, 16384), + ) + .unwrap(); + assert!(capable(&node)); + assert!(Dispatcher::permits_http_tcp_reuse(&node)); + assert_eq!(node.tasks.len(), 0); + if matches!(&config.security, crate::config::SecurityConfig::Reality(_)) { + assert!( + !node.upload.security.permits_static_http_reuse(), + "the shared VMess/Trojan helper must not gain REALITY permission" + ); + } + OutboundConnector::begin_shutdown(&node); + assert!(!capable(&node)); + } +} + +#[test] +fn static_vless_proof_is_not_limited_to_benchmark_modes_or_security_names() { + let mut standard_tcp = base(); + standard_tcp["tls"] = json!(true); + standard_tcp["servername"] = json!("proxy.invalid"); + let mut plain_h1 = xhttp(false, "http/1.1", "stream-one"); + plain_h1["tls"] = json!(false); + plain_h1.as_object_mut().unwrap().remove("servername"); + for raw in [ + base(), + standard_tcp, + reality(base()), + plain_h1, + xhttp(true, "h2", "packet-up"), + xhttp(false, "h2", "stream-up"), + xhttp(false, "h3", "packet-up"), + ] { + let node = node(raw, path(Dialer::default())); + assert!(capable(&node)); + } +} + +#[test] +fn actual_xhttp_versions_cover_implicit_and_explicit_download_legs() { + for version in ["http/1.1", "h2", "h3"] { + for mode in ["packet-up", "stream-up"] { + let mut raw = xhttp(false, version, mode); + let implicit = node(raw.clone(), path(Dialer::default())); + assert!(capable(&implicit)); + assert!(implicit.download.is_none()); + assert_eq!(implicit.tasks.len(), 0); + + raw["xhttp-opts"]["download-settings"] = json!({}); + let config = config(raw); + let explicit = VlessOutbound::new_with_paths( + &config, + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + assert!(capable(&explicit)); + assert!(explicit.download.is_some()); + assert_eq!(explicit.tasks.len(), 0); + } + } +} + +#[test] +fn vless_h3_uses_actual_xhttp_version_not_tcp_placeholder_or_parent_tcp_proof() { + let parent = Arc::new(node(vision(), path(Dialer::default()))); + assert!(capable(&parent)); + let h2 = node( + xhttp(true, "h2", "stream-one"), + UpstreamPath::proxy(parent.clone()), + ); + assert!(capable(&h2)); + let h3 = node( + xhttp(false, "h3", "stream-one"), + UpstreamPath::proxy(parent), + ); + assert!(matches!(&h3.transport, StreamTransport::Tcp)); + assert_eq!( + h3.xhttp.as_ref().unwrap().http_version(), + XHttpVersion::Http3 + ); + assert!( + !capable(&h3), + "a TCP proxy proof cannot prove its UDP carrier" + ); +} + +#[test] +fn every_static_download_leg_qualifies_but_dynamic_path_or_security_does_not() { + let mut raw = xhttp(true, "h2", "packet-up"); + raw["xhttp-opts"]["download-settings"] = json!({}); + let split_config = config(raw.clone()); + let node = VlessOutbound::new_with_paths( + &split_config, + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + assert!(capable(&node)); + let upload = node.xhttp.as_ref().unwrap(); + let download = &node.download.as_ref().unwrap().xhttp; + assert!(upload.uses_active_h2_reuse()); + assert!(download.uses_active_h2_reuse()); + assert!(capable(&node)); + assert!(upload.uses_active_h2_reuse()); + assert!(download.uses_active_h2_reuse()); + + let unknown_download = VlessOutbound::new_with_paths( + &split_config, + path(Dialer::default()), + Some(UpstreamPath::proxy(Arc::new(Unknown))), + ) + .unwrap(); + assert!(!capable(&unknown_download)); + let mut dynamic = xhttp(false, "h2", "packet-up"); + dynamic["xhttp-opts"]["download-settings"] = json!({"ech-opts":{"enable":true}}); + let dynamic = VlessOutbound::new_with_paths( + &config(dynamic), + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + assert!(!capable(&dynamic)); + raw["xhttp-opts"]["download-settings"] = json!({"server":"download.invalid"}); + let domain_download = VlessOutbound::new_with_paths( + &config(raw), + path(Dialer::default()), + Some(UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }), + ) + .unwrap(); + assert!(!capable(&domain_download)); +} + +#[test] +fn actual_download_h3_version_requires_its_own_direct_udp_path() { + let mut raw = xhttp(false, "h2", "packet-up"); + raw["xhttp-opts"]["download-settings"] = json!({"alpn":["h3"]}); + let config = config(raw); + let direct = VlessOutbound::new_with_paths( + &config, + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + assert_eq!( + direct.xhttp.as_ref().unwrap().http_version(), + XHttpVersion::Http2 + ); + assert_eq!( + direct.download.as_ref().unwrap().xhttp.http_version(), + XHttpVersion::Http3 + ); + assert!(capable(&direct)); + let parent = Arc::new(node(vision(), path(Dialer::default()))); + assert!(capable(&parent)); + let proxied_download = VlessOutbound::new_with_paths( + &config, + path(Dialer::default()), + Some(UpstreamPath::proxy(parent)), + ) + .unwrap(); + assert!(!capable(&proxied_download)); +} + +#[test] +fn actual_upload_and_download_xhttp_owner_stop_each_revoke_permission() { + let mut raw = xhttp(false, "h2", "packet-up"); + raw["xhttp-opts"]["download-settings"] = json!({}); + for stop_download in [false, true] { + let config = config(raw.clone()); + let node = VlessOutbound::new_with_paths( + &config, + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + assert!(capable(&node)); + let owner = if stop_download { + &node.download.as_ref().unwrap().xhttp + } else { + node.xhttp.as_ref().unwrap() + }; + owner.begin_stop(); + assert!(!node.cancellation.is_cancelled()); + assert!(!capable(&node)); + } +} + +fn with_owned_encryption(mut raw: Value, appearance: &str, rtt: &str) -> Value { + raw["encryption"] = json!(format!( + "mlkem768x25519plus.{appearance}.{rtt}.{}", + URL_SAFE_NO_PAD.encode([9_u8; 32]) + )); + raw +} + +fn encryption_cases(appearances: &[&str]) -> Vec { + let mut cases = Vec::new(); + for appearance in appearances { + for rtt in ["1rtt", "0rtt"] { + for enabled_vision in [false, true] { + let mut raw = base(); + if enabled_vision { + raw["flow"] = json!("xtls-rprx-vision"); + } + cases.push(with_owned_encryption(raw, appearance, rtt)); + } + } + } + cases +} + +#[test] +fn static_vless_rejects_dynamic_ech_without_static_identity() { + let mut dynamic = xhttp(false, "h3", "stream-one"); + dynamic["ech-opts"] = json!({"enable":true}); + assert!(!capable(&node(dynamic, path(Dialer::default())))); +} + +#[test] +fn static_encrypted_vless_actual_clients_qualify_without_io() { + for raw in encryption_cases(&["native", "xorpub", "random"]) { + let outbound = node(raw, path(Dialer::default())); + let client = outbound + .encryption + .as_ref() + .expect("actual encryption client"); + assert!(client.permits_http_tcp_reuse()); + assert!(capable(&outbound)); + assert!(Dispatcher::permits_http_tcp_reuse(&outbound)); + assert_eq!(outbound.tasks.len(), 0); + } +} + +#[test] +fn static_encrypted_vless_actual_client_and_node_stop_revoke_qualification() { + for raw in encryption_cases(&["native", "xorpub", "random"]) { + let stopped_client = node(raw.clone(), path(Dialer::default())); + let before_client = capable(&stopped_client); + let actual_client = stopped_client.encryption.is_some(); + if let Some(client) = &stopped_client.encryption { + client.close(); + } + let node_still_open = !stopped_client.cancellation.is_cancelled(); + let after_client = capable(&stopped_client); + let client_tasks = stopped_client.tasks.len(); + drop(stopped_client); + let stopped_node = node(raw, path(Dialer::default())); + let before_node = capable(&stopped_node); + OutboundConnector::begin_shutdown(&stopped_node); + let after_node = capable(&stopped_node); + let node_tasks = stopped_node.tasks.len(); + drop(stopped_node); + assert!(actual_client && node_still_open); + assert_eq!((client_tasks, node_tasks), (0, 0)); + assert!(before_client && before_node); + assert!(!after_client && !after_node); + } +} + +#[test] +fn static_encrypted_vless_keeps_all_physical_and_dependency_restrictions() { + for raw in encryption_cases(&["native", "xorpub", "random"]) { + let unknown = node(raw.clone(), UpstreamPath::proxy(Arc::new(Unknown))); + let unknown_permitted = capable(&unknown); + drop(unknown); + let mut restricted = Vec::new(); + for dialer in [ + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + ] { + let outbound = node(raw.clone(), path(dialer)); + restricted.push(capable(&outbound)); + drop(outbound); + } + let group = UpstreamPath::Group { + server: Destination::Ip("192.0.2.10:443".parse().unwrap()), + group: Arc::new(crate::outbound::SelectUpstream::new( + Arc::new(GroupSelection::new(0)), + vec![crate::outbound::SelectUpstreamMember::Direct], + )), + endpoint: None, + dialer: Dialer::default(), + }; + let grouped = node(raw.clone(), group); + let grouped_permitted = capable(&grouped); + drop(grouped); + let dialer = Dialer::default(); + let stopped = node(raw, path(dialer.clone())); + let before_stop = capable(&stopped); + dialer.begin_shutdown(); + let after_stop = capable(&stopped); + drop(stopped); + assert!(!unknown_permitted && !grouped_permitted); + assert!(restricted.iter().all(|permitted| !permitted)); + assert!(before_stop); + assert!(!after_stop); + } +} + +#[test] +fn static_random_vless_each_actual_upstream_dependency_stop_revokes_child_proof() { + for rtt in ["1rtt", "0rtt"] { + for stop_download in [false, true] { + for stop_client in [false, true] { + let parent_raw = with_owned_encryption(base(), "random", rtt); + let upload = Arc::new(node(parent_raw.clone(), path(Dialer::default()))); + let download = Arc::new(node(parent_raw, path(Dialer::default()))); + let mut raw = with_owned_encryption(xhttp(false, "h2", "packet-up"), "random", rtt); + raw["xhttp-opts"]["download-settings"] = json!({}); + let child = VlessOutbound::new_with_paths( + &config(raw), + UpstreamPath::proxy(upload.clone()), + Some(UpstreamPath::proxy(download.clone())), + ) + .unwrap(); + let before = capable(&upload) && capable(&download) && capable(&child); + let stopped = if stop_download { &download } else { &upload }; + let unaffected = if stop_download { &upload } else { &download }; + if stop_client { + stopped.encryption.as_ref().unwrap().close(); + } else { + OutboundConnector::begin_shutdown(stopped.as_ref()); + } + let dependency_revoked = !capable(stopped) && capable(unaffected); + let child_revoked = !capable(&child); + let child_owner_open = !child.cancellation.is_cancelled(); + let client_close_keeps_parent_owner_open = + !stop_client || !stopped.cancellation.is_cancelled(); + let tasks = child.tasks.len() + upload.tasks.len() + download.tasks.len(); + drop(child); + drop(upload); + drop(download); + assert!( + before, + "invalid control: actual Random dependency did not qualify" + ); + assert!(child_owner_open && client_close_keeps_parent_owner_open); + assert_eq!(tasks, 0); + assert!(dependency_revoked && child_revoked); + } + } + } +} + +#[test] +fn static_encrypted_vless_checks_each_download_path_and_owner() { + for appearance in ["native", "xorpub", "random"] { + for rtt in ["1rtt", "0rtt"] { + let mut raw = with_owned_encryption(xhttp(false, "h2", "packet-up"), appearance, rtt); + raw["xhttp-opts"]["download-settings"] = json!({}); + let selected = config(raw.clone()); + let direct = || path(Dialer::default()); + let make = |selected: &VlessOutboundConfig, download: UpstreamPath| { + VlessOutbound::new_with_paths(selected, direct(), Some(download)).unwrap() + }; + for stop_download in [false, true] { + let outbound = make(&selected, direct()); + let upload = outbound.xhttp.as_ref().unwrap(); + let download = &outbound.download.as_ref().unwrap().xhttp; + let private_pool = || { + ( + upload.uses_active_h2_reuse(), + download.uses_active_h2_reuse(), + ) + }; + let before = private_pool(); + assert!(capable(&outbound)); + assert_eq!(private_pool(), before); + if stop_download { + download.begin_stop(); + } else { + upload.begin_stop(); + } + assert!(!capable(&outbound)); + } + let unknown = make(&selected, UpstreamPath::proxy(Arc::new(Unknown))); + assert!(!capable(&unknown)); + let mut dynamic_upload = raw.clone(); + dynamic_upload["ech-opts"] = json!({"enable":true}); + raw["xhttp-opts"]["download-settings"] = json!({"ech-opts":{"enable":true}}); + for dynamic in [dynamic_upload, raw] { + assert!(!capable(&make(&config(dynamic), direct()))); + } + } + } +} + +#[test] +fn static_vless_preserves_upstream_and_physical_restrictions() { + for raw in [ + vision(), + jls(base()), + jls(xhttp(false, "http/1.1", "packet-up")), + jls(xhttp(false, "h2", "stream-one")), + xhttp(true, "h2", "stream-one"), + xhttp(false, "h3", "stream-one"), + ] { + assert!(!capable(&node( + raw.clone(), + UpstreamPath::proxy(Arc::new(Unknown)) + ))); + for dialer in [ + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + ] { + assert!(!capable(&node(raw.clone(), path(dialer)))); + } + let dialer = Dialer::default(); + let stopped = node(raw, path(dialer.clone())); + assert!(capable(&stopped)); + dialer.begin_shutdown(); + assert!(!capable(&stopped)); + } + let group = UpstreamPath::Group { + server: Destination::Ip("192.0.2.10:443".parse().unwrap()), + group: Arc::new(crate::outbound::SelectUpstream::new( + Arc::new(GroupSelection::new(0)), + vec![crate::outbound::SelectUpstreamMember::Direct], + )), + endpoint: None, + dialer: Dialer::default(), + }; + assert!(!capable(&node(vision(), group))); +} + +#[test] +fn business_http_proof_does_not_expand_xhttp_private_active_pool_qualification() { + let h2 = node(xhttp(true, "h2", "stream-one"), path(Dialer::default())); + assert!(capable(&h2)); + assert!(!h2.xhttp.as_ref().unwrap().uses_active_h2_reuse()); + let parent = Arc::new(node(vision(), path(Dialer::default()))); + let mut raw = xhttp(true, "h2", "packet-up"); + raw["xhttp-opts"]["download-settings"] = json!({}); + let config = config(raw); + let split = VlessOutbound::new_with_paths( + &config, + UpstreamPath::proxy(parent.clone()), + Some(UpstreamPath::proxy(parent)), + ) + .unwrap(); + assert!(capable(&split)); + assert!(!split.xhttp.as_ref().unwrap().uses_active_h2_reuse()); + assert!( + !split + .download + .as_ref() + .unwrap() + .xhttp + .uses_active_h2_reuse() + ); +} + +#[test] +fn static_vless_jls_actual_factories_keep_shared_security_keyless_and_stop() { + let mut cases = vec![jls(base())]; + for network in ["ws", "grpc"] { + let mut raw = jls(base()); + raw["network"] = json!(network); + cases.push(raw); + } + for version in ["http/1.1", "h2"] { + for mode in ["packet-up", "stream-up", "stream-one"] { + let raw = jls(xhttp(false, version, mode)); + cases.push(raw.clone()); + if mode != "stream-one" { + let mut split = raw; + split["xhttp-opts"]["download-settings"] = json!({ + "jls-opts":{"username":"other-memory-user","password":"other-memory-password"} + }); + cases.push(split); + } + } + } + for raw in cases { + for named_profile in [false, true] { + let mut raw = raw.clone(); + if !named_profile { + raw.as_object_mut().unwrap().remove("client-fingerprint"); + } + let config = config(raw); + let outbound = VlessOutbound::new_with_shared_security( + &config, + path(Dialer::default()), + config.download().map(|_| path(Dialer::default())), + &SecurityContext::new(), + 0, + VlessResourceLimits::new(65536, 16384, 16384), + ) + .unwrap(); + assert!(capable(&outbound)); + assert!(Dispatcher::permits_http_tcp_reuse(&outbound)); + assert!(!outbound.upload.security.permits_static_http_reuse()); + if let Some(download) = &outbound.download { + assert!(!download.transport.security.permits_static_http_reuse()); + } + assert_eq!(outbound.tasks.len(), 0); + OutboundConnector::begin_shutdown(&outbound); + assert!(!capable(&outbound)); + } + } +} + +#[test] +fn static_vless_jls_requires_actual_clients_for_both_marked_legs() { + let mut raw = jls(xhttp(false, "h2", "packet-up")); + raw["xhttp-opts"]["download-settings"] = json!({}); + let split = config(raw); + for replace_download in [false, true] { + for standard_client in [false, true] { + let mut outbound = VlessOutbound::new_with_paths( + &split, + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + assert!(capable(&outbound)); + let replacement_config = if standard_client { + config(xhttp(false, "h2", "stream-one")).security + } else { + crate::config::SecurityConfig::None + }; + let replacement = SecurityClient::from_security(&replacement_config).unwrap(); + assert!(replacement.permits_static_http_reuse()); + if replace_download { + outbound.download.as_mut().unwrap().transport.security = replacement; + } else { + outbound.upload.security = replacement; + } + assert!( + !capable(&outbound), + "a config marker cannot prove a different backend" + ); + } + let mut outbound = VlessOutbound::new_with_paths( + &split, + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + if replace_download { + outbound + .download + .as_mut() + .unwrap() + .transport + .http_reuse_security = HttpReuseSecurity::Unproven; + } else { + outbound.upload.http_reuse_security = HttpReuseSecurity::Unproven; + } + assert!( + !capable(&outbound), + "an actual JLS backend cannot override an unproven leg" + ); + } + let outbound = node(jls(base()), path(Dialer::default())); + assert!(!outbound.upload.permits_static_http_reuse(true)); +} + +#[test] +fn static_vless_jls_checks_each_download_path_and_owner() { + let mut raw = jls(xhttp(false, "http/1.1", "packet-up")); + raw["xhttp-opts"]["download-settings"] = json!({}); + let split = config(raw.clone()); + for stop_download in [false, true] { + let outbound = VlessOutbound::new_with_paths( + &split, + path(Dialer::default()), + Some(path(Dialer::default())), + ) + .unwrap(); + assert!(capable(&outbound)); + let owner = if stop_download { + &outbound.download.as_ref().unwrap().xhttp + } else { + outbound.xhttp.as_ref().unwrap() + }; + owner.begin_stop(); + assert!(!outbound.cancellation.is_cancelled()); + assert!(!capable(&outbound)); + } + for stop_download in [false, true] { + let upload_dialer = Dialer::default(); + let download_dialer = Dialer::default(); + let outbound = VlessOutbound::new_with_paths( + &split, + path(upload_dialer.clone()), + Some(path(download_dialer.clone())), + ) + .unwrap(); + assert!(capable(&outbound)); + if stop_download { + download_dialer.begin_shutdown(); + } else { + upload_dialer.begin_shutdown(); + } + assert!(!outbound.cancellation.is_cancelled()); + assert!(!capable(&outbound)); + } + for restricted_download in [false, true] { + for restricted_dialer in [ + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + ] { + let upload = path(if restricted_download { + Dialer::default() + } else { + restricted_dialer.clone() + }); + let download = path(if restricted_download { + restricted_dialer + } else { + Dialer::default() + }); + let outbound = VlessOutbound::new_with_paths(&split, upload, Some(download)).unwrap(); + assert!(!capable(&outbound)); + } + } + let unknown = VlessOutbound::new_with_paths( + &split, + path(Dialer::default()), + Some(UpstreamPath::proxy(Arc::new(Unknown))), + ) + .unwrap(); + assert!(!capable(&unknown)); + raw["xhttp-opts"]["download-settings"] = json!({"server":"download.invalid"}); + let domain = VlessOutbound::new_with_paths( + &config(raw), + path(Dialer::default()), + Some(UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }), + ) + .unwrap(); + assert!(!capable(&domain)); +} + +#[test] +fn static_vless_jls_does_not_change_private_physical_pool_qualification() { + for version in ["http/1.1", "h2"] { + let one = node( + jls(xhttp(false, version, "stream-one")), + path(Dialer::default()), + ); + assert!(capable(&one)); + assert!(!one.xhttp.as_ref().unwrap().uses_active_h2_reuse()); + let mut raw = jls(xhttp(false, version, "packet-up")); + raw["xhttp-opts"]["download-settings"] = json!({}); + let split = node(raw, path(Dialer::default())); + assert!(capable(&split)); + let expected = version == "h2"; + assert_eq!( + split.xhttp.as_ref().unwrap().uses_active_h2_reuse(), + expected + ); + assert_eq!( + split + .download + .as_ref() + .unwrap() + .xhttp + .uses_active_h2_reuse(), + expected + ); + } +} + +#[test] +fn static_vless_jls_invalid_credentials_never_construct_a_capable_node() { + let mut config = config(jls(base())); + let crate::config::SecurityConfig::Jls(identity) = &mut config.security else { + panic!("expected JLS"); + }; + identity.password.clear(); + assert!(SecurityClient::from_security(&config.security).is_err()); + assert!(VlessOutbound::new_with_path(&config, path(Dialer::default())).is_err()); +} + +#[test] +fn macos_mptcp_preference_preserves_the_actual_vless_static_tcp_proof() { + let mut raw = base(); + raw["mptcp"] = json!(true); + let parsed = + Config::parse_yaml(json!({"proxies": [raw.clone()]}).to_string().as_bytes()).unwrap(); + let proxy = &parsed.proxies[0]; + let requested = proxy.mptcp; + let ProxyProtocol::Vless(config) = &proxy.protocol else { + panic!("expected the normalized VLESS protocol"); + }; + let dialer = Dialer::default().with_mptcp(requested); + let configured = VlessOutbound::new_with_path(config, path(dialer.clone())).unwrap(); + let before = capable(&configured); + let dispatcher_before = Dispatcher::permits_http_tcp_reuse(&configured); + let tasks = configured.tasks.len(); + dialer.begin_shutdown(); + let after = capable(&configured); + drop(configured); + let ordinary = node(base(), path(Dialer::default())); + let ordinary_permitted = capable(&ordinary); + drop(ordinary); + assert!(requested && parsed.proxies[0].mptcp); + assert!(ordinary_permitted); + assert_eq!(tasks, 0); + assert_eq!(before, cfg!(target_os = "macos")); + assert_eq!(dispatcher_before, before); + assert!(!after); + + for restricted in [ + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_ip_version(IpVersion::Ipv6), + Dialer::default().with_egress(&crate::config::EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }), + ] { + let outbound = node(raw.clone(), path(restricted.with_mptcp(true))); + let permitted = capable(&outbound); + let tasks = outbound.tasks.len(); + drop(outbound); + assert_eq!(tasks, 0); + assert!( + !permitted, + "a configured MPTCP preference must not bypass physical restrictions" + ); + } +} diff --git a/src/outbound/vless/outbound.rs b/src/outbound/vless/outbound.rs index 24e2ee4..78e8915 100644 --- a/src/outbound/vless/outbound.rs +++ b/src/outbound/vless/outbound.rs @@ -51,11 +51,39 @@ use crate::outbound::{ server_destination, }; +// Classification is fixed only by this module's trusted constructors, which +// construct each concrete SecurityClient from the same normalized leg config. +// REALITY and JLS permission stays local to VLESS, not the shared proxy helper. +#[cfg(feature = "inbound-http")] +#[derive(Clone, Copy)] +enum HttpReuseSecurity { + Plain, + Standard, + Reality, + Jls, + Unproven, +} + +#[cfg(feature = "inbound-http")] +impl HttpReuseSecurity { + fn from_config(config: &crate::config::SecurityConfig) -> Self { + match config { + crate::config::SecurityConfig::None => Self::Plain, + crate::config::SecurityConfig::Tls(_) => Self::Standard, + crate::config::SecurityConfig::Reality(_) => Self::Reality, + crate::config::SecurityConfig::Jls(_) => Self::Jls, + crate::config::SecurityConfig::ShadowTls(_) => Self::Unproven, + } + } +} + #[derive(Clone)] struct VlessTransportLeg { server: crate::session::Destination, upstream: UpstreamPath, security: SecurityClient, + #[cfg(feature = "inbound-http")] + http_reuse_security: HttpReuseSecurity, } fn static_h2_security(config: &crate::config::SecurityConfig) -> bool { @@ -73,6 +101,25 @@ fn static_h2_security(config: &crate::config::SecurityConfig) -> bool { } impl VlessTransportLeg { + #[cfg(feature = "inbound-http")] + fn permits_static_http_reuse(&self, datagram_carrier: bool) -> bool { + let security = match self.http_reuse_security { + HttpReuseSecurity::Plain => { + !datagram_carrier && self.security.permits_static_http_reuse() + } + HttpReuseSecurity::Standard => self.security.permits_static_http_reuse(), + HttpReuseSecurity::Reality => !datagram_carrier, + HttpReuseSecurity::Jls => !datagram_carrier && self.security.has_fixed_jls_identity(), + HttpReuseSecurity::Unproven => false, + }; + security + && if datagram_carrier { + self.upstream.permits_static_direct_http_reuse(&self.server) + } else { + self.upstream.permits_static_http_reuse(&self.server) + } + } + async fn h2_lease<'a>( &self, client: &'a XHttpClient, @@ -327,8 +374,30 @@ impl VlessOutbound { && !options.only_tcp && !options.padding }); + // Yamux channel readiness does not prove a physical metadata flush. + // Share only the bounded POST geometry, never H2Mux's UDP budget proof. + let response_overlap = self.encryption.is_none() + && self.download.is_none() + && smux.is_some_and(|options| { + options.enabled + && options.protocol == crate::config::SingMuxProtocol::Yamux + && !options.only_tcp + && !options.padding + }); + // Smux gets the existing Body response geometry only. Keep its + // physical send retention and UDP control on the original path. + let smux_response_overlap = self.encryption.is_none() + && self.download.is_none() + && smux.is_some_and(|options| { + options.enabled + && options.protocol == crate::config::SingMuxProtocol::Smux + && !options.only_tcp + && !options.padding + }); if let Some(upload) = &mut self.xhttp { upload.set_shared_packet_up_transport(shared); + upload.set_packet_up_response_overlap(response_overlap || smux_response_overlap); + upload.set_yamux_packet_up_send_retention(response_overlap); } } @@ -565,6 +634,8 @@ impl VlessOutbound { server: server_destination(&config.address, config.port)?, upstream, security, + #[cfg(feature = "inbound-http")] + http_reuse_security: HttpReuseSecurity::from_config(&config.security), }, xhttp: { let mut request = @@ -594,6 +665,8 @@ impl VlessOutbound { server: server_destination(&config.address, config.port)?, upstream: upload_path, security: upload_security, + #[cfg(feature = "inbound-http")] + http_reuse_security: HttpReuseSecurity::from_config(&config.security), }, xhttp, download, @@ -989,6 +1062,37 @@ impl PreparedStream { } #[async_trait] impl OutboundConnector for VlessOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + if self.cancellation.is_cancelled() + || self + .encryption + .as_ref() + .is_some_and(|client| !client.permits_http_tcp_reuse()) + { + return false; + } + let upload_datagram = self + .xhttp + .as_ref() + .is_some_and(|client| client.http_version() == crate::config::XHttpVersion::Http3); + if self + .xhttp + .as_ref() + .is_some_and(|client| !client.is_http_reuse_owner_open()) + || !self.upload.permits_static_http_reuse(upload_datagram) + { + return false; + } + self.download.as_ref().is_none_or(|download| { + self.xhttp.is_some() + && download.xhttp.is_http_reuse_owner_open() + && download.transport.permits_static_http_reuse( + download.xhttp.http_version() == crate::config::XHttpVersion::Http3, + ) + }) + } + async fn connect_stream( &self, session: StreamSession, @@ -1093,6 +1197,11 @@ impl Drop for VlessOutbound { #[async_trait] impl Dispatcher for VlessOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + OutboundConnector::permits_http_tcp_reuse(self) + } + async fn connect_tcp(&self, session: StreamSession) -> Result { OutboundConnector::connect_stream(self, session, &EstablishContext::default()) .await @@ -1323,6 +1432,104 @@ mod active_h2_memory_tests { type Downloads = Arc>>>; + #[test] + fn private_split_h2_mptcp_preference_tracks_macos_plain_tcp_scope() { + let base = serde_json::json!({ + "mixed-port": 1080, + "proxies": [{ + "name": "peer", "type": "vless", "server": "192.0.2.1", "port": 443, + "uuid": "07070707-0707-0707-0707-070707070707", "mptcp": false, + "network": "xhttp", "tls": true, "servername": "memory.invalid", "alpn": ["h2"], + "xhttp-opts": {"mode": "packet-up", "path": "/x", + "download-settings": {"server": "192.0.2.2", "path": "/x"}} + }], + "rules": ["MATCH,peer"] + }); + // Static TLS clients and the actual static_h2_dialer proof are created; + // no connection, DNS operation, listener or protocol-driving task starts. + let observe = |raw: &serde_json::Value, dialer: Dialer| { + let parsed = crate::config::Config::parse_yaml(raw.to_string().as_bytes()).unwrap(); + let requested = parsed.proxies[0].mptcp; + let crate::config::ProxyProtocol::Vless(config) = &parsed.proxies[0].protocol else { + panic!("expected the normalized split-H2 VLESS protocol"); + }; + let outbound = + VlessOutbound::new_with_path(config, UpstreamPath::LazyDirect { dialer }).unwrap(); + let active = [ + outbound.xhttp.as_ref().unwrap().uses_active_h2_reuse(), + outbound + .download + .as_ref() + .unwrap() + .xhttp + .uses_active_h2_reuse(), + ]; + let cancellation = outbound + .upload + .upstream + .static_h2_dialer(&outbound.upload.server) + .map(Dialer::h2_reuse_cancellation); + let tasks = outbound.tasks.len(); + drop(outbound); + (active, tasks, requested, cancellation) + }; + let (ordinary, ordinary_tasks, ordinary_requested, token) = + observe(&base, Dialer::default()); + drop(token); + let mut marked = base.clone(); + marked["proxies"][0]["mptcp"] = serde_json::json!(true); + let dialer = Dialer::default().with_mptcp(true); + let (active, tasks, requested, token) = observe(&marked, dialer.clone()); + let before_stop = token.as_ref().map(CancellationToken::is_cancelled); + dialer.begin_shutdown(); + let after_stop = token.as_ref().map(CancellationToken::is_cancelled); + drop(token); + drop(dialer); + assert_eq!(ordinary, [true, true]); + assert_eq!(ordinary_tasks, 0); + assert!(!ordinary_requested && requested && marked["proxies"][0]["mptcp"] == true); + assert_eq!(tasks, 0); + assert_eq!(active, [cfg!(target_os = "macos"); 2]); + assert_eq!(before_stop, cfg!(target_os = "macos").then_some(false)); + assert_eq!(after_stop, cfg!(target_os = "macos").then_some(true)); + // uses_active_h2_reuse is an immutable pool-selection fact, not a + // shutdown receipt. Check the real Dialer cancellation token above. + + for restricted in [ + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + Dialer::default().with_ip_version(crate::config::IpVersion::Ipv4), + Dialer::default().with_egress(&crate::config::EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }), + ] { + let (active, tasks, requested, token) = observe(&marked, restricted.with_mptcp(true)); + drop(token); + assert_eq!(tasks, 0); + assert!(requested); + assert_eq!(active, [false, false]); + } + for change in ["mode", "version", "security"] { + let mut raw = marked.clone(); + match change { + "mode" => raw["proxies"][0]["xhttp-opts"]["mode"] = serde_json::json!("stream-up"), + "version" => raw["proxies"][0]["alpn"] = serde_json::json!(["http/1.1"]), + "security" => raw["proxies"][0]["ech-opts"] = serde_json::json!({"enable": true}), + _ => unreachable!(), + } + let (active, tasks, requested, token) = + observe(&raw, Dialer::default().with_mptcp(true)); + drop(token); + assert_eq!(tasks, 0); + assert!(requested); + assert_eq!( + active, + [false, false], + "private H2 bypassed its {change} gate" + ); + } + } + // Config -> production pool selection only. The memory peer below does // not perform native REALITY authentication; real TUN verifies it separately. fn with_static_reality(mut raw: serde_json::Value, reality: bool) -> serde_json::Value { @@ -1700,3 +1907,7 @@ mod active_h2_memory_tests { assert_eq!(verified_extra, 2, "new physicals did not both deliver/echo"); } } + +#[cfg(all(test, feature = "inbound-http"))] +#[path = "http_reuse_memory_tests.rs"] +mod http_reuse_memory_tests; diff --git a/src/outbound/vmess/http_cover_reuse_memory_tests.rs b/src/outbound/vmess/http_cover_reuse_memory_tests.rs new file mode 100644 index 0000000..1da14e1 --- /dev/null +++ b/src/outbound/vmess/http_cover_reuse_memory_tests.rs @@ -0,0 +1,1558 @@ +//! Real client construction with a bounded wire-authenticating memory peer. +//! Header parsing is a test-only finite model of v2ray-core AEAD/server.go. +//! BodyCodec is shared production code: this is not an official server run. +use super::*; +use crate::{ + config::{Config, ProxyProtocol}, + dispatch::{DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, UpstreamPath, + }, + session::{Destination, InboundKind, StreamSession}, +}; +use aes::cipher::{BlockCipherDecrypt, KeyInit}; +use async_trait::async_trait; +use futures_util::{FutureExt, future::poll_fn}; +use md5::Md5; +use sha2::{Digest, Sha256}; +use std::{ + collections::VecDeque, + future::Future, + panic::AssertUnwindSafe, + sync::{ + Arc, Mutex, Weak, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + time::{Duration, SystemTime, UNIX_EPOCH}, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt, DuplexStream}, + sync::oneshot, + time::timeout, +}; + +const ENTITY: usize = 64 * 1024; +const WAIT: Duration = Duration::from_secs(20); +const SETUP: Duration = Duration::from_secs(1); +const HTTP_HEAD_LIMIT: usize = 4096; +const REQUEST_LIMIT: usize = 512; +const UUID_BYTES: [u8; 16] = [7; 16]; +const HOST: &str = "cover.memory.invalid"; +const PATH: &str = "/memory-cover"; +const CIPHERS: [BodyCipher; 4] = [ + BodyCipher::Auto, + BodyCipher::None, + BodyCipher::Aes128Gcm, + BodyCipher::Chacha20Poly1305, +]; + +fn invalid(stage: &'static str) -> io::Error { + io::Error::new(io::ErrorKind::InvalidData, stage) +} +fn require(value: bool, stage: &'static str) -> io::Result<()> { + if value { Ok(()) } else { Err(invalid(stage)) } +} +fn stage(name: &'static str, result: io::Result) -> io::Result { + result.map_err(|error| io::Error::new(error.kind(), name)) +} +fn pending(value: Poll>, name: &'static str) -> io::Result<()> { + match value { + Poll::Pending => Ok(()), + Poll::Ready(Err(error)) => Err(error), + _ => Err(invalid(name)), + } +} +#[derive(Default, Debug)] +struct Counts { + opens: AtomicUsize, + requests: AtomicUsize, + targets: AtomicUsize, + responses: AtomicUsize, + auth_failures: AtomicUsize, + client_drops: AtomicUsize, + peer_drops: AtomicUsize, + client_write_pending: AtomicUsize, + peer_write_pending: AtomicUsize, + client_read_pending: AtomicUsize, + peer_read_pending: AtomicUsize, + partial_writes: AtomicUsize, + short_reads: AtomicUsize, + response_body_started: AtomicBool, +} +struct Raw { + io: DuplexStream, + counts: Arc, + peer: bool, + blocked: Option>, +} +impl Drop for Raw { + fn drop(&mut self) { + let value = if self.peer { + &self.counts.peer_drops + } else { + &self.counts.client_drops + }; + value.fetch_add(1, Ordering::SeqCst); + } +} +impl AsyncRead for Raw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + output: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if output.remaining() == 0 { + return Poll::Ready(Ok(())); + } + let limit = output.remaining().min(7); + let mut limited = ReadBuf::new(output.initialize_unfilled_to(limit)); + match Pin::new(&mut this.io).poll_read(cx, &mut limited) { + Poll::Ready(Ok(())) => { + let amount = limited.filled().len(); + if amount != 0 && amount < output.remaining() { + this.counts.short_reads.fetch_add(1, Ordering::SeqCst); + } + output.advance(amount); + Poll::Ready(Ok(())) + } + Poll::Ready(Err(error)) => Poll::Ready(Err(error)), + Poll::Pending => { + let count = if this.peer { + &this.counts.peer_read_pending + } else { + &this.counts.client_read_pending + }; + count.fetch_add(1, Ordering::SeqCst); + Poll::Pending + } + } + } +} +impl AsyncWrite for Raw { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let this = self.get_mut(); + let result = Pin::new(&mut this.io).poll_write(cx, &bytes[..bytes.len().min(31)]); + match &result { + Poll::Pending => { + let count = if this.peer { + &this.counts.peer_write_pending + } else { + &this.counts.client_write_pending + }; + count.fetch_add(1, Ordering::SeqCst); + if this.peer && this.counts.response_body_started.load(Ordering::SeqCst) { + if let Some(blocked) = this.blocked.take() { + let _ = blocked.send(()); + } + } + } + Poll::Ready(Ok(amount)) if *amount < bytes.len() => { + this.counts.partial_writes.fetch_add(1, Ordering::SeqCst); + } + _ => {} + } + result + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.get_mut().io).poll_shutdown(cx) + } +} +struct MemoryUpstream { + streams: Mutex)>>, + expected: Destination, +} +#[async_trait] +impl OutboundConnector for MemoryUpstream { + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + if session.destination != self.expected { + return Err(DispatchError::NotAllowed); + } + let (io, counts) = self + .streams + .lock() + .unwrap() + .pop_front() + .ok_or(DispatchError::NotAllowed)?; + counts.opens.fetch_add(1, Ordering::SeqCst); + Ok(ConnectedStream { + io, + effective_peer: self.expected.clone(), + }) + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +fn cipher_name(cipher: BodyCipher) -> &'static str { + match cipher { + BodyCipher::Auto => "auto", + BodyCipher::None => "none", + BodyCipher::Aes128Gcm => "aes-128-gcm", + BodyCipher::Chacha20Poly1305 => "chacha20-poly1305", + } +} +fn config(cipher: BodyCipher) -> io::Result { + let source = serde_json::json!({"proxies":[{"name":"cover","type":"vmess","server":"192.0.2.10","port":8443, + "uuid":"07070707-0707-0707-0707-070707070707","cipher":cipher_name(cipher),"network":"http", + "http-opts":{"method":"GET","path":[PATH],"headers":{"Host":[HOST]}}}],"rules":["MATCH,cover"]}); + let mut parsed = Config::parse_yaml(&serde_json::to_vec(&source).unwrap()) + .map_err(|_| invalid("actual VMess Config"))?; + let ProxyProtocol::Vmess(config) = parsed.proxies.remove(0).protocol else { + return Err(invalid("actual VMess type")); + }; + Ok(config) +} +fn session(target: Destination) -> StreamSession { + StreamSession { + metadata: Default::default(), + inbound: InboundKind::InternalMeasure, + source: "127.0.0.1:10000".parse().unwrap(), + destination: target, + sniffed_domain: None, + } +} + +struct Authenticated { + key: [u8; 16], + iv: [u8; 16], + response_key: [u8; 16], + response_iv: [u8; 16], + tag: u8, + options: BodyOptions, +} +fn command_key(uuid: [u8; 16]) -> [u8; 16] { + let mut hash = Md5::new(); + Digest::update(&mut hash, uuid); + Digest::update(&mut hash, b"c48619fe-8f02-49e0-b9e9-edf763e17e21"); + hash.finalize().into() +} +fn request_authenticate( + mut wire: Vec, + expected: &Destination, + cipher: BodyCipher, + uuid: [u8; 16], +) -> io::Result { + require( + (42 + 16..=REQUEST_LIMIT).contains(&wire.len()), + "bounded VMess request", + )?; + let auth: [u8; 16] = wire[..16].try_into().unwrap(); + let nonce: [u8; 8] = wire[34..42].try_into().unwrap(); + let command = command_key(uuid); + let auth_key = kdf(&command, &[b"AES Auth ID Encryption"]); + let mut decoded = auth; + aes::Aes128::new_from_slice(&auth_key[..16]) + .map_err(|_| invalid("AuthID key"))? + .decrypt_block((&mut decoded).into()); + let timestamp = u64::from_be_bytes(decoded[..8].try_into().unwrap()); + let now = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_err(|_| invalid("test clock"))? + .as_secs(); + require( + timestamp.abs_diff(now) <= 120 + && u32::from_be_bytes(decoded[12..].try_into().unwrap()) + == crc32fast::hash(&decoded[..12]), + "actual AuthID CRC/time", + )?; + let length_key = kdf(&command, &[b"VMess Header AEAD Key_Length", &auth, &nonce]); + let length_iv = kdf( + &command, + &[b"VMess Header AEAD Nonce_Length", &auth, &nonce], + ); + let length = open( + &aead_key(BodyCipher::Aes128Gcm, length_key[..16].try_into().unwrap()), + length_iv[..12].try_into().unwrap(), + &auth, + &mut wire[16..34], + )?; + require(length.len() == 2, "actual request length")?; + let length = usize::from(u16::from_be_bytes(length.try_into().unwrap())); + require( + (42..=320).contains(&length) && wire.len() == 42 + length + 16, + "exact initial VMess prefix", + )?; + let payload_key = kdf(&command, &[b"VMess Header AEAD Key", &auth, &nonce]); + let payload_iv = kdf(&command, &[b"VMess Header AEAD Nonce", &auth, &nonce]); + let plain = open( + &aead_key(BodyCipher::Aes128Gcm, payload_key[..16].try_into().unwrap()), + payload_iv[..12].try_into().unwrap(), + &auth, + &mut wire[42..], + )?; + require( + plain.len() == length && plain[0] == 1 && plain[36] == 0 && plain[37] == 1, + "actual TCP request fields", + )?; + let options = BodyOptions::new(cipher, false, false)?; + require( + plain[34] == options.wire(Command::Tcp) && plain[35] & 15 == cipher.resolved().wire(), + "actual body cipher/options", + )?; + let padding = usize::from(plain[35] >> 4); + let end = plain + .len() + .checked_sub(4 + padding) + .ok_or_else(|| invalid("request padding"))?; + require(end >= 38, "request target length")?; + let (target, used) = crate::outbound::address::decode_port_first(&plain[38..end])?; + require( + target == *expected && used == end - 38, + "authenticated actual target", + )?; + let checksum = plain[..plain.len() - 4] + .iter() + .fold(0x811c9dc5u32, |sum, byte| { + (sum ^ u32::from(*byte)).wrapping_mul(0x01000193) + }); + require( + checksum == u32::from_be_bytes(plain[plain.len() - 4..].try_into().unwrap()), + "actual request FNV", + )?; + let key: [u8; 16] = plain[17..33].try_into().unwrap(); + let iv: [u8; 16] = plain[1..17].try_into().unwrap(); + Ok(Authenticated { + key, + iv, + response_key: Sha256::digest(key)[..16].try_into().unwrap(), + response_iv: Sha256::digest(iv)[..16].try_into().unwrap(), + tag: plain[33], + options, + }) +} +#[derive(Clone, Copy)] +enum ResponseMode { + Valid, + BadTag, +} +fn response_prefix(auth: &Authenticated, mode: ResponseMode) -> io::Result { + let mut bytes = b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n\r\n".to_vec(); + for (mut data, key_salt, iv_salt) in [ + ( + 4u16.to_be_bytes().to_vec(), + b"AEAD Resp Header Len Key".as_slice(), + b"AEAD Resp Header Len IV".as_slice(), + ), + ( + vec![auth.tag, 0, 0, 0], + b"AEAD Resp Header Key".as_slice(), + b"AEAD Resp Header IV".as_slice(), + ), + ] { + let key = kdf(&auth.response_key, &[key_salt]); + let iv = kdf(&auth.response_iv, &[iv_salt]); + seal( + &aead_key(BodyCipher::Aes128Gcm, key[..16].try_into().unwrap()), + iv[..12].try_into().unwrap(), + &[], + &mut data, + )?; + bytes.extend_from_slice(&data); + } + if matches!(mode, ResponseMode::BadTag) { + *bytes.last_mut().unwrap() ^= 1; + } + Ok(bytes.into()) +} +async fn accept_request( + mut raw: Raw, + target: Destination, + cipher: BodyCipher, + uuid: [u8; 16], + mode: ResponseMode, +) -> io::Result { + let mut head = Vec::new(); + while !head.ends_with(b"\r\n\r\n") { + require(head.len() < HTTP_HEAD_LIMIT, "bounded cover head")?; + let mut byte = [0]; + stage("cover head read", raw.read_exact(&mut byte).await)?; + head.push(byte[0]); + } + let mut headers = [httparse::EMPTY_HEADER; 32]; + let mut parsed = httparse::Request::new(&mut headers); + require( + matches!(parsed.parse(&head).map_err(|_| invalid("cover parse"))?, httparse::Status::Complete(length) if length == head.len()) + && parsed.method == Some("GET") + && parsed.path == Some(PATH) + && parsed.version == Some(1), + "actual fixed cover", + )?; + let mut length = None; + let mut hosts = 0; + for header in parsed.headers.iter() { + if header.name.eq_ignore_ascii_case("host") { + hosts += 1; + require(header.value == HOST.as_bytes(), "cover Host")?; + } + if header.name.eq_ignore_ascii_case("content-length") { + require( + length.is_none() + && !header.value.is_empty() + && header.value.iter().all(u8::is_ascii_digit), + "single cover Content-Length", + )?; + length = Some( + std::str::from_utf8(header.value) + .map_err(|_| invalid("cover length"))? + .parse::() + .map_err(|_| invalid("cover length"))?, + ); + } + require( + !header.name.eq_ignore_ascii_case("transfer-encoding"), + "cover has no transfer coding", + )?; + } + let length = length.ok_or_else(|| invalid("cover length missing"))?; + require( + hosts == 1 && (58..=REQUEST_LIMIT).contains(&length), + "cover prefix bound", + )?; + raw.counts.requests.fetch_add(1, Ordering::SeqCst); + let mut wire = vec![0; length]; + stage("cover initial body", raw.read_exact(&mut wire).await)?; + let auth = match request_authenticate(wire, &target, cipher, uuid) { + Ok(auth) => auth, + Err(error) => { + raw.counts.auth_failures.fetch_add(1, Ordering::SeqCst); + return Err(error); + } + }; + raw.counts.targets.fetch_add(1, Ordering::SeqCst); + Peer::new(raw, auth, mode) +} + +struct Peer { + raw: Raw, + read: BodyCodec, + write: BodyCodec, + input: BytesMut, + expected: Option<(usize, usize)>, + plain: Bytes, + prefix: Bytes, + output: Bytes, + started: bool, + response_counted: bool, + eof: bool, + shutdown_queued: bool, +} +impl Peer { + fn new(raw: Raw, auth: Authenticated, mode: ResponseMode) -> io::Result { + let prefix = response_prefix(&auth, mode)?; + Ok(Self { + raw, + read: BodyCodec::new( + auth.options, + Command::Tcp, + &auth.key, + auth.iv, + &auth.key, + auth.iv, + ), + write: BodyCodec::new( + auth.options, + Command::Tcp, + &auth.response_key, + auth.response_iv, + &auth.key, + auth.iv, + ), + input: BytesMut::new(), + expected: None, + plain: Bytes::new(), + prefix, + output: Bytes::new(), + started: false, + response_counted: false, + eof: false, + shutdown_queued: false, + }) + } + fn fill( + &mut self, + wanted: usize, + budget: &mut usize, + cx: &mut Context<'_>, + ) -> Poll> { + while self.input.len() < wanted { + if *budget == 0 { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + *budget -= 1; + let mut scratch = [0; 512]; + let amount = (wanted - self.input.len()).min(scratch.len()); + let mut buffer = ReadBuf::new(&mut scratch[..amount]); + ready!(Pin::new(&mut self.raw).poll_read(cx, &mut buffer))?; + if buffer.filled().is_empty() { + return Poll::Ready(Ok(false)); + } + self.input.extend_from_slice(buffer.filled()); + } + Poll::Ready(Ok(true)) + } + fn drain(&mut self, cx: &mut Context<'_>) -> Poll> { + let mut budget = crate::limits::IO_POLL_BUDGET; + if self.started { + ready!(drain_wire(&mut self.raw, &mut self.prefix, &mut budget, cx))?; + if !self.response_counted { + self.raw.counts.responses.fetch_add(1, Ordering::SeqCst); + self.raw + .counts + .response_body_started + .store(true, Ordering::SeqCst); + self.response_counted = true; + } + } + drain_wire(&mut self.raw, &mut self.output, &mut budget, cx) + } +} +fn drain_wire( + raw: &mut Raw, + wire: &mut Bytes, + budget: &mut usize, + cx: &mut Context<'_>, +) -> Poll> { + while !wire.is_empty() { + if *budget == 0 { + cx.waker().wake_by_ref(); + return Poll::Pending; + } + *budget -= 1; + let amount = ready!(Pin::new(&mut *raw).poll_write(cx, wire))?; + if amount == 0 { + return Poll::Ready(Err(io::ErrorKind::WriteZero.into())); + } + wire.advance(amount); + } + Poll::Ready(Ok(())) +} +impl AsyncRead for Peer { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + output: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + if output.remaining() == 0 || this.eof { + return Poll::Ready(Ok(())); + } + if !this.read.framed { + return Pin::new(&mut this.raw).poll_read(cx, output); + } + let mut budget = crate::limits::IO_POLL_BUDGET; + loop { + if !this.plain.is_empty() { + let amount = this.plain.len().min(output.remaining()); + output.put_slice(&this.plain.split_to(amount)); + return Poll::Ready(Ok(())); + } + if this.expected.is_none() { + if !ready!(this.fill(this.read.length_size(), &mut budget, cx))? { + if !this.input.is_empty() { + return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); + } + this.eof = true; + return Poll::Ready(Ok(())); + } + let mut header = this.input.split_to(this.read.length_size()); + this.expected = Some(this.read.decode_length(&mut header)?); + } + let (length, padding) = this.expected.unwrap(); + if !ready!(this.fill(length, &mut budget, cx))? { + return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); + } + this.plain = this + .read + .decode_body(this.input.split_to(length), padding)?; + this.expected = None; + if this.plain.is_empty() { + this.eof = true; + return Poll::Ready(Ok(())); + } + } + } +} +impl AsyncWrite for Peer { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let this = self.get_mut(); + if this.shutdown_queued { + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + } + if bytes.is_empty() { + return Poll::Ready(Ok(0)); + } + this.started = true; + ready!(this.drain(cx))?; + let amount = bytes.len().min(WRITE_CHUNK); + this.output = this.write.encode(&bytes[..amount])?; + Poll::Ready(Ok(amount)) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + ready!(this.drain(cx))?; + Pin::new(&mut this.raw).poll_flush(cx) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + ready!(this.drain(cx))?; + if !this.shutdown_queued { + this.shutdown_queued = true; + if this.started && this.write.framed { + this.output = this.write.encode(&[])?; + } + } + ready!(this.drain(cx))?; + Pin::new(&mut this.raw).poll_shutdown(cx) + } +} +struct Guard { + node: Arc, + counts: Vec>, + waited: AtomicBool, +} +impl Guard { + fn begin_shutdown(&self) { + OutboundConnector::begin_shutdown(self.node.as_ref()); + } + async fn shutdown(&self) { + OutboundConnector::shutdown(self.node.as_ref()).await; + self.waited.store(true, Ordering::SeqCst); + } + fn receipt(&self) -> MemoryVmessHttpCoverReceipt { + let (cancelled, closed, empty) = self.node.http_cover_test_lifecycle(); + let mut r = MemoryVmessHttpCoverReceipt { + owners: 1, + owner_cancelled: usize::from(cancelled), + owner_closed: usize::from(closed), + owner_tasks_empty: usize::from(empty), + owner_wait_returned: usize::from(self.waited.load(Ordering::SeqCst)), + ..Default::default() + }; + for c in &self.counts { + r.opens += c.opens.load(Ordering::SeqCst); + r.target_handshakes += c.targets.load(Ordering::SeqCst); + r.cover_requests += c.requests.load(Ordering::SeqCst); + r.cover_responses += c.responses.load(Ordering::SeqCst); + r.client_drops += c.client_drops.load(Ordering::SeqCst); + r.peer_drops += c.peer_drops.load(Ordering::SeqCst); + r.auth_failures += c.auth_failures.load(Ordering::SeqCst); + r.client_write_pending += c.client_write_pending.load(Ordering::SeqCst); + r.peer_write_pending += c.peer_write_pending.load(Ordering::SeqCst); + r.client_read_pending += c.client_read_pending.load(Ordering::SeqCst); + r.peer_read_pending += c.peer_read_pending.load(Ordering::SeqCst); + r.partial_writes += c.partial_writes.load(Ordering::SeqCst); + r.short_reads += c.short_reads.load(Ordering::SeqCst); + } + r + } +} +impl Drop for Guard { + fn drop(&mut self) { + self.begin_shutdown(); + } +} +struct NodeFixture { + guard: Arc, + peers: Vec<(Raw, oneshot::Receiver<()>)>, +} +fn node_fixture(cipher: BodyCipher, capacity: usize, count: usize) -> io::Result { + require( + capacity >= 1 && (1..=2).contains(&count), + "finite memory fixture", + )?; + let mut streams = VecDeque::new(); + let mut peers = Vec::new(); + let mut counters = Vec::new(); + for _ in 0..count { + let counts = Arc::new(Counts::default()); + let (client, peer) = tokio::io::duplex(capacity); + let (blocked, signal) = oneshot::channel(); + streams.push_back(( + Box::new(Raw { + io: client, + counts: counts.clone(), + peer: false, + blocked: None, + }) as BoxStream, + counts.clone(), + )); + peers.push(( + Raw { + io: peer, + counts: counts.clone(), + peer: true, + blocked: Some(blocked), + }, + signal, + )); + counters.push(counts); + } + let upstream = Arc::new(MemoryUpstream { + streams: Mutex::new(streams), + expected: Destination::Ip("192.0.2.10:8443".parse().unwrap()), + }); + let node = Arc::new(super::super::VmessOutbound::new_with_path( + &config(cipher)?, + UpstreamPath::proxy(upstream), + )?); + Ok(NodeFixture { + guard: Arc::new(Guard { + node, + counts: counters, + waited: AtomicBool::new(false), + }), + peers, + }) +} +async fn open_wire( + guard: &Guard, + raw: Raw, + target: Destination, + cipher: BodyCipher, + uuid: [u8; 16], + mode: ResponseMode, +) -> io::Result<(BoxStream, Peer)> { + let context = EstablishContext::with_timeout(SETUP); + let client_target = target.clone(); + let client = async { + guard + .node + .connect_stream(session(client_target), &context) + .await + .map(|connected| connected.io) + .map_err(|_| invalid("actual VMess connect_stream")) + }; + // Both halves are inline, and each owns its exact IO. No peer task is spawned. + tokio::try_join!(client, accept_request(raw, target, cipher, uuid, mode)) +} + +pub(crate) type MemoryVmessAcceptedPeer = + Pin> + Send + 'static>>; +#[derive(Debug, Default)] +pub(crate) struct MemoryVmessHttpCoverReceipt { + pub(crate) owners: usize, + pub(crate) opens: usize, + pub(crate) target_handshakes: usize, + pub(crate) cover_requests: usize, + pub(crate) cover_responses: usize, + pub(crate) client_drops: usize, + pub(crate) peer_drops: usize, + pub(crate) owner_cancelled: usize, + pub(crate) owner_closed: usize, + pub(crate) owner_wait_returned: usize, + pub(crate) owner_tasks_empty: usize, + pub(crate) auth_failures: usize, + pub(crate) client_write_pending: usize, + pub(crate) peer_write_pending: usize, + pub(crate) client_read_pending: usize, + pub(crate) peer_read_pending: usize, + pub(crate) partial_writes: usize, + pub(crate) short_reads: usize, +} +pub(crate) struct MemoryVmessHttpCoverFactory { + cipher: BodyCipher, + capacity: usize, + guards: Mutex>>, +} +impl MemoryVmessHttpCoverFactory { + pub(crate) fn new(cipher: BodyCipher, capacity: usize) -> Arc { + Arc::new(Self { + cipher, + capacity, + guards: Mutex::new(Vec::new()), + }) + } + pub(crate) async fn open( + &self, + target: Destination, + ) -> io::Result<(BoxStream, crate::outbound::MemoryVmessAcceptedPeer)> { + let mut fixture = node_fixture(self.cipher, self.capacity, 1)?; + let (raw, blocked) = fixture.peers.remove(0); + // Register before any await, so parent timeout/cancellation still has + // this real node available for the later explicit shutdown barrier. + self.guards + .lock() + .unwrap_or_else(|error| error.into_inner()) + .push(fixture.guard.clone()); + let opened = open_wire( + &fixture.guard, + raw, + target, + self.cipher, + UUID_BYTES, + ResponseMode::Valid, + ) + .await; + drop(blocked); + match opened { + Ok((client, peer)) => Ok(( + client, + Box::pin(async move { Ok(Box::new(peer) as BoxStream) }), + )), + Err(error) => { + fixture.guard.shutdown().await; + Err(error) + } + } + } + pub(crate) fn begin_shutdown(&self) { + for guard in self + .guards + .lock() + .unwrap_or_else(|error| error.into_inner()) + .iter() + { + guard.begin_shutdown(); + } + } + pub(crate) async fn shutdown(&self) { + let guards = self + .guards + .lock() + .unwrap_or_else(|error| error.into_inner()) + .clone(); + for guard in &guards { + guard.begin_shutdown(); + } + for guard in guards { + guard.shutdown().await; + } + } + pub(crate) fn snapshot(&self) -> crate::outbound::MemoryVmessHttpCoverReceipt { + let guards = self + .guards + .lock() + .unwrap_or_else(|error| error.into_inner()); + let mut total = MemoryVmessHttpCoverReceipt::default(); + for guard in guards.iter() { + let r = guard.receipt(); + total.owners += r.owners; + total.opens += r.opens; + total.target_handshakes += r.target_handshakes; + total.cover_requests += r.cover_requests; + total.cover_responses += r.cover_responses; + total.client_drops += r.client_drops; + total.peer_drops += r.peer_drops; + total.owner_cancelled += r.owner_cancelled; + total.owner_closed += r.owner_closed; + total.owner_wait_returned += r.owner_wait_returned; + total.owner_tasks_empty += r.owner_tasks_empty; + total.auth_failures += r.auth_failures; + total.client_write_pending += r.client_write_pending; + total.peer_write_pending += r.peer_write_pending; + total.client_read_pending += r.client_read_pending; + total.peer_read_pending += r.peer_read_pending; + total.partial_writes += r.partial_writes; + total.short_reads += r.short_reads; + } + total + } +} + +async fn entity(io: &mut (impl AsyncRead + Unpin), byte: u8) -> io::Result<()> { + let mut data = vec![0; ENTITY]; + stage("complete synthetic entity", io.read_exact(&mut data).await)?; + require( + data.iter().all(|value| *value == byte), + "synthetic entity bytes", + ) +} +async fn exchange( + client: BoxStream, + mut peer: Peer, + blocked: oneshot::Receiver<()>, +) -> io::Result<()> { + let (allow, allowed) = oneshot::channel(); + tokio::try_join!( + async move { + let (mut read, mut write) = tokio::io::split(client); + write.write_all(b"!").await?; + write.flush().await?; + let mut payload = vec![0x31; ENTITY]; + payload.extend_from_slice(&vec![0x32; ENTITY]); + let mut upload = Box::pin(async { + write.write_all(&payload).await?; + write.flush().await + }); + pending( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))).await, + "real upload must remain Pending", + )?; + // Read while awaiting peer backpressure: the lazy response prefix + // can exceed64B, so waiting for a body-only event before reading + // would itself deadlock the valid constructor/response contract. + tokio::try_join!(entity(&mut read, 0x91), async { + blocked + .await + .map_err(|_| invalid("real peer body TX never blocked")) + })?; + pending( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))).await, + "response1 must finish while TX stays Pending", + )?; + let mut second = Box::pin(entity(&mut read, 0x92)); + pending( + poll_fn(|cx| Poll::Ready(second.as_mut().poll(cx))).await, + "response2 must wait for upload", + )?; + allow.send(()).map_err(|_| invalid("upload gate lost"))?; + tokio::try_join!(upload.as_mut(), second.as_mut())?; + drop((upload, second)); + // HTTP transport deliberately whole-closes after the two fully + // received responses; no later half-close read is claimed. + write.shutdown().await?; + Ok::<_, io::Error>(()) + }, + async move { + let mut marker = [0]; + peer.read_exact(&mut marker).await?; + require(marker == [b'!'], "actual initial payload")?; + peer.write_all(&vec![0x91; ENTITY]).await?; + peer.flush().await?; + allowed.await.map_err(|_| invalid("client RX gate lost"))?; + entity(&mut peer, 0x31).await?; + entity(&mut peer, 0x32).await?; + peer.write_all(&vec![0x92; ENTITY]).await?; + peer.flush().await?; + let mut extra = [0]; + require( + peer.read(&mut extra).await? == 0, + "no duplicate upload or target bytes", + )?; + Ok::<_, io::Error>(()) + } + )?; + Ok(()) +} +async fn close_fixture(fixture: NodeFixture) -> MemoryVmessHttpCoverReceipt { + fixture.guard.begin_shutdown(); + fixture.guard.shutdown().await; + let counts = fixture.guard.counts.clone(); + let node_weak = Arc::downgrade(&fixture.guard.node); + let guard_weak = Arc::downgrade(&fixture.guard); + let weak: Vec> = counts.iter().map(Arc::downgrade).collect(); + let expected = counts.len(); + let mut receipt = fixture.guard.receipt(); + drop(fixture); + receipt.client_drops = counts + .iter() + .map(|c| c.client_drops.load(Ordering::SeqCst)) + .sum(); + receipt.peer_drops = counts + .iter() + .map(|c| c.peer_drops.load(Ordering::SeqCst)) + .sum(); + drop(counts); + assert_eq!( + receipt.client_drops, expected, + "actual client IO survived: {receipt:?}" + ); + assert_eq!( + receipt.peer_drops, expected, + "actual peer IO survived: {receipt:?}" + ); + assert!( + weak.iter().all(|weak| weak.upgrade().is_none()), + "actual wire ownership survived real shutdown/drop" + ); + assert!( + node_weak.upgrade().is_none() && guard_weak.upgrade().is_none(), + "actual node/guard ownership survived shutdown/drop" + ); + assert_eq!( + ( + receipt.owner_cancelled, + receipt.owner_closed, + receipt.owner_wait_returned, + receipt.owner_tasks_empty + ), + (1, 1, 1, 1), + "{receipt:?}" + ); + receipt +} +fn operation_result( + outcome: Result< + Result, tokio::time::error::Elapsed>, + Box, + >, + cipher: BodyCipher, +) -> Result<(), String> { + match outcome { + Ok(Ok(Ok(()))) => Ok(()), + Ok(Ok(Err(error))) => Err(format!( + "{cipher:?}: operation kind={:?}; stage={error}", + error.kind() + )), + Ok(Err(_)) => Err(format!("{cipher:?}: bounded operation deadline")), + Err(_) => Err(format!("{cipher:?}: operation unwind (payload omitted)")), + } +} +#[tokio::test] +async fn vmess_http_cover_wire_auth_four_modes_two_entities_cross_direction() { + let mut results = Vec::new(); + for cipher in CIPHERS { + let mut fixture = node_fixture(cipher, 64, 1).unwrap(); + let (raw, blocked) = fixture.peers.remove(0); + let outcome = AssertUnwindSafe(timeout(WAIT, async { + let target = Destination::domain("body.memory.invalid", 443).unwrap(); + let (client, peer) = open_wire( + &fixture.guard, + raw, + target, + cipher, + UUID_BYTES, + ResponseMode::Valid, + ) + .await?; + exchange(client, peer, blocked).await + })) + .catch_unwind() + .await; + // The operation future owns both endpoints and is gone on every path. + // Cleanup/Weak proof always precedes desired result classification. + let receipt = close_fixture(fixture).await; + let mut result = operation_result(outcome, cipher); + if result.is_ok() + && !(receipt.opens == 1 + && receipt.target_handshakes == 1 + && receipt.cover_requests == 1 + && receipt.cover_responses == 1 + && receipt.auth_failures == 0 + && receipt.client_write_pending > 0 + && receipt.peer_write_pending > 0 + && receipt.client_read_pending > 0 + && receipt.peer_read_pending > 0 + && receipt.partial_writes > 0 + && receipt.short_reads > 0) + { + result = Err(format!( + "{cipher:?}: actual authentication/readiness receipt {receipt:?}" + )); + } + results.push(result); + } + let errors: Vec<_> = results.into_iter().filter_map(Result::err).collect(); + assert!( + errors.is_empty(), + "all four real wire-auth cases: {errors:?}" + ); +} + +#[tokio::test] +async fn vmess_http_cover_wire_auth_wrong_uuid_rejects_after_real_request() { + let mut results = Vec::new(); + for cipher in CIPHERS { + let mut fixture = node_fixture(cipher, 64, 1).unwrap(); + let (raw, blocked) = fixture.peers.remove(0); + drop(blocked); + let outcome = AssertUnwindSafe(timeout(WAIT, async { + let target = Destination::domain("body.memory.invalid", 443).unwrap(); + match open_wire( + &fixture.guard, + raw, + target, + cipher, + [8; 16], + ResponseMode::Valid, + ) + .await + { + Err(error) if error.kind() == io::ErrorKind::InvalidData => Ok(()), + Err(error) => Err(io::Error::new( + error.kind(), + "wrong UUID failed outside authenticated request", + )), + Ok((client, peer)) => { + drop((client, peer)); + Err(invalid("wrong UUID was authenticated")) + } + } + })) + .catch_unwind() + .await; + let receipt = close_fixture(fixture).await; + let mut result = operation_result(outcome, cipher); + if result.is_ok() + && !(receipt.opens == 1 + && receipt.cover_requests == 1 + && receipt.target_handshakes == 0 + && receipt.cover_responses == 0 + && receipt.auth_failures == 1) + { + result = Err(format!("{cipher:?}: wrong UUID receipt {receipt:?}")); + } + results.push(result); + } + let errors: Vec<_> = results.into_iter().filter_map(Result::err).collect(); + assert!(errors.is_empty(), "wrong UUID controls: {errors:?}"); +} + +#[tokio::test] +async fn vmess_http_cover_wire_response_tag_rejects_before_plaintext_including_none() { + let mut results = Vec::new(); + for cipher in CIPHERS { + let mut fixture = node_fixture(cipher, 64, 1).unwrap(); + let (raw, blocked) = fixture.peers.remove(0); + drop(blocked); + let outcome = AssertUnwindSafe(timeout(WAIT, async { + let target = Destination::domain("body.memory.invalid", 443).unwrap(); + let (mut client, mut peer) = open_wire( + &fixture.guard, + raw, + target, + cipher, + UUID_BYTES, + ResponseMode::BadTag, + ) + .await?; + let (read, write) = tokio::join!( + async { + let mut bytes = [0; 1]; + let mut output = ReadBuf::new(&mut bytes); + let result = + poll_fn(|cx| Pin::new(&mut client).poll_read(cx, &mut output)).await; + require( + output.filled().is_empty(), + "unauthenticated plaintext was delivered", + )?; + match result { + Err(error) if error.kind() == io::ErrorKind::InvalidData => Ok(()), + _ => Err(invalid("response authentication was not rejected")), + } + }, + async { + peer.write_all(b"must-not-deliver").await?; + peer.flush().await + } + ); + read?; + if let Err(error) = write { + require( + matches!( + error.kind(), + io::ErrorKind::BrokenPipe | io::ErrorKind::ConnectionReset + ), + "unexpected peer error after client auth rejection", + )?; + } + Ok::<_, io::Error>(()) + })) + .catch_unwind() + .await; + let receipt = close_fixture(fixture).await; + let mut result = operation_result(outcome, cipher); + if result.is_ok() + && !(receipt.opens == 1 + && receipt.target_handshakes == 1 + && receipt.cover_requests == 1 + && receipt.cover_responses == 1 + && receipt.auth_failures == 0) + { + result = Err(format!( + "{cipher:?}: response authentication receipt {receipt:?}" + )); + } + results.push(result); + } + let errors: Vec<_> = results.into_iter().filter_map(Result::err).collect(); + assert!( + errors.is_empty(), + "response authentication controls: {errors:?}" + ); +} + +#[tokio::test] +async fn vmess_http_cover_wire_child_drop_preserves_authenticated_sibling_until_stop() { + let mut results = Vec::new(); + for cipher in CIPHERS { + let mut fixture = node_fixture(cipher, 64, 2).unwrap(); + let (raw_one, signal_one) = fixture.peers.remove(0); + let (raw_two, signal_two) = fixture.peers.remove(0); + drop((signal_one, signal_two)); + let outcome = AssertUnwindSafe(timeout(WAIT, async { + let target = Destination::domain("sibling.memory.invalid", 443).unwrap(); + let (first, first_peer) = open_wire(&fixture.guard, raw_one, target.clone(), cipher, UUID_BYTES, ResponseMode::Valid).await?; + let (mut second, mut second_peer) = open_wire(&fixture.guard, raw_two, target, cipher, UUID_BYTES, ResponseMode::Valid).await?; + drop((first, first_peer)); + require(!fixture.guard.node.http_cover_test_lifecycle().0, "single child Drop cancelled actual parent")?; + tokio::try_join!( + async { second.write_all(b"sibling").await?; second.flush().await }, + async { let mut marker = [0; 7]; second_peer.read_exact(&mut marker).await?; require(marker.as_slice() == b"sibling", "live sibling payload") } + )?; + let payload = vec![0x41; ENTITY]; + let (mut read, mut write) = tokio::io::split(second); + let mut upload = Box::pin(async { write.write_all(&payload).await?; write.flush().await }); + pending(poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))).await, "live sibling TX must really be Pending")?; + let mut storage = [0; 1]; + let mut output = ReadBuf::new(&mut storage); + pending(poll_fn(|cx| Poll::Ready(Pin::new(&mut read).poll_read(cx, &mut output))).await, "live sibling RX must really be Pending")?; + fixture.guard.begin_shutdown(); + // Actual cancellation errors, followed by real IO Drop, not a + // Boolean stop receipt or a synthetic readiness event. + let read_result = poll_fn(|cx| Pin::new(&mut read).poll_read(cx, &mut output)).await; + drop(upload); + let write_result = write.write_all(b"forbidden").await; + require(matches!(read_result, Err(ref error) if error.kind() == io::ErrorKind::ConnectionAborted) + && matches!(write_result, Err(ref error) if error.kind() == io::ErrorKind::ConnectionAborted) + && output.filled().is_empty(), "real sibling Stop did not revoke IO")?; + drop((read, write, second_peer)); + Ok::<_, io::Error>(()) + })).catch_unwind().await; + let receipt = close_fixture(fixture).await; + let mut result = operation_result(outcome, cipher); + if result.is_ok() + && !(receipt.opens == 2 + && receipt.target_handshakes == 2 + && receipt.cover_requests == 2 + && receipt.cover_responses == 0 + && receipt.auth_failures == 0) + { + result = Err(format!("{cipher:?}: sibling receipt {receipt:?}")); + } + results.push(result); + } + let errors: Vec<_> = results.into_iter().filter_map(Result::err).collect(); + assert!( + errors.is_empty(), + "same-node authenticated sibling controls: {errors:?}" + ); +} + +// Interactive HTTP-cover progress controls. These are intentionally separate +// from the full entity tests: no application write follows the one-byte tail. +#[derive(Clone, Copy, Debug)] +enum InteractiveCase { + ExplicitFlush, + NoFlushThenRead, + ReadFirstExplicitFlush, + ReadFirstNoFlush, + ReadyReadWithPendingFlush, +} +async fn close_interactive_factory( + factory: Arc, +) -> MemoryVmessHttpCoverReceipt { + factory.begin_shutdown(); + factory.shutdown().await; + let (guards, nodes, counts) = { + let registry = factory + .guards + .lock() + .unwrap_or_else(|error| error.into_inner()); + ( + registry.iter().map(Arc::downgrade).collect::>(), + registry + .iter() + .map(|guard| Arc::downgrade(&guard.node)) + .collect::>(), + registry + .iter() + .flat_map(|guard| guard.counts.iter().cloned()) + .collect::>(), + ) + }; + let wires: Vec<_> = counts.iter().map(Arc::downgrade).collect(); + let owner = Arc::downgrade(&factory); + let mut receipt = factory.snapshot(); + drop(factory); + // Failed setup may leave an unused queue entry until its actual node is + // dropped. Read the final drop counters only after that ownership release. + receipt.client_drops = counts + .iter() + .map(|count| count.client_drops.load(Ordering::SeqCst)) + .sum(); + receipt.peer_drops = counts + .iter() + .map(|count| count.peer_drops.load(Ordering::SeqCst)) + .sum(); + drop(counts); + assert!( + owner.upgrade().is_none(), + "interactive factory owner survived" + ); + assert!( + guards.iter().all(|weak| weak.upgrade().is_none()), + "interactive guard survived" + ); + assert!( + nodes.iter().all(|weak| weak.upgrade().is_none()), + "interactive node survived" + ); + assert!( + wires.iter().all(|weak| weak.upgrade().is_none()), + "interactive wire survived" + ); + assert_eq!(receipt.client_drops, receipt.owners, "{receipt:?}"); + assert_eq!(receipt.peer_drops, receipt.owners, "{receipt:?}"); + assert_eq!(receipt.owner_cancelled, receipt.owners, "{receipt:?}"); + assert_eq!(receipt.owner_closed, receipt.owners, "{receipt:?}"); + assert_eq!(receipt.owner_wait_returned, receipt.owners, "{receipt:?}"); + assert_eq!(receipt.owner_tasks_empty, receipt.owners, "{receipt:?}"); + receipt +} +async fn interactive_case(cipher: BodyCipher, case: InteractiveCase) -> Result<(), String> { + let factory = MemoryVmessHttpCoverFactory::new(cipher, 64); + let outcome = AssertUnwindSafe(timeout(WAIT, async { + let (mut client, accept) = factory + .open(Destination::domain("interactive.memory.invalid", 443).unwrap()) + .await?; + let mut peer = accept.await?; + match case { + InteractiveCase::ExplicitFlush | InteractiveCase::NoFlushThenRead => { + tokio::try_join!( + async { + client.write_all(b"x").await?; + if matches!(case, InteractiveCase::ExplicitFlush) { + client.flush().await?; + } + let mut reply = [0; 1]; + client.read_exact(&mut reply).await?; + require(reply == [b'y'], "one-byte actual response differs") + }, + async { + let mut request = [0; 1]; + peer.read_exact(&mut request).await?; + require( + request == [b'x'], + "peer did not decode the accepted one-byte request", + )?; + peer.write_all(b"y").await?; + peer.flush().await + } + )?; + } + InteractiveCase::ReadFirstExplicitFlush | InteractiveCase::ReadFirstNoFlush => { + let (mut read, mut write) = tokio::io::split(client); + // The source stays genuinely open without supplying another + // byte. No EOF, timer, synthetic wake or second write can drive + // the response future after the accepted one-byte tail. + let (source_open, mut source) = tokio::io::duplex(1); + let raw_reads_before = factory.snapshot().client_read_pending; + let read_was_pending = AtomicBool::new(false); + let upload_accepted = AtomicBool::new(false); + let source_was_pending = AtomicBool::new(false); + tokio::try_join!( + async { + let mut reply = [0; 1]; + let mut read_reply = Box::pin(read.read_exact(&mut reply)); + let mut reading = Box::pin(poll_fn(|cx| { + let result = read_reply.as_mut().poll(cx); + if result.is_pending() { + read_was_pending.store(true, Ordering::SeqCst); + } + result + })); + let mut uploading = Box::pin(async { + require( + read_was_pending.load(Ordering::SeqCst) + && factory.snapshot().client_read_pending > raw_reads_before, + "read-first response did not really become Pending at raw IO before TX", + )?; + stage("read-first client write", write.write_all(b"x").await)?; + upload_accepted.store(true, Ordering::SeqCst); + if matches!(case, InteractiveCase::ReadFirstExplicitFlush) { + stage("read-first explicit flush", write.flush().await)?; + } + let mut remaining = [0; 1]; + let mut source_read = Box::pin(source.read_exact(&mut remaining)); + poll_fn(|cx| { + let result = source_read.as_mut().poll(cx); + if result.is_pending() { + source_was_pending.store(true, Ordering::SeqCst); + } + result + }) + .await?; + Err::<(), _>(invalid("read-first source unexpectedly supplied more bytes")) + }); + // Match the H1 pump: response polling precedes upload + // polling in this same parent. Do not write first and + // then directly await a freshly polled response. + let result = tokio::select! { + biased; + result = &mut reading => result.map(|_| ()), + result = &mut uploading => result, + }; + drop(uploading); + drop(reading); + drop(read_reply); + // Retain the real source writer across the whole wait. + drop(source_open); + stage("read-first client response", result)?; + require( + read_was_pending.load(Ordering::SeqCst) + && upload_accepted.load(Ordering::SeqCst) + && source_was_pending.load(Ordering::SeqCst), + "read-first response bypassed the blocked real upload source", + )?; + require(reply == [b'y'], "read-first actual response differs") + }, + async { + let mut request = [0; 1]; + stage("read-first peer request", peer.read_exact(&mut request).await)?; + require(request == [b'x'], "read-first peer did not decode the accepted tail")?; + stage("read-first peer response", peer.write_all(b"y").await)?; + stage("read-first peer flush", peer.flush().await) + } + )?; + } + InteractiveCase::ReadyReadWithPendingFlush => { + tokio::try_join!( + async { + client.write_all(b"x").await?; + client.flush().await?; + let mut first = [0; 1]; + client.read_exact(&mut first).await?; + require(first == [b'a'], "ready-RX setup marker differs") + }, + async { + let mut request = [0; 1]; + peer.read_exact(&mut request).await?; + require(request == [b'x'], "ready-RX peer request differs")?; + // A single real response record contains a+y. Reading + // only a leaves y decoded or already physically ready. + peer.write_all(b"ay").await?; + peer.flush().await + } + )?; + let (mut read, mut write) = tokio::io::split(client); + let payload = vec![0x51; WRITE_CHUNK]; + let accepted = + poll_fn(|cx| Poll::Ready(Pin::new(&mut write).poll_write(cx, &payload))).await; + require( + matches!(accepted, Poll::Ready(Ok(amount)) if amount == payload.len()), + "ready-RX TX chunk was not accepted", + )?; + let before = factory.snapshot().client_write_pending; + let mut flushing = Box::pin(write.flush()); + pending( + poll_fn(|cx| Poll::Ready(flushing.as_mut().poll(cx))).await, + "real TX flush must be Pending", + )?; + require( + factory.snapshot().client_write_pending > before, + "TX Pending never reached actual raw IO", + )?; + let mut reply = [0; 1]; + let mut output = ReadBuf::new(&mut reply); + let ready = + poll_fn(|cx| Poll::Ready(Pin::new(&mut read).poll_read(cx, &mut output))).await; + require( + matches!(ready, Poll::Ready(Ok(()))) && output.filled() == b"y", + "ready RX was blocked by pending TX flush", + )?; + pending( + poll_fn(|cx| Poll::Ready(flushing.as_mut().poll(cx))).await, + "RX must not silently complete the withheld upload", + )?; + drop(flushing); + drop((read, write)); + } + } + Ok::<_, io::Error>(()) + })) + .catch_unwind() + .await; + // Every completed/error/timeout/unwind future releases both endpoints + // before the real node/guard/raw Weak cleanup and the desired verdict. + let receipt = close_interactive_factory(factory).await; + let result = operation_result(outcome, cipher); + if let Err(error) = result { + return Err(format!("{case:?}: {error}; actual receipt={receipt:?}")); + } + if !(receipt.owners == 1 + && receipt.opens == 1 + && receipt.target_handshakes == 1 + && receipt.cover_requests == 1 + && receipt.cover_responses == 1 + && receipt.auth_failures == 0) + { + return Err(format!( + "{cipher:?}/{case:?}: actual authenticated path missing: {receipt:?}" + )); + } + Ok(()) +} + +#[tokio::test] +async fn vmess_http_cover_one_byte_explicit_flush_and_ready_rx_controls() { + let mut failures = Vec::new(); + for cipher in CIPHERS { + for case in [ + InteractiveCase::ExplicitFlush, + InteractiveCase::ReadyReadWithPendingFlush, + ] { + if let Err(error) = interactive_case(cipher, case).await { + failures.push(error); + } + } + } + assert!( + failures.is_empty(), + "interactive explicit-flush/RX-priority controls after cleanup: {failures:?}" + ); +} + +#[tokio::test] +async fn vmess_http_cover_one_byte_read_drives_accepted_write_without_flush() { + let mut failures = Vec::new(); + for cipher in CIPHERS { + if let Err(error) = interactive_case(cipher, InteractiveCase::NoFlushThenRead).await { + failures.push(error); + } + } + assert!( + failures.is_empty(), + "one-byte no-flush progress after cleanup: {failures:?}" + ); +} + +#[tokio::test] +async fn vmess_http_cover_read_first_explicit_flush_reaches_peer_after_pending_read() { + let mut failures = Vec::new(); + for cipher in CIPHERS { + if let Err(error) = interactive_case(cipher, InteractiveCase::ReadFirstExplicitFlush).await + { + failures.push(error); + } + } + assert!( + failures.is_empty(), + "read-first explicit-flush controls after cleanup: {failures:?}" + ); +} + +#[tokio::test] +async fn vmess_http_cover_read_first_accepted_write_reawakens_pending_response() { + let mut failures = Vec::new(); + for cipher in CIPHERS { + if let Err(error) = interactive_case(cipher, InteractiveCase::ReadFirstNoFlush).await { + failures.push(error); + } + } + assert!( + failures.is_empty(), + "read-first no-flush progress after cleanup: {failures:?}" + ); +} diff --git a/src/outbound/vmess/http_cover_reuse_owner.rs b/src/outbound/vmess/http_cover_reuse_owner.rs new file mode 100644 index 0000000..d06e8c1 --- /dev/null +++ b/src/outbound/vmess/http_cover_reuse_owner.rs @@ -0,0 +1,120 @@ +//! Complete VMess HTTP-cover ownership; keep independent caller wake slots. +use crate::{dispatch::BoxStream, outbound::owned_stream::OwnedStream}; +use futures_util::task::AtomicWaker; +use std::{ + io, + pin::Pin, + sync::Arc, + task::{Context, Poll, Wake, Waker}, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +use tokio_util::sync::CancellationToken; + +// The stable proxy is the only wake stored by the existing inner cancellation +// future and IO. It does not own the stream, cancellation token or a task. +struct Callers { + reader: AtomicWaker, + writer: AtomicWaker, +} +impl Callers { + fn wake_all(&self) { + self.reader.wake(); + self.writer.wake(); + } +} +impl Wake for Callers { + fn wake(self: Arc) { + self.wake_all(); + } + fn wake_by_ref(self: &Arc) { + self.wake_all(); + } +} + +pub(super) struct HttpCoverReuseOwner { + inner: OwnedStream, + callers: Arc, +} +impl HttpCoverReuseOwner { + pub(super) fn new(stream: BoxStream, child: CancellationToken) -> Self { + Self { + inner: OwnedStream::new(stream, child), + callers: Arc::new(Callers { + reader: AtomicWaker::new(), + writer: AtomicWaker::new(), + }), + } + } + fn poll_io( + &mut self, + cx: &mut Context<'_>, + reading: bool, + operation: impl FnOnce(Pin<&mut OwnedStream>, &mut Context<'_>) -> Poll>, + ) -> Poll> { + let slot = if reading { + &self.callers.reader + } else { + &self.callers.writer + }; + slot.register(cx.waker()); + let proxy = Waker::from(self.callers.clone()); + let result = operation(Pin::new(&mut self.inner), &mut Context::from_waker(&proxy)); + if result.is_ready() { + drop(slot.take()); + } + result + } +} +impl AsyncRead for HttpCoverReuseOwner { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + self.get_mut().poll_io(cx, true, |mut inner, proxy| { + match inner.as_mut().poll_read(proxy, out) { + ready @ Poll::Ready(_) => ready, + Poll::Pending => { + // A partial HTTP upload can wait for its response after + // VMess accepted the last small frame into its output. + // Drive that acknowledged output without holding ready RX + // behind a blocked writer or replacing its caller slot. + match inner.poll_flush(proxy) { + Poll::Ready(Err(error)) => Poll::Ready(Err(error)), + Poll::Ready(Ok(())) | Poll::Pending => Poll::Pending, + } + } + } + }) + } +} +impl AsyncWrite for HttpCoverReuseOwner { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + let this = self.get_mut(); + let result = this.poll_io(cx, false, |inner, proxy| inner.poll_write(proxy, bytes)); + if matches!(&result, Poll::Ready(Ok(amount)) if *amount > 0) { + // The response reader may already be parked while a partial + // upload accepts its final small frame and waits for more input. + // Let that reader drive the acknowledged output on its next poll. + this.callers.reader.wake(); + } + result + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.get_mut() + .poll_io(cx, false, |inner, proxy| inner.poll_flush(proxy)) + } + fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.get_mut() + .poll_io(cx, false, |inner, proxy| inner.poll_shutdown(proxy)) + } +} +impl Drop for HttpCoverReuseOwner { + fn drop(&mut self) { + self.callers.wake_all(); + } +} diff --git a/src/outbound/vmess/http_cover_reuse_owner_memory_tests.rs b/src/outbound/vmess/http_cover_reuse_owner_memory_tests.rs new file mode 100644 index 0000000..b7b776b --- /dev/null +++ b/src/outbound/vmess/http_cover_reuse_owner_memory_tests.rs @@ -0,0 +1,515 @@ +//! Complete VMess/HTTP owner tests over IO-only memory dependencies. +//! The finite HTTP head is not a VMess authenticated response. No peer task, +//! socket, resolver, successful body-auth claim or replacement owner is used. +use super::*; +use crate::{ + config::{Config, ProxyProtocol}, + session::InboundKind, +}; +use futures_util::task::{ArcWake, waker}; +use std::{ + collections::VecDeque, + sync::{ + Weak, + atomic::{AtomicBool, AtomicUsize, Ordering}, + }, + time::Duration, +}; +use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; + +const CIPHERS: [&str; 4] = ["auto", "none", "aes-128-gcm", "chacha20-poly1305"]; + +#[derive(Default)] +struct WakeCount(AtomicUsize); +impl ArcWake for WakeCount { + fn wake_by_ref(owner: &Arc) { + owner.0.fetch_add(1, Ordering::SeqCst); + } +} + +#[derive(Default)] +struct RawReceipt { + reads: AtomicUsize, + writes: AtomicUsize, + flushes: AtomicUsize, + shutdowns: AtomicUsize, + drops: AtomicUsize, + pending_writes: AtomicUsize, + blocked: AtomicBool, + response: Mutex>, + submitted: Mutex>, +} +impl RawReceipt { + fn polls(&self) -> usize { + self.reads.load(Ordering::SeqCst) + + self.writes.load(Ordering::SeqCst) + + self.flushes.load(Ordering::SeqCst) + + self.shutdowns.load(Ordering::SeqCst) + } + fn one_cover(&self) -> bool { + let bytes = self.submitted.lock().unwrap(); + let Some(end) = bytes.windows(4).position(|part| part == b"\r\n\r\n") else { + return false; + }; + let Ok(head) = std::str::from_utf8(&bytes[..end + 4]) else { + return false; + }; + let length = head + .lines() + .find_map(|line| line.strip_prefix("content-length: ")) + .and_then(|value| value.parse::().ok()); + head.starts_with("GET /memory-cover HTTP/1.1\r\n") + && head.contains("host: cover.memory.invalid\r\n") + && length.is_some_and(|length| length > 0 && bytes.len() >= end + 4 + length) + && bytes + .windows(b"GET /memory-cover HTTP/1.1".len()) + .filter(|part| *part == b"GET /memory-cover HTTP/1.1") + .count() + == 1 + } +} +struct Raw { + state: Arc, + read_wait: Option, + write_wait: Option, +} +impl Drop for Raw { + fn drop(&mut self) { + self.state.drops.fetch_add(1, Ordering::SeqCst); + } +} +impl AsyncRead for Raw { + fn poll_read( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + output: &mut ReadBuf<'_>, + ) -> Poll> { + let this = self.get_mut(); + this.state.reads.fetch_add(1, Ordering::SeqCst); + if output.remaining() == 0 { + return Poll::Ready(Ok(())); + } + let mut response = this.state.response.lock().unwrap(); + if response.is_empty() { + this.read_wait = Some(cx.waker().clone()); + return Poll::Pending; + } + while output.remaining() != 0 { + let Some(byte) = response.pop_front() else { + break; + }; + output.put_slice(&[byte]); + } + Poll::Ready(Ok(())) + } +} +impl AsyncWrite for Raw { + fn poll_write( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + let this = self.get_mut(); + this.state.writes.fetch_add(1, Ordering::SeqCst); + if this.state.blocked.load(Ordering::SeqCst) { + this.write_wait = Some(cx.waker().clone()); + this.state.pending_writes.fetch_add(1, Ordering::SeqCst); + return Poll::Pending; + } + let mut submitted = this.state.submitted.lock().unwrap(); + if input.len() > 16 * 1024 - submitted.len() { + return Poll::Ready(Err(io::ErrorKind::InvalidData.into())); + } + submitted.extend_from_slice(input); + Poll::Ready(Ok(input.len())) + } + fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + let this = self.get_mut(); + this.state.flushes.fetch_add(1, Ordering::SeqCst); + if this.state.blocked.load(Ordering::SeqCst) { + this.write_wait = Some(cx.waker().clone()); + Poll::Pending + } else { + Poll::Ready(Ok(())) + } + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.state.shutdowns.fetch_add(1, Ordering::SeqCst); + self.as_mut().poll_flush(cx) + } +} +struct MemoryUpstream { + streams: Mutex>, + calls: AtomicUsize, +} +#[async_trait] +impl OutboundConnector for MemoryUpstream { + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + self.calls.fetch_add(1, Ordering::SeqCst); + let io = self + .streams + .lock() + .unwrap() + .pop_front() + .ok_or(DispatchError::NotAllowed)?; + Ok(ConnectedStream { + io, + effective_peer: session.destination, + }) + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + Err(DispatchError::NotAllowed) + } +} +fn config(cipher: &str) -> VmessOutboundConfig { + let value = serde_json::json!({"proxies":[{"name":"cover","type":"vmess", + "server":"192.0.2.10","port":8443,"uuid":"07070707-0707-0707-0707-070707070707", + "cipher":cipher,"network":"http","http-opts":{"method":"GET","path":["/memory-cover"], + "headers":{"Host":["cover.memory.invalid"]}}}],"rules":["MATCH,cover"]}); + let mut parsed = Config::parse_yaml(&serde_json::to_vec(&value).unwrap()).unwrap(); + let ProxyProtocol::Vmess(config) = parsed.proxies.remove(0).protocol else { + panic!("actual VMess Config") + }; + config +} +fn fixture( + cipher: &str, + count: usize, + cover_response: bool, +) -> (VmessOutbound, Arc, Vec>) { + let states: Vec<_> = + (0..count) + .map(|_| { + let state = Arc::new(RawReceipt::default()); + if cover_response { + state.response.lock().unwrap().extend( + b"HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\n\r\n", + ); + } + state + }) + .collect(); + let upstream = Arc::new(MemoryUpstream { + streams: Mutex::new( + states + .iter() + .map(|state| { + Box::new(Raw { + state: state.clone(), + read_wait: None, + write_wait: None, + }) as BoxStream + }) + .collect(), + ), + calls: AtomicUsize::new(0), + }); + let node = VmessOutbound::new_with_path(&config(cipher), UpstreamPath::proxy(upstream.clone())) + .unwrap(); + (node, upstream, states) +} +fn session() -> StreamSession { + StreamSession { + metadata: Default::default(), + inbound: InboundKind::InternalMeasure, + source: "127.0.0.1:1".parse().unwrap(), + destination: Destination::Ip("192.0.2.2:443".parse().unwrap()), + sniffed_domain: None, + } +} +async fn connect(node: &VmessOutbound) -> BoxStream { + let context = EstablishContext::with_timeout(Duration::from_secs(1)); + let result = tokio::time::timeout( + Duration::from_secs(1), + node.connect_stream(session(), &context), + ) + .await; + match result { + Ok(Ok(connected)) => connected.io, + other => { + OutboundConnector::shutdown(node).await; + panic!("real complete VMess HTTP setup did not finish: {other:?}"); + } + } +} +fn read_poll(stream: &mut BoxStream, wake: &Waker) -> Poll> { + let mut storage = [0; 1]; + Pin::new(stream).poll_read( + &mut Context::from_waker(wake), + &mut ReadBuf::new(&mut storage), + ) +} +fn kind(result: Poll>) -> Option { + match result { + Poll::Ready(Err(error)) => Some(error.kind()), + _ => None, + } +} +fn released(weak: &Weak, reader: &Weak, writer: &Weak) -> bool { + weak.upgrade().is_none() && reader.upgrade().is_none() && writer.upgrade().is_none() +} + +#[tokio::test] +async fn vmess_http_cover_complete_owned_whole_close_control_releases_raw() { + for cipher in CIPHERS { + let (node, upstream, states) = fixture(cipher, 1, false); + let state = states[0].clone(); + let weak = Arc::downgrade(&state); + let mut stream = connect(&node).await; + let reader = Arc::new(WakeCount::default()); + let writer = Arc::new(WakeCount::default()); + let reader_weak = Arc::downgrade(&reader); + let writer_weak = Arc::downgrade(&writer); + let rx = waker(reader.clone()); + let tx = waker(writer.clone()); + let pending_read = read_poll(&mut stream, &rx).is_pending(); + let accepted = matches!( + Pin::new(&mut stream).poll_write(&mut Context::from_waker(&tx), b"whole close upload"), + Poll::Ready(Ok(18)) + ); + // Accepting buffered output now wakes the parked reader. Consume that + // notification and genuinely rearm it before observing whole-close. + let pending_before_close = read_poll(&mut stream, &rx).is_pending(); + reader.0.store(0, Ordering::SeqCst); + let closed = matches!( + Pin::new(&mut stream).poll_shutdown(&mut Context::from_waker(&tx)), + Poll::Ready(Ok(())) + ); + let woke = reader.0.load(Ordering::SeqCst) > 0; + let raw_released_while_stream_alive = state.drops.load(Ordering::SeqCst) == 1; + let read_after_close = kind(read_poll(&mut stream, &rx)); + let cover_once = state.one_cover(); + let no_physical_shutdown = state.shutdowns.load(Ordering::SeqCst) == 0; + OutboundConnector::shutdown(&node).await; + let joined = node.tasks.is_closed() && node.tasks.is_empty(); + drop(stream); + drop(node); + drop(upstream); + drop(states); + drop(state); + drop(rx); + drop(tx); + drop(reader); + drop(writer); + let owners_released = released(&weak, &reader_weak, &writer_weak); + assert!( + pending_read + && accepted + && pending_before_close + && closed + && woke + && cover_once + && no_physical_shutdown, + "actual complete whole-close control failed for {cipher}" + ); + assert_eq!(read_after_close, Some(io::ErrorKind::ConnectionAborted)); + assert!(raw_released_while_stream_alive && joined && owners_released); + } +} + +#[tokio::test] +async fn vmess_http_cover_complete_owned_stop_wakes_independent_read_and_write_callers() { + let mut observations = Vec::new(); + for cipher in CIPHERS { + for response in [false, true] { + for operation in ["write", "flush", "shutdown"] { + let (node, upstream, states) = fixture(cipher, 1, response); + let state = states[0].clone(); + let weak = Arc::downgrade(&state); + let mut stream = connect(&node).await; + let reader = Arc::new(WakeCount::default()); + let writer = Arc::new(WakeCount::default()); + let reader_weak = Arc::downgrade(&reader); + let writer_weak = Arc::downgrade(&writer); + let rx = waker(reader.clone()); + let tx = waker(writer.clone()); + state.blocked.store(true, Ordering::SeqCst); + let accepted = matches!( + Pin::new(&mut stream) + .poll_write(&mut Context::from_waker(&tx), b"pending upload"), + Poll::Ready(Ok(14)) + ); + let read_pending = read_poll(&mut stream, &rx).is_pending(); + let write_pending = match operation { + "write" => Pin::new(&mut stream) + .poll_write(&mut Context::from_waker(&tx), b"second") + .is_pending(), + "flush" => Pin::new(&mut stream) + .poll_flush(&mut Context::from_waker(&tx)) + .is_pending(), + _ => Pin::new(&mut stream) + .poll_shutdown(&mut Context::from_waker(&tx)) + .is_pending(), + }; + let genuine_raw_pending = state.pending_writes.load(Ordering::SeqCst) > 0; + reader.0.store(0, Ordering::SeqCst); + writer.0.store(0, Ordering::SeqCst); + OutboundConnector::begin_shutdown(&node); + // These snapshots precede every post-stop IO poll, event and Drop. + let read_woken_at_stop = reader.0.load(Ordering::SeqCst) > 0; + let write_woken_at_stop = writer.0.load(Ordering::SeqCst) > 0; + let read_error = kind(read_poll(&mut stream, &rx)); + let write_error = kind( + Pin::new(&mut stream).poll_write(&mut Context::from_waker(&tx), b"no replay"), + ); + let raw_released = state.drops.load(Ordering::SeqCst) == 1; + let cover_once = state.one_cover(); + OutboundConnector::shutdown(&node).await; + let joined = node.tasks.is_closed() && node.tasks.is_empty(); + drop(stream); + drop(node); + drop(upstream); + drop(states); + drop(state); + drop(rx); + drop(tx); + drop(reader); + drop(writer); + let owners_released = released(&weak, &reader_weak, &writer_weak); + observations.push(( + cipher, + response, + operation, + accepted && read_pending && write_pending && genuine_raw_pending, + read_woken_at_stop, + write_woken_at_stop, + read_error, + write_error, + raw_released && cover_once && joined && owners_released, + )); + } + } + } + assert_eq!(observations.len(), 24); + assert!( + observations + .iter() + .all(|(_, _, _, pending, _, _, read, write, cleanup)| *pending + && *read == Some(io::ErrorKind::ConnectionAborted) + && *write == Some(io::ErrorKind::ConnectionAborted) + && *cleanup), + "real Pending/cancellation/cleanup fixture failed: {observations:?}" + ); + assert!( + observations + .iter() + .all(|(_, _, _, _, rx, tx, _, _, _)| *rx && *tx), + "parent Stop must wake both unrelated callers before any repoll/Drop: {observations:?}" + ); +} + +#[tokio::test] +async fn vmess_http_cover_actual_prepare_stop_before_finish_never_polls_raw_again() { + for cipher in CIPHERS { + let (node, upstream, states) = fixture(cipher, 1, false); + let weak = Arc::downgrade(&states[0]); + let context = EstablishContext::with_timeout(Duration::from_secs(1)); + let prepared = match node.prepare(session(), &context).await { + Ok(prepared) => prepared, + Err(error) => { + OutboundConnector::shutdown(&node).await; + panic!("real prepared HTTP owner failed before Stop: {error:?}"); + } + }; + let before = states[0].polls(); + let token_was_open = !prepared.token.is_cancelled(); + OutboundConnector::begin_shutdown(&node); + let stopped_child = prepared.token.is_cancelled(); + let finished = prepared.finish(Command::Tcp, &session().destination).await; + let rejected = finished.is_err(); + drop(finished); + let calls = upstream.calls.load(Ordering::SeqCst); + let after_stop = node.connect_stream(session(), &context).await; + let rejects_new = after_stop.is_err(); + drop(after_stop); + let no_new_raw = + states[0].polls() == before && upstream.calls.load(Ordering::SeqCst) == calls; + let raw_dropped = states[0].drops.load(Ordering::SeqCst) == 1; + OutboundConnector::shutdown(&node).await; + let joined = node.tasks.is_closed() && node.tasks.is_empty(); + drop(node); + drop(upstream); + drop(states); + let owners_released = weak.upgrade().is_none(); + assert!( + token_was_open + && stopped_child + && rejected + && rejects_new + && no_new_raw + && raw_dropped + && joined + && owners_released, + "real prepare/Stop/finish must not publish or touch raw IO: {cipher}" + ); + } +} + +#[tokio::test] +async fn vmess_http_cover_complete_child_drop_preserves_sibling_until_parent_stop() { + for cipher in CIPHERS { + let (node, upstream, states) = fixture(cipher, 2, false); + let weak_one = Arc::downgrade(&states[0]); + let weak_two = Arc::downgrade(&states[1]); + let first = connect(&node).await; + let mut second = connect(&node).await; + drop(first); + let isolated = states[0].drops.load(Ordering::SeqCst) == 1 + && states[1].drops.load(Ordering::SeqCst) == 0 + && !node.cancellation.is_cancelled(); + let reader = Arc::new(WakeCount::default()); + let writer = Arc::new(WakeCount::default()); + let reader_weak = Arc::downgrade(&reader); + let writer_weak = Arc::downgrade(&writer); + let rx = waker(reader.clone()); + let tx = waker(writer.clone()); + let accepted = matches!( + Pin::new(&mut second).poll_write(&mut Context::from_waker(&tx), b"live sibling"), + Poll::Ready(Ok(12)) + ); + let flushed = matches!( + Pin::new(&mut second).poll_flush(&mut Context::from_waker(&tx)), + Poll::Ready(Ok(())) + ); + let pending_read = read_poll(&mut second, &rx).is_pending(); + reader.0.store(0, Ordering::SeqCst); + OutboundConnector::begin_shutdown(&node); + let woke = reader.0.load(Ordering::SeqCst) > 0; + let error = kind(read_poll(&mut second, &rx)); + let actual_drop = states + .iter() + .all(|state| state.drops.load(Ordering::SeqCst) == 1 && state.one_cover()); + OutboundConnector::shutdown(&node).await; + let joined = node.tasks.is_closed() && node.tasks.is_empty(); + drop(second); + drop(node); + drop(upstream); + drop(states); + drop(rx); + drop(tx); + drop(reader); + drop(writer); + let owners_released = + weak_one.upgrade().is_none() && released(&weak_two, &reader_weak, &writer_weak); + assert!( + isolated + && accepted + && flushed + && pending_read + && woke + && actual_drop + && joined + && owners_released, + "real child Drop/parent Stop ownership failed: {cipher}" + ); + assert_eq!(error, Some(io::ErrorKind::ConnectionAborted)); + } +} diff --git a/src/outbound/vmess/legacy_h2_memory_tests.rs b/src/outbound/vmess/legacy_h2_memory_tests.rs new file mode 100644 index 0000000..0e9f8fb --- /dev/null +++ b/src/outbound/vmess/legacy_h2_memory_tests.rs @@ -0,0 +1,326 @@ +//! Post-response-authentication seam only: no full VMess header authentication, +//! official peer, business HTTP cache, socket or performance acceptance. +use super::*; +use crate::session::Destination; +use futures_util::FutureExt; +use std::{ + future::{Future, poll_fn}, + panic::AssertUnwindSafe, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt, DuplexStream}, + sync::oneshot, + time::{Instant, timeout}, +}; + +const ENTITY: usize = 64 * 1024; +const WAIT: Duration = Duration::from_secs(10); + +fn invalid() -> io::Error { + io::ErrorKind::InvalidData.into() +} +fn body_codec() -> BodyCodec { + BodyCodec::new( + BodyOptions::new(BodyCipher::Aes128Gcm, false, false).unwrap(), + Command::Tcp, + &[7; 16], + [9; 16], + &[7; 16], + [9; 16], + ) +} +fn post_auth(io: BoxStream) -> VmessStream { + let handshake = ClientHandshake::new( + &super::super::VmessIdentity::new(uuid::Uuid::from_bytes([7; 16])), + Command::Tcp, + &Destination::domain("body.test", 443).unwrap(), + BodyOptions::new(BodyCipher::Aes128Gcm, false, false).unwrap(), + ) + .unwrap(); + let mut stream = VmessStream::new(io, handshake).with_whole_close(); + stream.read = body_codec(); + stream.write = body_codec(); + stream.stage = ReadStage::Length; + stream.handshake = None; + stream +} + +async fn send_entity( + send: &mut h2::SendStream, + codec: &mut BodyCodec, + byte: u8, + blocked: &mut Option>, +) -> io::Result<()> { + for _ in 0..ENTITY / WRITE_CHUNK { + let mut wire = codec.encode(&[byte; WRITE_CHUNK])?; + while !wire.is_empty() { + send.reserve_capacity(wire.len()); + let capacity = poll_fn(|cx| match send.poll_capacity(cx) { + Poll::Pending => { + if let Some(signal) = blocked.take() { + let _ = signal.send(()); + } + Poll::Pending + } + ready => ready, + }) + .await + .ok_or_else(invalid)? + .map_err(|_| invalid())?; + if capacity == 0 { + tokio::task::yield_now().await; + continue; + } + let count = capacity.min(wire.len()); + send.send_data(wire.split_to(count), false) + .map_err(|_| invalid())?; + } + } + Ok(()) +} + +async fn receive_entities(receive: &mut h2::RecvStream) -> io::Result<()> { + let mut decoder = body_codec(); + let mut wire = BytesMut::new(); + let mut next = None; + let mut consumed = 0; + while consumed < 2 * ENTITY { + let data = receive + .data() + .await + .ok_or_else(invalid)? + .map_err(|_| invalid())?; + receive + .flow_control() + .release_capacity(data.len()) + .map_err(|_| invalid())?; + wire.extend_from_slice(&data); + loop { + if next.is_none() { + if wire.len() < decoder.length_size() { + break; + } + next = Some(decoder.decode_length(&mut wire.split_to(decoder.length_size()))?); + } + let (length, padding) = next.unwrap(); + if wire.len() < length { + break; + } + let plain = decoder.decode_body(wire.split_to(length), padding)?; + if plain.is_empty() { + return Err(invalid()); + } + for &byte in plain.iter() { + let expected = if consumed < ENTITY { 0x31 } else { 0x32 }; + if consumed >= 2 * ENTITY || byte != expected { + return Err(invalid()); + } + consumed += 1; + } + next = None; + if consumed == 2 * ENTITY { + break; + } + } + } + if next.is_some() || !wire.is_empty() { + return Err(invalid()); + } + Ok(()) +} + +async fn peer( + raw: DuplexStream, + read_allowed: oneshot::Receiver<()>, + send_blocked: oneshot::Sender<()>, +) -> io::Result<()> { + let mut connection = h2::server::Builder::new() + .initial_window_size(128) + .handshake::<_, Bytes>(raw) + .await + .map_err(|_| invalid())?; + let (request, mut reply) = connection + .accept() + .await + .ok_or_else(invalid)? + .map_err(|_| invalid())?; + if request.method() != "PUT" || request.uri().path() != "/h2-reuse" { + return Err(invalid()); + } + let mut receive = request.into_body(); + let mut send = reply + .send_response(http::Response::new(()), false) + .map_err(|_| invalid())?; + let work = async move { + let mut encoder = body_codec(); + // More than the client's initial DATA window: it must really stall + // before the application starts consuming its first decoded entity. + send_entity(&mut send, &mut encoder, 0x91, &mut Some(send_blocked)).await?; + read_allowed.await.map_err(|_| invalid())?; + receive_entities(&mut receive).await?; + send_entity(&mut send, &mut encoder, 0x92, &mut None).await?; + match receive.data().await { + None | Some(Err(_)) => Ok(()), // Original Driver.stop/whole-close. + Some(Ok(_)) => Err(invalid()), + } + }; + tokio::pin!(work); + loop { + tokio::select! { + result = &mut work => return result, + next = connection.accept() => { + match next { + None | Some(Err(_)) => return work.await, + Some(Ok(_)) => return Err(invalid()), + } + } + } + } +} + +#[tokio::test] +async fn legacy_h2_post_auth_two_entities_progress_both_ways_and_join_stop() { + let (raw, server) = tokio::io::duplex(64); + let (allow_read, read_allowed) = oneshot::channel(); + let (send_blocked, blocked) = oneshot::channel(); + let mut peer = tokio::spawn(peer(server, read_allowed, send_blocked)); + let mut owner = None; + let outcome = AssertUnwindSafe(timeout(WAIT, async { + let (raw, driver) = crate::transport::legacy_h2( + Box::new(raw), + "http://cover.test/h2-reuse", + Instant::now() + WAIT, + ) + .await?; + owner = Some(driver); + let (mut read, mut write) = tokio::io::split(post_auth(raw)); + let mut upload_bytes = vec![0x31; ENTITY]; + upload_bytes.extend_from_slice(&vec![0x32; ENTITY]); + let mut upload = Box::pin(async { + write.write_all(&upload_bytes).await?; + write.flush().await + }); + assert!( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))) + .await + .is_pending(), + "withheld peer receive credit must block upload" + ); + blocked.await.map_err(|_| invalid())?; + let mut first = vec![0; ENTITY]; + read.read_exact(&mut first).await?; + assert_eq!(first, vec![0x91; ENTITY]); + assert!( + poll_fn(|cx| Poll::Ready(upload.as_mut().poll(cx))) + .await + .is_pending(), + "receive must progress while the independent upload remains blocked" + ); + let mut second = vec![0; ENTITY]; + let mut download = Box::pin(read.read_exact(&mut second)); + assert!( + poll_fn(|cx| Poll::Ready(download.as_mut().poll(cx))) + .await + .is_pending(), + "the second response remains withheld until upload credit is released" + ); + allow_read.send(()).map_err(|_| invalid())?; + tokio::try_join!(upload.as_mut(), download.as_mut())?; + drop((upload, download)); + assert_eq!(second, vec![0x92; ENTITY]); + Ok::<_, io::Error>((read, write)) + })) + .catch_unwind() + .await; + + let mut panic = None; + let (mut active, mut failure) = match outcome { + Ok(Ok(Ok(halves))) => (Some(halves), None), + Ok(Ok(Err(error))) => (None, Some(format!("body exchange: {:?}", error.kind()))), + Ok(Err(_)) => (None, Some("body exchange deadline".into())), + Err(error) => { + panic = Some(error); + (None, None) + } + }; + // Once connect returns its Driver, stop and await it before propagating an + // exchange failure. Cancellation inside connect retains its production + // Drop-abort fallback; this test does not prove a join for that path. + // Always await our separately owned peer task. + let stop_phase = AssertUnwindSafe(async { + if let Some((read, write)) = active.as_mut() { + let mut byte = [0]; + let mut pending = Box::pin(read.read(&mut byte)); + let before = poll_fn(|cx| Poll::Ready(pending.as_mut().poll(cx))).await; + let waiting = before.is_pending(); + if !waiting { + failure = Some("reader ended before Stop".into()); + } + let stopped = if let Some(driver) = owner.take() { + driver.stop().await + } else { + Err(invalid()) + }; + if stopped.is_err() { + failure = Some("carrier Stop join failed".into()); + } + if waiting { + if !matches!(timeout(WAIT, pending).await, Ok(Ok(0))) { + failure = Some("Stop did not wake the live VMess reader to EOF".into()); + } + } else { + drop(pending); + } + let after_stop = timeout(WAIT, async { + write.write_all(b"after-stop").await?; + write.flush().await + }) + .await; + if !matches!(after_stop, Ok(Err(error)) if error.kind() == io::ErrorKind::BrokenPipe) { + failure = Some("stopped VMess writer flush returned a different result".into()); + } + } else if let Some(driver) = owner.take() + && driver.stop().await.is_err() + { + failure = Some("failed exchange carrier Stop join failed".into()); + } + }) + .catch_unwind() + .await; + if let Err(error) = stop_phase { + if panic.is_none() { + panic = Some(error); + } + } + // A panic before taking the owner must still reach its actual stop barrier. + if let Some(driver) = owner.take() { + match AssertUnwindSafe(driver.stop()).catch_unwind().await { + Ok(Ok(())) => {} + Ok(Err(_)) => failure = Some("cleanup carrier Stop join failed".into()), + Err(error) => { + if panic.is_none() { + panic = Some(error); + } + } + } + } + drop(active); + let joined = match timeout(WAIT, &mut peer).await { + Ok(Ok(result)) => result, + Ok(Err(_)) => Err(invalid()), + Err(_) => { + peer.abort(); + let _ = peer.await; + Err(io::ErrorKind::TimedOut.into()) + } + }; + if let Some(error) = panic { + std::panic::resume_unwind(error); + } + assert!( + joined.is_ok(), + "peer must naturally exit after the actual Stop: {joined:?}" + ); + assert!(failure.is_none(), "{failure:?}"); +} diff --git a/src/outbound/vmess/mod.rs b/src/outbound/vmess/mod.rs index eb857e9..c155fd9 100644 --- a/src/outbound/vmess/mod.rs +++ b/src/outbound/vmess/mod.rs @@ -86,3 +86,8 @@ mod tests { ); } } + +#[cfg(all(test, feature = "inbound-http"))] +pub(crate) use stream::http_cover_reuse_memory_tests::{ + MemoryVmessAcceptedPeer, MemoryVmessHttpCoverFactory, MemoryVmessHttpCoverReceipt, +}; diff --git a/src/outbound/vmess/outbound.rs b/src/outbound/vmess/outbound.rs index 8e8ed4a..5ece3e3 100644 --- a/src/outbound/vmess/outbound.rs +++ b/src/outbound/vmess/outbound.rs @@ -14,6 +14,12 @@ use crate::{ session::{Datagram, Destination, StreamSession}, transport::{GrpcPool, connect_websocket, http_obfs, legacy_h2}, }; +#[cfg(feature = "inbound-http")] +#[path = "http_cover_reuse_owner.rs"] +mod http_cover_reuse_owner; +#[cfg(feature = "inbound-http")] +use http_cover_reuse_owner::HttpCoverReuseOwner; + use async_trait::async_trait; use std::{ future::Future, @@ -38,6 +44,9 @@ pub struct VmessOutbound { server: Destination, upstream: UpstreamPath, security: SecurityClient, + // Constructed from the same normalized identity as the actual client. + #[cfg(feature = "inbound-http")] + http_cover_plain_security: bool, options: Arc, encoding: VmessPacketEncoding, grpc_pool: Option, @@ -53,6 +62,15 @@ impl std::fmt::Debug for VmessOutbound { } impl VmessOutbound { + #[cfg(all(test, feature = "inbound-http"))] + pub(crate) fn http_cover_test_lifecycle(&self) -> (bool, bool, bool) { + ( + self.cancellation.is_cancelled(), + self.tasks.is_closed(), + self.tasks.is_empty(), + ) + } + pub fn new_with_path(config: &VmessOutboundConfig, upstream: UpstreamPath) -> io::Result { Self::with_shared_security( config, @@ -85,6 +103,11 @@ impl VmessOutbound { server: server_destination(&config.address, config.port)?, upstream, security, + #[cfg(feature = "inbound-http")] + http_cover_plain_security: matches!( + &config.security, + crate::config::SecurityConfig::None + ), options: Arc::new(SessionOptions { identity: VmessIdentity::new(config.id), body: BodyOptions::new(cipher, config.global_padding, config.authenticated_length)?, @@ -102,6 +125,13 @@ impl VmessOutbound { driver_admission: Arc::new(Mutex::new(())), }) } + #[cfg(feature = "inbound-http")] + fn has_fixed_plain_http_cover(&self) -> bool { + self.http_cover_plain_security + && matches!(&self.options.transport, VmessTransport::Http { uris, headers, .. } + if uris.len() == 1 && headers.values().all(|values| values.len() == 1)) + } + async fn connect_transport( &self, session: StreamSession, @@ -259,6 +289,20 @@ impl PreparedStream { #[async_trait] impl OutboundConnector for VmessOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + !self.cancellation.is_cancelled() + && match &self.options.transport { + VmessTransport::Tcp + | VmessTransport::WebSocket { .. } + | VmessTransport::Grpc { .. } => true, + VmessTransport::H2 { uris } => uris.len() == 1, + VmessTransport::Http { .. } => self.has_fixed_plain_http_cover(), + } + && self.security.permits_static_http_reuse() + && self.upstream.permits_static_http_reuse(&self.server) + } + async fn connect_stream( &self, session: StreamSession, @@ -268,6 +312,15 @@ impl OutboundConnector for VmessOutbound { let prepared = self.prepare(session, context).await?; let token = prepared.token.clone(); let stream = prepared.finish(Command::Tcp, &effective_peer).await?; + #[cfg(feature = "inbound-http")] + if self.has_fixed_plain_http_cover() { + // Shape, rather than live reuse permission, selects binding even + // when node Stop races the completed setup and cancels this child. + return Ok(ConnectedStream { + io: Box::new(HttpCoverReuseOwner::new(Box::new(stream), token)), + effective_peer, + }); + } Ok(ConnectedStream { io: Box::new(OwnedStream::new(Box::new(stream), token)), effective_peer, @@ -728,3 +781,7 @@ mod polled_datagram_memory_tests { } } } + +#[cfg(all(test, feature = "inbound-http"))] +#[path = "http_cover_reuse_owner_memory_tests.rs"] +mod http_cover_reuse_owner_memory_tests; diff --git a/src/outbound/vmess/stream.rs b/src/outbound/vmess/stream.rs index 95cbaf9..c9cc09a 100644 --- a/src/outbound/vmess/stream.rs +++ b/src/outbound/vmess/stream.rs @@ -956,3 +956,11 @@ mod tests { } } } + +#[cfg(test)] +#[path = "legacy_h2_memory_tests.rs"] +mod legacy_h2_memory_tests; + +#[cfg(all(test, feature = "inbound-http"))] +#[path = "http_cover_reuse_memory_tests.rs"] +pub(super) mod http_cover_reuse_memory_tests; diff --git a/src/outbound/wireguard/connected_factory_memory_tests.rs b/src/outbound/wireguard/connected_factory_memory_tests.rs new file mode 100644 index 0000000..dc654f2 --- /dev/null +++ b/src/outbound/wireguard/connected_factory_memory_tests.rs @@ -0,0 +1,264 @@ +//! Actual WG endpoint/transport acquisition; no host socket or Noise worker. +use super::*; +use crate::{ + dialer::{Dialer, ResolvedEndpoint}, + outbound::{ConnectedStream, OutboundConnector, SelectUpstream, SelectUpstreamMember}, + resources::observation::ResourceProbe, + routing::GroupSelection, + session::{InboundKind, StreamSession}, +}; +use std::sync::atomic::Ordering; +use vole_netstack::{ClientAddresses, ClientNetStackParts, NetStack, NetStackConfig}; + +fn factory(peer: SocketAddr, upstream: UpstreamPath) -> (Driver, ClientNetStackParts) { + let mut config = super::super::tests::config(); + config.address = peer.ip().to_string(); + config.port = peer.port(); + config.peers[0].address = config.address.clone(); + config.peers[0].port = peer.port(); + let config = Arc::new(config); + let stack = NetStack::start_client( + NetStackConfig { + mtu: usize::from(config.mtu), + packet_queue: 32, + ..Default::default() + }, + ClientAddresses { + ipv4: config.ipv4, + ipv6: config.ipv6, + }, + ) + .unwrap(); + let (ready, _) = watch::channel(Ready::Waiting); + let driver = Driver { + routes: Arc::new(Routes::new(&config)), + config, + index: 0, + upstream, + session: DatagramSession::new(InboundKind::Tun, "192.0.2.1:20000".parse().unwrap()), + cancel: CancellationToken::new(), + ready, + sink: stack.packet_sink.clone(), + registry: Arc::new(Registry::default()), + updated: Arc::new(Mutex::new(Instant::now())), + pending_probe: None, + }; + (driver, stack) +} + +async fn stop_factory(driver: Driver, stack: ClientNetStackParts) -> bool { + driver.cancel.cancel(); + drop(driver); + tokio::time::timeout(Duration::from_secs(1), stack.control.stop()) + .await + .expect("factory's real netstack must join"); + let stopped = stack.control.is_stopped(); + drop(stack); + stopped +} + +#[tokio::test(flavor = "current_thread")] +async fn wireguard_connected_factory_memory_direct_and_lazy_pin_actual_endpoint() { + let probe = ResourceProbe::default(); + let observations = probe + .scope(async { + let mut observations = Vec::new(); + for peer in [ + "198.51.100.1:51820".parse::().unwrap(), + "[2001:db8::10]:51820".parse::().unwrap(), + ] { + for prepared in [false, true] { + let upstream = if prepared { + UpstreamPath::direct( + ResolvedEndpoint { + logical_host: peer.ip().to_string(), + port: peer.port(), + addresses: vec![peer], + }, + Dialer::default(), + ) + } else { + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + } + }; + let (driver, stack) = factory(peer, upstream); + let context = EstablishContext::default(); + let (endpoint, path) = driver.endpoint(&context, false).await.unwrap(); + let mut transport = driver.transport(endpoint, &path, &context).await.unwrap(); + let actual_peer = endpoint == peer; + let budget = transport.payload_budget(&Destination::Ip(endpoint)); + let size = driver.config.mtu + 32; + let exclusive = !transport.supports_shared_destinations(); + let mut guards = true; + // Only the fixed branch can reject without socket acquisition. + // Old source records its real capability, then closes/joins + // every owner before the final semantic RED assertion. + if exclusive { + let packet = |remote| Datagram { + remote: Destination::Ip(remote), + payload: Bytes::from_static(b"whole"), + sniffed_domain: None, + }; + let mut other = endpoint; + other.set_port(other.port() + 1); + let mut rejected = vec![other]; + if let SocketAddr::V6(address) = endpoint { + let mut flow = address; + flow.set_flowinfo(address.flowinfo() + 1); + rejected.push(SocketAddr::V6(flow)); + let mut scope = address; + scope.set_scope_id(address.scope_id() + 1); + rejected.push(SocketAddr::V6(scope)); + } + for other in rejected { + guards &= matches!( + transport.send(packet(other)).await, + Err(DispatchError::NotAllowed) + ); + let returned = transport.send_owned(packet(other)).err(); + guards &= returned.is_some_and(|item| { + item.remote == Destination::Ip(other) + && item.payload == Bytes::from_static(b"whole") + }); + let returned = transport + .send_batch_owned(vec![packet(other), packet(other)]) + .err(); + guards &= returned.is_some_and(|items| { + items.len() == 2 + && items.iter().all(|item| { + item.remote == Destination::Ip(other) + && item.payload == Bytes::from_static(b"whole") + }) + }); + } + guards &= transport.send_owned(packet(endpoint)).is_err(); + } + let closed = transport.close().await.is_ok(); + let after_close = transport + .send(Datagram { + remote: Destination::Ip(endpoint), + payload: Bytes::from_static(b"after-close"), + sniffed_domain: None, + }) + .await + .is_err(); + drop(transport); + let stopped = stop_factory(driver, stack).await; + observations.push(( + actual_peer, + budget == DatagramBudget::new(size, size), + exclusive, + guards, + closed && after_close && stopped, + )); + } + } + observations + }) + .await; + assert!(probe.snapshot().is_idle()); + assert_eq!(observations.len(), 4); + for (peer, budget, exclusive, guards, closed) in observations { + assert!( + peer && budget && closed, + "actual WG factory and owner controls" + ); + assert!( + exclusive, + "WireGuard factory must acquire one fixed physical peer" + ); + assert!( + guards, + "actual fixed transport must reject every wrong peer before IO" + ); + } +} + +#[derive(Default)] +struct RejectProxy { + requests: Mutex)>>, +} +#[async_trait::async_trait] +impl OutboundConnector for RejectProxy { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + Err(DispatchError::NotAllowed) + } + async fn open_datagram( + &self, + request: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + self.requests.lock().unwrap().push(( + request.budget(), + request.udp_socket_options().receive_buffer, + )); + Err(DispatchError::NotAllowed) + } +} + +#[tokio::test(flavor = "current_thread")] +async fn wireguard_connected_factory_memory_groups_and_proxies_keep_original_scope() { + let probe = ResourceProbe::default(); + let observed = probe + .scope(async { + let peer = "198.51.100.1:51820".parse().unwrap(); + let selection = Arc::new(GroupSelection::new(0)); + let upstream = UpstreamPath::Group { + server: Destination::Ip(peer), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: None, + dialer: Dialer::default(), + }; + let (driver, stack) = factory(peer, upstream); + let context = EstablishContext::default(); + let (endpoint, path) = driver.endpoint(&context, false).await.unwrap(); + let mut first = driver.transport(endpoint, &path, &context).await.unwrap(); + let ordinary = first.supports_shared_destinations(); + selection.store(1, Ordering::Release); + let (same_endpoint, path) = driver.endpoint(&context, true).await.unwrap(); + let mut pinned = driver + .transport(same_endpoint, &path, &context) + .await + .unwrap(); + let pinned_original = + same_endpoint == endpoint && pinned.supports_shared_destinations(); + let rejects_new_context = driver + .endpoint(&EstablishContext::default(), true) + .await + .is_err(); + let closes = first.close().await.is_ok() && pinned.close().await.is_ok(); + drop((first, pinned)); + let group_stopped = stop_factory(driver, stack).await; + + let proxy = Arc::new(RejectProxy::default()); + let (driver, stack) = factory(peer, UpstreamPath::proxy(proxy.clone())); + let (endpoint, path) = driver.endpoint(&context, false).await.unwrap(); + let refused = matches!( + driver.transport(endpoint, &path, &context).await, + Err(DispatchError::NotAllowed) + ); + let requests = proxy.requests.lock().unwrap().clone(); + let proxy_stopped = stop_factory(driver, stack).await; + ( + ordinary && pinned_original && rejects_new_context, + closes && group_stopped && proxy_stopped, + refused, + requests, + ) + }) + .await; + assert!(probe.snapshot().is_idle()); + assert!(observed.0 && observed.1 && observed.2); + assert_eq!( + observed.3, + [(DatagramBudget::new(1440, 1440), Some(512 * 1024))] + ); +} diff --git a/src/outbound/wireguard/datagram.rs b/src/outbound/wireguard/datagram.rs index c77b090..dac8fe5 100644 --- a/src/outbound/wireguard/datagram.rs +++ b/src/outbound/wireguard/datagram.rs @@ -48,6 +48,13 @@ pub(super) struct Slot { _observation: observation::Guard, } impl Registry { + #[cfg(test)] + pub(super) fn memory_open( + self: &Arc, + maximum: u16, + ) -> Result<(Arc, mpsc::Receiver), DispatchError> { + self.open(maximum) + } fn open( self: &Arc, maximum: u16, diff --git a/src/outbound/wireguard/engine.rs b/src/outbound/wireguard/engine.rs index 8a0ac44..d87dcb5 100644 --- a/src/outbound/wireguard/engine.rs +++ b/src/outbound/wireguard/engine.rs @@ -61,6 +61,8 @@ impl Engine { NetStackConfig { mtu: usize::from(config.mtu), packet_queue: 32, + tcp_recv_buffer: 128 * 1024, + map_tcp_recv_buffer: cfg!(target_vendor = "apple"), tcp_send_buffer: 64 * 1024, ..Default::default() }, @@ -253,6 +255,18 @@ async fn pump_output( cancel.cancel(); } +#[cfg(test)] +pub(super) fn pending_memory_pump( + packets: PacketStream, + channel: Arc, + routes: Arc, + cancel: CancellationToken, +) -> impl std::future::Future { + let slot = PeerSlot::default(); + *slot.current.lock().unwrap() = Some(channel); + pump_output(packets, vec![slot].into(), routes, cancel) +} + #[cfg(test)] mod full_handoff_memory_tests { use super::*; diff --git a/src/outbound/wireguard/http_reuse_memory_tests.rs b/src/outbound/wireguard/http_reuse_memory_tests.rs new file mode 100644 index 0000000..a5163a2 --- /dev/null +++ b/src/outbound/wireguard/http_reuse_memory_tests.rs @@ -0,0 +1,501 @@ +//! Constructor/path proofs only: no engine, stack, packet, DNS or socket. +use super::*; +use crate::{ + config::{Config, ConnectionSettings, EgressOptions, IpVersion, ProxyProtocol}, + dialer::{Dialer, ResolvedEndpoint}, + dispatch::Dispatcher, + outbound::{ConnectorDispatcher, IpVersionConnector, SelectUpstream, SelectUpstreamMember}, + routing::GroupSelection, +}; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use serde_json::{Value, json}; + +fn public_key() -> String { + let secret = boringtun::x25519::StaticSecret::from(rand::random::<[u8; 32]>()); + STANDARD.encode(boringtun::x25519::PublicKey::from(&secret).as_bytes()) +} + +fn raw(multiple: bool) -> Value { + // Generated only inside this memory fixture; never written or printed. + let mut node = json!({ + "name":"memory-wireguard","type":"wireguard","ip":"10.0.0.2", + "ipv6":"fd00::2","private-key":STANDARD.encode(rand::random::<[u8;32]>()), + "udp":true,"mtu":1408,"reserved":[1,2,3],"persistent-keepalive":17 + }); + if multiple { + node["peers"] = json!([ + {"server":"192.0.2.10","port":51820,"public-key":public_key(), + "pre-shared-key":STANDARD.encode(rand::random::<[u8;32]>()), + "allowed-ips":["0.0.0.0/0","::/0"]}, + {"server":"198.51.100.20","port":51821,"public-key":public_key(), + "reserved":[4,5,6],"allowed-ips":["10.1.0.0/16","fd00:1::/64"]} + ]); + } else { + node["server"] = json!("192.0.2.10"); + node["port"] = json!(51820); + node["public-key"] = json!(public_key()); + node["pre-shared-key"] = json!(STANDARD.encode(rand::random::<[u8; 32]>())); + } + node +} + +fn config(raw: Value) -> WireGuardOutboundConfig { + let parsed = Config::parse_yaml(json!({"proxies":[raw]}).to_string().as_bytes()).unwrap(); + let ProxyProtocol::WireGuard(config) = &parsed.proxies[0].protocol else { + panic!("expected normalized WireGuard configuration"); + }; + config.clone() +} + +fn endpoint() -> ResolvedEndpoint { + ResolvedEndpoint { + logical_host: "192.0.2.10".into(), + port: 51820, + addresses: vec!["192.0.2.10:51820".parse().unwrap()], + } +} + +fn path(dialer: Dialer) -> UpstreamPath { + UpstreamPath::direct(endpoint(), dialer) +} + +fn node(config: &WireGuardOutboundConfig, path: UpstreamPath) -> WireGuardOutbound { + WireGuardOutbound::new_with_path(config, path).unwrap() +} + +fn pristine(node: &WireGuardOutbound) { + assert!(node.current.try_lock().unwrap().is_none()); + assert_eq!(node.retired.len(), 0); + assert!(!node.cancel.is_cancelled()); +} + +struct Unknown; +#[async_trait] +impl OutboundConnector for Unknown { + async fn connect_stream( + &self, + _: StreamSession, + _: &EstablishContext, + ) -> Result { + panic!("a WireGuard HTTP proof must not open a stream") + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("a WireGuard HTTP proof must not open a datagram path") + } +} + +#[test] +fn wireguard_single_and_multiple_peer_actual_constructors_remain_uninitialized() { + for multiple in [false, true] { + let config = config(raw(multiple)); + assert_eq!(config.refresh_server_ip_interval, 0); + assert_eq!(config.peers.len(), if multiple { 2 } else { 1 }); + let node = node(&config, path(Dialer::default())); + for _ in 0..3 { + assert!(node.permits_http_tcp_reuse()); + } + pristine(&node); + let adapted = ConnectorDispatcher::new(Arc::new(node)); + assert!(Dispatcher::permits_http_tcp_reuse(&adapted)); + } +} + +#[test] +fn wireguard_every_real_peer_is_checked_instead_of_representative_endpoint() { + let mut config = config(raw(true)); + config.address = "representative.invalid".into(); + config.port = 443; + let static_node = node(&config, path(Dialer::default())); + assert!( + static_node.permits_http_tcp_reuse(), + "the actual peer graph is literal" + ); + pristine(&static_node); + config.address = config.peers[0].address.clone(); + config.port = config.peers[0].port; + config.peers[1].address = "dynamic-second-peer.invalid".into(); + let dynamic = node(&config, path(Dialer::default())); + assert!(!dynamic.permits_http_tcp_reuse()); + pristine(&dynamic); + config.routes.retain(|(_, index)| *index == 0); + let unrouted = node(&config, path(Dialer::default())); + assert!( + !unrouted.permits_http_tcp_reuse(), + "the proof covers every configured peer" + ); + pristine(&unrouted); +} + +#[test] +fn wireguard_duplicate_key_normalization_uses_final_actual_endpoint() { + let mut document = raw(true); + document["peers"][1]["public-key"] = document["peers"][0]["public-key"].clone(); + for server in ["198.51.100.20", "last-declaration.invalid"] { + document["peers"][1]["server"] = json!(server); + let config = config(document.clone()); + assert_eq!(config.peers.len(), 1); + assert_eq!(config.peers[0].address, server); + assert_eq!(config.peers[0].port, 51821); + let node = node(&config, path(Dialer::default())); + assert_eq!(node.permits_http_tcp_reuse(), server == "198.51.100.20"); + pristine(&node); + } +} + +#[test] +fn wireguard_proof_follows_actual_for_server_retargeting_for_each_peer() { + let config = config(raw(true)); + let upstream = path(Dialer::default()); + let first = crate::outbound::server_destination(&config.peers[0].address, config.peers[0].port) + .unwrap(); + let second = + crate::outbound::server_destination(&config.peers[1].address, config.peers[1].port) + .unwrap(); + assert!(matches!( + upstream.for_server(&first, false), + UpstreamPath::Direct { .. } + )); + assert!(matches!( + upstream.for_server(&second, false), + UpstreamPath::LazyDirect { .. } + )); + let node = node(&config, upstream); + assert!(node.permits_http_tcp_reuse()); + pristine(&node); +} + +#[test] +fn wireguard_literal_refresh_paths_remain_proven_without_roaming_or_resolution() { + for refresh in [0, 1, -1, i64::MAX] { + let mut config = config(raw(true)); + config.refresh_server_ip_interval = refresh; + let node = node(&config, path(Dialer::default())); + for peer in &config.peers { + let server = crate::outbound::server_destination(&peer.address, peer.port).unwrap(); + assert!(matches!( + node.upstream.for_server(&server, true), + UpstreamPath::LazyDirect { .. } + )); + } + assert!(node.permits_http_tcp_reuse()); + pristine(&node); + config.peers[1].address = "refresh-second-peer.invalid".into(); + let dynamic = self::node(&config, path(Dialer::default())); + assert!(!dynamic.permits_http_tcp_reuse()); + pristine(&dynamic); + } +} + +#[test] +fn wireguard_exact_ipv6_literal_paths_remain_uninitialized() { + let mut document = raw(true); + document["peers"][0]["server"] = json!("2001:db8::10"); + document["peers"][1]["server"] = json!("2001:db8::20"); + document["refresh-server-ip-interval"] = json!(1); + let config = config(document); + let endpoint = ResolvedEndpoint { + logical_host: "2001:db8::10".into(), + port: 51820, + addresses: vec!["[2001:db8::10]:51820".parse().unwrap()], + }; + let node = node(&config, UpstreamPath::direct(endpoint, Dialer::default())); + assert!(node.permits_http_tcp_reuse()); + pristine(&node); +} + +#[test] +fn wireguard_mismatched_prepared_paths_follow_real_literal_retargeting() { + let mut mismatches = Vec::new(); + let mut wrong_host = endpoint(); + wrong_host.logical_host = "old-resolution.invalid".into(); + mismatches.push(wrong_host); + let mut wrong_port = endpoint(); + wrong_port.port = 443; + mismatches.push(wrong_port); + let mut empty = endpoint(); + empty.addresses.clear(); + mismatches.push(empty); + let mut wrong_ip = endpoint(); + wrong_ip.addresses[0] = "198.51.100.30:51820".parse().unwrap(); + mismatches.push(wrong_ip); + let mut wrong_address_port = endpoint(); + wrong_address_port.addresses[0] = "192.0.2.10:443".parse().unwrap(); + mismatches.push(wrong_address_port); + for endpoint in mismatches { + for refresh in [0, 1] { + let mut config = config(raw(false)); + config.refresh_server_ip_interval = refresh; + let server = + crate::outbound::server_destination(&config.peers[0].address, config.peers[0].port) + .unwrap(); + let upstream = UpstreamPath::direct(endpoint.clone(), Dialer::default()); + // The real driver discards this descriptor, keeping its same Dialer. + assert!(matches!( + upstream.for_server(&server, false), + UpstreamPath::LazyDirect { .. } + )); + let node = node(&config, upstream); + assert!(node.permits_http_tcp_reuse()); + pristine(&node); + } + } +} + +#[test] +fn wireguard_ip4p_initial_and_refresh_share_actual_address_and_encoded_port() { + let encoded = "[2001:0::1bb:c000:201]:8443".parse().unwrap(); + let physical = "192.0.2.1:443".parse().unwrap(); + for convert in [false, true] { + let mut document = raw(false); + document["server"] = json!("2001:0::1bb:c000:201"); + document["port"] = json!(8443); + document["refresh-server-ip-interval"] = json!(-1); + let config = config(document); + let settings = ConnectionSettings { + dialer_ip4p_convert: convert, + ..Default::default() + }; + let upstream = UpstreamPath::direct( + ResolvedEndpoint { + logical_host: config.peers[0].address.clone(), + port: config.peers[0].port, + addresses: vec![encoded], + }, + Dialer::default().with_connections(settings), + ); + let server = Destination::Ip(encoded); + let expected = if convert { physical } else { encoded }; + let UpstreamPath::Direct { endpoint, dialer } = upstream.for_server(&server, false) else { + panic!("initial exact literal must retain its prepared path"); + }; + assert_eq!( + dialer.ordered_connected_addresses(&endpoint.addresses), + [expected] + ); + let UpstreamPath::LazyDirect { dialer } = upstream.for_server(&server, true) else { + panic!("refresh must retain the same physical Dialer policy"); + }; + assert_eq!(dialer.connections(), settings); + // Literal physical_address uses this same immutable conversion before + // the ordinary second resolve in Driver::endpoint; no resolver is run. + assert_eq!( + dialer.connections().convert_ip4p_endpoint(encoded), + expected + ); + let node = node(&config, upstream); + assert!(node.permits_http_tcp_reuse()); + pristine(&node); + } +} + +#[test] +fn wireguard_rejects_unknown_proxy_group_and_even_a_proven_tcp_parent() { + let config = config(raw(false)); + assert!(!Unknown.permits_http_tcp_reuse()); + let unknown = node(&config, UpstreamPath::proxy(Arc::new(Unknown))); + assert!(!unknown.permits_http_tcp_reuse()); + pristine(&unknown); + let selection = Arc::new(GroupSelection::new(0)); + let grouped = node( + &config, + UpstreamPath::Group { + server: Destination::Ip("192.0.2.10:51820".parse().unwrap()), + group: Arc::new(SelectUpstream::new( + selection.clone(), + vec![SelectUpstreamMember::Direct, SelectUpstreamMember::Reject], + )), + endpoint: Some(endpoint()), + dialer: Dialer::default(), + }, + ); + assert!(!grouped.permits_http_tcp_reuse()); + selection.store(1, std::sync::atomic::Ordering::Release); + assert!(!grouped.permits_http_tcp_reuse()); + pristine(&grouped); + let parent = Arc::new(node(&config, path(Dialer::default()))); + assert!(parent.permits_http_tcp_reuse()); + let child = node(&config, UpstreamPath::proxy(parent)); + assert!( + !child.permits_http_tcp_reuse(), + "a TCP proof cannot authorize its UDP carrier" + ); + pristine(&child); +} + +struct NeverProtect; +impl crate::dialer::SocketProtector for NeverProtect { + fn protect(&self, _: i32) -> io::Result<()> { + panic!("proof queries must not create sockets or invoke protect") + } +} + +#[test] +fn wireguard_preserves_physical_restrictions_and_exact_prepared_endpoints() { + let config = config(raw(true)); + for dialer in [ + Dialer::default().with_ip_version(IpVersion::Ipv4), + Dialer::default().with_ip_version(IpVersion::Ipv6), + Dialer::default().with_ip_version(IpVersion::Ipv4Prefer), + Dialer::default().with_ip_version(IpVersion::Ipv6Prefer), + Dialer::default().with_source_ip("192.0.2.20".parse().unwrap()), + #[cfg(not(target_os = "macos"))] + Dialer::default().with_mptcp(true), + Dialer::default().with_egress(&EgressOptions { + interface: Some("memory-interface".into()), + ..Default::default() + }), + Dialer::default().with_protector(Arc::new(NeverProtect)), + ] { + let restricted = node(&config, path(dialer)); + assert!(!restricted.permits_http_tcp_reuse()); + pristine(&restricted); + } + for extra in ["198.51.100.30:51820", "192.0.2.10:51820"] { + for refresh in [0, 1] { + let mut config = config.clone(); + config.refresh_server_ip_interval = refresh; + let mut multiple = endpoint(); + multiple.addresses.push(extra.parse().unwrap()); + let server = Destination::Ip("192.0.2.10:51820".parse().unwrap()); + let upstream = UpstreamPath::direct(multiple, Dialer::default()); + // Validation retains this Direct, so its non-singleton list must + // fail even when refresh would later become a safe LazyDirect. + assert!(matches!( + upstream.for_server(&server, false), + UpstreamPath::Direct { .. } + )); + let ambiguous = node(&config, upstream); + assert!(!ambiguous.permits_http_tcp_reuse()); + pristine(&ambiguous); + } + } +} + +#[cfg(any( + target_os = "linux", + target_os = "macos", + target_os = "ios", + target_os = "tvos" +))] +#[test] +fn wireguard_dns_bound_physical_path_keeps_existing_restriction() { + let config = config(raw(false)); + let dialer = Dialer::default() + .for_dns_source( + crate::dns::source::DnsBinding { + interface: "memory-dns-interface".into(), + interface_index: None, + }, + "192.0.2.10:51820".parse().unwrap(), + ) + .unwrap(); + let node = node(&config, path(dialer)); + assert!(!node.permits_http_tcp_reuse()); + pristine(&node); +} + +#[test] +fn wireguard_invalid_config_never_reaches_a_static_proof() { + let valid = config(raw(true)); + let mut empty = valid.clone(); + empty.peers.clear(); + let mut invalid_route = valid.clone(); + invalid_route.routes[0].1 = invalid_route.peers.len(); + let mut invalid_port = valid.clone(); + invalid_port.peers[1].port = 0; + for invalid in [empty, invalid_route, invalid_port] { + assert!(WireGuardOutbound::new_with_path(&invalid, path(Dialer::default())).is_err()); + } +} + +#[test] +fn wireguard_actual_ip_version_wrapper_does_not_hide_family_policy() { + let config = config(raw(false)); + for version in [ + IpVersion::Dual, + IpVersion::Ipv4, + IpVersion::Ipv6, + IpVersion::Ipv4Prefer, + IpVersion::Ipv6Prefer, + ] { + let node = Arc::new(node(&config, path(Dialer::default()))); + let wrapped = IpVersionConnector { + inner: node.clone(), + version, + }; + assert_eq!(wrapped.permits_http_tcp_reuse(), version == IpVersion::Dual); + pristine(&node); + OutboundConnector::begin_shutdown(node.as_ref()); + assert!(!wrapped.permits_http_tcp_reuse()); + } +} + +#[test] +fn wireguard_constructor_pins_crypto_route_and_local_config_without_mutating_input() { + let mut document = raw(true); + document["remote-dns-resolve"] = json!(true); + document["dns"] = json!(["udp://192.0.2.53"]); + document["refresh-server-ip-interval"] = json!(1); + let mut input = config(document); + assert!(!input.dns.is_empty()); + let expected = input.clone(); + let node = node(&input, path(Dialer::default())); + assert!(node.config.as_ref() == &expected); + input.private_key = input.peers[0].public_key.clone(); + input.peers[1].public_key = input.peers[0].public_key.clone(); + input.peers[0].pre_shared_key = None; + input.peers[1].reserved = [7, 8, 9]; + input.peers[1].allowed_ips.clear(); + input.routes.clear(); + input.ipv4 = Some("10.9.9.9".parse().unwrap()); + input.ipv6 = None; + input.mtu = 1280; + input.persistent_keepalive = 0; + input.dns.clear(); + input.refresh_server_ip_interval = -1; + input.address = "externally-changed.invalid".into(); + input.port = 443; + assert!(node.config.as_ref() == &expected); + assert!(node.permits_http_tcp_reuse()); + pristine(&node); +} + +#[test] +fn wireguard_owner_and_original_dialer_stop_each_revoke_static_permission() { + let config = config(raw(true)); + for lazy in [false, true] { + let dialer = Dialer::default(); + let upstream = if lazy { + UpstreamPath::LazyDirect { + dialer: dialer.clone(), + } + } else { + path(dialer.clone()) + }; + let node = node(&config, upstream); + assert!(node.permits_http_tcp_reuse()); + dialer.begin_shutdown(); + assert!(!node.permits_http_tcp_reuse()); + pristine(&node); + } + let node = self::node(&config, path(Dialer::default())); + assert!(node.permits_http_tcp_reuse()); + OutboundConnector::begin_shutdown(&node); + assert!(!node.permits_http_tcp_reuse()); + assert!(node.current.try_lock().unwrap().is_none()); +} + +#[tokio::test] +async fn wireguard_never_opened_shutdown_does_not_initialize_an_engine() { + let config = config(raw(true)); + let node = node(&config, path(Dialer::default())); + assert!(node.permits_http_tcp_reuse()); + OutboundConnector::shutdown(&node).await; + assert!(!node.permits_http_tcp_reuse()); + assert!(node.current.try_lock().unwrap().is_none()); + assert_eq!(node.retired.len(), 0); +} diff --git a/src/outbound/wireguard/mod.rs b/src/outbound/wireguard/mod.rs index 6e25e93..071d88a 100644 --- a/src/outbound/wireguard/mod.rs +++ b/src/outbound/wireguard/mod.rs @@ -2,6 +2,8 @@ mod channel; mod datagram; mod engine; +#[cfg(all(test, feature = "inbound-http"))] +mod http_reuse_memory_tests; mod peer; mod resolver; mod routes; @@ -89,6 +91,38 @@ impl WireGuardOutbound { } #[async_trait] impl OutboundConnector for WireGuardOutbound { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + if self.cancel.is_cancelled() || self.config.peers.is_empty() { + return false; + } + // The validated private config fixes all keys, routes and actual peers. + // Follow Driver::endpoint for each peer, not the representative address. + let fixed = self.config.peers.iter().all(|peer| { + let Ok(server) = super::server_destination(&peer.address, peer.port) else { + return false; + }; + if !matches!(server, Destination::Ip(_)) { + return false; + } + if !self + .upstream + .for_server(&server, false) + .permits_static_direct_http_reuse(&server) + { + return false; + } + // Literal refresh uses the same immutable physical Dialer/IP4P + // policy; equal endpoints retain their existing carrier and Noise. + self.config.refresh_server_ip_interval == 0 + || self + .upstream + .for_server(&server, true) + .permits_static_direct_http_reuse(&server) + }); + fixed && !self.cancel.is_cancelled() + } + async fn connect_stream( &self, session: StreamSession, diff --git a/src/outbound/wireguard/peer.rs b/src/outbound/wireguard/peer.rs index 136eaf7..31c26b3 100644 --- a/src/outbound/wireguard/peer.rs +++ b/src/outbound/wireguard/peer.rs @@ -18,7 +18,9 @@ use boringtun::{ }; use bytes::Bytes; use std::{ + future::Future, net::{IpAddr, SocketAddr}, + pin::Pin, sync::{Arc, Mutex}, time::Duration, }; @@ -27,7 +29,131 @@ use tokio::{ time::{Instant, MissedTickBehavior}, }; use tokio_util::sync::CancellationToken; -use vole_netstack::{Packet, PacketSink, parse_udp_packet_view}; +use vole_netstack::{NetStackError, Packet, PacketSink, parse_udp_packet_view}; + +// One already validated packet, never a second queue or a spawned task. Losing +// a select branch drops only the short await wrapper, not this admission future. +struct PendingIngress { + admission: Pin> + Send>>, + #[cfg(test)] + disposition: PendingDisposition, + #[cfg(test)] + probe: Option>>, +} +impl PendingIngress { + fn new( + sink: &PacketSink, + packet: Packet, + #[cfg(test)] probe: Option>>, + ) -> Self { + let sink = sink.clone(); + #[cfg(test)] + if let Some(probe) = &probe { + let mut counts = probe.lock().unwrap(); + counts.created += 1; + counts.current += 1; + counts.peak = counts.peak.max(counts.current); + } + Self { + admission: Box::pin(async move { sink.send(packet).await }), + #[cfg(test)] + disposition: PendingDisposition::Abandoned, + #[cfg(test)] + probe, + } + } + async fn admit(&mut self) -> Result<(), NetStackError> { + let result = self.admission.as_mut().await; + #[cfg(test)] + { + self.disposition = if result.is_ok() { + PendingDisposition::Admitted + } else { + PendingDisposition::Failed + }; + } + result + } +} +struct PeerState { + timer: tokio::time::Interval, + established: bool, + handshake_deadline: Instant, + ingress: Option, +} +impl PeerState { + fn new(handshake_deadline: Instant, ingress: Option) -> Self { + let mut timer = tokio::time::interval(Duration::from_millis(250)); + timer.set_missed_tick_behavior(MissedTickBehavior::Skip); + Self { + timer, + established: false, + handshake_deadline, + ingress, + } + } + fn discard_for_timer(&mut self) { + if let Some(pending) = self.ingress.take() { + #[cfg(test)] + let pending = { + let mut pending = pending; + pending.disposition = PendingDisposition::Timer; + pending + }; + drop(pending); + } + } + fn discard_for_refresh(&mut self) { + if let Some(pending) = self.ingress.take() { + #[cfg(test)] + let pending = { + let mut pending = pending; + pending.disposition = PendingDisposition::Refresh; + pending + }; + drop(pending); + } + } +} + +#[cfg(test)] +#[derive(Clone, Copy)] +enum PendingDisposition { + Admitted, + Failed, + Timer, + Refresh, + Abandoned, +} +#[cfg(test)] +#[derive(Clone, Copy, Default)] +struct PendingMemoryCounts { + created: usize, + current: usize, + peak: usize, + admitted: usize, + failed: usize, + timer: usize, + refresh: usize, + abandoned: usize, +} +#[cfg(test)] +impl Drop for PendingIngress { + fn drop(&mut self) { + if let Some(probe) = &self.probe { + let mut counts = probe.lock().unwrap(); + counts.current -= 1; + match self.disposition { + PendingDisposition::Admitted => counts.admitted += 1, + PendingDisposition::Failed => counts.failed += 1, + PendingDisposition::Timer => counts.timer += 1, + PendingDisposition::Refresh => counts.refresh += 1, + PendingDisposition::Abandoned => counts.abandoned += 1, + } + } + } +} + struct Driver { config: Arc, index: usize, @@ -39,6 +165,8 @@ struct Driver { registry: Arc, routes: Arc, updated: Arc>, + #[cfg(test)] + pending_probe: Option>>, } impl Driver { fn peer(&self) -> &WireGuardPeerConfig { @@ -73,6 +201,11 @@ impl Driver { let request = DatagramRequest::new(self.session.clone()) .with_budget(DatagramBudget::new(size, size)) .with_udp_receive_buffer_size(512 * 1024); + #[cfg(target_os = "macos")] + let mut transport = path + .open_fixed_peer_datagram(request, endpoint, context) + .await?; + #[cfg(not(target_os = "macos"))] let mut transport = path.open_datagram(request, context).await?; let budget = transport.payload_budget(&Destination::Ip(endpoint)); if budget.transmit() < size || budget.receive() < size { @@ -83,12 +216,96 @@ impl Driver { } Ok(transport) } + fn network_datagram(&self, packet: &[u8], endpoint: SocketAddr) -> Datagram { + let mut wire = packet.to_vec(); + wire[1..4].copy_from_slice(&self.peer().reserved); + Datagram { + remote: Destination::Ip(endpoint), + payload: Bytes::from(wire), + sniffed_domain: None, + } + } + #[cfg(target_os = "macos")] + async fn send_network_batch( + &self, + mut packets: Vec, + transport: &mut dyn DatagramTransport, + deadline: Instant, + ) -> Result<(), DispatchError> { + if packets.len() >= 2 { + // Keep the original ciphertext FIFO until a positive physical + // completion confirms its prefix. Clone only Bytes handles. + if let Ok(operation) = transport.send_batch_owned(packets.clone()) { + let accepted = tokio::select! {biased; + () = self.cancel.cancelled() => return Err(DispatchError::ConnectionRefused), + result = tokio::time::timeout_at(deadline, operation) => { + result.map_err(|_| DispatchError::TimedOut)?.map_err(DispatchError::from)? + } + }; + if accepted == 0 || accepted > packets.len() { + return Err(std::io::Error::from(std::io::ErrorKind::InvalidData).into()); + } + drop(packets.drain(..accepted)); + } + } + // Unsupported admission performs no IO. A short success sends only + // its untouched suffix here; an IO error above is never replayed. + for datagram in packets { + tokio::select! {biased; + () = self.cancel.cancelled() => return Err(DispatchError::ConnectionRefused), + result = tokio::time::timeout_at(deadline, transport.send(datagram)) => { + result.map_err(|_| DispatchError::TimedOut)??; + } + } + } + Ok(()) + } + #[cfg(target_os = "macos")] + #[allow(clippy::too_many_arguments)] + async fn send_ready_data_batch( + &self, + first: Datagram, + tunn: &mut Tunn, + endpoint: SocketAddr, + transport: &mut dyn DatagramTransport, + deadline: Instant, + pending: &mut Option, + packets: &mut mpsc::Receiver, + scratch: &mut [u8], + ) -> Result<(), DispatchError> { + let mut batch = Vec::with_capacity(crate::dispatch::DATAGRAM_SEND_BATCH_LIMIT); + batch.push(first); + while batch.len() < crate::dispatch::DATAGRAM_SEND_BATCH_LIMIT { + if self.cancel.is_cancelled() { + return Err(DispatchError::ConnectionRefused); + } + let Ok(packet) = packets.try_recv() else { + break; + }; + match tunn.encapsulate(packet.data(), scratch) { + TunnResult::WriteToNetwork(wire) if wire.first() == Some(&4) => { + batch.push(self.network_datagram(wire, endpoint)); + } + other => { + // Rekey/control, Done and errors keep their original + // handling after every preceding data ciphertext is sent. + // Never re-encapsulate a dequeued packet or wait to fill. + self.send_network_batch(batch, transport, deadline).await?; + return self + .handle(other, endpoint, transport, deadline, pending) + .await; + } + } + } + self.send_network_batch(batch, transport, deadline).await + } async fn handle( &self, result: TunnResult<'_>, endpoint: SocketAddr, transport: &mut dyn DatagramTransport, deadline: Instant, + pending: &mut Option, ) -> Result<(), DispatchError> { match result { TunnResult::Done => Ok(()), @@ -97,13 +314,7 @@ impl Driver { } TunnResult::Err(_) => Ok(()), TunnResult::WriteToNetwork(packet) => { - let mut wire = packet.to_vec(); - wire[1..4].copy_from_slice(&self.peer().reserved); - let datagram = Datagram { - remote: Destination::Ip(endpoint), - payload: Bytes::from(wire), - sniffed_domain: None, - }; + let datagram = self.network_datagram(packet, endpoint); tokio::select! {biased;()=self.cancel.cancelled()=>Err(DispatchError::ConnectionRefused),result=tokio::time::timeout_at(deadline,transport.send(datagram))=>result.map_err(|_|DispatchError::TimedOut)?} } TunnResult::WriteToTunnelV4(packet, _) | TunnResult::WriteToTunnelV6(packet, _) => { @@ -120,9 +331,24 @@ impl Driver { self.registry .deliver(udp.source, udp.destination, udp.payload); } else { - let _ = self - .sink - .try_send(Packet::new(Bytes::copy_from_slice(packet))); + // No second plaintext allocation while one packet is owned. + if pending.is_none() { + let packet = Packet::new(Bytes::copy_from_slice(packet)); + if let Err((NetStackError::Backpressure, packet)) = + self.sink.try_send_recover(packet) + { + // Active sinks can accept more than the send MTU; + // only a bounded in-MTU Full packet is retained. + if packet.len() <= usize::from(self.config.mtu) { + *pending = Some(PendingIngress::new( + &self.sink, + packet, + #[cfg(test)] + self.pending_probe.clone(), + )); + } + } + } } Ok(()) } @@ -156,6 +382,8 @@ pub(super) async fn drive( registry, routes, updated, + #[cfg(test)] + pending_probe: None, }; let setup = async { let (endpoint, path) = driver.endpoint(&context, false).await?; @@ -175,9 +403,16 @@ pub(super) async fn drive( let size = usize::from(driver.config.mtu + 32).max(148); let mut scratch = vec![0; size]; let mut network = vec![0; size]; + let mut ingress = None; let first = tunn.format_handshake_initiation(&mut scratch, true); if driver - .handle(first, endpoint, transport.as_mut(), context.deadline()) + .handle( + first, + endpoint, + transport.as_mut(), + context.deadline(), + &mut ingress, + ) .await .is_ok() { @@ -186,7 +421,7 @@ pub(super) async fn drive( &mut tunn, endpoint, &mut transport, - &context, + PeerState::new(context.deadline(), ingress), &mut packets, &mut commands, &mut scratch, @@ -200,13 +435,123 @@ pub(super) async fn drive( driver.ready.send_replace(Ready::Failed); driver.cancel.cancel(); } +#[allow(clippy::too_many_arguments)] +async fn handle_peer_datagram( + driver: &Driver, + tunn: &mut Tunn, + endpoint: SocketAddr, + transport: &mut Box, + state: &mut PeerState, + deadline: Instant, + scratch: &mut [u8], + network: &mut [u8], + datagram: Datagram, +) -> Result<(), DispatchError> { + #[cfg(target_os = "macos")] + if driver.cancel.is_cancelled() { + return Err(DispatchError::ConnectionRefused); + } + let len = datagram.payload.len(); + if datagram.remote != Destination::Ip(endpoint) || !(4..=network.len()).contains(&len) { + return Ok(()); + } + // Standard packets already have zero reserved bytes. BoringTun + // borrows its input and returns only scratch-backed output. + let input: &[u8] = if datagram.payload[1..4] == [0, 0, 0] { + datagram.payload.as_ref() + } else { + // Preserve compatibility with a peer's nonzero reserved + // bytes using the same existing normalization buffer. + network[..len].copy_from_slice(&datagram.payload); + network[1..4].fill(0); + &network[..len] + }; + let result = tunn.decapsulate(Some(endpoint.ip()), input, scratch); + let authenticated = matches!(input[0], 1 | 2) + && matches!(result, TunnResult::WriteToNetwork(_)) + && tunn.time_since_last_handshake().is_some(); + driver + .handle( + result, + endpoint, + transport.as_mut(), + deadline, + &mut state.ingress, + ) + .await?; + loop { + let result = tunn.decapsulate(None, &[], scratch); + if matches!(result, TunnResult::Done) { + break; + } + driver + .handle( + result, + endpoint, + transport.as_mut(), + deadline, + &mut state.ingress, + ) + .await?; + } + if !state.established && authenticated { + state.established = true; + driver.ready.send_replace(Ready::Established); + tracing::debug!("WireGuard handshake ready"); + } + + Ok(()) +} + +#[cfg(target_os = "macos")] +async fn poll_ready_datagram( + transport: &mut Box, +) -> std::task::Poll> { + // Exactly one poll with the caller's real Context. Pending drops only the + // cancellation-safe receive wrapper, then returns to the original select. + let mut receive = std::pin::pin!(transport.receive()); + std::future::poll_fn(|context| std::task::Poll::Ready(receive.as_mut().poll(context))).await +} + +#[cfg(target_os = "macos")] +#[allow(clippy::too_many_arguments)] +async fn drain_ready_datagrams( + driver: &Driver, + tunn: &mut Tunn, + endpoint: SocketAddr, + transport: &mut Box, + state: &mut PeerState, + deadline: Instant, + scratch: &mut [u8], + network: &mut [u8], +) -> Result<(), DispatchError> { + // The selected packet was already processed. Every complete extra outer + // datagram, including invalid input and keepalives, consumes one of three. + for _ in 0..3 { + if driver.cancel.is_cancelled() { + return Err(DispatchError::ConnectionRefused); + } + if !state.established || state.ingress.is_some() { + break; + } + let std::task::Poll::Ready(datagram) = poll_ready_datagram(transport).await else { + break; + }; + handle_peer_datagram( + driver, tunn, endpoint, transport, state, deadline, scratch, network, datagram?, + ) + .await?; + } + Ok(()) +} + #[allow(clippy::too_many_arguments)] async fn run_peer( driver: &Driver, tunn: &mut Tunn, mut endpoint: SocketAddr, transport: &mut Box, - context: &EstablishContext, + mut state: PeerState, packets: &mut mpsc::Receiver, commands: &mut mpsc::Receiver, scratch: &mut [u8], @@ -216,82 +561,87 @@ async fn run_peer( Datagram(Result), Packet(Option), Command(Option), + Ingress(Result<(), NetStackError>), Timer, } - let mut timer = tokio::time::interval(Duration::from_millis(250)); - timer.set_missed_tick_behavior(MissedTickBehavior::Skip); - let mut established = false; - let mut handshake_deadline = context.deadline(); loop { - let deadline = if established { + let deadline = if state.established { Instant::now() + DEFAULT_ESTABLISH_TIMEOUT } else { - handshake_deadline + state.handshake_deadline }; // Cancellation and the original handshake deadline stay ahead of all // work. Ready network input must not starve output, refresh or timers. + let has_pending = state.ingress.is_some(); let event = tokio::select! {biased; ()=driver.cancel.cancelled()=>return Err(DispatchError::ConnectionRefused), - ()=tokio::time::sleep_until(handshake_deadline),if !established=>return Err(DispatchError::TimedOut), + ()=tokio::time::sleep_until(state.handshake_deadline),if !state.established=>return Err(DispatchError::TimedOut), event=async { tokio::select! { - datagram=transport.receive()=>Event::Datagram(datagram), - packet=packets.recv(),if established=>Event::Packet(packet), - command=commands.recv(),if established=>Event::Command(command), - _=timer.tick()=>Event::Timer, + datagram=async { transport.receive().await },if !has_pending=>Event::Datagram(datagram), + result=async { state.ingress.as_mut().expect("pending ingress branch").admit().await },if has_pending=>Event::Ingress(result), + packet=packets.recv(),if state.established=>Event::Packet(packet), + command=commands.recv(),if state.established=>Event::Command(command), + _=state.timer.tick()=>Event::Timer, } }=>event, }; match event { Event::Datagram(datagram) => { - let datagram = datagram?; - let len = datagram.payload.len(); - if datagram.remote != Destination::Ip(endpoint) - || !(4..=network.len()).contains(&len) - { - continue; - } - // Standard packets already have zero reserved bytes. BoringTun - // borrows its input and returns only scratch-backed output. - let input: &[u8] = if datagram.payload[1..4] == [0, 0, 0] { - datagram.payload.as_ref() - } else { - // Preserve compatibility with a peer's nonzero reserved - // bytes using the same existing normalization buffer. - network[..len].copy_from_slice(&datagram.payload); - network[1..4].fill(0); - &network[..len] - }; - let result = tunn.decapsulate(Some(endpoint.ip()), input, scratch); - let authenticated = matches!(input[0], 1 | 2) - && matches!(result, TunnResult::WriteToNetwork(_)) - && tunn.time_since_last_handshake().is_some(); - driver - .handle(result, endpoint, transport.as_mut(), deadline) + #[cfg(target_os = "macos")] + let was_established = state.established; + handle_peer_datagram( + driver, tunn, endpoint, transport, &mut state, deadline, scratch, network, + datagram?, + ) + .await?; + #[cfg(target_os = "macos")] + if was_established { + drain_ready_datagrams( + driver, tunn, endpoint, transport, &mut state, deadline, scratch, network, + ) .await?; - loop { - let result = tunn.decapsulate(None, &[], scratch); - if matches!(result, TunnResult::Done) { - break; - } - driver - .handle(result, endpoint, transport.as_mut(), deadline) - .await?; - } - if !established && authenticated { - established = true; - driver.ready.send_replace(Ready::Established); - tracing::debug!("WireGuard handshake ready"); } } Event::Packet(packet) => { let packet = packet.ok_or(DispatchError::ConnectionRefused)?; + let result = tunn.encapsulate(packet.data(), scratch); + #[cfg(target_os = "macos")] + let result = match result { + TunnResult::WriteToNetwork(wire) + if state.established + && usize::from(driver.config.mtu) + 32 + <= crate::dispatch::DATAGRAM_SEND_BATCH_BYTES + / crate::dispatch::DATAGRAM_SEND_BATCH_LIMIT + && wire.first() == Some(&4) => + { + // Only the existing ready FIFO is drained, at most + // four MTU-bounded ciphertexts and 8 KiB. RX/control + // selection and every original deadline stay outside. + let first = driver.network_datagram(wire, endpoint); + driver + .send_ready_data_batch( + first, + tunn, + endpoint, + transport.as_mut(), + deadline, + &mut state.ingress, + packets, + scratch, + ) + .await?; + continue; + } + other => other, + }; driver .handle( - tunn.encapsulate(packet.data(), scratch), + result, endpoint, transport.as_mut(), deadline, + &mut state.ingress, ) .await?; } @@ -313,10 +663,11 @@ async fn run_peer( if let Ok(next) = update { *driver.updated.lock().unwrap() = Instant::now(); if let Some((next, new)) = next { + state.discard_for_refresh(); let mut old = std::mem::replace(transport, new); endpoint = next; - established = false; - handshake_deadline = command.context.deadline(); + state.established = false; + state.handshake_deadline = command.context.deadline(); driver.ready.send_replace(Ready::Waiting); let _ = tokio::time::timeout(Duration::from_secs(1), old.close()).await; driver @@ -324,7 +675,8 @@ async fn run_peer( tunn.format_handshake_initiation(scratch, true), endpoint, transport.as_mut(), - handshake_deadline, + state.handshake_deadline, + &mut state.ingress, ) .await?; } @@ -333,13 +685,23 @@ async fn run_peer( // a later business call, as in reference updateServerAddr. let _ = command.reply.send(()); } + Event::Ingress(result) => { + // A completed admission owns the only commit; errors keep the + // previous local-drop semantics. The persistent waiter ends here. + let _ = result; + state.ingress = None; + } Event::Timer => { + // Bound RX suspension by a selected existing timer, not a new + // timer or a wall-time promise. Resume control/UDP RX on fallback. + state.discard_for_timer(); driver .handle( tunn.update_timers(scratch), endpoint, transport.as_mut(), deadline, + &mut state.ingress, ) .await?; } @@ -359,3 +721,11 @@ pub(super) fn addresses(packet: &[u8]) -> Option<(IpAddr, IpAddr)> { _ => None, } } + +#[cfg(test)] +#[path = "pending_ingress_memory_tests.rs"] +mod pending_ingress_memory_tests; + +#[cfg(all(test, target_os = "macos"))] +#[path = "connected_factory_memory_tests.rs"] +mod connected_factory_memory_tests; diff --git a/src/outbound/wireguard/pending_ingress_memory_tests.rs b/src/outbound/wireguard/pending_ingress_memory_tests.rs new file mode 100644 index 0000000..4b78a03 --- /dev/null +++ b/src/outbound/wireguard/pending_ingress_memory_tests.rs @@ -0,0 +1,1339 @@ +//! Real Noise and netstack queues; no host sockets or fake raw-RX consumer. +use super::*; +use crate::session::InboundKind; +use futures_util::{future::BoxFuture, task::noop_waker}; +use std::{ + collections::VecDeque, + sync::atomic::{AtomicUsize, Ordering}, + task::{Context, Poll}, +}; +use vole_netstack::{ + ClientAddresses, ClientNetStackParts, NetStack, NetStackConfig, TcpConnector, TcpStream, + UdpDatagram, encode_udp_packet_into, +}; + +fn network(result: TunnResult<'_>) -> Vec { + match result { + TunnResult::WriteToNetwork(bytes) => bytes.to_vec(), + _ => panic!("real Noise output required"), + } +} +fn noise_pair() -> (Tunn, Tunn) { + let mut client = Tunn::new( + x25519::StaticSecret::from([1; 32]), + x25519::PublicKey::from(&x25519::StaticSecret::from([2; 32])), + None, + None, + 1, + None, + ); + let mut server = Tunn::new( + x25519::StaticSecret::from([2; 32]), + x25519::PublicKey::from(&x25519::StaticSecret::from([1; 32])), + None, + None, + 2, + None, + ); + let mut scratch = vec![0; 1440]; + let first = network(client.format_handshake_initiation(&mut scratch, true)); + let response = network(server.decapsulate(None, &first, &mut scratch)); + let keepalive = network(client.decapsulate(None, &response, &mut scratch)); + assert!(matches!( + server.decapsulate(None, &keepalive, &mut scratch), + TunnResult::Done + )); + assert!(client.time_since_last_handshake().is_some()); + (client, server) +} +fn checksum(bytes: &[u8]) -> u16 { + let mut sum = 0_u32; + for pair in bytes.chunks(2) { + sum += u32::from(u16::from_be_bytes([pair[0], *pair.get(1).unwrap_or(&0)])); + } + while sum >> 16 != 0 { + sum = (sum & 0xffff) + (sum >> 16); + } + !u16::try_from(sum).unwrap() +} +fn syn_ack(syn: &Packet) -> Packet { + let syn = syn.data(); + let offset = usize::from(syn[0] & 15) * 4; + assert_eq!(syn[9], 6); + assert_eq!(syn[offset + 13] & 0x17, 2); + let mut bytes = vec![0; 40]; + bytes[0] = 0x45; + bytes[2..4].copy_from_slice(&40_u16.to_be_bytes()); + bytes[4..6].copy_from_slice(&0xbeef_u16.to_be_bytes()); + bytes[8] = 64; + bytes[9] = 6; + bytes[12..16].copy_from_slice(&syn[16..20]); + bytes[16..20].copy_from_slice(&syn[12..16]); + bytes[20..22].copy_from_slice(&syn[offset + 2..offset + 4]); + bytes[22..24].copy_from_slice(&syn[offset..offset + 2]); + bytes[24..28].copy_from_slice(&42_u32.to_be_bytes()); + let sequence = u32::from_be_bytes(syn[offset + 4..offset + 8].try_into().unwrap()); + bytes[28..32].copy_from_slice(&sequence.wrapping_add(1).to_be_bytes()); + bytes[32] = 0x50; + bytes[33] = 0x12; + bytes[34..36].copy_from_slice(&u16::MAX.to_be_bytes()); + let ip_sum = checksum(&bytes[..20]); + bytes[10..12].copy_from_slice(&ip_sum.to_be_bytes()); + let mut pseudo = bytes[12..20].to_vec(); + pseudo.extend_from_slice(&[0, 6, 0, 20]); + pseudo.extend_from_slice(&bytes[20..]); + let tcp_sum = checksum(&pseudo); + bytes[36..38].copy_from_slice(&tcp_sum.to_be_bytes()); + Packet::new(bytes) +} +fn connect(tcp: TcpConnector) -> BoxFuture<'static, std::io::Result> { + Box::pin(async move { + tcp.connect( + "10.0.0.1:443".parse().unwrap(), + Instant::now() + Duration::from_secs(10), + ) + .await + }) +} +async fn until(mut predicate: impl FnMut() -> bool) { + // Predicate is the phase barrier. This finite harness guard prevents a + // paused-time regression from auto-advancing or hanging on a bad fixture. + for _ in 0..4096 { + if predicate() { + return; + } + tokio::task::yield_now().await; + } + panic!("real queue phase did not become ready"); +} + +async fn stop(control: &vole_netstack::NetStackControl) { + tokio::time::timeout(Duration::from_secs(1), control.stop()) + .await + .expect("real stack Stop did not join"); + assert!(control.is_stopped()); +} + +struct WirePeer { + server: Tunn, + endpoint: SocketAddr, + incoming: VecDeque, + sent: Arc, + received: Arc, +} +#[async_trait::async_trait] +impl DatagramTransport for WirePeer { + fn supports_shared_destinations(&self) -> bool { + false + } + fn payload_budget(&self, _: &Destination) -> DatagramBudget { + DatagramBudget::new(1440, 1440) + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { + assert_eq!(datagram.remote, Destination::Ip(self.endpoint)); + let mut scratch = vec![0; 1440]; + match self + .server + .decapsulate(None, &datagram.payload, &mut scratch) + { + TunnResult::Done + | TunnResult::WriteToTunnelV4(..) + | TunnResult::WriteToTunnelV6(..) => {} + _ => panic!("TX must reach the same authenticated Noise peer"), + } + self.sent.fetch_add(1, Ordering::Relaxed); + Ok(()) + } + async fn receive(&mut self) -> Result { + self.received.fetch_add(1, Ordering::Relaxed); + match self.incoming.pop_front() { + Some(datagram) => Ok(datagram), + None => std::future::pending().await, + } + } +} +struct Saturated { + driver: Driver, + client: Tunn, + transport: Box, + state: PeerState, + packets: mpsc::Receiver, + commands: mpsc::Receiver, + _command_owner: mpsc::Sender, + pump: Pin + Send>>, + connects: Vec>>, + control: vole_netstack::NetStackControl, + cancel: CancellationToken, + sent: Arc, + received: Arc, + probe: Arc>, + _udp_slot: Arc, + udp: mpsc::Receiver, +} +async fn saturated() -> Saturated { + let config = Arc::new(super::super::tests::config()); + let routes = Arc::new(Routes::new(&config)); + let ClientNetStackParts { + packet_sink, + mut packet_stream, + tcp_connector, + control, + stats, + } = NetStack::start_client( + NetStackConfig { + mtu: 1408, + packet_queue: 32, + tcp_send_buffer: 64 * 1024, + ..Default::default() + }, + ClientAddresses { + ipv4: config.ipv4, + ipv6: None, + }, + ) + .unwrap(); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + let mut connects = vec![connect(tcp_connector.clone())]; + assert!(connects[0].as_mut().poll(&mut cx).is_pending()); + let first_syn = tokio::time::timeout(Duration::from_secs(1), packet_stream.recv()) + .await + .expect("real stack emitted no initial SYN") + .unwrap(); + let ingress = syn_ack(&first_syn); + for _ in 0..32 { + let mut request = connect(tcp_connector.clone()); + assert!(request.as_mut().poll(&mut cx).is_pending()); + connects.push(request); + } + until(|| stats.snapshot().active_tcp == 33).await; + + let cancel = CancellationToken::new(); + let (channel, packets) = super::super::channel::Channel::memory_ready(cancel.child_token()); + let mut raw = Vec::new(); + encode_udp_packet_into( + &UdpDatagram::new( + "10.0.0.2:20000".parse().unwrap(), + "10.0.0.1:53".parse().unwrap(), + Bytes::from_static(b"tx"), + ), + 1408, + &mut raw, + ) + .unwrap(); + for _ in 0..32 { + channel.tx.try_send(Packet::new(raw.clone())).unwrap(); + } + assert_eq!(channel.tx.capacity(), 0); + let mut pump = Box::pin(super::super::engine::pending_memory_pump( + packet_stream, + channel.clone(), + routes.clone(), + cancel.clone(), + )); + assert!(pump.as_mut().poll(&mut cx).is_pending()); + // Replace the one output slot the blocked pump took, before priming RX. + let mut request = connect(tcp_connector); + assert!(request.as_mut().poll(&mut cx).is_pending()); + connects.push(request); + until(|| stats.snapshot().active_tcp == 34).await; + // One non-pure-ACK waits in RawIpDevice with TX full; the real raw queue + // then admits exactly another 32. No fake receiver clears that queue. + let mut accepted = 0; + until(|| { + while accepted < 33 { + match packet_sink.try_send_recover(ingress.clone()) { + Ok(()) => accepted += 1, + Err((NetStackError::Backpressure, _)) => break, + Err((error, _)) => panic!("unexpected fixture admission: {error}"), + } + } + accepted == 33 + }) + .await; + assert!(matches!( + packet_sink.try_send_recover(ingress.clone()), + Err((NetStackError::Backpressure, _)) + )); + + let (outbound, _, _) = super::super::tests::outbound(false); + let registry = Arc::new(Registry::default()); + let (udp_slot, udp) = registry.memory_open(1200).unwrap(); + let probe = Arc::new(Mutex::new(PendingMemoryCounts::default())); + let (ready, _) = watch::channel(Ready::Established); + let driver = Driver { + config, + index: 0, + upstream: outbound.upstream.clone(), + session: DatagramSession::new(InboundKind::Tun, "192.0.2.1:20000".parse().unwrap()), + cancel: channel.cancel.clone(), + ready, + sink: packet_sink, + registry, + routes, + updated: Arc::new(Mutex::new(Instant::now())), + pending_probe: Some(probe.clone()), + }; + let (mut client, mut server) = noise_pair(); + let mut scratch = vec![0; 1440]; + let encrypted = network(server.encapsulate(ingress.data(), &mut scratch)); + let decoded = client.decapsulate(None, &encrypted, &mut scratch); + assert!(matches!(&decoded, TunnResult::WriteToTunnelV4(..))); + let context = EstablishContext::with_timeout(Duration::from_secs(10)); + let mut state = PeerState::new(context.deadline(), None); + state.established = true; + // Consume the pre-existing immediate initial tick before the staged Full; + // production creates this same interval only after its initial send. + state.timer.tick().await; + let endpoint = "198.51.100.1:51820".parse().unwrap(); + let sent = Arc::new(AtomicUsize::new(0)); + let received = Arc::new(AtomicUsize::new(0)); + let mut udp_raw = Vec::new(); + encode_udp_packet_into( + &UdpDatagram::new( + "10.0.0.1:53".parse().unwrap(), + SocketAddr::new("10.0.0.2".parse().unwrap(), udp_slot.port), + Bytes::from_static(b"udp-after-pending"), + ), + 1408, + &mut udp_raw, + ) + .unwrap(); + let encrypted_udp = network(server.encapsulate(&udp_raw, &mut vec![0; 1440])); + let mut transport: Box = Box::new(WirePeer { + server, + endpoint, + incoming: VecDeque::from([Datagram { + remote: Destination::Ip(endpoint), + payload: Bytes::from(encrypted_udp), + sniffed_domain: None, + }]), + sent: sent.clone(), + received: received.clone(), + }); + let mut handoff = Box::pin(driver.handle( + decoded, + endpoint, + transport.as_mut(), + context.deadline(), + &mut state.ingress, + )); + assert!( + matches!(handoff.as_mut().poll(&mut cx), Poll::Ready(Ok(()))), + "Full handoff must not await stack capacity" + ); + drop(handoff); + assert!(state.ingress.is_some()); + assert_eq!(probe.lock().unwrap().created, 1); + let (command_owner, commands) = mpsc::channel(1); + Saturated { + driver, + client, + transport, + state, + packets, + commands, + _command_owner: command_owner, + pump, + connects, + control, + cancel, + sent, + received, + probe, + _udp_slot: udp_slot, + udp, + } +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn pending_ingress_real_noise_cycle_keeps_tx_progress_and_admits_once() { + let Saturated { + driver, + mut client, + mut transport, + state, + mut packets, + mut commands, + _command_owner, + mut pump, + connects, + control, + cancel, + sent, + received, + probe, + _udp_slot, + mut udp, + } = saturated().await; + let mut scratch = vec![0; 1440]; + let mut normalization = vec![0; 1440]; + let mut worker = Box::pin(run_peer( + &driver, + &mut client, + "198.51.100.1:51820".parse().unwrap(), + &mut transport, + state, + &mut packets, + &mut commands, + &mut scratch, + &mut normalization, + )); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!(worker.as_mut().poll(&mut cx).is_pending()); + assert!( + sent.load(Ordering::Relaxed) > 0, + "real peer TX must run while ingress is still Full" + ); + assert_eq!(probe.lock().unwrap().current, 1); + assert_eq!(probe.lock().unwrap().admitted, 0); + assert_eq!( + received.load(Ordering::Relaxed), + 0, + "outer RX is paused, not dropped or falsely delivered" + ); + let mut resumed = None; + until(|| { + assert!(pump.as_mut().poll(&mut cx).is_pending()); + assert!(worker.as_mut().poll(&mut cx).is_pending()); + if resumed.is_none() { + resumed = udp.try_recv().ok(); + } + probe.lock().unwrap().admitted == 1 && resumed.is_some() + }) + .await; + assert_eq!(probe.lock().unwrap().peak, 1); + assert_eq!(probe.lock().unwrap().current, 0); + assert_eq!(resumed.unwrap().payload.as_ref(), b"udp-after-pending"); + cancel.cancel(); + assert!(worker.as_mut().poll(&mut cx).is_ready()); + drop(worker); + assert!(pump.as_mut().poll(&mut cx).is_ready()); + drop(pump); + drop(connects); + stop(&control).await; + assert_eq!(probe.lock().unwrap().admitted, 1); +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn pending_ingress_original_timer_fallback_resumes_udp_and_stop_releases() { + let Saturated { + driver, + mut client, + mut transport, + state, + mut packets, + mut commands, + _command_owner, + pump, + connects, + control, + cancel, + sent: _, + received, + probe, + _udp_slot, + mut udp, + } = saturated().await; + let mut scratch = vec![0; 1440]; + let mut normalization = vec![0; 1440]; + let mut worker = Box::pin(run_peer( + &driver, + &mut client, + "198.51.100.1:51820".parse().unwrap(), + &mut transport, + state, + &mut packets, + &mut commands, + &mut scratch, + &mut normalization, + )); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!(worker.as_mut().poll(&mut cx).is_pending()); + assert_eq!(probe.lock().unwrap().current, 1); + assert_eq!(received.load(Ordering::Relaxed), 0); + // Leave the real pump parked: TX stays full and raw RX cannot drain. + tokio::time::advance(Duration::from_millis(250)).await; + let mut resumed = None; + until(|| { + assert!(worker.as_mut().poll(&mut cx).is_pending()); + if resumed.is_none() { + resumed = udp.try_recv().ok(); + } + probe.lock().unwrap().timer == 1 && resumed.is_some() + }) + .await; + assert_eq!(probe.lock().unwrap().current, 0); + assert_eq!(probe.lock().unwrap().admitted, 0); + assert_eq!(resumed.unwrap().payload.as_ref(), b"udp-after-pending"); + cancel.cancel(); + assert!(worker.as_mut().poll(&mut cx).is_ready()); + drop(worker); + drop(pump); + drop(connects); + stop(&control).await; +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn pending_ingress_cancel_ready_precedes_tx_and_discards_owned_waiter() { + let Saturated { + driver, + mut client, + mut transport, + state, + mut packets, + mut commands, + _command_owner, + pump, + connects, + control, + cancel, + sent, + received, + probe, + _udp_slot, + udp: _, + } = saturated().await; + let mut scratch = vec![0; 1440]; + let mut normalization = vec![0; 1440]; + let mut worker = Box::pin(run_peer( + &driver, + &mut client, + "198.51.100.1:51820".parse().unwrap(), + &mut transport, + state, + &mut packets, + &mut commands, + &mut scratch, + &mut normalization, + )); + cancel.cancel(); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + assert!(worker.as_mut().poll(&mut cx).is_ready()); + drop(worker); + assert_eq!(sent.load(Ordering::Relaxed), 0); + assert_eq!(received.load(Ordering::Relaxed), 0); + assert_eq!(probe.lock().unwrap().current, 0); + assert_eq!(probe.lock().unwrap().abandoned, 1); + drop(pump); + drop(connects); + stop(&control).await; +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn pending_ingress_same_endpoint_refresh_keeps_original_waiter() { + let Saturated { + driver, + mut client, + mut transport, + state, + mut packets, + mut commands, + _command_owner: command_owner, + pump, + connects, + control, + cancel, + sent: _, + received, + probe, + _udp_slot, + udp: _, + } = saturated().await; + let (reply, mut done) = tokio::sync::oneshot::channel(); + command_owner + .try_send(Refresh { + context: EstablishContext::with_timeout(Duration::from_secs(10)), + reply, + }) + .unwrap(); + let mut scratch = vec![0; 1440]; + let mut normalization = vec![0; 1440]; + let mut worker = Box::pin(run_peer( + &driver, + &mut client, + "198.51.100.1:51820".parse().unwrap(), + &mut transport, + state, + &mut packets, + &mut commands, + &mut scratch, + &mut normalization, + )); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + until(|| { + assert!(worker.as_mut().poll(&mut cx).is_pending()); + done.try_recv().is_ok() + }) + .await; + assert_eq!(probe.lock().unwrap().current, 1); + assert_eq!(probe.lock().unwrap().refresh, 0); + assert_eq!(received.load(Ordering::Relaxed), 0); + cancel.cancel(); + assert!(worker.as_mut().poll(&mut cx).is_ready()); + drop(worker); + assert_eq!(probe.lock().unwrap().current, 0); + assert_eq!(probe.lock().unwrap().abandoned, 1); + drop(pump); + drop(connects); + stop(&control).await; +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn pending_ingress_full_packet_above_configured_mtu_keeps_old_drop_policy() { + let Saturated { + driver, + client: _, + mut transport, + state, + packets: _, + commands: _, + _command_owner, + pump, + connects, + control, + cancel, + sent: _, + received: _, + probe, + _udp_slot, + udp: _, + } = saturated().await; + let mut oversized = vec![0; usize::from(driver.config.mtu) + 1]; + oversized[0] = 0x45; + oversized[12..16].copy_from_slice(&[10, 0, 0, 1]); + oversized[16..20].copy_from_slice(&[10, 0, 0, 2]); + let mut other = None; + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + let mut handoff = Box::pin(driver.handle( + TunnResult::WriteToTunnelV4(&mut oversized, "10.0.0.1".parse().unwrap()), + "198.51.100.1:51820".parse().unwrap(), + transport.as_mut(), + Instant::now() + Duration::from_secs(10), + &mut other, + )); + assert!(matches!( + handoff.as_mut().poll(&mut cx), + Poll::Ready(Ok(())) + )); + drop(handoff); + assert!(other.is_none()); + assert_eq!(probe.lock().unwrap().created, 1); + // Actual replacement uses this same cleanup before transport swap. The + // literal no-op path is exercised separately through the real command. + let mut state = state; + state.discard_for_refresh(); + assert_eq!(probe.lock().unwrap().current, 0); + assert_eq!(probe.lock().unwrap().refresh, 1); + cancel.cancel(); + drop(state); + drop(pump); + drop(connects); + stop(&control).await; +} + +// Established authenticated data; legacy send must finish before semantic RED. +#[cfg(target_os = "macos")] +mod ready_data_batch_memory_tests { + use super::*; + use crate::resources::observation::ResourceProbe; + + struct PhysicalState { + server: Tunn, + emitted: Vec, + singles: usize, + batches: usize, + active: usize, + peak: usize, + close_active: usize, + closes: usize, + invalid: usize, + } + impl PhysicalState { + fn emit(&mut self, packet: Datagram, endpoint: SocketAddr) -> Result<(), DispatchError> { + if packet.remote != Destination::Ip(endpoint) { + self.invalid += 1; + return Err(DispatchError::NotAllowed); + } + let mut scratch = [0_u8; 1440]; + let result = self.server.decapsulate(None, &packet.payload, &mut scratch); + let raw = match result { + TunnResult::WriteToTunnelV4(raw, _) => raw, + _ => { + self.invalid += 1; + return Err(DispatchError::NotAllowed); + } + }; + let Some(udp) = parse_udp_packet_view(raw) else { + self.invalid += 1; + return Err(DispatchError::NotAllowed); + }; + if udp.payload.len() != 1 { + self.invalid += 1; + return Err(DispatchError::NotAllowed); + } + self.emitted.push(udp.payload[0]); + Ok(()) + } + } + struct SendLease(Arc>); + impl Drop for SendLease { + fn drop(&mut self) { + self.0.lock().unwrap().active -= 1; + } + } + struct Physical { + shared: Arc>, + endpoint: SocketAddr, + } + #[async_trait::async_trait] + impl DatagramTransport for Physical { + fn supports_shared_destinations(&self) -> bool { + false + } + fn payload_budget(&self, _: &Destination) -> DatagramBudget { + DatagramBudget::new(1440, 1440) + } + fn send_batch_owned( + &mut self, + packets: Vec, + ) -> Result> { + if packets.len() < 2 + || packets.len() > crate::dispatch::DATAGRAM_SEND_BATCH_LIMIT + || packets.iter().map(|p| p.payload.len()).sum::() + > crate::dispatch::DATAGRAM_SEND_BATCH_BYTES + { + return Err(packets); + } + let shared = self.shared.clone(); + { + let mut state = shared.lock().unwrap(); + state.active += 1; + state.peak = state.peak.max(state.active); + } + let lease = SendLease(shared.clone()); + let endpoint = self.endpoint; + Ok(Box::pin(async move { + let _lease = lease; + let count = packets.len(); + let mut state = shared.lock().unwrap(); + state.batches += 1; + for packet in packets { + state.emit(packet, endpoint).map_err(|_| { + std::io::Error::new(std::io::ErrorKind::InvalidData, "memory Noise packet") + })?; + } + Ok(count) + })) + } + async fn send(&mut self, packet: Datagram) -> Result<(), DispatchError> { + let mut state = self.shared.lock().unwrap(); + state.singles += 1; + // Required old path: authenticate and deliver, never panic for not batching. + state.emit(packet, self.endpoint) + } + async fn receive(&mut self) -> Result { + std::future::pending().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + let mut state = self.shared.lock().unwrap(); + state.close_active = state.active; + state.closes += 1; + Ok(()) + } + } + + #[tokio::test(flavor = "current_thread", start_paused = true)] + async fn wireguard_memory_ready_data_uses_authenticated_batch_after_stop() { + let probe = ResourceProbe::default(); + let observed = probe + .scope(async { + let config = Arc::new(super::super::super::tests::config()); + let routes = Arc::new(Routes::new(&config)); + let ClientNetStackParts { + packet_sink, + packet_stream, + control, + .. + } = NetStack::start_client( + NetStackConfig { + mtu: 1408, + packet_queue: 32, + ..Default::default() + }, + ClientAddresses { + ipv4: config.ipv4, + ipv6: None, + }, + ) + .unwrap(); + let cancel = CancellationToken::new(); + let (packets_tx, mut packets) = mpsc::channel(32); + let (commands_tx, mut commands) = mpsc::channel(1); + let (ready, _ready_rx) = watch::channel(Ready::Established); + let (outbound, _, _) = super::super::super::tests::outbound(false); + let driver = Driver { + config, + index: 0, + upstream: outbound.upstream.clone(), + session: DatagramSession::new( + InboundKind::Tun, + "192.0.2.1:20000".parse().unwrap(), + ), + cancel: cancel.clone(), + ready, + sink: packet_sink, + registry: Arc::new(Registry::default()), + routes, + updated: Arc::new(Mutex::new(Instant::now())), + pending_probe: None, + }; + let (mut client, server) = noise_pair(); + let shared = Arc::new(Mutex::new(PhysicalState { + server, + emitted: Vec::new(), + singles: 0, + batches: 0, + active: 0, + peak: 0, + close_active: 0, + closes: 0, + invalid: 0, + })); + let endpoint = "198.51.100.1:51820".parse().unwrap(); + let mut transport: Box = Box::new(Physical { + shared: shared.clone(), + endpoint, + }); + // The four raw data packets are already ready, not supplied by a fill timer. + for sequence in 0_u8..4 { + let mut raw = Vec::new(); + encode_udp_packet_into( + &UdpDatagram::new( + "10.0.0.2:20000".parse().unwrap(), + "10.0.0.1:53".parse().unwrap(), + Bytes::copy_from_slice(&[sequence]), + ), + 1408, + &mut raw, + ) + .unwrap(); + packets_tx.try_send(Packet::new(raw)).unwrap(); + } + let mut state = PeerState::new(Instant::now() + Duration::from_secs(10), None); + state.established = true; // Both real Noise endpoints completed noise_pair(). + state.timer.tick().await; + let mut scratch = [0_u8; 1440]; + let mut normalization = [0_u8; 1440]; + let mut worker = Box::pin(run_peer( + &driver, + &mut client, + endpoint, + &mut transport, + state, + &mut packets, + &mut commands, + &mut scratch, + &mut normalization, + )); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + let mut ended = false; + for _ in 0..64 { + if worker.as_mut().poll(&mut cx).is_ready() { + ended = true; + break; + } + if shared.lock().unwrap().emitted.len() == 4 { + break; + } + tokio::task::yield_now().await; + } + cancel.cancel(); + let cancelled = ended || worker.as_mut().poll(&mut cx).is_ready(); + drop(worker); // Drop all owned sends before physical close. + let close_ok = transport.close().await.is_ok(); + drop(transport); + drop(driver); + drop(packets_tx); + drop(commands_tx); + drop(packet_stream); + drop(outbound); + stop(&control).await; + let state = shared.lock().unwrap(); + ( + state.emitted.clone(), + state.singles, + state.batches, + state.active, + state.peak, + state.close_active, + state.closes, + state.invalid, + cancelled, + close_ok, + ) + }) + .await; + // All semantic assertions follow cancellation, physical close and real stack Stop/join. + assert!(probe.snapshot().is_idle()); + assert!(observed.8 && observed.9); + assert_eq!( + (observed.3, observed.5, observed.6, observed.7), + (0, 0, 1, 0) + ); + assert_eq!( + observed.0, + [0, 1, 2, 3], + "real authenticated data must arrive once in FIFO order" + ); + assert!(observed.4 <= 1, "at most one physical send owner"); + assert!( + observed.2 > 0, + "already-ready established data never used the existing batch path" + ); + assert_eq!( + observed.1, 0, + "a fully confirmed ready batch needs no ordinary retransmission" + ); + } + + #[derive(Clone, Copy, PartialEq, Eq)] + enum ControlCase { + Short, + Unsupported, + ErrorAfterPrefix, + Cancel, + Deadline, + HighMtu, + Control, + Single, + } + #[derive(Default)] + struct ControlFacts { + attempts: usize, + submitted: Vec<(u64, usize)>, + ordinary: Vec<(u64, usize)>, + submitted_bytes: Vec>, + ordinary_bytes: Vec>, + controls: usize, + } + struct Controlled { + physical: Physical, + case: ControlCase, + facts: Arc>, + } + fn wire_id(packet: &Datagram) -> (u64, usize) { + let counter = packet + .payload + .get(8..16) + .and_then(|b| b.try_into().ok()) + .map(u64::from_le_bytes) + .unwrap_or(u64::MAX); + (counter, packet.payload.as_ptr() as usize) + } + #[async_trait::async_trait] + impl DatagramTransport for Controlled { + fn supports_shared_destinations(&self) -> bool { + false + } + fn payload_budget(&self, _: &Destination) -> DatagramBudget { + DatagramBudget::new(4096, 4096) + } + fn send_batch_owned( + &mut self, + packets: Vec, + ) -> Result> { + self.facts.lock().unwrap().attempts += 1; + if self.case == ControlCase::Unsupported { + return Err(packets); + } + let shared = self.physical.shared.clone(); + { + let mut state = shared.lock().unwrap(); + state.active += 1; + state.peak = state.peak.max(state.active); + } + let lease = SendLease(shared.clone()); + let facts = self.facts.clone(); + let endpoint = self.physical.endpoint; + let case = self.case; + Ok(Box::pin(async move { + let _lease = lease; + if !(2..=crate::dispatch::DATAGRAM_SEND_BATCH_LIMIT).contains(&packets.len()) + || packets.iter().map(|p| p.payload.len()).sum::() + > crate::dispatch::DATAGRAM_SEND_BATCH_BYTES + { + return Err(std::io::ErrorKind::InvalidData.into()); + } + { + let mut recorded = facts.lock().unwrap(); + if recorded.submitted.len() + packets.len() > 16 { + return Err(std::io::ErrorKind::InvalidData.into()); + } + recorded.submitted.extend(packets.iter().map(wire_id)); + recorded + .submitted_bytes + .extend(packets.iter().map(|p| p.payload.to_vec())); + } + shared.lock().unwrap().batches += 1; + if matches!(case, ControlCase::Cancel | ControlCase::Deadline) { + std::future::pending::<()>().await; + } + let count = if matches!(case, ControlCase::Short | ControlCase::ErrorAfterPrefix) { + packets.len().min(2) + } else { + packets.len() + }; + let mut state = shared.lock().unwrap(); + for packet in packets.into_iter().take(count) { + state.emit(packet, endpoint).map_err(|_| { + std::io::Error::new(std::io::ErrorKind::InvalidData, "memory Noise packet") + })?; + } + if case == ControlCase::ErrorAfterPrefix { + // Physical acceptance happened, but no successful prefix is reported. + return Err(std::io::ErrorKind::Other.into()); + } + Ok(count) + })) + } + async fn send(&mut self, packet: Datagram) -> Result<(), DispatchError> { + if packet.payload.first() != Some(&4) { + let mut state = self.physical.shared.lock().unwrap(); + let mut scratch = [0_u8; 1440]; + let accepted = matches!( + state.server.decapsulate(None, &packet.payload, &mut scratch), + TunnResult::WriteToNetwork(reply) if reply.first() == Some(&2) + ); + state.singles += 1; + if !accepted { + state.invalid += 1; + return Err(DispatchError::NotAllowed); + } + self.facts.lock().unwrap().controls += 1; + return Ok(()); + } + { + let mut facts = self.facts.lock().unwrap(); + if facts.ordinary.len() >= 16 { + return Err(DispatchError::NotAllowed); + } + facts.ordinary.push(wire_id(&packet)); + facts.ordinary_bytes.push(packet.payload.to_vec()); + } + self.physical.send(packet).await + } + async fn receive(&mut self) -> Result { + std::future::pending().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.physical.close().await + } + } + struct ControlResult { + emitted: Vec, + singles: usize, + batches: usize, + before_stop: usize, + ended_before_cancel: bool, + timed_out: bool, + attempts: usize, + submitted: Vec<(u64, usize)>, + ordinary: Vec<(u64, usize)>, + submitted_bytes: Vec>, + ordinary_bytes: Vec>, + controls: usize, + } + async fn controlled_case(case: ControlCase) -> ControlResult { + let probe = ResourceProbe::default(); + let result = probe + .scope(async { + let mut raw_config = super::super::super::tests::config(); + if case == ControlCase::HighMtu { + raw_config.mtu = 2017; + } + let mtu = usize::from(raw_config.mtu); + let config = Arc::new(raw_config); + let routes = Arc::new(Routes::new(&config)); + let ClientNetStackParts { + packet_sink, + packet_stream, + control, + .. + } = NetStack::start_client( + NetStackConfig { + mtu, + packet_queue: 32, + ..Default::default() + }, + ClientAddresses { + ipv4: config.ipv4, + ipv6: None, + }, + ) + .unwrap(); + let cancel = CancellationToken::new(); + let (packets_tx, mut packets) = mpsc::channel(32); + let (commands_tx, mut commands) = mpsc::channel(1); + let (ready, _ready_rx) = watch::channel(Ready::Established); + let (outbound, _, _) = super::super::super::tests::outbound(false); + let driver = Driver { + config, + index: 0, + upstream: outbound.upstream.clone(), + session: DatagramSession::new( + InboundKind::Tun, + "192.0.2.1:20000".parse().unwrap(), + ), + cancel: cancel.clone(), + ready, + sink: packet_sink, + registry: Arc::new(Registry::default()), + routes, + updated: Arc::new(Mutex::new(Instant::now())), + pending_probe: None, + }; + let (mut client, server) = noise_pair(); + let shared = Arc::new(Mutex::new(PhysicalState { + server, + emitted: Vec::new(), + singles: 0, + batches: 0, + active: 0, + peak: 0, + close_active: 0, + closes: 0, + invalid: 0, + })); + let facts = Arc::new(Mutex::new(ControlFacts::default())); + let endpoint = "198.51.100.1:51820".parse().unwrap(); + let mut transport: Box = Box::new(Controlled { + physical: Physical { + shared: shared.clone(), + endpoint, + }, + case, + facts: facts.clone(), + }); + let count = if case == ControlCase::Single { 1 } else { 4 }; + let mut scratch = vec![0_u8; mtu + 32]; + let mut normalization = vec![0_u8; mtu + 32]; + let mut ended_before_cancel = false; + let mut timed_out = false; + let before_stop; + let cancelled; + if case == ControlCase::Control { + // Real authenticated peer accepts a forced Noise initiation. + // It is the existing direct control path, not a fake DATA tag. + let result = driver + .handle( + client.format_handshake_initiation(&mut scratch, true), + endpoint, + transport.as_mut(), + Instant::now() + DEFAULT_ESTABLISH_TIMEOUT, + &mut None, + ) + .await; + ended_before_cancel = result.is_err(); + before_stop = shared.lock().unwrap().active; + cancel.cancel(); + cancelled = true; + } else { + for sequence in 0_u8..count { + let mut raw = Vec::new(); + encode_udp_packet_into( + &UdpDatagram::new( + "10.0.0.2:20000".parse().unwrap(), + "10.0.0.1:53".parse().unwrap(), + Bytes::copy_from_slice(&[sequence]), + ), + mtu, + &mut raw, + ) + .unwrap(); + packets_tx.try_send(Packet::new(raw)).unwrap(); + } + let mut state = PeerState::new(Instant::now() + Duration::from_secs(10), None); + state.established = true; + state.timer.tick().await; + let mut worker = Box::pin(run_peer( + &driver, + &mut client, + endpoint, + &mut transport, + state, + &mut packets, + &mut commands, + &mut scratch, + &mut normalization, + )); + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + for _ in 0..64 { + if let Poll::Ready(result) = worker.as_mut().poll(&mut cx) { + ended_before_cancel = true; + timed_out = matches!(result, Err(DispatchError::TimedOut)); + break; + } + let ready = { + let state = shared.lock().unwrap(); + state.emitted.len() == usize::from(count) + || (matches!(case, ControlCase::Cancel | ControlCase::Deadline) + && state.active == 1 + && state.batches > 0) + }; + if ready { + break; + } + tokio::task::yield_now().await; + } + before_stop = shared.lock().unwrap().active; + if case == ControlCase::Deadline && !ended_before_cancel { + tokio::time::advance(DEFAULT_ESTABLISH_TIMEOUT + Duration::from_millis(1)) + .await; + for _ in 0..64 { + if let Poll::Ready(result) = worker.as_mut().poll(&mut cx) { + ended_before_cancel = true; + timed_out = matches!(result, Err(DispatchError::TimedOut)); + break; + } + tokio::task::yield_now().await; + } + } + cancel.cancel(); + cancelled = ended_before_cancel || worker.as_mut().poll(&mut cx).is_ready(); + drop(worker); + } + let close_ok = transport.close().await.is_ok(); + drop(transport); + drop(driver); + drop(packets_tx); + drop(commands_tx); + drop(packet_stream); + drop(outbound); + stop(&control).await; + let state = shared.lock().unwrap(); + let facts = facts.lock().unwrap(); + let observed = ControlResult { + emitted: state.emitted.clone(), + singles: state.singles, + batches: state.batches, + before_stop, + ended_before_cancel, + timed_out, + attempts: facts.attempts, + submitted: facts.submitted.clone(), + ordinary: facts.ordinary.clone(), + submitted_bytes: facts.submitted_bytes.clone(), + ordinary_bytes: facts.ordinary_bytes.clone(), + controls: facts.controls, + }; + ( + observed, + ( + state.active, + state.peak, + state.close_active, + state.closes, + state.invalid, + ), + cancelled, + close_ok, + ) + }) + .await; + // Every branch drops the actual operation, closes carrier and joins stack first. + assert!(probe.snapshot().is_idle()); + assert!(result.2 && result.3); + assert_eq!( + (result.1.0, result.1.2, result.1.3, result.1.4), + (0, 0, 1, 0) + ); + assert!(result.1.1 <= 1); + result.0 + } + #[tokio::test(flavor = "current_thread", start_paused = true)] + async fn wireguard_memory_ready_batch_short_prefix_keeps_original_ciphertext_suffix() { + let got = controlled_case(ControlCase::Short).await; + assert_eq!(got.emitted, [0, 1, 2, 3]); + assert_eq!((got.batches, got.singles), (1, 2)); + assert_eq!(got.submitted.len(), 4); + assert_eq!( + got.ordinary, + got.submitted[2..], + "unsent suffix was copied or re-encapsulated" + ); + assert_eq!( + got.ordinary_bytes, + got.submitted_bytes[2..], + "original ciphertext suffix bytes changed" + ); + } + #[tokio::test(flavor = "current_thread", start_paused = true)] + async fn wireguard_memory_ready_batch_unsupported_and_single_keep_ordinary_fifo() { + let unsupported = controlled_case(ControlCase::Unsupported).await; + let single = controlled_case(ControlCase::Single).await; + assert_eq!(unsupported.emitted, [0, 1, 2, 3]); + assert_eq!( + ( + unsupported.attempts, + unsupported.batches, + unsupported.singles + ), + (1, 0, 4) + ); + assert_eq!(single.emitted, [0]); + assert_eq!((single.attempts, single.batches, single.singles), (0, 0, 1)); + } + #[tokio::test(flavor = "current_thread", start_paused = true)] + async fn wireguard_memory_ready_batch_error_after_physical_prefix_never_replays() { + let got = controlled_case(ControlCase::ErrorAfterPrefix).await; + assert!(got.ended_before_cancel && !got.timed_out); + assert_eq!(got.emitted, [0, 1]); + assert_eq!((got.batches, got.singles, got.ordinary.len()), (1, 0, 0)); + } + #[tokio::test(flavor = "current_thread", start_paused = true)] + async fn wireguard_memory_ready_batch_cancel_and_deadline_drop_owner_before_close() { + let cancelled = controlled_case(ControlCase::Cancel).await; + let deadline = controlled_case(ControlCase::Deadline).await; + assert_eq!((cancelled.before_stop, deadline.before_stop), (1, 1)); + assert!(cancelled.emitted.is_empty() && deadline.emitted.is_empty()); + assert_eq!( + ( + cancelled.batches, + deadline.batches, + cancelled.singles, + deadline.singles + ), + (1, 1, 0, 0) + ); + assert!(deadline.ended_before_cancel && deadline.timed_out); + } + #[tokio::test(flavor = "current_thread", start_paused = true)] + async fn wireguard_memory_ready_batch_large_mtu_and_control_are_never_batched() { + let large = controlled_case(ControlCase::HighMtu).await; + let control = controlled_case(ControlCase::Control).await; + assert_eq!(large.emitted, [0, 1, 2, 3]); + assert_eq!((large.attempts, large.batches, large.singles), (0, 0, 4)); + assert!(!control.ended_before_cancel && control.emitted.is_empty()); + assert_eq!( + ( + control.attempts, + control.batches, + control.singles, + control.controls + ), + (0, 0, 1, 1) + ); + } +} + +#[cfg(target_os = "macos")] +#[path = "ready_receive_memory_tests.rs"] +mod ready_receive_memory_tests; diff --git a/src/outbound/wireguard/ready_receive_memory_tests.rs b/src/outbound/wireguard/ready_receive_memory_tests.rs new file mode 100644 index 0000000..57f98e0 --- /dev/null +++ b/src/outbound/wireguard/ready_receive_memory_tests.rs @@ -0,0 +1,263 @@ +//! New private-helper contracts, not a deterministic old-source RED. +//! The real Noise/stack fixture is shared with existing PendingIngress controls. +use super::*; +use futures_util::task::{ArcWake, waker}; + +#[derive(Default)] +struct WakeCount(AtomicUsize); +impl ArcWake for WakeCount { + fn wake_by_ref(owner: &Arc) { + owner.0.fetch_add(1, Ordering::Relaxed); + } +} +#[derive(Default)] +struct ReceiveFacts { + polls: usize, + drops: usize, + closes: usize, + remaining: usize, + original_context: bool, +} +struct ReceiveDrop(Arc>); +impl Drop for ReceiveDrop { + fn drop(&mut self) { + self.0.lock().unwrap().drops += 1; + } +} +struct ReadyReceive { + incoming: VecDeque, + facts: Arc>, + expected_waker: Option, +} +#[async_trait::async_trait] +impl DatagramTransport for ReadyReceive { + fn supports_shared_destinations(&self) -> bool { + false + } + async fn send(&mut self, _: Datagram) -> Result<(), DispatchError> { + Err(DispatchError::NotAllowed) + } + async fn receive(&mut self) -> Result { + let _owner = ReceiveDrop(self.facts.clone()); + std::future::poll_fn(|context| { + let mut facts = self.facts.lock().unwrap(); + facts.polls += 1; + facts.original_context = self + .expected_waker + .as_ref() + .is_none_or(|expected| context.waker().will_wake(expected)); + match self.incoming.pop_front() { + Some(datagram) => Poll::Ready(Ok(datagram)), + None => Poll::Pending, + } + }) + .await + } + async fn close(&mut self) -> Result<(), DispatchError> { + let mut facts = self.facts.lock().unwrap(); + facts.closes += 1; + facts.remaining = self.incoming.len(); + Ok(()) + } +} + +#[tokio::test(flavor = "current_thread")] +async fn wireguard_memory_ready_rx_single_poll_keeps_context_and_drops_pending() { + let facts = Arc::new(Mutex::new(ReceiveFacts::default())); + let wake_count = Arc::new(WakeCount::default()); + let original_waker = waker(wake_count.clone()); + let mut context = Context::from_waker(&original_waker); + let mut transport: Box = Box::new(ReadyReceive { + incoming: VecDeque::new(), + facts: facts.clone(), + expected_waker: Some(original_waker.clone()), + }); + // Construction is not a poll. A single actual helper poll observes inner + // Pending and drops that receive wrapper without waiting or self-waking. + let unpolled = Box::pin(poll_ready_datagram(&mut transport)); + drop(unpolled); + let before = facts.lock().unwrap().polls; + let mut operation = Box::pin(poll_ready_datagram(&mut transport)); + let observed = operation.as_mut().poll(&mut context); + drop(operation); + let closed = transport.close().await.is_ok(); + drop(transport); + let facts = facts.lock().unwrap(); + assert!(closed && matches!(observed, Poll::Ready(Poll::Pending))); + assert_eq!( + (before, facts.polls, facts.drops, facts.closes), + (0, 1, 1, 1) + ); + assert!(facts.original_context); + assert_eq!(wake_count.0.load(Ordering::Relaxed), 0); +} + +#[tokio::test(flavor = "current_thread", start_paused = true)] +async fn wireguard_memory_ready_rx_real_noise_cap_and_ingress_cancel_boundaries() { + let resource_probe = crate::resources::observation::ResourceProbe::default(); + let observed = resource_probe + .scope(async { + let mut fixture = saturated().await; + let pending = fixture.state.ingress.take(); + let (mut client, mut server) = noise_pair(); + let endpoint: SocketAddr = "198.51.100.1:51820".parse().unwrap(); + let mut scratch = vec![0; 1440]; + let mut normalization = vec![0; 1440]; + let mut incoming = VecDeque::new(); + for sequence in 0_u8..5 { + let mut raw = Vec::new(); + if sequence != 2 { + encode_udp_packet_into( + &UdpDatagram::new( + "10.0.0.1:53".parse().unwrap(), + SocketAddr::new("10.0.0.2".parse().unwrap(), fixture._udp_slot.port), + Bytes::from(vec![sequence]), + ), + 1408, + &mut raw, + ) + .unwrap(); + } + let encrypted = network(server.encapsulate(&raw, &mut scratch)); + incoming.push_back(Datagram { + // Wrong endpoint and a genuine encrypted keepalive must both + // consume one slot of the same three-extra-packet quantum. + remote: Destination::Ip(if sequence == 1 { + "198.51.100.2:51820".parse().unwrap() + } else { + endpoint + }), + payload: Bytes::from(encrypted), + sniffed_domain: None, + }); + } + let first = incoming.pop_front().unwrap(); + let facts = Arc::new(Mutex::new(ReceiveFacts::default())); + let mut transport: Box = Box::new(ReadyReceive { + incoming, + facts: facts.clone(), + expected_waker: None, + }); + let deadline = fixture.state.handshake_deadline; + // Invoke the actual production first-packet handler, then its exact + // extra-ready helper. This is a helper contract, not select RNG proof. + let first_ok = handle_peer_datagram( + &fixture.driver, + &mut client, + endpoint, + &mut transport, + &mut fixture.state, + deadline, + &mut scratch, + &mut normalization, + first, + ) + .await + .is_ok(); + let burst_ok = drain_ready_datagrams( + &fixture.driver, + &mut client, + endpoint, + &mut transport, + &mut fixture.state, + deadline, + &mut scratch, + &mut normalization, + ) + .await + .is_ok(); + let mut delivered = Vec::new(); + while let Ok(datagram) = fixture.udp.try_recv() { + delivered.push(datagram.payload.to_vec()); + } + let after_burst = facts.lock().unwrap().polls; + fixture.state.ingress = pending; + let blocked_ok = drain_ready_datagrams( + &fixture.driver, + &mut client, + endpoint, + &mut transport, + &mut fixture.state, + deadline, + &mut scratch, + &mut normalization, + ) + .await + .is_ok(); + let after_ingress = facts.lock().unwrap().polls; + let retained = fixture.state.ingress.is_some(); + drop(fixture.state.ingress.take()); + fixture.state.established = false; + let unestablished_ok = drain_ready_datagrams( + &fixture.driver, + &mut client, + endpoint, + &mut transport, + &mut fixture.state, + deadline, + &mut scratch, + &mut normalization, + ) + .await + .is_ok(); + let after_unestablished = facts.lock().unwrap().polls; + fixture.state.established = true; + fixture.cancel.cancel(); + let cancelled = matches!( + drain_ready_datagrams( + &fixture.driver, + &mut client, + endpoint, + &mut transport, + &mut fixture.state, + deadline, + &mut scratch, + &mut normalization, + ) + .await, + Err(DispatchError::ConnectionRefused) + ); + let closed = transport.close().await.is_ok(); + drop(transport); + let original_closed = fixture.transport.close().await.is_ok(); + drop(fixture.pump); + drop(fixture.connects); + stop(&fixture.control).await; + let facts = facts.lock().unwrap(); + ( + first_ok, + burst_ok, + blocked_ok, + unestablished_ok, + cancelled, + closed && original_closed, + retained, + delivered, + after_burst, + after_ingress, + after_unestablished, + facts.polls, + facts.drops, + facts.closes, + facts.remaining, + ) + }) + .await; + // Every semantic assertion is after carrier close and real stack Stop/join. + assert!(resource_probe.snapshot().is_idle()); + assert!( + observed.0 + && observed.1 + && observed.2 + && observed.3 + && observed.4 + && observed.5 + && observed.6 + ); + assert_eq!(observed.7, vec![vec![0], vec![3]]); + assert_eq!( + (observed.8, observed.9, observed.10, observed.11), + (3, 3, 3, 3) + ); + assert_eq!((observed.12, observed.13, observed.14), (3, 1, 1)); +} diff --git a/src/platform/apple_runtime_qos.rs b/src/platform/apple_runtime_qos.rs new file mode 100644 index 0000000..a02c383 --- /dev/null +++ b/src/platform/apple_runtime_qos.rs @@ -0,0 +1,239 @@ +//! Best-effort public Apple QoS on fresh Core-owned runtime threads only. +use libc::{c_int, c_uint}; + +const USER_INITIATED: c_uint = 0x19; +unsafe extern "C" { + fn pthread_set_qos_class_self_np(class: c_uint, relative_priority: c_int) -> c_int; + #[cfg(any(test, feature = "http-diagnostics"))] + fn pthread_get_qos_class_np( + thread: libc::pthread_t, + class: *mut c_uint, + relative: *mut c_int, + ) -> c_int; +} + +#[derive(Clone, Copy)] +pub(crate) enum Role { + EngineOwner, + Tokio, +} + +/// Only call from the engine's fresh std-thread closure or Tokio start hook. +/// No caller/host thread is promoted, and this never affects startup success. +pub(crate) fn request(role: Role) { + #[cfg(any(test, feature = "http-diagnostics"))] + let before = requested(); + // SAFETY: public current-thread API; SDK USER_INITIATED and relative zero. + // Callers own this fresh thread until real engine/runtime shutdown joins it. + let code = unsafe { pthread_set_qos_class_self_np(USER_INITIATED, 0) }; + #[cfg(any(test, feature = "http-diagnostics"))] + stats(role).record(before, code, requested()); + #[cfg(not(any(test, feature = "http-diagnostics")))] + let _ = (role, code); +} + +#[cfg(any(test, feature = "http-diagnostics"))] +#[derive(Clone, Copy)] +struct Requested { + code: c_int, + value: Option<(c_uint, c_int)>, +} + +#[cfg(any(test, feature = "http-diagnostics"))] +fn requested() -> Requested { + let (mut class, mut relative) = (0, 0); + // SAFETY: pthread_self is this live owned thread, outputs are valid scalars. + let code = unsafe { pthread_get_qos_class_np(libc::pthread_self(), &mut class, &mut relative) }; + Requested { + code, + value: (code == 0).then_some((class, relative)), + } +} + +#[cfg(any(test, feature = "http-diagnostics"))] +use std::sync::atomic::{AtomicI32, AtomicU64, Ordering}; + +#[cfg(any(test, feature = "http-diagnostics"))] +struct Stats { + requests: AtomicU64, + succeeded: AtomicU64, + failed: AtomicU64, + before_error: AtomicU64, + after_error: AtomicU64, + verified: AtomicU64, + last_set_code: AtomicI32, + last_failed_set_code: AtomicI32, + before_classes: [AtomicU64; 7], + after_classes: [AtomicU64; 7], +} + +#[cfg(any(test, feature = "http-diagnostics"))] +impl Stats { + const fn new() -> Self { + Self { + requests: AtomicU64::new(0), + succeeded: AtomicU64::new(0), + failed: AtomicU64::new(0), + before_error: AtomicU64::new(0), + after_error: AtomicU64::new(0), + verified: AtomicU64::new(0), + last_set_code: AtomicI32::new(0), + last_failed_set_code: AtomicI32::new(0), + before_classes: [const { AtomicU64::new(0) }; 7], + after_classes: [const { AtomicU64::new(0) }; 7], + } + } + fn class(query: Requested, errors: &AtomicU64, classes: &[AtomicU64; 7]) { + if query.code != 0 || query.value.is_none() { + errors.fetch_add(1, Ordering::Relaxed); + return; + } + let index = match query.value.map(|value| value.0) { + Some(0) => 0, + Some(9) => 1, + Some(17) => 2, + Some(21) => 3, + Some(25) => 4, + Some(33) => 5, + _ => 6, + }; + classes[index].fetch_add(1, Ordering::Relaxed); + } + fn record(&self, before: Requested, code: c_int, after: Requested) { + // The API returns errno directly; never sample last_os_error here. + self.last_set_code.store(code, Ordering::Relaxed); + if code != 0 { + self.last_failed_set_code.store(code, Ordering::Relaxed); + } + self.requests.fetch_add(1, Ordering::Relaxed); + let counter = if code == 0 { + &self.succeeded + } else { + &self.failed + }; + counter.fetch_add(1, Ordering::Relaxed); + Self::class(before, &self.before_error, &self.before_classes); + Self::class(after, &self.after_error, &self.after_classes); + if code == 0 && after.code == 0 && after.value == Some((USER_INITIATED, 0)) { + self.verified.fetch_add(1, Ordering::Relaxed); + } + } + #[cfg(feature = "http-diagnostics")] + fn snapshot(&self) -> serde_json::Value { + let load = |value: &AtomicU64| value.load(Ordering::Relaxed); + let classes = |values: &[AtomicU64; 7]| { + serde_json::json!({ + "unspecified":load(&values[0]), "background":load(&values[1]), "utility":load(&values[2]), + "default":load(&values[3]), "userInitiated":load(&values[4]), + "userInteractive":load(&values[5]), "other":load(&values[6])}) + }; + serde_json::json!({"requests":load(&self.requests), "setSucceeded":load(&self.succeeded), + "setFailed":load(&self.failed), "beforeQueryFailed":load(&self.before_error), + "afterQueryFailed":load(&self.after_error), "verifiedRequestedAfterSet":load(&self.verified), + "lastSetReturnCode":(load(&self.requests) != 0).then(|| self.last_set_code.load(Ordering::Relaxed)), + "lastFailedSetReturnCode":(load(&self.failed) != 0).then(|| self.last_failed_set_code.load(Ordering::Relaxed)), + "beforeRequestedClasses":classes(&self.before_classes), "afterRequestedClasses":classes(&self.after_classes)}) + } +} + +#[cfg(any(test, feature = "http-diagnostics"))] +fn stats(role: Role) -> &'static Stats { + static OWNER: Stats = Stats::new(); + static TOKIO: Stats = Stats::new(); + match role { + Role::EngineOwner => &OWNER, + Role::Tokio => &TOKIO, + } +} + +#[cfg(feature = "http-diagnostics")] +pub(crate) fn snapshot() -> serde_json::Value { + serde_json::json!({"enabled":true, "targetRequestedClass":USER_INITIATED, + "targetRequestedRelativePriority":0, "effectiveClassAvailable":false, "cpuPlacementAvailable":false, + "scope":"fresh Core engine owner and its Tokio threads only; excludes host/caller, preparation, current-thread measurements and disposable script owners", + "units":"process-lifetime fixed counts; before/after requested-class histograms; quiescent snapshots required for conservation", + "engineOwner":stats(Role::EngineOwner).snapshot(), "tokioThreads":stats(Role::Tokio).snapshot()}) +} + +#[cfg(test)] +mod tests { + use super::*; + fn current() -> (c_int, Option<(c_uint, c_int)>) { + let observation = requested(); + (observation.code, observation.value) + } + + #[test] + fn owned_thread_request_preserves_the_host_calling_thread() { + let caller = current(); + assert_eq!(caller.0, 0); + std::thread::spawn(|| { + request(Role::EngineOwner); + assert_eq!(current(), (0, Some((USER_INITIATED, 0)))); + }) + .join() + .unwrap(); + assert_eq!(current(), caller); + } + + #[test] + fn runtime_hook_covers_scheduler_and_blocking_threads_without_promoting_the_caller() { + let caller = current(); + assert_eq!(caller.0, 0); + let runtime = crate::invoke::engine_runtime_builder() + .worker_threads(1) + .max_blocking_threads(2) + .enable_all() + .build() + .unwrap(); + runtime.block_on(async { + assert_eq!( + tokio::spawn(async { current() }).await.unwrap(), + (0, Some((USER_INITIATED, 0))) + ); + assert_eq!( + tokio::task::spawn_blocking(current).await.unwrap(), + (0, Some((USER_INITIATED, 0))) + ); + assert_eq!(current(), caller); + }); + drop(runtime); + assert_eq!(current(), caller); + } + + fn query(code: c_int, value: Option<(c_uint, c_int)>) -> Requested { + Requested { code, value } + } + #[test] + fn successful_request_requires_a_successful_target_getter() { + let stats = Stats::new(); + stats.record( + query(0, Some((21, 0))), + 0, + query(0, Some((USER_INITIATED, 0))), + ); + assert_eq!(stats.requests.load(Ordering::Relaxed), 1); + assert_eq!(stats.verified.load(Ordering::Relaxed), 1); + assert_eq!(stats.before_classes[3].load(Ordering::Relaxed), 1); + assert_eq!(stats.after_classes[4].load(Ordering::Relaxed), 1); + } + #[test] + fn failure_or_getter_error_never_becomes_verified_success() { + let stats = Stats::new(); + stats.record(query(5, None), 22, query(0, Some((USER_INITIATED, 0)))); + stats.record(query(0, Some((21, 0))), 0, query(5, None)); + stats.record( + query(0, Some((21, 0))), + 0, + query(0, Some((USER_INITIATED, -1))), + ); + assert_eq!(stats.requests.load(Ordering::Relaxed), 3); + assert_eq!(stats.succeeded.load(Ordering::Relaxed), 2); + assert_eq!(stats.failed.load(Ordering::Relaxed), 1); + assert_eq!(stats.before_error.load(Ordering::Relaxed), 1); + assert_eq!(stats.after_error.load(Ordering::Relaxed), 1); + assert_eq!(stats.verified.load(Ordering::Relaxed), 0); + assert_eq!(stats.last_set_code.load(Ordering::Relaxed), 0); + assert_eq!(stats.last_failed_set_code.load(Ordering::Relaxed), 22); + } +} diff --git a/src/platform/mod.rs b/src/platform/mod.rs index 47343a7..180c0db 100644 --- a/src/platform/mod.rs +++ b/src/platform/mod.rs @@ -3,6 +3,11 @@ any(target_os = "ios", target_os = "tvos", target_os = "macos") ))] pub(crate) mod apple_logging; +#[cfg(all( + feature = "invoke", + any(target_os = "ios", target_os = "tvos", target_os = "macos") +))] +pub(crate) mod apple_runtime_qos; #[cfg(all(feature = "tun", any(target_os = "linux", test)))] #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub(crate) mod linux_network; diff --git a/src/platform/tun_rs_io.rs b/src/platform/tun_rs_io.rs index 6829347..3bd6236 100644 --- a/src/platform/tun_rs_io.rs +++ b/src/platform/tun_rs_io.rs @@ -2,7 +2,10 @@ use std::{fmt, io, os::fd::IntoRawFd}; use tokio::io::unix::AsyncFd; -use crate::{IpVersion, Result, TunFraming, VoleError}; +use crate::{ + IpVersion, Result, TunFraming, VoleError, + http_processing::diagnostics::{Counter, increment}, +}; use super::{TUN_PACKET_BATCH_SIZE, TunFd}; @@ -286,17 +289,25 @@ impl TunRsIo { Some(ready) => ready, None => readiness.insert(self.device.writable().await?), }; - match ready.try_io(|inner| inner.get_ref().send(packet)) { + match ready.try_io(|inner| { + increment(Counter::TunWriteBatchSendAttempts); + inner.get_ref().send(packet) + }) { #[cfg(target_vendor = "apple")] Ok(Err(error)) if error.raw_os_error() == Some(libc::ENOBUFS) => { // Only this unaccepted packet is retried. Drop the // guard across the same cancellable Darwin backoff // used by the single-packet path. + increment(Counter::TunWriteBatchEnobufsErrors); readiness = None; + increment(Counter::TunWriteBatchSleep1msRequests); tokio::time::sleep(std::time::Duration::from_millis(1)).await; } Ok(result) => break result?, - Err(_would_block) => readiness = None, + Err(_would_block) => { + increment(Counter::TunWriteBatchWouldBlock); + readiness = None; + } } }; if written != packet.len() { @@ -304,6 +315,7 @@ impl TunRsIo { io::Error::new(io::ErrorKind::WriteZero, "partial TUN packet write").into(), ); } + increment(Counter::TunWriteBatchAcceptedPackets); outcomes.push(Ok(version)); } Ok(()) @@ -315,18 +327,26 @@ impl TunRsIo { let version = validate_write_packet(packet, self.mtu)?; let written = loop { let mut ready = self.device.writable().await?; - match ready.try_io(|inner| inner.get_ref().send(packet)) { + match ready.try_io(|inner| { + increment(Counter::TunWriteSingleSendAttempts); + inner.get_ref().send(packet) + }) { #[cfg(target_vendor = "apple")] Ok(Err(error)) if error.raw_os_error() == Some(libc::ENOBUFS) => { // Darwin can exhaust packet/mbuf space after a cached // writable event. No packet was accepted: retain this one // packet, yield without spinning, and let Stop cancel the // future. Do not resize the host's shared socket buffers. + increment(Counter::TunWriteSingleEnobufsErrors); drop(ready); + increment(Counter::TunWriteSingleSleep1msRequests); tokio::time::sleep(std::time::Duration::from_millis(1)).await; } Ok(result) => break result?, - Err(_would_block) => continue, + Err(_would_block) => { + increment(Counter::TunWriteSingleWouldBlock); + continue; + } } }; if written != packet.len() { @@ -335,6 +355,7 @@ impl TunRsIo { "partial TUN packet write", ))); } + increment(Counter::TunWriteSingleAcceptedPackets); Ok(version) } } diff --git a/src/routing/dispatcher.rs b/src/routing/dispatcher.rs index f3dd326..d0ca81c 100644 --- a/src/routing/dispatcher.rs +++ b/src/routing/dispatcher.rs @@ -781,6 +781,79 @@ fn preferred_address(addresses: &[IpAddr]) -> Option { #[async_trait] impl Dispatcher for RoutingDispatcher { + #[cfg(feature = "inbound-http")] + async fn prepare_http_tcp( + &self, + mut session: StreamSession, + ) -> Result>, DispatchError> { + if business(session.inbound) { + session.capture_original(); + } + self.ensure_destination_allowed(&session.destination)?; + // DNS-over-TCP's special stream remains on the original entry point. + if session.inbound == InboundKind::Tun + && matches!(&session.destination, Destination::Ip(a) if self.tun_config.hijacks_dns(*a)) + && self.dns.as_ref().is_some_and(|dns| dns.is_enabled()) + { + return Ok(None); + } + let traced = self.diagnostics.is_some() && business(session.inbound); + let (prepared, trace) = if traced { + crate::dns::trace::capture(self.prepare_tcp_route(&session)).await + } else { + (self.prepare_tcp_route(&session).await, Vec::new()) + }; + let (decision, selected) = prepared?; + let direct = + decision.action == RuleAction::Direct || selected.as_ref().is_some_and(|s| s.direct); + let static_connector = selected + .as_ref() + .map_or(&self.direct, |s| &s.dispatcher) + .permits_http_tcp_reuse(); + // DIRECT still needs a fixed selected IP without address racing. A + // proven proxy has its own immutable physical path; its business + // destination may remain a remotely resolved name. No route is rerun + // here, and a rejected/keyless leaf cannot borrow DIRECT's permission. + let stable_route = if direct { + matches!(decision.destination, Destination::Ip(_)) + && !(self.tcp_concurrent + && decision + .resolved_addresses + .as_ref() + .is_some_and(|a| a.len() > 1)) + } else { + selected.as_ref().is_some_and(|s| !s.direct) + }; + let key = if static_connector && stable_route { + Some(crate::dispatch::HttpTcpReuseKey::new(HttpRouteIdentity { + rules: self.rules.clone(), + leaf: selected + .as_ref() + .map_or_else(|| self.direct.clone(), |s| s.dispatcher.clone()), + session: session.clone(), + action: decision.action, + rule_index: decision.rule_index, + endpoint: decision.destination.clone(), + resolved: decision.resolved_addresses.clone(), + metadata: decision.metadata.clone(), + process: decision.process.clone(), + dns_mode: decision.dns_mode, + chain: selected.as_ref().map_or_else(Vec::new, |s| s.chain.clone()), + })) + } else { + None + }; + Ok(Some(Box::new(RoutingHttpTcpPlan { + router: self.clone_parts(), + session, + decision, + selected, + key, + trace, + traced, + }))) + } + async fn sniff_plan( &self, source: SocketAddr, @@ -789,6 +862,17 @@ impl Dispatcher for RoutingDispatcher { let Some(policy) = self.sniffer.as_ref() else { return Ok(None); }; + // A SOCKS domain address can contain a numeric host. Normalize only + // sniff admission so it shares IP mapping/exclusion rules without + // changing the session destination or its original ingress facts. + let numeric_destination = match destination { + Destination::Domain { host, port } => host + .parse::() + .ok() + .map(|ip| Destination::Ip(SocketAddr::new(ip, *port))), + Destination::Ip(_) => None, + }; + let destination = numeric_destination.as_ref().unwrap_or(destination); let (host, mapped) = match destination { Destination::Domain { host, .. } => (Some(host.clone()), false), Destination::Ip(address) => { @@ -835,6 +919,83 @@ impl Dispatcher for RoutingDispatcher { } } +#[cfg(feature = "inbound-http")] +struct HttpRouteIdentity { + rules: Arc, + leaf: Arc, + session: StreamSession, + action: RuleAction, + rule_index: usize, + endpoint: Destination, + resolved: Option>, + metadata: Destination, + process: crate::process::Identity, + dns_mode: &'static str, + chain: Vec, +} +#[cfg(feature = "inbound-http")] +impl PartialEq for HttpRouteIdentity { + fn eq(&self, other: &Self) -> bool { + Arc::ptr_eq(&self.rules, &other.rules) + && Arc::ptr_eq(&self.leaf, &other.leaf) + && self.session == other.session + && self.action == other.action + && self.rule_index == other.rule_index + && self.endpoint == other.endpoint + && self.resolved == other.resolved + && self.metadata == other.metadata + && self.process == other.process + && self.dns_mode == other.dns_mode + && self.chain == other.chain + } +} +#[cfg(feature = "inbound-http")] +impl Eq for HttpRouteIdentity {} +#[cfg(feature = "inbound-http")] +struct RoutingHttpTcpPlan { + router: RoutingDispatcher, + session: StreamSession, + decision: RouteDecision, + selected: Option, + key: Option, + trace: Vec<&'static str>, + traced: bool, +} +#[cfg(feature = "inbound-http")] +#[async_trait] +impl crate::dispatch::HttpTcpPlan for RoutingHttpTcpPlan { + fn reuse_key(&self) -> Option<&crate::dispatch::HttpTcpReuseKey> { + self.key.as_ref() + } + async fn connect(self: Box) -> Result { + let Self { + router, + session, + decision, + selected, + trace, + traced, + .. + } = *self; + if traced { + crate::dns::trace::capture(async { + for step in trace { + crate::dns::trace::record(step); + } + router + .connect_tcp_decision(session, decision, selected) + .await + }) + .await + .0 + } else { + router + .connect_tcp_decision(session, decision, selected) + .await + } + } +} + impl RoutingDispatcher { fn routed_datagrams(&self, session: DatagramSession) -> RoutedDatagramTransport { let managed_ready = (self.diagnostics.is_some() && business(session.inbound)) @@ -854,6 +1015,8 @@ impl RoutingDispatcher { flows: DatagramRoutes::new(self.tun_config.udp_timeout), logged_route_actions: HashSet::new(), receive_wakeup: Arc::new(Notify::new()), + #[cfg(target_os = "macos")] + pending_tun_send: None, } } @@ -872,6 +1035,15 @@ impl RoutingDispatcher { return Ok(self.dns_tcp_stream(dns.clone())); } + let (decision, resolved_target) = self.prepare_tcp_route(&session).await?; + self.connect_tcp_decision(session, decision, resolved_target) + .await + } + + async fn prepare_tcp_route( + &self, + session: &StreamSession, + ) -> Result<(RouteDecision, Option), DispatchError> { let mut decision = self .route( Network::Tcp, @@ -887,6 +1059,15 @@ impl RoutingDispatcher { self.resolve_direct_destination(&mut decision).await?; } log_route_decision(Network::Tcp, &decision); + Ok((decision, resolved_target)) + } + + async fn connect_tcp_decision( + &self, + mut session: StreamSession, + decision: RouteDecision, + resolved_target: Option, + ) -> Result { let chain = resolved_target .as_ref() .map_or_else(Vec::new, |target| target.chain.clone()); @@ -1066,6 +1247,26 @@ struct RoutedDatagramTransport { flows: DatagramRoutes, logged_route_actions: HashSet, receive_wakeup: Arc, + #[cfg(target_os = "macos")] + pending_tun_send: Option, +} + +#[cfg(target_os = "macos")] +enum PendingTunRoute { + Managed { + key: Destination, + shared: Option, + size: usize, + }, + Cached((RouteTargetId, Option)), +} + +#[cfg(target_os = "macos")] +struct PendingRouteSend { + route: PendingTunRoute, + completion: crate::dispatch::TunSendToken, + cancel: tokio_util::sync::CancellationToken, + deferred_remove: bool, } // Each synthetic target owns an association: two names may resolve to the same @@ -1255,7 +1456,24 @@ impl RoutedDatagramTransport { self.router.diagnostics.is_some() && business(self.session.inbound) } + #[cfg(target_os = "macos")] + fn tun_send_removal_deferred(&self) -> bool { + self.pending_tun_send + .as_ref() + .is_some_and(|pending| pending.deferred_remove) + } + async fn remove_managed(&mut self, key: &Destination) -> Result<(), DispatchError> { + #[cfg(target_os = "macos")] + if let Some(pending) = self.pending_tun_send.as_mut() + && matches!(&pending.route, PendingTunRoute::Managed { key: sending, .. } if sending == key) + { + // Receive/controller cleanup cannot close a still-leased wire. + // One flag suffices: normal completion performs original removal. + pending.deferred_remove = true; + pending.cancel.cancel(); + return Ok(()); + } let Some(mut flow) = self.managed_flows.remove(key) else { return Ok(()); }; @@ -1600,6 +1818,12 @@ impl RoutedDatagramTransport { async fn receive_managed(&mut self) -> Result { loop { self.clean_managed().await; + #[cfg(target_os = "macos")] + if self.tun_send_removal_deferred() { + // Yield to the TUN owner even under an unconstrained poll. + // It must drop IO before completing the deferred removal. + return Err(DispatchError::NotAllowed); + } let idle_timeout = self.router.tun_config.udp_timeout; let result = { let polled = std::future::poll_fn(|context| { @@ -1661,6 +1885,10 @@ impl RoutedDatagramTransport { flow.connection.failed(&error); } let _ = self.remove_managed(&key).await; + #[cfg(target_os = "macos")] + if self.tun_send_removal_deferred() { + return Err(DispatchError::NotAllowed); + } } Some(ManagedDatagramEvent::Shared(id, Ok(datagram))) => { let key = &datagram.remote; @@ -1669,6 +1897,10 @@ impl RoutedDatagramTransport { { if flow.connection.cancelled() || flow.last_used.elapsed() >= idle_timeout { let _ = self.remove_managed(key).await; + #[cfg(target_os = "macos")] + if self.tun_send_removal_deferred() { + return Err(DispatchError::NotAllowed); + } } else { flow.connection.download(datagram.payload.len()); flow.last_used = Instant::now(); @@ -1677,7 +1909,11 @@ impl RoutedDatagramTransport { } } Some(ManagedDatagramEvent::Shared(id, Err(error))) => { - self.fail_managed_shared(id, &error).await + self.fail_managed_shared(id, &error).await; + #[cfg(target_os = "macos")] + if self.tun_send_removal_deferred() { + return Err(error); + } } None => {} } @@ -1696,6 +1932,14 @@ impl RoutedDatagramTransport { .map(|(key, _)| key.clone()) .collect::>(); for key in expired { + #[cfg(target_os = "macos")] + if let Some(pending) = self.pending_tun_send.as_mut() + && matches!(&pending.route, PendingTunRoute::Cached(sending) if sending == &key) + { + pending.deferred_remove = true; + pending.cancel.cancel(); + continue; + } if let Some(mut cached) = self.route_transports.remove(&key) { let _ = cached.transport.close().await; } @@ -1945,6 +2189,219 @@ impl DatagramTransport for RoutedDatagramTransport { false } + #[cfg(target_os = "macos")] + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + flow_id: Option<&[u8]>, + ) -> Result { + if self.pending_tun_send.is_some() + || self.session.inbound != InboundKind::Tun + || datagram.sniffed_domain.is_some() + || flow_id.is_some_and(|id| id.is_empty() || id.len() > 25) + || !matches!(datagram.remote, Destination::Ip(_)) + { + return Err(datagram); + } + let now = Instant::now(); + let key = datagram.remote.clone(); + let size = datagram.payload.len(); + let (mut operation, route, connection_cancel) = if self.tracked() { + if now >= self.managed_next_cleanup { + return Err(datagram); + } + let Some(flow) = self.managed_flows.get_mut(&key) else { + return Err(datagram); + }; + if flow.connection.cancelled() + || flow.last_used.elapsed() >= self.router.tun_config.udp_timeout + || flow.restore + || flow.destination != key + || flow_id.is_some_and(|id| flow.flow_id.as_deref() != Some(id)) + { + return Err(datagram); + } + let connection_cancel = flow.connection.token(); + let (transport, shared) = match &mut flow.transport { + ManagedTransport::Dedicated(transport) => (transport, None), + ManagedTransport::Shared(id) => ( + &mut self + .managed_shared + .get_mut(id) + .expect("shared flow owner") + .transport, + Some(*id), + ), + }; + let operation = transport.try_begin_tun_send(datagram, None)?; + // Unsupported admission above changes no routing/accounting state. + flow.last_used = now; + ( + operation, + PendingTunRoute::Managed { key, shared, size }, + Some(connection_cancel), + ) + } else { + let Destination::Ip(destination) = key else { + return Err(datagram); + }; + if now >= self.flows.next_cleanup + || self.route_transports.iter().any(|((_, target), cached)| { + target.is_some() + && cached.last_used.elapsed() >= self.router.tun_config.udp_timeout + }) + || self + .fake_flows + .values() + .any(|flow| flow.last_used.elapsed() >= self.router.tun_config.udp_timeout) + || self.fake_flows.contains_key(&destination) + || self + .router + .dns + .as_ref() + .is_some_and(|dns| !matches!(dns.recover_fake_ip(destination.ip()), Ok(None))) + { + return Err(datagram); + } + let Some(flow) = self.flows.entries.get(&destination) else { + return Err(datagram); + }; + if now.duration_since(flow.last_used) >= self.flows.idle_timeout + || flow_id.is_some_and(|id| flow.flow_id.as_deref() != Some(id)) + { + return Err(datagram); + } + let RuleAction::Route(id) = flow.action else { + return Err(datagram); + }; + let cache_key = ( + id, + self.router + .route_targets + .per_flow(id) + .then_some(Destination::Ip(destination)), + ); + let Some(cached) = self.route_transports.get_mut(&cache_key) else { + return Err(datagram); + }; + if cached.direct || cached.last_used.elapsed() >= self.router.tun_config.udp_timeout { + return Err(datagram); + } + let operation = cached.transport.try_begin_tun_send(datagram, None)?; + cached.last_used = now; + self.flows + .entries + .get_mut(&destination) + .expect("cached flow") + .last_used = now; + (operation, PendingTunRoute::Cached(cache_key), None) + }; + let cancel = tokio_util::sync::CancellationToken::new(); + let abort = cancel.clone(); + let io = operation.operation; + operation.operation = Box::pin(async move { + let connection_cancelled = async { + match connection_cancel { + Some(token) => token.cancelled().await, + None => std::future::pending().await, + } + }; + tokio::select! { + biased; + () = abort.cancelled() => Err(DispatchError::NotAllowed), + () = connection_cancelled => Err(DispatchError::NotAllowed), + result = io => result, + } + }); + self.pending_tun_send = Some(PendingRouteSend { + route, + completion: operation.completion.clone(), + cancel, + deferred_remove: false, + }); + Ok(operation) + } + + #[cfg(target_os = "macos")] + async fn finish_tun_send( + &mut self, + completion: crate::dispatch::TunSendToken, + outcome: crate::dispatch::TunSendOutcome, + ) -> Result<(), DispatchError> { + use crate::dispatch::TunSendOutcome; + if !self + .pending_tun_send + .as_ref() + .is_some_and(|pending| pending.completion.same(&completion)) + { + return Err(DispatchError::NotAllowed); + } + let pending = self + .pending_tun_send + .take() + .expect("verified TUN send identity"); + // The caller has already dropped IO; take the sole pin before awaits. + let completed = matches!(&outcome, TunSendOutcome::Completed(_)); + match pending.route { + PendingTunRoute::Managed { key, shared, size } => { + let result = match self.managed_flows.get_mut(&key) { + Some(flow) => match &mut flow.transport { + ManagedTransport::Dedicated(transport) => { + transport.finish_tun_send(completion, outcome).await + } + ManagedTransport::Shared(id) => match self.managed_shared.get_mut(id) { + Some(owner) => { + owner.transport.finish_tun_send(completion, outcome).await + } + None => Err(DispatchError::NotAllowed), + }, + }, + None => Err(DispatchError::NotAllowed), + }; + if !completed || pending.deferred_remove { + // External cancellation/timeout never impersonates IO failure. + let _ = self.remove_managed(&key).await; + return result; + } + if let Some(flow) = self.managed_flows.get(&key) { + match &result { + Ok(()) => flow.connection.upload(size), + Err(error) if shared.is_none() && !flow.connection.cancelled() => { + flow.connection.failed(error) + } + Err(_) => {} + } + } + if let Err(error) = &result { + let cancelled = self + .managed_flows + .get(&key) + .is_none_or(|flow| flow.connection.cancelled()); + if let Some(id) = shared + && !cancelled + { + self.fail_managed_shared(id, error).await; + } else { + let _ = self.remove_managed(&key).await; + } + } + result + } + PendingTunRoute::Cached(key) => { + let result = match self.route_transports.get_mut(&key) { + Some(cached) => cached.transport.finish_tun_send(completion, outcome).await, + None => Err(DispatchError::NotAllowed), + }; + if pending.deferred_remove + && let Some(mut cached) = self.route_transports.remove(&key) + { + let _ = cached.transport.close().await; + } + result + } + } + } + async fn send(&mut self, mut datagram: Datagram) -> Result<(), DispatchError> { if self.tracked() { return crate::dns::trace::capture(self.send_managed(datagram)) @@ -2197,6 +2654,11 @@ mod tests { }; use bytes::Bytes; + include!("numeric_host_sniff_tests.rs"); + include!("http_reuse_memory_tests.rs"); + #[cfg(target_os = "macos")] + include!("dispatcher_tun_send_green_tests.rs"); + #[derive(Default)] struct RecordingDispatcher { tcp_only: bool, diff --git a/src/routing/dispatcher_tun_send_green_tests.rs b/src/routing/dispatcher_tun_send_green_tests.rs new file mode 100644 index 0000000..484d26b --- /dev/null +++ b/src/routing/dispatcher_tun_send_green_tests.rs @@ -0,0 +1,567 @@ +// Typed GREEN controls for router admission, attribution and pin lifetime. +// Include inside the existing dispatcher tests module on macOS only. +mod c11_tun_send_green { + use super::*; + use crate::dispatch::tun_send_memory_test_support::{Packets, Probe}; + use crate::dispatch::{TunPendingSend, TunSendOutcome}; + + struct LeafCounters { + io: Arc, + opens: AtomicUsize, + receive_error: Arc, + } + struct LeafDispatcher { + counters: Arc, + shareable: bool, + accept: bool, + } + struct Leaf { + io: Packets, + shareable: bool, + receive_error: Arc, + } + + #[async_trait] + impl Dispatcher for LeafDispatcher { + async fn connect_tcp(&self, _: StreamSession) -> Result { + panic!("router owned-send GREEN must not open TCP"); + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + self.counters.opens.fetch_add(1, Ordering::Relaxed); + let mut io = Packets::new(self.counters.io.clone()); + io.accept = self.accept; + Ok(Box::new(Leaf { + io, + shareable: self.shareable, + receive_error: self.counters.receive_error.clone(), + })) + } + } + + #[async_trait] + impl DatagramTransport for Leaf { + fn supports_shared_destinations(&self) -> bool { + self.shareable + } + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + flow_id: Option<&[u8]>, + ) -> Result { + self.io.try_begin_tun_send(datagram, flow_id) + } + async fn finish_tun_send( + &mut self, + completion: crate::dispatch::TunSendToken, + outcome: TunSendOutcome, + ) -> Result<(), DispatchError> { + self.io.finish_tun_send(completion, outcome).await + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { + self.io.send(datagram).await + } + async fn receive(&mut self) -> Result { + if self.receive_error.swap(false, Ordering::AcqRel) { + return Err(DispatchError::ConnectionRefused); + } + self.io.receive().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.io.close().await + } + } + + fn fixture( + tracked: bool, + shareable: bool, + accept: bool, + ) -> ( + RoutedDatagramTransport, + Arc, + Arc, + ) { + let config = crate::config::Config::parse_yaml( + b"mixed-port: 1080\nproxies: [{name: edge, type: socks5, server: 192.0.2.1, port: 1080}]\nrules: ['MATCH,edge']\n" + ).unwrap(); + let counters = Arc::new(LeafCounters { + io: Arc::new(Probe::default()), + opens: AtomicUsize::new(0), + receive_error: Arc::new(AtomicBool::new(false)), + }); + let leaf: Arc = Arc::new(LeafDispatcher { + counters: counters.clone(), + shareable, + accept, + }); + let rules = RuleSet::compile(config.rules.clone()).unwrap(); + let registry = Arc::new(crate::connections::Registry::default()); + let mut router = RoutingDispatcher::new( + ProxyDispatchers::new(vec![leaf]).unwrap(), + Arc::new(RecordingDispatcher::default()), + None, + rules.clone(), + Arc::new(EmptyGeoMatcher), + ); + if tracked { + router = router.with_diagnostics(Arc::new( + crate::routing::diagnostics::Diagnostics::new(&config, &rules, registry.clone()), + )); + } + ( + router.routed_datagrams(association(InboundKind::Tun)), + counters, + registry, + ) + } + + fn snapshot(registry: &crate::connections::Registry) -> serde_json::Value { + let mut value = serde_json::to_value(registry.snapshot()).unwrap(); + value.as_object_mut().unwrap().remove("memory"); + value + } + fn assert_packet(actual: Datagram, expected: &Datagram) { + assert_eq!(actual.remote, expected.remote); + assert_eq!(actual.sniffed_domain, expected.sniffed_domain); + assert_eq!(actual.payload.as_ptr(), expected.payload.as_ptr()); + assert_eq!(actual.payload.len(), expected.payload.len()); + } + fn begin(transport: &mut RoutedDatagramTransport, peer: SocketAddr) -> TunPendingSend { + let Ok(pending) = transport.try_begin_tun_send(datagram(peer, b"io"), Some(b"stable")) + else { + panic!("eligible cached typed leaf was not admitted"); + }; + pending + } + async fn warm(transport: &mut RoutedDatagramTransport, peer: SocketAddr) { + transport + .send_with_flow_id(datagram(peer, b"warm"), b"stable") + .await + .unwrap(); + } + + #[tokio::test] + async fn cold_changed_identity_and_unsupported_admission_preserve_packet_and_state() { + for tracked in [false, true] { + let (mut transport, counters, registry) = fixture(tracked, false, false); + let peer = "198.51.100.1:443".parse().unwrap(); + let packet = datagram(peer, b"io"); + let Err(returned) = transport.try_begin_tun_send(packet.clone(), Some(b"stable")) + else { + panic!("cold route must use ordinary preparation"); + }; + assert_packet(returned, &packet); + assert_eq!(counters.opens.load(Ordering::Relaxed), 0); + assert!(transport.pending_tun_send.is_none()); + + warm(&mut transport, peer).await; + let before = snapshot(®istry); + let last_used = if tracked { + transport + .managed_flows + .get(&packet.remote) + .unwrap() + .last_used + } else { + transport.flows.entries.get(&peer).unwrap().last_used + }; + let Err(returned) = transport.try_begin_tun_send(packet.clone(), Some(b"changed")) + else { + panic!("changed authenticated identity must use ordinary routing"); + }; + assert_packet(returned, &packet); + assert_eq!(counters.io.begins.load(Ordering::Relaxed), 0); + + let Err(returned) = transport.try_begin_tun_send(packet.clone(), Some(b"stable")) + else { + panic!("unsupported leaf must return the original packet"); + }; + assert_packet(returned, &packet); + assert_eq!(counters.io.begins.load(Ordering::Relaxed), 1); + assert_eq!(counters.opens.load(Ordering::Relaxed), 1); + assert!(transport.pending_tun_send.is_none()); + let after_used = if tracked { + transport + .managed_flows + .get(&packet.remote) + .unwrap() + .last_used + } else { + transport.flows.entries.get(&peer).unwrap().last_used + }; + assert_eq!(last_used, after_used); + assert_eq!(snapshot(®istry), before); + transport.close().await.unwrap(); + } + } + + #[tokio::test] + async fn cached_untracked_admission_preserves_one_completion_identity() { + let (mut transport, counters, _) = fixture(false, false, true); + let peer = "198.51.100.1:443".parse().unwrap(); + warm(&mut transport, peer).await; + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + assert!(matches!( + &transport.pending_tun_send.as_ref().unwrap().route, + PendingTunRoute::Cached(_) + )); + operation.await.unwrap(); + transport + .finish_tun_send(completion, TunSendOutcome::Completed(Ok(()))) + .await + .unwrap(); + assert!(transport.pending_tun_send.is_none()); + assert_eq!(counters.io.finishes.load(Ordering::Relaxed), 1); + assert_eq!(counters.opens.load(Ordering::Relaxed), 1); + transport.close().await.unwrap(); + } + + #[tokio::test] + async fn managed_dedicated_and_shared_success_accounts_only_completed_send_once() { + for shared in [false, true] { + let (mut transport, counters, registry) = fixture(true, shared, true); + let peer = "198.51.100.1:443".parse().unwrap(); + warm(&mut transport, peer).await; + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + let duplicate = completion.clone(); + assert_eq!(snapshot(®istry)["connections"][0]["upload"], 4); + operation.await.unwrap(); + transport + .finish_tun_send(completion, TunSendOutcome::Completed(Ok(()))) + .await + .unwrap(); + assert_eq!(snapshot(®istry)["connections"][0]["upload"], 6); + assert!(matches!( + transport + .finish_tun_send(duplicate, TunSendOutcome::Completed(Ok(()))) + .await, + Err(DispatchError::NotAllowed) + )); + assert_eq!(snapshot(®istry)["connections"][0]["upload"], 6); + assert_eq!(counters.io.finishes.load(Ordering::Relaxed), 1); + transport.close().await.unwrap(); + } + } + + #[tokio::test] + async fn managed_completed_error_keeps_original_dedicated_and_shared_failure_cleanup() { + for shared in [false, true] { + let (mut transport, counters, registry) = fixture(true, shared, true); + let peer = "198.51.100.1:443".parse().unwrap(); + warm(&mut transport, peer).await; + if shared { + warm(&mut transport, "198.51.100.2:443".parse().unwrap()).await; + } + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + operation.await.unwrap(); + assert!(matches!( + transport + .finish_tun_send( + completion, + TunSendOutcome::Completed(Err(DispatchError::ConnectionRefused)) + ) + .await, + Err(DispatchError::ConnectionRefused) + )); + let result = snapshot(®istry); + assert!(result["connections"].as_array().unwrap().is_empty()); + assert_eq!( + result["errors"].as_array().unwrap().len(), + if shared { 2 } else { 1 } + ); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 1); + assert!(transport.pending_tun_send.is_none()); + transport.close().await.unwrap(); + } + } + + #[tokio::test] + async fn managed_remove_defers_pin_and_wire_close_until_operation_is_dropped() { + for shared in [false, true] { + let (mut transport, counters, registry) = fixture(true, shared, true); + let peer = "198.51.100.1:443".parse().unwrap(); + warm(&mut transport, peer).await; + let sibling: SocketAddr = "198.51.100.2:443".parse().unwrap(); + if shared { + warm(&mut transport, sibling).await; + } + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + transport + .remove_managed(&Destination::Ip(peer)) + .await + .unwrap(); + assert!(transport.pending_tun_send.as_ref().unwrap().deferred_remove); + assert!(transport.managed_flows.contains_key(&Destination::Ip(peer))); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 0); + if shared { + transport + .remove_managed(&Destination::Ip(sibling)) + .await + .unwrap(); + assert_eq!(transport.managed_shared.values().next().unwrap().members, 1); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 0); + } + // The cancellation branch drops the lower owned operation before return. + assert!(matches!(operation.await, Err(DispatchError::NotAllowed))); + assert!(matches!( + transport + .finish_tun_send(completion, TunSendOutcome::Cancelled) + .await, + Err(DispatchError::NotAllowed) + )); + assert!(transport.pending_tun_send.is_none()); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 1); + assert!(snapshot(®istry)["errors"].as_array().unwrap().is_empty()); + assert!( + snapshot(®istry)["connections"] + .as_array() + .unwrap() + .is_empty() + ); + transport.close().await.unwrap(); + } + } + + #[tokio::test] + async fn external_timeout_and_cancel_do_not_fabricate_transport_failure() { + for timed_out in [false, true] { + let (mut transport, counters, registry) = fixture(true, false, true); + let peer = "198.51.100.1:443".parse().unwrap(); + warm(&mut transport, peer).await; + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + drop(operation); + let outcome = if timed_out { + TunSendOutcome::TimedOut + } else { + TunSendOutcome::Cancelled + }; + let result = transport.finish_tun_send(completion, outcome).await; + if timed_out { + assert!(matches!(result, Err(DispatchError::TimedOut))); + } else { + assert!(matches!(result, Err(DispatchError::NotAllowed))); + } + let view = snapshot(®istry); + assert!(view["errors"].as_array().unwrap().is_empty()); + assert!(view["connections"].as_array().unwrap().is_empty()); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 1); + transport.close().await.unwrap(); + } + } + + #[tokio::test] + async fn foreign_completion_cannot_release_an_original_operation_pin() { + let (mut transport, counters, registry) = fixture(true, false, true); + let peer = "198.51.100.1:443".parse().unwrap(); + warm(&mut transport, peer).await; + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + let foreign = TunPendingSend::new(Box::pin(async { Ok(()) })); + assert!(matches!( + transport + .finish_tun_send(foreign.completion, TunSendOutcome::Cancelled) + .await, + Err(DispatchError::NotAllowed) + )); + assert!(transport.pending_tun_send.is_some()); + assert!(transport.managed_flows.contains_key(&Destination::Ip(peer))); + assert_eq!(counters.io.finishes.load(Ordering::Relaxed), 0); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 0); + assert_eq!(snapshot(®istry)["connections"][0]["upload"], 4); + drop(operation); + assert!(matches!( + transport + .finish_tun_send(completion, TunSendOutcome::Cancelled) + .await, + Err(DispatchError::NotAllowed) + )); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 1); + transport.close().await.unwrap(); + } + + fn poll_receive_once( + transport: &mut RoutedDatagramTransport, + ) -> Poll> { + use std::future::Future as _; + let waker = futures_util::task::noop_waker(); + let mut context = Context::from_waker(&waker); + let mut receive = Box::pin(tokio::task::unconstrained(transport.receive())); + receive.as_mut().poll(&mut context) + } + + #[tokio::test] + async fn cancelled_or_expired_pin_returns_receive_error_in_one_unconstrained_poll() { + for expired in [false, true] { + let (mut transport, counters, registry) = fixture(true, false, true); + let peer = "198.51.100.1:443".parse().unwrap(); + let key = Destination::Ip(peer); + warm(&mut transport, peer).await; + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + if expired { + let timeout = transport.router.tun_config.udp_timeout; + transport.managed_flows.get_mut(&key).unwrap().last_used = Instant::now() - timeout; + transport.managed_next_cleanup = Instant::now(); + } else { + let view = snapshot(®istry); + let id = view["connections"][0]["id"].as_str().unwrap(); + registry.close(id); + } + // No surrounding timeout or Tokio cooperative yield can manufacture + // this readiness: the production receive future is polled once. + assert!(matches!( + poll_receive_once(&mut transport), + Poll::Ready(Err(DispatchError::NotAllowed)) + )); + let pending = transport.pending_tun_send.as_ref().unwrap(); + assert!(pending.completion.same(&completion)); + assert!(pending.deferred_remove); + assert!(transport.managed_flows.contains_key(&key)); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 0); + assert_eq!(counters.io.finishes.load(Ordering::Relaxed), 0); + assert!(snapshot(®istry)["errors"].as_array().unwrap().is_empty()); + // Keep the owned operation alive throughout the receive assertion. + drop(operation); + assert!(matches!( + transport + .finish_tun_send(completion, TunSendOutcome::Cancelled) + .await, + Err(DispatchError::NotAllowed) + )); + assert!(transport.pending_tun_send.is_none()); + assert!(transport.managed_flows.iter().next().is_none()); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 1); + assert!( + snapshot(®istry)["connections"] + .as_array() + .unwrap() + .is_empty() + ); + transport.close().await.unwrap(); + } + } + + #[tokio::test] + async fn shared_receive_error_returns_original_error_in_one_poll_without_closing_pin() { + let (mut transport, counters, registry) = fixture(true, true, true); + let peer = "198.51.100.1:443".parse().unwrap(); + let key = Destination::Ip(peer); + warm(&mut transport, peer).await; + warm(&mut transport, "198.51.100.2:443".parse().unwrap()).await; + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + counters.receive_error.store(true, Ordering::Release); + assert!(matches!( + poll_receive_once(&mut transport), + Poll::Ready(Err(DispatchError::ConnectionRefused)) + )); + let pending = transport.pending_tun_send.as_ref().unwrap(); + assert!(pending.completion.same(&completion)); + assert!(pending.deferred_remove); + assert!(transport.managed_flows.contains_key(&key)); + assert_eq!(transport.managed_shared.values().next().unwrap().members, 1); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 0); + assert_eq!(counters.io.finishes.load(Ordering::Relaxed), 0); + assert_eq!(snapshot(®istry)["errors"].as_array().unwrap().len(), 2); + drop(operation); + assert!(matches!( + transport + .finish_tun_send(completion, TunSendOutcome::Cancelled) + .await, + Err(DispatchError::NotAllowed) + )); + assert!(transport.pending_tun_send.is_none()); + assert!(transport.managed_flows.iter().next().is_none()); + assert!(transport.managed_shared.is_empty()); + assert_eq!(counters.io.closes.load(Ordering::Relaxed), 1); + let view = snapshot(®istry); + assert!(view["connections"].as_array().unwrap().is_empty()); + assert_eq!(view["errors"].as_array().unwrap().len(), 2); + transport.close().await.unwrap(); + } + + #[tokio::test] + async fn maintenance_due_declines_without_mutation_then_ordinary_send_maintains_cache() { + for tracked in [false, true] { + let (mut transport, counters, registry) = fixture(tracked, false, true); + let peer = "198.51.100.1:443".parse().unwrap(); + let key = Destination::Ip(peer); + warm(&mut transport, peer).await; + let due = Instant::now(); + if tracked { + transport.managed_next_cleanup = due; + } else { + transport.flows.next_cleanup = due; + } + let before = snapshot(®istry); + let last_used = if tracked { + transport.managed_flows.get(&key).unwrap().last_used + } else { + transport.flows.entries.get(&peer).unwrap().last_used + }; + let original = datagram(peer, b"io"); + let Err(returned) = transport.try_begin_tun_send(original.clone(), Some(b"stable")) + else { + panic!("due maintenance must retain the ordinary path"); + }; + assert_packet(returned, &original); + assert!(transport.pending_tun_send.is_none()); + assert_eq!(counters.io.begins.load(Ordering::Relaxed), 0); + assert_eq!(counters.opens.load(Ordering::Relaxed), 1); + assert_eq!(snapshot(®istry), before); + if tracked { + assert_eq!(transport.managed_next_cleanup, due); + assert_eq!( + transport.managed_flows.get(&key).unwrap().last_used, + last_used + ); + } else { + assert_eq!(transport.flows.next_cleanup, due); + assert_eq!( + transport.flows.entries.get(&peer).unwrap().last_used, + last_used + ); + } + transport + .send_with_flow_id(datagram(peer, b"more"), b"stable") + .await + .unwrap(); + let TunPendingSend { + operation, + completion, + } = begin(&mut transport, peer); + operation.await.unwrap(); + transport + .finish_tun_send(completion, TunSendOutcome::Completed(Ok(()))) + .await + .unwrap(); + assert!(transport.pending_tun_send.is_none()); + assert_eq!(counters.io.begins.load(Ordering::Relaxed), 1); + assert_eq!(counters.opens.load(Ordering::Relaxed), 1); + transport.close().await.unwrap(); + } + } +} diff --git a/src/routing/http_reuse_memory_tests.rs b/src/routing/http_reuse_memory_tests.rs new file mode 100644 index 0000000..4f60a9d --- /dev/null +++ b/src/routing/http_reuse_memory_tests.rs @@ -0,0 +1,423 @@ +#[cfg(all(feature = "inbound-http", feature = "outbound-http"))] +mod http_reuse_memory_tests { + use super::*; + use crate::{ + dialer::{Dialer, ResolvedEndpoint}, + dispatch::{HttpTcpPlan, HttpTcpReuseKey}, + outbound::{ConnectorDispatcher, DirectOutbound, UpstreamPath, http::HttpOutbound}, + security::SecurityContext, + session::InboundMetadata, + }; + use std::collections::BTreeMap; + + const PROXY: &str = "192.0.2.10:8080"; + + // No test opens a plan. The real protocol and routing objects below only + // prepare immutable equality evidence; their endpoints are never dialled. + struct OpaqueNoIo; + + #[async_trait] + impl Dispatcher for OpaqueNoIo { + async fn connect_tcp(&self, _: StreamSession) -> Result { + panic!("HTTP reuse preparation must not connect an opaque dispatcher") + } + + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + panic!("HTTP reuse preparation must not open a datagram transport") + } + } + + struct NoBusinessDns; + + #[async_trait] + impl RoutingDns for NoBusinessDns { + async fn resolve(&self, _: &str) -> Result, DispatchError> { + panic!("proxy preparation must not resolve the symbolic business destination") + } + + async fn exchange(&self, _: &[u8]) -> Result { + panic!("HTTP reuse preparation must not exchange DNS packets") + } + + async fn domain_hint(&self, _: IpAddr) -> Option { + None + } + } + + fn business_session() -> StreamSession { + StreamSession { + metadata: InboundMetadata { + local_port: 1080, + user: Some(Arc::from("memory-user-a")), + local_address: Some("198.51.100.1:1080".parse().unwrap()), + original: None, + }, + inbound: InboundKind::Http, + source: "198.51.100.2:20000".parse().unwrap(), + destination: Destination::domain("business.invalid", 443).unwrap(), + sniffed_domain: None, + } + } + + fn proxy_endpoint() -> ResolvedEndpoint { + let address: SocketAddr = PROXY.parse().unwrap(); + ResolvedEndpoint { + logical_host: address.ip().to_string(), + port: address.port(), + addresses: vec![address], + } + } + + fn http_node(upstream: UpstreamPath) -> Arc { + let address: SocketAddr = PROXY.parse().unwrap(); + let config = crate::config::HttpOutboundConfig { + address: address.ip().to_string(), + port: address.port(), + tls: None, + auth: None, + headers: BTreeMap::new(), + }; + Arc::new(ConnectorDispatcher::new(Arc::new( + HttpOutbound::with_shared_security( + &config, + upstream, + &SecurityContext::new(), + 1, + 32 * 1024, + ) + .unwrap(), + ))) + } + + fn static_http_node() -> Arc { + http_node(UpstreamPath::direct(proxy_endpoint(), Dialer::default())) + } + + fn memory_router( + nodes: Vec>, + direct: Arc, + rules: Vec, + ) -> RoutingDispatcher { + let mut router = RoutingDispatcher::new( + ProxyDispatchers::new(nodes).unwrap(), + direct, + None, + RuleSet::compile(rules).unwrap(), + Arc::new(EmptyGeoMatcher), + ); + router.dns = Some(Arc::new(NoBusinessDns)); + router + } + + fn proxy_router(node: Arc) -> RoutingDispatcher { + memory_router( + vec![node], + Arc::new(OpaqueNoIo), + vec![rule(RuleKind::Match, proxy_action(0))], + ) + } + + fn group_router( + nodes: Vec>, + configs: Vec, + ) -> (RoutingDispatcher, Arc) { + let direct: Arc = Arc::new(OpaqueNoIo); + let groups = ProxyGroups::new(&configs, nodes.clone(), direct.clone()).unwrap(); + let mut router = RoutingDispatcher::new( + ProxyDispatchers::with_proxy_groups(nodes, &groups).unwrap(), + direct, + None, + RuleSet::compile(vec![rule(RuleKind::Match, group_action(0))]).unwrap(), + Arc::new(EmptyGeoMatcher), + ); + router.dns = Some(Arc::new(NoBusinessDns)); + (router, groups) + } + + fn node_member(index: usize) -> ProxyGroupMemberTarget { + ProxyGroupMemberTarget::Route(RouteTargetId::Proxy(ProxyId::new(index).unwrap())) + } + + fn group_member(index: usize) -> ProxyGroupMemberTarget { + ProxyGroupMemberTarget::Route(RouteTargetId::Group(ProxyGroupId::new(index).unwrap())) + } + + async fn plan(router: &RoutingDispatcher, session: StreamSession) -> Box { + router + .prepare_http_tcp(session) + .await + .expect("route preparation must succeed without IO") + .expect("ordinary business TCP must return an owned plan") + } + + fn key(plan: &dyn HttpTcpPlan) -> HttpTcpReuseKey { + plan.reuse_key() + .expect("a proven static HTTP proxy must provide equality evidence") + .clone() + } + + #[tokio::test] + async fn immutable_proxy_preparation_repeats_without_resolving_business_domain() { + for upstream in [ + UpstreamPath::direct(proxy_endpoint(), Dialer::default()), + UpstreamPath::LazyDirect { + dialer: Dialer::default(), + }, + ] { + let router = proxy_router(http_node(upstream)); + let session = business_session(); + let (decision, _) = router.prepare_tcp_route(&session).await.unwrap(); + assert_eq!(decision.destination, session.destination); + assert!(decision.resolved_addresses.is_none()); + + let first = plan(&router, session.clone()).await; + let second = plan(&router, session.clone()).await; + let cloned_router = router.clone_parts(); + let cloned = plan(&cloned_router, session).await; + assert!(key(first.as_ref()).same(&key(second.as_ref()))); + assert!(key(first.as_ref()).same(&key(cloned.as_ref()))); + } + } + + #[tokio::test] + async fn immutable_proxy_keys_preserve_every_session_identity_dimension() { + let router = proxy_router(static_http_node()); + let original = business_session(); + let baseline = key(plan(&router, original.clone()).await.as_ref()); + let mut variants = Vec::new(); + + let mut changed = original.clone(); + changed.metadata.user = Some(Arc::from("memory-user-b")); + variants.push(("authenticated account", changed)); + + let mut changed = original.clone(); + changed.source.set_port(20001); + variants.push(("source connection", changed)); + + let mut changed = original.clone(); + changed.source.set_ip("198.51.100.3".parse().unwrap()); + variants.push(("source address", changed)); + + let mut changed = original.clone(); + changed.metadata.local_port = 1081; + variants.push(("listener port", changed)); + + let mut changed = original.clone(); + changed.metadata.local_address = Some("198.51.100.4:1080".parse().unwrap()); + variants.push(("accepted local address", changed)); + + let mut changed = original.clone(); + changed.inbound = InboundKind::Socks5; + variants.push(("inbound kind", changed)); + + let mut changed = original.clone(); + changed.destination = Destination::domain("other-business.invalid", 443).unwrap(); + variants.push(("authority hostname", changed)); + + let mut changed = original.clone(); + changed.destination = Destination::domain("business.invalid", 8443).unwrap(); + variants.push(("authority port", changed)); + + let mut changed = original.clone(); + changed.sniffed_domain = Some("observed-business.invalid".into()); + variants.push(("sniffed routing metadata", changed)); + + let mut changed = original; + changed.capture_original(); + Arc::make_mut(changed.metadata.original.as_mut().unwrap()).destination = + Destination::domain("original-business.invalid", 443).unwrap(); + variants.push(("original ingress snapshot", changed)); + + for (dimension, session) in variants { + let changed = key(plan(&router, session).await.as_ref()); + assert!( + !baseline.same(&changed), + "changed {dimension} must not borrow the previous upstream" + ); + } + } + + #[tokio::test] + async fn immutable_proxy_keys_keep_rule_and_leaf_generations_distinct() { + let node = static_http_node(); + let router = proxy_router(node.clone()); + let baseline = key(plan(&router, business_session()).await.as_ref()); + + // Identical text and the same concrete leaf do not merge generations. + let replacement_rules = proxy_router(node); + let replacement = key(plan(&replacement_rules, business_session()).await.as_ref()); + assert!(!baseline.same(&replacement)); + + // Keep this router's exact rules/session while replacing the concrete + // protocol owner with an independently configured equivalent node. + let mut replacement_leaf = router.clone_parts(); + replacement_leaf.route_targets = ProxyDispatchers::new(vec![static_http_node()]).unwrap(); + let replacement = key(plan(&replacement_leaf, business_session()).await.as_ref()); + assert!(!baseline.same(&replacement)); + } + + #[tokio::test] + async fn immutable_proxy_group_selection_invalidates_the_old_leaf_key() { + let (router, groups) = group_router( + vec![static_http_node(), static_http_node()], + vec![select_group( + "choice", + vec![("first", node_member(0)), ("second", node_member(1))], + )], + ); + let first = key(plan(&router, business_session()).await.as_ref()); + let repeat = key(plan(&router, business_session()).await.as_ref()); + assert!(first.same(&repeat)); + + groups.select("choice", "second").unwrap(); + let second = key(plan(&router, business_session()).await.as_ref()); + assert!(!first.same(&second)); + assert!(first.same(&repeat), "previous evidence remains immutable"); + let repeat_second = key(plan(&router, business_session()).await.as_ref()); + assert!(second.same(&repeat_second)); + } + + #[tokio::test] + async fn immutable_proxy_group_chain_changes_even_when_the_leaf_is_identical() { + let (router, groups) = group_router( + vec![static_http_node()], + vec![ + select_group( + "entry", + vec![("left", group_member(1)), ("right", group_member(2))], + ), + select_group("left", vec![("same-leaf", node_member(0))]), + select_group("right", vec![("same-leaf", node_member(0))]), + ], + ); + let session = business_session(); + let (_, left) = router.prepare_tcp_route(&session).await.unwrap(); + let left = left.unwrap(); + let first = key(plan(&router, session.clone()).await.as_ref()); + + groups.select("entry", "right").unwrap(); + let (_, right) = router.prepare_tcp_route(&session).await.unwrap(); + let right = right.unwrap(); + assert!(Arc::ptr_eq(&left.dispatcher, &right.dispatcher)); + assert_ne!(left.chain, right.chain); + let second = key(plan(&router, session).await.as_ref()); + assert!(!first.same(&second)); + } + + #[tokio::test] + async fn opaque_and_nonstatic_proxy_paths_never_produce_reuse_keys() { + let opaque = proxy_router(Arc::new(OpaqueNoIo)); + assert!(plan(&opaque, business_session()).await.reuse_key().is_none()); + + let bound = http_node(UpstreamPath::direct( + proxy_endpoint(), + Dialer::default().with_source_ip("192.0.2.44".parse().unwrap()), + )); + let bound = proxy_router(bound); + assert!(plan(&bound, business_session()).await.reuse_key().is_none()); + + let mut mismatched = proxy_endpoint(); + mismatched.addresses = vec!["192.0.2.11:8080".parse().unwrap()]; + let mismatched = proxy_router(http_node(UpstreamPath::direct( + mismatched, + Dialer::default(), + ))); + assert!( + plan(&mismatched, business_session()) + .await + .reuse_key() + .is_none() + ); + } + + #[tokio::test] + async fn rejected_routes_keep_their_decision_and_have_no_reuse_key() { + let router = memory_router( + vec![static_http_node()], + Arc::new(DirectOutbound::new(Dialer::default())), + vec![rule(RuleKind::Match, RuleAction::Reject)], + ); + let mut session = business_session(); + session.destination = Destination::Ip("203.0.113.10:443".parse().unwrap()); + let (decision, selected) = router.prepare_tcp_route(&session).await.unwrap(); + assert_eq!(decision.action, RuleAction::Reject); + assert!(selected.is_none()); + assert!(plan(&router, session).await.reuse_key().is_none()); + + let (router, _) = group_router( + vec![static_http_node()], + vec![select_group( + "rejecting", + vec![("REJECT", ProxyGroupMemberTarget::Reject)], + )], + ); + let session = business_session(); + let (decision, selected) = router.prepare_tcp_route(&session).await.unwrap(); + assert_eq!(decision.action, group_action(0)); + let selected = selected.unwrap(); + assert!(!selected.direct); + assert_eq!(selected.chain, vec!["REJECT", "rejecting"]); + assert!(plan(&router, session).await.reuse_key().is_none()); + } + + #[tokio::test] + async fn direct_reuse_still_rejects_opaque_or_bound_physical_egress() { + for direct in [ + Arc::new(OpaqueNoIo) as Arc, + Arc::new(DirectOutbound::new( + Dialer::default().with_source_ip("192.0.2.44".parse().unwrap()), + )), + ] { + let router = memory_router( + Vec::new(), + direct, + vec![rule(RuleKind::Match, RuleAction::Direct)], + ); + let mut session = business_session(); + session.destination = Destination::Ip("203.0.113.10:443".parse().unwrap()); + assert!(plan(&router, session).await.reuse_key().is_none()); + } + } + + struct MemoryDirectDns; + + #[async_trait] + impl RoutingDns for MemoryDirectDns { + async fn resolve(&self, host: &str) -> Result, DispatchError> { + assert_eq!(host, "business.invalid"); + Ok(vec![ + "203.0.113.10".parse().unwrap(), + "203.0.113.11".parse().unwrap(), + ]) + } + + async fn exchange(&self, _: &[u8]) -> Result { + panic!("memory-only address selection must not exchange DNS packets") + } + + async fn domain_hint(&self, _: IpAddr) -> Option { + None + } + } + + #[tokio::test] + async fn direct_concurrent_address_racing_still_has_no_reuse_key() { + let mut router = memory_router( + Vec::new(), + Arc::new(DirectOutbound::new(Dialer::default())), + vec![rule(RuleKind::Match, RuleAction::Direct)], + ); + router.dns = Some(Arc::new(MemoryDirectDns)); + let concurrent = router.clone_parts().with_tcp_concurrent(true); + assert!( + plan(&concurrent, business_session()) + .await + .reuse_key() + .is_none() + ); + assert!(plan(&router, business_session()).await.reuse_key().is_some()); + } +} diff --git a/src/routing/numeric_host_sniff_tests.rs b/src/routing/numeric_host_sniff_tests.rs new file mode 100644 index 0000000..fbe384c --- /dev/null +++ b/src/routing/numeric_host_sniff_tests.rs @@ -0,0 +1,170 @@ +mod numeric_host_sniff_tests { + use super::*; + + const REQUEST: &[u8] = b"GET / HTTP/1.1\r\nHost: observed.example\r\n\r\n"; + + fn router(settings: &str, dns: Option>) -> RoutingDispatcher { + let config = crate::config::Config::parse_yaml(settings.as_bytes()).unwrap(); + dispatcher( + Arc::new(RecordingDispatcher::default()), + Arc::new(RecordingDispatcher::default()), + dns, + Vec::new(), + ) + .with_sniffer(&config.sniffer) + } + + async fn observe( + router: &RoutingDispatcher, + destination: Destination, + expected_active: bool, + ) { + let mut session = StreamSession { + metadata: Default::default(), + inbound: InboundKind::Socks5, + source: "198.51.100.2:9000".parse().unwrap(), + destination: destination.clone(), + sniffed_domain: None, + }; + let plan = router + .sniff_plan(session.source, &session.destination) + .await + .unwrap() + .unwrap(); + assert_eq!(plan.tcp_enabled(), expected_active, "{destination:?}"); + // Reading a plan must not rewrite the caller's ingress metadata. + assert_eq!(session.destination, destination); + assert!(session.metadata.original.is_none()); + + let mut unread = REQUEST; + let prefix = plan.sniff(&mut unread, &mut session).await.unwrap(); + assert_eq!([prefix.as_slice(), unread].concat(), REQUEST); + assert_eq!( + session.sniffed_domain.as_deref(), + expected_active.then_some("observed.example") + ); + // All fixtures use override=false. Even accepted sniffing must retain + // the original Domain wire target and the snapshot must describe it. + assert_eq!(session.destination, destination); + assert_eq!( + session.metadata.original.as_ref().unwrap().destination, + destination + ); + if !expected_active { + assert!(prefix.is_empty()); + assert_eq!(unread, REQUEST); + } + } + + #[tokio::test] + async fn numeric_host_sniff_plan_matches_ip_for_pure_ip_and_exclusions() { + for (literal, extra, expected) in [ + ("203.0.113.7", "", true), + ("2001:db8::7", "", true), + ("203.0.113.7", " parse-pure-ip: false\n", false), + ( + "203.0.113.7", + " skip-dst-address: [203.0.113.0/24]\n", + false, + ), + ( + "2001:db8::7", + " skip-dst-address: ['2001:db8::/32']\n", + false, + ), + ( + "203.0.113.7", + " skip-src-address: [198.51.100.0/24]\n", + false, + ), + ] { + let settings = format!( + "sniffer:\n enable: true\n override-destination: false\n{extra} sniff:\n HTTP: {{ports: [80]}}\n" + ); + let router = router(&settings, None); + let ip: IpAddr = literal.parse().unwrap(); + let domain = Destination::domain(literal, 80).unwrap(); + let address = Destination::Ip(SocketAddr::new(ip, 80)); + observe(&router, domain, expected).await; + observe(&router, address, expected).await; + } + } + + struct NumericDns { + fake: Option<&'static str>, + hint: Option<&'static str>, + fake_lookups: AtomicUsize, + hint_lookups: AtomicUsize, + } + + #[async_trait] + impl RoutingDns for NumericDns { + fn recover_fake_ip(&self, address: IpAddr) -> Result, DispatchError> { + assert_eq!(address, "203.0.113.7".parse::().unwrap()); + self.fake_lookups.fetch_add(1, Ordering::Relaxed); + Ok(self.fake.map(str::to_owned)) + } + + async fn domain_hint(&self, address: IpAddr) -> Option { + assert_eq!(address, "203.0.113.7".parse::().unwrap()); + self.hint_lookups.fetch_add(1, Ordering::Relaxed); + self.hint.map(str::to_owned) + } + + async fn resolve(&self, _: &str) -> Result, DispatchError> { + panic!("sniff admission must not resolve a numeric host") + } + + async fn exchange(&self, _: &[u8]) -> Result { + panic!("sniff admission must not exchange DNS packets") + } + } + + #[tokio::test] + async fn numeric_host_sniff_plan_reuses_dns_mapping_and_fake_ip_admission() { + for (fake, hint, extra, expected) in [ + (None, Some("mapped.example"), "", true), + ( + None, + Some("mapped.example"), + " force-dns-mapping: false\n", + false, + ), + (Some("fake.example"), None, "", false), + ( + Some("fake.example"), + None, + " force-domain: [fake.example]\n", + true, + ), + ] { + let settings = format!( + "sniffer:\n enable: true\n parse-pure-ip: false\n override-destination: false\n{extra} sniff:\n HTTP: {{ports: [80]}}\n" + ); + let dns = Arc::new(NumericDns { + fake, + hint, + fake_lookups: AtomicUsize::new(0), + hint_lookups: AtomicUsize::new(0), + }); + let router = router(&settings, Some(dns.clone())); + observe( + &router, + Destination::domain("203.0.113.7", 80).unwrap(), + expected, + ) + .await; + observe( + &router, + Destination::Ip("203.0.113.7:80".parse().unwrap()), + expected, + ) + .await; + assert_eq!(dns.fake_lookups.load(Ordering::Relaxed), 2); + assert_eq!( + dns.hint_lookups.load(Ordering::Relaxed), + if fake.is_some() { 0 } else { 2 } + ); + } + } +} diff --git a/src/routing/proxy_group.rs b/src/routing/proxy_group.rs index 5c67dc9..32309bb 100644 --- a/src/routing/proxy_group.rs +++ b/src/routing/proxy_group.rs @@ -665,6 +665,10 @@ impl Dispatcher for SelectProxyGroupDispatcher { // Core-originated DNS/probes also enter groups without a first destination. // Resolve their leaf on first send and retain it through the association. +#[cfg(all(test, target_os = "macos"))] +#[path = "proxy_group_tun_send_memory_tests.rs"] +mod tun_send_memory_tests; + struct BalancedDatagrams { groups: Arc, id: ProxyGroupId, @@ -678,6 +682,30 @@ impl DatagramTransport for BalancedDatagrams { false } + #[cfg(target_os = "macos")] + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + flow_id: Option<&[u8]>, + ) -> Result { + match self.transport.as_mut() { + Some(transport) => transport.try_begin_tun_send(datagram, flow_id), + None => Err(datagram), + } + } + + #[cfg(target_os = "macos")] + async fn finish_tun_send( + &mut self, + completion: crate::dispatch::TunSendToken, + outcome: crate::dispatch::TunSendOutcome, + ) -> Result<(), DispatchError> { + match self.transport.as_mut() { + Some(transport) => transport.finish_tun_send(completion, outcome).await, + None => Err(DispatchError::NotAllowed), + } + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { if self.transport.is_none() { let leaf = self.groups.resolve_leaf_for( diff --git a/src/routing/proxy_group_tun_send_memory_tests.rs b/src/routing/proxy_group_tun_send_memory_tests.rs new file mode 100644 index 0000000..4d23285 --- /dev/null +++ b/src/routing/proxy_group_tun_send_memory_tests.rs @@ -0,0 +1,62 @@ +use super::*; +use crate::dispatch::tun_send_memory_test_support::{ + Packets, Probe, assert_untouched, completion_outcomes, packet, +}; +use crate::session::InboundKind; + +struct NoOpen; +#[async_trait] +impl Dispatcher for NoOpen { + async fn connect_tcp(&self, _: StreamSession) -> Result { + panic!("owned admission must not open a stream"); + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + panic!("owned admission must not select or open a leaf"); + } +} + +fn wrapper(transport: Option>) -> BalancedDatagrams { + BalancedDatagrams { + groups: ProxyGroups::new(&[], Vec::new(), Arc::new(NoOpen)).unwrap(), + id: ProxyGroupId::new(0).unwrap(), + session: DatagramSession::for_tun("192.0.2.2:1234".parse().unwrap(), 1400), + transport, + } +} + +#[test] +fn tun_owned_balanced_cold_path_returns_original_packet_without_selecting() { + let mut transport = wrapper(None); + assert_eq!(transport.session.inbound, InboundKind::Tun); + let original = packet(b"ok"); + let Err(returned) = transport.try_begin_tun_send(original.clone(), Some(b"opaque")) else { + panic!("cold group must retain ordinary leaf selection"); + }; + assert_untouched(returned, &original); + assert!(transport.transport.is_none()); +} + +#[tokio::test] +async fn tun_owned_balanced_open_leaf_forwards_identity_metadata_and_all_outcomes() { + let probe = Arc::new(Probe::default()); + let mut transport = wrapper(Some(Box::new(Packets::new(probe.clone())))); + completion_outcomes(&mut transport, &probe).await; +} + +#[test] +fn tun_owned_balanced_unsupported_leaf_returns_original_packet() { + let probe = Arc::new(Probe::default()); + let mut packets = Packets::new(probe.clone()); + packets.accept = false; + let mut transport = wrapper(Some(Box::new(packets))); + let original = packet(b"ok"); + let Err(returned) = transport.try_begin_tun_send(original.clone(), None) else { + panic!("unsupported cached leaf must decline"); + }; + assert_untouched(returned, &original); + assert_eq!(probe.begins.load(Ordering::Relaxed), 1); + assert_eq!(probe.legacy.load(Ordering::Relaxed), 0); +} diff --git a/src/runtime/health.rs b/src/runtime/health.rs index 2f8a19e..067f146 100644 --- a/src/runtime/health.rs +++ b/src/runtime/health.rs @@ -32,6 +32,11 @@ pub(super) struct ActiveDispatcher { } #[async_trait::async_trait] impl Dispatcher for ActiveDispatcher { + #[cfg(feature = "inbound-http")] + fn permits_http_tcp_reuse(&self) -> bool { + self.dispatcher.permits_http_tcp_reuse() + } + fn supports_udp(&self) -> bool { self.dispatcher.supports_udp() } diff --git a/src/runtime/providers.rs b/src/runtime/providers.rs index faa5784..f6a7335 100644 --- a/src/runtime/providers.rs +++ b/src/runtime/providers.rs @@ -676,6 +676,28 @@ impl RuntimeResources for ProviderRuntime { } #[async_trait] impl Dispatcher for ProviderRuntime { + #[cfg(feature = "inbound-http")] + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + if self.cancellation.is_cancelled() { + return Err(DispatchError::NotAllowed); + } + let generation = self.current.load_full(); + let inner = generation.dispatcher.prepare_http_tcp(session).await?; + Ok(inner.map(|inner| { + let key = inner + .reuse_key() + .cloned() + .map(|k| k.with_generation(generation.clone())); + Box::new(GenerationHttpTcpPlan { + inner, + generation, + key, + }) as Box + })) + } #[cfg(feature = "inbound-http")] fn http_context(&self) -> Option { if self.cancellation.is_cancelled() { @@ -746,6 +768,25 @@ struct PinnedDispatcher { } #[async_trait] impl Dispatcher for PinnedDispatcher { + #[cfg(feature = "inbound-http")] + async fn prepare_http_tcp( + &self, + session: StreamSession, + ) -> Result>, DispatchError> { + let generation = self.generation.clone(); + let inner = self.dispatcher.prepare_http_tcp(session).await?; + Ok(inner.map(|inner| { + let key = inner + .reuse_key() + .cloned() + .map(|k| k.with_generation(generation.clone())); + Box::new(GenerationHttpTcpPlan { + inner, + generation, + key, + }) as Box + })) + } fn supports_udp(&self) -> bool { self.dispatcher.supports_udp() } @@ -776,6 +817,30 @@ impl Dispatcher for PinnedDispatcher { })) } } +#[cfg(feature = "inbound-http")] +struct GenerationHttpTcpPlan { + inner: Box, + generation: Arc, + key: Option, +} +#[cfg(feature = "inbound-http")] +#[async_trait] +impl crate::dispatch::HttpTcpPlan for GenerationHttpTcpPlan { + fn reuse_key(&self) -> Option<&crate::dispatch::HttpTcpReuseKey> { + self.key.as_ref() + } + async fn connect(self: Box) -> Result { + let Self { + inner, generation, .. + } = *self; + let io = inner.connect().await?; + Ok(Box::new(GenerationStream { + io, + _generation: generation, + })) + } +} + struct GenerationStream { io: BoxStream, _generation: Arc, @@ -804,6 +869,29 @@ impl AsyncWrite for GenerationStream { Pin::new(&mut self.io).poll_shutdown(cx) } } + +#[cfg(target_os = "macos")] +fn pin_tun_send_generation( + pending: crate::dispatch::TunPendingSend, + generation: Arc, +) -> crate::dispatch::TunPendingSend { + let crate::dispatch::TunPendingSend { + operation, + completion, + } = pending; + crate::dispatch::TunPendingSend { + operation: Box::pin(async move { + let _generation = generation; + operation.await + }), + completion, + } +} + +#[cfg(all(test, target_os = "macos"))] +#[path = "providers_tun_send_memory_tests.rs"] +mod tun_send_memory_tests; + struct GenerationDatagram { io: Box, _generation: Arc, @@ -817,6 +905,27 @@ impl DatagramTransport for GenerationDatagram { fn payload_budget(&self, peer: &Destination) -> DatagramBudget { self.io.payload_budget(peer) } + + #[cfg(target_os = "macos")] + fn try_begin_tun_send( + &mut self, + datagram: Datagram, + flow_id: Option<&[u8]>, + ) -> Result { + self.io + .try_begin_tun_send(datagram, flow_id) + .map(|pending| pin_tun_send_generation(pending, self._generation.clone())) + } + + #[cfg(target_os = "macos")] + async fn finish_tun_send( + &mut self, + completion: crate::dispatch::TunSendToken, + outcome: crate::dispatch::TunSendOutcome, + ) -> Result<(), DispatchError> { + self.io.finish_tun_send(completion, outcome).await + } + async fn send(&mut self, datagram: Datagram) -> Result<(), DispatchError> { self.io.send(datagram).await } diff --git a/src/runtime/providers_tun_send_memory_tests.rs b/src/runtime/providers_tun_send_memory_tests.rs new file mode 100644 index 0000000..7083800 --- /dev/null +++ b/src/runtime/providers_tun_send_memory_tests.rs @@ -0,0 +1,53 @@ +use super::pin_tun_send_generation; +use crate::dispatch::{TunPendingSend, TunSendToken}; +use std::sync::{ + Arc, + atomic::{AtomicUsize, Ordering}, +}; + +struct Lease(Arc); +impl Drop for Lease { + fn drop(&mut self) { + self.0.fetch_add(1, Ordering::Relaxed); + } +} + +fn assert_same(actual: &TunSendToken, expected: &TunSendToken) { + assert!( + actual.same(expected), + "lease wrapper changed completion identity" + ); +} + +#[tokio::test] +async fn tun_owned_operation_keeps_generation_lease_through_completion() { + let drops = Arc::new(AtomicUsize::new(0)); + let lease = Arc::new(Lease(drops.clone())); + let weak = Arc::downgrade(&lease); + let original = TunPendingSend::new(Box::pin(async { Ok(()) })); + let token = original.completion.clone(); + let pending = pin_tun_send_generation(original, lease.clone()); + assert_same(&pending.completion, &token); + drop(lease); + assert!(weak.upgrade().is_some()); + assert_eq!(drops.load(Ordering::Relaxed), 0); + pending.operation.await.unwrap(); + assert!(weak.upgrade().is_none()); + assert_eq!(drops.load(Ordering::Relaxed), 1); +} + +#[test] +fn tun_owned_cancel_drops_generation_lease_without_poll_or_task() { + let drops = Arc::new(AtomicUsize::new(0)); + let lease = Arc::new(Lease(drops.clone())); + let weak = Arc::downgrade(&lease); + let original = TunPendingSend::new(Box::pin(std::future::pending())); + let token = original.completion.clone(); + let pending = pin_tun_send_generation(original, lease.clone()); + assert_same(&pending.completion, &token); + drop(lease); + assert!(weak.upgrade().is_some()); + drop(pending.operation); + assert!(weak.upgrade().is_none()); + assert_eq!(drops.load(Ordering::Relaxed), 1); +} diff --git a/src/security/boring.rs b/src/security/boring.rs index 6e492be..bc90e08 100644 --- a/src/security/boring.rs +++ b/src/security/boring.rs @@ -54,6 +54,19 @@ impl Connector { } impl BoringTlsClient { + #[cfg(all( + feature = "inbound-http", + feature = "outbound-shadowsocks", + feature = "shadow-tls-v3" + ))] + pub(super) fn has_fixed_shadowtls_http_identity(&self) -> bool { + self.ech.is_none() + && self + .identity + .as_ref() + .is_none_or(TlsClientIdentity::has_inline_http_identity) + } + pub(super) fn standard( context: &SecurityContext, server_name: &str, diff --git a/src/security/client.rs b/src/security/client.rs index 2e28d3c..d9a4d1f 100644 --- a/src/security/client.rs +++ b/src/security/client.rs @@ -71,6 +71,46 @@ impl std::fmt::Debug for SecurityClient { } impl SecurityClient { + /// Initial business-HTTP proof scope: Plain and immutable standard TLS. + /// Other security backends keep their existing one-shot HTTP behavior. + #[cfg(all( + feature = "inbound-http", + any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-vless" + ) + ))] + #[cfg_attr( + not(any(feature = "outbound-vmess", feature = "outbound-trojan")), + allow(dead_code) + )] + pub(crate) fn permits_static_http_reuse(&self) -> bool { + match &self.backend { + SecurityBackend::Plain => true, + SecurityBackend::Standard(client) => client.permits_static_http_reuse(), + _ => false, + } + } + + /// SS plugin-local permission; never broadens shared security permission. + #[cfg(all(feature = "inbound-http", feature = "outbound-shadowsocks"))] + pub(crate) fn permits_ss_shadowtls_http_reuse(&self) -> bool { + match &self.backend { + #[cfg(feature = "shadow-tls-v3")] + SecurityBackend::ShadowTls(client) => client.permits_ss_http_reuse(), + _ => false, + } + } + + /// Witness for VLESS's private factory proof, not shared HTTP permission. + /// This backend exists only after the immutable Boring JLS client builds. + #[cfg(all(feature = "inbound-http", feature = "outbound-vless"))] + pub(crate) fn has_fixed_jls_identity(&self) -> bool { + matches!(&self.backend, SecurityBackend::Jls { .. }) + } + #[cfg(feature = "quinn-h3-transport")] pub(crate) async fn quic_config_with_context( &self, diff --git a/src/security/identity_rotation_tests.rs b/src/security/identity_rotation_tests.rs index b34827d..e0503a2 100644 --- a/src/security/identity_rotation_tests.rs +++ b/src/security/identity_rotation_tests.rs @@ -520,3 +520,40 @@ fn transient_read_failure_retries_after_permissions_recover_without_content_chan context.identities.refresh(&CancellationToken::new()); assert_identity(&identity, &b, 2); } + +#[cfg(all( + feature = "inbound-http", + feature = "outbound-shadowsocks", + feature = "shadow-tls-v3" +))] +#[test] +fn shadowtls_http_reuse_uses_actual_inline_or_published_file_identity_storage() { + let identity = chain_with_usage(false, ExtendedKeyUsagePurpose::ClientAuth); + let context = SecurityContext::new(); + let files = Files::new(&identity); + let mut options = crate::config::ShadowTlsConfig { + server_name: "cover.invalid".into(), + password: "synthetic-relay".into(), + alpn: vec![], + required_alpn: None, + identity: None, + certificate: Default::default(), + client_fingerprint: None, + }; + let absent = crate::security::ShadowTlsClient::new(&context, &options).unwrap(); + let absent_allowed = absent.permits_ss_http_reuse(); + options.identity = Some(identity.identity_pem()); + let inline = crate::security::ShadowTlsClient::new(&context, &options).unwrap(); + let inline_allowed = inline.permits_ss_http_reuse(); + options.identity = Some(files.configuration()); + let published = crate::security::ShadowTlsClient::new(&context, &options).unwrap(); + let published_rejected = !published.permits_ss_http_reuse(); + let plain = + crate::security::SecurityClient::from_security(&crate::config::SecurityConfig::None) + .unwrap(); + let other_backend_rejected = !plain.permits_ss_shadowtls_http_reuse(); + drop(( + absent, inline, published, plain, options, context, files, identity, + )); + assert!(absent_allowed && inline_allowed && published_rejected && other_backend_rejected); +} diff --git a/src/security/shadow_tls.rs b/src/security/shadow_tls.rs index 2b9196c..c67e55a 100644 --- a/src/security/shadow_tls.rs +++ b/src/security/shadow_tls.rs @@ -37,6 +37,11 @@ impl std::fmt::Debug for ShadowTlsClient { } impl ShadowTlsClient { + #[cfg(all(feature = "inbound-http", feature = "outbound-shadowsocks"))] + pub(super) fn permits_ss_http_reuse(&self) -> bool { + self.tls.has_fixed_shadowtls_http_identity() + } + pub fn new(context: &SecurityContext, config: &ShadowTlsConfig) -> io::Result { config.validate().map_err(|_| invalid())?; Ok(Self { @@ -458,3 +463,7 @@ impl AsyncWrite for Verified { result } } + +#[cfg(all(test, feature = "outbound-shadowsocks"))] +#[path = "shadow_tls_ss_stack_memory_tests.rs"] +mod ss_stack_memory_tests; diff --git a/src/security/shadow_tls_ss_stack_memory_tests.rs b/src/security/shadow_tls_ss_stack_memory_tests.rs new file mode 100644 index 0000000..0b34ef4 --- /dev/null +++ b/src/security/shadow_tls_ss_stack_memory_tests.rs @@ -0,0 +1,399 @@ +//! Synthetic native-TLS + Vole ShadowTLS/SS + official SS server stack. +//! No routing key, socket, listener, official ShadowTLS peer, or HTTP pool credit. +use super::*; +use base64::{Engine as _, engine::general_purpose::STANDARD}; +use futures_util::future::poll_fn; +use shadowsocks::{ + ServerConfig as SsConfig, + config::ServerType, + context::Context as SsContext, + relay::{socks5::Address, tcprelay::proxy_stream::ProxyServerStream}, +}; +use std::{future::Future, sync::Mutex, task::Waker, time::Duration}; +use tokio::{ + io::{AsyncReadExt, DuplexStream}, + sync::oneshot, +}; +#[derive(Default)] +struct Budget { + left: Option, + written: usize, + target: Option, + read_total: usize, + gated_pending: usize, + installed: bool, + first_then_eight: bool, + waker: Option, + dropped: bool, +} +#[derive(Default)] +struct Watch { + state: Mutex, +} +impl Watch { + fn arm(&self, bytes: Option) { + let mut s = self.state.lock().unwrap(); + s.left = bytes; + s.target = bytes; + s.written = 0; + s.first_then_eight = bytes.is_none(); + } + fn reached(&self) -> bool { + let s = self.state.lock().unwrap(); + s.target.is_some_and(|n| s.written == n) + } + fn read_total(&self) -> usize { + self.state.lock().unwrap().read_total + } + fn target(&self) -> Option { + self.state.lock().unwrap().target + } + fn pending_writes(&self) -> usize { + self.state.lock().unwrap().gated_pending + } + fn blocked_since(&self, before: usize) -> bool { + let s = self.state.lock().unwrap(); + s.target.is_some_and(|n| s.written == n) && s.waker.is_some() && s.gated_pending > before + } + fn release(&self) { + let waker = { + let mut s = self.state.lock().unwrap(); + s.left = None; + s.first_then_eight = false; + s.waker.take() + }; + if let Some(waker) = waker { + waker.wake(); + } + } +} +struct Gate { + raw: DuplexStream, + watch: Arc, +} +impl Gate { + fn new(raw: DuplexStream, watch: Arc) -> Self { + watch.state.lock().unwrap().installed = true; + Self { raw, watch } + } +} +impl Drop for Gate { + fn drop(&mut self) { + let mut s = self.watch.state.lock().unwrap(); + s.waker.take(); + s.dropped = true; + } +} +impl AsyncRead for Gate { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + let before = out.filled().len(); + let result = Pin::new(&mut self.raw).poll_read(cx, out); + self.watch.state.lock().unwrap().read_total += out.filled().len() - before; + result + } +} +impl AsyncWrite for Gate { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + bytes: &[u8], + ) -> Poll> { + if bytes.is_empty() { + return Poll::Ready(Ok(0)); + } + let limit = { + let mut s = self.watch.state.lock().unwrap(); + if s.first_then_eight { + if bytes.len() < 5 || bytes[..3] != [23, 3, 3] { + return Poll::Ready(Err(failed("invalid test record-boundary seam"))); + } + let target = 5 + usize::from(u16::from_be_bytes([bytes[3], bytes[4]])) + 8; + s.left = Some(target); + s.target = Some(target); + s.first_then_eight = false; + } + if s.left == Some(0) { + s.gated_pending += 1; + s.waker = Some(cx.waker().clone()); + return Poll::Pending; + } + s.left.unwrap_or(bytes.len()).min(bytes.len()) + }; + let result = Pin::new(&mut self.raw).poll_write(cx, &bytes[..limit]); + if let Poll::Ready(Ok(count)) = &result { + let mut s = self.watch.state.lock().unwrap(); + s.written += *count; + if let Some(left) = &mut s.left { + *left -= *count; + } + } + result + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.raw).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.raw).poll_shutdown(cx) + } +} +fn failed(message: &'static str) -> io::Error { + io::Error::other(message) +} +fn peer_error(error: impl std::fmt::Display) -> io::Error { + io::Error::other(error.to_string()) +} +enum Step { + Complete(io::Result), + Cancelled, +} +#[tokio::test(flavor = "current_thread")] +async fn ss2022_over_authenticated_shadowtls_preserves_partial_cancelled_write_and_idle_read() +-> io::Result<()> { + let (cover, context, options) = crate::security::shadow_tls_tests::ss_stack_material(); + let client = ShadowTlsClient::new(&context, &options)?; + let password = options.password.as_bytes().to_vec(); + drop((context, options)); + let method = crate::config::ShadowsocksCipher::Aes128Gcm + .as_str() + .parse() + .map_err(peer_error)?; + let key = [7_u8; 16]; + let config = Arc::new( + SsConfig::new(("192.0.2.10", 443), STANDARD.encode(key), method).map_err(peer_error)?, + ); + let client_config = config.clone(); + let upload = Arc::new([vec![0x41_u8; 65536], vec![0x42; 65536]].concat()); + let reply = Arc::new([vec![0x61_u8; 65536], vec![0x62; 65536]].concat()); + let (client_payload, server_payload) = (upload.clone(), upload.clone()); + let (client_reply, server_reply) = (reply.clone(), reply.clone()); + let client_watch = Arc::new(Watch::default()); + let server_watch = Arc::new(Watch::default()); + let client_weak = Arc::downgrade(&client_watch); + let server_weak = Arc::downgrade(&server_watch); + let (write_watch, read_watch) = (client_watch.clone(), server_watch.clone()); + let peer_watch = server_watch.clone(); + let (raw, mut peer) = tokio::io::duplex(73); + let raw = Gate::new(raw, client_watch.clone()); + let (ready, handshake_done) = oneshot::channel(); + let caller = async move { + let relay = client.connect(Box::new(raw)).await?; + handshake_done.await.map_err(peer_error)?; + let target = + crate::session::Destination::domain("stack.invalid", 443).map_err(peer_error)?; + let mut stream = + crate::outbound::memory_test_ss_stack_stream(relay, &client_config, &target); + write_watch.arm(Some(7)); + let mut admitted = 0; + let mut cancelled_write = false; + let mut write_observation_polls = 0_usize; + for _ in 0..4 { + let raw_pending_before = write_watch.pending_writes(); + let mut future = Box::pin(stream.write(&client_payload[admitted..])); + let step = poll_fn(|cx| { + write_observation_polls += 1; + if write_observation_polls > 4096 { + return Poll::Ready(Step::Complete(Err(failed( + "bounded write observation seam exhausted", + )))); + } + match Future::poll(future.as_mut(), cx) { + Poll::Pending if write_watch.blocked_since(raw_pending_before) => { + Poll::Ready(Step::Cancelled) + } + Poll::Pending => { + if write_watch.reached() { + cx.waker().wake_by_ref(); + } + Poll::Pending + } + Poll::Ready(result) => Poll::Ready(Step::Complete(result)), + } + }) + .await; + drop(future); + match step { + Step::Cancelled => { + cancelled_write = true; + break; + } + Step::Complete(result) => { + let count = result?; + if count == 0 || count > client_payload.len() - admitted { + return Err(failed("invalid write admission before cancellation seam")); + } + admitted += count; + } + } + } + if !cancelled_write || admitted == 0 || !write_watch.reached() { + return Err(failed( + "invalid seam: no admitted SS bytes then partial raw write Pending", + )); + } + write_watch.release(); + // Never retry already accepted plaintext after dropping write future. + stream.write_all(&client_payload[admitted..]).await?; + stream.flush().await?; + let mut received = vec![0_u8; client_reply.len()]; + let mut offset = 0; + let mut cancelled_read = false; + // One baseline for the WHOLE probe, retained across ready plaintext prefixes. + let raw_read_before_probe = write_watch.read_total(); + let mut read_observation_polls = 0_usize; + for _ in 0..16 { + let mut future = Box::pin(stream.read(&mut received[offset..])); + let step = poll_fn(|cx| { + read_observation_polls += 1; + if read_observation_polls > 4096 { + return Poll::Ready(Step::Complete(Err(failed( + "bounded read observation seam exhausted", + )))); + } + match Future::poll(future.as_mut(), cx) { + Poll::Pending => { + let delta = write_watch.read_total().checked_sub(raw_read_before_probe); + let target = read_watch.target(); + if read_watch.reached() && target.is_some() && delta == target { + return Poll::Ready(Step::Cancelled); + } + if let (Some(delta), Some(target)) = (delta, target) + && delta > target + { + return Poll::Ready(Step::Complete(Err(failed( + "raw read observation exceeded peer target", + )))); + } + if read_watch.reached() { + cx.waker().wake_by_ref(); + } + Poll::Pending + } + Poll::Ready(result) => Poll::Ready(Step::Complete(result)), + } + }) + .await; + drop(future); + match step { + Step::Cancelled => { + cancelled_read = true; + break; + } + Step::Complete(result) => { + let count = result?; + if count == 0 || count > received.len() - offset { + return Err(failed("invalid read before cancellation seam")); + } + offset += count; + if offset == received.len() { + break; + } + } + } + } + if !cancelled_read + || !read_watch.reached() + || write_watch.read_total().checked_sub(raw_read_before_probe) != read_watch.target() + || received[..offset] != client_reply[..offset] + { + return Err(failed( + "invalid seam: no partial second authenticated relay record Pending", + )); + } + read_watch.release(); + stream.read_exact(&mut received[offset..]).await?; + if received.as_slice() != client_reply.as_slice() { + return Err(failed("stacked response changed")); + } + stream.shutdown().await?; + if stream.read(&mut [0; 1]).await? != 0 { + return Err(failed("unexpected response tail")); + } + Ok::<_, io::Error>(()) + }; + let responder = async move { + let seed = + crate::security::shadow_tls_tests::ss_stack_handshake_seed(&mut peer, cover).await?; + // Real TLS above; business HMAC uses production Verified in reverse + // directions. This is NOT an independent official ShadowTLS server. + let relay = Verified { + raw: Box::new(Gate::new(peer, peer_watch.clone())), + record: Record::new(), + pending: None, + tx: Mac::new(&password, &seed, b"S"), + rx: Mac::new(&password, &seed, b"C"), + ignore: None, + write: Vec::new(), + written: 0, + failed: false, + closing: None, + closed: false, + }; + let mut stream = ProxyServerStream::from_stream( + SsContext::new_shared(ServerType::Server), + relay, + method, + &key, + ); + ready + .send(()) + .map_err(|_| failed("caller stopped during cover handshake"))?; + if stream.handshake().await.map_err(peer_error)? + != Address::DomainNameAddress("stack.invalid".into(), 443) + { + return Err(failed("SS target prelude changed")); + } + let mut actual = vec![0_u8; server_payload.len()]; + stream.read_exact(&mut actual).await?; + if actual.as_slice() != server_payload.as_slice() { + return Err(failed("SS upload duplicated or changed")); + } + // Let one COMPLETE authenticated relay record through, then only 8B of + // the next. This advances the SS reader as well as partial relay state. + peer_watch.arm(None); + stream.write_all(&server_reply).await?; + stream.flush().await?; + stream.shutdown().await?; + if stream.read(&mut [0; 1]).await? != 0 { + return Err(failed("duplicate SS target or upload tail")); + } + Ok::<_, io::Error>(()) + }; + // No spawned task: try_join drops the other future on error; timeout drops + // both complete future trees. Every IO owner is gone before any assertion. + let result = tokio::time::timeout(Duration::from_secs(10), async move { + tokio::try_join!(caller, responder) + }) + .await; + let client_state = { + let s = client_watch.state.lock().unwrap(); + (s.installed, s.dropped, s.waker.is_none()) + }; + let server_state = { + let s = server_watch.state.lock().unwrap(); + (s.installed, s.dropped, s.waker.is_none()) + }; + let installed_closed = + (!client_state.0 || client_state.1) && (!server_state.0 || server_state.1); + let both_installed_dropped = + client_state.0 && client_state.1 && server_state.0 && server_state.1; + let released = client_state.2 && server_state.2; + drop((client_watch, server_watch, config, upload, reply)); + let weak_closed = client_weak.upgrade().is_none() && server_weak.upgrade().is_none(); + if !installed_closed || !released || !weak_closed { + return Err(io::Error::other(format!( + "installed stack owners survived cleanup; original: {result:?}" + ))); + } + // If TLS failed before the server Gate existed, preserve that real error. + // Successful transfer still requires BOTH actual Gate installations/drops. + result.map_err(|_| failed("bounded stacked protocol fixture expired"))??; + assert!( + both_installed_dropped, + "successful stack skipped a Gate installation" + ); + Ok(()) +} diff --git a/src/security/shadow_tls_tests.rs b/src/security/shadow_tls_tests.rs index 3dad1b6..9ec3237 100644 --- a/src/security/shadow_tls_tests.rs +++ b/src/security/shadow_tls_tests.rs @@ -566,3 +566,20 @@ async fn shutdown_has_a_five_second_bound_even_when_the_caller_transport_never_b .await .unwrap(); } + +// Shared only by the stacked protocol memory test; no listener or route factory. +#[cfg(feature = "outbound-shadowsocks")] +pub(super) fn ss_stack_material() -> (Arc, SecurityContext, ShadowTlsConfig) { + let m = material(); + (m.server, m.context, m.options) +} +#[cfg(feature = "outbound-shadowsocks")] +pub(super) async fn ss_stack_handshake_seed( + raw: &mut DuplexStream, + server: Arc, +) -> io::Result<[u8; 32]> { + let (_, flight) = handshake(raw, server).await?; + flight + .seed + .ok_or_else(|| io::Error::other("synthetic handshake lacked relay seed")) +} diff --git a/src/security/tls.rs b/src/security/tls.rs index e07ce82..4db211a 100644 --- a/src/security/tls.rs +++ b/src/security/tls.rs @@ -133,6 +133,15 @@ impl NativeIdentityClient { } impl TlsClientIdentity { + #[cfg(all( + feature = "inbound-http", + feature = "outbound-shadowsocks", + feature = "shadow-tls-v3" + ))] + pub(super) fn has_inline_http_identity(&self) -> bool { + matches!(&self.storage, IdentityStorage::Inline(_)) + } + pub fn from_pem(certificate: &str, private_key: &str) -> io::Result { use rustls::pki_types::pem::PemObject; let invalid = || io::Error::new(io::ErrorKind::InvalidInput, "invalid TLS client identity"); @@ -258,6 +267,26 @@ pub struct StandardTlsClient { buffer_limit: usize, require_ech: bool, dynamic_ech: Option>, + #[cfg(all( + feature = "inbound-http", + any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ) + ))] + #[cfg_attr( + not(any( + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2" + )), + allow(dead_code) + )] + http_reuse_identity_static: bool, #[cfg(feature = "quiche-h3-transport")] quiche_source: Option>, } @@ -321,6 +350,31 @@ impl std::fmt::Debug for StandardTlsClient { } impl StandardTlsClient { + /// A private HTTP stream may retain only an inline identity and static ECH. + /// This query consumes no snapshot, file source, DNS or handshake work. + #[cfg(all( + feature = "inbound-http", + any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ) + ))] + #[cfg_attr( + not(any( + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2" + )), + allow(dead_code) + )] + pub(crate) fn permits_static_http_reuse(&self) -> bool { + self.http_reuse_identity_static && self.dynamic_ech.is_none() + } + #[cfg(feature = "quiche-h3-transport")] pub(crate) fn prepare_quiche_identity(&self) -> io::Result<()> { if let Some(source) = &self.quiche_source { @@ -455,6 +509,21 @@ impl StandardTlsClient { let name = ServerName::try_from(server_name.clone()) .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "invalid TLS server name"))?; let mut options = options; + #[cfg(all( + feature = "inbound-http", + any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ) + ))] + let http_reuse_identity_static = options + .identity + .as_ref() + .is_none_or(|identity| matches!(&identity.storage, IdentityStorage::Inline(_))); if let Some(identity) = &options.identity { identity.snapshot().material.validate()?; } @@ -569,6 +638,18 @@ impl StandardTlsClient { buffer_limit, require_ech, dynamic_ech: None, + #[cfg(all( + feature = "inbound-http", + any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ) + ))] + http_reuse_identity_static, #[cfg(feature = "quiche-h3-transport")] quiche_source, }); @@ -655,6 +736,18 @@ impl StandardTlsClient { buffer_limit, require_ech, dynamic_ech: None, + #[cfg(all( + feature = "inbound-http", + any( + feature = "outbound-anytls", + feature = "outbound-vmess", + feature = "outbound-trojan", + feature = "outbound-hysteria2", + feature = "outbound-tuic", + feature = "outbound-vless" + ) + ))] + http_reuse_identity_static, #[cfg(feature = "quiche-h3-transport")] quiche_source, }) diff --git a/src/sniffing.rs b/src/sniffing.rs index 05abca1..e1ad64e 100644 --- a/src/sniffing.rs +++ b/src/sniffing.rs @@ -100,7 +100,7 @@ pub struct Plan { decision: crate::config::RuleDecision, } impl Plan { - #[cfg(feature = "tun")] + #[cfg(any(feature = "tun", feature = "inbound-http"))] pub(crate) fn with_cancellation( self, cancellation: tokio_util::sync::CancellationToken, @@ -133,6 +133,51 @@ impl Plan { pub(crate) fn quic_enabled(&self) -> bool { self.active && self.policy.config.matches_quic_port(self.port) } + /// A parsed cleartext HTTP request already establishes its protocol and + /// authority. Reuse the configured plan without reading or replaying body + /// bytes, and keep protocol-specific admission and override semantics. + #[cfg(feature = "inbound-http")] + pub(crate) fn observe_http_host( + &self, + host: &str, + session: &mut crate::session::StreamSession, + ) -> Result<(), crate::config::MatchFailure> { + session.capture_original(); + self.decision.check()?; + if !self.active || !self.policy.config.matches_http_port(self.port) { + return Ok(()); + } + let host = host.trim_matches(['[', ']']); + if host.parse::().is_ok() { + return Ok(()); + } + let Ok(domain) = crate::routing::normalize_domain_name(host) else { + return Ok(()); + }; + self.apply_domain(crate::tcp_sniffer::SniffProtocol::Http, domain, session) + } + fn apply_domain( + &self, + protocol: crate::tcp_sniffer::SniffProtocol, + domain: String, + session: &mut crate::session::StreamSession, + ) -> Result<(), crate::config::MatchFailure> { + if !self.accepts(&domain)? { + return Ok(()); + } + let override_destination = match protocol { + crate::tcp_sniffer::SniffProtocol::Http => self.policy.config.http_override, + crate::tcp_sniffer::SniffProtocol::Tls => self.policy.config.tls_override, + }; + if override_destination { + session.destination = Destination::Domain { + host: domain.clone(), + port: self.port, + }; + } + session.sniffed_domain = Some(domain); + Ok(()) + } pub(crate) async fn sniff( &self, reader: &mut R, @@ -158,20 +203,8 @@ impl Plan { .filter_map(|(protocol, enabled)| enabled.then_some(protocol)) .collect(); let mut sniffer = TcpSniffer::with_protocols(protocols); - if let Ok(SniffOutcome::Matched { protocol, domain }) = sniffer.sniff(reader).await - && self.accepts(&domain)? - { - let override_destination = match protocol { - SniffProtocol::Http => self.policy.config.http_override, - SniffProtocol::Tls => self.policy.config.tls_override, - }; - if override_destination { - session.destination = Destination::Domain { - host: domain.clone(), - port: self.port, - }; - } - session.sniffed_domain = Some(domain); + if let Ok(SniffOutcome::Matched { protocol, domain }) = sniffer.sniff(reader).await { + self.apply_domain(protocol, domain, session)?; } Ok(sniffer.into_buffered()) } diff --git a/src/transport/grpc.rs b/src/transport/grpc.rs index d3ae0a2..2f3c96d 100644 --- a/src/transport/grpc.rs +++ b/src/transport/grpc.rs @@ -584,18 +584,24 @@ impl Grpc { ) -> Poll> { let ack = self.coalesced.as_ref().expect("private h2mux writer"); ack.check(cx)?; - if self.send.poll_reset(cx).is_ready() { - ack.fail(io::ErrorKind::BrokenPipe); - return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); - } if input.is_empty() { + if self.send.poll_reset(cx).is_ready() { + ack.fail(io::ErrorKind::BrokenPipe); + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + } return Poll::Ready(Ok(0)); } let wanted = input.len().min(CHUNK); self.send.reserve_capacity(wanted); - let count = ready!(self.send.poll_capacity(cx)) - .ok_or(io::ErrorKind::BrokenPipe)? - .map_err(|_| io::ErrorKind::BrokenPipe)?; + // h2 checks closed state before granting capacity and again before + // buffering DATA. drain keeps its reset waiter while receipts are held. + let count = match ready!(self.send.poll_capacity(cx)) { + Some(Ok(count)) => count, + _ => { + ack.fail(io::ErrorKind::BrokenPipe); + return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); + } + }; let count = wanted.min(count); if count == 0 { cx.waker().wake_by_ref(); @@ -608,8 +614,11 @@ impl Grpc { ack.fail(io::ErrorKind::BrokenPipe); return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())); } - // Retain demand for accepted buffered DATA, not the caller's unaccepted tail. - self.send.reserve_capacity(0); + // Full acceptance leaves only buffered DATA demand in h2. A partial + // write must return its unaccepted tail before the caller can go idle. + if count < wanted { + self.send.reserve_capacity(0); + } // The existing h2 capacity includes max_send_buffer_size. No private // tail/oneshot remains; its Connection owns every accepted byte. Poll::Ready(Ok(count)) @@ -1001,6 +1010,14 @@ mod coalesced_partial_memory_tests { } } +#[cfg(all(test, feature = "sing-mux"))] +#[path = "grpc_private_rst_memory_tests.rs"] +mod private_rst_memory_tests; + #[cfg(test)] #[path = "grpc_gun_streaming_read_memory_tests.rs"] mod streaming_read_memory_tests; + +#[cfg(all(test, feature = "sing-mux"))] +#[path = "grpc_private_demand_memory_tests.rs"] +mod private_demand_memory_tests; diff --git a/src/transport/grpc_pool.rs b/src/transport/grpc_pool.rs index 1600cbc..57ad78d 100644 --- a/src/transport/grpc_pool.rs +++ b/src/transport/grpc_pool.rs @@ -99,7 +99,8 @@ impl GrpcPool { ..Default::default() }); // One CONNECT-IP response carries the node's inner IP traffic. - pool.stream_receive_window = 128 * 1024; + // Match its stream and connection receive credit at establishment. + pool.stream_receive_window = 512 * 1024; pool } /// Trojan keeps its response and lease after upload END_STREAM. @@ -306,11 +307,17 @@ impl GrpcPool { builder .enable_push(false) .initial_window_size(self.stream_receive_window) - .initial_connection_window_size((2 * super::STREAM_BUFFER_BYTES) as u32) + .initial_connection_window_size( + self.stream_receive_window + .max((2 * super::STREAM_BUFFER_BYTES) as u32), + ) .max_frame_size(super::STREAM_CHUNK_BYTES as u32) .max_header_list_size(super::STREAM_CHUNK_BYTES as u32) .max_concurrent_streams(0) .max_send_buffer_size(super::STREAM_CHUNK_BYTES); + if empty.is_some() { + builder.max_concurrent_reset_streams(super::h2_empty::RECENT_RESET_STREAMS); + } #[cfg(any( feature = "outbound-vmess", feature = "outbound-vless", @@ -445,7 +452,7 @@ mod tests { .scope(async { let mut owners = vec![ ("generic", GrpcPool::new(GrpcOptions::default()), 64 * 1024), - ("masque-ip", GrpcPool::masque_ip(), 128 * 1024), + ("masque-ip", GrpcPool::masque_ip(), 512 * 1024), ]; #[cfg(feature = "outbound-trusttunnel")] owners.push(("trusttunnel", GrpcPool::connect_client(), 64 * 1024)); @@ -519,7 +526,11 @@ mod tests { assert!(observation.snapshot().is_idle()); for (name, window, connection_window, expected) in advertised { assert_eq!(window, expected, "MASQUE_H2_SCOPED_STREAM_WINDOW: {name}"); - assert_eq!(connection_window, 128 * 1024, "{name} connection window"); + assert_eq!( + connection_window, + expected.max(128 * 1024), + "{name} connection window" + ); } } diff --git a/src/transport/grpc_private_demand_memory_tests.rs b/src/transport/grpc_private_demand_memory_tests.rs new file mode 100644 index 0000000..df8adeb --- /dev/null +++ b/src/transport/grpc_private_demand_memory_tests.rs @@ -0,0 +1,154 @@ +//! Real native h2 credit after full private writes; no modeled demand state. +use super::*; +use futures_util::future::poll_fn; +use std::time::Duration; + +async fn exercise_full_accept_idle(buffered_prefix: bool) { + let first = vec![b'a'; if buffered_prefix { CHUNK / 4 } else { CHUNK }]; + let second = buffered_prefix.then(|| vec![b'b'; CHUNK / 2]); + let mut expected = first.clone(); + if let Some(second) = &second { + expected.extend_from_slice(second); + } + let expected_len = expected.len(); + let (raw, peer) = tokio::io::duplex(64 * 1024); + let (raw, writes) = Writes::wrap(Box::new(raw)); + let (mut sender, connection) = h2::client::Builder::new() + .enable_push(false) + .max_send_buffer_size(CHUNK) + .handshake::<_, Payload>(raw) + .await + .unwrap(); + let (ready, ready_rx) = tokio::sync::oneshot::channel(); + let (observed, observed_rx) = tokio::sync::oneshot::channel(); + let (release, release_rx) = tokio::sync::oneshot::channel(); + let server = async move { + let mut connection = h2::server::Builder::new() + .initial_window_size(CHUNK as u32) + .handshake::<_, Bytes>(peer) + .await + .unwrap(); + let (request, mut reply) = connection.accept().await.unwrap().unwrap(); + let output = reply.send_response(http::Response::new(()), false).unwrap(); + drop(reply); + let mut input = request.into_body(); + let mut ping = connection.ping_pong().unwrap(); + macro_rules! drive { + ($future:expr) => {{ + let future = $future; + tokio::pin!(future); + loop { + tokio::select! { biased; + result = &mut future => break result, + next = connection.accept() => { + assert!(matches!(next, Some(Ok(_))), "peer closed before credit barrier"); + } + } + } + }}; + } + drive!(ping.ping(h2::Ping::opaque())).unwrap(); + drive!(ping.ping(h2::Ping::opaque())).unwrap(); + ready.send(()).unwrap(); + let mut received = Vec::with_capacity(expected_len); + let mut held = Vec::new(); + while received.len() < expected_len { + let bytes = drive!(input.data()).unwrap().unwrap(); + received.extend_from_slice(&bytes); + // No consumed credit is returned before the idle observation. + held.push(bytes); + } + connection + .set_initial_window_size((CHUNK * 2) as u32) + .unwrap(); + // As in the existing partial-write test, the second PING is ordered + // after genuine SETTINGS. Its ACK proves the client processed them. + drive!(ping.ping(h2::Ping::opaque())).unwrap(); + drive!(ping.ping(h2::Ping::opaque())).unwrap(); + observed.send(received).unwrap(); + drive!(release_rx).unwrap(); + drop((held, input, output, ping)); + while let Some(result) = connection.accept().await { + result.unwrap(); + } + }; + let client = async move { + let request = http::Request::builder() + .method("CONNECT") + .uri("https://fixture.invalid") + .body(()) + .unwrap(); + let (response, send) = sender.send_request(request, false).unwrap(); + let mut stream = Grpc::new( + response, + send, + Framing::Plain, + true, + Instant::now() + Duration::from_secs(5), + Arc::default(), + None, + None, + writes, + ); + stream.coalesced = Some(Arc::new(CoalescedAck::default())); + stream.response_deadline = false; + ready_rx.await.unwrap(); + // Both real writes occur in one application poll. The driver future + // below cannot run between them, so the second full write sees actual + // previously buffered native DATA, rather than a copied state model. + let (first_count, second_poll) = poll_fn(|cx| { + let first_count = std::task::ready!(Pin::new(&mut stream).poll_write(cx, &first))?; + let second_poll = second + .as_ref() + .map(|bytes| Pin::new(&mut stream).poll_write(cx, bytes)); + Poll::Ready(Ok::<_, io::Error>((first_count, second_poll))) + }) + .await + .unwrap(); + assert_eq!( + first_count, + first.len(), + "full-write fixture admitted a prefix" + ); + if let Some(second) = &second { + match second_poll { + Some(Poll::Ready(Ok(count))) => { + assert_eq!(count, second.len(), "buffered fixture admitted a prefix"); + } + result => panic!("second full write was not immediately accepted: {result:?}"), + } + } else { + assert!(second_poll.is_none()); + } + // Do not flush, reserve or write again: those operations could hide + // stale unaccepted demand while the peer grants genuine fresh credit. + let received = observed_rx.await.unwrap(); + let unused = match &stream.send { + H2Send::Direct(native) => Some(native.capacity()), + H2Send::Shared(_) => None, + }; + release.send(()).unwrap(); + drop((stream, sender)); + (received, unused) + }; + let ((received, unused), (), driver) = tokio::time::timeout(Duration::from_secs(8), async { + tokio::join!(client, server, connection) + }) + .await + .expect("full-write duplex owners did not finish"); + // The behavioral assertions follow natural completion of both owners. + assert!(driver.is_ok(), "client cleanup failed: {driver:?}"); + assert_eq!(received, expected, "full-write DATA changed bytes or order"); + assert_eq!( + unused, + Some(0), + "idle full writer retained unaccepted credit" + ); +} + +#[tokio::test] +async fn private_h2mux_full_write_leaves_no_idle_unaccepted_credit() { + for buffered_prefix in [false, true] { + exercise_full_accept_idle(buffered_prefix).await; + } +} diff --git a/src/transport/grpc_private_rst_memory_tests.rs b/src/transport/grpc_private_rst_memory_tests.rs new file mode 100644 index 0000000..4f15a60 --- /dev/null +++ b/src/transport/grpc_private_rst_memory_tests.rs @@ -0,0 +1,252 @@ +//! Real h2 duplex peers: capacity/reset ordering, not CPU or throughput proof. +use super::*; +use futures_util::{FutureExt, future::poll_fn}; +use std::{ + panic::{AssertUnwindSafe, resume_unwind}, + sync::atomic::{AtomicUsize, Ordering}, + task::{Wake, Waker}, + time::Duration, +}; +use tokio::io::AsyncWriteExt; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Scenario { + ZeroCapacity, + ReadyCapacity, + EmptyWrite, + CapacityThenReset, + FinAfterPrefix, + PeerEof, +} + +#[derive(Default)] +struct WriteWake { + count: AtomicUsize, + changed: tokio::sync::Notify, +} +impl Wake for WriteWake { + fn wake(self: Arc) { + self.wake_by_ref(); + } + fn wake_by_ref(self: &Arc) { + self.count.fetch_add(1, Ordering::SeqCst); + self.changed.notify_one(); + } +} + +async fn exercise(scenario: Scenario) { + let (raw, peer) = tokio::io::duplex(64 * 1024); + let (raw, writes) = Writes::wrap(Box::new(raw)); + let (mut sender, connection) = h2::client::Builder::new() + .enable_push(false) + .max_send_buffer_size(CHUNK) + .handshake::<_, Payload>(raw) + .await + .unwrap(); + let (ready, ready_rx) = tokio::sync::oneshot::channel(); + let (reset, reset_rx) = tokio::sync::oneshot::channel(); + let (prefix, prefix_rx) = tokio::sync::oneshot::channel(); + let server = async move { + let window = if matches!(scenario, Scenario::ZeroCapacity | Scenario::PeerEof) { + 0 + } else { + CHUNK as u32 + }; + let mut connection = h2::server::Builder::new() + .initial_window_size(window) + .handshake::<_, Bytes>(peer) + .await + .unwrap(); + let (request, mut response) = connection.accept().await.unwrap().unwrap(); + let mut output = response + .send_response(http::Response::new(()), false) + .unwrap(); + drop(response); + let mut input = request.into_body(); + let mut ping = connection.ping_pong().unwrap(); + macro_rules! drive { + ($future:expr) => {{ + let future = $future; tokio::pin!(future); + loop { + tokio::select! { biased; + result = &mut future => break result, + next = connection.accept() => { + assert!(matches!(next, Some(Ok(_))), "peer closed before control barrier"); + } + } + } + }}; + } + // The second genuine PING is after the initial SETTINGS, as in the + // existing partial-credit fixture; no simulated capacity/reset state. + drive!(ping.ping(h2::Ping::opaque())).unwrap(); + drive!(ping.ping(h2::Ping::opaque())).unwrap(); + ready.send(()).unwrap(); + if scenario == Scenario::FinAfterPrefix { + let bytes = drive!(input.data()).unwrap().unwrap(); + assert_eq!(bytes.as_ref(), b"before"); + input.flow_control().release_capacity(bytes.len()).unwrap(); + prefix.send(()).unwrap(); + } else { + drop(prefix); + } + drive!(reset_rx).unwrap(); + if scenario == Scenario::PeerEof { + // Dropping the actual peer connection/IO exercises the library's + // connection error wake-up, not a manual CoalescedAck failure. + drop((input, output, ping, connection)); + return; + } + output.send_reset(h2::Reason::CANCEL); + drop((input, output, ping)); + while let Some(result) = connection.accept().await { + result.unwrap(); + } + }; + let client = async move { + let request = http::Request::builder() + .method("CONNECT") + .uri("https://fixture.invalid") + .body(()) + .unwrap(); + let (response, send) = sender.send_request(request, false).unwrap(); + // Same typed constructor and marker as private mux_stream. Keep the + // actual native SendStream visible to observe its protocol barriers. + let mut stream = Grpc::new( + response, + send, + Framing::Plain, + true, + Instant::now() + Duration::from_secs(5), + Arc::default(), + None, + None, + writes, + ); + let ack = Arc::new(CoalescedAck::default()); + stream.coalesced = Some(ack.clone()); + stream.response_deadline = false; + ready_rx.await.unwrap(); + let rejected; + let mut fin_stayed_open = true; + if matches!(scenario, Scenario::ZeroCapacity | Scenario::PeerEof) { + let mut writing = Box::pin(stream.write(b"blocked")); + let wake = Arc::new(WriteWake::default()); + let waker = Waker::from(wake.clone()); + let mut observed = wake.count.load(Ordering::SeqCst); + assert!( + writing + .as_mut() + .poll(&mut Context::from_waker(&waker)) + .is_pending() + ); + reset.send(()).unwrap(); + // The peer and driver share the parent task, but the write is not + // repolled by those wakes. Only its own registered waiter permits it. + let completed = loop { + while wake.count.load(Ordering::SeqCst) == observed { + wake.changed.notified().await; + } + observed = wake.count.load(Ordering::SeqCst); + if let Poll::Ready(result) = writing.as_mut().poll(&mut Context::from_waker(&waker)) + { + break result; + } + }; + let error = completed.unwrap_err(); + rejected = error.kind() == io::ErrorKind::BrokenPipe; + } else { + if scenario == Scenario::FinAfterPrefix { + stream.write_all(b"before").await.unwrap(); + stream.flush().await.unwrap(); + prefix_rx.await.unwrap(); + } else { + stream.send.reserve_capacity(CHUNK); + let capacity = poll_fn(|cx| stream.send.poll_capacity(cx)) + .await + .unwrap() + .unwrap(); + assert!( + capacity > 0, + "fixture did not establish genuine spare credit" + ); + } + reset.send(()).unwrap(); + // Establish receipt of the peer's real RST before checking writes. + // poll_reset observes state only; it does not fail CoalescedAck. + let reason = poll_fn(|cx| stream.send.poll_reset(cx)).await.unwrap(); + assert_eq!(reason, h2::Reason::CANCEL); + rejected = match scenario { + Scenario::CapacityThenReset => { + // This tests the native guard for the capacity->send race; + // it does not pretend to interleave inside Grpc's function. + let payload = stream + .writes + .coalesced_payload(Bytes::from_static(b"late"), &ack) + .unwrap(); + stream.send.send_data(payload, false).is_err() + } + Scenario::EmptyWrite => { + poll_fn(|cx| Pin::new(&mut stream).poll_write(cx, &[])) + .await + .unwrap_err() + .kind() + == io::ErrorKind::BrokenPipe + } + Scenario::FinAfterPrefix => { + let rejected = + stream.shutdown().await.unwrap_err().kind() == io::ErrorKind::BrokenPipe; + fin_stayed_open = !stream.upload_closed; + rejected + } + Scenario::ReadyCapacity => { + stream.write(b"late").await.unwrap_err().kind() == io::ErrorKind::BrokenPipe + } + _ => unreachable!(), + }; + } + let ack_failed_before_drop = + poll_fn(|cx| Poll::Ready(matches!(ack.poll_flushed(cx), Poll::Ready(Err(_))))).await; + // Dropping this logical stream then the last sender lets both real h2 + // connection futures finish. No spawned task/abort is used as a PASS. + drop((stream, sender)); + (rejected, ack_failed_before_drop, fin_stayed_open) + }; + let result = AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(8), async { + tokio::join!(client, server, connection) + })) + .catch_unwind() + .await; + let ((rejected, ack_failed, fin_stayed_open), (), driver) = match result { + Ok(result) => result.expect("duplex protocol owners did not finish"), + Err(panic) => resume_unwind(panic), + }; + if scenario != Scenario::PeerEof { + assert!(driver.is_ok(), "client owner failed: {driver:?}"); + } + assert!( + rejected, + "RST/EOF admitted a late write or FIN: {scenario:?}" + ); + if scenario != Scenario::FinAfterPrefix { + assert!( + ack_failed, + "terminal write did not fail/wake its private ack before Drop: {scenario:?}" + ); + } + assert!(fin_stayed_open, "failed FIN changed local upload state"); +} + +#[tokio::test] +async fn private_h2mux_real_peer_reset_covers_credit_empty_write_fin_and_eof() { + for scenario in [ + Scenario::ZeroCapacity, + Scenario::ReadyCapacity, + Scenario::EmptyWrite, + Scenario::CapacityThenReset, + Scenario::FinAfterPrefix, + Scenario::PeerEof, + ] { + exercise(scenario).await; + } +} diff --git a/src/transport/h2_empty.rs b/src/transport/h2_empty.rs index a1407c3..3915bbe 100644 --- a/src/transport/h2_empty.rs +++ b/src/transport/h2_empty.rs @@ -15,6 +15,10 @@ use std::{ }; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; +// Keep recently cancelled TrustTunnel streams through a burst of CONNECTs +// so the h2 client can discard responses already in flight. +pub(super) const RECENT_RESET_STREAMS: usize = 256; + #[derive(Clone, Default)] pub(super) struct Registry(Arc); @@ -481,7 +485,7 @@ impl AsyncWrite for EmptyIo { #[cfg(test)] mod tests { use super::super::h2_write::{Payload, Writes}; - use super::{Registry, Send, Ticket}; + use super::{RECENT_RESET_STREAMS, Registry, Send, Ticket}; use crate::{ dispatch::BoxStream, resources::observation::{self, ResourceKind, ResourceProbe}, @@ -517,6 +521,7 @@ mod tests { .enable_push(false) .initial_window_size(64 * 1024) .initial_connection_window_size(128 * 1024) + .max_concurrent_reset_streams(RECENT_RESET_STREAMS) .handshake::<_, Payload>(registry.wrap(Box::new(raw))) .await .unwrap(); @@ -723,6 +728,85 @@ mod tests { response.into_body() } + #[tokio::test] + async fn recently_cancelled_connect_retains_late_response_state() { + let probe = ResourceProbe::default(); + let result = timeout( + DEADLINE, + probe.scope(async { + let (mut client, mut peer) = raw_peer().await; + let (response, send, ticket, sibling_id) = client.request().await; + let mut sibling = admit_raw(&mut peer, response, &ticket, sibling_id, false).await; + + let mut cancelled = 0; + for _ in 0..192 { + let (response, mut send, ticket, id) = client.request().await; + request_reached_peer(&mut peer, id).await; + ticket.close(); + send.send_reset(h2::Reason::CANCEL); + drop((response, send, ticket)); + loop { + let (kind, _, incoming, payload) = read_frame(&mut peer).await; + if kind == 3 && incoming == id { + assert_eq!(payload, u32::from(h2::Reason::CANCEL).to_be_bytes()); + break; + } + } + cancelled = id; + } + + // The last CONNECT closes before its response reaches the + // client. Its already-sent headers and final DATA arrive + // together with the sibling's response on the same carrier. + let marker = *b"retained"; + let mut batch = frame(1, 4, cancelled, &[0x88]); + batch.extend(frame(0, 1, cancelled, b"late")); + batch.extend(frame(0, 1, sibling_id, b"alive")); + batch.extend(frame(6, 0, 0, &marker)); + peer.write_all(&batch).await.unwrap(); + + let mut redundant_resets = Vec::new(); + loop { + let (kind, flags, id, payload) = read_frame(&mut peer).await; + if kind == 3 && id == cancelled { + redundant_resets + .push(u32::from_be_bytes(payload.as_slice().try_into().unwrap())); + } + if (kind, flags, id) == (6, 1, 0) && payload == marker { + break; + } + } + // PONG bypasses the stream output queue. A subsequently + // submitted request observes earlier stream output before Stop. + let (next_response, next_send, next_ticket, next_id) = client.request().await; + loop { + let (kind, _, id, payload) = read_frame(&mut peer).await; + if kind == 3 && id == cancelled { + redundant_resets + .push(u32::from_be_bytes(payload.as_slice().try_into().unwrap())); + } + if kind == 1 && id == next_id { + break; + } + } + let received = body(&mut sibling).await; + client.stop().await; + drop((next_response, next_send, next_ticket)); + drop((sibling, send, ticket, client, peer)); + (redundant_resets, received) + }), + ) + .await + .expect("cancelled CONNECT fixture failed to complete"); + assert!(probe.snapshot().is_idle()); + assert!( + result.0.is_empty(), + "late response reset the closed CONNECT again: {:?}", + result.0 + ); + assert_eq!(result.1, b"alive"); + } + #[tokio::test] async fn interleaved_empty_data_preserves_payload_final_sibling_and_joined_stop() { let probe = ResourceProbe::default(); diff --git a/src/transport/h2_write.rs b/src/transport/h2_write.rs index efb4fcd..8ede020 100644 --- a/src/transport/h2_write.rs +++ b/src/transport/h2_write.rs @@ -5,7 +5,10 @@ use bytes::{Buf, Bytes}; #[cfg(feature = "sing-mux")] use futures_util::task::AtomicWaker; #[cfg(feature = "sing-mux")] -use std::sync::Weak; +use std::sync::{ + Weak, + atomic::{AtomicBool, Ordering}, +}; use std::{ io, pin::Pin, @@ -43,6 +46,19 @@ enum Encoded { Coalesced(Weak), } +// A cohort is detached only at a codec-drained physical flush boundary. +// Later Payload::advance calls must not change its confirmation watermark. +// Fair-drain caps additional raw admission, not retained payload memory. +#[cfg(feature = "sing-mux")] +const PRIVATE_PENDING_FLUSH_WRITE_BYTES: usize = crate::limits::XHTTP_H3_PACKET_BATCH_BYTES; + +#[cfg(feature = "sing-mux")] +#[derive(Debug)] +enum Frozen { + Strong(Completion), + Coalesced(Weak, u64), +} + #[derive(Default, Debug)] struct State { closed: bool, @@ -56,6 +72,7 @@ struct State { pub(super) struct CoalescedAck { state: Mutex, wake: AtomicWaker, + barrier_requested: AtomicBool, } #[cfg(feature = "sing-mux")] @@ -82,17 +99,27 @@ impl CoalescedAck { pub(super) fn poll_flushed(&self, cx: &mut Context<'_>) -> Poll> { self.wake.register(cx.waker()); let state = self.state.lock().unwrap(); - if let Some(error) = state.error { + let result = if let Some(error) = state.error { Poll::Ready(Err(error.into())) } else if state.flushed == state.submitted { Poll::Ready(Ok(())) } else { Poll::Pending - } + }; + // Record an explicit logical flush/FIN request, not ordinary DATA. + // Set and clear under AckState so an old completion cannot erase a + // later caller's request. Cancellation may conservatively leave it set. + self.barrier_requested + .store(result.is_pending(), Ordering::Release); + result } pub(super) fn fail(&self, error: io::ErrorKind) { - self.state.lock().unwrap().error.get_or_insert(error); + { + let mut state = self.state.lock().unwrap(); + state.error.get_or_insert(error); + self.barrier_requested.store(false, Ordering::Release); + } self.wake.wake(); } } @@ -137,6 +164,35 @@ impl State { } } + #[cfg(feature = "sing-mux")] + fn freeze_private(&mut self) -> Option> { + if !self + .encoded + .iter() + .any(|entry| matches!(entry, Encoded::Coalesced(weak) if weak.strong_count() != 0)) + { + return None; + } + self.prune_remaining = 0; + Some( + std::mem::take(&mut self.encoded) + .into_iter() + .filter_map(|entry| match entry { + Encoded::Strong(done) => Some(Frozen::Strong(done)), + Encoded::Coalesced(weak) => { + let ack = weak.upgrade()?; + let mut progress = ack.state.lock().unwrap(); + let ticket = progress.encoded; + // New tickets can register in the next current cohort. + // Completing this frozen cohort must not clear that flag. + progress.registered = false; + Some(Frozen::Coalesced(weak, ticket)) + } + }) + .collect(), + ) + } + // Only the h2 Connection advances Payloads and flushes its supplied IO. // Its codec drains encoded bytes before entering raw.poll_flush. Marking // and deregistration stay in one Writes critical section; wake outside it. @@ -183,6 +239,32 @@ fn notify_finished(encoded: Vec, error: Option, strong: } } +#[cfg(feature = "sing-mux")] +fn notify_frozen(encoded: Vec, error: Option, strong: bool) { + for entry in encoded { + match entry { + Frozen::Strong(done) => { + if strong { + let _ = done.send(error.map_or(Ok(()), |error| Err(error.into()))); + } + } + Frozen::Coalesced(weak, ticket) => { + if let Some(ack) = weak.upgrade() { + let mut progress = ack.state.lock().unwrap(); + if let Some(error) = error { + progress.error.get_or_insert(error); + } else if progress.error.is_none() { + // Frozen cohorts complete FIFO, before current state. + progress.flushed = ticket; + } + drop(progress); + ack.wake.wake(); + } + } + } + } +} + impl Writes { pub fn wrap(raw: BoxStream) -> (impl AsyncRead + AsyncWrite + Unpin + Send, Self) { let writes = Self::default(); @@ -192,6 +274,10 @@ impl Writes { writes: writes.clone(), #[cfg(feature = "sing-mux")] wrote_since_flush: false, + #[cfg(feature = "sing-mux")] + pending_flush: None, + #[cfg(feature = "sing-mux")] + pending_write_bytes: 0, }, writes, ) @@ -301,15 +387,57 @@ struct FlushIo { writes: Writes, #[cfg(feature = "sing-mux")] wrote_since_flush: bool, + #[cfg(feature = "sing-mux")] + pending_flush: Option>, + #[cfg(feature = "sing-mux")] + pending_write_bytes: usize, +} +impl FlushIo { + #[cfg(feature = "sing-mux")] + fn has_requested_barrier(&self) -> bool { + if self.pending_flush.as_ref().is_some_and(|cohort| { + cohort.iter().any(|entry| match entry { + Frozen::Strong(_) => true, + Frozen::Coalesced(weak, _) => weak + .upgrade() + .is_some_and(|ack| ack.barrier_requested.load(Ordering::Acquire)), + }) + }) { + return true; + } + self.writes + .0 + .lock() + .unwrap() + .encoded + .iter() + .any(|entry| match entry { + Encoded::Strong(_) => true, + Encoded::Coalesced(weak) => weak + .upgrade() + .is_some_and(|ack| ack.barrier_requested.load(Ordering::Acquire)), + }) + } + + #[cfg(feature = "sing-mux")] + fn finish_pending(&mut self, error: Option, strong: bool) { + if let Some(encoded) = self.pending_flush.take() { + self.pending_write_bytes = 0; + notify_frozen(encoded, error, strong); + } + } + + fn finish_current(&mut self, error: Option, strong: bool) { + let encoded = self.writes.0.lock().unwrap().finish(error); + notify_finished(encoded, error, strong); + } } impl Drop for FlushIo { fn drop(&mut self) { - let encoded = { - let mut state = self.writes.0.lock().unwrap(); - state.closed = true; - state.finish(Some(io::ErrorKind::BrokenPipe)) - }; - notify_finished(encoded, Some(io::ErrorKind::BrokenPipe), false); + self.writes.0.lock().unwrap().closed = true; + #[cfg(feature = "sing-mux")] + self.finish_pending(Some(io::ErrorKind::BrokenPipe), false); + self.finish_current(Some(io::ErrorKind::BrokenPipe), false); } } impl AsyncRead for FlushIo { @@ -327,10 +455,55 @@ impl AsyncWrite for FlushIo { cx: &mut Context<'_>, input: &[u8], ) -> Poll> { + #[cfg(feature = "sing-mux")] + if !input.is_empty() && self.pending_flush.is_some() { + // The codec may already have advanced a new Payload into current + // state, even though none of that frame has reached rawWrite yet. + // A ready old flush may confirm only its previously frozen cohort. + if let Poll::Ready(result) = Pin::new(&mut self.raw).poll_flush(cx) { + let error = result.as_ref().err().map(io::Error::kind); + self.finish_pending(error, true); + self.wrote_since_flush = false; + if let Err(error) = result { + self.finish_current(Some(error.kind()), true); + return Poll::Ready(Err(error)); + } + } + // Pending permits bounded productive writes. Once that allowance + // is exhausted, the raw flush waker/timer must create a quiet gap. + } + #[cfg(feature = "sing-mux")] + let input = if !input.is_empty() && self.pending_flush.is_some() { + let remaining = + PRIVATE_PENDING_FLUSH_WRITE_BYTES.saturating_sub(self.pending_write_bytes); + if remaining == 0 { + // A late logical waiter is checked against both current and + // frozen owners. Ordinary DATA needs only PacketUp backpressure. + if self.has_requested_barrier() { + // The real raw flush above already registered its waker. + return Poll::Pending; + } + input + } else { + &input[..input.len().min(remaining)] + } + } else { + input + }; let result = Pin::new(&mut self.raw).poll_write(cx, input); #[cfg(feature = "sing-mux")] if matches!(&result, Poll::Ready(Ok(count)) if *count > 0) { self.wrote_since_flush = true; + if self.pending_flush.is_some() + && let Poll::Ready(Ok(count)) = &result + { + // Ordinary DATA can continue beyond this observation threshold; + // keep only saturated metadata for a later explicit barrier. + self.pending_write_bytes = self + .pending_write_bytes + .saturating_add(*count) + .min(PRIVATE_PENDING_FLUSH_WRITE_BYTES); + } } result } @@ -338,15 +511,28 @@ impl AsyncWrite for FlushIo { let result = Pin::new(&mut self.raw).poll_flush(cx); #[cfg(feature = "sing-mux")] { + if result.is_pending() && self.pending_flush.is_none() { + // Only this entry point is codec-drained. Do not snapshot + // current encoded markers at the pre-write probe above. + let pending = self.writes.0.lock().unwrap().freeze_private(); + self.pending_flush = pending; + self.pending_write_bytes = 0; + } // A chained h2 DATA can drain before its stronger IO flush is // ready. Re-poll productive private owners once so already queued // frames can fill the same bounded PacketUp batch. - let repoll = result.is_pending() && std::mem::take(&mut self.wrote_since_flush) && { - let state = self.writes.0.lock().unwrap(); - state.encoded.iter().any( + let repoll = result.is_pending() + && std::mem::take(&mut self.wrote_since_flush) + && { + let state = self.writes.0.lock().unwrap(); + state.encoded.iter().any( |entry| matches!(entry, Encoded::Coalesced(weak) if weak.strong_count() != 0), - ) - }; + ) || self.pending_flush.as_ref().is_some_and(|cohort| { + cohort.iter().any( + |entry| matches!(entry, Frozen::Coalesced(weak, _) if weak.strong_count() != 0), + ) + }) + }; if repoll { cx.waker().wake_by_ref(); } @@ -357,8 +543,11 @@ impl AsyncWrite for FlushIo { self.wrote_since_flush = false; } let error = result.as_ref().err().map(io::Error::kind); - let encoded = self.writes.0.lock().unwrap().finish(error); - notify_finished(encoded, error, true); + #[cfg(feature = "sing-mux")] + self.finish_pending(error, true); + // Normal poll_flush follows a fully drained codec, so current markers + // are now written too. Preserve pending -> current confirmation order. + self.finish_current(error, true); Poll::Ready(result) } fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { @@ -557,6 +746,10 @@ mod tests { } } +#[cfg(all(test, feature = "sing-mux"))] +#[path = "h2_write_prefix_wire_tests.rs"] +mod prefix_wire_tests; + #[cfg(all(test, feature = "sing-mux"))] mod productive_repoll_memory_tests { use super::*; @@ -805,6 +998,208 @@ mod productive_repoll_memory_tests { ); } + #[tokio::test] + async fn frozen_private_cohort_cannot_confirm_a_new_same_ack_ticket_before_raw_write() { + let mut fixture = Fixture::new(); + let ack = fixture.coalesced(); + let mut old_strong = fixture.strong(); + let first_write = fixture.write(b"old"); + let first_flush = fixture.flush(); + // Simulate the codec's small-DATA advance before its rawWrite. B's + // real h2 Connection fixture independently covers that ordering. + let mut next = fixture + .writes + .coalesced_payload(Bytes::from_static(b"next"), &ack) + .unwrap(); + next.advance(4); + drop(next); + let mut new_strong = fixture.strong(); + fixture.control.flush.store(1, Ordering::SeqCst); + fixture.control.write.store(1, Ordering::SeqCst); + let blocked_new_write = fixture.write(b"next"); + let old_completed = matches!(old_strong.try_recv(), Ok(Ok(()))); + let new_still_pending = matches!( + new_strong.try_recv(), + Err(oneshot::error::TryRecvError::Empty) + ); + let ack_still_pending = acknowledged(&ack).is_pending(); + let frozen_progress = { + let state = ack.state.lock().unwrap(); + ( + state.flushed, + state.encoded, + state.submitted, + state.registered, + ) + }; + fixture.control.flush.store(0, Ordering::SeqCst); + fixture.control.write.store(0, Ordering::SeqCst); + let next_write = fixture.write(b"next"); + let next_flush = fixture.flush(); + fixture.control.flush.store(1, Ordering::SeqCst); + let final_flush = fixture.flush(); + let new_completed = matches!(new_strong.try_recv(), Ok(Ok(()))); + let ack_completed = matches!(acknowledged(&ack), Poll::Ready(Ok(()))); + let final_ticket = ack.state.lock().unwrap().flushed; + drop(fixture.raw); + + assert!(matches!(first_write, Poll::Ready(Ok(3))) && first_flush.is_pending()); + assert!(blocked_new_write.is_pending() && old_completed); + assert!(new_still_pending && ack_still_pending); + assert_eq!(frozen_progress, (1, 2, 2, true)); + assert!(matches!(next_write, Poll::Ready(Ok(4))) && next_flush.is_pending()); + assert!(matches!(final_flush, Poll::Ready(Ok(())))); + assert!(new_completed && ack_completed); + assert_eq!( + final_ticket, 2, + "an old cohort rolled confirmation backwards" + ); + } + + #[tokio::test] + async fn ordinary_strong_owner_never_probes_an_old_private_flush_before_write() { + let mut fixture = Fixture::new(); + let mut receipt = fixture.strong(); + let write = fixture.write(b"old"); + let pending = fixture.flush(); + fixture.control.flush.store(1, Ordering::SeqCst); + fixture.control.write.store(1, Ordering::SeqCst); + let blocked = fixture.write(b"next"); + let receipt_pending = + matches!(receipt.try_recv(), Err(oneshot::error::TryRecvError::Empty)); + let ready = fixture.flush(); + let completed = matches!(receipt.try_recv(), Ok(Ok(()))); + drop(fixture.raw); + + assert!(matches!(write, Poll::Ready(Ok(3))) && pending.is_pending()); + assert!(blocked.is_pending() && receipt_pending); + assert!(matches!(ready, Poll::Ready(Ok(()))) && completed); + } + + #[tokio::test] + async fn frozen_and_current_receipts_both_terminate_on_probe_error_or_driver_drop() { + let mut observations = Vec::new(); + for probe_error in [true, false] { + let mut fixture = Fixture::new(); + let ack = fixture.coalesced(); + let mut old_receipt = fixture.strong(); + let write = fixture.write(b"old"); + let pending = fixture.flush(); + let mut next = fixture + .writes + .coalesced_payload(Bytes::from_static(b"next"), &ack) + .unwrap(); + next.advance(4); + drop(next); + let mut new_receipt = fixture.strong(); + let probe_failed = if probe_error { + fixture.control.flush.store(2, Ordering::SeqCst); + matches!(fixture.write(b"next"), Poll::Ready(Err(error)) + if error.kind() == io::ErrorKind::ConnectionReset) + } else { + true + }; + drop(fixture.raw); + let old = old_receipt.try_recv(); + let new = new_receipt.try_recv(); + let kind = match acknowledged(&ack) { + Poll::Ready(Err(error)) => Some(error.kind()), + _ => None, + }; + let receipts_terminated = if probe_error { + matches!(old, Ok(Err(error)) if error.kind() == io::ErrorKind::ConnectionReset) + && matches!(new, Ok(Err(error)) if error.kind() == io::ErrorKind::ConnectionReset) + } else { + matches!(old, Err(oneshot::error::TryRecvError::Closed)) + && matches!(new, Err(oneshot::error::TryRecvError::Closed)) + }; + observations.push((write, pending, probe_failed, kind, receipts_terminated)); + } + for (index, (write, pending, probe_failed, kind, receipts_terminated)) in + observations.into_iter().enumerate() + { + assert!(matches!(write, Poll::Ready(Ok(3))) && pending.is_pending()); + assert!(probe_failed && receipts_terminated); + assert_eq!( + kind, + Some(if index == 0 { + io::ErrorKind::ConnectionReset + } else { + io::ErrorKind::BrokenPipe + }) + ); + } + } + + #[tokio::test] + async fn old_cohort_completion_preserves_a_new_same_ack_barrier() { + let mut fixture = Fixture::new(); + let ack = fixture.coalesced(); + let first_write = fixture.write(b"old"); + let first_flush = fixture.flush(); + let mut next = fixture + .writes + .coalesced_payload(Bytes::from_static(b"next"), &ack) + .unwrap(); + next.advance(4); + drop(next); + let requested = acknowledged(&ack).is_pending(); + fixture.control.flush.store(1, Ordering::SeqCst); + fixture.control.write.store(1, Ordering::SeqCst); + let blocked_new_write = fixture.write(b"next"); + let old_ticket = ack.state.lock().unwrap().flushed; + // Do not poll the ACK again: that would mask an old completion that + // accidentally cleared the already-requested second-ticket barrier. + fixture.control.flush.store(0, Ordering::SeqCst); + fixture.control.write.store(0, Ordering::SeqCst); + let next_write = fixture.write(b"next"); + let next_flush = fixture.flush(); + let chunk = [0; 1024]; + let mut productive = true; + for _ in 0..PRIVATE_PENDING_FLUSH_WRITE_BYTES / chunk.len() { + productive &= matches!(fixture.write(&chunk), Poll::Ready(Ok(1024))); + } + let barrier_stopped = fixture.write(b"x").is_pending(); + fixture.control.flush.store(1, Ordering::SeqCst); + let finished = fixture.flush(); + let acknowledged = matches!(acknowledged(&ack), Poll::Ready(Ok(()))); + drop(fixture.raw); + assert!(matches!(first_write, Poll::Ready(Ok(3))) && first_flush.is_pending()); + assert!(requested && blocked_new_write.is_pending()); + assert_eq!(old_ticket, 1); + assert!(matches!(next_write, Poll::Ready(Ok(4))) && next_flush.is_pending()); + assert!( + productive && barrier_stopped, + "old ticket erased a new flush request" + ); + assert!(matches!(finished, Poll::Ready(Ok(()))) && acknowledged); + } + + #[tokio::test] + async fn current_strong_receipt_still_requires_the_exhausted_private_gate() { + let mut fixture = Fixture::new(); + let _ordinary = fixture.coalesced(); + let first_write = fixture.write(b"old"); + let first_flush = fixture.flush(); + let chunk = [0; 1024]; + let mut productive = true; + for _ in 0..PRIVATE_PENDING_FLUSH_WRITE_BYTES / chunk.len() { + productive &= matches!(fixture.write(&chunk), Poll::Ready(Ok(1024))); + } + let mut receipt = fixture.strong(); + let stopped = fixture.write(b"new").is_pending(); + let pending = matches!(receipt.try_recv(), Err(oneshot::error::TryRecvError::Empty)); + // These new encoded Strong bytes never reached a codec-drained flush. + // Drop must cancel them rather than manufacture a successful receipt. + drop(fixture.raw); + let cancelled = matches!( + receipt.try_recv(), + Err(oneshot::error::TryRecvError::Closed) + ); + assert!(matches!(first_write, Poll::Ready(Ok(3))) && first_flush.is_pending()); + assert!(productive && stopped && pending && cancelled); + } + #[tokio::test] async fn expired_coalesced_owner_does_not_qualify_ordinary_progress() { let mut fixture = Fixture::new(); diff --git a/src/transport/h2_write_prefix_wire_tests.rs b/src/transport/h2_write_prefix_wire_tests.rs new file mode 100644 index 0000000..0059ae9 --- /dev/null +++ b/src/transport/h2_write_prefix_wire_tests.rs @@ -0,0 +1,605 @@ +//! Real H2 encoding over a bounded moving-prefix supplied IO. +//! No Payload::advance or private receipt-state mutation is used here. +use super::*; +use futures_util::task::noop_waker; +use std::future::Future; +use tokio::io::DuplexStream; + +#[derive(Default)] +struct Progress { + accepted: usize, + committed: usize, + automatic: bool, + pending_flushes: usize, + acknowledged: Option, + writes_after_ack: usize, +} +#[derive(Default)] +struct Control { + progress: Mutex, + flush: AtomicWaker, +} +impl Control { + fn automatic(&self, enabled: bool) { + let mut progress = self.progress.lock().unwrap(); + progress.automatic = enabled; + if enabled { + progress.committed = progress.accepted; + } + drop(progress); + self.flush.wake(); + } + fn acknowledge_current_prefix(&self) -> usize { + let mut progress = self.progress.lock().unwrap(); + progress.committed = progress.accepted; + progress.acknowledged = Some(progress.accepted); + let target = progress.accepted; + drop(progress); + self.flush.wake(); + target + } +} +struct MovingIo { + raw: DuplexStream, + control: Arc, +} +impl AsyncRead for MovingIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.raw).poll_read(cx, out) + } +} +impl AsyncWrite for MovingIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + let result = Pin::new(&mut self.raw).poll_write(cx, input); + if let Poll::Ready(Ok(count)) = &result { + let mut progress = self.control.progress.lock().unwrap(); + progress.accepted += *count; + if progress.acknowledged.is_some() { + progress.writes_after_ack += *count; + } + if progress.automatic { + progress.committed = progress.accepted; + } + } + result + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.control.flush.register(cx.waker()); + let mut progress = self.control.progress.lock().unwrap(); + if progress.committed != progress.accepted { + progress.pending_flushes += 1; + return Poll::Pending; + } + drop(progress); + Pin::new(&mut self.raw).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + std::task::ready!(self.as_mut().poll_flush(cx))?; + Pin::new(&mut self.raw).poll_shutdown(cx) + } +} + +struct Fixture { + client: Pin> + Send>>, + peer: h2::server::Connection, + sender: Option>, + requests: [Option>; 2], + responses: [Option; 2], + client_bodies: [Option; 2], + peer_bodies: [Option; 2], + replies: [Option>; 2], + received: [Vec; 2], + held: Vec, + release_udp_credit: bool, + peer_eof: [bool; 2], + client_eof: [bool; 2], + writes: Writes, + control: Arc, + accepted_requests: usize, + client_done: bool, + peer_done: bool, +} +impl Fixture { + async fn open() -> Self { + let (raw, peer) = tokio::io::duplex(65536); + let control = Arc::new(Control::default()); + control.automatic(true); + let (raw, writes) = Writes::wrap(Box::new(MovingIo { + raw, + control: control.clone(), + })); + let (client, peer) = tokio::join!( + h2::client::Builder::new() + .enable_push(false) + .initial_window_size(65536) + .initial_connection_window_size(524288) + .max_frame_size(16384) + .max_header_list_size(16384) + .max_concurrent_streams(0) + .max_send_buffer_size(16384) + .handshake::<_, Payload>(raw), + h2::server::Builder::new().handshake::<_, Bytes>(peer), + ); + let (sender, client) = client.unwrap(); + let mut fixture = Self { + client: Box::pin(client), + peer: peer.unwrap(), + sender: Some(sender), + requests: [None, None], + responses: [None, None], + client_bodies: [None, None], + peer_bodies: [None, None], + replies: [None, None], + received: [Vec::new(), Vec::new()], + held: Vec::new(), + release_udp_credit: false, + peer_eof: [false; 2], + client_eof: [false; 2], + writes, + control, + accepted_requests: 0, + client_done: false, + peer_done: false, + }; + for index in 0..2 { + for _ in 0..128 { + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + if let Poll::Ready(result) = fixture.sender.as_mut().unwrap().poll_ready(&mut cx) { + result.unwrap(); + let request = http::Request::builder() + .method("CONNECT") + .uri("https://localhost") + .body(()) + .unwrap(); + let (response, send) = fixture + .sender + .as_mut() + .unwrap() + .send_request(request, false) + .unwrap(); + fixture.requests[index] = Some(send); + fixture.responses[index] = Some(response); + break; + } + fixture.drive(); + } + assert!( + fixture.requests[index].is_some(), + "CONNECT admission stalled" + ); + } + for _ in 0..128 { + fixture.drive(); + if fixture.accepted_requests == 2 && fixture.client_bodies.iter().all(Option::is_some) { + // Drain handshake/SETTINGS traffic before the controlled phase. + for _ in 0..8 { + fixture.drive(); + } + return fixture; + } + } + panic!("real H2 CONNECT setup did not finish within bounded polls"); + } + fn drive(&mut self) { + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + if !self.client_done { + if let Poll::Ready(result) = self.client.as_mut().poll(&mut cx) { + result.unwrap(); + self.client_done = true; + } + } + if !self.peer_done { + match self.peer.poll_accept(&mut cx) { + Poll::Ready(Some(Ok((request, mut reply)))) => { + let index = self.accepted_requests; + assert!(index < 2, "fixture opened an unexpected stream"); + assert_eq!(request.method(), "CONNECT"); + self.peer_bodies[index] = Some(request.into_body()); + self.replies[index] = + Some(reply.send_response(http::Response::new(()), false).unwrap()); + self.accepted_requests += 1; + } + Poll::Ready(Some(Err(error))) => panic!("H2 peer failed: {error}"), + Poll::Ready(None) => self.peer_done = true, + Poll::Pending => {} + } + } + for index in 0..2 { + if let Some(response) = &mut self.responses[index] { + if let Poll::Ready(result) = Pin::new(response).poll(&mut cx) { + self.client_bodies[index] = Some(result.unwrap().into_body()); + self.responses[index] = None; + } + } + if let Some(body) = &mut self.peer_bodies[index] { + for _ in 0..8 { + match body.poll_data(&mut cx) { + Poll::Ready(Some(Ok(bytes))) => { + self.received[index].extend_from_slice(&bytes); + if index == 1 && self.release_udp_credit { + // Only the sustained sibling control replenishes + // credit, after retaining a bounded payload copy. + body.flow_control().release_capacity(bytes.len()).unwrap(); + } else { + // Existing tests keep their no-credit-rescue control. + self.held.push(bytes); + } + } + Poll::Ready(Some(Err(error))) => panic!("request body failed: {error}"), + Poll::Ready(None) => { + self.peer_eof[index] = true; + break; + } + Poll::Pending => break, + } + } + } + if let Some(body) = &mut self.client_bodies[index] { + match body.poll_data(&mut cx) { + Poll::Ready(Some(Ok(bytes))) => { + assert!(bytes.is_empty(), "unexpected response DATA"); + } + Poll::Ready(Some(Err(error))) => panic!("response body failed: {error}"), + Poll::Ready(None) => self.client_eof[index] = true, + Poll::Pending => {} + } + } + } + } + fn finish(mut self) -> bool { + self.control.automatic(true); + for stream in self.requests.iter_mut().flatten() { + stream.send_data(Payload::empty(), true).unwrap(); + } + for stream in self.replies.iter_mut().flatten() { + stream.send_data(Bytes::new(), true).unwrap(); + } + for _ in 0..128 { + self.drive(); + if self.peer_eof == [true; 2] && self.client_eof == [true; 2] { + break; + } + } + let streams_finished = self.peer_eof == [true; 2] && self.client_eof == [true; 2]; + self.requests = [None, None]; + self.responses = [None, None]; + self.client_bodies = [None, None]; + self.peer_bodies = [None, None]; + self.replies = [None, None]; + self.sender = None; + self.held.clear(); + for _ in 0..128 { + self.drive(); + if self.client_done && self.peer_done { + break; + } + } + streams_finished && self.client_done && self.peer_done + } +} + +#[tokio::test] +async fn acknowledged_raw_prefix_progresses_tcp_metadata_without_signing_new_udp() { + let mut fixture = Fixture::open().await; + let ack = Arc::new(CoalescedAck::default()); + let metadata = Bytes::from_static(b"tcp-metadata"); + let udp = Bytes::from_static(b"new-udp-body"); + fixture.control.automatic(false); + let payload = fixture + .writes + .coalesced_payload(metadata.clone(), &ack) + .unwrap(); + fixture.requests[0] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + for _ in 0..128 { + fixture.drive(); + if fixture.received[0] == metadata + && fixture.control.progress.lock().unwrap().pending_flushes > 0 + { + break; + } + } + let metadata_reached_peer = fixture.received[0] == metadata; + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + let original_pending = ack.poll_flushed(&mut cx).is_pending(); + let old_prefix = fixture.control.acknowledge_current_prefix(); + // ACK wakes the connection, but do not poll it before a sibling admits DATA. + // Only the real Connection advances/encodes either Payload. + let (payload, mut receipt) = fixture.writes.payload(udp.clone()); + fixture.requests[1] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + for _ in 0..128 { + fixture.drive(); + if fixture.received[1] == udp { + break; + } + } + let tcp_ready = matches!(ack.poll_flushed(&mut cx), Poll::Ready(Ok(()))); + let udp_pending = matches!(receipt.try_recv(), Err(oneshot::error::TryRecvError::Empty)); + let udp_reached_peer = fixture.received[1] == udp; + let (accepted, committed, new_raw_bytes) = { + let progress = fixture.control.progress.lock().unwrap(); + ( + progress.accepted, + progress.committed, + progress.writes_after_ack, + ) + }; + let joined = fixture.finish(); + // All inline protocol futures have naturally completed before candidate assertions. + assert!(joined, "real H2 client/peer did not naturally complete"); + assert!( + metadata_reached_peer && original_pending, + "old prefix was not pending" + ); + assert!( + udp_reached_peer && new_raw_bytes > 0 && accepted > old_prefix && committed == old_prefix, + "fixture did not witness new real DATA/rawWrite after acknowledging the old prefix" + ); + assert!( + udp_pending, + "new UDP receipt crossed an unacknowledged raw prefix" + ); + assert!( + tcp_ready, + "old TCP metadata flush chased newly accepted sibling UDP bytes" + ); +} + +#[tokio::test] +async fn sustained_udp_fair_drain_stops_at_raw_budget_inside_a_real_h2_frame() { + // This manually polled codec model does not test Tokio scheduling. + // Isolate its longer fixed sequence from the surrounding test task budget. + tokio::task::unconstrained(async { + let mut fixture = Fixture::open().await; + fixture.release_udp_credit = true; + let ack = Arc::new(CoalescedAck::default()); + let metadata = Bytes::from_static(b"tcp-metadata"); + fixture.control.automatic(false); + let payload = fixture + .writes + .coalesced_payload(metadata.clone(), &ack) + .unwrap(); + fixture.requests[0] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + for _ in 0..128 { + fixture.drive(); + if fixture.received[0] == metadata + && fixture.control.progress.lock().unwrap().pending_flushes > 0 + { + break; + } + } + let old_reached_peer = fixture.received[0] == metadata; + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + let old_initially_pending = ack.poll_flushed(&mut cx).is_pending(); + let base = fixture.control.progress.lock().unwrap().accepted; + let budget = crate::limits::XHTTP_H3_PACKET_BATCH_BYTES; + let chunk = Bytes::from(vec![b'u'; 4096]); + let mut submitted = 0; + let mut receipts = Vec::new(); + // Real flow-credit feedback keeps one sibling producing well beyond a + // single H2 receive window. At most one new 4KiB Payload is queued per turn. + for _ in 0..64 { + let (payload, receipt) = fixture.writes.payload(chunk.clone()); + fixture.requests[1] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + receipts.push(receipt); + submitted += chunk.len(); + for _ in 0..128 { + fixture.drive(); + let accepted = fixture.control.progress.lock().unwrap().accepted - base; + if accepted >= budget || fixture.received[1].len() >= submitted { + break; + } + } + if fixture.control.progress.lock().unwrap().accepted - base >= budget { + break; + } + } + let admitted = fixture.control.progress.lock().unwrap().accepted - base; + let partial_frame_waiting = fixture.received[1].len() < submitted; + // No new write, ACK, empty-write or shutdown may renew the allowance. + for _ in 0..8 { + fixture.drive(); + } + let still_admitted = fixture.control.progress.lock().unwrap().accepted - base; + let old_still_pending = ack.poll_flushed(&mut cx).is_pending(); + let last_before_ack = matches!( + receipts.last_mut().unwrap().try_recv(), + Err(oneshot::error::TryRecvError::Empty) + ); + // ACK the actual raw byte prefix, including only part of the last DATA. + // This models independent PacketUp response feedback, not h2 frame progress. + let acknowledged_prefix = fixture.control.acknowledge_current_prefix(); + for _ in 0..128 { + fixture.drive(); + if fixture.received[1].len() == submitted { + break; + } + } + let tcp_ready = matches!(ack.poll_flushed(&mut cx), Poll::Ready(Ok(()))); + let resumed_frame = fixture.received[1].len() == submitted; + let accepted_after_resume = fixture.control.progress.lock().unwrap().accepted; + let last_after_prefix_ack = matches!( + receipts.last_mut().unwrap().try_recv(), + Err(oneshot::error::TryRecvError::Empty) + ); + let joined = fixture.finish(); + let all_receipts_finished = receipts + .iter_mut() + .all(|receipt| matches!(receipt.try_recv(), Ok(Ok(())))); + + assert!(joined, "real client/peer protocol owners did not finish"); + assert!(old_reached_peer && old_initially_pending); + assert_eq!(budget, 128 * 1024); + assert_eq!( + admitted, budget, + "pending private raw admission exceeded its fixed allowance" + ); + assert_eq!( + still_admitted, admitted, + "Pending polls renewed fair-drain admission" + ); + assert!( + partial_frame_waiting, + "the byte cap did not stop inside the actual last DATA" + ); + assert!(old_still_pending && last_before_ack); + assert!( + tcp_ready && resumed_frame, + "raw-prefix ACK failed to resume the incomplete frame" + ); + assert!(accepted_after_resume > acknowledged_prefix); + assert!( + last_after_prefix_ack, + "the incomplete frame's Strong receipt completed before its suffix was acknowledged" + ); + assert!( + all_receipts_finished, + "normal cleanup lost a submitted Strong receipt" + ); + }) + .await; +} + +#[tokio::test] +async fn ordinary_data_exceeds_the_quiet_budget_until_a_late_flush_requests_it() { + tokio::task::unconstrained(async { + let mut fixture = Fixture::open().await; + fixture.release_udp_credit = true; + let quiet = Arc::new(CoalescedAck::default()); + let data = Arc::new(CoalescedAck::default()); + let prefix = Bytes::from_static(b"ordinary-prefix"); + fixture.control.automatic(false); + let payload = fixture + .writes + .coalesced_payload(prefix.clone(), &quiet) + .unwrap(); + fixture.requests[0] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + for _ in 0..128 { + fixture.drive(); + if fixture.received[0] == prefix + && fixture.control.progress.lock().unwrap().pending_flushes > 0 + { + break; + } + } + let prefix_arrived = fixture.received[0] == prefix; + let base = fixture.control.progress.lock().unwrap().accepted; + let chunk = Bytes::from(vec![b'u'; 4096]); + let target = 40 * chunk.len(); + let mut submitted = 0; + // Never poll either logical ACK during this ordinary DATA phase. + // One new 4KiB Payload is produced only after the preceding peer DATA. + for _ in 0..40 { + let payload = fixture + .writes + .coalesced_payload(chunk.clone(), &data) + .unwrap(); + fixture.requests[1] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + submitted += chunk.len(); + for _ in 0..128 { + fixture.drive(); + if fixture.received[1].len() == submitted { + break; + } + } + if fixture.received[1].len() != submitted { + break; + } + } + let ordinary_received = fixture.received[1].len(); + let before_waiter = fixture.control.progress.lock().unwrap().accepted; + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + // A request arriving after the cohort was frozen must close an already + // exhausted gate. This is an actual logical ACK poll, not a flag edit. + let late_pending = quiet.poll_flushed(&mut cx).is_pending(); + let payload = fixture + .writes + .coalesced_payload(chunk.clone(), &data) + .unwrap(); + fixture.requests[1] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + submitted += chunk.len(); + for _ in 0..8 { + fixture.drive(); + } + let late_stopped = fixture.control.progress.lock().unwrap().accepted == before_waiter; + let strong_bytes = Bytes::from_static(b"current-strong"); + let (payload, mut strong) = fixture.writes.payload(strong_bytes.clone()); + fixture.requests[0] + .as_mut() + .unwrap() + .send_data(payload, false) + .unwrap(); + for _ in 0..8 { + fixture.drive(); + } + let strong_before = matches!(strong.try_recv(), Err(oneshot::error::TryRecvError::Empty)); + let acknowledged = fixture.control.acknowledge_current_prefix(); + for _ in 0..128 { + fixture.drive(); + if fixture.received[1].len() == submitted + && fixture.received[0].len() == prefix.len() + strong_bytes.len() + { + break; + } + } + let prefix_ready = matches!(quiet.poll_flushed(&mut cx), Poll::Ready(Ok(()))); + let resumed = fixture.received[1].len() == submitted + && fixture.received[0] == [prefix.as_ref(), strong_bytes.as_ref()].concat(); + let wrote_suffix = fixture.control.progress.lock().unwrap().accepted > acknowledged; + let strong_after = matches!(strong.try_recv(), Err(oneshot::error::TryRecvError::Empty)); + let joined = fixture.finish(); + let strong_finished = matches!(strong.try_recv(), Ok(Ok(()))); + let ordinary_ack_finished = matches!(data.poll_flushed(&mut cx), Poll::Ready(Ok(()))); + // Intended old-behavior red comes only after actual natural owner exit. + assert!(joined, "real H2 protocol owners did not naturally finish"); + assert!(prefix_arrived && late_pending && late_stopped); + assert!(strong_before && strong_after && strong_finished && ordinary_ack_finished); + assert!(prefix_ready && resumed && wrote_suffix); + assert_eq!( + ordinary_received, target, + "ordinary DATA gained an unrequested quiet barrier" + ); + assert!(before_waiter - base > crate::limits::XHTTP_H3_PACKET_BATCH_BYTES); + }) + .await; +} diff --git a/src/transport/h3_connect.rs b/src/transport/h3_connect.rs index 67c3014..7f8d292 100644 --- a/src/transport/h3_connect.rs +++ b/src/transport/h3_connect.rs @@ -6,7 +6,7 @@ use crate::{ transport::{quic, quiche_h3}, }; use bytes::{Buf, Bytes}; -use futures_util::task::AtomicWaker; +use futures_util::task::{ArcWake, AtomicWaker, waker_ref}; use std::{ future::Future, io, @@ -700,6 +700,12 @@ struct Close { writer: AtomicWaker, cancel: CancellationToken, } +impl ArcWake for Close { + fn wake_by_ref(this: &Arc) { + this.reader.wake(); + this.writer.wake(); + } +} impl Close { fn stop(&self, failed: bool) { if failed { @@ -748,14 +754,21 @@ impl Stream { self.close.writer.register(cx.waker()); self.progress(cx) } - fn progress(&mut self, cx: &mut Context<'_>) -> Poll> { + fn progress(&mut self, _cx: &mut Context<'_>) -> Poll> { if self.stopped() { return Poll::Ready(Err(closed())); } if let Some(pending) = &mut self.pending { - let (send, result) = ready!(pending.as_mut().poll(cx)); + // Both halves can advance this one operation. Native write readiness + // must retain both callers even when the reader stops polling it. + let wake = waker_ref(&self.close); + let mut context = Context::from_waker(&wake); + let (send, result) = ready!(pending.as_mut().poll(&mut context)); self.pending = None; self.send = Some(send); + // A reader can finish the operation without another native wake. + // Re-poll the waiting writer even when both halves share a task. + self.close.writer.wake(); if result.is_err() { self.close.stop(true); } @@ -908,6 +921,8 @@ mod tests { sync::mpsc, }; + include!("h3_connect_write_waker_memory_tests.rs"); + #[cfg(feature = "outbound-masque")] #[tokio::test(start_paused = true)] async fn masque_ip_budget_wait_observes_growth_and_enforces_stop_and_deadline() { @@ -1159,7 +1174,14 @@ mod tests { _=>break, } }; - let (request,mut stream)=request.resolve_request().await.unwrap(); + let (request,mut stream)=match request.resolve_request().await { + Ok(request)=>request, + // A cancelled client may reset before headers resolve. + // Keep the memory peer alive to join its native owner. + Err(h3::error::StreamError::RemoteTerminate {code, ..}) + if code==h3::error::Code::H3_REQUEST_CANCELLED=>continue, + Err(error)=>panic!("memory peer request resolution failed: {error:?}"), + }; assert_eq!(request.method(),http::Method::CONNECT); assert!(request.uri().scheme().is_none()); assert!(request.uri().path_and_query().is_none()); diff --git a/src/transport/h3_connect_write_waker_memory_tests.rs b/src/transport/h3_connect_write_waker_memory_tests.rs new file mode 100644 index 0000000..10fec75 --- /dev/null +++ b/src/transport/h3_connect_write_waker_memory_tests.rs @@ -0,0 +1,896 @@ +// Included inside h3_connect::tests; the existing real memory Peer is reused. +mod write_waker_memory_tests { + use super::*; + use futures_util::{ + FutureExt, + future::poll_fn, + task::{ArcWake, waker_ref}, + }; + use std::panic::{AssertUnwindSafe, resume_unwind}; + + #[derive(Default)] + struct Gate { + paused: AtomicBool, + blocked: AtomicBool, + failed: AtomicBool, + changed: Notify, + observed: Arc, + } + impl Gate { + async fn wait(&self) { + loop { + let changed = self.changed.notified(); + if !self.paused.load(Ordering::Acquire) { + return; + } + self.blocked.store(true, Ordering::Release); + self.observed.notify_one(); + changed.await; + } + } + fn release(&self) { + self.paused.store(false, Ordering::Release); + self.changed.notify_waiters(); + } + } + struct GatedPackets { + inner: Box, + gate: Arc, + } + #[async_trait] + impl DatagramTransport for GatedPackets { + fn supports_shared_destinations(&self) -> bool { + self.inner.supports_shared_destinations() + } + fn payload_budget(&self, peer: &Destination) -> DatagramBudget { + self.inner.payload_budget(peer) + } + async fn send(&mut self, packet: Datagram) -> Result<(), DispatchError> { + self.gate.wait().await; + if self.gate.failed.load(Ordering::Acquire) { + return Err(DispatchError::ConnectionRefused); + } + self.inner.send(packet).await + } + async fn receive(&mut self) -> Result { + self.inner.receive().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.inner.close().await + } + } + + struct Relay { + target: AtomicWaker, + armed: AtomicBool, + wakes: AtomicUsize, + observed: Arc, + } + impl Relay { + fn new(observed: Arc) -> Arc { + Arc::new(Self { + target: AtomicWaker::new(), + armed: AtomicBool::new(false), + wakes: AtomicUsize::new(0), + observed, + }) + } + } + impl ArcWake for Relay { + fn wake_by_ref(this: &Arc) { + // Setup wakes cannot leave an already-runnable writer behind the + // reader's final native registration. No IO result is fabricated. + if this.armed.load(Ordering::Acquire) { + this.wakes.fetch_add(1, Ordering::AcqRel); + this.observed.notify_one(); + this.target.wake(); + } + } + } + struct NativeTap { + caller: AtomicWaker, + notifications: AtomicUsize, + pending_polls: AtomicUsize, + observed: Arc, + } + impl NativeTap { + fn new(observed: Arc) -> Arc { + Arc::new(Self { + caller: AtomicWaker::new(), + notifications: AtomicUsize::new(0), + pending_polls: AtomicUsize::new(0), + observed, + }) + } + } + impl ArcWake for NativeTap { + fn wake_by_ref(this: &Arc) { + // Only the real retained send_data future receives this waker. + // Response-header and response-channel wakes cannot increment it. + this.caller.wake(); + this.notifications.fetch_add(1, Ordering::AcqRel); + this.observed.notify_one(); + } + } + struct TappedOperation { + inner: SendOperation, + tap: Arc, + } + impl Future for TappedOperation { + type Output = (SendHalf, io::Result<()>); + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + let this = self.get_mut(); + this.tap.caller.register(cx.waker()); + let wake = waker_ref(&this.tap); + let result = this.inner.as_mut().poll(&mut Context::from_waker(&wake)); + if result.is_pending() { + this.tap.pending_polls.fetch_add(1, Ordering::AcqRel); + this.tap.observed.notify_one(); + } + result + } + } + + async fn open_typed(pool: &Pool, peer: &Arc, target: &str) -> io::Result { + let factory = peer.clone(); + let (mut sender, lease) = pool + .acquire(Instant::now() + Duration::from_secs(5), move || { + factory.connect() + }) + .await?; + let request = sender + .send_request(request(target)) + .await + .map_err(|_| closed())?; + let (send, receive) = request.split(); + let close = Arc::new(Close::default()); + let headers_close = close.clone(); + let physical = lease.0.clone(); + let cancel = pool.cancellation.clone(); + let (ready, response) = oneshot::channel(); + pool.spawn(async move { + let mut receive = ReceiveHalf(receive); + let result = tokio::select! { biased; + ()=cancel.cancelled()=>Err(closed()), + ()=headers_close.cancel.cancelled()=>Err(closed()), + ()=physical.cancel.cancelled()=>Err(closed()), + response=receive.0.recv_response()=>response + .map_err(|_| closed()).and_then(|response| { + if response.status() == 200 { Ok(()) } else { Err(closed()) } + }), + }; + if result.is_err() { + headers_close.stop(true); + } + let _ = ready.send(result.map(|()| receive)); + })?; + Ok(Stream { + response: Some(response), + receive: None, + send: Some(SendHalf { stream: send }), + pending: None, + data: Bytes::new(), + close, + lease: Some(lease), + finishing: false, + finished: false, + _observation: observation::track(ResourceKind::Session), + }) + } + async fn observe(notify: &Notify, ready: impl Fn() -> bool) -> io::Result<()> { + tokio::time::timeout(Duration::from_secs(3), async { + loop { + let changed = notify.notified(); + if ready() { + return; + } + changed.await; + } + }) + .await + .map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "native-wake setup/event watchdog")) + } + + #[tokio::test(flavor = "current_thread")] + async fn trusttunnel_h3_native_write_wake_reaches_writer_while_reader_response_is_full() { + let probe = ResourceProbe::default(); + let (result, cleanup, empty, calls, closed, close_released) = probe.scope(async { + let peer = Peer::new(); + let pool = Pool::new(None); + let users = TaskTracker::new(); + let cancel = CancellationToken::new(); + let observed = Arc::new(Notify::new()); + let gate = Arc::new(Gate { observed: observed.clone(), ..Default::default() }); + let writer = Relay::new(observed.clone()); + let reader = Relay::new(observed.clone()); + let write_pending = Arc::new(AtomicBool::new(false)); + let read_pending = Arc::new(AtomicBool::new(false)); + let response_pending = Arc::new(AtomicBool::new(false)); + let (responses, mut response) = mpsc::channel(1); + responses.try_send(()).unwrap(); + let mut close_weak = None; + let result = AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(15), async { + let factory = peer.clone(); + let transport_gate = gate.clone(); + pool.probe(request("_check"), Instant::now() + Duration::from_secs(5), move || async move { + let mut raw = factory.connect().await?; + raw.transport = Box::new(GatedPackets { inner: raw.transport, gate: transport_gate }); + Ok(raw) + }).await?; + gate.paused.store(true, Ordering::Release); + let (finished, fin) = oneshot::channel(); + *peer.duplex_fin.lock().unwrap() = Some(finished); + let typed = open_typed(&pool, &peer, "large-duplex.invalid:443").await?; + close_weak = Some(Arc::downgrade(&typed.close)); + let stream = Arc::new(Mutex::new(typed)); + let payload = Arc::new((0..LARGE_DUPLEX_BYTES) + .map(|index| (index as u8).wrapping_mul(31).wrapping_add(7)).collect::>()); + let read_complete = Arc::new(Notify::new()); + let (sent, upload) = oneshot::channel(); + let task_stream = stream.clone(); + let task_payload = payload.clone(); + let task_writer = writer.clone(); + let task_pending = write_pending.clone(); + let task_read_complete = read_complete.clone(); + let task_cancel = cancel.clone(); + users.spawn(observation::task(async move { + let operation = async { + let mut offset = 0; + poll_fn(|cx| { + task_writer.target.register(cx.waker()); + let wake = waker_ref(&task_writer); + let mut native = Context::from_waker(&wake); + let mut stream = task_stream.lock().unwrap(); + while offset < task_payload.len() { + match Pin::new(&mut *stream).poll_write(&mut native, &task_payload[offset..]) { + Poll::Ready(Ok(0)) => return Poll::Ready(Err(io::ErrorKind::WriteZero.into())), + Poll::Ready(Ok(n)) => offset += n, + Poll::Ready(Err(error)) => return Poll::Ready(Err(error)), + Poll::Pending => { + // poll_write can be Pending here only in drain's real + // SendOperation::send_data poll, not in this test gate. + task_pending.store(true, Ordering::Release); + task_writer.observed.notify_one(); + return Poll::Pending; + } + } + } + Pin::new(&mut *stream).poll_flush(&mut native) + }).await?; + task_read_complete.notified().await; + poll_fn(|cx| { + task_writer.target.register(cx.waker()); + let wake = waker_ref(&task_writer); + Pin::new(&mut *task_stream.lock().unwrap()) + .poll_shutdown(&mut Context::from_waker(&wake)) + }).await + }; + let result = tokio::select! { biased; + ()=task_cancel.cancelled()=>Err(io::ErrorKind::Interrupted.into()), + result=operation=>result, + }; + let _ = sent.send(result); + })); + observe(&observed, || write_pending.load(Ordering::Acquire) && gate.blocked.load(Ordering::Acquire)).await?; + + let tap = NativeTap::new(observed.clone()); + { + let mut stream = stream.lock().unwrap(); + let inner = stream.pending.take().ok_or_else(|| io::Error::other("no real retained send operation"))?; + stream.pending = Some(Box::pin(TappedOperation { inner, tap: tap.clone() })); + } + // Re-poll the real writer once after insertion, so the native + // Signals::write slot holds the tap, not a pre-tap caller. + writer.target.wake(); + observe(&observed, || tap.pending_polls.load(Ordering::Acquire) > 0).await?; + let writer_pending_polls = tap.pending_polls.load(Ordering::Acquire); + + let (received, download) = oneshot::channel(); + let task_stream = stream.clone(); + let task_reader = reader.clone(); + let task_read_pending = read_pending.clone(); + let task_response_pending = response_pending.clone(); + let task_cancel = cancel.clone(); + users.spawn(observation::task(async move { + let operation = async { + poll_fn(|cx| { + task_reader.target.register(cx.waker()); + let wake = waker_ref(&task_reader); + let mut byte = [0]; + let mut buffer = ReadBuf::new(&mut byte); + match Pin::new(&mut *task_stream.lock().unwrap()) + .poll_read(&mut Context::from_waker(&wake), &mut buffer) { + Poll::Pending => { + task_read_pending.store(true, Ordering::Release); + Poll::Ready(Ok(())) + } + _ => Poll::Ready(Err(io::Error::other("reader did not replace a real Pending send registration"))), + } + }).await?; + let send = responses.send(()); + tokio::pin!(send); + poll_fn(|cx| { + let result = send.as_mut().poll(cx); + if result.is_pending() { + task_response_pending.store(true, Ordering::Release); + task_reader.observed.notify_one(); + } + result + }).await.map_err(|_| closed())?; + let mut echoed = vec![0; LARGE_DUPLEX_BYTES]; + let mut offset = 0; + poll_fn(|cx| { + let mut stream = task_stream.lock().unwrap(); + while offset < echoed.len() { + let mut buffer = ReadBuf::new(&mut echoed[offset..]); + ready!(Pin::new(&mut *stream).poll_read(cx, &mut buffer))?; + let n = buffer.filled().len(); + if n == 0 { return Poll::Ready(Err(io::ErrorKind::UnexpectedEof.into())); } + offset += n; + } + let mut extra = [0]; + let mut buffer = ReadBuf::new(&mut extra); + ready!(Pin::new(&mut *stream).poll_read(cx, &mut buffer))?; + if !buffer.filled().is_empty() { return Poll::Ready(Err(io::Error::other("extra duplex response bytes"))); } + Poll::Ready(Ok(())) + }).await?; + if echoed != *payload { return Err(io::Error::other("duplex response mismatch")); } + read_complete.notify_one(); + Ok(()) + }; + let result = tokio::select! { biased; + ()=task_cancel.cancelled()=>Err(io::ErrorKind::Interrupted.into()), + result=operation=>result, + }; + let _ = received.send(result); + })); + observe(&observed, || read_pending.load(Ordering::Acquire) && response_pending.load(Ordering::Acquire)).await?; + if tap.pending_polls.load(Ordering::Acquire) <= writer_pending_polls { + return Err(io::Error::other("reader did not poll the real retained native Pending operation")); + } + let setup_wakes_clear = writer.wakes.load(Ordering::Acquire) == 0 && reader.wakes.load(Ordering::Acquire) == 0; + let native_before = tap.notifications.load(Ordering::Acquire); + writer.armed.store(true, Ordering::Release); + reader.armed.store(true, Ordering::Release); + gate.release(); + observe(&observed, || tap.notifications.load(Ordering::Acquire) > native_before).await?; + // Freeze BEFORE rescue, reader unpark and Close::stop: each of + // those may legitimately wake the writer for another reason. + let native_wakes = (writer.wakes.load(Ordering::Acquire), reader.wakes.load(Ordering::Acquire)); + let native_notifications = tap.notifications.load(Ordering::Acquire) - native_before; + let rescue = native_wakes.0 == 0; + response.recv().await.ok_or_else(closed)?; + let complete = async { + upload.await.map_err(|_| closed())??; + download.await.map_err(|_| closed())??; + let bytes = fin.await.map_err(|_| closed())??; + if bytes != LARGE_DUPLEX_BYTES { return Err(io::Error::other("short real request FIN witness")); } + Ok::<_, io::Error>(()) + }; + tokio::pin!(complete); + loop { + tokio::select! { + result=&mut complete=>{ result?; break; }, + ()=tokio::time::sleep(Duration::from_millis(1)), if rescue=>{ + // Recovery only: never enters Relay::wakes or the + // already frozen native verdict. Old source still + // finishes wire/FIN and joins before semantic RED. + writer.target.wake(); + }, + } + } + drop(stream); + Ok::<_, io::Error>((setup_wakes_clear, native_wakes, native_notifications)) + })).catch_unwind().await; + gate.release(); + response.close(); + cancel.cancel(); + writer.target.wake(); + let cleanup = tokio::time::timeout(Duration::from_secs(7), async { + users.close(); users.wait().await; + pool.shutdown().await; + peer.stop().await; + }).await; + let empty = users.is_empty() && pool.tasks.is_empty() && peer.tasks.is_empty(); + let calls = peer.calls.load(Ordering::Acquire); + let closed = peer.closed.load(Ordering::Acquire); + drop((pool, peer)); + let close_released = close_weak.as_ref().is_none_or(|close| close.upgrade().is_none()); + (result, cleanup, empty, calls, closed, close_released) + }).await; + let result = match result { + Ok(result) => result, + Err(panic) => resume_unwind(panic), + }; + cleanup.expect("write-waker Stop/pool/peer join watchdog"); + assert!(empty); + assert_eq!(calls, 1); + assert_eq!(closed, 1); + assert!(probe.snapshot().is_idle()); + assert!( + close_released, + "stream Close waker owner survived joined cleanup" + ); + let (setup_wakes_clear, native_wakes, native_notifications) = result + .expect("write-waker fixture watchdog, not semantic RED") + .expect("write-waker real IO/FIN setup failed, not semantic RED"); + assert!(setup_wakes_clear); + assert!(native_notifications > 0); + assert!( + native_wakes.1 > 0, + "native Pending reader registration never woke" + ); + assert!( + native_wakes.0 > 0, + "native write readiness woke only the parked reader; independent writer required rescue" + ); + } + + #[tokio::test(flavor = "current_thread")] + async fn trusttunnel_h3_reader_ready_handoff_wakes_waiting_writer_without_another_native_event() + { + // The same-waker arm also rejects an optimization that skips handoff + // merely because reader and writer currently share one caller task. + for same_caller in [false, true] { + ready_handoff(same_caller).await; + } + } + + async fn ready_handoff(same_caller: bool) { + let probe = ResourceProbe::default(); + let (result, cleanup, empty, calls, closed, close_released) = + probe + .scope(async { + let peer = Peer::new(); + let pool = Pool::new(None); + let observed = Arc::new(Notify::new()); + let gate = Arc::new(Gate { + observed: observed.clone(), + ..Default::default() + }); + let writer = Relay::new(observed.clone()); + let reader = Relay::new(observed.clone()); + writer.armed.store(true, Ordering::Release); + reader.armed.store(true, Ordering::Release); + let mut close_weak = None; + let result = + AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(15), async { + let factory = peer.clone(); + let transport_gate = gate.clone(); + pool.probe( + request("_check"), + Instant::now() + Duration::from_secs(5), + move || async move { + let mut raw = factory.connect().await?; + raw.transport = Box::new(GatedPackets { + inner: raw.transport, + gate: transport_gate, + }); + Ok(raw) + }, + ) + .await?; + gate.paused.store(true, Ordering::Release); + let (finished, fin) = oneshot::channel(); + *peer.duplex_fin.lock().unwrap() = Some(finished); + let mut stream = + open_typed(&pool, &peer, "large-duplex.invalid:443").await?; + close_weak = Some(Arc::downgrade(&stream.close)); + let payload = (0..LARGE_DUPLEX_BYTES) + .map(|index| (index as u8).wrapping_mul(31).wrapping_add(7)) + .collect::>(); + let write_wake = waker_ref(&writer); + let read_wake = if same_caller { + waker_ref(&writer) + } else { + waker_ref(&reader) + }; + let mut write_context = Context::from_waker(&write_wake); + let first = match Pin::new(&mut stream) + .poll_write(&mut write_context, &payload[..CHUNK]) + { + Poll::Ready(Ok(n)) if n == CHUNK => n, + _ => { + return Err(io::Error::other( + "real initial DATA admission did not accept one CHUNK", + )); + } + }; + if !Pin::new(&mut stream) + .poll_flush(&mut write_context) + .is_pending() + { + return Err(io::Error::other( + "real native send never reached Pending before the gate opened", + )); + } + let tap = NativeTap::new(observed.clone()); + let inner = stream + .pending + .take() + .ok_or_else(|| io::Error::other("missing native pending half"))?; + stream.pending = Some(Box::pin(TappedOperation { + inner, + tap: tap.clone(), + })); + if !stream.drain(&mut write_context).is_pending() + || tap.pending_polls.load(Ordering::Acquire) == 0 + { + return Err(io::Error::other( + "writer did not re-poll the retained native Pending operation", + )); + } + stream.close.reader.register(&read_wake); + if !stream + .progress(&mut Context::from_waker(&read_wake)) + .is_pending() + { + return Err(io::Error::other( + "reader did not take over the retained native Pending operation", + )); + } + gate.release(); + let ready_delta = loop { + let native_before = tap.notifications.load(Ordering::Acquire); + // Re-arm the already-observed waiting writer after earlier + // native wakes. This is a controlled handoff registration, + // not a synthetic send operation or a fake credit result. + stream.close.writer.register(&write_wake); + let before = writer.wakes.load(Ordering::Acquire); + let had_pending = stream.pending.is_some(); + let progress = stream.progress(&mut Context::from_waker(&read_wake)); + let after = writer.wakes.load(Ordering::Acquire); + // No await or driver poll between before/after on this + // current-thread runtime: only this Ready handoff counts. + match progress { + Poll::Ready(Ok(())) if had_pending && stream.pending.is_none() => { + break after - before; + } + Poll::Ready(_) => { + return Err(io::Error::other("native reader completion failed")); + } + Poll::Pending => { + observe(&observed, || { + tap.notifications.load(Ordering::Acquire) > native_before + }) + .await?; + } + } + }; + let (mut read, mut write) = tokio::io::split(stream); + let read_complete = Notify::new(); + let upload = async { + write.write_all(&payload[first..]).await?; + write.flush().await?; + read_complete.notified().await; + write.shutdown().await + }; + let download = async { + let mut echoed = vec![0; LARGE_DUPLEX_BYTES]; + read.read_exact(&mut echoed).await?; + if echoed != payload { + return Err(io::Error::other("Ready handoff echo mismatch")); + } + let mut extra = [0]; + if read.read(&mut extra).await? != 0 { + return Err(io::Error::other("extra Ready handoff response bytes")); + } + read_complete.notify_one(); + Ok::<_, io::Error>(()) + }; + tokio::try_join!(upload, download)?; + if fin.await.map_err(|_| closed())?? != LARGE_DUPLEX_BYTES { + return Err(io::Error::other( + "Ready handoff request FIN witness was short", + )); + } + drop((read, write)); + Ok::<_, io::Error>(ready_delta) + })) + .catch_unwind() + .await; + gate.release(); + let cleanup = tokio::time::timeout(Duration::from_secs(7), async { + pool.shutdown().await; + peer.stop().await; + }) + .await; + let empty = pool.tasks.is_empty() && peer.tasks.is_empty(); + let calls = peer.calls.load(Ordering::Acquire); + let closed = peer.closed.load(Ordering::Acquire); + drop((pool, peer)); + let close_released = close_weak + .as_ref() + .is_none_or(|close| close.upgrade().is_none()); + (result, cleanup, empty, calls, closed, close_released) + }) + .await; + let result = match result { + Ok(result) => result, + Err(panic) => resume_unwind(panic), + }; + cleanup.expect("Ready handoff Stop/pool/peer join watchdog"); + assert!(empty); + assert_eq!(calls, 1); + assert_eq!(closed, 1); + assert!(probe.snapshot().is_idle()); + assert!( + close_released, + "Ready handoff Close waker owner survived joined cleanup" + ); + let ready_delta = result + .expect("Ready handoff fixture watchdog, not semantic RED") + .expect("Ready handoff real IO/FIN setup failed, not semantic RED"); + assert!( + ready_delta > 0, + "reader completed native pending DATA without waking the waiting writer" + ); + } + + #[derive(Clone, Copy, Debug)] + enum PendingEnd { + PoolStop, + StreamDrop, + PhysicalError, + } + + async fn pending_waiter( + stream: Arc>, + write: bool, + pending: Arc, + observed: Arc, + cancel: CancellationToken, + ) -> Option> { + let operation = poll_fn(|cx| { + let mut stream = stream.lock().unwrap(); + let result = if write { + Pin::new(&mut *stream).poll_flush(cx) + } else { + let mut byte = [0]; + Pin::new(&mut *stream).poll_read(cx, &mut ReadBuf::new(&mut byte)) + }; + match result { + Poll::Pending => { + pending.store(true, Ordering::Release); + observed.notify_one(); + Poll::Pending + } + Poll::Ready(result) => Poll::Ready(result.map_err(|error| error.kind())), + } + }); + tokio::select! { biased; + ()=cancel.cancelled()=>None, + result=operation=>Some(result), + } + } + + #[tokio::test(flavor = "current_thread")] + async fn trusttunnel_h3_native_pending_stop_drop_and_transport_error_release_all_owners() { + for end in [ + PendingEnd::PoolStop, + PendingEnd::StreamDrop, + PendingEnd::PhysicalError, + ] { + pending_end(end).await; + } + } + + async fn pending_end(end: PendingEnd) { + let probe = ResourceProbe::default(); + let (result, cleanup, empty, calls, closed, close_released) = probe + .scope(async { + let peer = Peer::new(); + let pool = Pool::new(None); + let users = TaskTracker::new(); + let cancel = CancellationToken::new(); + let observed = Arc::new(Notify::new()); + let gate = Arc::new(Gate { + observed: observed.clone(), + ..Default::default() + }); + let mut close_weak = None; + let result = + AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(15), async { + let factory = peer.clone(); + let transport_gate = gate.clone(); + pool.probe( + request("_check"), + Instant::now() + Duration::from_secs(5), + move || async move { + let mut raw = factory.connect().await?; + raw.transport = Box::new(GatedPackets { + inner: raw.transport, + gate: transport_gate, + }); + Ok(raw) + }, + ) + .await?; + gate.paused.store(true, Ordering::Release); + // This real peer handler waits for its existing reject gate, + // so cancellation before request DATA cannot panic an echo + // handler that expected a first body record. + let mut stream = open_typed(&pool, &peer, "reject.invalid:443").await?; + close_weak = Some(Arc::downgrade(&stream.close)); + let physical = stream.lease.as_ref().ok_or_else(closed)?.0.clone(); + let mut context = Context::from_waker(std::task::Waker::noop()); + let payload = [7; CHUNK]; + match Pin::new(&mut stream).poll_write(&mut context, &payload) { + Poll::Ready(Ok(n)) if n == CHUNK => {} + _ => { + return Err(io::Error::other( + "pending-end initial native admission failed", + )); + } + } + if !Pin::new(&mut stream).poll_flush(&mut context).is_pending() { + return Err(io::Error::other( + "pending-end initial native flush was not Pending", + )); + } + let tap = NativeTap::new(observed.clone()); + let inner = stream + .pending + .take() + .ok_or_else(|| io::Error::other("pending-end missing native half"))?; + stream.pending = Some(Box::pin(TappedOperation { + inner, + tap: tap.clone(), + })); + if !Pin::new(&mut stream).poll_flush(&mut context).is_pending() { + return Err(io::Error::other( + "pending-end tapped native operation was not Pending", + )); + } + let stream = Arc::new(Mutex::new(stream)); + let read_pending = Arc::new(AtomicBool::new(false)); + let write_pending = Arc::new(AtomicBool::new(false)); + let (read_return, read_result) = oneshot::channel(); + let read = pending_waiter( + stream.clone(), + false, + read_pending.clone(), + observed.clone(), + cancel.clone(), + ); + users.spawn(observation::task(async move { + let _ = read_return.send(read.await); + })); + let (write_return, write_result) = oneshot::channel(); + let write = pending_waiter( + stream.clone(), + true, + write_pending.clone(), + observed.clone(), + cancel.clone(), + ); + users.spawn(observation::task(async move { + let _ = write_return.send(write.await); + })); + observe(&observed, || { + read_pending.load(Ordering::Acquire) + && write_pending.load(Ordering::Acquire) + && gate.blocked.load(Ordering::Acquire) + && tap.pending_polls.load(Ordering::Acquire) >= 3 + }) + .await?; + let registered_pending = { + let stream = stream.lock().unwrap(); + stream.pending.is_some() && stream.send.is_none() + }; + // Every verdict below follows a positive real native Pending + // and both task registrations. No successful credit or IO + // completion is synthesized for shutdown. + match end { + PendingEnd::PoolStop => pool.shutdown().await, + PendingEnd::StreamDrop => cancel.cancel(), + PendingEnd::PhysicalError => { + gate.failed.store(true, Ordering::Release); + gate.release(); + } + } + let read_end = read_result.await.map_err(|_| closed())?; + let write_end = write_result.await.map_err(|_| closed())?; + users.close(); + users.wait().await; + let still_pending = { + let stream = stream.lock().unwrap(); + stream.pending.is_some() && stream.send.is_none() + }; + let owned_half_valid = { + let stream = stream.lock().unwrap(); + // An error may leave the original operation pending or + // return its half before reporting failure. Either owner + // state must release normally when this Stream is dropped. + stream.pending.is_some() != stream.send.is_some() + }; + let sole_owner = Arc::strong_count(&stream) == 1; + // For Drop, cancel and join the two borrowing IO futures first, + // then actually drop their shared Stream. A dropped future + // returns no IO result; it is not relabeled ConnectionAborted. + drop(stream); + let active_after_drop = physical.usage.lock().unwrap().active; + drop((physical, tap)); + Ok::<_, io::Error>(( + registered_pending, + still_pending, + owned_half_valid, + sole_owner, + active_after_drop, + read_end, + write_end, + )) + })) + .catch_unwind() + .await; + // Failure paths also release the test gate and cancel/join both + // application tasks before stopping the actual pool and peer. + gate.release(); + cancel.cancel(); + let cleanup = tokio::time::timeout(Duration::from_secs(7), async { + users.close(); + users.wait().await; + pool.shutdown().await; + peer.stop().await; + }) + .await; + let empty = users.is_empty() && pool.tasks.is_empty() && peer.tasks.is_empty(); + let calls = peer.calls.load(Ordering::Acquire); + let closed = peer.closed.load(Ordering::Acquire); + drop((pool, peer)); + let close_released = close_weak + .as_ref() + .is_none_or(|close| close.upgrade().is_none()); + (result, cleanup, empty, calls, closed, close_released) + }) + .await; + let result = match result { + Ok(result) => result, + Err(panic) => resume_unwind(panic), + }; + cleanup.expect("pending-end normal Stop/pool/peer join watchdog"); + assert!(empty, "{end:?}"); + assert_eq!(calls, 1, "{end:?}"); + assert_eq!(closed, 1, "{end:?}"); + assert!(probe.snapshot().is_idle(), "{end:?}"); + assert!( + close_released, + "pending-end Close owner survived joined cleanup: {end:?}" + ); + let ( + registered_pending, + still_pending, + owned_half_valid, + sole_owner, + active_after_drop, + read_end, + write_end, + ) = result + .expect("pending-end fixture watchdog, not a successful cancellation") + .expect("pending-end real native setup/control failed"); + assert!( + registered_pending && owned_half_valid && sole_owner, + "{end:?}" + ); + assert_eq!(active_after_drop, 0, "{end:?}"); + match end { + PendingEnd::StreamDrop => { + assert!(still_pending); + assert_eq!(read_end, None); + assert_eq!(write_end, None); + } + PendingEnd::PoolStop | PendingEnd::PhysicalError => { + assert_eq!( + read_end, + Some(Err(io::ErrorKind::ConnectionAborted)), + "{end:?}" + ); + assert_eq!( + write_end, + Some(Err(io::ErrorKind::ConnectionAborted)), + "{end:?}" + ); + } + } + } +} diff --git a/src/transport/quic.rs b/src/transport/quic.rs index 58644be..3e547e4 100644 --- a/src/transport/quic.rs +++ b/src/transport/quic.rs @@ -39,6 +39,10 @@ use tokio_util::sync::CancellationToken; pub const QUEUE_LIMIT: usize = 32; pub const CLOSE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1); +#[cfg(all(test, target_os = "macos"))] +#[path = "quic/send_batch_memory_tests.rs"] +mod send_batch_memory_tests; + #[derive(Clone, Copy, Debug, Default)] pub struct Stats { pub sent: usize, @@ -372,6 +376,67 @@ pub fn attach_mapped( )) } +enum PendingSend { + Single(crate::dispatch::OwnedDatagramSend), + #[cfg(target_os = "macos")] + Batch { + operation: crate::dispatch::OwnedDatagramBatchSend, + submitted: usize, + }, +} +enum SendCompletion { + Single, + #[cfg(target_os = "macos")] + Batch(usize), +} +impl PendingSend { + async fn complete(&mut self) -> io::Result { + match self { + Self::Single(operation) => { + operation.as_mut().await.map_err(dispatch_error)?; + Ok(SendCompletion::Single) + } + #[cfg(target_os = "macos")] + Self::Batch { + operation, + submitted, + } => { + let accepted = operation.as_mut().await?; + if accepted == 0 || accepted > *submitted { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "invalid physical datagram batch completion", + )); + } + Ok(SendCompletion::Batch(accepted)) + } + } + } +} + +#[cfg(target_os = "macos")] +fn ready_send_batch(shared: &Shared, peer: SocketAddr) -> Vec { + let state = shared.state.lock().unwrap(); + if state.closed || state.outgoing.len() < 2 { + return Vec::new(); + } + let mut bytes = 0usize; + state + .outgoing + .iter() + .take(crate::dispatch::DATAGRAM_SEND_BATCH_LIMIT) + .take_while(|payload| { + bytes += payload.len(); + bytes <= crate::dispatch::DATAGRAM_SEND_BATCH_BYTES + }) + .map(|payload| Datagram { + remote: peer.into(), + payload: payload.clone(), + sniffed_domain: None, + }) + .collect() +} + async fn drive( transport: &mut dyn DatagramTransport, peer: SocketAddr, @@ -381,7 +446,9 @@ async fn drive( ) -> io::Result<()> { let mut has_sent = false; let mut receive_scratch = Vec::new(); - let mut pending_send: Option = None; + let mut pending_send: Option = None; + #[cfg(target_os = "macos")] + let mut batch_available = true; loop { let (can_receive, can_send) = { let state = shared.state.lock().unwrap(); @@ -393,12 +460,25 @@ async fn drive( tokio::select! { _ = cancel.cancelled() => return Ok(()), _ = shared.changed.notified() => {}, - sent = async { pending_send.as_mut().expect("owned send branch").as_mut().await }, if pending_send.is_some() => { - sent.map_err(dispatch_error)?; + sent = async { pending_send.as_mut().expect("owned send branch").complete().await }, if pending_send.is_some() => { + let sent = sent?; pending_send.take(); has_sent = true; let mut state = shared.state.lock().unwrap(); - state.stats.sent += 1; + match sent { + SendCompletion::Single => state.stats.sent += 1, + #[cfg(target_os = "macos")] + SendCompletion::Batch(accepted) => { + // Driver Drop may have cleared the queue while IO completed. + if state.closed { return Ok(()); } + if state.outgoing.len() < accepted { + return Err(io::ErrorKind::InvalidData.into()); + } + drop(state.outgoing.drain(..accepted)); + state.stats.sent += accepted; + } + } + drop(state); shared.writer.wake(); }, // Notify permits coalesce. A producer may have queued several @@ -428,6 +508,32 @@ async fn drive( } } if pending_send.is_none() { + #[cfg(target_os = "macos")] + { + // Clone handles only. The original FIFO remains the capacity + // ledger until a positive physical completion consumes a prefix. + let packets = if batch_available { + ready_send_batch(shared, peer) + } else { + Vec::new() + }; + if packets.len() >= 2 { + let submitted = packets.len(); + match transport.send_batch_owned(packets) { + Ok(operation) => { + pending_send = Some(PendingSend::Batch { + operation, + submitted, + }); + continue; + } + // DIRECT may become eligible after its ordinary first + // send initializes IO. Later refusal is stable here. + Err(_) if has_sent => batch_available = false, + Err(_) => {} + } + } + } let payload = shared.state.lock().unwrap().outgoing.pop_front(); if let Some(payload) = payload { shared.writer.wake(); @@ -437,7 +543,7 @@ async fn drive( sniffed_domain: None, }; match transport.send_owned(packet) { - Ok(send) => pending_send = Some(send), + Ok(send) => pending_send = Some(PendingSend::Single(send)), Err(packet) => { // An upstream without an owned path keeps its existing // cancellation-safe send; never open another socket. diff --git a/src/transport/quic/send_batch_memory_tests.rs b/src/transport/quic/send_batch_memory_tests.rs new file mode 100644 index 0000000..1c965c0 --- /dev/null +++ b/src/transport/quic/send_batch_memory_tests.rs @@ -0,0 +1,336 @@ +//! Real generic owner with an injected physical send boundary; no sockets. +use super::*; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use tokio::sync::{Semaphore, mpsc}; + +struct Control { + batches: Mutex>>, + emitted: Mutex>, + outcomes: Mutex>>, + credit: Semaphore, + active: AtomicUsize, + closes: AtomicUsize, + drops: AtomicUsize, + singles: AtomicUsize, + close_error: AtomicBool, + pointers: Mutex>, +} +impl Default for Control { + fn default() -> Self { + Self { + batches: Mutex::default(), + emitted: Mutex::default(), + outcomes: Mutex::default(), + credit: Semaphore::new(0), + active: AtomicUsize::new(0), + closes: AtomicUsize::new(0), + drops: AtomicUsize::new(0), + singles: AtomicUsize::new(0), + close_error: AtomicBool::new(false), + pointers: Mutex::default(), + } + } +} +struct SendLease(Arc); +impl Drop for SendLease { + fn drop(&mut self) { + self.0.active.fetch_sub(1, Ordering::Relaxed); + } +} +struct MemoryPhysical { + control: Arc, + input: mpsc::Receiver, +} +impl Drop for MemoryPhysical { + fn drop(&mut self) { + self.control.drops.fetch_add(1, Ordering::Relaxed); + } +} +#[async_trait::async_trait] +impl DatagramTransport for MemoryPhysical { + fn supports_shared_destinations(&self) -> bool { + false + } + fn send_batch_owned( + &mut self, + packets: Vec, + ) -> Result> { + let control = self.control.clone(); + control.active.fetch_add(1, Ordering::Relaxed); + let lease = SendLease(control.clone()); + Ok(Box::pin(async move { + let _lease = lease; + let sequence: Vec<_> = packets.iter().map(|packet| packet.payload[0]).collect(); + control.batches.lock().unwrap().push(sequence.clone()); + control.pointers.lock().unwrap().extend( + packets + .iter() + .map(|packet| (packet.payload[0], packet.payload.as_ptr() as usize)), + ); + control.credit.acquire().await.unwrap().forget(); + let count = control + .outcomes + .lock() + .unwrap() + .pop_front() + .unwrap_or(Ok(sequence.len())) + .map_err(io::Error::from)?; + if count <= sequence.len() { + control + .emitted + .lock() + .unwrap() + .extend_from_slice(&sequence[..count]); + } + Ok(count) + })) + } + fn send_owned( + &mut self, + packet: Datagram, + ) -> Result { + let control = self.control.clone(); + control.active.fetch_add(1, Ordering::Relaxed); + let lease = SendLease(control.clone()); + Ok(Box::pin(async move { + let _lease = lease; + control.singles.fetch_add(1, Ordering::Relaxed); + control.credit.acquire().await.unwrap().forget(); + control.emitted.lock().unwrap().push(packet.payload[0]); + Ok(()) + })) + } + async fn send(&mut self, _: Datagram) -> Result<(), DispatchError> { + panic!("already open memory path") + } + async fn receive(&mut self) -> Result { + self.input + .recv() + .await + .ok_or(DispatchError::ConnectionRefused) + } + async fn close(&mut self) -> Result<(), DispatchError> { + assert_eq!( + self.control.active.load(Ordering::Relaxed), + 0, + "send lease survived close" + ); + self.control.closes.fetch_add(1, Ordering::Relaxed); + if self.control.close_error.load(Ordering::Relaxed) { + Err(DispatchError::TimedOut) + } else { + Ok(()) + } + } +} +fn fixture() -> ( + Arc, + DatagramDriver, + Arc, + mpsc::Sender, +) { + let control = Arc::new(Control::default()); + let (input, receive) = mpsc::channel(4); + let (socket, driver) = attach( + Box::new(MemoryPhysical { + control: control.clone(), + input: receive, + }), + "192.0.2.1:443".parse().unwrap(), + DatagramBudget::new(1400, 1400), + ) + .unwrap(); + (socket, driver, control, input) +} +fn enqueue(socket: &DatagramSocket, sequence: u8) -> io::Result<()> { + socket.try_send(&quinn::udp::Transmit { + destination: socket.peer, + ecn: None, + contents: &[sequence; 1200], + segment_size: None, + src_ip: None, + }) +} +async fn until(mut predicate: impl FnMut() -> bool) -> io::Result<()> { + tokio::time::timeout(std::time::Duration::from_secs(1), async { + while !predicate() { + tokio::task::yield_now().await; + } + }) + .await + .map_err(|_| io::ErrorKind::TimedOut.into()) +} + +#[tokio::test] +async fn macos_quic_batch_memory_partial_prefix_is_emitted_once_in_fifo_order() { + let (socket, driver, control, _input) = fixture(); + control + .outcomes + .lock() + .unwrap() + .extend([Ok(2), Ok(1), Ok(2)]); + for sequence in 0..5 { + enqueue(&socket, sequence).unwrap(); + } + let pointers: Vec<_> = socket + .shared + .state + .lock() + .unwrap() + .outgoing + .iter() + .map(|payload| payload.as_ptr() as usize) + .collect(); + control.credit.add_permits(5); + let result = until(|| socket.stats().sent == 5).await; + let stopped = driver.stop().await; + result.unwrap(); + stopped.unwrap(); + assert_eq!(*control.emitted.lock().unwrap(), [0, 1, 2, 3, 4]); + assert_eq!( + *control.batches.lock().unwrap(), + [vec![0, 1, 2, 3], vec![2, 3, 4], vec![3, 4]] + ); + assert_eq!(control.singles.load(Ordering::Relaxed), 0); + assert_eq!(control.closes.load(Ordering::Relaxed), 1); + assert_eq!(control.drops.load(Ordering::Relaxed), 1); + for &(sequence, pointer) in control.pointers.lock().unwrap().iter() { + assert_eq!( + pointer, + pointers[usize::from(sequence)], + "batch copied a queued payload" + ); + } +} + +#[tokio::test] +async fn macos_quic_batch_memory_pending_prefix_keeps_queue_capacity_and_rx_live() { + let (socket, driver, control, input) = fixture(); + for sequence in 0..32 { + enqueue(&socket, sequence).unwrap(); + } + let result = async { + until(|| { + control.singles.load(Ordering::Relaxed) > 0 + || !control.batches.lock().unwrap().is_empty() + }) + .await?; + let full = enqueue(&socket, 32).err().map(|error| error.kind()); + control.outcomes.lock().unwrap().push_back(Ok(2)); + control.credit.add_permits(1); + until(|| socket.stats().sent >= 1).await?; + let sent_prefix = socket.stats().sent; + let first_slot = enqueue(&socket, 32).is_ok(); + let second_slot = enqueue(&socket, 33).is_ok(); + let still_full = enqueue(&socket, 34).err().map(|error| error.kind()); + input + .send(Datagram { + remote: socket.peer.into(), + payload: Bytes::from_static(b"reply"), + sniffed_domain: None, + }) + .await + .unwrap(); + until(|| socket.stats().received == 1).await?; + let context = &mut Context::from_waker(std::task::Waker::noop()); + let prefix_done = socket.poll_transmitted(context, 2).is_ready(); + let suffix_pending = socket.poll_transmitted(context, 3).is_pending(); + Ok::<_, io::Error>(( + full, + still_full, + sent_prefix, + first_slot, + second_slot, + prefix_done, + suffix_pending, + )) + } + .await; + let stopped = driver.stop().await; + let (full, still_full, sent_prefix, first_slot, second_slot, prefix_done, suffix_pending) = + result.unwrap(); + stopped.unwrap(); + assert_eq!( + (full, still_full), + ( + Some(io::ErrorKind::WouldBlock), + Some(io::ErrorKind::WouldBlock) + ) + ); + assert_eq!(sent_prefix, 2); + assert!(first_slot && second_slot); + assert!(prefix_done && suffix_pending); + assert_eq!(control.active.load(Ordering::Relaxed), 0); + assert_eq!(control.closes.load(Ordering::Relaxed), 1); + assert_eq!(control.drops.load(Ordering::Relaxed), 1); +} + +#[tokio::test] +async fn macos_quic_batch_memory_fatal_and_invalid_counts_close_without_single_replay() { + for outcome in [ + Err(io::ErrorKind::ConnectionReset), + Err(io::ErrorKind::PermissionDenied), + Ok(0), + Ok(5), + ] { + let (socket, driver, control, _input) = fixture(); + control.outcomes.lock().unwrap().push_back(outcome); + for sequence in 0..4 { + enqueue(&socket, sequence).unwrap(); + } + control.credit.add_permits(1); + let completed = + until(|| socket.stats().sent > 0 || control.closes.load(Ordering::Relaxed) == 1).await; + let stopped = driver.stop().await; + completed.unwrap(); + let expected = outcome.err().unwrap_or(io::ErrorKind::InvalidData); + assert_eq!(stopped.unwrap_err().kind(), expected); + assert_eq!(control.singles.load(Ordering::Relaxed), 0); + assert!(control.emitted.lock().unwrap().is_empty()); + assert_eq!(control.active.load(Ordering::Relaxed), 0); + assert_eq!(control.drops.load(Ordering::Relaxed), 1); + } +} + +#[tokio::test] +async fn macos_quic_batch_memory_stop_and_cleared_queue_release_pending_leases() { + let (socket, driver, control, _input) = fixture(); + for sequence in 0..4 { + enqueue(&socket, sequence).unwrap(); + } + let started = until(|| { + control.singles.load(Ordering::Relaxed) > 0 || !control.batches.lock().unwrap().is_empty() + }) + .await; + socket.shared.finish(None); + control.credit.add_permits(1); + let stopped = driver.stop().await; + started.unwrap(); + stopped.unwrap(); + assert_eq!(control.active.load(Ordering::Relaxed), 0); + assert_eq!(control.closes.load(Ordering::Relaxed), 1); + assert_eq!(control.drops.load(Ordering::Relaxed), 1); + assert!(!control.batches.lock().unwrap().is_empty()); +} + +#[tokio::test] +async fn macos_quic_batch_memory_original_io_error_survives_close_failure() { + let (socket, driver, control, _input) = fixture(); + control.close_error.store(true, Ordering::Relaxed); + control + .outcomes + .lock() + .unwrap() + .push_back(Err(io::ErrorKind::PermissionDenied)); + for sequence in 0..4 { + enqueue(&socket, sequence).unwrap(); + } + control.credit.add_permits(1); + let completed = until(|| control.closes.load(Ordering::Relaxed) == 1).await; + let stopped = driver.stop().await; + completed.unwrap(); + assert_eq!(stopped.unwrap_err().kind(), io::ErrorKind::PermissionDenied); + assert_eq!(control.active.load(Ordering::Relaxed), 0); + assert_eq!(control.closes.load(Ordering::Relaxed), 1); + assert_eq!(control.drops.load(Ordering::Relaxed), 1); +} diff --git a/src/transport/quiche_h3.rs b/src/transport/quiche_h3.rs index 1b98fc7..5dd1b1b 100644 --- a/src/transport/quiche_h3.rs +++ b/src/transport/quiche_h3.rs @@ -13,7 +13,7 @@ use http::{Request, Response}; use quiche::h3::NameValue; use quinn::AsyncUdpSocket; use std::{ - collections::{BTreeMap, VecDeque}, + collections::{BTreeMap, BTreeSet, VecDeque}, io, net::SocketAddr, sync::{Arc, Mutex}, @@ -134,6 +134,13 @@ struct State { connection: Option, h3: Option, streams: BTreeMap, + // Only IDs: payloads, wakers and application halves are released at Drop. + // Entries follow native RESET/STOP collection, not historical requests. + retired: BTreeSet, + retired_cursor: Option, + // A finite sweep is armed only by new retirement/native RX/terminal work. + // Self-wakes consume this debt rather than starting another full sweep. + retired_debt: usize, closed: bool, goaway: bool, ready: bool, @@ -156,6 +163,9 @@ impl Shared { body.wake(); } state.streams.clear(); + state.retired.clear(); + state.retired_cursor = None; + state.retired_debt = 0; state.h3.take(); state.connection.take(); state.datagram_budget = None; @@ -248,6 +258,9 @@ impl Driver { connection: Some(connection), h3: None, streams: BTreeMap::new(), + retired: BTreeSet::new(), + retired_cursor: None, + retired_debt: 0, closed: false, goaway: false, ready: false, @@ -303,6 +316,7 @@ impl Driver { // One native-pop allowance for the complete owner turn, including // the outer H3 pass, inline RX and the publication pass below. let mut datagram_work = WORK; + let mut retirement_work = WORK; if cancel.is_cancelled() && closing.is_none() { closing = Some(tokio::time::Instant::now() + quic::CLOSE_TIMEOUT); let mut state = self.shared.state.lock().unwrap(); @@ -348,6 +362,9 @@ impl Driver { self.shared.status.notify_waiters(); } process_h3(&mut state, &mut datagram_work)?; + if reap_retired_h3(&mut state, &mut retirement_work) { + self.shared.changed.notify_one(); + } state.datagram_budget = state.connection.as_mut().unwrap().dgram_max_writable_len(); if closing.is_none() && keepalive.is_some_and(|at| tokio::time::Instant::now() >= at) @@ -484,7 +501,14 @@ impl Driver { } }; match result { - Ok(_) | Err(quiche::Error::Done) => {} + Ok(consumed) => { + if consumed != 0 { + // Real accepted native input can ACK a + // reset or complete a stopped stream. + state.retired_debt = state.retired.len(); + } + } + Err(quiche::Error::Done) => {} Err(error) => { // Inline frames are still private under // State; do not publish them on failure. @@ -551,6 +575,9 @@ impl Driver { state.closed = true; return Poll::Ready(Err(error)); } + if reap_retired_h3(&mut state, &mut retirement_work) { + self.shared.changed.notify_one(); + } } if received { Poll::Ready(Ok(())) @@ -587,6 +614,79 @@ fn retire_grace(connection: &NativeConnection) -> Duration { .saturating_add(Duration::from_millis(25)) .min(quic::CLOSE_TIMEOUT) } + +// quiche 0.30 keeps H3 request state separately from native QUIC state. +// A native RESET/STOP alone does not mark H3's local send half finished. +// Its public send_body error path removes the H3 entry after native collection +// (the collect_reset_streams test uses the same notification). Prove that the +// transport ID is gone first, so this call cannot enqueue DATA or a FIN. +fn retire_collected_h3(state: &mut State, id: u64) -> bool { + let (Some(connection), Some(h3)) = (state.connection.as_mut(), state.h3.as_mut()) else { + return false; + }; + if !connection.stream_closed(id) { + return false; + } + let collected = match connection.stream_capacity(id) { + Err(quiche::Error::InvalidStreamState(_)) => true, + // This public query can itself collect a complete stopped stream but + // still returns StreamStopped. Recheck once under the same lock; do + // not wait for another packet/notification which might never arrive. + Err(quiche::Error::StreamStopped(_)) => { + connection.stream_closed(id) + && matches!( + connection.stream_capacity(id), + Err(quiche::Error::InvalidStreamState(_)) + ) + } + _ => false, + }; + if !collected { + return false; + } + matches!( + h3.send_body(connection, id, &[], true), + Err(quiche::h3::Error::TransportError( + quiche::Error::InvalidStreamState(_) + )) | Err(quiche::h3::Error::FrameUnexpected) + ) +} + +// Share one allowance across the existing owner turn, including inline RX. +// Round-robin prevents an unacknowledged low ID from hiding collectable IDs. +// One finite sweep reaches later ready IDs even if the first batch all waits +// on its peer. An all-unready sweep consumes its debt and stops self-waking. +fn reap_retired_h3(state: &mut State, remaining: &mut usize) -> bool { + let scans = (*remaining) + .min(state.retired_debt) + .min(state.retired.len()); + for _ in 0..scans { + let id = state + .retired_cursor + .and_then(|cursor| { + state + .retired + .range(( + std::ops::Bound::Excluded(cursor), + std::ops::Bound::Unbounded, + )) + .next() + .copied() + }) + .or_else(|| state.retired.first().copied()); + let Some(id) = id else { break }; + state.retired_cursor = Some(id); + *remaining -= 1; + state.retired_debt -= 1; + if retire_collected_h3(state, id) { + state.retired.remove(&id); + } + } + if state.retired.is_empty() { + state.retired_debt = 0; + } + state.retired_debt != 0 +} fn process_h3(state: &mut State, datagram_work: &mut usize) -> io::Result<()> { let Some(h3) = state.h3.as_mut() else { return Ok(()); @@ -630,12 +730,20 @@ fn process_h3(state: &mut State, datagram_work: &mut usize) -> io::Result<()> { } } Ok((id, quiche::h3::Event::Finished)) => { + if state.retired.contains(&id) { + // H3 polling can finish native reads after the RX turn's + // first sweep. A new terminal event arms one finite sweep. + state.retired_debt = state.retired.len(); + } if let Some(body) = state.streams.get_mut(&id) { body.finished = true; body.signals.read.wake(); } } Ok((id, quiche::h3::Event::Reset(_))) => { + if state.retired.contains(&id) { + state.retired_debt = state.retired.len(); + } if let Some(body) = state.streams.get_mut(&id) { body.failed = true; body.wake(); @@ -1140,6 +1248,7 @@ fn stop_half(client: &Client, id: u64, send: bool, code: u64) { body.datagrams.take(); } let remove = !body.send_owned && !body.receive_owned; + let cancelled = !body.send_finished || !body.finished; if !graceful { let _ = state.connection.as_mut().unwrap().stream_shutdown( id, @@ -1153,6 +1262,9 @@ fn stop_half(client: &Client, id: u64, send: bool, code: u64) { } if remove { state.streams.remove(&id); + if cancelled && !retire_collected_h3(&mut state, id) && state.retired.insert(id) { + state.retired_debt = state.retired.len(); + } } drop(state); client.shared.changed.notify_one(); @@ -1713,6 +1825,16 @@ mod tests { .1, 1 ); + drop(state); + drop(receive); + drop(send); + // Current-thread test: no await lets the driver/peer ACK this + // cancellation before Stop. Exercise joined teardown with a real + // admitted native request still awaiting retirement. + let state = client.shared.state.lock().unwrap(); + assert!(state.streams.is_empty()); + assert!(state.retired.contains(&id)); + assert!(state.retired_debt > 0); }; let result = tokio::time::timeout(Duration::from_secs(10), operation).await; cancel.cancel(); @@ -1722,7 +1844,14 @@ mod tests { assert!(closed.load(std::sync::atomic::Ordering::Acquire)); assert!(client.close_reason().is_some()); assert!(client.shared.state.lock().unwrap().connection.is_none()); - assert!(client.shared.state.lock().unwrap().streams.is_empty()); + { + let state = client.shared.state.lock().unwrap(); + assert!(state.streams.is_empty()); + assert!(state.retired.is_empty()); + assert!(state.retired_cursor.is_none()); + assert_eq!(state.retired_debt, 0); + assert!(state.h3.is_none()); + } assert_eq!( retained_ready_wakers.load(std::sync::atomic::Ordering::Relaxed), 0, diff --git a/src/transport/quiche_h3_native_ready_batch_memory_tests.rs b/src/transport/quiche_h3_native_ready_batch_memory_tests.rs index 2d49214..2d3bbab 100644 --- a/src/transport/quiche_h3_native_ready_batch_memory_tests.rs +++ b/src/transport/quiche_h3_native_ready_batch_memory_tests.rs @@ -122,6 +122,9 @@ impl Wire { connection: Some(client), h3: Some(h3), streams: BTreeMap::new(), + retired: BTreeSet::new(), + retired_cursor: None, + retired_debt: 0, closed: false, goaway: false, ready: true, @@ -382,3 +385,601 @@ fn quiche_h3_native_memory_data_fin_preserves_delivered_prefix_until_finished_po .is_err() ); } + +// Real QUIC/TLS/H3 packets exercise cancellation collection independently of +// application Body removal, including flow control and shared-owner fairness. +fn halves(wire: &Wire, id: u64) -> (SendStream, RecvStream) { + let signals = wire.client.shared.state.lock().unwrap().streams[&id] + .signals + .clone(); + ( + SendStream { + client: wire.client.clone(), + id, + signals: signals.clone(), + }, + RecvStream { + client: wire.client.clone(), + id, + signals, + }, + ) +} + +fn poll_retirement_peer(peer: &mut NativeConnection, h3: &mut quiche::h3::Connection) { + for _ in 0..256 { + match h3.poll(peer) { + Ok(_) => {} + Err(quiche::h3::Error::Done) => return, + Err(error) => panic!("memory retirement peer H3 protocol error: {error:?}"), + } + } + panic!("memory retirement peer H3 work bound exceeded"); +} + +// Real wire progress without running the candidate reaper, so tests can place +// an already-collected suffix behind an unacknowledged prefix. +fn exchange_without_reaping(wire: &mut Wire, turns: usize) { + for _ in 0..turns { + let mut state = wire.client.shared.state.lock().unwrap(); + state + .connection + .as_mut() + .unwrap() + .send_ack_eliciting() + .unwrap(); + transfer( + state.connection.as_mut().unwrap(), + &mut wire.peer, + wire.local, + wire.remote, + ); + poll_retirement_peer(&mut wire.peer, &mut wire.peer_h3); + wire.peer.send_ack_eliciting().unwrap(); + if transfer( + &mut wire.peer, + state.connection.as_mut().unwrap(), + wire.remote, + wire.local, + ) != 0 + { + // Mirrors the owner hook only after actual native recv succeeded. + state.retired_debt = state.retired.len(); + } + super::process_h3(&mut state, &mut { WORK }).unwrap(); + } +} + +fn admit_retirement_requests(wire: &mut Wire, count: usize) -> Vec { + let mut ids = wire.ids.to_vec(); + { + let mut state = wire.client.shared.state.lock().unwrap(); + for _ in 0..count { + let request = Request::builder() + .method(http::Method::CONNECT) + .uri("https://example.invalid/") + .body(()) + .unwrap(); + let headers = request_headers(&request).unwrap(); + let State { + connection, + h3, + streams, + .. + } = &mut *state; + let id = h3 + .as_mut() + .unwrap() + .send_request(connection.as_mut().unwrap(), &headers, false) + .unwrap(); + streams.insert(id, Body::new(Arc::new(Signals::default()))); + ids.push(id); + } + } + for _ in 0..8 { + let mut state = wire.client.shared.state.lock().unwrap(); + transfer( + state.connection.as_mut().unwrap(), + &mut wire.peer, + wire.local, + wire.remote, + ); + let mut drained = false; + for _ in 0..256 { + match wire.peer_h3.poll(&mut wire.peer) { + Ok((id, quiche::h3::Event::Headers { .. })) => { + wire.peer_h3 + .send_response( + &mut wire.peer, + id, + &[quiche::h3::Header::new(b":status", b"200")], + false, + ) + .unwrap(); + } + Ok(_) => {} + Err(quiche::h3::Error::Done) => { + drained = true; + break; + } + Err(error) => panic!("memory retirement admission H3 error: {error:?}"), + } + } + assert!( + drained, + "memory retirement admission H3 work bound exceeded" + ); + transfer( + &mut wire.peer, + state.connection.as_mut().unwrap(), + wire.remote, + wire.local, + ); + super::process_h3(&mut state, &mut { WORK }).unwrap(); + } + for id in &ids { + assert_eq!( + wire.client.shared.state.lock().unwrap().streams[id] + .headers + .as_ref() + .unwrap() + .status(), + 200 + ); + } + ids +} + +fn exchange_reset_wire(wire: &mut Wire, id: u64) { + for _ in 0..128 { + let mut state = wire.client.shared.state.lock().unwrap(); + // Synthetic PINGs make ACK progress observable without sleeps, an OS + // socket, a new task, or fabricated acknowledgement state. + state + .connection + .as_mut() + .unwrap() + .send_ack_eliciting() + .unwrap(); + transfer( + state.connection.as_mut().unwrap(), + &mut wire.peer, + wire.local, + wire.remote, + ); + poll_retirement_peer(&mut wire.peer, &mut wire.peer_h3); + wire.peer.send_ack_eliciting().unwrap(); + if transfer( + &mut wire.peer, + state.connection.as_mut().unwrap(), + wire.remote, + wire.local, + ) != 0 + { + state.retired_debt = state.retired.len(); + } + super::process_h3(&mut state, &mut { WORK }).unwrap(); + super::reap_retired_h3(&mut state, &mut { WORK }); + let native = state.connection.as_mut().unwrap(); + if native.stream_closed(id) + && matches!( + native.stream_capacity(id), + Err(quiche::Error::InvalidStreamState(_)) + ) + { + return; + } + } + panic!("native reset was not collected within bounded real wire exchanges"); +} + +fn assert_h3_forgotten_without_wire_output(wire: &Wire, id: u64) { + let mut state = wire.client.shared.state.lock().unwrap(); + let State { connection, h3, .. } = &mut *state; + let native = connection.as_mut().unwrap(); + assert!(native.stream_closed(id)); + assert!(matches!( + native.stream_capacity(id), + Err(quiche::Error::InvalidStreamState(_)) + )); + let sent = native.stats().sent; + // The native absent/collected gate is the no-output proof. Packet count + // below is auxiliary, not proof that an arbitrary API queued no FIN. + // This is a mutable public API probe, not a getter. An empty non-FIN body + // is deliberately rejected before native output. Done means a stale H3 + // entry survived; FrameUnexpected means the request entry is absent. + assert!(matches!( + h3.as_mut().unwrap().send_body(native, id, &[], false), + Err(quiche::h3::Error::FrameUnexpected) + )); + assert_eq!(native.stats().sent, sent); +} + +#[test] +fn quiche_h3_native_memory_dropped_halves_retire_h3_after_actual_native_collection() { + for read_first in [false, true] { + let mut wire = Wire::new(); + let id = wire.ids[0]; + let (mut send, receive) = halves(&wire, id); + if read_first { + drop(receive); + // The surviving upload and its Body stay owned until its Drop. + assert!( + wire.client + .shared + .state + .lock() + .unwrap() + .streams + .contains_key(&id) + ); + send.stop_stream(REQUEST_CANCELLED); + send.stop_stream(REQUEST_CANCELLED); // Explicit stop + Drop is idempotent. + drop(send); + } else { + drop(send); + assert!( + wire.client + .shared + .state + .lock() + .unwrap() + .streams + .contains_key(&id) + ); + drop(receive); + } + assert!( + !wire + .client + .shared + .state + .lock() + .unwrap() + .streams + .contains_key(&id) + ); + exchange_reset_wire(&mut wire, id); + // One extra owner turn covers collection caused by the final native + // capacity check, without advancing a timer or resetting the carrier. + super::reap_retired_h3(&mut wire.client.shared.state.lock().unwrap(), &mut { WORK }); + assert_h3_forgotten_without_wire_output(&wire, id); + assert!(wire.client.shared.state.lock().unwrap().retired.is_empty()); + + let sibling = wire.ids[1]; + wire.peer_h3 + .send_body(&mut wire.peer, sibling, b"sibling", false) + .unwrap(); + wire.receive_wire(); + wire.publish(&mut { WORK }); + let (_sibling_send, mut sibling_receive) = halves(&wire, sibling); + assert_eq!( + sibling_receive + .recv_response() + .now_or_never() + .unwrap() + .unwrap() + .status(), + 200 + ); + let data = futures_util::future::poll_fn(|cx| sibling_receive.poll_recv_data(cx)) + .now_or_never() + .unwrap() + .unwrap() + .unwrap(); + assert_eq!(data.as_ref(), b"sibling"); + assert!(wire.client.can_open_request()); + } +} + +#[test] +fn quiche_h3_native_memory_retirement_waits_without_fin_under_actual_backpressure() { + let mut wire = Wire::new(); + let id = wire.ids[0]; + let (send, receive) = halves(&wire, id); + // Fill the real native/H3 sender until it rejects new data. No model or + // forced credit variable stands in for transport backpressure. + { + let mut state = wire.client.shared.state.lock().unwrap(); + let State { connection, h3, .. } = &mut *state; + let mut blocked = false; + for _ in 0..256 { + match h3.as_mut().unwrap().send_body( + connection.as_mut().unwrap(), + id, + &[0x61; CHUNK], + false, + ) { + Ok(_) => {} + Err(quiche::h3::Error::Done) => { + blocked = true; + break; + } + Err(error) => panic!("unexpected memory backpressure result: {error:?}"), + } + } + assert!(blocked); + } + drop(send); + drop(receive); + { + let mut state = wire.client.shared.state.lock().unwrap(); + let native = state.connection.as_mut().unwrap(); + let sent = native.stats().sent; + assert!(!super::retire_collected_h3(&mut state, id)); + let mut budget = 1; + assert!(!super::reap_retired_h3(&mut state, &mut budget)); + assert_eq!(budget, 0); + assert!(state.retired.contains(&id)); + assert_eq!(state.connection.as_ref().unwrap().stats().sent, sent); + assert!(!state.streams.contains_key(&id)); + } + exchange_reset_wire(&mut wire, id); + super::reap_retired_h3(&mut wire.client.shared.state.lock().unwrap(), &mut { WORK }); + assert_h3_forgotten_without_wire_output(&wire, id); + // The same final owner teardown used by Driver::run drops all native/H3 + // state and tombstones. Full driver stop/join remains covered separately. + wire.client.shared.finish(); + let state = wire.client.shared.state.lock().unwrap(); + assert!(state.streams.is_empty() && state.retired.is_empty()); + assert!(state.h3.is_none() && state.connection.is_none()); +} + +#[test] +fn quiche_h3_native_memory_pending_retirement_round_robin_uses_only_shared_allowance() { + let wire = Wire::new(); + for id in wire.ids { + let (send, receive) = halves(&wire, id); + drop(send); + drop(receive); + } + let mut state = wire.client.shared.state.lock().unwrap(); + assert_eq!(state.retired.len(), 2); + let mut allowance = 1; + assert!(super::reap_retired_h3(&mut state, &mut allowance)); + assert_eq!(allowance, 0); + let first = state.retired_cursor; + // The second pass in the SAME owner turn has zero remaining work. + assert!(super::reap_retired_h3(&mut state, &mut allowance)); + assert_eq!(state.retired_cursor, first); + allowance = 1; + assert!(!super::reap_retired_h3(&mut state, &mut allowance)); + assert_eq!(allowance, 0); + assert_ne!(state.retired_cursor, first); + assert_eq!(state.retired.len(), 2); + assert!(state.streams.is_empty()); + drop(state); + wire.client.shared.finish(); + assert!(wire.client.shared.state.lock().unwrap().retired.is_empty()); +} + +#[test] +fn quiche_h3_native_memory_graceful_fin_does_not_add_reset_or_retirement() { + let mut wire = Wire::new(); + let id = wire.ids[0]; + let (mut send, mut receive) = halves(&wire, id); + send.finish().now_or_never().unwrap().unwrap(); + wire.peer_h3 + .send_body(&mut wire.peer, id, &[], true) + .unwrap(); + for _ in 0..4 { + let mut state = wire.client.shared.state.lock().unwrap(); + transfer( + state.connection.as_mut().unwrap(), + &mut wire.peer, + wire.local, + wire.remote, + ); + poll_retirement_peer(&mut wire.peer, &mut wire.peer_h3); + transfer( + &mut wire.peer, + state.connection.as_mut().unwrap(), + wire.remote, + wire.local, + ); + super::process_h3(&mut state, &mut { WORK }).unwrap(); + } + assert_eq!( + receive + .recv_response() + .now_or_never() + .unwrap() + .unwrap() + .status(), + 200 + ); + assert!( + futures_util::future::poll_fn(|cx| receive.poll_recv_data(cx)) + .now_or_never() + .unwrap() + .unwrap() + .is_none() + ); + let before = wire + .client + .shared + .state + .lock() + .unwrap() + .connection + .as_ref() + .unwrap() + .stats(); + drop(receive); + drop(send); + let state = wire.client.shared.state.lock().unwrap(); + let after = state.connection.as_ref().unwrap().stats(); + assert_eq!( + after.reset_stream_count_local, + before.reset_stream_count_local + ); + assert_eq!( + after.stopped_stream_count_local, + before.stopped_stream_count_local + ); + assert!(state.retired.is_empty()); + assert!(!state.streams.contains_key(&id)); +} + +#[test] +fn quiche_h3_native_memory_peer_stop_sending_collection_is_rechecked_in_same_drop() { + let mut wire = Wire::new(); + // Consume response FIN BEFORE the upload is stopped. Reading FIN after + // RESET/ACK could collect native state in stream_recv and miss the exact + // capacity-query branch this regression must exercise. + for id in wire.ids { + wire.peer_h3 + .send_body(&mut wire.peer, id, &[], true) + .unwrap(); + } + for _ in 0..4 { + let mut state = wire.client.shared.state.lock().unwrap(); + transfer( + &mut wire.peer, + state.connection.as_mut().unwrap(), + wire.remote, + wire.local, + ); + super::process_h3(&mut state, &mut { WORK }).unwrap(); + } + { + let mut state = wire.client.shared.state.lock().unwrap(); + for id in wire.ids { + assert!( + state.streams[&id].finished, + "response FIN not consumed before STOP for {id}" + ); + let native = state.connection.as_mut().unwrap(); + // Actual public writable-interest registration, above this real + // stream's 128 KiB credit; no private flag or fabricated state. + // STOP sees was_writable=false and links the writable notification + // which ACK collection preserves until StreamStopped is consumed. + let writable = native.stream_writable(id, 1024 * 1024); + assert!( + matches!(writable, Ok(false)), + "expected blocked writable interest for {id}: {writable:?}" + ); + } + } + // Now encode STOP_SENDING separately, then exchange genuine RESET/ACKs. + // No later FIN read is allowed to consume the collection opportunity. + for id in wire.ids { + wire.peer + .stream_shutdown(id, quiche::Shutdown::Read, REQUEST_CANCELLED) + .unwrap(); + } + exchange_without_reaping(&mut wire, 64); + { + let mut state = wire.client.shared.state.lock().unwrap(); + let native = state.connection.as_mut().unwrap(); + let control = wire.ids[0]; + assert!(native.stream_closed(control)); + // This real stopped stream demonstrates the API's one-call-late + // return: the first query collects but still reports StreamStopped. + let first = native.stream_capacity(control); + assert!( + matches!(first, Err(quiche::Error::StreamStopped(_))), + "first stopped capacity query must collect and report StreamStopped: {first:?}" + ); + let second = native.stream_capacity(control); + assert!( + matches!(second, Err(quiche::Error::InvalidStreamState(_))), + "second capacity query must see native collection: {second:?}" + ); + } + let id = wire.ids[1]; + let (send, receive) = halves(&wire, id); + drop(receive); + drop(send); + // No new packet, timer, reaper turn or caller-side capacity query occurs + // between the last Drop and this assertion. + assert_h3_forgotten_without_wire_output(&wire, id); + assert!( + !wire + .client + .shared + .state + .lock() + .unwrap() + .retired + .contains(&id) + ); +} + +#[test] +fn quiche_h3_native_memory_finite_sweep_reaches_ready_tail_after_unacked_prefix() { + let mut wire = Wire::new(); + let ids = admit_retirement_requests(&mut wire, WORK); + assert_eq!(ids.len(), WORK + 2); + let (waiting, ready) = ids.split_at(WORK); + // Retire the high-ID suffix and let its genuine RESET/ACK exchange finish. + // The candidate reaper is deliberately not run during this wire flush. + for &id in ready { + let (send, receive) = halves(&wire, id); + drop(send); + drop(receive); + } + exchange_without_reaping(&mut wire, 64); + { + let mut state = wire.client.shared.state.lock().unwrap(); + for &id in ready { + let native = state.connection.as_mut().unwrap(); + assert!(native.stream_closed(id)); + if matches!( + native.stream_capacity(id), + Err(quiche::Error::StreamStopped(_)) + ) { + assert!(matches!( + native.stream_capacity(id), + Err(quiche::Error::InvalidStreamState(_)) + )); + } + assert!(matches!( + native.stream_capacity(id), + Err(quiche::Error::InvalidStreamState(_)) + )); + assert!(state.retired.contains(&id)); + } + } + // Now retire the lower IDs without delivering their STOP/RESET to the + // peer. No later RX event is available to rescue an incorrectly stopped + // first batch. Every ID was a real admitted request, not a fake tombstone. + for &id in waiting { + let (send, receive) = halves(&wire, id); + drop(send); + drop(receive); + } + { + let mut state = wire.client.shared.state.lock().unwrap(); + assert_eq!(state.retired.len(), ids.len()); + assert_eq!(state.retired_debt, ids.len()); + assert!(state.streams.is_empty()); + let mut allowance = WORK; + assert!(super::reap_retired_h3(&mut state, &mut allowance)); + assert_eq!(allowance, 0); + assert_eq!(state.retired_debt, 2); + assert!(ready.iter().all(|id| state.retired.contains(id))); + allowance = WORK; + assert!(!super::reap_retired_h3(&mut state, &mut allowance)); + assert_eq!(allowance, WORK - 2); + assert_eq!(state.retired_debt, 0); + assert_eq!(state.retired.len(), waiting.len()); + assert!(ready.iter().all(|id| !state.retired.contains(id))); + let cursor = state.retired_cursor; + // A peer which never ACKs cannot cause an unbounded cleanup self-loop. + for _ in 0..4 { + allowance = WORK; + assert!(!super::reap_retired_h3(&mut state, &mut allowance)); + assert_eq!(allowance, WORK); + assert_eq!(state.retired_cursor, cursor); + assert_eq!(state.retired_debt, 0); + } + } + for &id in ready { + assert_h3_forgotten_without_wire_output(&wire, id); + } + wire.client.shared.finish(); + let state = wire.client.shared.state.lock().unwrap(); + assert!(state.retired.is_empty()); + assert_eq!(state.retired_debt, 0); +} diff --git a/src/transport/sing_mux.rs b/src/transport/sing_mux.rs index d8f23d6..c8ebf2a 100644 --- a/src/transport/sing_mux.rs +++ b/src/transport/sing_mux.rs @@ -40,6 +40,8 @@ pub(crate) struct SuppliedStream { pub(crate) struct Pool { options: SingMuxConfig, autonomous_writes: bool, + coalesce_h3_queued_flush: bool, + udp_lane: Option, state: Arc>, opening: tokio::sync::Mutex<()>, cancel: CancellationToken, @@ -47,6 +49,11 @@ pub(crate) struct Pool { drained: Option>, } #[derive(Default)] +struct Lane { + state: Arc>, + opening: tokio::sync::Mutex<()>, +} +#[derive(Default)] struct State { closed: bool, connections: Vec, @@ -83,6 +90,8 @@ impl Pool { Self { options, autonomous_writes: false, + coalesce_h3_queued_flush: false, + udp_lane: None, state: Arc::default(), opening: Default::default(), cancel: CancellationToken::new(), @@ -96,6 +105,25 @@ impl Pool { && (self.options.protocol == SingMuxProtocol::Smux || (self.options.protocol == SingMuxProtocol::H2Mux && h2_packet_up)); } + pub(crate) fn set_h3_queued_flush_coalescing(&mut self, qualified: bool) { + self.coalesce_h3_queued_flush = qualified + && self.autonomous_writes + && self.options.enabled + && self.options.protocol == SingMuxProtocol::Smux + && !self.options.padding + && !self.options.only_tcp; + } + /// Fixed by the typed factory before the connector is published. + pub(crate) fn set_h3_udp_lane(&mut self, qualified: bool) { + self.udp_lane = (qualified + && self.autonomous_writes + && self.options.enabled + && self.options.protocol == SingMuxProtocol::Smux + && !self.options.padding + && !self.options.only_tcp + && self.options.brutal.is_none()) + .then(Lane::default); + } pub(crate) fn autonomous_writes(&self) -> bool { self.autonomous_writes } @@ -123,17 +151,21 @@ impl Pool { F: FnOnce() -> Fut, Fut: Future>, { + let (lane_state, opening) = match (udp, self.udp_lane.as_ref()) { + (true, Some(lane)) => (&lane.state, &lane.opening), + _ => (&self.state, &self.opening), + }; let operation = async { let mut connect = Some(connect); let reservation = { - let _opening = self.opening.lock().await; + let _opening = opening.lock().await; loop { // notify_one stores a permit if the final lease drains // between the state check and polling this waiter. The // opening lock permits only one retirement waiter. let notified = self.drained.as_ref().map(|notify| notify.notified()); let (existing, retiring) = { - let mut state = self.state.lock().unwrap(); + let mut state = lane_state.lock().unwrap(); if state.closed { return Err(io::ErrorKind::ConnectionAborted.into()); } @@ -155,7 +187,7 @@ impl Pool { && active < self.options.max_streams } }) - .map(|c| c.reserve(&self.state, self.drained.as_ref())); + .map(|c| c.reserve(lane_state, self.drained.as_ref())); let retiring = self.options.brutal.is_some() && existing.is_none() && !state.connections.is_empty(); @@ -188,7 +220,12 @@ impl Pool { if self.options.padding { raw = Box::new(padding::Padding::new(raw)); } - let connection = self.establish(raw).await?; + #[cfg(feature = "outbound-vless")] + let h3_packet_up = self.captures_h3_udp() + && supplied.h3_udp.as_ref().and_then(Weak::upgrade).is_some(); + #[cfg(not(feature = "outbound-vless"))] + let h3_packet_up = false; + let connection = self.establish(raw, lane_state, h3_packet_up).await?; #[cfg(feature = "outbound-vless")] let connection = { let mut connection = connection; @@ -213,11 +250,11 @@ impl Pool { #[cfg(not(target_os = "linux"))] let _ = rate; } - let mut state = self.state.lock().unwrap(); + let mut state = lane_state.lock().unwrap(); if state.closed { return Err(io::ErrorKind::ConnectionAborted.into()); } - let pair = connection.reserve(&self.state, self.drained.as_ref()); + let pair = connection.reserve(lane_state, self.drained.as_ref()); state.connections.push(connection); break pair; } @@ -250,28 +287,37 @@ impl Pool { result = timeout_at(deadline, operation) => result.map_err(|_|io::Error::from(io::ErrorKind::TimedOut))?, } } - async fn establish(&self, raw: BoxStream) -> io::Result { + async fn establish( + &self, + raw: BoxStream, + state: &Arc>, + h3_packet_up: bool, + ) -> io::Result { if self.options.protocol == SingMuxProtocol::Smux { - let (sender, driver) = - smux_driver::new_with_autonomous_writes(raw, self.autonomous_writes); - return self.own(Sender::Smux(sender), driver); + let (sender, driver) = smux_driver::new_with_queued_flush_coalescing( + raw, + self.autonomous_writes, + self.coalesce_h3_queued_flush, + ); + return self.own(Sender::Smux(sender), driver, state); } if self.options.protocol == SingMuxProtocol::Yamux { let (sender, driver) = yamux_driver::new(raw); - return self.own(Sender::Yamux(sender), driver); + return self.own(Sender::Yamux(sender), driver, state); } - let (sender, driver) = h2_driver::new(raw).await?; - self.own(Sender::H2(sender), driver) + let (sender, driver) = h2_driver::new(raw, h3_packet_up).await?; + self.own(Sender::H2(sender), driver, state) } fn own( &self, sender: Sender, driver: impl Future + Send + 'static, + state: &Arc>, ) -> io::Result { let cancel = self.cancel.child_token(); let token = cancel.clone(); let drained = self.drained.clone(); - let state = self.state.lock().unwrap(); + let state = state.lock().unwrap(); if state.closed { return Err(io::ErrorKind::ConnectionAborted.into()); } @@ -299,6 +345,11 @@ impl Pool { state.closed = true; self.cancel.cancel(); state.connections.clear(); + if let Some(lane) = &self.udp_lane { + let mut udp = lane.state.lock().unwrap(); + udp.closed = true; + udp.connections.clear(); + } self.tasks.close(); } pub(crate) async fn stop(&self) { @@ -591,7 +642,7 @@ mod tests { } } }); - let (sender, driver) = h2_driver::new(Box::new(raw)).await.unwrap(); + let (sender, driver) = h2_driver::new(Box::new(raw), false).await.unwrap(); let client_driver = tokio::spawn(driver); let sender = Sender::H2(sender); let deadline = Instant::now() + Duration::from_secs(5); @@ -757,7 +808,7 @@ mod tests { } } }); - let (sender, driver) = h2_driver::new(Box::new(raw)).await.unwrap(); + let (sender, driver) = h2_driver::new(Box::new(raw), false).await.unwrap(); let client_driver = tokio::spawn(driver); let deadline = Instant::now() + std::time::Duration::from_secs(10); let mut raw = Sender::H2(sender).open(deadline, false).await.unwrap(); diff --git a/src/transport/sing_mux/h2_driver.rs b/src/transport/sing_mux/h2_driver.rs index ae90512..d89d0a0 100644 --- a/src/transport/sing_mux/h2_driver.rs +++ b/src/transport/sing_mux/h2_driver.rs @@ -3,15 +3,26 @@ use super::*; use crate::transport::h2_write::{Sender, Writes}; use std::time::Duration; -pub(super) async fn new(raw: BoxStream) -> io::Result<(Sender, impl Future + Send)> { +const CONNECTION_RECEIVE_WINDOW: u32 = 1024 * 1024; +const H3_PACKET_UP_CONNECTION_RECEIVE_WINDOW: u32 = 1536 * 1024; + +pub(super) async fn new( + raw: BoxStream, + h3_packet_up: bool, +) -> io::Result<(Sender, impl Future + Send)> { let last_read = Arc::new(Mutex::new(Instant::now())); let (raw, writes) = Writes::wrap(raw); + let connection_window = if h3_packet_up { + H3_PACKET_UP_CONNECTION_RECEIVE_WINDOW + } else { + CONNECTION_RECEIVE_WINDOW + }; let (sender, mut connection) = h2::client::Builder::new() .enable_push(false) - .initial_window_size(65536) + .initial_window_size(131072) // Leave bounded connection credit for other streams when a few TCP // consumers hold their individual receive windows. - .initial_connection_window_size(524288) + .initial_connection_window_size(connection_window) .max_frame_size(16384) .max_header_list_size(16384) .max_concurrent_streams(0) @@ -182,10 +193,13 @@ mod prequeued_flush_memory_tests { let gate = Arc::new(Gate::default()); let peer_gate = Arc::new(Gate::default()); let (client, server) = tokio::join!( - new(Box::new(MemoryIo { - raw, - gate: gate.clone(), - })), + new( + Box::new(MemoryIo { + raw, + gate: gate.clone(), + }), + false, + ), h2::server::Builder::new().handshake::<_, Bytes>(MemoryIo { raw: peer, gate: peer_gate.clone(), @@ -433,3 +447,7 @@ mod prequeued_flush_memory_tests { ); } } + +#[cfg(test)] +#[path = "h2_receive_credit_memory_tests.rs"] +mod receive_credit_memory_tests; diff --git a/src/transport/sing_mux/h2_initial_receive_window_tests.rs b/src/transport/sing_mux/h2_initial_receive_window_tests.rs new file mode 100644 index 0000000..8be13a0 --- /dev/null +++ b/src/transport/sing_mux/h2_initial_receive_window_tests.rs @@ -0,0 +1,219 @@ +// Actual private H2Mux factory and peer; memory only, no copied flow algorithm. +use super::*; + +const CAPTURE_BYTES: usize = 4096; +const PREFACE: &[u8] = b"PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + +#[derive(Default)] +pub(super) struct Wire { + bytes: Vec, + overflow: bool, +} +impl Wire { + fn record(&mut self, bytes: &[u8]) { + let count = bytes.len().min(CAPTURE_BYTES - self.bytes.len()); + self.overflow |= count != bytes.len(); + self.bytes.extend_from_slice(&bytes[..count]); + } + + // Observe accepted protocol bytes, not a shadow flow-control state. + fn initial_credit(&self) -> Result<(Vec, Vec), &'static str> { + if self.overflow || !self.bytes.starts_with(PREFACE) { + return Err("bounded client preface unavailable"); + } + let mut settings = Vec::new(); + let mut connection = Vec::new(); + let mut offset = PREFACE.len(); + while offset < self.bytes.len() { + let head = self.bytes.get(offset..offset + 9).ok_or("partial frame head")?; + let length = (usize::from(head[0]) << 16) + | (usize::from(head[1]) << 8) + | usize::from(head[2]); + let kind = head[3]; + let flags = head[4]; + let stream = u32::from_be_bytes([head[5], head[6], head[7], head[8]]) + & 0x7fff_ffff; + offset += 9; + let payload = self.bytes.get(offset..offset + length).ok_or("partial frame")?; + if kind == 4 && flags & 1 == 0 { + if stream != 0 || length % 6 != 0 { + return Err("invalid actual SETTINGS"); + } + for value in payload.chunks_exact(6) { + if u16::from_be_bytes([value[0], value[1]]) == 4 { + settings.push(u32::from_be_bytes([value[2], value[3], value[4], value[5]])); + } + } + } + if kind == 8 && stream == 0 { + if payload.len() != 4 { + return Err("invalid actual connection WINDOW_UPDATE"); + } + connection.push(u32::from_be_bytes([payload[0], payload[1], payload[2], payload[3]]) + & 0x7fff_ffff); + } + offset += length; + } + Ok((settings, connection)) + } +} + +pub(super) struct ObservedIo { + pub(super) inner: DuplexStream, + pub(super) wire: Arc>, +} +impl AsyncRead for ObservedIo { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + out: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.inner).poll_read(cx, out) + } +} +impl AsyncWrite for ObservedIo { + fn poll_write( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[u8], + ) -> Poll> { + let result = Pin::new(&mut self.inner).poll_write(cx, input); + if let Poll::Ready(Ok(count)) = &result { + self.wire.lock().unwrap().record(&input[..*count]); + } + result + } + fn poll_write_vectored( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + input: &[std::io::IoSlice<'_>], + ) -> Poll> { + let result = Pin::new(&mut self.inner).poll_write_vectored(cx, input); + if let Poll::Ready(Ok(count)) = &result { + let mut remaining = *count; + let mut wire = self.wire.lock().unwrap(); + for part in input { + let count = part.len().min(remaining); + wire.record(&part[..count]); + remaining -= count; + if remaining == 0 { + break; + } + } + } + result + } + fn is_write_vectored(&self) -> bool { + self.inner.is_write_vectored() + } + fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_flush(cx) + } + fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Pin::new(&mut self.inner).poll_shutdown(cx) + } +} + +#[tokio::test] +async fn initial_receive_credit_matches_settings_and_admits_bounded_entities() { + tokio::task::unconstrained(async { + // The +1024 case is opaque carrier data at a TLS-sized boundary, not + // a claim that this harness executes TLS or an HTTP rewrite engine. + for length in [32768, 65536, 65536 + 1024, 131072] { + let mut fixture = OrdinaryFixture::open(false).await; + let initial = fixture.wire.lock().unwrap().initial_credit(); + fixture.outputs[0].as_mut().unwrap() + .send_data(Bytes::from(vec![1; length]), false).unwrap(); + fixture.outputs[TCP].as_mut().unwrap() + .send_data(Bytes::from_static(b"u"), false).unwrap(); + for _ in 0..512 { + fixture.drive(); + fixture.collect(); + if fixture.tcp[0] == length && fixture.sibling == b"u" { + break; + } + } + let before_release = fixture.tcp; + let sibling = fixture.sibling.clone(); + let active = !fixture.driver_done && !fixture.peer_done; + let (joined, final_tcp, contents_ok, final_sibling) = fixture.finish(); + // Real credit release, both EOF directions and both protocol + // owners precede every observation assertion, including old red. + assert!(joined, "real H2 protocol owners did not naturally finish"); + let (settings, connection) = initial.expect("accepted initial H2 wire"); + assert_eq!(settings, [131072], "actual SETTINGS_INITIAL_WINDOW_SIZE"); + assert_eq!(connection, [1048576 - 65535], "original connection increment"); + assert!(active && contents_ok); + assert_eq!(before_release[0], length, "stream stalled before real release"); + assert!(before_release[1..].iter().all(|count| *count == 0)); + assert_eq!(final_tcp, before_release); + assert_eq!(sibling, b"u"); + assert_eq!(final_sibling, b"u"); + } + }).await; +} + +async fn hold_and_release_receive_credit( + h3_packet_up: bool, + sibling_before_release: bool, +) { + tokio::task::unconstrained(async { + let mut fixture = Fixture::::open(h3_packet_up).await; + let initial = fixture.wire.lock().unwrap().initial_credit(); + for index in 0..TCP { + fixture.outputs[index].as_mut().unwrap() + .send_data(Bytes::from(vec![(index + 1) as u8; 131072]), false).unwrap(); + } + for _ in 0..1024 { + fixture.drive(); + fixture.collect(); + if fixture.tcp == [131072; TCP] { + break; + } + } + let held_tcp = fixture.tcp; + fixture.sibling_pending_polls = 0; + fixture.outputs[TCP].as_mut().unwrap() + .send_data(Bytes::from_static(b"u"), false).unwrap(); + for _ in 0..64 { + fixture.drive(); + fixture.collect(); + } + let before_release = fixture.sibling.clone(); + let pending = fixture.sibling_pending_polls; + let active = !fixture.driver_done && !fixture.peer_done; + // finish() returns the actual retained TCP credit before draining the + // sibling. No fabricated grant, extra connection credit or timeout. + let (joined, final_tcp, contents_ok, final_sibling) = fixture.finish(); + assert!(joined, "real H2 protocol owners did not naturally finish"); + let (settings, connection) = initial.expect("accepted initial H2 wire"); + assert_eq!(settings, [131072]); + let expected_window = if h3_packet_up { 1572864 } else { 1048576 }; + assert_eq!(connection, [expected_window - 65535]); + assert!(active && contents_ok); + assert_eq!(held_tcp, [131072; TCP]); + if sibling_before_release { + assert_eq!(before_release, b"u", "sibling did not use remaining connection credit"); + } else { + assert!(before_release.is_empty() && pending > 0, + "sibling DATA exceeded the connection receive credit"); + } + assert_eq!(final_tcp, held_tcp); + assert_eq!(final_sibling, b"u", "actual credit release did not resume sibling"); + }).await; +} + +#[tokio::test] +async fn held_receive_data_stays_bounded_by_the_connection_window() { + hold_and_release_receive_credit::<9, 8>(false, false).await; +} + +#[tokio::test] +async fn h3_packet_up_connection_credit_leaves_room_for_a_ninth_stream() { + hold_and_release_receive_credit::<9, 8>(true, true).await; +} + +#[tokio::test] +async fn h3_packet_up_connection_credit_blocks_after_twelve_full_streams() { + hold_and_release_receive_credit::<13, 12>(true, false).await; +} diff --git a/src/transport/sing_mux/h2_receive_credit_memory_tests.rs b/src/transport/sing_mux/h2_receive_credit_memory_tests.rs new file mode 100644 index 0000000..d7ba254 --- /dev/null +++ b/src/transport/sing_mux/h2_receive_credit_memory_tests.rs @@ -0,0 +1,302 @@ +//! Actual production h2mux receive credit over a bounded memory carrier. +//! TCP/UDP names describe consumer roles; this is not a datagram-codec test. +use super::*; +use bytes::Bytes; +use futures_util::task::noop_waker; +use std::future::Future; +use std::sync::{Arc, Mutex}; +use tokio::io::{AsyncRead, AsyncWrite, DuplexStream, ReadBuf}; + +const TCP: usize = 8; +const STREAMS: usize = TCP + 1; +const STREAM_BYTES: usize = 65536; + +type Requester = h2::client::SendRequest; +type OrdinaryFixture = Fixture; + +struct Fixture { + wire: Arc>, + driver: Pin + Send>>, + peer: h2::server::Connection, + sender: Option, + responses: [Option; STREAMS], + bodies: [Option; STREAMS], + inputs: [Option; STREAMS], + outputs: [Option>; STREAMS], + tcp: [usize; TCP], + sibling: Vec, + sibling_pending_polls: usize, + held: Vec, + body_eof: [bool; STREAMS], + input_eof: [bool; STREAMS], + accepted: usize, + contents_ok: bool, + driver_done: bool, + peer_done: bool, +} +impl Fixture { + async fn open(h3_packet_up: bool) -> Self { + assert_eq!(STREAMS, TCP + 1); + let (client, peer) = tokio::io::duplex(65536); + let wire = Arc::new(Mutex::new(initial_window_contract::Wire::default())); + let (client, peer) = tokio::join!( + new( + Box::new(initial_window_contract::ObservedIo { + inner: client, + wire: wire.clone(), + }), + h3_packet_up, + ), + h2::server::Builder::new().handshake::<_, Bytes>(peer), + ); + let (sender, driver) = client.unwrap(); + let mut fixture = Self { + wire, + driver: Box::pin(driver), + peer: peer.unwrap(), + sender: Some(sender.request), + responses: std::array::from_fn(|_| None), + bodies: std::array::from_fn(|_| None), + inputs: std::array::from_fn(|_| None), + outputs: std::array::from_fn(|_| None), + tcp: [0; TCP], + sibling: Vec::new(), + sibling_pending_polls: 0, + held: Vec::new(), + body_eof: [false; STREAMS], + input_eof: [false; STREAMS], + accepted: 0, + contents_ok: true, + driver_done: false, + peer_done: false, + }; + for index in 0..STREAMS { + for _ in 0..128 { + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + if let Poll::Ready(result) = fixture.sender.as_mut().unwrap().poll_ready(&mut cx) { + result.unwrap(); + let request = http::Request::builder() + .method("CONNECT") + .uri("https://localhost") + .body(()) + .unwrap(); + let (response, _) = fixture + .sender + .as_mut() + .unwrap() + .send_request(request, true) + .unwrap(); + fixture.responses[index] = Some(response); + break; + } + fixture.drive(); + } + assert!( + fixture.responses[index].is_some(), + "real CONNECT admission stalled" + ); + } + for _ in 0..128 { + fixture.drive(); + if fixture.accepted == STREAMS && fixture.bodies.iter().all(Option::is_some) { + for _ in 0..8 { + fixture.drive(); + } + return fixture; + } + } + panic!("real H2 response setup did not complete"); + } + fn drive(&mut self) { + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + if !self.driver_done { + self.driver_done = self.driver.as_mut().poll(&mut cx).is_ready(); + } + if !self.peer_done { + match self.peer.poll_accept(&mut cx) { + Poll::Ready(Some(Ok((request, mut reply)))) => { + let index = self.accepted; + assert!(index < STREAMS && request.method() == "CONNECT"); + self.inputs[index] = Some(request.into_body()); + self.outputs[index] = + Some(reply.send_response(http::Response::new(()), false).unwrap()); + self.accepted += 1; + } + Poll::Ready(Some(Err(error))) => panic!("real H2 peer failed: {error}"), + Poll::Ready(None) => self.peer_done = true, + Poll::Pending => {} + } + } + for index in 0..STREAMS { + if let Some(response) = &mut self.responses[index] { + if let Poll::Ready(result) = Pin::new(response).poll(&mut cx) { + self.bodies[index] = Some(result.unwrap().into_body()); + self.responses[index] = None; + } + } + } + } + fn collect(&mut self) { + let waker = noop_waker(); + let mut cx = Context::from_waker(&waker); + for index in 0..STREAMS { + if let Some(body) = &mut self.bodies[index] { + for _ in 0..8 { + match body.poll_data(&mut cx) { + Poll::Ready(Some(Ok(bytes))) => { + if index < TCP { + self.tcp[index] += bytes.len(); + self.contents_ok &= + bytes.iter().all(|byte| *byte == (index + 1) as u8); + // Keep the real payload and do not release its credit. + self.held.push(bytes); + } else { + self.sibling.extend_from_slice(&bytes); + } + } + Poll::Ready(Some(Err(error))) => panic!("real H2 body failed: {error}"), + Poll::Ready(None) => { + self.body_eof[index] = true; + break; + } + Poll::Pending => { + if index == TCP { + self.sibling_pending_polls += 1; + } + break; + } + } + } + } + if let Some(input) = &mut self.inputs[index] { + match input.poll_data(&mut cx) { + Poll::Ready(None) => self.input_eof[index] = true, + Poll::Ready(Some(Ok(bytes))) => { + assert!(bytes.is_empty(), "unexpected request DATA") + } + Poll::Ready(Some(Err(error))) => panic!("request EOF failed: {error}"), + Poll::Pending => {} + } + } + } + } + fn finish(mut self) -> (bool, [usize; TCP], bool, Vec) { + // A blocked sibling must resume after true consumption. + for index in 0..TCP { + self.bodies[index] + .as_mut() + .unwrap() + .flow_control() + .release_capacity(self.tcp[index]) + .unwrap(); + } + self.held.clear(); + for _ in 0..256 { + self.drive(); + self.collect(); + if self.sibling.len() == 1 { + break; + } + } + self.bodies[TCP] + .as_mut() + .unwrap() + .flow_control() + .release_capacity(self.sibling.len()) + .unwrap(); + for output in self.outputs.iter_mut().flatten() { + output.send_data(Bytes::new(), true).unwrap(); + } + for _ in 0..256 { + self.drive(); + self.collect(); + if self.body_eof.iter().all(|eof| *eof) && self.input_eof.iter().all(|eof| *eof) { + break; + } + } + let all_eof = self.body_eof.iter().all(|eof| *eof) && self.input_eof.iter().all(|eof| *eof); + for index in 0..STREAMS { + drop(self.responses[index].take()); + drop(self.bodies[index].take()); + drop(self.inputs[index].take()); + drop(self.outputs[index].take()); + } + drop(self.sender.take()); + self.held.clear(); + for _ in 0..256 { + self.drive(); + if self.driver_done && self.peer_done { + break; + } + } + ( + all_eof && self.driver_done && self.peer_done, + self.tcp, + self.contents_ok, + self.sibling, + ) + } +} + +#[tokio::test] +async fn held_tcp_windows_leave_receive_credit_for_a_sibling() { + tokio::task::unconstrained(async { + let mut fixture = OrdinaryFixture::open(false).await; + for index in 0..TCP { + fixture.outputs[index] + .as_mut() + .unwrap() + .send_data(Bytes::from(vec![(index + 1) as u8; STREAM_BYTES]), false) + .unwrap(); + } + for _ in 0..512 { + fixture.drive(); + fixture.collect(); + if fixture.tcp == [STREAM_BYTES; TCP] { + break; + } + } + let held_tcp = fixture.tcp; + fixture.sibling_pending_polls = 0; + fixture.outputs[TCP] + .as_mut() + .unwrap() + .send_data(Bytes::from_static(b"u"), false) + .unwrap(); + for _ in 0..64 { + fixture.drive(); + fixture.collect(); + } + let before_release = fixture.sibling.clone(); + let pending_before_release = fixture.sibling_pending_polls; + // An empty result records real recv Pending after the peer queued DATA; + // no fake flow-control count or copied production window is involved. + let active = !fixture.driver_done && !fixture.peer_done; + let (joined, final_tcp, contents_ok, final_sibling) = fixture.finish(); + assert!(joined, "real H2 protocol owners did not naturally finish"); + assert!(active && contents_ok); + assert!(!before_release.is_empty() || pending_before_release > 0); + assert_eq!( + held_tcp, [STREAM_BYTES; TCP], + "the original 64KiB TCP entities were not actually retained" + ); + assert_eq!(final_tcp, held_tcp); + assert_eq!( + final_sibling, b"u", + "true TCP credit release did not resume the sibling" + ); + // Expected old-code red is last, after real credit release and owner exit. + assert_eq!( + before_release, b"u", + "held TCP stream windows exhausted sibling connection credit" + ); + }) + .await; +} + +#[forbid(unsafe_code)] +mod initial_window_contract { + include!("h2_initial_receive_window_tests.rs"); +} diff --git a/src/transport/sing_mux/smux_driver.rs b/src/transport/sing_mux/smux_driver.rs index 8b2954b..428c588 100644 --- a/src/transport/sing_mux/smux_driver.rs +++ b/src/transport/sing_mux/smux_driver.rs @@ -1,2 +1,2 @@ //! Preserve the sing-mux v1 framing contract through the shared raw driver. -pub(super) use crate::transport::smux::{Client, new_with_autonomous_writes}; +pub(super) use crate::transport::smux::{Client, new_with_queued_flush_coalescing}; diff --git a/src/transport/smux.rs b/src/transport/smux.rs index a5a2a80..e9d93fb 100644 --- a/src/transport/smux.rs +++ b/src/transport/smux.rs @@ -191,23 +191,39 @@ impl Drop for Lifetime { pub(crate) fn new(raw: BoxStream) -> (Client, impl Future + Send) { with_options(raw, Options::default()).expect("valid default smux options") } -#[cfg(any(feature = "sing-mux", test))] +#[cfg(test)] pub(crate) fn new_with_autonomous_writes( raw: BoxStream, autonomous_writes: bool, ) -> (Client, impl Future + Send) { - configure(raw, Options::default(), autonomous_writes).expect("valid default smux options") + configure(raw, Options::default(), autonomous_writes, false) + .expect("valid default smux options") +} +#[cfg(any(feature = "sing-mux", test))] +pub(crate) fn new_with_queued_flush_coalescing( + raw: BoxStream, + autonomous_writes: bool, + coalesce_queued_flush: bool, +) -> (Client, impl Future + Send) { + configure( + raw, + Options::default(), + autonomous_writes, + coalesce_queued_flush, + ) + .expect("valid default smux options") } pub(crate) fn with_options( raw: BoxStream, options: Options, ) -> io::Result<(Client, impl Future + Send)> { - configure(raw, options, false) + configure(raw, options, false, false) } fn configure( raw: BoxStream, options: Options, autonomous_writes: bool, + coalesce_queued_flush: bool, ) -> io::Result<(Client, impl Future + Send)> { if !(1..=2).contains(&options.version) || !(1..=65535).contains(&options.frame_size) @@ -219,6 +235,8 @@ fn configure( { return Err(io::ErrorKind::InvalidInput.into()); } + // The typed VLESS factory grants this only before the pool is used. + let coalesce_queued_flush = coalesce_queued_flush && autonomous_writes; let receive_budget = Arc::new(tokio::sync::Semaphore::new(options.receive_buffer)); let epoch = tokio::time::Instant::now(); let last_read = Arc::new(AtomicU64::new(0)); @@ -428,7 +446,10 @@ fn configure( && entry.flow.update.load(Ordering::Acquire)) }) }; - if flush_barrier + // A queued strong ticket may share one later real flush + // with already queued commands. No write crosses a Pending + // flush and no receipt is completed before that real flush. + if (flush_barrier && !coalesce_queued_flush) || result.is_err() || count == crate::limits::SING_MUX_COMMAND_QUEUE || processed + count >= crate::limits::IO_POLL_BUDGET @@ -1484,6 +1505,197 @@ mod tests { .unwrap(); } } + #[cfg(all(feature = "sing-mux", feature = "outbound-vless"))] + mod h3_queued_flush_memory_tests { + use super::*; + use crate::{ + dispatch::{DatagramTransport, DispatchError}, + outbound::{ + ConnectedStream, DatagramRequest, EstablishContext, OutboundConnector, + SingMuxConnector, + }, + session::{Destination, InboundKind, StreamSession}, + }; + use futures_util::FutureExt; + use std::panic::{AssertUnwindSafe, resume_unwind}; + + struct MemoryCarrier(Mutex>); + #[async_trait::async_trait] + impl OutboundConnector for MemoryCarrier { + async fn connect_stream( + &self, + session: StreamSession, + _: &EstablishContext, + ) -> Result { + let io = self + .0 + .lock() + .unwrap() + .take() + .ok_or_else(|| io::Error::other("second physical carrier"))?; + Ok(ConnectedStream { + io, + effective_peer: session.destination, + }) + } + async fn open_datagram( + &self, + _: DatagramRequest, + _: &EstablishContext, + ) -> Result, DispatchError> { + panic!("memory Smux fixture must use its supplied TCP carrier") + } + async fn shutdown(&self) {} + } + + fn proxy( + alpn: &str, + mode: &str, + placement: &str, + split: bool, + only_tcp: bool, + ) -> crate::config::ProxyConfig { + let mut xhttp = serde_json::json!({"path":"/x", "mode":mode}); + if placement != "body" { + xhttp["uplink-data-placement"] = placement.into(); + if placement != "auto" { + xhttp["uplink-data-key"] = "payload".into(); + } + } + if split { + xhttp["download-settings"] = serde_json::json!({}); + } + let raw = serde_json::json!({ + "proxies":[{"name":"memory", "type":"vless", "server":"192.0.2.1", "port":443, + "uuid":"00000000-0000-0000-0000-000000000001", "tls":true, "alpn":[alpn], + "network":"xhttp", "xhttp-opts":xhttp, + "smux":{"enabled":true,"protocol":"smux","max-connections":1, + "padding":false,"only-tcp":only_tcp}}], + "rules":["MATCH,DIRECT"] + }); + crate::config::Config::parse_yaml(raw.to_string().as_bytes()) + .unwrap() + .proxies + .remove(0) + } + + async fn observe(proxy: crate::config::ProxyConfig, outcome: u8) -> usize { + let (raw, peer) = tokio::io::duplex(65536); + let gate = Arc::new(FlushGateState::default()); + gate.mode.store(1, Ordering::Release); + let carrier = Arc::new(MemoryCarrier(Mutex::new(Some(Box::new(FlushGate { + raw, + state: gate.clone(), + }))))); + let node = SingMuxConnector::new(carrier, proxy.smux.as_ref().unwrap().clone()) + .with_autonomous_xhttp(&proxy); + let observed = AssertUnwindSafe(tokio::time::timeout(Duration::from_secs(2), async { + let session = StreamSession { + metadata: Default::default(), + inbound: InboundKind::Socks5, + source: "192.0.2.3:40001".parse().unwrap(), + destination: Destination::domain("memory.invalid", 443).unwrap(), + sniffed_domain: None, + }; + let context = EstablishContext::default(); + let mut first = node + .connect_stream(session.clone(), &context) + .await + .unwrap(); + let mut second = node.connect_stream(session, &context).await.unwrap(); + first.io.write_all(b"first").await.unwrap(); + second.io.write_all(b"second").await.unwrap(); + // Empty writes observe both actual autonomous DATA receipts; + // no extra DATA or strong flush is introduced by this setup. + assert_eq!(first.io.write(b"").await.unwrap(), 0); + assert_eq!(second.io.write(b"").await.unwrap(), 0); + let before = gate.flushes.load(Ordering::Acquire); + gate.mode.store(0, Ordering::Release); + let mut a = Box::pin(first.io.flush()); + let mut b = Box::pin(second.io.flush()); + // On the current-thread runtime both tickets are queued before + // the owned real Smux driver can run. + assert!(futures_util::poll!(a.as_mut()).is_pending()); + assert!(futures_util::poll!(b.as_mut()).is_pending()); + tokio::task::yield_now().await; + assert!(futures_util::poll!(a.as_mut()).is_pending()); + assert!(futures_util::poll!(b.as_mut()).is_pending()); + assert_eq!(gate.flushes.load(Ordering::Acquire), before); + // Cancellation retains the real Stream's pending receiver; + // the retry must not enqueue another strong ticket. + drop(a); + let mut a = Box::pin(first.io.flush()); + assert!(futures_util::poll!(a.as_mut()).is_pending()); + if outcome == 3 { + node.begin_shutdown(); + } else { + gate.mode.store(outcome, Ordering::Release); + gate.changed.wake(); + } + let (a_result, b_result) = tokio::join!(a, b); + if outcome == 1 { + assert!(a_result.is_ok() && b_result.is_ok()); + } else { + assert!( + a_result.is_err() && b_result.is_err(), + "failed/Stopped flush acknowledged bytes" + ); + } + gate.flushes.load(Ordering::Acquire) - before + })) + .catch_unwind() + .await; + // Every assertion/error/timeout is reported only after Stop joins + // the actual factory-owned driver and the memory peer is dropped. + node.shutdown().await; + drop(node); + drop(peer); + match observed { + Ok(result) => result.expect("bounded factory Smux fixture timed out"), + Err(panic) => resume_unwind(panic), + } + } + + #[tokio::test] + async fn qualified_factory_coalesces_queued_flushes_without_early_success() { + for placement in ["body", "auto"] { + let successful = + observe(proxy("h3", "packet-up", placement, false, false), 1).await; + assert_eq!( + successful, 1, + "two already queued tickets used separate real flushes" + ); + } + assert_eq!( + observe(proxy("h3", "packet-up", "body", false, false), 2).await, + 0 + ); + assert_eq!( + observe(proxy("h3", "packet-up", "body", false, false), 3).await, + 0 + ); + } + + #[tokio::test] + async fn excluded_factories_keep_separate_queued_flush_boundaries() { + for (alpn, mode, placement, split, only_tcp) in [ + ("http/1.1", "packet-up", "body", false, false), + ("h2", "packet-up", "body", false, false), + ("h3", "stream-up", "body", false, false), + ("h3", "stream-one", "body", false, false), + ("h3", "packet-up", "header", false, false), + ("h3", "packet-up", "cookie", false, false), + ("h3", "packet-up", "body", true, false), + ("h3", "packet-up", "body", false, true), + ] { + assert_eq!( + observe(proxy(alpn, mode, placement, split, only_tcp), 1).await, + 2, + "excluded {alpn}/{mode}/{placement}/{split}/{only_tcp} coalesced" + ); + } + } + } } #[cfg(test)] diff --git a/src/transport/xhttp.rs b/src/transport/xhttp.rs index 919319d..7d20930 100644 --- a/src/transport/xhttp.rs +++ b/src/transport/xhttp.rs @@ -121,6 +121,8 @@ pub struct XHttpClient { send_buffer_size: usize, upload_chunk_size: usize, shared_packet_up: bool, + packet_up_response_overlap: bool, + yamux_packet_up_send_retention: bool, http_version: crate::config::XHttpVersion, owner: Arc, reuse: Option>, @@ -165,6 +167,8 @@ impl XHttpClient { send_buffer_size: DEFAULT_H2_SEND_BUFFER_SIZE, upload_chunk_size: DEFAULT_UPLOAD_CHUNK_SIZE, shared_packet_up: false, + packet_up_response_overlap: false, + yamux_packet_up_send_retention: false, http_version, owner: Arc::default(), pool: Arc::new(pool::Pool::new(reuse.clone(), http_version)), @@ -177,6 +181,9 @@ impl XHttpClient { pub(crate) fn set_shared_packet_up_transport(&mut self, shared: bool) { #[cfg(all(feature = "outbound-vless", feature = "sing-mux"))] let previous = self.udp_budget_qualified(); + if shared { + self.set_yamux_packet_up_send_retention(false); + } self.shared_packet_up = shared; #[cfg(all(feature = "outbound-vless", feature = "sing-mux"))] if previous != self.udp_budget_qualified() { @@ -184,6 +191,46 @@ impl XHttpClient { self.pool = Arc::new(pool::Pool::new(self.reuse.clone(), self.http_version)); } } + + /// Fixed by the VLESS factory before publication; geometry grants no UDP credit. + #[cfg(any(feature = "invoke", test))] + pub(crate) fn set_packet_up_response_overlap(&mut self, enabled: bool) { + self.packet_up_response_overlap = enabled + && self.http_version == crate::config::XHttpVersion::Http3 + && self.mode == XHttpMode::PacketUp + && matches!( + &self.request.options.data, + crate::config::xhttp::DataPlacement::Body + ); + } + + /// Fixed by the VLESS/Yamux factory before publication; this is not an + /// adaptive UDP proof or evidence of a physical metadata flush. + #[cfg(any(feature = "invoke", test))] + pub(crate) fn set_yamux_packet_up_send_retention(&mut self, enabled: bool) { + let qualified = enabled + && !self.shared_packet_up + && self.http_version == crate::config::XHttpVersion::Http3 + && self.mode == XHttpMode::PacketUp + && matches!( + &self.request.options.data, + crate::config::xhttp::DataPlacement::Body + ); + if self.yamux_packet_up_send_retention != qualified { + self.yamux_packet_up_send_retention = qualified; + // A changed physical budget must not inherit either clone's pool. + self.pool = Arc::new(pool::Pool::new(self.reuse.clone(), self.http_version)); + } + } + + fn h3_initial_send_window(&self) -> u64 { + if self.yamux_packet_up_send_retention && !self.shared_packet_up { + crate::limits::XHTTP_H3_YAMUX_SEND_WINDOW as u64 + } else { + crate::limits::XHTTP_H3_SEND_WINDOW as u64 + } + } + #[cfg(all(feature = "outbound-vless", feature = "sing-mux"))] fn udp_budget_qualified(&self) -> bool { self.shared_packet_up @@ -542,6 +589,13 @@ impl XHttpClient { self.http_version } + /// Business HTTP may retain this logical stream only while its actual + /// transport owner is open. Carrier pool/mode/lease policy is unchanged. + #[cfg(all(feature = "outbound-vless", feature = "inbound-http"))] + pub(crate) fn is_http_reuse_owner_open(&self) -> bool { + !self.owner.cancellation.is_cancelled() + } + #[cfg(feature = "interop-test")] pub(crate) fn quic_pings(&self) -> Vec { self.pool.quic_pings() @@ -558,6 +612,7 @@ impl XHttpClient { match transport { TransportIo::Stream(stream) if self.http_version != crate::config::XHttpVersion::Http3 => self.handshake_active(stream).await, TransportIo::Quic(transport) if self.http_version == crate::config::XHttpVersion::Http3 => h3_driver::connect(*transport, self.reuse.as_ref().map_or(0, |r| r.keep_alive_seconds), + self.h3_initial_send_window(), #[cfg(all(feature = "outbound-vless", feature = "sing-mux"))] self.udp_budget_qualified(), &self.owner).await, @@ -632,7 +687,7 @@ impl XHttpClient { sender: SendRequest, session: Arc, ) -> io::Result { - let overlap = self.shared_packet_up + let overlap = (self.shared_packet_up || self.packet_up_response_overlap) && self.mode == XHttpMode::PacketUp && matches!(&sender, SendRequest::H3(_)) && matches!( diff --git a/src/transport/xhttp/h3_driver.rs b/src/transport/xhttp/h3_driver.rs index 2a7c2ef..bba84b4 100644 --- a/src/transport/xhttp/h3_driver.rs +++ b/src/transport/xhttp/h3_driver.rs @@ -62,6 +62,7 @@ pub(super) struct Sender { pub(super) async fn connect( raw: QuicTransport, keepalive: i32, + initial_send_window: u64, #[cfg(all(feature = "outbound-vless", feature = "sing-mux"))] udp_qualified: bool, owner: &DriverOwner, ) -> io::Result<(SendRequest, Arc)> { @@ -115,7 +116,7 @@ pub(super) async fn connect( .max_concurrent_uni_streams((crate::limits::XHTTP_H3_UNI_STREAMS as u32).into()) .stream_receive_window((crate::limits::XHTTP_H3_STREAM_WINDOW as u32).into()) .receive_window((crate::limits::XHTTP_H3_CONNECTION_WINDOW as u32).into()) - .send_window(crate::limits::XHTTP_H3_SEND_WINDOW as u64) + .send_window(initial_send_window) .datagram_receive_buffer_size(None) .datagram_send_buffer_size(0) .max_idle_timeout(Some(Duration::from_secs(300).try_into().map_err(failure)?)) diff --git a/src/transport/xhttp/h3_packet_overlap_memory_tests.rs b/src/transport/xhttp/h3_packet_overlap_memory_tests.rs index ff2f5e9..10b01bc 100644 --- a/src/transport/xhttp/h3_packet_overlap_memory_tests.rs +++ b/src/transport/xhttp/h3_packet_overlap_memory_tests.rs @@ -252,6 +252,15 @@ impl Fixture { } fn node(smux: Option, placement: &str, split: bool) -> VlessOutbound { + node_with_encryption(smux, placement, split, false) +} + +fn node_with_encryption( + smux: Option, + placement: &str, + split: bool, + encryption: bool, +) -> VlessOutbound { let mut raw = serde_json::json!({ "proxies":[{"name":"fixture", "type":"vless", "server":"example.com", "port":443, "uuid":"00000000-0000-0000-0000-000000000001", "tls":true, "alpn":["h3"], @@ -268,6 +277,12 @@ fn node(smux: Option, placement: &str, split: bool) -> VlessO raw["proxies"][0]["xhttp-opts"]["download-settings"] = serde_json::json!({ "server":"download.example", "port":8443, "tls":true, "alpn":["h3"]}); } + if encryption { + raw["proxies"][0]["encryption"] = serde_json::json!(format!( + "mlkem768x25519plus.native.1rtt.{}", + base64::engine::general_purpose::URL_SAFE_NO_PAD.encode([9_u8; 32]) + )); + } let config = crate::config::Config::parse_yaml(raw.to_string().as_bytes()).unwrap(); let proxy = &config.proxies[0]; let crate::config::ProxyProtocol::Vless(settings) = &proxy.protocol else { @@ -288,16 +303,66 @@ fn node(smux: Option, placement: &str, split: bool) -> VlessO node.configure_shared_xhttp_transport(proxy.smux.as_ref()); node } -fn shared_node(placement: &str) -> VlessOutbound { +fn shared_node(protocol: &str, placement: &str) -> VlessOutbound { node( Some( - serde_json::json!({"enabled":true, "protocol":"h2mux", "only-tcp":false, + serde_json::json!({"enabled":true, "protocol":protocol, "only-tcp":false, "padding":false}), ), placement, false, ) } + +fn overlap_version_mode_node(protocol: &str, alpn: &str, mode: &str) -> VlessOutbound { + let raw = serde_json::json!({ + "proxies":[{"name":"fixture", "type":"vless", "server":"example.com", "port":443, + "uuid":"00000000-0000-0000-0000-000000000001", "tls":true, "alpn":[alpn], + "network":"xhttp", "xhttp-opts":{"path":"/x", "mode":mode}, + "smux":{"enabled":true,"protocol":protocol,"only-tcp":false,"padding":false}}], + "rules":["MATCH,DIRECT"] + }); + let config = crate::config::Config::parse_yaml(raw.to_string().as_bytes()).unwrap(); + let proxy = &config.proxies[0]; + let crate::config::ProxyProtocol::Vless(settings) = &proxy.protocol else { + panic!("not VLESS") + }; + let endpoint = crate::dialer::ResolvedEndpoint { + logical_host: "example.com".into(), + port: 443, + addresses: vec!["192.0.2.2:443".parse().unwrap()], + }; + let mut node = VlessOutbound::new_with_endpoints( + settings, + endpoint, + None, + crate::dialer::Dialer::default(), + ) + .unwrap(); + node.configure_shared_xhttp_transport(proxy.smux.as_ref()); + node +} + +#[test] +fn overlap_other_http_versions_and_stream_modes_keep_original_factories() { + for protocol in ["yamux", "smux"] { + for (alpn, mode) in [ + ("http/1.1", "packet-up"), + ("h2", "packet-up"), + ("h3", "stream-up"), + ("h3", "stream-one"), + ] { + let node = overlap_version_mode_node(protocol, alpn, mode); + let (client, download) = node.test_xhttp_clients().unwrap(); + assert!(download.is_none()); + assert!(!client.packet_up_response_overlap); + assert!(!client.shared_packet_up); + assert!(!client.udp_budget_qualified()); + OutboundConnector::begin_shutdown(&node); + } + } +} + fn payload(sequence: usize) -> Vec { payload_len(sequence, BATCH) } @@ -367,99 +432,212 @@ fn finish(result: Result, Box= Duration::from_millis(2), - "partial POST bypassed aggregation" - ); - assert!( - elapsed < Duration::from_millis(5), - "qualified default still waited five ms" - ); - assert_eq!(writer.snapshot().accepted, 64); - assert_eq!(writer.snapshot().committed, 0); - pending_flush(&mut writer).await; - release.send(()).unwrap(); - writer.flush().await.unwrap(); - assert_eq!(writer.snapshot().committed, 64); - writer.shutdown().await.unwrap(); - })) - .catch_unwind() - .await; - fixture.stop().await; - node.shutdown().await; - finish(result); + for protocol in ["h2mux", "yamux", "smux"] { + let node = shared_node(protocol, "body"); + let (client, _) = node.test_xhttp_clients().unwrap(); + let mut fixture = Fixture::new(client, false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let mut peer = fixture.initialize().await; + let (arrived, arrival) = oneshot::channel(); + let (release, released) = oneshot::channel(); + fixture.spawn(async move { + let mut first = accept(&mut peer, "default-five", 0).await; + let at = tokio::time::Instant::now(); + body_len(&mut first, 0, 64).await; + arrived.send(at).unwrap(); + released.await.unwrap(); + respond(&mut first, 200).await; + let _ = peer.accept().await; + }); + let mut writer = fixture.writer("default-five"); + let began = tokio::time::Instant::now(); + writer.write_all(&payload_len(0, 64)).await.unwrap(); + let at = arrival.await.unwrap(); + // Real peer headers/body/FIN are observed, not the delay expression. + // Arrival may include transport service; the preceding 5 ms default + // cannot pass this bound even when its transport service is immediate. + let elapsed = at - began; + assert!( + elapsed >= Duration::from_millis(2), + "partial POST bypassed aggregation" + ); + assert!( + elapsed < Duration::from_millis(5), + "qualified default still waited five ms" + ); + assert_eq!(writer.snapshot().accepted, 64); + assert_eq!(writer.snapshot().committed, 0); + pending_flush(&mut writer).await; + release.send(()).unwrap(); + writer.flush().await.unwrap(); + assert_eq!(writer.snapshot().committed, 64); + writer.shutdown().await.unwrap(); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); + } } #[tokio::test] async fn two_held_post_responses_reuse_one_body_backing_and_bound_the_third_write() { - for placement in ["body", "auto"] { - let node = shared_node(placement); - let (client, download) = node.test_xhttp_clients().unwrap(); - assert!(download.is_none()); + for protocol in ["h2mux", "yamux", "smux"] { + for placement in ["body", "auto"] { + let node = shared_node(protocol, placement); + let (client, download) = node.test_xhttp_clients().unwrap(); + assert!(download.is_none()); + let mut fixture = Fixture::new(client, false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let mut peer = fixture.initialize().await; + let (first, arrived_first) = oneshot::channel(); + let (second, arrived_second) = oneshot::channel(); + let (release, released) = oneshot::channel(); + fixture.spawn(async move { + let mut a = accept(&mut peer, "two", 0).await; + body(&mut a, 0).await; + first.send(()).unwrap(); + let mut b = accept(&mut peer, "two", 1).await; + body(&mut b, 1).await; + second.send(()).unwrap(); + released.await.unwrap(); + respond(&mut a, 200).await; + respond(&mut b, 200).await; + let _ = peer.accept().await; + }); + let mut writer = fixture.writer("two"); + writer.write_all(&payload(0)).await.unwrap(); + // This immediate read occurs before yielding to the worker in the + // current-thread runtime. Do not inspect the taken/empty Vec later. + let first = writer.snapshot(); + assert_eq!(first.buffer_len, BATCH); + assert_eq!(first.buffer_capacity, BATCH); + arrived_first.await.unwrap(); + writer.write_all(&payload(1)).await.unwrap(); + let second = writer.snapshot(); + assert_eq!(second.buffer_len, BATCH); + assert_eq!(second.buffer_capacity, BATCH); + assert_eq!( + second.buffer_ptr, first.buffer_ptr, + "the body backing must be recovered, not copied into a parallel workspace" + ); + arrived_second.await.unwrap(); + pending_write(&mut writer).await; + pending_flush(&mut writer).await; + assert_eq!(writer.snapshot().accepted, (2 * BATCH) as u64); + assert_eq!(writer.snapshot().committed, 0); + release.send(()).unwrap(); + writer.flush().await.unwrap(); + writer.shutdown().await.unwrap(); + assert_eq!(writer.snapshot().committed, (2 * BATCH) as u64); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); + } + } +} + +#[tokio::test] +async fn consumed_second_response_cannot_cross_a_failed_first_response_hole() { + for protocol in ["h2mux", "yamux", "smux"] { + let node = shared_node(protocol, "body"); + let (client, _) = node.test_xhttp_clients().unwrap(); let mut fixture = Fixture::new(client, false, 16, 256 * 1024); let result = AssertUnwindSafe(timeout(LIMIT, async { let mut peer = fixture.initialize().await; - let (first, arrived_first) = oneshot::channel(); let (second, arrived_second) = oneshot::channel(); - let (release, released) = oneshot::channel(); + let (fail_first, failed_first) = oneshot::channel(); fixture.spawn(async move { - let mut a = accept(&mut peer, "two", 0).await; + let mut a = accept(&mut peer, "hole", 0).await; + body(&mut a, 0).await; + let mut b = accept(&mut peer, "hole", 1).await; + body(&mut b, 1).await; + respond(&mut b, 200).await; + second.send(()).unwrap(); + failed_first.await.unwrap(); + respond(&mut a, 500).await; + // A fresh writer on this same live H3 connection is a positive + // barrier: a replayed failed session would not match this request. + let mut control = accept(&mut peer, "control", 0).await; + body(&mut control, 0).await; + respond(&mut control, 200).await; + let _ = peer.accept().await; + }); + let mut writer = fixture.writer("hole"); + writer.write_all(&payload(0)).await.unwrap(); + writer.write_all(&payload(1)).await.unwrap(); + arrived_second.await.unwrap(); + loop { + let seen = writer.snapshot(); + if seen.ready_out_of_order { + assert_eq!(seen.occupied_responses, 2); + assert_eq!(seen.ready_responses, 1); + assert_eq!(seen.committed, 0); + break; + } + tokio::task::yield_now().await; + } + // These are checks after actual response consumption, not a race with + // an unpolled response future. Pending alone would be insufficient. + pending_write(&mut writer).await; + pending_flush(&mut writer).await; + fail_first.send(()).unwrap(); + let failure = writer.flush().await.unwrap_err(); + assert!( + failure.to_string().contains("HTTP status 500"), + "wrong failure: {failure}" + ); + assert_eq!(writer.snapshot().committed, 0); + assert!(writer.write_all(b"no replay").await.is_err()); + let mut control = fixture.writer("control"); + control.write_all(&payload(0)).await.unwrap(); + control.flush().await.unwrap(); + control.shutdown().await.unwrap(); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); + } +} + +#[tokio::test] +async fn one_peer_stream_credit_jointly_drives_old_response_and_next_open() { + for protocol in ["h2mux", "yamux", "smux"] { + let node = shared_node(protocol, "body"); + let (client, _) = node.test_xhttp_clients().unwrap(); + let mut fixture = Fixture::new(client, false, 1, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let mut peer = fixture.initialize().await; + let (first, arrived_first) = oneshot::channel(); + let (release, released) = oneshot::channel(); + let (second, arrived_second) = oneshot::channel(); + fixture.spawn(async move { + let mut a = accept(&mut peer, "credit", 0).await; body(&mut a, 0).await; first.send(()).unwrap(); - let mut b = accept(&mut peer, "two", 1).await; - body(&mut b, 1).await; - second.send(()).unwrap(); released.await.unwrap(); respond(&mut a, 200).await; + drop(a); + let mut b = accept(&mut peer, "credit", 1).await; + body(&mut b, 1).await; + second.send(()).unwrap(); respond(&mut b, 200).await; let _ = peer.accept().await; }); - let mut writer = fixture.writer("two"); + let mut writer = fixture.writer("credit"); writer.write_all(&payload(0)).await.unwrap(); - // This immediate read occurs before yielding to the worker in the - // current-thread runtime. Do not inspect the taken/empty Vec later. - let first = writer.snapshot(); - assert_eq!(first.buffer_len, BATCH); - assert_eq!(first.buffer_capacity, BATCH); arrived_first.await.unwrap(); writer.write_all(&payload(1)).await.unwrap(); - let second = writer.snapshot(); - assert_eq!(second.buffer_len, BATCH); - assert_eq!(second.buffer_capacity, BATCH); - assert_eq!( - second.buffer_ptr, first.buffer_ptr, - "the body backing must be recovered, not copied into a parallel workspace" - ); - arrived_second.await.unwrap(); pending_write(&mut writer).await; pending_flush(&mut writer).await; - assert_eq!(writer.snapshot().accepted, (2 * BATCH) as u64); - assert_eq!(writer.snapshot().committed, 0); release.send(()).unwrap(); + arrived_second.await.unwrap(); writer.flush().await.unwrap(); writer.shutdown().await.unwrap(); assert_eq!(writer.snapshot().committed, (2 * BATCH) as u64); @@ -472,211 +650,110 @@ async fn two_held_post_responses_reuse_one_body_backing_and_bound_the_third_writ } } -#[tokio::test] -async fn consumed_second_response_cannot_cross_a_failed_first_response_hole() { - let node = shared_node("body"); - let (client, _) = node.test_xhttp_clients().unwrap(); - let mut fixture = Fixture::new(client, false, 16, 256 * 1024); - let result = AssertUnwindSafe(timeout(LIMIT, async { - let mut peer = fixture.initialize().await; - let (second, arrived_second) = oneshot::channel(); - let (fail_first, failed_first) = oneshot::channel(); - fixture.spawn(async move { - let mut a = accept(&mut peer, "hole", 0).await; - body(&mut a, 0).await; - let mut b = accept(&mut peer, "hole", 1).await; - body(&mut b, 1).await; - respond(&mut b, 200).await; - second.send(()).unwrap(); - failed_first.await.unwrap(); - respond(&mut a, 500).await; - // A fresh writer on this same live H3 connection is a positive - // barrier: a replayed failed session would not match this request. - let mut control = accept(&mut peer, "control", 0).await; - body(&mut control, 0).await; - respond(&mut control, 200).await; - let _ = peer.accept().await; - }); - let mut writer = fixture.writer("hole"); - writer.write_all(&payload(0)).await.unwrap(); - writer.write_all(&payload(1)).await.unwrap(); - arrived_second.await.unwrap(); - loop { - let seen = writer.snapshot(); - if seen.ready_out_of_order { - assert_eq!(seen.occupied_responses, 2); - assert_eq!(seen.ready_responses, 1); - assert_eq!(seen.committed, 0); - break; - } - tokio::task::yield_now().await; - } - // These are checks after actual response consumption, not a race with - // an unpolled response future. Pending alone would be insufficient. - pending_write(&mut writer).await; - pending_flush(&mut writer).await; - fail_first.send(()).unwrap(); - let failure = writer.flush().await.unwrap_err(); - assert!( - failure.to_string().contains("HTTP status 500"), - "wrong failure: {failure}" - ); - assert_eq!(writer.snapshot().committed, 0); - assert!(writer.write_all(b"no replay").await.is_err()); - let mut control = fixture.writer("control"); - control.write_all(&payload(0)).await.unwrap(); - control.flush().await.unwrap(); - control.shutdown().await.unwrap(); - })) - .catch_unwind() - .await; - fixture.stop().await; - node.shutdown().await; - finish(result); -} - -#[tokio::test] -async fn one_peer_stream_credit_jointly_drives_old_response_and_next_open() { - let node = shared_node("body"); - let (client, _) = node.test_xhttp_clients().unwrap(); - let mut fixture = Fixture::new(client, false, 1, 256 * 1024); - let result = AssertUnwindSafe(timeout(LIMIT, async { - let mut peer = fixture.initialize().await; - let (first, arrived_first) = oneshot::channel(); - let (release, released) = oneshot::channel(); - let (second, arrived_second) = oneshot::channel(); - fixture.spawn(async move { - let mut a = accept(&mut peer, "credit", 0).await; - body(&mut a, 0).await; - first.send(()).unwrap(); - released.await.unwrap(); - respond(&mut a, 200).await; - drop(a); - let mut b = accept(&mut peer, "credit", 1).await; - body(&mut b, 1).await; - second.send(()).unwrap(); - respond(&mut b, 200).await; - let _ = peer.accept().await; - }); - let mut writer = fixture.writer("credit"); - writer.write_all(&payload(0)).await.unwrap(); - arrived_first.await.unwrap(); - writer.write_all(&payload(1)).await.unwrap(); - pending_write(&mut writer).await; - pending_flush(&mut writer).await; - release.send(()).unwrap(); - arrived_second.await.unwrap(); - writer.flush().await.unwrap(); - writer.shutdown().await.unwrap(); - assert_eq!(writer.snapshot().committed, (2 * BATCH) as u64); - })) - .catch_unwind() - .await; - fixture.stop().await; - node.shutdown().await; - finish(result); -} - #[tokio::test] async fn early_rejection_of_a_credit_blocked_body_cancels_and_joins_stop() { - let node = shared_node("body"); - let (client, _) = node.test_xhttp_clients().unwrap(); - let mut fixture = Fixture::new(client, false, 16, 32 * 1024); - let result = AssertUnwindSafe(timeout(LIMIT, async { - let mut peer = fixture.initialize().await; - let (prefix, saw_prefix) = oneshot::channel(); - let (reject, rejected) = oneshot::channel(); - fixture.spawn(async move { - let mut a = accept(&mut peer, "early", 0).await; - let data = a.recv_data().await.unwrap().unwrap(); - let count = data.remaining(); - assert!(count > 0 && count < BATCH); - drop(data); - prefix.send(count).unwrap(); - // No further request reads: the 32 KiB stream credit plus that - // one consumed prefix cannot deliver this full 128 KiB body/FIN. - rejected.await.unwrap(); - respond(&mut a, 500).await; - let _ = peer.accept().await; - drop(a); - }); - let mut writer = fixture.writer("early"); - writer.write_all(&payload(0)).await.unwrap(); - assert!(saw_prefix.await.unwrap() < BATCH); - assert!(writer.snapshot().in_flight); - pending_write(&mut writer).await; - pending_flush(&mut writer).await; - reject.send(()).unwrap(); - let failure = writer.flush().await.unwrap_err(); - assert!( - failure.to_string().contains("HTTP status 500"), - "early status must be consumed while body is blocked: {failure}" - ); - fixture.client.stop().await; - assert!(writer.write_all(b"after Stop").await.is_err()); - })) - .catch_unwind() - .await; - fixture.stop().await; - node.shutdown().await; - finish(result); + for protocol in ["h2mux", "yamux", "smux"] { + let node = shared_node(protocol, "body"); + let (client, _) = node.test_xhttp_clients().unwrap(); + let mut fixture = Fixture::new(client, false, 16, 32 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let mut peer = fixture.initialize().await; + let (prefix, saw_prefix) = oneshot::channel(); + let (reject, rejected) = oneshot::channel(); + fixture.spawn(async move { + let mut a = accept(&mut peer, "early", 0).await; + let data = a.recv_data().await.unwrap().unwrap(); + let count = data.remaining(); + assert!(count > 0 && count < BATCH); + drop(data); + prefix.send(count).unwrap(); + // No further request reads: the 32 KiB stream credit plus that + // one consumed prefix cannot deliver this full 128 KiB body/FIN. + rejected.await.unwrap(); + respond(&mut a, 500).await; + let _ = peer.accept().await; + drop(a); + }); + let mut writer = fixture.writer("early"); + writer.write_all(&payload(0)).await.unwrap(); + assert!(saw_prefix.await.unwrap() < BATCH); + assert!(writer.snapshot().in_flight); + pending_write(&mut writer).await; + pending_flush(&mut writer).await; + reject.send(()).unwrap(); + let failure = writer.flush().await.unwrap_err(); + assert!( + failure.to_string().contains("HTTP status 500"), + "early status must be consumed while body is blocked: {failure}" + ); + fixture.client.stop().await; + assert!(writer.write_all(b"after Stop").await.is_err()); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); + } } #[tokio::test] async fn dropping_a_completed_upload_preserves_its_fin_sibling_and_active_stop() { - let node = shared_node("body"); - let (client, _) = node.test_xhttp_clients().unwrap(); - let mut fixture = Fixture::new(client, false, 16, 256 * 1024); - let result = AssertUnwindSafe(timeout(LIMIT, async { - let mut peer = fixture.initialize().await; - let (first, arrived_first) = oneshot::channel(); - let (check, checked) = oneshot::channel(); - let (fin, fin_checked) = oneshot::channel(); - let (active, arrived_active) = oneshot::channel(); - fixture.spawn(async move { - let mut a = accept(&mut peer, "drop", 0).await; - body(&mut a, 0).await; - first.send(()).unwrap(); - let mut b = accept(&mut peer, "sibling", 0).await; - body(&mut b, 0).await; - checked.await.unwrap(); - assert!( - a.recv_data().await.unwrap().is_none(), - "completed request FIN became a reset/error" - ); - fin.send(()).unwrap(); - respond(&mut b, 200).await; - let mut c = accept(&mut peer, "active", 0).await; - body(&mut c, 0).await; - active.send(()).unwrap(); - // Hold both pending responses until the owner's real Stop. - let _ = peer.accept().await; - drop((a, c)); - }); - let mut dropped = fixture.writer("drop"); - dropped.write_all(&payload(0)).await.unwrap(); - arrived_first.await.unwrap(); - pending_flush(&mut dropped).await; - drop(dropped); - let mut sibling = fixture.writer("sibling"); - sibling.write_all(&payload(0)).await.unwrap(); - check.send(()).unwrap(); - fin_checked.await.unwrap(); - sibling.flush().await.unwrap(); - sibling.shutdown().await.unwrap(); - let mut active = fixture.writer("active"); - active.write_all(&payload(0)).await.unwrap(); - arrived_active.await.unwrap(); - pending_flush(&mut active).await; - fixture.client.stop().await; - assert!(active.flush().await.is_err()); - assert!(active.write_all(b"after Stop").await.is_err()); - })) - .catch_unwind() - .await; - fixture.stop().await; - node.shutdown().await; - finish(result); + for protocol in ["h2mux", "yamux", "smux"] { + let node = shared_node(protocol, "body"); + let (client, _) = node.test_xhttp_clients().unwrap(); + let mut fixture = Fixture::new(client, false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let mut peer = fixture.initialize().await; + let (first, arrived_first) = oneshot::channel(); + let (check, checked) = oneshot::channel(); + let (fin, fin_checked) = oneshot::channel(); + let (active, arrived_active) = oneshot::channel(); + fixture.spawn(async move { + let mut a = accept(&mut peer, "drop", 0).await; + body(&mut a, 0).await; + first.send(()).unwrap(); + let mut b = accept(&mut peer, "sibling", 0).await; + body(&mut b, 0).await; + checked.await.unwrap(); + assert!( + a.recv_data().await.unwrap().is_none(), + "completed request FIN became a reset/error" + ); + fin.send(()).unwrap(); + respond(&mut b, 200).await; + let mut c = accept(&mut peer, "active", 0).await; + body(&mut c, 0).await; + active.send(()).unwrap(); + // Hold both pending responses until the owner's real Stop. + let _ = peer.accept().await; + drop((a, c)); + }); + let mut dropped = fixture.writer("drop"); + dropped.write_all(&payload(0)).await.unwrap(); + arrived_first.await.unwrap(); + pending_flush(&mut dropped).await; + drop(dropped); + let mut sibling = fixture.writer("sibling"); + sibling.write_all(&payload(0)).await.unwrap(); + check.send(()).unwrap(); + fin_checked.await.unwrap(); + sibling.flush().await.unwrap(); + sibling.shutdown().await.unwrap(); + let mut active = fixture.writer("active"); + active.write_all(&payload(0)).await.unwrap(); + arrived_active.await.unwrap(); + pending_flush(&mut active).await; + fixture.client.stop().await; + assert!(active.flush().await.is_err()); + assert!(active.write_all(b"after Stop").await.is_err()); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); + } } async fn serial_post(peer: &mut Peer, placement: &str, sequence: usize) -> PeerStream { @@ -741,16 +818,66 @@ async fn normalized_ineligible_factories_keep_one_unacknowledged_body() { false, "body", ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"yamux","only-tcp":true})), + false, + "body", + ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"yamux","padding":true})), + false, + "body", + ), + ( + Some(serde_json::json!({"enabled":false,"protocol":"yamux","only-tcp":false})), + false, + "body", + ), ( Some(serde_json::json!({"enabled":true,"protocol":"yamux","only-tcp":false})), + true, + "body", + ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"yamux","only-tcp":false})), + false, + "header", + ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"yamux","only-tcp":false})), + false, + "cookie", + ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"smux","only-tcp":true})), + false, + "body", + ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"smux","padding":true})), + false, + "body", + ), + ( + Some(serde_json::json!({"enabled":false,"protocol":"smux","only-tcp":false})), false, "body", ), ( Some(serde_json::json!({"enabled":true,"protocol":"smux","only-tcp":false})), - false, + true, "body", ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"smux","only-tcp":false})), + false, + "header", + ), + ( + Some(serde_json::json!({"enabled":true,"protocol":"smux","only-tcp":false})), + false, + "cookie", + ), ( Some(serde_json::json!({"enabled":false,"protocol":"h2mux","only-tcp":false})), false, @@ -760,8 +887,21 @@ async fn normalized_ineligible_factories_keep_one_unacknowledged_body() { (Some(shared()), false, "header"), (Some(shared()), false, "cookie"), ]; - for (smux, split, placement) in cases { - let node = node(smux, placement, split); + let ordinary = cases + .into_iter() + .map(|(smux, split, placement)| (node(smux, placement, split), placement)); + let encrypted = ["yamux", "smux"].into_iter().map(|protocol| { + ( + node_with_encryption( + Some(serde_json::json!({"enabled":true,"protocol":protocol,"only-tcp":false})), + "body", + false, + true, + ), + "body", + ) + }); + for (node, placement) in ordinary.chain(encrypted) { let (upload, download) = node.test_xhttp_clients().unwrap(); for (client, is_download) in std::iter::once((upload, false)).chain(download.map(|c| (c, true))) @@ -769,6 +909,8 @@ async fn normalized_ineligible_factories_keep_one_unacknowledged_body() { let mut fixture = Fixture::new(client, is_download, 16, 256 * 1024); let result = AssertUnwindSafe(timeout(LIMIT, async { let mut peer = fixture.initialize().await; + #[cfg(feature = "interop-test")] + udp_budget::assert_default_send_retention(&fixture).await; if let SendRequest::H3(sender) = fixture.sender.as_ref().unwrap() { assert!( sender.udp_control.is_none(), @@ -818,6 +960,37 @@ async fn normalized_ineligible_factories_keep_one_unacknowledged_body() { } } +#[cfg(feature = "interop-test")] +#[tokio::test] +async fn qualified_smux_overlap_keeps_native_send64_and_no_udp_raise_control() { + for placement in ["body", "auto"] { + let node = shared_node("smux", placement); + let (client, download) = node.test_xhttp_clients().unwrap(); + assert!(download.is_none()); + let mut fixture = Fixture::new(client, false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let peer = fixture.initialize().await; + assert!(fixture.client.packet_up_response_overlap); + assert!(!fixture.client.shared_packet_up); + assert!(!fixture.client.yamux_packet_up_send_retention); + assert!(!fixture.client.udp_budget_qualified()); + // Actual Quinn send acceptance under the existing held-ACK probe, + // not just comparison with a copied configuration constant. + udp_budget::assert_default_send_retention(&fixture).await; + let SendRequest::H3(sender) = fixture.sender.as_ref().unwrap() else { + panic!("not H3") + }; + assert!(sender.udp_control.is_none()); + drop(peer); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); + } +} + #[cfg(feature = "interop-test")] #[path = "h3_udp_budget_memory_tests.rs"] mod udp_budget; diff --git a/src/transport/xhttp/h3_udp_budget_memory_tests.rs b/src/transport/xhttp/h3_udp_budget_memory_tests.rs index 69a78b2..adb5cc3 100644 --- a/src/transport/xhttp/h3_udp_budget_memory_tests.rs +++ b/src/transport/xhttp/h3_udp_budget_memory_tests.rs @@ -272,6 +272,19 @@ fn native(fixture: &Fixture) -> quinn::Connection { sender.observation.clone() } async fn native_prefix(fixture: &Fixture, native: &quinn::Connection, raised: bool) { + let accepted = if raised { + // Native retained bytes must exceed the previous 192 KiB cap. + (192 * 1024 + 1)..=(256 * 1024) + } else { + 1..=(64 * 1024) + }; + native_prefix_in(fixture, native, accepted).await; +} +async fn native_prefix_in( + fixture: &Fixture, + native: &quinn::Connection, + accepted: std::ops::RangeInclusive, +) { let server = fixture.native_peer.as_ref().unwrap(); let mut warm = native.open_bi().await.unwrap().0; warm.write_all(b"warm").await.unwrap(); @@ -281,16 +294,13 @@ async fn native_prefix(fixture: &Fixture, native: &quinn::Connection, raised: bo assert_eq!(warm.stopped().await.unwrap(), None); fixture.gate.set(true); let (mut send, _) = native.open_bi().await.unwrap(); - let bytes = vec![0xa5; 256 * 1024]; + // Offer more than the candidate cap; the ACK gate must bound acceptance. + let bytes = vec![0xa5; 384 * 1024]; let prefix = send.write(&bytes).await.unwrap(); - if raised { - assert!( - prefix > 160 * 1024 && prefix <= 192 * 1024, - "raised prefix={prefix}" - ); - } else { - assert!(prefix > 0 && prefix <= 64 * 1024, "initial prefix={prefix}"); - } + assert!( + accepted.contains(&prefix), + "native send prefix {prefix} outside {accepted:?}" + ); assert!( std::future::poll_fn(|cx| Poll::Ready(Pin::new(&mut send).poll_write(cx, b"blocked"))) .await @@ -311,11 +321,20 @@ async fn native_prefix(fixture: &Fixture, native: &quinn::Connection, raised: bo assert_eq!(finished, None); assert_eq!(delivered, bytes); } +pub(super) async fn assert_default_send_retention(fixture: &Fixture) { + let SendRequest::H3(sender) = fixture.sender.as_ref().unwrap() else { + panic!("not H3") + }; + assert!(sender.udp_control.is_none()); + native_prefix(fixture, &native(fixture), false).await; +} #[tokio::test] async fn udp_metadata_flush_raises_only_its_live_carrier_after_outer_retirement() { let (mux, client, upstream) = configured(); - let mut a = Fixture::new(client.clone(), false, 32, 256 * 1024); - let mut b = Fixture::new(client.clone(), false, 32, 256 * 1024); + // Peer stream credit exceeds the local cap, so 256 KiB is not a + // peer receive-window artefact. Connection receive credit remains 1 MiB. + let mut a = Fixture::new(client.clone(), false, 32, 512 * 1024); + let mut b = Fixture::new(client.clone(), false, 32, 512 * 1024); let result = AssertUnwindSafe(timeout(LIMIT, async { let peer = a.initialize().await; let service = bridge(&mut a, peer); @@ -467,3 +486,210 @@ async fn proxy_hops_clear_the_carrier_h3_capture_for_tcp_and_datagrams() { assert!(context.h3_udp_capture().is_some()); assert!(capture.take().is_none()); } + +#[tokio::test] +async fn yamux_fixed_send_retention_has_no_adaptive_udp_control_or_raise() { + let node = shared_node("yamux", "body"); + let (client, download) = node.test_xhttp_clients().unwrap(); + assert!(download.is_none()); + assert!(!client.udp_budget_qualified()); + let mut fixture = Fixture::new(client, false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let peer = fixture.initialize().await; + let SendRequest::H3(sender) = fixture.sender.as_ref().unwrap() else { + panic!("not H3") + }; + assert!(sender.udp_control.is_none()); + // The HTTP acceptor is deliberately unpolled during the native probe. + let physical = native(&fixture); + native_prefix_in(&fixture, &physical, (96 * 1024 + 1)..=(128 * 1024)).await; + assert!(fixture.sender.as_ref().is_some_and(|sender| { + matches!(sender, SendRequest::H3(sender) if sender.udp_control.is_none()) + })); + drop(peer); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); +} + +#[tokio::test] +async fn yamux_h3_stream_modes_keep_the_native_64k_send_retention() { + for mode in ["stream-up", "stream-one"] { + let node = overlap_version_mode_node("yamux", "h3", mode); + let (client, _) = node.test_xhttp_clients().unwrap(); + let mut fixture = Fixture::new(client, false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let peer = fixture.initialize().await; + assert_default_send_retention(&fixture).await; + drop(peer); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); + } +} + +#[tokio::test] +async fn response_geometry_alone_keeps_native_send_retention_at_64k() { + let node = node(None, "body", false); + let (mut client, _) = node.test_xhttp_clients().unwrap(); + client.set_packet_up_response_overlap(true); + let mut fixture = Fixture::new(client, false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let peer = fixture.initialize().await; + assert_default_send_retention(&fixture).await; + drop(peer); + })) + .catch_unwind() + .await; + fixture.stop().await; + node.shutdown().await; + finish(result); +} + +#[tokio::test] +async fn fixed_yamux_budget_changes_isolate_live_clone_pools_in_both_directions() { + let node = shared_node("yamux", "body"); + let (client, _) = node.test_xhttp_clients().unwrap(); + let mut a = Fixture::new(client.clone(), false, 16, 256 * 1024); + let mut ordinary = client.clone(); + ordinary.set_yamux_packet_up_send_retention(false); + let mut b = Fixture::new(ordinary.clone(), false, 16, 256 * 1024); + let mut enabled = ordinary.clone(); + enabled.set_yamux_packet_up_send_retention(true); + let mut c = Fixture::new(enabled.clone(), false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let peer_a = a.initialize().await; + let physical_a = native(&a); + native_prefix_in(&a, &physical_a, (96 * 1024 + 1)..=(128 * 1024)).await; + + // A stays live in its active-only pool. The changed clone must dial + // instead of inheriting that existing 128 KiB physical. + let called = AtomicUsize::new(0); + assert!( + ordinary + .acquire(false, || async { + called.fetch_add(1, Ordering::SeqCst); + Err(io::Error::other("ordinary clone must dial")) + }) + .await + .is_err() + ); + assert_eq!(called.load(Ordering::SeqCst), 1); + let peer_b = b.initialize().await; + let physical_b = native(&b); + native_prefix(&b, &physical_b, false).await; + + // The reverse change must not inherit B's live 64 KiB physical either. + let called = AtomicUsize::new(0); + assert!( + enabled + .acquire(false, || async { + called.fetch_add(1, Ordering::SeqCst); + Err(io::Error::other("enabled clone must dial")) + }) + .await + .is_err() + ); + assert_eq!(called.load(Ordering::SeqCst), 1); + let peer_c = c.initialize().await; + let physical_c = native(&c); + native_prefix_in(&c, &physical_c, (96 * 1024 + 1)..=(128 * 1024)).await; + assert_ne!(physical_a.stable_id(), physical_b.stable_id()); + assert_ne!(physical_b.stable_id(), physical_c.stable_id()); + for fixture in [&a, &b, &c] { + assert!(matches!(fixture.sender.as_ref().unwrap(), + SendRequest::H3(sender) if sender.udp_control.is_none())); + } + drop((peer_a, peer_b, peer_c)); + node.shutdown().await; + assert!(physical_a.open_bi().await.is_err()); + assert!(physical_b.open_bi().await.is_err()); + assert!(physical_c.open_bi().await.is_err()); + assert!( + client + .open_transport(tokio::time::Instant::now() + LIMIT, || async { + panic!("stopped original owner dialed") + }) + .await + .is_err() + ); + assert!( + ordinary + .open_transport(tokio::time::Instant::now() + LIMIT, || async { + panic!("stopped ordinary owner dialed") + }) + .await + .is_err() + ); + assert!( + enabled + .open_transport(tokio::time::Instant::now() + LIMIT, || async { + panic!("stopped enabled owner dialed") + }) + .await + .is_err() + ); + })) + .catch_unwind() + .await; + node.shutdown().await; + a.stop().await; + b.stop().await; + c.stop().await; + finish(result); +} + +#[tokio::test] +async fn shared_h2_budget_context_clears_fixed_yamux_retention_and_isolates_its_pool() { + let node = shared_node("yamux", "body"); + let (client, _) = node.test_xhttp_clients().unwrap(); + let mut a = Fixture::new(client.clone(), false, 16, 256 * 1024); + let mut shared = client.clone(); + shared.set_shared_packet_up_transport(true); + // Snapshot after shared(true), before any fixed setter can hide a latent + // flag. Returning to ordinary must build a real 64 KiB physical. + let mut restored = shared.clone(); + restored.set_shared_packet_up_transport(false); + // A fixed-budget request cannot override the independent H2Mux context. + shared.set_yamux_packet_up_send_retention(true); + let mut b = Fixture::new(shared.clone(), false, 16, 256 * 1024); + let mut c = Fixture::new(restored.clone(), false, 16, 256 * 1024); + let result = AssertUnwindSafe(timeout(LIMIT, async { + let peer_a = a.initialize().await; + native_prefix_in(&a, &native(&a), (96 * 1024 + 1)..=(128 * 1024)).await; + let called = AtomicUsize::new(0); + assert!( + shared + .acquire(false, || async { + called.fetch_add(1, Ordering::SeqCst); + Err(io::Error::other("shared context must dial")) + }) + .await + .is_err() + ); + assert_eq!(called.load(Ordering::SeqCst), 1); + let peer_b = b.initialize().await; + let SendRequest::H3(sender) = b.sender.as_ref().unwrap() else { + panic!("not H3") + }; + assert!(!sender.udp_control.as_ref().unwrap().was_raised()); + native_prefix(&b, &native(&b), false).await; + assert!(!sender.udp_control.as_ref().unwrap().was_raised()); + let peer_c = c.initialize().await; + assert_default_send_retention(&c).await; + drop((peer_a, peer_b, peer_c)); + })) + .catch_unwind() + .await; + node.shutdown().await; + a.stop().await; + b.stop().await; + c.stop().await; + finish(result); +} diff --git a/src/tun_runtime.rs b/src/tun_runtime.rs index 546ecc3..7db1f97 100644 --- a/src/tun_runtime.rs +++ b/src/tun_runtime.rs @@ -32,6 +32,7 @@ use crate::{ classify_query, runtime::{DnsQueryPermit, RuntimeDns}, }, + http_processing::diagnostics::{Counter, increment, record_tun_ingress_header}, platform::{TUN_PACKET_BATCH_SIZE, TunIo}, quic_sniffer::QuicSniffer, resources::{ @@ -104,7 +105,7 @@ fn tun_netstack_config(limits: ResourceLimits, fake_icmp_echo: bool) -> NetStack packet_queue: limits.packet_queue_capacity, tcp_accept_queue: limits.event_queue_capacity, tcp_recv_buffer: limits.tcp_buffer_per_direction, - tcp_send_buffer: limits.tcp_buffer_per_direction, + tcp_send_buffer: limits.tun_tcp_send_buffer, fake_icmp_echo, ..NetStackConfig::default() } @@ -233,6 +234,10 @@ impl TunRuntime { fake_icmp_echo = self.fake_icmp_echo, "TUN runtime starting" ); + #[cfg(feature = "http-diagnostics")] + let parts = + NetStack::start_tcp_observed(config, observe_tun_driver).map_err(netstack_to_io)?; + #[cfg(not(feature = "http-diagnostics"))] let parts = NetStack::start_tcp(config).map_err(netstack_to_io)?; let control = parts.control.clone(); let netstack_stats = parts.stats.clone(); @@ -317,6 +322,31 @@ impl TunRuntime { } } +#[cfg(feature = "http-diagnostics")] +fn observe_tun_driver(event: vole_netstack::diagnostics::DriverObservation) { + use crate::http_processing::diagnostics::add_counter; + use vole_netstack::diagnostics::DriverObservation; + match event { + DriverObservation::DrivePass { + tcp_entry_visits, + app_rx_bytes, + app_tx_bytes, + no_data_progress, + } => { + increment(Counter::TunNetstackDriverDrivePasses); + add_counter(Counter::TunNetstackDriverTcpEntryVisits, tcp_entry_visits); + add_counter(Counter::TunNetstackDriverAppRxBytes, app_rx_bytes); + add_counter(Counter::TunNetstackDriverAppTxBytes, app_tx_bytes); + if no_data_progress { + increment(Counter::TunNetstackDriverNoDataProgressPasses); + } + } + DriverObservation::WaitIngress => increment(Counter::TunNetstackDriverWaitIngress), + DriverObservation::WaitNotify => increment(Counter::TunNetstackDriverWaitNotify), + DriverObservation::WaitTimer => increment(Counter::TunNetstackDriverWaitTimer), + } +} + async fn netstack_stats_loop( stats: NetStackStats, cancellation: CancellationToken, @@ -475,12 +505,17 @@ async fn tun_read_inner( let up_bytes = packets .iter() .zip(&outcomes) - .fold(0usize, |bytes, (packet, outcome)| { - if outcome.is_ok() { + .fold(0usize, |bytes, (packet, outcome)| match outcome { + Ok(_) => { + increment(Counter::TunIngressReadOkPackets); + record_tun_ingress_header(packet); bytes.saturating_add(packet.len()) - } else { + } + Err(VoleError::InvalidPacket(_)) => { + increment(Counter::TunIngressReadInvalidPacketOutcomes); bytes } + Err(_) => bytes, }); if up_bytes != 0 { traffic_stats.record_up(up_bytes); @@ -515,6 +550,7 @@ async fn tun_read_inner( // UDP bypasses PacketSink, so retain the same effective MTU check // before creating an association or admitting a DNS query. if packet.len() > mtu { + increment(Counter::TunIngressMtuExceededDrops); tracing::debug!( packet_bytes = packet.len(), mtu, @@ -540,6 +576,7 @@ async fn tun_read_inner( .await { Ok(()) => { + increment(Counter::TunIngressNetstackAcceptedPackets); if !first_ingress_logged { tracing::info!("netstack accepted first TUN packet"); first_ingress_logged = true; @@ -553,10 +590,13 @@ async fn tun_read_inner( | NetStackError::Backpressure), ) => { if matches!(error, NetStackError::Backpressure) { + increment(Counter::TunIngressNetstackBackpressureDrops); udp.context.resource_stats.queue_drop( ResourceQueue::Packet, udp.context.limits.packet_queue_capacity, ); + } else if matches!(error, NetStackError::MtuExceeded { .. }) { + increment(Counter::TunIngressMtuExceededDrops); } tracing::debug!( error_code = ?error, "dropping packet rejected by netstack ingress" @@ -898,19 +938,19 @@ async fn relay_tcp( let (mut inbound, dispatcher) = { let mut prefix = Vec::new(); let mut selected = dispatcher; - if let Some(http) = selected.http_context() - && http.candidate_port(destination_port) - { - match http - .try_intercept(&mut inbound, session.clone(), cancellation.clone()) - .await - { - Ok(crate::http_processing::Intercept::Handled) => return, - Ok(crate::http_processing::Intercept::Transparent { prefix: bytes }) => { - prefix = bytes; - selected = http.dispatcher().clone(); + if let Some(http) = selected.http_context() { + selected = http.dispatcher().clone(); + if http.candidate_port(destination_port) { + match http + .try_intercept(&mut inbound, session.clone(), cancellation.clone()) + .await + { + Ok(crate::http_processing::Intercept::Handled) => return, + Ok(crate::http_processing::Intercept::Transparent { prefix: bytes }) => { + prefix = bytes; + } + Err(_) => return, } - Err(_) => return, } } ( @@ -974,7 +1014,13 @@ async fn relay_tcp( let replayed = tokio::select! { biased; () = cancellation.cancelled() => return, - replayed = timeout(OUTBOUND_SEND_TIMEOUT, outbound.write_all(&prefetched)) => replayed, + replayed = timeout(OUTBOUND_SEND_TIMEOUT, async { + outbound.write_all(&prefetched).await?; + // Buffered protocol writers may accept the whole sniffed + // flight without sending it. The relay has no knowledge of + // that earlier write, so finish it before waiting for a reply. + outbound.flush().await + }) => replayed, }; match replayed { Ok(Ok(())) => {} @@ -1534,6 +1580,8 @@ enum AssociationEvent<'a> { Cancelled, SniffDeadline, ReadySend, + #[cfg(target_os = "macos")] + SendFinished(crate::dispatch::TunSendOutcome), Inbound(Option), Outbound(Result), ResponseCapacity(Result, mpsc::error::SendError<()>>), @@ -1604,11 +1652,10 @@ async fn wait_for_quic_sniff_deadline(deadline: Option) { } } -async fn send_tun_udp_datagram( - transport: &mut dyn DatagramTransport, +async fn prepare_tun_udp_datagram( prepared: PreparedTunUdpDatagram, context: &UdpAssociationTaskContext, -) -> io::Result { +) -> io::Result<(Datagram, Option)> { let PreparedTunUdpDatagram { datagram, mut sniffed_domain, @@ -1634,6 +1681,25 @@ async fn send_tun_udp_datagram( payload: datagram.payload, sniffed_domain, }; + Ok((datagram, flow_id)) +} + +#[cfg(any(not(target_os = "macos"), test))] +async fn send_tun_udp_datagram( + transport: &mut dyn DatagramTransport, + prepared: PreparedTunUdpDatagram, + context: &UdpAssociationTaskContext, +) -> io::Result { + let (datagram, flow_id) = prepare_tun_udp_datagram(prepared, context).await?; + send_prepared_tun_udp_datagram(transport, datagram, flow_id, context).await +} + +async fn send_prepared_tun_udp_datagram( + transport: &mut dyn DatagramTransport, + datagram: Datagram, + flow_id: Option, + context: &UdpAssociationTaskContext, +) -> io::Result { let send_datagram = async { match flow_id { Some(flow_id) => { @@ -1659,6 +1725,69 @@ async fn send_tun_udp_datagram( } } +#[cfg(target_os = "macos")] +struct PendingTunOperation { + send: crate::dispatch::TunPendingSend, + deadline: TokioInstant, +} + +#[cfg(target_os = "macos")] +async fn wait_tun_send( + pending: &mut Option, +) -> crate::dispatch::TunSendOutcome { + use crate::dispatch::TunSendOutcome; + match pending.as_mut() { + Some(pending) => { + match tokio::time::timeout_at(pending.deadline, pending.send.operation.as_mut()).await { + Ok(result) => TunSendOutcome::Completed(result), + Err(_) => TunSendOutcome::TimedOut, + } + } + None => std::future::pending().await, + } +} + +#[cfg(target_os = "macos")] +async fn complete_tun_send( + transport: &mut dyn DatagramTransport, + pending: PendingTunOperation, + outcome: crate::dispatch::TunSendOutcome, +) -> io::Result<()> { + use crate::dispatch::{TunPendingSend, TunSendOutcome}; + let TunPendingSend { + operation, + completion, + } = pending.send; + // The pinned route may close only after IO, including UniSend, is gone. + drop(operation); + let externally_cancelled = matches!(&outcome, TunSendOutcome::Cancelled); + let finish = transport.finish_tun_send(completion, outcome); + tokio::pin!(finish); + // First-poll completion releases each wrapper's single pin before its + // first await, even if the original IO deadline has already elapsed. + if let std::task::Poll::Ready(result) = futures_util::poll!(finish.as_mut()) { + return if externally_cancelled { + Ok(()) + } else { + result.map_err(dispatch_to_io) + }; + } + let deadline = if externally_cancelled { + TokioInstant::now() + UDP_CLOSE_TIMEOUT + } else { + pending.deadline + }; + match tokio::time::timeout_at(deadline, finish).await { + Ok(result) if !externally_cancelled => result.map_err(dispatch_to_io), + Ok(_) => Ok(()), + Err(_) if externally_cancelled => Ok(()), + Err(_) => Err(io::Error::new( + io::ErrorKind::TimedOut, + "TUN UDP outbound send timed out", + )), + } +} + fn append_ready_datagrams( ready: &mut VecDeque, mut datagrams: VecDeque, @@ -1721,8 +1850,14 @@ where }; let mut first_response_logged = false; let mut received_in_burst = 0; + #[cfg(target_os = "macos")] + let mut owned_send: Option = None; + // Preserve ordinary protocol early-error behavior. Only a leased operation + // adds mandatory drop/completion cleanup before this result escapes. + let result: io::Result<()> = async { loop { let sniff_deadline = quic_sniff.next_deadline(); + #[cfg(target_os = "macos")] let event = tokio::select! { biased; () = context.cancellation.cancelled() => AssociationEvent::Cancelled, @@ -1735,6 +1870,21 @@ where permit = context.responses.reserve(), if pending_response.datagram.is_some() => { AssociationEvent::ResponseCapacity(permit) } + outcome = wait_tun_send(&mut owned_send) => AssociationEvent::SendFinished(outcome), + datagram = async { transport.receive().await }, if pending_response.datagram.is_none() => AssociationEvent::Outbound(datagram), + () = std::future::ready(()), if (pending_send.is_some() || !ready.is_empty()) && owned_send.is_none() => AssociationEvent::ReadySend, + datagram = inbound.recv(), if owned_send.is_none() => AssociationEvent::Inbound(datagram), + }; + #[cfg(not(target_os = "macos"))] + let event = tokio::select! { + biased; + () = context.cancellation.cancelled() => AssociationEvent::Cancelled, + () = wait_for_quic_sniff_deadline(sniff_deadline), if sniff_deadline.is_some() => { + AssociationEvent::SniffDeadline + } + permit = context.responses.reserve(), if pending_response.datagram.is_some() => { + AssociationEvent::ResponseCapacity(permit) + } datagram = async { transport.receive().await }, if pending_response.datagram.is_none() => AssociationEvent::Outbound(datagram), () = std::future::ready(()), if pending_send.is_some() || !ready.is_empty() => AssociationEvent::ReadySend, datagram = inbound.recv() => AssociationEvent::Inbound(datagram), @@ -1760,9 +1910,30 @@ where .take() .or_else(|| ready.pop_front()) .expect("ready-send event requires a queued datagram"); - if !send_tun_udp_datagram(transport.as_mut(), prepared, context).await? { - break; + #[cfg(target_os = "macos")] + { + let (datagram, flow_id) = prepare_tun_udp_datagram(prepared, context).await?; + // Original send selects parent cancellation before polling + // transport.send after this asynchronous preparation. + if context.cancellation.is_cancelled() { break; } + let identity = flow_id.as_ref().map(|id| id.routing_identity()); + let deadline = TokioInstant::now() + OUTBOUND_SEND_TIMEOUT; + match transport.try_begin_tun_send(datagram, identity.as_ref().map(|id| id.as_slice())) { + Ok(send) => owned_send = Some(PendingTunOperation { send, deadline }), + Err(datagram) => { + if !send_prepared_tun_udp_datagram(transport.as_mut(), datagram, flow_id, context).await? { + break; + } + } + } } + #[cfg(not(target_os = "macos"))] + if !send_tun_udp_datagram(transport.as_mut(), prepared, context).await? { break; } + } + #[cfg(target_os = "macos")] + AssociationEvent::SendFinished(outcome) => { + let pending = owned_send.take().expect("one pending TUN send"); + complete_tun_send(transport.as_mut(), pending, outcome).await?; } AssociationEvent::Inbound(Some(datagram)) => { let sniff_quic = if let Some(plan) = context @@ -1837,6 +2008,21 @@ where } } } + Ok(()) + }.await; + #[cfg(target_os = "macos")] + if let Some(pending) = owned_send.take() { + // Also covers receive errors, response closure, sniff errors and cancel. + // No operation can outlive the transport or reach close while leased. + let _ = complete_tun_send( + transport.as_mut(), + pending, + crate::dispatch::TunSendOutcome::Cancelled, + ) + .await; + } + // Unsupported early errors retain the original no-extra-close behavior. + result?; match timeout(UDP_CLOSE_TIMEOUT, transport.close()).await { Ok(Ok(())) => {} Ok(Err(error)) => { @@ -1884,5 +2070,12 @@ fn dispatch_to_io(error: DispatchError) -> io::Error { } } +#[cfg(all(feature = "interop-test", unix))] +pub(crate) mod interop; + +#[cfg(all(test, target_os = "macos"))] +#[path = "tun_runtime/tun_send_completion_memory_tests.rs"] +mod tun_send_completion_memory_tests; + #[cfg(all(test, unix))] mod tests; diff --git a/src/tun_runtime/cancel_prepare_memory_tests.rs b/src/tun_runtime/cancel_prepare_memory_tests.rs new file mode 100644 index 0000000..7e7cddc --- /dev/null +++ b/src/tun_runtime/cancel_prepare_memory_tests.rs @@ -0,0 +1,139 @@ +//! Focused cancellation control for the real private TUN association entry. +use super::*; + +#[tokio::test] +async fn cancelled_tun_prepare_never_admits_a_send_after_its_await() { + #[derive(Default)] + struct Counts { + sniff_calls: AtomicUsize, + begins: AtomicUsize, + legacy_sends: AtomicUsize, + closes: AtomicUsize, + entered_prepare: Notify, + release_prepare: Notify, + } + struct GateDispatcher(Arc); + struct GateDatagrams(Arc); + + #[async_trait] + impl Dispatcher for GateDispatcher { + async fn connect_tcp(&self, _: StreamSession) -> Result { + Err(DispatchError::NotAllowed) + } + async fn sniff_plan( + &self, + _: SocketAddr, + _: &Destination, + ) -> Result, DispatchError> { + // Inbound classification is call one. ReadySend preparation is + // call two, and must resume only after parent cancellation. + if self.0.sniff_calls.fetch_add(1, Ordering::AcqRel) == 1 { + self.0.entered_prepare.notify_one(); + self.0.release_prepare.notified().await; + } + Ok(None) + } + async fn open_datagram( + &self, + _: DatagramSession, + ) -> Result, DispatchError> { + Ok(Box::new(GateDatagrams(self.0.clone()))) + } + } + #[async_trait] + impl DatagramTransport for GateDatagrams { + fn supports_shared_destinations(&self) -> bool { + false + } + fn try_begin_tun_send( + &mut self, + _: Datagram, + _: Option<&[u8]>, + ) -> Result { + self.0.begins.fetch_add(1, Ordering::AcqRel); + Ok(crate::dispatch::TunPendingSend::new(Box::pin(async { + Ok(()) + }))) + } + async fn send(&mut self, _: Datagram) -> Result<(), DispatchError> { + self.0.legacy_sends.fetch_add(1, Ordering::AcqRel); + Ok(()) + } + async fn receive(&mut self) -> Result { + std::future::pending().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + self.0.closes.fetch_add(1, Ordering::AcqRel); + Ok(()) + } + } + + let counts = Arc::new(Counts::default()); + let probe = observation::ResourceProbe::default(); + let (entered_prepare, association_joined) = probe + .scope(async { + let source = "192.0.2.10:12000".parse().unwrap(); + let destination = "198.51.100.20:80".parse().unwrap(); + let (input, inbound) = mpsc::channel(1); + input + .try_send(UdpDatagram::new(source, destination, b"x".as_slice())) + .unwrap(); + let (responses, output) = mpsc::channel(1); + let parent = CancellationToken::new(); + let stats = RuntimeResourceStats::new("tun_cancel_prepare_test"); + let activity = stats.begin(ResourceActivity::UdpAssociation); + let context = UdpAssociationTaskContext { + association_id: 1, + source, + responses, + dispatcher: Arc::new(GateDispatcher(counts.clone())), + resource_stats: stats, + association_clock: AssociationClock::realtime(), + last_activity: Arc::new(AtomicU64::new(0)), + tun_mtu: TUN_MTU, + udp_timeout: Duration::from_secs(30), + sniffer: None, + cancellation: parent.child_token(), + }; + let mut task = tokio::spawn(observation::task(run_udp_association( + inbound, activity, context, + ))); + let entered = timeout(Duration::from_secs(1), counts.entered_prepare.notified()) + .await + .is_ok(); + // This ordering is unconditional, including a failed entry witness. + parent.cancel(); + counts.release_prepare.notify_one(); + drop(input); + let joined = match timeout(Duration::from_secs(2), &mut task).await { + Ok(Ok((_, _, result))) => result.is_ok(), + Ok(Err(_)) => false, + Err(_) => { + task.abort(); + let _ = task.await; + false + } + }; + drop(output); + (entered, joined) + }) + .await; + let probe_idle = probe.snapshot().is_idle(); + // No verdict can skip parent cancellation, gate release, or the owner join. + assert!( + entered_prepare && association_joined && probe_idle, + "TUN prepare cancellation fixture did not close" + ); + assert_eq!(counts.sniff_calls.load(Ordering::Acquire), 2); + assert_eq!( + counts.begins.load(Ordering::Acquire), + 0, + "cancelled preparation consumed a TUN send admission" + ); + assert_eq!( + counts.legacy_sends.load(Ordering::Acquire), + 0, + "cancelled preparation reached legacy send" + ); + assert_eq!(counts.closes.load(Ordering::Acquire), 1); +} diff --git a/src/tun_runtime/interop.rs b/src/tun_runtime/interop.rs new file mode 100644 index 0000000..89098ad --- /dev/null +++ b/src/tun_runtime/interop.rs @@ -0,0 +1,88 @@ +//! Interoperability-only access to the unchanged private association entry. +//! The caller polls and closes the real future; no relay or mock transport runs here. +use super::*; +use std::{future::Future, pin::Pin}; + +pub struct InteropTunRoutingRegistry { + registry: Arc, +} + +impl InteropTunRoutingRegistry { + pub fn close(self) -> bool { + let empty = serde_json::to_value(self.registry.snapshot()) + .ok() + .and_then(|value| value["connections"].as_array().map(Vec::is_empty)) + .unwrap_or(false); + self.registry.shutdown(); + empty + } +} + +pub fn interop_tracked_tun_router( + router: crate::routing::RoutingDispatcher, + config: &crate::config::Config, + rules: &crate::routing::RuleSet, +) -> (crate::routing::RoutingDispatcher, InteropTunRoutingRegistry) { + let registry = Arc::new(crate::connections::Registry::default()); + let diagnostics = Arc::new(crate::routing::diagnostics::Diagnostics::new( + config, + rules, + registry.clone(), + )); + ( + router.with_diagnostics(diagnostics), + InteropTunRoutingRegistry { registry }, + ) +} + +pub type InteropTunUdpTask = Pin> + Send>>; + +pub struct InteropTunUdpReplies { + inner: mpsc::Receiver, +} + +impl InteropTunUdpReplies { + pub async fn receive(&mut self) -> Option { + self.inner.recv().await.map(|response| response.datagram) + } +} + +pub fn interop_tun_udp_association( + dispatcher: Arc, + source: SocketAddr, +) -> ( + mpsc::Sender, + InteropTunUdpReplies, + CancellationToken, + InteropTunUdpTask, +) { + let stats = RuntimeResourceStats::new("interop_tun_udp_association"); + let dispatcher = crate::dispatch::observe_sessions_with_stats(dispatcher, stats.clone()); + let activity = stats.begin(ResourceActivity::UdpAssociation); + // A one-entry input exposes consumption through the sender's existing capacity API. + let (input, inbound) = mpsc::channel(1); + let (responses, replies) = mpsc::channel(1); + let cancellation = CancellationToken::new(); + let context = UdpAssociationTaskContext { + association_id: 1, + source, + responses, + dispatcher, + resource_stats: stats, + association_clock: AssociationClock::realtime(), + last_activity: Arc::new(AtomicU64::new(0)), + tun_mtu: 1_500, + udp_timeout: Duration::from_secs(30), + sniffer: None, + cancellation: cancellation.clone(), + }; + let task = Box::pin(observation::task(async move { + run_udp_association(inbound, activity, context).await.2 + })); + ( + input, + InteropTunUdpReplies { inner: replies }, + cancellation, + task, + ) +} diff --git a/src/tun_runtime/tests.rs b/src/tun_runtime/tests.rs index 10a4d03..1dfd132 100644 --- a/src/tun_runtime/tests.rs +++ b/src/tun_runtime/tests.rs @@ -28,6 +28,10 @@ use crate::{ routing::{EmptyGeoMatcher, ProxyDispatchers, RuleSet}, }; +#[cfg(target_os = "macos")] +#[path = "cancel_prepare_memory_tests.rs"] +mod cancel_prepare_memory_tests; + fn test_tun_config() -> TunConfig { TunConfig { mtu: 1500, @@ -1943,15 +1947,59 @@ async fn default_udp_response_queue_absorbs_bounded_bursts_without_blocking_dns( } #[test] -fn tun_netstack_keeps_queue_and_per_flow_bounds_without_a_flow_count_ceiling() { +fn tun_netstack_maps_runtime_queue_and_buffer_limits() { let limits = ResourceLimits::default(); let config = tun_netstack_config(limits, false); + assert_eq!(config.mtu, limits.tun_max_datagram_size); + assert_eq!(config.packet_queue, limits.packet_queue_capacity); assert_eq!(config.tcp_accept_queue, limits.event_queue_capacity); assert_eq!(config.tcp_recv_buffer, limits.tcp_buffer_per_direction); - assert_eq!(config.tcp_send_buffer, limits.tcp_buffer_per_direction); - assert_eq!(config.mtu, 1_500); - assert_eq!(limits.max_datagram_size, 65_535); + assert_eq!(config.tcp_send_buffer, limits.tun_tcp_send_buffer); +} + +#[tokio::test] +async fn tun_tcp_send_budget_preserves_independent_explicit_limits() { + for (recv, send) in [(8194, 4096), (4096, 8194), (32 * 1024, 32 * 1024)] { + let limits = ResourceLimits { + tcp_buffer_per_direction: recv, + tun_tcp_send_buffer: send, + ..ResourceLimits::default() + } + .validate() + .unwrap(); + let config = tun_netstack_config(limits, false); + assert_eq!(config.tcp_recv_buffer, recv); + assert_eq!(config.tcp_send_buffer, send); + let parts = NetStack::start_tcp(config).unwrap(); + parts.control.stop().await; + assert!(parts.control.is_stopped()); + assert_eq!(parts.stats.snapshot().active_tcp, 0); + } +} + +#[test] +fn tun_tcp_send_budget_keeps_invalid_explicit_values_for_netstack_validation() { + for send in [1, 4095, 4097, usize::MAX] { + let limits = ResourceLimits { + tun_tcp_send_buffer: send, + ..ResourceLimits::default() + } + .validate() + .unwrap(); + let config = tun_netstack_config(limits, false); + assert_eq!(config.tcp_recv_buffer, 32 * 1024); + assert_eq!(config.tcp_send_buffer, send); + assert!(matches!( + NetStack::start_tcp(config), + Err(vole_netstack::NetStackError::Config( + vole_netstack::ConfigError::TcpBuffer { + name: "tcp_send_buffer", + value, + } + )) if value == send + )); + } } fn test_association( @@ -2082,6 +2130,7 @@ fn periodic_cleanup_removes_expired_and_closed_but_preserves_active_entries() { #[derive(Default)] struct MockDispatcher { + buffered_tcp: bool, tcp_sessions: Mutex>, udp_sessions: Mutex>, tcp_called: Notify, @@ -2102,7 +2151,11 @@ impl Dispatcher for MockDispatcher { } } }); - Ok(Box::new(client)) + if self.buffered_tcp { + Ok(Box::new(tokio::io::BufWriter::new(client))) + } else { + Ok(Box::new(client)) + } } async fn open_datagram( @@ -2472,13 +2525,20 @@ fn test_runtime_dns(dispatcher: Arc) -> Arc { #[tokio::test] async fn synthetic_fd_with_dns_disabled_dispatches_tcp_and_reuses_udp_association() { + #[cfg(feature = "http-diagnostics")] + let observer_before = crate::http_processing::diagnostics::snapshot(); let (host, peer) = UnixDatagram::pair().unwrap(); host.set_nonblocking(true).unwrap(); peer.set_nonblocking(true).unwrap(); let fd = TunFd::duplicate_mock(host.as_raw_fd()).unwrap(); let tun = TunIo::new_mock(fd, crate::TunFraming::RawIp).unwrap(); let peer = tokio::net::UnixDatagram::from_std(peer).unwrap(); - let dispatcher = Arc::new(MockDispatcher::default()); + // A sniffed request must reach a buffered protocol writer before the + // client sends another byte or closes its write half. + let dispatcher = Arc::new(MockDispatcher { + buffered_tcp: true, + ..MockDispatcher::default() + }); let limits = ResourceLimits { packet_queue_capacity: 8, event_queue_capacity: 4, @@ -2624,6 +2684,30 @@ async fn synthetic_fd_with_dns_disabled_dispatches_tcp_and_reuses_udp_associatio .expect("TUN runtime stop timed out") .unwrap() .unwrap(); + #[cfg(feature = "http-diagnostics")] + { + let after = crate::http_processing::diagnostics::snapshot(); + for (name, minimum) in [ + ("tunNetstackDriverDrivePasses", 1_u64), + ("tunNetstackDriverTcpEntryVisits", 1), + ( + "tunNetstackDriverAppRxBytes", + u64::try_from(request.len()).unwrap(), + ), + ( + "tunNetstackDriverAppTxBytes", + u64::try_from(request.len()).unwrap(), + ), + ("tunNetstackDriverWaitIngress", 1), + ] { + let before = observer_before["counters"][name].as_u64().unwrap(); + let after = after["counters"][name].as_u64().unwrap(); + assert!( + after >= before + minimum, + "real TUN relay observer missing {name}" + ); + } + } } #[tokio::test] diff --git a/src/tun_runtime/tun_send_completion_memory_tests.rs b/src/tun_runtime/tun_send_completion_memory_tests.rs new file mode 100644 index 0000000..b7e7984 --- /dev/null +++ b/src/tun_runtime/tun_send_completion_memory_tests.rs @@ -0,0 +1,118 @@ +use super::*; +use crate::dispatch::{TunPendingSend, TunSendOutcome, TunSendToken}; +use std::{ + pin::Pin, + sync::atomic::AtomicBool, + task::{Context, Poll}, +}; + +struct PendingIo(Arc); +impl std::future::Future for PendingIo { + type Output = Result<(), DispatchError>; + fn poll(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll { + Poll::Pending + } +} +impl Drop for PendingIo { + fn drop(&mut self) { + self.0.store(true, Ordering::Release); + } +} +struct CompletionProbe { + dropped: Arc, + pinned: Arc, + lease: Arc, + park_close: bool, +} +struct CloseLease(Arc); +impl Drop for CloseLease { + fn drop(&mut self) { + self.0.store(false, Ordering::Release); + } +} +#[async_trait::async_trait] +impl DatagramTransport for CompletionProbe { + fn supports_shared_destinations(&self) -> bool { + false + } + async fn send(&mut self, _: Datagram) -> Result<(), DispatchError> { + unreachable!() + } + async fn receive(&mut self) -> Result { + std::future::pending().await + } + async fn close(&mut self) -> Result<(), DispatchError> { + unreachable!() + } + async fn finish_tun_send( + &mut self, + _: TunSendToken, + outcome: TunSendOutcome, + ) -> Result<(), DispatchError> { + assert!( + self.dropped.load(Ordering::Acquire), + "IO must drop before route completion" + ); + assert!( + self.pinned.swap(false, Ordering::AcqRel), + "one completion pin" + ); + let _lease = CloseLease(self.lease.clone()); + if self.park_close { + std::future::pending::<()>().await; + } + outcome.into_result() + } +} + +#[tokio::test(start_paused = true)] +async fn expired_send_deadline_releases_pin_before_pending_close_is_cancelled() { + let dropped = Arc::new(AtomicBool::new(false)); + let pinned = Arc::new(AtomicBool::new(true)); + let lease = Arc::new(AtomicBool::new(true)); + let mut transport = CompletionProbe { + dropped: dropped.clone(), + pinned: pinned.clone(), + lease: lease.clone(), + park_close: true, + }; + let deadline = TokioInstant::now(); + let pending = PendingTunOperation { + send: TunPendingSend::new(Box::pin(PendingIo(dropped.clone()))), + deadline, + }; + let result = complete_tun_send(&mut transport, pending, TunSendOutcome::TimedOut).await; + assert!(matches!(result, Err(error) if error.kind() == io::ErrorKind::TimedOut)); + assert!(dropped.load(Ordering::Acquire)); + assert!(!pinned.load(Ordering::Acquire)); + assert!(!lease.load(Ordering::Acquire)); + assert!(TokioInstant::now() - deadline < Duration::from_millis(10)); +} + +#[tokio::test(start_paused = true)] +async fn parent_cancel_drops_io_and_bounds_pending_completion_without_failure_result() { + let dropped = Arc::new(AtomicBool::new(false)); + let pinned = Arc::new(AtomicBool::new(true)); + let lease = Arc::new(AtomicBool::new(true)); + let mut transport = CompletionProbe { + dropped: dropped.clone(), + pinned: pinned.clone(), + lease: lease.clone(), + park_close: true, + }; + let start = TokioInstant::now(); + let pending = PendingTunOperation { + send: TunPendingSend::new(Box::pin(PendingIo(dropped.clone()))), + deadline: start + OUTBOUND_SEND_TIMEOUT, + }; + assert!( + complete_tun_send(&mut transport, pending, TunSendOutcome::Cancelled) + .await + .is_ok() + ); + assert!(dropped.load(Ordering::Acquire)); + assert!(!pinned.load(Ordering::Acquire)); + assert!(!lease.load(Ordering::Acquire)); + assert!(TokioInstant::now() - start >= UDP_CLOSE_TIMEOUT); + assert!(TokioInstant::now() - start < UDP_CLOSE_TIMEOUT + Duration::from_millis(10)); +} diff --git a/tests/README.md b/tests/README.md index 4f5159a..3c2eacf 100644 --- a/tests/README.md +++ b/tests/README.md @@ -1,287 +1,108 @@ # 测试 -本仓库维护配置、协议编解码、内存I/O、资源所有权和生命周期回归。 -网络互通与压力由独立容器工具管理,结果与结论统一保存在 benchmark 工程。 +Core 在宿主机运行明确选定的配置、编解码、内存 I/O 和所有权回归。协议互通与压力由独立的 benchmark 工程运行,执行环境和证据范围见[验收边界](../docs/acceptance.md)。 ## 本地检查 -按[编译文档](../scripts/README.md)准备原生依赖后执行: +按[编译文档](../scripts/README.md)准备原生依赖。Linux 与 macOS 的全目标检查以编译为限: ```sh cargo fmt --all -- --check cargo clippy --locked --all-features --lib --bins -- -D warnings cargo test --locked --all-features --all-targets --no-run -cargo test --manifest-path crates/vole-netstack/Cargo.toml --all-targets +cargo test --locked --manifest-path crates/vole-netstack/Cargo.toml --all-targets uv run --project scripts --locked python -m unittest discover -s scripts/tests uv run --project scripts --locked ruff check scripts uv run --project scripts --locked ruff format --check scripts ``` -宿主只运行明确的无网络对端回归,全目标测试仅编译。`invoke::tests::`包含监听器用例, -不能整体在宿主执行。CI完整过滤器以[Tests workflow](../.github/workflows/test.yml)为准; -CI使用Debug和继承Release优化的`ci-release`,正式产物使用标准`release`。 -Core Debug、Release 和 Quality 测试使用 Ubuntu 26.04;发布构建的 Linux runner 保持 Ubuntu 24.04。 -Windows的UWP/Wintun feature互斥,应明确选择后端,不使用`--all-features`。 +Windows 编译和测试显式选择 UWP 或 Wintun。CI 的测试范围及构建 profile 由 [Tests workflow](../.github/workflows/test.yml)维护。含真实监听器的整组测试在隔离环境执行。 ## 定向回归 -Unix TUN 适配器与数据面循环:`platform::tun_rs_io::tests::`、`tun_runtime::tests::` 使用 Unix socketpair 和内存 Dispatcher 检查包边界、批量收发、配置 MTU、取消与描述符所有权。Linux 仅在 `cfg(test)` 使用共享描述符适配,真实构造器仍拒绝非 TUN;Apple 保留 tun-rs 的包信息头路径。这些回归不代替真实 TUN 验收。 +按改动选择以下命令。Cargo 过滤器匹配测试名称,核对结果中实际执行的用例数。各组使用合成输入、内存传输或本机临时文件。 -Mieru UDP载体的TCP上传收尾:`outbound::mieru::udp::tests::mieru_udp_upload_`。 -五项纯内存回归使用真实编解码、可靠驱动与有界origin流,覆盖尾包首发成功后丢失、重传后EOF, -以及待ACK时的Stop、取消shutdown future、同载体兄弟、立即Drop与对端Close;不代签真实TUN交付或RSS。 - -关闭后的收包边界:`outbound::mieru::udp::tests::mieru_udp_closed_`,以实际首Close丢失、迟到ACK和origin EOF验证最后SID与同载体兄弟。 -`outbound::mieru::udp::balanced_driver_tests::mieru_udp_empty_sid_ready_invalid_preserves_idle_retirement_cancel_and_first_send_gate` -覆盖首发前不收包、空会话持续无效输入下的原空闲退休及Stop;这些纯内存结果不替代真实TUN验收。 -`outbound::mieru::udp::tests::mieru_udp_first_close_loss_recovers_with_silent_peer_before_origin_eof` -使用真实可靠驱动、codec与有界origin,覆盖首Close丢失且目标无后续DATA/ACK时的正常原站EOF; -保留payload/hash与资源回收检查,不代签自然关闭故障归因或真实TUN压力表现。 -同模块的 `mieru_udp_close_retry_` 使用实际驱动验证无响应时最多两次补发,以及补发等待中的活动Stop与owner回收。 -同模块的 `mieru_udp_timeout_epoch_` 以真实codec验证TX拆批间ACK增长、旧flight超时惩罚归并、 -实际重发再次超时、fast/timeout优先级及未ACK许可回收;不代替真实TUN的丢失恢复和性能验收。 -`outbound::mieru::udp::tests::mieru_udp_saved_rto_` 通过同一物理owner的两类业务与真实codec,验证 -UDP发送时期限、TCP动态期限、失败发送不发布状态、快速重传及整write许可回收。 - -smux 纯内存边界:`transport::smux::`,覆盖就绪 DATA 的单次 poll 预算、未读流与兄弟流、整帧分配预算、极小合法配额、本地关闭释放和远端 DATA→FIN 顺序。 -调度测试隔离 Tokio 的独立 cooperative allowance;这些测试不代替真实 TUN 性能验证。 - -VMess/Trojan gRPC 延迟响应(纯内存 H2 duplex,Trojan 加内存 TLS):启用 -`cli,interop-test` 后运行 `--test grpc_protocol_pool`。覆盖认证提交后跨越原期限的上传、 -迟到状态校验、Trojan 半关闭尾部,以及同一挂起读取的活动 Stop、对端自然退出和资源释放。 -Trojan-only 构建使用 `--no-default-features --features outbound-trojan --lib`;不代替真实 TUN 验证。 - -VLESS 的同类边界使用 `--test vless_transports grpc_committed_vless_request_outlives_delayed_http_response`, -同 target 的 `grpc_unresponsive_peer_keeps_original_setup_deadline` 检查未收到 SETTINGS 时仍受原期限约束; -另以 `--test vless_lifecycle vless_all_handshakes_keep_the_original_deadline_and_join_cancelled_io` -保留未完成建链的原期限;VLESS-only 编译使用 `--no-default-features --features outbound-vless --lib`,不添加 `cli`。 - -客户端凭据与输入(纯内存):`config::tests::client_uuid_`、 -`config::vmess::cipher_compatibility_tests::`、`config::hysteria2::p08_tests::hopping_`。 -实际映射凭据、端口跳跃和各协议数据面由真实 TUN 另验收。 -UDP 配置归一化(纯内存):`config::mihomo_udp_tests::`,覆盖 VLESS `none` 使用 -XUDP 并保留 Vision、既有编码,以及 HY2/TUIC 的固有 UDP 能力和 SOCKS5 显式开启控制。 -仅经 `Config::parse_yaml` 检查公开配置与归一化结果,不初始化运行时,不代替真实 TUN 选路或协议互通。 -WS 查询和头预算:`config::vmess::websocket_query_tests::` 与内存 duplex 的 -`--test stream_foundations websocket_early_data_and_remaining_frames_keep_the_original_byte_order`; -XHTTP 输入和自定义上行方法:`--test xhttp_config`、 -`--test xhttp_requests packet_metadata_and_upload_methods_are_sent_in_each_supported_location`。 -VLESS packetaddr 自主写使用实际 PacketUp Writer 的纯内存 H2 duplex: -`--test vless_transports packetaddr_xhttp_memory::packetaddr_xhttp_keeps_first_flush_and_drives_last_datagram_without_post_ack`。 -覆盖请求头/首 DATA 的 POST 确认,以及最后单帧的独立推进、确认前接收和同步 Stop。 -已建立关联的部分写取消使用库过滤器 -`outbound::vless::datagram::tests::established_packetaddr_partial_write_resumes_by_send_or_receive_without_replay`, -检查越过原建链期限后由 send/receive 恢复同帧、无重放及回复来源。 -这些内存 seam 不代替 H3、真实 TUN、进程 RSS 或压力验收。 - -VLESS 私有 H2 split 活动租约:`--lib outbound::vless::outbound::active_h2_memory_tests::private_split_h2_shares_four_active_leases_and_stops_both_legs -- --exact`,以真实 duplex H2 两腿验证四租约共享、阈值扩容、兄弟关闭、末租约释放和同步 Stop/join;它不是实际 TUN 或 TLS wire 互通验收。 -REALITY 资格使用同模块的 `private_split_h2_reality_qualification_shares_four_active_leases_and_stops_both_legs`; -`private_split_h2_reality_peer_stream_credit_opens_new_download_physicals` 检查低对端信用, -Linux 的 `private_split_h2_reality_control_fallback_and_dialer_stop_do_not_take_cached_sender` 检查独立 TCP-control 与 Dialer/节点 Stop。 -这些纯内存测试从公开 REALITY 配置进入池选择,但测试 peer 不执行 REALITY/TLS 认证;真实 TUN 认证与 RSS 必须单独验证。 - -Gun 增量读取(纯内存):`transport::grpc::streaming_read_memory_tests::`。 -实际H2/有界duplex覆盖已校验前缀在消息尾到达前交付、拆分头与varint、空消息、 -取消恢复、原有合法编码、截断与trailers,以及半关闭尾读和Stop/join;不代表TUN压力结果。 - -private h2mux PacketUp 两阶段写(纯内存): -`outbound::sing_mux::tests::private_packet_up_h2mux_hands_off_tail_and_keeps_strong_flush_fin_stop` -经过真实私有包装器与 duplex H2,覆盖末块自主移交、强 flush、半关闭尾读和活动 Stop/join; -`transport::h2_write::tests::coalesced_writer_bounds_markers_and_never_flushes_unencoded_or_failed_payloads` -检查固定确认登记、未编码兄弟隔离及取消/失败唤醒。另保留既有 datagram 首帧强 flush/部分写取消回归。 -`transport::sing_mux::h2_driver::prequeued_flush_memory_tests::already_queued_large_data_progresses_before_pending_raw_flush_completes` -检查真实 H2 已排队 DATA 在底层强 flush Pending 时继续推进; -`transport::h2_write::productive_repoll_memory_tests::` 检查仅有正写入进度且有存活私有确认所有者时 -才重调度一次,以及普通写、零进度、失败、Drop 和强 flush 确认边界。 -这些测试不代替 XHTTP/H3、真实 TUN、内存或容量验收。 - -共享 H3 PacketUp 有界响应重叠(纯内存):`transport::xhttp::h3_packet_overlap_memory_tests::`, -经过归一化节点和实际 factory/H3 driver,检查单正文回收、两响应槽、乱序确认缺口、低流信用、早错误、FIN/Drop 和同步 Stop。 -`transport::xhttp::packet_up::overlap::lease_memory_tests::` 检查真实 Bytes 最后引用释放的通知、同一 Vec 回收及 closed/Weak 所有权。 -这些检查不代替真实 TUN、RSS、吞吐或平台验收。 - -规则输入与 selector 元数据(纯内存):`config::name_regex::tests::`、 -`config::domain_regex::tests::`、`config::rule_provider::tests::classical_`、 -`routing::tests::in_name_`。覆盖命名/数字捕获编号、IN-NAME 和混合 classical 条件。 - -TFO 纯内存策略与生命周期: -`config::functional::tests::node_tfo_is_explicit_and_does_not_inherit_across_proxy_chain`、 -`config::providers::tests::provider_tfo_override_preserves_false_and_materializes_exact_node_policy`、 -Linux `dialer::server_tcp::tests::` 和 `dialer::fast_open::tests::`。 -`dialer::fast_open::gate::real_tun_private_tfo_gate` 为显式 ignored 容器驱动, -实际 SYN-data、首读/空写/半关闭、源绑定/protect、建链期限与 Stop 须由 Linux 真实 TUN 验证。 -这些内存过滤器不证明内核 Fast Open 或其它平台行为。 - -MPTCP / TCP Brutal 纯内存过滤器:`--lib mptcp`、`config::functional::tests::`、 -`config::sing_mux::tests::`、`transport::sing_mux::brutal::tests::`、 -Linux `dialer::tcp_control::tests::`;池与生命周期另用下方 sing_mux 集成回归。 -sing-mux 懒响应与首业务写入期限:`transport::sing_mux::tests::`,覆盖纯上传期间 -延迟 H2 headers/status、空/未完成写入保留原期限,以及迟到状态校验与半关闭。 -双子流、出口约束、TCP 回退、TFO、模块及真实参数/发送侧生效、对端协商与 Stop -须在隔离 Linux 真实 TUN 中另验;1 / 3 Gbps 压力及平台、真机结果分别记录。 - -TUN 网络计划(纯内存,不查询宿主路由或创建接口):`config::tun_network::tests::`、 -`platform::linux_network::plan::tests::`、`platform::linux_network::tests::`; -Linux 目标的报文编码:`platform::linux_network::netlink::tests::`。 -ICMP 配置的纯内存过滤器:`config::tests::tun_icmp_options_`;Linux 覆盖默认/零值、 -实际秒值、禁用与现有重连门禁,以及负值/时钟范围/整数溢出拒绝;其他平台验证未知字段拒绝。 -Linux Echo 所有权用 `tun_runtime::echo::tests::`,netstack 编解码用 `echo::tests::`; -不打开物理 ping socket,不代替实际 TUN、物理源、校验和、权限与 Stop 验证。 -被动 TCP 的 PMTU 与兄弟流:netstack 集成过滤器 -`passive_tun_pmtu_resegments_only_live_sent_tcp_and_preserves_siblings`。 - -Linux Unix Controller 的配置与共享鉴权(不绑定 socket): -`config::controller::tests::controller_unix_`、 -`controller::tests::local_context_shares_limits_and_bypasses_only_local_rest_and_websocket_auth`、 -`invoke::foreground::overrides::tests::unix_override_`、 -二进制 `cli::tests::unix_controller_flag_only_transports_the_explicit_text_value`。 -实际文件权限、绑定冲突、对象替换、drop/Stop 清理在隔离 Linux 真实 TUN 夹具验收。 -Linux socket 创建权限、路径替换与严格 umask 的内核回归使用 `controller::unix::tests:: -- --ignored --test-threads=1`, -仅在隔离 Linux 容器运行;它们检查实际 Unix socket 与本地 IPC,不代替真实 TUN 或完整 Controller 业务验收。 -管理 mark 另选 `config::controller::tests::controller_mark_`、 -`invoke::foreground::overrides::tests::mark_override_` 和二进制 -`cli::tests::controller_mark_flag_`;实际管理回复包 mark 在同一 Linux 夹具核对。 - -Controller 推送(纯内存 duplex,无网络监听):`controller::websocket::tests::`; -安全传输/CORS:`controller::secure_tests::`;DNS 展示:`controller::dns::tests::`; -实例完整日志/动态级别过滤:`logging::tests::`。 -组固定清除:`routing::proxy_group::tests::automatic_fixed_clear_uses_existing_health_without_probe`。 -这些过滤器不代替真实 TUN 计数与 Stop 验证。 -临时规则控制另选 `routing::rule_disable::tests::`、`controller::rules::tests::`、 -`controller::tests::small_json_body_`、 -`routing::program::tests::disabled_main_rules_skip_subprograms_and_keep_the_decision_snapshot`、 -`routing::diagnostics::tests::rule_switch_view_shares_only_small_state_with_the_program` 和 -`runtime::providers::tests::file_refresh_publishes_valid_members_and_preserves_old_sessions`。 - -规则重匹配的配置与失败关闭(纯内存):`config::functional::tests::rematch_`、 -`config::measure::tests::measurement_rejects_routing_only_rematch_nodes`、 -`routing::tests::rematch_name_predicate_is_trimmed_nonempty_and_case_sensitive`、 -`outbound::control::tests::`。 -运行时消费者与续跑另选 `routing::program::tests::rematch_`、`routing::rematch::tests::`、 -`routing::dispatcher::tests::rematch_`、`dns::runtime::tests::rematch_`;这些用例只使用内存 -Dispatcher 和合成端点,不建立监听器或发送网络报文,不代替真实 TUN 组切换验收。 - -功能出站(纯内存):`config::functional::tests::`、`outbound::dns::tests::`、 -`outbound::reject::tests::`;直连解析角色接线: -`dns::runtime::tests::runtime_dns_separates_bootstrap_proxy_direct_and_hosts`。 - -进程规则与原始元信息(纯内存,无系统查询):`config::process::tests::`、 -`process::tests::`、`process::linux::tests::`(Linux)、`process::macos::tests::`(macOS)、 -`routing::program::tests::process_cursor_is_lazy_once_and_keeps_dns_and_subrule_progress`、 -`routing::program::tests::classical_process_provider_resumes_without_selector_side_effects`、 -`dialer::tests::process_inspection_small_concurrency_preserves_identity_and_joins_stop`。 -共享 socket 初始化槽占满的身份查询截止:`dialer::tests::process_inspection_shared_socket_capacity_has_its_own_deadline`。 - -Linux 原生 socket 初始化的许可、取消与 Stop(纯内存): -`dialer::native_init_memory_tests::typed_admission_bounds_cancelled_waiters_and_waits_for_stop`。 -`dialer::native_init_fd_tests::` 默认忽略,包含真实 socket 创建与 bind;仅在隔离 Linux -容器内,借用真实 raw-IP TUN fd 后显式运行。它验证初始化调度、选项、回调与 fd 释放, -不代表 TUN 业务或压力通过;后者使用普通 CLI 的独立真实 TUN 验证。 - -对受影响范围选择过滤器,不逐次重跑整张表。下列库测试使用: +### 配置、规则和生命周期 ```sh -cargo test --locked --no-default-features --features cli,interop-test --lib <过滤器> +cargo test --locked --features cli,interop-test --lib config::tests:: +cargo test --locked --lib geodata::tests:: +cargo test --locked --features cli --lib routing::proxy_group::tests:: +cargo test --locked --features cli --lib dns::runtime::tests::stale_refresh_ +cargo test --locked --features cli --lib runtime::providers::apply::http_tests:: +cargo test --locked --features cli --lib resource::http_control::tests:: +cargo test --locked --features cli --lib invoke::foreground::tests:: +cargo test --locked --features cli --lib invoke::tests::envelope_and_payload_are_strict -- --exact +cargo test --locked --features cli --bin vole cli::tests:: ``` -| 范围 | 过滤器 | 覆盖重点 | -| --- | --- | --- | -| 配置 | `config::tests::` | YAML准入、图、字段单位与边界 | -| 物理出口 | `config::egress::tests::`、`config::dns::upstream_options_tests::`、`platform::linux_network::native::tests::`、`dialer::tests::egress_clones_keep_the_protection_and_stop_owner` | 全局/节点继承、Provider整数覆盖、DNS名称优先与池身份、auto-route标记共存和共同Stop owner | -| GeoData | `geodata::tests::` | 合成DAT/MMDB、selector、更新发布和取消 | -| 资源与Provider | `config::rule_provider::`、`runtime::providers::tests::`、`resource::cache::tests::`、`resource::provider_input::tests::`、`resource::http::tests::` | 域名紧凑索引、MRS、URI/Base64/AGE候选、流式gzip与认证隔离、失败保留与旧代资源 | -| 策略组 | `routing::proxy_group::tests::`、`routing::balance::tests::` | 选择、容差、恢复和负载均衡 | -| DNS | `dns::cache::tests::`、`dns::runtime::tests::stale_refresh_`、`dns::runtime::tests::dns_fallback_`、`dns::runtime::tests::resolve_ipv6_` | 缓存、过期答复/后台预算/退避/epoch/Stop、双栈、竞速和取消 | -| 入口嗅探 | `tcp_sniffer::tests::`、`tcp_sniffer::http2::tests::`、`udp_sniffing::tests::`、`tun_runtime::tests::quic_` | HTTP1/HTTP2目标、HPACK与完整前缀回放;共享QUIC域名键、ECH、预算与重组 | -| QUIC与H3 | `transport::quic::`、`transport::quinn_h3::tests::`、`transport::quiche_h3::tests::`、`dns_quic_` | 官方窗口、真实内存QUIC、DATA读取背压、请求取消、兄弟请求及Stop | -| XHTTP与XUDP | `transport::xhttp::`、`transport::h2_write::tests::`、`xudp::tests::` | 正文缓冲共享、标量部分写入、flush确认、计时与Stop | -| TLS与ECH | `security::context::tests::`、`security::ech::tests::`、`dns::runtime::ech_tests::` | 证书与身份、内存TLS、动态ECH来源 | -| TrustTunnel/Mieru/MASQUE | `trusttunnel`、`mieru`、`masque_` | 真实编解码、信用/背压、复用、单流关闭及同步Stop | -| 有界队列与内存策略 | `routing::datagram_ready::tests::`、`managed_udp_connections_`、`allocator_relief`、`platform::process_memory::tests::` | 就绪轮询、排空、取消和单次回收 | -| UDP 共享与隔离 | `managed_udp_connections_`、`fake_ip_routing_preserves_tcp_names_and_distinct_udp_reply_addresses`、`quic_override_resolves_new_domain_and_restores_udp_response_target` | 同源多目标、固定目标、逐目标关闭与旧回复隔离,支持共享的底层仍保留 Fake-IP/嗅探还原隔离 | -| TUN 响应背压 | `tun_runtime::tests::backpressured_udp_response_handoff` | 满队列下每源至多暂持一包、双向推进及取消 | -| UoT | `outbound::uot::tests::` | 半帧取消后继续、v2首部、原期限、单槽响应与Stop | -| VMess 响应边界 | `outbound::vmess::header::delayed_response_memory_tests::`、`outbound::vmess::stream::tests::`、`outbound::vmess::outbound::polled_datagram_memory_tests::`、`--test vmess_lifecycle` | 官方延迟响应向量、HTTP迟到响应与节点取消、提交前期限、响应认证、收发计数回绕、加密 packetaddr 多目标帧与回包来源、跨回绕连续交付、认证错误关闭、逐字节轮询、读写交错取消与关闭 | -| SS2022 | `outbound::shadowsocks::datagram::tests::` | 官方内存对端、三种 cipher、空 UDP/EIH、认证后 cipher 准入、取消与轮换 ID、重放边界 | -| Trojan UDP | `routing::dispatcher::tests::managed_trojan_udp_`、`--test trojan` | 真实内存帧、同源多目标共享、来源及关闭后旧回复隔离、取消与流释放 | -| TUIC UDP | `outbound::tuic::wire::tests::`、`outbound::tuic::datagram::tests::` | 按声明长度交付、分片满表下新包前进、资源界限和来源隔离 | -| SOCKS5 UDP | `outbound::socks5::tests::` | 真实内存握手与帧、同源多目标复用、异源隔离、关闭重建后旧回复隔离、relay 来源和嵌套预算 | -| HTTP 编译与执行 | `http_processing::` | 严格规则与 provider、URL/头/正文、压缩与 JSON Patch、选择性 TLS、H1/H2 和有界回退 | -| HTTP Invoke | `invoke::http::`、`resource::http_control::tests::` | 有界私密输入、离线演算、来源未准备、下载 dispatcher 接线、单一准入、取消与 Stop 收尾 | -| HTTP 在线配置 | `runtime::providers::apply::http_tests::` | 活动快照继承、变更要求重连、旧候选保留 | -| CLI前台 | `invoke::foreground::tests::`、`invoke::foreground::input::tests::` | 文件/stdin、原生路径、显式 HTTP 文件、CA 读取边界、信号取消及清理 | +覆盖配置准入、GeoData、选择与缓存、HTTP 在线候选、资源回收和 Invoke 边界。全量 `invoke::tests::` 含监听用例,宿主执行应使用明确的过滤器。集成范围见[配置与资源](../docs/http-processing.md#配置与资源)及 [Invoke API](../docs/invoke-api.md)。 -独立集成回归按目标运行,例如: +### 协议与传输 ```sh -cargo test --locked --no-default-features --features cli,interop-test --test tuic_memory -cargo test --locked --no-default-features --features cli,interop-test --test grpc_pool --test grpc_protocol_pool -cargo test --locked --no-default-features --features cli,interop-test --test sing_mux -cargo test --locked --no-default-features --features cli,interop-test --test shadowsocks_backpressure --test shadowsocks_uot -cargo test --locked --no-default-features --features cli --bin vole cli::tests:: +cargo test --locked --features cli,interop-test --test tuic_memory +cargo test --locked --features cli,interop-test --test grpc_pool --test grpc_protocol_pool +cargo test --locked --features cli,interop-test --test sing_mux +cargo test --locked --features cli,interop-test --test shadowsocks_backpressure --test shadowsocks_uot +cargo test --locked --features cli,interop-test --lib outbound::vless::encryption::records::tests:: +cargo test --locked --features cli,interop-test --lib transport::quiche_h3::tests:: +cargo test --locked --features cli,interop-test --lib transport::h2_write::tests:: +cargo test --locked --features cli,interop-test --lib transport::smux::tests:: cargo test --locked -p vole-blake3-raw --test derive ``` -内存QUIC/H3对端通过受控DatagramTransport交换真实包,不绑定宿主监听器。 -`transport::quiche_h3::native_ready_batch_memory_tests::` 验证真实wire帧的共享排空额度、已轮询FIN/RESET、兄弟流和可靠body前缀;不代替完整driver与TUN验收。 -netstack的`active_tcp_shutdown_drains_accepted_tail_before_fin_without_prior_acks`与`active_tcp_drop_drains_accepted_tail_before_fin_without_prior_acks`使用既有缓冲和真实ACK,验证未确认写入的前缀、FIN排序及最终释放。 -`stack::tests::failed_fast_retransmit_survives_another_socket_filling_tx`使用两个真实内存TCP socket与重复ACK, -验证兄弟socket占满输出后,失败的快速重传在容量恢复时仍可立即重试;不启动网络对端或TUN。 -SS2022 的严格官方 TCP codec 回归可单独选择 `official_tcp_codecs_all_ciphers_` 和 -`tcp_response_header_time_salt_auth_and_fragmentation_follow_official_codec`;不要在宿主整体运行 -`outbound::shadowsocks::tests::`,其中还包含监听器用例。 -Mieru回归保留TCP/UDP分池、慢读背压、单槽交接、终态传播、接收分配复用和未读响应下的Stop。 -`outbound::mieru::tcp::udp_send_credit_memory_tests::` 用实际Client::create与有生命周期计数的 -内存DatagramTransport验证默认LOW UDP Associate载体共享96 KiB发送信用;非默认预算、 -其他业务/模式/载体不变,并组接两个真实RawStream验证共享信用、原FIFO2及取消/Stop回收。 -两笔32 KiB写入后仍有32 KiB信用;第三笔写被原FIFO2阻塞,不冒充96 KiB已耗尽。 -`outbound::mieru::udp::tests::mieru_udp_send_credit96_two_sids_keep_fragment_leases_until_their_acks` -通过原可靠分片与真实codec输出验证部分/重复ACK、first-send与独立SID许可退休,原TX8不变。 -这些用例不创建socket、DNS、监听器或网络对端,不证明真实TUN性能或RSS。 +内存对端可验证实际编解码、信用和背压、取消、半关闭与 owner 退出。各协议在真实 TUN 的数据路径、配置组合和容量由 benchmark 分别验证。平台及协议功能见 [出站契约](../docs/outbounds.md)。 -`outbound::mieru::tcp::udp_admission_memory_tests::` 使用原命令通道、完成回执和字节许可, -验证保守四写 UDP 准入、第五笔发送屏障、就绪错误、空写、部分记录取消和 NoWait 收尾;TCP 写入保留原等待边界。 -`outbound::mieru::udp::tests::mieru_udp_admission_depth4_` 另通过实际编解码与可靠驱动,验证 FIFO 分片、累计ACK许可释放和延迟Close拒绝。 -`outbound::mieru::tcp::udp_pool_memory_tests::` 使用真实池预留、RawStream、原有界命令通道与字节许可, -覆盖繁忙TCP载体与UDP业务隔离、UDP同业务活动复用、许可未退休时背压及Stop释放;不启动物理驱动。 -同模块的 `least_load_` 检查真实State与Reservation对两载体复用选择的影响,保留随机tie起点、 -原新建桶及非LOW/非UDP载体行为;不测量网络负载或RSS。 -新增多目标真实 codec 回归使用 `outbound::mieru::packet_routing_tests::`、 -`outbound::trusttunnel::packet::tests::`、`outbound::vmess::header::datagram_memory_tests::`、 -`wireguard_memory_shared_udp_targets_cancel_and_close_independently` 与 -`masque_ip_memory_shared_udp_leases_cancel_and_close_independently`。 -HY2 透明混淆/pacer 传递使用 -`salamander_memory_and_pacer_preserve_address_sharing_owned_send_and_close`。 -它们覆盖逐包地址、取消与独立关闭,不以能力布尔断言替代真实帧和所有权验证。 -GeoData、AGE、Provider和缓存测试使用合成输入、公开固定向量、内存流及临时文件。 -fake-IP 热更新使用 `runtime::tests::live_dns_`,经实际运行时组装检查 DNS 停用/重开、 -A/AAAA 内存 wire,以及临时 redb 的映射、游标加载和持久 owner 复用,不创建网络 socket。 -这些局部预算与行为检查不证明进程RSS、网络吞吐或真机内存达标。 -命名指纹准入使用 `config::fingerprint_tests::`;标准 H2 SETTINGS/ACK 与 ALPS 可选性使用 -`selected_profiles_use_standard_h2_settings_when_the_server_supports_alps`(内存 TLS/H2)。 -REALITY 允许经典/混合协商的配置与两腿真实 share 使用 -`--test reality_config --test security_capabilities`(无网络 IO)。 +### TUN 与内存 -协议输入见[protocols](protocols/README.md),ClientHello输入见[fingerprints](fingerprints/README.md)。 -脚本回归验证产物布局、后端/ABI选择和归档;真实编译与原生加载分别验证。 +```sh +cargo test --locked --features cli --lib tun_runtime::tests:: +cargo test --locked --features cli --lib platform::tun_rs_io::tests:: +cargo test --locked --manifest-path crates/vole-netstack/Cargo.toml mapped_rx_ +``` + +前两项在 Unix 验证内存 Dispatcher 或 socketpair 的包边界、描述符所有权与取消。接收映射回归检查容量、缓存和 Stop。真实 TUN fd、设备路径和 `phys_footprint` 使用对应平台的实际证据。[TUN 平台层](../docs/tun-platform.md) + +## HTTP 处理与 Invoke + +```sh +cargo test --locked --features invoke --lib http_processing::config::document::selector_sharing_tests:: +cargo test --locked --features invoke --lib http_processing::script_config::tests:: +cargo test --locked --features invoke --lib http_processing::script_message::tests:: +cargo test --locked --features invoke --lib http_processing::tests::ingress_memory_tests:: +cargo test --locked --features invoke --lib http_processing::h2_frame_validation:: +cargo test --locked --features invoke --lib shared_collector +cargo test --locked --features invoke --lib outbound::connector::http_reuse_memory_tests:: +cargo test --locked --features invoke --lib invoke::http::tests:: +cargo test --locked --features invoke,http-diagnostics --lib invoke::tests::http_diagnostics_ +``` + +该组覆盖规则与脚本静态校验、共享入口与原始 URL、内存 H2 帧、正文的收集和回放、静态复用资格、私密输入与只读诊断。macOS 的真实脚本后端测试串行运行,避免独立用例争用进程内的单个执行许可: + +```sh +cargo test --locked --features invoke --lib http_processing::tests::script_h1_tests:: -- --test-threads=1 +cargo test --locked --features invoke --lib http_processing::scripts::tests:: -- --test-threads=1 +cargo test --locked --features invoke --lib platform::apple_runtime_qos::tests:: +``` + +这些 Apple 用例验证本进程的事务、JSC 和线程请求等级。HTTPS 客户端信任、物理设备包 I/O 与性能单独运行。[HTTP 处理](../docs/http-processing.md) · [诊断 Invoke](../docs/invoke-api.md#方法) ## Windows原生检查 -名称选择只使用JSON和未注册的内存profile对象,不创建系统VPN或启动连接: +内存 profile 的名称选择测试使用 Windows UWP feature: ```sh cargo test --locked --no-default-features --features ffi,windows-uwp --lib windows::host::tests:: ``` -构建UWP DLL后,在同架构Windows/Python上执行C ABI与COM所有权检查: +构建 UWP DLL 后,在同架构 Windows/Python 上检查 C ABI 与 COM 所有权: ```sh python scripts/check_windows_com.py --dll dist/windows/arm64/uwp/vole.dll ``` -x64使用`dist/windows/x64/uwp/vole.dll`。四个独立子进程覆盖线程初始化、MTA所有权、 -线程切换、STA拒绝和响应释放;仅查询未打包环境,不访问VPN或网络。 -通过不代表包内、Wintun或设备验证。 +x64 产物使用 `dist/windows/x64/uwp/vole.dll`。设备 VPN、包内调用和 Wintun 的验证范围见 [Windows VPN](../docs/windows-vpn.md)。 ## 网络与压力 @@ -291,126 +112,4 @@ container-benchmark stress --source vole=/path/to/Vole container-benchmark compare --source vole=/path/to/Vole ``` -所有网络业务经真实TUN,Controller仅作管理入口;服务端与原站遵守[容器隔离](../docs/testing-isolation.md)。 -`interop --list`可离线列举当前用例。测试工具维护负载、对端和计量,Vole不依赖其checkout编译。 -互通、压力、平台编译、原生调用与真机验证的结果分别记录,见[验收边界](../docs/acceptance.md)。 - - -在线配置的纯内存定向回归:`resource::config_apply::tests::`、`config::live_update::tests::`、`controller::configs::tests::`、`runtime::providers::apply::tests::`、`configuration_candidate_reads_bundle_without_persisting_body_or_metadata`、`configuration_publication_stops_late_old_tree_hint_refill`。覆盖单候选许可、异步/外部线程结果交付、取消后持许可至收尾、严格 API 字段、启动资源拒绝、坏候选保旧图、新 provider 模板延续、候选不写活动资源,以及退休 DNS 树不能回填活动提示。真实 TUN 见证由 benchmark 夹具执行,内存回归不代替平台或业务互通。 - -共享流式安全身份的纯内存检查(不启动宿主监听器): - -```shell -cargo test --locked --lib config::security::tests:: -cargo test --locked --lib security::client_identity_tests:: -``` - -配置检查覆盖具名协议的安全模式、传输限制、XHTTP 两腿继承和 cover mTLS 文件预算; -内存 IO 检查共享连接器握手取消和每次握手的独立状态。真实对端互通另行验收。 - - -SS2022 流式插件的纯内存过滤器:`config::shadowsocks_plugin::tests::`、 -`transport::ss_framed::tests::`、`transport::smux::`。 -它们使用内存流,不启动网络对端;真实TUN互通与压力仍由外部夹具单独验收。 - -HY2 共享握手的纯内存所有权/期限/同步 Stop:`outbound::hysteria2::outbound::shared_handshake_memory_tests::`。 - -文件 mTLS 身份的纯内存 TLS/临时文件回归: -`security::tls::tests::identity_rotation_memory_tests::`(启用 `outbound-http`;命名后端再启用 `tls-fingerprint`)、 -`security::identity::tests::` 与 `config::identity_files::tests::`。 -覆盖连续换代/旧连接与票据隔离、坏文件保留和读取失败恢复、来源独立、取消/Stop、输入预算及原生材料按需分配; -不创建监听器,实际 TUN/QUIC 轮换仍由容器夹具验收。 - -HY2 Gecko/Realm 的配置和内存wire回归按 `gecko_`、`realm_` 中列出的memory-only名称定向执行; -TUIC ClientHello 使用 `tuic_disable_sni_changes_real_quic_hello_without_changing_verification_policy`。 -不得将包含网络peer的整个outbound模块直接作为宿主测试执行。 - -## HTTP 处理与 Invoke - -`http_processing::` 使用合成规则、临时文件、内存 dispatcher 和 duplex,不创建宿主监听器。 -规则入口采用 `http-ports`、`mitm`、`rewrite-providers`、`rewrite` 四个顶层字段, -覆盖严格类型与数值、URL 捕获与替换、请求/响应头、文本与 JSON Patch、压缩、正文预算及整阶段回退。 -provider 回归覆盖启用引用的有序展开、关闭引用零 I/O、来源身份、实际 payload 快照、 -失败保留、缓存原子发布与取消。规则与私密 CA 的完整合同见 [HTTP 处理](../docs/http-processing.md)。 - -H1/H2 内存对端覆盖共享 TUN/mixed/CONNECT 适配、预读、最终目标单次选路、 -原始 URL 选择、跨 origin 凭据隔离、Expect 早响应、流式背压、半关闭、截断拒绝与取消。 -选择性 TLS 同时检查 CA/私钥匹配、叶证书 AKI、证书缓存计费与逐 authority 授权。 -未命中正文规则时不收集完整正文;命中后只在有界工作区完成处理,失败恢复原始阶段内容。 - -`invoke::http::` 检查私密输入在 JSON Value 分配前的准入与 `testHttp` 离线演算。 -离线演算不下载、不读 provider、不生成证书;没有实际来源时报告未准备, -没有方向样本时仅报告规则被选中,不声称正文已验证。重写总开关关闭仍可演算启用规则, -真实 HTTPS 授权与 CA 条件单独判断。 - -`resource::http_control::tests::` 检查指定 dispatcher 的传递、共享配置许可、 -Store 争用及取消后等待下载收尾;`invoke::http::` 同时检查 idle refresh 与实例创建互斥。 -`runtime::providers::apply::http_tests::` 检查普通路由更新保留活动 HTTP 快照, -HTTP 内容或来源上下文变更要求显式重连。失败恢复的策略组选择另选 -`recovery_snapshot_keeps_current_group_member_without_selection_persistence`。 - -显式配置传递另选 `main_config_and_provider_rebuild_preserve_the_addendum_until_explicit_clear`、 -`update_http_addendum_preserves_optional_clear_and_its_separate_byte_limit` 和二进制 -`cli::tests::http_addendum_option_only_transports_an_explicit_native_path`。 -`resource::paths::tests::` 与 -`resource::cache::tests::authorized_provider_roots_read_file_sources_and_write_only_http_caches` -检查原生授权根、符号链接边界、file 读取与 HTTP 缓存写入分离;候选回归同时检查授权上下文继承。 -`resource::cache::tests::provider_metadata_requires_bounded_regular_files` 检查 sidecar 大小与 FIFO 拒绝,坏 metadata 不阻止有效正文读取。 -`invoke::foreground::overrides::tests::` 检查具体 Controller 覆盖、空值保留及沿用地址解析器; -`invoke::foreground::input::tests::` 检查 Base64 来源优先、标准 padding、认证 AGE 固定向量、 -输入预算、取消、单份有效输入复用与主文件重读; -`runtime::providers::apply::http_tests::routing_updates_keep_active_http_and_changed_http_requires_reconnect` -同时检查 foreground 内部模板输入共用候选工作器、坏候选保留与启动资源变化拒绝。`invoke::tests::owned_invoke_uses_the_shared_strict_and_runtime_thread_boundaries` -检查 CLI 的 owned 请求与借用请求共用严格准入和重入边界。 -`invoke::foreground::tests::` 检查显式文件与路径、校验不初始化、不自动加载 HTTP 文件、 -MITM 关闭不读 CA、无 HTTP 配置的 CA 参数提前拒绝,以及启动期信号取消后 join 清理。 -Windows 平台另编译 `snapshot_identity_and_readback_include_the_http_addendum`, -`snapshot_preserves_valid_http_content_expanded_beyond_one_mibibyte` 和 -`snapshot_json_budget_counts_actual_escaping_before_allocation`,检查规则实际内容、 -独立展开预算、JSON 转义计数与私密材料的会话快照边界。 -无默认特性的纯内存回归选择 -`http_documents_without_adapter_are_rejected_before_resource_preparation`; -`ca_identity_is_public_der_and_does_not_require_the_http_adapter` 检查公开证书身份不依赖 HTTP 适配器, -启用 HTTP 后另选 `ca_identity_matches_runtime_authority_without_weakening_key_validation` 检查运行期密钥校验。 - -HTTP/1 早响应与空正文 Upgrade 的定向内存回归:`inbound::http::server::early_final_memory_tests::`;不运行包含宿主 socket 的整个入站测试模块。 -上传完成后的响应等待、静默上限与首字节后绝对读头期限:`inbound::http::server::response_deadline_memory_tests::`;使用 paused Tokio clock 和内存 duplex。 - -这些回归不证明真实 TUN 互通、进程 RSS、吞吐、设备信任安装、系统 VPN 或平台真机行为; -对应验收分别由容器夹具、平台构建和设备测试完成。 - -IP4P 纯解码与严格配置回归:`config::ip4p::tests::`;不创建 socket 或解析网络名称。 - -IP4P 接点纯内存回归:`dns::resolution::ip4p_tests::`、 -`dialer::tests::connected_ip4p_conversion_precedes_family_and_source_binding_only_at_opted_in_seams`、 -`dialer::tests::ip4p_loopback_mapping_cannot_acquire_a_new_literal_exemption`、 -`outbound::connector::tests::ip4p_udp_node_endpoint_retains_chain_identity_and_uses_actual_reply_peer`。 -这些测试不建立网络 socket;真实 TUN 的 TCP/SS2022/SOCKS5/WireGuard 及 UWP 平台路径单独验收。 - -TUIC 冷连接的公开 API 门禁(纯内存、无票据缓存或网络 socket): -`tuic_cold_connection_cannot_publish_an_early_quinn_handle_without_resumption`。 -它检查仅启用 early-data 不能取得 Quinn 的早期客户端连接,不代表恢复连接或服务端验收。 - -Linux 受控物理 QUIC 的纯内存过滤器:`physical_quic_memory_` 与 -`physical_quic_switches_are_session_scoped_strict_and_keep_mihomo_defaults`。 -检查分段的逐包/总字节预算、来源与显式源覆盖拒绝、完整接收边界、默认值与严格字段; -不创建 socket,不证明真实 ECN/GSO、protect、RSS、吞吐或设备行为。 -`transport::quic::physical::tests::physical_quic_memory_revocation_releases_io_with_retained_broadcast_pollers` -在纯内存中检查多等待者广播、注册交错与持有已退役句柄时释放 IO。 -`physical_quic_memory_concurrent_read_leases_delay_retirement_until_both_release` 另验两个并发读者、 -退役等待双方释放及资源只析构一次。显式 ignored 的 -`transport::quic::physical::gate::real_tun_native_udp_retirement_gate` 仅供隔离 Linux -容器以真实 TUN 验证适配器的 fd、资源计数和 Stop;常规内存回归不得执行该网络门禁。 - -MASQUE H2 capsule已就绪合批的纯内存过滤器: -`outbound::masque::ip::h2_output_batch_memory_tests::` 与 -`transport::masque_codec::tests::masque_capsule_append_fit_and_rejection_preserve_the_existing_wire_prefix`。 -使用实际pump、内存PacketStream与codec验证合并、单包及时提交、大包与单溢出帧顺序、 -TTL、取消安全、强flush背压及错误;不创建网络socket,不代替真实TUN与RSS验收。 - -WireGuard 输出准入的纯内存过滤器:`outbound::wireguard::engine::full_handoff_memory_tests::`。 -使用真实 netstack 和原 32 槽队列,检查单 peer 保留满队列包至释放一槽、取消后资源释放, -以及多 peer 的有界交接与兄弟 peer 进展。 - -WireGuard 路由表的纯内存过滤器:`outbound::wireguard::routes::tests::`。 -经实际配置校验和路由表构造检查空表、单前缀、主机边界、双栈隔离、最长前缀及同前缀最后声明的所有者。 +`interop --list` 离线列出组合。网络验收使用真实 TUN,Mac socketpair 模拟另记路径和结果。Controller 仅用作管理入口。外部 benchmark 负责对端、负载和过程记录。[测试隔离](../docs/testing-isolation.md) · [验收边界](../docs/acceptance.md) diff --git a/tests/limit_foundations.rs b/tests/limit_foundations.rs index 7f07826..2ec8645 100644 --- a/tests/limit_foundations.rs +++ b/tests/limit_foundations.rs @@ -11,7 +11,7 @@ use std::collections::BTreeMap; fn registry_matches_live_production_constants_and_has_owned_boundary_cases() { use vole::{ResourceLimits, dispatch, transport}; let defaults = ResourceLimits::default(); - let expected = BTreeMap::from([ + let mut expected = BTreeMap::from([ ("tuic-quic-payload", vole::limits::TUIC_QUIC_PAYLOAD), ("tuic-control-readers", vole::limits::TUIC_CONTROL_READERS), ("tuic-send-window", vole::limits::TUIC_SEND_WINDOW), @@ -99,6 +99,7 @@ fn registry_matches_live_production_constants_and_has_owned_boundary_cases() { ("udp-payload", defaults.max_datagram_size), ("tun-packet", defaults.tun_max_datagram_size), ("tcp-buffer", defaults.tcp_buffer_per_direction), + ("tun-tcp-send-buffer", defaults.tun_tcp_send_buffer), ("dns-cache", defaults.dns_address_cache_entries), ("dns-hints", defaults.dns_redir_host_entries), ( @@ -158,18 +159,16 @@ fn registry_matches_live_production_constants_and_has_owned_boundary_cases() { serde_json::from_str(include_str!("protocols/limits.json")).unwrap(); let rows = registry["limits"].as_array().unwrap(); assert_eq!(rows.len(), expected.len()); - let mut actual = BTreeMap::new(); for row in rows { let id = row["id"].as_str().unwrap(); - assert!( - actual - .insert(id, row["value"].as_u64().unwrap() as usize) - .is_none() + assert_eq!( + Some(row["value"].as_u64().unwrap() as usize), + expected.remove(id), + "stale, unknown or duplicate limit: {id}" ); for key in ["unit", "owner", "saturation", "cancellation"] { assert!(!row[key].as_str().unwrap().is_empty()); } assert!(!row["boundary_cases"].as_array().unwrap().is_empty()); } - assert_eq!(actual, expected); } diff --git a/tests/protocols/limits.json b/tests/protocols/limits.json index 7f42e6b..aabce0a 100644 --- a/tests/protocols/limits.json +++ b/tests/protocols/limits.json @@ -292,10 +292,10 @@ }, { "id": "xhttp-h3-udp-send-window", - "value": 196608, + "value": 262144, "unit": "bytes", "owner": "limits::XHTTP_H3_UDP_SEND_WINDOW", - "saturation": "qualified physical starts64KiB; successful local mux UDP metadata flush raises shared retained-write admission192KiB once", + "saturation": "Qualified physical connection starts at 64 KiB. The first successful local mux UDP metadata flush raises its shared retention budget to 256 KiB.", "cancellation": "failed/cancelled metadata does not raise; Weak does not own native lifecycle; original Stop joins drivers", "boundary_cases": ["XHTTP-UNIT"] }, @@ -613,6 +613,17 @@ "FOUNDATIONS-REGRESSION" ] }, + { + "id": "tun-tcp-send-buffer", + "value": 131072, + "unit": "bytes-per-flow", + "owner": "ResourceLimits::tun_tcp_send_buffer", + "saturation": "split equally between smoltcp TX and app-send queue; full app queue returns Pending until the driver can drain it", + "cancellation": "existing runtime-owned cancellation and Stop barrier", + "boundary_cases": [ + "FOUNDATIONS-REGRESSION" + ] + }, { "id": "dns-cache", "value": 256, diff --git a/tests/tuic_memory.rs b/tests/tuic_memory.rs index 10cc608..87eae5d 100644 --- a/tests/tuic_memory.rs +++ b/tests/tuic_memory.rs @@ -910,7 +910,7 @@ async fn association_id_exhaustion_retires_without_reuse_or_migrating_old_stream } #[tokio::test] -async fn quic_partial_control_streams_have_a_credit_bound_and_expire_without_blocking_tcp() { +async fn quic_partial_control_streams_expire_without_blocking_tcp() { let (mut config, udp_path, endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); let (_, tcp_path, tcp_endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); config.stream_window = vole::config::QuicReceiveWindow { @@ -944,11 +944,8 @@ async fn quic_partial_control_streams_have_a_credit_bound_and_expire_without_blo .unwrap(); partial.push(stream); } - assert!( - tokio::time::timeout(Duration::from_millis(50), connection.open_uni()) - .await - .is_err() - ); + // These 32 actual partial decoders retain their admission TTL. + // Advertised UNI credit has its separate real lane controls below. ready.send(()).unwrap(); for stream in &partial { assert_eq!( @@ -1128,6 +1125,318 @@ async fn cancelled_uni_credit_wait_does_not_replay_or_close_sibling_tcp() { finish(tcp_endpoint, tcp_peer).await; } +// This case deliberately exercises the private TUN association entry through +// production Observed -> Routed -> Connector -> normal TUIC, not a fake sender. +// All assertions follow unconditional cancellation, Stop and owner joins. +#[cfg(all(feature = "tun", target_os = "macos"))] +#[tokio::test] +async fn tun_tuic_reply_progresses_while_same_association_uni_send_waits_for_credit() { + for tracked in [false, true] { + tun_tuic_duplex_case(tracked).await; + } +} + +#[cfg(all(feature = "tun", target_os = "macos"))] +async fn tun_tuic_duplex_case(tracked: bool) { + use std::{net::SocketAddr, task::Poll}; + use vole::{ + config::{ProxyId, RouteTargetId, RuleAction, RuleKind, RuleSpec}, + dispatch::Dispatcher, + outbound::ConnectorDispatcher, + routing::{EmptyGeoMatcher, ProxyDispatchers, RoutingDispatcher, RuleSet}, + }; + + async fn checked_auth(endpoint: &quinn::Endpoint) -> Result { + let incoming = endpoint.accept().await.ok_or("peer accept closed")?; + let connection = incoming.await.map_err(|_| "peer handshake failed")?; + let mut auth_stream = connection + .accept_uni() + .await + .map_err(|_| "auth stream missing")?; + let auth = auth_stream + .read_to_end(50) + .await + .map_err(|_| "auth frame failed")?; + let mut expected = [0; 32]; + connection + .export_keying_material(&mut expected, &[7; 16], b" raw\0context ") + .map_err(|_| "auth exporter failed")?; + if auth.len() != 50 + || auth[..18] != [5, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7] + || auth[18..] != expected + { + return Err("auth identity differed"); + } + Ok(connection) + } + + async fn join_peer(mut task: tokio::task::JoinHandle>) -> bool { + match tokio::time::timeout(Duration::from_secs(2), &mut task).await { + Ok(Ok(result)) => result.is_ok(), + Ok(Err(_)) => false, + Err(_) => { + task.abort(); + let _ = task.await; + false + } + } + } + + let (mut config, udp_path, endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); + let (_, tcp_path, tcp_endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); + config.stream_window = vole::config::QuicReceiveWindow { + initial: 256 * 1024, + maximum: 256 * 1024, + }; + config.connection_window = vole::config::QuicReceiveWindow { + initial: 1024 * 1024, + maximum: 1024 * 1024, + }; + config.disable_mtu_discovery = true; + let paths = Arc::new(Paths(Mutex::new(VecDeque::from([udp_path, tcp_path])))); + let outbound = + Arc::new(TuicOutbound::new_with_path(&config, UpstreamPath::proxy(paths.clone())).unwrap()); + let connector: Arc = Arc::new(ConnectorDispatcher::new(outbound.clone())); + let rules = RuleSet::compile(vec![RuleSpec { + kind: RuleKind::Match, + no_resolve: true, + action: RuleAction::Route(RouteTargetId::Proxy(ProxyId::new(0).unwrap())), + }]) + .unwrap(); + // Even the unused DIRECT entry is the real memory-only connector. No branch + // in this fixture can resolve a name or create a host socket. + let router = RoutingDispatcher::new( + ProxyDispatchers::new(vec![connector.clone()]).unwrap(), + connector, + None, + rules.clone(), + Arc::new(EmptyGeoMatcher), + ); + let (router, registry) = if tracked { + // Diagnostics uses the same real TUIC node identity and rule index; + // it only enables the existing production tracked routing path. + let diagnostic_config = Config::parse_yaml( + serde_json::json!({ + "mixed-port": 1080, + "proxies": [{ + "name": "peer", "type": "tuic", "server": "192.0.2.1", "port": 443, + "uuid": "07070707-0707-0707-0707-070707070707", + "password": " raw\u{0000}context ", "sni": "fixture.invalid", + "skip-cert-verify": true, "congestion-controller": "cubic", + "udp": true, "udp-relay-mode": "quic" + }], + "rules": ["MATCH,peer"] + }) + .to_string() + .as_bytes(), + ) + .unwrap(); + let (router, registry) = + vole::interop_tracked_tun_router(router, &diagnostic_config, &rules); + (router, Some(registry)) + } else { + (router, None) + }; + let router: Arc = Arc::new(router); + let source: SocketAddr = "192.0.2.10:12000".parse().unwrap(); + let destination: SocketAddr = "198.51.100.20:80".parse().unwrap(); + let (held_tx, held_rx) = tokio::sync::oneshot::channel(); + let (reply_tx, reply_rx) = tokio::sync::oneshot::channel(); + let peer_endpoint = endpoint.clone(); + let peer = tokio::spawn(async move { + let connection = checked_auth(&peer_endpoint).await?; + let mut unread = Vec::with_capacity(2); + let mut association = None; + for _ in 0..2 { + let mut stream = connection + .accept_uni() + .await + .map_err(|_| "credit stream missing")?; + let mut header = [0; 10]; + stream + .read_exact(&mut header) + .await + .map_err(|_| "UDP header missing")?; + if header[..2] != [5, 2] || header[6..] != [1, 0, 0, 1] { + return Err("UDP frame differed"); + } + let id = [header[2], header[3]]; + if association.is_some_and(|previous| previous != id) { + return Err("UDP association changed"); + } + association = Some(id); + // Retain address and payload unread: neither receive stream reaches + // EOF, so both real Quinn UNI credits remain occupied. + unread.push(stream); + } + held_tx + .send(()) + .map_err(|_| "credit witness receiver closed")?; + reply_rx.await.map_err(|_| "reply authorization closed")?; + // This probes the real exhausted credit; it never releases either held + // stream. The TUN future has already consumed and polled the third send. + if tokio::time::timeout(Duration::from_millis(40), connection.accept_uni()) + .await + .is_ok() + { + return Err("third send escaped exhausted UNI credit"); + } + let [hi, lo] = association.ok_or("association missing")?; + let mut response = connection + .open_uni() + .await + .map_err(|_| "reply stream failed")?; + response + .write_all(&[ + 5, 2, hi, lo, 0, 0, 1, 0, 0, 1, 1, 198, 51, 100, 20, 0, 80, b'r', + ]) + .await + .map_err(|_| "reply write failed")?; + response.finish().map_err(|_| "reply finish failed")?; + connection.closed().await; + drop(unread); + Ok(()) + }); + let peer_endpoint = tcp_endpoint.clone(); + let tcp_peer = tokio::spawn(async move { + let connection = checked_auth(&peer_endpoint).await?; + let (mut send, mut recv) = connection + .accept_bi() + .await + .map_err(|_| "TCP stream missing")?; + let mut wire = [0; 8]; + recv.read_exact(&mut wire) + .await + .map_err(|_| "TCP request missing")?; + if wire != *b"\x05\x01\x00\x01x\x00\x50a" { + return Err("sibling TCP frame differed"); + } + send.write_all(b"a").await.map_err(|_| "TCP reply failed")?; + connection.closed().await; + Ok(()) + }); + let probe = ResourceProbe::default(); + let (observed, association_stopped, outbound_stopped, both_paths_used) = probe + .scope(async { + let (input, mut replies, cancellation, mut association) = + vole::interop_tun_udp_association(router.clone(), source); + let observed: Result<(), &'static str> = async { + for _ in 0..2 { + tokio::time::timeout(Duration::from_secs(1), async { + tokio::select! { + biased; + _ = &mut association => Err("association ended during setup"), + result = input.send(vole_netstack::UdpDatagram::new( + source, destination, bytes::Bytes::from_static(b"x"), + )) => result.map_err(|_| "TUN input closed"), + } + }) + .await + .map_err(|_| "initial TUN enqueue timed out")??; + } + tokio::time::timeout(Duration::from_secs(1), async { + tokio::select! { + biased; + _ = &mut association => Err("association ended before credit hold"), + result = held_rx => result.map_err(|_| "peer credit witness failed"), + } + }) + .await + .map_err(|_| "credit hold timed out")??; + input + .send(vole_netstack::UdpDatagram::new( + source, destination, bytes::Bytes::from_static(b"x"), + )) + .await + .map_err(|_| "third TUN enqueue failed")?; + // Poll the actual entry to Pending with cooperative-budget + // deferral disabled, before the peer is allowed to send a reply. + let third_pending = matches!( + futures_util::poll!(tokio::task::unconstrained(association.as_mut())), + Poll::Pending + ); + if !third_pending || input.capacity() != input.max_capacity() { + return Err("third real association send did not reach Pending"); + } + tokio::time::timeout(Duration::from_secs(1), async { + let mut tcp = router.connect_tcp(request()).await.map_err(|_| "sibling TCP open failed")?; + tcp.write_all(b"a").await.map_err(|_| "sibling TCP write failed")?; + let byte = tcp.read_u8().await.map_err(|_| "sibling TCP read failed")?; + if byte != b'a' { + return Err("sibling TCP reply differed"); + } + Ok(()) + }) + .await + .map_err(|_| "sibling TCP timed out")??; + reply_tx.send(()).map_err(|_| "peer reply authorization failed")?; + let response = tokio::time::timeout(Duration::from_millis(500), async { + tokio::select! { + biased; + _ = &mut association => Err("association ended before peer reply"), + response = replies.receive() => response.ok_or("TUN response channel closed"), + } + }) + .await + .map_err(|_| "same-association reply starved behind pending send")??; + if response.source != destination + || response.destination != source + || response.payload != b"r"[..] + { + return Err("same-association TUN reply differed"); + } + Ok(()) + } + .await; + // Every success/error above rejoins here before any assertion. + cancellation.cancel(); + outbound.begin_shutdown(); + let association_stopped = matches!( + tokio::time::timeout(Duration::from_secs(2), &mut association).await, + Ok(Ok(())) + ); + drop(association); + drop(input); + drop(replies); + let outbound_stopped = + tokio::time::timeout(Duration::from_secs(2), outbound.shutdown()).await.is_ok(); + let both_paths_used = paths.0.lock().unwrap().is_empty(); + (observed, association_stopped, outbound_stopped, both_paths_used) + }) + .await; + endpoint.close(0_u8.into(), b""); + tcp_endpoint.close(0_u8.into(), b""); + let peer_joined = join_peer(peer).await; + let tcp_peer_joined = join_peer(tcp_peer).await; + let peer_idle = tokio::time::timeout(Duration::from_secs(2), endpoint.wait_idle()) + .await + .is_ok(); + let tcp_peer_idle = tokio::time::timeout(Duration::from_secs(2), tcp_endpoint.wait_idle()) + .await + .is_ok(); + drop(router); + drop(outbound); + let tracking_idle = registry.is_none_or(vole::InteropTunRoutingRegistry::close); + let probe_idle = probe.snapshot().is_idle(); + assert!( + association_stopped + && outbound_stopped + && peer_joined + && tcp_peer_joined + && peer_idle + && tcp_peer_idle + && probe_idle + && tracking_idle + && both_paths_used, + "TUIC duplex fixture ownership/Stop failed" + ); + assert!( + observed.is_ok(), + "{}", + observed.err().unwrap_or("unknown observation") + ); +} + #[cfg(unix)] #[tokio::test] async fn physical_protection_failure_stops_before_udp_or_tcp_fallback() { @@ -1569,7 +1878,8 @@ async fn configured_mtu_discovery_changes_native_probes_and_path_mtu() { } #[tokio::test] -async fn official_quinn_credit_is_bounded_and_replenished_independent_of_owner_threshold() { +async fn official_quinn_tcp_lane_credit_is_bounded_and_replenished_independent_of_owner_threshold() +{ let (mut config, packets, endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); config.max_open_streams = i64::MAX as usize - 1; let outbound = TuicOutbound::new_with_path( @@ -1650,16 +1960,18 @@ async fn official_quinn_credit_is_bounded_and_replenished_independent_of_owner_t let probe = ResourceProbe::default(); probe .scope(async { - let udp = outbound - .open_datagram(udp_request(), &EstablishContext::default()) + // Lane zero keeps its original receive credit in QUIC relay mode. + let stream = outbound + .connect_stream(request(), &EstablishContext::default()) .await - .unwrap(); + .unwrap() + .io; tokio::time::timeout(Duration::from_secs(4), wait) .await .unwrap() .unwrap(); outbound.shutdown().await; - drop(udp); + drop(stream); assert!(probe.snapshot().is_idle(), "{:?}", probe.snapshot()); }) .await; @@ -1966,3 +2278,10 @@ async fn quic_business_lanes_retire_only_udp_while_tcp_is_held_and_stop_all() { finish(udp_endpoint, udp_peer).await; finish(fresh_endpoint, fresh_peer).await; } + +#[path = "tuic_memory/uot_lane.rs"] +mod uot_lane_memory; + +#[cfg(target_os = "macos")] +#[path = "tuic_memory/uni_credit.rs"] +mod uni_credit_memory; diff --git a/tests/tuic_memory/uni_credit.rs b/tests/tuic_memory/uni_credit.rs new file mode 100644 index 0000000..715930e --- /dev/null +++ b/tests/tuic_memory/uni_credit.rs @@ -0,0 +1,386 @@ +//! Actual TUIC UDP-lane UNI credit over bounded memory packets. +use super::*; + +#[cfg(target_os = "macos")] +#[tokio::test] +async fn quic_udp_advertised_uni_credit_is_128_and_recycles_at_17() { + #[derive(Debug, Default)] + struct CreditObservation { + admitted: usize, + remote_bidi_refused: bool, + initial_129_pending: bool, + after_16_pending: usize, + replenished_batches: usize, + replenished_streams: usize, + final_129_pending: bool, + all_steps_completed: bool, + } + + let (mut config, packets, endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); + // Keep owner admission independent of remotely initiated stream credit. + config.max_open_streams = i64::MAX as usize - 1; + let outbound = TuicOutbound::new_with_path( + &config, + UpstreamPath::proxy(Arc::new(MemoryUpstream(Mutex::new(Some(packets))))), + ) + .unwrap(); + let ep = endpoint.clone(); + let (ready, wait) = tokio::sync::oneshot::channel(); + let mut peer = tokio::spawn(async move { + // This existing helper verifies the unchanged authentication fixture; + // none of the intended C8 semantic RED paths assert inside the peer. + let connection = authenticated(&ep).await; + let mut observed = CreditObservation::default(); + let mut held = VecDeque::new(); + // Keep the entire credit observation below the original decoder TTL, + // so a slow observation cannot borrow credits from five-second expiry. + let completed = tokio::time::timeout(Duration::from_secs(3), async { + observed.remote_bidi_refused = + tokio::time::timeout(Duration::from_millis(50), connection.open_bi()) + .await + .is_err(); + if !observed.remote_bidi_refused { + return Err(()); + } + // Independent expected contract, never read the implementation's + // advertised-credit or decoder constants to manufacture a PASS. + // One total admission deadline bounds the old C8 RED at open 33; + // it cannot wait 128 times for a per-stream timeout. + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + for _ in 0..128 { + let stream = tokio::time::timeout_at(deadline, connection.open_uni()) + .await + .map_err(|_| ())? + .map_err(|_| ())?; + held.push_back(stream); + observed.admitted += 1; + } + observed.initial_129_pending = + tokio::time::timeout(Duration::from_millis(100), connection.open_uni()) + .await + .is_err(); + if !observed.initial_129_pending { + return Err(()); + } + // No stream data was sent before the 128/129 boundary check. + // Receiving the highest ID now implicitly opens all earlier gaps. + tokio::time::timeout( + Duration::from_secs(1), + held.back_mut().ok_or(())?.write_all(&[5]), + ) + .await + .map_err(|_| ())? + .map_err(|_| ())?; + + // Exact Quinn batches MAX_STREAMS only after more than C/8 have + // been freed. For C=128, 16 is insufficient and the 17th releases + // one bounded batch. Two cycles prove recycling without a grid. + for _ in 0..2 { + for _ in 0..16 { + let mut stream = held.pop_front().ok_or(())?; + stream.finish().map_err(|_| ())?; + } + let pending = + tokio::time::timeout(Duration::from_millis(100), connection.open_uni()) + .await + .is_err(); + if !pending { + return Err(()); + } + observed.after_16_pending += 1; + let mut stream = held.pop_front().ok_or(())?; + stream.finish().map_err(|_| ())?; + drop(stream); + let deadline = tokio::time::Instant::now() + Duration::from_secs(2); + for _ in 0..17 { + let mut next = tokio::time::timeout_at(deadline, connection.open_uni()) + .await + .map_err(|_| ())? + .map_err(|_| ())?; + tokio::time::timeout_at(deadline, next.write_all(&[5])) + .await + .map_err(|_| ())? + .map_err(|_| ())?; + held.push_back(next); + observed.replenished_streams += 1; + } + observed.replenished_batches += 1; + } + observed.final_129_pending = + tokio::time::timeout(Duration::from_millis(100), connection.open_uni()) + .await + .is_err(); + if !observed.final_129_pending { + return Err(()); + } + Ok::<(), ()>(()) + }) + .await; + observed.all_steps_completed = matches!(completed, Ok(Ok(()))); + // The expected old-source failure drops all held send owners, reports + // its false observations, then waits for the real parent-owned close. + drop(held); + let _ = ready.send(observed); + connection.closed().await; + }); + let probe = ResourceProbe::default(); + let (opened, observed, stopped) = probe + .scope(async { + let opened = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await; + let was_opened = opened.is_ok(); + // Covers both 2-second credit waits and the fixed finite checks. + let observed = tokio::time::timeout(Duration::from_secs(8), wait) + .await + .ok() + .and_then(Result::ok); + outbound.begin_shutdown(); + drop(opened); + endpoint.close(0_u8.into(), b""); + let stopped = tokio::time::timeout(Duration::from_secs(2), outbound.shutdown()) + .await + .is_ok(); + (was_opened, observed, stopped) + }) + .await; + // Do not use the original finish() helper here: its join unwrap precedes + // endpoint.wait_idle, while this RED control must attempt every join first. + let peer_joined = match tokio::time::timeout(Duration::from_secs(2), &mut peer).await { + Ok(result) => result.is_ok(), + Err(_) => { + peer.abort(); + let _ = peer.await; + false + } + }; + let endpoint_idle = tokio::time::timeout(Duration::from_secs(2), endpoint.wait_idle()) + .await + .is_ok(); + drop(endpoint); + drop(outbound); + let resources_idle = probe.snapshot().is_idle(); + // Every expected semantic RED assertion happens after owned closure. + assert!( + opened && stopped && peer_joined && endpoint_idle && resources_idle, + "actual fixture/Stop/peer/endpoint closure failed: {:?}", + probe.snapshot() + ); + let observed = observed.expect("joined peer did not publish its bounded observation"); + assert!( + observed.remote_bidi_refused + && observed.admitted == 128 + && observed.initial_129_pending + && observed.after_16_pending == 2 + && observed.replenished_batches == 2 + && observed.replenished_streams == 34 + && observed.final_129_pending + && observed.all_steps_completed, + "actual UDP-lane UNI permission must be 128 with bounded 17-credit recycling: {observed:?}" + ); +} + +#[tokio::test(start_paused = true)] +async fn quic_udp_uni_credit_keeps_32_decoders_and_original_admission_ttl() { + let (mut config, udp_path, endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); + let (_, tcp_path, tcp_endpoint) = fixture_parts(1400, true, 8, "cubic", "quic"); + config.disable_mtu_discovery = true; + let paths = Arc::new(Paths(Mutex::new(VecDeque::from([udp_path, tcp_path])))); + let outbound = TuicOutbound::new_with_path(&config, UpstreamPath::proxy(paths)).unwrap(); + let ep = endpoint.clone(); + let (ready, wait) = tokio::sync::oneshot::channel(); + let (wave, wave_wait) = tokio::sync::oneshot::channel(); + let mut peer = tokio::spawn(async move { + let connection = authenticated(&ep).await; + let setup = tokio::time::timeout(Duration::from_secs(2), async { + // The real outbound first packet proves association zero exists. + let mut first = connection.accept_uni().await.map_err(|_| ())?; + let first = first.read_to_end(64).await.map_err(|_| ())?; + if first.get(..4) != Some(b"\x05\x02\x00\x00".as_slice()) { + return Err(()); + } + let mut partial = Vec::new(); + for packet in 0..32_u16 { + let mut stream = connection.open_uni().await.map_err(|_| ())?; + let mut header = + b"\x05\x02\x00\x00\x00\x00\x01\x00\x00\x01\x00\x01x\x00\x50".to_vec(); + header[4..6].copy_from_slice(&packet.to_be_bytes()); + stream.write_all(&header).await.map_err(|_| ())?; + // Valid association/address, declared one-byte body absent. + partial.push(stream); + } + let mut marker = connection.open_uni().await.map_err(|_| ())?; + marker + .write_all(b"\x05\x02\x00\x00\x00\x20\x01\x00\x00\x01\x00\x01x\x00\x50m") + .await + .map_err(|_| ())?; + marker.finish().map_err(|_| ())?; + // Same-connection receipt barrier, not application consumption: + // FIN plus all marker bytes must be ACKed before ready is true. + // This is covered by the original two-second setup deadline. + if !matches!(marker.stopped().await, Ok(None)) { + return Err(()); + } + Ok::<_, ()>(partial) + }) + .await; + match setup { + Ok(Ok(partial)) => { + let _ = ready.send(true); + // One shared deadline across the whole first wave. Sequential + // per-stream six-second budgets would hide extra TTL waves. + let stopped = tokio::time::timeout(Duration::from_secs(6), async { + for stream in &partial { + if !matches!(stream.stopped().await, Ok(Some(code)) if code == 0_u8.into()) + { + return false; + } + } + true + }) + .await + .unwrap_or(false); + let _ = wave.send(stopped); + // Answer STOP via normal peer owner release; no fake FIN ACK. + drop(partial); + } + _ => { + // Old C8 reaches its 33rd-open timeout here. Keep a semantic + // false result, then allow the parent to close every owner. + let _ = ready.send(false); + let _ = wave.send(false); + } + } + connection.closed().await; + }); + let tcp_ep = tcp_endpoint.clone(); + let mut tcp_peer = tokio::spawn(async move { + let connection = authenticated(&tcp_ep).await; + let echoed = tokio::time::timeout(Duration::from_secs(4), async { + let (mut send, mut recv) = connection.accept_bi().await.map_err(|_| ())?; + let mut request = [0; 8]; + recv.read_exact(&mut request).await.map_err(|_| ())?; + if &request != b"\x05\x01\x00\x01x\x00\x50a" { + return Err(()); + } + send.write_all(b"a").await.map_err(|_| ())?; + Ok::<_, ()>(()) + }) + .await; + connection.closed().await; + matches!(echoed, Ok(Ok(()))) + }); + let probe = ResourceProbe::default(); + let facts = probe + .scope(async { + let mut udp = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .ok(); + let sent = if let Some(udp) = &mut udp { + udp.send(Datagram { + remote: request().destination, + payload: bytes::Bytes::from_static(b"start"), + sniffed_domain: None, + }) + .await + .is_ok() + } else { + false + }; + let prepared = tokio::time::timeout(Duration::from_secs(3), wait) + .await + .ok() + .and_then(Result::ok) + .unwrap_or(false); + let mut early_pending = false; + if prepared && let Some(udp) = &mut udp { + early_pending = tokio::time::timeout(Duration::from_millis(100), udp.receive()) + .await + .is_err(); + } + // Check UDP blocking first. All TCP establishment/write/echo work + // has one budget, so it cannot consume the first five-second TTL. + let tcp_attempt = tokio::time::timeout(Duration::from_secs(1), async { + let mut tcp = outbound + .connect_stream( + request(), + &EstablishContext::with_timeout(Duration::from_secs(1)), + ) + .await + .map_err(|_| ())? + .io; + tcp.write_all(b"a").await.map_err(|_| ())?; + if tcp.read_u8().await.map_err(|_| ())? != b'a' { + return Err(()); + } + Ok::<_, ()>(tcp) + }) + .await; + let (tcp, tcp_echo) = match tcp_attempt { + Ok(Ok(tcp)) => (Some(tcp), true), + _ => (None, false), + }; + let mut marker_delivered = false; + if early_pending && let Some(udp) = &mut udp { + marker_delivered = matches!( + tokio::time::timeout(Duration::from_secs(6), udp.receive()).await, + Ok(Ok(packet)) if packet.payload.as_ref() == b"m" + ); + } + let first_wave = tokio::time::timeout(Duration::from_secs(7), wave_wait) + .await + .ok() + .and_then(Result::ok) + .unwrap_or(false); + outbound.begin_shutdown(); + drop(udp); + drop(tcp); + endpoint.close(0_u8.into(), b""); + tcp_endpoint.close(0_u8.into(), b""); + let stopped = tokio::time::timeout(Duration::from_secs(2), outbound.shutdown()) + .await + .is_ok(); + ( + sent, + prepared, + tcp_echo, + early_pending, + marker_delivered, + first_wave, + stopped, + ) + }) + .await; + let peer_joined = match tokio::time::timeout(Duration::from_secs(2), &mut peer).await { + Ok(result) => result.is_ok(), + Err(_) => { + peer.abort(); + let _ = peer.await; + false + } + }; + let tcp_joined = match tokio::time::timeout(Duration::from_secs(2), &mut tcp_peer).await { + Ok(result) => result.unwrap_or(false), + Err(_) => { + tcp_peer.abort(); + let _ = tcp_peer.await; + false + } + }; + let idle = tokio::time::timeout(Duration::from_secs(2), endpoint.wait_idle()) + .await + .is_ok(); + let tcp_idle = tokio::time::timeout(Duration::from_secs(2), tcp_endpoint.wait_idle()) + .await + .is_ok(); + drop((endpoint, tcp_endpoint, outbound)); + assert!( + facts.6 && peer_joined && tcp_joined && idle && tcp_idle && probe.snapshot().is_idle(), + "all real fixture owners must close before semantic assertions: {facts:?}" + ); + assert!( + facts.0 && facts.1 && facts.2 && facts.3 && facts.4 && facts.5, + "the 33rd complete packet must wait for the original first 32 decoder TTLs: {facts:?}" + ); +} diff --git a/tests/tuic_memory/uot_lane.rs b/tests/tuic_memory/uot_lane.rs new file mode 100644 index 0000000..cb99dad --- /dev/null +++ b/tests/tuic_memory/uot_lane.rs @@ -0,0 +1,350 @@ +//! Real TUIC authentication, Connect and UoT over the existing bounded memory peer. +use super::*; +use tokio_util::sync::CancellationToken; + +#[derive(Debug)] +struct Evidence { + tags: [u8; 9], + pools_before_retirement: usize, + pools_with_retired: usize, + pools_with_one_old_owner: usize, + pools_after_old_owners: usize, + remaining_paths: usize, +} + +#[derive(Debug)] +struct Case { + mode: &'static str, + evidence: Result, + stopped_reads: bool, + stop_elapsed: Duration, + probe_idle: bool, + peers_joined: bool, + endpoints_idle: bool, +} + +// Independent bounded wire peer. Every response includes its physical path tag; +// no lane index, pointer equality or production selection helper is consulted. +async fn echo_stream( + mut send: quinn::SendStream, + mut recv: quinn::RecvStream, + tag: u8, +) -> Result<(), String> { + let mut prefix = [0; 4]; + recv.read_exact(&mut prefix) + .await + .map_err(|e| e.to_string())?; + if prefix[..3] != [5, 1, 0] || usize::from(prefix[3]) > 32 { + return Err("invalid TUIC Connect prefix".into()); + } + let mut target = [0; 34]; + let length = usize::from(prefix[3]) + 2; + recv.read_exact(&mut target[..length]) + .await + .map_err(|e| e.to_string())?; + let uot = if &target[..length] == b"x\0P" { + false + } else if &target[..length] == b"sp.v2.udp-over-tcp.arpa\0\0" { + true + } else { + return Err("unexpected Connect target".into()); + }; + if uot { + let mut request = [0; 8]; + recv.read_exact(&mut request) + .await + .map_err(|e| e.to_string())?; + if request != [0, 1, 1, 2, 3, 4, 0, 53] { + return Err("invalid UoT datagram-mode request".into()); + } + } + let mut first = [0; 1]; + while let Ok(Some(1)) = recv.read(&mut first).await { + if uot { + let mut rest = [0; 9]; + recv.read_exact(&mut rest) + .await + .map_err(|e| e.to_string())?; + if first[0] != 0 || rest[..8] != [1, 2, 3, 4, 0, 53, 0, 1] { + return Err("invalid bounded UoT frame".into()); + } + send.write_all(&[0, 1, 2, 3, 4, 0, 53, 0, 2, tag, rest[8]]) + .await + .map_err(|e| e.to_string())?; + } else { + send.write_all(&[tag, first[0]]) + .await + .map_err(|e| e.to_string())?; + } + } + let _ = send.finish(); + Ok(()) +} + +fn serve( + endpoint: quinn::Endpoint, + tag: u8, + stop: CancellationToken, +) -> tokio::task::JoinHandle> { + tokio::spawn(async move { + // The shared helper checks the UUID and the exporter from this actual + // TLS connection before any application response can be produced. + let connection = tokio::select! { biased; + () = stop.cancelled() => return Ok(()), + connection = authenticated(&endpoint) => connection, + }; + let mut streams = tokio::task::JoinSet::new(); + loop { + tokio::select! { + () = stop.cancelled() => { + connection.close(0_u8.into(), b""); + break; + } + _ = connection.closed() => break, + stream = connection.accept_bi() => { + let Ok((send, recv)) = stream else { break; }; + streams.spawn(echo_stream(send, recv, tag)); + } + } + } + let mut result = Ok(()); + while let Some(joined) = streams.join_next().await { + match joined { + Ok(Ok(())) => {} + Ok(Err(error)) => result = Err(error), + Err(error) => result = Err(error.to_string()), + } + } + result + }) +} + +async fn tcp_echo(stream: &mut vole::dispatch::BoxStream, byte: u8) -> Result { + stream.write_all(&[byte]).await.map_err(|e| e.to_string())?; + let mut reply = [0; 2]; + stream + .read_exact(&mut reply) + .await + .map_err(|e| e.to_string())?; + if reply[1] != byte { + return Err("TCP payload changed".into()); + } + Ok(reply[0]) +} + +async fn uot_echo(stream: &mut Box, byte: u8) -> Result { + stream + .send(Datagram { + remote: Destination::Ip("1.2.3.4:53".parse().unwrap()), + payload: bytes::Bytes::copy_from_slice(&[byte]), + sniffed_domain: None, + }) + .await + .map_err(|e| e.to_string())?; + let reply = stream.receive().await.map_err(|e| e.to_string())?; + if reply.remote != Destination::Ip("1.2.3.4:53".parse().unwrap()) + || reply.payload.len() != 2 + || reply.payload[1] != byte + { + return Err("UoT payload or reply source changed".into()); + } + Ok(reply.payload[0]) +} + +async fn exercise( + outbound: &TuicOutbound, + paths: &Paths, + probe: &ResourceProbe, +) -> Result< + ( + Evidence, + vole::dispatch::BoxStream, + Box, + ), + String, +> { + let context = EstablishContext::with_timeout(Duration::from_secs(2)); + let mut tcp = outbound + .connect_stream(request(), &context) + .await + .map_err(|e| e.to_string())? + .io; + let tcp_tag = tcp_echo(&mut tcp, b'a').await?; + let mut first = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .map_err(|e| e.to_string())?; + let first_tag = uot_echo(&mut first, b'p').await?; + let mut held = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .map_err(|e| e.to_string())?; + let held_tag = uot_echo(&mut held, b'q').await?; + let mut third = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .map_err(|e| e.to_string())?; + let third_tag = uot_echo(&mut third, b'v').await?; + let pools_before_retirement = probe.snapshot().current(ResourceKind::Pool); + let mut fresh = outbound + .open_datagram(udp_request(), &EstablishContext::default()) + .await + .map_err(|e| e.to_string())?; + let fresh_tag = uot_echo(&mut fresh, b'r').await?; + let pools_with_retired = probe.snapshot().current(ResourceKind::Pool); + // New TCP after UoT retirement must still reuse the original TCP lane. + let mut sibling = outbound + .connect_stream(request(), &EstablishContext::default()) + .await + .map_err(|e| e.to_string())? + .io; + let sibling_tag = tcp_echo(&mut sibling, b'x').await?; + drop(sibling); + let old_tag = uot_echo(&mut first, b's').await?; + let tcp_after = tcp_echo(&mut tcp, b'b').await?; + held.close().await.map_err(|e| e.to_string())?; + drop(held); + third.close().await.map_err(|e| e.to_string())?; + drop(third); + let pools_with_one_old_owner = probe.snapshot().current(ResourceKind::Pool); + let after_sibling_close = uot_echo(&mut first, b't').await?; + first.close().await.map_err(|e| e.to_string())?; + drop(first); + // Allow the existing five-second FIN ownership ceiling; do not assume that + // local shutdown is immediate peer ACK or change the production grace. + tokio::time::timeout(Duration::from_secs(6), async { + while probe.snapshot().current(ResourceKind::Pool) > 2 { + tokio::task::yield_now().await; + } + }) + .await + .map_err(|_| "retired owner did not release".to_owned())?; + Ok(( + Evidence { + tags: [ + tcp_tag, + first_tag, + held_tag, + third_tag, + sibling_tag, + fresh_tag, + old_tag, + tcp_after, + after_sibling_close, + ], + pools_before_retirement, + pools_with_retired, + pools_with_one_old_owner, + pools_after_old_owners: probe.snapshot().current(ResourceKind::Pool), + remaining_paths: paths.0.lock().unwrap().len(), + }, + tcp, + fresh, + )) +} + +async fn case(mode: &'static str) -> Case { + let (mut config, tcp_path, tcp_ep) = fixture_parts(1400, true, 8, "cubic", mode); + let (_, uot_path, uot_ep) = fixture_parts(1400, true, 8, "cubic", mode); + let (_, fresh_path, fresh_ep) = fixture_parts(1400, true, 8, "cubic", mode); + config.udp_over_stream = true; + config.disable_mtu_discovery = true; + // Three owners let the legacy shared pool complete every operation too; + // only observed connection tags/counts should produce its semantic RED. + config.max_open_streams = 3; + let paths = Arc::new(Paths(Mutex::new(VecDeque::from([ + tcp_path, uot_path, fresh_path, + ])))); + let outbound = + TuicOutbound::new_with_path(&config, UpstreamPath::proxy(paths.clone())).unwrap(); + let endpoints = [tcp_ep, uot_ep, fresh_ep]; + let peer_stop = CancellationToken::new(); + let peers: Vec<_> = endpoints + .iter() + .enumerate() + .map(|(tag, ep)| serve(ep.clone(), tag as u8, peer_stop.clone())) + .collect(); + let probe = ResourceProbe::default(); + let (evidence, stopped_reads, stop_elapsed, probe_idle) = probe + .scope(async { + // The baseline shared implementation can perform the same complete + // workload. Its RED is the observed tags/counts after all cleanup. + let mut outcome = + tokio::time::timeout(Duration::from_secs(12), exercise(&outbound, &paths, &probe)) + .await + .map_err(|_| "client exercise deadline".to_owned()) + .and_then(|v| v); + let before = tokio::time::Instant::now(); + outbound.shutdown().await; + let stop_elapsed = before.elapsed(); + let stopped_reads = if let Ok((_, tcp, fresh)) = &mut outcome { + let tcp_stopped = tokio::time::timeout(Duration::from_secs(1), tcp.read_u8()) + .await + .is_ok_and(|v| v.is_err()); + let uot_stopped = tokio::time::timeout(Duration::from_secs(1), fresh.receive()) + .await + .is_ok_and(|v| v.is_err()); + tcp_stopped && uot_stopped + } else { + false + }; + let evidence = outcome.map(|(evidence, tcp, fresh)| { + drop((tcp, fresh)); + evidence + }); + ( + evidence, + stopped_reads, + stop_elapsed, + probe.snapshot().is_idle(), + ) + }) + .await; + for endpoint in &endpoints { + endpoint.close(0_u8.into(), b""); + } + peer_stop.cancel(); + let mut peers_joined = true; + for peer in peers { + peers_joined &= matches!(peer.await, Ok(Ok(()))); + } + let mut endpoints_idle = true; + for endpoint in &endpoints { + endpoints_idle &= tokio::time::timeout(Duration::from_secs(2), endpoint.wait_idle()) + .await + .is_ok(); + } + drop((endpoints, outbound, paths)); + Case { + mode, + evidence, + stopped_reads, + stop_elapsed, + probe_idle, + peers_joined, + endpoints_idle, + } +} + +#[tokio::test] +async fn tuic_uot_lane_reuses_each_class_retires_with_old_owners_and_joins_stop() { + // Both modes complete and stop before the first verdict, including RED. + let cases = [case("native").await, case("quic").await]; + for case in cases { + assert!(case.peers_joined && case.endpoints_idle, "{case:?}"); + assert!(case.probe_idle && case.stopped_reads, "{case:?}"); + assert!(case.stop_elapsed < Duration::from_secs(2), "{case:?}"); + let evidence = case.evidence.as_ref().expect("completed memory exchange"); + assert_eq!( + evidence.tags, + [0, 1, 1, 1, 0, 2, 1, 0, 1], + "mode={}", + case.mode + ); + assert_eq!(evidence.pools_before_retirement, 2); + assert_eq!(evidence.pools_with_retired, 3); + assert_eq!(evidence.pools_with_one_old_owner, 3); + assert_eq!(evidence.pools_after_old_owners, 2); + assert_eq!(evidence.remaining_paths, 0); + } +}