Add HTTP JavaScript rewriting and optimize proxy transports (#9)

* Add HTTP JavaScript processing and shared inbound handling

* Optimize HTTP rewriting and proxy transport paths

* Update the Boring dependency to 5.5.1

* Restore resource limit and production lint checks

* Prune duplicate tests and stale validation notes

* Align TUN bridge tests and Apple diagnostics

* Scope the diagnostic timing reference to its caller

* Replace draining HTTP/2 upstream sessions

* Stabilize rule matching budget tests

* Match non-exhaustive H3 cancellation errors

* Run a smaller CI matrix on pull requests
This commit is contained in:
yiguodev
2026-11-20 13:41:53 +08:00
committed by GitHub
parent f870ffe454
commit 3288448fe2
240 changed files with 63467 additions and 1692 deletions
+5
View File
@@ -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
+214
View File
@@ -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
+3
View File
@@ -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: |
+24 -25
View File
@@ -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.
+13 -3
View File
@@ -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
Generated
+437 -7
View File
@@ -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"
+13 -6
View File
@@ -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" }
+1
View File
@@ -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.
+5
View File
@@ -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",
+12
View File
@@ -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.
+6
View File
@@ -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);
+85 -12
View File
@@ -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());
}
}
}
+20
View File
@@ -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);
+2
View File
@@ -8,6 +8,8 @@
mod client;
mod config;
mod device;
#[cfg(feature = "diagnostics")]
pub mod diagnostics;
mod echo;
mod icmp;
mod packet;
@@ -0,0 +1,108 @@
use super::*;
use futures_util::task::noop_waker;
use std::{future::Future, task::Context};
fn fixture() -> (PacketSink, mpsc::Receiver<Packet>, 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);
}
}
+5
View File
@@ -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;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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"
);
}
+63 -52
View File
@@ -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<u8> = (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<u8> = (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]
+13 -30
View File
@@ -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 边界。
@@ -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 完成不能代替真实结束。
+2 -2
View File
@@ -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。
+84 -5
View File
@@ -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)
+20 -10
View File
@@ -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;入口认证和用户名语义保持。
+16
View File
@@ -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;空路径与 `-` 拒绝。
+83 -22
View File
@@ -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)。
+48 -19
View File
@@ -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)。
+7 -9
View File
@@ -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 工程维护。
+1
View File
@@ -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 来源 |
+9 -12
View File
@@ -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 的系统网络
+18 -1
View File
@@ -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 对齐
+26 -9
View File
@@ -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 保持。
+1
View File
@@ -1,5 +1,6 @@
module LibVole {
header "vole.h"
link "c++"
link framework "JavaScriptCore"
export *
}
+4 -2
View File
@@ -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` 交叉工具链。
+101
View File
@@ -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()
+88
View File
@@ -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)
+38 -19
View File
@@ -47,6 +47,8 @@ pub(crate) struct DecisionBudget {
work: u64,
backtracks: usize,
match_time: Duration,
#[cfg(test)]
fixed_match_duration: Option<Duration>,
failure: Option<MatchFailure>,
cancellation: Vec<CancellationToken>,
deadline: Option<Instant>,
@@ -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<F: std::future::Future>(&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]+(?<!private)\.test$", "edge.public.test"),
@@ -740,37 +755,29 @@ mod tests {
),
] {
let regex = DomainRegex::new(pattern).unwrap();
assert!(
regex
.match_bounded(domain, &mut DecisionBudget::new(), None)
.unwrap()
);
assert_eq!(regex.is_match(domain, &decision), Ok(true), "{pattern}");
assert_eq!(regex, regex.clone());
assert_eq!(format!("{regex:?}"), "DomainRegex { .. }");
}
assert!(
assert_eq!(
DomainRegex::new("")
.unwrap()
.is_match("api.test", &Default::default())
.unwrap()
.is_match("api.test", &decision),
Ok(true)
);
let fast = DomainRegex::new(r"(?i)^cdn[0-9]+\.test$").unwrap();
assert!(matches!(fast.0.engine, Engine::Linear(_)));
assert!(
fast.match_bounded("CDN7.test", &mut DecisionBudget::new(), None)
.unwrap()
);
assert!(
!fast
.match_bounded("other.test", &mut DecisionBudget::new(), None)
.unwrap()
);
assert_eq!(fast.is_match("CDN7.test", &decision), Ok(true));
assert_eq!(fast.is_match("other.test", &decision), Ok(false));
}
#[test]
fn domain_decision_budget_is_shared_sticky_and_cancelled() {
let regex = DomainRegex::new(r"(?=api)api\.test$").unwrap();
let mut budget = DecisionBudget::new();
budget.backtracks = 2 * (CALL_BACKTRACKS + 1);
let mut budget = DecisionBudget {
backtracks: 2 * (CALL_BACKTRACKS + 1),
fixed_match_duration: Some(Duration::ZERO),
..DecisionBudget::new()
};
assert!(regex.match_bounded("api.test", &mut budget, None).unwrap());
assert!(regex.match_bounded("api.test", &mut budget, None).unwrap());
assert_eq!(
@@ -802,4 +809,16 @@ mod tests {
.is_err()
);
}
#[test]
fn elapsed_match_budget_accumulates_and_stays_exhausted() {
let mut budget = DecisionBudget::new();
assert_eq!(budget.finish(Duration::from_millis(1), None), Ok(()));
assert_eq!(budget.finish(Duration::from_millis(1), None), Ok(()));
assert_eq!(
budget.finish(Duration::from_nanos(1), None),
Err(MatchFailure::Budget)
);
assert_eq!(budget.visit(None), Err(MatchFailure::Budget));
}
}
+817
View File
@@ -446,3 +446,820 @@ mod realm_tests {
assert!(files.inline_node(&mut source["proxies"][0]).is_err());
}
}
#[cfg(all(
test,
feature = "inbound-http",
any(
feature = "outbound-http",
feature = "outbound-socks5",
feature = "outbound-vmess",
feature = "outbound-trojan",
feature = "outbound-anytls",
feature = "outbound-hysteria2",
feature = "outbound-tuic",
feature = "outbound-vless"
)
))]
mod http_reuse_security_memory_tests {
use super::{IdentityFileOrigin, PairStamp};
#[cfg(feature = "outbound-vmess")]
use crate::outbound::vmess::VmessOutbound;
use crate::{
config::{StaticEchConfig, TlsIdentityPem},
security::SecurityContext,
};
#[cfg(any(
feature = "outbound-http",
feature = "outbound-socks5",
feature = "outbound-vmess",
feature = "outbound-trojan",
feature = "outbound-hysteria2",
feature = "outbound-tuic"
))]
use crate::{
dialer::Dialer,
outbound::{OutboundConnector, UpstreamPath},
};
use std::{path::PathBuf, sync::Arc};
fn identity() -> 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<TlsIdentityPem>,
ech: Option<StaticEchConfig>,
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<TlsIdentityPem>,
ech: Option<StaticEchConfig>,
security: &SecurityContext,
) -> std::io::Result<crate::outbound::Socks5Outbound> {
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<TlsIdentityPem>,
ech: Option<StaticEchConfig>,
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<TlsIdentityPem>,
ech: Option<StaticEchConfig>,
) -> 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<dyn OutboundConnector>)> {
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<dyn OutboundConnector>,
),
#[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<dyn OutboundConnector>,
),
]
}
#[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<TlsIdentityPem>,
ech: Option<StaticEchConfig>,
profile: Option<crate::config::ClientFingerprint>,
) -> 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<crate::outbound::ConnectedStream, crate::dispatch::DispatchError>
{
panic!("a structural query must not open opaque IO")
}
async fn open_datagram(
&self,
_: crate::outbound::DatagramRequest,
_: &crate::outbound::EstablishContext,
) -> std::result::Result<
Box<dyn crate::dispatch::DatagramTransport>,
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());
}
}
+8 -5
View File
@@ -170,8 +170,11 @@ pub(crate) fn uid_ranges(payload: &str) -> Result<Vec<UidRange>> {
#[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);
+10 -1
View File
@@ -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;
+289
View File
@@ -19,10 +19,148 @@ impl<T> AsyncStream for T where T: AsyncRead + AsyncWrite + Unpin + Send {}
pub type BoxStream = Box<dyn AsyncStream>;
/// 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<dyn std::any::Any + Send + Sync>,
equal: fn(&dyn std::any::Any, &dyn std::any::Any) -> bool,
generation: Option<Arc<dyn std::any::Any + Send + Sync>>,
}
#[cfg(feature = "inbound-http")]
impl HttpTcpReuseKey {
pub(crate) fn new<T: Eq + Send + Sync + 'static>(value: T) -> Self {
fn equal<T: Eq + 'static>(a: &dyn std::any::Any, b: &dyn std::any::Any) -> bool {
a.downcast_ref::<T>()
.zip(b.downcast_ref::<T>())
.is_some_and(|(a, b)| a == b)
}
Self {
value: Arc::new(value),
equal: equal::<T>,
generation: None,
}
}
pub(crate) fn with_generation<T: Send + Sync + 'static>(mut self, generation: Arc<T>) -> 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<Self>) -> Result<BoxStream, DispatchError>;
}
/// One owned send operation; its owner must cancel or complete it before close.
pub type OwnedDatagramSend =
Pin<Box<dyn std::future::Future<Output = Result<(), DispatchError>> + 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<Box<dyn std::future::Future<Output = io::Result<usize>> + 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<std::net::SocketAddr> {
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<TunPendingSend, Datagram> {
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<Datagram>,
) -> Result<OwnedDatagramBatchSend, Vec<Datagram>> {
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<Option<Box<dyn HttpTcpPlan>>, DispatchError> {
Ok(None)
}
#[cfg(feature = "inbound-http")]
#[doc(hidden)]
fn http_context(&self) -> Option<crate::http_processing::HttpContext> {
@@ -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<Option<Box<dyn HttpTcpPlan>>, 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<dyn HttpTcpPlan>
}))
}
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<Option<Box<dyn HttpTcpPlan>>, 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<dyn HttpTcpPlan>
}))
}
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<dyn HttpTcpPlan>,
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<Self>) -> Result<BoxStream, DispatchError> {
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<dyn Dispatcher>,
@@ -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<TunPendingSend, Datagram> {
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<Datagram>,
) -> Result<OwnedDatagramBatchSend, Vec<Datagram>> {
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<Pin<Box<dyn Dispatcher>>> = 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::{
+48
View File
@@ -91,6 +91,14 @@ struct Bounded {
observation: Option<crate::resources::observation::Guard>,
}
#[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<super::TunPendingSend, Datagram> {
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<Datagram>,
) -> Result<super::OwnedDatagramBatchSend, Vec<Datagram>> {
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);
@@ -0,0 +1,84 @@
use super::*;
use bytes::Bytes;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
struct PhysicalBoundary {
calls: Arc<AtomicUsize>,
closes: Arc<AtomicUsize>,
}
#[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<Datagram>,
) -> Result<super::super::OwnedDatagramBatchSend, Vec<Datagram>> {
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<Datagram, DispatchError> {
panic!("batch boundary only")
}
async fn close(&mut self) -> Result<(), DispatchError> {
self.closes.fetch_add(1, Ordering::Relaxed);
Ok(())
}
}
fn packets(length: usize) -> Vec<Datagram> {
(0..2)
.map(|_| Datagram {
remote: "192.0.2.1:443"
.parse::<std::net::SocketAddr>()
.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::<std::net::SocketAddr>()
.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);
}
@@ -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);
}
@@ -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<Option<Vec<u8>>>,
}
pub(crate) struct Packets {
pub(crate) probe: Arc<Probe>,
pub(crate) accept: bool,
pub(crate) budget: DatagramBudget,
completion: Option<TunSendToken>,
}
impl Packets {
pub(crate) fn new(probe: Arc<Probe>) -> 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<TunPendingSend, Datagram> {
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<Datagram, DispatchError> {
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);
}
+35
View File
@@ -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);
}
File diff suppressed because it is too large Load Diff
+570 -12
View File
@@ -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<usize> {
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<usize> {
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<Self> {
if input > MAX_BODY || output > MAX_BODY {
return None;
}
let vector = std::mem::size_of::<Vec<u16>>();
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<usize> {
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<Inner>);
@@ -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<Reservation> {
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<Self> {
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<u8>,
// 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<u8>),
#[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<MappedDropWitness>,
}
#[cfg(all(test, unix, feature = "inbound-http"))]
struct MappedDropWitness {
budget: Budget,
observed_used: Arc<AtomicUsize>,
}
#[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<Reservation> {
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<usize> {
capacity.checked_add(std::mem::size_of::<Self>())
}
pub(crate) fn new(budget: &Budget, capacity: usize) -> Option<Self> {
let bytes = capacity.checked_add(std::mem::size_of::<Self>())?;
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<Self> {
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<Self> {
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<Vec<u8>> {
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<Self> {
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> {
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<Self> {
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<memmap2::MmapMut>,
vector: impl FnOnce(usize) -> Option<Vec<u8>>,
) -> Option<Self> {
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<Self> {
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<usize>,
) -> 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::<Vec<u16>>();
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;
@@ -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<AtomicUsize> {
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");
}
@@ -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);
}
@@ -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<AtomicUsize>,
observed: Arc<tokio::sync::Notify>,
}
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<Option<Result<hyper::body::Frame<Bytes>, 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<BoxStream, DispatchError> {
Err(DispatchError::NotAllowed)
}
async fn open_datagram(
&self,
_: DatagramSession,
) -> Result<Box<dyn DatagramTransport>, 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>(_: E) -> io::Error {
failed()
}
fn origin_pair(
stop: CancellationToken,
incomplete: Arc<tokio::sync::Notify>,
received: Arc<AtomicUsize>,
phase: Arc<AtomicUsize>,
) -> (BoxStream, JoinHandle<io::Result<()>>) {
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<Pin<Box<dyn Future<Output = io::Result<()>> + 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<Box<dyn Future<Output=io::Result<()>> + 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<AtomicUsize>; 2] =
std::array::from_fn(|_| Arc::new(AtomicUsize::new(0)));
let mut tasks: Vec<JoinHandle<io::Result<()>>> = 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<AtomicUsize>,
}
impl DropOwnedIo {
fn new(io: tokio::io::DuplexStream, live: &Arc<AtomicUsize>) -> 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<io::Result<()>> {
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<io::Result<usize>> {
Pin::new(&mut self.io).poll_write(cx, bytes)
}
fn poll_flush(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut std::task::Context<'_>,
) -> Poll<io::Result<()>> {
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<AtomicUsize>,
) -> (BoxStream, JoinHandle<io::Result<()>>) {
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<Target> {
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<u64>) -> 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<JoinHandle<io::Result<()>>> = 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:?}");
}
+22 -1
View File
@@ -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<Document>,
pub(super) rules: Arc<[Rule]>,
pub(crate) scripts: Arc<[CompiledScript]>,
pub(super) payloads: BTreeMap<String, Arc<Payload>>,
pub(super) identity: [u8; 32],
pub(super) origins: Box<[SourceLocation]>,
@@ -84,6 +86,7 @@ impl PolicyCandidate {
material: Option<&CaMaterial>,
) -> io::Result<Arc<Policy>> {
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<Document>,
candidate: Option<Arc<PolicyCandidate>>,
scripts_backend_ready: bool,
#[cfg(feature = "inbound-http")]
mitm: Option<Arc<super::mitm::Mitm>>,
}
@@ -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<super::body_budget::Budget> =
+912
View File
@@ -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<Counter> {
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<String, Value> = COUNTERS
.iter()
.zip(&self.counters)
.map(|(key, value)| ((*key).into(), load(value).into()))
.collect();
let timings: Map<String, Value> = TIMINGS
.iter()
.zip(&self.timings)
.map(|(key, value)| ((*key).into(), value.snapshot()))
.collect();
let stages: Map<String, Value> = 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<String, Value> = BODY_POINTS
.iter()
.zip(&self.bypasses)
.map(|(point, values)| {
let reasons: Map<String, Value> = 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
));
}
}
}
+21 -3
View File
@@ -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<Arc<PolicyCandidate>> {
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;
+142
View File
@@ -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
);
}
+311 -16
View File
@@ -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<R: AsyncBufRead + Unpin, W: AsyncWrite + Unpin>(
&self,
reader: &mut R,
writer: &mut W,
request: &RequestHead,
session: StreamSession,
mut session: StreamSession,
scheme: Scheme,
config: &HttpServerConfig,
scope: (&HttpServerConfig, &CancellationToken),
upstream: &mut Option<server::UpstreamSlot>,
) -> io::Result<bool> {
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<W: AsyncWrite + Unpin>(
writer: &mut W,
local: super::script_message::LocalResponse,
idle: Duration,
) -> io::Result<bool> {
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<Url> {
let mut hosts = request
.headers
+372 -3
View File
@@ -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<Option<PreparedBody>>,
pub(crate) scripts: Option<ScriptContext>,
}
impl Message<'_> {
@@ -37,6 +53,14 @@ impl Message<'_> {
plan: &mut RequestPlan,
config: &HttpServerConfig,
) -> io::Result<PreparedBody> {
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<u64> {
}
}
// 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<W: AsyncWrite + Unpin> AsyncWrite for FinalFlushProbe<'_, W> {
fn poll_write(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
bytes: &[u8],
) -> Poll<io::Result<usize>> {
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<io::Result<usize>> {
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<io::Result<()>> {
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<io::Result<()>> {
Pin::new(&mut *self.writer).poll_shutdown(cx)
}
}
pub(crate) struct PreparedBody {
framing: Body,
cursor: Option<Cursor>,
prefix: Option<BudgetedBytes>,
result: Option<body::ResultBody>,
buffered: Option<Bytes>,
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<String>,
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<R: AsyncBufRead + Unpin, W: AsyncWrite + Unpin>(
self,
reader: &mut R,
@@ -173,11 +362,36 @@ impl PreparedBody {
blocklist: &HashSet<String>,
dechunk: bool,
) -> io::Result<()> {
self.transfer_with_origin(reader, writer, idle, blocklist, dechunk)
.await
.map(|_| ())
}
pub(crate) async fn transfer_with_origin<R: AsyncBufRead + Unpin, W: AsyncWrite + Unpin>(
self,
reader: &mut R,
writer: &mut W,
idle: Duration,
blocklist: &HashSet<String>,
dechunk: bool,
) -> io::Result<bool> {
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<R: AsyncBufRead + Unpin>(
reader: &mut R,
framing: Body,
blocklist: &HashSet<String>,
idle: Duration,
transaction: Option<Transaction<'_>>,
fields: &mut Fields,
) -> io::Result<(PreparedBody, Option<body::Entity>)> {
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<R: AsyncBufRead + Unpin>(
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<R: AsyncBufRead + Unpin>(
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<R: AsyncBufRead + Unpin>(
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<super::super::rules::Rule> {
let value: serde_yaml_ng::Value =
serde_yaml_ng::from_str("{url: '.', action: response-body-set, value: changed}")
+561 -185
View File
@@ -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<Bytes>),
Shared {
lease: &'a h2_reuse::Lease,
sender: h2::client::SendRequest<Bytes>,
},
}
// 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<u64>,
asterisk: bool,
script: Option<ScriptExchange>,
}
struct ScriptExchange {
original: OriginalSnapshot,
request: Option<RequestSnapshot>,
cancellation: CancellationToken,
}
struct BodyMessage {
phase: Phase,
wire: Option<WireBodyMeta>,
expected: Option<u64>,
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<h2::RecvStream>,
response: h2::server::SendResponse<Bytes>,
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<h2::RecvStream>,
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<u64>)> {
) -> io::Result<(h2_body::Source, Option<u64>, Option<Entity>)> {
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<Vec<u8>>)> {
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<Box<dyn HttpTcpPlan>>,
deadline: Instant,
) -> io::Result<(BoxStream, Option<Vec<u8>>)> {
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<h2_body::Source>,
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<Bytes>,
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<D, E, T, X>(driver: D, exchange: E) -> io::Result<T>
where
D: Future<Output = Result<(), X>>,
@@ -683,3 +1055,7 @@ fn original_url(request: &Request<h2::RecvStream>) -> 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;
+163 -2
View File
@@ -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<HeaderMap>) -> Self {
pub(super) fn buffered(data: Bytes, trailers: Option<HeaderMap>) -> 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<u64>) -> 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<u64>,
}
pub(super) struct SharedPrepared {
pub(super) source: Source,
pub(super) expected: Option<u64>,
pub(super) entity: Option<Entity>,
}
pub(super) async fn prepare_shared(
mut source: Source,
mut transaction: Transaction<'_>,
expected: Option<u64>,
strip_credentials: bool,
fields: &mut headers::Fields,
) -> io::Result<SharedPrepared> {
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<Bytes>,
expected: Option<u64>,
strip_credentials: bool,
finished: tokio::sync::oneshot::Sender<()>,
}
pub(super) struct RequestUpload(Option<PendingUpload>);
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<Bytes>,
request: http::Request<()>,
source: Source,
expected: Option<u64>,
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},
+499
View File
@@ -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<Vec<u8>>,
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<Mutex<DuplexStream>>,
trace: Arc<Trace>,
write_pending: bool,
flush_pending: bool,
}
impl ShortIo {
fn new(io: Arc<Mutex<DuplexStream>>, trace: &Arc<Trace>) -> 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<io::Result<()>> {
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<io::Result<usize>> {
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<io::Result<()>> {
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<io::Result<()>> {
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<Bytes>,
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<JoinHandle<io::Result<()>>>,
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::<Vec<_>>(),
);
let text = (0..header_len)
.map(|i| 33 + ((i * 73 + i / 29) % 94) as u8)
.collect::<Vec<_>>();
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:?}");
}
-7
View File
@@ -169,10 +169,3 @@ impl Body for Upload {
hint
}
}
pub(super) async fn download(
body: h2_body::Source,
target: h2::SendStream<Bytes>,
expected: Option<u64>,
) -> io::Result<()> {
h2_body::relay(body, target, expected, false).await
}
+27
View File
@@ -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 {
@@ -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<AtomicUsize>,
writes: Option<Arc<Mutex<WireWrites>>>,
data: Option<Arc<ClientData>>,
}
#[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<usize>,
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<DataSnapshot> {
self.error
.map_or(Ok(self.snapshot), |message| Err(failed(message)))
}
}
struct ClientData {
frames: Mutex<DataFrames>,
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<DataSnapshot> {
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<u8>,
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<AtomicUsize>) -> 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<io::Result<()>> {
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<io::Result<usize>> {
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<io::Result<usize>> {
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<io::Result<()>> {
Pin::new(&mut self.inner).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.inner).poll_shutdown(cx)
}
}
fn failed(message: &'static str) -> io::Error {
io::Error::other(message)
}
async fn joined<T>(mut owner: tokio::task::JoinHandle<T>) -> Result<T, String> {
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<u32>,
concurrent: Option<u32>,
frame: Option<u32>,
}
async fn read_advertised(client: &mut CountedIo) -> io::Result<Advertised> {
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<AtomicUsize>,
}
impl Drop for PendingPlan {
fn drop(&mut self) {
self.live.fetch_sub(1, Ordering::AcqRel);
}
}
struct HeldDispatcher {
live: Arc<AtomicUsize>,
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<Option<Box<dyn crate::dispatch::HttpTcpPlan>>, 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<BoxStream, DispatchError> {
self.physical_calls.fetch_add(1, Ordering::AcqRel);
Err(DispatchError::NotAllowed)
}
async fn open_datagram(
&self,
_: DatagramSession,
) -> Result<Box<dyn DatagramTransport>, 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");
}
@@ -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<AtomicUsize>,
}
impl CountedIo {
fn new(io: DuplexStream, live: &Arc<AtomicUsize>) -> 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<io::Result<()>> {
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<io::Result<usize>> {
Pin::new(&mut self.io).poll_write(cx, bytes)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_shutdown(cx)
}
}
fn error<E>(_error: E) -> io::Error {
failed()
}
struct Pair {
sender: h2::client::SendRequest<Bytes>,
client: h2::client::Connection<CountedIo, Bytes>,
server: h2::server::Connection<CountedIo, Bytes>,
}
impl Pair {
async fn new(live: &Arc<AtomicUsize>) -> io::Result<Self> {
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::RecvStream>, h2::server::SendResponse<Bytes>)> {
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<F: Future>(&mut self, work: F) -> io::Result<F::Output> {
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<u64>,
headers_eos: bool,
expected_error: Option<io::ErrorKind>,
}
async fn collect(mut body: h2::RecvStream, expected: &[u8]) -> io::Result<Option<HeaderMap>> {
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<Value> {
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<Value> {
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}");
}
}
+338
View File
@@ -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<Box<dyn Future<Output = Result<(), h2::Error>> + Send + 'static>>;
type OwnedDriver = Pin<Box<dyn Future<Output = ()> + 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<Bytes>, 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<Self> {
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<Arc<State>>);
impl Drop for Provisional {
fn drop(&mut self) {
if let Some(state) = &self.0 {
state.retire();
}
}
}
struct DriverEnd {
driver: Option<Driver>,
state: Arc<State>,
}
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<State>,
accepted: oneshot::Sender<()>,
}
struct Slot {
identity: Identity,
sender: h2::client::SendRequest<Bytes>,
state: Arc<State>,
}
impl Slot {
async fn admit(&self, deadline: Instant) -> io::Result<Option<Acquired>> {
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<State>,
}
impl Lease {
fn new(state: &Arc<State>) -> io::Result<Self> {
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<Bytes>,
},
H1(BoxStream),
}
/// Never escapes this serve_h2's fixed HttpContext/security scope.
pub(super) struct Sessions {
slot: Mutex<Option<Slot>>,
registrations: mpsc::Sender<Registration>,
}
/// All registered drivers remain inline in this parent, including while idle.
pub(super) struct Parent {
registrations: mpsc::Receiver<Registration>,
drivers: FuturesUnordered<OwnedDriver>,
}
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<F, O>(
&self,
identity: Identity,
connect_deadline: Instant,
open: F,
) -> io::Result<Acquired>
where
F: FnOnce() -> O,
O: Future<Output = io::Result<(BoxStream, Option<Vec<u8>>)>>,
{
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<serde_json::Value> {
validation::run()
}
#[cfg(test)]
#[path = "https_h2_reuse_memory_tests.rs"]
mod integration_tests;
+753
View File
@@ -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<AtomicUsize>,
}
impl CountedIo {
fn new(io: DuplexStream, live: &Arc<AtomicUsize>) -> 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<io::Result<()>> {
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<io::Result<usize>> {
Pin::new(&mut self.io).poll_write(cx, bytes)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
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<E>(_error: E) -> io::Error {
failed()
}
struct Fixture {
client: StdMutex<Option<BoxStream>>,
peer: Option<CountedIo>,
live_io: Arc<AtomicUsize>,
opens: AtomicUsize,
budget: Budget,
last_slice: Arc<StdMutex<Option<Bytes>>>,
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<Vec<u8>>)> {
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<Output = io::Result<usize>> + 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<Bytes>) -> 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<Value> {
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<Value> {
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::<Arc<State>>);
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<Value> {
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<Value> {
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<Value> {
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<Value> {
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<AtomicUsize>,
}
impl AsyncRead for MeteredIo {
fn poll_read(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
buf: &mut ReadBuf<'_>,
) -> Poll<io::Result<()>> {
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<io::Result<usize>> {
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<io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_shutdown(cx)
}
}
type ProbeClient = h2::client::Connection<MeteredIo, Bytes>;
type ProbeServer = h2::server::Connection<MeteredIo, Bytes>;
struct SendReceiver {
response: h2::client::ResponseFuture,
body: Option<h2::RecvStream>,
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<Value> {
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<Value> {
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}),
)
}
+357
View File
@@ -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<Vec<u8>> {
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::<serde_json::Value>(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#"
@@ -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<Authority>,
scope: Arc<()>,
alpn: Option<&'static [u8]>,
reply: Reply,
reject: AtomicBool,
prepares: AtomicUsize,
opens: AtomicUsize,
accepts: Arc<AtomicUsize>,
live: Arc<AtomicUsize>,
heads: Arc<Mutex<Vec<String>>>,
uploads: Arc<Mutex<Vec<Vec<u8>>>>,
sni: Arc<Mutex<Vec<String>>>,
negotiated: Arc<Mutex<Vec<Option<Vec<u8>>>>>,
sessions: Mutex<Vec<StreamSession>>,
peers: Mutex<Vec<JoinHandle<()>>>,
partial: Arc<tokio::sync::Notify>,
#[cfg(feature = "outbound-shadowsocks")]
obfs: Mutex<Option<Arc<crate::outbound::MemoryObfsFactory>>>,
#[cfg(feature = "outbound-vmess")]
vmess_http_cover: Mutex<Option<Arc<crate::outbound::MemoryVmessHttpCoverFactory>>>,
}
#[derive(Clone)]
struct MemoryTls(Arc<State>);
// 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<Self>) -> Result<BoxStream, DispatchError> {
let Self {
origin, session, ..
} = *self;
origin.open(session).await
}
}
struct OwnedClient {
io: BoxStream,
live: Arc<AtomicUsize>,
}
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<io::Result<()>> {
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<io::Result<usize>> {
Pin::new(&mut self.io).poll_write(cx, bytes)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
Pin::new(&mut self.io).poll_shutdown(cx)
}
}
#[async_trait]
impl Dispatcher for MemoryTls {
async fn prepare_http_tcp(
&self,
session: StreamSession,
) -> Result<Option<Box<dyn HttpTcpPlan>>, 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<BoxStream, DispatchError> {
self.open(session).await
}
async fn open_datagram(
&self,
_: DatagramSession,
) -> Result<Box<dyn DatagramTransport>, DispatchError> {
Err(DispatchError::NotAllowed)
}
}
type AcceptedMemoryPeer = Pin<Box<dyn std::future::Future<Output = io::Result<BoxStream>> + 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<BoxStream, DispatchError> {
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::<usize>().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<tokio::io::DuplexStream>,
cancellation: CancellationToken,
serving: JoinHandle<io::Result<()>>,
}
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<T>(mut task: JoinHandle<T>) -> Result<T, String> {
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<u8>)> {
request_fields(running, authority, path, "").await
}
async fn request_fields(
running: &mut Running,
authority: &str,
path: &str,
fields: &str,
) -> io::Result<(String, Vec<u8>)> {
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<u8>)>, 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<u8>)> {
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<String> = (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")
}));
}
@@ -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<AtomicUsize>,
tasks: Mutex<Vec<JoinHandle<()>>>,
relays: Arc<Mutex<Vec<JoinHandle<()>>>>,
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<ConnectedStream, DispatchError> {
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<Box<dyn DatagramTransport>, 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<SingMuxConnector>,
scope: Arc<()>,
probe: ResourceProbe,
}
struct MuxPlan {
node: Arc<SingMuxConnector>,
session: StreamSession,
key: Option<HttpTcpReuseKey>,
probe: ResourceProbe,
}
#[async_trait]
impl HttpTcpPlan for MuxPlan {
fn reuse_key(&self) -> Option<&HttpTcpReuseKey> {
self.key.as_ref()
}
async fn connect(self: Box<Self>) -> Result<BoxStream, DispatchError> {
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<Option<Box<dyn HttpTcpPlan>>, 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<BoxStream, DispatchError> {
self.node
.connect_stream(session, &EstablishContext::default())
.await
.map(|stream| stream.io)
}
async fn open_datagram(
&self,
_: DatagramSession,
) -> Result<Box<dyn DatagramTransport>, 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;
}
@@ -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<io::Result<()>, String>,
failures: Vec<String>,
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<MemoryObfsFactory>, reply: Reply) {
run_with_factory_options(factory, reply, "", false).await;
}
#[cfg(target_vendor = "apple")]
pub(super) async fn run_scripted_with_factory(factory: Arc<MemoryObfsFactory>, extra: &str) {
run_with_factory_options(factory, Reply::Persistent, extra, true).await;
}
fn response_witness(result: io::Result<(String, Vec<u8>)>, 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<MemoryObfsFactory>,
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;
}
}
}
@@ -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"
);
}
}
@@ -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<io::Result<()>, String>,
failures: Vec<String>,
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<String>,
uploads: Vec<Vec<u8>>,
sni: Vec<String>,
negotiated: Vec<Option<Vec<u8>>>,
}
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<u8>)>, 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;
}
}
File diff suppressed because it is too large Load Diff
@@ -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<MemoryObfsFactory>, mode: PostReply) {
run_with_factory_options(factory, mode, "", false).await;
}
#[cfg(target_vendor = "apple")]
pub(super) async fn run_scripted_with_factory(factory: Arc<MemoryObfsFactory>, extra: &str) {
run_with_factory_options(factory, PostReply::Complete, extra, true).await;
}
async fn run_with_factory_options(
factory: Arc<MemoryObfsFactory>,
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;
}
}
}
@@ -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"
);
}
}
@@ -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;
}
}
+425
View File
@@ -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<Vec<StreamSession>>,
heads: Mutex<Vec<String>>,
live_at_connect: Mutex<Vec<usize>>,
live: Arc<AtomicUsize>,
tasks: Mutex<Vec<tokio::task::JoinHandle<()>>>,
}
#[derive(Clone, Default)]
struct FixedOrigin {
recorded: Arc<Recorded>,
sniff: Option<Arc<crate::sniffing::Policy>>,
}
struct StreamOwner {
io: DuplexStream,
live: Arc<AtomicUsize>,
}
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<std::io::Result<()>> {
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<std::io::Result<usize>> {
Pin::new(&mut self.io).poll_write(cx, buf)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<std::io::Result<()>> {
Pin::new(&mut self.io).poll_flush(cx)
}
fn poll_shutdown(
mut self: Pin<&mut Self>,
cx: &mut TaskContext<'_>,
) -> Poll<std::io::Result<()>> {
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<Self>) -> Result<BoxStream, DispatchError> {
self.origin.connect_tcp(self.session).await
}
}
#[async_trait]
impl Dispatcher for FixedOrigin {
async fn sniff_plan(
&self,
source: SocketAddr,
destination: &Destination,
) -> Result<Option<crate::sniffing::Plan>, 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<Option<Box<dyn HttpTcpPlan>>, 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<BoxStream, DispatchError> {
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<Box<dyn DatagramTransport>, DispatchError> {
Err(DispatchError::NotAllowed)
}
}
async fn join_owned<T>(mut task: tokio::task::JoinHandle<T>) -> Result<T, String> {
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<DuplexStream>,
CancellationToken,
tokio::task::JoinHandle<std::io::Result<()>>,
) {
start_with_policy(origin, Policy::compile(policy).unwrap(), auth)
}
fn start_with_policy(
origin: &FixedOrigin,
policy: Arc<Policy>,
auth: bool,
) -> (
BufReader<DuplexStream>,
CancellationToken,
tokio::task::JoinHandle<std::io::Result<()>>,
) {
let fixed: Arc<dyn Dispatcher> = 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<dyn Dispatcher> = 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<DuplexStream>,
cancel: CancellationToken,
task: tokio::task::JoinHandle<std::io::Result<()>>,
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<DuplexStream>) -> std::io::Result<String> {
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}"
);
}
}
}
+3 -1
View File
@@ -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
+18 -1
View File
@@ -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;
@@ -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<Rule> {
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<BudgetedBytes> {
// 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<bool> {
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<Group> {
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<Group> {
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<Group> {
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",
"(?P<letter>a)(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<Group> {
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<Group> {
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<u128> {
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<T>(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<Group> {
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<Value> {
let mut groups = Vec::new();
for (id, expected, function) in [
(
"all-ascii-pairs",
ASCII_CASES,
ascii_pairs as fn(&Budget) -> io::Result<Group>,
),
("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"}),
)
}
+2
View File
@@ -168,6 +168,8 @@ impl Store {
cancellation: &CancellationToken,
force_refresh: bool,
) -> io::Result<Arc<PolicyCandidate>> {
check_cancel(cancellation)?;
document.http_scripts.prepare_platform(cancellation)?;
check_cancel(cancellation)?;
let paths = resolve_paths(&document, context, true)?;
if force_refresh {
@@ -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);
}
}
+25 -17
View File
@@ -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<Decision> {
@@ -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<Target> {
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::<IpAddr>() {
@@ -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 {
+37
View File
@@ -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<String> {
+33 -4
View File
@@ -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<str>),
Prefix(Box<str>),
Regex(Regex),
Regex(Arc<Regex>),
}
/// One native-selector builder profile, scoped to one candidate compilation.
#[derive(Default)]
pub(crate) struct SelectorCompiler {
regexes: BTreeMap<Box<str>, Arc<Regex>>,
}
impl SelectorCompiler {
fn regex(&mut self, pattern: &str) -> io::Result<Arc<Regex>> {
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(&regex));
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<Self> {
pub(crate) fn compile(raw: RawRule, total_text: &mut usize) -> io::Result<Self> {
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<Self> {
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()),
};
+316
View File
@@ -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<RawScript>,
}
#[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<Phase, D::Error> {
RawPhase::deserialize(deserializer).map(|phase| match phase {
RawPhase::Request => Phase::Request,
RawPhase::Response => Phase::Response,
})
}
fn serialize_phase<S: Serializer>(phase: &Phase, serializer: S) -> Result<S::Ok, S::Error> {
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<Vec<CompiledScript>> {
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<input.request.headers.length;i++){if(input.request.headers[i].name==='x-required'){found=true;}}if(!found){return {type:'pass'};}return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('a','b')}};}";
const RESPONSE_GUARD: &str = "function rewrite(input){let found=false;for(let i=0;i<input.response.headers.length;i++){if(input.response.headers[i].name==='x-required'){found=true;}}if(!found){return {type:'pass'};}return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('a','b')}};}";
const UNUSED_UNKNOWN: &str = "function rewrite(input){const ignored=JSON.parse('null');return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('a','b')}};}";
fn declaration(source: &str, body: BodyMode, phase: Phase) -> 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
);
}
}
+134
View File
@@ -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<Origin>) {
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<input.request.headers.length;i++) {
if(input.request.headers[i].name === "x-native") found=true;
}
if(!found) return {type:"abort"};
return {type:"respond",status:200,body:{kind:"text",data:"local-jsc"}};
}
"#,b"GET /a HTTP/1.1\r\nHost: old.invalid\r\nConnection: close\r\n\r\n").await;
assert!(response.starts_with("HTTP/1.1 200"), "{response}");
assert!(response.ends_with("\r\n\r\nlocal-jsc"), "{response}");
assert!(origin.sessions.lock().unwrap().is_empty());
}
#[tokio::test]
async fn response_native_then_scripts_preserve_success_before_invalid_output() {
let (response,origin)=exchange(r#"
rewrite:
enabled: true
rules:
- {url: '.', action: response-body-set, value: native}
http-scripts:
enabled: true
scripts:
- name: change
phase: response
url: '.'
body: text
source: 'function rewrite(input) {return {type:"modify",body:{kind:"text",data:input.body.data+":js"}};}'
- name: invalid
phase: response
url: '.'
body: text
source: 'function rewrite(input) {return {type:"modify",headers:[{op:"set",name:"Content-Length",values:["1"]}],body:{kind:"text",data:"bad"}};}'
- name: final
phase: response
url: '.'
source: 'function rewrite(input) {return {type:"modify",status:201,headers:[{op:"add",name:"x-final",values:["yes"]}]};}'
"#,b"GET /a HTTP/1.1\r\nHost: old.invalid\r\nConnection: close\r\n\r\n").await;
assert!(response.starts_with("HTTP/1.1 201"), "{response}");
assert!(
response.to_ascii_lowercase().contains("x-final: yes\r\n"),
"{response}"
);
assert!(response.ends_with("\r\n\r\nnative:js"), "{response}");
assert_eq!(origin.sessions.lock().unwrap().len(), 1);
}
#[tokio::test]
async fn request_url_scripts_match_u0_and_only_connect_the_final_target() {
let (response,origin)=exchange(r#"
rewrite:
enabled: true
rules:
- {url: 'http://old.invalid/', match: prefix, action: replace, replacement: 'http://middle.invalid/'}
http-scripts:
enabled: true
scripts:
- name: original
phase: request
url: 'http://old.invalid/'
match: prefix
source: 'function rewrite(input) {return {type:"modify",url:"http://final.invalid:8081/end",headers:[{op:"set",name:"Authorization",values:["Bearer final"]}]};}'
- name: should-not-match
phase: request
url: 'http://final.invalid:8081/'
match: prefix
source: 'function rewrite(input) {return {type:"abort"};}'
"#,b"GET /a HTTP/1.1\r\nHost: old.invalid\r\nAuthorization: old-secret\r\nCookie: old-cookie\r\nConnection: close\r\n\r\n").await;
assert!(response.ends_with("\r\n\r\nok"));
let sessions = origin.sessions.lock().unwrap();
assert_eq!(sessions.len(), 1);
assert_eq!(
sessions[0].destination,
Destination::domain("final.invalid", 8081).unwrap()
);
let heads = origin.heads.lock().unwrap();
assert!(heads[0].starts_with("GET /end HTTP/1.1"));
assert!(
heads[0]
.to_ascii_lowercase()
.contains("authorization: bearer final")
);
assert!(!heads[0].contains("old-secret"));
assert!(!heads[0].contains("old-cookie"));
}
File diff suppressed because it is too large Load Diff
@@ -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);
}
@@ -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<input.{array}.headers.length;i++){{if(input.{array}.headers[i].name==='x-check'&&input.{array}.headers[i].value==='中文😀'){{found=true;}}}}if(!found){{return {{type:'pass'}};}}return {{type:'modify',body:{{kind:'text',data:input.body.data.replaceAll('-', '_')}}}};}}"
)
}
fn message(phase: Phase, request: Fields, response: Fields, budget: &Budget) -> 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<u8>) {
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()
);
}
@@ -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);
}
@@ -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> {
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<Output = io::Result<Outcome>>>,
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);
}
File diff suppressed because it is too large Load Diff
@@ -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<AtomicBool>,
released_normally: Arc<AtomicBool>,
}
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<Option<TlsGate>> = 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);
}
File diff suppressed because it is too large Load Diff
@@ -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<String>,
}
pub(super) fn analyze(function: &Function<'_>) -> OutputBound {
let Some(parameter) = function.params.items.first() else {
return OutputBound::Maximum;
};
let BindingPattern::BindingIdentifier(parameter) = &parameter.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<String>,
bindings: BTreeMap<String, StringProof>,
writes: BTreeSet<String>,
root_strings: BTreeSet<String>,
audited_writes: BTreeSet<String>,
other_writes: BTreeSet<String>,
returns: Vec<StringProof>,
}
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<StringProof> {
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<StringProof> {
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<BTreeMap<String, &'b Expression<'a>>> {
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<input.response.headers.length;index++){if(input.response.headers[index].name==='anything')found=true;}const fields=Object.values(input);fields.push(input.body);fields.reverse();fields.pop();const ops=[];if(found)ops.push({op:'set',name:'x-any',values:['v']});JSON.stringify(input.response.headers);return {type:'modify',headers:ops,body:{kind:'text',data:input.body.data.replaceAll('u','v')}};}";
assert_eq!(
hint(source),
OutputBound::InputOrConstant {
maximum_literal_bytes: 0
}
);
}
#[test]
fn every_legal_unknown_or_unsafe_program_falls_back_without_rejection() {
for source in [
"function rewrite(input){let d=input.body.data;d='long';return {type:'modify',body:{kind:'text',data:d}};}",
"function rewrite(input){let d=input.body.data;const alias=d;d+='long';return {type:'modify',body:{kind:'text',data:alias}};}",
"function rewrite(input){let d=input.body.data;String(d='long');return {type:'modify',body:{kind:'text',data:d}};}",
"function rewrite(input){let d=input.body.data;d++;return {type:'modify',body:{kind:'text',data:d}};}",
"function rewrite(input){const d=input.body.data;{const d='long';return {type:'modify',body:{kind:'text',data:d}};}return {type:'pass'};}",
"function rewrite(input){const b=input.body;b.data='long';return {type:'modify',body:{kind:'text',data:input.body.data}};}",
"function rewrite(input){if(false)input.body['data']='long';return {type:'modify',body:{kind:'text',data:input.body.data}};}",
"function rewrite(input){for(let i=0;i<0;input.body.data='long'){}return {type:'modify',body:{kind:'text',data:input.body.data}};}",
"function rewrite(input){String(input.body.data='long');return {type:'modify',body:{kind:'text',data:input.body.data}};}",
"function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data,data:'long'}};}",
"function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data},body:{kind:'text',data:'long'}};}",
"function rewrite(input){return {type:'modify',type:'respond',body:{kind:'text',data:input.body.data}};}",
"function rewrite(input){const result={type:'modify',body:{kind:'text',data:input.body.data}};return result;}",
"function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.toUpperCase()}};}",
"function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('ab','cd')}};}",
"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('q','$')}};}",
"function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data.replaceAll('q','$&')}};}",
"function rewrite(input){return {type:'modify',body:{kind:'bytes',data:Uint8Array.from([1,2,3])}};}",
"function rewrite(input){if(input.phase)return {type:'pass'};}",
"function rewrite(input){return input;}",
"function rewrite(input){return;}",
] {
assert_eq!(
hint(source),
OutputBound::Maximum,
"unsafe hint for {source}"
);
}
}
#[test]
fn unsupported_public_syntax_stays_rejected_and_emitted_js_stays_identical() {
for source in [
"function rewrite(renamed){return {type:'modify',body:{kind:'text',data:renamed.body.data}};}",
"function rewrite(input){input={};return {type:'pass'};}",
"function rewrite(input){{let input={};}return {type:'pass'};}",
"function rewrite(input){Object.setPrototypeOf(input.body,{});return {type:'pass'};}",
"function rewrite(input){return {type:'modify',['body']:{kind:'text',data:input.body.data}};}",
] {
assert!(
super::super::compile_with_output_bound(source).is_err(),
"changed language acceptance: {source}"
);
}
let source = "function rewrite(input){return {type:'modify',body:{kind:'text',data:input.body.data}};}";
let (code, _) = super::super::compile_with_output_bound(source).unwrap();
assert_eq!(
code,
r#"function rewrite(input){"use strict";__voleTick();return __voleValue({"type":"modify","body":__voleValue({"kind":"text","data":__voleGet(__voleGet(input,"body"),"data")})});}"#
);
}
#[test]
fn optional_analysis_caps_and_raw_trusted_sources_default_to_maximum() {
let mut source = String::from("function rewrite(input){let ");
for index in 0..=MAX_PROOF_BINDINGS {
if index != 0 {
source.push(',');
}
source.push_str(&format!("item{index}"));
}
source.push_str(";return {type:'modify',body:{kind:'text',data:input.body.data}};}");
assert_eq!(hint(&source), OutputBound::Maximum);
// No initializers: 129 '=' operators would correctly exceed the
// existing lexical preflight cap before optional proof analysis.
// Uninitialized let bindings are valid and exceed only the proof cap.
let mut nodes = String::from("function rewrite(input){");
for _ in 0..=MAX_PROOF_NODES / 2 {
nodes.push_str("0;");
}
nodes.push_str("return {type:'pass'};}");
assert_eq!(hint(&nodes), OutputBound::Maximum);
let raw = crate::http_processing::scripts::CompiledSource {
code: "function rewrite(input){return {type:'pass'};}".into(),
..Default::default()
};
assert_eq!(raw.output_bound, OutputBound::Maximum);
assert_eq!(
raw.maximum_output_bytes(1),
super::super::super::super::body_budget::MAX_BODY
);
}
#[test]
fn an_unknown_future_call_cannot_inherit_a_previously_proved_output_hint() {
let source = "function rewrite(input){input.body.data.padEnd(100000,'q');return {type:'modify',body:{kind:'text',data:input.body.data}};}";
let allocator = oxc_allocator::Allocator::default();
let parsed =
oxc_parser::Parser::new(&allocator, source, oxc_span::SourceType::script()).parse();
assert!(parsed.diagnostics.is_empty());
let Statement::FunctionDeclaration(function) = &parsed.program.body[0] else {
panic!("expected test function");
};
assert_eq!(analyze(function), OutputBound::Maximum);
assert!(super::super::compile_with_output_bound(source).is_err());
}
}
+698
View File
@@ -0,0 +1,698 @@
//! Static finite-language preparation and a platform-owned execution adapter.
use std::{io, sync::Arc};
#[cfg(all(feature = "inbound-http", target_vendor = "apple"))]
mod apple;
#[cfg(feature = "inbound-http")]
mod frontend;
#[cfg(all(feature = "inbound-http", any(target_vendor = "apple", test)))]
mod platform_init;
#[cfg(all(feature = "inbound-http", target_vendor = "apple"))]
mod scoped_qos;
#[cfg(all(test, feature = "inbound-http", target_vendor = "apple"))]
mod tests;
#[cfg(all(
feature = "inbound-http",
feature = "http-diagnostics",
target_os = "tvos"
))]
pub(crate) mod plan_validation;
#[cfg(all(feature = "inbound-http", target_vendor = "apple"))]
mod static_literal_plan;
#[cfg(all(feature = "inbound-http", target_vendor = "apple"))]
static EXECUTION_LANE: tokio::sync::Semaphore = tokio::sync::Semaphore::const_new(1);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(not(feature = "inbound-http"), allow(dead_code))]
pub(crate) enum OutputBound {
#[default]
Maximum,
InputOrConstant {
maximum_literal_bytes: usize,
},
}
#[derive(Clone, Debug, Default)]
pub(crate) struct CompiledSource {
#[cfg_attr(
not(all(feature = "inbound-http", target_vendor = "apple")),
allow(dead_code)
)]
pub(crate) code: Arc<str>,
#[cfg_attr(not(feature = "inbound-http"), allow(dead_code))]
pub(crate) output_bound: OutputBound,
#[cfg(all(feature = "inbound-http", target_vendor = "apple"))]
plan: Option<Arc<static_literal_plan::Plan>>,
}
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<CompiledSource> {
#[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<super::body::BorrowedBody<'_>>,
) -> 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<super::body::BorrowedBody<'a>>),
}
#[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<super::body::BorrowedBody<'a>> {
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<usize> = 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<serde_json::Value> {
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<serde_json::Value> {
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<super::body::BorrowedBody<'_>>,
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<serde_json::Value> {
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<Self> {
// 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<super::body::BorrowedBody<'_>>,
output_body: &mut super::body_budget::BudgetedBytes,
cancellation: &tokio_util::sync::CancellationToken,
lane: InvocationLane,
) -> io::Result<serde_json::Value> {
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<serde_json::Value> {
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<serde_json::Value> {
#[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<T: Send>(
operation: impl FnOnce() -> io::Result<T> + Send,
) -> io::Result<T> {
run_on_script_thread(OwnerBackend::Jsc, operation)
}
#[cfg(all(feature = "inbound-http", target_vendor = "apple"))]
fn run_on_script_thread<T: Send>(
owner: OwnerBackend,
operation: impl FnOnce() -> io::Result<T> + Send,
) -> io::Result<T> {
#[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<T: Send>(
name: &str,
operation: impl FnOnce() -> io::Result<T> + Send,
) -> io::Result<T> {
// 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<T>(operation: impl FnOnce() -> io::Result<T>) -> io::Result<T> {
#[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;
@@ -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<io::ErrorKind>,
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<Instant>,
waiting: mpsc::Receiver<()>,
release: Release,
cancel: CancellationToken,
seen: Arc<Mutex<Option<Seen>>>,
budget: Budget,
last: Option<bytes::Bytes>,
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<Seen> {
*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();
}
File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More