From 80e183597d6f0f4b686506572553a20c13ecc486 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 14 Nov 2026 12:29:08 -0800 Subject: [PATCH 1/3] feat(moq-webrtc)!: remove peer-to-peer moq-dev/moq keeps what a large live-media platform uses. Peer-to-peer routing, with browsers and native nodes forwarding for each other, moves to a downstream product that re-plans it there (maintainer decision 2026-11-14). Git history keeps the code for a later port. Removed: - moq-webrtc's `p2p` module and feature (MoQ over a data channel, host candidates per interface, mDNS `.local` resolution) and the ICE agent's STUN Binding client and trickle events, which only it used. - The vendored sctp-proto and str0m's data channels (about 25k lines), which only the data-channel transport used. WHIP/WHEP keep str0m, dimpl, and the `is` ICE agent. - The private `@moq/p2p` package, `test/p2p`, its interop CI step, and its nightly bench. - moq-relay's public STUN responder: the `stun` feature, the `[stun]` config, `--stun-bind` / `MOQ_STUN_BIND`, the `moq_relay::stun` module, and its `moq_relay_stun_*` metrics. - The stun-types dependency, and if-addrs from the workspace. mdns-sd stays for LAN cluster discovery. - The P2P, browser mesh, and WHIP-without-SCTP quests. Public API: moq-webrtc loses the `p2p` feature and module; moq-relay loses the `stun` feature, its config section, flag, env var, module, and metrics. None of it was ever released: `origin/release` ships moq-rtc with no data-channel transport and moq-relay 0.17.16 with no STUN responder, so no MIGRATE.md entries are needed. Migration: a relay config with `[stun]`, `--stun-bind`, or `MOQ_STUN_BIND` must drop it, and an application that listed the relay as a STUN server points ICE at a dedicated STUN server instead. Users of `moq_webrtc::p2p` or `@moq/p2p` stay on an earlier commit or port the code from history. Wire: a WHIP or WHEP offer's `m=application` (data channel) section is now answered rejected (port 0, left out of BUNDLE) instead of accepted with an SCTP association nobody read. Audio and video negotiate as before. moq-lite and moq-transport are unchanged. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/interop.yml | 7 - .github/workflows/release-gate.yml | 2 - .oss-scanner/Dockerfile | 5 +- .oss-scanner/threat_model.md | 6 +- Cargo.lock | 80 +- Cargo.toml | 7 +- bun.lock | 31 - doc/bin/relay/config.md | 37 +- doc/concept/transport.md | 19 +- doc/lib/rs/index.md | 2 +- doc/setup/upgrade.md | 9 +- js/justfile | 5 - js/p2p/README.md | 34 - js/p2p/bench/transport.ts | 57 - js/p2p/bench/tsconfig.json | 1 - js/p2p/bunfig.toml | 3 - js/p2p/package.json | 31 - js/p2p/src/channel.ts | 190 - js/p2p/src/index.ts | 2 - js/p2p/src/mock.ts | 117 - js/p2p/src/transport.test.ts | 263 - js/p2p/src/transport.ts | 172 - js/p2p/tsconfig.build.json | 4 - js/p2p/tsconfig.json | 5 - nix/Cargo.nix | 361 +- package.json | 2 - quest/m2/cluster-routes/README.md | 2 +- quest/m3/cluster-routing/README.md | 22 +- quest/m3/cluster-routing/federation.md | 2 +- quest/m3/mesh/README.md | 3 +- quest/m3/one-port/README.md | 19 +- quest/m3/release/npm-first-publish.md | 4 - quest/m3/routing-guide.md | 4 +- quest/m3/uring-demux.md | 4 +- quest/m3/vendor-sync/README.md | 4 +- quest/m3/vendor-sync/webrtc-stack.md | 20 +- quest/m3/webrtc/README.md | 10 +- quest/m3/webrtc/dtls-timeout.md | 3 +- quest/m3/webrtc/socket-error.md | 45 +- quest/m4/bun-check.md | 2 +- quest/m4/p2p/README.md | 174 - quest/m4/p2p/cli.md | 47 - quest/m4/p2p/cost-scopes.md | 53 - quest/m4/p2p/harness.md | 52 - quest/m4/p2p/native-quic.md | 68 - quest/m4/p2p/signal.md | 97 - quest/m4/p2p/watch.md | 36 - quest/m4/test-inventory-followups.md | 7 +- quest/m4/webrtc-browser-only.md | 4 +- quest/m4/webrtc-sctp-feature.md | 20 - quest/m5/browser-mesh.md | 64 - quest/m5/mesh-ice.md | 3 +- quest/m9/uring-cluster-dial.md | 2 +- rs/moq-relay/Cargo.toml | 4 - rs/moq-relay/src/config.rs | 54 - rs/moq-relay/src/internal.rs | 66 - rs/moq-relay/src/lib.rs | 2 - rs/moq-relay/src/relay.rs | 50 - rs/moq-relay/src/settings.rs | 12 - rs/moq-relay/src/stun.rs | 532 -- rs/moq-tokio/Cargo.toml | 2 +- rs/moq-webrtc/Cargo.toml | 24 +- rs/moq-webrtc/src/ice/agent.rs | 252 +- rs/moq-webrtc/src/ice/mod.rs | 7 +- rs/moq-webrtc/src/ice/wire.rs | 2 +- rs/moq-webrtc/src/lib.rs | 4 +- rs/moq-webrtc/src/p2p/channel.rs | 229 - rs/moq-webrtc/src/p2p/mod.rs | 1030 ---- rs/moq-webrtc/src/p2p/resolver.rs | 298 - rs/moq-webrtc/src/p2p/tests.rs | 454 -- rs/moq-webrtc/src/sdp.rs | 4 +- rs/moq-webrtc/src/session.rs | 4 +- rs/moq-webrtc/src/vendor/mod.rs | 15 +- .../src/vendor/sctp_proto/LICENSE-APACHE | 202 - .../src/vendor/sctp_proto/LICENSE-MIT | 22 - .../association/association_test.rs | 5414 ----------------- .../src/vendor/sctp_proto/association/mod.rs | 4146 ------------- .../vendor/sctp_proto/association/state.rs | 102 - .../vendor/sctp_proto/association/stats.rs | 59 - .../vendor/sctp_proto/association/stream.rs | 738 --- .../association/timed_reliability_test.rs | 313 - .../vendor/sctp_proto/association/timer.rs | 244 - .../vendor/sctp_proto/chunk/chunk_abort.rs | 89 - .../sctp_proto/chunk/chunk_cookie_ack.rs | 55 - .../sctp_proto/chunk/chunk_cookie_echo.rs | 62 - .../vendor/sctp_proto/chunk/chunk_error.rs | 91 - .../sctp_proto/chunk/chunk_forward_tsn.rs | 176 - .../vendor/sctp_proto/chunk/chunk_header.rs | 102 - .../sctp_proto/chunk/chunk_heartbeat.rs | 92 - .../sctp_proto/chunk/chunk_heartbeat_ack.rs | 121 - .../sctp_proto/chunk/chunk_i_forward_tsn.rs | 121 - .../src/vendor/sctp_proto/chunk/chunk_init.rs | 285 - .../sctp_proto/chunk/chunk_payload_data.rs | 248 - .../vendor/sctp_proto/chunk/chunk_reconfig.rs | 146 - .../sctp_proto/chunk/chunk_selective_ack.rs | 156 - .../vendor/sctp_proto/chunk/chunk_shutdown.rs | 70 - .../sctp_proto/chunk/chunk_shutdown_ack.rs | 55 - .../chunk/chunk_shutdown_complete.rs | 55 - .../src/vendor/sctp_proto/chunk/chunk_test.rs | 842 --- .../src/vendor/sctp_proto/chunk/chunk_type.rs | 94 - .../src/vendor/sctp_proto/chunk/mod.rs | 182 - rs/moq-webrtc/src/vendor/sctp_proto/config.rs | 443 -- .../sctp_proto/endpoint/endpoint_test.rs | 3734 ------------ .../src/vendor/sctp_proto/endpoint/mod.rs | 688 --- rs/moq-webrtc/src/vendor/sctp_proto/error.rs | 241 - rs/moq-webrtc/src/vendor/sctp_proto/lib.rs | 183 - rs/moq-webrtc/src/vendor/sctp_proto/packet.rs | 481 -- .../src/vendor/sctp_proto/param/mod.rs | 92 - .../sctp_proto/param/param_chunk_list.rs | 72 - .../param/param_forward_tsn_supported.rs | 49 - .../vendor/sctp_proto/param/param_header.rs | 62 - .../sctp_proto/param/param_heartbeat_info.rs | 45 - .../param/param_outgoing_reset_request.rs | 122 - .../vendor/sctp_proto/param/param_random.rs | 45 - .../param/param_reconfig_response.rs | 132 - .../param/param_requested_hmac_algorithm.rs | 110 - .../sctp_proto/param/param_state_cookie.rs | 60 - .../param/param_supported_address_types.rs | 79 - .../param/param_supported_extensions.rs | 68 - .../src/vendor/sctp_proto/param/param_test.rs | 330 - .../src/vendor/sctp_proto/param/param_type.rs | 164 - .../vendor/sctp_proto/param/param_uknown.rs | 67 - .../src/vendor/sctp_proto/queue/mod.rs | 7 - .../vendor/sctp_proto/queue/outbound_queue.rs | 204 - .../sctp_proto/queue/outbound_queue_test.rs | 331 - .../vendor/sctp_proto/queue/payload_queue.rs | 199 - .../vendor/sctp_proto/queue/pending_queue.rs | 179 - .../src/vendor/sctp_proto/queue/queue_test.rs | 1293 ---- .../sctp_proto/queue/reassembly_queue.rs | 606 -- rs/moq-webrtc/src/vendor/sctp_proto/shared.rs | 80 - .../sctp_proto/tests/partial_reliability.rs | 630 -- rs/moq-webrtc/src/vendor/sctp_proto/util.rs | 394 -- .../src/vendor/str0m/change/direct.rs | 73 - rs/moq-webrtc/src/vendor/str0m/change/sdp.rs | 652 +- rs/moq-webrtc/src/vendor/str0m/channel.rs | 772 --- rs/moq-webrtc/src/vendor/str0m/config.rs | 104 - rs/moq-webrtc/src/vendor/str0m/error.rs | 13 - rs/moq-webrtc/src/vendor/str0m/lib.rs | 248 +- rs/moq-webrtc/src/vendor/str0m/media/mod.rs | 15 - rs/moq-webrtc/src/vendor/str0m/poll.rs | 2 +- rs/moq-webrtc/src/vendor/str0m/sctp/dcep.rs | 122 - rs/moq-webrtc/src/vendor/str0m/sctp/error.rs | 55 - rs/moq-webrtc/src/vendor/str0m/sctp/mod.rs | 1825 ------ rs/moq-webrtc/src/vendor/str0m/sctp/snap.rs | 177 - rs/moq-webrtc/src/vendor/str0m/sdp/data.rs | 34 - .../src/vendor/str0m/tests/api-errors.rs | 6 +- .../src/vendor/str0m/tests/common.rs | 67 - .../vendor/str0m/tests/config-validation.rs | 5 +- .../vendor/str0m/tests/data-channel-direct.rs | 123 - .../src/vendor/str0m/tests/data-channel.rs | 902 --- .../src/vendor/str0m/tests/dtls-close.rs | 2 - .../vendor/str0m/tests/dtls-fingerprint.rs | 3 +- .../src/vendor/str0m/tests/dtls-retransmit.rs | 2 - .../src/vendor/str0m/tests/dtls-security.rs | 5 +- .../vendor/str0m/tests/flappy-ice-state.rs | 3 +- .../vendor/str0m/tests/handshake-direct.rs | 752 --- .../src/vendor/str0m/tests/ice-candidates.rs | 163 +- .../str0m/tests/ice-lite-connectivity.rs | 3 +- .../tests/ice-remote-binding-keepalive.rs | 3 +- .../src/vendor/str0m/tests/ice-restart.rs | 3 +- rs/moq-webrtc/src/vendor/str0m/tests/mod.rs | 8 - .../src/vendor/str0m/tests/mtu-compliance.rs | 29 +- .../src/vendor/str0m/tests/partial-init.rs | 19 - .../src/vendor/str0m/tests/sdp-negotiation.rs | 560 -- .../src/vendor/str0m/tests/sdp-unique-mids.rs | 48 +- .../str0m/tests/simulcast-rid-mapping.rs | 2 +- .../tests/stale-network-time-after-pause.rs | 2 - rs/workspace-hack/Cargo.toml | 12 +- sh/gh/nightly.sh | 3 +- sh/rs/select.sh | 2 - sh/rs/select.test.py | 9 +- test/justfile | 5 - test/p2p/index.html | 2 - test/p2p/package.json | 19 - test/p2p/src/main.ts | 125 - test/p2p/transport.browser.ts | 57 - test/p2p/tsconfig.json | 5 - 177 files changed, 277 insertions(+), 37504 deletions(-) delete mode 100644 js/p2p/README.md delete mode 100644 js/p2p/bench/transport.ts delete mode 100644 js/p2p/bench/tsconfig.json delete mode 100644 js/p2p/bunfig.toml delete mode 100644 js/p2p/package.json delete mode 100644 js/p2p/src/channel.ts delete mode 100644 js/p2p/src/index.ts delete mode 100644 js/p2p/src/mock.ts delete mode 100644 js/p2p/src/transport.test.ts delete mode 100644 js/p2p/src/transport.ts delete mode 100644 js/p2p/tsconfig.build.json delete mode 100644 js/p2p/tsconfig.json delete mode 100644 quest/m4/p2p/README.md delete mode 100644 quest/m4/p2p/cli.md delete mode 100644 quest/m4/p2p/cost-scopes.md delete mode 100644 quest/m4/p2p/harness.md delete mode 100644 quest/m4/p2p/native-quic.md delete mode 100644 quest/m4/p2p/signal.md delete mode 100644 quest/m4/p2p/watch.md delete mode 100644 quest/m4/webrtc-sctp-feature.md delete mode 100644 quest/m5/browser-mesh.md delete mode 100644 rs/moq-relay/src/stun.rs delete mode 100644 rs/moq-webrtc/src/p2p/channel.rs delete mode 100644 rs/moq-webrtc/src/p2p/mod.rs delete mode 100644 rs/moq-webrtc/src/p2p/resolver.rs delete mode 100644 rs/moq-webrtc/src/p2p/tests.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-APACHE delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-MIT delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/association/association_test.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/association/mod.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/association/state.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/association/stats.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/association/stream.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/association/timed_reliability_test.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/association/timer.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_abort.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_ack.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_echo.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_error.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_forward_tsn.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_header.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat_ack.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_i_forward_tsn.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_init.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_payload_data.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_reconfig.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_selective_ack.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_ack.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_complete.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_test.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_type.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/chunk/mod.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/config.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/endpoint/endpoint_test.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/endpoint/mod.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/error.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/lib.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/packet.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/mod.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_chunk_list.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_forward_tsn_supported.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_header.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_heartbeat_info.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_outgoing_reset_request.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_random.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_reconfig_response.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_requested_hmac_algorithm.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_state_cookie.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_address_types.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_extensions.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_test.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_type.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/param/param_uknown.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/queue/mod.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue_test.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/queue/payload_queue.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/queue/pending_queue.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/queue/queue_test.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/queue/reassembly_queue.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/shared.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/tests/partial_reliability.rs delete mode 100644 rs/moq-webrtc/src/vendor/sctp_proto/util.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/channel.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/sctp/dcep.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/sctp/error.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/sctp/mod.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/sctp/snap.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/tests/data-channel-direct.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/tests/data-channel.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs delete mode 100644 rs/moq-webrtc/src/vendor/str0m/tests/partial-init.rs delete mode 100644 test/p2p/index.html delete mode 100644 test/p2p/package.json delete mode 100644 test/p2p/src/main.ts delete mode 100644 test/p2p/transport.browser.ts delete mode 100644 test/p2p/tsconfig.json diff --git a/.github/workflows/interop.yml b/.github/workflows/interop.yml index 6fd5378f77c..c55c3a9c9a9 100644 --- a/.github/workflows/interop.yml +++ b/.github/workflows/interop.yml @@ -110,12 +110,6 @@ jobs: run: nix develop --command just test bare-fin shell: bash -leo pipefail {0} - - name: P2P data-channel transport - id: p2p - if: ${{ !cancelled() && steps.setup.outcome == 'success' }} - run: nix develop --command just test p2p - shell: bash -leo pipefail {0} - - name: Interop (full matrix) id: interop if: ${{ !cancelled() && steps.setup.outcome == 'success' }} @@ -238,7 +232,6 @@ jobs: "Receive credit recovery": "${{ steps.receive-credit.outcome }}", "Harness regressions": "${{ steps.harness.outcome }}", "Subscription termination interop": "${{ steps.bare-fin.outcome }}", - "P2P data-channel transport": "${{ steps.p2p.outcome }}", "Interop (full matrix)": "${{ steps.interop.outcome }}", "Interop (moq-transport)": "${{ steps.interop-ietf.outcome }}", "Released wire compatibility": "${{ steps.wire-compat.outcome }}", diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index aa248aac142..84db9dc13d0 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -122,8 +122,6 @@ jobs: # A backported change to the interop harness itself; nightly covers main. interop: - "test/lib/**" - - "test/p2p/**" - - "js/p2p/**" - "test/interop/**" - "test/max-age/**" - "test/portrait/**" diff --git a/.oss-scanner/Dockerfile b/.oss-scanner/Dockerfile index b0a60150b82..5a2cb70fcfe 100644 --- a/.oss-scanner/Dockerfile +++ b/.oss-scanner/Dockerfile @@ -26,10 +26,9 @@ ARG CRATES="kio hang moq-auth moq-crypto moq-hls moq-json moq-loc moq-msf moq-mu # Path specs, because the lockfile also has published copies of some workspace crates. # io-uring compiles the relay's io_uring QUIC workers (`--runtime-io-uring`), which the default features leave out. -# p2p compiles moq-webrtc's data channel transport and its tests. RUN cargo fetch --locked \ && specs=$(printf -- '-p path+file:///src/rs/%s ' $CRATES) \ - && cargo build --locked $specs --features moq-relay/io-uring,moq-webrtc/p2p --bins \ - && cargo test --locked --no-run $specs --features moq-relay/io-uring,moq-webrtc/p2p + && cargo build --locked $specs --features moq-relay/io-uring --bins \ + && cargo test --locked --no-run $specs --features moq-relay/io-uring ENV CARGO_NET_OFFLINE=true diff --git a/.oss-scanner/threat_model.md b/.oss-scanner/threat_model.md index f28160de499..19b8c843787 100644 --- a/.oss-scanner/threat_model.md +++ b/.oss-scanner/threat_model.md @@ -11,7 +11,7 @@ Treat everything a peer sends as hostile, before and after authentication: - **WebSocket and HTTP** on the relay's `[web]` listeners: the upgrade, the public `/announced`, `/fetch` and `/certificate.sha256` endpoints, and query strings. - **Authorization inputs**: the JWT (`moq-auth`), the SETUP token, the dialed path and query, and the relay's handling of grants (root, publish and subscribe pattern unions, mounts, expiry, revalidation). - **Media payloads**: catalogs (`hang`, `moq-msf`, JSON in `moq-json`) and containers and codecs parsed by `moq-mux` (fMP4, MPEG-TS, FLV, MKV, LOC, and the H.264, H.265, AV1, VP8, VP9, AAC, Opus and FLAC bitstream parsers). A publisher controls these bytes, and the relay or a subscriber may parse them. -- **Ingest gateways**: RTMP (`moq-rtmp`), RTSP (`moq-rtsp`), SRT (`moq-srt`), WebRTC, ICE/STUN, and data channels (`moq-webrtc`, including the str0m, dimpl, and sctp-proto copies vendored in `rs/moq-webrtc/src/vendor`), and HLS playlists and segments (`moq-hls`). +- **Ingest gateways**: RTMP (`moq-rtmp`), RTSP (`moq-rtsp`), SRT (`moq-srt`), WebRTC WHIP/WHEP with ICE/STUN (`moq-webrtc`, including the str0m and dimpl copies vendored in `rs/moq-webrtc/src/vendor`), and HLS playlists and segments (`moq-hls`). - **Peer relays** in a cluster are authenticated but should not be able to break a node beyond what their grant allows. ## Security properties the relay must hold @@ -24,7 +24,7 @@ The relay is deployed on the public internet as shared infrastructure: one proce - **Multi-tenancy.** A grant's `root` scopes a session to one subtree; `mounts` add read-only views. A session must never publish, subscribe, receive announcements, fetch, or see stats outside its grant, whether through path normalization, pattern matching (`moq-pattern`), the HTTP endpoints, cluster forwarding, or a revalidation that changes the grant mid-session. One tenant must not be able to degrade another beyond its fair share, for example by exhausting a shared cache or a shared connection limit. - **Cache integrity.** The relay caches and forwards groups by broadcast, track, and group. A publisher must not be able to overwrite or inject into a broadcast it was not granted, and a subscriber must never receive one tenant's data under another tenant's name. - **Cluster trust.** Peer relays authenticate with tokens or mTLS and get broader rights than clients. A relay dials only configured or discovered peers, never a URL learned from an announcement. LAN discovery over mDNS (`[cluster.lan]`) is open to anyone on the network unless `secret` is set, which is documented; with `secret` set, an unkeyed host must not be able to join. -- **Amplification and reflection.** QUIC's anti-amplification limit and address validation, the opt-in public STUN responder (`rs/moq-relay/src/stun.rs`), and ICE in the WebRTC gateway all answer unauthenticated UDP. A response larger than the request toward a spoofed source is a finding. +- **Amplification and reflection.** QUIC's anti-amplification limit and address validation, and ICE in the WebRTC gateway, answer unauthenticated UDP. A response larger than the request toward a spoofed source is a finding. - **End-to-end encryption and signing.** `moq-crypto` encrypts groups, datagrams, and track names so a relay cannot read them, and signs frames so a relay cannot forge them. A flaw in either construction (nonce reuse, a key or name leaking to the relay, a forgeable group or signature) is in scope. ## Components that matter most / least @@ -45,7 +45,7 @@ Out of scope: `js/` and the other language bindings (`py/`, `swift/`, `kt/`, `go The image is offline, with every crate fetched and `CARGO_NET_OFFLINE` set. The debug build of the in-scope crates, their test binaries, and the `moq-relay` and `moq` binaries are already built in `/src/target/debug`. Debug builds keep overflow checks on. -- **Tests**: `cargo nextest run -p path+file:///src/rs/moq-net` (or any in-scope crate; the path spec is needed because the lockfile also has published copies of some crates). Use nextest as CI does: some tests install process-global state and fail under plain `cargo test`. Add `--features moq-relay/io-uring` for the relay and `moq-uring` so the io\_uring backend's tests run (they skip on a kernel without io\_uring support), and `--features moq-webrtc/p2p` for the data channel transport's. Unit tests use the deterministic clock in `kio::clock` rather than wall time, so they are fast and reproducible. +- **Tests**: `cargo nextest run -p path+file:///src/rs/moq-net` (or any in-scope crate; the path spec is needed because the lockfile also has published copies of some crates). Use nextest as CI does: some tests install process-global state and fail under plain `cargo test`. Add `--features moq-relay/io-uring` for the relay and `moq-uring` so the io\_uring backend's tests run (they skip on a kernel without io\_uring support). Unit tests use the deterministic clock in `kio::clock` rather than wall time, so they are fast and reproducible. - **A relay to attack**: `./target/debug/moq-relay demo/relay/localhost.toml` listens on UDP and TCP `[::]:4443` with a self-signed certificate and anonymous access to every path. The binary is built with io\_uring support; pass `--runtime-io-uring` to serve QUIC from the io\_uring workers in `rs/moq-uring` and `rs/moq-relay/src/uring.rs` instead of tokio. For authorization testing, grant a narrow anonymous pattern with `[auth] public_subscribe` / `public_publish`, or run the reference auth server (`moq auth generate`, `moq auth sign`, `moq auth serve`, then `[auth] url`; see `doc/bin/cli.md`) and try to escape a signed token's root and patterns. `doc/bin/relay/` documents the config, auth, cluster, and HTTP endpoints. - **A client**: `./target/debug/moq --help` publishes, subscribes, fetches, and lists announcements against a relay. `curl http://localhost:4443/announced/` and `curl http://localhost:4443/fetch//` hit the HTTP endpoints. - **Fuzz harnesses**: `rs/moq-net/fuzz` and `rs/moq-quic/fuzz` hold cargo-fuzz targets for the wire codecs and the QUIC state machine. cargo-fuzz and a nightly toolchain are not in the image, but the targets show the parser entry points. diff --git a/Cargo.lock b/Cargo.lock index 6e1ffa66f5b..ba4d4856081 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4677,7 +4677,6 @@ dependencies = [ "serde_json", "serde_with", "socket2 0.6.5", - "stun-types", "sysinfo", "tempfile", "test-env", @@ -5036,17 +5035,13 @@ dependencies = [ "aes 0.9.4", "arrayvec", "axum", - "base64ct", "bytes", "ccm", "combine", "crc", "fastrand", - "futures", "hang", - "if-addrs", "kio", - "mdns-sd", "moq-crypto", "moq-mux", "moq-net", @@ -5054,18 +5049,14 @@ dependencies = [ "nom 8.0.0", "once_cell", "pcap-file", - "qmux 0.7.0", "rand 0.10.3", "rcgen", "reqwest", "rind", "rind-rcgen", - "rustc-hash 2.1.3", "serde", "serde_json", - "slab", "spki 0.8.1", - "stun-types", "subtle", "thiserror 2.0.21", "time", @@ -6733,20 +6724,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" dependencies = [ "libc", - "rand_chacha 0.3.1", + "rand_chacha", "rand_core 0.6.4", ] -[[package]] -name = "rand" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" -dependencies = [ - "rand_chacha 0.9.0", - "rand_core 0.9.5", -] - [[package]] name = "rand" version = "0.10.3" @@ -6768,16 +6749,6 @@ dependencies = [ "rand_core 0.6.4", ] -[[package]] -name = "rand_chacha" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" -dependencies = [ - "ppv-lite86", - "rand_core 0.9.5", -] - [[package]] name = "rand_core" version = "0.6.4" @@ -6787,15 +6758,6 @@ dependencies = [ "getrandom 0.2.17", ] -[[package]] -name = "rand_core" -version = "0.9.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" -dependencies = [ - "getrandom 0.3.4", -] - [[package]] name = "rand_core" version = "0.10.1" @@ -7369,7 +7331,7 @@ dependencies = [ "serde", "serde_json", "serde_urlencoded", - "sha1 0.11.0", + "sha1", "sha2 0.11.1", "smallvec", "std-next", @@ -7451,7 +7413,7 @@ dependencies = [ "base64-simd", "hmac 0.13.0", "jiff", - "sha1 0.11.0", + "sha1", "smallvec", "thiserror 2.0.21", ] @@ -7841,17 +7803,6 @@ dependencies = [ "digest 0.10.7", ] -[[package]] -name = "sha1" -version = "0.10.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" -dependencies = [ - "cfg-if", - "cpufeatures 0.2.17", - "digest 0.10.7", -] - [[package]] name = "sha1" version = "0.11.0" @@ -8277,25 +8228,6 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" -[[package]] -name = "stun-types" -version = "2.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "034e7be5ad5d62256b8df9b7344ef58b1cfee797cc7dabfacdc28efb3d3a192d" -dependencies = [ - "byteorder", - "crc", - "hmac 0.12.1", - "md-5 0.10.6", - "rand 0.9.5", - "sha1 0.10.7", - "sha2 0.10.9", - "smallvec", - "subtle", - "thiserror 2.0.21", - "tracing", -] - [[package]] name = "subtle" version = "2.6.1" @@ -9107,7 +9039,7 @@ dependencies = [ "rand 0.10.3", "rustls", "rustls-pki-types", - "sha1 0.11.0", + "sha1", "thiserror 2.0.21", ] @@ -10386,7 +10318,6 @@ dependencies = [ "bitflags 2.13.2", "block2 0.6.2", "bytemuck", - "byteorder", "bytes", "camino", "cc", @@ -10424,7 +10355,6 @@ dependencies = [ "half", "hashbrown 0.17.1", "hex", - "hmac 0.12.1", "hyper", "hyper-rustls", "hyper-util", @@ -10433,7 +10363,6 @@ dependencies = [ "libc", "linux-raw-sys 0.12.1", "log", - "md-5 0.10.6", "md-5 0.11.0", "memchr", "mio", @@ -10475,7 +10404,6 @@ dependencies = [ "serde_json", "serde_spanned 1.1.3", "serde_with", - "sha2 0.10.9", "siphasher", "slab", "smallvec", diff --git a/Cargo.toml b/Cargo.toml index 84ac9d1a16b..29192f4232b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -86,7 +86,6 @@ axum = { version = "0.8", default-features = false, features = [ # Features off so each consumer picks its rustls provider. axum-server = "0.9" base64 = "0.23" -base64ct = "1" bitflags = "2" # MSB-first bit reading for codec configs; the version h264-reader builds on. bitstream-io = "4.10" @@ -116,8 +115,6 @@ humantime = "2.3" humantime-serde = "1.1.1" hyper = "1.11" hyper-util = { version = "0.1.21", features = ["tokio"] } -# Interface addresses for WebRTC host candidates (moq-webrtc's `p2p` feature). -if-addrs = "0.15" indexmap = "2.14.2" io-uring = "0.7.15" jni = "0.22" @@ -127,8 +124,7 @@ kio-macros = { version = "0.1.0", path = "rs/kio/macros" } libc = "0.2" libloading = "0.9" linux-raw-sys = { version = "0.12.1", features = ["ioctl"] } -# DNS-SD advertisement and browsing for LAN peer discovery (moq-tokio's `mdns` feature), -# and `.local` candidate resolution (moq-webrtc's `p2p` feature). +# DNS-SD advertisement and browsing for LAN peer discovery (moq-tokio's `mdns` feature). # `async` awaits the event channel instead of blocking a thread on it. mdns-sd = { version = "0.21", features = ["async"] } moq-archive = { version = "0.0.11", path = "rs/moq-archive" } @@ -227,7 +223,6 @@ serde_with = "3" slab = "0.4.12" socket2 = "0.6" spki = "0.8" -stun-types = "2.0.3" subtle = "2.6" tempfile = "3" thiserror = "2" diff --git a/bun.lock b/bun.lock index e621b20142c..b04f481947d 100644 --- a/bun.lock +++ b/bun.lock @@ -270,19 +270,6 @@ "zod": "^4.5.0", }, }, - "js/p2p": { - "name": "@moq/p2p", - "version": "0.1.0", - "dependencies": { - "@moq/qmux": "workspace:^", - }, - "devDependencies": { - "@moq/clock": "workspace:^", - "@types/bun": "^1.4.4", - "@typescript/lib-dom": "npm:@types/web@^0.0.358", - "typescript": "7.0.2", - }, - }, "js/pattern": { "name": "@moq/pattern", "version": "0.2.1", @@ -490,20 +477,6 @@ "tsx": "^4.23.15", }, }, - "test/p2p": { - "name": "@moq/p2p-test", - "dependencies": { - "@moq/net": "workspace:*", - "@moq/p2p": "workspace:*", - }, - "devDependencies": { - "@types/bun": "^1.4.4", - "@typescript/lib-dom": "npm:@types/web@^0.0.358", - "playwright": "1.64.1", - "typescript": "7.0.2", - "vite": "^8.3.6", - }, - }, "test/qmux": { "name": "@moq/qmux-interop", "dependencies": { @@ -878,10 +851,6 @@ "@moq/net": ["@moq/net@workspace:js/net"], - "@moq/p2p": ["@moq/p2p@workspace:js/p2p"], - - "@moq/p2p-test": ["@moq/p2p-test@workspace:test/p2p"], - "@moq/pattern": ["@moq/pattern@workspace:js/pattern"], "@moq/publish": ["@moq/publish@workspace:js/publish"], diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md index 4a20996c421..3c3906b6cd7 100644 --- a/doc/bin/relay/config.md +++ b/doc/bin/relay/config.md @@ -64,10 +64,10 @@ arrive without one. `bind` is the relay's one UDP port. Beside QUIC it carries WebRTC media for an [embedder](/bin/relay/#embed) that takes it; otherwise that traffic is dropped, -as are STUN Binding queries ([`[stun]`](#stun) has its own port) and anything -else. `/metrics` counts the drops in `moq_relay_demux_dropped_total` by `reason`: -`unclaimed` (WebRTC with no embedder), `overflow`, `stun`, and `unknown`. Not -with `runtime.io_uring`, which serves QUIC alone. +as are STUN Binding queries and anything else. `/metrics` counts the drops in +`moq_relay_demux_dropped_total` by `reason`: `unclaimed` (WebRTC with no +embedder), `overflow`, `stun`, and `unknown`. Not with `runtime.io_uring`, which +serves QUIC alone. `reset.secret` lets a relay restarted on the same address reset its predecessor's QUIC connections, so clients reconnect at once instead of @@ -255,35 +255,6 @@ keep the connection open; a WebSocket upgrade hands its lifetime to MoQ. See [HTTP endpoints](/bin/relay/http). -## \[stun] - -Build with `cargo install moq-relay --features stun` to use the relay as an -explicitly selected STUN server for WebRTC ICE. This feature is off by default. -The listener has its own UDP port and is disabled unless configured: - -```toml -[stun] -bind = "[::]:3478" # Or --stun-bind / MOQ_STUN_BIND. -``` - -List `stun:relay.example.com:3478` in the application's ICE servers. Clients -never infer a STUN server from their relay session. This provides Binding -responses with the sender's mapped address, without TURN relaying or ICE -signaling. It is plain STUN over UDP, so it needs no TLS certificate; -`stuns:` (STUN over TLS) is not served. - -The private limits are 10 requests/second per source IP with a burst of 20, -and 1000/second globally with a burst of 2000. The source table retains at most -4096 IPs; an idle entry can be replaced once its two-second bucket has refilled. -Excess, malformed, unsupported, and non-Binding datagrams receive no reply. -The internal `/metrics` endpoint reports `moq_relay_stun_replies_total` and -`moq_relay_stun_dropped_total` with `reason` values `source`, `global`, -`capacity`, `invalid`, and `io`, only when this listener is configured. -`io` counts replies that could not be sent; `moq_relay_stun_io_errors_total` -also counts asynchronous peer errors reported while receiving. Peer network -errors and interrupted calls leave the listener running; other local socket -failures stop the relay. - ## \[auth] ```toml diff --git a/doc/concept/transport.md b/doc/concept/transport.md index 5f16c4b0596..c11055053de 100644 --- a/doc/concept/transport.md +++ b/doc/concept/transport.md @@ -1,6 +1,6 @@ --- title: Transport -description: QUIC, WebTransport, the WebSocket fallback, raw QUIC, stream listeners, and WebRTC data channels +description: QUIC, WebTransport, the WebSocket fallback, raw QUIC, and stream listeners --- # Transport @@ -88,23 +88,6 @@ authenticate through the same JWT and public-access rules as QUIC, and the Unix socket can additionally allowlist the connecting process by uid, gid, or pid. See [stream listeners](/bin/relay/auth#stream-listeners). -## WebRTC data channels (experimental) - -The private workspace P2P transport is exercised by `test/p2p`; it is not a -published package. Applications in this checkout that negotiate a browser -`RTCPeerConnection` can pass an -[`@moq/p2p` transport](https://github.com/moq-dev/moq/tree/main/js/p2p) to -`@moq/net`'s connect or accept. One reliable ordered data channel carries qmux -records, with no datagrams. The application supplies signaling and ICE and -keeps ownership of the peer connection; closing the transport closes only its -channel. SCTP ordering means one lost packet can hold back every stream. - -Native peers can use `moq-webrtc`'s `p2p` feature, which runs its own ICE agent: -host candidates on every interface, server-reflexive candidates from the STUN -servers it is given, and mDNS resolution of a browser's `.local` candidates. -The application still carries the offer, answer, and candidates; the offering -peer connects as the MoQ client and the answering peer accepts. - ## Custom Rust transports `moq-net` runs over its own poll traits, so a custom transport implements diff --git a/doc/lib/rs/index.md b/doc/lib/rs/index.md index 5fee8af3a99..4900e9f3455 100644 --- a/doc/lib/rs/index.md +++ b/doc/lib/rs/index.md @@ -43,7 +43,7 @@ missing required CPU feature before starting transport cryptography. | [moq-loc](https://docs.rs/moq-loc), [moq-msf](https://docs.rs/moq-msf) | The IETF LOC container and MSF catalog. | | [moq-stats](https://docs.rs/moq-stats) | Publish and consume relay traffic counters as tracks. | | [kio](/lib/rs/kio) | The async primitives everything polls through, and one clock for time and timers on tokio and a deterministic test simulator. | -| [moq-hls](https://docs.rs/moq-hls), [moq-rtmp](https://docs.rs/moq-rtmp), [moq-srt](https://docs.rs/moq-srt), [moq-rtsp](https://github.com/moq-dev/moq/tree/main/rs/moq-rtsp), [moq-webrtc](https://github.com/moq-dev/moq/tree/main/rs/moq-webrtc) | The [gateways](/bin/), as libraries you can embed with your own auth. moq-webrtc's `p2p` feature also runs MoQ over a data channel with a browser peer, signaled by the caller. | +| [moq-hls](https://docs.rs/moq-hls), [moq-rtmp](https://docs.rs/moq-rtmp), [moq-srt](https://docs.rs/moq-srt), [moq-rtsp](https://github.com/moq-dev/moq/tree/main/rs/moq-rtsp), [moq-webrtc](https://github.com/moq-dev/moq/tree/main/rs/moq-webrtc) | The [gateways](/bin/), as libraries you can embed with your own auth. | | [moq-ffi](https://docs.rs/moq-ffi), [moq-c](/lib/c/) | The UniFFI core behind the language bindings, and the C ABI. | | [moq-relay](/bin/relay/), [moq-cli](/bin/cli) | The binaries, also usable as crates. | | [web-transport](https://github.com/moq-dev/web-transport) | The WebTransport traits and the browser transport, in a sibling repository. | diff --git a/doc/setup/upgrade.md b/doc/setup/upgrade.md index 1ab33b58ada..21950eba480 100644 --- a/doc/setup/upgrade.md +++ b/doc/setup/upgrade.md @@ -36,14 +36,7 @@ These land with the next breaking release. - **WebRTC moves to `moq-webrtc`.** The `moq-rtc` crate is renamed `moq-webrtc`: replace `moq_rtc::` with `moq_webrtc::`. Its last release stays - on crates.io. moq-tokio's `webrtc` feature is gone: enable moq-webrtc's `p2p` - feature and use `moq_webrtc::p2p` instead of `moq_tokio::webrtc`, with - `offerer.connect(&client)` for `client.connect_webrtc(&offerer)` and - `answerer.accept(&listener)` for `listener.accept_webrtc(&answerer)`. The - ICE agent that was `moq-ice`, never published, is a private module of - moq-webrtc. moq-cli's `webrtc` cargo feature is gone: drop it from your - build; `import rtc` and `export rtc` never needed it. Nothing changes on the - wire. + on crates.io. Nothing changes on the wire. - **The default priority byte moves again.** Priorities are signed in every API, -128 to 127 with 0 unset, so nobody has to know that 127 is the middle of a byte. The wire keeps one byte and one urgency on both protocols, so an diff --git a/js/justfile b/js/justfile index 81de35ff266..1ddd7801056 100644 --- a/js/justfile +++ b/js/justfile @@ -187,11 +187,6 @@ audio-warmup-bench: uv run --no-project python ../sh/js/install.py frozen bun watch/bench/warmup.ts -# Sweep data-channel qmux stream count and payload size. -p2p-bench: - uv run --no-project python ../sh/js/install.py frozen - bun p2p/bench/transport.ts - # Sweep E2EE frame size against writes in flight through the WebCrypto pump. e2ee-bench: uv run --no-project python ../sh/js/install.py frozen diff --git a/js/p2p/README.md b/js/p2p/README.md deleted file mode 100644 index 0bf38b3906d..00000000000 --- a/js/p2p/README.md +++ /dev/null @@ -1,34 +0,0 @@ -# @moq/p2p - -Private workspace package, exercised by `test/p2p`; it is not published. - -A WebTransport-shaped MoQ transport over one reliable ordered WebRTC data channel. -Applications own signaling, ICE configuration, admission, and the `RTCPeerConnection`. -The transport owns its data channel. Closing it leaves the peer connection open. - -```ts -import { Transport } from "@moq/p2p"; -import { Connection } from "@moq/net"; - -// The application agrees this ALPN with its peer through signaling. -const protocol = "moq-lite-07-wip"; -const transport = Transport.connect({ peer, protocol }); -const connection = await Connection.connect({ url, transport }); -``` - -The receiver adopts the incoming channel with -`Transport.accept({ peer, channel, protocol })` and passes that transport to -`Connection.accept({ url, transport })`. The channel's protocol must match the -agreed ALPN. Unordered or partially reliable channels are refused. - -Each binary data-channel message carries one qmux-01 record without its size -field. Records are capped at 16 KiB and the negotiated SCTP message limit; -a limit below qmux-01's 16,382-byte minimum is refused. There are no datagrams. -SCTP preserves ordering, so packet loss can hold back every stream. -The accepting side sends nothing until the dialer's first record arrives, since -Chromium reports an announced channel open before its stream is open and silently drops -what is sent in between. A close stops that wait, so the close frame goes out at once. - -`just test p2p` runs SETUP and a media transfer between two real peer connections -in Chromium. `just js p2p-bench` sweeps stream counts and payload sizes through -an in-memory data-channel pair. diff --git a/js/p2p/bench/transport.ts b/js/p2p/bench/transport.ts deleted file mode 100644 index 433c0a7732d..00000000000 --- a/js/p2p/bench/transport.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** Sweep concurrent streams and bytes per stream through the real qmux adapter. @module */ -import { peers } from "../src/mock.ts"; -import { Transport } from "../src/transport.ts"; - -async function receive(stream: ReadableStream) { - const reader = stream.getReader(); - let bytes = 0; - try { - for (;;) { - const { value, done } = await reader.read(); - if (done) return bytes; - bytes += value.byteLength; - } - } finally { - reader.releaseLock(); - } -} - -async function measure(streams: number, bytes: number) { - const { left, right } = peers(); - const protocol = "moq-lite-07-wip"; - const client = Transport.connect({ peer: left.asPeer(), protocol }); - const server = Transport.accept({ peer: right.asPeer(), channel: right.incoming.asChannel(), protocol }); - left.channel.open(); - right.incoming.open(); - await Promise.all([client.ready, server.ready]); - const reader = server.incomingUnidirectionalStreams.getReader(); - const receiving = (async () => { - const pending: Promise[] = []; - for (let i = 0; i < streams; i++) { - const { value, done } = await reader.read(); - if (done) throw new Error("missing benchmark stream"); - pending.push(receive(value)); - } - return (await Promise.all(pending)).reduce((total, value) => total + value, 0); - })(); - const payload = new Uint8Array(bytes); - const start = performance.now(); - await Promise.all( - Array.from({ length: streams }, async () => { - const writer = (await client.createUnidirectionalStream()).getWriter(); - await writer.write(payload); - await writer.close(); - }), - ); - const delivered = await receiving; - const elapsed = performance.now() - start; - if (delivered !== streams * bytes || left.channel.records.some((record) => record.byteLength > 16384)) - throw new Error("benchmark delivery changed"); - console.log(`${streams},${bytes},${left.channel.records.length},${elapsed.toFixed(3)}`); - reader.releaseLock(); - client.close(); - await server.closed; -} - -console.log("streams,bytes_per_stream,records,elapsed_ms"); -for (const streams of [1, 8, 64]) for (const bytes of [1024, 16384, 262144]) await measure(streams, bytes); diff --git a/js/p2p/bench/tsconfig.json b/js/p2p/bench/tsconfig.json deleted file mode 100644 index 172517b5a4c..00000000000 --- a/js/p2p/bench/tsconfig.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "../tsconfig.json", "compilerOptions": { "rootDir": "..", "noEmit": true }, "include": ["transport.ts"] } diff --git a/js/p2p/bunfig.toml b/js/p2p/bunfig.toml deleted file mode 100644 index 199d28178f4..00000000000 --- a/js/p2p/bunfig.toml +++ /dev/null @@ -1,3 +0,0 @@ -[test] -# A test fails when a timer fires on the host clock, unless it called hostTime(). -preload = ["../clock/src/preload.ts"] diff --git a/js/p2p/package.json b/js/p2p/package.json deleted file mode 100644 index a25df379d04..00000000000 --- a/js/p2p/package.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "name": "@moq/p2p", - "type": "module", - "version": "0.1.0", - "description": "Media over QUIC transports over reliable WebRTC data channels.", - "license": "(MIT OR Apache-2.0)", - "repository": { - "type": "git", - "url": "git+https://github.com/moq-dev/moq.git", - "directory": "js/p2p" - }, - "sideEffects": false, - "exports": { - ".": "./src/index.ts" - }, - "scripts": { - "build": "rm -rf dist && tsc -b tsconfig.build.json && bun ../common/package.ts", - "check": "tsc --noEmit && tsc --noEmit --project bench/tsconfig.json", - "test": "bun test --only-failures" - }, - "dependencies": { - "@moq/qmux": "workspace:^" - }, - "devDependencies": { - "@moq/clock": "workspace:^", - "@types/bun": "^1.4.4", - "@typescript/lib-dom": "npm:@types/web@^0.0.358", - "typescript": "7.0.2" - }, - "private": true -} diff --git a/js/p2p/src/channel.ts b/js/p2p/src/channel.ts deleted file mode 100644 index 7e772c44f4c..00000000000 --- a/js/p2p/src/channel.ts +++ /dev/null @@ -1,190 +0,0 @@ -const RECORD_SIZE = 16 * 1024; -// Qmux-01 does not permit a smaller advertised record limit. -const MIN_RECORD_SIZE = 16382; -const SEND_WINDOW = RECORD_SIZE * 4; - -/** The data channel a {@link Channel} owns, and whether it arrived from the peer. */ -export interface ChannelProps { - /** The peer connection carrying the channel, read for its SCTP message limit. */ - peer: RTCPeerConnection; - /** The reliable ordered data channel to own. */ - channel: RTCDataChannel; - /** The negotiated MoQ ALPN. */ - protocol: string; - /** Whether the peer created the channel, so this side writes only after it hears the peer. */ - accepted: boolean; -} - -/** The WebSocketStream shape qmux consumes, backed by one owned data channel. */ -export class Channel { - readonly url = "webrtc://data-channel"; - readonly opened; - readonly closed; - maxRecordSize = RECORD_SIZE; - #open = Promise.withResolvers<{ - readable: ReadableStream; - writable: WritableStream; - extensions: string; - protocol: string; - }>(); - #closed = Promise.withResolvers<{ closeCode: number; reason: string }>(); - #drain?: ReturnType>; - #reader?: ReadableStreamDefaultController; - #ended = false; - // Pending until an accepted channel hears its dialer or starts closing, then cleared so writes skip it. - #unheard?: ReturnType>; - #readable: ReadableStream; - #writable: WritableStream; - - private peer: RTCPeerConnection; - private channel: RTCDataChannel; - private protocol: string; - - constructor({ peer, channel, protocol, accepted }: ChannelProps) { - this.peer = peer; - this.channel = channel; - this.protocol = protocol; - // Chromium reports a channel the peer announced as open before its SCTP stream is, and - // silently drops what is sent in between. Only a delivered record proves the stream open, - // and the dialing side always speaks first, so the accepting side holds its writes until it - // hears the dialer. Only writes wait: the session, and its idle deadline, start on open. - if (accepted) { - this.#unheard = Promise.withResolvers(); - void this.#unheard.promise.catch(() => {}); - } - this.opened = this.#open.promise; - this.closed = this.#closed.promise; - void this.opened.catch(() => {}); - void this.closed.catch(() => {}); - channel.binaryType = "arraybuffer"; - channel.bufferedAmountLowThreshold = SEND_WINDOW / 2; - this.#readable = new ReadableStream( - { - start: (controller) => { - this.#reader = controller; - }, - cancel: () => { - this.#reader = undefined; - this.close(); - }, - }, - new ByteLengthQueuingStrategy({ highWaterMark: SEND_WINDOW }), - ); - // An in-flight write retains the queue slot until the browser's send buffer - // falls below its low threshold, so writer.ready follows actual backpressure. - this.#writable = new WritableStream( - { - write: (data) => - this.#write(data).catch((error) => { - this.#finish(error); - throw error; - }), - close: () => this.close(), - abort: (reason) => this.#finish(reason instanceof Error ? reason : new Error(String(reason))), - }, - { highWaterMark: 1 }, - ); - channel.addEventListener("open", this.#onOpen); - channel.addEventListener("message", this.#onMessage); - channel.addEventListener("bufferedamountlow", this.#onDrain); - channel.addEventListener("close", this.#onClose); - channel.addEventListener("error", this.#onError); - if (channel.readyState === "open") this.#onOpen(); - else if (channel.readyState !== "connecting") this.#finish(new Error("data channel is already closing")); - } - - #onOpen = () => { - if (this.#ended) return; - // WebRTC reports an unbounded negotiated message size as positive Infinity. - const max = this.peer.sctp?.maxMessageSize; - if (max === undefined || Number.isNaN(max) || max < 0) { - this.#finish(new Error("data channel has no negotiated SCTP message limit")); - return; - } - this.maxRecordSize = Math.min(RECORD_SIZE, max); - if (this.maxRecordSize < MIN_RECORD_SIZE) { - this.#finish(new Error(`SCTP message limit ${max} is smaller than qmux's minimum ${MIN_RECORD_SIZE}`)); - return; - } - this.#open.resolve({ - readable: this.#readable, - writable: this.#writable, - extensions: "", - protocol: `qmux-01.${this.protocol}`, - }); - }; - - #onMessage = (event: MessageEvent) => { - if (this.#ended) return; - if (!(event.data instanceof ArrayBuffer)) { - this.#finish(new Error("qmux requires binary data-channel messages")); - return; - } - if (event.data.byteLength > this.maxRecordSize || (this.#reader?.desiredSize ?? 0) < event.data.byteLength) { - this.#finish(new Error("data-channel receive record exceeds its bounded queue")); - return; - } - this.#reader?.enqueue(new Uint8Array(event.data)); - this.release(); - }; - #onDrain = () => { - this.#drain?.resolve(); - this.#drain = undefined; - }; - #onClose = () => this.#finish(); - #onError = (event: Event) => - this.#finish("error" in event && event.error instanceof Error ? event.error : new Error("data channel failed")); - - async #wait() { - if (this.#ended || this.channel.readyState !== "open") throw new Error("data channel is closed"); - if (this.channel.bufferedAmount <= this.channel.bufferedAmountLowThreshold) return; - this.#drain ??= Promise.withResolvers(); - await this.#drain.promise; - } - - async #write(data: Uint8Array | string) { - await this.opened; - if (typeof data === "string") throw new TypeError("qmux requires binary records"); - if (data.byteLength > this.maxRecordSize) throw new RangeError("qmux record exceeds the SCTP message limit"); - if (this.#unheard) await this.#unheard.promise; - await this.#wait(); - this.channel.send(data.buffer instanceof ArrayBuffer ? (data as Uint8Array) : data.slice()); - await this.#wait(); - } - - #finish(error?: Error) { - if (this.#ended) return; - this.#ended = true; - const closed = error ?? new Error("data channel is closed"); - this.#open.reject(closed); - this.#unheard?.reject(closed); - this.#unheard = undefined; - this.#drain?.reject(closed); - this.#drain = undefined; - if (error) { - this.#reader?.error(error); - this.#closed.reject(error); - } else { - this.#reader?.close(); - this.#closed.resolve({ closeCode: 1000, reason: "" }); - } - this.#reader = undefined; - this.channel.removeEventListener("open", this.#onOpen); - this.channel.removeEventListener("message", this.#onMessage); - this.channel.removeEventListener("bufferedamountlow", this.#onDrain); - this.channel.removeEventListener("close", this.#onClose); - this.channel.removeEventListener("error", this.#onError); - this.channel.close(); - } - - /** Stop holding writes for the dialer, so a closing session can flush its close frame. */ - release() { - // A send Chromium drops now loses nothing: the channel closes once the flush settles. - this.#unheard?.resolve(); - this.#unheard = undefined; - } - - close() { - this.#finish(); - } -} diff --git a/js/p2p/src/index.ts b/js/p2p/src/index.ts deleted file mode 100644 index 1a23a3b790b..00000000000 --- a/js/p2p/src/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -/** WebTransport-shaped transports over reliable ordered WebRTC data channels. @module */ -export { type AcceptProps, type ConnectProps, Transport } from "./transport.ts"; diff --git a/js/p2p/src/mock.ts b/js/p2p/src/mock.ts deleted file mode 100644 index 7f47e7bae39..00000000000 --- a/js/p2p/src/mock.ts +++ /dev/null @@ -1,117 +0,0 @@ -class MockChannel extends EventTarget { - binaryType = "blob"; - bufferedAmount = 0; - bufferedAmountLowThreshold = 0; - readyState: RTCDataChannelState = "connecting"; - ordered = true; - maxRetransmits: number | null = null; - maxPacketLifeTime: number | null = null; - protocol: string; - partner!: MockChannel; - autoDrain = true; - // Chromium reports an announced channel open before its SCTP stream is, and drops what is - // sent in between while still counting it in bufferedAmount. - stream = true; - records: Uint8Array[] = []; - listeners = new Set(); - constructor(protocol: string) { - super(); - this.protocol = protocol; - } - override addEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: AddEventListenerOptions | boolean, - ) { - if (callback) this.listeners.add(callback); - super.addEventListener(type, callback, options); - } - override removeEventListener( - type: string, - callback: EventListenerOrEventListenerObject | null, - options?: EventListenerOptions | boolean, - ) { - if (callback) this.listeners.delete(callback); - super.removeEventListener(type, callback, options); - } - open() { - this.readyState = "open"; - this.dispatchEvent(new Event("open")); - } - send(data: Uint8Array) { - if (this.readyState !== "open") throw new Error("send on closed channel"); - const record = data.slice(); - this.records.push(record); - this.bufferedAmount += record.byteLength; - if (!this.stream) return; - queueMicrotask(() => { - if (this.partner.readyState === "open") { - // A delivered record means the stream has opened. - this.partner.stream = true; - this.partner.dispatchEvent(new MessageEvent("message", { data: record.buffer })); - } - if (this.autoDrain) this.drain(); - }); - } - drain() { - this.bufferedAmount = 0; - this.dispatchEvent(new Event("bufferedamountlow")); - } - close() { - if (this.readyState === "closed") return; - this.readyState = "closed"; - queueMicrotask(() => { - this.dispatchEvent(new Event("close")); - if (this.partner.readyState !== "closed") { - this.partner.readyState = "closed"; - this.partner.dispatchEvent(new Event("close")); - } - }); - } - asChannel(): RTCDataChannel { - return this as unknown as RTCDataChannel; - } -} - -class MockPeer { - sctp = { maxMessageSize: 65536 }; - #channel?: MockChannel; - #incoming?: MockChannel; - partner!: MockPeer; - closed = false; - options?: RTCDataChannelInit; - createDataChannel(_label: string, options: RTCDataChannelInit) { - this.options = options; - const channel = new MockChannel(options.protocol ?? ""); - const incoming = new MockChannel(options.protocol ?? ""); - channel.partner = incoming; - incoming.partner = channel; - this.#channel = channel; - this.partner.#incoming = incoming; - return channel.asChannel(); - } - get channel() { - if (!this.#channel) throw new Error("mock peer has no outgoing channel"); - return this.#channel; - } - get incoming() { - if (!this.#incoming) throw new Error("mock peer has no incoming channel"); - return this.#incoming; - } - - close() { - this.closed = true; - } - asPeer(): RTCPeerConnection { - return this as unknown as RTCPeerConnection; - } -} - -export function peers(maxMessageSize = 65536) { - const left = new MockPeer(); - const right = new MockPeer(); - left.partner = right; - right.partner = left; - left.sctp.maxMessageSize = right.sctp.maxMessageSize = maxMessageSize; - return { left, right }; -} diff --git a/js/p2p/src/transport.test.ts b/js/p2p/src/transport.test.ts deleted file mode 100644 index 66e2bfc0676..00000000000 --- a/js/p2p/src/transport.test.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { expect, test } from "bun:test"; -import { Duration, yieldNow } from "@moq/clock"; -import { Manual } from "@moq/clock/test"; -import { Channel } from "./channel.ts"; -import { peers } from "./mock.ts"; -import { Transport } from "./transport.ts"; - -const protocol = "moq-lite-07-wip"; - -function pair(maxMessageSize = 65536) { - const mock = peers(maxMessageSize); - const left = Transport.connect({ peer: mock.left.asPeer(), protocol }); - const right = Transport.accept({ peer: mock.right.asPeer(), channel: mock.right.incoming.asChannel(), protocol }); - mock.left.channel.open(); - mock.right.incoming.open(); - return { ...mock, client: left, server: right }; -} - -async function next(stream: ReadableStream): Promise { - const reader = stream.getReader(); - try { - const { value, done } = await reader.read(); - if (done) throw new Error("stream ended before its item"); - return value; - } finally { - reader.releaseLock(); - } -} - -async function readAll(stream: ReadableStream): Promise { - const reader = stream.getReader(); - const chunks: Uint8Array[] = []; - let size = 0; - while (true) { - const { value, done } = await reader.read(); - if (done) break; - chunks.push(value); - size += value.byteLength; - } - const result = new Uint8Array(size); - let offset = 0; - for (const chunk of chunks) { - result.set(chunk, offset); - offset += chunk.byteLength; - } - return result; -} - -test("qmux carries large streams in bounded binary records and preserves both stream-id roles", async () => { - for (const max of [16382, 16384, 65536, Infinity]) { - const { client, server, left, right } = pair(max); - await Promise.all([client.ready, server.ready]); - expect(left.options).toEqual({ ordered: true, protocol }); - expect(left.channel.binaryType).toBe("arraybuffer"); - expect(client.datagrams.maxDatagramSize).toBe(0); - const payload = Uint8Array.from({ length: 256 * 1024 }, (_, i) => i % 251); - const receiving = next(server.incomingUnidirectionalStreams).then(readAll); - const writer = (await client.createUnidirectionalStream()).getWriter(); - await writer.write(payload); - await writer.close(); - expect(await receiving).toEqual(payload); - const bidiIncoming = next(client.incomingBidirectionalStreams); - const bidi = await server.createBidirectionalStream(); - const response = bidi.writable.getWriter(); - await response.write(new Uint8Array([4, 2])); - await response.close(); - expect(await readAll((await bidiIncoming).readable)).toEqual(new Uint8Array([4, 2])); - expect(left.channel.records.every((record) => record.byteLength <= Math.min(16384, max))).toBe(true); - client.close({ closeCode: 42, reason: "bye" }); - expect(await server.closed).toEqual({ closeCode: 42, reason: "bye" }); - await client.closed; - expect(left.closed).toBe(false); - expect(right.closed).toBe(false); - expect(left.channel.listeners.size).toBe(0); - expect(right.incoming.listeners.size).toBe(0); - } -}); - -test("the accepting side stays silent until the dialer's first record proves its stream open", async () => { - const mock = peers(); - const client = Transport.connect({ peer: mock.left.asPeer(), protocol }); - mock.right.incoming.readyState = "open"; - mock.right.incoming.stream = false; - const server = Transport.accept({ peer: mock.right.asPeer(), channel: mock.right.incoming.asChannel(), protocol }); - // Give the accepting side every chance to speak into the dropped window. - await yieldNow(); - mock.left.channel.open(); - // The client opens a stream only on credit from the server's transport parameters. - const receiving = next(server.incomingUnidirectionalStreams).then(readAll); - const writer = (await client.createUnidirectionalStream()).getWriter(); - await writer.write(new Uint8Array([4, 2])); - await writer.close(); - expect(await receiving).toEqual(new Uint8Array([4, 2])); - client.close(); - await Promise.all([client.closed, server.closed]); -}); - -test("an accepted channel whose dialer stays silent closes at the handshake deadline without sending", async () => { - const clock = new Manual(); - const installed = clock.install(); - try { - const { left, right } = peers(); - left.createDataChannel("moq", { ordered: true, protocol }); - const server = Transport.accept({ peer: right.asPeer(), channel: right.incoming.asChannel(), protocol }); - right.incoming.open(); - // The session starts on open, so its 10 s handshake deadline runs while its first write - // waits on the silent dialer's parameters. - await clock.advance(Duration.millis(11_000)); - await expect(server.closed).rejects.toThrow("handshake timeout"); - expect(right.incoming.records).toEqual([]); - expect(right.incoming.listeners.size).toBe(0); - } finally { - installed.close(); - } -}); - -test("an accepted side that closes before hearing its dialer still closes gracefully at once", async () => { - const clock = new Manual(); - const installed = clock.install(); - try { - const mock = peers(); - const client = Transport.connect({ peer: mock.left.asPeer(), protocol }); - const server = Transport.accept({ - peer: mock.right.asPeer(), - channel: mock.right.incoming.asChannel(), - protocol, - }); - // The dialer's records are lost, so the accepting side never hears it. - mock.left.channel.stream = false; - mock.left.channel.open(); - mock.right.incoming.open(); - // Its `ready` waits for the dialer's lost parameters. The datagram writable starts once - // the session exists, which then starts on the open channel in pure microtask work. - const datagrams = server.datagrams.writable.getWriter(); - await datagrams.ready; - datagrams.releaseLock(); - for (let i = 0; i < 10; i++) await Promise.resolve(); - server.close({ closeCode: 7, reason: "bye" }); - // No clock advance: the close must not wait out qmux's flush timeout. - expect(await client.closed).toEqual({ closeCode: 7, reason: "bye" }); - expect(await server.closed).toEqual({ closeCode: 7, reason: "bye" }); - await yieldNow(); - expect(mock.right.incoming.readyState).toBe("closed"); - expect(mock.right.incoming.listeners.size).toBe(0); - } finally { - installed.close(); - } -}); - -test("close before the channel opens settles closed and rejects ready without closing the peer", async () => { - const { left } = peers(); - const transport = Transport.connect({ peer: left.asPeer(), protocol }); - transport.close({ closeCode: 7, reason: "cancelled" }); - expect(await transport.closed).toEqual({ closeCode: 7, reason: "cancelled" }); - await expect(transport.ready).rejects.toThrow("closed"); - expect(left.channel.readyState).toBe("closed"); - expect(left.closed).toBe(false); - expect(left.channel.listeners.size).toBe(0); -}); - -test("accept refuses partial reliability, unordered delivery, and a different negotiated protocol", () => { - for (const change of [ - { ordered: false }, - { maxRetransmits: 1 }, - { maxPacketLifeTime: 10 }, - { protocol: "other" }, - ]) { - const { left, right } = peers(); - left.createDataChannel("moq", { ordered: true, protocol }); - Object.assign(right.incoming, change); - expect(() => - Transport.accept({ peer: right.asPeer(), channel: right.incoming.asChannel(), protocol }), - ).toThrow(); - } - expect(() => Transport.connect({ peer: peers().left.asPeer(), protocol: "" })).toThrow("ALPN"); -}); - -test("an SCTP message limit below qmux's protocol minimum is refused", async () => { - const { client, server, left } = pair(8192); - await expect(client.ready).rejects.toThrow("minimum"); - await expect(server.ready).rejects.toThrow(); - await expect(client.closed).rejects.toThrow("minimum"); - expect(left.channel.listeners.size).toBe(0); -}); - -test("writer.ready follows bufferedamountlow and closing releases a blocked write", async () => { - const { left } = peers(); - const channel = left.createDataChannel("moq", { ordered: true, protocol }); - left.channel.autoDrain = false; - const socket = new Channel({ peer: left.asPeer(), channel, protocol, accepted: false }); - left.channel.open(); - const { writable } = await socket.opened; - const writer = writable.getWriter(); - const record = new Uint8Array(16384); - await writer.write(record); - await writer.write(record); - const pending = writer.write(record); - let sent = false; - void pending.then( - () => { - sent = true; - }, - () => {}, - ); - await Promise.resolve(); - await Promise.resolve(); - expect(writer.desiredSize).toBe(0); - expect(sent).toBe(false); - left.channel.drain(); - await pending; - expect(sent).toBe(true); - await writer.write(record); - await writer.write(record); - const blocked = writer.write(record); - await Promise.resolve(); - socket.close(); - await expect(blocked).rejects.toThrow("closed"); - expect(left.channel.listeners.size).toBe(0); -}); - -test("malformed binary input and an overflowing receive queue close the channel", async () => { - for (const data of ["text", new ArrayBuffer(16385), new ArrayBuffer(16384)]) { - const { left } = peers(); - const channel = left.createDataChannel("moq", { ordered: true, protocol }); - const socket = new Channel({ peer: left.asPeer(), channel, protocol, accepted: false }); - left.channel.open(); - await socket.opened; - if (data instanceof ArrayBuffer && data.byteLength === 16384) { - for (let i = 0; i < 4; i++) left.channel.dispatchEvent(new MessageEvent("message", { data })); - } - left.channel.dispatchEvent(new MessageEvent("message", { data })); - await expect(socket.closed).rejects.toThrow(); - expect(left.channel.listeners.size).toBe(0); - } -}); - -test("each side holds more than qmux's default of 100 streams open in each direction", async () => { - const { client, server } = pair(); - await Promise.all([client.ready, server.ready]); - // Refused at once, rather than waiting, past the peer's stream limit. - const now = { waitUntilAvailable: false }; - for (let i = 0; i < 150; i++) { - await client.createUnidirectionalStream(now); - await client.createBidirectionalStream(now); - await server.createUnidirectionalStream(now); - await server.createBidirectionalStream(now); - } - client.close(); - await Promise.all([client.closed, server.closed]); -}); - -test("incoming stream cancellation waits for the channel to open", async () => { - const mock = peers(); - const client = Transport.connect({ peer: mock.left.asPeer(), protocol }); - const server = Transport.accept({ peer: mock.right.asPeer(), channel: mock.right.incoming.asChannel(), protocol }); - const cancelled = client.incomingUnidirectionalStreams.cancel(); - mock.left.channel.open(); - mock.right.incoming.open(); - await cancelled; - await Promise.all([client.ready, server.ready]); - client.close(); - await Promise.all([client.closed, server.closed]); -}); diff --git a/js/p2p/src/transport.ts b/js/p2p/src/transport.ts deleted file mode 100644 index a734faee01c..00000000000 --- a/js/p2p/src/transport.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { type SendStreamOptions, Session } from "@moq/qmux"; -import { Channel } from "./channel.ts"; - -/** The peer connection and the MoQ ALPN agreed through signaling. */ -export interface ConnectProps { - /** The caller-owned peer connection. */ - peer: RTCPeerConnection; - /** The negotiated MoQ ALPN, such as moq-lite-07-wip. */ - protocol: string; -} - -/** An incoming data channel and its agreed MoQ protocol. */ -export interface AcceptProps extends ConnectProps { - /** The reliable ordered data channel whose ownership transfers to the transport. */ - channel: RTCDataChannel; -} - -function incoming(stream: Promise>): ReadableStream { - const opened = stream.then((stream) => stream.getReader()); - return new ReadableStream({ - async start() { - await opened; - }, - async pull(controller) { - const reader = await opened; - const { value, done } = await reader.read(); - if (done) { - reader.releaseLock(); - controller.close(); - } else controller.enqueue(value); - }, - async cancel(reason) { - const reader = await opened; - await reader.cancel(reason); - reader.releaseLock(); - }, - }); -} - -/** A WebTransport-shaped handle owning one reliable ordered data channel. */ -export class Transport implements WebTransport { - /** The transport label used by MoQ connection statistics. */ - readonly transport = "webrtc"; - /** The MoQ ALPN agreed through signaling. */ - readonly protocol: string; - /** Resolves once the channel and qmux session are ready. */ - readonly ready: Promise; - /** Resolves on an application close or rejects on transport failure. */ - readonly closed: Promise; - /** The connection uses reliable delivery only. */ - readonly reliability = "reliable-only"; - /** SCTP controls congestion for the connection. */ - readonly congestionControl = "default"; - /** Incoming bidirectional qmux streams. */ - readonly incomingBidirectionalStreams: ReadableStream; - /** Incoming unidirectional qmux streams. */ - readonly incomingUnidirectionalStreams: ReadableStream>; - /** Datagram-shaped streams with a zero send limit, since this binding has no datagrams. */ - readonly datagrams: WebTransportDatagramDuplexStream; - #session: Promise; - #active?: Session; - #socket: Channel; - #closing = false; - #closed = Promise.withResolvers(); - - private constructor({ peer, channel, protocol }: AcceptProps, server: boolean) { - if (!protocol || /\s/.test(protocol)) throw new TypeError("a negotiated MoQ ALPN is required"); - if (!channel.ordered || channel.maxRetransmits !== null || channel.maxPacketLifeTime !== null) { - throw new TypeError("qmux requires a reliable ordered data channel"); - } - if (channel.protocol !== protocol) throw new TypeError("data-channel protocol does not match the agreed ALPN"); - this.protocol = protocol; - this.#socket = new Channel({ peer, channel, protocol, accepted: server }); - this.closed = this.#closed.promise; - // SCTP's negotiated limit is known only after the data channel opens. - this.#session = this.#socket.opened.then(() => { - if (this.#closing) throw new Error("transport closed before opening"); - // MoQ holds a stream open per subscription and per live group, far past qmux's default - // of 100 each way. Matches the stream limit of Rust's sessions. - const config = { - maxStreamsBidi: 10_000n, - maxStreamsUni: 10_000n, - maxRecordSize: BigInt(this.#socket.maxRecordSize), - maxDatagramFrameSize: null, - }; - const session = server - ? Session.accept(this.#socket, { config, protocol: `qmux-01.${protocol}` }) - : new Session(this.#socket, { config }); - this.#active = session; - void session.closed.then(this.#closed.resolve, this.#closed.reject); - return session; - }); - this.ready = this.#session.then((session) => session.ready); - void this.ready.catch((error) => { - // A session that started settles `closed` and closes the channel itself, gracefully - // when closed before its handshake finished. Only a channel that never opened has none. - if (this.#active) return; - this.#closed.reject(error); - this.#socket.close(); - }); - void this.closed.catch(() => {}); - this.incomingBidirectionalStreams = incoming( - this.#session.then((session) => session.incomingBidirectionalStreams), - ); - this.incomingUnidirectionalStreams = incoming( - this.#session.then((session) => session.incomingUnidirectionalStreams), - ); - let writer: WritableStreamDefaultWriter; - this.datagrams = { - maxDatagramSize: 0, - incomingHighWaterMark: 1, - incomingMaxAge: null, - outgoingHighWaterMark: 1, - outgoingMaxAge: null, - readable: incoming(this.#session.then((session) => session.datagrams.readable)), - writable: new WritableStream({ - start: async () => { - writer = (await this.#session).datagrams.writable.getWriter(); - }, - write: (data) => writer.write(data), - close: () => writer.close(), - abort: (reason) => writer.abort(reason), - }), - }; - } - - /** Create a reliable ordered data channel, leaving the peer connection with its caller. */ - static connect({ peer, protocol }: ConnectProps): Transport { - if (!protocol || /\s/.test(protocol)) throw new TypeError("a negotiated MoQ ALPN is required"); - const channel = peer.createDataChannel("moq", { ordered: true, protocol }); - try { - return new Transport({ peer, channel, protocol }, false); - } catch (error) { - channel.close(); - throw error; - } - } - - /** Adopt an incoming reliable ordered data channel, leaving the peer connection with its caller. */ - static accept(props: AcceptProps): Transport { - return new Transport(props, true); - } - - /** Open a bidirectional qmux stream. */ - async createBidirectionalStream(options?: SendStreamOptions): Promise { - return (await this.#session).createBidirectionalStream(options); - } - - /** Open a unidirectional qmux stream. */ - async createUnidirectionalStream(options?: SendStreamOptions): Promise> { - return (await this.#session).createUnidirectionalStream(options); - } - - /** Close the qmux session and its data channel. */ - close(info: WebTransportCloseInfo = {}) { - if (this.#closing) return; - if (this.#active) { - this.#socket.release(); - this.#active.close(info); - this.#closing = true; - } else { - this.#closing = true; - this.#closed.resolve(info); - this.#socket.close(); - } - } - - /** Refuse HTTP/3 statistics, which this data-channel binding does not provide. */ - async getStats(): Promise { - throw new Error("WebTransport connection statistics are unavailable over WebRTC"); - } -} diff --git a/js/p2p/tsconfig.build.json b/js/p2p/tsconfig.build.json deleted file mode 100644 index 2bd3a373587..00000000000 --- a/js/p2p/tsconfig.build.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "extends": "./tsconfig.json", - "exclude": ["src/**/*.test.ts", "src/mock.ts"] -} diff --git a/js/p2p/tsconfig.json b/js/p2p/tsconfig.json deleted file mode 100644 index d49d1326bbf..00000000000 --- a/js/p2p/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../tsconfig.json", - "compilerOptions": { "rootDir": "./src", "outDir": "dist", "types": ["bun"] }, - "include": ["src"] -} diff --git a/nix/Cargo.nix b/nix/Cargo.nix index e083b7f46bc..926169dc5ac 100644 --- a/nix/Cargo.nix +++ b/nix/Cargo.nix @@ -10077,7 +10077,6 @@ rec { "dep:js-sys" ]; }; - resolvedDefaultFeatures = [ "std" ]; }; "getrandom 0.4.3" = rec { crateName = "getrandom"; @@ -12750,7 +12749,6 @@ rec { features = { "std" = [ "digest/std" ]; }; - resolvedDefaultFeatures = [ "reset" ]; }; "hmac 0.13.0" = rec { crateName = "hmac"; @@ -20432,11 +20430,6 @@ rec { "base64" ]; } - { - name = "stun-types"; - packageId = "stun-types"; - optional = true; - } { name = "sysinfo"; packageId = "sysinfo"; @@ -20581,10 +20574,6 @@ rec { target = { target, features }: ("linux" == target."os" or null); features = [ "all" ]; } - { - name = "stun-types"; - packageId = "stun-types"; - } { name = "tempfile"; packageId = "tempfile"; @@ -20638,7 +20627,6 @@ rec { "_quic" "moq-tokio/quic" ]; - "stun" = [ "dep:stun-types" ]; "test-support" = [ "moq-tokio/sim" ]; "uds" = [ "moq-tokio/uds" ]; "websocket" = [ @@ -20657,7 +20645,6 @@ rec { "jemalloc" "qlog" "quic" - "stun" "test-support" "uds" "websocket" @@ -22681,10 +22668,6 @@ rec { "tracing" ]; } - { - name = "base64ct"; - packageId = "base64ct"; - } { name = "bytes"; packageId = "bytes"; @@ -22710,22 +22693,11 @@ rec { name = "hang"; packageId = "hang"; } - { - name = "if-addrs"; - packageId = "if-addrs"; - optional = true; - } { name = "kio"; packageId = "kio"; features = [ "runtime" ]; } - { - name = "mdns-sd"; - packageId = "mdns-sd"; - optional = true; - features = [ "async" ]; - } { name = "moq-crypto"; packageId = "moq-crypto"; @@ -22756,12 +22728,6 @@ rec { name = "once_cell"; packageId = "once_cell"; } - { - name = "qmux"; - packageId = "qmux 0.7.0"; - optional = true; - usesDefaultFeatures = false; - } { name = "rand"; packageId = "rand 0.10.3"; @@ -22786,27 +22752,15 @@ rec { name = "rind-rcgen"; packageId = "rind-rcgen"; } - { - name = "rustc-hash"; - packageId = "rustc-hash 2.1.3"; - } { name = "serde"; packageId = "serde"; features = [ "derive" ]; } - { - name = "slab"; - packageId = "slab"; - } { name = "spki"; packageId = "spki 0.8.1"; } - { - name = "stun-types"; - packageId = "stun-types"; - } { name = "subtle"; packageId = "subtle"; @@ -22845,10 +22799,6 @@ rec { } ]; devDependencies = [ - { - name = "futures"; - packageId = "futures"; - } { name = "moq-tokio"; packageId = "moq-tokio"; @@ -22891,17 +22841,10 @@ rec { ]; features = { "default" = [ "server" ]; - "p2p" = [ - "dep:if-addrs" - "dep:mdns-sd" - "dep:qmux" - "moq-tokio/qmux" - ]; "server" = [ "dep:axum" ]; }; resolvedDefaultFeatures = [ "default" - "p2p" "server" ]; }; @@ -39847,7 +39790,7 @@ rec { } { name = "rand_chacha"; - packageId = "rand_chacha 0.3.1"; + packageId = "rand_chacha"; optional = true; usesDefaultFeatures = false; } @@ -39889,62 +39832,7 @@ rec { "std_rng" ]; }; - "rand 0.9.5" = rec { - crateName = "rand"; - version = "0.9.5"; - edition = "2021"; - sha256 = "0hbvllk8g28mqjld6hqmckk69w296qpzg95whm3didsyg46ivvxr"; - authors = [ - "The Rand Project Developers" - "The Rust Project Developers" - ]; - dependencies = [ - { - name = "rand_chacha"; - packageId = "rand_chacha 0.9.0"; - optional = true; - usesDefaultFeatures = false; - } - { - name = "rand_core"; - packageId = "rand_core 0.9.5"; - usesDefaultFeatures = false; - } - ]; - features = { - "default" = [ - "std" - "std_rng" - "os_rng" - "small_rng" - "thread_rng" - ]; - "os_rng" = [ "rand_core/os_rng" ]; - "serde" = [ - "dep:serde" - "rand_core/serde" - ]; - "std" = [ - "rand_core/std" - "rand_chacha?/std" - "alloc" - ]; - "std_rng" = [ "dep:rand_chacha" ]; - "thread_rng" = [ - "std" - "std_rng" - "os_rng" - ]; - }; - resolvedDefaultFeatures = [ - "alloc" - "os_rng" - "std" - "std_rng" - "thread_rng" - ]; - }; - "rand_chacha 0.3.1" = rec { + "rand_chacha" = rec { crateName = "rand_chacha"; version = "0.3.1"; edition = "2018"; @@ -39974,46 +39862,6 @@ rec { }; resolvedDefaultFeatures = [ "std" ]; }; - "rand_chacha 0.9.0" = rec { - crateName = "rand_chacha"; - version = "0.9.0"; - edition = "2021"; - sha256 = "1jr5ygix7r60pz0s1cv3ms1f6pd1i9pcdmnxzzhjc3zn3mgjn0nk"; - authors = [ - "The Rand Project Developers" - "The Rust Project Developers" - "The CryptoCorrosion Contributors" - ]; - dependencies = [ - { - name = "ppv-lite86"; - packageId = "ppv-lite86"; - usesDefaultFeatures = false; - features = [ "simd" ]; - } - { - name = "rand_core"; - packageId = "rand_core 0.9.5"; - } - ]; - devDependencies = [ - { - name = "rand_core"; - packageId = "rand_core 0.9.5"; - features = [ "os_rng" ]; - } - ]; - features = { - "default" = [ "std" ]; - "os_rng" = [ "rand_core/os_rng" ]; - "serde" = [ "dep:serde" ]; - "std" = [ - "ppv-lite86/std" - "rand_core/std" - ]; - }; - resolvedDefaultFeatures = [ "std" ]; - }; "rand_core 0.10.1" = rec { crateName = "rand_core"; version = "0.10.1"; @@ -40056,32 +39904,6 @@ rec { "std" ]; }; - "rand_core 0.9.5" = rec { - crateName = "rand_core"; - version = "0.9.5"; - edition = "2021"; - sha256 = "0g6qc5r3f0hdmz9b11nripyp9qqrzb0xqk9piip8w8qlvqkcibvn"; - authors = [ - "The Rand Project Developers" - "The Rust Project Developers" - ]; - dependencies = [ - { - name = "getrandom"; - packageId = "getrandom 0.3.4"; - optional = true; - } - ]; - features = { - "os_rng" = [ "dep:getrandom" ]; - "serde" = [ "dep:serde" ]; - "std" = [ "getrandom?/std" ]; - }; - resolvedDefaultFeatures = [ - "os_rng" - "std" - ]; - }; "rand_pcg" = rec { crateName = "rand_pcg"; version = "0.10.2"; @@ -43845,7 +43667,7 @@ rec { } { name = "sha1"; - packageId = "sha1 0.11.0"; + packageId = "sha1"; } { name = "sha2"; @@ -44158,7 +43980,7 @@ rec { } { name = "sha1"; - packageId = "sha1 0.11.0"; + packageId = "sha1"; } { name = "smallvec"; @@ -45573,49 +45395,7 @@ rec { "std" ]; }; - "sha1 0.10.7" = rec { - crateName = "sha1"; - version = "0.10.7"; - edition = "2018"; - sha256 = "1f632d529qzz95yrprr632w1fxqkrv6b6jksjc11vnzl049lay59"; - authors = [ - "RustCrypto Developers" - ]; - dependencies = [ - { - name = "cfg-if"; - packageId = "cfg-if"; - } - { - name = "cpufeatures"; - packageId = "cpufeatures 0.2.17"; - target = - { target, features }: - ( - ("aarch64" == target."arch" or null) - || ("x86" == target."arch" or null) - || ("x86_64" == target."arch" or null) - ); - } - { - name = "digest"; - packageId = "digest 0.10.7"; - } - ]; - devDependencies = [ - { - name = "digest"; - packageId = "digest 0.10.7"; - features = [ "dev" ]; - } - ]; - features = { - "default" = [ "std" ]; - "oid" = [ "digest/oid" ]; - "std" = [ "digest/std" ]; - }; - }; - "sha1 0.11.0" = rec { + "sha1" = rec { crateName = "sha1"; version = "0.11.0"; edition = "2024"; @@ -47024,95 +46804,6 @@ rec { ]; }; - "stun-types" = rec { - crateName = "stun-types"; - version = "2.0.4"; - edition = "2021"; - sha256 = "0b8r78yzp3n2rpxanzfcjzkzw74bym739dzrimmjaqjxmpjpnkh3"; - libName = "stun_types"; - authors = [ - "Matthew Waters " - ]; - dependencies = [ - { - name = "byteorder"; - packageId = "byteorder"; - usesDefaultFeatures = false; - } - { - name = "crc"; - packageId = "crc"; - } - { - name = "hmac"; - packageId = "hmac 0.12.1"; - } - { - name = "md-5"; - packageId = "md-5 0.10.6"; - usesDefaultFeatures = false; - } - { - name = "rand"; - packageId = "rand 0.9.5"; - usesDefaultFeatures = false; - features = [ "os_rng" ]; - } - { - name = "sha1"; - packageId = "sha1 0.10.7"; - usesDefaultFeatures = false; - } - { - name = "sha2"; - packageId = "sha2 0.10.9"; - usesDefaultFeatures = false; - } - { - name = "smallvec"; - packageId = "smallvec"; - } - { - name = "subtle"; - packageId = "subtle"; - } - { - name = "thiserror"; - packageId = "thiserror 2.0.21"; - usesDefaultFeatures = false; - } - { - name = "tracing"; - packageId = "tracing"; - usesDefaultFeatures = false; - features = [ "attributes" ]; - } - ]; - devDependencies = [ - { - name = "tracing"; - packageId = "tracing"; - usesDefaultFeatures = false; - features = [ - "attributes" - "std" - ]; - } - ]; - features = { - "arbitrary" = [ "dep:arbitrary" ]; - "default" = [ "std" ]; - "std" = [ - "thiserror/std" - "rand/thread_rng" - "hmac/reset" - ]; - }; - resolvedDefaultFeatures = [ - "default" - "std" - ]; - }; "subtle" = rec { crateName = "subtle"; version = "2.6.1"; @@ -51058,7 +50749,7 @@ rec { } { name = "sha1"; - packageId = "sha1 0.11.0"; + packageId = "sha1"; optional = true; } { @@ -58669,10 +58360,6 @@ rec { target = { target, features }: (target.name == "x86_64-unknown-linux-gnu"); features = [ "aarch64_simd" ]; } - { - name = "byteorder"; - packageId = "byteorder"; - } { name = "bytes"; packageId = "bytes"; @@ -58996,12 +58683,6 @@ rec { name = "hex"; packageId = "hex"; } - { - name = "hmac"; - packageId = "hmac 0.12.1"; - usesDefaultFeatures = false; - features = [ "reset" ]; - } { name = "hyper"; packageId = "hyper"; @@ -59173,15 +58854,9 @@ rec { usesDefaultFeatures = false; features = [ "std" ]; } - { - name = "md-5"; - packageId = "md-5 0.10.6"; - rename = "md-5-93f6ce9d446188ac"; - } { name = "md-5"; packageId = "md-5 0.11.0"; - rename = "md-5-a6292c17cd707f01"; } { name = "memchr"; @@ -59583,10 +59258,6 @@ rec { "json" ]; } - { - name = "sha2"; - packageId = "sha2 0.10.9"; - } { name = "siphasher"; packageId = "siphasher"; @@ -60125,10 +59796,6 @@ rec { target = { target, features }: (target.name == "x86_64-unknown-linux-gnu"); features = [ "aarch64_simd" ]; } - { - name = "byteorder"; - packageId = "byteorder"; - } { name = "bytes"; packageId = "bytes"; @@ -60472,12 +60139,6 @@ rec { name = "hex"; packageId = "hex"; } - { - name = "hmac"; - packageId = "hmac 0.12.1"; - usesDefaultFeatures = false; - features = [ "reset" ]; - } { name = "hyper"; packageId = "hyper"; @@ -60649,15 +60310,9 @@ rec { usesDefaultFeatures = false; features = [ "std" ]; } - { - name = "md-5"; - packageId = "md-5 0.10.6"; - rename = "md-5-93f6ce9d446188ac"; - } { name = "md-5"; packageId = "md-5 0.11.0"; - rename = "md-5-a6292c17cd707f01"; } { name = "memchr"; @@ -61047,10 +60702,6 @@ rec { "json" ]; } - { - name = "sha2"; - packageId = "sha2 0.10.9"; - } { name = "siphasher"; packageId = "siphasher"; diff --git a/package.json b/package.json index fea5fa7c0f4..b45999aaa4d 100644 --- a/package.json +++ b/package.json @@ -38,7 +38,6 @@ "doc", "doc/.vitepress/api", "js/net", - "js/p2p", "js/qmux", "js/clock", "js/pattern", @@ -66,7 +65,6 @@ "test/receive-credit", "test/stream-credit", "test/video", - "test/p2p", "test/qmux", "test/worklet" ], diff --git a/quest/m2/cluster-routes/README.md b/quest/m2/cluster-routes/README.md index 4f9c28e3070..2617d74b61c 100644 --- a/quest/m2/cluster-routes/README.md +++ b/quest/m2/cluster-routes/README.md @@ -33,7 +33,7 @@ claim whose withdrawal is already known. The items below were decided 2026-11-10 (maintainer, /quest-plan on lite-07 routing), which reopened the route layer's rules after the echo ordering bug. -18. ✅ Asked who is an origin node: **every publisher stays an origin node.** Its identity is for signing, for one node across several links (redundant publishers), and because browsers will forward ([browser mesh](/quest/m5/browser-mesh.md)). Rejected: a relay originating, under its own Node ID, the claims of any peer that sends no Node ID or holds a scoped publish grant, as it already does for lite-06 and moq-transport publishers. That would make route state follow relays rather than publishers and remove qualified Node IDs, the Route Key, and the echo, but a publisher would have no identity of its own. Accepted cost: routes, holds, and seqno requests scale with publishers, so a node must still forget dead identities, and the echo that makes forgetting safe has to be sound. +18. ✅ Asked who is an origin node: **every publisher stays an origin node.** Its identity is for signing, for one node across several links (redundant publishers), and because browsers may forward (peer-to-peer routing, outside this repository since 2026-11-14). Rejected: a relay originating, under its own Node ID, the claims of any peer that sends no Node ID or holds a scoped publish grant, as it already does for lite-06 and moq-transport publishers. That would make route state follow relays rather than publishers and remove qualified Node IDs, the Route Key, and the echo, but a publisher would have no identity of its own. Accepted cost: routes, holds, and seqno requests scale with publishers, so a node must still forget dead identities, and the echo that makes forgetting safe has to be sound. 19. ✅ Asked whether to keep them: **ROUTE_HOLD stays, and the newest floor wins per identity.** Rejected: dropping holds, where each stall takes every claim behind the node offline and re-sends them all; and claims that follow only the selected next hop, which re-pulls a node's whole claim table on each next-hop change and showed revivals and false ENDs in the sweeps below. 20. ✅ Asked when an origin advances its seqno unprompted: **only when a route link changes**, implemented as a bump when a route link closes. Rejected: only to answer a ROUTE_REQUEST; keeping the per-stream bump. 21. ✅ Asked how one side's routing messages travel so none overtakes another: **one unidirectional Announce Stream per side**, carrying its requests, its answers, and its echoes in order ([the route stream](/quest/m2/cluster-routes/route-stream.md)). It replaces "There MAY be multiple Announce Streams". Rejected: one bidirectional Announce Stream per direction with the echo moved to the answering half; one bidirectional stream per session. diff --git a/quest/m3/cluster-routing/README.md b/quest/m3/cluster-routing/README.md index 0a259809ddb..aa41bb6423d 100644 --- a/quest/m3/cluster-routing/README.md +++ b/quest/m3/cluster-routing/README.md @@ -3,13 +3,14 @@ ## Goal One routing model serves CDN tiers, outbound-connected local clusters, and -application-selected P2P connections. Topology changes update reachability +application-selected peer connections. Topology changes update reachability per affected origin rather than replaying every advertisement behind it. Known advertisements remain distinct from current reachability, and stale copies cannot revive a claim after its withdrawal is known. -Reliability, federation, and P2P are independently shippable milestones of -this architecture. Active/passive delivery health is out of scope; its +Reliability and federation are independently shippable milestones of this +architecture. Peer-to-peer routing left the repository 2026-11-14 +(maintainer); this model stays what it builds on. Active/passive delivery health is out of scope; its plan was deleted 2026-11-09 for want of a consumer. ## Plan @@ -98,16 +99,16 @@ Decided with the maintainer, 2026-10-13: the two-view export plan.) - A local per-connection `proxy` preference decides whether a connection is sent routes learned from other connections. Relays default on; - applications choose per P2P connection (on for redundancy, off for + applications choose per peer connection (on for redundancy, off for conference offload). Browser tabs stay off until the [Rust model runs in the browser](/quest/m5/rs2ts-js.md). Applications - explicitly select P2P connections; discovery does not dial everyone. + explicitly select peer connections; discovery does not dial everyone. - Each CDN broadcast enters a local network once by configuration: local peers outrank a backup uplink, and origin aggregation joins the rest. -- The deferred P2P consumer owns proving that its CDN session and discovery - stay connected and unused CDN media demand is released after a handoff. - m1 provides and tests the shared routing primitives without requiring an - actual P2P integration. +- A peer-to-peer consumer, outside this repository, owns proving that its CDN + session and discovery stay connected and unused CDN media demand is released + after a handoff. m1 provides and tests the shared routing primitives without + requiring an actual peer-to-peer integration. The handoff proof showed a complete neighbor snapshot does not prove its claims are current; receivers merge origin-versioned views by floor instead. @@ -157,8 +158,7 @@ setup after the capabilities land. ## Related -- [P2P](/quest/m4/p2p/README.md) - application-selected peer sessions feed the shared routing model -- [Routing guide](/quest/m3/routing-guide.md) - concept page and federation setup; P2P extends it in m4 +- [Routing guide](/quest/m3/routing-guide.md) - concept page and federation setup - [Route wakes](/quest/m4/route-wakes.md) - local work follows affected fronts rather than the whole covered table - [Link quality](/quest/m5/link-quality.md) - optional measured link cost, distinct from delivery-health failover - [Cache-aware routing](/quest/m3/cache-routing/README.md) - per-broadcast warm routes ranked against these node routes diff --git a/quest/m3/cluster-routing/federation.md b/quest/m3/cluster-routing/federation.md index d9239984dd7..316d8daac8c 100644 --- a/quest/m3/cluster-routing/federation.md +++ b/quest/m3/cluster-routing/federation.md @@ -10,7 +10,7 @@ cluster with two uplinks, partition, and healing. No bespoke federation router. ## Plan Decided 2026-10-13: this is a required use case, independently shippable from -browser P2P. Existing cluster sessions are bidirectional and scoped peer +peer-to-peer routing. Existing cluster sessions are bidirectional and scoped peer admission exists; extend and prove those paths rather than creating a reverse connection protocol. Do not require an inbound connection to the local relay. diff --git a/quest/m3/mesh/README.md b/quest/m3/mesh/README.md index 268b1d25a54..ff81e9d406e 100644 --- a/quest/m3/mesh/README.md +++ b/quest/m3/mesh/README.md @@ -48,7 +48,7 @@ Decided 2026-10-25 with the maintainer (planning interview), still in force: service implements the same contract with its own accounts and billing. - Direct paths only to addresses a node can already dial: `[cluster.lan]` mDNS, plus [address hints](/quest/m3/mesh/addr.md) published on mesh - tracks. No ICE, STUN, or hole punching; the [P2P](/quest/m4/p2p/README.md) + tracks. No ICE, STUN, or hole punching; the P2P line is separate. - An endpoint ID is a persistent Ed25519 device key, iroh-style. It is not the [routing identity](/quest/m2/cluster-routes/README.md), which each @@ -132,7 +132,6 @@ Decided 2026-11-12 (maintainer, /quest-audit before the cut): - [Outbound federation](/quest/m3/cluster-routing/federation.md) - the relay node requires it; the other children do not - [Rust byte streams](/quest/m1/stream/rust.md) - the Endpoint requires it; the other children do not -- [P2P](/quest/m4/p2p/README.md) - internet peer sessions, which the m3 mesh does not use - [Mesh over ICE](/quest/m5/mesh-ice.md) - deferred direct paths between mesh nodes on different networks - [End-to-end encryption](/quest/m5/e2ee/README.md) - the AEAD the encryption level will reuse - [Teleoperation](/quest/m5/teleop-robot.md) - robot track conventions that could ride the mesh diff --git a/quest/m3/one-port/README.md b/quest/m3/one-port/README.md index 3918a191b5c..6dae827a7de 100644 --- a/quest/m3/one-port/README.md +++ b/quest/m3/one-port/README.md @@ -20,8 +20,7 @@ a blocker for this line. ## Plan -Deferred to m2 in the 2026-09-30 audit: the consumer is moq.pro's edge, and -STUN's only consumer is P2P, deferred to m2. SRT is not blocked upstream: +Deferred to m2 in the 2026-09-30 audit: the consumer is moq.pro's edge. SRT is not blocked upstream: [SRT demux](/quest/m3/one-port/srt-demux.md) decided on 2026-09-30 to drive sans-io `srt-protocol` directly instead of waiting on a socket abstraction in srt-tokio. @@ -35,8 +34,7 @@ them. The UDP demux has landed: `moq_sock::demux` classifies, and the tokio QUIC listener's socket diverts the WebRTC media path inline in its receive to a `moq_tokio::quic::demux::WebRtc` feed, which `moq_relay::Relay::webrtc` -hands an embedder. [Native pairs](/quest/m4/p2p/native-quic.md) reuse the -classifier. QUIC shard steering landed in #5638; reuse its filter rather than +hands an embedder. QUIC shard steering landed in #5638; reuse its filter rather than recreating that completed work. Decided 2026-10-31 by the maintainer, in @@ -85,13 +83,12 @@ decided. ### STUN -Decided 2026-10-08: the public STUN responder is left to P2P (m4), its -only consumer. Here, a Binding request carrying USERNAME is an ICE check -and goes to WebRTC, as does every Binding response, since the WebRTC agent -runs full ICE and only it sends requests from this port. Any other STUN is -dropped and counted. Decided 2026-10-13: -the responder binds its own port ([relay STUN](/doc/bin/relay/config.md#stun)), -so the shared port never answers public Binding requests. +A Binding request carrying USERNAME is an ICE check and goes to WebRTC, as +does every Binding response, since the WebRTC agent runs full ICE and only it +sends requests from this port. Any other STUN is dropped and counted: the +shared port never answers public Binding requests. Decided 2026-11-14 +(maintainer): the relay serves no public STUN responder, since peer-to-peer +routing, its only consumer, left the repository. ## Related diff --git a/quest/m3/release/npm-first-publish.md b/quest/m3/release/npm-first-publish.md index d95dc2abdcc..6e1225bc00c 100644 --- a/quest/m3/release/npm-first-publish.md +++ b/quest/m3/release/npm-first-publish.md @@ -41,10 +41,6 @@ published to npm yet` install failure on every run (noted 2026-11-03 from [run 41591680387](https://github.com/moq-dev/moq/actions/runs/41591680387)); it clears with the same publication. -`@moq/p2p` is out of scope: it is private with no release script, so the cut -does not publish it. [Watch opts in](/quest/m4/p2p/watch.md) owns its first -publication, including claiming its names. - Decided 2026-11-06 (maintainer, /quest-unblock): JSR is dropped (every `@moq` JSR package was archived on 2026-11-07), so no JSR names are claimed. diff --git a/quest/m3/routing-guide.md b/quest/m3/routing-guide.md index deaabd3b01f..93749bd9dad 100644 --- a/quest/m3/routing-guide.md +++ b/quest/m3/routing-guide.md @@ -13,9 +13,7 @@ by its own milestone. ✅ m3 (rejected: m2, where the cut would wait on it; pulling the m2 blocker into m1). It ranks right after m2, when it can start. The 2026-10-15 release audit kept federation guidance in m1, until the move -above. Deferred P2P -owns the later application-selected peer setup and extends this concept page. -Every feature PR still fixes docs it makes stale. +above. Every feature PR still fixes docs it makes stale. Walk an outbound-only local relay through scoped admission, two-way delivery, two uplinks, and partition/healing. Explain application-owned connection diff --git a/quest/m3/uring-demux.md b/quest/m3/uring-demux.md index 45c86759606..6cea9110bbf 100644 --- a/quest/m3/uring-demux.md +++ b/quest/m3/uring-demux.md @@ -18,8 +18,8 @@ customer feature, and moq.pro already ranks one-port above its uring rollout. Decided 2026-10-08: the UDP demux shrinks to QUIC plus the WebRTC hook, and -the public STUN responder belongs to the deferred m4 P2P line, so the ring carries no -STUN responder class either. An ICE Binding request is WebRTC traffic and +the relay serves no public STUN responder, so the ring carries no STUN +responder class either. An ICE Binding request is WebRTC traffic and follows that class. Each worker's endpoint receives a batch and feeds every segment straight to diff --git a/quest/m3/vendor-sync/README.md b/quest/m3/vendor-sync/README.md index f760fd1f7e6..cae29bca83e 100644 --- a/quest/m3/vendor-sync/README.md +++ b/quest/m3/vendor-sync/README.md @@ -58,8 +58,8 @@ moq-audio's NetEq time stretch port, once part of the WebRTC child, was replaced by a stretch written from its published description. moq-congestion's Cubic came from quinn and stays with the quinn child. -The 2026-11-12 audit found moq-webrtc's vendored str0m, dimpl, `is`, and -sctp-proto (vendored 2026-11-07, after that scan) with no child, so they got +The 2026-11-12 audit found moq-webrtc's vendored str0m, dimpl, and `is` +(vendored 2026-11-07, after that scan) with no child, so they got [one](/quest/m3/vendor-sync/webrtc-stack.md) starting from the revisions `rs/moq-webrtc/src/vendor/mod.rs` records. diff --git a/quest/m3/vendor-sync/webrtc-stack.md b/quest/m3/vendor-sync/webrtc-stack.md index c46497e08b9..2776f12aa7b 100644 --- a/quest/m3/vendor-sync/webrtc-stack.md +++ b/quest/m3/vendor-sync/webrtc-stack.md @@ -2,11 +2,9 @@ ## Goal -moq-webrtc's vendored str0m, `str0m_proto`, `is`, dimpl, and sctp-proto -carry every fix their upstreams -([algesten/str0m](https://github.com/algesten/str0m), -[algesten/dimpl](https://github.com/algesten/dimpl), and -[algesten/sctp-proto](https://github.com/algesten/sctp-proto)) have landed +moq-webrtc's vendored str0m, `str0m_proto`, `is`, and dimpl carry every fix +their upstreams ([algesten/str0m](https://github.com/algesten/str0m) and +[algesten/dimpl](https://github.com/algesten/dimpl)) have landed since the last check, each ported with its test or recorded as not applying, and the `Upstream` section of `rs/moq-webrtc/src/vendor/mod.rs` names the newest upstream commit checked for each. @@ -22,17 +20,17 @@ vendored on 2026-11-07 in Start from the revisions the module doc records: str0m `main` at [`dc317173`](https://github.com/algesten/str0m/commit/dc317173b16fc6ed86633e6b08b229c9195deb87) (2026-10-26; `str0m_proto`, `is`, and the test-only `netem` come from the same -repository), dimpl 0.9.0 at -[`c17b3b8`](https://github.com/algesten/dimpl/commit/c17b3b8b971b6eb2ecf7284f5dc0ecb86680ac4d), -and sctp-proto 0.10.7 as published on crates.io. Check each repository's -security advisories too: the stack parses untrusted SRTP, RTCP, DTLS, STUN, -and SCTP input from browsers, and cargo-deny cannot see an advisory against +repository), and dimpl 0.9.0 at +[`c17b3b8`](https://github.com/algesten/dimpl/commit/c17b3b8b971b6eb2ecf7284f5dc0ecb86680ac4d). +Check each repository's security advisories too: the stack parses untrusted +SRTP, RTCP, DTLS, and STUN input from browsers, and cargo-deny cannot see an advisory against vendored code. The vendored code was trimmed to what MoQ uses (the [WebRTC epic](/quest/m3/webrtc/README.md)'s "What goes" list: GCC bandwidth estimation, the leaky pacer, H.266, RED, DTMF, G.7xx and comfort noise, VLA -and simulcast layers, RTCP app feedback, stats, and DTLS 1.3), so a fix +and simulcast layers, RTCP app feedback, stats, DTLS 1.3, and str0m's data +channels), so a fix confined to removed code does not apply. Deleting an API with no consumer beats porting a fix to it. diff --git a/quest/m3/webrtc/README.md b/quest/m3/webrtc/README.md index 1f047235dd9..e9d7228e0bb 100644 --- a/quest/m3/webrtc/README.md +++ b/quest/m3/webrtc/README.md @@ -2,19 +2,19 @@ ## Goal -All of MoQ's WebRTC lives in one published crate, `moq-webrtc`, holding the WHIP/WHEP gateway, the ICE driver, the native data-channel transport (`p2p`), and vendored copies of str0m, dimpl, `is`, and sctp-proto. Fixes to the stack land in normal MoQ PRs instead of waiting on upstream, and code MoQ doesn't use is gone. +All of MoQ's WebRTC lives in one published crate, `moq-webrtc`, holding the WHIP/WHEP gateway, the ICE driver, and vendored copies of str0m, dimpl, and `is`. Fixes to the stack land in normal MoQ PRs instead of waiting on upstream, and code MoQ doesn't use is gone. -Non-goals: TURN; DTLS 1.3; replacing a vendored layer before there's a reason to. +Non-goals: TURN; DTLS 1.3; data channels; replacing a vendored layer before there's a reason to. ## Plan Decided 2026-10-30 with the maintainer (planning interview), after the str0m workarounds piled up: one `b=` line per SDP media section ([moq-dev/moq#7373](https://github.com/moq-dev/moq/pull/7373)), DTLS retransmits running out before ICE connects ([moq-dev/moq#7379](https://github.com/moq-dev/moq/pull/7379)), no hook to charge or serve NACK resends ([rtc-pacing](/quest/m3/rtc-pacing.md)), and `std::time::Instant` in a `kio::clock` workspace. No upstream reports were approved; vendoring replaces them. -- **Vendor, then replace.** Copy the upstream crates in, trim them, and fix them in-tree. Replacing a layer with our own (SDP, RTP/RTCP, SRTP, SCTP) is a later child once a concrete need appears; none is planned yet. -- **One crate.** The ICE driver (once `moq-ice`) and moq-tokio's former `webrtc` data-channel transport live in `moq-webrtc`, which depends on moq-tokio rather than the reverse, so moq-tokio needs no ICE or SCTP. The vendored crates become private modules, not separate published crates, keeping their MIT/Apache-2.0 notices (str0m's `packet/` carries webrtc-rs's Apache notice). +- **Vendor, then replace.** Copy the upstream crates in, trim them, and fix them in-tree. Replacing a layer with our own (SDP, RTP/RTCP, SRTP) is a later child once a concrete need appears; none is planned yet. +- **One crate.** The ICE driver (once `moq-ice`) lives in `moq-webrtc`, which depends on moq-tokio rather than the reverse, so moq-tokio needs no ICE. The vendored crates become private modules, not separate published crates, keeping their MIT/Apache-2.0 notices (str0m's `packet/` carries webrtc-rs's Apache notice). - **What goes** (from the 2026-10-30 inventory: we use frame mode, full ICE, and DTLS 1.2, and never enable str0m's BWE, pacer, or stats): GCC bandwidth estimation (8k lines; GCC is ported into `moq-congestion` as `moq_congestion::gcc`), the leaky pacer (replaced by moq-congestion's pacer, made public by [rtc-pacing](/quest/m3/rtc-pacing.md)), H.266, RED, DTMF, G.7xx and comfort noise, VLA and simulcast layers, RTCP app feedback, stats, internal test exports, and dimpl's DTLS 1.3 and version auto-selection. RTCP XR stays: its RRTR/DLRR blocks are the receive side's only RTT measurement, which sets NACK retries and the video recovery deadline. Roughly 17k of str0m's 72k lines and 11k of dimpl's 33k. - **DTLS 1.2 only.** Every browser negotiates 1.2 today, and the vendored rind crypto provider offers 1.2 only to match. -- **SCTP stays**, for browser data channels in [P2P](/quest/m4/p2p/README.md), but compiles only with the data-channel feature, so WHIP/WHEP builds carry none of it. Vendored, it can later be simplified or put on moq-congestion. +- **No SCTP.** Decided 2026-11-14 (maintainer): peer-to-peer routing, the only data-channel consumer, left the repository, so sctp-proto and str0m's data channels are cut and an offered `m=application` line is answered rejected. - **Upstream fixes:** after vendoring, nobody merges upstream automatically. The vendored upstream commits are recorded in `rs/moq-webrtc/src/vendor/mod.rs`'s `Upstream` section; the [vendor sync](/quest/m3/vendor-sync/webrtc-stack.md) checks the upstream changes once per release cycle for security fixes (malformed SRTP/RTCP input, for example) and ports them. - Docs a change makes stale (crate names, `doc/lib/rs`, `doc/setup/upgrade.md`, other quests naming a crate or module) change in the PR that makes them stale. diff --git a/quest/m3/webrtc/dtls-timeout.md b/quest/m3/webrtc/dtls-timeout.md index ede0320b1f7..563ffe21ebd 100644 --- a/quest/m3/webrtc/dtls-timeout.md +++ b/quest/m3/webrtc/dtls-timeout.md @@ -19,8 +19,7 @@ where upstream flattened it into `CryptoError::Other(String)`. - Classify it once at the str0m boundary in moq-webrtc's ICE module, the only place that sees str0m's error, by matching that variant; add no text match. - Add the variant to moq-webrtc's `ice::Error` and `moq_webrtc::Error`, named by role (for - example `DtlsTimeout`), and map it in `moq-webrtc`'s session loop and its - `p2p` transport, which also matches moq-webrtc's `ice::Error`. + example `DtlsTimeout`), and map it in `moq-webrtc`'s session loop. - Decide in the PR whether the variant stays distinct from `IceTimeout` or folds into one establishment-timeout variant, and record why. Distinct is recommended: an ICE timeout means no path, a DTLS timeout means a path that diff --git a/quest/m3/webrtc/socket-error.md b/quest/m3/webrtc/socket-error.md index e8b9b96d82d..0295a3cf6c3 100644 --- a/quest/m3/webrtc/socket-error.md +++ b/quest/m3/webrtc/socket-error.md @@ -1,14 +1,11 @@ -# [M] A failed client socket ends a WebRTC session with an error +# [S] A failed client socket ends a WebRTC session with an error ## Goal When the UDP socket under a moq-webrtc client session fails to receive, `Client::publish` and `Client::subscribe` end with `Error::Io` carrying the -socket's `io::Error`, instead of `Ok` as if the peer had disconnected. A -`p2p` connection that fails this way hands its opener `p2p::Error::Io` before -its channel opens, including an opener that asks after the failure, and fails -the MoQ session over an opened channel with `qmux::Error::Io`, instead of -`Closed`. A peer disconnect still ends `Ok`. The first cause wins: a peer +socket's `io::Error`, instead of `Ok` as if the peer had disconnected. A peer +disconnect still ends `Ok`. The first cause wins: a peer close that lands before the socket fails stays a close. ## Plan @@ -21,12 +18,12 @@ Where it goes wrong today: 1. `ice::reader` (`rs/moq-webrtc/src/ice/wire.rs`) logs a `recv_from` error and breaks, dropping its queue's sender. Client sessions (`session::bind_udp`) - and the `p2p` transport (`p2p::bind`) use it. + use it. 2. `Agent::next` (`rs/moq-webrtc/src/ice/agent.rs`) sees the queue end and fails with `ice::Error::Closed`, the same variant as an ICE disconnect or a dead `Rtc`. 3. `Session::run_loop` (`rs/moq-webrtc/src/session.rs`) maps `Closed` to - `Ok(())`. `p2p`'s `Error::ice` maps it to its own `Closed`. + `Ok(())`. The cause no caller can see is step 1: the reader drops the error. Fix it there. The reader hands its `io::Error` to the agent, for example as the queue's last @@ -34,21 +31,10 @@ item, and the agent fails with a new `ice::Error` variant named by role (such as `Socket`). `Agent::next` returns a clone of the stored failure on every later call, so `ice::Error` stays `Clone` and the variant holds an `Arc`. The session maps it to the existing `moq_webrtc::Error::Io`, which is already -documented as covering a receive error on the media socket. `p2p`'s -`Error::ice` maps it to `p2p::Error::Io`, whose doc widens from bind and STUN -failures to cover it. Rebuild an owned error from the `Arc` that keeps what -callers read: `io::Error::from_raw_os_error` when it has an OS code, so -`raw_os_error()` still answers, else `io::Error::new(err.kind(), err)`. - -Every handle on a `p2p` connection reads its end as `Closed` today, whatever the -cause: an opener that asks after the driver exited (the dropped command channel), -and an opened channel's `Reader` (the dropped `Inbox`) and `Writer` (the closed -outbox). Pushing the error into the `Inbox` alone would race: qmux's driver can -find the outbox closed before it reads the `Inbox`. Instead the driver records -its terminal error in one slot the handles share before it drops anything, and -each handle that finds its channel gone reports that error, as `p2p::Error` or -`qmux::Error::Io`, instead of `Closed`. That fixes every cause, not only the -socket. +documented as covering a receive error on the media socket. Rebuild an owned +error from the `Arc` that keeps what callers read: `io::Error::from_raw_os_error` +when it has an OS code, so `raw_os_error()` still answers, else +`io::Error::new(err.kind(), err)`. `Agent::next` judges the establishment deadline before it reads the inbound queue, so a socket error queued just before that deadline would surface as @@ -72,18 +58,13 @@ reports a loopback ICMP port unreachable as `ECONNREFUSED` on its next receive, with no rate limit on loopback. Connect a socket to a closed loopback port, send once, and feed the socket to `ice::reader` and an agent, as `agent.rs`'s `unpolled` fixture does. Then assert that the agent and the -session end with the socket error, not `Closed` or `Ok`. Also assert that a -`p2p` opener gets `p2p::Error::Io` with the underlying error whether it asked -before or after the failure. With a channel opened between two peers and a -write pending, and the outbox's closure reaching qmux before the `Inbox`'s, -failing one side's socket ends its MoQ session with -`qmux::Error::Io` and the OS code. A socket error queued behind a datagram, -read after the establishment deadline, still wins over `Timeout`. Keep the -existing peer-disconnect path asserting `Ok`. +session end with the socket error, not `Closed` or `Ok`. A socket error queued +behind a datagram, read after the establishment deadline, still wins over +`Timeout`. Keep the existing peer-disconnect path asserting `Ok`. Public API: none. The errors map to existing `Io` variants, and the new `ice::Error` variant is crate-private. Wire: none. ## Related -- [A typed DTLS handshake timeout error](/quest/m3/webrtc/dtls-timeout.md) - also adds an `ice::Error` variant mapped through the session loop and `p2p` +- [A typed DTLS handshake timeout error](/quest/m3/webrtc/dtls-timeout.md) - also adds an `ice::Error` variant mapped through the session loop diff --git a/quest/m4/bun-check.md b/quest/m4/bun-check.md index 9bfee5e9b13..62b0a1c7f95 100644 --- a/quest/m4/bun-check.md +++ b/quest/m4/bun-check.md @@ -10,7 +10,7 @@ Every package with a `bench/` typechecks it in its `check` script, so a removed export breaks the build, not Nightly. On `main` at c681b7a09, `clock`, `qmux`, `signals`, and `watch` have bench sources and no `bench/tsconfig.json`, and `json` and `publish` typecheck theirs only in the nightly bench recipes -(`js/justfile`), while `net`, `crypto`, `hang`, `p2p`, and `pattern` already +(`js/justfile`), while `net`, `crypto`, `hang`, and `pattern` already check theirs (added 2026-11-12 by /quest-plan, from moq's trimmed Pullfrog learnings). diff --git a/quest/m4/p2p/README.md b/quest/m4/p2p/README.md deleted file mode 100644 index 4d4b22d9539..00000000000 --- a/quest/m4/p2p/README.md +++ /dev/null @@ -1,174 +0,0 @@ -# P2P - -## Goal - -Opted-in moq-lite clients serve each other directly, over WebRTC data channels -when a browser is involved and over QUIC on an ICE path between native ones, -while the relay stays -the rendezvous and an available fallback route. A client subscribes through the -relay at once, negotiates peers in the background, and a subscription -migrates when an application-selected direct connection wins the shared -priority/cost ordering, and returns to the best eligible route when it goes -away. A peer serves its own publications or is an authorized native routing -node such as `moq-cli --p2p`. A browser never carries another peer's traffic. Nothing waits on ICE and nothing breaks when it -fails: a symmetric NAT, a denied local-network prompt, or a filtered multicast -segment leaves the client exactly where it started. - -The application is in charge of policy. It supplies the ICE servers (an empty -list disables ICE servers: only host and mDNS candidates, which pair on a -LAN when the network allows it, and can still pair across the Internet -when a host address, often IPv6, is publicly reachable), publishes opaque hints -about itself, decides which roster peers to dial, and may pass a peer an empty -`iceServers` list, for example past a roster size it picks. P2P is off unless the -application turns it on. - -Three endpoint pairs work: browser to browser and browser to native over a -data channel, and native to native over QUIC on the ICE-nominated path. -Decided 2026-10-13: no iroh. It brings discovery and relaying of its own -beside the relay; every pair uses the same STUN and ICE, with the relay as -rendezvous and fallback. - -Non-goals: TURN, since the relay already carries the media as a MoQ route and -relaying ICE traffic would cost the same egress with worse framing; operating -without a relay; RTP media; a channel-per-stream mapping, for the reasons -under "One channel, qmux, ordered". - -## Plan - -Deferred to m2 by the maintainer on 2026-10-15, with signaling, transports, -policy, and validation together. CDN-connected clients using selected peer -paths remain the consumer. Reuse the shared routing contracts; no second -routing implementation. Any incompatible wire additions after lite-07 -finalizes use a later wip/version. - -This epic owns practical P2P setup guidance extending the routing concept: -keep the CDN session while selecting peers, explain no browser transit, and -show application-selected ICE servers including an opt-in relay STUN endpoint -(`stun:relay.example.com:3478`). Link `/bin/relay/config#stun` and the -JS/native P2P reference. Do not imply that direct always beats CDN. - -### The relay is the rendezvous and the fallback - -Every opted-in peer already holds a session to the same relay, so discovery -and signaling ride that session as ordinary moq broadcasts under a reserved -prefix (`.p2p/` by default, configurable). The relay learns nothing new; -trust is its token scope. A peer that may publish -under the prefix is as trusted as any publisher the token admits, so this -line needs no E2EE. - -The CDN session and discovery remain connected. Release unused CDN media -demand after a same-epoch handoff, except bounded overlap while validating a -replacement. If a peer dies, drains, or was never reachable, the shared -origin selects the best remaining eligible route. This is ordinary transport -fallback; nothing TURN-shaped is built. Detecting a delivery stall on a -still-open route is out of scope. Epochless source changes restart instead of resume. - -The relay is the nearest STUN server a client can name, but this line takes -ICE servers from the application and works with any. Decided 2026-10-08: the -public STUN responder moved out of the [one-port](/quest/m3/one-port/README.md) -UDP demux into this line, since P2P is its only consumer. Decided 2026-10-13: -[Relay STUN](/doc/bin/relay/config.md#stun) runs on its own configured port, -off by default, and used only when the application lists it. - -### Policy is the application's - -`Peers` takes the shared origin, plus the knobs below (decided 2026-11-07, -maintainer, /quest-plan from the API sweep of open PRs and remaining quests: -no `max` roster gate, and the on/off `enabled` is the element's attribute, -not a `Peers` knob): - -- `prefix`: the reserved prefix, `.p2p/` under the session root by default; -- `iceServers`: the default RTCPeerConnection server list, which each - selected or admitted peer may override with its own; empty disables ICE - servers (no STUN or TURN), which is not a LAN-only guarantee. - Host and mDNS candidates are gathered where the browser's privacy policy - allows, so LAN pairing stays possible where local-network access and mDNS - work, with the relay as fallback otherwise, - and changing a peer's list never closes an established pair; -- `meta`: an opaque JSON value published in this peer's roster entry; -- application-owned peer selection: discovery exposes candidates and only - explicitly selected peers are dialed; incoming connections need application - admission too. No default dial-all or automatic - demand-selected dialing. Prefer an explicit set/handle over a policy callback; - settle the concrete public shape with its consumer before implementation. -- application-owned per-connection priority, whether CDN or P2P, followed by - configured additive cost. Discovery and transport do not decide route rank. - -Geo and AS hints are the application's to source (a peer does not know its -own AS); downstream exposes a whoami endpoint for exactly this. - -### One channel, qmux, ordered - -The transport is qmux over one reliable, ordered data channel, one qmux -record per SCTP message, as the WebSocket binding does. SCTP flow control is -message-based, so `max_record_size` defaults to 16 KiB and never exceeds the -negotiated `maxMessageSize` (256 KiB in Chrome). - -The cost is head-of-line blocking: one lost chunk stalls every stream until -SCTP retransmits it. Decided 2026-10-08: the channel is always ordered, and -unordered qmux was dropped. Receiver reassembly would exist only in the Rust -qmux, so it could cover native pairs alone, and a native pair runs QUIC, -whose streams are independent. The -[harness](/quest/m4/p2p/harness.md) reports the stall so the cost stays -visible. - -Channel-per-stream is not planned. moq opens a stream per group, so it churns -against Chrome's 1024-id cap and its close-event id reclaim, needs DCEP per -channel, and has no reset code without a side channel. - -### Routes and migration - -Routing is the [cluster routing line](/quest/m3/cluster-routing/README.md)'s: -every session speaks per-node ROUTEs and path-less ANNOUNCEs, and the -application priority followed by total cost picks the direct link or relay. - -A routing node id is declared by its origin and unverified (decided -2026-10-26, maintainer, dropping receiver-stamped per-session identities). -Switching between a CDN and a direct path resumes only across a matching -explicit epoch. - -Decided 2026-11-02 (maintainer, /quest-unblock): P2P trusts its peers. Joining the prefix takes the -relay's token, so a peer is as trusted as any publisher that token admits, -and a direct session serves without a peer grant or key proof. Peer grants and -P2P identity planning are dropped until a real use case asks for proof. Each -peer's roster `` is its public key, like an iroh endpoint id; nothing proves -it yet. Which roster peer serves an announce stays the application's explicit -selection. If identity or signing is wanted later, moq-lite-07's route -identity becomes a public key, independent of P2P. - -Decided 2026-11-10 (maintainer, /quest-plan on lite-07 routing): a browser -that forwards for its peers on a local network is planned separately, in m5 -behind the Rust-to-TypeScript port -([browser mesh](/quest/m5/browser-mesh.md)). Browsers in this epic stay -non-transit until it lands. - -Decided 2026-10-13: priority then total cost selects among authorized routes; -a direct connection does not always win. A watching tab never re-serves what -it receives. Offloading a room of watchers is a local relay's job -(`moq-cli --p2p` is the small one); warm routes pass only between relays -([cache-aware routing](/quest/m3/cache-routing/README.md)). [Peer route policy](/quest/m4/p2p/cost-scopes.md) sets the cost -knobs and defaults. - -Target the public `@moq/net` interface regardless of whether its -[backend](/quest/m5/rs2ts-js.md) is handwritten or built from Rust. -Backend choice does not change the policy that watching tabs never re-serve. - -### Risks - -- Chrome 147 prompts for local network access on a dial to a private address - from a public origin, and the same gate is proposed for WebRTC. A denial - costs join time, not correctness. -- Firefox bug 1698141: Firefox-initiated LAN P2P to Chrome can fail on mDNS - candidate parsing. -- Multicast-filtered networks break `.local` resolution; those peers pair - over server-reflexive candidates or not at all. -- Symmetric NATs on both ends fail ICE without TURN. By design the relay - keeps serving. - -Before `@moq/p2p` is first published, add its entrypoints to the API -Extractor declaration checks, which analyze only published packages since -[moq-dev/moq#6794](https://github.com/moq-dev/moq/pull/6794). - -## Related - -- [E2EE](/quest/m5/e2ee/README.md) - what a peer would need if the token scope stopped being the trust boundary diff --git a/quest/m4/p2p/cli.md b/quest/m4/p2p/cli.md deleted file mode 100644 index 0ce127f00ec..00000000000 --- a/quest/m4/p2p/cli.md +++ /dev/null @@ -1,47 +0,0 @@ -# [M] moq-cli joins - -## Goal - -`moq-cli --p2p` publishes a roster entry on its relay session, advertises how -it can be reached, dials other native peers over -[ICE and QUIC](/quest/m4/p2p/native-quic.md), and accepts browsers over data channels as a transit hop between -them and the relay. Its policy knobs mirror `@moq/p2p`. - -## Plan - -`--p2p` (`MOQ_P2P`) needs a relay session (`--connect`) and a listener -(`--listen`); shape the flag so the value carries those prerequisites rather -than adding startup checks. `--p2p-ice-server`, -`--p2p-prefix`, and `--p2p-meta` carry the same knobs the JS -`Peers` takes; there is no `--p2p-max` (decided 2026-11-07, maintainer, -/quest-plan from the API sweep of open PRs and remaining quests: no `max` -roster gate, see [signal](/quest/m4/p2p/signal.md)). Decided 2026-10-13: the operator explicitly selects peers; -there is no built-in dial-all default. Provide an explicit selection/configuration -surface and per-connection priority/cost mirroring the application API; settle -its concrete CLI shape before coding and update all invocations against --help. - -The roster entry mirrors the `info.json` schema from -[signaling](/quest/m4/p2p/signal.md): the listener's LAN addresses as -WebTransport URLs, ordered the way `mdns::Peer::urls` orders them, with the -listener's certificate fingerprint. Use signaling's ordered-list shape and -dialing order, confirmed in the quest audit, so multi-interface listeners -advertise one shared schema. Include `webrtc: true`, the native ICE+QUIC -field, and `meta`. No iroh endpoint id (decided 2026-10-13: P2P does not use -iroh). The generated certificate must satisfy the browser's -`serverCertificateHashes` rules (ECDSA P-256, under fourteen days); verify the -generator does. Offers and answers go through the same per-pair broadcasts, -mirrored in Rust. - -Every accepted session attaches to the shared origin with `with_publisher` -and `with_subscriber`, as the LAN mesh does, so the node is a hop: it -subscribes upstream once and serves each peer from the same origin. Native -pairs selected by the operator connect over ICE and QUIC, with -deterministic simultaneous-dial resolution. -Discovery alone does not initiate a connection. - -Docs: a "P2P" section in `doc/bin/cli.md` beside the LAN cluster one. - -## Required - -- [Native pairs over ICE and QUIC](/quest/m4/p2p/native-quic.md) - the native-to-native path -- [Signaling and policy](/quest/m4/p2p/signal.md) - the roster and offer schema this mirrors diff --git a/quest/m4/p2p/cost-scopes.md b/quest/m4/p2p/cost-scopes.md deleted file mode 100644 index c63503834c3..00000000000 --- a/quest/m4/p2p/cost-scopes.md +++ /dev/null @@ -1,53 +0,0 @@ -# [S] Peer route policy - -## Goal - -Application-selected CDN and direct connections feed one shared origin. Its -ordinary priority/cost rules choose the best eligible route, preserving the -CDN session and discovery while avoiding unused duplicate payload pulls. - -## Plan - -Decided 2026-10-13, replacing the unconditional direct-first policy: - -- Applications explicitly choose which discovered peers to connect to and - assign per-connection priority. Priority wins before configured additive - cost; links cost one by default and zero is refused (decided 2026-10-13). No automatic dial-all or - RTT-based repricing by default. A browser sends no warm routes; those pass - only between relays ([cache-aware routing](/quest/m3/cache-routing/README.md)). -- Within a priority, compare complete route cost including the origin's - prefix seed. A direct routing node loses when its total route is more - expensive. Equal distinct routes retain deterministic path hashing; newest - wins only for otherwise identical routes, not every new peer connection. -- A browser serves only what it publishes. Native routing nodes may transit - authorized content when the application turns on the connection's local - `proxy` preference (decided 2026-10-14): on for redundancy, such as reaching - the CDN through a peer whose uplink died, off for conference offload. - Browser tabs never relay, whatever the backend (decided 2026-10-22, - maintainer). A neighboring watcher is not a source of its received - media. A publisher's routing identity is declared and unverified (peers are - trusted, decided 2026-11-02 (maintainer, /quest-unblock)); switching between - its CDN and direct copies resumes only across a matching explicit epoch. - Which roster peer serves an announcement is the application's selection in - [Signaling and policy](/quest/m4/p2p/signal.md). -- Matching explicit epochs permit shared logical-track resume. Different or - missing epochs require Restart and fresh resolution. Keep CDN control and - discovery while releasing its unused media demand after P2P handover. -- Active/passive health may temporarily exclude a stalled route and restore - it after verified recovery, but only for epoch-bound broadcasts. That policy - belongs to Route health, not a P2P-specific resubscribe loop. - -Mirror the application's priority/cost controls in native configuration and -use the shared routing concept terminology. Test a preferred CDN overriding -cheaper P2P, a shorter same-priority peer winning, a longer peer losing, -a neighboring watcher offering nothing it merely receives, reconnect tie -behavior, and fallback retaining the CDN session without duplicate payload. - -Public API: application-owned connection priority/cost and `proxy` controls -in Peers and native configuration. Wire: none beyond shared routing and existing resume. - -## Required - -- [Routes and announces](/quest/m2/cluster-routes/README.md) - route identities and route ordering -- [Signaling and policy](/quest/m4/p2p/signal.md) - explicit application peer selection -- [moq-cli joins](/quest/m4/p2p/cli.md) - matching native controls diff --git a/quest/m4/p2p/harness.md b/quest/m4/p2p/harness.md deleted file mode 100644 index 008d8d6e661..00000000000 --- a/quest/m4/p2p/harness.md +++ /dev/null @@ -1,52 +0,0 @@ -# [M] Harness - -## Goal - -A Playwright harness under `test/p2p` that measures moq-lite over the data -channel against WebTransport through the relay on the same LAN and across a -NAT, browser to browser, browser to native, and native to native over ICE -and QUIC, in Chrome and Firefox with -Safari best effort, and writes a JSON report each mapping or cost decision -quotes. - -## Plan - -A Playwright driver with a local relay, `moq-bench` publishing synthetic -frames of known size and rate through it, and `moq-cli --p2p` as the native -hop. The NAT rows run the peers behind a network-namespace NAT with a -local STUN server, so a reflexive pair is exercised without leaving the host. - -Matrix: - -- browser to native: the same `moq-cli` hop over WebTransport and over the - qmux channel; -- browser to browser: a publishing tab to a watcher tab directly, and the - same publisher to two watcher tabs directly, against the same pairs through - the relay. A watcher tab never re-serves (decided 2026-10-01), so there is - no tab-transit row; -- native to native: two `moq-cli --p2p` nodes over ICE and QUIC, on the LAN - and across the NAT, against the same pair through the relay. There is no - native data channel row. - -Add publisher/consumer and roster/selected-pair sweeps, including explicit -full-mesh selection, roster churn, pending negotiations and cancellation. -Report connection counts, signaling bytes, wakes, CPU and retained state; -per-peer `iceServers` alone do not bound pairing. Verify the CDN control -session survives peer handover while unused CDN payload demand stops. -Route-health cases are out of scope. - -Metrics: sustained throughput ceiling, per-frame latency p50 and p99 from the -timestamp `moq-bench` stamps into each keyframe (same host, so one clock), -stall duration after an induced loss on the ordered channel, join time -including the WebTransport-first fallback and the relay-first subscription -that P2P then migrates, and migration gap at the switch. Record the browser -versions and the Firefox mDNS caveat beside each row. - -State the boundary beside the result: loopback and one wifi segment say -nothing about multicast-filtered venues or many-tab fan-out on real access -points. - -## Required - -- [moq-cli joins](/quest/m4/p2p/cli.md) -- [Signaling and policy](/quest/m4/p2p/signal.md) diff --git a/quest/m4/p2p/native-quic.md b/quest/m4/p2p/native-quic.md deleted file mode 100644 index 518c869832d..00000000000 --- a/quest/m4/p2p/native-quic.md +++ /dev/null @@ -1,68 +0,0 @@ -# [L] Native pairs over ICE and QUIC - -## Goal - -Two native peers (`moq-cli --p2p`, or any `moq-tokio` client that opts in) -selected by their applications connect directly across a NAT: ICE finds a -path through host and server-reflexive candidates, then a `moq-quic` -connection runs over the nominated pair, with each side's certificate pinned -by the fingerprint the other sent in its offer or answer. A pair with a -browser still uses a data channel (`moq_webrtc::p2p`). - -## Plan - -Decided with the maintainer on 2026-10-13: - -- No iroh. It brings its own discovery and relaying beside the relay, which - this line rejects; native pairs use the same STUN and ICE as browsers, with - the relay as rendezvous and fallback. -- ICE is str0m's standalone sans-IO agent, the `is` crate, vendored in - moq-webrtc beside str0m (`rs/moq-webrtc/src/vendor/is`). Gather - candidates with `moq_webrtc::p2p`'s host gathering, `.local` resolution, - and the STUN Binding client in moq-webrtc's ICE module; don't copy them. The first two - are private to the data channel transport today, so move them into the - ICE module. Decided 2026-10-30 (maintainer): the ICE driver, the - data-channel transport, and a vendored `is` all live in `moq-webrtc`; - take them from there. -- QUIC is `moq-quic`, fed datagrams from the nominated pair. -- Authentication: each side generates a self-signed certificate and sends - its SHA-256 fingerprint in its offer or answer, as DTLS fingerprints ride - in SDP. Both sides pin it with the existing `tls.fingerprint` check. Peers - are trusted (decided 2026-11-02 (maintainer, /quest-unblock)), so no peer grant runs on top. -- After nomination the session's socket carries ICE consent checks and - QUIC, split by `moq_sock::demux::classify`: `Ice` and `Stun` go to the - ICE agent and `Quic` to the endpoint. The tokio listener's `quic::demux` - routes for a relay (STUN queries dropped, no ICE agent), so the session - socket needs its own small policy over the same classifier. - -Roles are deterministic: the ICE controlling side is the QUIC client, so a -simultaneous dial resolves the same way [signaling](/quest/m4/p2p/signal.md) -resolves offers (the lower id wins). The offer and answer carry ICE -credentials, the fingerprint, and candidates on the pair's `signal` track; -settle the field names with signaling's schema, and add a roster field -saying a native peer accepts ICE+QUIC so a native dialer picks this over a -data channel. A failed ICE check is terminal for the pair, like signaling's -rule; no retry loop. The QUIC connection's path never migrates; ICE -restarts are out of scope. - -Open question for the implementer: `is` may re-nominate a different pair -without an ICE restart (a late trickled candidate, a network change), while -QUIC stays on the old tuple. Either freeze nomination once the QUIC -handshake starts, keeping consent checks on that pair, or follow the new -pair by migrating or recreating the QUIC path. Recommendation: freeze, and -if `is` cannot hold a pair, close the session on a nomination change rather -than migrate; it matches the no-retry rule and keeps QUIC on one path. -Either way, a test trickles a better candidate after QUIC starts and shows -the session never stalls on a stale tuple. - -Ordered qmux stays the only data channel mode: native pairs have -independent QUIC streams here, so unordered reassembly would serve nobody. - -Tests: unit tests drive two agents and two `moq-quic` endpoints in memory -with mocked time, covering nomination, a wrong fingerprint refused, and a -consent-check failure closing the session. The [harness](/quest/m4/p2p/harness.md) -covers LAN and NAT pairs between two `moq-cli --p2p` nodes. - -## Required - -- [Signaling and policy](/quest/m4/p2p/signal.md) - the offer schema and roster this extends diff --git a/quest/m4/p2p/signal.md b/quest/m4/p2p/signal.md deleted file mode 100644 index 52c020eba06..00000000000 --- a/quest/m4/p2p/signal.md +++ /dev/null @@ -1,97 +0,0 @@ -# [M] Signaling and policy - -## Goal - -An opted-in browser discovers the other opted-in peers on its relay session, -exposes candidates for the application to select, and ends up holding an established -`@moq/net` connection to each selected peer ICE can reach, wired into the shared origin -in both directions. The application supplies the ICE servers, per peer when -it wants. No new relay behavior. - -## Plan - -`Peers` in `@moq/p2p` takes the shared origin, a reconnect-safe handle to the -relay connection's auth, and the policy knobs from the -[questline README](/quest/m4/p2p/README.md): `prefix`, `iceServers`, -`meta`, plus application-owned selection and per-connection -priority/cost. `Peers` exists only while P2P is on; the on/off `enabled` -lives on the element as an attribute. Decided 2026-10-13: only explicitly selected peers are dialed; -there is no default dial-all. Prefer a selected set/handle to a callback, -settling the public shape with its consumer. Publishing into the origin reaches -the relay and its announce stream is the roster. Tests inject transport -factories and cover pairing, application selection, and per-peer ICE servers. - -Identity, decided 2026-11-02 (maintainer, /quest-unblock): each peer generates a keypair, and its -roster `` (also the perfect-negotiation tiebreak) is its public key, like an -iroh endpoint id. Nothing proves the key yet: peers are trusted (see Trust). -Which roster peer serves an announce is the application's explicit selection; -moq maps nothing automatically. The route-layer node id stays declared and -unverified ([routes](/quest/m2/cluster-routes/README.md)); if a use case -needs provable identity or signing, moq-lite-07's route identity becomes a -public key, independent of P2P. P2P identity planning and peer grants were -dropped until a real use case asks for them. Switching between a CDN and a -direct path resumes only across a matching explicit epoch. - -Roster: each peer publishes `` with an `info.json` snapshot track: -the moq ALPNs it accepts, `webrtc: true`, the application's `meta`, -and for native peers an optional WebTransport entry with an ordered list of -URLs and the listener's certificate fingerprint, plus the field -[native pairs](/quest/m4/p2p/native-quic.md) add for ICE+QUIC. -Decided in the quest audit: use a list so a native peer can advertise its -reachable interfaces without choosing one for every browser. This quest -owns the schema shared with [moq-cli](/quest/m4/p2p/cli.md). - -Pairing follows explicit selection: pair broadcasts exist only for selected -pairs. The application may still choose a full mesh, so measure that cost -rather than claiming sparsity from the API alone. Incoming offers also require -application admission before a connection is attached to the shared origin; -roster membership and token scope authorize access but do not select peers -on the application's behalf. An application may explicitly accept an offer -without having initiated a dial. When both sides select the same pair and dial at once, the -higher id abandons its own offer on seeing the lower id's, perfect -negotiation with the higher id polite. The dialer publishes -`/` with a `signal` stream track carrying the offer and -then each ICE candidate as it arrives; the target answers on -`/`. Every peer subscribes to its own `/` -prefix. - -ICE servers, decided 2026-11-07 (maintainer, /quest-plan from the API sweep -of open PRs and remaining quests): each selected or admitted peer takes its -own `iceServers`, defaulting to `Peers`' list, which replaces the earlier -roster-size gate and its `max` knob. An application that wants to stop using -STUN past some roster size passes an empty list for the peers it selects or -admits then. Host and mDNS candidates are gathered where the browser's privacy -policy allows, so an empty list can still pair on a LAN when local-network -access and mDNS resolution work, or across the Internet through a publicly -reachable host candidate, and a selected native peer may still connect over -its advertised WebTransport URL; otherwise the peers stay on the relay. -Changing a peer's list never closes an established pair; it applies to the -peer's next negotiation (a failed pair stays failed until a re-announce, as -Lifecycle says). Test roster churn and pending -negotiations separately. - -Native entries: when `info.webtransport` is present the dialer tries its -URLs in advertised order, using `connect` with the listener's fingerprint -pinned and the bounded attempt policy, then falls through to WebRTC if none -connects. Mirror this order in the CLI and test that a later address is tried -after an earlier one fails. Chrome 147 may prompt for local network access on that -dial; a denial falls through the same way. - -Lifecycle: application deselection or a retracted roster entry closes that -peer's session and releases its routing and signaling demand. Test an -unsolicited offer with no selected/admitted peers, explicit incoming admission, -and deselection during negotiation and while serving. An ICE -failure is terminal for the pair until either side re-announces; no retry -loop. Each established connection goes through `connect` with the supplied -transport on the dialing side and `accept` on the answering side, both with -`publish: origin.consume()` and `consume: origin`, so the tab serves what it -publishes, never what it receives (a tab is not transit). - -Trust, decided 2026-11-02 (maintainer, /quest-unblock): P2P trusts its peers. Joining the prefix -takes the relay's token, so a peer admitted to the prefix is as trusted as any -publisher that token admits, and a direct session serves what this tab -publishes without a peer grant or key proof. The relay token itself still -never crosses a peer session: a `moq_auth` JWT is a bearer credential, so a -peer that received one could replay it against the relay. Rejected: relay-issued, -key-bound peer grants with a possession proof (the earlier plan), until a use -case needs per-peer scopes. diff --git a/quest/m4/p2p/watch.md b/quest/m4/p2p/watch.md deleted file mode 100644 index dc563b88ad0..00000000000 --- a/quest/m4/p2p/watch.md +++ /dev/null @@ -1,36 +0,0 @@ -# [S] Watch opts in - -## Goal - -One attribute turns P2P on in the demo. A watcher tab keeps subscribing -through the shared origin, its subscriptions migrate to a direct peer that is -the broadcast's origin or a routing node, and they return to the relay when -the peer goes away, with no visible interruption. - -## Plan - -Publish `@moq/p2p` with its first application consumer in this quest. It is -currently private and has no release script; the `test/p2p` harness uses its -workspace source. Before its first workflow publish, a maintainer claims -`@moq/p2p` on npm with a placeholder and attaches the `moq-dev/moq` -trusted publisher, as [Claim new npm names](/quest/m3/release/npm-first-publish.md) -does for the cut's packages. - -`moq-watch` and `moq-publish` gain a `p2p` attribute that constructs -`Peers` on the shared connection's origin and its relay auth handle (see -[Signaling and policy](/quest/m4/p2p/signal.md)), with the demo's ICE servers -(per peer when the page selects them); `demo/web` exposes the toggle and an explicit application -peer-selection policy. Enabling discovery alone must not dial every peer. The route pick is the -origin's, under the rule from [Peer route policy](/quest/m4/p2p/cost-scopes.md): -application priority then total cost selects among eligible connections. -The CDN session remains, but unused CDN payload demand is released. Same-epoch -handover resumes; epochless source changes restart. A direct link need not win. - -Two topologies and the demo shows both: a publishing tab serving watcher tabs -directly, and watcher tabs pulling from a `moq-cli --p2p` hop. - -## Required - -- [Signaling and policy](/quest/m4/p2p/signal.md) -- [moq-cli joins](/quest/m4/p2p/cli.md) - the native hop the second topology shows -- [Peer route policy](/quest/m4/p2p/cost-scopes.md) diff --git a/quest/m4/test-inventory-followups.md b/quest/m4/test-inventory-followups.md index b93e8a67762..98540c9cb71 100644 --- a/quest/m4/test-inventory-followups.md +++ b/quest/m4/test-inventory-followups.md @@ -25,10 +25,9 @@ for the `#[ignore]` check. Left over: - Modules nested in a `#[path]`-loaded file resolve against that file's directory, but the walker places them under `//` unless the file is `mod.rs` (`sh/gh/test-inventory.py:663` and `:694-696`). So the vendored - crates `rs/moq-webrtc/src/vendor/mod.rs:44-57` loads go unseen, with their 3 - `#[ignore]` tests, such as `sctp_proto/queue/queue_test.rs:1207`. Walk a - `#[path]` child as owning its directory, and give the 3 tests callers or - allowlist entries (added 2026-11-12 by /quest-plan, from moq's trimmed + crates `rs/moq-webrtc/src/vendor/mod.rs:43-55` loads go unseen, with their + `#[ignore]` test `str0m/tests/poll-scaling.rs:50`. Walk a `#[path]` child as + owning its directory, and give the test a caller or an allowlist entry (added 2026-11-12 by /quest-plan, from moq's trimmed Pullfrog learnings). - The failure output lists `benchmark_stream_import` twice. Deduplicate orphans by name and location. diff --git a/quest/m4/webrtc-browser-only.md b/quest/m4/webrtc-browser-only.md index 3defcf9687f..2aa6232d7c5 100644 --- a/quest/m4/webrtc-browser-only.md +++ b/quest/m4/webrtc-browser-only.md @@ -2,7 +2,7 @@ ## Goal -The vendored str0m, dimpl, `is`, and sctp-proto drop every feature no +The vendored str0m, dimpl, and `is` drop every feature no browser's WebRTC negotiates today, starting with dimpl's PSK cipher suites and the `ccm` dependency they pull in, so nothing MoQ can't reach from a browser peer stays compiled. @@ -18,7 +18,7 @@ suites, extensions, SDP attributes, codecs' packetizers) against what the vendored code still carries, cite the evidence for each removal in the PR, and keep what a browser negotiates even if MoQ doesn't call it yet. The [WebRTC epic](/quest/m3/webrtc/README.md)'s settled removals (its "What goes" list, such as G.7xx, DTMF, and -comfort noise) and non-goals (TURN, DTLS 1.3) stay as decided: this trim +comfort noise) and non-goals (TURN, DTLS 1.3, data channels) stay as decided: this trim only removes more, never restores. API that moq-webrtc never calls but a browser could need stays for [the dead-API trim](/quest/m4/webrtc-dead-api.md). diff --git a/quest/m4/webrtc-sctp-feature.md b/quest/m4/webrtc-sctp-feature.md deleted file mode 100644 index 8be9ab15e64..00000000000 --- a/quest/m4/webrtc-sctp-feature.md +++ /dev/null @@ -1,20 +0,0 @@ -# [S] WHIP/WHEP builds carry no SCTP - -## Goal - -The vendored `sctp_proto` and str0m's SCTP glue compile only with -moq-webrtc's `p2p` feature (its data-channel transport), so a WHIP/WHEP-only -build has no SCTP code in its tree. - -## Plan - -Planned 2026-11-07 (maintainer, /quest-complete), a follow-up of -[moq-dev/moq#8163](https://github.com/moq-dev/moq/pull/8163), which vendors -the stack but still compiles SCTP into every build. The [WebRTC epic](/quest/m3/webrtc/README.md)'s settled -decision ("SCTP stays ... but compiles only with the data-channel feature") -gets this owner. Gate the modules and the str0m paths that reach them, -and add a check, in the feature matrix `just rs features` runs, that a -build without `p2p` neither compiles nor links `sctp_proto`. The feature -keeps its name. - -Public API: none. Wire: none. diff --git a/quest/m5/browser-mesh.md b/quest/m5/browser-mesh.md deleted file mode 100644 index 907c7629bde..00000000000 --- a/quest/m5/browser-mesh.md +++ /dev/null @@ -1,64 +0,0 @@ -# [L] Browser tabs forward for their peers on a local network - -## Goal - -A page that opts in forwards broadcasts between the peers it holds direct -sessions with, so browsers on one local network form a mesh: a broadcast one -tab publishes reaches a tab it has no direct session with through a tab that -has both, and keeps flowing when the site's internet drops. A tab is then a -routing node like any relay, and the relay session stays the fallback route. - -## Plan - -Decided 2026-11-10 (maintainer, /quest-plan on lite-07 routing): "Web clients -might forward too, honestly it would be lit to have P2P meshes for browsers -on the local network so please plan that." - -- ✅ The forwarding engine is the Rust router, run in the tab through the - [Rust model in the browser](/quest/m5/rs2ts-js.md), WebAssembly first since 2026-11-09, (rejected: handwriting - the forwarding rule in `js/net`, which was feasibility, route requests, - holds, and echoes when this was decided and is paths, withdrawals, holds, - and the doubt since the - [routes epic](/quest/m2/cluster-routes/README.md)'s Plan item 27, a second - implementation of the part of the protocol that has produced the most - bugs; pulling the port forward to m4). So the tab runs the router the route - model checks, and the [P2P epic](/quest/m4/p2p/README.md)'s "no second - routing implementation" holds. -- ✅ m5, behind that port. - -This lifts three statements once it lands: the P2P epic's "A browser never -carries another peer's traffic", the -[cluster routing](/quest/m3/cluster-routing/README.md) plan's browser tabs -keeping `proxy` off, and `js/net`'s non-transit -tab. Until then each stays true. - -It also settles why every publisher stays an origin node (Plan item 18 of -[Routes and announces](/quest/m2/cluster-routes/README.md)): a tab -that forwards needs its own identity. - -To settle when this starts: - -- Which sessions a tab meshes over. The P2P epic's data channels pair on a - LAN with host and mDNS candidates and an empty ICE server list; a tab can - also dial a local relay by WebTransport with a pinned certificate hash. - Recommended: reuse the P2P epic's `Peers`, with `proxy` turned on per - connection, rather than a second connection type. -- Trust. A forwarding tab can alter what it forwards, and a scoped peer's - identities are qualified, so a second scoped hop is refused today. Say - which grant LAN peers give each other, and whether the mesh needs more - than one scoped hop. -- Limits a tab needs that a relay does not: how many peers it forwards for, - and what it does on battery or a metered link. - -Test in the browser suite: three tabs in a line, where the ends share no -session, deliver a broadcast end to end, reroute when the middle tab closes -and a relay path exists, and never loop. - -Public API: a per-connection forwarding option in `@moq/net` or `@moq/p2p`. -Wire: none expected; a forwarding tab speaks the lite-07 route layer as a -relay does. - -## Required - -- [@moq/net runs the Rust model in the browser](/quest/m5/rs2ts-js.md) - the Rust router and model running in the tab -- [P2P](/quest/m4/p2p/README.md) - direct browser sessions, their signaling, and `Peers` diff --git a/quest/m5/mesh-ice.md b/quest/m5/mesh-ice.md index 4d219957b3c..ebd19650527 100644 --- a/quest/m5/mesh-ice.md +++ b/quest/m5/mesh-ice.md @@ -3,7 +3,7 @@ ## Goal Mesh nodes on different networks that cannot dial each other's addresses -connect directly through the [P2P](/quest/m4/p2p/README.md) line's native +connect directly through the P2P line's native QUIC-over-ICE pairs, with the relay as rendezvous and fallback, and the direct link joins the [sparse overlay](/quest/m3/mesh/overlay.md) as an ordinary link. @@ -18,5 +18,4 @@ carries the fallback route. ## Required -- [Native pairs over ICE and QUIC](/quest/m4/p2p/native-quic.md) - the transport this reuses - [Sparse overlay](/quest/m3/mesh/overlay.md) - the overlay the direct link joins diff --git a/quest/m9/uring-cluster-dial.md b/quest/m9/uring-cluster-dial.md index a57b45f6532..f8161eafae9 100644 --- a/quest/m9/uring-cluster-dial.md +++ b/quest/m9/uring-cluster-dial.md @@ -22,7 +22,7 @@ CPU per Gbps and latency on the relay-to-relay fanout shape, ring against tokio, swept over links and subscribers. Decided 2026-10-22 (maintainer), from the io_uring audit: cluster dials -stay measure-gated. WebRTC data channels stay on tokio. TCP and +stay measure-gated. TCP and WebSocket move onto the workers through [Stream transports](/quest/m9/stream-transports/README.md), which its own decision exempts from a gate. diff --git a/rs/moq-relay/Cargo.toml b/rs/moq-relay/Cargo.toml index f61470ee170..15a31d38734 100644 --- a/rs/moq-relay/Cargo.toml +++ b/rs/moq-relay/Cargo.toml @@ -38,8 +38,6 @@ doc = false # A programmatic relay fixture with generated TLS and ephemeral ports, and # `cluster::Options::network`, which routes peer dials over in-memory links. test-support = ["moq-tokio/sim"] -# The optional public STUN Binding listener (`--stun-bind`). -stun = ["dep:stun-types"] default = ["cluster-lan", "quic", "websocket", "uds"] # Discover cluster peers on the LAN with mDNS (`--cluster-lan`). cluster-lan = ["moq-tokio/mdns"] @@ -99,7 +97,6 @@ rustls = { version = "0.23", features = ["std"], default-features = false } serde = { workspace = true } serde_json = { workspace = true } serde_with = { workspace = true, features = ["json", "base64"] } -stun-types = { workspace = true, optional = true } sysinfo = { version = "0.40", default-features = false, features = ["system"] } thiserror = { workspace = true } tokio = { workspace = true, features = ["full"] } @@ -137,7 +134,6 @@ qmux = { workspace = true, features = ["tcp"] } rcgen = { workspace = true, features = ["pem"] } rind-rcgen = { workspace = true } rind-rustls = { workspace = true } -stun-types = { workspace = true } tempfile = { workspace = true } # Runs the tests that need a variable set or unset in a child process given it. test-env = { path = "../test-env" } diff --git a/rs/moq-relay/src/config.rs b/rs/moq-relay/src/config.rs index 126f886183f..3ccb011b53b 100644 --- a/rs/moq-relay/src/config.rs +++ b/rs/moq-relay/src/config.rs @@ -78,12 +78,6 @@ pub struct Config { #[serde(default)] pub web: web::Config, - /// Optional public STUN Binding listener, available with the `stun` feature. - #[cfg(feature = "stun")] - #[usage(flatten)] - #[serde(default)] - pub stun: crate::stun::Config, - /// Stats publishing configuration. Disabled unless `stats.enabled = true`. #[usage(flatten)] #[serde(default)] @@ -262,12 +256,6 @@ impl Config { env: &usage_rs::config::EnvLayer, file: Option>, ) -> anyhow::Result<()> { - #[cfg(not(feature = "stun"))] - anyhow::ensure!( - env.get("MOQ_STUN_BIND").is_none(), - "MOQ_STUN_BIND requires a moq-relay build with the stun feature" - ); - let mut deprecated = self.deprecated(); let (merged, resolved) = moq_tokio::cli::Merge { registry: crate::settings(), @@ -503,48 +491,6 @@ mod tests { assert!(!config.connect.extensions.ietf); } - #[cfg(feature = "stun")] - #[test] - fn stun_binding_merges_file_and_cli() { - if !test_env::Env::without(&["MOQ_STUN_BIND"]).isolate() { - return; - } - let dir = tempfile::tempdir().unwrap(); - let path = dir.path().join("stun.toml"); - std::fs::write(&path, "[stun]\nbind = \"127.0.0.1:3478\"\n").unwrap(); - let file = Config::parse_and_merge([std::ffi::OsString::from("moq-relay"), path.clone().into()]).unwrap(); - assert_eq!(file.stun.bind, Some("127.0.0.1:3478".parse().unwrap())); - let cli = Config::parse_and_merge([ - std::ffi::OsString::from("moq-relay"), - path.into(), - "--stun-bind=127.0.0.1:3479".into(), - ]) - .unwrap(); - assert_eq!(cli.stun.bind, Some("127.0.0.1:3479".parse().unwrap())); - assert!(toml::from_str::("[stun]\nrate = 10").is_err()); - } - - #[cfg(not(feature = "stun"))] - #[test] - fn a_stun_listener_requires_the_feature() { - assert!(toml::from_str::("[stun]\nbind = \"127.0.0.1:3478\"").is_err()); - assert!(Config::parse_and_merge(["moq-relay", "--stun-bind=127.0.0.1:3478"]).is_err()); - let cli = usage_rs::config::CliLayer::new(std::iter::empty::<(String, String)>()); - let env = usage_rs::config::EnvLayer::new([("MOQ_STUN_BIND".to_string(), "127.0.0.1:3478".to_string())]); - let error = Config::default().merge_into(&cli, &env, None).unwrap_err(); - assert!(error.to_string().contains("MOQ_STUN_BIND requires"), "{error}"); - } - - #[cfg(feature = "stun")] - #[test] - fn stun_binding_merges_the_environment() { - if !test_env::Env::default().set("MOQ_STUN_BIND", "[::1]:3478").isolate() { - return; - } - let config = Config::parse_and_merge(["moq-relay"]).unwrap(); - assert_eq!(config.stun.bind, Some("[::1]:3478".parse().unwrap())); - } - #[test] fn session_limits_merge_without_crossing_peer_policy() { if !test_env::Env::without(&["MOQ_LIMITS_CLIENT_ANNOUNCES", "MOQ_LIMITS_PEER_ANNOUNCES"]).isolate() { diff --git a/rs/moq-relay/src/internal.rs b/rs/moq-relay/src/internal.rs index 1c168633a48..ee81584144e 100644 --- a/rs/moq-relay/src/internal.rs +++ b/rs/moq-relay/src/internal.rs @@ -98,8 +98,6 @@ pub struct Internal { health: moq_tokio::accept::Health, listeners: Vec, uring: Vec, - #[cfg(any(feature = "stun", test))] - stun: Option, #[cfg(feature = "_quic")] demux: Option, shutdown: Option, @@ -115,8 +113,6 @@ struct InternalState { sessions: crate::session::Registry, listeners: Vec, uring: Vec, - #[cfg(any(feature = "stun", test))] - stun: Option, #[cfg(feature = "_quic")] demux: Option, shutdown: Option, @@ -146,8 +142,6 @@ impl Internal { health, listeners, uring: Vec::new(), - #[cfg(any(feature = "stun", test))] - stun: None, #[cfg(feature = "_quic")] demux: None, shutdown: None, @@ -156,12 +150,6 @@ impl Internal { } } - #[cfg(feature = "stun")] - pub(crate) fn with_stun(mut self, counters: Option) -> Self { - self.stun = counters; - self - } - #[cfg(feature = "_quic")] pub(crate) fn with_demux(mut self, counters: Option) -> Self { self.demux = counters; @@ -281,8 +269,6 @@ impl Internal { sessions: self.sessions.clone(), listeners: self.listeners.clone(), uring: self.uring.clone(), - #[cfg(any(feature = "stun", test))] - stun: self.stun.clone(), #[cfg(feature = "_quic")] demux: self.demux.clone(), shutdown: self.shutdown.clone(), @@ -450,10 +436,6 @@ async fn serve_health() -> Response { /// counts (`open - closed`). async fn serve_metrics(State(state): State) -> Response { let mut scrape = Scrape::new(state.stats.snapshot(), &state.listeners, &state.uring); - #[cfg(any(feature = "stun", test))] - { - scrape.stun = state.stun; - } #[cfg(feature = "_quic")] { scrape.demux = state.demux; @@ -590,8 +572,6 @@ struct Scrape { stats: moq_net::stats::Snapshot, listeners: Vec, uring: Vec, - #[cfg(any(feature = "stun", test))] - stun: Option, #[cfg(feature = "_quic")] demux: Option, draining: Option, @@ -620,8 +600,6 @@ impl Scrape { stats, listeners: listeners.to_vec(), uring: uring.to_vec(), - #[cfg(any(feature = "stun", test))] - stun: None, #[cfg(feature = "_quic")] demux: None, draining: None, @@ -639,10 +617,6 @@ impl Scrape { self.encode_sessions(encoder)?; encode_accepts(encoder, &self.listeners)?; encode_uring(encoder, &self.uring)?; - #[cfg(any(feature = "stun", test))] - if let Some(stun) = &self.stun { - stun.encode(encoder)?; - } #[cfg(feature = "_quic")] if let Some(demux) = &self.demux { encode_demux(encoder, demux)?; @@ -1267,30 +1241,6 @@ mod tests { } } - #[tokio::test] - async fn stun_metrics_are_present_only_for_a_configured_listener() { - for stun in [None, Some(crate::stun::Counters::default())] { - let configured = stun.is_some(); - let state = InternalState { - stats: moq_net::stats::Registry::disabled(), - nodes: None, - refusals: None, - sessions: crate::session::Registry::new(), - listeners: Vec::new(), - uring: Vec::new(), - stun, - #[cfg(feature = "_quic")] - demux: None, - shutdown: None, - }; - let response = serve_metrics(State(state)).await; - let body = axum::body::to_bytes(response.into_body(), usize::MAX).await.unwrap(); - let body = std::str::from_utf8(&body).unwrap(); - assert_eq!(body.contains("moq_relay_stun_replies_total"), configured); - assert_eq!(body.contains("moq_relay_stun_dropped_total"), configured); - } - } - /// Every drop reason renders from zero, and only for a relay whose QUIC port /// runs the demux. #[cfg(feature = "_quic")] @@ -1310,7 +1260,6 @@ mod tests { sessions: crate::session::Registry::new(), listeners: Vec::new(), uring: Vec::new(), - stun: None, demux, shutdown: None, }; @@ -1639,8 +1588,6 @@ mod tests { sessions: crate::session::Registry::new(), listeners: Vec::new(), uring: Vec::new(), - #[cfg(any(feature = "stun", test))] - stun: None, #[cfg(feature = "_quic")] demux: None, shutdown: None, @@ -1661,8 +1608,6 @@ mod tests { sessions: crate::session::Registry::new(), listeners: Vec::new(), uring: Vec::new(), - #[cfg(any(feature = "stun", test))] - stun: None, #[cfg(feature = "_quic")] demux: None, shutdown: None, @@ -2058,7 +2003,6 @@ mod tests { uring: vec![moq_uring::metrics::Metrics::default()], #[cfg(not(all(target_os = "linux", feature = "_uring")))] uring: Vec::new(), - stun: Some(crate::stun::Counters::default()), #[cfg(feature = "_quic")] demux: Some(moq_tokio::quic::demux::Counters::default()), shutdown: Some(shutdown), @@ -2110,9 +2054,6 @@ mod tests { # TYPE moq_relay_stale_bytes_total counter # TYPE moq_relay_stale_frames_total counter # TYPE moq_relay_stale_groups_total counter -# TYPE moq_relay_stun_dropped_total counter -# TYPE moq_relay_stun_io_errors_total counter -# TYPE moq_relay_stun_replies_total counter # TYPE moq_relay_subscriptions_closed_total counter # TYPE moq_relay_subscriptions_opened_total counter # TYPE moq_relay_viewers_closed_total counter @@ -2157,13 +2098,6 @@ counter moq_relay_stale_frames_total{role="publisher",tier="edge"} 0 counter moq_relay_stale_frames_total{role="subscriber",tier="edge"} 0 counter moq_relay_stale_groups_total{role="publisher",tier="edge"} 0 counter moq_relay_stale_groups_total{role="subscriber",tier="edge"} 0 -counter moq_relay_stun_dropped_total{reason="capacity"} 0 -counter moq_relay_stun_dropped_total{reason="global"} 0 -counter moq_relay_stun_dropped_total{reason="invalid"} 0 -counter moq_relay_stun_dropped_total{reason="io"} 0 -counter moq_relay_stun_dropped_total{reason="source"} 0 -counter moq_relay_stun_io_errors_total{} 0 -counter moq_relay_stun_replies_total{} 0 counter moq_relay_subscriptions_closed_total{role="publisher",tier="edge"} 0 counter moq_relay_subscriptions_closed_total{role="subscriber",tier="edge"} 0 counter moq_relay_subscriptions_opened_total{role="publisher",tier="edge"} 0 diff --git a/rs/moq-relay/src/lib.rs b/rs/moq-relay/src/lib.rs index 141ee27cd3b..9af363a9252 100644 --- a/rs/moq-relay/src/lib.rs +++ b/rs/moq-relay/src/lib.rs @@ -33,8 +33,6 @@ pub mod session; mod settings; pub mod shutdown; pub mod stats; -#[cfg(any(feature = "stun", test))] -pub mod stun; #[cfg(feature = "test-support")] mod test_support; #[cfg(all(target_os = "linux", feature = "_uring"))] diff --git a/rs/moq-relay/src/relay.rs b/rs/moq-relay/src/relay.rs index 6a7e2b89ec0..4376d2d3472 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -94,8 +94,6 @@ pub struct Relay { driver: Option, internal: internal::Internal, web: web::Web, - #[cfg(feature = "stun")] - stun: Option, addr: Option, shutdown: shutdown::Observer, shutdown_trigger: shutdown::Trigger, @@ -316,9 +314,6 @@ impl Relay { // starts them on its first accept. let server = server.bind().await.context("failed to bind listeners")?; - #[cfg(feature = "stun")] - let stun = crate::stun::Server::bind(config.stun).await?; - // Internal (ops) listener (plain HTTP, opt-in via `--internal-listen`) for // /metrics + /health + /nodes, separate from the customer-facing web server. No-op // when unconfigured. Every listener that performs a real accept(2) reports here, @@ -332,8 +327,6 @@ impl Relay { .with_listeners(web.accept_health()) .with_listeners(server.accept_health()) .bind()?; - #[cfg(feature = "stun")] - let internal = internal.with_stun(stun.as_ref().map(|stun| stun.counters.clone())); #[cfg(feature = "_quic")] let internal = internal.with_demux(demux.as_ref().map(|demux| demux.counters().clone())); // Bound but not yet serving: registering here (rather than after the @@ -362,8 +355,6 @@ impl Relay { driver: Some(driver), internal, web, - #[cfg(feature = "stun")] - stun, addr, shutdown, shutdown_trigger, @@ -585,8 +576,6 @@ impl Relay { cluster, internal, web, - #[cfg(feature = "stun")] - stun, shutdown, shutdown_trigger, signals, @@ -743,21 +732,11 @@ impl Relay { }) }; - let stun = async move { - #[cfg(feature = "stun")] - match stun { - Some(stun) => stun.run().await, - None => std::future::pending().await, - } - #[cfg(not(feature = "stun"))] - std::future::pending::>().await - }; // Box the large serving futures: a debug build copies each one into this poll's // stack frame several times, and an embedder's main thread pays for that frame. let result = tokio::select! { Err(err) = Box::pin(started.run()) => Err(err).context("cluster failed"), Err(err) = Box::pin(web.serve(web_routes)) => Err(err).context("web server failed"), - Err(err) = stun => Err(err).context("STUN server failed"), Err(err) = internal.serve(internal_routes) => Err(err).context("internal server failed"), Err(err) = serve_shared => Err(err).context("server failed"), Err(err) = quic_workers => Err(err).context("QUIC workers failed"), @@ -879,35 +858,6 @@ fn spawn_connection( #[cfg(test)] mod tests { - #[cfg(feature = "stun")] - #[tokio::test] - async fn stun_listener_runs_with_the_relay_and_stops_with_it() { - use stun_types::message::{BINDING, Message, MessageWriteVec}; - use stun_types::prelude::*; - let mut config = crate::Config::default(); - config.listen.tcp.bind = Some("127.0.0.1:0".parse().unwrap()); - config.stun.bind = Some("127.0.0.1:0".parse().unwrap()); - let mut relay = super::Relay::load(config).await.unwrap().with_signals(false); - let _admissions = relay.admissions().unwrap(); - let addr = relay.stun.as_ref().unwrap().addr(); - let ready = relay.ready(); - let shutdown = relay.shutdown_trigger().clone(); - let running = tokio::spawn(relay.run()); - ready.wait().await.unwrap(); - let client = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); - let request = Message::builder_request(BINDING, MessageWriteVec::new()).finish(); - client.send_to(&request, addr).await.unwrap(); - let mut reply = [0; 44]; - let (len, sender) = kio::clock::timeout(std::time::Duration::from_secs(5), client.recv_from(&mut reply)) - .await - .unwrap() - .unwrap(); - assert_eq!(sender, addr); - assert_eq!(len, 32); - shutdown.start(); - running.await.unwrap().unwrap(); - } - #[tokio::test(start_paused = true)] async fn pending_handshake_cannot_extend_the_drain_deadline() { use futures::FutureExt; diff --git a/rs/moq-relay/src/settings.rs b/rs/moq-relay/src/settings.rs index 0f6aece673a..e5a085ba9be 100644 --- a/rs/moq-relay/src/settings.rs +++ b/rs/moq-relay/src/settings.rs @@ -41,10 +41,6 @@ pub struct Settings { #[usage(flatten)] stats: Stats, - #[cfg(feature = "stun")] - #[usage(flatten)] - stun: Stun, - #[usage(flatten)] cache: Cache, @@ -269,11 +265,3 @@ struct PeerQuic { #[usage(env = "MOQ_LIMITS_PEER_QUIC_SEND_WINDOW", cli("--limits-peer-quic-send-window"))] send_window: Option, } - -#[cfg(feature = "stun")] -#[derive(usage_rs::Config)] -#[usage(prefix = "stun")] -struct Stun { - #[usage(env = "MOQ_STUN_BIND", cli("--stun-bind"))] - bind: Option, -} diff --git a/rs/moq-relay/src/stun.rs b/rs/moq-relay/src/stun.rs deleted file mode 100644 index 6ffa8fa7a86..00000000000 --- a/rs/moq-relay/src/stun.rs +++ /dev/null @@ -1,532 +0,0 @@ -//! Opt-in public STUN Binding on a separate UDP socket. - -use std::collections::{BTreeSet, HashMap}; -use std::net::{IpAddr, SocketAddr}; -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::time::Duration; - -use anyhow::Context; -use kio::clock::Instant; -use serde::{Deserialize, Serialize}; -use stun_types::attribute::XorMappedAddress; -use stun_types::message::{BINDING, Message, MessageClass, MessageHeader, MessageWriteMutSlice}; -use stun_types::prelude::*; - -/// Configuration for the optional public STUN Binding listener. -#[derive(usage_rs::Args, Clone, Debug, Default, Deserialize, Serialize)] -#[serde(deny_unknown_fields, default)] -#[non_exhaustive] -pub struct Config { - /// UDP address serving STUN Binding requests, disabled when unset. - #[usage(long = "stun-bind", name = "stun-bind", env = "MOQ_STUN_BIND", setting = "stun.bind")] - pub bind: Option, -} - -const SOURCE_RATE: u64 = 10; -const SOURCE_BURST: u64 = 20; -const GLOBAL_RATE: u64 = 1000; -const GLOBAL_BURST: u64 = 2000; -const SOURCES_MAX: usize = 4096; -const SOURCE_IDLE: Duration = Duration::from_secs(SOURCE_BURST / SOURCE_RATE); -const TOKEN: u64 = 1_000_000_000; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -enum Drop { - Invalid = 0, - Source = 1, - Global = 2, - Capacity = 3, - Io = 4, -} - -#[derive(Default)] -struct Totals { - replies: AtomicU64, - io_errors: AtomicU64, - dropped: [AtomicU64; 5], -} - -#[derive(Clone, Default)] -pub(crate) struct Counters(Arc); - -impl Counters { - fn drop(&self, reason: Drop) { - self.0.dropped[reason as usize].fetch_add(1, Ordering::Relaxed); - } - - pub(crate) fn encode(&self, encoder: &mut prometheus_client::encoding::DescriptorEncoder) -> std::fmt::Result { - use crate::internal::{counter, single}; - use prometheus_client::metrics::counter::ConstCounter; - - single( - encoder, - "moq_relay_stun_replies", - "STUN Binding replies sent.", - ConstCounter::new(self.0.replies.load(Ordering::Relaxed)), - )?; - counter( - encoder, - "moq_relay_stun_dropped", - "STUN datagrams dropped without replying.", - ["invalid", "source", "global", "capacity", "io"] - .into_iter() - .zip(&self.0.dropped) - .map(|(reason, count)| ([("reason", reason)], count.load(Ordering::Relaxed))), - )?; - single( - encoder, - "moq_relay_stun_io_errors", - "Recoverable STUN socket I/O errors.", - ConstCounter::new(self.0.io_errors.load(Ordering::Relaxed)), - ) - } -} - -struct Bucket { - credit: u64, - updated: Instant, -} - -impl Bucket { - fn new(burst: u64, now: Instant) -> Self { - Self { - credit: burst * TOKEN, - updated: now, - } - } - - fn take(&mut self, now: Instant, rate: u64, burst: u64) -> bool { - // Nanotokens preserve sub-token refill without floats or clock-dependent rounding. - let refill = now - .saturating_duration_since(self.updated) - .as_nanos() - .saturating_mul(u128::from(rate)); - self.credit = (u128::from(self.credit) + refill).min(u128::from(burst * TOKEN)) as u64; - self.updated = now; - if self.credit < TOKEN { - return false; - } - self.credit -= TOKEN; - true - } -} - -struct Limits { - global: Bucket, - sources: HashMap, - // One entry per IP, so activity cannot grow a stale-expiry queue indefinitely. - oldest: BTreeSet<(Instant, IpAddr)>, -} - -impl Limits { - fn new(now: Instant) -> Self { - Self { - global: Bucket::new(GLOBAL_BURST, now), - sources: HashMap::new(), - oldest: BTreeSet::new(), - } - } - - fn allow(&mut self, source: IpAddr, now: Instant) -> Result<(), Drop> { - if !self.global.take(now, GLOBAL_RATE, GLOBAL_BURST) { - return Err(Drop::Global); - } - let result = self.source(source.to_canonical(), now); - // An abusive source must not spend the global reply budget on its own refused packets. - if result.is_err() { - self.global.credit += TOKEN; - } - result - } - - fn source(&mut self, source: IpAddr, now: Instant) -> Result<(), Drop> { - if !self.sources.contains_key(&source) && self.sources.len() == SOURCES_MAX { - let &(last, ip) = self.oldest.first().expect("a full source table has an oldest entry"); - if now.saturating_duration_since(last) < SOURCE_IDLE { - return Err(Drop::Capacity); - } - self.oldest.remove(&(last, ip)); - self.sources.remove(&ip); - } - let bucket = self - .sources - .entry(source) - .or_insert_with(|| Bucket::new(SOURCE_BURST, now)); - self.oldest.remove(&(bucket.updated, source)); - let allowed = bucket.take(now, SOURCE_RATE, SOURCE_BURST); - self.oldest.insert((bucket.updated, source)); - if allowed { Ok(()) } else { Err(Drop::Source) } - } -} - -/// Decode through the maintained codec; UDP must contain exactly one whole message. -fn binding(data: &[u8], source: SocketAddr, output: &mut [u8; 44]) -> Option { - let header = MessageHeader::from_bytes(data).ok()?; - if usize::from(header.data_length()) + MessageHeader::LENGTH != data.len() { - return None; - } - if header.get_type().class() != MessageClass::Request || header.get_type().method() != BINDING { - return None; - } - let request = Message::from_bytes(data).ok()?; - // The general codec may ignore attributes after an ending attribute. This - // endpoint refuses those bytes and required extensions it does not implement. - let mut end = MessageHeader::LENGTH; - for (offset, attribute) in request.iter_attributes() { - if attribute.get_type().comprehension_required() { - return None; - } - end = offset + attribute.padded_len(); - } - if end != data.len() { - return None; - } - let mut reply = Message::builder_success(&request, MessageWriteMutSlice::new(output)); - let mapped = SocketAddr::new(source.ip().to_canonical(), source.port()); - reply - .add_attribute(&XorMappedAddress::new(mapped, request.transaction_id())) - .ok()?; - Some(reply.finish()) -} - -// Unconnected UDP can report a previous peer's ICMP error on the next receive. -// It says nothing about the listener or the media relay's other connections. -fn recoverable(error: &std::io::Error) -> bool { - matches!( - error.kind(), - std::io::ErrorKind::ConnectionRefused - | std::io::ErrorKind::ConnectionReset - | std::io::ErrorKind::HostUnreachable - | std::io::ErrorKind::NetworkUnreachable - | std::io::ErrorKind::Interrupted - ) -} - -pub(crate) struct Server { - socket: tokio::net::UdpSocket, - pub(crate) counters: Counters, -} - -impl Server { - #[cfg(all(test, feature = "stun"))] - pub(crate) fn addr(&self) -> SocketAddr { - self.socket.local_addr().unwrap() - } - - pub(crate) async fn bind(config: Config) -> anyhow::Result> { - let Some(bind) = config.bind else { - return Ok(None); - }; - let socket = tokio::net::UdpSocket::bind(bind) - .await - .context("failed to bind STUN listener")?; - tracing::info!(addr = %socket.local_addr()?, kind = "stun", "listening"); - Ok(Some(Self { - socket, - counters: Counters::default(), - })) - } - - pub(crate) async fn run(self) -> anyhow::Result<()> { - let mut limits = Limits::new(Instant::now()); - // A full UDP payload avoids treating truncation as a smaller valid request. - let mut input = vec![0; 65536]; - let mut output = [0; 44]; - loop { - let (len, source) = match self.socket.recv_from(&mut input).await { - Ok(packet) => packet, - Err(error) if recoverable(&error) => { - self.counters.0.io_errors.fetch_add(1, Ordering::Relaxed); - continue; - } - Err(error) => return Err(error).context("STUN receive failed"), - }; - if let Err(reason) = limits.allow(source.ip(), Instant::now()) { - self.counters.drop(reason); - continue; - } - let Some(len) = binding(&input[..len], source, &mut output) else { - self.counters.drop(Drop::Invalid); - continue; - }; - match self.socket.send_to(&output[..len], source).await { - Ok(_) => { - self.counters.0.replies.fetch_add(1, Ordering::Relaxed); - } - Err(error) if recoverable(&error) => { - self.counters.0.io_errors.fetch_add(1, Ordering::Relaxed); - self.counters.drop(Drop::Io); - } - Err(error) => return Err(error).context("STUN reply failed"), - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use stun_types::message::{MessageType, MessageWriteVec}; - - fn request() -> Vec { - Message::builder( - MessageType::from_class_method(MessageClass::Request, BINDING), - 0x0102030405060708090a0b0cu128.into(), - MessageWriteVec::new(), - ) - .finish() - } - - #[test] - fn binding_reply_contains_only_the_sender_mapping_and_transaction() { - let request = request(); - assert_eq!(request.len(), 20); - for addr in ["192.0.2.1:3478", "[2001:db8::1]:4567", "[::ffff:192.0.2.1]:3478"] { - let source: SocketAddr = addr.parse().unwrap(); - let mut output = [0; 44]; - let len = binding(&request, source, &mut output).unwrap(); - let reply = Message::from_bytes(&output[..len]).unwrap(); - assert_eq!(reply.class(), MessageClass::Success); - assert_eq!( - reply.transaction_id(), - Message::from_bytes(&request).unwrap().transaction_id() - ); - assert_eq!(reply.iter_attributes().count(), 1); - assert_eq!( - reply - .attribute::() - .unwrap() - .addr(reply.transaction_id()), - SocketAddr::new(source.ip().to_canonical(), source.port()) - ); - assert_eq!(len, if source.ip().to_canonical().is_ipv4() { 32 } else { 44 }); - } - let mut output = [0; 44]; - binding(&request, "192.0.2.1:3478".parse().unwrap(), &mut output).unwrap(); - // Independent RFC 8489 IPv4 XOR address bytes, without relying on the decoder. - assert_eq!( - &output[20..32], - &[0, 0x20, 0, 8, 0, 1, 0x2c, 0x84, 0xe1, 0x12, 0xa6, 0x43] - ); - } - - #[test] - fn malformed_non_binding_and_required_extensions_get_no_reply() { - let source = "192.0.2.1:3478".parse().unwrap(); - let mut input = vec![vec![], vec![0; 20], request()[..19].to_vec()]; - let mut trailing = request(); - trailing.push(0); - input.push(trailing); - for class in [MessageClass::Success, MessageClass::Indication, MessageClass::Error] { - input.push( - Message::builder( - MessageType::from_class_method(class, BINDING), - 1.into(), - MessageWriteVec::new(), - ) - .finish(), - ); - } - let mut method = request(); - method[1] = 3; - input.push(method); - let mut broken_attr = request(); - broken_attr[3] = 4; - broken_attr.extend_from_slice(&[0x80, 0x22, 0, 16]); - input.push(broken_attr); - let mut required = request(); - required[3] = 4; - required.extend_from_slice(&[0, 3, 0, 0]); - input.push(required); - for data in input { - assert!(binding(&data, source, &mut [0; 44]).is_none(), "{data:?}"); - } - } - - #[test] - fn fingerprint_is_validated_and_must_end_the_request() { - let source = "192.0.2.1:3478".parse().unwrap(); - let mut writer = Message::builder_request(BINDING, MessageWriteVec::new()); - writer.add_fingerprint().unwrap(); - let valid = writer.finish(); - assert!(binding(&valid, source, &mut [0; 44]).is_some()); - let mut invalid = valid.clone(); - *invalid.last_mut().unwrap() ^= 1; - assert!(binding(&invalid, source, &mut [0; 44]).is_none()); - let mut extra = valid; - extra[3] += 4; - extra.extend_from_slice(&[0x80, 0x22, 0, 0]); - assert!(binding(&extra, source, &mut [0; 44]).is_none()); - } - - #[tokio::test(start_paused = true)] - async fn source_bucket_refills_fractional_tokens_with_mock_time() { - let mut limits = Limits::new(Instant::now()); - let source = "192.0.2.1".parse().unwrap(); - for _ in 0..SOURCE_BURST { - limits.allow(source, Instant::now()).unwrap(); - } - assert_eq!(limits.allow(source, Instant::now()), Err(Drop::Source)); - tokio::time::advance(Duration::from_millis(99)).await; - assert_eq!(limits.allow(source, Instant::now()), Err(Drop::Source)); - tokio::time::advance(Duration::from_millis(1)).await; - limits.allow(source, Instant::now()).unwrap(); - assert_eq!(limits.allow(source, Instant::now()), Err(Drop::Source)); - // An IPv4-mapped representation is the same source IP, regardless of port/family. - assert_eq!( - limits.allow("::ffff:192.0.2.1".parse().unwrap(), Instant::now()), - Err(Drop::Source) - ); - assert_eq!(limits.sources.len(), 1); - } - - #[tokio::test(start_paused = true)] - async fn global_budget_bounds_distributed_sources_and_refills() { - let mut limits = Limits::new(Instant::now()); - for ip in 0..GLOBAL_BURST { - limits.allow(IpAddr::V4((ip as u32).into()), Instant::now()).unwrap(); - } - assert_eq!( - limits.allow("192.0.2.1".parse().unwrap(), Instant::now()), - Err(Drop::Global) - ); - tokio::time::advance(Duration::from_millis(1)).await; - limits.allow("192.0.2.1".parse().unwrap(), Instant::now()).unwrap(); - assert_eq!( - limits.allow("192.0.2.2".parse().unwrap(), Instant::now()), - Err(Drop::Global) - ); - } - - #[tokio::test(start_paused = true)] - async fn source_drops_do_not_spend_another_sources_global_budget() { - let mut limits = Limits::new(Instant::now()); - let ip = "192.0.2.1".parse().unwrap(); - for _ in 0..SOURCE_BURST { - limits.allow(ip, Instant::now()).unwrap(); - } - for _ in 0..GLOBAL_BURST { - assert_eq!(limits.allow(ip, Instant::now()), Err(Drop::Source)); - } - assert_eq!(limits.global.credit, (GLOBAL_BURST - SOURCE_BURST) * TOKEN); - limits.allow("192.0.2.2".parse().unwrap(), Instant::now()).unwrap(); - } - - #[tokio::test(start_paused = true)] - async fn source_table_refuses_growth_until_an_old_entry_has_fully_refilled() { - let mut limits = Limits::new(Instant::now()); - for ip in 0..SOURCES_MAX { - limits.source(IpAddr::V4((ip as u32).into()), Instant::now()).unwrap(); - } - assert_eq!( - limits.source("192.0.2.1".parse().unwrap(), Instant::now()), - Err(Drop::Capacity) - ); - tokio::time::advance(SOURCE_IDLE).await; - limits.source("192.0.2.1".parse().unwrap(), Instant::now()).unwrap(); - assert_eq!(limits.sources.len(), SOURCES_MAX); - assert_eq!(limits.oldest.len(), SOURCES_MAX); - } - - #[tokio::test] - async fn udp_listener_replies_and_disabled_listener_binds_nothing() { - assert!(Server::bind(Config::default()).await.unwrap().is_none()); - let server = Server::bind(Config { - bind: Some("127.0.0.1:0".parse().unwrap()), - }) - .await - .unwrap() - .unwrap(); - let addr = server.socket.local_addr().unwrap(); - let counters = server.counters.clone(); - let serving = tokio::spawn(server.run()); - let client = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); - client.send_to(&request(), addr).await.unwrap(); - let mut output = [0; 44]; - let (len, sender) = kio::clock::timeout(Duration::from_secs(5), client.recv_from(&mut output)) - .await - .unwrap() - .unwrap(); - assert_eq!(sender, addr); - let reply = Message::from_bytes(&output[..len]).unwrap(); - assert_eq!( - reply - .attribute::() - .unwrap() - .addr(reply.transaction_id()), - client.local_addr().unwrap() - ); - assert_eq!(counters.0.replies.load(Ordering::Relaxed), 1); - serving.abort(); - assert!(serving.await.unwrap_err().is_cancelled()); - } - #[test] - fn peer_icmp_errors_do_not_classify_the_listener_as_failed() { - use std::io::{Error, ErrorKind}; - for kind in [ - ErrorKind::ConnectionRefused, - ErrorKind::ConnectionReset, - ErrorKind::HostUnreachable, - ErrorKind::NetworkUnreachable, - ErrorKind::Interrupted, - ] { - assert!(recoverable(&Error::from(kind))); - } - for kind in [ - ErrorKind::PermissionDenied, - ErrorKind::InvalidInput, - ErrorKind::OutOfMemory, - ] { - assert!(!recoverable(&Error::from(kind))); - } - } - - #[test] - fn drop_metrics_preserve_reason_counts_without_source_labels() { - let counters = Counters::default(); - for reason in [Drop::Invalid, Drop::Source, Drop::Global, Drop::Capacity, Drop::Invalid] { - counters.drop(reason); - } - let output = crate::internal::render(move |encoder| counters.encode(encoder)); - assert!(output.contains("moq_relay_stun_replies_total 0")); - assert!(output.contains("reason=\"invalid\"} 2")); - for reason in ["source", "global", "capacity"] { - assert!(output.contains(&format!("reason=\"{reason}\"}} 1"))); - } - assert!(!output.contains("192.0.2")); - } - - #[test] - #[ignore = "benchmark"] - #[expect( - clippy::disallowed_methods, - clippy::disallowed_types, - reason = "the benchmark measures real per-request cost" - )] - fn benchmark_stun_sources() { - println!("sources,requests_per_source,ns_per_request"); - for sources in [1u32, 64, SOURCES_MAX as u32] { - for requests in [1u32, 20, 100] { - let now = Instant::now(); - let mut limits = Limits::new(now); - for ip in 0..sources { - limits.source(IpAddr::V4(ip.into()), now).unwrap(); - } - let started = std::time::Instant::now(); - for request in 0..requests { - let now = now.saturating_add(Duration::from_millis(100 * u64::from(request + 1))); - for ip in 0..sources { - limits.source(std::hint::black_box(IpAddr::V4(ip.into())), now).unwrap(); - } - } - println!( - "{sources},{requests},{}", - started.elapsed().as_nanos() / (u128::from(sources) * u128::from(requests)) - ); - assert_eq!(limits.oldest.len(), sources as usize); - assert_eq!(limits.sources.len(), sources as usize); - } - } - } -} diff --git a/rs/moq-tokio/Cargo.toml b/rs/moq-tokio/Cargo.toml index 7702744cf5e..1d951d5ea8d 100644 --- a/rs/moq-tokio/Cargo.toml +++ b/rs/moq-tokio/Cargo.toml @@ -42,7 +42,7 @@ jemalloc = ["dep:tikv-jemallocator", "dep:tikv-jemalloc-ctl"] websocket = ["qmux", "watch", "dep:dns-lookup", "dep:httparse", "dep:tokio-rustls", "dep:tokio-tungstenite"] # Qmux over TCP: plaintext `tcp://`, and `tls://`. Server-side and client-side. tcp = ["qmux", "dep:dns-lookup", "dep:tokio-rustls"] -# MoQ over a qmux session established elsewhere, such as moq-webrtc's data channel: +# MoQ over a qmux session established elsewhere, such as over a WebRTC data channel: # `Client::connect_with` and `Listener::accept_with`. Every qmux transport turns it on. qmux = ["_transport", "dep:qmux"] # Unix-domain-socket qmux transport (`unix://`), unix-only. Adds peer-credential diff --git a/rs/moq-webrtc/Cargo.toml b/rs/moq-webrtc/Cargo.toml index 1dddab6cff5..70584906837 100644 --- a/rs/moq-webrtc/Cargo.toml +++ b/rs/moq-webrtc/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "moq-webrtc" -description = "Media over QUIC - WebRTC: the WHIP/WHEP gateway and data-channel sessions with browser peers" +description = "Media over QUIC - WebRTC: the WHIP/WHEP gateway" authors = ["Luke Curley "] repository = "https://github.com/moq-dev/moq" license = "MIT OR Apache-2.0" @@ -24,19 +24,15 @@ default = ["server"] # stack and calls `whip::accept` / `whep::accept` drops them with # `default-features = false`. server = ["dep:axum"] -# MoQ sessions over a WebRTC data channel with a browser peer (the `p2p` module): qmux -# over SCTP, host candidates per interface, and `.local` candidates resolved over mDNS. -p2p = ["dep:if-addrs", "dep:mdns-sd", "dep:qmux", "moq-tokio/qmux"] -# Pure library: the WHIP/WHEP <-> MoQ gateway (axum routers + WHEP/WHIP client), and -# with `p2p`, MoQ sessions over a data channel. The CLI lives in `moq-cli` (the `rtc` -# subcommand); embedders mount the routers / dial with `Client` against their own origin. +# Pure library: the WHIP/WHEP <-> MoQ gateway (axum routers + WHEP/WHIP client). The CLI +# lives in `moq-cli` (the `rtc` subcommand); embedders mount the routers / dial with +# `Client` against their own origin. [dependencies] # The vendored stack's AES-CCM DTLS suites. aes = { workspace = true } arrayvec = { workspace = true } axum = { workspace = true, optional = true } -base64ct = { workspace = true } bytes = { workspace = true } ccm = { workspace = true } # The vendored stack's SDP parser. @@ -44,21 +40,17 @@ combine = { workspace = true } crc = { workspace = true } fastrand = { workspace = true } hang = { workspace = true } -if-addrs = { workspace = true, optional = true } # Drives each WebRTC connection over its UDP socket. kio = { workspace = true, features = ["runtime"] } -mdns-sd = { workspace = true, optional = true } # Refuses a CPU rind can't run on, and gives the WHIP/WHEP client rind's rustls provider. moq-crypto = { workspace = true, features = ["provider"] } moq-mux = { workspace = true, features = ["async"] } moq-net = { workspace = true } -# `RedactedUrl` keeps a dialed URL's query token and userinfo out of the logs, and with -# `p2p`, `Client::connect_with` and `Listener::accept_with` run MoQ over the data channel. +# `RedactedUrl` keeps a dialed URL's query token and userinfo out of the logs. moq-tokio = { workspace = true } # The vendored DTLS's record parser. nom = { workspace = true } once_cell = { workspace = true } -qmux = { workspace = true, optional = true } rand = { workspace = true } # The vendored DTLS's self-signed certificates. rcgen = { workspace = true } @@ -66,12 +58,8 @@ reqwest = { workspace = true, features = ["rustls-no-provider"] } # The vendored stack's crypto: DTLS, SRTP, and STUN MESSAGE-INTEGRITY. rind = { workspace = true } rind-rcgen = { workspace = true } -rustc-hash = { workspace = true } serde = { workspace = true } -slab = { workspace = true } spki = { workspace = true } -# The STUN Binding client the ICE agent runs for server-reflexive candidates. -stun-types = { workspace = true } subtle = { workspace = true } thiserror = { workspace = true } time = { workspace = true, features = ["formatting"] } @@ -83,8 +71,6 @@ uuid = { version = "1", features = ["v4"] } x509-cert = { workspace = true } [dev-dependencies] -# `poll!` checks what a data channel peer is still waiting on. -futures = { workspace = true } # The tests host their broadcasts on `origin::spawn`, and dial a session over TCP. moq-tokio = { workspace = true, features = ["net", "tcp"] } # The vendored stack's tests replay RTP captures. diff --git a/rs/moq-webrtc/src/ice/agent.rs b/rs/moq-webrtc/src/ice/agent.rs index 9ffa5612a40..c895e7e997c 100644 --- a/rs/moq-webrtc/src/ice/agent.rs +++ b/rs/moq-webrtc/src/ice/agent.rs @@ -7,10 +7,7 @@ use std::time::Duration; use kio::clock::Instant; use str0m::net::{Protocol, Receive}; -use str0m::{Candidate, IceConnectionState, Input, Output, Rtc}; -use stun_types::attribute::XorMappedAddress; -use stun_types::message::{BINDING, Message, MessageClass, MessageWriteVec, TransactionId}; -use stun_types::prelude::*; +use str0m::{Event, IceConnectionState, Input, Output, Rtc}; use tokio::net::UdpSocket; use super::{Inbound, Socket}; @@ -21,22 +18,8 @@ use super::{Inbound, Socket}; /// tried and exhausted (after ~21s at its defaults), but with no remote candidates /// it treats the session as still possible forever, since trickle ICE could add /// one. Set above str0m's own exhaustion so a slow but real peer is not clipped. -/// -/// It counts from when the peer could hold every local candidate: once gathering -/// ends, so a caller that sends its description only after the last candidate is -/// not clipped by an unreachable STUN server's retransmissions, and for an -/// [`Agent::awaiting_answer`], once the answer applies. const ESTABLISH_TIMEOUT: Duration = Duration::from_secs(30); -/// RFC 8489 section 6.2.1: the first retransmission timeout of a STUN request. -const STUN_RTO: Duration = Duration::from_millis(500); - -/// RFC 8489 section 6.2.1: how many times a STUN request is sent (`Rc`). -const STUN_SENDS: u32 = 7; - -/// RFC 8489 section 6.2.1: how long to wait after the last send, in RTOs (`Rm`). -const STUN_LAST_WAIT: u32 = 16; - /// Why an [`Agent`] stopped. #[derive(Clone, Debug, thiserror::Error)] pub enum Error { @@ -49,7 +32,7 @@ pub enum Error { #[error("ICE did not connect in time")] Timeout, - /// str0m failed (SDP, DTLS, SCTP, or ICE state). + /// str0m failed (SDP, DTLS, or ICE state). #[error("rtc error: {0}")] Rtc(String), } @@ -60,42 +43,8 @@ impl Error { } } -/// What [`Agent::next`] surfaced. -#[derive(Debug)] -#[expect( - clippy::large_enum_variant, - reason = "moved once per poll; boxing would allocate for every data channel message" -)] -pub enum Event { - /// An event from str0m. ICE disconnection is reported as [`Error::Closed`] instead. - Rtc(str0m::Event), - /// A server-reflexive candidate, already added locally, to signal to the peer. - #[cfg_attr( - not(feature = "p2p"), - allow(dead_code, reason = "only the p2p transport gathers server-reflexive candidates") - )] - Candidate(Candidate), - /// Every STUN server answered or gave up: no more local candidates follow. - Gathered, -} - -/// A STUN Binding request in flight to one server. -struct Query { - server: SocketAddr, - /// The host candidate the request leaves from, which a reply's mapping is the reflexive form of. - base: SocketAddr, - id: TransactionId, - request: Vec, - sends: u32, - rto: Duration, - /// When to retransmit, or give up after the last send. - deadline: Instant, -} - /// Where the connection is in its life. enum Phase { - /// An offer awaits its answer, which holds off the [`ESTABLISH_TIMEOUT`]. - Held, /// ICE has yet to connect; the [`ESTABLISH_TIMEOUT`] runs from `started`. Establishing { started: Instant, @@ -118,9 +67,6 @@ pub struct Agent { /// Never empty. locals: Vec, inbound: Inbound, - stun: Vec, - /// When every STUN query answered or gave up, once [`Event::Gathered`] went out. - gathered: Option, events: VecDeque, /// When str0m next wants a timeout, as of the last drain. timeout: Instant, @@ -145,8 +91,6 @@ impl Agent { socket_v6, locals, inbound, - stun: Vec::new(), - gathered: None, events: VecDeque::new(), timeout: now, outbox: VecDeque::new(), @@ -157,66 +101,19 @@ impl Agent { Ok(agent) } - /// Ask each STUN server for this socket's public mapping, offering what comes - /// back as a server-reflexive candidate. Servers of a family with no host - /// candidate are skipped. - #[cfg_attr( - not(feature = "p2p"), - allow(dead_code, reason = "only the p2p transport gathers server-reflexive candidates") - )] - pub fn with_stun(mut self, servers: &[SocketAddr]) -> Self { - let now = Instant::now(); - for &server in servers { - let server = canonical(server); - let Some(base) = self.locals.iter().find(|l| l.is_ipv4() == server.is_ipv4()).copied() else { - tracing::debug!(%server, "no host candidate of this family; skipping STUN server"); - continue; - }; - let request = Message::builder_request(BINDING, MessageWriteVec::new()); - let id = request.transaction_id(); - self.stun.push(Query { - server, - base, - id, - request: request.finish(), - sends: 0, - rto: STUN_RTO, - deadline: now, - }); - } - self - } - /// The connection being driven, read only. pub fn rtc(&self) -> &Rtc { &self.rtc } - /// Hold off the deadline for ICE to connect until the first [`Agent::rtc_mut`], - /// for an offer whose answer has yet to arrive: signaling time is the caller's. - #[cfg_attr(not(feature = "p2p"), allow(dead_code, reason = "only the p2p transport offers"))] - pub fn awaiting_answer(mut self) -> Self { - self.phase = Phase::Held; - self - } - /// Change the connection through a guard that drains what the change produced /// when dropped: transmits are sent, and events wait for [`Agent::next`]. pub fn rtc_mut(&mut self) -> RtcMut<'_> { - if let Phase::Held = self.phase { - self.phase = Phase::Establishing { - started: Instant::now(), - }; - } - self.change() - } - - /// [`Agent::rtc_mut`] for the agent's own changes, which never start the deadline. - fn change(&mut self) -> RtcMut<'_> { RtcMut(self) } - /// Drive the connection until it surfaces an [`Event`]. + /// Drive the connection until str0m surfaces an [`Event`]. ICE disconnection is + /// reported as [`Error::Closed`] instead. /// /// Cancel safe: the connection is always drained between calls, and a datagram /// the socket could not take yet is kept and sent first on the next call. @@ -228,11 +125,6 @@ impl Agent { if let Phase::Failed(err) = &self.phase { return Err(err.clone()); } - if self.gathered.is_none() && self.stun.is_empty() { - self.gathered = Some(Instant::now()); - return Ok(Event::Gathered); - } - while let Some((data, dst)) = self.outbox.front() { match self.socket.send_to(data, *dst).await { Ok(_) => {} @@ -252,9 +144,7 @@ impl Agent { self.fail(Error::Timeout); continue; } - - let deadline = self.stun.iter().map(|q| q.deadline).chain(establish); - let deadline = deadline.fold(self.timeout, Instant::min); + let deadline = establish.map_or(self.timeout, |at| at.min(self.timeout)); let now = Instant::now(); if deadline > now { @@ -272,21 +162,17 @@ impl Agent { } } - let now = Instant::now(); - let result = self.change().handle_input(Input::Timeout(now.into_std())); + let result = self.rtc_mut().handle_input(Input::Timeout(Instant::now().into_std())); if let Err(err) = result { self.fail(Error::rtc(err)); } - self.retransmit(now); } } - /// When [`ESTABLISH_TIMEOUT`] expires, or `None` while it is held, gathering, or over. + /// When [`ESTABLISH_TIMEOUT`] expires, or `None` once ICE connected or the connection ended. fn establish(&self) -> Option { - match (&self.phase, self.gathered) { - (Phase::Establishing { started }, Some(gathered)) => { - Some((*started).max(gathered).saturating_add(ESTABLISH_TIMEOUT)) - } + match &self.phase { + Phase::Establishing { started } => Some(started.saturating_add(ESTABLISH_TIMEOUT)), _ => None, } } @@ -322,7 +208,7 @@ impl Agent { self.phase = Phase::Connected; } } - self.events.push_back(Event::Rtc(event)); + self.events.push_back(event); } } } @@ -341,7 +227,7 @@ impl Agent { match self.socket.try_send_to(data, dst) { Ok(_) => {} // Changes can keep coming while the socket stays full, so the backlog is - // bounded like the inbound queue; ICE, SCTP, and RTP recover the loss. + // bounded like the inbound queue; ICE, DTLS, and RTP recover the loss. Err(err) if err.kind() == std::io::ErrorKind::WouldBlock && self.outbox.len() < crate::ice::INBOX => { self.outbox.push_back((data.to_vec(), dst)) } @@ -353,86 +239,20 @@ impl Agent { } fn receive(&mut self, data: &[u8], src: SocketAddr) { - if self.stun_reply(data, src) { - return; - } - let local = pick_local(&self.locals, src); - // Anything can arrive on a socket a server-reflexive candidate exposes, so a - // datagram that is not STUN, DTLS, or RTP is noise, not a failure. + // Anything can arrive on a public socket, so a datagram that is not STUN, + // DTLS, or RTP is noise, not a failure. let Ok(receive) = Receive::new(Protocol::Udp, src, local, data) else { tracing::debug!(%src, len = data.len(), "dropped unrecognized datagram"); return; }; let result = self - .change() + .rtc_mut() .handle_input(Input::Receive(Instant::now().into_std(), receive)); if let Err(err) = result { self.fail(Error::rtc(err)); } } - - /// Consume a reply to one of our STUN queries, returning false for anything else. - fn stun_reply(&mut self, data: &[u8], src: SocketAddr) -> bool { - if self.stun.is_empty() { - return false; - } - let Ok(reply) = Message::from_bytes(data) else { - return false; - }; - let id = reply.transaction_id(); - let Some(index) = self.stun.iter().position(|q| q.id == id && q.server == src) else { - return false; - }; - let query = self.stun.swap_remove(index); - - if !reply.has_method(BINDING) || !reply.has_class(MessageClass::Success) { - tracing::debug!(server = %query.server, "STUN server refused the binding request"); - return true; - } - let Ok(mapped) = reply.attribute::() else { - tracing::debug!(server = %query.server, "STUN reply carries no mapped address"); - return true; - }; - - let mapped = canonical(mapped.addr(id)); - match Candidate::server_reflexive(mapped, query.base, "udp") { - // None: redundant with a candidate the agent already has, as when there is no NAT. - Ok(candidate) => { - let added = self.change().add_local_candidate(candidate).cloned(); - if let Some(candidate) = added { - self.events.push_back(Event::Candidate(candidate)); - } - } - Err(err) => tracing::debug!(%err, %mapped, "unusable server-reflexive address"), - } - true - } - - /// Send each STUN request that is due, dropping those out of attempts. - fn retransmit(&mut self, now: Instant) { - let mut due = Vec::new(); - self.stun.retain_mut(|query| { - if query.deadline > now { - return true; - } - if query.sends == STUN_SENDS { - tracing::debug!(server = %query.server, "STUN server did not answer"); - return false; - } - query.sends += 1; - query.deadline = now.saturating_add(match query.sends { - STUN_SENDS => STUN_RTO * STUN_LAST_WAIT, - _ => query.rto, - }); - query.rto *= 2; - due.push((query.request.clone(), query.server)); - true - }); - for (request, server) in due { - self.send(&request, server); - } - } } /// Mutable access to an [`Agent`]'s connection, which drains it when dropped. @@ -519,36 +339,19 @@ mod tests { assert_eq!(agent.outbox.len(), crate::ice::INBOX); } - #[tokio::test] - async fn awaiting_answer_holds_the_deadline() { - let mut agent = unpolled().awaiting_answer(); - assert!(matches!(agent.phase, Phase::Held)); - // The agent's own changes, such as timeouts and STUN, leave it held. - drop(agent.change()); - assert!(matches!(agent.phase, Phase::Held)); - drop(agent.rtc_mut()); - assert!(matches!(agent.phase, Phase::Establishing { .. })); - } - - #[tokio::test] - async fn gathering_holds_the_deadline() { - let mut agent = unpolled().with_stun(&["127.0.0.1:3478".parse().unwrap()]); - // An unreachable STUN server retransmits for longer than the deadline, so the - // deadline waits for gathering to end. - assert_eq!(agent.establish(), None); - agent.stun.clear(); - assert!(matches!(agent.next().await, Ok(Event::Gathered))); - let gathered = agent.gathered.unwrap(); - assert_eq!(agent.establish(), Some(gathered.saturating_add(ESTABLISH_TIMEOUT))); - } - /// A peer that answers but never sends: DTLS gives up on its handshake before ICE /// connects, which reports as ICE never connecting rather than a DTLS failure. #[tokio::test(start_paused = true)] async fn a_handshake_giving_up_before_ice_connects_is_a_timeout() { let mut offerer = Rtc::builder().build(Instant::now().into_std()); let mut api = offerer.sdp_api(); - api.add_channel("test".into()); + api.add_media( + str0m::media::MediaKind::Audio, + str0m::media::Direction::SendOnly, + None, + None, + None, + ); let (offer, pending) = api.apply().unwrap(); let answer = Rtc::builder() .build(Instant::now().into_std()) @@ -560,12 +363,11 @@ mod tests { let socket = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap()); let local = socket.local_addr().unwrap(); let socket = Socket::new(socket.clone(), vec![local], crate::ice::reader(socket)).unwrap(); - // A STUN server that never answers holds the deadline past the handshake's - // retransmissions, so DTLS deterministically gives up first. - let stun = UdpSocket::bind("127.0.0.1:0").await.unwrap(); - let mut agent = Agent::new(offerer, socket) - .unwrap() - .with_stun(&[stun.local_addr().unwrap()]); + let mut agent = Agent::new(offerer, socket).unwrap(); + // Hold the deadline past the handshake's retransmissions, so DTLS + // deterministically gives up first. + let held = Instant::now().saturating_add(Duration::from_secs(3600)); + agent.phase = Phase::Establishing { started: held }; let err = loop { match agent.next().await { @@ -574,7 +376,7 @@ mod tests { } }; assert!(matches!(err, Error::Timeout), "{err:?}"); - assert_eq!(agent.establish(), None, "the deadline had yet to start"); + assert!(Instant::now() < held, "the deadline fired, not DTLS"); // The reason sticks: driving the agent again reports it again. let again = agent.next().await; assert!(matches!(again, Err(Error::Timeout)), "{again:?}"); diff --git a/rs/moq-webrtc/src/ice/mod.rs b/rs/moq-webrtc/src/ice/mod.rs index 3e20a0ec309..1c4d1cd3c0a 100644 --- a/rs/moq-webrtc/src/ice/mod.rs +++ b/rs/moq-webrtc/src/ice/mod.rs @@ -3,10 +3,7 @@ //! //! str0m is sans-IO, so [`Agent::next`] alternates between feeding it datagrams //! and timeouts and draining what it produces (transmits, events, the next -//! timeout), and runs a STUN Binding client on the same socket so the agent can -//! offer server-reflexive candidates. Shared by the WHIP/WHEP gateway and the -//! `p2p` data channel transport, which only differ in what they do with -//! the events. +//! timeout). //! //! str0m requires every mutation of an `Rtc` to be followed by draining its output //! to a timeout before the next one. The agent owns that cycle: [`Agent::rtc`] is @@ -21,5 +18,5 @@ mod agent; mod wire; -pub(crate) use agent::{Agent, Error, Event, canonical}; +pub(crate) use agent::{Agent, Error, canonical}; pub(crate) use wire::{INBOX, Inbound, Packet, Socket, reader}; diff --git a/rs/moq-webrtc/src/ice/wire.rs b/rs/moq-webrtc/src/ice/wire.rs index dbb80bd2d6d..b6827718426 100644 --- a/rs/moq-webrtc/src/ice/wire.rs +++ b/rs/moq-webrtc/src/ice/wire.rs @@ -10,7 +10,7 @@ use super::canonical; pub type Packet = (Vec, SocketAddr); /// Bound on a session's inbound datagram queue, sized like a socket buffer: past -/// it, datagrams are dropped rather than buffered, since ICE and SCTP tolerate loss +/// it, datagrams are dropped rather than buffered, since ICE, DTLS, and RTP tolerate loss /// and a stalled session must not grow memory without limit. pub const INBOX: usize = 256; diff --git a/rs/moq-webrtc/src/lib.rs b/rs/moq-webrtc/src/lib.rs index 0f500c86402..9099a876637 100644 --- a/rs/moq-webrtc/src/lib.rs +++ b/rs/moq-webrtc/src/lib.rs @@ -45,8 +45,6 @@ #![warn(missing_docs)] pub mod client; -#[cfg(feature = "p2p")] -pub mod p2p; mod rate; pub mod server; @@ -61,7 +59,7 @@ mod ice; mod ingest; mod sdp; mod session; -// str0m, dimpl, `is`, and sctp-proto, vendored and trimmed; see the module docs. +// str0m, dimpl, and `is`, vendored and trimmed; see the module docs. mod vendor; pub use client::Client; diff --git a/rs/moq-webrtc/src/p2p/channel.rs b/rs/moq-webrtc/src/p2p/channel.rs deleted file mode 100644 index 97fa6869b54..00000000000 --- a/rs/moq-webrtc/src/p2p/channel.rs +++ /dev/null @@ -1,229 +0,0 @@ -//! qmux message I/O over one reliable, ordered data channel. -//! -//! Each SCTP message carries one qmux-01 record without its size field, as a -//! WebSocket message does. The peer's driver task owns the channel; these halves -//! only hand messages to and from it. - -use std::sync::Arc; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::task::{Poll, ready}; - -use bytes::Bytes; -use tokio::sync::mpsc; - -/// The data channel, as the qmux transport a [`qmux::Session`] runs over. -pub(crate) struct Channel { - pub writer: Writer, - pub reader: Reader, -} - -impl qmux::transport::Transport for Channel { - fn poll_recv(&mut self, waiter: &kio::Waiter) -> Poll> { - self.reader.poll_recv(waiter) - } - - fn poll_ready(&mut self, waiter: &kio::Waiter) -> Poll> { - self.writer.poll_ready(waiter) - } - - fn send(&mut self, record: Bytes) -> Result<(), qmux::Error> { - self.writer.send(record) - } - - fn poll_flush(&mut self, waiter: &kio::Waiter) -> Poll> { - self.writer.poll_ready(waiter) - } - - fn poll_close(&mut self, waiter: &kio::Waiter) -> Poll> { - ready!(self.writer.poll_ready(waiter))?; - self.writer.close(); - Poll::Ready(Ok(())) - } -} - -/// A queue of outbound records, holding one at a time: the driver waits for SCTP to drain -/// before taking more, so a full send window holds back qmux's writer. -/// -/// Closing it from either end ends the session's writes: the [`Writer`] closes it to have the -/// driver close the channel, and the driver drops its [`Outbox`] once the channel is gone. -pub(crate) fn outbox(max: usize) -> (Outbox, Writer) { - let queue = kio::Queue::bounded(1); - let writer = Writer { - queue: queue.clone(), - pending: None, - max, - _driver: None, - }; - (Outbox(queue), writer) -} - -/// The driver's end of the outbound queue. -pub(crate) struct Outbox(kio::Queue); - -impl Outbox { - /// The session's next record, or `None` once its writer closed. - pub async fn next(&self) -> Option { - self.0.pop().await.ok() - } -} - -impl Drop for Outbox { - fn drop(&mut self) { - self.0.close(); - } -} - -/// Hands outbound records to the driver through its [`Outbox`]. -pub(crate) struct Writer { - queue: kio::Queue, - /// A record waiting for room in `queue`. - pending: Option, - /// The largest message the peer accepts. - max: usize, - /// Keeps the driver running while the session outlives the signaling handle. - pub _driver: Option>, -} - -impl Writer { - /// Wait until the pending record, if any, is in the queue. - pub fn poll_ready(&mut self, waiter: &kio::Waiter) -> Poll> { - if self.pending.is_some() { - let pending = &mut self.pending; - ready!( - self.queue - .poll_push_with(waiter, || pending.take().expect("checked above")) - ) - .map_err(|_| qmux::Error::Closed)?; - } - Poll::Ready(Ok(())) - } - - /// Queue a record, after [`Self::poll_ready`] found room. - pub fn send(&mut self, record: Bytes) -> Result<(), qmux::Error> { - if record.len() > self.max { - return Err(qmux::Error::FrameTooLarge); - } - self.pending = Some(record); - Ok(()) - } - - /// Queue a record and wait for the driver to take it. - #[cfg(test)] - pub async fn write(&mut self, record: Bytes) -> Result<(), qmux::Error> { - self.send(record)?; - kio::wait(|waiter| self.poll_ready(waiter)).await - } - - /// Close the channel once the driver takes what is queued. - pub fn close(&mut self) { - self.queue.close(); - } -} - -impl Drop for Writer { - fn drop(&mut self) { - self.close(); - } -} - -/// A queue of inbound records bounded by bytes the session has yet to read. -/// -/// The driver never stops reading the socket to wait for the session: that would -/// also stall ICE consent checks and the SACKs that free our own send buffer. -/// qmux's flow control bounds what an honest peer can have in flight, so the -/// queue only overflows when the peer ignores it, and then the channel closes. -pub(crate) fn queue(budget: u64) -> (Inbox, Reader) { - let (tx, rx) = mpsc::unbounded_channel(); - let unread = Arc::new(AtomicU64::new(0)); - let inbox = Inbox { - tx, - unread: unread.clone(), - budget, - }; - (inbox, Reader { rx, unread }) -} - -/// The driver's end of the inbound queue. -pub(crate) struct Inbox { - tx: mpsc::UnboundedSender>, - /// Bytes queued but not yet read, shared with the [`Reader`]. - unread: Arc, - budget: u64, -} - -impl Inbox { - /// Queue a record for the session, returning false once its reads have ended: - /// on an error, or with a flow control error when the record would leave more - /// than the budget unread. - pub fn push(&self, record: Result) -> bool { - // A closed reader drops the record. - let data = match record { - Ok(data) => data, - Err(err) => { - let _ = self.tx.send(Err(err)); - return false; - } - }; - // qmux records are never empty, so the byte budget also bounds their count. - if data.is_empty() { - let _ = self.tx.send(Err(qmux::Error::ProtocolViolation)); - return false; - } - let len = data.len() as u64; - if self.unread.fetch_add(len, Ordering::Relaxed) + len > self.budget { - let _ = self.tx.send(Err(qmux::Error::FlowControlError)); - return false; - } - let _ = self.tx.send(Ok(data)); - true - } -} - -/// Receives the records the driver read off the channel. -pub(crate) struct Reader { - rx: mpsc::UnboundedReceiver>, - unread: Arc, -} - -impl Reader { - /// The next record the driver read off the channel. - #[cfg_attr(test, kio::wrapper)] - pub fn poll_recv(&mut self, waiter: &kio::Waiter) -> Poll> { - let record = ready!(self.rx.poll_recv(&mut waiter.context())).unwrap_or(Err(qmux::Error::Closed))?; - self.unread.fetch_sub(record.len() as u64, Ordering::Relaxed); - Poll::Ready(Ok(record)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[tokio::test] - async fn queue_closes_past_its_budget() { - let (inbox, mut reader) = queue(10); - assert!(inbox.push(Ok(Bytes::from_static(&[0; 6])))); - assert!(inbox.push(Ok(Bytes::from_static(&[1; 4])))); - // Reading frees budget for the next record. - assert_eq!(reader.recv().await.unwrap().len(), 6); - assert!(inbox.push(Ok(Bytes::from_static(&[2; 6])))); - assert!(!inbox.push(Ok(Bytes::from_static(&[3; 1])))); - - // Records queued before the overflow still arrive, then the error. - assert_eq!(reader.recv().await.unwrap()[0], 1); - assert_eq!(reader.recv().await.unwrap()[0], 2); - assert!(matches!(reader.recv().await, Err(qmux::Error::FlowControlError))); - } - - #[tokio::test] - async fn queue_ends_on_empty_or_error_records() { - // Neither costs any bytes, so the budget alone would never stop a flood of them. - let (inbox, mut reader) = queue(10); - assert!(!inbox.push(Ok(Bytes::new()))); - assert!(matches!(reader.recv().await, Err(qmux::Error::ProtocolViolation))); - - let (inbox, mut reader) = queue(10); - assert!(!inbox.push(Err(qmux::Error::FrameTooLarge))); - assert!(matches!(reader.recv().await, Err(qmux::Error::FrameTooLarge))); - } -} diff --git a/rs/moq-webrtc/src/p2p/mod.rs b/rs/moq-webrtc/src/p2p/mod.rs deleted file mode 100644 index 44eecd61df6..00000000000 --- a/rs/moq-webrtc/src/p2p/mod.rs +++ /dev/null @@ -1,1030 +0,0 @@ -//! MoQ over one reliable, ordered WebRTC data channel, for sessions with browser peers. -//! -//! An [`Offerer`] or [`Answerer`] is one side of a str0m peer connection with a -//! full ICE agent: a dual-stack UDP socket, a host candidate per non-loopback -//! interface address, a server-reflexive candidate from each configured STUN -//! server, and remote `.local` candidates resolved over mDNS. Signaling is the -//! caller's: send the [`Offer`] or [`Answer`] and the local [`Candidate`]s to the -//! remote peer, and feed its replies back. -//! -//! The [`Offerer`] opens the data channel, labelled `moq` and carrying the agreed -//! MoQ ALPN as its protocol, and runs a [`moq_tokio::Client`] over it with -//! [`Offerer::connect`]. The [`Answerer`] adopts that channel and hands it to a -//! [`moq_tokio::Listener`] with [`Answerer::accept`]. This matches `@moq/p2p`, -//! where `Transport.connect` creates the channel and `Transport.accept` adopts it. -//! moq-net's session policy runs over the channel as over any other transport. -//! -//! Every entry point must run inside a tokio runtime, like the gateway's. -//! -//! The channel carries qmux-01, one record per SCTP message, capped at 16 KiB and -//! the peer's SCTP message limit. Ordered delivery means one lost chunk stalls -//! every stream until SCTP retransmits it. - -use crate::vendor::str0m; -use std::net::{IpAddr, Ipv4Addr, SocketAddr}; -use std::str::FromStr; -use std::sync::Arc; -use std::time::Duration; - -use bytes::Bytes; -use str0m::Rtc; -use str0m::change::{SdpAnswer, SdpOffer, SdpPendingOffer}; -use str0m::channel::{ChannelConfig, ChannelId, Reliability}; -use tokio::net::UdpSocket; -use tokio::sync::{mpsc, oneshot}; - -mod channel; -mod resolver; - -use resolver::Resolver; - -/// The data channel label, as `@moq/p2p` creates it. -const LABEL: &str = "moq"; - -/// The largest qmux record, as `@moq/p2p` sends: SCTP flow control is per -/// message, so a smaller record keeps one stream from holding the association. -const RECORD_SIZE: u64 = 16 * 1024; - -/// qmux-01 does not allow a peer to advertise a smaller record limit. -const MIN_RECORD_SIZE: u64 = 16_382; - -/// SCTP's message limit when a description omits `a=max-message-size` (RFC 8841 section 6.1). -const DEFAULT_MAX_MESSAGE_SIZE: u64 = 64 * 1024; - -/// Bytes the channel may hold unsent before qmux's writer waits, as `@moq/p2p` allows. -const SEND_WINDOW: usize = RECORD_SIZE as usize * 4; - -/// Unread bytes the channel tolerates past qmux's advertised `receive_window`, for the -/// frame headers and control frames that flow control does not count. A peer that -/// honors flow control with reasonably full records stays under it; one that -/// ignores it has the channel closed instead of growing memory without limit. -const READ_SLACK: u64 = 16 * RECORD_SIZE; - -/// The connection-level receive window a data channel session grants, the `[quic]` default -/// every qmux session takes. -const RECEIVE_WINDOW: u64 = moq_tokio::quic::DEFAULT_RECEIVE_WINDOW; - -/// The default STUN port (RFC 8489 section 18.10). -const STUN_PORT: u16 = 3478; - -/// Errors from a WebRTC peer connection or its data channel. -#[derive(Debug, thiserror::Error)] -#[non_exhaustive] -pub enum Error { - /// Binding the UDP socket or resolving a STUN server failed. - #[error(transparent)] - Io(#[from] std::io::Error), - - /// The peer disconnected, or the connection was closed. - #[error("peer connection closed")] - Closed, - - /// The connection and its data channel did not come up within [`Config::timeout`], - /// or ICE gave up first. - #[error("the peer connection did not come up in time")] - Timeout, - - /// The WebRTC stack failed (DTLS, SCTP, or ICE state). - #[error("rtc error: {0}")] - Rtc(String), - - /// This CPU lacks a feature rind, the stack's crypto, requires. - #[error(transparent)] - UnsupportedCpu(#[from] moq_crypto::cpu::UnsupportedCpu), - - /// A session description failed to parse or apply. - #[error("invalid session description: {0}")] - Sdp(String), - - /// An ICE candidate failed to parse. - #[error("invalid ICE candidate: {0}")] - Candidate(String), - - /// An ICE server URL is malformed or not a `stun:` URL. - #[error("unsupported ICE server: {0}")] - Server(String), - - /// No interface has an address to offer as a host candidate. - #[error("no network interface address to offer as a host candidate")] - NoHost, - - /// The data channel was already taken by a session. - #[error("the data channel is already in use")] - Taken, - - /// The protocol is not a MoQ ALPN this endpoint speaks, or the channel's is not the one signaling agreed. - #[error("unsupported MoQ protocol: {0:?}")] - Protocol(String), - - /// The peer opened an unordered or partially reliable channel, which qmux cannot run over. - #[error("the data channel must be reliable and ordered")] - Unreliable, - - /// The peer's SCTP message limit is below qmux's minimum record size. - #[error("SCTP message limit {0} is smaller than qmux's minimum record size")] - MessageSize(u64), - - /// The qmux handshake over the channel failed. - #[error("qmux handshake failed: {0}")] - Qmux(String), - - /// The MoQ session over the channel failed. - #[error(transparent)] - Session(#[from] moq_tokio::Error), -} - -impl From for Error { - fn from(err: qmux::Error) -> Self { - Self::Qmux(err.to_string()) - } -} - -impl Error { - /// Adopt the agent's error. Not a `From` impl, which would name the private agent in this API. - fn ice(err: crate::ice::Error) -> Self { - match err { - crate::ice::Error::Closed => Self::Closed, - crate::ice::Error::Timeout => Self::Timeout, - crate::ice::Error::Rtc(err) => Self::Rtc(err), - } - } -} - -/// The longest [`Config::timeout`] waits by default, matching the ICE agent's own backstop. -const TIMEOUT: Duration = Duration::from_secs(30); - -/// Run `establish` within `timeout`, where zero means no bound. -async fn bounded(timeout: Duration, establish: impl Future>) -> Result { - match timeout.is_zero() { - true => establish.await, - false => kio::clock::timeout(timeout, establish) - .await - .map_err(|_| Error::Timeout)?, - } -} - -/// How an [`Offerer`] or [`Answerer`] gathers its local candidates and bounds its connection. -#[derive(Clone, Debug)] -#[non_exhaustive] -pub struct Config { - /// STUN servers asked for this host's public address. Empty means LAN only: - /// host candidates and nothing else. - pub stun: Vec, - /// How long [`Offerer::connect`] and [`Answerer::accept`] wait for ICE, DTLS, and the - /// data channel to come up, and qmux to start over it. 30 seconds by default; zero - /// disables the bound. - pub timeout: Duration, -} - -impl Default for Config { - fn default() -> Self { - Self { - stun: Vec::new(), - timeout: TIMEOUT, - } - } -} - -/// A STUN server, written the way an `RTCIceServer` URL names one: `stun:host[:port]`. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Stun { - host: String, - port: u16, -} - -impl FromStr for Stun { - type Err = Error; - - fn from_str(url: &str) -> Result { - let invalid = || Error::Server(url.to_string()); - let (scheme, rest) = url.split_once(':').ok_or_else(invalid)?; - if !scheme.eq_ignore_ascii_case("stun") { - // TURN is out of scope: the relay already carries what a TURN server would. - return Err(invalid()); - } - - let (host, port) = match rest.strip_prefix('[') { - Some(rest) => { - let (host, port) = rest.split_once(']').ok_or_else(invalid)?; - let port = match port { - "" => None, - port => Some(port.strip_prefix(':').ok_or_else(invalid)?), - }; - ( - host.parse::().map_err(|_| invalid())?.to_string(), - port, - ) - } - None => { - let (host, port) = match rest.split_once(':') { - Some((host, port)) => (host, Some(port)), - None => (rest, None), - }; - // A DNS name or IPv4 address, so a fragment or stray character fails here - // instead of as a lookup that only warns. - if host.is_empty() - || !host - .chars() - .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '.' | '_')) - { - return Err(invalid()); - } - (host.to_string(), port) - } - }; - let port = match port { - Some(port) => port.parse().map_err(|_| invalid())?, - None => STUN_PORT, - }; - Ok(Self { host, port }) - } -} - -impl std::fmt::Display for Stun { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self.host.contains(':') { - true => write!(f, "stun:[{}]:{}", self.host, self.port), - false => write!(f, "stun:{}:{}", self.host, self.port), - } - } -} - -/// An SDP offer, as `RTCSessionDescription.sdp` carries it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Offer(String); - -/// An SDP answer, as `RTCSessionDescription.sdp` carries it. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Answer(String); - -/// An ICE candidate, as `RTCIceCandidate.candidate` carries it: `candidate:...`. -/// -/// The connection has one media section, so a browser takes it with `sdpMLineIndex: 0`. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct Candidate(String); - -macro_rules! text { - ($ty:ident) => { - impl $ty { - /// Wrap the text a browser produced. - pub fn new(text: impl Into) -> Self { - Self(text.into()) - } - - /// The text to hand a browser. - pub fn as_str(&self) -> &str { - &self.0 - } - } - - impl std::fmt::Display for $ty { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str(&self.0) - } - } - }; -} - -text!(Offer); -text!(Answer); -text!(Candidate); - -/// The offering side of a WebRTC peer connection, which opens the MoQ data channel -/// and runs the MoQ client over it with [`Offerer::connect`]. -/// -/// A background task drives the connection from creation, so ICE checks and STUN -/// replies are answered while signaling is still in progress. It runs until both -/// this handle and any session over its data channel are gone. Dropping the handle -/// stops signaling, including any remote `.local` candidates still resolving, but -/// leaves a running session alone. -pub struct Offerer { - peer: Peer, - timeout: Duration, -} - -impl Offerer { - /// Start a peer connection with a data channel for MoQ `protocol`, the ALPN the - /// peers agreed through signaling, returning the offer to send. - pub async fn new(config: &Config, protocol: &str) -> Result<(Self, Offer), Error> { - Self::with_hosts(config, protocol, hosts()?).await - } - - async fn with_hosts(config: &Config, protocol: &str, hosts: Vec) -> Result<(Self, Offer), Error> { - let protocol = negotiated(protocol)?; - let socket = bind(&hosts)?; - let mut rtc = rtc(socket.locals())?; - - let mut api = rtc.sdp_api(); - let id = api.add_channel_with_config(ChannelConfig { - label: LABEL.to_string(), - ordered: true, - reliability: Reliability::Reliable, - negotiated: None, - protocol, - }); - let (offer, pending) = api.apply().expect("adding a channel is an SDP change"); - - let role = Role::Offerer { - channel: id, - pending: Some(pending), - }; - let peer = Peer::spawn(config, rtc, socket, role, None).await?; - let offerer = Self { - peer, - timeout: config.timeout, - }; - Ok((offerer, Offer(offer.to_sdp_string()))) - } - - /// Apply the remote peer's answer to this offer. - pub async fn accept(&self, answer: &Answer) -> Result<(), Error> { - let (sdp, mdns) = split_mdns(answer.as_str())?; - let max_message = max_message_size(answer.as_str())?; - let parsed = SdpAnswer::from_sdp_string(&sdp).map_err(|err| Error::Sdp(err.to_string()))?; - - let (tx, rx) = oneshot::channel(); - self.peer.send(Command::Answer(parsed, max_message, tx)).await?; - rx.await.map_err(|_| Error::Closed)??; - self.peer.resolver.add(mdns).await - } - - /// The next local candidate to send the remote peer, or `None` once gathering is done. - /// - /// Host candidates ride in the offer; these are the server-reflexive ones that - /// STUN finds afterwards. - pub async fn candidate(&mut self) -> Option { - self.peer.candidates.recv().await - } - - /// Add a candidate the remote peer sent. - /// - /// This waits while the connection is still taking earlier candidates. A `.local` - /// address is resolved over mDNS first, one name at a time, so this also waits - /// while earlier names are still resolving. One that does not resolve is - /// dropped. An empty candidate, which a browser sends to mark the end of its - /// candidates, is ignored. - pub async fn add_candidate(&self, candidate: &Candidate) -> Result<(), Error> { - self.peer.add_candidate(candidate).await - } - - /// Run `client`'s MoQ session over the data channel once it opens. - /// - /// [`Config::timeout`] bounds ICE and the channel coming up, then the client's connect - /// timeout bounds the MoQ handshake. A peer link cannot be redialed, so there is no - /// reconnect: the session ends with the peer connection. Only one session may take - /// the channel. - pub async fn connect(&self, client: &moq_tokio::Client) -> Result { - let establish = async { - let opened = self.peer.channel().await?; - let (session, driver) = qmux::Session::connect(opened.channel, opened.config).await?; - tokio::spawn(driver); - Ok::<_, Error>(session) - }; - let session = bounded(self.timeout, establish).await?; - let session = client.connect_with(session).await?; - tracing::info!(version = %session.version(), transport = %moq_tokio::Transport::WebRtc, "connected"); - Ok(session) - } - - /// Wait for the data channel to open, and take it. - #[cfg(test)] - async fn channel(&self) -> Result { - self.peer.channel().await - } -} - -/// The answering side of a WebRTC peer connection, which adopts the remote peer's -/// MoQ data channel and serves it with [`Answerer::accept`]. -/// -/// Like [`Offerer`], a background task drives the connection until both this -/// handle and any session over its data channel are gone. -pub struct Answerer { - peer: Peer, - /// The MoQ ALPN the remote peer's channel must carry. - protocol: String, - timeout: Duration, -} - -impl Answerer { - /// Start a peer connection for the remote peer's offer and MoQ `protocol`, the - /// ALPN the peers agreed through signaling, returning the answer to send. - pub async fn new(config: &Config, offer: &Offer, protocol: &str) -> Result<(Self, Answer), Error> { - Self::with_hosts(config, offer, protocol, hosts()?).await - } - - async fn with_hosts( - config: &Config, - offer: &Offer, - protocol: &str, - hosts: Vec, - ) -> Result<(Self, Answer), Error> { - let protocol = negotiated(protocol)?; - let (sdp, mdns) = split_mdns(offer.as_str())?; - let max_message = max_message_size(offer.as_str())?; - let parsed = SdpOffer::from_sdp_string(&sdp).map_err(|err| Error::Sdp(err.to_string()))?; - - let socket = bind(&hosts)?; - let mut rtc = rtc(socket.locals())?; - let answer = rtc - .sdp_api() - .accept_offer(parsed) - .map_err(|err| Error::Sdp(err.to_string()))?; - - let peer = Peer::spawn(config, rtc, socket, Role::Answerer, Some(max_message)).await?; - peer.resolver.add(mdns).await?; - let answerer = Self { - peer, - protocol, - timeout: config.timeout, - }; - Ok((answerer, Answer(answer.to_sdp_string()))) - } - - /// The next local candidate to send the remote peer, or `None` once gathering is done. - /// - /// Host candidates ride in the answer; these are the server-reflexive ones that - /// STUN finds afterwards. - pub async fn candidate(&mut self) -> Option { - self.peer.candidates.recv().await - } - - /// Add a candidate the remote peer sent. - /// - /// This waits while the connection is still taking earlier candidates. A `.local` - /// address is resolved over mDNS first, one name at a time, so this also waits - /// while earlier names are still resolving. One that does not resolve is - /// dropped. An empty candidate, which a browser sends to mark the end of its - /// candidates, is ignored. - pub async fn add_candidate(&self, candidate: &Candidate) -> Result<(), Error> { - self.peer.add_candidate(candidate).await - } - - /// Read the MoQ SETUP from the data channel the remote peer opens, leaving admission - /// to the returned [`moq_tokio::server::Request`]. - /// - /// [`Config::timeout`] bounds ICE and the channel coming up, then `listener`'s - /// handshake timeout bounds the MoQ handshake. A drain of `listener` waits for the - /// connection meanwhile. The channel must carry the protocol signaling agreed. Only - /// one session may take the channel. - pub async fn accept(&self, listener: &moq_tokio::Listener) -> Result { - // Held until `accept_with` takes its own, so a drain that starts meanwhile waits. - let _establishing = listener.admission().enter().ok_or(moq_tokio::Error::Stopped)?; - let establish = async { - let opened = self.peer.channel().await?; - if opened.protocol != self.protocol { - return Err(Error::Protocol(opened.protocol)); - } - let (session, driver) = qmux::Session::accept(opened.channel, opened.config).await?; - tokio::spawn(driver); - Ok((session, opened.protocol)) - }; - let (session, protocol) = bounded(self.timeout, establish).await?; - let mut link = moq_tokio::server::Link::default(); - link.alpn = Some(protocol); - Ok(listener - .accept_with(moq_tokio::Transport::WebRtc, session, link) - .await?) - } - - /// Wait for the remote peer's data channel to open, and take it. - #[cfg(test)] - async fn channel(&self) -> Result { - self.peer.channel().await - } -} - -/// Check a MoQ ALPN agreed through signaling, as `@moq/p2p` does. -fn negotiated(protocol: &str) -> Result { - match protocol.is_empty() || protocol.contains(char::is_whitespace) { - true => Err(Error::Protocol(protocol.to_string())), - false => Ok(protocol.to_string()), - } -} - -/// The signaling handle both roles share: commands to the driver task, the -/// candidates it gathers, and the resolver for the remote peer's `.local` ones. -/// -/// The driver takes one command at a time, so a peer that trickles candidates -/// faster than the connection applies them holds up its own signaling instead -/// of queueing them. -struct Peer { - commands: mpsc::Sender, - candidates: mpsc::UnboundedReceiver, - resolver: Resolver, -} - -impl Peer { - async fn spawn( - config: &Config, - rtc: Rtc, - socket: crate::ice::Socket, - role: Role, - max_message: Option, - ) -> Result { - let stun = resolve_stun(&config.stun).await; - let mut agent = crate::ice::Agent::new(rtc, socket)?.with_stun(&stun); - if let Role::Offerer { .. } = role { - // The answer applies through `rtc_mut`, which starts the deadline. - agent = agent.awaiting_answer(); - } - - let (commands, rx) = mpsc::channel(1); - let (candidates_tx, candidates) = mpsc::unbounded_channel(); - let driver = Driver { - agent, - commands: rx, - candidates: Some(candidates_tx), - role, - max_message, - channel: None, - handout: Handout::Unasked, - }; - use tracing::Instrument; - tokio::spawn(moq_tokio::panic::isolate(driver.run()).instrument(tracing::Span::current())); - - let resolver = Resolver::spawn(commands.clone(), resolver::Mdns); - Ok(Self { - commands, - candidates, - resolver, - }) - } - - async fn add_candidate(&self, candidate: &Candidate) -> Result<(), Error> { - let line = candidate.as_str().trim(); - let line = line.strip_prefix("a=").unwrap_or(line); - if line.is_empty() { - return Ok(()); - } - if mdns_host(line)?.is_some() { - return self.resolver.add(vec![line.to_string()]).await; - } - let candidate = str0m::Candidate::from_sdp_string(line).map_err(|err| Error::Candidate(err.to_string()))?; - self.send(Command::Candidate(candidate)).await - } - - async fn channel(&self) -> Result { - let (tx, rx) = oneshot::channel(); - self.send(Command::Channel(tx)).await?; - let mut opened = rx.await.map_err(|_| Error::Closed)??; - // The session keeps the driver alive once this handle is gone. - opened.channel.writer._driver = Some(self.commands.clone()); - Ok(opened) - } - - async fn send(&self, command: Command) -> Result<(), Error> { - self.commands.send(command).await.map_err(|_| Error::Closed) - } -} - -/// A data channel that opened, ready to carry qmux. -struct Opened { - pub channel: channel::Channel, - /// The MoQ ALPN the channel carries. - pub protocol: String, - /// The qmux session settings for this channel. - pub config: qmux::Config, -} - -/// The qmux session settings for a channel carrying `protocol`, advertising -/// `max_record_size`: 16 KiB, capped by the peer's SCTP message limit. -fn session_config(protocol: &str, max_record_size: u64) -> qmux::Config { - // The `[quic]` limits every qmux session takes: moq-lite holds a stream open per - // subscription, past qmux's default stream count. - let mut config = qmux::Config::default(); - config.limits = moq_tokio::quic::Resolved::default().limits(); - config.version = qmux::Version::QMux01; - config.protocol = qmux::Protocol::Negotiated(protocol.to_string()); - config.max_record_size = max_record_size; - // Set rather than left to qmux's default, since the read queue is sized from it. - config.limits.receive_window = std::num::NonZeroU64::new(RECEIVE_WINDOW); - // The channel's read queue is sized by it, so it never widens. - config.fixed_receive_window = true; - // The binding has no datagrams. - config.max_datagram_frame_size = None; - config -} - -enum Command { - Answer(SdpAnswer, u64, oneshot::Sender>), - Candidate(str0m::Candidate), - Channel(oneshot::Sender>), -} - -enum Role { - Offerer { - channel: ChannelId, - /// Until the answer is applied. - pending: Option, - }, - Answerer, -} - -/// The open data channel, from the driver's side. -struct Open { - id: ChannelId, - protocol: String, - reads: channel::Inbox, - /// `None` once the session's writer closed. - writes: Option, - config: qmux::Config, - /// The session's halves, until a session takes them. - halves: Option, -} - -/// Owns the connection and runs it on its own task. -struct Driver { - agent: crate::ice::Agent, - commands: mpsc::Receiver, - /// Dropped once gathering finishes, ending [`Offerer::candidate`] and [`Answerer::candidate`]. - candidates: Option>, - role: Role, - /// The remote peer's SCTP message limit, once its description is applied. - max_message: Option, - channel: Option>, - handout: Handout, -} - -/// Which session the channel goes to: only one may carry it. -enum Handout { - /// No session asked for the channel yet. - Unasked, - /// A session waits for the channel to open or fail to. - Waiting(oneshot::Sender>), - /// A session took the channel, or heard why it never opened. - Taken, -} - -impl Driver { - async fn run(mut self) { - let err = loop { - let writable = self.writable(); - let writes = match &mut self.channel { - Some(Ok(Open { - writes: Some(writes), .. - })) => Some(writes), - _ => None, - }; - - tokio::select! { - event = self.agent.next() => match event { - Ok(event) => if let Err(err) = self.event(event) { - break err; - }, - Err(err) => break Error::ice(err), - }, - command = self.commands.recv() => match command { - Some(command) => self.command(command), - // Neither the signaling handle nor a session is left to use the connection. - None => return, - }, - data = next_write(writes), if writable => { - if let Err(err) = self.write(data) { - break err; - } - } - } - }; - - match &err { - Error::Closed => tracing::debug!("peer connection closed"), - err => tracing::debug!(%err, "peer connection failed"), - } - if let Handout::Waiting(waiter) = self.handout { - let _ = waiter.send(Err(err)); - } - } - - /// Whether the channel can take another record without passing [`SEND_WINDOW`]. - fn writable(&mut self) -> bool { - let Some(Ok(Open { - id, writes: Some(_), .. - })) = &self.channel - else { - return false; - }; - let id = *id; - self.agent - .rtc_mut() - .channel(id) - .is_some_and(|mut channel| channel.buffered_amount() < SEND_WINDOW) - } - - /// Hand a record from the session to SCTP, or close the channel when the session's writer closed. - fn write(&mut self, data: Option) -> Result<(), Error> { - let Some(Ok(open)) = &mut self.channel else { - return Ok(()); - }; - let id = open.id; - let Some(data) = data else { - open.writes = None; - self.agent.rtc_mut().direct_api().close_data_channel(id); - return Ok(()); - }; - let written = { - let mut rtc = self.agent.rtc_mut(); - let mut channel = rtc.channel(id).ok_or(Error::Closed)?; - channel.write(true, &data).map_err(|err| Error::Rtc(err.to_string()))? - }; - // The send window keeps the buffer well below str0m's, so a refusal is a bug, not backpressure. - match written { - true => Ok(()), - false => Err(Error::Rtc("SCTP refused a record within the send window".into())), - } - } - - fn command(&mut self, command: Command) { - match command { - Command::Answer(answer, max_message, reply) => { - // Only an `Offerer` sends an answer, so the answering role never has one pending. - let pending = match &mut self.role { - Role::Offerer { pending, .. } => pending.take(), - Role::Answerer => None, - }; - let result = match pending { - Some(pending) => { - let accepted = self.agent.rtc_mut().sdp_api().accept_answer(pending, answer); - accepted - .map(|()| self.max_message = Some(max_message)) - .map_err(|err| Error::Sdp(err.to_string())) - } - None => Err(Error::Sdp("the answer was already applied".into())), - }; - let _ = reply.send(result); - } - Command::Candidate(candidate) => self.agent.rtc_mut().add_remote_candidate(candidate), - Command::Channel(reply) => { - if !matches!(self.handout, Handout::Unasked) { - let _ = reply.send(Err(Error::Taken)); - return; - } - self.handout = Handout::Waiting(reply); - self.deliver(); - } - } - } - - fn event(&mut self, event: crate::ice::Event) -> Result<(), Error> { - let event = match event { - crate::ice::Event::Candidate(candidate) => { - if let Some(candidates) = &self.candidates { - let _ = candidates.send(Candidate(candidate.to_sdp_string())); - } - return Ok(()); - } - crate::ice::Event::Gathered => { - self.candidates = None; - return Ok(()); - } - crate::ice::Event::Rtc(event) => event, - }; - - match event { - str0m::Event::ChannelOpen(id, _) => self.open(id), - str0m::Event::ChannelData(data) => { - let Some(Ok(open)) = &self.channel else { - return Ok(()); - }; - if data.id != open.id { - return Ok(()); - } - let record = if !data.binary { - Err(qmux::Error::ProtocolViolation) - } else if data.data.len() as u64 > open.config.max_record_size { - Err(qmux::Error::FrameTooLarge) - } else { - Ok(Bytes::from(data.data)) - }; - if !open.reads.push(record) { - tracing::debug!("closing the data channel: the peer broke qmux framing or flow control"); - let id = open.id; - self.agent.rtc_mut().direct_api().close_data_channel(id); - self.channel = Some(Err(Error::Closed)); - } - } - str0m::Event::ChannelClose(id) => { - if let Some(Ok(open)) = &self.channel - && open.id == id - { - // The session's reader sees the end of its records. - self.channel = Some(Err(Error::Closed)); - } - } - _ => {} - } - Ok(()) - } - - /// Take a channel that opened as the session's, if it is the one this role expects. - fn open(&mut self, id: ChannelId) { - let expected = match &self.role { - Role::Offerer { channel, .. } => *channel == id, - // The remote peer may open other channels first; only the `moq` one is the session's. - Role::Answerer => self - .agent - .rtc_mut() - .channel(id) - .and_then(|channel| channel.config().map(|config| config.label == LABEL)) - .unwrap_or(false), - }; - if !expected || self.channel.is_some() { - tracing::debug!(?id, "closing an unexpected data channel"); - self.agent.rtc_mut().direct_api().close_data_channel(id); - return; - } - - let opened = self.adopt(id); - if opened.is_err() { - self.agent.rtc_mut().direct_api().close_data_channel(id); - } - self.channel = Some(opened); - self.deliver(); - } - - fn adopt(&mut self, id: ChannelId) -> Result { - let max_message = self.max_message.unwrap_or(DEFAULT_MAX_MESSAGE_SIZE); - let max_record_size = RECORD_SIZE.min(max_message); - if max_record_size < MIN_RECORD_SIZE { - return Err(Error::MessageSize(max_message)); - } - - let protocol = { - let mut rtc = self.agent.rtc_mut(); - let mut channel = rtc.channel(id).ok_or(Error::Closed)?; - let config = channel.config().ok_or(Error::Unreliable)?; - if !config.ordered || config.reliability != Reliability::Reliable { - return Err(Error::Unreliable); - } - let protocol = config.protocol.clone(); - channel.set_buffered_amount_low_threshold(SEND_WINDOW / 2); - protocol - }; - - let config = session_config(&protocol, max_record_size); - let (reads, reader) = channel::queue(RECEIVE_WINDOW + READ_SLACK); - let (writes, writer) = channel::outbox(usize::try_from(max_message).unwrap_or(usize::MAX)); - Ok(Open { - id, - protocol, - reads, - writes: Some(writes), - config, - halves: Some(channel::Channel { writer, reader }), - }) - } - - /// Answer a waiting session once the channel opened or failed to. - fn deliver(&mut self) { - let Some(channel) = &mut self.channel else { - return; - }; - let handout = std::mem::replace(&mut self.handout, Handout::Taken); - let Handout::Waiting(waiter) = handout else { - self.handout = handout; - return; - }; - let result = match channel { - Ok(open) => Ok(Opened { - channel: open.halves.take().expect("only the first session takes the halves"), - protocol: open.protocol.clone(), - config: open.config.clone(), - }), - Err(err) => Err(match err { - Error::Unreliable => Error::Unreliable, - Error::MessageSize(size) => Error::MessageSize(*size), - _ => Error::Closed, - }), - }; - let _ = waiter.send(result); - } -} - -/// The session's next record, or `None` when its writer closed. Pends without a channel. -async fn next_write(writes: Option<&mut channel::Outbox>) -> Option { - match writes { - Some(writes) => writes.next().await, - None => std::future::pending().await, - } -} - -/// A str0m connection with this socket's host candidates. -fn rtc(locals: &[SocketAddr]) -> Result { - let mut rtc = crate::session::rtc_config()?.build(kio::clock::now().into_std()); - for &addr in locals { - let candidate = str0m::Candidate::host(addr, "udp").map_err(|err| Error::Candidate(err.to_string()))?; - rtc.add_local_candidate(candidate); - } - Ok(rtc) -} - -/// Every address worth offering as a host candidate: not loopback, and not -/// link-local, which IPv6 cannot use without a scope and str0m refuses for IPv4. -fn hosts() -> Result, Error> { - let mut hosts = Vec::new(); - for interface in if_addrs::get_if_addrs()? { - let ip = interface.ip(); - if interface.is_loopback() || interface.is_link_local() || ip.is_multicast() || hosts.contains(&ip) { - continue; - } - hosts.push(ip); - } - Ok(hosts) -} - -/// Bind a dual-stack socket on an ephemeral port, pairing it with each host -/// address, and start reading it. -fn bind(hosts: &[IpAddr]) -> Result { - use moq_tokio::bind; - let socket = bind::udp(bind::Udp::new("[::]:0".parse().unwrap())) - .or_else(|_| bind::udp(bind::Udp::new("0.0.0.0:0".parse().unwrap())))?; - socket.set_nonblocking(true)?; - // A `[::]` socket that stayed v6-only can't send to IPv4 candidates. - let ipv4 = socket.local_addr()?.is_ipv4() || bind::udp_is_dual_stack(&socket); - let socket = UdpSocket::from_std(socket)?; - let local = socket.local_addr()?; - - let locals: Vec = hosts - .iter() - .filter(|ip| if ip.is_ipv4() { ipv4 } else { local.is_ipv6() }) - .map(|&ip| SocketAddr::new(ip, local.port())) - .collect(); - if locals.is_empty() { - return Err(Error::NoHost); - } - let udp = Arc::new(socket); - Ok(crate::ice::Socket::new(udp.clone(), locals, crate::ice::reader(udp))?) -} - -/// Look up each STUN server. One that does not resolve is skipped, since a missing -/// reflexive candidate only costs the paths that needed it. -async fn resolve_stun(servers: &[Stun]) -> Vec { - let mut addrs = Vec::new(); - for server in servers { - match tokio::net::lookup_host((server.host.as_str(), server.port)).await { - Ok(found) => addrs.extend(found), - Err(err) => tracing::warn!(%err, %server, "failed to resolve STUN server"), - } - } - addrs -} - -/// The SCTP message limit a description advertises, where `0` means unlimited. -fn max_message_size(sdp: &str) -> Result { - let Some(value) = sdp - .lines() - .find_map(|line| line.trim().strip_prefix("a=max-message-size:")) - else { - return Ok(DEFAULT_MAX_MESSAGE_SIZE); - }; - match value.trim().parse::() { - Ok(0) => Ok(u64::MAX), - Ok(size) => Ok(size), - Err(_) => Err(Error::Sdp(format!("invalid max-message-size: {value}"))), - } -} - -/// Split a description's `.local` candidates out, since str0m only parses IP addresses. -fn split_mdns(sdp: &str) -> Result<(String, Vec), Error> { - let mut kept = String::with_capacity(sdp.len()); - let mut mdns = Vec::new(); - for line in sdp.split_inclusive('\n') { - if let Some(candidate) = line.trim_end().strip_prefix("a=") - && candidate.starts_with("candidate:") - && mdns_host(candidate)?.is_some() - { - mdns.push(candidate.to_string()); - continue; - } - kept.push_str(line); - } - Ok((kept, mdns)) -} - -/// The `.local` host name a `candidate:` line connects to, if any. The rest of the -/// line is checked now, so a malformed candidate fails before it costs a query. -fn mdns_host(line: &str) -> Result, Error> { - let Some(host) = candidate_address(line).filter(|host| host.ends_with(".local")) else { - return Ok(None); - }; - with_address(line, IpAddr::V4(Ipv4Addr::UNSPECIFIED))?; - Ok(Some(host)) -} - -/// The connection address of a `candidate:` line (RFC 8839 section 5.1). -fn candidate_address(line: &str) -> Option<&str> { - line.split_whitespace().nth(4) -} - -/// Parse a `candidate:` line with `ip` as its connection address. -fn with_address(line: &str, ip: IpAddr) -> Result { - let ip = ip.to_string(); - let mut fields: Vec<&str> = line.split_whitespace().collect(); - let Some(addr) = fields.get_mut(4) else { - return Err(Error::Candidate(line.to_string())); - }; - *addr = &ip; - str0m::Candidate::from_sdp_string(&fields.join(" ")).map_err(|err| Error::Candidate(err.to_string())) -} - -#[cfg(test)] -mod tests; diff --git a/rs/moq-webrtc/src/p2p/resolver.rs b/rs/moq-webrtc/src/p2p/resolver.rs deleted file mode 100644 index 6242935b212..00000000000 --- a/rs/moq-webrtc/src/p2p/resolver.rs +++ /dev/null @@ -1,298 +0,0 @@ -//! Resolves a peer's `.local` candidates over mDNS, one distinct name at a time. - -use std::collections::HashMap; -use std::future::Future; -use std::net::IpAddr; -use std::sync::Mutex; -use std::time::Duration; - -use tokio::sync::mpsc; - -use super::{Command, Error, candidate_address, with_address}; - -/// How long to wait for a `.local` name to resolve: mdns-sd's first query plus its -/// retransmissions at one and two seconds (RFC 6762 section 5.2). -const MDNS_TIMEOUT: Duration = Duration::from_secs(5); - -/// Looks up the address behind a `.local` host name, or `None` if it does not resolve. -pub(super) trait Lookup: Send + Sync + 'static { - fn lookup(&self, host: &str) -> impl Future> + Send; -} - -/// A peer's resolver task, cancelled when this drops. -/// -/// The task resolves one name at a time and takes one batch of lines ahead of the -/// one it is working on, so a peer's queued work is bounded by what its signaling -/// already sent, and its signaling waits behind its own slow names. -pub(super) struct Resolver { - batches: mpsc::Sender>, - task: tokio::task::JoinHandle<()>, -} - -impl Resolver { - /// Start resolving into the driver's `commands`. - pub fn spawn(commands: mpsc::Sender, lookup: impl Lookup) -> Self { - let (batches, rx) = mpsc::channel(1); - use tracing::Instrument; - let task = tokio::spawn( - async move { - moq_tokio::panic::isolate(run(rx, commands, lookup)).await; - } - .instrument(tracing::Span::current()), - ); - Self { batches, task } - } - - /// Queue `.local` candidate lines, waiting while the resolver is behind. - pub async fn add(&self, lines: Vec) -> Result<(), Error> { - if lines.is_empty() { - return Ok(()); - } - self.batches.send(lines).await.map_err(|_| Error::Closed) - } -} - -impl Drop for Resolver { - fn drop(&mut self) { - self.task.abort(); - } -} - -async fn run(batches: mpsc::Receiver>, commands: mpsc::Sender, lookup: impl Lookup) { - // Once the driver exits no lookup can reach a connection, so stop, and let - // signaling see the peer is closed. - tokio::select! { - _ = commands.closed() => {} - _ = resolve(batches, &commands, lookup) => {} - } -} - -async fn resolve(mut batches: mpsc::Receiver>, commands: &mpsc::Sender, lookup: impl Lookup) { - while let Some(lines) = batches.recv().await { - for (host, lines) in by_host(&lines) { - let Some(ip) = lookup.lookup(host).await else { - tracing::debug!(%host, "dropped remote candidates: the name did not resolve"); - continue; - }; - for line in lines { - match with_address(line, ip) { - Ok(candidate) => { - if commands.send(Command::Candidate(candidate)).await.is_err() { - return; - } - } - Err(err) => tracing::debug!(%err, "dropped a remote candidate"), - } - } - } - } -} - -/// Group candidate lines by host name, in the order each name first appears. -fn by_host(lines: &[String]) -> Vec<(&str, Vec<&str>)> { - let mut index = HashMap::new(); - let mut groups: Vec<(&str, Vec<&str>)> = Vec::new(); - for line in lines { - let Some(host) = candidate_address(line) else { - continue; - }; - let group = *index.entry(host).or_insert_with(|| { - groups.push((host, Vec::new())); - groups.len() - 1 - }); - groups[group].1.push(line); - } - groups -} - -/// The process-wide mDNS daemon, started on the first `.local` candidate. -static MDNS: Mutex> = Mutex::new(None); - -/// Multicast DNS, preferring a name's IPv4 address. -pub(super) struct Mdns; - -impl Lookup for Mdns { - async fn lookup(&self, host: &str) -> Option { - let daemon = { - let mut daemon = MDNS.lock().unwrap(); - match daemon.as_ref() { - Some(daemon) => daemon.clone(), - None => daemon - .insert( - mdns_sd::ServiceDaemon::new() - .inspect_err(|err| tracing::debug!(%err, "failed to start the mDNS daemon")) - .ok()?, - ) - .clone(), - } - }; - - let name = format!("{host}."); - let timeout = MDNS_TIMEOUT.as_millis() as u64; - let events = daemon - .resolve_hostname(&name, Some(timeout)) - .inspect_err(|err| tracing::debug!(%err, "failed to query mDNS")) - .ok()?; - let found = loop { - match events.recv_async().await { - Ok(mdns_sd::HostnameResolutionEvent::AddressesFound(_, addrs)) if !addrs.is_empty() => { - let addrs: Vec = addrs.iter().map(|addr| addr.to_ip_addr()).collect(); - break addrs.iter().find(|ip| ip.is_ipv4()).or(addrs.first()).copied(); - } - Ok(mdns_sd::HostnameResolutionEvent::SearchTimeout(_)) | Err(_) => break None, - Ok(_) => {} - } - }; - let _ = daemon.stop_resolve_hostname(&name); - found - } -} - -#[cfg(test)] -mod tests { - use std::net::Ipv4Addr; - use std::sync::Arc; - use std::sync::atomic::{AtomicUsize, Ordering}; - - use super::*; - use crate::vendor::str0m; - - /// How long the fake takes to answer, on the paused clock. - const DELAY: Duration = Duration::from_secs(1); - - /// Answers each name after [`DELAY`], recording the queries and how many overlap. - #[derive(Clone, Default)] - struct Fake { - queries: Arc>>, - in_flight: Arc, - most_in_flight: Arc, - } - - impl Fake { - fn queries(&self) -> Vec { - self.queries.lock().unwrap().clone() - } - } - - /// Counts a query in flight until its future completes or is dropped. - struct InFlight(Arc); - - impl Drop for InFlight { - fn drop(&mut self) { - self.0.fetch_sub(1, Ordering::SeqCst); - } - } - - impl Lookup for Fake { - async fn lookup(&self, host: &str) -> Option { - self.queries.lock().unwrap().push(host.to_string()); - let now = self.in_flight.fetch_add(1, Ordering::SeqCst) + 1; - let _in_flight = InFlight(self.in_flight.clone()); - self.most_in_flight.fetch_max(now, Ordering::SeqCst); - kio::clock::sleep(DELAY).await; - let index: u8 = host - .trim_start_matches("host") - .trim_end_matches(".local") - .parse() - .unwrap(); - Some(IpAddr::V4(Ipv4Addr::new(192, 0, 2, index))) - } - } - - fn line(foundation: usize, host: usize) -> String { - format!("candidate:{foundation} 1 udp 2113937151 host{host}.local 54321 typ host") - } - - /// The next candidate the resolver handed the driver, or `None` once it stopped. - async fn next(commands: &mut mpsc::Receiver) -> Option { - match commands.recv().await? { - Command::Candidate(candidate) => Some(candidate), - _ => panic!("the resolver only sends candidates"), - } - } - - #[tokio::test(start_paused = true)] - async fn lines_sharing_a_name_issue_one_query() { - let fake = Fake::default(); - let (tx, mut commands) = mpsc::channel(1); - let resolver = Resolver::spawn(tx, fake.clone()); - - resolver.add((0..100).map(|i| line(i, 7)).collect()).await.unwrap(); - for _ in 0..100 { - let candidate = next(&mut commands).await.unwrap(); - assert_eq!(candidate.addr(), "192.0.2.7:54321".parse().unwrap()); - } - assert_eq!(fake.queries(), ["host7.local"]); - } - - #[tokio::test(start_paused = true)] - async fn distinct_names_resolve_one_at_a_time() { - let fake = Fake::default(); - let (tx, mut commands) = mpsc::channel(1); - let resolver = Resolver::spawn(tx, fake.clone()); - - let start = kio::clock::now(); - resolver.add((0..10).map(|i| line(i, i)).collect()).await.unwrap(); - for i in 0..10 { - let candidate = next(&mut commands).await.unwrap(); - assert_eq!(candidate.addr().ip(), IpAddr::V4(Ipv4Addr::new(192, 0, 2, i as u8))); - } - assert_eq!(fake.most_in_flight.load(Ordering::SeqCst), 1); - assert_eq!(start.elapsed(), DELAY * 10); - } - - #[tokio::test(start_paused = true)] - async fn trickled_names_wait_for_the_resolver() { - let fake = Fake::default(); - let (tx, _commands) = mpsc::channel(1); - let resolver = Resolver::spawn(tx, fake.clone()); - - // The first is resolving and the second waits in the channel. - resolver.add(vec![line(0, 0)]).await.unwrap(); - resolver.add(vec![line(1, 1)]).await.unwrap(); - - // The third waits for the first to finish, rather than queueing. - let start = kio::clock::now(); - resolver.add(vec![line(2, 2)]).await.unwrap(); - assert_eq!(start.elapsed(), DELAY); - assert_eq!(fake.most_in_flight.load(Ordering::SeqCst), 1); - } - - #[tokio::test(start_paused = true)] - async fn dropping_the_resolver_cancels_resolution() { - let fake = Fake::default(); - let (tx, mut commands) = mpsc::channel(1); - let resolver = Resolver::spawn(tx, fake.clone()); - - resolver.add(vec![line(0, 0), line(1, 1)]).await.unwrap(); - while fake.queries().is_empty() { - tokio::task::yield_now().await; - } - drop(resolver); - - // The task is gone, with its query and its handle on the driver. - assert!(next(&mut commands).await.is_none()); - assert_eq!(fake.in_flight.load(Ordering::SeqCst), 0); - assert_eq!(fake.queries(), ["host0.local"]); - } - - #[tokio::test(start_paused = true)] - async fn resolution_stops_with_the_driver() { - let fake = Fake::default(); - let (tx, commands) = mpsc::channel(1); - let resolver = Resolver::spawn(tx, fake.clone()); - - resolver.add(vec![line(0, 0), line(1, 1)]).await.unwrap(); - while fake.queries().is_empty() { - tokio::task::yield_now().await; - } - drop(commands); - - // The query in flight is cancelled before it answers, the rest of the batch - // is skipped, and signaling sees the peer is closed. - kio::clock::sleep(DELAY / 2).await; - assert_eq!(fake.in_flight.load(Ordering::SeqCst), 0); - assert!(matches!(resolver.add(vec![line(2, 2)]).await, Err(Error::Closed))); - assert_eq!(fake.queries(), ["host0.local"]); - } -} diff --git a/rs/moq-webrtc/src/p2p/tests.rs b/rs/moq-webrtc/src/p2p/tests.rs deleted file mode 100644 index 6c41e1a45a1..00000000000 --- a/rs/moq-webrtc/src/p2p/tests.rs +++ /dev/null @@ -1,454 +0,0 @@ -use crate::vendor::str0m; -use std::net::{IpAddr, Ipv4Addr}; -use std::time::Duration; - -use super::*; - -/// Real sockets and real ICE, so these run on the wall clock. -const TIMEOUT: Duration = Duration::from_secs(10); - -const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST); - -/// A protocol both the default client and server speak. -fn protocol() -> &'static str { - moq_tokio::connect::Config::default().versions().alpns()[0] -} - -/// A one-frame broadcast named `test` and the handles that keep it alive. -fn broadcast(payload: &[u8]) -> (moq_net::origin::Producer, impl Sized) { - let origin = moq_tokio::origin::spawn(); - let broadcast = origin.route("test", moq_net::origin::RouteOptions::default()).unwrap(); - let track = broadcast - .broadcast() - .create_track( - "video", - moq_net::track::Info::default().with_timescale(moq_net::Timescale::MILLI), - ) - .unwrap(); - let mut group = track.append_group().unwrap(); - group.write_frame(moq_net::Timestamp::ZERO, payload.to_vec()).unwrap(); - group.finish().unwrap(); - (origin, (broadcast, track)) -} - -/// Serve a one-frame broadcast from the answering peer, subscribe from the -/// offering one, and read the frame back across the data channel. -async fn transfer(offerer: &Offerer, answerer: &Answerer, payload: &[u8]) { - let (origin, _keep) = broadcast(payload); - let listener = moq_tokio::listen::Config::default() - .init_streams() - .unwrap() - .listen() - .await - .unwrap(); - let server = async { - let request = answerer.accept(&listener).await.unwrap(); - assert_eq!(request.transport(), moq_tokio::Transport::WebRtc); - assert_eq!(request.alpn(), Some(answerer.protocol.as_str())); - request.with_publisher(&origin).ok().await.unwrap() - }; - - let subscribed = moq_tokio::origin::spawn(); - let consumer = subscribed.consume(); - let mut announced = consumer.announced(); - let client = moq_tokio::client::Config::default() - .init() - .unwrap() - .with_subscriber(subscribed); - let (_server, _client) = kio::clock::timeout(TIMEOUT, async { - tokio::join!(server, async { offerer.connect(&client).await.unwrap() }) - }) - .await - .expect("handshake timed out"); - - let read = async { - let Some(moq_net::announce::Event::Present(route)) = announced.next().await else { - panic!("expected the broadcast to be announced"); - }; - assert_eq!(route.prefix.as_str(), "test"); - let broadcast = consumer.request("test", None).await.unwrap(); - let mut track = broadcast.track("video").unwrap().subscribe(None).await.unwrap(); - let mut group = track.recv_group().await.unwrap().unwrap(); - group.read_frame().await.unwrap().unwrap() - }; - let frame = kio::clock::timeout(TIMEOUT, read).await.expect("transfer timed out"); - assert!(frame.payload[..] == *payload, "the frame arrived corrupted"); -} - -#[tokio::test] -async fn session_over_loopback() { - let config = Config::default(); - let (offerer, offer) = Offerer::with_hosts(&config, protocol(), vec![LOOPBACK]).await.unwrap(); - let (answerer, answer) = Answerer::with_hosts(&config, &offer, protocol(), vec![LOOPBACK]) - .await - .unwrap(); - offerer.accept(&answer).await.unwrap(); - - transfer(&offerer, &answerer, b"hello").await; -} - -/// A zero timeout disables the bound rather than elapsing at once. -#[tokio::test] -async fn zero_timeout_is_unbounded() { - let config = Config { - timeout: Duration::ZERO, - ..Config::default() - }; - let (offerer, offer) = Offerer::with_hosts(&config, protocol(), vec![LOOPBACK]).await.unwrap(); - let (answerer, answer) = Answerer::with_hosts(&config, &offer, protocol(), vec![LOOPBACK]) - .await - .unwrap(); - offerer.accept(&answer).await.unwrap(); - - transfer(&offerer, &answerer, b"hello").await; -} - -/// A frame many records long fills the SCTP send window, so the writer has to -/// wait for the peer's acknowledgements and resume. -#[tokio::test] -async fn large_frame_over_loopback() { - let config = Config::default(); - let (offerer, offer) = Offerer::with_hosts(&config, protocol(), vec![LOOPBACK]).await.unwrap(); - let (answerer, answer) = Answerer::with_hosts(&config, &offer, protocol(), vec![LOOPBACK]) - .await - .unwrap(); - offerer.accept(&answer).await.unwrap(); - - let payload: Vec = (0..1024 * 1024).map(|i| i as u8).collect(); - transfer(&offerer, &answerer, &payload).await; -} - -/// Open the data channel between two loopback peers, without a MoQ session over it. -async fn channels() -> (Offerer, Answerer, Opened, Opened) { - let config = Config::default(); - let (offerer, offer) = Offerer::with_hosts(&config, protocol(), vec![LOOPBACK]).await.unwrap(); - let (answerer, answer) = Answerer::with_hosts(&config, &offer, protocol(), vec![LOOPBACK]) - .await - .unwrap(); - offerer.accept(&answer).await.unwrap(); - let (sent, received) = kio::clock::timeout(TIMEOUT, async { tokio::join!(offerer.channel(), answerer.channel()) }) - .await - .expect("the channel did not open"); - (offerer, answerer, sent.unwrap(), received.unwrap()) -} - -/// A full record, numbered so its order can be checked. -fn record(index: usize) -> Bytes { - Bytes::from(vec![index as u8; RECORD_SIZE as usize]) -} - -/// A session that is not reading must not stop the peer connection: the agent -/// keeps acknowledging, so the remote writer gets well past the send window. -#[tokio::test] -async fn unread_records_do_not_stall_the_writer() { - let (_offerer, _answerer, sent, received) = channels().await; - let (mut writer, mut reader) = (sent.channel.writer, received.channel.reader); - let count = 8 * SEND_WINDOW / RECORD_SIZE as usize; - kio::clock::timeout(TIMEOUT, async { - for index in 0..count { - writer.write(record(index)).await.unwrap(); - } - }) - .await - .expect("the writer stalled while the reader was idle"); - - for index in 0..count { - assert_eq!(reader.recv().await.unwrap(), record(index)); - } -} - -/// A peer that sends past qmux's receive window while the session is not reading -/// has the channel closed, after the records within the budget. -#[tokio::test] -async fn ignoring_flow_control_closes_the_channel() { - let (_offerer, _answerer, sent, received) = channels().await; - let budget = RECEIVE_WINDOW + READ_SLACK; - let within = (budget / RECORD_SIZE) as usize; - let (mut writer, mut reader) = (sent.channel.writer, received.channel.reader); - kio::clock::timeout(TIMEOUT, async { - for index in 0..within + 8 { - if writer.write(record(index)).await.is_err() { - break; - } - } - }) - .await - .expect("the writer stalled"); - - for index in 0..within { - assert_eq!(reader.recv().await.unwrap(), record(index)); - } - assert!(matches!(reader.recv().await, Err(qmux::Error::FlowControlError))); -} - -/// Answer STUN Binding requests with the source address, as a public server would. -async fn stun_server() -> SocketAddr { - use stun_types::attribute::XorMappedAddress; - use stun_types::message::{Message, MessageWriteVec}; - use stun_types::prelude::*; - - let socket = UdpSocket::bind((LOOPBACK, 0)).await.unwrap(); - let addr = socket.local_addr().unwrap(); - tokio::spawn(async move { - let mut buf = [0; 1500]; - while let Ok((len, src)) = socket.recv_from(&mut buf).await { - let request = Message::from_bytes(&buf[..len]).unwrap(); - let mut reply = Message::builder_success(&request, MessageWriteVec::new()); - reply - .add_attribute(&XorMappedAddress::new(src, request.transaction_id())) - .unwrap(); - socket.send_to(&reply.finish(), src).await.unwrap(); - } - }); - addr -} - -/// Drop the candidates a description carries, so only trickled ones reach the peer. -fn strip_candidates(sdp: &str) -> String { - sdp.split_inclusive('\n') - .filter(|line| !line.starts_with("a=candidate:")) - .collect() -} - -/// The offerer sits behind a pretend NAT: it advertises 127.0.0.2, which the -/// answerer never learns, and reaches the world as 127.0.0.1. With no candidates -/// in either description and none trickled back, the answerer can only reach the -/// offerer through the server-reflexive candidate STUN found. -#[tokio::test] -async fn server_reflexive_candidate_is_offered_and_selected() { - let stun = stun_server().await; - let config = Config { - stun: vec![format!("stun:{stun}").parse().unwrap()], - ..Default::default() - }; - let private = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)); - let (mut offerer, offer) = Offerer::with_hosts(&config, protocol(), vec![private]).await.unwrap(); - let offer = Offer::new(strip_candidates(offer.as_str())); - let (answerer, answer) = Answerer::with_hosts(&Config::default(), &offer, protocol(), vec![LOOPBACK]) - .await - .unwrap(); - offerer - .accept(&Answer::new(strip_candidates(answer.as_str()))) - .await - .unwrap(); - - let candidate = kio::clock::timeout(TIMEOUT, offerer.candidate()) - .await - .expect("gathering timed out") - .expect("no server-reflexive candidate"); - let parsed = str0m::Candidate::from_sdp_string(candidate.as_str()).unwrap(); - assert_eq!(parsed.kind(), str0m::CandidateKind::ServerReflexive); - assert_eq!(parsed.addr().ip(), LOOPBACK); - answerer.add_candidate(&candidate).await.unwrap(); - assert_eq!( - offerer.candidate().await, - None, - "gathering should end after the only server answers" - ); - - transfer(&offerer, &answerer, b"hello").await; -} - -/// A channel carrying a protocol that is not MoQ opens, and moq-net's policy refuses it on both sides. -#[tokio::test] -async fn unsupported_protocol_is_refused() { - let config = Config::default(); - let (offerer, offer) = Offerer::with_hosts(&config, "not-moq", vec![LOOPBACK]).await.unwrap(); - let (answerer, answer) = Answerer::with_hosts(&config, &offer, "not-moq", vec![LOOPBACK]) - .await - .unwrap(); - offerer.accept(&answer).await.unwrap(); - - let listener = moq_tokio::listen::Config::default() - .init_streams() - .unwrap() - .listen() - .await - .unwrap(); - let client = moq_tokio::client::Config::default().init().unwrap(); - let (accepted, connected) = kio::clock::timeout(TIMEOUT, async { - tokio::join!(answerer.accept(&listener), offerer.connect(&client)) - }) - .await - .expect("the refusal timed out"); - assert!(accepted.is_err(), "the answerer accepted an unsupported protocol"); - assert!(connected.is_err(), "the offerer connected with an unsupported protocol"); -} - -/// A channel carrying another supported ALPN than the one signaling agreed is refused. -#[tokio::test] -async fn unsignaled_protocol_is_refused() { - let versions = moq_tokio::connect::Config::default().versions(); - let [agreed, other, ..] = versions.alpns()[..] else { - panic!("expected two supported ALPNs"); - }; - let config = Config::default(); - let (offerer, offer) = Offerer::with_hosts(&config, other, vec![LOOPBACK]).await.unwrap(); - let (answerer, answer) = Answerer::with_hosts(&config, &offer, agreed, vec![LOOPBACK]) - .await - .unwrap(); - offerer.accept(&answer).await.unwrap(); - - let listener = moq_tokio::listen::Config::default() - .init_streams() - .unwrap() - .listen() - .await - .unwrap(); - let accepted = kio::clock::timeout(TIMEOUT, answerer.accept(&listener)) - .await - .expect("the channel did not open"); - assert!(matches!(accepted, Err(Error::Protocol(protocol)) if protocol == other)); -} - -#[test] -fn stun_urls() { - let parse = |url: &str| url.parse::().map(|stun| stun.to_string()).ok(); - assert_eq!( - parse("stun:stun.example.com").as_deref(), - Some("stun:stun.example.com:3478") - ); - assert_eq!(parse("STUN:1.2.3.4:19302").as_deref(), Some("stun:1.2.3.4:19302")); - assert_eq!(parse("stun:[::1]").as_deref(), Some("stun:[::1]:3478")); - assert_eq!(parse("stun:[::1]:5349").as_deref(), Some("stun:[::1]:5349")); - for bad in [ - "turn:turn.example.com", - "stuns:stun.example.com", - "stun:", - "stun:host:port", - "stun:host:3478?transport=udp", - "stun:[::1]x", - "stun:[nope]", - "stun:server.example#fragment", - "stun:server example", - "stun:server\texample", - "stun.example.com", - ] { - assert_eq!(parse(bad), None, "{bad}"); - } -} - -#[test] -fn max_message_sizes() { - assert_eq!(max_message_size("v=0\r\n").unwrap(), DEFAULT_MAX_MESSAGE_SIZE); - assert_eq!(max_message_size("a=max-message-size:262144\r\n").unwrap(), 262_144); - assert_eq!(max_message_size("a=max-message-size:0\r\n").unwrap(), u64::MAX); - assert!(max_message_size("a=max-message-size:big\r\n").is_err()); -} - -#[test] -fn mdns_candidates_are_split_out() { - let sdp = "v=0\r\n\ - a=candidate:1 1 udp 2113937151 0a1b2c3d.local 54321 typ host\r\n\ - a=candidate:2 1 udp 2113937151 192.168.1.2 54321 typ host\r\n\ - a=end-of-candidates\r\n"; - let (kept, mdns) = split_mdns(sdp).unwrap(); - assert_eq!( - kept, - "v=0\r\na=candidate:2 1 udp 2113937151 192.168.1.2 54321 typ host\r\na=end-of-candidates\r\n" - ); - assert_eq!(mdns, ["candidate:1 1 udp 2113937151 0a1b2c3d.local 54321 typ host"]); -} - -/// A malformed `.local` candidate is refused up front, not after costing a query. -#[test] -fn malformed_mdns_candidates_are_refused() { - let sdp = "v=0\r\na=candidate:1 1 udp nope 0a1b2c3d.local 54321 typ host\r\n"; - assert!(matches!(split_mdns(sdp), Err(Error::Candidate(_)))); - assert!(mdns_host("candidate:1 1 udp 2113937151 0a1b2c3d.local 54321 typ nope").is_err()); - assert_eq!( - mdns_host("candidate:1 1 udp 2113937151 0a1b2c3d.local 54321 typ host").unwrap(), - Some("0a1b2c3d.local") - ); -} - -/// Building a peer mutates its `Rtc` several times before the agent's first drain: -/// a host candidate per address, then the channel or the answer. str0m wants a -/// drain after each, which is a no-op while none of them queues output; pin that, -/// so a str0m upgrade that changes it fails here. -#[test] -fn construction_queues_no_output() { - fn idle(rtc: &mut Rtc) { - assert!(matches!(rtc.poll_output(), Ok(str0m::Output::Timeout(_)))); - } - fn host(rtc: &mut Rtc, addr: &str) { - let candidate = str0m::Candidate::host(addr.parse().unwrap(), "udp").unwrap(); - rtc.add_local_candidate(candidate); - idle(rtc); - } - - let mut offerer = Rtc::builder().build(kio::clock::now().into_std()); - host(&mut offerer, "127.0.0.1:5000"); - host(&mut offerer, "[::1]:5000"); - let mut api = offerer.sdp_api(); - api.add_channel(LABEL.to_string()); - let (offer, _pending) = api.apply().unwrap(); - idle(&mut offerer); - - let mut answerer = Rtc::builder().build(kio::clock::now().into_std()); - host(&mut answerer, "127.0.0.1:5001"); - host(&mut answerer, "[::1]:5001"); - answerer.sdp_api().accept_offer(offer).unwrap(); - idle(&mut answerer); -} - -/// A trickled IP candidate waits for the driver to take the one before it, so a -/// peer cannot queue candidates faster than the connection applies them. -#[tokio::test(start_paused = true)] -async fn trickled_candidates_wait_for_the_driver() { - let (commands, mut driver) = mpsc::channel(1); - let (_candidates, candidates) = mpsc::unbounded_channel(); - let peer = Peer { - resolver: Resolver::spawn(commands.clone(), resolver::Mdns), - commands, - candidates, - }; - let candidate = Candidate::new("candidate:1 1 udp 2113937151 192.0.2.1 54321 typ host"); - - peer.add_candidate(&candidate).await.unwrap(); - let mut second = std::pin::pin!(peer.add_candidate(&candidate)); - assert!( - futures::poll!(&mut second).is_pending(), - "the second candidate queued while the driver held the first" - ); - - assert!(matches!(driver.recv().await, Some(Command::Candidate(_)))); - second.await.unwrap(); - assert!(matches!(driver.recv().await, Some(Command::Candidate(_)))); -} - -/// A drain that starts while the channel is still coming up waits for the connection, -/// which is admitted rather than refused once its MoQ handshake starts. -#[tokio::test] -async fn a_drain_waits_for_an_establishing_peer() { - let config = Config::default(); - let (offerer, offer) = Offerer::with_hosts(&config, protocol(), vec![LOOPBACK]).await.unwrap(); - let (answerer, answer) = Answerer::with_hosts(&config, &offer, protocol(), vec![LOOPBACK]) - .await - .unwrap(); - - let admission = moq_net::server::Admission::default(); - let mut config = moq_tokio::server::Config::default(); - config.admission = admission.clone(); - let listener = config.init_streams().unwrap().listen().await.unwrap(); - let mut accept = std::pin::pin!(answerer.accept(&listener)); - // The answer is not applied yet, so the channel cannot open. - assert!(futures::poll!(accept.as_mut()).is_pending()); - let mut closed = std::pin::pin!(admission.close()); - assert!( - futures::poll!(closed.as_mut()).is_pending(), - "the drain skipped the establishing peer" - ); - - offerer.accept(&answer).await.unwrap(); - let client = moq_tokio::client::Config::default().init().unwrap(); - let (request, session) = kio::clock::timeout(TIMEOUT, async { tokio::join!(accept, offerer.connect(&client)) }) - .await - .expect("handshake timed out"); - let request = request.expect("the drain refused an establishing peer"); - assert!(futures::poll!(closed.as_mut()).is_pending()); - drop((request, session)); - kio::clock::timeout(TIMEOUT, closed) - .await - .expect("the drain never finished"); -} diff --git a/rs/moq-webrtc/src/sdp.rs b/rs/moq-webrtc/src/sdp.rs index 72eaba16679..112d234c9a2 100644 --- a/rs/moq-webrtc/src/sdp.rs +++ b/rs/moq-webrtc/src/sdp.rs @@ -114,7 +114,7 @@ mod tests { m=video 0 UDP/TLS/RTP/SAVPF 0\r\n\ c=IN IP4 0.0.0.0\r\n\ a=mid:1\r\n\ - m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ + m=application 0 UDP/DTLS/SCTP webrtc-datachannel\r\n\ c=IN IP4 0.0.0.0\r\n\ a=mid:2\r\n\ m=video 9 UDP/TLS/RTP/SAVPF 96\r\n\ @@ -126,7 +126,7 @@ mod tests { assert!(!sections[0].contains("b="), "the session section stays unbounded"); assert!(sections[1].contains(bounded), "{}", sections[1]); assert!(!sections[2].contains("b="), "a rejected section stays unbounded"); - assert!(!sections[3].contains("b="), "the data channel stays unbounded"); + assert!(!sections[3].contains("b="), "the rejected data channel stays unbounded"); assert!(sections[4].contains(bounded), "{}", sections[4]); } diff --git a/rs/moq-webrtc/src/session.rs b/rs/moq-webrtc/src/session.rs index acbcf3b341f..51eab73941a 100644 --- a/rs/moq-webrtc/src/session.rs +++ b/rs/moq-webrtc/src/session.rs @@ -252,9 +252,7 @@ impl Session { } => self.send_remb(), event = self.agent.next() => match event { - Ok(crate::ice::Event::Rtc(event)) => self.handle_event(event)?, - // No STUN servers are configured, so there is nothing to trickle. - Ok(_) => {} + Ok(event) => self.handle_event(event)?, Err(crate::ice::Error::Closed) => return Ok(()), Err(crate::ice::Error::Timeout) => return Err(Error::IceTimeout), Err(crate::ice::Error::Rtc(err)) => return Err(Error::Rtc(err)), diff --git a/rs/moq-webrtc/src/vendor/mod.rs b/rs/moq-webrtc/src/vendor/mod.rs index 834c3f43022..40b3ecdecac 100644 --- a/rs/moq-webrtc/src/vendor/mod.rs +++ b/rs/moq-webrtc/src/vendor/mod.rs @@ -1,15 +1,16 @@ //! The WebRTC stack moq-webrtc runs on: str0m (SDP, RTP/RTCP, SRTP, the `Rtc` -//! state machine) with its ICE agent `is`, DTLS from dimpl, and SCTP from -//! sctp-proto. Each lives here as a private module, trimmed to what MoQ uses, so -//! fixes land in normal MoQ PRs. +//! state machine) with its ICE agent `is`, and DTLS from dimpl. Each lives here +//! as a private module, trimmed to what MoQ uses, so fixes land in normal MoQ +//! PRs. str0m's data channels (SCTP over DTLS) are cut: an offered +//! `m=application` line is answered rejected. //! //! # Upstream //! //! Vendored on 2026-11-07, each module keeping its upstream layout and its //! license (MIT OR Apache-2.0). The `LICENSE-*` files sit beside `str0m` (whose //! file covers the other crates from its repository, which ship none of their -//! own), `dimpl`, and `sctp_proto`, and `str0m/packet/LICENSE-APACHE.txt` keeps -//! webrtc-rs's notice on `str0m::packet`: +//! own) and `dimpl`, and `str0m/packet/LICENSE-APACHE.txt` keeps webrtc-rs's +//! notice on `str0m::packet`: //! - `str0m` (0.24.1+), `str0m_proto` (0.7.0), `is` (0.11.1), and the test-only //! `netem` (0.4.0): //! at [`dc317173`](https://github.com/algesten/str0m/commit/dc317173b16fc6ed86633e6b08b229c9195deb87) @@ -17,8 +18,6 @@ //! crypto provider. //! - `dimpl`: 0.9.0 //! ([`c17b3b8`](https://github.com/algesten/dimpl/commit/c17b3b8b971b6eb2ecf7284f5dc0ecb86680ac4d)). -//! - `sctp_proto`: 0.10.7, as published -//! on crates.io. //! - `str0m_rind` and dimpl's `crypto::rind`, the stack's crypto providers: //! 's `rind-str0m` (as of //! [`86567aad`](https://github.com/kixel-ai/rind/commit/86567aadabc22d2b2ac23ea534598a0fffc66538), @@ -48,8 +47,6 @@ mod is; #[cfg(test)] #[path = "netem/lib.rs"] mod netem; -#[path = "sctp_proto/lib.rs"] -mod sctp_proto; #[path = "str0m/lib.rs"] pub(crate) mod str0m; #[path = "str0m_proto/lib.rs"] diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-APACHE b/rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-APACHE deleted file mode 100644 index 5fa038acf90..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-APACHE +++ /dev/null @@ -1,202 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - -2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - -4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - -5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - -6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - -7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - -8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - -9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - -END OF TERMS AND CONDITIONS - -APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - -Copyright (c) 2021-2026 WebRTC.rs -Copyright (c) 2026 Martin Algesten - -Licensed under the Apache License, Version 2.0 (the "License"); -you may not use this file except in compliance with the License. -You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - -Unless required by applicable law or agreed to in writing, software -distributed under the License is distributed on an "AS IS" BASIS, -WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -See the License for the specific language governing permissions and -limitations under the License. diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-MIT b/rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-MIT deleted file mode 100644 index b80b4e9f0dc..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/LICENSE-MIT +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2021-2026 WebRTC.rs -Copyright (c) 2026 Martin Algesten - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/association/association_test.rs b/rs/moq-webrtc/src/vendor/sctp_proto/association/association_test.rs deleted file mode 100644 index 7df8cdd20c3..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/association/association_test.rs +++ /dev/null @@ -1,5414 +0,0 @@ -use crate::vendor::sctp_proto::chunk::chunk_i_forward_tsn::ChunkIForwardTsnStream; -use crate::vendor::sctp_proto::chunk::{Chunk, chunk_init::ChunkInit}; -use crate::vendor::sctp_proto::config::DEFAULT_SCTP_PORT; -use crate::vendor::sctp_proto::config::generate_snap_token; - -use super::*; - -const ACCEPT_CH_SIZE: usize = 16; - -fn create_association(config: TransportConfig) -> Association { - Association::new( - None, - Arc::new(config), - 1400, - 0, - SocketAddr::from_str("0.0.0.0:0").unwrap(), - None, - Instant::now(), - ) -} - -#[test] -fn test_assoc_is_closing() { - let closing_states = [ - AssociationState::ShutdownSent, - AssociationState::ShutdownAckSent, - AssociationState::ShutdownPending, - AssociationState::ShutdownReceived, - ]; - - for state in [ - AssociationState::Closed, - AssociationState::CookieWait, - AssociationState::CookieEchoed, - AssociationState::Established, - ] { - let a = Association { - state, - ..Default::default() - }; - - assert!(!a.is_closing(), "{state} should not be closing"); - } - - for state in closing_states { - let a = Association { - state, - ..Default::default() - }; - - assert!(a.is_closing(), "{state} should be closing"); - assert!(!a.is_closed(), "{state} should not be closed"); - } -} - -fn outgoing_reset(rsn: u32, stream_id: StreamId) -> ChunkReconfig { - ChunkReconfig { - param_a: Some(Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: rsn, - stream_identifiers: vec![stream_id], - ..Default::default() - })), - ..Default::default() - } -} - -fn insert_active_reset(a: &mut Association, rsn: u32, stream_id: StreamId) { - a.reconfigs.insert(rsn, outgoing_reset(rsn, stream_id)); - a.active_reconfig = Some(rsn); -} - -fn insert_queued_reset(a: &mut Association, rsn: u32, stream_id: StreamId) { - let reset = outgoing_reset(rsn, stream_id); - a.reconfigs.insert(rsn, reset.clone()); - let packet = a.create_packet(vec![Box::new(reset)]); - a.control_queue.push_back(packet); -} - -fn reconfig_response_result(packets: &[Packet], rsn: u32) -> Option { - packets.iter().find_map(|packet| { - packet.chunks.iter().find_map(|chunk| { - let reconfig = chunk.as_any().downcast_ref::()?; - reconfig - .param_a - .iter() - .chain(reconfig.param_b.iter()) - .find_map(|param| { - let response = param.as_any().downcast_ref::()?; - (response.reconfig_response_sequence_number == rsn).then_some(response.result) - }) - }) - }) -} - -#[test] -fn test_reconfig_in_progress_timeout_does_not_consume_retry_budget() -> Result<()> { - let now = Instant::now(); - let rsn = 7; - let mut a = create_association( - TransportConfig::default() - .with_max_init_retransmits(Some(0)) - .with_rto_initial_ms(1), - ); - - insert_active_reset(&mut a, rsn, 1); - a.timers.start(Timer::Reconfig, now, a.rto_mgr.get_rto()); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result: ReconfigResult::InProgress, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - // The outbound path restarts the timer after processing InProgress. RFC - // 6525 section 5.2.7 H2 requires the next expiry to retransmit without - // incrementing the error counter. - a.timers.restart_if_stale(Timer::Reconfig, now, a.rto_mgr.get_rto()); - let deadline = a.timers.get(Timer::Reconfig).unwrap(); - a.handle_timeout(deadline); - - assert!(a.reconfigs.contains_key(&rsn)); - assert!(a.will_retransmit_reconfig); - Ok(()) -} - -#[test] -fn test_reset_complete_only_for_successful_reconfig_response() -> Result<()> { - let rsn = 7; - let stream_id = 1; - - for result in [ - ReconfigResult::SuccessNop, - ReconfigResult::SuccessPerformed, - ReconfigResult::Denied, - ReconfigResult::ErrorWrongSsn, - ReconfigResult::ErrorRequestAlreadyInProgress, - ReconfigResult::ErrorBadSequenceNumber, - ReconfigResult::InProgress, - ReconfigResult::Unknown, - ] { - let mut a = Association::default(); - a.pending_reset_completions.insert(stream_id); - insert_active_reset(&mut a, rsn, stream_id); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - let completed = matches!( - a.poll(), - Some(Event::Stream(StreamEvent::ResetComplete { id })) if id == stream_id - ); - let should_complete = matches!(result, ReconfigResult::SuccessNop | ReconfigResult::SuccessPerformed); - assert_eq!(completed, should_complete, "unexpected result for {result}"); - } - - Ok(()) -} - -#[test] -fn test_reconfig_retransmission_failure_is_terminal() { - let rsn = 7; - let stream_id = 1; - let mut a = Association::default(); - a.pending_reset_completions.insert(stream_id); - insert_active_reset(&mut a, rsn, stream_id); - - a.on_retransmission_failure(Timer::Reconfig); - - assert!(matches!( - a.poll(), - Some(Event::Stream(StreamEvent::ResetFailed { - id, - reason: StreamResetError::Failed, - })) if id == stream_id - )); -} - -#[test] -fn test_ambiguous_reset_failure_keeps_existing_stream_quarantined() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - a.stream(stream_id)?.stop()?; - let _ = a.gather_outbound(Instant::now()); - assert!(a.active_reconfig.is_some()); - - a.on_retransmission_failure(Timer::Reconfig); - - assert!(a.failed_reset_streams.contains(&stream_id)); - assert!( - !a.stream(stream_id)?.is_writable(), - "an unacknowledged reset may have succeeded at the peer, so old SSNs remain unsafe" - ); - Ok(()) -} - -#[test] -fn test_denied_reset_emits_terminal_event_and_remains_quarantined() -> Result<()> { - let rsn = 7; - let stream_id = 1; - let mut a = Association::default(); - a.pending_reset_completions.insert(stream_id); - insert_active_reset(&mut a, rsn, stream_id); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result: ReconfigResult::Denied, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - assert!(matches!( - a.poll(), - Some(Event::Stream(StreamEvent::ResetFailed { - id, - reason: StreamResetError::Denied, - })) if id == stream_id - )); - assert!(!a.pending_reset_completions.contains(&stream_id)); - assert!( - matches!( - a.open_stream(stream_id, PayloadProtocolIdentifier::Binary), - Err(Error::ErrStreamResetPending) - ), - "the quarantine must prevent the failed stream ID from being reused" - ); - Ok(()) -} - -#[test] -fn test_reset_complete_preserves_stream_generations() { - let stream_id = 1; - let mut a = Association::default(); - - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - a.unregister_stream(stream_id, true); - - // Incoming DATA can recreate an id while the previous reciprocal reset is - // still pending. A second reset of that id is a distinct generation. - assert!(a.get_or_create_stream(stream_id).is_some()); - a.unregister_stream(stream_id, true); - - a.emit_reset_complete([stream_id]); - a.emit_reset_complete([stream_id]); - - let mut finished = 0; - let mut reset_complete = 0; - while let Some(event) = a.poll() { - match event { - Event::Stream(StreamEvent::Finished { id }) if id == stream_id => finished += 1, - Event::Stream(StreamEvent::ResetComplete { id }) if id == stream_id => { - reset_complete += 1; - } - _ => {} - } - } - - assert_eq!(finished, 2); - assert_eq!(reset_complete, 2); -} - -#[test] -fn test_reset_complete_preserves_generations_through_responses() -> Result<()> { - let stream_id = 1; - let first_rsn = 7; - let second_rsn = 8; - let mut a = Association::default(); - - // Two Finished events for the same stream ID represent two distinct - // incarnations. Each successful reset response must complete one. - a.pending_reset_completions.insert(stream_id); - a.pending_reset_completions.insert(stream_id); - a.reconfigs.insert(first_rsn, outgoing_reset(first_rsn, stream_id)); - a.reconfigs.insert(second_rsn, outgoing_reset(second_rsn, stream_id)); - - for rsn in [first_rsn, second_rsn] { - a.active_reconfig = Some(rsn); - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - } - - let reset_complete = core::iter::from_fn(|| a.poll()) - .filter(|event| { - matches!( - event, - Event::Stream(StreamEvent::ResetComplete { id }) if *id == stream_id - ) - }) - .count(); - - assert_eq!( - reset_complete, 2, - "each completed stream generation needs its own ResetComplete" - ); - Ok(()) -} - -#[test] -fn test_overlapping_generations_success_then_denied_reports_success() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - - a.pending_reset_completions.insert(stream_id); - a.pending_reset_completions.insert(stream_id); - a.reconfigs.insert(7, outgoing_reset(7, stream_id)); - a.reconfigs.insert(8, outgoing_reset(8, stream_id)); - - for (rsn, result) in [(7, ReconfigResult::SuccessPerformed), (8, ReconfigResult::Denied)] { - a.active_reconfig = Some(rsn); - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - } - - let reset_complete = core::iter::from_fn(|| a.poll()) - .filter(|event| { - matches!( - event, - Event::Stream(StreamEvent::ResetComplete { id }) if *id == stream_id - ) - }) - .count(); - - assert_eq!( - reset_complete, 1, - "the successful generation still needs its ResetComplete" - ); - Ok(()) -} - -#[test] -fn test_overlapping_generations_denied_then_success_reports_only_success() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - - a.pending_reset_completions.insert(stream_id); - a.pending_reset_completions.insert(stream_id); - a.reconfigs.insert(7, outgoing_reset(7, stream_id)); - a.reconfigs.insert(8, outgoing_reset(8, stream_id)); - - for (rsn, result) in [(7, ReconfigResult::Denied), (8, ReconfigResult::SuccessPerformed)] { - a.active_reconfig = Some(rsn); - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - } - - let reset_complete = core::iter::from_fn(|| a.poll()) - .filter(|event| { - matches!( - event, - Event::Stream(StreamEvent::ResetComplete { id }) if *id == stream_id - ) - }) - .count(); - - assert_eq!( - reset_complete, 1, - "the denied generation must not inherit a later successful completion" - ); - Ok(()) -} - -#[test] -fn test_outgoing_reset_implicitly_acknowledges_pending_request() -> Result<()> { - let local_rsn = 7; - let stream_id = 1; - let mut a = Association::default(); - - insert_active_reset(&mut a, local_rsn, stream_id); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - - // RFC 6525 section 5.2.2 E1: the response sequence number carried by an - // incoming Outgoing Reset Request acknowledges our matching request. - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: local_rsn, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![], - }); - a.handle_reconfig_param(&request, &mut vec![])?; - - assert!( - !a.reconfigs.contains_key(&local_rsn), - "the implicitly acknowledged request must no longer be in flight" - ); - assert!( - a.timers.get(Timer::Reconfig).is_none(), - "the timer must stop after the final in-flight request is acknowledged" - ); - Ok(()) -} - -#[test] -fn test_outgoing_reset_does_not_ack_unsent_reciprocal() -> Result<()> { - let stream_id = 1; - let mut a = Association { - my_next_tsn: 1, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - // Handling this request queues a reciprocal Outgoing Reset Request in - // `reply`, but it has not been transmitted and its timer is not running. - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - - let reciprocal_rsn = *a.reconfigs.keys().next().unwrap(); - assert!(!reply.is_empty()); - assert!(a.timers.get(Timer::Reconfig).is_none()); - - // RFC 6525 section 5.2.2 E1 only acknowledges a request for which the - // Re-configuration Timer is running. A peer must not be able to pre-ack - // the queued reciprocal before the application polls it for transmission. - let premature_ack: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: reciprocal_rsn, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![], - }); - a.handle_reconfig_param(&premature_ack, &mut vec![])?; - - let reset_complete = core::iter::from_fn(|| a.poll()) - .filter(|event| { - matches!( - event, - Event::Stream(StreamEvent::ResetComplete { id }) if *id == stream_id - ) - }) - .count(); - assert_eq!( - (a.reconfigs.contains_key(&reciprocal_rsn), reset_complete), - (true, 0), - "an unsent reciprocal must remain pending and cannot complete a reset" - ); - Ok(()) -} - -#[test] -fn test_reset_complete_does_not_override_newer_failure() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - - a.pending_reset_completions.insert(stream_id); - a.pending_reset_completions.insert(stream_id); - a.reconfigs.insert(7, outgoing_reset(7, stream_id)); - a.reconfigs.insert(8, outgoing_reset(8, stream_id)); - - for (rsn, result) in [(7, ReconfigResult::SuccessPerformed), (8, ReconfigResult::Denied)] { - a.active_reconfig = Some(rsn); - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - } - - assert!(matches!( - a.poll(), - Some(Event::Stream(StreamEvent::ResetComplete { id })) if id == stream_id - )); - assert!(matches!( - a.poll(), - Some(Event::Stream(StreamEvent::ResetFailed { - id, - reason: StreamResetError::Denied, - })) if id == stream_id - )); - assert!(matches!( - a.open_stream(stream_id, PayloadProtocolIdentifier::Binary), - Err(Error::ErrStreamResetPending) - )); - Ok(()) -} - -#[test] -fn test_reconfig_response_does_not_ack_unsent_reciprocal() -> Result<()> { - let stream_id = 1; - let mut a = Association { - my_next_tsn: 1, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - - let reciprocal_rsn = *a.reconfigs.keys().next().unwrap(); - assert!(!reply.is_empty()); - assert!(a.timers.get(Timer::Reconfig).is_none()); - - // The reciprocal is only queued in the reply and has not been transmitted. - // RFC 6525 H1 says to ignore a response for an RSN whose timer is not running. - let premature_response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: reciprocal_rsn, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&premature_response, &mut vec![])?; - - let reset_complete = core::iter::from_fn(|| a.poll()) - .filter(|event| { - matches!( - event, - Event::Stream(StreamEvent::ResetComplete { id }) if *id == stream_id - ) - }) - .count(); - assert_eq!( - (a.reconfigs.contains_key(&reciprocal_rsn), reset_complete), - (true, 0), - "RFC 6525 H1 requires a response for an RSN whose timer is not running to be ignored" - ); - Ok(()) -} - -#[test] -fn test_outgoing_reset_does_not_ack_unsent_reciprocal_with_unrelated_timer() -> Result<()> { - let stream_id = 1; - let sent_rsn = 99; - let mut a = Association { - my_next_tsn: 1, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - insert_active_reset(&mut a, sent_rsn, 2); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - - // The global timer belongs to the already-sent request above. Processing - // this incoming request queues a distinct reciprocal, but does not send it. - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - - let reciprocal_rsn = *a.reconfigs.keys().find(|&&rsn| rsn != sent_rsn).unwrap(); - assert!(!reply.is_empty()); - - let premature_ack: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: reciprocal_rsn, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![3], - }); - a.handle_reconfig_param(&premature_ack, &mut vec![])?; - - let reset_complete = core::iter::from_fn(|| a.poll()) - .filter(|event| { - matches!( - event, - Event::Stream(StreamEvent::ResetComplete { id }) if *id == stream_id - ) - }) - .count(); - assert_eq!( - (a.reconfigs.contains_key(&reciprocal_rsn), reset_complete), - (true, 0), - "a timer running for another RSN must not make an unsent reciprocal acknowledgeable" - ); - Ok(()) -} - -#[test] -fn test_failed_generation_stays_quarantined_after_other_success() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - - a.pending_reset_completions.insert(stream_id); - a.pending_reset_completions.insert(stream_id); - a.reconfigs.insert(7, outgoing_reset(7, stream_id)); - a.reconfigs.insert(8, outgoing_reset(8, stream_id)); - - // The older generation completes, but the newer generation is denied. - // A success for the former cannot make the latter safe to reuse. - for (rsn, result) in [(7, ReconfigResult::SuccessPerformed), (8, ReconfigResult::Denied)] { - a.active_reconfig = Some(rsn); - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - } - - assert!(matches!( - a.open_stream(stream_id, PayloadProtocolIdentifier::Binary), - Err(Error::ErrStreamResetPending) - )); - Ok(()) -} - -#[test] -fn test_second_reconfig_request_stays_buffered_while_timer_runs() -> Result<()> { - let stream_id = 1; - let sent_rsn = 99; - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - insert_active_reset(&mut a, sent_rsn, 2); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - - // Processing the peer's request creates a reciprocal request while another - // local request is already in flight. RFC 6525 section 5.1.1 requires the - // reciprocal request to remain buffered until the running timer stops. - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - - let reciprocal_rsn = *a.reconfigs.keys().find(|&&rsn| rsn != sent_rsn).unwrap(); - a.control_queue.extend(reply); - - assert!(a.poll_transmit(Instant::now()).is_some()); - assert_eq!( - a.active_reconfig, - Some(sent_rsn), - "a second request must remain buffered while the first request's timer runs" - ); - assert!(a.reconfigs.contains_key(&reciprocal_rsn)); - assert_eq!(a.control_queue.len(), 1); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: sent_rsn, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - assert!(a.poll_transmit(Instant::now()).is_some()); - assert_eq!(a.active_reconfig, Some(reciprocal_rsn)); - assert!(a.control_queue.is_empty()); - Ok(()) -} - -#[test] -fn test_peer_recreated_quarantined_stream_is_not_writable() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - - // The peer may start its new incoming generation before our reciprocal - // outgoing reset is acknowledged. Reading that generation is safe, but - // sending with a freshly initialized SSN is not yet safe. - a.pending_reset_completions.insert(stream_id); - insert_active_reset(&mut a, 7, stream_id); - - assert!(a.get_or_create_stream(stream_id).is_some()); - assert!( - !a.stream(stream_id)?.is_writable(), - "a pending reciprocal reset must quarantine the outgoing direction" - ); - Ok(()) -} - -#[test] -fn test_pending_reset_blocks_existing_stream_writes() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - insert_active_reset(&mut a, 7, stream_id); - - assert!( - !a.stream(stream_id)?.is_writable(), - "new SSNs must not be assigned while an outgoing reset is pending" - ); - Ok(()) -} - -#[test] -fn test_reset_completion_does_not_reopen_finished_write_half() -> Result<()> { - let stream_id = 1; - let rsn = 7; - let mut a = Association::default(); - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - insert_active_reset(&mut a, rsn, stream_id); - - // Finishing the write half is permanent, including while a reset request - // temporarily makes the stream non-writable for protocol reasons. - a.stream(stream_id)?.finish()?; - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - assert!( - !a.stream(stream_id)?.is_writable(), - "reset completion must not undo Stream::finish()" - ); - Ok(()) -} - -#[test] -fn test_successful_outgoing_reset_restarts_stream_sequence_number() -> Result<()> { - let stream_id = 1; - let rsn = 7; - let mut a = Association::default(); - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - a.streams.get_mut(&stream_id).unwrap().sequence_number = 9; - insert_active_reset(&mut a, rsn, stream_id); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - assert_eq!( - a.streams.get(&stream_id).unwrap().sequence_number, - 0, - "RFC 6525 section 5.2.7 H4 requires the affected outgoing SSN to reset" - ); - Ok(()) -} - -#[test] -fn test_only_one_buffered_reconfig_is_sent_when_timer_is_idle() { - let mut a = Association { - state: AssociationState::Established, - ..Default::default() - }; - - for (rsn, stream_id) in [(7, 1), (8, 2)] { - insert_queued_reset(&mut a, rsn, stream_id); - } - assert!(a.timers.get(Timer::Reconfig).is_none()); - - assert!(a.poll_transmit(Instant::now()).is_some()); - assert_eq!(a.active_reconfig, Some(7)); - assert_eq!(a.control_queue.len(), 1); - assert!(a.reconfigs.contains_key(&8)); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: 7, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![]).unwrap(); - assert!(a.poll_transmit(Instant::now()).is_some()); - assert_eq!(a.active_reconfig, Some(8)); - assert!(a.control_queue.is_empty()); -} - -#[test] -fn test_close_discards_buffered_reconfig_requests() -> Result<()> { - let mut a = Association { - state: AssociationState::Established, - ..Default::default() - }; - insert_active_reset(&mut a, 7, 1); - insert_queued_reset(&mut a, 8, 2); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - - a.close()?; - - assert!( - a.poll_transmit(Instant::now()).is_none(), - "a closed association must not send a buffered stream-reset request" - ); - assert!(a.active_reconfig.is_none()); - assert!(a.reconfigs.is_empty()); - Ok(()) -} - -#[test] -fn test_in_progress_keeps_later_request_buffered() -> Result<()> { - let mut a = Association { - state: AssociationState::Established, - ..Default::default() - }; - - insert_active_reset(&mut a, 7, 1); - insert_queued_reset(&mut a, 8, 2); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: 7, - result: ReconfigResult::InProgress, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - assert!(a.reconfigs.contains_key(&7)); - - let _ = a.poll_transmit(Instant::now()); - assert_eq!(a.active_reconfig, Some(7)); - assert_eq!(a.control_queue.len(), 1); - Ok(()) -} - -#[test] -fn test_local_reset_stays_queued_while_reconfig_timer_runs() -> Result<()> { - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - ..Default::default() - }; - - insert_active_reset(&mut a, 7, 1); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - a.send_reset_request(2)?; - - let _ = a.poll_transmit(Instant::now()); - assert_eq!( - a.reconfigs.len(), - 1, - "a locally initiated reset must remain queued while another request is in flight" - ); - assert_eq!(a.pending_reset_streams.iter().copied().collect::>(), [2]); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: 7, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - assert!(a.poll_transmit(Instant::now()).is_some()); - assert_ne!(a.active_reconfig, Some(7)); - assert!(a.active_reconfig.is_some()); - assert!(a.pending_reset_streams.is_empty()); - Ok(()) -} - -#[test] -fn test_local_reset_does_not_overtake_pending_data() -> Result<()> { - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - ..Default::default() - }; - queue_inflight( - &mut a, - ChunkPayloadData { - tsn: 1, - user_data: Bytes::from_static(b"inflight"), - ..Default::default() - }, - ); - queue_pending( - &mut a, - ChunkPayloadData { - stream_identifier: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"pending"), - ..Default::default() - }, - ); - a.send_reset_request(1)?; - - let _ = a.poll_transmit(Instant::now()); - assert!(a.active_reconfig.is_none()); - assert!(a.reconfigs.is_empty()); - assert_eq!(a.pending_reset_streams.len(), 1); - Ok(()) -} - -#[test] -fn test_local_reset_is_not_blocked_by_unrelated_pending_data() -> Result<()> { - let reset_stream_id = 1; - let unrelated_stream_id = 2; - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 2, - cwnd: 0, - rwnd: 0, - mtu: 1400, - ..Default::default() - }; - queue_inflight( - &mut a, - ChunkPayloadData { - tsn: 1, - stream_identifier: unrelated_stream_id, - user_data: Bytes::from_static(b"inflight"), - ..Default::default() - }, - ); - queue_pending( - &mut a, - ChunkPayloadData { - stream_identifier: unrelated_stream_id, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"flow controlled"), - ..Default::default() - }, - ); - a.send_reset_request(reset_stream_id)?; - - let _ = a.gather_outbound(Instant::now()); - - assert!( - a.active_reconfig.is_some(), - "flow-controlled DATA on another stream must not starve this reset" - ); - assert!( - a.outbound_queue.pending_len() != 0, - "the test requires the unrelated DATA to remain flow controlled" - ); - Ok(()) -} - -#[test] -fn test_reset_sender_last_tsn_wraps_at_zero() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 0, - ..Default::default() - }; - a.send_reset_request(stream_id)?; - - let _ = a.gather_outbound(Instant::now()); - - let reset = a - .reconfigs - .get(&a.active_reconfig.unwrap()) - .unwrap() - .param_a - .as_ref() - .and_then(|param| param.as_any().downcast_ref::()) - .unwrap(); - assert_eq!( - reset.sender_last_tsn, - u32::MAX, - "the TSN preceding zero must wrap to u32::MAX" - ); - Ok(()) -} - -#[test] -fn test_reset_request_sequence_number_wraps() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - my_next_rsn: u32::MAX, - ..Default::default() - }; - a.send_reset_request(stream_id)?; - - let _ = a.gather_outbound(Instant::now()); - - assert_eq!(a.active_reconfig, Some(u32::MAX)); - assert_eq!( - a.my_next_rsn, 0, - "the re-configuration request sequence number must wrap" - ); - Ok(()) -} - -#[test] -fn test_local_reset_acknowledges_latest_peer_request_sequence() -> Result<()> { - let peer_rsn = 41; - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - ..Default::default() - }; - - let peer_request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: peer_rsn, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![], - }); - a.handle_reconfig_param(&peer_request, &mut vec![])?; - assert_eq!(a.max_completed_reconfig_rsn, Some(peer_rsn)); - - a.send_reset_request(1)?; - let _ = a.gather_outbound(Instant::now()); - - let reset = a - .reconfigs - .get(&a.active_reconfig.unwrap()) - .unwrap() - .param_a - .as_ref() - .and_then(|param| param.as_any().downcast_ref::()) - .unwrap(); - assert_eq!( - reset.reconfig_response_sequence_number, peer_rsn, - "RFC 6525 section 5.1.2 A4 requires the latest peer RSN in the response field" - ); - Ok(()) -} - -#[test] -fn test_reciprocal_reset_covers_preexisting_pending_data() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - cwnd: 1400, - rwnd: 1400, - mtu: 1400, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - queue_pending( - &mut a, - ChunkPayloadData { - stream_identifier: stream_id, - stream_sequence_number: 4, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"pending"), - ..Default::default() - }, - ); - - // Receiving the peer's outgoing reset creates a reciprocal outgoing reset. - // DATA accepted before that request must be assigned a TSN covered by the - // reciprocal request's Sender's Last Assigned TSN boundary. - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - a.control_queue.extend(reply); - - let _ = a.gather_outbound(Instant::now()); - - let data_tsn = a.outbound_queue.get(1).unwrap().tsn; - let reciprocal = a - .reconfigs - .get(&a.active_reconfig.unwrap()) - .unwrap() - .param_a - .as_ref() - .and_then(|param| param.as_any().downcast_ref::()) - .unwrap(); - assert!( - sna32gte(reciprocal.sender_last_tsn, data_tsn), - "the reciprocal reset boundary must cover DATA queued before the reset" - ); - Ok(()) -} - -#[test] -fn test_data_above_deferred_reset_boundary_waits_for_new_generation() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - peer_last_tsn: 0, - my_next_tsn: 1, - max_receive_buffer_size: 1024, - max_receive_message_size: 1024, - max_payload_size: 1200, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 1, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&request, &mut vec![])?; - assert!(a.reconfig_requests.contains_key(&7)); - - // TSN 2 belongs to the post-reset generation, but arrives while TSN 1 is - // still missing and the reset therefore remains InProgress. - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"new"), - ..Default::default() - })?; - - assert!( - a.poll().is_none(), - "post-reset DATA must not notify the old stream generation" - ); - assert!( - a.stream(stream_id)?.read()?.is_none(), - "post-reset DATA must not be readable before the reset boundary arrives" - ); - - // Once TSN 1 arrives, its payload remains readable as the last message of - // the old generation. Held TSN 2 is released only after that generation is - // drained, into a newly created generation whose SSN starts at zero. - a.handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"old"), - ..Default::default() - })?; - - let message = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(message.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - - let message = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(message.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"new"); - Ok(()) -} - -#[test] -fn test_reset_boundary_data_remains_readable_before_finished() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - peer_last_tsn: 0, - my_next_tsn: 1, - max_receive_buffer_size: 1024, - max_receive_message_size: 1024, - max_payload_size: 1200, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 1, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&request, &mut vec![])?; - - a.handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"last"), - ..Default::default() - })?; - - loop { - match a.poll() { - Some(Event::Stream(StreamEvent::Readable { id })) if id == stream_id => break, - Some(Event::Stream(StreamEvent::Finished { id })) if id == stream_id => { - panic!("Finished must not overtake readable boundary DATA") - } - Some(_) => {} - None => panic!("missing Readable event for boundary DATA"), - } - } - - assert!( - a.poll().is_none(), - "Finished must remain hidden until the readable boundary DATA is drained" - ); - - let message = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 4]; - assert_eq!(message.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"last"); - assert!(matches!( - core::iter::from_fn(|| a.poll()).find(|event| matches!( - event, - Event::Stream(StreamEvent::Finished { id }) if *id == stream_id - )), - Some(Event::Stream(StreamEvent::Finished { id })) if id == stream_id - )); - Ok(()) -} - -#[test] -fn test_successive_resets_preserve_each_unread_generation() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - peer_last_tsn: 0, - my_next_tsn: 1, - max_receive_buffer_size: 1024, - max_receive_message_size: 1024, - max_payload_size: 1200, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - let first_reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 1, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&first_reset, &mut vec![])?; - a.handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"gen-a"), - ..Default::default() - })?; - - // The successor arrives while generation A is still unread. - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"gen-b"), - ..Default::default() - })?; - let second_reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 2, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&second_reset, &mut vec![])?; - - // Model successful reciprocal handshakes for both reset generations. - a.emit_reset_complete([stream_id]); - a.emit_reset_complete([stream_id]); - - let first = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 5]; - assert_eq!(first.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"gen-a"); - - let mut finished = 0; - let mut reset_complete = 0; - while reset_complete == 0 { - match a.poll() { - Some(Event::Stream(StreamEvent::Finished { id })) if id == stream_id => finished += 1, - Some(Event::Stream(StreamEvent::ResetComplete { id })) if id == stream_id => { - reset_complete += 1; - } - Some(_) => {} - None => panic!("generation A terminal event was blocked by unread generation B"), - } - } - assert_eq!(finished, 1); - - assert!( - core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::Stream(StreamEvent::Readable { id }) if id == stream_id - )), - "generation B must advertise readability before its Finished event" - ); - - let second = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 5]; - assert_eq!(second.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"gen-b"); - assert!( - a.stream(stream_id).is_err(), - "generation B was also reset and must retire after it is drained" - ); - - while let Some(event) = a.poll() { - match event { - Event::Stream(StreamEvent::Finished { id }) if id == stream_id => finished += 1, - Event::Stream(StreamEvent::ResetComplete { id }) if id == stream_id => { - reset_complete += 1; - } - _ => {} - } - } - assert_eq!(finished, 2); - assert_eq!(reset_complete, 2); - Ok(()) -} - -fn association_with_retiring_boundary_data() -> Result { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - peer_last_tsn: 0, - my_next_tsn: 1, - max_receive_buffer_size: 1024, - max_receive_message_size: 1024, - max_payload_size: 1200, - use_forward_tsn: true, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 1, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - a.handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"old"), - ..Default::default() - })?; - Ok(a) -} - -fn assert_successor_ssn_one_is_readable(mut a: Association) -> Result<()> { - let stream_id = 1; - let old = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - - a.handle_data(&ChunkPayloadData { - tsn: 3, - stream_identifier: stream_id, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"new"), - ..Default::default() - })?; - let successor = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(successor.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"new"); - Ok(()) -} - -#[test] -fn test_forward_tsn_skip_is_applied_to_reset_successor() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - assert_successor_ssn_one_is_readable(a) -} - -#[test] -fn test_i_forward_tsn_skip_is_applied_to_reset_successor() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.handle_i_forward_tsn(&ChunkIForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkIForwardTsnStream { - identifier: 1, - unordered: false, - mid: 0, - }], - })?; - assert_successor_ssn_one_is_readable(a) -} - -#[test] -fn test_forward_tsn_during_in_progress_reset_applies_to_old_generation() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - peer_last_tsn: 0, - my_next_tsn: 1, - max_receive_buffer_size: 1024, - max_receive_message_size: 1024, - max_payload_size: 1200, - use_forward_tsn: true, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 1, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - - // The reset has not reached its TSN boundary yet, so this skip belongs to - // the old generation even though the association-level cumulative TSN - // advances beyond that boundary. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: stream_id, - sequence: 0, - }], - })?; - - a.handle_data(&ChunkPayloadData { - tsn: 3, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"new"), - ..Default::default() - })?; - let successor = a.stream(stream_id)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(successor.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"new"); - Ok(()) -} - -fn association_with_queued_second_reset() -> Result { - let mut a = association_with_retiring_boundary_data()?; - let second_reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 2, - stream_identifiers: vec![1], - }); - a.handle_reconfig_param(&second_reset, &mut vec![])?; - assert!(a.reconfig_requests.contains_key(&8)); - Ok(a) -} - -fn assert_generation_c_ssn_zero_is_readable(mut a: Association) -> Result<()> { - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"gen-c"), - ..Default::default() - })?; - let generation_c = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 5]; - assert_eq!(generation_c.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"gen-c"); - Ok(()) -} - -#[test] -fn test_forward_tsn_skip_is_scoped_to_queued_reset_generation() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_forward_tsn(&ChunkForwardTsn { - // TSN 2 is generation B's abandoned SSN 0. TSN 3 belongs to an - // unrelated stream, so the aggregate cumulative point cannot identify - // which stream generation the per-stream SSN describes. - new_cumulative_tsn: 3, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - assert_generation_c_ssn_zero_is_readable(a) -} - -#[test] -fn test_retransmitted_forward_tsn_stays_with_reset_generation() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - - // The first FORWARD-TSN advances through generation B's abandoned SSN 0 - // and lets its pending reset complete. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - assert!(!a.reconfig_requests.contains_key(&8)); - - // If the resulting SACK is lost, the sender can legitimately repeat the - // same stream skip while advancing over an unrelated abandoned TSN. The - // repeated entry still belongs to generation B, not the future tail. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 3, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - - assert_generation_c_ssn_zero_is_readable(a) -} - -fn assert_successor_ssn_one_after_reused_forward_ssn(mut a: Association) -> Result<()> { - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"gen-c"), - ..Default::default() - })?; - let generation_c = a - .stream(1)? - .read()? - .expect("generation C SSN 1 should follow its abandoned SSN 0"); - let mut payload = [0; 5]; - assert_eq!(generation_c.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"gen-c"); - Ok(()) -} - -#[test] -fn test_successor_forward_tsn_can_reuse_reset_ssn() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - for new_cumulative_tsn in [2, 3] { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - } - assert_successor_ssn_one_after_reused_forward_ssn(a) -} - -#[test] -fn test_successor_i_forward_tsn_can_reuse_reset_mid() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - for new_cumulative_tsn in [2, 3] { - a.handle_i_forward_tsn(&ChunkIForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkIForwardTsnStream { - identifier: 1, - unordered: false, - mid: 0, - }], - })?; - } - assert_successor_ssn_one_after_reused_forward_ssn(a) -} - -#[test] -fn test_repeated_old_forward_tsn_does_not_skip_later_successor_ssn() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - for new_cumulative_tsn in [2, 3] { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 1, - }], - })?; - } - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - - for (tsn, ssn, bytes) in [(4, 0, b"zero".as_slice()), (5, 1, b"one".as_slice())] { - a.handle_data(&ChunkPayloadData { - tsn, - stream_identifier: 1, - stream_sequence_number: ssn, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::copy_from_slice(bytes), - ..Default::default() - })?; - let message = a - .stream(1)? - .read()? - .expect("an old-generation repeat must not skip a live successor SSN"); - let mut payload = [0; 4]; - assert_eq!(message.read(&mut payload)?, bytes.len()); - assert_eq!(&payload[..bytes.len()], bytes); - } - Ok(()) -} - -#[test] -fn test_repeated_old_forward_tsn_preserves_partial_successor_above_cumulative() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: false, - user_data: Bytes::from_static(b"live-"), - ..Default::default() - })?; - - // TSN 3 is unrelated to this stream. Repeating generation B's skip must - // not discard generation C's fragment at TSN 4. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 3, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - a.handle_data(&ChunkPayloadData { - tsn: 5, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: false, - ending_fragment: true, - user_data: Bytes::from_static(b"data"), - ..Default::default() - })?; - - let message = a - .stream(1)? - .read()? - .expect("the successor fragments should still reassemble"); - let mut payload = [0; 9]; - assert_eq!(message.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"live-data"); - Ok(()) -} - -#[test] -fn test_deferred_forward_tsn_discards_partial_missing_pre_cumulative_tsn() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 4, - stream_identifiers: vec![1], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - - // B/SSN 0 is missing its beginning at TSN 2, while B/SSN 1 is complete. - for chunk in [ - ChunkPayloadData { - tsn: 3, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: false, - ending_fragment: true, - user_data: Bytes::from_static(b"orphan"), - ..Default::default() - }, - ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"next"), - ..Default::default() - }, - ] { - a.handle_data(&chunk)?; - } - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - - assert_eq!( - a.get_my_receiver_window_credit(), - a.max_receive_buffer_size - 3 - 4, - "the partial message missing TSN 2 must release its six bytes immediately" - ); - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - - let next = a - .stream(1)? - .read()? - .expect("discarding abandoned SSN 0 must unblock complete SSN 1"); - let mut payload = [0; 4]; - assert_eq!(next.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"next"); - Ok(()) -} - -#[test] -fn test_reordered_successor_waits_before_consuming_old_forward_tsn() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - for new_cumulative_tsn in [2, 3] { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - } - a.handle_data(&ChunkPayloadData { - tsn: 5, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert!( - a.stream(1)?.read()?.is_none(), - "SSN 1 must wait while SSN 0's post-FWD TSN is still missing" - ); - - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"zero"), - ..Default::default() - })?; - for expected in [b"zero".as_slice(), b"one".as_slice()] { - let message = a - .stream(1)? - .read()? - .expect("successor messages should become readable in SSN order"); - let mut payload = [0; 4]; - assert_eq!(message.read(&mut payload)?, expected.len()); - assert_eq!(&payload[..expected.len()], expected); - } - Ok(()) -} - -#[test] -fn test_reordered_successor_waits_before_consuming_repeated_old_forward_tsn() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - for new_cumulative_tsn in [2, 3] { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 1, - }], - })?; - } - a.handle_data(&ChunkPayloadData { - tsn: 5, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert!( - a.stream(1)?.read()?.is_none(), - "SSN 1 must wait while SSN 0's post-FWD TSN is still missing" - ); - - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"zero"), - ..Default::default() - })?; - for expected in [b"zero".as_slice(), b"one".as_slice()] { - let message = a - .stream(1)? - .read()? - .expect("successor messages should become readable in SSN order"); - let mut payload = [0; 4]; - assert_eq!(message.read(&mut payload)?, expected.len()); - assert_eq!(&payload[..expected.len()], expected); - } - Ok(()) -} - -#[test] -fn test_successor_forward_tsn_releases_covered_out_of_order_message() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - a.handle_data(&ChunkPayloadData { - tsn: 5, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - - // The sender did not receive the gap acknowledgement for TSN 5 and - // abandons both missing SSN 0 and the already-complete SSN 1. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 5, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 1, - }], - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - - let successor = a - .stream(1)? - .read()? - .expect("the successor skip must release the complete covered message"); - let mut payload = [0; 3]; - assert_eq!(successor.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"one"); - Ok(()) -} - -#[test] -fn test_cross_generation_forward_tsn_does_not_skip_uncovered_successor_ssn() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 1, - }], - })?; - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"zero"), - ..Default::default() - })?; - - // A lost SACK can make one FORWARD-TSN span old SSN 1 and successor SSN - // 0. The old maximum SSN must not also skip successor SSN 1. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 4, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 1, - }], - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - let zero = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 4]; - assert_eq!(zero.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"zero"); - - a.handle_data(&ChunkPayloadData { - tsn: 5, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - let one = a - .stream(1)? - .read()? - .expect("the successor SSN outside the covered TSN range must remain live"); - let mut payload = [0; 3]; - assert_eq!(one.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"one"); - Ok(()) -} - -#[test] -fn test_successor_forward_tsn_releases_covered_message_before_lost_tail() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - - // Successor SSN 0/TSN 3 and SSN 2/TSN 5 were both abandoned. The - // complete covered SSN 1 can be released before SSN 2 is observed. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 5, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 2, - }], - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - let one = a - .stream(1)? - .read()? - .expect("covered successor data must not wait for the lost final SSN"); - let mut payload = [0; 3]; - assert_eq!(one.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"one"); - Ok(()) -} - -#[test] -fn test_resolved_successor_prefix_releases_message_before_stale_tail() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 2, - }], - })?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 3, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 2, - }], - })?; - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - let one = a - .stream(1)? - .read()? - .expect("resolved successor data must not wait for the stale old tail"); - let mut payload = [0; 3]; - assert_eq!(one.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"one"); - Ok(()) -} - -fn assert_covered_partial_after_unaffected_anchor_is_discarded(last_ssn: u16) -> Result<()> { - let mut a = association_with_queued_second_reset()?; - for new_cumulative_tsn in [2, 3] { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: last_ssn, - }], - })?; - } - for chunk in [ - ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: false, - ending_fragment: true, - user_data: Bytes::from_static(b"orphan"), - ..Default::default() - }, - ChunkPayloadData { - tsn: 5, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"zero"), - ..Default::default() - }, - ] { - a.handle_data(&chunk)?; - } - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - let zero = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 4]; - assert_eq!(zero.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"zero"); - assert_eq!( - a.get_my_receiver_window_credit(), - a.max_receive_buffer_size, - "the covered partial message must release its receive-window credit" - ); - Ok(()) -} - -#[test] -fn test_full_forward_update_discards_covered_partial_after_anchor() -> Result<()> { - assert_covered_partial_after_unaffected_anchor_is_discarded(1) -} - -#[test] -fn test_partial_forward_update_discards_covered_partial_after_anchor() -> Result<()> { - assert_covered_partial_after_unaffected_anchor_is_discarded(2) -} - -#[test] -fn test_drained_generation_discards_retained_forward_suffix() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 5, - stream_identifiers: vec![1], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 5, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 2, - }], - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - let one = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(one.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"one"); - assert!( - a.deferred_forward_tsns - .get(&1) - .is_none_or(|updates| { updates.iter().all(|update| update.generation_boundary != Some(5)) }), - "a drained reset generation must discard its retained ambiguous suffix" - ); - Ok(()) -} - -#[test] -fn test_first_reset_discards_retained_tail_forward_suffix() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - a.handle_data(&ChunkPayloadData { - tsn: 4, - stream_identifier: 1, - stream_sequence_number: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"one"), - ..Default::default() - })?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 5, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 2, - }], - })?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - let one = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(one.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"one"); - assert!( - a.deferred_forward_tsns[&1] - .iter() - .any(|update| update.generation_boundary.is_none()) - ); - - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 9, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 5, - stream_identifiers: vec![1], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - assert!( - !a.deferred_forward_tsns.contains_key(&1), - "resetting a drained tail must discard its retained ambiguous suffix" - ); - Ok(()) -} - -#[test] -fn test_i_forward_tsn_skip_is_scoped_to_queued_reset_generation() -> Result<()> { - let mut a = association_with_queued_second_reset()?; - a.handle_i_forward_tsn(&ChunkIForwardTsn { - new_cumulative_tsn: 3, - streams: vec![ChunkIForwardTsnStream { - identifier: 1, - unordered: false, - mid: 0, - }], - })?; - assert_generation_c_ssn_zero_is_readable(a) -} - -fn assert_later_reset_claims_tail_forward_tsn(mut a: Association) -> Result<()> { - let second_reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 2, - stream_identifiers: vec![1], - }); - a.handle_reconfig_param(&second_reset, &mut vec![])?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - - a.handle_data(&ChunkPayloadData { - tsn: 3, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"gen-c"), - ..Default::default() - })?; - let generation_c = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 5]; - assert_eq!(generation_c.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"gen-c"); - Ok(()) -} - -#[test] -fn test_later_reset_claims_tail_forward_tsn_generation() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - assert_later_reset_claims_tail_forward_tsn(a) -} - -#[test] -fn test_later_reset_claims_tail_i_forward_tsn_generation() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.handle_i_forward_tsn(&ChunkIForwardTsn { - new_cumulative_tsn: 2, - streams: vec![ChunkIForwardTsnStream { - identifier: 1, - unordered: false, - mid: 0, - }], - })?; - assert_later_reset_claims_tail_forward_tsn(a) -} - -fn association_with_complete_deferred_successor() -> Result { - let mut a = association_with_retiring_boundary_data()?; - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"received"), - ..Default::default() - })?; - Ok(a) -} - -fn assert_received_message_survives_forward_tsn(mut a: Association) -> Result<()> { - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - - let received = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 8]; - assert_eq!(received.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"received"); - Ok(()) -} - -#[test] -fn test_forward_tsn_preserves_complete_deferred_message() -> Result<()> { - let mut a = association_with_complete_deferred_successor()?; - a.handle_forward_tsn(&ChunkForwardTsn { - // SSN 0 was received completely; only the following SSN 1 was - // abandoned. RFC 3758 requires the stranded complete message to be - // made available when the skip advances the ordered stream. - new_cumulative_tsn: 3, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 1, - }], - })?; - assert_received_message_survives_forward_tsn(a) -} - -#[test] -fn test_forward_tsn_preserves_out_of_order_complete_deferred_message() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - - // Generation B's complete SSN 0 arrives above a TSN gap, so it remains in - // both the association payload queue and the reset-generation holding map. - a.handle_data(&ChunkPayloadData { - tsn: 3, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"received"), - ..Default::default() - })?; - - // The sender may not have received the gap SACK before abandoning TSNs 2 - // and 3. Advancing the cumulative TSN must not erase a complete message - // that this receiver already holds for the successor generation. - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 3, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - - assert_received_message_survives_forward_tsn(a) -} - -#[test] -fn test_i_forward_tsn_preserves_complete_deferred_message() -> Result<()> { - let mut a = association_with_complete_deferred_successor()?; - a.handle_i_forward_tsn(&ChunkIForwardTsn { - new_cumulative_tsn: 3, - streams: vec![ChunkIForwardTsnStream { - identifier: 1, - unordered: false, - mid: 1, - }], - })?; - assert_received_message_survives_forward_tsn(a) -} - -fn association_with_deferred_unordered_fragment() -> Result { - let mut a = association_with_retiring_boundary_data()?; - a.streams.get_mut(&1).unwrap().unordered = true; - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 1, - unordered: true, - beginning_fragment: true, - ending_fragment: false, - user_data: Bytes::from_static(b"orphan"), - ..Default::default() - })?; - Ok(a) -} - -fn assert_abandoned_unordered_fragment_is_discarded(mut a: Association) -> Result<()> { - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - - assert_eq!( - a.streams - .get(&1) - .map(StreamState::get_num_bytes_in_reassembly_queue) - .unwrap_or_default(), - 0, - "an abandoned partial unordered message must not survive replay" - ); - assert_eq!(a.get_my_receiver_window_credit(), a.max_receive_buffer_size); - Ok(()) -} - -#[test] -fn test_forward_tsn_discards_deferred_unordered_fragment() -> Result<()> { - let mut a = association_with_deferred_unordered_fragment()?; - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 3, - streams: vec![], - })?; - assert_abandoned_unordered_fragment_is_discarded(a) -} - -#[test] -fn test_i_forward_tsn_discards_deferred_unordered_fragment() -> Result<()> { - let mut a = association_with_deferred_unordered_fragment()?; - a.handle_i_forward_tsn(&ChunkIForwardTsn { - new_cumulative_tsn: 3, - streams: vec![ChunkIForwardTsnStream { - identifier: 1, - unordered: true, - mid: 0, - }], - })?; - assert_abandoned_unordered_fragment_is_discarded(a) -} - -#[test] -fn test_forward_tsn_releases_abandoned_deferred_fragment_credit_immediately() -> Result<()> { - let mut a = association_with_deferred_unordered_fragment()?; - let old_generation_bytes = a.streams.get(&1).unwrap().get_num_bytes_in_reassembly_queue() as u32; - - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: 3, - streams: vec![], - })?; - - assert_eq!( - a.get_my_receiver_window_credit(), - a.max_receive_buffer_size - old_generation_bytes, - "abandoned successor fragments must not hold receive-window credit until the old generation drains" - ); - Ok(()) -} - -#[test] -fn test_deferred_unordered_forward_tsn_updates_are_coalesced() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.streams.get_mut(&1).unwrap().unordered = true; - - for new_cumulative_tsn in 2..=9 { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![], - })?; - } - - let updates = a.deferred_forward_tsns.get(&1).unwrap(); - assert_eq!( - updates.len(), - 1, - "newer unordered cumulative TSNs supersede older updates for the same generation" - ); - assert!(matches!( - updates.front(), - Some(DeferredForwardTsn { - kind: DeferredForwardTsnKind::Unordered { new_cumulative_tsn: 9 }, - .. - }) - )); - Ok(()) -} - -#[test] -fn test_deferred_tail_ordered_forward_tsn_duplicates_are_coalesced() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - for new_cumulative_tsn in 2..=9 { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: 0, - }], - })?; - } - - let ordered: Vec<_> = a.deferred_forward_tsns[&1] - .iter() - .filter(|update| { - update.generation_boundary.is_none() && matches!(update.kind, DeferredForwardTsnKind::Ordered { .. }) - }) - .collect(); - assert_eq!( - ordered.len(), - 1, - "lost-SACK repeats for an ambiguous tail SSN should coalesce" - ); - Ok(()) -} - -#[test] -fn test_deferred_bounded_ordered_forward_tsn_updates_are_coalesced() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 10, - stream_identifiers: vec![1], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - - for new_cumulative_tsn in 2..=9 { - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 1, - sequence: (new_cumulative_tsn - 2) as u16, - }], - })?; - } - - let ordered: Vec<_> = a.deferred_forward_tsns[&1] - .iter() - .filter(|update| { - update.generation_boundary == Some(10) && matches!(update.kind, DeferredForwardTsnKind::Ordered { .. }) - }) - .collect(); - assert_eq!( - ordered.len(), - 1, - "a newer ordered skip supersedes older skips for the same reset boundary" - ); - assert!(matches!( - ordered[0].kind, - DeferredForwardTsnKind::Ordered { last_ssn: 7, .. } - )); - Ok(()) -} - -#[test] -fn test_unread_retiring_stream_does_not_block_unrelated_events() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - assert!(a.create_stream(2, false, PayloadProtocolIdentifier::Binary).is_some()); - - assert!( - core::iter::from_fn(|| a.poll()).any(|event| matches!(event, Event::Stream(StreamEvent::Readable { id: 1 }))) - ); - assert!(a.poll().is_none(), "stream 1 Finished should still wait"); - - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 2, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"other"), - ..Default::default() - })?; - - assert!(matches!(a.poll(), Some(Event::DatagramReceived))); - assert!(matches!(a.poll(), Some(Event::Stream(StreamEvent::Readable { id: 2 })))); - Ok(()) -} - -#[test] -fn test_stop_discards_unread_retiring_data_and_unblocks_finished() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - assert!( - core::iter::from_fn(|| a.poll()).any(|event| matches!(event, Event::Stream(StreamEvent::Readable { id: 1 }))) - ); - assert!(a.poll().is_none(), "Finished should wait for old DATA"); - - a.stream(1)?.stop()?; - assert!(matches!(a.poll(), Some(Event::Stream(StreamEvent::Finished { id: 1 })))); - Ok(()) -} - -#[test] -fn test_stop_during_retirement_does_not_queue_duplicate_reset() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - assert_eq!(a.reconfigs.len(), 1, "peer reset should queue one reciprocal"); - assert!(a.pending_reset_streams.is_empty()); - - a.stream(1)?.stop()?; - - assert!( - a.pending_reset_streams.is_empty(), - "the reciprocal already resets this outgoing stream" - ); - assert_eq!(a.reconfigs.len(), 1); - Ok(()) -} - -fn assert_shutdown_during_retirement_allows_reuse(close: bool) -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - if close { - a.stream(1)?.close()?; - } else { - a.stream(1)?.stop()?; - } - - let rsn = *a.reconfigs.keys().next().unwrap(); - a.active_reconfig = Some(rsn); - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - assert!( - !a.streams.contains_key(&1), - "a completed reciprocal reset must remove the locally shut down stream" - ); - assert!( - a.open_stream(1, PayloadProtocolIdentifier::Binary).is_ok(), - "ResetComplete must make the retired stream id reusable" - ); - Ok(()) -} - -#[test] -fn test_stop_during_retirement_allows_reuse_after_reset_complete() -> Result<()> { - assert_shutdown_during_retirement_allows_reuse(false) -} - -#[test] -fn test_close_during_retirement_allows_reuse_after_reset_complete() -> Result<()> { - assert_shutdown_during_retirement_allows_reuse(true) -} - -fn assert_reset_complete_before_shutdown_allows_reuse(close: bool) -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - let rsn = *a.reconfigs.keys().next().unwrap(); - a.active_reconfig = Some(rsn); - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: rsn, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - if close { - a.stream(1)?.close()?; - } else { - a.stream(1)?.stop()?; - } - - assert!( - a.pending_reset_streams.is_empty() && a.reconfigs.is_empty(), - "shutting down a completed retiring stream must not queue a duplicate reset" - ); - assert!( - !a.streams.contains_key(&1), - "discarding the retired generation after ResetComplete must remove the stream" - ); - assert!( - a.open_stream(1, PayloadProtocolIdentifier::Binary).is_ok(), - "the completed stream id should be immediately reusable" - ); - Ok(()) -} - -#[test] -fn test_reset_complete_before_stop_allows_reuse() -> Result<()> { - assert_reset_complete_before_shutdown_allows_reuse(false) -} - -#[test] -fn test_reset_complete_before_close_allows_reuse() -> Result<()> { - assert_reset_complete_before_shutdown_allows_reuse(true) -} - -#[test] -fn test_stop_does_not_reopen_read_half_on_deferred_successor() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"successor"), - ..Default::default() - })?; - - let mut stream = a.stream(1)?; - stream.stop()?; - assert_eq!(stream.read().unwrap_err(), Error::ErrStreamClosed); - Ok(()) -} - -#[test] -fn test_stop_discards_deferred_successor_bytes_and_notifications() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - while a.poll().is_some() {} - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"successor"), - ..Default::default() - })?; - - a.stream(1)?.stop()?; - - assert_eq!( - a.streams.get(&1).unwrap().get_num_bytes_in_reassembly_queue(), - 0, - "stop must not strand bytes in a write-only successor" - ); - assert_eq!(a.get_my_receiver_window_credit(), a.max_receive_buffer_size); - assert!( - !core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::Stream(StreamEvent::Opened { id } | StreamEvent::Readable { id }) if id == 1 - )), - "stop must not advertise an unreadable successor" - ); - Ok(()) -} - -#[test] -fn test_finish_remains_closed_across_deferred_successor() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"successor"), - ..Default::default() - })?; - a.stream(1)?.finish()?; - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - assert_eq!(a.streams.get(&1).unwrap().state, RecvSendState::Readable); - - let successor = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 9]; - assert_eq!(successor.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"successor"); - Ok(()) -} - -#[test] -fn test_close_remains_closed_across_deferred_successor() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"successor"), - ..Default::default() - })?; - - a.stream(1)?.close()?; - - let successor = a.streams.get(&1).unwrap(); - assert_eq!(successor.state, RecvSendState::Closed); - assert_eq!(successor.get_num_bytes_in_reassembly_queue(), 0); - assert_eq!(a.get_my_receiver_window_credit(), a.max_receive_buffer_size); - Ok(()) -} - -#[test] -fn test_duplicate_stream_ids_retire_only_one_generation() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - peer_last_tsn: 0, - my_next_tsn: 1, - max_receive_buffer_size: 1024, - max_receive_message_size: 1024, - max_payload_size: 1200, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - a.handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"old"), - ..Default::default() - })?; - - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 1, - stream_identifiers: vec![stream_id, stream_id], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - - assert_eq!(a.retiring_streams.get(&stream_id).unwrap().len(), 1); - assert_eq!(a.pending_reset_completions.0.get(&stream_id), Some(&1)); - assert_eq!( - a.reconfigs - .values() - .flat_map(Association::reconfig_stream_ids) - .collect::>(), - vec![stream_id] - ); - Ok(()) -} - -#[test] -fn test_reconfig_rejects_two_outgoing_resets_without_mutation() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - let boundaries_before = a.retiring_streams.get(&1).unwrap().len(); - let completions_before = a.pending_reset_completions.0.get(&1).copied(); - let reconfigs_before = a.reconfigs.len(); - - let reconfig = ChunkReconfig { - param_a: Some(Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 8, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![1], - })), - param_b: Some(Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 9, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![1], - })), - }; - let packet = a.create_packet(vec![Box::new(reconfig)]); - let result = a.handle_chunk(&packet, &packet.chunks[0], Instant::now()); - - assert!(result.is_err(), "two Outgoing Reset parameters are invalid"); - assert_eq!(a.retiring_streams.get(&1).unwrap().len(), boundaries_before); - assert_eq!(a.pending_reset_completions.0.get(&1).copied(), completions_before); - assert_eq!(a.reconfigs.len(), reconfigs_before); - Ok(()) -} - -#[test] -fn test_stop_before_reset_boundary_does_not_leave_finished_blocked() -> Result<()> { - let stream_id = 1; - let mut a = Association { - state: AssociationState::Established, - peer_last_tsn: 0, - my_next_tsn: 1, - max_receive_buffer_size: 1024, - max_receive_message_size: 1024, - max_payload_size: 1200, - ..Default::default() - }; - for id in [stream_id, 2] { - assert!(a.create_stream(id, false, PayloadProtocolIdentifier::Binary).is_some()); - } - - // TSN 2 is readable but cannot advance the cumulative point past missing - // TSN 1, leaving time for the application to stop the read half. - a.handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: stream_id, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"discard"), - ..Default::default() - })?; - let reset: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: 2, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&reset, &mut vec![])?; - a.stream(stream_id)?.stop()?; - - a.handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: 2, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"gap"), - ..Default::default() - })?; - - assert!(a.stream(stream_id).is_err()); - assert!( - core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::Stream(StreamEvent::Finished { id }) if id == stream_id - )), - "a stopped read half cannot be left waiting for an impossible drain" - ); - Ok(()) -} - -#[test] -fn test_oversized_deferred_successor_is_rejected_before_old_read() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.max_receive_message_size = 3; - - let error = a - .handle_data(&ChunkPayloadData { - tsn: 2, - stream_identifier: 1, - stream_sequence_number: 0, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"too-big"), - ..Default::default() - }) - .unwrap_err(); - assert_eq!(error, Error::ErrInboundPacketTooLarge); - - let old = a.stream(1)?.read()?.unwrap(); - let mut payload = [0; 3]; - assert_eq!(old.read(&mut payload)?, payload.len()); - assert_eq!(&payload, b"old"); - Ok(()) -} - -#[test] -fn test_future_peer_reconfig_sequence_is_rejected() -> Result<()> { - let stream_id = 1; - let mut a = Association { - peer_last_tsn: 0, - peer_last_reconfig_rsn: 40, - peer_reconfig_rsn_initialized: true, - my_next_tsn: 1, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - let future: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 42, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&future, &mut reply)?; - - assert_eq!( - reconfig_response_result(&reply, 42), - Some(ReconfigResult::ErrorBadSequenceNumber) - ); - assert_eq!(a.peer_last_reconfig_rsn, 40); - assert!(a.max_completed_reconfig_rsn.is_none()); - assert!(a.streams.contains_key(&stream_id)); - - let expected: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 41, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - a.handle_reconfig_param(&expected, &mut vec![])?; - assert!(!a.streams.contains_key(&stream_id)); - assert_eq!(a.max_completed_reconfig_rsn, Some(41)); - Ok(()) -} - -#[test] -fn test_peer_reconfig_sequence_accepts_wrap_to_zero() -> Result<()> { - let stream_id = 1; - let mut a = Association { - peer_last_tsn: 0, - peer_last_reconfig_rsn: u32::MAX, - peer_reconfig_rsn_initialized: true, - my_next_tsn: 1, - ..Default::default() - }; - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 0, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![stream_id], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - - assert_ne!( - reconfig_response_result(&reply, 0), - Some(ReconfigResult::ErrorBadSequenceNumber) - ); - assert_eq!(a.peer_last_reconfig_rsn, 0); - assert_eq!(a.max_completed_reconfig_rsn, Some(0)); - assert!(!a.streams.contains_key(&stream_id)); - Ok(()) -} - -#[test] -fn test_empty_reset_stream_list_resets_all_streams() -> Result<()> { - let mut a = Association { - my_next_tsn: 1, - ..Default::default() - }; - for stream_id in [1, 2] { - assert!( - a.create_stream(stream_id, false, PayloadProtocolIdentifier::Binary) - .is_some() - ); - } - - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - - assert!(a.streams.is_empty(), "an omitted stream list means all streams"); - let reciprocal_ids = a - .reconfigs - .values() - .next() - .map(Association::reconfig_stream_ids) - .unwrap_or_default(); - assert!(reciprocal_ids.is_empty(), "reset-all must remain compact on the wire"); - let mut completion_ids = a.reconfig_reset_streams.values().next().cloned().unwrap_or_default(); - completion_ids.sort_unstable(); - assert_eq!(completion_ids, vec![1, 2]); - Ok(()) -} - -#[test] -fn test_reset_all_reciprocal_fits_reconfig_chunk_length() -> Result<()> { - let mut a = Association { - my_next_tsn: 1, - ..Default::default() - }; - for stream_id in 0..32_758u32 { - assert!( - a.create_stream(stream_id as StreamId, false, PayloadProtocolIdentifier::Binary,) - .is_some() - ); - } - - let request: Box = Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: 7, - reconfig_response_sequence_number: u32::MAX, - sender_last_tsn: a.peer_last_tsn, - stream_identifiers: vec![], - }); - let mut reply = vec![]; - a.handle_reconfig_param(&request, &mut reply)?; - - for packet in reply { - packet.marshal()?; - } - Ok(()) -} - -#[test] -fn test_blocked_reconfig_does_not_allow_later_rsn_to_overtake() { - let mut a = Association { - state: AssociationState::Established, - my_next_tsn: 1, - cwnd: 0, - rwnd: 0, - mtu: 1400, - ..Default::default() - }; - queue_inflight( - &mut a, - ChunkPayloadData { - tsn: 0, - stream_identifier: 2, - user_data: Bytes::from_static(b"inflight"), - ..Default::default() - }, - ); - queue_pending( - &mut a, - ChunkPayloadData { - stream_identifier: 1, - beginning_fragment: true, - ending_fragment: true, - user_data: Bytes::from_static(b"pending"), - ..Default::default() - }, - ); - insert_queued_reset(&mut a, 7, 1); - insert_queued_reset(&mut a, 8, 2); - - let _ = a.gather_outbound(Instant::now()); - assert!( - a.active_reconfig.is_none(), - "RSN 8 must not overtake RSN 7 while RSN 7 waits for its DATA boundary" - ); - assert_eq!(a.control_queue.len(), 2); - - a.cwnd = 1400; - a.rwnd = 1400; - let _ = a.gather_outbound(Instant::now()); - assert_eq!(a.active_reconfig, Some(7)); - assert_eq!(a.control_queue.len(), 1); -} - -#[test] -fn test_retransmission_does_not_send_buffered_reconfigs() { - let mut a = Association { - state: AssociationState::Established, - ..Default::default() - }; - - insert_active_reset(&mut a, 7, 1); - insert_queued_reset(&mut a, 8, 2); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - a.will_retransmit_reconfig = true; - - let (packets, _) = a.gather_outbound(Instant::now()); - assert_eq!( - packets.len(), - 1, - "retransmission must include only the request associated with the running timer" - ); -} - -fn association_with_inflight_data(cumulative_tsn_ack_point: u32, now: Instant) -> Association { - let mut a = Association { - state: AssociationState::Established, - cumulative_tsn_ack_point, - advanced_peer_tsn_ack_point: cumulative_tsn_ack_point, - my_next_tsn: cumulative_tsn_ack_point.wrapping_add(4), - cwnd: 1400, - rwnd: 1400, - mtu: 1400, - ..Default::default() - }; - - for stream_sequence_number in 0..3 { - queue_inflight( - &mut a, - ChunkPayloadData { - tsn: cumulative_tsn_ack_point.wrapping_add(u32::from(stream_sequence_number) + 1), - stream_identifier: 1, - stream_sequence_number, - beginning_fragment: true, - ending_fragment: true, - payload_type: PayloadProtocolIdentifier::Binary, - user_data: Bytes::from_static(b"payload"), - nsent: 1, - since: Some(now), - ..Default::default() - }, - ); - let tsn = cumulative_tsn_ack_point.wrapping_add(u32::from(stream_sequence_number) + 1); - a.outbound_queue.get_mut(tsn).unwrap().since = Some(now); - } - - a -} - -fn assert_retransmitted_packet(packet: &Packet, expected_tsns: &[u32]) { - assert_eq!(packet.chunks.len(), expected_tsns.len()); - for (chunk, expected_tsn) in packet.chunks.iter().zip(expected_tsns) { - let data = chunk.as_any().downcast_ref::().unwrap(); - assert_eq!(data.tsn, *expected_tsn); - assert_eq!(data.user_data, Bytes::from_static(b"payload")); - } -} - -#[test] -fn test_data_retransmission_wraps_tsn() -> Result<()> { - let now = Instant::now(); - for cumulative_tsn in [10, u32::MAX - 1, u32::MAX] { - let mut a = association_with_inflight_data(cumulative_tsn, now); - let acked_tsn = cumulative_tsn.wrapping_add(2); - a.outbound_queue.mark_as_acked(acked_tsn); - a.on_retransmission_timeout(Timer::T3RTX, 1); - - let packets = a.get_data_packets_to_retransmit(now); - assert_eq!(packets.len(), 1); - let packet = Packet::unmarshal(&packets[0].marshal()?)?; - let retransmitted_tsns = [cumulative_tsn.wrapping_add(1), cumulative_tsn.wrapping_add(3)]; - assert_retransmitted_packet(&packet, &retransmitted_tsns); - for tsn in retransmitted_tsns { - let chunk = a.outbound_queue.get(tsn).unwrap(); - assert!(!chunk.retransmit); - assert_eq!(chunk.nsent, 2); - } - assert_eq!(a.outbound_queue.get(acked_tsn).unwrap().nsent, 1); - assert!(a.get_data_packets_to_retransmit(now).is_empty()); - } - Ok(()) -} - -#[test] -fn test_poll_transmit_at_tsn_wraparound() { - let mut a = Association { - state: AssociationState::Established, - cumulative_tsn_ack_point: u32::MAX, - advanced_peer_tsn_ack_point: u32::MAX, - ..Default::default() - }; - - assert!(a.poll_transmit(Instant::now()).is_none()); -} - -#[test] -fn test_zero_window_probe_wraps_tsn() -> Result<()> { - let now = Instant::now(); - for cumulative_tsn in [u32::MAX - 1, u32::MAX] { - let mut a = association_with_inflight_data(cumulative_tsn, now); - a.rwnd = 0; - a.on_retransmission_timeout(Timer::T3RTX, 1); - - let packets = a.get_data_packets_to_retransmit(now); - assert_eq!(packets.len(), 1); - assert_retransmitted_packet(&packets[0], &[cumulative_tsn.wrapping_add(1)]); - for offset in [2, 3] { - let chunk = a.outbound_queue.get(cumulative_tsn.wrapping_add(offset)).unwrap(); - assert!(chunk.retransmit); - assert_eq!(chunk.nsent, 1); - } - assert!(a.get_data_packets_to_retransmit(now).is_empty()); - } - Ok(()) -} - -#[test] -fn test_fast_retransmission_wraps_tsn() -> Result<()> { - let now = Instant::now(); - for cumulative_tsn in [10, u32::MAX - 1, u32::MAX] { - let mut a = association_with_inflight_data(cumulative_tsn, now); - let acked_tsn = cumulative_tsn.wrapping_add(2); - a.outbound_queue.mark_as_acked(acked_tsn); - let retransmitted_tsns = [cumulative_tsn.wrapping_add(1), cumulative_tsn.wrapping_add(3)]; - for tsn in retransmitted_tsns { - a.outbound_queue.get_mut(tsn).unwrap().miss_indicator = 3; - } - a.will_retransmit_fast = true; - - let packets = a.gather_outbound_fast_retransmission_packets(vec![], now); - assert_eq!(packets.len(), 1); - assert_retransmitted_packet(&Packet::unmarshal(&packets[0])?, &retransmitted_tsns); - for tsn in retransmitted_tsns { - assert_eq!(a.outbound_queue.get(tsn).unwrap().nsent, 2); - } - assert_eq!(a.outbound_queue.get(acked_tsn).unwrap().nsent, 1); - assert!(!a.will_retransmit_fast); - assert_eq!(a.stats.get_num_fast_retrans(), 2); - } - Ok(()) -} - -#[test] -fn test_cumulative_sack_wraps_tsn() -> Result<()> { - let now = Instant::now(); - for cumulative_tsn in [10, u32::MAX - 1, u32::MAX] { - let mut a = association_with_inflight_data(cumulative_tsn, now); - a.timers.start(Timer::T3RTX, now, a.rto_mgr.get_rto()); - let ack_tsn = cumulative_tsn.wrapping_add(2); - let (bytes_acked, htna) = a.process_selective_ack( - &ChunkSelectiveAck { - cumulative_tsn_ack: ack_tsn, - ..Default::default() - }, - now, - )?; - - assert_eq!(bytes_acked, HashMap::from([(1, 14)])); - assert_eq!(htna, ack_tsn); - assert_eq!(a.outbound_queue.inflight_len(), 1); - assert!(a.outbound_queue.get(cumulative_tsn.wrapping_add(3)).is_some()); - assert!(a.timers.get(Timer::T3RTX).is_none()); - } - Ok(()) -} - -#[test] -fn test_gap_sack_wraps_tsn() -> Result<()> { - let now = Instant::now(); - for cumulative_tsn in [10, u32::MAX - 1, u32::MAX] { - let mut sender = association_with_inflight_data(cumulative_tsn, now); - let mut receiver = Association { - peer_last_tsn: cumulative_tsn, - ..Default::default() - }; - for offset in [2, 3] { - let data = sender - .outbound_queue - .get(cumulative_tsn.wrapping_add(offset)) - .unwrap() - .clone(); - assert!(receiver.payload_queue.push(data, cumulative_tsn)); - } - let sack = receiver.create_selective_ack_chunk(); - let (bytes_acked, htna) = sender.process_selective_ack(&sack, now)?; - - assert_eq!(bytes_acked, HashMap::from([(1, 14)])); - assert_eq!(htna, cumulative_tsn.wrapping_add(3)); - assert_eq!(sender.outbound_queue.inflight_bytes(), 7); - for offset in [1, 2, 3] { - let data = sender.outbound_queue.get(cumulative_tsn.wrapping_add(offset)).unwrap(); - assert_eq!(data.acked, offset != 1); - } - } - Ok(()) -} - -#[test] -fn test_fast_recovery_wraps_tsn() -> Result<()> { - let now = Instant::now(); - for cumulative_tsn in [10, u32::MAX - 1, u32::MAX] { - for in_fast_recovery in [false, true] { - let mut a = association_with_inflight_data(cumulative_tsn, now); - a.in_fast_recovery = in_fast_recovery; - let htna = cumulative_tsn.wrapping_add(3); - a.fast_recover_exit_point = htna; - a.outbound_queue.mark_as_acked(htna); - for offset in [1, 2] { - a.outbound_queue - .get_mut(cumulative_tsn.wrapping_add(offset)) - .unwrap() - .miss_indicator = 2; - } - - a.process_fast_retransmission(cumulative_tsn, htna, true)?; - - assert!(a.in_fast_recovery); - assert!(a.will_retransmit_fast); - assert_eq!(a.fast_recover_exit_point, htna); - for offset in [1, 2] { - let chunk = a.outbound_queue.get(cumulative_tsn.wrapping_add(offset)).unwrap(); - assert_eq!(chunk.miss_indicator, 3); - } - assert_eq!(a.outbound_queue.get(htna).unwrap().miss_indicator, 0); - } - } - Ok(()) -} - -#[test] -fn test_forward_tsn_wraparound() -> Result<()> { - let now = Instant::now(); - for cumulative_tsn in [10, u32::MAX - 1, u32::MAX] { - for from_timeout in [false, true] { - let mut a = association_with_inflight_data(cumulative_tsn, now); - a.use_forward_tsn = true; - for offset in [1, 2] { - a.outbound_queue - .get_mut(cumulative_tsn.wrapping_add(offset)) - .unwrap() - .abandoned = true; - } - - if from_timeout { - a.on_retransmission_timeout(Timer::T3RTX, 1); - } else { - a.handle_sack( - &ChunkSelectiveAck { - cumulative_tsn_ack: cumulative_tsn, - advertised_receiver_window_credit: 1400, - ..Default::default() - }, - now, - )?; - } - - assert_eq!(a.advanced_peer_tsn_ack_point, cumulative_tsn.wrapping_add(2)); - assert!(a.will_send_forward_tsn); - let packets = a.gather_outbound_forward_tsn_packets(vec![]); - assert_eq!(packets.len(), 1); - let packet = Packet::unmarshal(&packets[0])?; - assert_eq!(packet.chunks.len(), 1); - let forward = packet.chunks[0].as_any().downcast_ref::().unwrap(); - assert_eq!(forward.new_cumulative_tsn, cumulative_tsn.wrapping_add(2)); - assert_eq!(forward.streams.len(), 1); - assert_eq!(forward.streams[0].identifier, 1); - assert_eq!(forward.streams[0].sequence, 1); - assert!(!a.will_send_forward_tsn); - } - } - Ok(()) -} - -#[test] -fn test_older_completion_does_not_make_newer_generation_writable() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - - a.pending_reset_completions.insert(stream_id); - a.pending_reset_completions.insert(stream_id); - insert_active_reset(&mut a, 7, stream_id); - insert_queued_reset(&mut a, 8, stream_id); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - - assert!(a.get_or_create_stream(stream_id).is_some()); - assert!(!a.stream(stream_id)?.is_writable()); - - let response: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: 7, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&response, &mut vec![])?; - - assert!(a.reconfigs.contains_key(&8)); - assert!( - !a.stream(stream_id)?.is_writable(), - "an older success cannot release the newer generation's outgoing quarantine" - ); - Ok(()) -} - -#[test] -fn test_stale_completion_does_not_override_newer_denial() -> Result<()> { - let stream_id = 1; - let mut a = Association::default(); - - a.pending_reset_completions.insert(stream_id); - insert_active_reset(&mut a, 7, stream_id); - - let success: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: 7, - result: ReconfigResult::SuccessPerformed, - }); - a.handle_reconfig_param(&success, &mut vec![])?; - - // Before the application polls generation 7's completion, the peer opens - // and uses generation 8, then resets it. Its nonzero outgoing sequence - // means a denied reciprocal reset must quarantine the id. - assert!(a.get_or_create_stream(stream_id).is_some()); - a.streams.get_mut(&stream_id).unwrap().sequence_number = 1; - a.unregister_stream(stream_id, true); - insert_active_reset(&mut a, 8, stream_id); - a.timers.start(Timer::Reconfig, Instant::now(), a.rto_mgr.get_rto()); - - let denied: Box = Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: 8, - result: ReconfigResult::Denied, - }); - a.handle_reconfig_param(&denied, &mut vec![])?; - - // Polling the stale completion must not resurrect reuse permission after - // generation 8 has already failed. - assert!(matches!( - a.poll(), - Some(Event::Stream(StreamEvent::ResetComplete { id })) if id == stream_id - )); - - assert!(matches!( - a.open_stream(stream_id, PayloadProtocolIdentifier::Binary), - Err(Error::ErrStreamResetPending) - )); - Ok(()) -} - -#[test] -fn test_create_forward_tsn_forward_one_abandoned() -> Result<()> { - let mut a = Association { - cumulative_tsn_ack_point: 9, - advanced_peer_tsn_ack_point: 10, - ..Default::default() - }; - - queue_inflight( - &mut a, - ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: 10, - stream_identifier: 1, - stream_sequence_number: 2, - user_data: Bytes::from_static(b"ABC"), - nsent: 1, - ..Default::default() - }, - ); - - a.outbound_queue.abandon(10, &mut a.my_next_tsn).unwrap(); - - let fwdtsn = a.create_forward_tsn(); - - assert_eq!(10, fwdtsn.new_cumulative_tsn, "should be able to serialize"); - assert_eq!(1, fwdtsn.streams.len(), "there should be one stream"); - assert_eq!(1, fwdtsn.streams[0].identifier, "si should be 1"); - assert_eq!(2, fwdtsn.streams[0].sequence, "ssn should be 2"); - - Ok(()) -} - -#[test] -fn test_create_forward_tsn_forward_two_abandoned_with_the_same_si() -> Result<()> { - let mut a = Association { - cumulative_tsn_ack_point: 9, - advanced_peer_tsn_ack_point: 12, - ..Default::default() - }; - - queue_inflight( - &mut a, - ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: 10, - stream_identifier: 1, - stream_sequence_number: 2, - user_data: Bytes::from_static(b"ABC"), - nsent: 1, - ..Default::default() - }, - ); - queue_inflight( - &mut a, - ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: 11, - stream_identifier: 1, - stream_sequence_number: 3, - user_data: Bytes::from_static(b"DEF"), - nsent: 1, - ..Default::default() - }, - ); - queue_inflight( - &mut a, - ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: 12, - stream_identifier: 2, - stream_sequence_number: 1, - user_data: Bytes::from_static(b"123"), - nsent: 1, - ..Default::default() - }, - ); - - a.outbound_queue.abandon(10, &mut a.my_next_tsn).unwrap(); - a.outbound_queue.abandon(11, &mut a.my_next_tsn).unwrap(); - a.outbound_queue.abandon(12, &mut a.my_next_tsn).unwrap(); - - let fwdtsn = a.create_forward_tsn(); - - assert_eq!(12, fwdtsn.new_cumulative_tsn, "should be able to serialize"); - assert_eq!(2, fwdtsn.streams.len(), "there should be two stream"); - - let mut si1ok = false; - let mut si2ok = false; - for s in &fwdtsn.streams { - match s.identifier { - 1 => { - assert_eq!(3, s.sequence, "ssn should be 3"); - si1ok = true; - } - 2 => { - assert_eq!(1, s.sequence, "ssn should be 1"); - si2ok = true; - } - _ => panic!("unexpected stream indentifier"), - } - } - assert!(si1ok, "si=1 should be present"); - assert!(si2ok, "si=2 should be present"); - - Ok(()) -} - -#[test] -fn test_handle_forward_tsn_forward_3unreceived_chunks() -> Result<()> { - let mut a = Association { - use_forward_tsn: true, - ..Default::default() - }; - - let prev_tsn = a.peer_last_tsn; - - let fwdtsn = ChunkForwardTsn { - new_cumulative_tsn: a.peer_last_tsn + 3, - streams: vec![ChunkForwardTsnStream { - identifier: 0, - sequence: 0, - }], - }; - - let p = a.handle_forward_tsn(&fwdtsn)?; - - let delayed_ack_triggered = a.delayed_ack_triggered; - let immediate_ack_triggered = a.immediate_ack_triggered; - assert_eq!(a.peer_last_tsn, prev_tsn + 3, "peerLastTSN should advance by 3 "); - assert!(delayed_ack_triggered, "delayed sack should be triggered"); - assert!(!immediate_ack_triggered, "immediate sack should NOT be triggered"); - assert!(p.is_empty(), "should return empty"); - - Ok(()) -} - -#[test] -fn test_handle_forward_tsn_forward_1for1_missing() -> Result<()> { - let mut a = Association { - use_forward_tsn: true, - ..Default::default() - }; - - let prev_tsn = a.peer_last_tsn; - - // this chunk is blocked by the missing chunk at tsn=1 - a.payload_queue.push( - ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 2, - stream_identifier: 0, - stream_sequence_number: 1, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }, - a.peer_last_tsn, - ); - - let fwdtsn = ChunkForwardTsn { - new_cumulative_tsn: a.peer_last_tsn + 1, - streams: vec![ChunkForwardTsnStream { - identifier: 0, - sequence: 1, - }], - }; - - let p = a.handle_forward_tsn(&fwdtsn)?; - - let delayed_ack_triggered = a.delayed_ack_triggered; - let immediate_ack_triggered = a.immediate_ack_triggered; - assert_eq!(a.peer_last_tsn, prev_tsn + 2, "peerLastTSN should advance by 2"); - assert!(delayed_ack_triggered, "delayed sack should be triggered"); - assert!(!immediate_ack_triggered, "immediate sack should NOT be triggered"); - assert!(p.is_empty(), "should return empty"); - - Ok(()) -} - -#[test] -fn test_handle_forward_tsn_forward_1for2_missing() -> Result<()> { - let mut a = Association { - use_forward_tsn: true, - ..Default::default() - }; - - a.use_forward_tsn = true; - let prev_tsn = a.peer_last_tsn; - - // this chunk is blocked by the missing chunk at tsn=1 - a.payload_queue.push( - ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 3, - stream_identifier: 0, - stream_sequence_number: 1, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }, - a.peer_last_tsn, - ); - - let fwdtsn = ChunkForwardTsn { - new_cumulative_tsn: a.peer_last_tsn + 1, - streams: vec![ChunkForwardTsnStream { - identifier: 0, - sequence: 1, - }], - }; - - let p = a.handle_forward_tsn(&fwdtsn)?; - - let immediate_ack_triggered = a.immediate_ack_triggered; - assert_eq!(a.peer_last_tsn, prev_tsn + 1, "peerLastTSN should advance by 1"); - assert!(immediate_ack_triggered, "immediate sack should be triggered"); - assert!(p.is_empty(), "should return empty"); - - Ok(()) -} - -#[test] -fn test_handle_forward_tsn_dup_forward_tsn_chunk_should_generate_sack() -> Result<()> { - let mut a = Association { - use_forward_tsn: true, - ..Default::default() - }; - - let prev_tsn = a.peer_last_tsn; - - let fwdtsn = ChunkForwardTsn { - new_cumulative_tsn: a.peer_last_tsn, - streams: vec![ChunkForwardTsnStream { - identifier: 0, - sequence: 1, - }], - }; - - let p = a.handle_forward_tsn(&fwdtsn)?; - - let ack_state = a.ack_state; - assert_eq!(a.peer_last_tsn, prev_tsn, "peerLastTSN should not advance"); - assert_eq!(AckState::Immediate, ack_state, "sack should be requested"); - assert!(p.is_empty(), "should return empty"); - - Ok(()) -} - -fn queued_chunk(tsn: u32) -> ChunkPayloadData { - ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - } -} - -/// A peer names `new_cumulative_tsn` freely, up to ~2^31 ahead in serial-number -/// arithmetic. Advancing one TSN per iteration turned that into a multi-second -/// hang per chunk; the cost must follow the queue, not the size of the jump. -#[test] -fn test_handle_forward_tsn_huge_gap_is_bounded() -> Result<()> { - let mut a = Association { - use_forward_tsn: true, - ..Default::default() - }; - let gap: u32 = 1 << 30; - - // One chunk the jump abandons, one beyond it that must survive. - assert!(a.payload_queue.push(queued_chunk(5), 0)); - assert!(a.payload_queue.push(queued_chunk(gap + 5), 0)); - - let start = Instant::now(); - a.handle_forward_tsn(&ChunkForwardTsn { - new_cumulative_tsn: gap, - streams: vec![], - })?; - let elapsed = start.elapsed(); - - assert!( - elapsed < Duration::from_secs(2), - "advance must be bounded by queued data, took {elapsed:?}" - ); - assert_eq!(a.peer_last_tsn, gap, "should reach the new cumulative TSN"); - assert!(a.payload_queue.get(5).is_none(), "abandoned chunk dropped"); - assert!(a.payload_queue.get(gap + 5).is_some(), "later chunk kept"); - assert_eq!(a.payload_queue.get_num_bytes(), 3, "bytes follow the drop"); - - Ok(()) -} - -/// The I-FORWARD-TSN handler (RFC 8260) carries its own copy of the advance. -#[test] -fn test_handle_i_forward_tsn_huge_gap_is_bounded() -> Result<()> { - let mut a = Association { - use_forward_tsn: true, - ..Default::default() - }; - let gap: u32 = 1 << 30; - - let start = Instant::now(); - a.handle_i_forward_tsn(&ChunkIForwardTsn { - new_cumulative_tsn: gap, - streams: vec![], - })?; - let elapsed = start.elapsed(); - - assert!( - elapsed < Duration::from_secs(2), - "advance must be bounded by queued data, took {elapsed:?}" - ); - assert_eq!(a.peer_last_tsn, gap, "should reach the new cumulative TSN"); - - Ok(()) -} - -#[test] -fn test_assoc_create_new_stream() -> Result<()> { - let mut a = Association::default(); - - for i in 0..ACCEPT_CH_SIZE { - let stream_identifier = if let Some(s) = a.create_stream(i as u16, true, PayloadProtocolIdentifier::Unknown) { - s.stream_identifier - } else { - panic!("{} should success", i); - }; - let result = a.streams.get(&stream_identifier); - assert!(result.is_some(), "should be in a.streams map"); - } - - let new_si = ACCEPT_CH_SIZE as u16; - let result = a.streams.get(&new_si); - assert!(result.is_none(), "should NOT be in a.streams map"); - - let to_be_ignored = ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 1, - stream_identifier: new_si, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }; - - let p = a.handle_data(&to_be_ignored)?; - assert!(p.is_empty(), "should return empty"); - - Ok(()) -} - -fn handle_init_test(name: &str, initial_state: AssociationState, expect_err: bool) { - let mut a = create_association(TransportConfig::default()); - a.set_state(initial_state); - let pkt = Packet { - common_header: CommonHeader { - source_port: 5001, - destination_port: 5002, - ..Default::default() - }, - ..Default::default() - }; - let mut init = ChunkInit { - initial_tsn: 1234, - num_outbound_streams: 1001, - num_inbound_streams: 1002, - initiate_tag: 5678, - advertised_receiver_window_credit: 512 * 1024, - ..Default::default() - }; - init.set_supported_extensions(); - - let result = a.handle_init(&pkt, &init); - if expect_err { - assert!(result.is_err(), "{} should fail", name); - return; - } else { - assert!(result.is_ok(), "{} should be ok", name); - } - assert_eq!( - if init.initial_tsn == 0 { - u32::MAX - } else { - init.initial_tsn - 1 - }, - a.peer_last_tsn, - "{} should match", - name - ); - assert_eq!(1001, a.my_max_num_outbound_streams, "{} should match", name); - assert_eq!(1002, a.my_max_num_inbound_streams, "{} should match", name); - assert_eq!(5678, a.peer_verification_tag, "{} should match", name); - assert_eq!( - pkt.common_header.source_port, a.destination_port, - "{} should match", - name - ); - assert_eq!( - pkt.common_header.destination_port, a.source_port, - "{} should match", - name - ); - assert!(a.use_forward_tsn, "{} should be set to true", name); - assert_eq!( - 512 * 1024, - a.rwnd, - "{} rwnd should be initialized from peer's advertised_receiver_window_credit", - name - ); - assert_eq!(a.rwnd, a.ssthresh, "{} ssthresh should be initialized to rwnd", name); -} - -#[test] -fn test_assoc_handle_init() -> Result<()> { - handle_init_test("normal", AssociationState::Closed, false); - - handle_init_test("unexpected state established", AssociationState::Established, true); - - handle_init_test( - "unexpected state shutdownAckSent", - AssociationState::ShutdownAckSent, - true, - ); - - handle_init_test( - "unexpected state shutdownPending", - AssociationState::ShutdownPending, - true, - ); - - handle_init_test( - "unexpected state shutdownReceived", - AssociationState::ShutdownReceived, - true, - ); - - handle_init_test("unexpected state shutdownSent", AssociationState::ShutdownSent, true); - - Ok(()) -} - -#[test] -fn test_assoc_max_send_message_size_default() -> Result<()> { - let mut a = create_association(TransportConfig::default()); - assert_eq!(65536, a.max_send_message_size, "should match"); - - let ppi = PayloadProtocolIdentifier::Unknown; - let stream = a.create_stream(1, false, ppi); - assert!(stream.is_some(), "should succeed"); - - if let Some(mut s) = stream { - let p = Bytes::from(vec![0u8; 65537]); - - if let Err(err) = s.write_sctp(&p.slice(..65536), ppi) { - assert_ne!( - Error::ErrOutboundPacketTooLarge, - err, - "should be not Error::ErrOutboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - - if let Err(err) = s.write_sctp(&p.slice(..65537), ppi) { - assert_eq!( - Error::ErrOutboundPacketTooLarge, - err, - "should be Error::ErrOutboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - } - - Ok(()) -} - -#[test] -fn test_assoc_max_send_message_size_explicit() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_send_message_size(30000)); - assert_eq!(30000, a.max_send_message_size, "should match"); - - let ppi = PayloadProtocolIdentifier::Unknown; - let stream = a.create_stream(1, false, ppi); - assert!(stream.is_some(), "should succeed"); - - if let Some(mut s) = stream { - let p = Bytes::from(vec![0u8; 30001]); - - if let Err(err) = s.write_sctp(&p.slice(..30000), ppi) { - assert_ne!( - Error::ErrOutboundPacketTooLarge, - err, - "should be not Error::ErrOutboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - - if let Err(err) = s.write_sctp(&p.slice(..30001), ppi) { - assert_eq!( - Error::ErrOutboundPacketTooLarge, - err, - "should be Error::ErrOutboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - } - - Ok(()) -} - -#[test] -fn test_assoc_max_receive_message_size_default() -> Result<()> { - let mut a = create_association(TransportConfig::default()); - assert_eq!(65536, a.max_receive_message_size, "should match"); - - let p = Bytes::from(vec![0u8; 65537]); - - let size_ok = ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 1, - stream_identifier: 1, - user_data: p.slice(..65536), - ..Default::default() - }; - - assert!(a.handle_data(&size_ok).is_ok(), "should succeed"); - - let too_large = ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 1, - stream_identifier: 1, - user_data: p, - ..Default::default() - }; - - if let Err(err) = a.handle_data(&too_large) { - assert_eq!( - Error::ErrInboundPacketTooLarge, - err, - "should be Error::ErrInboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - - Ok(()) -} - -#[test] -fn test_assoc_max_receive_message_size_explicit() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_message_size(1024)); - assert_eq!(1024, a.max_receive_message_size, "should match"); - - let first_chunk = ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 1, - stream_identifier: 1, - user_data: Bytes::from(vec![0u8; 512]), - ..Default::default() - }; - - assert!(a.handle_data(&first_chunk).is_ok(), "should succeed"); - - let second_chunk = ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 1, - stream_identifier: 1, - user_data: Bytes::from(vec![0u8; 513]), - ..Default::default() - }; - - if let Err(err) = a.handle_data(&second_chunk) { - assert_eq!( - Error::ErrInboundPacketTooLarge, - err, - "should be Error::ErrInboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - - Ok(()) -} - -#[test] -fn test_assoc_max_message_size_asymmetric() -> Result<()> { - let config = TransportConfig::default() - .with_max_send_message_size(1024) - .with_max_receive_message_size(30000); - - let mut a = create_association(config); - assert_eq!(1024, a.max_send_message_size, "should match"); - assert_eq!(30000, a.max_receive_message_size, "should match"); - - let ppi = PayloadProtocolIdentifier::Unknown; - let stream = a.create_stream(1, false, ppi); - assert!(stream.is_some(), "should succeed"); - - if let Some(mut s) = stream { - let p = Bytes::from(vec![0u8; 1025]); - - if let Err(err) = s.write_sctp(&p.slice(..1024), ppi) { - assert_ne!( - Error::ErrOutboundPacketTooLarge, - err, - "should be not Error::ErrOutboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - - if let Err(err) = s.write_sctp(&p.slice(..1025), ppi) { - assert_eq!( - Error::ErrOutboundPacketTooLarge, - err, - "should be Error::ErrOutboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - } - - let p = Bytes::from(vec![0u8; 30001]); - - let size_ok = ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 1, - stream_identifier: 1, - user_data: p.slice(..30000), - ..Default::default() - }; - - assert!(a.handle_data(&size_ok).is_ok(), "should succeed"); - - let too_large = ChunkPayloadData { - beginning_fragment: true, - ending_fragment: true, - tsn: a.peer_last_tsn + 1, - stream_identifier: 1, - user_data: p, - ..Default::default() - }; - - if let Err(err) = a.handle_data(&too_large) { - assert_eq!( - Error::ErrInboundPacketTooLarge, - err, - "should be Error::ErrInboundPacketTooLarge" - ); - } else { - panic!("should be error"); - } - - Ok(()) -} - -#[test] -fn test_generate_out_of_band_init() { - let config = TransportConfig::default(); - let init_bytes = generate_snap_token(&config).unwrap(); - - // Parse it back to validate - let parsed = ChunkInit::unmarshal(&init_bytes).unwrap(); - - assert!(!parsed.is_ack, "Should be INIT, not INIT ACK"); - assert!(parsed.initiate_tag != 0, "Initiate tag should not be zero"); - // Token always advertises u16::MAX for stream counts; - // actual limits are applied from TransportConfig during negotiation. - assert_eq!( - parsed.num_outbound_streams, - u16::MAX, - "Outbound streams should always be u16::MAX in token" - ); - assert_eq!( - parsed.num_inbound_streams, - u16::MAX, - "Inbound streams should always be u16::MAX in token" - ); - assert_eq!( - parsed.advertised_receiver_window_credit, - config.max_receive_buffer_size(), - "ARWND should match config" - ); -} - -#[test] -fn test_generate_out_of_band_init_with_custom_config() { - let config = TransportConfig::default() - .with_max_receive_buffer_size(2_000_000) - .with_max_num_outbound_streams(256) - .with_max_num_inbound_streams(512); - - let init_bytes = generate_snap_token(&config).unwrap(); - let parsed = ChunkInit::unmarshal(&init_bytes).unwrap(); - - // Token always advertises u16::MAX for stream counts; - // actual limits are applied from TransportConfig during negotiation. - assert_eq!(parsed.num_outbound_streams, u16::MAX); - assert_eq!(parsed.num_inbound_streams, u16::MAX); - assert_eq!(parsed.advertised_receiver_window_credit, 2_000_000); -} - -#[test] -fn test_generate_out_of_band_init_uniqueness() { - // Each call to generate_snap_token creates a new INIT with unique random tags. - let config1 = TransportConfig::default(); - let config2 = TransportConfig::default(); - - let init1 = generate_snap_token(&config1).unwrap(); - let init2 = generate_snap_token(&config2).unwrap(); - - let parsed1 = ChunkInit::unmarshal(&init1).unwrap(); - let parsed2 = ChunkInit::unmarshal(&init2).unwrap(); - - // Initiate tags should be different (random) - assert_ne!( - parsed1.initiate_tag, parsed2.initiate_tag, - "Initiate tags should be unique across calls" - ); - - // Initial TSNs should be different (random) - assert_ne!( - parsed1.initial_tsn, parsed2.initial_tsn, - "Initial TSNs should be unique across calls" - ); -} - -#[test] -fn test_out_of_band_association_creation() { - let local_config = Arc::new(TransportConfig::default()); - let remote_config = TransportConfig::default(); - let max_payload_size = 1200; - - let local_init_bytes = generate_snap_token(&local_config).unwrap(); - let remote_init_bytes = generate_snap_token(&remote_config).unwrap(); - - let local_init = ChunkInit::unmarshal(&local_init_bytes).unwrap(); - let remote_init = ChunkInit::unmarshal(&remote_init_bytes).unwrap(); - - let remote_addr: SocketAddr = "192.168.1.1:5000".parse().unwrap(); - - let assoc = Association::new_with_out_of_band_init( - local_config.clone(), - max_payload_size, - remote_addr, - None, - local_init.clone(), - remote_init.clone(), - ) - .expect("Should create out-of-band init association"); - - // Verify the association is in ESTABLISHED state - assert_eq!( - assoc.state(), - AssociationState::Established, - "Out-of-band init association should be in ESTABLISHED state" - ); - - // Verify handshake is marked complete - assert!( - assoc.handshake_completed, - "Out-of-band init association should have handshake completed" - ); - - // Verify verification tags - assert_eq!( - assoc.my_verification_tag, local_init.initiate_tag, - "My verification tag should match local init" - ); - assert_eq!( - assoc.peer_verification_tag, remote_init.initiate_tag, - "Peer verification tag should match remote init" - ); - - // Verify TSN setup - assert_eq!( - assoc.my_next_tsn, local_init.initial_tsn, - "My next TSN should match local init" - ); - assert_eq!( - assoc.peer_last_tsn, - remote_init.initial_tsn.wrapping_sub(1), - "Peer last TSN should be remote init TSN - 1" - ); - - // Verify rwnd - assert_eq!( - assoc.rwnd, remote_init.advertised_receiver_window_credit, - "rwnd should match remote advertised credit" - ); -} - -#[test] -fn test_out_of_band_association_stream_negotiation() { - let config = Arc::new( - TransportConfig::default() - .with_max_num_outbound_streams(100) - .with_max_num_inbound_streams(200), - ); - - // Remote uses default config - token always advertises u16::MAX - let remote_config = TransportConfig::default(); - - let local_init_bytes = generate_snap_token(&config).unwrap(); - let remote_init_bytes = generate_snap_token(&remote_config).unwrap(); - - let local_init = ChunkInit::unmarshal(&local_init_bytes).unwrap(); - let remote_init = ChunkInit::unmarshal(&remote_init_bytes).unwrap(); - - // Token always advertises u16::MAX for stream counts - assert_eq!(local_init.num_outbound_streams, u16::MAX); - assert_eq!(local_init.num_inbound_streams, u16::MAX); - assert_eq!(remote_init.num_outbound_streams, u16::MAX); - assert_eq!(remote_init.num_inbound_streams, u16::MAX); - - let remote_addr: SocketAddr = "192.168.1.1:5000".parse().unwrap(); - - let assoc = - Association::new_with_out_of_band_init(config.clone(), 1200, remote_addr, None, local_init, remote_init) - .expect("Should create out-of-band init association"); - - // Stream limits should be clamped by the local config, since the - // remote token always offers u16::MAX. - // my_max_num_outbound_streams = min(config.max_out=100, remote_in=MAX) = 100 - assert_eq!( - assoc.my_max_num_outbound_streams, 100, - "Outbound streams should be clamped by local config" - ); - - // my_max_num_inbound_streams = min(config.max_in=200, remote_out=MAX) = 200 - assert_eq!( - assoc.my_max_num_inbound_streams, 200, - "Inbound streams should be clamped by local config" - ); -} - -#[test] -fn test_out_of_band_connected_event() { - let local_config = Arc::new(TransportConfig::default()); - let remote_config = TransportConfig::default(); - - let local_init_bytes = generate_snap_token(&local_config).unwrap(); - let remote_init_bytes = generate_snap_token(&remote_config).unwrap(); - - let local_init = ChunkInit::unmarshal(&local_init_bytes).unwrap(); - let remote_init = ChunkInit::unmarshal(&remote_init_bytes).unwrap(); - - let remote_addr: SocketAddr = "192.168.1.1:5000".parse().unwrap(); - - let mut assoc = - Association::new_with_out_of_band_init(local_config.clone(), 1200, remote_addr, None, local_init, remote_init) - .expect("Should create out-of-band init association"); - - // Poll should return a Connected event - let event = assoc.poll(); - assert!( - matches!(event, Some(Event::Connected)), - "Should emit Connected event, got {:?}", - event - ); -} - -#[test] -fn test_out_of_band_symmetric_setup() { - // Test that both sides of an out-of-band init association work correctly - let config_a = Arc::new(TransportConfig::default()); - let config_b = Arc::new(TransportConfig::default()); - - let init_a_bytes = generate_snap_token(&config_a).unwrap(); - let init_b_bytes = generate_snap_token(&config_b).unwrap(); - - let init_a = ChunkInit::unmarshal(&init_a_bytes).unwrap(); - let init_b = ChunkInit::unmarshal(&init_b_bytes).unwrap(); - - let addr_a: SocketAddr = "192.168.1.1:5000".parse().unwrap(); - let addr_b: SocketAddr = "192.168.1.2:5000".parse().unwrap(); - - // Create association A (local=A, remote=B) - let assoc_a = - Association::new_with_out_of_band_init(config_a.clone(), 1200, addr_b, None, init_a.clone(), init_b.clone()) - .expect("Should create association A"); - - // Create association B (local=B, remote=A) - let assoc_b = - Association::new_with_out_of_band_init(config_b.clone(), 1200, addr_a, None, init_b.clone(), init_a.clone()) - .expect("Should create association B"); - - // Verify both are in ESTABLISHED state - assert_eq!(assoc_a.state(), AssociationState::Established); - assert_eq!(assoc_b.state(), AssociationState::Established); - - // Verify verification tags are cross-matched - assert_eq!(assoc_a.my_verification_tag, assoc_b.peer_verification_tag); - assert_eq!(assoc_b.my_verification_tag, assoc_a.peer_verification_tag); -} - -#[test] -fn test_out_of_band_with_forward_tsn_support() { - let local_config = Arc::new(TransportConfig::default()); - let remote_config = TransportConfig::default(); - - let local_init_bytes = generate_snap_token(&local_config).unwrap(); - let remote_init_bytes = generate_snap_token(&remote_config).unwrap(); - - let local_init = ChunkInit::unmarshal(&local_init_bytes).unwrap(); - let remote_init = ChunkInit::unmarshal(&remote_init_bytes).unwrap(); - - // Verify supported extensions are present - let mut has_forward_tsn = false; - for param in &local_init.params { - if let Some(ext) = param - .as_any() - .downcast_ref::( - ) { - for ct in &ext.chunk_types { - if *ct == crate::vendor::sctp_proto::chunk::chunk_type::CT_FORWARD_TSN { - has_forward_tsn = true; - } - } - } - } - assert!(has_forward_tsn, "Generated INIT should include ForwardTSN support"); - - let remote_addr: SocketAddr = "192.168.1.1:5000".parse().unwrap(); - - let assoc = - Association::new_with_out_of_band_init(local_config.clone(), 1200, remote_addr, None, local_init, remote_init) - .expect("Should create out-of-band init association"); - - assert!( - assoc.use_forward_tsn, - "Out-of-band init association should have ForwardTSN enabled" - ); -} - -#[test] -fn test_out_of_band_initial_tsn_zero_wrap() { - // Test edge case where initial TSN is 0 (wraps to MAX) - let config = Arc::new(TransportConfig::default()); - - let local_init_bytes = generate_snap_token(&config).unwrap(); - let mut remote_init = ChunkInit::unmarshal(&local_init_bytes).unwrap(); - - // Set initial TSN to 0 to test the edge case - remote_init.initial_tsn = 0; - remote_init.initiate_tag = 12345; - - // Generate a fresh local init for the association - let actual_local_init_bytes = generate_snap_token(&config).unwrap(); - let local_init = ChunkInit::unmarshal(&actual_local_init_bytes).unwrap(); - let remote_addr: SocketAddr = "192.168.1.1:5000".parse().unwrap(); - - let assoc = - Association::new_with_out_of_band_init(config.clone(), 1200, remote_addr, None, local_init, remote_init) - .expect("Should create out-of-band init association"); - - // peer_last_tsn should be u32::MAX when initial_tsn is 0 - assert_eq!( - assoc.peer_last_tsn, - u32::MAX, - "peer_last_tsn should wrap to MAX when initial_tsn is 0" - ); -} - -#[test] -fn test_out_of_band_rwnd_negotiation() { - let local_config = Arc::new(TransportConfig::default().with_max_receive_buffer_size(500_000)); - - let remote_config = TransportConfig::default().with_max_receive_buffer_size(300_000); - - let local_init_bytes = generate_snap_token(&local_config).unwrap(); - let remote_init_bytes = generate_snap_token(&remote_config).unwrap(); - - let local_init = ChunkInit::unmarshal(&local_init_bytes).unwrap(); - let remote_init = ChunkInit::unmarshal(&remote_init_bytes).unwrap(); - - let remote_addr: SocketAddr = "192.168.1.1:5000".parse().unwrap(); - - let assoc = - Association::new_with_out_of_band_init(local_config.clone(), 1200, remote_addr, None, local_init, remote_init) - .expect("Should create out-of-band init association"); - - // rwnd should be set to remote's advertised receiver window credit - assert_eq!(assoc.rwnd, 300_000, "rwnd should be remote's advertised window"); -} - -#[test] -fn test_initial_cwnd_small_mtu() { - // Regression test for #47: a small MTU made 4*MTU < 4380, which previously - // panicked because clamp(4380, 4*MTU) was called with min > max. - let max_payload_size = 100; - let mtu = max_payload_size + COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE; - assert!(4 * mtu < 4380, "test must exercise the small-MTU branch"); - - let assoc = Association::new( - None, - Arc::new(TransportConfig::default()), - max_payload_size, - 0, - SocketAddr::from_str("0.0.0.0:0").unwrap(), - None, - Instant::now(), - ); - - // RFC 4960 Sec 7.2.1: min(4*MTU, max(2*MTU, 4380)). - assert_eq!(assoc.cwnd, (4 * mtu).min((2 * mtu).max(4380))); - assert_eq!(assoc.cwnd, 4 * mtu); -} - -fn first_transmit_common_header(a: &mut Association) -> CommonHeader { - let transmit = a - .poll_transmit(Instant::now()) - .expect("client association should emit an INIT"); - - let raw = match transmit.payload { - Payload::RawEncode(ref raws) => raws.first().expect("at least one packet").clone(), - _ => panic!("outbound transmit should encode"), - }; - - Packet::unmarshal(&raw).expect("INIT should unmarshal").common_header -} - -#[test] -fn test_client_uses_configured_sctp_ports() { - let mut a = create_association(TransportConfig::default().with_local_port(41234).with_remote_port(9899)); - - assert_eq!(41234, a.source_port); - assert_eq!(9899, a.destination_port); - - let header = first_transmit_common_header(&mut a); - assert_eq!(41234, header.source_port, "INIT source port on the wire"); - assert_eq!(9899, header.destination_port, "INIT destination port on the wire"); -} - -#[test] -fn test_client_defaults_to_well_known_sctp_port() { - let mut a = create_association(TransportConfig::default()); - assert_eq!(DEFAULT_SCTP_PORT, a.source_port); - assert_eq!(DEFAULT_SCTP_PORT, a.destination_port); - - let header = first_transmit_common_header(&mut a); - assert_eq!(DEFAULT_SCTP_PORT, header.source_port); - assert_eq!(DEFAULT_SCTP_PORT, header.destination_port); -} - -#[test] -fn test_out_of_band_init_uses_configured_sctp_ports() { - let local_init = ChunkInit { - initiate_tag: 1, - ..Default::default() - }; - let remote_init = ChunkInit { - initiate_tag: 2, - ..Default::default() - }; - let a = Association::new_with_out_of_band_init( - Arc::new(TransportConfig::default().with_local_port(6001).with_remote_port(6002)), - 1400, - SocketAddr::from_str("0.0.0.0:0").unwrap(), - None, - local_init, - remote_init, - ) - .expect("out-of-band association"); - - assert_eq!(6001, a.source_port); - assert_eq!(6002, a.destination_port); -} - -fn receive_capacity_fragment(tsn: u32, first: bool, last: bool) -> ChunkPayloadData { - ChunkPayloadData { - tsn, - stream_identifier: 1, - beginning_fragment: first, - ending_fragment: last, - user_data: Bytes::from(vec![0; 1024]), - ..Default::default() - } -} - -fn receive_capacity_datagram(a: &mut Association, chunk: ChunkPayloadData) -> Result<()> { - let packet = a.create_packet(vec![Box::new(chunk)]).marshal()?; - a.handle_event(AssociationEvent(AssociationEventInner::Datagram(Transmit { - now: Instant::now(), - remote: a.remote_addr(), - ecn: None, - local_ip: None, - payload: Payload::PartialDecode(crate::vendor::sctp_proto::packet::PartialDecode::unmarshal(&packet)?), - }))); - Ok(()) -} - -#[test] -fn test_receive_capacity_reports_undrainable_message() -> Result<()> { - for unordered in [false, true] { - for initial_tsn in [0u32, u32::MAX - 16] { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.set_state(AssociationState::Established); - a.peer_last_tsn = initial_tsn; - for index in 1..=32 { - let mut fragment = receive_capacity_fragment(initial_tsn.wrapping_add(index), index == 1, false); - fragment.unordered = unordered; - receive_capacity_datagram(&mut a, fragment)?; - if index < 32 { - assert!(!a.is_closed()); - assert_eq!(a.get_my_receiver_window_credit(), (32 - index) * 1024); - assert!(a.stream(1)?.read()?.is_none()); - } - } - assert!(a.is_closed()); - assert!(core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::AssociationLost { - reason: AssociationError::ReceiveBufferExhausted - } - ))); - let packets = a.gather_outbound(Instant::now()).0; - assert_eq!(packets.len(), 1); - let packet = crate::vendor::sctp_proto::packet::PartialDecode::unmarshal(&packets[0])?.finish()?; - let abort = packet.chunks[0].as_any().downcast_ref::().unwrap(); - assert_eq!( - abort.error_causes[0].code, - crate::vendor::sctp_proto::chunk::OUT_OF_RESOURCE - ); - // Closing actually releases storage, rather than inventing credit. - assert_eq!(a.get_my_receiver_window_credit(), 32 * 1024); - } - } - Ok(()) -} - -#[test] -fn test_receive_capacity_zero_window_preserves_backpressure() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.set_state(AssociationState::Established); - a.peer_last_tsn = 0; - for tsn in 1..=32 { - a.handle_data(&receive_capacity_fragment(tsn, tsn == 1, tsn == 32))?; - } - assert_eq!(a.get_my_receiver_window_credit(), 0); - a.ack_state = AckState::Immediate; - let packets = a.gather_outbound_sack_packets(vec![]); - let packet = crate::vendor::sctp_proto::packet::PartialDecode::unmarshal(&packets[0])?.finish()?; - let sack = packet.chunks[0].as_any().downcast_ref::().unwrap(); - assert_eq!(sack.advertised_receiver_window_credit, 0); - assert_eq!(sack.cumulative_tsn_ack, 32); - let mut next = receive_capacity_fragment(33, true, true); - next.stream_identifier = 2; - for _ in 0..3 { - a.handle_data(&next)?; - assert_eq!(a.peer_last_tsn, 32); - assert_eq!(a.get_my_receiver_window_credit(), 0); - assert!(!a.is_closed()); - } - assert!(a.stream(1)?.read()?.is_some()); - assert_eq!(a.get_my_receiver_window_credit(), 32 * 1024); - a.handle_data(&next)?; - assert!(a.stream(2)?.read()?.is_some()); - assert_eq!(a.get_my_receiver_window_credit(), 32 * 1024); - Ok(()) -} - -#[test] -fn test_receive_capacity_gap_fill_and_duplicates() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.peer_last_tsn = u32::MAX - 16; - let initial_tsn = a.peer_last_tsn; - // Lose the beginning fragment and reorder the ending fragment. Accepted - // duplicates do not consume extra storage or turn gap recovery into failure. - for index in (2..=33).rev() { - let chunk = receive_capacity_fragment(initial_tsn.wrapping_add(index), false, index == 33); - a.handle_data(&chunk)?; - let credit = a.get_my_receiver_window_credit(); - a.handle_data(&chunk)?; - assert_eq!(a.get_my_receiver_window_credit(), credit); - } - assert_eq!(a.get_my_receiver_window_credit(), 0); - a.handle_data(&receive_capacity_fragment(initial_tsn.wrapping_add(1), true, false))?; - assert_eq!(a.peer_last_tsn, initial_tsn.wrapping_add(33)); - assert_eq!(a.get_my_receiver_window_credit(), 0); - assert!(a.stream(1)?.read()?.is_some()); - assert_eq!(a.get_my_receiver_window_credit(), 32 * 1024); - Ok(()) -} - -#[test] -fn test_receive_capacity_shared_by_incomplete_streams() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.set_state(AssociationState::Established); - a.peer_last_tsn = 0; - for tsn in 1..=32 { - let mut chunk = receive_capacity_fragment(tsn, tsn <= 2, false); - chunk.stream_identifier = (tsn % 2) as u16; - chunk.unordered = true; - receive_capacity_datagram(&mut a, chunk)?; - } - assert!(a.is_closed()); - assert!(core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::AssociationLost { - reason: AssociationError::ReceiveBufferExhausted - } - ))); - Ok(()) -} - -#[test] -fn test_receive_capacity_counts_retiring_and_deferred_data() -> Result<()> { - let mut a = association_with_retiring_boundary_data()?; - a.max_receive_buffer_size = 32 * 1024; - a.max_receive_message_size = 64 * 1024; - let mut successor = receive_capacity_fragment(2, true, false); - successor.user_data = Bytes::from(vec![0; 32 * 1024 - 3]); - a.handle_data(&successor)?; - assert_eq!(a.get_my_receiver_window_credit(), 0); - assert!(!a.deferred_reset_data.is_empty()); - assert!(!a.is_closed()); - // Reading the retiring generation releases only its three bytes. Moving - // the successor out of deferred storage must not create additional credit. - assert!(a.stream(1)?.read()?.is_some()); - assert_eq!(a.get_my_receiver_window_credit(), 3); - assert!(a.deferred_reset_data.is_empty()); - assert!(a.stream(1)?.read()?.is_none()); - let mut tail = receive_capacity_fragment(3, false, false); - tail.user_data = Bytes::from_static(b"new"); - assert_eq!(a.handle_data(&tail).unwrap_err(), Error::ErrReceiveBufferExhausted); - assert_eq!(a.get_my_receiver_window_credit(), 0); - Ok(()) -} - -#[test] -fn test_receive_capacity_detected_after_reading_last_complete_message() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.set_state(AssociationState::Established); - a.peer_last_tsn = 0; - let mut complete = receive_capacity_fragment(1, true, true); - complete.payload_type = PayloadProtocolIdentifier::Binary; - complete.user_data = Bytes::from_static(b"old"); - a.handle_data(&complete)?; - for tsn in 2..=33 { - let mut partial = receive_capacity_fragment(tsn, tsn == 2, false); - partial.stream_identifier = 2; - a.handle_data(&partial)?; - } - assert_eq!(a.get_my_receiver_window_credit(), 0); - assert!(!a.is_closed()); - assert!(a.stream(1)?.read()?.is_some()); - assert!(a.is_closed()); - let events: Vec<_> = core::iter::from_fn(|| a.poll()).collect(); - let final_stats = events - .iter() - .find_map(|event| match event { - Event::DataChannelStatsFinal(stats) if stats.stream_identifier == 1 => Some(stats), - _ => None, - }) - .expect("receive-capacity closure preserves final stats"); - assert_eq!((final_stats.messages_received, final_stats.bytes_received), (1, 3)); - assert!(events.iter().any(|event| matches!( - event, - Event::AssociationLost { - reason: AssociationError::ReceiveBufferExhausted - } - ))); - Ok(()) -} - -#[test] -fn test_receive_capacity_reports_exhaustion_after_forward_tsn_gap_closure() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.set_state(AssociationState::Established); - a.use_forward_tsn = true; - a.peer_last_tsn = 0; - // TSN 1 is an abandoned message on stream 2. Stream 1's reliable message - // fills the receive budget while that missing TSN keeps the gap queue alive. - for tsn in 2..=33 { - receive_capacity_datagram(&mut a, receive_capacity_fragment(tsn, tsn == 2, false))?; - } - assert!(!a.is_closed()); - assert_eq!(a.get_my_receiver_window_credit(), 0); - assert!(a.stream(1)?.read()?.is_none()); - let forward = ChunkForwardTsn { - new_cumulative_tsn: 1, - streams: vec![ChunkForwardTsnStream { - identifier: 2, - sequence: 0, - }], - }; - let packet = a.create_packet(vec![Box::new(forward)]).marshal()?; - a.handle_event(AssociationEvent(AssociationEventInner::Datagram(Transmit { - now: Instant::now(), - remote: a.remote_addr(), - ecn: None, - local_ip: None, - payload: Payload::PartialDecode(crate::vendor::sctp_proto::packet::PartialDecode::unmarshal(&packet)?), - }))); - assert!( - a.is_closed(), - "FORWARD-TSN must reject the now-undrainable receive buffer" - ); - assert!(core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::AssociationLost { - reason: AssociationError::ReceiveBufferExhausted - } - ))); - Ok(()) -} - -#[test] -fn test_receive_capacity_stopped_stream_cannot_supply_backpressure() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.set_state(AssociationState::Established); - a.peer_last_tsn = 0; - receive_capacity_datagram(&mut a, receive_capacity_fragment(1, true, true))?; - a.stream(1)?.stop()?; - assert_eq!(a.stream(1)?.read().unwrap_err(), Error::ErrStreamClosed); - // A completed message on the stopped read half cannot release storage via - // the public API. The independent reliable message fills the remaining - // receive budget, and its ending fragment would be a new highest TSN. - for tsn in 2..=32 { - let mut chunk = receive_capacity_fragment(tsn, tsn == 2, false); - chunk.stream_identifier = 2; - receive_capacity_datagram(&mut a, chunk)?; - } - if !a.is_closed() { - assert_eq!(a.get_my_receiver_window_credit(), 0); - assert!(a.stream(2)?.read()?.is_none()); - // The peer can have assigned its last TSN to the ending fragment - // before answering the reset. That reset cannot free the stopped - // stream until this new highest TSN is received. - let mut replies = vec![]; - a.reset_streams_if_any( - &ParamOutgoingResetRequest { - reconfig_request_sequence_number: 1, - reconfig_response_sequence_number: 0, - sender_last_tsn: 33, - stream_identifiers: vec![1], - }, - true, - &mut replies, - )?; - let mut ending = receive_capacity_fragment(33, false, true); - ending.stream_identifier = 2; - for _ in 0..3 { - receive_capacity_datagram(&mut a, ending.clone())?; - assert_eq!(a.peer_last_tsn, 32); - assert_eq!(a.get_my_receiver_window_credit(), 0); - } - } - assert!( - a.is_closed(), - "a stopped read half cannot make receive storage drainable" - ); - assert!(core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::AssociationLost { - reason: AssociationError::ReceiveBufferExhausted - } - ))); - Ok(()) -} - -#[test] -fn test_receive_capacity_detected_when_last_readable_stream_stops() -> Result<()> { - let mut a = create_association(TransportConfig::default().with_max_receive_buffer_size(32 * 1024)); - a.set_state(AssociationState::Established); - a.peer_last_tsn = 0; - receive_capacity_datagram(&mut a, receive_capacity_fragment(1, true, true))?; - for tsn in 2..=32 { - let mut chunk = receive_capacity_fragment(tsn, tsn == 2, false); - chunk.stream_identifier = 2; - receive_capacity_datagram(&mut a, chunk)?; - } - assert!(!a.is_closed()); - assert_eq!(a.get_my_receiver_window_credit(), 0); - a.stream(1)?.stop()?; - assert!(a.is_closed(), "stop must detect storage the API can no longer drain"); - assert!(core::iter::from_fn(|| a.poll()).any(|event| matches!( - event, - Event::AssociationLost { - reason: AssociationError::ReceiveBufferExhausted - } - ))); - Ok(()) -} - -#[test] -fn test_data_channel_stats_acceptance_and_delivery() -> Result<()> { - let mut a = create_association(TransportConfig::default()); - a.set_state(AssociationState::Established); - let ppi = PayloadProtocolIdentifier::Binary; - let mut stream = a.create_stream(12, false, ppi).unwrap(); - let initial = stream.stats()?; - assert_eq!(initial.messages_sent, 0); - assert_eq!(initial, stream.stats()?); - stream.write(b"abc")?; - stream.write_chunk(&Bytes::from_static(b"xy"))?; - stream.write_sctp(&Bytes::from_static(b"z"), ppi)?; - stream.write_with_ppi("é".as_bytes(), PayloadProtocolIdentifier::String)?; - stream.write_with_ppi(&[0], PayloadProtocolIdentifier::BinaryEmpty)?; - stream.write_with_ppi(&[0], PayloadProtocolIdentifier::StringEmpty)?; - stream.write_with_ppi(b"control", PayloadProtocolIdentifier::Dcep)?; - stream.write_with_ppi(b"unknown", PayloadProtocolIdentifier::Unknown)?; - stream.write(b"")?; - let mut buffers = [ - Bytes::new(), - Bytes::from_static(b"first"), - Bytes::from_static(b"second"), - ]; - assert_eq!(stream.write_chunks(&mut buffers)?, 5); - assert_eq!(buffers[2], b"second"[..]); - let stats = stream.stats()?; - assert_eq!((stats.messages_sent, stats.bytes_sent), (7, 13)); - assert!(stream.write(&vec![0; 1_000_000]).is_err()); - assert_eq!(stats, stream.stats()?); - - // Fragmentation, reordering and duplicates are accounted only at handoff. - let data = Bytes::from(vec![42; 3000]); - stream.write_sctp(&data, ppi)?; - let before_read = stream.stats()?; - let receiver = a.streams.get_mut(&12).unwrap(); - let mut fragments = vec![]; - for (i, part) in data.chunks(1000).enumerate() { - fragments.push(ChunkPayloadData { - tsn: i as u32 + 1, - stream_identifier: 12, - stream_sequence_number: 0, - beginning_fragment: i == 0, - ending_fragment: i == 2, - payload_type: ppi, - user_data: Bytes::copy_from_slice(part), - ..Default::default() - }); - } - receiver.handle_data(&fragments[2])?; - receiver.handle_data(&fragments[0])?; - receiver.handle_data(&fragments[0])?; - assert!(a.stream(12).unwrap().read()?.is_none()); - a.streams.get_mut(&12).unwrap().handle_data(&fragments[1])?; - let mut stream = a.stream(12).unwrap(); - let mut message = stream.read()?.unwrap(); - assert_eq!(message.next(1).unwrap().bytes.len(), 1); - let mut output = vec![0; 3000]; - message.clone().read(&mut output)?; - message.read(&mut output)?; - assert!(stream.read()?.is_none()); - let stats = stream.stats()?; - assert_eq!((stats.messages_received, stats.bytes_received), (1, 3000)); - assert_eq!(stats.messages_sent, before_read.messages_sent); - stream.finish()?; - assert!(stream.write(b"rejected").is_err()); - assert_eq!(stats, stream.stats()?); - Ok(()) -} - -#[test] -fn test_data_channel_stats_retirement_reuse_and_loss() -> Result<()> { - let mut a = create_association(TransportConfig::default()); - a.set_state(AssociationState::Established); - let initial = a - .create_stream(4, false, PayloadProtocolIdentifier::Binary) - .unwrap() - .stats()?; - a.streams.get_mut(&4).unwrap().handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: 4, - beginning_fragment: true, - ending_fragment: true, - payload_type: PayloadProtocolIdentifier::StringEmpty, - user_data: Bytes::from_static(&[0]), - ..Default::default() - })?; - a.retire_stream(4, 1); - assert!(a.stream(4).unwrap().read()?.is_some()); - let mut finals = vec![]; - while let Some(event) = a.poll() { - if let Event::DataChannelStatsFinal(stats) = event { - finals.push(stats); - } - } - assert_eq!(finals.len(), 1); - assert_eq!(finals[0].generation, initial.generation); - assert_eq!((finals[0].messages_received, finals[0].bytes_received), (1, 0)); - let fresh = a - .create_stream(4, false, PayloadProtocolIdentifier::Binary) - .unwrap() - .stats()?; - assert_ne!(fresh.generation, initial.generation); - assert_eq!(fresh.messages_received, 0); - a.close()?; - a.close()?; - while let Some(event) = a.poll() { - if let Event::DataChannelStatsFinal(stats) = event { - finals.push(stats); - } - } - assert_eq!(finals.len(), 2); - assert_eq!(finals[1], fresh); - Ok(()) -} - -#[test] -fn test_data_channel_stats_receive_projection_and_isolation() -> Result<()> { - let mut a = create_association(TransportConfig::default()); - a.set_state(AssociationState::Established); - a.create_stream(1, false, PayloadProtocolIdentifier::Binary).unwrap(); - let untouched = a - .create_stream(2, false, PayloadProtocolIdentifier::Binary) - .unwrap() - .stats()?; - let mut other = create_association(TransportConfig::default()); - let separate = other - .create_stream(1, false, PayloadProtocolIdentifier::Binary) - .unwrap() - .stats()?; - let payloads = [ - (PayloadProtocolIdentifier::Binary, &b"abc"[..]), - (PayloadProtocolIdentifier::String, "é".as_bytes()), - (PayloadProtocolIdentifier::StringEmpty, &b"\0"[..]), - (PayloadProtocolIdentifier::BinaryEmpty, &b"\0"[..]), - (PayloadProtocolIdentifier::Dcep, &b"control"[..]), - (PayloadProtocolIdentifier::Unknown, &b"unknown"[..]), - ]; - for (i, (ppi, data)) in payloads.into_iter().enumerate() { - a.streams.get_mut(&1).unwrap().handle_data(&ChunkPayloadData { - tsn: i as u32 + 1, - stream_sequence_number: i as u16, - stream_identifier: 1, - beginning_fragment: true, - ending_fragment: true, - payload_type: ppi, - user_data: Bytes::copy_from_slice(data), - ..Default::default() - })?; - a.stream(1)?.read()?.unwrap(); - } - let stats = a.stream(1)?.stats()?; - assert_eq!((stats.messages_received, stats.bytes_received), (4, 5)); - assert_eq!(a.stream(2)?.stats()?, untouched); - assert_eq!(other.stream(1)?.stats()?, separate); - // A closed receive half rejects reads without changing cumulative totals. - a.stream(1)?.stop()?; - assert!(a.stream(1)?.read().is_err()); - assert_eq!(a.stream(1)?.stats()?, stats); - Ok(()) -} - -#[test] -fn test_data_channel_stats_failed_queue_and_abandoned_receive() -> Result<()> { - let mut a = create_association(TransportConfig::default()); - let before = a - .create_stream(1, false, PayloadProtocolIdentifier::Binary) - .unwrap() - .stats()?; - // Queueing rejects a write before the association is established. - assert!(a.stream(1)?.write(b"not accepted").is_err()); - assert_eq!(a.stream(1)?.stats()?, before); - a.set_state(AssociationState::Established); - a.streams.get_mut(&1).unwrap().handle_data(&ChunkPayloadData { - tsn: 1, - stream_identifier: 1, - beginning_fragment: true, - ending_fragment: false, - payload_type: PayloadProtocolIdentifier::Binary, - user_data: Bytes::from_static(b"incomplete"), - ..Default::default() - })?; - assert!(a.stream(1)?.read()?.is_none()); - a.streams - .get_mut(&1) - .unwrap() - .reassembly_queue - .forward_tsn_for_ordered(0); - assert!(a.stream(1)?.read()?.is_none()); - assert_eq!(a.stream(1)?.stats()?, before); - a.next_stream_generation = u64::MAX; - assert!(a.create_stream(2, false, PayloadProtocolIdentifier::Binary).is_none()); - assert_eq!(a.stream(1)?.stats()?, before); - Ok(()) -} - -fn queue_pending(a: &mut Association, chunk: ChunkPayloadData) { - a.outbound_queue.push(vec![chunk]); -} - -fn queue_inflight(a: &mut Association, mut chunk: ChunkPayloadData) { - // These fixtures insert one complete message through the real scheduler. - chunk.beginning_fragment = true; - chunk.ending_fragment = true; - let tsn = chunk.tsn; - queue_pending(a, chunk); - a.outbound_queue.send_next(&mut { tsn }, Instant::now()).unwrap(); -} - -fn fragmented_retransmission_fixture(limit: u32) -> Association { - let mut a = Association { - state: AssociationState::Established, - use_forward_tsn: true, - my_next_tsn: 1, - max_send_message_size: 100, - max_receive_message_size: 100, - max_payload_size: 4, - cwnd: 100, - rwnd: 100, - mtu: 1400, - ..Default::default() - }; - a.create_stream(1, false, PayloadProtocolIdentifier::Binary).unwrap(); - let mut stream = a.stream(1).unwrap(); - stream - .set_reliability_params(false, ReliabilityType::Rexmit, limit) - .unwrap(); - stream.write(b"abcdefghij").unwrap(); - a -} - -#[test] -fn test_fast_retransmission_abandons_message_and_pending_tail() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - a.send_next_data_chunk(now).unwrap(); - a.send_next_data_chunk(now).unwrap(); - for tsn in 1..=2 { - a.outbound_queue.get_mut(tsn).unwrap().miss_indicator = 3; - } - a.will_retransmit_fast = true; - assert!(a.gather_outbound_fast_retransmission_packets(vec![], now).is_empty()); - assert!(a.outbound_queue.is_abandoned(1)); - assert!(a.outbound_queue.is_abandoned(2)); - assert_eq!(a.outbound_queue.pending_len(), 0); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); - assert_eq!(a.my_next_tsn, 4); - let packets = a.gather_outbound_forward_tsn_packets(vec![]); - assert_eq!(packets.len(), 1); - let packet = Packet::unmarshal(&packets[0]).unwrap(); - let forward = packet.chunks[0].as_any().downcast_ref::().unwrap(); - assert_eq!(forward.new_cumulative_tsn, 3); - assert_eq!(forward.streams[0].identifier, 1); - assert_eq!(forward.streams[0].sequence, 0); -} - -#[test] -fn test_later_fragment_exhaustion_cancels_earlier_scheduled_retry() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(1); - a.send_next_data_chunk(now).unwrap(); - a.send_next_data_chunk(now).unwrap(); - // Chunks keep independent retry counts. Once one exhausts its allowance, - // even siblings already selected in this batch must be abandoned. - a.outbound_queue.get_mut(2).unwrap().nsent = 2; - a.outbound_queue.mark_all_to_retransmit(); - assert!(a.get_data_packets_to_retransmit(now).is_empty()); - assert!(a.outbound_queue.is_abandoned(1)); - assert!(a.outbound_queue.is_abandoned(2)); - assert_eq!(a.outbound_queue.pending_len(), 0); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); -} - -#[test] -fn test_fast_retry_counts_toward_timer_retransmission_limit() { - for limit in [1, 2] { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(limit); - for _ in 0..3 { - a.send_next_data_chunk(now).unwrap(); - } - for tsn in 1..=3 { - a.outbound_queue.get_mut(tsn).unwrap().miss_indicator = 3; - } - a.will_retransmit_fast = true; - assert_eq!(a.gather_outbound_fast_retransmission_packets(vec![], now).len(), 1); - for tsn in 1..=3 { - assert_eq!(a.outbound_queue.get(tsn).unwrap().nsent, 2); - assert!(!a.outbound_queue.is_abandoned(tsn)); - } - a.outbound_queue.mark_all_to_retransmit(); - let packets = a.get_data_packets_to_retransmit(now); - assert_eq!(packets.len(), (limit - 1) as usize); - if limit == 2 { - a.outbound_queue.mark_all_to_retransmit(); - assert!(a.get_data_packets_to_retransmit(now).is_empty()); - } - for tsn in 1..=3 { - assert_eq!(a.outbound_queue.get(tsn).unwrap().nsent, limit + 1); - assert!(a.outbound_queue.is_abandoned(tsn)); - } - } -} - -#[test] -fn abandoned_retry_message_releases_credit_without_ack_credit() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - a.send_next_data_chunk(now).unwrap(); - a.send_next_data_chunk(now).unwrap(); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 10); - a.outbound_queue.mark_all_to_retransmit(); - assert!(a.get_data_packets_to_retransmit(now).is_empty()); - assert_eq!(a.outbound_queue.inflight_bytes(), 0); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); - assert_eq!( - a.events - .iter() - .filter(|event| matches!(event, Event::Stream(StreamEvent::BufferedAmountLow { id: 1 }))) - .count(), - 1 - ); - let rto = a.rto_mgr.get_rto(); - let (credit, _) = a - .process_selective_ack( - &ChunkSelectiveAck { - cumulative_tsn_ack: 3, - ..Default::default() - }, - now + Duration::from_millis(200), - ) - .unwrap(); - assert!(credit.is_empty()); - assert_eq!(a.rto_mgr.get_rto(), rto); - assert_eq!(a.outbound_queue.inflight_len(), 0); -} - -#[test] -fn retry_abandonment_does_not_credit_reused_stream() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - a.send_next_data_chunk(now).unwrap(); - // Model the old stream's removal while its retransmission metadata remains. - a.streams.remove(&1); - a.create_stream(1, false, PayloadProtocolIdentifier::Binary).unwrap(); - a.stream(1).unwrap().write(b"new").unwrap(); - a.outbound_queue.mark_all_to_retransmit(); - assert!(a.get_data_packets_to_retransmit(now).is_empty()); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 3); - assert_eq!(a.outbound_queue.pending_bytes(), 3); - assert!( - a.events - .iter() - .all(|event| !matches!(event, Event::Stream(StreamEvent::BufferedAmountLow { id: 1 }))) - ); -} - -#[test] -fn review_fast_abandonment_cancels_pending_fragments_in_same_poll() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - a.send_next_data_chunk(now).unwrap(); - // Three missing reports make the original a fast-recovery candidate. - // The congestion window also permits the pending tail in this poll. - a.outbound_queue.get_mut(1).unwrap().miss_indicator = 3; - a.will_retransmit_fast = true; - let (packets, _) = a.gather_outbound(now); - assert!(a.outbound_queue.is_abandoned(1)); - for raw in packets { - let packet = Packet::unmarshal(&raw).unwrap(); - for chunk in packet.chunks { - if let Some(data) = chunk.as_any().downcast_ref::() { - assert!( - !a.outbound_queue.is_abandoned(data.tsn), - "poll emitted TSN {} after abandoning its whole message", - data.tsn - ); - } - } - } -} - -fn check_old_generation_ack_credit(gap_ack: bool) { - use crate::vendor::sctp_proto::chunk::chunk_selective_ack::GapAckBlock; - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - a.send_next_data_chunk(now).unwrap(); - // Same generation transition as retry_abandonment_does_not_credit_reused_stream. - a.streams.remove(&1); - a.create_stream(1, false, PayloadProtocolIdentifier::Binary).unwrap(); - a.stream(1).unwrap().write(b"new").unwrap(); - let sack = ChunkSelectiveAck { - cumulative_tsn_ack: if gap_ack { 0 } else { 1 }, - gap_ack_blocks: if gap_ack { - vec![GapAckBlock { start: 1, end: 1 }] - } else { - vec![] - }, - advertised_receiver_window_credit: 100, - ..Default::default() - }; - a.handle_sack(&sack, now + Duration::from_millis(20)).unwrap(); - assert_eq!( - a.stream(1).unwrap().buffered_amount().unwrap(), - 3, - "old generation ACK must not release new stream credit (gap={gap_ack})" - ); - assert!( - a.events - .iter() - .all(|event| !matches!(event, Event::Stream(StreamEvent::BufferedAmountLow { id: 1 }))) - ); -} - -#[test] -fn review_old_generation_cumulative_ack_preserves_new_stream_credit() { - check_old_generation_ack_credit(false); -} - -#[test] -fn review_old_generation_gap_ack_preserves_new_stream_credit() { - check_old_generation_ack_credit(true); -} - -#[test] -fn cancelled_retry_batch_reuses_window_for_unrelated_message() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(1); - for _ in 0..3 { - a.send_next_data_chunk(now).unwrap(); - } - a.stream(1).unwrap().write(b"live").unwrap(); - a.send_next_data_chunk(now).unwrap(); - a.outbound_queue.get_mut(2).unwrap().nsent = 2; - a.outbound_queue.mark_all_to_retransmit(); - a.cwnd = 4; - let packets = a.get_data_packets_to_retransmit(now); - assert_eq!(packets.len(), 1, "cancelled siblings must release this batch's window"); - assert_eq!(packets[0].chunks.len(), 1); - let data = packets[0].chunks[0] - .as_any() - .downcast_ref::() - .unwrap(); - assert_eq!(data.tsn, 4); - assert_eq!(&data.user_data[..], b"live"); - assert_eq!( - a.outbound_queue.get(1).unwrap().nsent, - 1, - "cancelled selection was never sent" - ); -} - -#[test] -fn gap_ack_after_abandoned_prefix_restarts_outstanding_timer() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - for _ in 0..3 { - a.send_next_data_chunk(now).unwrap(); - } - assert!(a.abandon_if_needed(1, now)); - a.stream(1).unwrap().write(b"live").unwrap(); - a.send_next_data_chunk(now).unwrap(); - a.timers.start(Timer::T3RTX, now, 1000); - let ack_time = now + Duration::from_millis(100); - a.handle_sack( - &ChunkSelectiveAck { - cumulative_tsn_ack: 0, - gap_ack_blocks: vec![crate::vendor::sctp_proto::chunk::chunk_selective_ack::GapAckBlock { - start: 4, - end: 4, - }], - advertised_receiver_window_credit: 100, - ..Default::default() - }, - ack_time, - ) - .unwrap(); - assert_eq!( - a.timers.get(Timer::T3RTX), - Some(ack_time + Duration::from_millis(a.rto_mgr.get_rto())) - ); -} - -#[test] -fn late_ack_of_abandoned_data_resets_errors_but_duplicates_do_not() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - a.send_next_data_chunk(now).unwrap(); - assert!(a.abandon_if_needed(1, now)); - a.timers = TimerTable::new(None, Some(1), 60000); - a.timers.start(Timer::T3RTX, now, 1); - assert_eq!( - a.timers.is_expired(Timer::T3RTX, now + Duration::from_millis(1)), - (true, false, 1) - ); - let sack = ChunkSelectiveAck { - cumulative_tsn_ack: 0, - gap_ack_blocks: vec![crate::vendor::sctp_proto::chunk::chunk_selective_ack::GapAckBlock { start: 1, end: 1 }], - advertised_receiver_window_credit: 100, - ..Default::default() - }; - a.handle_sack(&sack, now + Duration::from_millis(2)).unwrap(); - a.timers.start(Timer::T3RTX, now, 1); - assert_eq!( - a.timers.is_expired(Timer::T3RTX, now + Duration::from_millis(2)), - (true, false, 1) - ); - a.handle_sack(&sack, now + Duration::from_millis(3)).unwrap(); - a.timers.start(Timer::T3RTX, now, 1); - assert_eq!( - a.timers.is_expired(Timer::T3RTX, now + Duration::from_millis(4)), - (true, true, 2) - ); -} - -#[test] -fn forward_only_marker_ack_does_not_reset_peer_errors() { - let now = Instant::now(); - let mut a = fragmented_retransmission_fixture(0); - a.send_next_data_chunk(now).unwrap(); - assert!(a.abandon_if_needed(1, now)); - assert_eq!(a.outbound_queue.get(2).unwrap().nsent, 0); - a.timers = TimerTable::new(None, Some(1), 60000); - a.timers.start(Timer::T3RTX, now, 1); - assert_eq!( - a.timers.is_expired(Timer::T3RTX, now + Duration::from_millis(1)), - (true, false, 1) - ); - a.handle_sack( - &ChunkSelectiveAck { - cumulative_tsn_ack: 0, - gap_ack_blocks: vec![crate::vendor::sctp_proto::chunk::chunk_selective_ack::GapAckBlock { - start: 2, - end: 2, - }], - advertised_receiver_window_credit: 100, - ..Default::default() - }, - now + Duration::from_millis(2), - ) - .unwrap(); - a.timers.start(Timer::T3RTX, now, 1); - assert_eq!( - a.timers.is_expired(Timer::T3RTX, now + Duration::from_millis(4)), - (true, true, 2) - ); -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/association/mod.rs b/rs/moq-webrtc/src/vendor/sctp_proto/association/mod.rs deleted file mode 100644 index fdcebcad24c..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/association/mod.rs +++ /dev/null @@ -1,4146 +0,0 @@ -use crate::vendor::sctp_proto::association::state::{AckMode, AckState, AssociationState}; -use crate::vendor::sctp_proto::association::stats::AssociationStats; -use crate::vendor::sctp_proto::chunk::Chunk; -use crate::vendor::sctp_proto::chunk::ErrorCauseUnrecognizedChunkType; -use crate::vendor::sctp_proto::chunk::USER_INITIATED_ABORT; -use crate::vendor::sctp_proto::chunk::chunk_abort::ChunkAbort; -use crate::vendor::sctp_proto::chunk::chunk_cookie_ack::ChunkCookieAck; -use crate::vendor::sctp_proto::chunk::chunk_cookie_echo::ChunkCookieEcho; -use crate::vendor::sctp_proto::chunk::chunk_error::ChunkError; -use crate::vendor::sctp_proto::chunk::chunk_forward_tsn::{ChunkForwardTsn, ChunkForwardTsnStream}; -use crate::vendor::sctp_proto::chunk::chunk_heartbeat::ChunkHeartbeat; -use crate::vendor::sctp_proto::chunk::chunk_heartbeat_ack::ChunkHeartbeatAck; -use crate::vendor::sctp_proto::chunk::chunk_i_forward_tsn::ChunkIForwardTsn; -use crate::vendor::sctp_proto::chunk::chunk_init::{ChunkInit, ChunkInitAck}; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier}; -use crate::vendor::sctp_proto::chunk::chunk_reconfig::ChunkReconfig; -use crate::vendor::sctp_proto::chunk::chunk_selective_ack::ChunkSelectiveAck; -use crate::vendor::sctp_proto::chunk::chunk_shutdown::ChunkShutdown; -use crate::vendor::sctp_proto::chunk::chunk_shutdown_ack::ChunkShutdownAck; -use crate::vendor::sctp_proto::chunk::chunk_shutdown_complete::ChunkShutdownComplete; -use crate::vendor::sctp_proto::chunk::chunk_type::CT_FORWARD_TSN; -use crate::vendor::sctp_proto::config::COMMON_HEADER_SIZE; -use crate::vendor::sctp_proto::config::DATA_CHUNK_HEADER_SIZE; -use crate::vendor::sctp_proto::config::{ServerConfig, TransportConfig}; -use crate::vendor::sctp_proto::error::{Error, Result}; -use crate::vendor::sctp_proto::packet::{CommonHeader, Packet}; -use crate::vendor::sctp_proto::param::Param; -use crate::vendor::sctp_proto::param::param_heartbeat_info::ParamHeartbeatInfo; -use crate::vendor::sctp_proto::param::param_outgoing_reset_request::ParamOutgoingResetRequest; -use crate::vendor::sctp_proto::param::param_reconfig_response::{ParamReconfigResponse, ReconfigResult}; -use crate::vendor::sctp_proto::param::param_state_cookie::ParamStateCookie; -use crate::vendor::sctp_proto::param::param_supported_extensions::ParamSupportedExtensions; -use crate::vendor::sctp_proto::queue::outbound_queue::OutboundQueue; -use crate::vendor::sctp_proto::queue::payload_queue::PayloadQueue; -use crate::vendor::sctp_proto::queue::reassembly_queue::ReassemblyQueue; -use crate::vendor::sctp_proto::shared::{AssociationEventInner, AssociationId, EndpointEvent, EndpointEventInner}; -use crate::vendor::sctp_proto::util::{sna16lt, sna32gt, sna32gte, sna32lt, sna32lte}; -use crate::vendor::sctp_proto::{AssociationEvent, Payload, Side, Transmit}; -use stream::DataChannelStats; -use stream::{ReliabilityType, Stream, StreamEvent, StreamId, StreamResetError, StreamState}; -use timer::{ACK_INTERVAL, RtoManager, Timer, TimerTable}; - -use crate::vendor::sctp_proto::association::stream::RecvSendState; -use bytes::Bytes; -use core::net::{IpAddr, SocketAddr}; -use core::num::NonZeroU32; -use core::str::FromStr; -use core::time::Duration; -use rand::random; -use rustc_hash::{FxHashMap, FxHashSet}; -use std::boxed::Box; -use std::collections::HashMap; -use std::collections::VecDeque; -use std::string::String; -use std::sync::Arc; -use std::time::Instant; -use std::vec; -use std::vec::Vec; -use thiserror::Error; -use tracing::{debug, error, trace, warn}; - -pub(crate) mod state; -pub(crate) mod stats; -pub(crate) mod stream; -mod timer; - -#[cfg(test)] -mod association_test; - -#[cfg(test)] -mod timed_reliability_test; - -/// Reasons why an association might be lost -#[non_exhaustive] -#[derive(Debug, Error, Clone, PartialEq)] -pub enum AssociationError { - /// Handshake failed - #[error("{0}")] - HandshakeFailed(#[from] Error), - /// The peer violated the SCTP specification as understood by this implementation - #[error("transport error")] - TransportError, - /// Receive storage filled with messages that the whole-message API cannot drain. - #[error("receive buffer exhausted during message reassembly")] - ReceiveBufferExhausted, - /// The peer's SCTP stack aborted the association - #[error("aborted by peer")] - AssociationClosed, - /// The peer closed the association - #[error("closed by peer")] - ApplicationClosed, - /// The peer is unable to continue processing this association, usually due to having restarted - #[error("reset by peer")] - Reset, - /// Communication with the peer has lapsed for longer than the negotiated idle timeout - /// - /// If neither side is sending keep-alives, an association will time out after a long enough idle - /// period even if the peer is still reachable - #[error("timed out")] - TimedOut, - /// The local application closed the association - #[error("closed")] - LocallyClosed, -} - -/// Events of interest to the application -#[non_exhaustive] -#[derive(Debug)] -pub enum Event { - /// The association was successfully established - Connected, - /// The association handshake failed - /// - /// Emitted if the handshake (INIT/COOKIE exchange) fails. - HandshakeFailed { - /// Reason that the handshake failed - reason: AssociationError, - }, - /// The association was lost - /// - /// Emitted if the peer closes the association or an error is encountered - AssociationLost { - /// Reason that the association was closed - reason: AssociationError, - }, - /// Stream events - Stream(StreamEvent), - /// Final counters for a removed stream generation, including association loss. - /// - /// Emitted exactly once per removed generation. Drain events after reads and - /// close/reset operations as well as transport input, and before dropping - /// the association. The embedding layer owns retention of closed reports. - DataChannelStatsFinal(DataChannelStats), - /// One or more application datagrams have been received - DatagramReceived, -} - -/// Multiset of stream ids owing a terminal reset event. -/// Each `Finished` for an id arms one result, a re-created id is a distinct -/// generation and owes its own. -#[derive(Debug, Default)] -struct PendingResetCompletions(FxHashMap); - -impl PendingResetCompletions { - /// Arm one completion for this id. - fn insert(&mut self, id: StreamId) { - *self.0.entry(id).or_default() += 1; - } - - fn contains(&self, id: &StreamId) -> bool { - self.0.contains_key(id) - } - - /// Consume one armed completion for this id. - fn take_one(&mut self, id: StreamId) -> bool { - if let Some(count) = self.0.get_mut(&id) { - *count -= 1; - if *count == 0 { - self.0.remove(&id); - } - true - } else { - false - } - } - - fn clear(&mut self) { - self.0.clear(); - } -} - -#[derive(Debug, Copy, Clone)] -enum DeferredForwardTsnKind { - Ordered { last_ssn: u16, new_cumulative_tsn: u32 }, - Unordered { new_cumulative_tsn: u32 }, -} - -#[derive(Debug, Copy, Clone)] -struct DeferredForwardTsn { - /// The reset boundary ending the generation this update belongs to. - /// None identifies the active tail generation after all accepted resets. - generation_boundary: Option, - kind: DeferredForwardTsnKind, -} - -///Association represents an SCTP association -//13.2. Parameters Necessary per Association (i.e., the TCB) -//Peer : Tag value to be sent in every packet and is received -//Verification: in the INIT or INIT ACK chunk. -//Tag : -// -//My : Tag expected in every inbound packet and sent in the -//Verification: INIT or INIT ACK chunk. -// -//Tag : -//State : A state variable indicating what state the association -// : is in, i.e., COOKIE-WAIT, COOKIE-ECHOED, ESTABLISHED, -// : SHUTDOWN-PENDING, SHUTDOWN-SENT, SHUTDOWN-RECEIVED, -// : SHUTDOWN-ACK-SENT. -// -// No Closed state is illustrated since if a -// association is Closed its TCB SHOULD be removed. -#[derive(Debug)] -pub struct Association { - side: Side, - state: AssociationState, - handshake_completed: bool, - max_send_message_size: u32, - max_receive_message_size: u32, - inflight_queue_length: usize, - will_send_shutdown: bool, - next_stream_generation: u64, - bytes_received: usize, - bytes_sent: usize, - - peer_verification_tag: u32, - my_verification_tag: u32, - my_next_tsn: u32, - peer_last_tsn: u32, - // for RTT measurement - min_tsn2measure_rtt: u32, - will_send_forward_tsn: bool, - will_retransmit_fast: bool, - will_retransmit_reconfig: bool, - - will_send_shutdown_ack: bool, - will_send_shutdown_complete: bool, - - // Reconfig - my_next_rsn: u32, - reconfigs: FxHashMap, - /// Stream ids semantically covered by an outgoing reset. Reset-all stays - /// compact on the wire, so its completion ids cannot be recovered from the - /// serialized parameter itself. - reconfig_reset_streams: FxHashMap>, - /// The one request whose Re-configuration Timer is running. - active_reconfig: Option, - /// Application-initiated resets waiting for the active request to finish. - pending_reset_streams: VecDeque, - reconfig_requests: FxHashMap, - /// DATA received above an InProgress reset boundary. A copy is retained - /// after cumulative TSN processing removes it from `payload_queue`, so it - /// can remain withheld until the old stream generation is drained. - deferred_reset_data: FxHashMap, - max_completed_reconfig_rsn: Option, - /// Re-configuration Request Sequence Number most recently accepted from - /// the peer, initialized to the peer's initial TSN minus one. - peer_last_reconfig_rsn: u32, - /// Whether `peer_last_reconfig_rsn` has been initialized from an INIT or a - /// first request in test/manual construction. - peer_reconfig_rsn_initialized: bool, - /// Stream ids for which `StreamEvent::Finished` is queued but whose terminal - /// reset event is still awaited. - pending_reset_completions: PendingResetCompletions, - /// Stream ids whose latest completed reset was unsuccessful. - failed_reset_streams: FxHashSet, - /// Reset boundaries for generations that cannot finish until an older - /// application-readable generation with the same stream id is drained. - retiring_streams: FxHashMap>, - /// Number of queued Finished events whose generation has actually drained. - ready_stream_finishes: PendingResetCompletions, - /// Finished events already delivered to the application and therefore - /// eligible to be followed by one terminal reset event. - delivered_stream_finishes: PendingResetCompletions, - /// Forward-TSN updates that belong to a successor hidden behind a - /// still-readable stream generation. - deferred_forward_tsns: FxHashMap>, - - // Non-RFC internal data - remote_addr: SocketAddr, - local_ip: Option, - source_port: u16, - destination_port: u16, - my_max_num_inbound_streams: u16, - my_max_num_outbound_streams: u16, - my_cookie: Option, - - payload_queue: PayloadQueue, - outbound_queue: OutboundQueue, - control_queue: VecDeque, - stream_queue: VecDeque, - - pub(crate) mtu: u32, - // max DATA chunk payload size - max_payload_size: u32, - cumulative_tsn_ack_point: u32, - advanced_peer_tsn_ack_point: u32, - use_forward_tsn: bool, - - pub(crate) rto_mgr: RtoManager, - timers: TimerTable, - - // Congestion control parameters - max_receive_buffer_size: u32, - // my congestion window size - pub(crate) cwnd: u32, - // calculated peer's receiver windows size - rwnd: u32, - // slow start threshold - pub(crate) ssthresh: u32, - partial_bytes_acked: u32, - pub(crate) in_fast_recovery: bool, - fast_recover_exit_point: u32, - - // Chunks stored for retransmission - stored_init: Option, - stored_cookie_echo: Option, - pub(crate) streams: FxHashMap, - - events: VecDeque, - endpoint_events: VecDeque, - error: Option, - - // per inbound packet context - delayed_ack_triggered: bool, - immediate_ack_triggered: bool, - - pub(crate) stats: AssociationStats, - ack_state: AckState, - - // for testing - pub(crate) ack_mode: AckMode, -} - -impl Default for Association { - fn default() -> Self { - Association { - side: Side::default(), - state: AssociationState::default(), - handshake_completed: false, - max_send_message_size: 0, - max_receive_message_size: 0, - inflight_queue_length: 0, - will_send_shutdown: false, - next_stream_generation: 0, - bytes_received: 0, - bytes_sent: 0, - - peer_verification_tag: 0, - my_verification_tag: 0, - my_next_tsn: 0, - peer_last_tsn: 0, - // for RTT measurement - min_tsn2measure_rtt: 0, - will_send_forward_tsn: false, - will_retransmit_fast: false, - will_retransmit_reconfig: false, - - will_send_shutdown_ack: false, - will_send_shutdown_complete: false, - - // Reconfig - my_next_rsn: 0, - reconfigs: FxHashMap::default(), - reconfig_reset_streams: FxHashMap::default(), - active_reconfig: None, - pending_reset_streams: VecDeque::default(), - reconfig_requests: FxHashMap::default(), - deferred_reset_data: FxHashMap::default(), - max_completed_reconfig_rsn: None, - peer_last_reconfig_rsn: 0, - peer_reconfig_rsn_initialized: false, - pending_reset_completions: PendingResetCompletions::default(), - failed_reset_streams: FxHashSet::default(), - retiring_streams: FxHashMap::default(), - ready_stream_finishes: PendingResetCompletions::default(), - delivered_stream_finishes: PendingResetCompletions::default(), - deferred_forward_tsns: FxHashMap::default(), - - // Non-RFC internal data - remote_addr: SocketAddr::from_str("0.0.0.0:0").unwrap(), - local_ip: None, - source_port: 0, - destination_port: 0, - my_max_num_inbound_streams: 0, - my_max_num_outbound_streams: 0, - my_cookie: None, - - payload_queue: PayloadQueue::default(), - outbound_queue: OutboundQueue::default(), - control_queue: VecDeque::default(), - stream_queue: VecDeque::default(), - - mtu: 0, - // max DATA chunk payload size - max_payload_size: 0, - cumulative_tsn_ack_point: 0, - advanced_peer_tsn_ack_point: 0, - use_forward_tsn: false, - - rto_mgr: RtoManager::default(), - timers: TimerTable::default(), - - // Congestion control parameters - max_receive_buffer_size: 0, - // my congestion window size - cwnd: 0, - // calculated peer's receiver windows size - rwnd: 0, - // slow start threshold - ssthresh: 0, - partial_bytes_acked: 0, - in_fast_recovery: false, - fast_recover_exit_point: 0, - - // Chunks stored for retransmission - stored_init: None, - stored_cookie_echo: None, - streams: FxHashMap::default(), - - events: VecDeque::default(), - endpoint_events: VecDeque::default(), - error: None, - - // per inbound packet context - delayed_ack_triggered: false, - immediate_ack_triggered: false, - - stats: AssociationStats::default(), - ack_state: AckState::default(), - - // for testing - ack_mode: AckMode::default(), - } - } -} - -impl Association { - fn new_common( - config: Arc, - max_payload_size: u32, - remote_addr: SocketAddr, - local_ip: Option, - side: Side, - verification_tag: u32, - initial_tsn: u32, - ) -> Self { - // It's a bit strange, but we're going backwards from the calculation in - // config.rs to get max_payload_size from INITIAL_MTU. - let mtu = max_payload_size + COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE; - - // RFC 4960 Sec 7.2.1 - // The initial cwnd before DATA transmission or after a sufficiently - // long idle period MUST be set to min(4*MTU, max (2*MTU, 4380bytes)). - let cwnd = (4 * mtu).min((2 * mtu).max(4380)); - - Association { - side, - handshake_completed: false, - max_receive_buffer_size: config.max_receive_buffer_size(), - max_send_message_size: config.max_send_message_size(), - max_receive_message_size: config.max_receive_message_size(), - my_max_num_outbound_streams: config.max_num_outbound_streams(), - my_max_num_inbound_streams: config.max_num_inbound_streams(), - max_payload_size, - - rto_mgr: RtoManager::new(config.rto_initial_ms(), config.rto_min_ms(), config.rto_max_ms()), - timers: TimerTable::new( - config.max_init_retransmits(), - config.max_data_retransmits(), - config.rto_max_ms(), - ), - - mtu, - cwnd, - remote_addr, - local_ip, - - source_port: config.local_port(), - destination_port: config.remote_port(), - - my_verification_tag: verification_tag, - my_next_tsn: initial_tsn, - my_next_rsn: initial_tsn, - min_tsn2measure_rtt: initial_tsn, - cumulative_tsn_ack_point: initial_tsn.wrapping_sub(1), - advanced_peer_tsn_ack_point: initial_tsn.wrapping_sub(1), - error: None, - - ..Default::default() - } - } - - pub(crate) fn new( - server_config: Option>, - config: Arc, - max_payload_size: u32, - local_aid: AssociationId, - remote_addr: SocketAddr, - local_ip: Option, - now: Instant, - ) -> Self { - let side = if server_config.is_some() { - Side::Server - } else { - Side::Client - }; - - let tsn = random::().get(); - - let mut this = Self::new_common(config, max_payload_size, remote_addr, local_ip, side, local_aid, tsn); - - if side.is_client() { - let mut init = ChunkInit { - initial_tsn: this.my_next_tsn, - num_outbound_streams: this.my_max_num_outbound_streams, - num_inbound_streams: this.my_max_num_inbound_streams, - initiate_tag: this.my_verification_tag, - advertised_receiver_window_credit: this.max_receive_buffer_size, - ..Default::default() - }; - init.set_supported_extensions(); - - this.set_state(AssociationState::CookieWait); - this.stored_init = Some(init); - let _ = this.send_init(); - this.timers.start(Timer::T1Init, now, this.rto_mgr.get_rto()); - } - - this - } - - /// Creates a new association using out-of-band exchanged SNAP tokens (INIT chunks). - /// - /// This allows skipping the SCTP 4-way handshake (RFC 4960 Section 5.1) - /// by exchanging tokens out-of-band (e.g., via a signaling channel - /// using SDP `a=sctp-init`). The association immediately transitions to - /// the ESTABLISHED state. - /// - /// **Note:** When using SNAP, **both** peers must call - /// [`Endpoint::connect`](crate::vendor::sctp_proto::Endpoint::connect). There is no - /// server-side SNAP via [`Endpoint::handle`](crate::vendor::sctp_proto::Endpoint::handle). - /// - /// See [draft-hancke-tsvwg-snap-01](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). - /// - /// # Arguments - /// * `config` - Transport configuration. - /// * `max_payload_size` - Maximum payload size. - /// * `remote_addr` - Remote socket address. - /// * `local_ip` - Optional local IP address. - /// * `local_init` - Parsed local token (INIT chunk). - /// * `remote_init` - Parsed remote token (INIT chunk). - /// - /// # Returns - /// A new association in the ESTABLISHED state, or an error if the - /// tokens are invalid. - pub(crate) fn new_with_out_of_band_init( - config: Arc, - max_payload_size: u32, - remote_addr: SocketAddr, - local_ip: Option, - local_init: ChunkInit, - remote_init: ChunkInit, - ) -> Result { - // Derive side deterministically: the peer with the lower initiate_tag - // acts as server so that log lines are distinguishable. This is purely - // cosmetic - equal tags are impossible because the caller in - // `connect_with_snap` rejects that case with `AidCollision`. - let side = if local_init.initiate_tag <= remote_init.initiate_tag { - Side::Server - } else { - Side::Client - }; - - // Use the TSN from our local INIT chunk - let tsn = local_init.initial_tsn; - - let mut this = Self::new_common( - config.clone(), - max_payload_size, - remote_addr, - local_ip, - side, - local_init.initiate_tag, - tsn, - ); - - // Negotiate stream counts: use the smaller of our config limit and - // what the remote offers (RFC 4960 §5.1.1 cross-negotiation). - this.my_max_num_inbound_streams = - core::cmp::min(config.max_num_inbound_streams(), remote_init.num_outbound_streams); - this.my_max_num_outbound_streams = - core::cmp::min(config.max_num_outbound_streams(), remote_init.num_inbound_streams); - - this.peer_verification_tag = remote_init.initiate_tag; - - this.handshake_completed = true; - - this.apply_remote_init_params( - remote_init.initial_tsn, - remote_init.advertised_receiver_window_credit, - &remote_init.params, - "out-of-band init", - ); - - // Set state to ESTABLISHED - out-of-band init skips the handshake - this.set_state(AssociationState::Established); - this.events.push_back(Event::Connected); - - debug!( - "[{}] out-of-band init association established: my_tag={:#x} peer_tag={:#x} tsn={}", - this.side, this.my_verification_tag, this.peer_verification_tag, this.my_next_tsn - ); - - Ok(this) - } - - /// Returns application-facing event - /// - /// Associations should be polled for events after: - /// - a call was made to `handle_event` - /// - a call was made to `handle_timeout` - #[must_use] - pub fn poll(&mut self) -> Option { - // A reset boundary can become cumulative after its DATA was made - // readable. Keep events for that stream generation behind Finished, - // while allowing unrelated association and stream events to progress. - let mut blocked_streams = FxHashSet::default(); - let mut selected = None; - for (index, event) in self.events.iter().enumerate() { - if let Event::Stream(StreamEvent::Finished { id }) = event { - if self.state != AssociationState::Closed && !self.ready_stream_finishes.contains(id) { - blocked_streams.insert(*id); - continue; - } - } - - if let Event::Stream(stream_event) = event { - let stream_id = match stream_event { - StreamEvent::Opened { id } - | StreamEvent::Readable { id } - | StreamEvent::Writable { id } - | StreamEvent::Finished { id } - | StreamEvent::ResetComplete { id } - | StreamEvent::ResetFailed { id, .. } - | StreamEvent::Stopped { id, .. } - | StreamEvent::BufferedAmountLow { id } - | StreamEvent::BufferedAmountHigh { id } => Some(*id), - StreamEvent::Available => None, - }; - if let Some(stream_id) = stream_id { - if blocked_streams.contains(&stream_id) { - let terminal_for_delivered_generation = - matches!( - stream_event, - StreamEvent::ResetComplete { .. } | StreamEvent::ResetFailed { .. } - ) && self.delivered_stream_finishes.contains(&stream_id); - let readable_current_generation = - matches!(stream_event, StreamEvent::Opened { .. } | StreamEvent::Readable { .. }); - if !terminal_for_delivered_generation && !readable_current_generation { - continue; - } - } - } - } - - selected = Some(index); - break; - } - - if let Some(index) = selected { - let x = self.events.remove(index).expect("selected event must exist"); - match &x { - Event::Stream(StreamEvent::Finished { id }) => { - self.ready_stream_finishes.take_one(*id); - if self.state != AssociationState::Closed { - self.delivered_stream_finishes.insert(*id); - } - } - Event::Stream(StreamEvent::ResetComplete { id } | StreamEvent::ResetFailed { id, .. }) => { - self.delivered_stream_finishes.take_one(*id); - } - _ => {} - } - return Some(x); - } - - /*TODO: if let Some(event) = self.streams.poll() { - return Some(Event::Stream(event)); - }*/ - - if let Some(err) = self.error.take() { - return Some(Event::HandshakeFailed { reason: err }); - } - - None - } - - /// Return endpoint-facing event - #[must_use] - pub fn poll_endpoint_event(&mut self) -> Option { - self.endpoint_events.pop_front().map(EndpointEvent) - } - - /// Returns the next time at which `handle_timeout` should be called - /// - /// The value returned may change after: - /// - the application performed some I/O on the association - /// - a call was made to `handle_transmit` - /// - a call to `poll_transmit` returned `Some` - /// - a call was made to `handle_timeout` - #[must_use] - pub fn poll_timeout(&self) -> Option { - self.timers.next_timeout() - } - - /// Returns packets to transmit - /// - /// Associations should be polled for transmit after: - /// - the application performed some I/O on the Association - /// - a call was made to `handle_event` - /// - a call was made to `handle_timeout` - #[must_use] - pub fn poll_transmit(&mut self, now: Instant) -> Option { - let (contents, _) = self.gather_outbound(now); - if contents.is_empty() { - None - } else { - trace!( - "[{}] sending {} bytes (total {} datagrams)", - self.side, - contents.iter().fold(0, |l, c| l + c.len()), - contents.len() - ); - Some(Transmit { - now, - remote: self.remote_addr, - payload: Payload::RawEncode(contents), - ecn: None, - local_ip: self.local_ip, - }) - } - } - - /// Process timer expirations - /// - /// Executes protocol logic, potentially preparing signals (including application `Event`s, - /// `EndpointEvent`s and outgoing datagrams) that should be extracted through the relevant - /// methods. - /// - /// It is most efficient to call this immediately after the system clock reaches the latest - /// `Instant` that was output by `poll_timeout`; however spurious extra calls will simply - /// no-op and therefore are safe. - pub fn handle_timeout(&mut self, now: Instant) { - for &timer in &Timer::VALUES { - let (expired, failure, n_rtos) = self.timers.is_expired(timer, now); - if !expired { - continue; - } - self.timers.set(timer, None); - - if timer == Timer::Ack { - self.on_ack_timeout(); - } else if failure { - self.on_retransmission_failure(timer); - } else { - self.on_retransmission_timeout(timer, n_rtos); - self.timers.start(timer, now, self.rto_mgr.get_rto()); - } - } - } - - /// Process `AssociationEvent`s generated by the associated `Endpoint` - /// - /// Will execute protocol logic upon receipt of an association event, in turn preparing signals - /// (including application `Event`s, `EndpointEvent`s and outgoing datagrams) that should be - /// extracted through the relevant methods. - pub fn handle_event(&mut self, event: AssociationEvent) { - match event.0 { - AssociationEventInner::Datagram(transmit) => { - // If this packet could initiate a migration and we're a client or a server that - // forbids migration, drop the datagram. This could be relaxed to heuristically - // permit NAT-rebinding-like migration. - /*TODO:if remote != self.remote && self.server_config.as_ref().map_or(true, |x| !x.migration) - { - trace!("discarding packet from unrecognized peer {}", remote); - return; - }*/ - - if let Payload::PartialDecode(partial_decode) = transmit.payload { - trace!( - "[{}] receiving {} bytes", - self.side, - COMMON_HEADER_SIZE as usize + partial_decode.remaining.len() - ); - - let pkt = match partial_decode.finish() { - Ok(p) => p, - Err(err) => { - warn!("[{}] unable to parse SCTP packet {}", self.side, err); - return; - } - }; - - if let Err(err) = self.handle_inbound(pkt, transmit.now) { - error!("handle_inbound got err: {}", err); - if err == Error::ErrReceiveBufferExhausted { - self.abort_receive_capacity(); - } else { - let _ = self.close(); - } - } - } else { - trace!("discarding invalid partial_decode"); - } - } //TODO: - } - } - - fn receive_capacity_exhausted(&self) -> bool { - self.get_my_receiver_window_credit() == 0 - && (!self.deferred_reset_data.is_empty() - || self.streams.values().any(|s| s.get_num_bytes_in_reassembly_queue() > 0)) - && self.payload_queue.is_empty() - && !self.streams.values().any(|s| { - matches!(s.state, RecvSendState::Readable | RecvSendState::ReadWritable) - && s.reassembly_queue.is_readable() - }) - } - - fn abort_receive_capacity(&mut self) { - let _ = self.close_with_reason(AssociationError::ReceiveBufferExhausted); - let abort = ChunkAbort { - error_causes: vec![crate::vendor::sctp_proto::chunk::ErrorCause { - code: crate::vendor::sctp_proto::chunk::OUT_OF_RESOURCE, - raw: Bytes::new(), - }], - }; - self.control_queue.push_back(self.create_packet(vec![Box::new(abort)])); - } - - /// Returns Association statistics - pub fn stats(&self) -> AssociationStats { - self.stats - } - - /// Whether the Association is in the process of being established - /// - /// If this returns `false`, the Association may be either established or closed, signaled by the - /// emission of a `Connected` or `AssociationLost` message respectively. - pub fn is_handshaking(&self) -> bool { - !self.handshake_completed - } - - /// Whether the Association is closed - /// - /// Closed Associations cannot transport any further data. An association becomes closed when - /// either peer application intentionally closes it, or when either transport layer detects an - /// error such as a time-out or certificate validation failure. - /// - /// A `AssociationLost` event is emitted with details when the association becomes closed. - pub fn is_closed(&self) -> bool { - self.state == AssociationState::Closed - } - - /// Whether the Association has started SCTP shutdown, but is not closed yet - /// - /// Closing Associations may still need polling, timer-driven retransmission, and packet output - /// before they become fully closed. - pub fn is_closing(&self) -> bool { - self.state.is_closing() - } - - /// Whether there is no longer any need to keep the association around - /// - /// Closed associations become drained after a brief timeout to absorb any remaining in-flight - /// packets from the peer. All drained associations have been closed. - pub fn is_drained(&self) -> bool { - self.state.is_drained() - } - - /// Look up whether we're the client or server of this Association - pub fn side(&self) -> Side { - self.side - } - - /// The latest socket address for this Association's peer - pub fn remote_addr(&self) -> SocketAddr { - self.remote_addr - } - - /// Current best estimate of this Association's latency (round-trip-time) - pub fn rtt(&self) -> Duration { - Duration::from_millis(self.rto_mgr.get_rto()) - } - - /// The local IP address which was used when the peer established - /// the association - /// - /// This can be different from the address the endpoint is bound to, in case - /// the endpoint is bound to a wildcard address like `0.0.0.0` or `::`. - /// - /// This will return `None` for clients. - /// - /// Retrieving the local IP address is currently supported on the following - /// platforms: - /// - Linux - /// - /// On all non-supported platforms the local IP address will not be available, - /// and the method will return `None`. - pub fn local_ip(&self) -> Option { - self.local_ip - } - - /// Shutdown initiates the shutdown sequence. The method blocks until the - /// shutdown sequence is completed and the association is closed, or until the - /// passed context is done, in which case the context's error is returned. - pub fn shutdown(&mut self) -> Result<()> { - debug!("[{}] closing association..", self.side); - - let state = self.state(); - if state != AssociationState::Established { - return Err(Error::ErrShutdownNonEstablished); - } - - // Attempt a graceful shutdown. - self.set_state(AssociationState::ShutdownPending); - - if self.inflight_queue_length == 0 { - // No more outstanding, send shutdown. - self.will_send_shutdown = true; - self.awake_write_loop(); - self.set_state(AssociationState::ShutdownSent); - } - - self.endpoint_events.push_back(EndpointEventInner::Drained); - - Ok(()) - } - - /// Close ends the SCTP Association and cleans up any state - pub fn close(&mut self) -> Result<()> { - self.close_with_reason(AssociationError::AssociationClosed) - } - - fn close_with_reason(&mut self, reason: AssociationError) -> Result<()> { - if self.state() != AssociationState::Closed { - self.set_state(AssociationState::Closed); - - debug!("[{}] closing association..", self.side); - - self.close_all_timers(); - - for si in self.streams.keys().cloned().collect::>() { - self.unregister_stream(si, false); - } - - // AssociationLost stops any pending ResetComplete. - self.pending_reset_completions.clear(); - self.failed_reset_streams.clear(); - self.retiring_streams.clear(); - self.ready_stream_finishes.clear(); - self.delivered_stream_finishes.clear(); - self.deferred_forward_tsns.clear(); - self.pending_reset_streams.clear(); - self.reconfigs.clear(); - self.reconfig_reset_streams.clear(); - self.reconfig_requests.clear(); - self.deferred_reset_data.clear(); - self.control_queue.clear(); - self.active_reconfig = None; - self.will_retransmit_reconfig = false; - - self.events.push_back(Event::AssociationLost { reason }); - - debug!("[{}] association closed", self.side); - debug!("[{}] stats nDATAs (in) : {}", self.side, self.stats.get_num_datas()); - debug!("[{}] stats nSACKs (in) : {}", self.side, self.stats.get_num_sacks()); - debug!( - "[{}] stats nT3Timeouts : {}", - self.side, - self.stats.get_num_t3timeouts() - ); - debug!( - "[{}] stats nAckTimeouts: {}", - self.side, - self.stats.get_num_ack_timeouts() - ); - debug!( - "[{}] stats nFastRetrans: {}", - self.side, - self.stats.get_num_fast_retrans() - ); - } - - Ok(()) - } - - /// open_stream opens a stream - pub fn open_stream( - &mut self, - stream_identifier: StreamId, - default_payload_type: PayloadProtocolIdentifier, - ) -> Result> { - if self.streams.contains_key(&stream_identifier) { - return Err(Error::ErrStreamAlreadyExist); - } - - if self.stream_reset_blocked(stream_identifier) { - return Err(Error::ErrStreamResetPending); - } - - if let Some(s) = self.create_stream(stream_identifier, false, default_payload_type) { - Ok(s) - } else { - Err(Error::ErrStreamCreateFailed) - } - } - - /// accept_stream accepts a stream - pub fn accept_stream(&mut self) -> Option> { - self.stream_queue.pop_front().map(move |stream_identifier| Stream { - stream_identifier, - association: self, - }) - } - - /// stream returns a stream - pub fn stream(&mut self, stream_identifier: StreamId) -> Result> { - if !self.streams.contains_key(&stream_identifier) { - Err(Error::ErrStreamNotExisted) - } else { - Ok(Stream { - stream_identifier, - association: self, - }) - } - } - - /// stream_ids returns a list of all active stream identifiers - pub fn stream_ids(&self) -> Vec { - self.streams.keys().cloned().collect() - } - - /// bytes_sent returns the number of bytes sent - pub(crate) fn bytes_sent(&self) -> usize { - self.bytes_sent - } - - /// bytes_received returns the number of bytes received - pub(crate) fn bytes_received(&self) -> usize { - self.bytes_received - } - - /// max_send_message_size returns the maximum message size you can send. - pub(crate) fn max_send_message_size(&self) -> u32 { - self.max_send_message_size - } - - /// set_max_send_message_size sets the maximum message size you can send. - pub fn set_max_send_message_size(&mut self, value: u32) { - self.max_send_message_size = value; - } - - /// max_receive_message_size returns the maximum message size accepted. - pub(crate) fn max_receive_message_size(&self) -> u32 { - self.max_receive_message_size - } - - /// set_max_receive_message_size sets the maximum message size accepted. - pub(crate) fn set_max_receive_message_size(&mut self, value: u32) { - self.max_receive_message_size = value; - } - - /// max_message_size returns the maximum message size you can send. - #[deprecated(note = "Use max_send_message_size instead")] - pub(crate) fn max_message_size(&self) -> u32 { - self.max_send_message_size() - } - - /// set_max_message_size sets the maximum message size you can send. - #[deprecated(note = "Use set_max_send_message_size instead")] - pub(crate) fn set_max_message_size(&mut self, value: u32) { - self.set_max_send_message_size(value) - } - - /// Push one [`StreamEvent::ResetComplete`] for each candidate id whose reset - /// handshake has completed and `Finished` has already been fired for it. - fn emit_reset_complete(&mut self, ids: impl IntoIterator) { - for id in ids { - let notify = self.pending_reset_completions.take_one(id); - // Requests are serialized, so a success supersedes any older failure - // for the same stream id. A newer pending generation still blocks reuse. - self.failed_reset_streams.remove(&id); - let reset_blocked = self.stream_reset_blocked(id); - if !reset_blocked { - let application_closed = notify - && self - .streams - .get(&id) - .is_some_and(|stream| matches!(stream.state, RecvSendState::Closed | RecvSendState::Writable)); - if application_closed { - self.unregister_stream(id, false); - } else if let Some(stream) = self.streams.get_mut(&id) { - // RFC 6525 section 5.2.7 H4 resets the outgoing SSN. Do not - // alter `state`: a protocol reset must never undo an - // application-level `Stream::finish()`. - stream.sequence_number = 0; - } - } - if notify { - self.events.push_back(Event::Stream(StreamEvent::ResetComplete { id })); - } - } - } - - /// Report a terminal reset failure and keep the stream id quarantined. - fn emit_reset_failed(&mut self, ids: impl IntoIterator, reason: StreamResetError) { - for id in ids { - self.pending_reset_completions.take_one(id); - self.failed_reset_streams.insert(id); - self.events - .push_back(Event::Stream(StreamEvent::ResetFailed { id, reason })); - } - } - - /// Returns true if the given stream ID appears in any pending outgoing - /// RE-CONFIG that has not yet been acknowledged by the remote peer. - fn has_pending_reset_for_stream(&self, stream_id: StreamId) -> bool { - self.reconfigs.values().any(|c| { - c.param_a - .iter() - .chain(c.param_b.iter()) - .find_map(|p| p.as_any().downcast_ref::()) - .is_some_and(|p| Self::reset_request_affects_stream(p, stream_id)) - }) - } - - fn reset_request_affects_stream(request: &ParamOutgoingResetRequest, stream_id: StreamId) -> bool { - request.stream_identifiers.is_empty() || request.stream_identifiers.contains(&stream_id) - } - - /// Whether the current generation of a stream id is unsafe to send or reuse. - fn stream_reset_blocked(&self, stream_id: StreamId) -> bool { - self.pending_reset_completions.contains(&stream_id) - || self.failed_reset_streams.contains(&stream_id) - || self.retiring_streams.contains_key(&stream_id) - || self.stream_reset_in_progress(stream_id) - } - - /// Whether a request currently prevents assigning new SSNs for this stream. - fn stream_reset_in_progress(&self, stream_id: StreamId) -> bool { - self.pending_reset_streams.contains(&stream_id) || self.has_pending_reset_for_stream(stream_id) - } - - fn reconfig_stream_ids(c: &ChunkReconfig) -> Vec { - c.param_a - .iter() - .chain(c.param_b.iter()) - .find_map(|p| p.as_any().downcast_ref::()) - .map(|p| p.stream_identifiers.clone()) - .unwrap_or_default() - } - - fn packet_reconfig_request_rsn(packet: &Packet) -> Option { - packet.chunks.iter().find_map(|chunk| { - let reconfig = chunk.as_any().downcast_ref::()?; - reconfig - .param_a - .iter() - .chain(reconfig.param_b.iter()) - .find_map(|param| { - param - .as_any() - .downcast_ref::() - .map(|request| request.reconfig_request_sequence_number) - }) - }) - } - - fn reconfig_with_sender_last_tsn(c: &ChunkReconfig, sender_last_tsn: u32) -> ChunkReconfig { - fn update( - param: &Option>, - sender_last_tsn: u32, - ) -> Option> { - param.as_ref().map(|param| { - if let Some(request) = param.as_any().downcast_ref::() { - let mut request = request.clone(); - request.sender_last_tsn = sender_last_tsn; - Box::new(request) as Box - } else { - param.clone() - } - }) - } - - ChunkReconfig { - param_a: update(&c.param_a, sender_last_tsn), - param_b: update(&c.param_b, sender_last_tsn), - } - } - - fn reconfig_has_pending_data(&self, rsn: u32) -> bool { - self.reconfigs.get(&rsn).is_some_and(|c| { - let stream_ids = Self::reconfig_stream_ids(c); - if stream_ids.is_empty() { - self.outbound_queue.pending_len() != 0 - } else { - stream_ids - .iter() - .any(|id| self.outbound_queue.pending_contains_stream(*id)) - } - }) - } - - fn refresh_unsent_reconfig(&mut self, rsn: u32) -> Option { - let sender_last_tsn = self.my_next_tsn.wrapping_sub(1); - let reconfig = self - .reconfigs - .get(&rsn) - .map(|c| Self::reconfig_with_sender_last_tsn(c, sender_last_tsn))?; - self.reconfigs.insert(rsn, reconfig.clone()); - Some(self.create_packet(vec![Box::new(reconfig)])) - } - - /// Finish the one request associated with the running Re-configuration Timer. - fn finish_reconfig(&mut self, rsn: u32, outcome: core::result::Result<(), StreamResetError>) -> bool { - if self.active_reconfig != Some(rsn) { - return false; - } - - let fallback_ids = self - .reconfigs - .remove(&rsn) - .map(|c| Self::reconfig_stream_ids(&c)) - .unwrap_or_default(); - let ids = self.reconfig_reset_streams.remove(&rsn).unwrap_or(fallback_ids); - self.active_reconfig = None; - self.will_retransmit_reconfig = false; - self.timers.stop(Timer::Reconfig); - - match outcome { - Ok(()) => self.emit_reset_complete(ids), - Err(reason) => self.emit_reset_failed(ids, reason), - } - - // A buffered request or locally queued reset can now become active. - self.awake_write_loop(); - true - } - - /// unregister_stream un-registers a stream from the association - /// The caller should hold the association write lock. - fn unregister_stream(&mut self, stream_identifier: StreamId, emit_stream_finished: bool) { - if let Some(mut s) = self.streams.remove(&stream_identifier) { - debug!("[{}] unregister_stream {}", self.side, stream_identifier); - self.events.push_back(Event::DataChannelStatsFinal(s.stats)); - s.state = RecvSendState::Closed; - if emit_stream_finished { - self.queue_stream_finished(stream_identifier, true); - } - } - } - - fn queue_stream_finished(&mut self, stream_identifier: StreamId, ready: bool) { - self.events - .push_back(Event::Stream(StreamEvent::Finished { id: stream_identifier })); - // Every Finished owes a terminal reset event, even if the peer - // re-creates the stream id before the handshake completes. - self.pending_reset_completions.insert(stream_identifier); - if ready { - self.ready_stream_finishes.insert(stream_identifier); - } - } - - /// Queue the end of an incoming stream generation while preserving any - /// already-acknowledged DATA until the application drains it. - fn retire_stream(&mut self, stream_identifier: StreamId, sender_last_tsn: u32) { - if let Some(boundaries) = self.retiring_streams.get_mut(&stream_identifier) { - boundaries.push_back(sender_last_tsn); - if let Some(updates) = self.deferred_forward_tsns.get_mut(&stream_identifier) { - for update in updates { - if update.generation_boundary.is_none() { - update.generation_boundary = Some(sender_last_tsn); - } - } - } - self.queue_stream_finished(stream_identifier, false); - return; - } - - let has_readable_data = self.streams.get(&stream_identifier).is_some_and(|stream| { - matches!(stream.state, RecvSendState::Readable | RecvSendState::ReadWritable) - && stream.get_num_bytes_in_reassembly_queue() != 0 - }); - - if !has_readable_data { - self.deferred_forward_tsns.remove(&stream_identifier); - self.unregister_stream(stream_identifier, true); - return; - } - - if let Some(updates) = self.deferred_forward_tsns.get_mut(&stream_identifier) { - for update in updates { - if update.generation_boundary.is_none() { - update.generation_boundary = Some(sender_last_tsn); - } - } - } - let mut boundaries = VecDeque::new(); - boundaries.push_back(sender_last_tsn); - self.retiring_streams.insert(stream_identifier, boundaries); - self.queue_stream_finished(stream_identifier, false); - } - - /// Drop a drained old generation and release DATA held for its successor. - pub(crate) fn finish_retiring_stream(&mut self, stream_identifier: StreamId) -> Result<()> { - if !self.retiring_streams.contains_key(&stream_identifier) { - return Ok(()); - } - - let inherited_state = self - .streams - .get(&stream_identifier) - .map(|stream| stream.state) - .unwrap_or(RecvSendState::ReadWritable); - if let Some(mut stream) = self.streams.remove(&stream_identifier) { - self.events.push_back(Event::DataChannelStatsFinal(stream.stats)); - stream.state = RecvSendState::Closed; - } - - loop { - let (completed_boundary, next_boundary) = { - let boundaries = self - .retiring_streams - .get_mut(&stream_identifier) - .expect("retiring stream must retain a boundary"); - let completed = boundaries - .pop_front() - .expect("retiring stream must have a current generation"); - (completed, boundaries.front().copied()) - }; - self.discard_deferred_forward_tsns_through(stream_identifier, completed_boundary); - self.ready_stream_finishes.insert(stream_identifier); - - let Some(next_boundary) = next_boundary else { - self.retiring_streams.remove(&stream_identifier); - let result = self.release_deferred_reset_data(); - self.inherit_stream_state(stream_identifier, inherited_state); - return result; - }; - - self.release_deferred_generation_data(stream_identifier, completed_boundary, next_boundary)?; - self.inherit_stream_state(stream_identifier, inherited_state); - - let has_unread_data = self - .streams - .get(&stream_identifier) - .is_some_and(|stream| stream.get_num_bytes_in_reassembly_queue() != 0); - if has_unread_data { - return Ok(()); - } - - // This generation contained no deliverable DATA. Its already-queued - // Finished event can become ready immediately, and any forwarding - // state scoped to it must not leak into the following generation. - if let Some(mut stream) = self.streams.remove(&stream_identifier) { - self.events.push_back(Event::DataChannelStatsFinal(stream.stats)); - stream.state = RecvSendState::Closed; - } - self.discard_deferred_forward_tsns_through(stream_identifier, next_boundary); - } - } - - fn inherit_stream_state(&mut self, stream_identifier: StreamId, inherited_state: RecvSendState) { - if let Some(stream) = self.streams.get_mut(&stream_identifier) { - stream.state = ((stream.state as u8) & (inherited_state as u8)).into(); - } - } - - /// Close every retained incoming generation without replaying its DATA. - /// The current StreamState is kept so an application-owned write half and - /// its configuration survive a read-side stop. - pub(crate) fn discard_retiring_streams(&mut self, stream_identifier: StreamId) { - let Some(boundaries) = self.retiring_streams.remove(&stream_identifier) else { - return; - }; - - for _ in boundaries { - self.ready_stream_finishes.insert(stream_identifier); - } - let discarded_tsns: Vec = self - .deferred_reset_data - .iter() - .filter_map(|(tsn, chunk)| (chunk.stream_identifier == stream_identifier).then_some(*tsn)) - .collect(); - for tsn in discarded_tsns { - self.payload_queue.mark_as_acked(tsn); - } - self.deferred_reset_data - .retain(|_, chunk| chunk.stream_identifier != stream_identifier); - self.deferred_forward_tsns.remove(&stream_identifier); - self.events.retain(|event| { - !matches!( - event, - Event::Stream( - StreamEvent::Opened { id } | StreamEvent::Readable { id } - ) if *id == stream_identifier - ) - }); - - if let Some(stream) = self.streams.get_mut(&stream_identifier) { - stream.reassembly_queue = ReassemblyQueue::new(stream_identifier, self.max_receive_message_size); - } - if !self.stream_reset_blocked(stream_identifier) { - self.unregister_stream(stream_identifier, false); - } - } - - /// set_state atomically sets the state of the Association. - fn set_state(&mut self, new_state: AssociationState) { - if new_state != self.state { - debug!("[{}] state change: '{}' => '{}'", self.side, self.state, new_state,); - } - self.state = new_state; - } - - /// state atomically returns the state of the Association. - pub(crate) fn state(&self) -> AssociationState { - self.state - } - - /// Apply common remote-side parameters from an INIT or INIT-ACK chunk. - /// - /// Sets `peer_last_tsn`, `rwnd`, `ssthresh`, and `use_forward_tsn` based - /// on the remote peer's initial TSN, advertised window, and supported - /// extensions. Used by `handle_init`, `handle_init_ack`, and - /// `new_with_out_of_band_init`. - fn apply_remote_init_params( - &mut self, - initial_tsn: u32, - advertised_receiver_window_credit: u32, - params: &[Box], - context: &str, - ) { - // RFC 4960 §13.2: peer_last_tsn is the peer's initial TSN minus one. - self.peer_last_tsn = initial_tsn.wrapping_sub(1); - // RFC 6525 §4: the peer's first request sequence number is its initial - // TSN, so A4's initial response value is one less than that. - self.peer_last_reconfig_rsn = initial_tsn.wrapping_sub(1); - self.peer_reconfig_rsn_initialized = true; - - self.rwnd = advertised_receiver_window_credit; - debug!("[{}] initial rwnd={}", self.side, self.rwnd); - - // RFC 4960 Sec 7.2.1 - // o The initial value of ssthresh MAY be arbitrarily high (for - // example, implementations MAY use the size of the receiver - // advertised window). - self.ssthresh = self.rwnd; - trace!( - "[{}] updated cwnd={} ssthresh={} inflight={} ({})", - self.side, - self.cwnd, - self.ssthresh, - self.outbound_queue.inflight_bytes(), - context, - ); - - for param in params { - if let Some(v) = param.as_any().downcast_ref::() { - for t in &v.chunk_types { - if *t == CT_FORWARD_TSN { - debug!("[{}] use ForwardTSN (on {})", self.side, context); - self.use_forward_tsn = true; - } - } - } - } - if !self.use_forward_tsn { - warn!("[{}] not using ForwardTSN (on {})", self.side, context); - } - } - - /// caller must hold self.lock - fn send_init(&mut self) -> Result<()> { - if let Some(stored_init) = &self.stored_init { - debug!("[{}] sending INIT", self.side); - - let outbound = Packet { - common_header: CommonHeader { - source_port: self.source_port, - destination_port: self.destination_port, - verification_tag: self.peer_verification_tag, - }, - chunks: vec![Box::new(stored_init.clone())], - }; - - self.control_queue.push_back(outbound); - self.awake_write_loop(); - - Ok(()) - } else { - Err(Error::ErrInitNotStoredToSend) - } - } - - /// caller must hold self.lock - fn send_cookie_echo(&mut self) -> Result<()> { - if let Some(stored_cookie_echo) = &self.stored_cookie_echo { - debug!("[{}] sending COOKIE-ECHO", self.side); - - let outbound = Packet { - common_header: CommonHeader { - source_port: self.source_port, - destination_port: self.destination_port, - verification_tag: self.peer_verification_tag, - }, - chunks: vec![Box::new(stored_cookie_echo.clone())], - }; - - self.control_queue.push_back(outbound); - self.awake_write_loop(); - - Ok(()) - } else { - Err(Error::ErrCookieEchoNotStoredToSend) - } - } - - /// handle_inbound parses incoming raw packets - fn handle_inbound(&mut self, p: Packet, now: Instant) -> Result<()> { - if let Err(err) = p.check_packet() { - warn!("[{}] failed validating packet {}", self.side, err); - return Ok(()); - } - - self.handle_chunk_start(); - - for c in &p.chunks { - self.handle_chunk(&p, c, now)?; - } - - self.handle_chunk_end(now); - - Ok(()) - } - - fn handle_chunk_start(&mut self) { - self.delayed_ack_triggered = false; - self.immediate_ack_triggered = false; - } - - fn handle_chunk_end(&mut self, now: Instant) { - if self.immediate_ack_triggered { - self.ack_state = AckState::Immediate; - self.timers.stop(Timer::Ack); - self.awake_write_loop(); - } else if self.delayed_ack_triggered { - // Will send delayed ack in the next ack timeout - self.ack_state = AckState::Delay; - self.timers.start(Timer::Ack, now, ACK_INTERVAL); - } - } - - #[allow(clippy::borrowed_box)] - fn handle_chunk(&mut self, p: &Packet, chunk: &Box, now: Instant) -> Result<()> { - chunk.check()?; - let chunk_any = chunk.as_any(); - let packets = if let Some(c) = chunk_any.downcast_ref::() { - if c.is_ack { - self.handle_init_ack(p, c, now)? - } else { - self.handle_init(p, c)? - } - } else if let Some(c) = chunk_any.downcast_ref::() { - let mut err_str = String::new(); - for e in &c.error_causes { - if matches!(e.code, USER_INITIATED_ABORT) { - debug!("User initiated abort received"); - let _ = self.close(); - return Ok(()); - } - err_str += &format!("({})", e); - } - return Err(Error::ErrAbortChunk(err_str)); - } else if let Some(c) = chunk_any.downcast_ref::() { - let mut err_str = String::new(); - for e in &c.error_causes { - err_str += &format!("({})", e); - } - return Err(Error::ErrAbortChunk(err_str)); - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_heartbeat(c)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_cookie_echo(c)? - } else if chunk_any.downcast_ref::().is_some() { - self.handle_cookie_ack()? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_data(c)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_sack(c, now)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_reconfig(c)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_forward_tsn(c)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_i_forward_tsn(c)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_shutdown(c)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_shutdown_ack(c)? - } else if let Some(c) = chunk_any.downcast_ref::() { - self.handle_shutdown_complete(c)? - } else { - return Err(Error::ErrChunkTypeUnhandled); - }; - - if !packets.is_empty() { - let mut buf: VecDeque<_> = packets.into_iter().collect(); - self.control_queue.append(&mut buf); - self.awake_write_loop(); - } - - Ok(()) - } - - fn handle_init(&mut self, p: &Packet, i: &ChunkInit) -> Result> { - let state = self.state(); - debug!("[{}] chunkInit received in state '{}'", self.side, state); - - // https://tools.ietf.org/html/rfc4960#section-5.2.1 - // Upon receipt of an INIT in the COOKIE-WAIT state, an endpoint MUST - // respond with an INIT ACK using the same parameters it sent in its - // original INIT chunk (including its Initiate Tag, unchanged). When - // responding, the endpoint MUST send the INIT ACK back to the same - // address that the original INIT (sent by this endpoint) was sent. - - if state != AssociationState::Closed - && state != AssociationState::CookieWait - && state != AssociationState::CookieEchoed - { - // 5.2.2. Unexpected INIT in States Other than CLOSED, COOKIE-ECHOED, - // COOKIE-WAIT, and SHUTDOWN-ACK-SENT - return Err(Error::ErrHandleInitState); - } - - // Should we be setting any of these permanently until we've ACKed further? - self.my_max_num_inbound_streams = core::cmp::min(i.num_inbound_streams, self.my_max_num_inbound_streams); - self.my_max_num_outbound_streams = core::cmp::min(i.num_outbound_streams, self.my_max_num_outbound_streams); - self.peer_verification_tag = i.initiate_tag; - self.source_port = p.common_header.destination_port; - self.destination_port = p.common_header.source_port; - - self.apply_remote_init_params(i.initial_tsn, i.advertised_receiver_window_credit, &i.params, "init"); - - let mut outbound = Packet { - common_header: CommonHeader { - verification_tag: self.peer_verification_tag, - source_port: self.source_port, - destination_port: self.destination_port, - }, - chunks: vec![], - }; - - let mut init_ack = ChunkInit { - is_ack: true, - initial_tsn: self.my_next_tsn, - num_outbound_streams: self.my_max_num_outbound_streams, - num_inbound_streams: self.my_max_num_inbound_streams, - initiate_tag: self.my_verification_tag, - advertised_receiver_window_credit: self.max_receive_buffer_size, - ..Default::default() - }; - - if self.my_cookie.is_none() { - self.my_cookie = Some(ParamStateCookie::new()); - } - - if let Some(my_cookie) = &self.my_cookie { - init_ack.params = vec![Box::new(my_cookie.clone())]; - } - - init_ack.set_supported_extensions(); - - outbound.chunks = vec![Box::new(init_ack)]; - - Ok(vec![outbound]) - } - - fn handle_init_ack(&mut self, p: &Packet, i: &ChunkInitAck, now: Instant) -> Result> { - let state = self.state(); - debug!("[{}] chunkInitAck received in state '{}'", self.side, state); - if state != AssociationState::CookieWait { - // RFC 4960 - // 5.2.3. Unexpected INIT ACK - // If an INIT ACK is received by an endpoint in any state other than the - // COOKIE-WAIT state, the endpoint should discard the INIT ACK chunk. - // An unexpected INIT ACK usually indicates the processing of an old or - // duplicated INIT chunk. - return Ok(vec![]); - } - - self.my_max_num_inbound_streams = core::cmp::min(i.num_inbound_streams, self.my_max_num_inbound_streams); - self.my_max_num_outbound_streams = core::cmp::min(i.num_outbound_streams, self.my_max_num_outbound_streams); - self.peer_verification_tag = i.initiate_tag; - if self.source_port != p.common_header.destination_port || self.destination_port != p.common_header.source_port - { - warn!("[{}] handle_init_ack: port mismatch", self.side); - return Ok(vec![]); - } - - self.apply_remote_init_params(i.initial_tsn, i.advertised_receiver_window_credit, &i.params, "initAck"); - - self.timers.stop(Timer::T1Init); - self.stored_init = None; - - let cookie_param = i - .params - .iter() - .find_map(|param| param.as_any().downcast_ref::()); - - if let Some(v) = cookie_param { - self.stored_cookie_echo = Some(ChunkCookieEcho { - cookie: v.cookie.clone(), - }); - - self.send_cookie_echo()?; - - self.timers.start(Timer::T1Cookie, now, self.rto_mgr.get_rto()); - - self.set_state(AssociationState::CookieEchoed); - - Ok(vec![]) - } else { - Err(Error::ErrInitAckNoCookie) - } - } - - fn handle_heartbeat(&self, c: &ChunkHeartbeat) -> Result> { - trace!("[{}] chunkHeartbeat", self.side); - if let Some(p) = c.params.first() { - if let Some(hbi) = p.as_any().downcast_ref::() { - return Ok(vec![Packet { - common_header: CommonHeader { - verification_tag: self.peer_verification_tag, - source_port: self.source_port, - destination_port: self.destination_port, - }, - chunks: vec![Box::new(ChunkHeartbeatAck { - params: vec![Box::new(ParamHeartbeatInfo { - heartbeat_information: hbi.heartbeat_information.clone(), - })], - })], - }]); - } else { - warn!("[{}] failed to handle Heartbeat, no ParamHeartbeatInfo", self.side,); - } - } - - Ok(vec![]) - } - - fn handle_cookie_echo(&mut self, c: &ChunkCookieEcho) -> Result> { - let state = self.state(); - debug!("[{}] COOKIE-ECHO received in state '{}'", self.side, state); - - if let Some(my_cookie) = &self.my_cookie { - match state { - AssociationState::Established => { - if my_cookie.cookie != c.cookie { - return Ok(vec![]); - } - } - AssociationState::Closed | AssociationState::CookieWait | AssociationState::CookieEchoed => { - if my_cookie.cookie != c.cookie { - return Ok(vec![]); - } - - self.timers.stop(Timer::T1Init); - self.stored_init = None; - - self.timers.stop(Timer::T1Cookie); - self.stored_cookie_echo = None; - - self.events.push_back(Event::Connected); - self.set_state(AssociationState::Established); - self.handshake_completed = true; - } - _ => return Ok(vec![]), - }; - } else { - debug!("[{}] COOKIE-ECHO received before initialization", self.side); - return Ok(vec![]); - } - - Ok(vec![Packet { - common_header: CommonHeader { - verification_tag: self.peer_verification_tag, - source_port: self.source_port, - destination_port: self.destination_port, - }, - chunks: vec![Box::new(ChunkCookieAck {})], - }]) - } - - fn handle_cookie_ack(&mut self) -> Result> { - let state = self.state(); - debug!("[{}] COOKIE-ACK received in state '{}'", self.side, state); - if state != AssociationState::CookieEchoed { - // RFC 4960 - // 5.2.5. Handle Duplicate COOKIE-ACK. - // At any state other than COOKIE-ECHOED, an endpoint should silently - // discard a received COOKIE ACK chunk. - return Ok(vec![]); - } - - self.timers.stop(Timer::T1Cookie); - self.stored_cookie_echo = None; - - self.events.push_back(Event::Connected); - self.set_state(AssociationState::Established); - self.handshake_completed = true; - - Ok(vec![]) - } - - fn data_is_above_pending_reset(&self, d: &ChunkPayloadData) -> bool { - self.retiring_streams.contains_key(&d.stream_identifier) - || self.reconfig_requests.values().any(|request| { - Self::reset_request_affects_stream(request, d.stream_identifier) - && sna32gt(d.tsn, request.sender_last_tsn) - }) - } - - fn current_reset_boundary(&self, stream_identifier: StreamId) -> Option { - self.retiring_streams - .get(&stream_identifier) - .and_then(|boundaries| boundaries.front().copied()) - } - - fn pending_reset_boundary(&self, stream_identifier: StreamId) -> Option { - self.reconfig_requests - .values() - .find(|request| Self::reset_request_affects_stream(request, stream_identifier)) - .map(|request| request.sender_last_tsn) - } - - fn forward_tsn_applies_to_current_generation(&self, stream_identifier: StreamId) -> bool { - let current_boundary = self.current_reset_boundary(stream_identifier); - current_boundary.is_none() || current_boundary == self.pending_reset_boundary(stream_identifier) - } - - fn apply_or_defer_ordered_forward_tsn( - &mut self, - stream_identifier: StreamId, - last_ssn: u16, - new_cumulative_tsn: u32, - ) { - if !self.forward_tsn_applies_to_current_generation(stream_identifier) { - let generation_boundary = self.pending_reset_boundary(stream_identifier); - let kind = { - let updates = self.deferred_forward_tsns.entry(stream_identifier).or_default(); - let previous = updates.iter_mut().find(|update| { - if update.generation_boundary != generation_boundary { - return false; - } - let DeferredForwardTsnKind::Ordered { - last_ssn: previous_ssn, .. - } = update.kind - else { - return false; - }; - previous_ssn == last_ssn || (generation_boundary.is_some() && sna16lt(previous_ssn, last_ssn)) - }); - - if let Some(previous) = previous { - let DeferredForwardTsnKind::Ordered { - last_ssn: previous_ssn, - new_cumulative_tsn: previous_cumulative_tsn, - } = &mut previous.kind - else { - unreachable!(); - }; - if sna16lt(*previous_ssn, last_ssn) { - *previous_ssn = last_ssn; - } - if sna32lt(*previous_cumulative_tsn, new_cumulative_tsn) { - *previous_cumulative_tsn = new_cumulative_tsn; - } - previous.kind - } else { - let kind = DeferredForwardTsnKind::Ordered { - last_ssn, - new_cumulative_tsn, - }; - updates.push_back(DeferredForwardTsn { - generation_boundary, - kind, - }); - kind - } - }; - self.prune_deferred_reset_data_for_forward_tsn(stream_identifier, generation_boundary, kind); - return; - } - - let became_readable = self.streams.get_mut(&stream_identifier).is_some_and(|stream| { - let was_readable = stream.reassembly_queue.is_readable(); - stream.reassembly_queue.forward_tsn_for_ordered(last_ssn); - !was_readable && stream.reassembly_queue.is_readable() - }); - if became_readable { - self.events - .push_back(Event::Stream(StreamEvent::Readable { id: stream_identifier })); - } - } - - fn apply_or_defer_unordered_forward_tsn(&mut self, stream_identifier: StreamId, new_cumulative_tsn: u32) { - if !self.forward_tsn_applies_to_current_generation(stream_identifier) { - let generation_boundary = self.pending_reset_boundary(stream_identifier); - let effective_cumulative_tsn = { - let updates = self.deferred_forward_tsns.entry(stream_identifier).or_default(); - if let Some(previous_cumulative_tsn) = updates.iter_mut().find_map(|update| { - if update.generation_boundary != generation_boundary { - return None; - } - match &mut update.kind { - DeferredForwardTsnKind::Unordered { new_cumulative_tsn } => Some(new_cumulative_tsn), - DeferredForwardTsnKind::Ordered { .. } => None, - } - }) { - if sna32lt(*previous_cumulative_tsn, new_cumulative_tsn) { - *previous_cumulative_tsn = new_cumulative_tsn; - } - *previous_cumulative_tsn - } else { - updates.push_back(DeferredForwardTsn { - generation_boundary, - kind: DeferredForwardTsnKind::Unordered { new_cumulative_tsn }, - }); - new_cumulative_tsn - } - }; - self.prune_deferred_reset_data_for_forward_tsn( - stream_identifier, - generation_boundary, - DeferredForwardTsnKind::Unordered { - new_cumulative_tsn: effective_cumulative_tsn, - }, - ); - return; - } - - if let Some(stream) = self.streams.get_mut(&stream_identifier) { - stream.reassembly_queue.forward_tsn_for_unordered(new_cumulative_tsn); - } - } - - fn apply_unordered_forward_tsn_to_current_streams(&mut self, new_cumulative_tsn: u32) { - let stream_ids: Vec = self.streams.keys().copied().collect(); - for stream_identifier in stream_ids { - self.apply_or_defer_unordered_forward_tsn(stream_identifier, new_cumulative_tsn); - } - } - - fn deferred_forward_tsn_application( - &self, - stream_identifier: StreamId, - update: DeferredForwardTsn, - ) -> Option<(DeferredForwardTsnKind, bool)> { - match update.kind { - DeferredForwardTsnKind::Ordered { - last_ssn, - new_cumulative_tsn, - } => self.streams.get(&stream_identifier).and_then(|stream| { - stream - .reassembly_queue - .applicable_forward_tsn_for_ordered_bounded(last_ssn, new_cumulative_tsn, self.peer_last_tsn) - .map(|applicable_last_ssn| { - ( - DeferredForwardTsnKind::Ordered { - last_ssn: applicable_last_ssn, - new_cumulative_tsn, - }, - applicable_last_ssn == last_ssn, - ) - }) - }), - DeferredForwardTsnKind::Unordered { .. } => Some((update.kind, true)), - } - } - - fn apply_deferred_forward_tsns(&mut self, stream_identifier: StreamId) { - if !self.streams.contains_key(&stream_identifier) { - return; - } - - let boundary = self.current_reset_boundary(stream_identifier); - let Some(updates) = self.deferred_forward_tsns.get(&stream_identifier) else { - return; - }; - let mut removals = Vec::with_capacity(updates.len()); - let mut ready = vec![]; - for update in updates { - let application = if update.generation_boundary == boundary { - self.deferred_forward_tsn_application(stream_identifier, *update) - } else { - None - }; - let remove = application.is_some_and(|(_, remove)| remove); - removals.push(remove); - if let Some((kind, _)) = application { - ready.push(kind); - } - } - - if ready.is_empty() { - return; - } - - let mut index = 0; - if let Some(updates) = self.deferred_forward_tsns.get_mut(&stream_identifier) { - updates.retain(|_| { - let retain = !removals[index]; - index += 1; - retain - }); - } - if self - .deferred_forward_tsns - .get(&stream_identifier) - .is_some_and(VecDeque::is_empty) - { - self.deferred_forward_tsns.remove(&stream_identifier); - } - - let became_readable = if let Some(stream) = self.streams.get_mut(&stream_identifier) { - let was_readable = stream.reassembly_queue.is_readable(); - for kind in ready { - match kind { - DeferredForwardTsnKind::Ordered { - last_ssn, - new_cumulative_tsn, - } => { - stream - .reassembly_queue - .forward_tsn_for_ordered_bounded(last_ssn, new_cumulative_tsn); - } - DeferredForwardTsnKind::Unordered { new_cumulative_tsn } => { - stream.reassembly_queue.forward_tsn_for_unordered(new_cumulative_tsn); - } - } - } - !was_readable && stream.reassembly_queue.is_readable() - } else { - false - }; - if became_readable { - self.events - .push_back(Event::Stream(StreamEvent::Readable { id: stream_identifier })); - } - } - - fn discard_deferred_forward_tsns_through(&mut self, stream_identifier: StreamId, boundary: u32) { - if let Some(updates) = self.deferred_forward_tsns.get_mut(&stream_identifier) { - updates.retain(|update| update.generation_boundary != Some(boundary)); - if updates.is_empty() { - self.deferred_forward_tsns.remove(&stream_identifier); - } - } - } - - /// Release receive-window credit for incomplete successor messages that a - /// deferred Forward-TSN has abandoned. Complete messages remain available - /// when that stream generation is eventually exposed to the application. - fn prune_deferred_reset_data_for_forward_tsn( - &mut self, - stream_identifier: StreamId, - generation_boundary: Option, - kind: DeferredForwardTsnKind, - ) { - let mut chunks: Vec = self - .deferred_reset_data - .values() - .filter(|chunk| { - chunk.stream_identifier == stream_identifier - && self - .deferred_generation_bounds(stream_identifier, chunk.tsn) - .is_some_and(|(_, upper)| upper == generation_boundary) - }) - .cloned() - .collect(); - if chunks.is_empty() { - return; - } - - chunks.sort_unstable_by_key(|chunk| { - self.deferred_generation_bounds(stream_identifier, chunk.tsn) - .map(|(lower, _)| chunk.tsn.wrapping_sub(lower)) - .unwrap_or_default() - }); - let targeted_tsns: FxHashSet = chunks.iter().map(|chunk| chunk.tsn).collect(); - - let mut queue = ReassemblyQueue::new(stream_identifier, self.max_receive_message_size); - for chunk in chunks { - // These chunks were validated before being retained. If rebuilding - // their generation unexpectedly fails, keep the data conservatively. - if queue.push(chunk).is_err() { - return; - } - } - match kind { - DeferredForwardTsnKind::Ordered { - last_ssn, - new_cumulative_tsn, - } => { - queue.forward_tsn_for_ordered_bounded(last_ssn, new_cumulative_tsn); - } - DeferredForwardTsnKind::Unordered { new_cumulative_tsn } => { - queue.forward_tsn_for_unordered(new_cumulative_tsn); - } - } - - let retained_tsns: FxHashSet = queue - .ordered - .iter() - .chain(&queue.unordered) - .flat_map(|chunks| chunks.chunks.iter()) - .chain(queue.unordered_chunks.iter()) - .map(|chunk| chunk.tsn) - .collect(); - self.deferred_reset_data - .retain(|tsn, _| !targeted_tsns.contains(tsn) || retained_tsns.contains(tsn)); - } - - fn deliver_deferred_reset_data(&mut self, d: &ChunkPayloadData) -> Result<()> { - if self.get_or_create_stream(d.stream_identifier).is_none() { - debug!("[{}] discard {}", self.side, d.stream_sequence_number); - return Ok(()); - } - - if let Some(stream) = self.streams.get_mut(&d.stream_identifier) { - let queued = stream.handle_data(d)?; - self.events.push_back(Event::DatagramReceived); - if queued && stream.reassembly_queue.is_readable() { - self.events.push_back(Event::Stream(StreamEvent::Readable { - id: d.stream_identifier, - })); - } - } - - Ok(()) - } - - fn release_deferred_generation_data( - &mut self, - stream_identifier: StreamId, - previous_boundary: u32, - boundary: u32, - ) -> Result<()> { - let mut ready: Vec = self - .deferred_reset_data - .values() - .filter(|chunk| { - chunk.stream_identifier == stream_identifier - && sna32gt(chunk.tsn, previous_boundary) - && sna32lte(chunk.tsn, boundary) - }) - .cloned() - .collect(); - ready.sort_unstable_by_key(|chunk| chunk.tsn.wrapping_sub(previous_boundary)); - - for chunk in ready { - self.deliver_deferred_reset_data(&chunk)?; - self.deferred_reset_data.remove(&chunk.tsn); - } - self.apply_deferred_forward_tsns(stream_identifier); - - Ok(()) - } - - fn deferred_generation_bounds(&self, stream_identifier: StreamId, tsn: u32) -> Option<(u32, Option)> { - let retirement_boundaries = self.retiring_streams.get(&stream_identifier); - let pending_boundary = self - .reconfig_requests - .values() - .find(|request| Self::reset_request_affects_stream(request, stream_identifier)) - .map(|request| request.sender_last_tsn); - - let mut boundaries: Vec = retirement_boundaries - .into_iter() - .flat_map(|boundaries| boundaries.iter().copied()) - .collect(); - if let Some(pending_boundary) = pending_boundary { - if boundaries.last().copied() != Some(pending_boundary) { - boundaries.push(pending_boundary); - } - } - - let mut lower = *boundaries.first()?; - for upper in boundaries.into_iter().skip(1) { - if sna32lte(tsn, upper) { - return Some((lower, Some(upper))); - } - lower = upper; - } - Some((lower, None)) - } - - fn validate_deferred_reset_data(&self, d: &ChunkPayloadData) -> Result<()> { - let Some((lower, upper)) = self.deferred_generation_bounds(d.stream_identifier, d.tsn) else { - return Ok(()); - }; - - let mut chunks: Vec = self - .deferred_reset_data - .values() - .filter(|chunk| { - chunk.stream_identifier == d.stream_identifier - && sna32gt(chunk.tsn, lower) - && upper.is_none_or(|upper| sna32lte(chunk.tsn, upper)) - }) - .cloned() - .collect(); - chunks.sort_unstable_by_key(|chunk| chunk.tsn.wrapping_sub(lower)); - - let mut validation_queue = ReassemblyQueue::new(d.stream_identifier, self.max_receive_message_size); - for chunk in chunks { - validation_queue.push(chunk)?; - } - validation_queue.push(d.clone())?; - Ok(()) - } - - fn release_deferred_reset_data(&mut self) -> Result<()> { - let ready: Vec = self - .deferred_reset_data - .values() - .filter(|chunk| !self.data_is_above_pending_reset(chunk)) - .cloned() - .collect(); - let stream_ids: FxHashSet = ready.iter().map(|chunk| chunk.stream_identifier).collect(); - - for chunk in ready { - self.deliver_deferred_reset_data(&chunk)?; - self.deferred_reset_data.remove(&chunk.tsn); - } - for stream_identifier in stream_ids { - self.apply_deferred_forward_tsns(stream_identifier); - } - - Ok(()) - } - - fn handle_data(&mut self, d: &ChunkPayloadData) -> Result> { - trace!( - "[{}] DATA: tsn={} immediateSack={} len={}", - self.side, - d.tsn, - d.immediate_sack, - d.user_data.len() - ); - self.stats.inc_datas(); - - let can_push = self.payload_queue.can_push(d, self.peer_last_tsn); - let mut stream_handle_data = false; - let mut defer_stream_data = false; - if can_push && self.data_is_above_pending_reset(d) { - if self.get_my_receiver_window_credit() > 0 { - defer_stream_data = true; - } else if let Some(last_tsn) = self.payload_queue.get_last_tsn_received() { - if sna32lt(d.tsn, *last_tsn) { - debug!( - "[{}] receive buffer full, but accepted deferred \ - reset DATA as missing chunk tsn={} ssn={}", - self.side, d.tsn, d.stream_sequence_number - ); - defer_stream_data = true; - } - } - } else if can_push { - if self.get_or_create_stream(d.stream_identifier).is_some() { - if self.get_my_receiver_window_credit() > 0 { - // Pass the new chunk to stream level as soon as it arrives - stream_handle_data = true; - } else { - // Receive buffer is full - if let Some(last_tsn) = self.payload_queue.get_last_tsn_received() { - if sna32lt(d.tsn, *last_tsn) { - debug!( - "[{}] receive buffer full, but accepted \ - as missing chunk tsn={} ssn={}", - self.side, d.tsn, d.stream_sequence_number - ); - stream_handle_data = true; - } - } else { - debug!( - "[{}] receive buffer full. dropping DATA with tsn={} ssn={}", - self.side, d.tsn, d.stream_sequence_number - ); - } - } - } else { - // silently discard the data. (sender will retry on T3-rtx timeout) - // see pion/sctp#30 - debug!("[{}] discard {}", self.side, d.stream_sequence_number); - return Ok(vec![]); - } - } - - let immediate_sack = d.immediate_sack; - - if defer_stream_data { - self.validate_deferred_reset_data(d)?; - if self.payload_queue.push(d.clone(), self.peer_last_tsn) { - self.deferred_reset_data.insert(d.tsn, d.clone()); - } - } else if stream_handle_data { - if let Some(s) = self.streams.get_mut(&d.stream_identifier) { - let queued = s.handle_data(d)?; - // Only commit to payload_queue after reassembly accepts the chunk - self.payload_queue.push(d.clone(), self.peer_last_tsn); - self.events.push_back(Event::DatagramReceived); - if queued && s.reassembly_queue.is_readable() { - self.events.push_back(Event::Stream(StreamEvent::Readable { - id: d.stream_identifier, - })) - } - } - // A deferred skip may describe this successor generation. Queue - // DATA first so a complete message reusing the skipped SSN remains - // readable, while a genuinely abandoned SSN can still be advanced. - self.apply_deferred_forward_tsns(d.stream_identifier); - } - - self.handle_peer_last_tsn_and_acknowledgement(immediate_sack) - } - - fn handle_sack(&mut self, d: &ChunkSelectiveAck, now: Instant) -> Result> { - trace!( - "[{}] {}, SACK: cumTSN={} a_rwnd={}", - self.side, self.cumulative_tsn_ack_point, d.cumulative_tsn_ack, d.advertised_receiver_window_credit - ); - let state = self.state(); - if state != AssociationState::Established - && state != AssociationState::ShutdownPending - && state != AssociationState::ShutdownReceived - { - return Ok(vec![]); - } - - self.stats.inc_sacks(); - - if sna32gt(self.cumulative_tsn_ack_point, d.cumulative_tsn_ack) { - // RFC 4960 sec 6.2.1. Processing a Received SACK - // D) - // i) If Cumulative TSN Ack is less than the Cumulative TSN Ack - // Point, then drop the SACK. Since Cumulative TSN Ack is - // monotonically increasing, a SACK whose Cumulative TSN Ack is - // less than the Cumulative TSN Ack Point indicates an out-of- - // order SACK. - - debug!( - "[{}] SACK Cumulative ACK {} is older than ACK point {}", - self.side, d.cumulative_tsn_ack, self.cumulative_tsn_ack_point - ); - - return Ok(vec![]); - } - - // Process selective ack - let outstanding_before = self.outbound_queue.inflight_bytes(); - let (bytes_acked_per_stream, htna) = self.process_selective_ack(d, now)?; - // Peer delivery earns congestion credit even after its stream was reset. - // Application credit below belongs only to the current stream generation. - let total_bytes_acked = (outstanding_before - self.outbound_queue.inflight_bytes()) as i64; - - let mut cum_tsn_ack_point_advanced = false; - if sna32lt(self.cumulative_tsn_ack_point, d.cumulative_tsn_ack) { - trace!( - "[{}] SACK: cumTSN advanced: {} -> {}", - self.side, self.cumulative_tsn_ack_point, d.cumulative_tsn_ack - ); - - self.cumulative_tsn_ack_point = d.cumulative_tsn_ack; - cum_tsn_ack_point_advanced = true; - self.on_cumulative_tsn_ack_point_advanced(total_bytes_acked, now); - } - - for (si, n_bytes_acked) in &bytes_acked_per_stream { - if let Some(s) = self.streams.get_mut(si) { - if s.on_buffer_released(*n_bytes_acked) { - self.events - .push_back(Event::Stream(StreamEvent::BufferedAmountLow { id: *si })) - } - } - } - - // New rwnd value - // RFC 4960 sec 6.2.1. Processing a Received SACK - // D) - // ii) Set rwnd equal to the newly received a_rwnd minus the number - // of bytes still outstanding after processing the Cumulative - // TSN Ack and the Gap Ack Blocks. - - // bytes acked were already subtracted by markAsAcked() method - let bytes_outstanding = self.outbound_queue.inflight_bytes() as u32; - if bytes_outstanding >= d.advertised_receiver_window_credit { - self.rwnd = 0; - } else { - self.rwnd = d.advertised_receiver_window_credit - bytes_outstanding; - } - - self.process_fast_retransmission(d.cumulative_tsn_ack, htna, cum_tsn_ack_point_advanced)?; - - if self.use_forward_tsn { - self.advance_peer_tsn_ack_point(); - - // RFC 3758 Sec 3.5 C3 - if sna32gt(self.advanced_peer_tsn_ack_point, self.cumulative_tsn_ack_point) { - self.will_send_forward_tsn = true; - debug!( - "[{}] handleSack {}: sna32GT({}, {})", - self.side, - self.will_send_forward_tsn, - self.advanced_peer_tsn_ack_point, - self.cumulative_tsn_ack_point - ); - } - self.awake_write_loop(); - } - - self.postprocess_sack(state, cum_tsn_ack_point_advanced, now); - - Ok(vec![]) - } - - fn handle_reconfig(&mut self, c: &ChunkReconfig) -> Result> { - trace!("[{}] handle_reconfig", self.side); - - let mut pp = vec![]; - - if let Some(param_a) = &c.param_a { - self.handle_reconfig_param(param_a, &mut pp)?; - } - - if let Some(param_b) = &c.param_b { - self.handle_reconfig_param(param_b, &mut pp)?; - } - - Ok(pp) - } - - fn handle_forward_tsn(&mut self, c: &ChunkForwardTsn) -> Result> { - trace!("[{}] FwdTSN: {}", self.side, c); - - if !self.use_forward_tsn { - warn!("[{}] received FwdTSN but not enabled", self.side); - // Return an error chunk - let cerr = ChunkError { - error_causes: vec![ErrorCauseUnrecognizedChunkType::default()], - }; - - let outbound = Packet { - common_header: CommonHeader { - verification_tag: self.peer_verification_tag, - source_port: self.source_port, - destination_port: self.destination_port, - }, - chunks: vec![Box::new(cerr)], - }; - return Ok(vec![outbound]); - } - - // From RFC 3758 Sec 3.6: - // Note, if the "New Cumulative TSN" value carried in the arrived - // FORWARD TSN chunk is found to be behind or at the current cumulative - // TSN point, the data receiver MUST treat this FORWARD TSN as out-of- - // date and MUST NOT update its Cumulative TSN. The receiver SHOULD - // send a SACK to its peer (the sender of the FORWARD TSN) since such a - // duplicate may indicate the previous SACK was lost in the network. - - trace!( - "[{}] should send ack? newCumTSN={} peer_last_tsn={}", - self.side, c.new_cumulative_tsn, self.peer_last_tsn - ); - if sna32lte(c.new_cumulative_tsn, self.peer_last_tsn) { - trace!("[{}] sending ack on Forward TSN", self.side); - self.ack_state = AckState::Immediate; - self.timers.stop(Timer::Ack); - self.awake_write_loop(); - return Ok(vec![]); - } - - // From RFC 3758 Sec 3.6: - // the receiver MUST perform the same TSN handling, including duplicate - // detection, gap detection, SACK generation, cumulative TSN - // advancement, etc. as defined in RFC 2960 [2]---with the following - // exceptions and additions. - - // When a FORWARD TSN chunk arrives, the data receiver MUST first update - // its cumulative TSN point to the value carried in the FORWARD TSN - // chunk, - - // Advance to the peer's new cumulative tsn point, - // dropping the chunks it abandoned along the way. - self.payload_queue.pop_up_to(c.new_cumulative_tsn); - self.peer_last_tsn = c.new_cumulative_tsn; - - // Report new peer_last_tsn value and abandoned largest SSN value to - // corresponding streams so that the abandoned chunks can be removed - // from the reassemblyQueue. - for forwarded in &c.streams { - self.apply_or_defer_ordered_forward_tsn(forwarded.identifier, forwarded.sequence, c.new_cumulative_tsn); - } - - // TSN may be forwarded for unordered chunks. ForwardTSN chunk does not - // report which stream identifier it skipped for unordered chunks. - // Therefore, we need to broadcast this event to all existing streams for - // unordered chunks. - // See https://github.com/pion/sctp/issues/106 - self.apply_unordered_forward_tsn_to_current_streams(c.new_cumulative_tsn); - - let mut reply = vec![]; - self.reevaluate_pending_reset_requests(&mut reply)?; - reply.extend(self.handle_peer_last_tsn_and_acknowledgement(false)?); - Ok(reply) - } - - /// Handle I-FORWARD-TSN (RFC 8260) - identical to FORWARD-TSN but with - /// 32-bit MID and explicit per-entry unordered flag. - fn handle_i_forward_tsn(&mut self, c: &ChunkIForwardTsn) -> Result> { - trace!("[{}] I-FwdTSN: {}", self.side, c); - - if !self.use_forward_tsn { - warn!("[{}] received I-FwdTSN but not enabled", self.side); - let cerr = ChunkError { - error_causes: vec![ErrorCauseUnrecognizedChunkType::default()], - }; - - let outbound = Packet { - common_header: CommonHeader { - verification_tag: self.peer_verification_tag, - source_port: self.source_port, - destination_port: self.destination_port, - }, - chunks: vec![Box::new(cerr)], - }; - return Ok(vec![outbound]); - } - - if sna32lte(c.new_cumulative_tsn, self.peer_last_tsn) { - trace!("[{}] sending ack on I-Forward TSN", self.side); - self.ack_state = AckState::Immediate; - self.timers.stop(Timer::Ack); - self.awake_write_loop(); - return Ok(vec![]); - } - - // Advance to the peer's new cumulative tsn point, - // dropping the chunks it abandoned along the way. - self.payload_queue.pop_up_to(c.new_cumulative_tsn); - self.peer_last_tsn = c.new_cumulative_tsn; - - // Handle per-stream entries using the explicit unordered flag - for forwarded in &c.streams { - if forwarded.unordered { - self.apply_or_defer_unordered_forward_tsn(forwarded.identifier, c.new_cumulative_tsn); - } else { - // MID maps to SSN for ordered streams; truncate to u16 - self.apply_or_defer_ordered_forward_tsn( - forwarded.identifier, - forwarded.mid as u16, - c.new_cumulative_tsn, - ); - } - } - - // Broadcast to all unordered streams - self.apply_unordered_forward_tsn_to_current_streams(c.new_cumulative_tsn); - - let mut reply = vec![]; - self.reevaluate_pending_reset_requests(&mut reply)?; - reply.extend(self.handle_peer_last_tsn_and_acknowledgement(false)?); - Ok(reply) - } - - fn handle_shutdown(&mut self, _: &ChunkShutdown) -> Result> { - let state = self.state(); - - if state == AssociationState::Established { - if self.outbound_queue.inflight_len() != 0 { - self.set_state(AssociationState::ShutdownReceived); - } else { - // No more outstanding, send shutdown ack. - self.will_send_shutdown_ack = true; - self.set_state(AssociationState::ShutdownAckSent); - - self.awake_write_loop(); - } - } else if state == AssociationState::ShutdownSent { - // self.cumulative_tsn_ack_point = c.cumulative_tsn_ack - - self.will_send_shutdown_ack = true; - self.set_state(AssociationState::ShutdownAckSent); - - self.awake_write_loop(); - } - - Ok(vec![]) - } - - fn handle_shutdown_ack(&mut self, _: &ChunkShutdownAck) -> Result> { - let state = self.state(); - if state == AssociationState::ShutdownSent || state == AssociationState::ShutdownAckSent { - self.timers.stop(Timer::T2Shutdown); - self.will_send_shutdown_complete = true; - - self.awake_write_loop(); - } - - Ok(vec![]) - } - - fn handle_shutdown_complete(&mut self, _: &ChunkShutdownComplete) -> Result> { - let state = self.state(); - if state == AssociationState::ShutdownAckSent { - self.timers.stop(Timer::T2Shutdown); - self.close()?; - } - - Ok(vec![]) - } - - fn reevaluate_pending_reset_requests(&mut self, reply: &mut Vec) -> Result<()> { - let requests: Vec = self.reconfig_requests.values().cloned().collect(); - for request in requests { - let seq = request.reconfig_request_sequence_number; - self.reset_streams_if_any(&request, false, reply)?; - if !self.reconfig_requests.contains_key(&seq) { - self.max_completed_reconfig_rsn = Some(seq); - } - } - Ok(()) - } - - /// A common routine for handle_data and handle_forward_tsn routines - fn handle_peer_last_tsn_and_acknowledgement(&mut self, sack_immediately: bool) -> Result> { - let mut reply = vec![]; - - // Try to advance peer_last_tsn - - // From RFC 3758 Sec 3.6: - // .. and then MUST further advance its cumulative TSN point locally - // if possible - // Meaning, if peer_last_tsn+1 points to a chunk that is received, - // advance peer_last_tsn until peer_last_tsn+1 points to unreceived chunk. - //debug!("[{}] peer_last_tsn = {}", self.side, self.peer_last_tsn); - while let Some(chunk) = self.payload_queue.pop(self.peer_last_tsn.wrapping_add(1)) { - self.peer_last_tsn = self.peer_last_tsn.wrapping_add(1); - //debug!("[{}] peer_last_tsn = {}", self.side, self.peer_last_tsn); - - self.reevaluate_pending_reset_requests(&mut reply)?; - - if let Some(deferred) = self.deferred_reset_data.get(&chunk.tsn).cloned() { - if !self.data_is_above_pending_reset(&deferred) { - self.deliver_deferred_reset_data(&deferred)?; - self.deferred_reset_data.remove(&chunk.tsn); - } - } - } - - // A resolved TSN gap can disambiguate a deferred ordered skip whose - // later SSN arrived first on a reset successor. - let stream_ids: Vec = self.deferred_forward_tsns.keys().copied().collect(); - for stream_identifier in stream_ids { - self.apply_deferred_forward_tsns(stream_identifier); - } - - // DATA and FORWARD-TSN can both close the final gap. Once every - // accepted TSN is cumulative, only new highest-TSN DATA could complete - // an unreadable message; RFC 9260 section 6.2 forbids admitting it at - // zero credit. Fail explicitly rather than pinning receive storage. - if self.receive_capacity_exhausted() { - return Err(Error::ErrReceiveBufferExhausted); - } - - let has_packet_loss = !self.payload_queue.is_empty(); - if has_packet_loss { - trace!( - "[{}] packetloss: {}", - self.side, - self.payload_queue.get_gap_ack_blocks_string(self.peer_last_tsn) - ); - } - - if (self.ack_state != AckState::Immediate - && !sack_immediately - && !has_packet_loss - && self.ack_mode == AckMode::Normal) - || self.ack_mode == AckMode::AlwaysDelay - { - if self.ack_state == AckState::Idle { - self.delayed_ack_triggered = true; - } else { - self.immediate_ack_triggered = true; - } - } else { - self.immediate_ack_triggered = true; - } - - Ok(reply) - } - - #[allow(clippy::borrowed_box)] - fn handle_reconfig_param(&mut self, raw: &Box, reply: &mut Vec) -> Result<()> { - if let Some(p) = raw.as_any().downcast_ref::() { - // RFC 6525 section 5.2.2 E1: the response sequence number in an - // Outgoing Reset Request implicitly acknowledges our request. - self.finish_reconfig(p.reconfig_response_sequence_number, Ok(())); - - let seq = p.reconfig_request_sequence_number; - // Detect retransmission of a completed request. An InProgress request - // is still in reconfig_requests, so we must let those through for - // re-evaluation (the TSN may have advanced). - if !self.reconfig_requests.contains_key(&seq) - && self.max_completed_reconfig_rsn.is_some_and(|w| sna32lte(seq, w)) - { - // Retransmission of an already-completed request. Resend the response - // but do NOT reprocess stream resets (stream IDs may have been reused). - self.push_reconfig_response(reply, seq, ReconfigResult::SuccessPerformed); - return Ok(()); - } - - if !self.reconfig_requests.contains_key(&seq) { - // RFC 6525 section 5.2.2 E4: only the next expected peer - // request sequence number may start a new operation. A request - // already deferred in reconfig_requests is a retransmission and - // remains eligible for re-evaluation. - if !self.reconfig_requests.is_empty() { - self.push_reconfig_response(reply, seq, ReconfigResult::ErrorRequestAlreadyInProgress); - return Ok(()); - } - - if self.peer_reconfig_rsn_initialized && seq != self.peer_last_reconfig_rsn.wrapping_add(1) { - self.push_reconfig_response(reply, seq, ReconfigResult::ErrorBadSequenceNumber); - return Ok(()); - } - - self.peer_last_reconfig_rsn = seq; - self.peer_reconfig_rsn_initialized = true; - self.reconfig_requests.insert(seq, p.clone()); - } - - // Re-evaluate the original request for this RSN. This prevents a - // retransmission with altered stream identifiers or TSN boundary - // from changing an operation that is already in progress. - let request = self.reconfig_requests.get(&seq).cloned().unwrap(); - self.reset_streams_if_any(&request, true, reply)?; - // Update watermark only after successful completion (request - // removed from reconfig_requests by reset_streams_if_any). - if !self.reconfig_requests.contains_key(&seq) { - self.max_completed_reconfig_rsn = Some(seq); - } - Ok(()) - } else if let Some(p) = raw.as_any().downcast_ref::() { - let rsn = p.reconfig_response_sequence_number; - // RFC 6525 section 5.2.7 H1: ignore responses unless this RSN owns - // the running Re-configuration Timer. - if self.active_reconfig != Some(rsn) { - return Ok(()); - } - - // In progress result means the peer has deferred the request, - // not answered it. The request stays outstanding and its timer restarts - // without counting toward the retransmission limit. - if p.result == ReconfigResult::InProgress { - if self.reconfigs.contains_key(&rsn) { - self.will_retransmit_reconfig = false; - // Pause without resetting the existing retry count. The outbound - // poll starts it again and the next expiry is exempted by H2. - self.timers.set(Timer::Reconfig, None); - self.timers.suppress_error_count(Timer::Reconfig); - self.awake_write_loop(); - } - return Ok(()); - } - - let outcome = match p.result { - ReconfigResult::SuccessNop | ReconfigResult::SuccessPerformed => Ok(()), - ReconfigResult::Denied => Err(StreamResetError::Denied), - _ => Err(StreamResetError::Failed), - }; - self.finish_reconfig(rsn, outcome); - Ok(()) - } else { - Err(Error::ErrParameterType) - } - } - - fn push_reconfig_response(&self, reply: &mut Vec, sequence_number: u32, result: ReconfigResult) { - reply.push(self.create_packet(vec![Box::new(ChunkReconfig { - param_a: Some(Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: sequence_number, - result, - })), - param_b: None, - })])); - } - - fn process_selective_ack(&mut self, d: &ChunkSelectiveAck, now: Instant) -> Result<(HashMap, u32)> { - let mut bytes_acked_per_stream = HashMap::new(); - let mut newly_acked_data = false; - let earliest_outstanding = self.outbound_queue.earliest_outstanding_tsn(); - - // New ack point, so pop cumulatively ACKed chunks from the outbound queue. - // We add 1 because the "currentAckPoint" has already been popped from the inflight queue - // For the first SACK we take care of this by setting the ackpoint to cumAck - 1 - let first_outstanding_tsn = self.cumulative_tsn_ack_point.wrapping_add(1); - let mut i = first_outstanding_tsn; - //tracing::debug!("[{}] i={} d={}", self.name, i, d.cumulative_tsn_ack); - while sna32lte(i, d.cumulative_tsn_ack) { - if let Some(c) = self.outbound_queue.pop(i) { - newly_acked_data |= !c.acked && c.nsent > 0; - if !c.acked && !c.abandoned { - let n_bytes_acked = c.user_data.len() as i64; - - // Sum the number of bytes acknowledged per stream - if !self - .streams - .get(&c.stream_identifier) - .is_some_and(|stream| c.message_id < stream.first_message_id) - { - *bytes_acked_per_stream.entry(c.stream_identifier).or_insert(0) += n_bytes_acked; - } - - // RFC 4960 sec 6.3.1. RTO Calculation - // C4) When data is in flight and when allowed by rule C5 below, a new - // RTT measurement MUST be made each round trip. Furthermore, new - // RTT measurements SHOULD be made no more than once per round trip - // for a given destination transport address. - // C5) Karn's algorithm: RTT measurements MUST NOT be made using - // packets that were retransmitted (and thus for which it is - // ambiguous whether the reply was for the first instance of the - // chunk or for a later instance) - if c.nsent == 1 && sna32gte(c.tsn, self.min_tsn2measure_rtt) { - self.min_tsn2measure_rtt = self.my_next_tsn; - if let Some(since) = &c.since { - let rtt = now.duration_since(*since); - let srtt = self.rto_mgr.set_new_rtt(rtt.as_millis() as u64); - trace!( - "[{}] SACK: measured-rtt={} srtt={} new-rto={}", - self.side, - rtt.as_millis(), - srtt, - self.rto_mgr.get_rto() - ); - } else { - error!("[{}] invalid c.since", self.side); - } - } - } - - if self.in_fast_recovery && c.tsn == self.fast_recover_exit_point { - debug!("[{}] exit fast-recovery", self.side); - self.in_fast_recovery = false; - } - } else { - return Err(Error::ErrInflightQueueTsnPop); - } - - i = i.wrapping_add(1); - } - - let mut htna = d.cumulative_tsn_ack; - - // Mark selectively acknowledged chunks as "acked" - for g in &d.gap_ack_blocks { - for i in g.start..=g.end { - let tsn = d.cumulative_tsn_ack.wrapping_add(i as u32); - - let (is_existed, is_acked) = if let Some(c) = self.outbound_queue.get(tsn) { - newly_acked_data |= !c.acked && c.nsent > 0; - (true, c.acked) - } else { - (false, false) - }; - let n_bytes_acked = if is_existed && !is_acked { - self.outbound_queue.mark_as_acked(tsn) as i64 - } else { - 0 - }; - - if let Some(c) = self.outbound_queue.get(tsn) { - if !is_acked && !c.abandoned { - // Sum the number of bytes acknowledged per stream - if !self - .streams - .get(&c.stream_identifier) - .is_some_and(|stream| c.message_id < stream.first_message_id) - { - *bytes_acked_per_stream.entry(c.stream_identifier).or_insert(0) += n_bytes_acked; - } - - trace!("[{}] tsn={} has been sacked", self.side, c.tsn); - - if c.nsent == 1 { - self.min_tsn2measure_rtt = self.my_next_tsn; - if let Some(since) = &c.since { - let rtt = now.duration_since(*since); - let srtt = self.rto_mgr.set_new_rtt(rtt.as_millis() as u64); - trace!( - "[{}] SACK: measured-rtt={} srtt={} new-rto={}", - self.side, - rtt.as_millis(), - srtt, - self.rto_mgr.get_rto() - ); - } else { - error!("[{}] invalid c.since", self.side); - } - } - - if sna32lt(htna, tsn) { - htna = tsn; - } - } - } else { - return Err(Error::ErrTsnRequestNotExist); - } - } - } - - // Local retirement and duplicate SACKs are not new peer progress. - if newly_acked_data { - self.timers.reset_retrans(Timer::T3RTX); - } - // RFC 4960 R3 applies to the earliest outstanding DATA, even when - // abandoned TSNs precede it or it is acknowledged by a Gap ACK. - if earliest_outstanding.is_some_and(|tsn| { - sna32lte(tsn, d.cumulative_tsn_ack) || self.outbound_queue.get(tsn).is_some_and(|c| c.acked) - }) { - self.timers.set(Timer::T3RTX, None); - } - Ok((bytes_acked_per_stream, htna)) - } - - fn on_cumulative_tsn_ack_point_advanced(&mut self, total_bytes_acked: i64, now: Instant) { - // RFC 4096, sec 6.3.2. Retransmission Timer Rules - // R2) Whenever all outstanding data sent to an address have been - // acknowledged, turn off the T3-rtx timer of that address. - if self.outbound_queue.inflight_len() == 0 { - trace!( - "[{}] SACK: no more packet in-flight (pending={})", - self.side, - self.outbound_queue.pending_len() - ); - self.timers.stop(Timer::T3RTX); - } else { - trace!("[{}] T3-rtx timer start (pt2)", self.side); - self.timers.restart_if_stale(Timer::T3RTX, now, self.rto_mgr.get_rto()); - } - - // Update congestion control parameters - if self.cwnd <= self.ssthresh { - // RFC 4096, sec 7.2.1. Slow-Start - // o When cwnd is less than or equal to ssthresh, an SCTP endpoint MUST - // use the slow-start algorithm to increase cwnd only if the current - // congestion window is being fully utilized, an incoming SACK - // advances the Cumulative TSN Ack Point, and the data sender is not - // in Fast Recovery. Only when these three conditions are met can - // the cwnd be increased; otherwise, the cwnd MUST not be increased. - // If these conditions are met, then cwnd MUST be increased by, at - // most, the lesser of 1) the total size of the previously - // outstanding DATA chunk(s) acknowledged, and 2) the destination's - // path MTU. - if !self.in_fast_recovery && self.outbound_queue.pending_len() != 0 { - self.cwnd += core::cmp::min(total_bytes_acked as u32, self.cwnd); // TCP way - // self.cwnd += min32(uint32(total_bytes_acked), self.mtu) // SCTP way (slow) - trace!( - "[{}] updated cwnd={} ssthresh={} acked={} (SS)", - self.side, self.cwnd, self.ssthresh, total_bytes_acked - ); - } else { - trace!( - "[{}] cwnd did not grow: cwnd={} ssthresh={} acked={} FR={} pending={}", - self.side, - self.cwnd, - self.ssthresh, - total_bytes_acked, - self.in_fast_recovery, - self.outbound_queue.pending_len() - ); - } - } else { - // RFC 4096, sec 7.2.2. Congestion Avoidance - // o Whenever cwnd is greater than ssthresh, upon each SACK arrival - // that advances the Cumulative TSN Ack Point, increase - // partial_bytes_acked by the total number of bytes of all new chunks - // acknowledged in that SACK including chunks acknowledged by the new - // Cumulative TSN Ack and by Gap Ack Blocks. - self.partial_bytes_acked += total_bytes_acked as u32; - - // o When partial_bytes_acked is equal to or greater than cwnd and - // before the arrival of the SACK the sender had cwnd or more bytes - // of data outstanding (i.e., before arrival of the SACK, flight size - // was greater than or equal to cwnd), increase cwnd by MTU, and - // reset partial_bytes_acked to (partial_bytes_acked - cwnd). - if self.partial_bytes_acked >= self.cwnd && self.outbound_queue.pending_len() != 0 { - self.partial_bytes_acked -= self.cwnd; - self.cwnd += self.mtu; - trace!( - "[{}] updated cwnd={} ssthresh={} acked={} (CA)", - self.side, self.cwnd, self.ssthresh, total_bytes_acked - ); - } - } - } - - fn process_fast_retransmission( - &mut self, - cum_tsn_ack_point: u32, - htna: u32, - cum_tsn_ack_point_advanced: bool, - ) -> Result<()> { - // HTNA algorithm - RFC 4960 Sec 7.2.4 - // Increment missIndicator of each chunks that the SACK reported missing - // when either of the following is met: - // a) Not in fast-recovery - // miss indications are incremented only for missing TSNs prior to the - // highest TSN newly acknowledged in the SACK. - // b) In fast-recovery AND the Cumulative TSN Ack Point advanced - // the miss indications are incremented for all TSNs reported missing - // in the SACK. - if !self.in_fast_recovery || cum_tsn_ack_point_advanced { - let max_tsn = if !self.in_fast_recovery { - // a) increment only for missing TSNs prior to the HTNA - htna - } else { - // b) increment for all TSNs reported missing - cum_tsn_ack_point - .wrapping_add(self.outbound_queue.inflight_len() as u32) - .wrapping_add(1) - }; - - let mut tsn = cum_tsn_ack_point.wrapping_add(1); - while sna32lt(tsn, max_tsn) { - if let Some(c) = self.outbound_queue.get_mut(tsn) { - if !c.acked && !c.abandoned && c.miss_indicator < 3 { - c.miss_indicator += 1; - if c.miss_indicator == 3 && !self.in_fast_recovery { - // 2) If not in Fast Recovery, adjust the ssthresh and cwnd of the - // destination address(es) to which the missing DATA chunks were - // last sent, according to the formula described in Section 7.2.3. - self.in_fast_recovery = true; - self.fast_recover_exit_point = htna; - self.ssthresh = core::cmp::max(self.cwnd / 2, 4 * self.mtu); - self.cwnd = self.ssthresh; - self.partial_bytes_acked = 0; - self.will_retransmit_fast = true; - - trace!( - "[{}] updated cwnd={} ssthresh={} inflight={} (FR)", - self.side, - self.cwnd, - self.ssthresh, - self.outbound_queue.inflight_bytes() - ); - } - } - } else { - return Err(Error::ErrTsnRequestNotExist); - } - - tsn = tsn.wrapping_add(1); - } - } - - if self.in_fast_recovery && cum_tsn_ack_point_advanced { - self.will_retransmit_fast = true; - } - - Ok(()) - } - - /// The caller must hold the lock. This method was only added because the - /// linter was complaining about the "cognitive complexity" of handle_sack. - fn postprocess_sack(&mut self, state: AssociationState, mut should_awake_write_loop: bool, now: Instant) { - if self.outbound_queue.inflight_len() != 0 { - // Start timer. (noop if already started) - trace!("[{}] T3-rtx timer start (pt3)", self.side); - self.timers.restart_if_stale(Timer::T3RTX, now, self.rto_mgr.get_rto()); - } else if state == AssociationState::ShutdownPending { - // No more outstanding, send shutdown. - should_awake_write_loop = true; - self.will_send_shutdown = true; - self.set_state(AssociationState::ShutdownSent); - } else if state == AssociationState::ShutdownReceived { - // No more outstanding, send shutdown ack. - should_awake_write_loop = true; - self.will_send_shutdown_ack = true; - self.set_state(AssociationState::ShutdownAckSent); - } - - if should_awake_write_loop { - self.awake_write_loop(); - } - } - - fn reset_streams_if_any( - &mut self, - p: &ParamOutgoingResetRequest, - from_wire: bool, - reply: &mut Vec, - ) -> Result<()> { - let mut result = ReconfigResult::SuccessPerformed; - let mut sis_to_reset = vec![]; - - let performed = sna32lte(p.sender_last_tsn, self.peer_last_tsn); - if performed { - debug!( - "[{}] resetStream(): senderLastTSN={} <= peer_last_tsn={}", - self.side, p.sender_last_tsn, self.peer_last_tsn - ); - let mut stream_ids = if p.stream_identifiers.is_empty() { - self.streams.keys().copied().collect::>() - } else { - p.stream_identifiers.clone() - }; - stream_ids.sort_unstable(); - stream_ids.dedup(); - - for id in stream_ids { - if self.streams.contains_key(&id) { - sis_to_reset.push(id); - self.retire_stream(id, p.sender_last_tsn); - } - } - self.reconfig_requests.remove(&p.reconfig_request_sequence_number); - } else { - debug!( - "[{}] resetStream(): senderLastTSN={} > peer_last_tsn={}", - self.side, p.sender_last_tsn, self.peer_last_tsn - ); - result = ReconfigResult::InProgress; - } - - // RFC 8831 section 6.7 closes a bidirectional WebRTC data channel by - // resetting the corresponding outgoing stream after its incoming half - // is reset. `Stream` models that paired channel, so perform the - // reciprocal reset automatically. - // - // The reciprocal also keeps each unregistered id pending in - // `reconfigs`, which is what defers `StreamEvent::ResetComplete` - // until the reciprocal is acknowledged (handle_reconfig_param) or - // abandoned (on_retransmission_failure). - if !sis_to_reset.is_empty() { - let rsn = self.generate_next_rsn(); - let tsn = self.my_next_tsn.wrapping_sub(1); - let reset_all = p.stream_identifiers.is_empty(); - self.reconfig_reset_streams.insert(rsn, sis_to_reset.clone()); - - let c = ChunkReconfig { - param_a: Some(Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: rsn, - reconfig_response_sequence_number: p.reconfig_request_sequence_number, - sender_last_tsn: tsn, - stream_identifiers: if reset_all { vec![] } else { sis_to_reset }, - })), - ..Default::default() - }; - - // Store before queueing. It becomes the active retransmission entry only - // when gather_outbound actually serializes this packet. - self.reconfigs.insert(rsn, c.clone()); - - let p = self.create_packet(vec![Box::new(c)]); - reply.push(p); - } - - if performed { - self.release_deferred_reset_data()?; - } - - // Respond to every request that arrived, fresh, retransmitted - // or deferred by arrival of in-flight data. - // - // Intermediate re-evaluations that still fail due to in-flight data - // stay silent rather than repeating "In progress" on every advance. - if from_wire || performed { - let packet = self.create_packet(vec![Box::new(ChunkReconfig { - param_a: Some(Box::new(ParamReconfigResponse { - reconfig_response_sequence_number: p.reconfig_request_sequence_number, - result, - })), - param_b: None, - })]); - - debug!("[{}] RESET RESPONSE: {}", self.side, packet); - - reply.push(packet); - } - - Ok(()) - } - - /// create_packet wraps chunks in a packet. - /// The caller should hold the read lock. - pub(crate) fn create_packet(&self, chunks: Vec>) -> Packet { - Packet { - common_header: CommonHeader { - verification_tag: self.peer_verification_tag, - source_port: self.source_port, - destination_port: self.destination_port, - }, - chunks, - } - } - - /// create_stream creates a stream. The caller should hold the lock - /// and check no stream exists for this id. - fn create_stream( - &mut self, - stream_identifier: StreamId, - accept: bool, - default_payload_type: PayloadProtocolIdentifier, - ) -> Option> { - let generation = self.next_stream_generation; - self.next_stream_generation = generation.checked_add(1)?; - let mut s = StreamState::new( - self.side, - stream_identifier, - self.max_payload_size, - self.max_receive_message_size, - default_payload_type, - ); - - s.stats.generation = generation; - s.first_message_id = self.outbound_queue.next_message_id(); - - if accept { - self.stream_queue.push_back(stream_identifier); - self.events - .push_back(Event::Stream(StreamEvent::Opened { id: stream_identifier })); - } - - self.streams.insert(stream_identifier, s); - - Some(Stream { - stream_identifier, - association: self, - }) - } - - /// get_or_create_stream gets or creates a stream. The caller should hold the lock. - fn get_or_create_stream(&mut self, stream_identifier: StreamId) -> Option> { - if self.streams.contains_key(&stream_identifier) { - Some(Stream { - stream_identifier, - association: self, - }) - } else { - self.create_stream(stream_identifier, true, PayloadProtocolIdentifier::default()) - } - } - - pub(crate) fn get_my_receiver_window_credit(&self) -> u32 { - let mut bytes_queued = 0; - for s in self.streams.values() { - bytes_queued += s.get_num_bytes_in_reassembly_queue() as u32; - } - for chunk in self.deferred_reset_data.values() { - bytes_queued += chunk.user_data.len() as u32; - } - - self.max_receive_buffer_size.saturating_sub(bytes_queued) - } - - /// gather_outbound gathers outgoing packets. The returned bool value set to - /// false means the association should be closed down after the final send. - fn gather_outbound(&mut self, now: Instant) -> (Vec, bool) { - let mut raw_packets = self.gather_outbound_control_packets(vec![], now); - - let state = self.state(); - match state { - AssociationState::Established => { - raw_packets = self.gather_data_packets_to_retransmit(raw_packets, now); - // Decide fast-recovery abandonment before selecting any pending tail. - raw_packets = self.gather_outbound_fast_retransmission_packets(raw_packets, now); - raw_packets = self.gather_outbound_data_and_reconfig_packets(raw_packets, now); - // A queued reciprocal reset may have been held back until the - // DATA it covers received TSNs above. Give it another chance in - // this same poll so DATA and RE-CONFIG can leave together. - raw_packets = self.gather_outbound_control_packets(raw_packets, now); - raw_packets = self.gather_outbound_sack_packets(raw_packets); - raw_packets = self.gather_outbound_forward_tsn_packets(raw_packets); - (raw_packets, true) - } - AssociationState::ShutdownPending | AssociationState::ShutdownSent | AssociationState::ShutdownReceived => { - raw_packets = self.gather_data_packets_to_retransmit(raw_packets, now); - raw_packets = self.gather_outbound_fast_retransmission_packets(raw_packets, now); - raw_packets = self.gather_outbound_sack_packets(raw_packets); - raw_packets = self.gather_outbound_forward_tsn_packets(raw_packets); - self.gather_outbound_shutdown_packets(raw_packets, now) - } - AssociationState::ShutdownAckSent => self.gather_outbound_shutdown_packets(raw_packets, now), - _ => (raw_packets, true), - } - } - - fn gather_outbound_control_packets(&mut self, mut raw_packets: Vec, now: Instant) -> Vec { - if !self.control_queue.is_empty() { - let mut buffered = VecDeque::new(); - let mut request_blocked = false; - let queued = core::mem::take(&mut self.control_queue); - for p in queued { - let outgoing_rsn = Self::packet_reconfig_request_rsn(&p); - - if outgoing_rsn.is_some() && request_blocked { - buffered.push_back(p); - continue; - } - - if outgoing_rsn.is_some_and(|rsn| self.active_reconfig.is_some() && self.active_reconfig != Some(rsn)) { - request_blocked = true; - buffered.push_back(p); - continue; - } - - // The reset boundary cannot be fixed until all already-queued - // DATA for the affected streams has received a TSN. - if outgoing_rsn.is_some_and(|rsn| self.reconfig_has_pending_data(rsn)) { - request_blocked = true; - buffered.push_back(p); - continue; - } - - let p = if let Some(rsn) = outgoing_rsn { - self.refresh_unsent_reconfig(rsn).unwrap_or(p) - } else { - p - }; - - match p.marshal() { - Ok(raw) => { - raw_packets.push(raw); - if let Some(rsn) = outgoing_rsn { - self.active_reconfig = Some(rsn); - } - } - Err(_) => { - warn!("[{}] failed to serialize a control packet", self.side); - // A queued request owns reset state and must not be lost. - if outgoing_rsn.is_some() { - request_blocked = true; - buffered.push_back(p); - } - } - } - } - self.control_queue = buffered; - } - - if self.active_reconfig.is_some() { - self.timers - .restart_if_stale(Timer::Reconfig, now, self.rto_mgr.get_rto()); - } - - raw_packets - } - - fn gather_data_packets_to_retransmit(&mut self, mut raw_packets: Vec, now: Instant) -> Vec { - for p in &self.get_data_packets_to_retransmit(now) { - if let Ok(raw) = p.marshal() { - raw_packets.push(raw); - } else { - warn!("[{}] failed to serialize a DATA packet to be retransmitted", self.side); - } - } - - raw_packets - } - - fn gather_outbound_data_and_reconfig_packets(&mut self, mut raw_packets: Vec, now: Instant) -> Vec { - // Pop unsent data chunks from the pending queue to send as much as - // cwnd and rwnd allow. - let chunks = self.pop_pending_data_chunks_to_send(now); - if !chunks.is_empty() { - // Start timer. (noop if already started) - trace!("[{}] T3-rtx timer start (pt1)", self.side); - self.timers.restart_if_stale(Timer::T3RTX, now, self.rto_mgr.get_rto()); - - for p in &self.bundle_data_chunks_into_packets(chunks) { - if let Ok(raw) = p.marshal() { - raw_packets.push(raw); - } else { - warn!("[{}] failed to serialize a DATA packet", self.side); - } - } - } - - if self.will_retransmit_reconfig { - self.will_retransmit_reconfig = false; - if let Some(rsn) = self.active_reconfig { - debug!("[{}] retransmit RECONFIG rsn={}", self.side, rsn); - if let Some(c) = self.reconfigs.get(&rsn) { - let p = self.create_packet(vec![Box::new(c.clone())]); - if let Ok(raw) = p.marshal() { - raw_packets.push(raw); - } else { - warn!( - "[{}] failed to serialize a RECONFIG packet to be retransmitted", - self.side, - ); - } - } - } - } - - // RFC 6525 section 5.1.1 permits only one request in flight. Keep - // application resets separate from DATA until that request completes. - if self.active_reconfig.is_none() && self.reconfigs.is_empty() && !self.pending_reset_streams.is_empty() { - // DATA on an unrelated stream must not starve a reset, nor should - // one busy stream hold back ready reset requests for other streams. - let outbound_queue = &self.outbound_queue; - let mut stream_ids = vec![]; - self.pending_reset_streams.retain(|id| { - if outbound_queue.pending_contains_stream(*id) { - true - } else { - stream_ids.push(*id); - false - } - }); - - if stream_ids.is_empty() { - return raw_packets; - } - - let rsn = self.generate_next_rsn(); - let tsn = self.my_next_tsn.wrapping_sub(1); - debug!( - "[{}] sending RECONFIG: rsn={} tsn={} streams={:?}", - self.side, rsn, tsn, stream_ids - ); - - self.reconfig_reset_streams.insert(rsn, stream_ids.clone()); - let c = ChunkReconfig { - param_a: Some(Box::new(ParamOutgoingResetRequest { - reconfig_request_sequence_number: rsn, - reconfig_response_sequence_number: self.peer_last_reconfig_rsn, - sender_last_tsn: tsn, - stream_identifiers: stream_ids, - })), - ..Default::default() - }; - self.reconfigs.insert(rsn, c.clone()); - - let p = self.create_packet(vec![Box::new(c)]); - if let Ok(raw) = p.marshal() { - self.active_reconfig = Some(rsn); - raw_packets.push(raw); - } else { - warn!( - "[{}] failed to serialize a RECONFIG packet to be transmitted", - self.side - ); - // Preserve the request for a later serialization attempt. - self.control_queue.push_back(p); - } - } - - // The timer belongs to exactly the request selected above or while - // draining the control queue. - if self.active_reconfig.is_some() { - self.timers - .restart_if_stale(Timer::Reconfig, now, self.rto_mgr.get_rto()); - } - - raw_packets - } - - fn gather_outbound_fast_retransmission_packets(&mut self, mut raw_packets: Vec, now: Instant) -> Vec { - self.expire_inflight_messages(now); - if self.will_retransmit_fast { - self.will_retransmit_fast = false; - - let mut to_fast_retrans: Vec> = vec![]; - let mut fast_retrans_size = COMMON_HEADER_SIZE; - - let mut i = 0; - loop { - let tsn = self.cumulative_tsn_ack_point.wrapping_add(i).wrapping_add(1); - if let Some(c) = self.outbound_queue.get(tsn) { - if c.acked || c.abandoned || c.nsent > 1 || c.miss_indicator < 3 { - i += 1; - continue; - } - - // RFC 4960 Sec 7.2.4 Fast Retransmit on Gap Reports - // 3) Determine how many of the earliest (i.e., lowest TSN) DATA chunks - // marked for retransmission will fit into a single packet, subject - // to constraint of the path MTU of the destination transport - // address to which the packet is being sent. Call this value K. - // Retransmit those K DATA chunks in a single packet. When a Fast - // Retransmit is being performed, the sender SHOULD ignore the value - // of cwnd and SHOULD NOT delay retransmission for this single - // packet. - - if self.abandon_if_needed(tsn, now) { - i += 1; - continue; - } - - let c = self.outbound_queue.get_mut(tsn).unwrap(); - let data_chunk_size = DATA_CHUNK_HEADER_SIZE + c.user_data.len() as u32; - if self.mtu < fast_retrans_size + data_chunk_size { - break; - } - - fast_retrans_size += data_chunk_size; - self.stats.inc_fast_retrans(); - c.nsent += 1; - } else { - break; // end of pending data - } - - if let Some(c) = self.outbound_queue.get_mut(tsn) { - to_fast_retrans.push(Box::new(c.clone())); - trace!( - "[{}] fast-retransmit: tsn={} sent={} htna={}", - self.side, c.tsn, c.nsent, self.fast_recover_exit_point - ); - } - i += 1; - } - - to_fast_retrans.retain(|chunk| { - let data = chunk.as_any().downcast_ref::().unwrap(); - !self.outbound_queue.is_abandoned(data.tsn) - }); - if !to_fast_retrans.is_empty() { - if let Ok(raw) = self.create_packet(to_fast_retrans).marshal() { - raw_packets.push(raw); - } else { - warn!( - "[{}] failed to serialize a DATA packet to be fast-retransmitted", - self.side - ); - } - } - } - - raw_packets - } - - fn gather_outbound_sack_packets(&mut self, mut raw_packets: Vec) -> Vec { - if self.ack_state == AckState::Immediate { - self.ack_state = AckState::Idle; - let sack = self.create_selective_ack_chunk(); - trace!("[{}] sending SACK: {}", self.side, sack); - if let Ok(raw) = self.create_packet(vec![Box::new(sack)]).marshal() { - raw_packets.push(raw); - } else { - warn!("[{}] failed to serialize a SACK packet", self.side); - } - } - - raw_packets - } - - /// RFC 3758 section 3.5 C1-C2: advance over abandoned messages' sent TSNs. - fn advance_peer_tsn_ack_point(&mut self) { - if sna32lt(self.advanced_peer_tsn_ack_point, self.cumulative_tsn_ack_point) { - self.advanced_peer_tsn_ack_point = self.cumulative_tsn_ack_point; - } - let mut next = self.advanced_peer_tsn_ack_point.wrapping_add(1); - while self.outbound_queue.is_abandoned(next) { - self.advanced_peer_tsn_ack_point = next; - next = next.wrapping_add(1); - } - } - - fn gather_outbound_forward_tsn_packets(&mut self, mut raw_packets: Vec) -> Vec { - // Retransmission decisions above may have just abandoned DATA. Advance - // now, including after a timeout with no subsequent incoming SACK. - if self.use_forward_tsn { - let previous = self.advanced_peer_tsn_ack_point; - self.advance_peer_tsn_ack_point(); - if sna32gt(self.advanced_peer_tsn_ack_point, previous) - && sna32gt(self.advanced_peer_tsn_ack_point, self.cumulative_tsn_ack_point) - { - self.will_send_forward_tsn = true; - } - } - /*tracing::debug!( - "[{}] gatherOutboundForwardTSNPackets {}", - self.name, - self.will_send_forward_tsn - );*/ - if self.will_send_forward_tsn { - self.will_send_forward_tsn = false; - if sna32gt(self.advanced_peer_tsn_ack_point, self.cumulative_tsn_ack_point) { - let fwd_tsn = self.create_forward_tsn(); - if let Ok(raw) = self.create_packet(vec![Box::new(fwd_tsn)]).marshal() { - raw_packets.push(raw); - } else { - warn!("[{}] failed to serialize a Forward TSN packet", self.side); - } - } - } - - raw_packets - } - - fn gather_outbound_shutdown_packets(&mut self, mut raw_packets: Vec, now: Instant) -> (Vec, bool) { - let mut ok = true; - - if self.will_send_shutdown { - self.will_send_shutdown = false; - - let shutdown = ChunkShutdown { - cumulative_tsn_ack: self.cumulative_tsn_ack_point, - }; - - if let Ok(raw) = self.create_packet(vec![Box::new(shutdown)]).marshal() { - self.timers.start(Timer::T2Shutdown, now, self.rto_mgr.get_rto()); - raw_packets.push(raw); - } else { - warn!("[{}] failed to serialize a Shutdown packet", self.side); - } - } else if self.will_send_shutdown_ack { - self.will_send_shutdown_ack = false; - - let shutdown_ack = ChunkShutdownAck {}; - - if let Ok(raw) = self.create_packet(vec![Box::new(shutdown_ack)]).marshal() { - self.timers.start(Timer::T2Shutdown, now, self.rto_mgr.get_rto()); - raw_packets.push(raw); - } else { - warn!("[{}] failed to serialize a ShutdownAck packet", self.side); - } - } else if self.will_send_shutdown_complete { - self.will_send_shutdown_complete = false; - - let shutdown_complete = ChunkShutdownComplete {}; - - if let Ok(raw) = self.create_packet(vec![Box::new(shutdown_complete)]).marshal() { - raw_packets.push(raw); - ok = false; - } else { - warn!("[{}] failed to serialize a ShutdownComplete packet", self.side); - } - } - - (raw_packets, ok) - } - - /// get_data_packets_to_retransmit is called when T3-rtx is timed - /// out and retransmit outstanding data chunks that are not acked - /// or abandoned yet. - fn get_data_packets_to_retransmit(&mut self, now: Instant) -> Vec { - self.expire_inflight_messages(now); - let awnd = core::cmp::min(self.cwnd, self.rwnd); - let mut chunks: Vec = vec![]; - let mut bytes_to_send = 0; - let mut done = false; - let mut i = 0; - while !done { - let tsn = self.cumulative_tsn_ack_point.wrapping_add(i).wrapping_add(1); - if let Some(c) = self.outbound_queue.get(tsn) { - if !c.retransmit { - i += 1; - continue; - } - - if self.abandon_if_needed(tsn, now) { - chunks.retain(|c| !self.outbound_queue.is_abandoned(c.tsn)); - bytes_to_send = chunks.iter().map(|c| c.user_data.len()).sum(); - i += 1; - continue; - } - - let c = self.outbound_queue.get_mut(tsn).unwrap(); - if i == 0 && self.rwnd < c.user_data.len() as u32 { - // Send it as a zero window probe - done = true; - } else if bytes_to_send + c.user_data.len() > awnd as usize { - break; - } - - bytes_to_send += c.user_data.len(); - } else { - break; // end of pending data - } - - if let Some(c) = self.outbound_queue.get_mut(tsn) { - trace!( - "[{}] retransmitting tsn={} ssn={} sent={}", - self.side, c.tsn, c.stream_sequence_number, c.nsent - ); - - chunks.push(c.clone()); - } - i += 1; - } - - // A later fragment may exhaust the message's policy after an earlier - // fragment was selected in this pass. Neither should be retransmitted. - for chunk in &mut chunks { - let c = self.outbound_queue.get_mut(chunk.tsn).unwrap(); - c.retransmit = false; - c.nsent += 1; - chunk.nsent = c.nsent; - } - self.bundle_data_chunks_into_packets(chunks) - } - - /// pop_pending_data_chunks_to_send pops chunks from the pending queues as many as - /// the cwnd and rwnd allows to send. - fn pop_pending_data_chunks_to_send(&mut self, now: Instant) -> Vec { - self.expire_inflight_messages(now); - let mut chunks = vec![]; - if self.outbound_queue.pending_len() != 0 { - // RFC 4960 sec 6.1. Transmission of DATA Chunks - // A) At any given time, the data sender MUST NOT transmit new data to - // any destination transport address if its peer's rwnd indicates - // that the peer has no buffer space (i.e., rwnd is 0; see Section - // 6.2.1). However, regardless of the value of rwnd (including if it - // is 0), the data sender can always have one DATA chunk in flight to - // the receiver if allowed by cwnd (see rule B, below). - - loop { - if self.use_forward_tsn { - if let Some((id, unordered, bytes)) = self.outbound_queue.expire_pending(now) { - if let Some(stream) = self.streams.get_mut(&id) { - if !unordered { - stream.sequence_number = stream.sequence_number.wrapping_sub(1); - } - if stream.on_buffer_released(bytes as i64) { - self.events - .push_back(Event::Stream(StreamEvent::BufferedAmountLow { id })); - } - } - continue; - } - } - let Some(c) = self.outbound_queue.peek_pending() else { - break; - }; - let data_len = c.user_data.len(); - - if self.outbound_queue.inflight_bytes() + data_len > self.cwnd as usize { - break; // would exceeds cwnd - } - - if data_len > self.rwnd as usize { - break; // no more rwnd - } - - self.rwnd -= data_len as u32; - - if let Some(chunk) = self.send_next_data_chunk(now) { - chunks.push(chunk); - } - } - - // the data sender can always have one DATA chunk in flight to the receiver - if chunks.is_empty() && self.outbound_queue.inflight_len() == 0 { - // Send zero window probe - if let Some(chunk) = self.send_next_data_chunk(now) { - chunks.push(chunk); - } - } - } - - chunks - } - - /// bundle_data_chunks_into_packets packs DATA chunks into packets. It tries to bundle - /// DATA chunks into a packet so long as the resulting packet size does not exceed - /// the path MTU. - fn bundle_data_chunks_into_packets(&self, chunks: Vec) -> Vec { - let mut packets = vec![]; - let mut chunks_to_send = vec![]; - let mut bytes_in_packet = COMMON_HEADER_SIZE; - - for c in chunks { - // RFC 4960 sec 6.1. Transmission of DATA Chunks - // Multiple DATA chunks committed for transmission MAY be bundled in a - // single packet. Furthermore, DATA chunks being retransmitted MAY be - // bundled with new DATA chunks, as long as the resulting packet size - // does not exceed the path MTU. - if bytes_in_packet + c.user_data.len() as u32 > self.mtu { - packets.push(self.create_packet(chunks_to_send)); - chunks_to_send = vec![]; - bytes_in_packet = COMMON_HEADER_SIZE; - } - - bytes_in_packet += DATA_CHUNK_HEADER_SIZE + c.user_data.len() as u32; - chunks_to_send.push(Box::new(c)); - } - - if !chunks_to_send.is_empty() { - packets.push(self.create_packet(chunks_to_send)); - } - - packets - } - - /// generate_next_rsn returns the my_next_rsn and increases it. The caller should hold the lock. - fn generate_next_rsn(&mut self) -> u32 { - let rsn = self.my_next_rsn; - self.my_next_rsn = self.my_next_rsn.wrapping_add(1); - rsn - } - - /// Timed messages expire at their deadline, before any DATA is selected. - /// In particular, a blocked early chunk must not hide later expired DATA. - fn expire_inflight_messages(&mut self, now: Instant) { - if self.use_forward_tsn { - self.outbound_queue.start_timed_messages(now); - let mut abandoned = false; - for tsn in self.outbound_queue.expired_inflight(now) { - abandoned |= self.abandon_if_needed(tsn, now); - } - while let Some((id, message_id, bytes)) = - self.outbound_queue.expire_pending_tail(now, &mut self.my_next_tsn) - { - self.release_abandoned_buffer(id, message_id, bytes); - abandoned = true; - } - if abandoned { - self.timers.restart_if_stale(Timer::T3RTX, now, self.rto_mgr.get_rto()); - } - } - } - - /// Evaluate retry candidates or messages whose lifetime expired. - /// Abandoning a message also drops its unsent tail. - fn abandon_if_needed(&mut self, tsn: u32, now: Instant) -> bool { - let Some(c) = self.outbound_queue.get(tsn) else { - return false; - }; - if c.abandoned { - return true; - } - if !self.use_forward_tsn { - return false; - } - // Data-channel establishment messages always use reliable delivery. - if c.payload_type == PayloadProtocolIdentifier::Dcep { - return false; - } - let Some((reliability_type, reliability_value)) = c.reliability.or_else(|| { - self.streams - .get(&c.stream_identifier) - .map(|stream| (stream.reliability_type, stream.reliability_value)) - }) else { - return false; - }; - let expired = match reliability_type { - // nsent includes the original send; maxRTX counts only retries. - ReliabilityType::Rexmit => c.nsent > reliability_value, - ReliabilityType::Timed => c.deadline.is_some_and(|deadline| now >= deadline), - ReliabilityType::Reliable => false, - }; - if !expired { - return false; - } - let message_id = c.message_id; - trace!("[{}] abandoning message containing tsn={}", self.side, tsn); - if let Some((id, bytes)) = self.outbound_queue.abandon(tsn, &mut self.my_next_tsn) { - self.release_abandoned_buffer(id, message_id, bytes); - } - true - } - - fn release_abandoned_buffer(&mut self, id: u16, message_id: u64, bytes: usize) { - if let Some(stream) = self.streams.get_mut(&id) { - if message_id >= stream.first_message_id && stream.on_buffer_released(bytes as i64) { - self.events - .push_back(Event::Stream(StreamEvent::BufferedAmountLow { id })); - } - } - } - - fn create_selective_ack_chunk(&mut self) -> ChunkSelectiveAck { - ChunkSelectiveAck { - cumulative_tsn_ack: self.peer_last_tsn, - advertised_receiver_window_credit: self.get_my_receiver_window_credit(), - gap_ack_blocks: self.payload_queue.get_gap_ack_blocks(self.peer_last_tsn), - duplicate_tsn: self.payload_queue.pop_duplicates(), - } - } - - /// create_forward_tsn generates ForwardTSN chunk. - /// This method is called when use_forward_tsn is set to true. - fn create_forward_tsn(&self) -> ChunkForwardTsn { - // RFC 3758 Sec 3.5 C4 - let mut stream_map: HashMap = HashMap::new(); // to report only once per SI - let mut i = self.cumulative_tsn_ack_point.wrapping_add(1); - while sna32lte(i, self.advanced_peer_tsn_ack_point) { - if let Some(c) = self.outbound_queue.get(i) { - // RFC 3758 C4: unordered DATA advances only the TSN point. - if c.unordered { - i = i.wrapping_add(1); - continue; - } - if let Some(ssn) = stream_map.get(&c.stream_identifier) { - if sna16lt(*ssn, c.stream_sequence_number) { - // to report only once with greatest SSN - stream_map.insert(c.stream_identifier, c.stream_sequence_number); - } - } else { - stream_map.insert(c.stream_identifier, c.stream_sequence_number); - } - } else { - break; - } - - i = i.wrapping_add(1); - } - - let mut fwd_tsn = ChunkForwardTsn { - new_cumulative_tsn: self.advanced_peer_tsn_ack_point, - streams: vec![], - }; - - let mut stream_str = String::new(); - for (si, ssn) in &stream_map { - stream_str += format!("(si={} ssn={})", si, ssn).as_str(); - fwd_tsn.streams.push(ChunkForwardTsnStream { - identifier: *si, - sequence: *ssn, - }); - } - trace!( - "[{}] building fwd_tsn: newCumulativeTSN={} cumTSN={} - {}", - self.side, fwd_tsn.new_cumulative_tsn, self.cumulative_tsn_ack_point, stream_str - ); - - fwd_tsn - } - - /// Assign a TSN to the next pending fragment and retain it for retransmission. - fn send_next_data_chunk(&mut self, now: Instant) -> Option { - let chunk = self.outbound_queue.send_next(&mut self.my_next_tsn, now)?; - trace!( - "[{}] sending ppi={} tsn={} ssn={} len={}", - self.side, - chunk.payload_type, - chunk.tsn, - chunk.stream_sequence_number, - chunk.user_data.len() - ); - Some(chunk) - } - - pub(crate) fn send_reset_request(&mut self, stream_identifier: StreamId) -> Result<()> { - let state = self.state(); - if state != AssociationState::Established { - return Err(Error::ErrResetPacketInStateNotExist); - } - - self.pending_reset_streams.push_back(stream_identifier); - self.awake_write_loop(); - - Ok(()) - } - - /// send_payload_data sends the data chunks. - pub(crate) fn send_payload_data(&mut self, message: Vec) -> Result<()> { - let state = self.state(); - if state != AssociationState::Established { - return Err(Error::ErrPayloadDataStateNotExist); - } - - self.outbound_queue.push(message); - - self.awake_write_loop(); - Ok(()) - } - - /// buffered_amount returns total amount (in bytes) of currently buffered user data. - /// This is used only by testing. - pub(crate) fn buffered_amount(&self) -> usize { - self.outbound_queue.pending_bytes() + self.outbound_queue.inflight_bytes() - } - - fn awake_write_loop(&self) { - // No Op on Purpose - } - - fn close_all_timers(&mut self) { - // Close all retransmission & ack timers - for timer in Timer::VALUES { - self.timers.stop(timer); - } - } - - fn on_ack_timeout(&mut self) { - trace!("[{}] ack timed out (ack_state: {})", self.side, self.ack_state); - self.stats.inc_ack_timeouts(); - self.ack_state = AckState::Immediate; - self.awake_write_loop(); - } - - fn on_retransmission_timeout(&mut self, timer_id: Timer, n_rtos: usize) { - match timer_id { - Timer::T1Init => { - if let Err(err) = self.send_init() { - debug!( - "[{}] failed to retransmit init (n_rtos={}): {:?}", - self.side, n_rtos, err - ); - } - } - - Timer::T1Cookie => { - if let Err(err) = self.send_cookie_echo() { - debug!( - "[{}] failed to retransmit cookie-echo (n_rtos={}): {:?}", - self.side, n_rtos, err - ); - } - } - - Timer::T2Shutdown => { - debug!("[{}] retransmission of shutdown timeout (n_rtos={})", self.side, n_rtos); - let state = self.state(); - match state { - AssociationState::ShutdownSent => { - self.will_send_shutdown = true; - self.awake_write_loop(); - } - AssociationState::ShutdownAckSent => { - self.will_send_shutdown_ack = true; - self.awake_write_loop(); - } - _ => {} - } - } - - Timer::T3RTX => { - self.stats.inc_t3timeouts(); - - // RFC 4960 sec 6.3.3 - // E1) For the destination address for which the timer expires, adjust - // its ssthresh with rules defined in Section 7.2.3 and set the - // cwnd <- MTU. - // RFC 4960 sec 7.2.3 - // When the T3-rtx timer expires on an address, SCTP should perform slow - // start by: - // ssthresh = max(cwnd/2, 4*MTU) - // cwnd = 1*MTU - - self.ssthresh = core::cmp::max(self.cwnd / 2, 4 * self.mtu); - self.cwnd = self.mtu; - trace!( - "[{}] updated cwnd={} ssthresh={} inflight={} (RTO)", - self.side, - self.cwnd, - self.ssthresh, - self.outbound_queue.inflight_bytes() - ); - - // RFC 3758 sec 3.5 - // A5) Any time the T3-rtx timer expires, on any destination, the sender - // SHOULD try to advance the "Advanced.Peer.Ack.Point" by following - // the procedures outlined in C2 - C5. - if self.use_forward_tsn { - self.advance_peer_tsn_ack_point(); - - // RFC 3758 Sec 3.5 C3 - if sna32gt(self.advanced_peer_tsn_ack_point, self.cumulative_tsn_ack_point) { - self.will_send_forward_tsn = true; - debug!( - "[{}] on_retransmission_timeout {}: sna32GT({}, {})", - self.side, - self.will_send_forward_tsn, - self.advanced_peer_tsn_ack_point, - self.cumulative_tsn_ack_point - ); - } - } - - debug!( - "[{}] T3-rtx timed out: n_rtos={} cwnd={} ssthresh={}", - self.side, n_rtos, self.cwnd, self.ssthresh - ); - - self.outbound_queue.mark_all_to_retransmit(); - self.awake_write_loop(); - } - - Timer::Reconfig => { - self.will_retransmit_reconfig = true; - self.awake_write_loop(); - } - - _ => {} - } - } - - fn on_retransmission_failure(&mut self, id: Timer) { - match id { - Timer::T1Init => { - error!("[{}] retransmission failure: T1-init", self.side); - self.error = Some(AssociationError::HandshakeFailed(Error::ErrHandshakeInitAck)); - } - - Timer::T1Cookie => { - error!("[{}] retransmission failure: T1-cookie", self.side); - self.error = Some(AssociationError::HandshakeFailed(Error::ErrHandshakeCookieEcho)); - } - - Timer::T2Shutdown => { - error!("[{}] retransmission failure: T2-shutdown", self.side); - } - - Timer::T3RTX => { - // T3-rtx timer will not fail by design - // Justifications: - // * ICE would fail if the connectivity is lost - // * WebRTC spec is not clear how this incident should be reported to ULP - error!("[{}] retransmission failure: T3-rtx (DATA)", self.side); - } - - Timer::Reconfig => { - if let Some(rsn) = self.active_reconfig { - error!("[{}] retransmission failure: Reconfig rsn={}", self.side, rsn); - self.finish_reconfig(rsn, Err(StreamResetError::Failed)); - } else { - self.timers.stop(Timer::Reconfig); - } - } - - _ => {} - } - } - - /// Whether no timers are running - #[cfg(test)] - pub(crate) fn is_idle(&self) -> bool { - Timer::VALUES - .iter() - //.filter(|&&t| t != Timer::KeepAlive && t != Timer::PushNewCid) - .filter_map(|&t| Some((t, self.timers.get(t)?))) - .min_by_key(|&(_, time)| time) - //.map_or(true, |(timer, _)| timer == Timer::Idle) - .is_none() - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/association/state.rs b/rs/moq-webrtc/src/vendor/sctp_proto/association/state.rs deleted file mode 100644 index 9d92487c777..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/association/state.rs +++ /dev/null @@ -1,102 +0,0 @@ -use core::fmt; - -/// association state enums -#[derive(Debug, Copy, Clone, PartialEq, Default)] -pub(crate) enum AssociationState { - #[default] - Closed = 0, - CookieWait = 1, - CookieEchoed = 2, - Established = 3, - ShutdownAckSent = 4, - ShutdownPending = 5, - ShutdownReceived = 6, - ShutdownSent = 7, -} - -impl From for AssociationState { - fn from(v: u8) -> AssociationState { - match v { - 1 => AssociationState::CookieWait, - 2 => AssociationState::CookieEchoed, - 3 => AssociationState::Established, - 4 => AssociationState::ShutdownAckSent, - 5 => AssociationState::ShutdownPending, - 6 => AssociationState::ShutdownReceived, - 7 => AssociationState::ShutdownSent, - _ => AssociationState::Closed, - } - } -} - -impl fmt::Display for AssociationState { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - AssociationState::Closed => "Closed", - AssociationState::CookieWait => "CookieWait", - AssociationState::CookieEchoed => "CookieEchoed", - AssociationState::Established => "Established", - AssociationState::ShutdownPending => "ShutdownPending", - AssociationState::ShutdownSent => "ShutdownSent", - AssociationState::ShutdownReceived => "ShutdownReceived", - AssociationState::ShutdownAckSent => "ShutdownAckSent", - }; - write!(f, "{}", s) - } -} - -impl AssociationState { - pub(crate) fn is_closing(&self) -> bool { - matches!( - *self, - AssociationState::ShutdownSent - | AssociationState::ShutdownAckSent - | AssociationState::ShutdownPending - | AssociationState::ShutdownReceived - ) - } - - pub(crate) fn is_drained(&self) -> bool { - self.is_closing() - } -} - -/// ack mode (for testing) -#[derive(Debug, Copy, Clone, PartialEq, Default)] -pub(crate) enum AckMode { - #[default] - Normal, - NoDelay, - AlwaysDelay, -} - -impl fmt::Display for AckMode { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - AckMode::Normal => "Normal", - AckMode::NoDelay => "NoDelay", - AckMode::AlwaysDelay => "AlwaysDelay", - }; - write!(f, "{}", s) - } -} - -/// ack transmission state -#[derive(Debug, Copy, Clone, PartialEq, Default)] -pub(crate) enum AckState { - #[default] - Idle, // ack timer is off - Immediate, // will send ack immediately - Delay, // ack timer is on (ack is being delayed) -} - -impl fmt::Display for AckState { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - AckState::Idle => "Idle", - AckState::Immediate => "Immediate", - AckState::Delay => "Delay", - }; - write!(f, "{}", s) - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/association/stats.rs b/rs/moq-webrtc/src/vendor/sctp_proto/association/stats.rs deleted file mode 100644 index bf24d3f980f..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/association/stats.rs +++ /dev/null @@ -1,59 +0,0 @@ -/// Association statistics -#[derive(Default, Debug, Copy, Clone)] -pub struct AssociationStats { - n_datas: u64, - n_sacks: u64, - n_t3timeouts: u64, - n_ack_timeouts: u64, - n_fast_retrans: u64, -} - -impl AssociationStats { - pub fn inc_datas(&mut self) { - self.n_datas += 1; - } - - pub fn get_num_datas(&mut self) -> u64 { - self.n_datas - } - - pub fn inc_sacks(&mut self) { - self.n_sacks += 1; - } - - pub fn get_num_sacks(&mut self) -> u64 { - self.n_sacks - } - - pub fn inc_t3timeouts(&mut self) { - self.n_t3timeouts += 1; - } - - pub fn get_num_t3timeouts(&mut self) -> u64 { - self.n_t3timeouts - } - - pub fn inc_ack_timeouts(&mut self) { - self.n_ack_timeouts += 1; - } - - pub fn get_num_ack_timeouts(&mut self) -> u64 { - self.n_ack_timeouts - } - - pub fn inc_fast_retrans(&mut self) { - self.n_fast_retrans += 1; - } - - pub fn get_num_fast_retrans(&mut self) -> u64 { - self.n_fast_retrans - } - - pub fn reset(&mut self) { - self.n_datas = 0; - self.n_sacks = 0; - self.n_t3timeouts = 0; - self.n_ack_timeouts = 0; - self.n_fast_retrans = 0; - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/association/stream.rs b/rs/moq-webrtc/src/vendor/sctp_proto/association/stream.rs deleted file mode 100644 index d41f3a258b3..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/association/stream.rs +++ /dev/null @@ -1,738 +0,0 @@ -use crate::vendor::sctp_proto::association::Association; -use crate::vendor::sctp_proto::association::state::AssociationState; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier}; -use crate::vendor::sctp_proto::error::{Error, Result}; -use crate::vendor::sctp_proto::queue::reassembly_queue::{Chunks, ReassemblyQueue}; -use crate::vendor::sctp_proto::{ErrorCauseCode, Side}; - -use crate::vendor::sctp_proto::util::{ByteSlice, BytesArray, BytesSource}; -use bytes::Bytes; -use core::fmt; -use std::vec; -use std::vec::Vec; -use tracing::{debug, error, trace}; - -/// Identifier for a stream within a particular association -pub type StreamId = u16; - -/// Cumulative WebRTC application payload totals at the SCTP API boundary. -/// -/// Writes count once after queue acceptance; reads count once when a complete -/// message is returned. Retries, acknowledgements and abandonment do not change -/// these totals. Text uses UTF-8 bytes. Empty-message PPIDs count one message -/// and zero bytes; DCEP and unknown PPIDs are excluded. An empty write that -/// queues no SCTP message is excluded (use the empty PPID with its dummy byte). -/// All counters saturate at `u64::MAX`. -/// -/// This is not a complete RTCDataChannelStats report: the embedding layer owns -/// label, protocol, WebRTC state, timestamp and report ID. Sends buffered above -/// SCTP and reads discarded above SCTP require accounting at that layer's API -/// boundary. Use checked conversion for WebIDL's 32-bit message counters. -/// Pair `generation` with an association identity for a unique report identity; -/// the numeric stream ID alone can be reused. Retain final snapshots from -/// [`crate::vendor::sctp_proto::Event::DataChannelStatsFinal`] for closed-channel reporting. -#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)] -pub struct DataChannelStats { - /// SCTP stream identifier. - pub stream_identifier: StreamId, - /// Unique stream generation within this association. - pub generation: u64, - /// Successfully accepted application messages. - pub messages_sent: u64, - /// Application payload bytes accepted for sending. - pub bytes_sent: u64, - /// Complete application messages returned to the caller. - pub messages_received: u64, - /// Application payload bytes returned to the caller. - pub bytes_received: u64, -} - -impl DataChannelStats { - fn payload_bytes(ppi: PayloadProtocolIdentifier, len: usize) -> Option { - match ppi { - PayloadProtocolIdentifier::String | PayloadProtocolIdentifier::Binary => { - Some(u64::try_from(len).unwrap_or(u64::MAX)) - } - PayloadProtocolIdentifier::StringEmpty | PayloadProtocolIdentifier::BinaryEmpty => Some(0), - _ => None, - } - } - - fn sent(&mut self, ppi: PayloadProtocolIdentifier, len: usize) { - if let Some(bytes) = Self::payload_bytes(ppi, len) { - self.messages_sent = self.messages_sent.saturating_add(1); - self.bytes_sent = self.bytes_sent.saturating_add(bytes); - } - } - - fn received(&mut self, ppi: PayloadProtocolIdentifier, len: usize) { - if let Some(bytes) = Self::payload_bytes(ppi, len) { - self.messages_received = self.messages_received.saturating_add(1); - self.bytes_received = self.bytes_received.saturating_add(bytes); - } - } -} - -/// Why a stream reset did not complete successfully. -#[non_exhaustive] -#[derive(Debug, Copy, Clone, PartialEq, Eq)] -pub enum StreamResetError { - /// The peer explicitly denied the reset request. - Denied, - /// The reset failed because of a protocol error or exhausted retransmissions. - Failed, -} - -/// Application events about streams -#[non_exhaustive] -#[derive(Debug, PartialEq, Eq)] -pub enum StreamEvent { - /// One or more new streams has been opened - Opened { - /// Which stream was opened - id: StreamId, - }, - /// A currently open stream has data or errors waiting to be read - Readable { - /// Which stream is now readable - id: StreamId, - }, - /// A formerly write-blocked stream might be ready for a write or have been stopped - /// - /// Only generated for streams that are currently open. - Writable { - /// Which stream is now writable - id: StreamId, - }, - /// The stream was torn down by a reset, an inbound reset - /// request from the peer naming the id was processed or - /// its reciprocal to a locally-initiated one. - /// - /// No more data can be read from or written to it. - /// - /// Once this fires, either [`StreamEvent::ResetComplete`] or - /// [`StreamEvent::ResetFailed`] for the same id is guaranteed to eventually - /// follow, unless the association closes first. - Finished { - /// Which stream has been finished - id: StreamId, - }, - /// A reset handshake involving this stream id completed successfully. - /// - /// The id can be reused unless a newer reset for the same id has since - /// started or failed. - ResetComplete { - /// Which stream id completed its reset. - id: StreamId, - }, - /// A reset handshake involving this stream id did not complete. - /// - /// The id remains unavailable for reuse until a later reset succeeds or - /// the association closes. - ResetFailed { - /// Which stream id failed to reset. - id: StreamId, - /// Why the reset did not complete. - reason: StreamResetError, - }, - /// The peer asked us to stop sending on an outgoing stream - Stopped { - /// Which stream has been stopped - id: StreamId, - /// Error code supplied by the peer - error_code: ErrorCauseCode, - }, - /// At least one new stream of a certain directionality may be opened - Available, - /// The number of bytes of outgoing data buffered is lower than the threshold. - BufferedAmountLow { - /// Which stream is now readable - id: StreamId, - }, - /// The number of bytes of outgoing data buffered is higher than the threshold. - BufferedAmountHigh { - /// Which stream has crossed the high threshold - id: StreamId, - }, -} - -/// Reliability type for stream -#[derive(Debug, Copy, Clone, PartialEq, Default)] -pub enum ReliabilityType { - /// ReliabilityTypeReliable is used for reliable transmission - #[default] - Reliable = 0, - /// Limit retries per DATA chunk, excluding its original transmission. - /// Originals and the last permitted retry remain buffered until acknowledged - /// or a subsequent recovery event requires abandonment. - Rexmit = 1, - /// ReliabilityTypeTimed is used for partial reliability by retransmission duration - Timed = 2, -} - -impl fmt::Display for ReliabilityType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - ReliabilityType::Reliable => "Reliable", - ReliabilityType::Rexmit => "Rexmit", - ReliabilityType::Timed => "Timed", - }; - write!(f, "{}", s) - } -} - -impl From for ReliabilityType { - fn from(v: u8) -> ReliabilityType { - match v { - 1 => ReliabilityType::Rexmit, - 2 => ReliabilityType::Timed, - _ => ReliabilityType::Reliable, - } - } -} - -/// Stream represents an SCTP stream -pub struct Stream<'a> { - pub(crate) stream_identifier: StreamId, - pub(crate) association: &'a mut Association, -} - -impl<'a> Stream<'a> { - /// Return a read-only snapshot for the current stream generation. - pub fn stats(&self) -> Result { - self.association - .streams - .get(&self.stream_identifier) - .map(|s| s.stats) - .ok_or(Error::ErrStreamClosed) - } - - /// read reads a packet of len(p) bytes, dropping the Payload Protocol Identifier. - /// Returns EOF when the stream is reset or an error if the stream is closed - /// otherwise. - pub fn read(&mut self) -> Result> { - self.read_sctp() - } - - /// read_sctp reads a packet of len(p) bytes and returns the associated Payload - /// Protocol Identifier. - /// Returns EOF when the stream is reset or an error if the stream is closed - /// otherwise. - pub fn read_sctp(&mut self) -> Result> { - let (message, drained, generation) = if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) - { - if s.state != RecvSendState::ReadWritable && s.state != RecvSendState::Readable { - return Err(Error::ErrStreamClosed); - } - - let message = s.reassembly_queue.read(); - let drained = message.is_some() && s.reassembly_queue.get_num_bytes() == 0; - (message, drained, s.stats.generation) - } else { - return Err(Error::ErrStreamClosed); - }; - - if drained { - self.association.finish_retiring_stream(self.stream_identifier)?; - } - - // A DATA chunk may exceed the last few bytes of receive credit. Reading - // the final complete message can therefore leave a full partial message. - if message.is_some() && self.association.receive_capacity_exhausted() { - self.association.abort_receive_capacity(); - } - - if let Some(message) = &message { - let stats = self - .association - .streams - .get_mut(&self.stream_identifier) - .filter(|s| s.stats.generation == generation) - .map(|s| &mut s.stats) - .or_else(|| { - self.association.events.iter_mut().find_map(|event| match event { - crate::vendor::sctp_proto::Event::DataChannelStatsFinal(stats) - if stats.generation == generation => - { - Some(stats) - } - _ => None, - }) - }); - if let Some(stats) = stats { - stats.received(message.ppi, message.len()); - } - } - Ok(message) - } - - /// write_sctp writes len(p) bytes from p to the DTLS connection - pub fn write_sctp(&mut self, p: &Bytes, ppi: PayloadProtocolIdentifier) -> Result { - self.write_source(&mut ByteSlice::from_slice(p), ppi) - } - - /// Send data on the given stream. - /// - /// Uses the deafult payload protocol (PPI). - /// - /// Returns the number of bytes successfully written. - pub fn write(&mut self, data: &[u8]) -> Result { - self.write_with_ppi(data, self.get_default_payload_type()?) - } - - /// Send data on the given stream, with a specific payload protocol. - /// - /// Returns the number of bytes successfully written. - pub fn write_with_ppi(&mut self, data: &[u8], ppi: PayloadProtocolIdentifier) -> Result { - self.write_source(&mut ByteSlice::from_slice(data), ppi) - } - - /// write writes len(p) bytes from p with the default Payload Protocol Identifier - pub fn write_chunk(&mut self, p: &Bytes) -> Result { - self.write_source(&mut ByteSlice::from_slice(p), self.get_default_payload_type()?) - } - - /// Send data on the given stream - /// - /// Returns the number of bytes and chunks successfully written. - /// Note that this method might also write a partial chunk. In this case - /// it will not count this chunk as fully written. However - /// the chunk will be advanced and contain only non-written data after the call. - pub fn write_chunks(&mut self, data: &mut [Bytes]) -> Result { - self.write_source(&mut BytesArray::from_chunks(data), self.get_default_payload_type()?) - } - - /// write_source writes BytesSource to the DTLS connection - fn write_source(&mut self, source: &mut B, ppi: PayloadProtocolIdentifier) -> Result { - if !self.is_writable() { - return Err(Error::ErrStreamClosed); - } - - if source.remaining() > self.association.max_send_message_size() as usize { - return Err(Error::ErrOutboundPacketTooLarge); - } - - let state: AssociationState = self.association.state(); - match state { - AssociationState::ShutdownSent - | AssociationState::ShutdownAckSent - | AssociationState::ShutdownPending - | AssociationState::ShutdownReceived => return Err(Error::ErrStreamClosed), - _ => {} - }; - - let (p, _) = source.pop_chunk(self.association.max_send_message_size() as usize); - - if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) { - let (is_buffered_amount_high, mut chunks) = s.packetize(&p, ppi); - for chunk in &mut chunks { - chunk.reliability = Some((s.reliability_type, s.reliability_value)); - } - let queued = !chunks.is_empty(); - self.association.send_payload_data(chunks)?; - if queued { - self.association - .streams - .get_mut(&self.stream_identifier) - .expect("accepted stream remains registered") - .stats - .sent(ppi, p.len()); - } - - if is_buffered_amount_high { - trace!("StreamEvent::BufferedAmountHigh"); - self.association - .events - .push_back(crate::vendor::sctp_proto::association::Event::Stream( - StreamEvent::BufferedAmountHigh { - id: self.stream_identifier, - }, - )); - } - - Ok(p.len()) - } else { - Err(Error::ErrStreamClosed) - } - } - - pub fn is_readable(&self) -> bool { - if let Some(s) = self.association.streams.get(&self.stream_identifier) { - s.state == RecvSendState::Readable || s.state == RecvSendState::ReadWritable - } else { - false - } - } - - pub fn is_writable(&self) -> bool { - // RFC 6525 section 5.1.2 A1 forbids assigning new SSNs while an - // Outgoing SSN Reset Request for this stream is pending. A failed - // reset also quarantines the outgoing direction because the peer may - // already have reset its corresponding incoming stream. - if self.association.stream_reset_blocked(self.stream_identifier) { - return false; - } - if let Some(s) = self.association.streams.get(&self.stream_identifier) { - s.state == RecvSendState::Writable || s.state == RecvSendState::ReadWritable - } else { - false - } - } - - /// stop closes the read-direction of the stream. - /// Future calls to read are not permitted after calling stop. - /// If stopping removes the last way to drain an exhausted receive buffer, - /// the association reports [`super::AssociationError::ReceiveBufferExhausted`]. - /// - /// NOTE: a stream closed without a queued reset never produces - /// `StreamEvent::Finished` followed by `StreamEvent::ResetComplete` or - /// `StreamEvent::ResetFailed`. - pub fn stop(&mut self) -> Result<()> { - let retiring = self.association.retiring_streams.contains_key(&self.stream_identifier); - let reset = self - .association - .streams - .get(&self.stream_identifier) - .is_some_and(|s| s.state == RecvSendState::Readable || s.state == RecvSendState::ReadWritable); - - if reset && !retiring && !self.association.stream_reset_in_progress(self.stream_identifier) { - // Reset the outgoing stream - // https://tools.ietf.org/html/rfc6525 - // - // Queued before clearing the read bit below, send_reset_request - // is the only fallible step, and failing after the state - // mutation would leave the stream half-closed with the reset - // silently dropped and unretryable. - self.association.send_reset_request(self.stream_identifier)?; - } - - if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) { - s.state = ((s.state as u8) & 0x2).into(); - } - - // stop() promises that future reads are not permitted. If a reset was - // preserving unread boundary DATA, discard that old generation now so - // its Finished event and unrelated association events cannot stall. - if retiring { - self.association.discard_retiring_streams(self.stream_identifier); - } - - if self.association.receive_capacity_exhausted() { - self.association.abort_receive_capacity(); - } - - Ok(()) - } - - /// finish closes the write-direction of the stream. - /// Future calls to write are not permitted after calling Close. - pub fn finish(&mut self) -> Result<()> { - if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) { - s.state = ((s.state as u8) & 0x1).into(); - } - Ok(()) - } - - /// close shuts down both the read and write halves of this stream. - /// - /// This is a convenience method that calls `finish()` followed by `stop()`. - /// Resets the stream when both halves are shutdown. - /// - /// The single failure mode is `stop()`'s, if the association is not - /// established, no reset was queued, retrying `close()` will - /// attempt the reset again. - pub fn close(&mut self) -> Result<()> { - self.finish()?; - self.stop() - } - - /// stream_identifier returns the Stream identifier associated to the stream. - pub fn stream_identifier(&self) -> StreamId { - self.stream_identifier - } - - /// set_default_payload_type sets the default payload type used by write. - pub fn set_default_payload_type(&mut self, default_payload_type: PayloadProtocolIdentifier) -> Result<()> { - if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) { - s.default_payload_type = default_payload_type; - Ok(()) - } else { - Err(Error::ErrStreamClosed) - } - } - - /// get_default_payload_type returns the payload type associated to the stream. - pub fn get_default_payload_type(&self) -> Result { - if let Some(s) = self.association.streams.get(&self.stream_identifier) { - Ok(s.default_payload_type) - } else { - Err(Error::ErrStreamClosed) - } - } - - /// set_reliability_params sets reliability parameters for this stream. - /// - /// Timed-message lifetimes start at the next [`Association::poll_transmit`], using its - /// caller-supplied time, and include waiting for send credit after that poll. Each - /// accepted message retains its reliability policy even if the stream settings change. - pub fn set_reliability_params(&mut self, unordered: bool, rel_type: ReliabilityType, rel_val: u32) -> Result<()> { - if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) { - debug!( - "[{}] reliability params: ordered={} type={} value={}", - s.side, !unordered, rel_type, rel_val - ); - s.unordered = unordered; - s.reliability_type = rel_type; - s.reliability_value = rel_val; - Ok(()) - } else { - Err(Error::ErrStreamClosed) - } - } - - /// buffered_amount returns the number of bytes of data currently queued to be sent over this stream. - pub fn buffered_amount(&self) -> Result { - if let Some(s) = self.association.streams.get(&self.stream_identifier) { - Ok(s.buffered_amount) - } else { - Err(Error::ErrStreamClosed) - } - } - - /// buffered_amount_low_threshold returns the number of bytes of buffered outgoing data that is - /// considered "low." Defaults to 0. - pub fn buffered_amount_low_threshold(&self) -> Result { - if let Some(s) = self.association.streams.get(&self.stream_identifier) { - Ok(s.buffered_amount_low) - } else { - Err(Error::ErrStreamClosed) - } - } - - /// set_buffered_amount_low_threshold is used to update the threshold. - /// See buffered_amount_low_threshold(). - pub fn set_buffered_amount_low_threshold(&mut self, th: usize) -> Result<()> { - if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) { - s.buffered_amount_low = th; - Ok(()) - } else { - Err(Error::ErrStreamClosed) - } - } - - /// buffered_amount_high_threshold returns the number of bytes of buffered outgoing data that is - /// considered "high." Defaults to usize::MAX (effectively disabled). - pub fn buffered_amount_high_threshold(&self) -> Result { - if let Some(s) = self.association.streams.get(&self.stream_identifier) { - Ok(s.buffered_amount_high) - } else { - Err(Error::ErrStreamClosed) - } - } - - /// set_buffered_amount_high_threshold is used to update the threshold. - /// See buffered_amount_high_threshold(). - pub fn set_buffered_amount_high_threshold(&mut self, th: usize) -> Result<()> { - if let Some(s) = self.association.streams.get_mut(&self.stream_identifier) { - s.buffered_amount_high = th; - Ok(()) - } else { - Err(Error::ErrStreamClosed) - } - } -} - -#[derive(Debug, Copy, Clone, Eq, PartialEq, Default)] -pub enum RecvSendState { - #[default] - Closed = 0, - Readable = 1, - Writable = 2, - ReadWritable = 3, -} - -impl From for RecvSendState { - fn from(v: u8) -> Self { - match v { - 1 => RecvSendState::Readable, - 2 => RecvSendState::Writable, - 3 => RecvSendState::ReadWritable, - _ => RecvSendState::Closed, - } - } -} - -/// StreamState represents the state of an SCTP stream -#[derive(Default, Debug)] -pub struct StreamState { - pub(crate) stats: DataChannelStats, - pub(crate) first_message_id: u64, - pub(crate) side: Side, - pub(crate) max_payload_size: u32, - pub(crate) stream_identifier: StreamId, - pub(crate) default_payload_type: PayloadProtocolIdentifier, - pub(crate) reassembly_queue: ReassemblyQueue, - pub(crate) sequence_number: u16, - pub(crate) state: RecvSendState, - pub(crate) unordered: bool, - pub(crate) reliability_type: ReliabilityType, - pub(crate) reliability_value: u32, - pub(crate) buffered_amount: usize, - pub(crate) buffered_amount_low: usize, - pub(crate) buffered_amount_high: usize, -} -impl StreamState { - pub(crate) fn new( - side: Side, - stream_identifier: StreamId, - max_payload_size: u32, - max_receive_message_size: u32, - default_payload_type: PayloadProtocolIdentifier, - ) -> Self { - StreamState { - stats: DataChannelStats { - stream_identifier, - ..Default::default() - }, - first_message_id: 0, - side, - stream_identifier, - max_payload_size, - default_payload_type, - reassembly_queue: ReassemblyQueue::new(stream_identifier, max_receive_message_size), - sequence_number: 0, - state: RecvSendState::ReadWritable, - unordered: false, - reliability_type: ReliabilityType::Reliable, - reliability_value: 0, - buffered_amount: 0, - buffered_amount_low: 0, - buffered_amount_high: usize::MAX, - } - } - - pub(crate) fn handle_data(&mut self, pd: &ChunkPayloadData) -> Result { - self.reassembly_queue.push(pd.clone()) - } - - fn packetize(&mut self, raw: &Bytes, ppi: PayloadProtocolIdentifier) -> (bool, Vec) { - let mut i = 0; - let mut remaining = raw.len(); - - // From draft-ietf-rtcweb-data-protocol-09, section 6: - // All Data Channel Establishment Protocol messages MUST be sent using - // ordered delivery and reliable transmission. - let unordered = ppi != PayloadProtocolIdentifier::Dcep && self.unordered; - - let mut chunks = vec![]; - - while remaining != 0 { - // self.association.max_payload_size - let fragment_size = core::cmp::min(self.max_payload_size as usize, remaining); - - // Copy the userdata since we'll have to store it until acked - // and the caller may re-use the buffer in the mean time - let user_data = raw.slice(i..i + fragment_size); - - let chunk = ChunkPayloadData { - stream_identifier: self.stream_identifier, - user_data, - unordered, - beginning_fragment: i == 0, - ending_fragment: remaining - fragment_size == 0, - immediate_sack: false, - payload_type: ppi, - stream_sequence_number: self.sequence_number, - ..Default::default() - }; - - chunks.push(chunk); - - remaining -= fragment_size; - i += fragment_size; - } - - // RFC 4960 Sec 6.6 - // Note: When transmitting ordered and unordered data, an endpoint does - // not increment its Stream Sequence Number when transmitting a DATA - // chunk with U flag set to 1. - if !unordered { - self.sequence_number = self.sequence_number.wrapping_add(1); - } - - let old_amount = self.buffered_amount; - self.buffered_amount += raw.len(); - let new_amount = self.buffered_amount; - - // Check if we crossed the high threshold - let is_buffered_amount_high = old_amount < self.buffered_amount_high && new_amount >= self.buffered_amount_high; - - (is_buffered_amount_high, chunks) - } - - /// This method is called by association's read_loop (go-)routine to notify this stream - /// of the specified amount of outgoing data has been delivered to the peer. - pub(crate) fn on_buffer_released(&mut self, n_bytes_released: i64) -> bool { - if n_bytes_released <= 0 { - return false; - } - - let from_amount = self.buffered_amount; - let new_amount = if from_amount < n_bytes_released as usize { - self.buffered_amount = 0; - error!( - "[{}] released buffer size {} should be <= {}", - self.side, n_bytes_released, 0, - ); - 0 - } else { - self.buffered_amount -= n_bytes_released as usize; - - from_amount - n_bytes_released as usize - }; - - let buffered_amount_low = self.buffered_amount_low; - - trace!( - "[{}] bufferedAmount = {}, from_amount = {}, buffered_amount_low = {}", - self.side, new_amount, from_amount, buffered_amount_low, - ); - - from_amount > buffered_amount_low && new_amount <= buffered_amount_low - } - - pub(crate) fn get_num_bytes_in_reassembly_queue(&self) -> usize { - // No lock is required as it reads the size with atomic load function. - self.reassembly_queue.get_num_bytes() - } -} - -#[cfg(test)] -mod stats_tests { - use super::*; - - #[test] - fn counters_saturate_and_share_payload_projection() { - let mut stats = DataChannelStats { - messages_sent: u64::MAX - 1, - bytes_sent: u64::MAX - 1, - messages_received: u64::MAX - 1, - bytes_received: u64::MAX - 1, - ..Default::default() - }; - for ppi in [PayloadProtocolIdentifier::Binary, PayloadProtocolIdentifier::String] { - stats.sent(ppi, 2); - stats.received(ppi, 2); - } - assert_eq!(stats.messages_sent, u64::MAX); - assert_eq!(stats.bytes_sent, u64::MAX); - assert_eq!(stats.messages_received, u64::MAX); - assert_eq!(stats.bytes_received, u64::MAX); - for ppi in [PayloadProtocolIdentifier::Dcep, PayloadProtocolIdentifier::Unknown] { - let mut stats = DataChannelStats::default(); - stats.sent(ppi, 10); - stats.received(ppi, 10); - assert_eq!(stats, DataChannelStats::default()); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/association/timed_reliability_test.rs b/rs/moq-webrtc/src/vendor/sctp_proto/association/timed_reliability_test.rs deleted file mode 100644 index 8a4c4d745ca..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/association/timed_reliability_test.rs +++ /dev/null @@ -1,313 +0,0 @@ -use super::*; - -fn timed_fixture(unordered: bool) -> Association { - let mut a = Association { - state: AssociationState::Established, - use_forward_tsn: true, - my_next_tsn: 1, - max_send_message_size: 100, - max_receive_message_size: 100, - max_payload_size: 4, - cwnd: 100, - rwnd: 100, - mtu: 1400, - ..Default::default() - }; - a.create_stream(1, false, PayloadProtocolIdentifier::Binary).unwrap(); - let mut stream = a.stream(1).unwrap(); - stream - .set_reliability_params(unordered, ReliabilityType::Timed, 10) - .unwrap(); - stream.write(b"abcdefghij").unwrap(); - a -} - -#[test] -fn timed_recovery_obeys_exact_deadline() { - let now = Instant::now(); - for fast in [false, true] { - for unordered in [false, true] { - for delay in [9, 10, 20, 2_000] { - let mut a = timed_fixture(unordered); - a.pop_pending_data_chunks_to_send(now); - for tsn in 1..=3 { - let c = a.outbound_queue.get_mut(tsn).unwrap(); - c.retransmit = true; - c.miss_indicator = 3; - } - let later = now + Duration::from_millis(delay); - let packets = if fast { - a.will_retransmit_fast = true; - a.gather_outbound_fast_retransmission_packets(vec![], later) - } else { - a.get_data_packets_to_retransmit(later) - .into_iter() - .map(|p| p.marshal().unwrap()) - .collect() - }; - assert_eq!(packets.is_empty(), delay >= 10); - for tsn in 1..=3 { - assert_eq!(a.outbound_queue.is_abandoned(tsn), delay >= 10); - } - } - } - } -} - -#[test] -fn timed_expiry_is_not_hidden_by_window_or_fast_packet_limit() { - let now = Instant::now(); - for fast in [false, true] { - let mut a = timed_fixture(false); - a.pop_pending_data_chunks_to_send(now); - // An earlier reliable message exhausts the available send budget. - let first = a.outbound_queue.get_mut(1).unwrap(); - first.deadline = None; - first.reliability = Some((ReliabilityType::Reliable, 0)); - first.message_id = u64::MAX; - for tsn in 1..=3 { - let c = a.outbound_queue.get_mut(tsn).unwrap(); - c.retransmit = true; - c.miss_indicator = 3; - } - a.cwnd = 0; - a.mtu = 0; - let later = now + Duration::from_millis(10); - if fast { - a.will_retransmit_fast = true; - assert!(a.gather_outbound_fast_retransmission_packets(vec![], later).is_empty()); - } else { - assert!(a.get_data_packets_to_retransmit(later).is_empty()); - } - assert!(!a.outbound_queue.is_abandoned(1)); - assert!(a.outbound_queue.is_abandoned(2)); - assert!(a.outbound_queue.is_abandoned(3)); - assert_eq!(a.outbound_queue.get(1).unwrap().nsent, 1); - } -} - -#[test] -fn timed_expiry_abandons_pending_tail_at_tsn_wrap_without_retry() { - let now = Instant::now(); - for unordered in [false, true] { - let mut a = timed_fixture(unordered); - a.my_next_tsn = u32::MAX; - a.cumulative_tsn_ack_point = u32::MAX - 1; - a.advanced_peer_tsn_ack_point = u32::MAX - 1; - a.send_next_data_chunk(now).unwrap(); - // Expiry must run even when no retransmission has been requested and - // before a pending sibling could be sent for the first time. - let later = now + Duration::from_millis(10); - assert!(a.pop_pending_data_chunks_to_send(later).is_empty()); - assert!(a.outbound_queue.is_abandoned(u32::MAX)); - assert!(a.outbound_queue.is_abandoned(0)); - assert_eq!(a.outbound_queue.pending_len(), 0); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); - assert_eq!(a.outbound_queue.get(u32::MAX).unwrap().nsent, 1); - } -} - -#[test] -fn timed_expiry_preserves_delivered_message_and_gap_acked_siblings() { - let now = Instant::now(); - for all_delivered in [false, true] { - let mut a = timed_fixture(false); - a.pop_pending_data_chunks_to_send(now); - let end = if all_delivered { 3 } else { 2 }; - for tsn in 1..=end { - let released = a.outbound_queue.mark_as_acked(tsn); - a.streams.get_mut(&1).unwrap().on_buffer_released(released as i64); - } - let later = now + Duration::from_secs(2); - a.outbound_queue.mark_all_to_retransmit(); - assert!(a.get_data_packets_to_retransmit(later).is_empty()); - assert_eq!(a.outbound_queue.is_abandoned(3), !all_delivered); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); - // Repeated recovery must neither refund bytes again nor send DATA. - a.outbound_queue.mark_all_to_retransmit(); - assert!(a.get_data_packets_to_retransmit(later).is_empty()); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); - for tsn in 1..=end { - assert!(a.outbound_queue.get(tsn).unwrap().acked); - assert_eq!(a.outbound_queue.get(tsn).unwrap().nsent, 1); - } - } -} - -#[test] -fn timed_expiry_preserves_reliable_dcep_and_non_negotiated_traffic() { - let now = Instant::now(); - for control in 0..3 { - let mut a = timed_fixture(false); - a.pop_pending_data_chunks_to_send(now); - if control == 2 { - a.use_forward_tsn = false; - } - for tsn in 1..=3 { - let c = a.outbound_queue.get_mut(tsn).unwrap(); - c.retransmit = true; - match control { - 0 => { - c.reliability = Some((ReliabilityType::Reliable, 0)); - c.deadline = None; - } - 1 => c.payload_type = PayloadProtocolIdentifier::Dcep, - _ => {} - } - } - assert!( - !a.get_data_packets_to_retransmit(now + Duration::from_secs(2)) - .is_empty() - ); - assert!(!a.outbound_queue.is_abandoned(1)); - } -} - -#[test] -fn timed_expiry_uses_original_message_deadline_after_stream_changes() { - let now = Instant::now(); - let mut a = timed_fixture(false); - a.send_next_data_chunk(now).unwrap(); - a.stream(1) - .unwrap() - .set_reliability_params(false, ReliabilityType::Reliable, 0) - .unwrap(); - // A later fragment's transmission time cannot restart the lifetime. - a.send_next_data_chunk(now + Duration::from_millis(9)).unwrap(); - assert!( - a.pop_pending_data_chunks_to_send(now + Duration::from_millis(10)) - .is_empty() - ); - assert!(a.outbound_queue.is_abandoned(1)); - assert!(a.outbound_queue.is_abandoned(2)); - assert!(a.outbound_queue.is_abandoned(3)); -} - -#[test] -fn timed_shutdown_retries_lost_forward_tsn() { - let now = Instant::now(); - for state in [ - AssociationState::ShutdownPending, - AssociationState::ShutdownSent, - AssociationState::ShutdownReceived, - ] { - let mut a = timed_fixture(false); - a.gather_outbound(now); - a.state = state; - let later = now + Duration::from_secs(2); - let (packets, _) = a.gather_outbound(later); - let contains_forward = |packets: &[Bytes]| { - packets.iter().any(|raw| { - Packet::unmarshal(raw) - .unwrap() - .chunks - .iter() - .any(|c| c.as_any().is::()) - }) - }; - assert!(contains_forward(&packets)); - assert!(a.timers.get(Timer::T3RTX).is_some()); - // Lose the first FORWARD-TSN, then recover through caller-controlled T3. - a.on_retransmission_timeout(Timer::T3RTX, 1); - let (packets, _) = a.gather_outbound(later + Duration::from_secs(3)); - assert!(contains_forward(&packets)); - assert!(a.timers.get(Timer::T3RTX).is_some()); - for raw in packets { - assert!( - Packet::unmarshal(&raw) - .unwrap() - .chunks - .iter() - .all(|c| !c.as_any().is::()) - ); - } - } -} - -#[test] -fn timed_expiry_abandons_tail_after_entire_prefix_was_gap_acked() { - let now = Instant::now(); - let mut a = timed_fixture(false); - a.send_next_data_chunk(now).unwrap(); - let released = a.outbound_queue.mark_as_acked(1); - a.streams.get_mut(&1).unwrap().on_buffer_released(released as i64); - assert!( - a.pop_pending_data_chunks_to_send(now + Duration::from_millis(10)) - .is_empty() - ); - assert_eq!(a.outbound_queue.pending_len(), 0); - assert!(a.outbound_queue.is_abandoned(2)); - assert!(a.outbound_queue.get(1).unwrap().acked); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); - assert!(!a.gather_outbound_forward_tsn_packets(vec![]).is_empty()); -} - -#[test] -fn timed_expiry_retains_forward_recovery_after_prefix_cumulative_ack() { - let now = Instant::now(); - let mut a = timed_fixture(false); - a.send_next_data_chunk(now).unwrap(); - a.process_selective_ack( - &ChunkSelectiveAck { - cumulative_tsn_ack: 1, - ..Default::default() - }, - now, - ) - .unwrap(); - a.cumulative_tsn_ack_point = 1; - a.streams.get_mut(&1).unwrap().on_buffer_released(4); - assert_eq!(a.outbound_queue.inflight_len(), 0); - assert!(a.timers.get(Timer::T3RTX).is_none()); - assert!( - a.pop_pending_data_chunks_to_send(now + Duration::from_millis(10)) - .is_empty() - ); - assert_eq!(a.outbound_queue.pending_len(), 0); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); - assert!(a.outbound_queue.is_abandoned(2)); - assert!(!a.gather_outbound_forward_tsn_packets(vec![]).is_empty()); - assert!(a.timers.get(Timer::T3RTX).is_some()); -} - -#[test] -fn pending_timed_messages_keep_distinct_lifetimes_across_polls() { - let now = Instant::now(); - let mut a = timed_fixture(false); - a.create_stream(2, false, PayloadProtocolIdentifier::Binary).unwrap(); - let mut blocker = a.stream(2).unwrap(); - blocker - .set_reliability_params(true, ReliabilityType::Reliable, 0) - .unwrap(); - blocker.write(b"hold").unwrap(); - a.cwnd = 4; - let chunks = a.pop_pending_data_chunks_to_send(now); - assert_eq!(chunks.len(), 1); - assert_eq!(chunks[0].stream_identifier, 2); - - a.stream(1).unwrap().write(b"new").unwrap(); - assert!( - a.pop_pending_data_chunks_to_send(now + Duration::from_millis(5)) - .is_empty() - ); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 13); - assert!( - a.pop_pending_data_chunks_to_send(now + Duration::from_millis(10)) - .is_empty() - ); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 3); - assert_eq!(a.my_next_tsn, 2, "the unsent expired message needs no TSN"); - - a.cwnd = 100; - let chunks = a.pop_pending_data_chunks_to_send(now + Duration::from_millis(14)); - assert_eq!(chunks.len(), 1); - assert_eq!(chunks[0].user_data.as_ref(), b"new"); - assert_eq!(chunks[0].stream_sequence_number, 0); - assert_eq!(chunks[0].deadline, Some(now + Duration::from_millis(15))); - assert!( - a.get_data_packets_to_retransmit(now + Duration::from_millis(15)) - .is_empty() - ); - assert!(a.outbound_queue.is_abandoned(2)); - assert_eq!(a.stream(1).unwrap().buffered_amount().unwrap(), 0); -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/association/timer.rs b/rs/moq-webrtc/src/vendor/sctp_proto/association/timer.rs deleted file mode 100644 index 545673d4c4d..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/association/timer.rs +++ /dev/null @@ -1,244 +0,0 @@ -use core::time::Duration; -use std::time::Instant; - -use crate::vendor::sctp_proto::config::{RTO_INITIAL, RTO_MAX, RTO_MIN}; - -pub(crate) const ACK_INTERVAL: u64 = 200; -const TIMER_COUNT: usize = 6; - -#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq)] -pub(crate) enum Timer { - T1Init = 0, - T1Cookie = 1, - T2Shutdown = 2, - T3RTX = 3, - Reconfig = 4, - Ack = 5, -} - -impl Timer { - pub(crate) const VALUES: [Self; TIMER_COUNT] = [ - Timer::T1Init, - Timer::T1Cookie, - Timer::T2Shutdown, - Timer::T3RTX, - Timer::Reconfig, - Timer::Ack, - ]; -} - -/// A table of data associated with each distinct kind of `Timer` -#[derive(Debug, Copy, Clone)] -pub(crate) struct TimerTable { - data: [Option; TIMER_COUNT], - retrans: [usize; TIMER_COUNT], - /// Maximum retransmissions for each timer. `None` means unlimited. - max_retrans: [Option; TIMER_COUNT], - /// Timers whose next expiry must not increment the error counter - no_error_count: [bool; TIMER_COUNT], - /// Maximum RTO value for exponential backoff. - rto_max: u64, -} - -impl Default for TimerTable { - fn default() -> Self { - TimerTable { - data: [None; TIMER_COUNT], - retrans: [0; TIMER_COUNT], - max_retrans: [None; TIMER_COUNT], - no_error_count: [false; TIMER_COUNT], - rto_max: 60000, // Default RTO_MAX - } - } -} - -impl TimerTable { - pub fn new(max_init_retransmits: Option, max_data_retransmits: Option, rto_max: u64) -> Self { - TimerTable { - max_retrans: [ - max_init_retransmits, //T1Init - max_init_retransmits, //T1Cookie - None, //T2Shutdown (unlimited) - max_data_retransmits, //T3RTX - max_init_retransmits, //Reconfig - None, //Ack (unlimited) - ], - rto_max, - ..Default::default() - } - } - - pub fn set(&mut self, timer: Timer, time: Option) { - self.data[timer as usize] = time; - } - - pub fn get(&self, timer: Timer) -> Option { - self.data[timer as usize] - } - - pub fn next_timeout(&self) -> Option { - self.data.iter().filter_map(|&x| x).min() - } - - pub fn start(&mut self, timer: Timer, now: Instant, interval: u64) { - let interval = if timer == Timer::Ack { - interval - } else { - calculate_next_timeout(interval, self.retrans[timer as usize], self.rto_max) - }; - - let time = now + Duration::from_millis(interval); - self.data[timer as usize] = Some(time); - } - - /// Restarts the timer if the current instant is none or elapsed. - pub fn restart_if_stale(&mut self, timer: Timer, now: Instant, interval: u64) { - if let Some(current) = self.data[timer as usize] { - if current >= now { - return; - } - } - - self.start(timer, now, interval); - } - - pub fn stop(&mut self, timer: Timer) { - self.data[timer as usize] = None; - self.retrans[timer as usize] = 0; - self.no_error_count[timer as usize] = false; - } - - /// Clear peer error accounting without changing the recovery deadline. - pub fn reset_retrans(&mut self, timer: Timer) { - self.retrans[timer as usize] = 0; - } - - /// Exempt the timer's next expiry from the `max_retrans` accounting. - pub fn suppress_error_count(&mut self, timer: Timer) { - self.no_error_count[timer as usize] = true; - } - - pub fn is_expired(&mut self, timer: Timer, after: Instant) -> (bool, bool, usize) { - let expired = self.data[timer as usize].is_some_and(|x| x <= after); - let mut failure = false; - if expired { - if self.no_error_count[timer as usize] { - self.no_error_count[timer as usize] = false; - } else { - self.retrans[timer as usize] += 1; - if let Some(max) = self.max_retrans[timer as usize] { - if self.retrans[timer as usize] > max { - failure = true; - } - } - // If max_retrans is None, failure stays false (unlimited) - } - } - - (expired, failure, self.retrans[timer as usize]) - } -} - -const RTO_ALPHA: u64 = 1; -const RTO_BETA: u64 = 2; -const RTO_BASE: u64 = 8; - -/// rtoManager manages Rtx timeout values. -/// This is an implementation of RFC 4960 sec 6.3.1. -#[derive(Debug)] -pub(crate) struct RtoManager { - pub(crate) srtt: u64, - pub(crate) rttvar: f64, - pub(crate) rto: u64, - pub(crate) no_update: bool, - pub(crate) rto_initial: u64, - pub(crate) rto_min: u64, - pub(crate) rto_max: u64, -} - -impl Default for RtoManager { - fn default() -> Self { - RtoManager { - srtt: 0, - rttvar: 0.0, - rto: RTO_INITIAL, - no_update: false, - rto_initial: RTO_INITIAL, - rto_min: RTO_MIN, - rto_max: RTO_MAX, - } - } -} - -impl RtoManager { - /// Creates a new RtoManager with configurable RTO values. - pub(crate) fn new(rto_initial: u64, rto_min: u64, rto_max: u64) -> Self { - RtoManager { - srtt: 0, - rttvar: 0.0, - rto: rto_initial, - no_update: false, - rto_initial, - rto_min, - rto_max, - } - } - - /// set_new_rtt takes a newly measured RTT then adjust the RTO in msec. - pub(crate) fn set_new_rtt(&mut self, rtt: u64) -> u64 { - if self.no_update { - return self.srtt; - } - - if self.srtt == 0 { - // First measurement - self.srtt = rtt; - self.rttvar = rtt as f64 / 2.0; - } else { - // Subsequent rtt measurement - self.rttvar = ((RTO_BASE - RTO_BETA) as f64 * self.rttvar - + RTO_BETA as f64 * (self.srtt as i64 - rtt as i64).abs() as f64) - / RTO_BASE as f64; - self.srtt = ((RTO_BASE - RTO_ALPHA) * self.srtt + RTO_ALPHA * rtt) / RTO_BASE; - } - - self.rto = (self.srtt + (4.0 * self.rttvar) as u64).clamp(self.rto_min, self.rto_max); - - self.srtt - } - - /// get_rto simply returns the current RTO in msec. - pub(crate) fn get_rto(&self) -> u64 { - self.rto - } - - /// reset resets the RTO variables to the initial values. - pub(crate) fn reset(&mut self) { - if self.no_update { - return; - } - - self.srtt = 0; - self.rttvar = 0.0; - self.rto = self.rto_initial; - } - - /// set RTO value for testing - pub(crate) fn set_rto(&mut self, rto: u64, no_update: bool) { - self.rto = rto; - self.no_update = no_update; - } -} - -fn calculate_next_timeout(rto: u64, n_rtos: usize, rto_max: u64) -> u64 { - // RFC 4096 sec 6.3.3. Handle T3-rtx Expiration - // E2) For the destination address for which the timer expires, set RTO - // <- RTO * 2 ("back off the timer"). The maximum value discussed - // in rule C7 above (RTO.max) may be used to provide an upper bound - // to this doubling operation. - if n_rtos < 31 { - core::cmp::min(rto << n_rtos, rto_max) - } else { - rto_max - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_abort.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_abort.rs deleted file mode 100644 index 36eb7eab061..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_abort.rs +++ /dev/null @@ -1,89 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -use std::string::ToString; - -///Abort represents an SCTP Chunk of type ABORT -/// -///The ABORT chunk is sent to the peer of an association to close the -///association. The ABORT chunk may contain Cause Parameters to inform -///the receiver about the reason of the abort. DATA chunks MUST NOT be -///bundled with ABORT. Control chunks (except for INIT, INIT ACK, and -///SHUTDOWN COMPLETE) MAY be bundled with an ABORT, but they MUST be -///placed before the ABORT in the SCTP packet or they will be ignored by -///the receiver. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 6 |Reserved |T| Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| zero or more Error Causes | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkAbort { - pub(crate) error_causes: Vec, -} - -/// String makes chunkAbort printable -impl fmt::Display for ChunkAbort { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = vec![self.header().to_string()]; - - for cause in &self.error_causes { - res.push(format!(" - {}", cause)); - } - - write!(f, "{}", res.join("\n")) - } -} - -impl Chunk for ChunkAbort { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_ABORT, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_ABORT { - return Err(Error::ErrChunkTypeNotAbort); - } - - let value_end = CHUNK_HEADER_SIZE + header.value_length(); - let mut error_causes = vec![]; - let mut offset = CHUNK_HEADER_SIZE; - while offset + ERROR_CAUSE_HEADER_LENGTH <= value_end { - let e = ErrorCause::unmarshal(&raw.slice(offset..value_end))?; - offset += e.length(); - error_causes.push(e); - } - - Ok(ChunkAbort { error_causes }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - for ec in &self.error_causes { - buf.extend(ec.marshal()); - } - Ok(buf.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - self.error_causes.iter().fold(0, |length, ec| length + ec.length()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_ack.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_ack.rs deleted file mode 100644 index dafbd130633..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_ack.rs +++ /dev/null @@ -1,55 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -/// chunkCookieAck represents an SCTP Chunk of type chunkCookieAck -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | Type = 11 |Chunk Flags | Length = 4 | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Debug, Clone)] -pub(crate) struct ChunkCookieAck; - -/// makes ChunkCookieAck printable -impl fmt::Display for ChunkCookieAck { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Chunk for ChunkCookieAck { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_COOKIE_ACK, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_COOKIE_ACK { - return Err(Error::ErrChunkTypeNotCookieAck); - } - - Ok(ChunkCookieAck {}) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - Ok(buf.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - 0 - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_echo.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_echo.rs deleted file mode 100644 index 8525dec3756..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_cookie_echo.rs +++ /dev/null @@ -1,62 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -/// CookieEcho represents an SCTP Chunk of type CookieEcho -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | Type = 10 |Chunk Flags | Length | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | Cookie | -/// | | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkCookieEcho { - pub(crate) cookie: Bytes, -} - -/// makes ChunkCookieEcho printable -impl fmt::Display for ChunkCookieEcho { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Chunk for ChunkCookieEcho { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_COOKIE_ECHO, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_COOKIE_ECHO { - return Err(Error::ErrChunkTypeNotCookieEcho); - } - - let cookie = raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()); - Ok(ChunkCookieEcho { cookie }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - buf.extend(self.cookie.clone()); - Ok(buf.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - self.cookie.len() - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_error.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_error.rs deleted file mode 100644 index bf5b3a50945..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_error.rs +++ /dev/null @@ -1,91 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -use std::string::ToString; - -///Operation Error (ERROR) (9) -/// -///An endpoint sends this chunk to its peer endpoint to notify it of -///certain error conditions. It contains one or more error causes. An -///Operation Error is not considered fatal in and of itself, but may be -///used with an ERROR chunk to report a fatal condition. It has the -///following parameters: -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 9 | Chunk Flags | Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| one or more Error Causes | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///Chunk Flags: 8 bits -/// Set to 0 on transmit and ignored on receipt. -///Length: 16 bits (unsigned integer) -/// Set to the size of the chunk in bytes, including the chunk header -/// and all the Error Cause fields present. -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkError { - pub(crate) error_causes: Vec, -} - -/// makes ChunkError printable -impl fmt::Display for ChunkError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = vec![self.header().to_string()]; - - for cause in &self.error_causes { - res.push(format!(" - {}", cause)); - } - - write!(f, "{}", res.join("\n")) - } -} - -impl Chunk for ChunkError { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_ERROR, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_ERROR { - return Err(Error::ErrChunkTypeNotCt); - } - - let value_end = CHUNK_HEADER_SIZE + header.value_length(); - let mut error_causes = vec![]; - let mut offset = CHUNK_HEADER_SIZE; - while offset + ERROR_CAUSE_HEADER_LENGTH <= value_end { - let e = ErrorCause::unmarshal(&raw.slice(offset..value_end))?; - offset += e.length(); - error_causes.push(e); - } - - Ok(ChunkError { error_causes }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - for ec in &self.error_causes { - buf.extend(ec.marshal()); - } - Ok(buf.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - self.error_causes.iter().fold(0, |length, ec| length + ec.length()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_forward_tsn.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_forward_tsn.rs deleted file mode 100644 index a896a8824ee..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_forward_tsn.rs +++ /dev/null @@ -1,176 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -use std::string::ToString; - -///This chunk shall be used by the data sender to inform the data -///receiver to adjust its cumulative received TSN point forward because -///some missing TSNs are associated with data chunks that SHOULD NOT be -///transmitted or retransmitted by the sender. -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 192 | Flags = 0x00 | Length = Variable | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| New Cumulative TSN | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Stream-1 | Stream Sequence-1 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Stream-N | Stream Sequence-N | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkForwardTsn { - /// This indicates the new cumulative TSN to the data receiver. Upon - /// the reception of this value, the data receiver MUST consider - /// any missing TSNs earlier than or equal to this value as received, - /// and stop reporting them as gaps in any subsequent SACKs. - pub(crate) new_cumulative_tsn: u32, - pub(crate) streams: Vec, -} - -pub(crate) const NEW_CUMULATIVE_TSN_LENGTH: usize = 4; -pub(crate) const FORWARD_TSN_STREAM_LENGTH: usize = 4; - -/// makes ChunkForwardTsn printable -impl fmt::Display for ChunkForwardTsn { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = vec![self.header().to_string()]; - res.push(format!("New Cumulative TSN: {}", self.new_cumulative_tsn)); - for s in &self.streams { - res.push(format!(" - si={}, ssn={}", s.identifier, s.sequence)); - } - - write!(f, "{}", res.join("\n")) - } -} - -impl Chunk for ChunkForwardTsn { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_FORWARD_TSN, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(buf: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(buf)?; - - if header.typ != CT_FORWARD_TSN { - return Err(Error::ErrChunkTypeNotForwardTsn); - } - - if header.value_length() < NEW_CUMULATIVE_TSN_LENGTH { - return Err(Error::ErrChunkTooShort); - } - - let mut offset = CHUNK_HEADER_SIZE + NEW_CUMULATIVE_TSN_LENGTH; - let reader = &mut buf.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()); - let new_cumulative_tsn = reader.get_u32(); - - let mut streams = vec![]; - let value_end = CHUNK_HEADER_SIZE + header.value_length(); - let mut remaining = value_end - offset; - while remaining > 0 { - let s = ChunkForwardTsnStream::unmarshal(&buf.slice(offset..value_end))?; - offset += s.value_length(); - remaining -= s.value_length(); - streams.push(s); - } - - Ok(ChunkForwardTsn { - new_cumulative_tsn, - streams, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - - writer.put_u32(self.new_cumulative_tsn); - - for s in &self.streams { - writer.extend(s.marshal()?); - } - - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - NEW_CUMULATIVE_TSN_LENGTH + FORWARD_TSN_STREAM_LENGTH * self.streams.len() - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ChunkForwardTsnStream { - /// This field holds a stream number that was skipped by this - /// FWD-TSN. - pub(crate) identifier: u16, - - /// This field holds the sequence number associated with the stream - /// that was skipped. The stream sequence field holds the largest - /// stream sequence number in this stream being skipped. The receiver - /// of the FWD-TSN's can use the Stream-N and Stream Sequence-N fields - /// to enable delivery of any stranded TSN's that remain on the stream - /// re-ordering queues. This field MUST NOT report TSN's corresponding - /// to DATA chunks that are marked as unordered. For ordered DATA - /// chunks this field MUST be filled in. - pub(crate) sequence: u16, -} - -/// makes ChunkForwardTsnStream printable -impl fmt::Display for ChunkForwardTsnStream { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}, {}", self.identifier, self.sequence) - } -} - -impl Chunk for ChunkForwardTsnStream { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: ChunkType(0), - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(buf: &Bytes) -> Result { - if buf.len() < FORWARD_TSN_STREAM_LENGTH { - return Err(Error::ErrChunkTooShort); - } - - let reader = &mut buf.clone(); - let identifier = reader.get_u16(); - let sequence = reader.get_u16(); - - Ok(ChunkForwardTsnStream { identifier, sequence }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - writer.put_u16(self.identifier); - writer.put_u16(self.sequence); - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - FORWARD_TSN_STREAM_LENGTH - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_header.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_header.rs deleted file mode 100644 index af9b69e9b9b..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_header.rs +++ /dev/null @@ -1,102 +0,0 @@ -use super::{chunk_type::*, *}; - -///chunkHeader represents a SCTP Chunk header, defined in https://tools.ietf.org/html/rfc4960#section-3.2 -///The figure below illustrates the field format for the chunks to be -///transmitted in the SCTP packet. Each chunk is formatted with a Chunk -///Type field, a chunk-specific Flag field, a Chunk Length field, and a -///Value field. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Chunk Type | Chunk Flags | Chunk Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| Chunk Value | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkHeader { - pub(crate) typ: ChunkType, - pub(crate) flags: u8, - pub(crate) value_length: u16, -} - -pub(crate) const CHUNK_HEADER_SIZE: usize = 4; - -/// makes ChunkHeader printable -impl fmt::Display for ChunkHeader { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.typ) - } -} - -impl Chunk for ChunkHeader { - fn header(&self) -> ChunkHeader { - self.clone() - } - - fn unmarshal(raw: &Bytes) -> Result { - if raw.len() < CHUNK_HEADER_SIZE { - return Err(Error::ErrChunkHeaderTooSmall); - } - - let reader = &mut raw.clone(); - - let typ = ChunkType(reader.get_u8()); - let flags = reader.get_u8(); - let length = reader.get_u16(); - - if length < CHUNK_HEADER_SIZE as u16 { - return Err(Error::ErrChunkHeaderInvalidLength); - } - - // Length includes Chunk header - let value_length = length as isize - CHUNK_HEADER_SIZE as isize; - let length_after_value = raw.len() as isize - length as isize; - if length_after_value < 0 { - return Err(Error::ErrChunkHeaderNotEnoughSpace); - } else if length_after_value < 4 { - // https://tools.ietf.org/html/rfc4960#section-3.2 - // The Chunk Length field does not count any chunk PADDING. - // Chunks (including Type, Length, and Value fields) are padded out - // by the sender with all zero bytes to be a multiple of 4 bytes - // long. This PADDING MUST NOT be more than 3 bytes in total. The - // Chunk Length value does not include terminating PADDING of the - // chunk. However, it does include PADDING of any variable-length - // parameter except the last parameter in the chunk. The receiver - // MUST ignore the PADDING. - for i in (1..=length_after_value).rev() { - let padding_offset = CHUNK_HEADER_SIZE + (value_length + i - 1) as usize; - if raw[padding_offset] != 0 { - return Err(Error::ErrChunkHeaderPaddingNonZero); - } - } - } - - Ok(ChunkHeader { - typ, - flags, - value_length: length - CHUNK_HEADER_SIZE as u16, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - writer.put_u8(self.typ.0); - writer.put_u8(self.flags); - writer.put_u16(self.value_length + CHUNK_HEADER_SIZE as u16); - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - self.value_length as usize - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat.rs deleted file mode 100644 index f7f65ab6f5c..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat.rs +++ /dev/null @@ -1,92 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; -use crate::vendor::sctp_proto::param::{param_header::*, param_type::*, *}; - -///chunkHeartbeat represents an SCTP Chunk of type HEARTBEAT -/// -///An endpoint should send this chunk to its peer endpoint to probe the -///reachability of a particular destination transport address defined in -///the present association. -/// -///The parameter field contains the Heartbeat Information, which is a -///variable-length opaque data structure understood only by the sender. -/// -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 4 | Chunk Flags | Heartbeat Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| Heartbeat Information TLV (Variable-Length) | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// -///Defined as a variable-length parameter using the format described -///in Section 3.2.1, i.e.: -/// -///Variable Parameters Status Type Value -///------------------------------------------------------------- -///heartbeat Info Mandatory 1 -#[derive(Default, Debug)] -pub(crate) struct ChunkHeartbeat { - pub(crate) params: Vec>, -} - -/// makes ChunkHeartbeat printable -impl fmt::Display for ChunkHeartbeat { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Chunk for ChunkHeartbeat { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_HEARTBEAT, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_HEARTBEAT { - return Err(Error::ErrChunkTypeNotHeartbeat); - } - - if header.value_length() < PARAM_HEADER_LENGTH { - return Err(Error::ErrHeartbeatNotLongEnoughInfo); - } - - let p = build_param(&raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()))?; - if p.header().typ != ParamType::HeartbeatInfo { - return Err(Error::ErrHeartbeatParam); - } - let params = vec![p]; - - Ok(ChunkHeartbeat { params }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - for p in &self.params { - buf.extend(p.marshal()?); - } - Ok(buf.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - self.params - .iter() - .fold(0, |length, p| length + PARAM_HEADER_LENGTH + p.value_length()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat_ack.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat_ack.rs deleted file mode 100644 index c927b776a7f..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_heartbeat_ack.rs +++ /dev/null @@ -1,121 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; -use crate::vendor::sctp_proto::param::param_type::ParamType; -use crate::vendor::sctp_proto::param::{param_header::*, *}; -use crate::vendor::sctp_proto::util::get_padding_size; - -///chunkHeartbeatAck represents an SCTP Chunk of type HEARTBEAT ACK -/// -///An endpoint should send this chunk to its peer endpoint as a response -///to a HEARTBEAT chunk (see Section 8.3). A HEARTBEAT ACK is always -///sent to the source IP address of the IP datagram containing the -///HEARTBEAT chunk to which this ack is responding. -/// -///The parameter field contains a variable-length opaque data structure. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 5 | Chunk Flags | Heartbeat Ack Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| Heartbeat Information TLV (Variable-Length) | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// -/// -///Defined as a variable-length parameter using the format described -///in Section 3.2.1, i.e.: -/// -///Variable Parameters Status Type Value -///------------------------------------------------------------- -///Heartbeat Info Mandatory 1 -#[derive(Default, Debug)] -pub(crate) struct ChunkHeartbeatAck { - pub(crate) params: Vec>, -} - -/// makes ChunkHeartbeatAck printable -impl fmt::Display for ChunkHeartbeatAck { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Chunk for ChunkHeartbeatAck { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_HEARTBEAT_ACK, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_HEARTBEAT_ACK { - return Err(Error::ErrChunkTypeNotHeartbeatAck); - } - - if header.value_length() < PARAM_HEADER_LENGTH { - return Err(Error::ErrHeartbeatNotLongEnoughInfo); - } - - let p = build_param(&raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()))?; - if p.header().typ != ParamType::HeartbeatInfo { - return Err(Error::ErrHeartbeatParam); - } - let params = vec![p]; - - Ok(ChunkHeartbeatAck { params }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - if self.params.len() != 1 { - return Err(Error::ErrHeartbeatAckParams); - } - if self.params[0].header().typ != ParamType::HeartbeatInfo { - return Err(Error::ErrHeartbeatAckNotHeartbeatInfo); - } - - self.header().marshal_to(buf)?; - for (idx, p) in self.params.iter().enumerate() { - let pp = p.marshal()?; - let pp_len = pp.len(); - buf.extend(pp); - - // Chunks (including Type, Length, and Value fields) are padded out - // by the sender with all zero bytes to be a multiple of 4 bytes - // long. This PADDING MUST NOT be more than 3 bytes in total. The - // Chunk Length value does not include terminating PADDING of the - // chunk. *However, it does include PADDING of any variable-length - // parameter except the last parameter in the chunk.* The receiver - // MUST ignore the PADDING. - if idx != self.params.len() - 1 { - let cnt = get_padding_size(pp_len); - buf.extend(vec![0u8; cnt]); - } - } - Ok(buf.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - let mut l = 0; - for (idx, p) in self.params.iter().enumerate() { - let p_len = PARAM_HEADER_LENGTH + p.value_length(); - l += p_len; - if idx != self.params.len() - 1 { - l += get_padding_size(p_len); - } - } - l - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_i_forward_tsn.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_i_forward_tsn.rs deleted file mode 100644 index 1d282e3d728..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_i_forward_tsn.rs +++ /dev/null @@ -1,121 +0,0 @@ -use super::{chunk_forward_tsn::NEW_CUMULATIVE_TSN_LENGTH, chunk_header::*, chunk_type::*, *}; -use std::string::ToString; - -/// I-FORWARD-TSN chunk (RFC 8260). -/// -/// Identical purpose to FORWARD-TSN (RFC 3758) but carries per-stream -/// entries with a 32-bit Message Identifier (MID) instead of a 16-bit SSN, -/// and an explicit unordered flag per entry. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 194 | Flags = 0x00 | Length = Variable | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| New Cumulative TSN | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Stream Identifier | Flags | Reserved | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Message Identifier (MID) | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// ... -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkIForwardTsn { - pub(crate) new_cumulative_tsn: u32, - pub(crate) streams: Vec, -} - -const I_FORWARD_TSN_STREAM_ENTRY_LENGTH: usize = 8; - -impl fmt::Display for ChunkIForwardTsn { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = vec![self.header().to_string()]; - res.push(format!("New Cumulative TSN: {}", self.new_cumulative_tsn)); - for s in &self.streams { - res.push(format!( - " - si={}, unordered={}, mid={}", - s.identifier, s.unordered, s.mid - )); - } - write!(f, "{}", res.join("\n")) - } -} - -impl Chunk for ChunkIForwardTsn { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_I_FORWARD_TSN, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(buf: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(buf)?; - - if header.typ != CT_I_FORWARD_TSN { - return Err(Error::ErrChunkTypeNotForwardTsn); - } - - let value_end = CHUNK_HEADER_SIZE + header.value_length(); - if header.value_length() < NEW_CUMULATIVE_TSN_LENGTH { - return Err(Error::ErrChunkTooShort); - } - - let reader = &mut buf.slice(CHUNK_HEADER_SIZE..value_end); - let new_cumulative_tsn = reader.get_u32(); - - let mut streams = vec![]; - let mut offset = CHUNK_HEADER_SIZE + NEW_CUMULATIVE_TSN_LENGTH; - while offset + I_FORWARD_TSN_STREAM_ENTRY_LENGTH <= value_end { - let entry_buf = &mut buf.slice(offset..value_end); - let identifier = entry_buf.get_u16(); - let flags = entry_buf.get_u8(); - let _reserved = entry_buf.get_u8(); - let mid = entry_buf.get_u32(); - - streams.push(ChunkIForwardTsnStream { - identifier, - unordered: (flags & 0x01) != 0, - mid, - }); - offset += I_FORWARD_TSN_STREAM_ENTRY_LENGTH; - } - - Ok(ChunkIForwardTsn { - new_cumulative_tsn, - streams, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - writer.put_u32(self.new_cumulative_tsn); - for s in &self.streams { - writer.put_u16(s.identifier); - writer.put_u8(if s.unordered { 0x01 } else { 0x00 }); - writer.put_u8(0); // reserved - writer.put_u32(s.mid); - } - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - 4 + I_FORWARD_TSN_STREAM_ENTRY_LENGTH * self.streams.len() - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} - -#[derive(Debug, Clone)] -pub(crate) struct ChunkIForwardTsnStream { - pub(crate) identifier: u16, - pub(crate) unordered: bool, - pub(crate) mid: u32, -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_init.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_init.rs deleted file mode 100644 index 24269fde7f9..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_init.rs +++ /dev/null @@ -1,285 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; -use crate::vendor::sctp_proto::param::param_supported_extensions::ParamSupportedExtensions; -use crate::vendor::sctp_proto::param::{param_header::*, *}; -use crate::vendor::sctp_proto::util::get_padding_size; - -///chunkInitCommon represents an SCTP Chunk body of type INIT and INIT ACK -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 1 | Chunk Flags | Chunk Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Initiate Tag | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Advertised Receiver Window Credit (a_rwnd) | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Number of Outbound Streams | Number of Inbound Streams | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Initial TSN | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| Optional/Variable-Length Parameters | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// -///The INIT chunk contains the following parameters. Unless otherwise -///noted, each parameter MUST only be included once in the INIT chunk. -/// -///Fixed Parameters Status -///---------------------------------------------- -///Initiate Tag Mandatory -///Advertised Receiver Window Credit Mandatory -///Number of Outbound Streams Mandatory -///Number of Inbound Streams Mandatory -///Initial TSN Mandatory -/// -///Init represents an SCTP Chunk of type INIT -/// -///See chunkInitCommon for the fixed headers -/// -///Variable Parameters Status Type Value -///------------------------------------------------------------- -///IPv4 IP (Note 1) Optional 5 -///IPv6 IP (Note 1) Optional 6 -///Cookie Preservative Optional 9 -///Reserved for ECN Capable (Note 2) Optional 32768 (0x8000) -///Host Name IP (Note 3) Optional 11 -///Supported IP Types (Note 4) Optional 12 -/// -/// -/// chunkInitAck represents an SCTP Chunk of type INIT ACK -/// -///See chunkInitCommon for the fixed headers -/// -///Variable Parameters Status Type Value -///------------------------------------------------------------- -///State Cookie Mandatory 7 -///IPv4 IP (Note 1) Optional 5 -///IPv6 IP (Note 1) Optional 6 -///Unrecognized Parameter Optional 8 -///Reserved for ECN Capable (Note 2) Optional 32768 (0x8000) -///Host Name IP (Note 3) Optional 11 -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkInit { - pub(crate) is_ack: bool, - pub(crate) initiate_tag: u32, - pub(crate) advertised_receiver_window_credit: u32, - pub(crate) num_outbound_streams: u16, - pub(crate) num_inbound_streams: u16, - pub(crate) initial_tsn: u32, - pub(crate) params: Vec>, -} - -pub(crate) type ChunkInitAck = ChunkInit; - -pub(crate) const INIT_CHUNK_MIN_LENGTH: usize = 16; -pub(crate) const INIT_OPTIONAL_VAR_HEADER_LENGTH: usize = 4; - -/// makes chunkInitCommon printable -impl fmt::Display for ChunkInit { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = format!( - "is_ack: {} - initiate_tag: {} - advertised_receiver_window_credit: {} - num_outbound_streams: {} - num_inbound_streams: {} - initial_tsn: {}", - self.is_ack, - self.initiate_tag, - self.advertised_receiver_window_credit, - self.num_outbound_streams, - self.num_inbound_streams, - self.initial_tsn, - ); - - for (i, param) in self.params.iter().enumerate() { - res += format!("Param {}:\n {}", i, param).as_str(); - } - write!(f, "{} {}", self.header(), res) - } -} - -impl Chunk for ChunkInit { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: if self.is_ack { CT_INIT_ACK } else { CT_INIT }, - flags: 0, - value_length: self.value_length() as u16, - } - } - - ///https://tools.ietf.org/html/rfc4960#section-3.2.1 - /// - ///Chunk values of SCTP control chunks consist of a chunk-type-specific - ///header of required fields, followed by zero or more parameters. The - ///optional and variable-length parameters contained in a chunk are - ///defined in a Type-Length-Value format as shown below. - /// - ///0 1 2 3 - ///0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - ///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - ///| Parameter Type | Parameter Length | - ///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - ///| | - ///| Parameter Value | - ///| | - ///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if !(header.typ == CT_INIT || header.typ == CT_INIT_ACK) { - return Err(Error::ErrChunkTypeNotTypeInit); - } else if header.value_length() < INIT_CHUNK_MIN_LENGTH { - return Err(Error::ErrChunkValueNotLongEnough); - } - - // The Chunk Flags field in INIT is reserved, and all bits in it should - // be set to 0 by the sender and ignored by the receiver. The sequence - // of parameters within an INIT can be processed in any order. - if header.flags != 0 { - return Err(Error::ErrChunkTypeInitFlagZero); - } - - let reader = &mut raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()); - - let initiate_tag = reader.get_u32(); - let advertised_receiver_window_credit = reader.get_u32(); - let num_outbound_streams = reader.get_u16(); - let num_inbound_streams = reader.get_u16(); - let initial_tsn = reader.get_u32(); - - let mut params = vec![]; - let mut offset = CHUNK_HEADER_SIZE + INIT_CHUNK_MIN_LENGTH; - let value_end = CHUNK_HEADER_SIZE + header.value_length(); - let mut remaining = value_end as isize - offset as isize; - while remaining >= INIT_OPTIONAL_VAR_HEADER_LENGTH as isize { - let p = build_param(&raw.slice(offset..CHUNK_HEADER_SIZE + header.value_length()))?; - let p_len = PARAM_HEADER_LENGTH + p.value_length(); - let len_plus_padding = p_len + get_padding_size(p_len); - params.push(p); - offset += len_plus_padding; - remaining -= len_plus_padding as isize; - } - - Ok(ChunkInit { - is_ack: header.typ == CT_INIT_ACK, - initiate_tag, - advertised_receiver_window_credit, - num_outbound_streams, - num_inbound_streams, - initial_tsn, - params, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - - writer.put_u32(self.initiate_tag); - writer.put_u32(self.advertised_receiver_window_credit); - writer.put_u16(self.num_outbound_streams); - writer.put_u16(self.num_inbound_streams); - writer.put_u32(self.initial_tsn); - for (idx, p) in self.params.iter().enumerate() { - let pp = p.marshal()?; - let pp_len = pp.len(); - writer.extend(pp); - - // Chunks (including Type, Length, and Value fields) are padded out - // by the sender with all zero bytes to be a multiple of 4 bytes - // long. This padding MUST NOT be more than 3 bytes in total. The - // Chunk Length value does not include terminating padding of the - // chunk. *However, it does include padding of any variable-length - // parameter except the last parameter in the chunk.* The receiver - // MUST ignore the padding. - if idx != self.params.len() - 1 { - let cnt = get_padding_size(pp_len); - writer.extend(vec![0u8; cnt]); - } - } - - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - // The receiver of the INIT (the responding end) records the value of - // the Initiate Tag parameter. This value MUST be placed into the - // Verification Tag field of every SCTP packet that the receiver of - // the INIT transmits within this association. - // - // The Initiate Tag is allowed to have any value except 0. See - // Section 5.3.1 for more on the selection of the tag value. - // - // If the value of the Initiate Tag in a received INIT chunk is found - // to be 0, the receiver MUST treat it as an error and close the - // association by transmitting an ABORT. - if self.initiate_tag == 0 { - return Err(Error::ErrChunkTypeInitInitiateTagZero); - } - - // Defines the maximum number of streams the sender of this INIT - // chunk allows the peer end to create in this association. The - // value 0 MUST NOT be used. - // - // Note: There is no negotiation of the actual number of streams but - // instead the two endpoints will use the min(requested, offered). - // See Section 5.1.1 for details. - // - // Note: A receiver of an INIT with the MIS value of 0 SHOULD abort - // the association. - if self.num_inbound_streams == 0 { - return Err(Error::ErrInitInboundStreamRequestZero); - } - - // Defines the number of outbound streams the sender of this INIT - // chunk wishes to create in this association. The value of 0 MUST - // NOT be used. - // - // Note: A receiver of an INIT with the OS value set to 0 SHOULD - // abort the association. - - if self.num_outbound_streams == 0 { - return Err(Error::ErrInitOutboundStreamRequestZero); - } - - // An SCTP receiver MUST be able to receive a minimum of 1500 bytes in - // one SCTP packet. This means that an SCTP endpoint MUST NOT indicate - // less than 1500 bytes in its initial a_rwnd sent in the INIT or INIT - // ACK. - if self.advertised_receiver_window_credit < 1500 { - return Err(Error::ErrInitAdvertisedReceiver1500); - } - - Ok(()) - } - - fn value_length(&self) -> usize { - let mut l = 4 + 4 + 2 + 2 + 4; - for (idx, p) in self.params.iter().enumerate() { - let p_len = PARAM_HEADER_LENGTH + p.value_length(); - l += p_len; - if idx != self.params.len() - 1 { - l += get_padding_size(p_len); - } - } - l - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} - -impl ChunkInit { - pub(crate) fn set_supported_extensions(&mut self) { - // RFC5061 https://tools.ietf.org/html/rfc6525#section-5.2 - // An implementation supporting this (Supported Extensions Parameter) - // extension MUST list the ASCONF, the ASCONF-ACK, and the AUTH chunks - // in its INIT and INIT-ACK parameters. - self.params.push(Box::new(ParamSupportedExtensions { - chunk_types: vec![CT_RECONFIG, CT_FORWARD_TSN], - })); - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_payload_data.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_payload_data.rs deleted file mode 100644 index 92e851f001e..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_payload_data.rs +++ /dev/null @@ -1,248 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -use std::time::Instant; - -pub(crate) const PAYLOAD_DATA_ENDING_FRAGMENT_BITMASK: u8 = 1; -pub(crate) const PAYLOAD_DATA_BEGINING_FRAGMENT_BITMASK: u8 = 2; -pub(crate) const PAYLOAD_DATA_UNORDERED_BITMASK: u8 = 4; -pub(crate) const PAYLOAD_DATA_IMMEDIATE_SACK: u8 = 8; -pub(crate) const PAYLOAD_DATA_HEADER_SIZE: usize = 12; - -/// PayloadProtocolIdentifier is an enum for DataChannel payload types -// PayloadProtocolIdentifier enums -// -#[derive(Debug, Copy, Clone, PartialEq)] -#[repr(C)] -#[derive(Default)] -pub enum PayloadProtocolIdentifier { - Dcep = 50, - String = 51, - Binary = 53, - StringEmpty = 56, - BinaryEmpty = 57, - #[default] - Unknown, -} - -impl fmt::Display for PayloadProtocolIdentifier { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - PayloadProtocolIdentifier::Dcep => "WebRTC DCEP", - PayloadProtocolIdentifier::String => "WebRTC String", - PayloadProtocolIdentifier::Binary => "WebRTC Binary", - PayloadProtocolIdentifier::StringEmpty => "WebRTC String (Empty)", - PayloadProtocolIdentifier::BinaryEmpty => "WebRTC Binary (Empty)", - _ => "Unknown Payload Protocol Identifier", - }; - write!(f, "{}", s) - } -} - -impl From for PayloadProtocolIdentifier { - fn from(v: u32) -> PayloadProtocolIdentifier { - match v { - 50 => PayloadProtocolIdentifier::Dcep, - 51 => PayloadProtocolIdentifier::String, - 53 => PayloadProtocolIdentifier::Binary, - 56 => PayloadProtocolIdentifier::StringEmpty, - 57 => PayloadProtocolIdentifier::BinaryEmpty, - _ => PayloadProtocolIdentifier::Unknown, - } - } -} - -/// ChunkPayloadData represents an SCTP Chunk of type DATA -// -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -//| Type = 0 | Reserved|U|B|E| Length | -//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -//| TSN | -//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -//| Stream Identifier S | Stream Sequence Number n | -//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -//| Payload Protocol Identifier | -//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -//| | -//| User Data (seq n of Stream S) | -//| | -//+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// -// -//An unfragmented user message shall have both the B and E bits set to -//'1'. Setting both B and E bits to '0' indicates a middle fragment of -//a multi-fragment user message, as summarized in the following table: -// B E Description -//============================================================ -//| 1 0 | First piece of a fragmented user message | -//+----------------------------------------------------------+ -//| 0 0 | Middle piece of a fragmented user message | -//+----------------------------------------------------------+ -//| 0 1 | Last piece of a fragmented user message | -//+----------------------------------------------------------+ -//| 1 1 | Unfragmented message | -//============================================================ -//| Table 1: Fragment Description Flags | -//============================================================ -#[derive(Debug, Clone)] -pub struct ChunkPayloadData { - pub(crate) unordered: bool, - pub(crate) beginning_fragment: bool, - pub(crate) ending_fragment: bool, - pub(crate) immediate_sack: bool, - - pub(crate) tsn: u32, - pub(crate) stream_identifier: u16, - pub(crate) stream_sequence_number: u16, - pub(crate) payload_type: PayloadProtocolIdentifier, - pub(crate) user_data: Bytes, - - /// Whether this data chunk was acknowledged (received by peer) - pub(crate) acked: bool, - /// Missing reports saturate at the fast-retransmit threshold of three. - pub(crate) miss_indicator: u8, - - /// Sender-only identity shared by value across a message's fragments. - pub(crate) message_id: u64, - pub(crate) abandoned: bool, - - /// Partial-reliability parameters used only by sender - pub(crate) since: Option, - pub(crate) reliability: Option<(crate::vendor::sctp_proto::ReliabilityType, u32)>, - pub(crate) deadline: Option, - /// number of transmission made for this chunk - pub(crate) nsent: u32, - - /// Retransmission flag set when T1-RTX timeout occurred and this - /// chunk is still in the inflight queue - pub(crate) retransmit: bool, -} - -impl Default for ChunkPayloadData { - fn default() -> Self { - ChunkPayloadData { - unordered: false, - beginning_fragment: false, - ending_fragment: false, - immediate_sack: false, - tsn: 0, - stream_identifier: 0, - stream_sequence_number: 0, - payload_type: PayloadProtocolIdentifier::default(), - user_data: Bytes::new(), - acked: false, - miss_indicator: 0, - message_id: 0, - abandoned: false, - since: None, - reliability: None, - deadline: None, - nsent: 0, - retransmit: false, - } - } -} - -/// makes chunkPayloadData printable -impl fmt::Display for ChunkPayloadData { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}\n{}", self.header(), self.tsn) - } -} - -impl Chunk for ChunkPayloadData { - fn header(&self) -> ChunkHeader { - let mut flags: u8 = 0; - if self.ending_fragment { - flags = 1; - } - if self.beginning_fragment { - flags |= 1 << 1; - } - if self.unordered { - flags |= 1 << 2; - } - if self.immediate_sack { - flags |= 1 << 3; - } - - ChunkHeader { - typ: CT_PAYLOAD_DATA, - flags, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_PAYLOAD_DATA { - return Err(Error::ErrChunkTypeNotPayloadData); - } - - let immediate_sack = (header.flags & PAYLOAD_DATA_IMMEDIATE_SACK) != 0; - let unordered = (header.flags & PAYLOAD_DATA_UNORDERED_BITMASK) != 0; - let beginning_fragment = (header.flags & PAYLOAD_DATA_BEGINING_FRAGMENT_BITMASK) != 0; - let ending_fragment = (header.flags & PAYLOAD_DATA_ENDING_FRAGMENT_BITMASK) != 0; - - if header.value_length() < PAYLOAD_DATA_HEADER_SIZE { - return Err(Error::ErrChunkPayloadSmall); - } - - let reader = &mut raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()); - - let tsn = reader.get_u32(); - let stream_identifier = reader.get_u16(); - let stream_sequence_number = reader.get_u16(); - let payload_type: PayloadProtocolIdentifier = reader.get_u32().into(); - let user_data = - raw.slice(CHUNK_HEADER_SIZE + PAYLOAD_DATA_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()); - - Ok(ChunkPayloadData { - unordered, - beginning_fragment, - ending_fragment, - immediate_sack, - tsn, - stream_identifier, - stream_sequence_number, - payload_type, - user_data, - - acked: false, - miss_indicator: 0, - message_id: 0, - abandoned: false, - since: None, - reliability: None, - deadline: None, - nsent: 0, - retransmit: false, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - - writer.put_u32(self.tsn); - writer.put_u16(self.stream_identifier); - writer.put_u16(self.stream_sequence_number); - writer.put_u32(self.payload_type as u32); - writer.extend_from_slice(&self.user_data); - - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - PAYLOAD_DATA_HEADER_SIZE + self.user_data.len() - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_reconfig.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_reconfig.rs deleted file mode 100644 index c0bd121a683..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_reconfig.rs +++ /dev/null @@ -1,146 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; -use crate::vendor::sctp_proto::param::param_type::ParamType; -use crate::vendor::sctp_proto::param::{param_header::*, *}; -use crate::vendor::sctp_proto::util::get_padding_size; - -///https://tools.ietf.org/html/rfc6525#section-3.1 -///chunkReconfig represents an SCTP Chunk used to reconfigure streams. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 130 | Chunk Flags | Chunk Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| Re-configuration Parameter | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| Re-configuration Parameter (optional) | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug)] -pub(crate) struct ChunkReconfig { - pub(crate) param_a: Option>, - pub(crate) param_b: Option>, -} - -impl Clone for ChunkReconfig { - fn clone(&self) -> Self { - ChunkReconfig { - param_a: self.param_a.as_ref().cloned(), - param_b: self.param_b.as_ref().cloned(), - } - } -} - -/// makes chunkReconfig printable -impl fmt::Display for ChunkReconfig { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = String::new(); - if let Some(param_a) = &self.param_a { - res += format!("Param A:\n {}", param_a).as_str(); - } - if let Some(param_b) = &self.param_b { - res += format!("Param B:\n {}", param_b).as_str() - } - write!(f, "{}", res) - } -} - -impl Chunk for ChunkReconfig { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_RECONFIG, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_RECONFIG { - return Err(Error::ErrChunkTypeNotReconfig); - } - - if header.value_length() < PARAM_HEADER_LENGTH { - return Err(Error::ErrChunkTooShort); - } - - let param_a = build_param(&raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()))?; - - let padding = get_padding_size(PARAM_HEADER_LENGTH + param_a.value_length()); - let offset = CHUNK_HEADER_SIZE + PARAM_HEADER_LENGTH + param_a.value_length() + padding; - let param_b = if CHUNK_HEADER_SIZE + header.value_length() > offset { - Some(build_param( - &raw.slice(offset..CHUNK_HEADER_SIZE + header.value_length()), - )?) - } else { - None - }; - - Ok(ChunkReconfig { - param_a: Some(param_a), - param_b, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - - let param_a_value_length = if let Some(param_a) = &self.param_a { - writer.extend(param_a.marshal()?); - param_a.value_length() - } else { - return Err(Error::ErrChunkReconfigInvalidParamA); - }; - - if let Some(param_b) = &self.param_b { - // Pad param A - let padding = get_padding_size(PARAM_HEADER_LENGTH + param_a_value_length); - writer.extend(vec![0u8; padding]); - writer.extend(param_b.marshal()?); - } - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - let param_a = self.param_a.as_ref().ok_or(Error::ErrChunkReconfigInvalidParamA)?; - let Some(param_b) = &self.param_b else { - return Ok(()); - }; - - let combination = (param_a.header().typ, param_b.header().typ); - if matches!( - combination, - (ParamType::OutSsnResetReq, ParamType::IncSsnResetReq) - | (ParamType::AddOutStreamsReq, ParamType::AddIncStreamsReq) - | (ParamType::ReconfigResp, ParamType::OutSsnResetReq) - | (ParamType::ReconfigResp, ParamType::ReconfigResp) - ) { - Ok(()) - } else { - Err(Error::ErrChunkReconfigInvalidParamCombination) - } - } - - fn value_length(&self) -> usize { - let mut l = PARAM_HEADER_LENGTH; - let param_a_value_length = if let Some(param_a) = &self.param_a { - l += param_a.value_length(); - param_a.value_length() - } else { - 0 - }; - if let Some(param_b) = &self.param_b { - let padding = get_padding_size(PARAM_HEADER_LENGTH + param_a_value_length); - l += PARAM_HEADER_LENGTH + param_b.value_length() + padding; - } - l - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_selective_ack.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_selective_ack.rs deleted file mode 100644 index 9c8297abf22..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_selective_ack.rs +++ /dev/null @@ -1,156 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -///chunkSelectiveAck represents an SCTP Chunk of type SACK -/// -///This chunk is sent to the peer endpoint to acknowledge received DATA -///chunks and to inform the peer endpoint of gaps in the received -///subsequences of DATA chunks as represented by their TSNs. -///0 1 2 3 -///0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 3 |Chunk Flags | Chunk Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Cumulative TSN Ack | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Advertised Receiver Window Credit (a_rwnd) | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Number of Gap Ack Blocks = N | Number of Duplicate TSNs = X | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Gap Ack Block #1 Start | Gap Ack Block #1 End | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| ... | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Gap Ack Block #N Start | Gap Ack Block #N End | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Duplicate TSN 1 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| | -///| ... | -///| | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Duplicate TSN X | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Debug, Default, Copy, Clone)] -pub(crate) struct GapAckBlock { - pub(crate) start: u16, - pub(crate) end: u16, -} - -/// makes gapAckBlock printable -impl fmt::Display for GapAckBlock { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} - {}", self.start, self.end) - } -} - -#[derive(Default, Debug)] -pub(crate) struct ChunkSelectiveAck { - pub(crate) cumulative_tsn_ack: u32, - pub(crate) advertised_receiver_window_credit: u32, - pub(crate) gap_ack_blocks: Vec, - pub(crate) duplicate_tsn: Vec, -} - -/// makes chunkSelectiveAck printable -impl fmt::Display for ChunkSelectiveAck { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = format!( - "SACK cumTsnAck={} arwnd={} dupTsn={:?}", - self.cumulative_tsn_ack, self.advertised_receiver_window_credit, self.duplicate_tsn - ); - - for gap in &self.gap_ack_blocks { - res += format!("\n gap ack: {}", gap).as_str(); - } - - write!(f, "{}", res) - } -} - -pub(crate) const SELECTIVE_ACK_HEADER_SIZE: usize = 12; - -impl Chunk for ChunkSelectiveAck { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_SACK, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_SACK { - return Err(Error::ErrChunkTypeNotSack); - } - - if header.value_length() < SELECTIVE_ACK_HEADER_SIZE { - return Err(Error::ErrSackSizeNotLargeEnoughInfo); - } - - let reader = &mut raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()); - - let cumulative_tsn_ack = reader.get_u32(); - let advertised_receiver_window_credit = reader.get_u32(); - let gap_ack_blocks_len = reader.get_u16() as usize; - let duplicate_tsn_len = reader.get_u16() as usize; - - // The reader is bounded by header.value_length(), so we - // must check against that, not raw.len() which may include - // subsequent chunks. - if header.value_length() < SELECTIVE_ACK_HEADER_SIZE + (4 * gap_ack_blocks_len + 4 * duplicate_tsn_len) { - return Err(Error::ErrSackSizeNotLargeEnoughInfo); - } - - let mut gap_ack_blocks = vec![]; - let mut duplicate_tsn = vec![]; - for _ in 0..gap_ack_blocks_len { - let start = reader.get_u16(); - let end = reader.get_u16(); - gap_ack_blocks.push(GapAckBlock { start, end }); - } - for _ in 0..duplicate_tsn_len { - duplicate_tsn.push(reader.get_u32()); - } - - Ok(ChunkSelectiveAck { - cumulative_tsn_ack, - advertised_receiver_window_credit, - gap_ack_blocks, - duplicate_tsn, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - - writer.put_u32(self.cumulative_tsn_ack); - writer.put_u32(self.advertised_receiver_window_credit); - writer.put_u16(self.gap_ack_blocks.len() as u16); - writer.put_u16(self.duplicate_tsn.len() as u16); - for g in &self.gap_ack_blocks { - writer.put_u16(g.start); - writer.put_u16(g.end); - } - for t in &self.duplicate_tsn { - writer.put_u32(*t); - } - - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - SELECTIVE_ACK_HEADER_SIZE + self.gap_ack_blocks.len() * 4 + self.duplicate_tsn.len() * 4 - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown.rs deleted file mode 100644 index e3cdfddc530..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown.rs +++ /dev/null @@ -1,70 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -///chunkShutdown represents an SCTP Chunk of type chunkShutdown -/// -///0 1 2 3 -///0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 7 | Chunk Flags | Length = 8 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Cumulative TSN Ack | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkShutdown { - pub(crate) cumulative_tsn_ack: u32, -} - -pub(crate) const CUMULATIVE_TSN_ACK_LENGTH: usize = 4; - -/// makes chunkShutdown printable -impl fmt::Display for ChunkShutdown { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Chunk for ChunkShutdown { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_SHUTDOWN, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_SHUTDOWN { - return Err(Error::ErrChunkTypeNotShutdown); - } - - if header.value_length() != CUMULATIVE_TSN_ACK_LENGTH { - return Err(Error::ErrInvalidChunkSize); - } - - let reader = &mut raw.slice(CHUNK_HEADER_SIZE..CHUNK_HEADER_SIZE + header.value_length()); - - let cumulative_tsn_ack = reader.get_u32(); - - Ok(ChunkShutdown { cumulative_tsn_ack }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - writer.put_u32(self.cumulative_tsn_ack); - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - CUMULATIVE_TSN_ACK_LENGTH - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_ack.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_ack.rs deleted file mode 100644 index bafb04f3d88..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_ack.rs +++ /dev/null @@ -1,55 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -///chunkShutdownAck represents an SCTP Chunk of type chunkShutdownAck -/// -///0 1 2 3 -///0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 8 | Chunk Flags | Length = 4 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkShutdownAck; - -/// makes chunkShutdownAck printable -impl fmt::Display for ChunkShutdownAck { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Chunk for ChunkShutdownAck { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_SHUTDOWN_ACK, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_SHUTDOWN_ACK { - return Err(Error::ErrChunkTypeNotShutdownAck); - } - - Ok(ChunkShutdownAck {}) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - 0 - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_complete.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_complete.rs deleted file mode 100644 index d368713bc22..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_shutdown_complete.rs +++ /dev/null @@ -1,55 +0,0 @@ -use super::{chunk_header::*, chunk_type::*, *}; - -///chunkShutdownComplete represents an SCTP Chunk of type chunkShutdownComplete -/// -///0 1 2 3 -///0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 14 |Reserved |T| Length = 4 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone)] -pub(crate) struct ChunkShutdownComplete; - -/// makes chunkShutdownComplete printable -impl fmt::Display for ChunkShutdownComplete { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Chunk for ChunkShutdownComplete { - fn header(&self) -> ChunkHeader { - ChunkHeader { - typ: CT_SHUTDOWN_COMPLETE, - flags: 0, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ChunkHeader::unmarshal(raw)?; - - if header.typ != CT_SHUTDOWN_COMPLETE { - return Err(Error::ErrChunkTypeNotShutdownComplete); - } - - Ok(ChunkShutdownComplete {}) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - self.header().marshal_to(writer)?; - Ok(writer.len()) - } - - fn check(&self) -> Result<()> { - Ok(()) - } - - fn value_length(&self) -> usize { - 0 - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_test.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_test.rs deleted file mode 100644 index d658eecfb1a..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_test.rs +++ /dev/null @@ -1,842 +0,0 @@ -use std::string::ToString; -use std::vec; -use std::vec::Vec; - -use super::*; - -/////////////////////////////////////////////////////////////////// -//chunk_type_test -/////////////////////////////////////////////////////////////////// -use super::chunk_type::*; - -#[test] -fn test_chunk_type_string() -> Result<()> { - let tests = vec![ - (CT_PAYLOAD_DATA, "DATA"), - (CT_INIT, "INIT"), - (CT_INIT_ACK, "INIT-ACK"), - (CT_SACK, "SACK"), - (CT_HEARTBEAT, "HEARTBEAT"), - (CT_HEARTBEAT_ACK, "HEARTBEAT-ACK"), - (CT_ABORT, "ABORT"), - (CT_SHUTDOWN, "SHUTDOWN"), - (CT_SHUTDOWN_ACK, "SHUTDOWN-ACK"), - (CT_ERROR, "ERROR"), - (CT_COOKIE_ECHO, "COOKIE-ECHO"), - (CT_COOKIE_ACK, "COOKIE-ACK"), - (CT_CWR, "ECNE"), - (CT_SHUTDOWN_COMPLETE, "SHUTDOWN-COMPLETE"), - (CT_RECONFIG, "RECONFIG"), - (CT_FORWARD_TSN, "FORWARD-TSN"), - (ChunkType(255), "Unknown ChunkType: 255"), - ]; - - for (ct, expected) in tests { - assert_eq!( - ct.to_string(), - expected, - "failed to stringify chunkType {}, expected {}", - ct, - expected - ); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_abort_test -/////////////////////////////////////////////////////////////////// -use super::chunk_abort::*; - -#[test] -fn test_abort_chunk_one_error_cause() -> Result<()> { - let abort1 = ChunkAbort { - error_causes: vec![ErrorCause { - code: PROTOCOL_VIOLATION, - ..Default::default() - }], - }; - - let b = abort1.marshal()?; - let abort2 = ChunkAbort::unmarshal(&b)?; - - assert_eq!(1, abort2.error_causes.len(), "should have only one cause"); - assert_eq!( - abort1.error_causes[0].error_cause_code(), - abort2.error_causes[0].error_cause_code(), - "errorCause code should match" - ); - - Ok(()) -} - -#[test] -fn test_abort_chunk_many_error_causes() -> Result<()> { - let abort1 = ChunkAbort { - error_causes: vec![ - ErrorCause { - code: INVALID_MANDATORY_PARAMETER, - ..Default::default() - }, - ErrorCause { - code: UNRECOGNIZED_CHUNK_TYPE, - ..Default::default() - }, - ErrorCause { - code: PROTOCOL_VIOLATION, - ..Default::default() - }, - ], - }; - - let b = abort1.marshal()?; - let abort2 = ChunkAbort::unmarshal(&b)?; - assert_eq!(3, abort2.error_causes.len(), "should have only one cause"); - for (i, error_cause) in abort1.error_causes.iter().enumerate() { - assert_eq!( - error_cause.error_cause_code(), - abort2.error_causes[i].error_cause_code(), - "errorCause code should match" - ); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_error_test -/////////////////////////////////////////////////////////////////// -use super::chunk_error::*; -use std::sync::LazyLock; - -const CHUNK_FLAGS: u8 = 0x00; -static ORG_UNRECOGNIZED_CHUNK: Bytes = Bytes::from_static(&[0xc0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x3]); - -static RAW_IN: LazyLock = LazyLock::new(|| { - let mut raw = BytesMut::new(); - raw.put_u8(CT_ERROR.0); - raw.put_u8(CHUNK_FLAGS); - raw.extend(vec![0x00, 0x10, 0x00, 0x06, 0x00, 0x0c]); - raw.extend(ORG_UNRECOGNIZED_CHUNK.clone()); - raw.freeze() -}); - -#[test] -fn test_chunk_error_unrecognized_chunk_type_unmarshal() -> Result<()> { - let c = ChunkError::unmarshal(&RAW_IN)?; - assert_eq!(CT_ERROR, c.header().typ, "chunk type should be ERROR"); - assert_eq!(1, c.error_causes.len(), "there should be on errorCause"); - - let ec = &c.error_causes[0]; - assert_eq!( - UNRECOGNIZED_CHUNK_TYPE, - ec.error_cause_code(), - "cause code should be unrecognizedChunkType" - ); - assert_eq!(ec.raw, ORG_UNRECOGNIZED_CHUNK, "should have valid unrecognizedChunk"); - - Ok(()) -} - -#[test] -fn test_chunk_error_unrecognized_chunk_type_marshal() -> Result<()> { - let ec_unrecognized_chunk_type = ErrorCause { - code: UNRECOGNIZED_CHUNK_TYPE, - raw: ORG_UNRECOGNIZED_CHUNK.clone(), - }; - - let ec = ChunkError { - error_causes: vec![ec_unrecognized_chunk_type], - }; - - let raw = ec.marshal()?; - assert_eq!(raw, *RAW_IN, "unexpected serialization result"); - - Ok(()) -} - -#[test] -fn test_chunk_error_unrecognized_chunk_type_marshal_with_cause_value_being_nil() -> Result<()> { - let expected = Bytes::from_static(&[CT_ERROR.0, CHUNK_FLAGS, 0x00, 0x08, 0x00, 0x06, 0x00, 0x04]); - let ec_unrecognized_chunk_type = ErrorCause { - code: UNRECOGNIZED_CHUNK_TYPE, - ..Default::default() - }; - - let ec = ChunkError { - error_causes: vec![ec_unrecognized_chunk_type], - }; - - let raw = ec.marshal()?; - assert_eq!(raw, expected, "unexpected serialization result"); - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_forward_tsn_test -/////////////////////////////////////////////////////////////////// -use super::chunk_forward_tsn::*; - -static CHUNK_FORWARD_TSN_BYTES: Bytes = Bytes::from_static(&[0xc0, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x3]); - -#[test] -fn test_chunk_forward_tsn_success() -> Result<()> { - let tests = vec![ - CHUNK_FORWARD_TSN_BYTES.clone(), - Bytes::from_static(&[0xc0, 0x0, 0x0, 0xc, 0x0, 0x0, 0x0, 0x3, 0x0, 0x4, 0x0, 0x5]), - Bytes::from_static(&[ - 0xc0, 0x0, 0x0, 0x10, 0x0, 0x0, 0x0, 0x3, 0x0, 0x4, 0x0, 0x5, 0x0, 0x6, 0x0, 0x7, - ]), - ]; - - for binary in tests { - let actual = ChunkForwardTsn::unmarshal(&binary)?; - let b = actual.marshal()?; - assert_eq!(binary, b, "test not equal"); - } - - Ok(()) -} - -#[test] -fn test_chunk_forward_tsn_unmarshal_failure() -> Result<()> { - let tests = vec![ - ("chunk header to short", Bytes::from_static(&[0xc0])), - ("missing New Cumulative TSN", Bytes::from_static(&[0xc0, 0x0, 0x0, 0x4])), - ( - "missing stream sequence", - Bytes::from_static(&[0xc0, 0x0, 0x0, 0xe, 0x0, 0x0, 0x0, 0x3, 0x0, 0x4, 0x0, 0x5, 0x0, 0x6]), - ), - ]; - - for (name, binary) in tests { - let result = ChunkForwardTsn::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_reconfig_test -/////////////////////////////////////////////////////////////////// -use super::chunk_reconfig::*; - -static TEST_CHUNK_RECONFIG_PARAM_A: Bytes = Bytes::from_static(&[ - 0x0, 0xd, 0x0, 0x16, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x0, 0x4, 0x0, 0x5, 0x0, 0x6, -]); - -static TEST_CHUNK_RECONFIG_PARAM_B: Bytes = Bytes::from_static(&[ - 0x0, 0xd, 0x0, 0x10, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, -]); - -static TEST_CHUNK_RECONFIG_RESPONCE: Bytes = - Bytes::from_static(&[0x0, 0x10, 0x0, 0xc, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1]); - -static TEST_CHUNK_RECONFIG_BYTES: LazyLock> = LazyLock::new(|| { - let mut tests = vec![]; - { - let mut test = BytesMut::new(); - test.extend(vec![0x82, 0x0, 0x0, 0x1a]); - test.extend(TEST_CHUNK_RECONFIG_PARAM_A.clone()); - tests.push(test.freeze()); - } - { - let mut test = BytesMut::new(); - test.extend(vec![0x82, 0x0, 0x0, 0x14]); - test.extend(TEST_CHUNK_RECONFIG_PARAM_B.clone()); - tests.push(test.freeze()); - } - { - let mut test = BytesMut::new(); - test.extend(vec![0x82, 0x0, 0x0, 0x10]); - test.extend(TEST_CHUNK_RECONFIG_RESPONCE.clone()); - tests.push(test.freeze()); - } - { - let mut test = BytesMut::new(); - test.extend(vec![0x82, 0x0, 0x0, 0x2c]); - test.extend(TEST_CHUNK_RECONFIG_PARAM_A.clone()); - test.extend(vec![0u8; 2]); - test.extend(TEST_CHUNK_RECONFIG_PARAM_B.clone()); - tests.push(test.freeze()); - } - { - let mut test = BytesMut::new(); - test.extend(vec![0x82, 0x0, 0x0, 0x2a]); - test.extend(TEST_CHUNK_RECONFIG_PARAM_B.clone()); - test.extend(TEST_CHUNK_RECONFIG_PARAM_A.clone()); - tests.push(test.freeze()); - } - - tests -}); - -#[test] -fn test_chunk_reconfig_success() -> Result<()> { - for (i, binary) in TEST_CHUNK_RECONFIG_BYTES.iter().enumerate() { - let actual = ChunkReconfig::unmarshal(binary)?; - let b = actual.marshal()?; - assert_eq!(*binary, b, "test {} not equal: {:?} vs {:?}", i, *binary, b); - } - - Ok(()) -} - -#[test] -fn test_chunk_reconfig_unmarshal_failure() -> Result<()> { - let mut test = BytesMut::new(); - test.extend(vec![0x82, 0x0, 0x0, 0x18]); - test.extend(TEST_CHUNK_RECONFIG_PARAM_B.clone()); - test.extend(vec![0x0, 0xd, 0x0, 0x0]); - let tests = vec![ - ("chunk header to short", Bytes::from_static(&[0x82])), - ( - "missing parse param type (A)", - Bytes::from_static(&[0x82, 0x0, 0x0, 0x4]), - ), - ( - "wrong param (A)", - Bytes::from_static(&[0x82, 0x0, 0x0, 0x8, 0x0, 0xd, 0x0, 0x0]), - ), - ("wrong param (B)", test.freeze()), - ]; - - for (name, binary) in tests { - let result = ChunkReconfig::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_shutdown_test -/////////////////////////////////////////////////////////////////// -use super::chunk_shutdown::*; - -#[test] -fn test_chunk_shutdown_success() -> Result<()> { - let tests = vec![Bytes::from_static(&[0x07, 0x00, 0x00, 0x08, 0x12, 0x34, 0x56, 0x78])]; - - for binary in tests { - let actual = ChunkShutdown::unmarshal(&binary)?; - let b = actual.marshal()?; - assert_eq!(binary, b, "test not equal"); - } - - Ok(()) -} - -#[test] -fn test_chunk_shutdown_failure() -> Result<()> { - let tests = vec![ - ( - "length too short", - Bytes::from_static(&[0x07, 0x00, 0x00, 0x07, 0x12, 0x34, 0x56, 0x78]), - ), - ( - "length too long", - Bytes::from_static(&[0x07, 0x00, 0x00, 0x09, 0x12, 0x34, 0x56, 0x78]), - ), - ( - "payload too short", - Bytes::from_static(&[0x07, 0x00, 0x00, 0x08, 0x12, 0x34, 0x56]), - ), - ( - "payload too long", - Bytes::from_static(&[0x07, 0x00, 0x00, 0x08, 0x12, 0x34, 0x56, 0x78, 0x9f]), - ), - ( - "invalid type", - Bytes::from_static(&[0x08, 0x00, 0x00, 0x08, 0x12, 0x34, 0x56, 0x78]), - ), - ]; - - for (name, binary) in tests { - let result = ChunkShutdown::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_shutdown_ack_test -/////////////////////////////////////////////////////////////////// -use super::chunk_shutdown_ack::*; - -#[test] -fn test_chunk_shutdown_ack_success() -> Result<()> { - let tests = vec![Bytes::from_static(&[0x08, 0x00, 0x00, 0x04])]; - - for binary in tests { - let actual = ChunkShutdownAck::unmarshal(&binary)?; - let b = actual.marshal()?; - assert_eq!(binary, b, "test not equal"); - } - - Ok(()) -} - -#[test] -fn test_chunk_shutdown_ack_failure() -> Result<()> { - let tests = vec![ - ("length too short", Bytes::from_static(&[0x08, 0x00, 0x00])), - ("length too long", Bytes::from_static(&[0x08, 0x00, 0x00, 0x04, 0x12])), - ("invalid type", Bytes::from_static(&[0x0f, 0x00, 0x00, 0x04])), - ]; - - for (name, binary) in tests { - let result = ChunkShutdownAck::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_shutdown_complete_test -/////////////////////////////////////////////////////////////////// -use super::chunk_shutdown_complete::*; - -#[test] -fn test_chunk_shutdown_complete_success() -> Result<()> { - let tests = vec![Bytes::from_static(&[0x0e, 0x00, 0x00, 0x04])]; - - for binary in tests { - let actual = ChunkShutdownComplete::unmarshal(&binary)?; - let b = actual.marshal()?; - assert_eq!(binary, b, "test not equal"); - } - - Ok(()) -} - -#[test] -fn test_chunk_shutdown_complete_failure() -> Result<()> { - let tests = vec![ - ("length too short", Bytes::from_static(&[0x0e, 0x00, 0x00])), - ("length too long", Bytes::from_static(&[0x0e, 0x00, 0x00, 0x04, 0x12])), - ("invalid type", Bytes::from_static(&[0x0f, 0x00, 0x00, 0x04])), - ]; - - for (name, binary) in tests { - let result = ChunkShutdownComplete::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//chunk_test -/////////////////////////////////////////////////////////////////// -use crate::vendor::sctp_proto::chunk::chunk_init::*; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::*; -use crate::vendor::sctp_proto::chunk::chunk_selective_ack::ChunkSelectiveAck; -use crate::vendor::sctp_proto::packet::*; -use crate::vendor::sctp_proto::param::param_forward_tsn_supported::ParamForwardTsnSupported; -use crate::vendor::sctp_proto::param::param_outgoing_reset_request::ParamOutgoingResetRequest; -use crate::vendor::sctp_proto::param::param_state_cookie::*; -use crate::vendor::sctp_proto::param::param_supported_extensions::ParamSupportedExtensions; - -#[test] -fn test_init_chunk() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0x81, 0x46, 0x9d, 0xfc, 0x01, 0x00, 0x00, 0x56, 0x55, 0xb9, - 0x64, 0xa5, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0xe8, 0x6d, 0x10, 0x30, 0xc0, 0x00, 0x00, 0x04, - 0x80, 0x08, 0x00, 0x09, 0xc0, 0x0f, 0xc1, 0x80, 0x82, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x24, 0x9f, 0xeb, - 0xbb, 0x5c, 0x50, 0xc9, 0xbf, 0x75, 0x9c, 0xb1, 0x2c, 0x57, 0x4f, 0xa4, 0x5a, 0x51, 0xba, 0x60, 0x17, 0x78, - 0x27, 0x94, 0x5c, 0x31, 0xe6, 0x5d, 0x5b, 0x09, 0x47, 0xe2, 0x22, 0x06, 0x80, 0x04, 0x00, 0x06, 0x00, 0x01, - 0x00, 0x00, 0x80, 0x03, 0x00, 0x06, 0x80, 0xc1, 0x00, 0x00, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - - if let Some(c) = pkt.chunks[0].as_any().downcast_ref::() { - assert_eq!( - c.initiate_tag, 1438213285, - "Unmarshal passed for SCTP packet, but got incorrect initiate tag exp: {} act: {}", - 1438213285, c.initiate_tag - ); - assert_eq!( - c.advertised_receiver_window_credit, 131072, - "Unmarshal passed for SCTP packet, but got incorrect \ - advertisedReceiverWindowCredit exp: {} act: {}", - 131072, c.advertised_receiver_window_credit - ); - assert_eq!( - c.num_outbound_streams, 1024, - "Unmarshal passed for SCTP packet, but got incorrect numOutboundStreams tag exp:{} act: {}", - 1024, c.num_outbound_streams - ); - assert_eq!( - c.num_inbound_streams, 2048, - "Unmarshal passed for SCTP packet, but got incorrect numInboundStreams exp: {} act: {}", - 2048, c.num_inbound_streams - ); - assert_eq!( - c.initial_tsn, 3899461680u32, - "Unmarshal passed for SCTP packet, but got incorrect initialTSN exp: {} act: {}", - 3899461680u32, c.initial_tsn - ); - } else { - panic!("Failed to cast Chunk -> Init"); - } - - Ok(()) -} - -#[test] -fn test_init_ack() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xce, 0x15, 0x79, 0xa2, 0x96, 0x19, 0xe8, 0xb2, 0x02, 0x00, 0x00, 0x1c, 0xeb, 0x81, - 0x4e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x50, 0xdf, 0x90, 0xd9, 0x00, 0x07, 0x00, 0x08, - 0x94, 0x06, 0x2f, 0x93, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - assert!( - pkt.chunks[0].as_any().downcast_ref::().is_some(), - "Failed to cast Chunk -> Init" - ); - - Ok(()) -} - -#[test] -fn test_chrome_chunk1_init() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0xbc, 0xb3, 0x45, 0xa2, 0x01, 0x00, 0x00, 0x56, 0xce, 0x15, - 0x79, 0xa2, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x94, 0x57, 0x95, 0xc0, 0xc0, 0x00, 0x00, 0x04, - 0x80, 0x08, 0x00, 0x09, 0xc0, 0x0f, 0xc1, 0x80, 0x82, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x24, 0xff, 0x5c, - 0x49, 0x19, 0x4a, 0x94, 0xe8, 0x2a, 0xec, 0x58, 0x55, 0x62, 0x29, 0x1f, 0x8e, 0x23, 0xcd, 0x7c, 0xe8, 0x46, - 0xba, 0x58, 0x1b, 0x3d, 0xab, 0xd7, 0x7e, 0x50, 0xf2, 0x41, 0xb1, 0x2e, 0x80, 0x04, 0x00, 0x06, 0x00, 0x01, - 0x00, 0x00, 0x80, 0x03, 0x00, 0x06, 0x80, 0xc1, 0x00, 0x00, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - let raw_pkt2 = pkt.marshal()?; - assert_eq!(raw_pkt, raw_pkt2); - - Ok(()) -} - -#[test] -fn test_chrome_chunk2_init_ack() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xce, 0x15, 0x79, 0xa2, 0xb5, 0xdb, 0x2d, 0x93, 0x02, 0x00, 0x01, 0x90, 0x9b, 0xd5, - 0xb3, 0x6f, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0xef, 0xb4, 0x72, 0x87, 0xc0, 0x00, 0x00, 0x04, - 0x80, 0x08, 0x00, 0x09, 0xc0, 0x0f, 0xc1, 0x80, 0x82, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x24, 0x2e, 0xf9, - 0x9c, 0x10, 0x63, 0x72, 0xed, 0x0d, 0x33, 0xc2, 0xdc, 0x7f, 0x9f, 0xd7, 0xef, 0x1b, 0xc9, 0xc4, 0xa7, 0x41, - 0x9a, 0x07, 0x68, 0x6b, 0x66, 0xfb, 0x6a, 0x4e, 0x32, 0x5d, 0xe4, 0x25, 0x80, 0x04, 0x00, 0x06, 0x00, 0x01, - 0x00, 0x00, 0x80, 0x03, 0x00, 0x06, 0x80, 0xc1, 0x00, 0x00, 0x00, 0x07, 0x01, 0x38, 0x4b, 0x41, 0x4d, 0x45, - 0x2d, 0x42, 0x53, 0x44, 0x20, 0x31, 0x2e, 0x31, 0x00, 0x00, 0x00, 0x00, 0x9c, 0x1e, 0x49, 0x5b, 0x00, 0x00, - 0x00, 0x00, 0xd2, 0x42, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x60, 0xea, 0x00, 0x00, 0xc4, 0x13, 0x3d, 0xe9, - 0x86, 0xb1, 0x85, 0x75, 0xa2, 0x79, 0x15, 0xce, 0x9b, 0xd5, 0xb3, 0x6f, 0x20, 0xe0, 0x9f, 0x89, 0xe0, 0x27, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x20, 0xe0, 0x9f, 0x89, - 0xe0, 0x27, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x01, 0x00, 0x01, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x01, 0x00, 0x00, 0x56, 0xce, 0x15, 0x79, 0xa2, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x94, 0x57, - 0x95, 0xc0, 0xc0, 0x00, 0x00, 0x04, 0x80, 0x08, 0x00, 0x09, 0xc0, 0x0f, 0xc1, 0x80, 0x82, 0x00, 0x00, 0x00, - 0x80, 0x02, 0x00, 0x24, 0xff, 0x5c, 0x49, 0x19, 0x4a, 0x94, 0xe8, 0x2a, 0xec, 0x58, 0x55, 0x62, 0x29, 0x1f, - 0x8e, 0x23, 0xcd, 0x7c, 0xe8, 0x46, 0xba, 0x58, 0x1b, 0x3d, 0xab, 0xd7, 0x7e, 0x50, 0xf2, 0x41, 0xb1, 0x2e, - 0x80, 0x04, 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x80, 0x03, 0x00, 0x06, 0x80, 0xc1, 0x00, 0x00, 0x02, 0x00, - 0x01, 0x90, 0x9b, 0xd5, 0xb3, 0x6f, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0xef, 0xb4, 0x72, 0x87, - 0xc0, 0x00, 0x00, 0x04, 0x80, 0x08, 0x00, 0x09, 0xc0, 0x0f, 0xc1, 0x80, 0x82, 0x00, 0x00, 0x00, 0x80, 0x02, - 0x00, 0x24, 0x2e, 0xf9, 0x9c, 0x10, 0x63, 0x72, 0xed, 0x0d, 0x33, 0xc2, 0xdc, 0x7f, 0x9f, 0xd7, 0xef, 0x1b, - 0xc9, 0xc4, 0xa7, 0x41, 0x9a, 0x07, 0x68, 0x6b, 0x66, 0xfb, 0x6a, 0x4e, 0x32, 0x5d, 0xe4, 0x25, 0x80, 0x04, - 0x00, 0x06, 0x00, 0x01, 0x00, 0x00, 0x80, 0x03, 0x00, 0x06, 0x80, 0xc1, 0x00, 0x00, 0xca, 0x0c, 0x21, 0x11, - 0xce, 0xf4, 0xfc, 0xb3, 0x66, 0x99, 0x4f, 0xdb, 0x4f, 0x95, 0x6b, 0x6f, 0x3b, 0xb1, 0xdb, 0x5a, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - let raw_pkt2 = pkt.marshal()?; - assert_eq!(raw_pkt, raw_pkt2); - - Ok(()) -} - -/// An INIT whose parameters end with a Forward TSN supported carrying no value, -/// the order mediasoup's SCTP stack emits. Compare test_chrome_chunk1_init, -/// which carries the same parameter in a non-final position. -static RAW_MEDIASOUP_INIT: Bytes = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0x92, 0x57, 0x55, 0xc7, 0x01, 0x00, 0x00, 0x20, 0x12, 0x34, 0x56, - 0x78, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x08, 0x00, 0x08, 0x82, 0xc0, - 0x40, 0xc2, 0xc0, 0x00, 0x00, 0x04, -]); - -/// The INIT ACK counterpart, where the state cookie precedes the capability -/// parameters and so Forward TSN supported is again last. -static RAW_MEDIASOUP_INIT_ACK: Bytes = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xca, 0xfe, 0xba, 0xbe, 0x43, 0xc1, 0x8f, 0x28, 0x02, 0x00, 0x00, 0x44, 0x12, 0x34, 0x56, - 0x78, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x00, 0x24, 0x00, 0x01, - 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, - 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x80, 0x08, 0x00, 0x08, 0x82, 0xc0, 0x40, 0xc2, - 0xc0, 0x00, 0x00, 0x04, -]); - -#[test] -fn test_mediasoup_chunk_init() -> Result<()> { - let pkt = Packet::unmarshal(&RAW_MEDIASOUP_INIT)?; - let raw_pkt2 = pkt.marshal()?; - assert_eq!(RAW_MEDIASOUP_INIT, raw_pkt2); - - Ok(()) -} - -#[test] -fn test_mediasoup_chunk_init_ack() -> Result<()> { - let pkt = Packet::unmarshal(&RAW_MEDIASOUP_INIT_ACK)?; - let raw_pkt2 = pkt.marshal()?; - assert_eq!(RAW_MEDIASOUP_INIT_ACK, raw_pkt2); - - Ok(()) -} - -#[test] -fn test_init_chunk_value_length_matches_wire() -> Result<()> { - // The packet decode loop locates the next chunk from value_length(), so a - // value_length() disagreeing with the Chunk Length on the wire shifts every - // chunk that follows. - for raw_pkt in [&RAW_MEDIASOUP_INIT, &RAW_MEDIASOUP_INIT_ACK] { - let raw_chunk = raw_pkt.slice(PACKET_HEADER_SIZE..); - let header = ChunkHeader::unmarshal(&raw_chunk)?; - let c = ChunkInit::unmarshal(&raw_chunk)?; - - assert_eq!( - c.value_length(), - header.value_length(), - "value_length() should match the Chunk Length on the wire" - ); - } - - Ok(()) -} - -#[test] -fn test_init_marshal_unmarshal() -> Result<()> { - let mut p = Packet { - common_header: CommonHeader { - destination_port: 1, - source_port: 1, - verification_tag: 123, - }, - chunks: vec![], - }; - - let mut init_ack = ChunkInit { - is_ack: true, - initiate_tag: 123, - advertised_receiver_window_credit: 1024, - num_outbound_streams: 1, - num_inbound_streams: 1, - initial_tsn: 123, - params: vec![], - }; - - let cookie = Box::new(ParamStateCookie::new()); - init_ack.params.push(cookie); - - p.chunks.push(Box::new(init_ack)); - - let raw_pkt = p.marshal()?; - let pkt = Packet::unmarshal(&raw_pkt)?; - - if let Some(c) = pkt.chunks[0].as_any().downcast_ref::() { - assert_eq!( - c.initiate_tag, 123, - "Unmarshal passed for SCTP packet, but got incorrect initiate tag exp: {} act: {}", - 123, c.initiate_tag - ); - assert_eq!( - c.advertised_receiver_window_credit, 1024, - "Unmarshal passed for SCTP packet, but got incorrect \ - advertisedReceiverWindowCredit exp: {} act: {}", - 1024, c.advertised_receiver_window_credit - ); - assert_eq!( - c.num_outbound_streams, 1, - "Unmarshal passed for SCTP packet, but got incorrect numOutboundStreams tag exp:{} act: {}", - 1, c.num_outbound_streams - ); - assert_eq!( - c.num_inbound_streams, 1, - "Unmarshal passed for SCTP packet, but got incorrect numInboundStreams exp: {} act: {}", - 1, c.num_inbound_streams - ); - assert_eq!( - c.initial_tsn, 123, - "Unmarshal passed for SCTP packet, but got incorrect initialTSN exp: {} act: {}", - 123, c.initial_tsn - ); - } else { - panic!("Failed to cast Chunk -> InitAck"); - } - - Ok(()) -} - -#[test] -fn test_init_trailing_param_without_value() -> Result<()> { - // The Chunk Length includes the padding of every parameter except the last, - // so a last parameter carrying no value leaves exactly PARAM_HEADER_LENGTH - // bytes of chunk value. - let init = ChunkInit { - is_ack: false, - initiate_tag: 0x1234_5678, - advertised_receiver_window_credit: 131072, - num_outbound_streams: 1024, - num_inbound_streams: 1024, - initial_tsn: 1, - params: vec![ - Box::new(ParamSupportedExtensions { - chunk_types: vec![CT_RECONFIG, CT_FORWARD_TSN], - }), - Box::new(ParamForwardTsnSupported {}), - ], - }; - - let p = Packet { - common_header: CommonHeader { - source_port: 5000, - destination_port: 5000, - verification_tag: 0, - }, - chunks: vec![Box::new(init)], - }; - - let raw_pkt = p.marshal()?; - let pkt = Packet::unmarshal(&raw_pkt)?; - assert_eq!(pkt.chunks.len(), 1, "expected a single INIT chunk"); - - let c = pkt.chunks[0] - .as_any() - .downcast_ref::() - .expect("Failed to cast Chunk -> Init"); - - assert_eq!(c.initiate_tag, 0x1234_5678); - assert_eq!(c.advertised_receiver_window_credit, 131072); - assert_eq!(c.num_outbound_streams, 1024); - assert_eq!(c.num_inbound_streams, 1024); - assert_eq!(c.initial_tsn, 1); - assert_eq!(c.params.len(), 2, "expected both parameters"); - - let supported_ext = c.params[0] - .as_any() - .downcast_ref::() - .expect("Failed to cast Param -> SupportedExtensions"); - assert_eq!(supported_ext.chunk_types, vec![CT_RECONFIG, CT_FORWARD_TSN]); - - c.params[1] - .as_any() - .downcast_ref::() - .expect("Failed to cast Param -> ForwardTsnSupported"); - - assert_eq!(raw_pkt, pkt.marshal()?, "expected a byte-exact round trip"); - - Ok(()) -} - -#[test] -fn test_payload_data_marshal_unmarshal() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xfc, 0xd6, 0x3f, 0xc6, 0xbe, 0xfa, 0xdc, 0x52, 0x0a, 0x00, 0x00, 0x24, 0x9b, 0x28, - 0x7e, 0x48, 0xa3, 0x7b, 0xc1, 0x83, 0xc4, 0x4b, 0x41, 0x04, 0xa4, 0xf7, 0xed, 0x4c, 0x93, 0x62, 0xc3, 0x49, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x1f, 0xa8, 0x79, - 0xa1, 0xc7, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x03, 0x00, 0x00, 0x66, 0x6f, 0x6f, 0x00, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - assert!( - pkt.chunks[1].as_any().downcast_ref::().is_some(), - "Failed to cast Chunk -> PayloadData" - ); - Ok(()) -} - -#[test] -fn test_select_ack_chunk() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xc2, 0x98, 0x98, 0x0f, 0x42, 0x31, 0xea, 0x78, 0x03, 0x00, 0x00, 0x14, 0x87, 0x73, - 0xbd, 0xa4, 0x00, 0x01, 0xfe, 0x74, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x02, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - assert!( - pkt.chunks[0].as_any().downcast_ref::().is_some(), - "Failed to cast Chunk -> SelectiveAck" - ); - Ok(()) -} - -#[test] -fn test_reconfig_chunk() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xb6, 0xa5, 0x12, 0xe5, 0x75, 0x3b, 0x12, 0xd3, 0x82, 0x0, 0x0, 0x16, 0x0, 0xd, 0x0, - 0x12, 0x4e, 0x1c, 0xb9, 0xe6, 0x3a, 0x74, 0x8d, 0xff, 0x4e, 0x1c, 0xb9, 0xe6, 0x0, 0x1, 0x0, 0x0, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - if let Some(c) = pkt.chunks[0].as_any().downcast_ref::() { - assert!(c.param_a.is_some(), "param_a must not be none"); - assert_eq!( - c.param_a - .as_ref() - .unwrap() - .as_any() - .downcast_ref::() - .unwrap() - .stream_identifiers[0], - 1, - "unexpected stream identifier" - ); - } else { - panic!("Failed to cast Chunk -> Reconfig"); - } - - Ok(()) -} - -#[test] -fn test_forward_tsn_chunk() -> Result<()> { - let mut raw_pkt = BytesMut::new(); - raw_pkt.extend(vec![ - 0x13, 0x88, 0x13, 0x88, 0xb6, 0xa5, 0x12, 0xe5, 0x1f, 0x9d, 0xa0, 0xfb, - ]); - raw_pkt.extend(CHUNK_FORWARD_TSN_BYTES.clone()); - let raw_pkt = raw_pkt.freeze(); - let pkt = Packet::unmarshal(&raw_pkt)?; - - if let Some(c) = pkt.chunks[0].as_any().downcast_ref::() { - assert_eq!( - c.new_cumulative_tsn, 3, - "unexpected New Cumulative TSN: {}", - c.new_cumulative_tsn - ); - } else { - panic!("Failed to cast Chunk -> Forward TSN"); - } - - Ok(()) -} - -#[test] -fn test_select_ack_chunk_followed_by_a_payload_data_chunk() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xc2, 0x98, 0x98, 0x0f, 0x58, 0xcf, 0x38, 0xC0, // A SACK chunk follows. - 0x03, 0x00, 0x00, 0x14, 0x87, 0x73, 0xbd, 0xa4, 0x00, 0x01, 0xfe, 0x74, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, - 0x00, 0x02, // A payload data chunk follows. - 0x00, 0x07, 0x00, 0x3B, 0xA4, 0x50, 0x7B, 0xC5, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x7B, 0x22, - 0x65, 0x76, 0x65, 0x6E, 0x74, 0x22, 0x3A, 0x22, 0x72, 0x65, 0x73, 0x69, 0x7A, 0x65, 0x22, 0x2C, 0x22, 0x77, - 0x69, 0x64, 0x74, 0x68, 0x22, 0x3A, 0x36, 0x36, 0x35, 0x2C, 0x22, 0x68, 0x65, 0x69, 0x67, 0x68, 0x74, 0x22, - 0x3A, 0x34, 0x39, 0x39, 0x7D, 0x00, - ]); - let pkt = Packet::unmarshal(&raw_pkt)?; - assert!( - pkt.chunks[0].as_any().downcast_ref::().is_some(), - "Failed to cast Chunk -> SelectiveAck" - ); - assert!( - pkt.chunks[1].as_any().downcast_ref::().is_some(), - "Failed to cast Chunk -> PayloadData" - ); - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_type.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_type.rs deleted file mode 100644 index 8cbc8ab7a2e..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/chunk_type.rs +++ /dev/null @@ -1,94 +0,0 @@ -use core::fmt; - -// chunkType is an enum for SCTP Chunk Type field -// This field identifies the type of information contained in the -// Chunk Value field. -#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] -pub(crate) struct ChunkType(pub(crate) u8); - -pub(crate) const CT_PAYLOAD_DATA: ChunkType = ChunkType(0); -pub(crate) const CT_INIT: ChunkType = ChunkType(1); -pub(crate) const CT_INIT_ACK: ChunkType = ChunkType(2); -pub(crate) const CT_SACK: ChunkType = ChunkType(3); -pub(crate) const CT_HEARTBEAT: ChunkType = ChunkType(4); -pub(crate) const CT_HEARTBEAT_ACK: ChunkType = ChunkType(5); -pub(crate) const CT_ABORT: ChunkType = ChunkType(6); -pub(crate) const CT_SHUTDOWN: ChunkType = ChunkType(7); -pub(crate) const CT_SHUTDOWN_ACK: ChunkType = ChunkType(8); -pub(crate) const CT_ERROR: ChunkType = ChunkType(9); -pub(crate) const CT_COOKIE_ECHO: ChunkType = ChunkType(10); -pub(crate) const CT_COOKIE_ACK: ChunkType = ChunkType(11); -pub(crate) const CT_CWR: ChunkType = ChunkType(13); -pub(crate) const CT_SHUTDOWN_COMPLETE: ChunkType = ChunkType(14); -pub(crate) const CT_RECONFIG: ChunkType = ChunkType(130); -pub(crate) const CT_FORWARD_TSN: ChunkType = ChunkType(192); -pub(crate) const CT_I_FORWARD_TSN: ChunkType = ChunkType(194); - -impl fmt::Display for ChunkType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let others = format!("Unknown ChunkType: {}", self.0); - let s = match *self { - CT_PAYLOAD_DATA => "DATA", - CT_INIT => "INIT", - CT_INIT_ACK => "INIT-ACK", - CT_SACK => "SACK", - CT_HEARTBEAT => "HEARTBEAT", - CT_HEARTBEAT_ACK => "HEARTBEAT-ACK", - CT_ABORT => "ABORT", - CT_SHUTDOWN => "SHUTDOWN", - CT_SHUTDOWN_ACK => "SHUTDOWN-ACK", - CT_ERROR => "ERROR", - CT_COOKIE_ECHO => "COOKIE-ECHO", - CT_COOKIE_ACK => "COOKIE-ACK", - CT_CWR => "ECNE", // Explicit Congestion Notification Echo - CT_SHUTDOWN_COMPLETE => "SHUTDOWN-COMPLETE", - CT_RECONFIG => "RECONFIG", // Re-configuration - CT_FORWARD_TSN => "FORWARD-TSN", - CT_I_FORWARD_TSN => "I-FORWARD-TSN", - _ => others.as_str(), - }; - write!(f, "{}", s) - } -} - -#[cfg(test)] -mod test { - use std::string::ToString; - use std::vec; - - use super::*; - - #[test] - fn test_chunk_type_string() { - let tests = vec![ - (CT_PAYLOAD_DATA, "DATA"), - (CT_INIT, "INIT"), - (CT_INIT_ACK, "INIT-ACK"), - (CT_SACK, "SACK"), - (CT_HEARTBEAT, "HEARTBEAT"), - (CT_HEARTBEAT_ACK, "HEARTBEAT-ACK"), - (CT_ABORT, "ABORT"), - (CT_SHUTDOWN, "SHUTDOWN"), - (CT_SHUTDOWN_ACK, "SHUTDOWN-ACK"), - (CT_ERROR, "ERROR"), - (CT_COOKIE_ECHO, "COOKIE-ECHO"), - (CT_COOKIE_ACK, "COOKIE-ACK"), - (CT_CWR, "ECNE"), - (CT_SHUTDOWN_COMPLETE, "SHUTDOWN-COMPLETE"), - (CT_RECONFIG, "RECONFIG"), - (CT_FORWARD_TSN, "FORWARD-TSN"), - (CT_I_FORWARD_TSN, "I-FORWARD-TSN"), - (ChunkType(255), "Unknown ChunkType: 255"), - ]; - - for (ct, expected) in tests { - assert_eq!( - ct.to_string(), - expected, - "failed to stringify chunkType {}, expected {}", - ct, - expected - ); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/mod.rs b/rs/moq-webrtc/src/vendor/sctp_proto/chunk/mod.rs deleted file mode 100644 index 96e2b24b733..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/chunk/mod.rs +++ /dev/null @@ -1,182 +0,0 @@ -#[cfg(test)] -mod chunk_test; - -pub(crate) mod chunk_abort; -pub(crate) mod chunk_cookie_ack; -pub(crate) mod chunk_cookie_echo; -pub(crate) mod chunk_error; -pub(crate) mod chunk_forward_tsn; -pub(crate) mod chunk_header; -pub(crate) mod chunk_heartbeat; -pub(crate) mod chunk_heartbeat_ack; -pub(crate) mod chunk_i_forward_tsn; -pub(crate) mod chunk_init; -pub mod chunk_payload_data; -pub(crate) mod chunk_reconfig; -pub(crate) mod chunk_selective_ack; -pub(crate) mod chunk_shutdown; -pub(crate) mod chunk_shutdown_ack; -pub(crate) mod chunk_shutdown_complete; -pub(crate) mod chunk_type; - -use crate::vendor::sctp_proto::error::{Error, Result}; -use chunk_header::*; - -use bytes::{Buf, BufMut, Bytes, BytesMut}; -use core::{any::Any, fmt}; -use std::boxed::Box; -use std::string::String; -use std::vec; -use std::vec::Vec; - -pub(crate) trait Chunk: fmt::Display + fmt::Debug { - fn header(&self) -> ChunkHeader; - fn unmarshal(raw: &Bytes) -> Result - where - Self: Sized; - fn marshal_to(&self, buf: &mut BytesMut) -> Result; - fn check(&self) -> Result<()>; - fn value_length(&self) -> usize; - fn as_any(&self) -> &(dyn Any + Send + Sync); - - fn marshal(&self) -> Result { - let capacity = CHUNK_HEADER_SIZE + self.value_length(); - let mut buf = BytesMut::with_capacity(capacity); - self.marshal_to(&mut buf)?; - Ok(buf.freeze()) - } -} - -/// ErrorCauseCode is a cause code that appears in either a ERROR or ABORT chunk -#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)] -pub struct ErrorCauseCode(pub(crate) u16); - -pub(crate) const INVALID_STREAM_IDENTIFIER: ErrorCauseCode = ErrorCauseCode(1); -pub(crate) const MISSING_MANDATORY_PARAMETER: ErrorCauseCode = ErrorCauseCode(2); -pub(crate) const STALE_COOKIE_ERROR: ErrorCauseCode = ErrorCauseCode(3); -pub(crate) const OUT_OF_RESOURCE: ErrorCauseCode = ErrorCauseCode(4); -pub(crate) const UNRESOLVABLE_ADDRESS: ErrorCauseCode = ErrorCauseCode(5); -pub(crate) const UNRECOGNIZED_CHUNK_TYPE: ErrorCauseCode = ErrorCauseCode(6); -pub(crate) const INVALID_MANDATORY_PARAMETER: ErrorCauseCode = ErrorCauseCode(7); -pub(crate) const UNRECOGNIZED_PARAMETERS: ErrorCauseCode = ErrorCauseCode(8); -pub(crate) const NO_USER_DATA: ErrorCauseCode = ErrorCauseCode(9); -pub(crate) const COOKIE_RECEIVED_WHILE_SHUTTING_DOWN: ErrorCauseCode = ErrorCauseCode(10); -pub(crate) const RESTART_OF_AN_ASSOCIATION_WITH_NEW_ADDRESSES: ErrorCauseCode = ErrorCauseCode(11); -pub(crate) const USER_INITIATED_ABORT: ErrorCauseCode = ErrorCauseCode(12); -pub(crate) const PROTOCOL_VIOLATION: ErrorCauseCode = ErrorCauseCode(13); - -impl fmt::Display for ErrorCauseCode { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let others = format!("Unknown CauseCode: {}", self.0); - let s = match *self { - INVALID_STREAM_IDENTIFIER => "Invalid Stream Identifier", - MISSING_MANDATORY_PARAMETER => "Missing Mandatory Parameter", - STALE_COOKIE_ERROR => "Stale Cookie Error", - OUT_OF_RESOURCE => "Out Of Resource", - UNRESOLVABLE_ADDRESS => "Unresolvable IP", - UNRECOGNIZED_CHUNK_TYPE => "Unrecognized Chunk Type", - INVALID_MANDATORY_PARAMETER => "Invalid Mandatory Parameter", - UNRECOGNIZED_PARAMETERS => "Unrecognized Parameters", - NO_USER_DATA => "No User Data", - COOKIE_RECEIVED_WHILE_SHUTTING_DOWN => "Cookie Received While Shutting Down", - RESTART_OF_AN_ASSOCIATION_WITH_NEW_ADDRESSES => "Restart Of An Association With New Addresses", - USER_INITIATED_ABORT => "User Initiated Abort", - PROTOCOL_VIOLATION => "Protocol Violation", - _ => others.as_str(), - }; - write!(f, "{}", s) - } -} - -impl From for ErrorCauseCode { - fn from(v: u16) -> Self { - ErrorCauseCode(v) - } -} - -/// ErrorCauseHeader represents the shared header that is shared by all error causes -#[derive(Debug, Clone, Default)] -pub(crate) struct ErrorCause { - pub(crate) code: ErrorCauseCode, - pub(crate) raw: Bytes, -} - -/// ErrorCauseInvalidMandatoryParameter represents an SCTP error cause -pub(crate) type ErrorCauseInvalidMandatoryParameter = ErrorCause; - -/// ErrorCauseUnrecognizedChunkType represents an SCTP error cause -pub(crate) type ErrorCauseUnrecognizedChunkType = ErrorCause; - -/// -/// This error cause MAY be included in ABORT chunks that are sent -/// because an SCTP endpoint detects a protocol violation of the peer -/// that is not covered by the error causes described in Section 3.3.10.1 -/// to Section 3.3.10.12. An implementation MAY provide additional -/// information specifying what kind of protocol violation has been -/// detected. -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// | Cause Code=13 | Cause Length=Variable | -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// / Additional Information / -/// \ \ -/// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// -pub(crate) type ErrorCauseProtocolViolation = ErrorCause; - -pub(crate) const ERROR_CAUSE_HEADER_LENGTH: usize = 4; - -/// makes ErrorCauseHeader printable -impl fmt::Display for ErrorCause { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.code) - } -} - -impl ErrorCause { - pub(crate) fn unmarshal(buf: &Bytes) -> Result { - if buf.len() < ERROR_CAUSE_HEADER_LENGTH { - return Err(Error::ErrErrorCauseTooSmall); - } - - let reader = &mut buf.clone(); - - let code = ErrorCauseCode(reader.get_u16()); - let len = reader.get_u16(); - - if len < ERROR_CAUSE_HEADER_LENGTH as u16 { - return Err(Error::ErrErrorCauseTooSmall); - } - - let value_length = len as usize - ERROR_CAUSE_HEADER_LENGTH; - if buf.len() < ERROR_CAUSE_HEADER_LENGTH + value_length { - return Err(Error::ErrErrorCauseTooSmall); - } - let raw = buf.slice(ERROR_CAUSE_HEADER_LENGTH..ERROR_CAUSE_HEADER_LENGTH + value_length); - - Ok(ErrorCause { code, raw }) - } - - pub(crate) fn marshal(&self) -> Bytes { - let mut buf = BytesMut::with_capacity(self.length()); - let _ = self.marshal_to(&mut buf); - buf.freeze() - } - - pub(crate) fn marshal_to(&self, writer: &mut BytesMut) -> usize { - let len = self.raw.len() + ERROR_CAUSE_HEADER_LENGTH; - writer.put_u16(self.code.0); - writer.put_u16(len as u16); - writer.extend(self.raw.clone()); - writer.len() - } - - pub(crate) fn length(&self) -> usize { - self.raw.len() + ERROR_CAUSE_HEADER_LENGTH - } - - pub(crate) fn error_cause_code(&self) -> ErrorCauseCode { - self.code - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/config.rs b/rs/moq-webrtc/src/vendor/sctp_proto/config.rs deleted file mode 100644 index 0549f5f556b..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/config.rs +++ /dev/null @@ -1,443 +0,0 @@ -use crate::vendor::sctp_proto::util::{AssociationIdGenerator, RandomAssociationIdGenerator}; - -use bytes::Bytes; -use core::fmt; -use std::boxed::Box; -use std::sync::Arc; - -/// MTU for inbound packet (from DTLS) -pub(crate) const RECEIVE_MTU: usize = 8192; -/// initial MTU for outgoing packets (to DTLS) -pub(crate) const INITIAL_MTU: u32 = 1228; -pub(crate) const INITIAL_RECV_BUF_SIZE: u32 = 1024 * 1024; -pub(crate) const COMMON_HEADER_SIZE: u32 = 12; -pub(crate) const DATA_CHUNK_HEADER_SIZE: u32 = 16; -pub(crate) const DEFAULT_MAX_MESSAGE_SIZE: u32 = 65536; - -// Default RTO values in milliseconds (RFC 4960) -pub(crate) const RTO_INITIAL: u64 = 3000; -pub(crate) const RTO_MIN: u64 = 1000; -pub(crate) const RTO_MAX: u64 = 60000; - -// Default max retransmit value (RFC 4960 Section 15) -const DEFAULT_MAX_INIT_RETRANS: usize = 8; - -/// Config collects the arguments to create_association construction into -/// a single structure -#[derive(Debug)] -pub struct TransportConfig { - max_receive_buffer_size: u32, - max_num_outbound_streams: u16, - max_num_inbound_streams: u16, - - /// Maximum message size we will SEND (respects remote's advertised limit) - /// Can be updated after association creation via set_max_send_message_size() - max_send_message_size: u32, - - /// Maximum message size we will RECEIVE (what we advertise in SDP) - /// Enforced during reassembly - messages exceeding this are rejected - max_receive_message_size: u32, - - /// Maximum number of retransmissions for INIT chunks during handshake. - /// Set to `None` for unlimited retries (recommended for WebRTC). - /// Default: Some(8) - max_init_retransmits: Option, - - /// Maximum number of retransmissions for DATA chunks. - /// Set to `None` for unlimited retries (recommended for WebRTC). - /// Default: None (unlimited) - max_data_retransmits: Option, - - /// Initial retransmission timeout in milliseconds. - /// Default: 3000 - rto_initial_ms: u64, - - /// Minimum retransmission timeout in milliseconds. - /// Default: 1000 - rto_min_ms: u64, - - /// Maximum retransmission timeout in milliseconds. - /// Default: 60000 - rto_max_ms: u64, - - /// SCTP source port when this endpoint initiates the association. - /// - /// Default: [`DEFAULT_SCTP_PORT`] - local_port: u16, - - /// SCTP destination port when this endpoint initiates the association. - /// - /// Default: [`DEFAULT_SCTP_PORT`] - remote_port: u16, -} - -impl Default for TransportConfig { - fn default() -> Self { - TransportConfig { - max_receive_buffer_size: INITIAL_RECV_BUF_SIZE, - max_send_message_size: DEFAULT_MAX_MESSAGE_SIZE, - max_receive_message_size: DEFAULT_MAX_MESSAGE_SIZE, - max_num_outbound_streams: u16::MAX, - max_num_inbound_streams: u16::MAX, - max_init_retransmits: Some(DEFAULT_MAX_INIT_RETRANS), - max_data_retransmits: None, - rto_initial_ms: RTO_INITIAL, - rto_min_ms: RTO_MIN, - rto_max_ms: RTO_MAX, - local_port: DEFAULT_SCTP_PORT, - remote_port: DEFAULT_SCTP_PORT, - } - } -} - -impl TransportConfig { - /// Set the receive storage budget across all streams, including reset-deferred DATA. - /// - /// Reads deliver complete messages only. If this budget is exhausted with no - /// readable message and no TSN gaps that can still be filled, the association - /// fails with [`crate::vendor::sctp_proto::AssociationError::ReceiveBufferExhausted`] and sends an - /// Out Of Resource ABORT. No partial message is delivered. This can happen - /// when a message exceeds the budget or multiple incomplete messages share it. - /// Messages retained on stopped read halves also consume this budget until reset. - /// Complete messages on readable streams apply ordinary receive-window backpressure. - /// The maximum receive-message size remains an independent limit. - pub fn with_max_receive_buffer_size(mut self, value: u32) -> Self { - self.max_receive_buffer_size = value; - self - } - - pub fn with_max_send_message_size(mut self, value: u32) -> Self { - self.max_send_message_size = value; - self - } - - /// Set maximum size of messages we will accept - pub fn with_max_receive_message_size(mut self, value: u32) -> Self { - self.max_receive_message_size = value; - self - } - - #[deprecated(note = "Use with_max_send_message_size instead")] - pub fn with_max_message_size(self, value: u32) -> Self { - self.with_max_send_message_size(value) - } - - pub fn with_max_num_outbound_streams(mut self, value: u16) -> Self { - self.max_num_outbound_streams = value; - self - } - - pub fn with_max_num_inbound_streams(mut self, value: u16) -> Self { - self.max_num_inbound_streams = value; - self - } - - pub(crate) fn max_receive_buffer_size(&self) -> u32 { - self.max_receive_buffer_size - } - - pub(crate) fn max_send_message_size(&self) -> u32 { - self.max_send_message_size - } - - pub(crate) fn max_receive_message_size(&self) -> u32 { - self.max_receive_message_size - } - - pub(crate) fn max_num_outbound_streams(&self) -> u16 { - self.max_num_outbound_streams - } - - pub(crate) fn max_num_inbound_streams(&self) -> u16 { - self.max_num_inbound_streams - } - - /// Set maximum INIT retransmissions. `None` means unlimited. - pub fn with_max_init_retransmits(mut self, value: Option) -> Self { - self.max_init_retransmits = value; - self - } - - /// Set maximum DATA retransmissions. `None` means unlimited. - pub fn with_max_data_retransmits(mut self, value: Option) -> Self { - self.max_data_retransmits = value; - self - } - - /// Set initial RTO in milliseconds. - pub fn with_rto_initial_ms(mut self, value: u64) -> Self { - self.rto_initial_ms = value; - self - } - - /// Set minimum RTO in milliseconds. - pub fn with_rto_min_ms(mut self, value: u64) -> Self { - self.rto_min_ms = value; - self - } - - /// Set maximum RTO in milliseconds. - pub fn with_rto_max_ms(mut self, value: u64) -> Self { - self.rto_max_ms = value; - self - } - - /// Set the SCTP source port used when initiating an association. - /// A zero port is rejected by [`crate::vendor::sctp_proto::Endpoint::connect`]. - pub fn with_local_port(mut self, value: u16) -> Self { - self.local_port = value; - self - } - - /// Set the SCTP destination port used when initiating an association. - /// A zero port is rejected by [`crate::vendor::sctp_proto::Endpoint::connect`]. - pub fn with_remote_port(mut self, value: u16) -> Self { - self.remote_port = value; - self - } - - pub(crate) fn max_init_retransmits(&self) -> Option { - self.max_init_retransmits - } - - pub(crate) fn max_data_retransmits(&self) -> Option { - self.max_data_retransmits - } - - pub(crate) fn rto_initial_ms(&self) -> u64 { - self.rto_initial_ms - } - - pub(crate) fn rto_min_ms(&self) -> u64 { - self.rto_min_ms - } - - pub(crate) fn rto_max_ms(&self) -> u64 { - self.rto_max_ms - } - - pub(crate) fn local_port(&self) -> u16 { - self.local_port - } - - pub(crate) fn remote_port(&self) -> u16 { - self.remote_port - } -} - -/// Global configuration for the endpoint, affecting all associations -/// -/// Default values should be suitable for most internet applications. -#[derive(Clone)] -pub struct EndpointConfig { - pub(crate) max_payload_size: u32, - - /// AID generator factory - /// - /// Create a aid generator for local aid in Endpoint struct - pub(crate) aid_generator_factory: Arc Box + Send + Sync>, -} - -impl Default for EndpointConfig { - fn default() -> Self { - Self::new() - } -} - -impl EndpointConfig { - /// Create a default config - pub fn new() -> Self { - let aid_factory: fn() -> Box = || Box::::default(); - Self { - max_payload_size: INITIAL_MTU - (COMMON_HEADER_SIZE + DATA_CHUNK_HEADER_SIZE), - aid_generator_factory: Arc::new(aid_factory), - } - } - - /// Supply a custom Association ID generator factory - /// - /// Called once by each `Endpoint` constructed from this configuration to obtain the AID - /// generator which will be used to generate the AIDs used for incoming packets on all - /// associations involving that `Endpoint`. A custom AID generator allows applications to embed - /// information in local association IDs, e.g. to support stateless packet-level load balancers. - /// - /// `EndpointConfig::new()` applies a default random AID generator factory. This functions - /// accepts any customized AID generator to reset AID generator factory that implements - /// the `AssociationIdGenerator` trait. - pub fn aid_generator Box + Send + Sync + 'static>( - &mut self, - factory: F, - ) -> &mut Self { - self.aid_generator_factory = Arc::new(factory); - self - } - - /// Maximum payload size accepted from peers. - /// - /// The default is suitable for typical internet applications. Applications which expect to run - /// on networks supporting Ethernet jumbo frames or similar should set this appropriately. - pub fn max_payload_size(&mut self, value: u32) -> &mut Self { - self.max_payload_size = value; - self - } - - /// Get the current value of `max_payload_size` - /// - /// While most parameters don't need to be readable, this must be exposed to allow higher-level - /// layers to determine how large a receive buffer to allocate to - /// support an externally-defined `EndpointConfig`. - /// - /// While `get_` accessors are typically unidiomatic in Rust, we favor concision for setters, - /// which will be used far more heavily. - pub fn get_max_payload_size(&self) -> u32 { - self.max_payload_size - } -} - -impl fmt::Debug for EndpointConfig { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_struct("EndpointConfig") - .field("max_payload_size", &self.max_payload_size) - .field("aid_generator_factory", &"[ elided ]") - .finish() - } -} - -/// Parameters governing incoming associations -/// -/// Default values should be suitable for most internet applications. -#[derive(Debug, Clone)] -pub struct ServerConfig { - /// Transport configuration to use for incoming associations - pub transport: Arc, - - /// Maximum number of concurrent associations - pub(crate) concurrent_associations: u32, -} - -impl Default for ServerConfig { - fn default() -> Self { - ServerConfig { - transport: Arc::new(TransportConfig::default()), - concurrent_associations: 100_000, - } - } -} - -impl ServerConfig { - /// Create a default config with a particular handshake token key - pub fn new() -> Self { - ServerConfig::default() - } -} - -/// Default SCTP source/destination port (conventional for WebRTC data channels). -pub const DEFAULT_SCTP_PORT: u16 = 5000; - -/// Maximum allowed size (in bytes) of a serialized SNAP token (INIT chunk) -/// accepted via out-of-band negotiation. A typical token is well under -/// 100 bytes; this limit prevents accidentally feeding megabytes of -/// untrusted signaling data into the parser. -pub const MAX_SNAP_INIT_BYTES: usize = 2048; - -/// Configuration for outgoing associations. -/// -/// Default values should be suitable for most internet applications. -#[derive(Debug, Clone)] -pub struct ClientConfig { - /// Transport configuration to use - pub transport: Arc, - /// Local SNAP token (INIT chunk) bytes. - /// - /// Generated via [`generate_snap_token`]. When both `local_sctp_init` and - /// `remote_sctp_init` are set, the association skips the SCTP 4-way - /// handshake (RFC 4960 Section 5.1) and immediately transitions to the - /// ESTABLISHED state. - /// - /// If only one side is set (e.g. the peer does not support SNAP), the - /// association falls back to the normal SCTP handshake. - /// - /// See [draft-hancke-tsvwg-snap-01](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). - pub(crate) local_sctp_init: Option, - /// Remote SNAP token (INIT chunk) bytes. - /// - /// Received from the peer via a signaling channel (e.g., SDP `a=sctp-init` - /// attribute). Must be provided together with `local_sctp_init` to enable - /// SNAP. - /// - /// See [draft-hancke-tsvwg-snap-01](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). - pub(crate) remote_sctp_init: Option, -} - -impl Default for ClientConfig { - fn default() -> Self { - ClientConfig { - transport: Arc::new(TransportConfig::default()), - local_sctp_init: None, - remote_sctp_init: None, - } - } -} - -impl ClientConfig { - /// Create a default config with a particular cryptographic config - pub fn new() -> Self { - ClientConfig::default() - } - - /// Enable SNAP (SCTP Negotiation Acceleration Protocol). - /// - /// Both a local and remote SNAP token (INIT chunk) must be provided. - /// The local token should be generated via [`generate_snap_token`] and - /// exchanged with the remote peer through a signaling channel (e.g., - /// SDP `a=sctp-init` attribute). The remote token is the peer's - /// corresponding bytes received via signaling. - /// - /// When both are set, the association skips the SCTP 4-way handshake - /// (RFC 4960 Section 5.1) and immediately transitions to the ESTABLISHED - /// state. - /// - /// **Note:** When using SNAP, **both** peers must call - /// [`Endpoint::connect`](crate::vendor::sctp_proto::Endpoint::connect) - there is no - /// server-side SNAP via [`Endpoint::handle`](crate::vendor::sctp_proto::Endpoint::handle). - /// - /// See [draft-hancke-tsvwg-snap-01](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). - pub fn with_snap(mut self, local_sctp_init: Bytes, remote_sctp_init: Bytes) -> Self { - self.local_sctp_init = Some(local_sctp_init); - self.remote_sctp_init = Some(remote_sctp_init); - self - } -} - -/// Generate a SNAP token (INIT chunk) for out-of-band negotiation. -/// -/// Creates a serialized SCTP INIT **chunk** (not a full SCTP packet - no -/// common header or IP/UDP framing) with random `initiate_tag` and -/// `initial_tsn` values, using the receiver window from the provided -/// [`TransportConfig`]. Stream counts are set to `u16::MAX` so that the -/// actual limit is determined by the peer's offer during negotiation. -/// -/// The returned bytes are suitable for exchange via a signaling channel -/// (e.g., SDP `a=sctp-init`) as described in -/// [draft-hancke-tsvwg-snap-01](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). -/// -/// Each call generates fresh random values. The caller must hold onto the -/// returned bytes and pass them to [`ClientConfig::with_snap`] alongside -/// the remote peer's token. -pub fn generate_snap_token(config: &TransportConfig) -> Result { - use crate::vendor::sctp_proto::chunk::{Chunk, chunk_init::ChunkInit}; - use core::num::NonZeroU32; - use rand::random; - - let mut init = ChunkInit { - initiate_tag: random::().get(), - initial_tsn: random::().get(), - num_outbound_streams: u16::MAX, - num_inbound_streams: u16::MAX, - advertised_receiver_window_credit: config.max_receive_buffer_size(), - ..Default::default() - }; - init.set_supported_extensions(); - init.check()?; - init.marshal() -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/endpoint/endpoint_test.rs b/rs/moq-webrtc/src/vendor/sctp_proto/endpoint/endpoint_test.rs deleted file mode 100644 index ac4fe5530cc..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/endpoint/endpoint_test.rs +++ /dev/null @@ -1,3734 +0,0 @@ -use std::borrow::ToOwned; -use std::println; -use std::vec; -use std::vec::Vec; -use tracing::debug; - -use super::*; -use crate::vendor::sctp_proto::association::Event; -use crate::vendor::sctp_proto::config::generate_snap_token; -use crate::vendor::sctp_proto::error::{Error, Result}; - -use crate::vendor::sctp_proto::association::state::{AckMode, AssociationState}; -use crate::vendor::sctp_proto::association::stream::{ReliabilityType, Stream, StreamEvent, StreamResetError}; -use crate::vendor::sctp_proto::chunk::chunk_abort::ChunkAbort; -use crate::vendor::sctp_proto::chunk::chunk_cookie_echo::ChunkCookieEcho; -use crate::vendor::sctp_proto::chunk::chunk_error::ChunkError; -use crate::vendor::sctp_proto::chunk::chunk_forward_tsn::ChunkForwardTsn; -use crate::vendor::sctp_proto::chunk::chunk_heartbeat::ChunkHeartbeat; -use crate::vendor::sctp_proto::chunk::chunk_init::ChunkInit; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier}; -use crate::vendor::sctp_proto::chunk::chunk_reconfig::ChunkReconfig; -use crate::vendor::sctp_proto::chunk::chunk_selective_ack::{ChunkSelectiveAck, GapAckBlock}; -use crate::vendor::sctp_proto::chunk::chunk_shutdown::ChunkShutdown; -use crate::vendor::sctp_proto::chunk::chunk_shutdown_ack::ChunkShutdownAck; -use crate::vendor::sctp_proto::chunk::chunk_shutdown_complete::ChunkShutdownComplete; -use crate::vendor::sctp_proto::chunk::{ErrorCauseProtocolViolation, PROTOCOL_VIOLATION}; -use crate::vendor::sctp_proto::packet::{CommonHeader, Packet}; -use crate::vendor::sctp_proto::param::param_outgoing_reset_request::ParamOutgoingResetRequest; -use crate::vendor::sctp_proto::param::param_reconfig_response::ParamReconfigResponse; -use crate::vendor::sctp_proto::param::param_supported_address_types::ParamSupportedAddressTypes; -use crate::vendor::sctp_proto::param::param_type::ParamType; -macro_rules! assert_matches { - ($e:expr, $($p:tt)+) => { - assert!(matches!($e, $($p)+)) - }; -} -use core::net::Ipv6Addr; -use core::ops::RangeFrom; -use core::str::FromStr; -use core::time::Duration; -use core::{cmp, mem}; -use std::sync::{LazyLock, Mutex}; -use std::time::Instant; -use tracing::{info, trace}; - -pub static SERVER_PORTS: LazyLock>> = LazyLock::new(|| Mutex::new(4433..)); -pub static CLIENT_PORTS: LazyLock>> = LazyLock::new(|| Mutex::new(44433..)); - -fn min_opt(x: Option, y: Option) -> Option { - match (x, y) { - (Some(x), Some(y)) => Some(cmp::min(x, y)), - (Some(x), _) => Some(x), - (_, Some(y)) => Some(y), - _ => None, - } -} - -/// The maximum of datagrams TestEndpoint will produce via `poll_transmit` -const MAX_DATAGRAMS: usize = 10; - -fn split_transmit(transmit: Transmit) -> Vec { - let mut transmits = Vec::new(); - if let Payload::RawEncode(contents) = transmit.payload { - for content in contents { - transmits.push(Transmit { - now: transmit.now, - remote: transmit.remote, - payload: Payload::RawEncode(vec![content]), - ecn: transmit.ecn, - local_ip: transmit.local_ip, - }); - } - } - - transmits -} - -pub fn client_config() -> ClientConfig { - ClientConfig::new() -} - -pub fn server_config() -> ServerConfig { - ServerConfig::new() -} - -struct TestEndpoint { - endpoint: Endpoint, - addr: SocketAddr, - timeout: Option, - outbound: VecDeque, - delayed: VecDeque, - inbound: VecDeque<(Instant, Option, Bytes)>, - accepted: Option, - associations: HashMap, - conn_events: HashMap>, -} - -impl TestEndpoint { - fn new(endpoint: Endpoint, addr: SocketAddr) -> Self { - Self { - endpoint, - addr, - timeout: None, - outbound: VecDeque::new(), - delayed: VecDeque::new(), - inbound: VecDeque::new(), - accepted: None, - associations: HashMap::default(), - conn_events: HashMap::default(), - } - } - - pub fn drive(&mut self, now: Instant, remote: SocketAddr) { - while self.inbound.front().is_some_and(|x| x.0 <= now) { - let (recv_time, ecn, packet) = self.inbound.pop_front().unwrap(); - if let Some((ch, event)) = self.endpoint.handle(recv_time, remote, None, ecn, packet) { - match event { - DatagramEvent::NewAssociation(conn) => { - self.associations.insert(ch, conn); - self.accepted = Some(ch); - } - DatagramEvent::AssociationEvent(event) => { - self.conn_events.entry(ch).or_default().push_back(event); - } - } - } - } - - while let Some(x) = self.poll_transmit() { - self.outbound.extend(split_transmit(x)); - } - - let mut endpoint_events: Vec<(AssociationHandle, EndpointEvent)> = vec![]; - for (ch, conn) in self.associations.iter_mut() { - if self.timeout.is_some_and(|x| x <= now) { - self.timeout = None; - conn.handle_timeout(now); - } - - for (_, mut events) in self.conn_events.drain() { - for event in events.drain(..) { - conn.handle_event(event); - } - } - - while let Some(event) = conn.poll_endpoint_event() { - endpoint_events.push((*ch, event)); - } - - while let Some(x) = conn.poll_transmit(now) { - self.outbound.extend(split_transmit(x)); - } - self.timeout = conn.poll_timeout(); - } - - for (ch, event) in endpoint_events { - if let Some(event) = self.handle_event(ch, event) { - if let Some(conn) = self.associations.get_mut(&ch) { - conn.handle_event(event); - } - } - } - } - - pub fn next_wakeup(&self) -> Option { - let next_inbound = self.inbound.front().map(|x| x.0); - min_opt(self.timeout, next_inbound) - } - - fn is_idle(&self) -> bool { - self.associations.values().all(|x| x.is_idle()) - } - - pub fn delay_outbound(&mut self) { - assert!(self.delayed.is_empty()); - mem::swap(&mut self.delayed, &mut self.outbound); - } - - pub fn finish_delay(&mut self) { - self.outbound.extend(self.delayed.drain(..)); - } - - pub fn assert_accept(&mut self) -> AssociationHandle { - self.accepted.take().expect("server didn't connect") - } -} - -impl ::core::ops::Deref for TestEndpoint { - type Target = Endpoint; - fn deref(&self) -> &Endpoint { - &self.endpoint - } -} - -impl ::core::ops::DerefMut for TestEndpoint { - fn deref_mut(&mut self) -> &mut Endpoint { - &mut self.endpoint - } -} - -struct Pair { - server: TestEndpoint, - client: TestEndpoint, - time: Instant, - latency: Duration, // One-way -} - -impl Pair { - pub fn new(endpoint_config: Arc, server_config: ServerConfig) -> Self { - let server = Endpoint::new(endpoint_config.clone(), Some(Arc::new(server_config))); - let client = Endpoint::new(endpoint_config, None); - - Pair::new_from_endpoint(client, server) - } - - pub fn new_from_endpoint(client: Endpoint, server: Endpoint) -> Self { - let server_addr = SocketAddr::new(Ipv6Addr::LOCALHOST.into(), SERVER_PORTS.lock().unwrap().next().unwrap()); - let client_addr = SocketAddr::new(Ipv6Addr::LOCALHOST.into(), CLIENT_PORTS.lock().unwrap().next().unwrap()); - Self { - server: TestEndpoint::new(server, server_addr), - client: TestEndpoint::new(client, client_addr), - time: Instant::now(), - latency: Duration::new(0, 0), - } - } - - /// Returns whether the association is not idle - pub fn step(&mut self) -> bool { - self.drive_client(); - self.drive_server(); - if self.client.is_idle() && self.server.is_idle() { - return false; - } - - let client_t = self.client.next_wakeup(); - let server_t = self.server.next_wakeup(); - match min_opt(client_t, server_t) { - Some(t) if Some(t) == client_t => { - if t != self.time { - self.time = self.time.max(t); - trace!("advancing to {:?} for client", self.time); - } - true - } - Some(t) if Some(t) == server_t => { - if t != self.time { - self.time = self.time.max(t); - trace!("advancing to {:?} for server", self.time); - } - true - } - Some(_) => unreachable!(), - None => false, - } - } - - /// Advance time until both associations are idle - pub fn drive(&mut self) { - while self.step() {} - } - - pub fn drive_client(&mut self) { - self.client.drive(self.time, self.server.addr); - for x in self.client.outbound.drain(..) { - if let Payload::RawEncode(contents) = x.payload { - for content in contents { - if self.server.addr == x.remote { - self.server - .inbound - .push_back((self.time + self.latency, x.ecn, content)); - } - } - } - } - } - - pub fn drive_server(&mut self) { - self.server.drive(self.time, self.client.addr); - for x in self.server.outbound.drain(..) { - if let Payload::RawEncode(contents) = x.payload { - for content in contents { - if self.client.addr == x.remote { - self.client - .inbound - .push_back((self.time + self.latency, x.ecn, content)); - } - } - } - } - } - - pub fn connect(&mut self) -> (AssociationHandle, AssociationHandle) { - self.connect_with(client_config()) - } - - pub fn connect_with(&mut self, config: ClientConfig) -> (AssociationHandle, AssociationHandle) { - info!("connecting"); - let client_ch = self.begin_connect(config); - self.drive(); - let server_ch = self.server.assert_accept(); - self.finish_connect(client_ch, server_ch); - (client_ch, server_ch) - } - - /// Just start connecting the client - pub fn begin_connect(&mut self, config: ClientConfig) -> AssociationHandle { - let (client_ch, client_conn) = self.client.connect(config, self.server.addr).unwrap(); - self.client.associations.insert(client_ch, client_conn); - client_ch - } - - fn finish_connect(&mut self, client_ch: AssociationHandle, server_ch: AssociationHandle) { - assert_matches!(self.client_conn_mut(client_ch).poll(), Some(Event::Connected)); - - assert_matches!(self.server_conn_mut(server_ch).poll(), Some(Event::Connected)); - } - - pub fn client_conn_mut(&mut self, ch: AssociationHandle) -> &mut Association { - self.client.associations.get_mut(&ch).unwrap() - } - - pub fn client_stream(&mut self, ch: AssociationHandle, si: u16) -> Result> { - self.client_conn_mut(ch).stream(si) - } - - pub fn server_conn_mut(&mut self, ch: AssociationHandle) -> &mut Association { - self.server.associations.get_mut(&ch).unwrap() - } - - pub fn server_stream(&mut self, ch: AssociationHandle, si: u16) -> Result> { - self.server_conn_mut(ch).stream(si) - } -} - -impl Default for Pair { - fn default() -> Self { - Pair::new(Default::default(), server_config()) - } -} - -fn create_association_pair( - ack_mode: AckMode, - recv_buf_size: u32, -) -> Result<(Pair, AssociationHandle, AssociationHandle)> { - let mut pair = Pair::new( - Arc::new(EndpointConfig::default()), - ServerConfig { - transport: Arc::new(if recv_buf_size > 0 { - TransportConfig::default().with_max_receive_buffer_size(recv_buf_size) - } else { - TransportConfig::default() - }), - ..Default::default() - }, - ); - let (client_ch, server_ch) = pair.connect_with(ClientConfig { - transport: Arc::new(if recv_buf_size > 0 { - TransportConfig::default().with_max_receive_buffer_size(recv_buf_size) - } else { - TransportConfig::default() - }), - ..Default::default() - }); - pair.client_conn_mut(client_ch).ack_mode = ack_mode; - pair.server_conn_mut(server_ch).ack_mode = ack_mode; - Ok((pair, client_ch, server_ch)) -} - -fn establish_session_pair( - pair: &mut Pair, - client_ch: AssociationHandle, - server_ch: AssociationHandle, - si: u16, -) -> Result<()> { - let hello_msg = Bytes::from_static(b"Hello"); - let _ = pair - .client_conn_mut(client_ch) - .open_stream(si, PayloadProtocolIdentifier::Binary)?; - let _ = pair - .client_stream(client_ch, si)? - .write_sctp(&hello_msg, PayloadProtocolIdentifier::Dcep)?; - pair.drive(); - - { - let s1 = pair.server_conn_mut(server_ch).accept_stream().unwrap(); - if si != s1.stream_identifier { - return Err(Error::Other("si should match".to_owned())); - } - } - pair.drive(); - - let mut buf = vec![0u8; 1024]; - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let n = chunks.read(&mut buf)?; - - if n != hello_msg.len() { - return Err(Error::Other("received data must by 3 bytes".to_owned())); - } - - if chunks.ppi != PayloadProtocolIdentifier::Dcep { - return Err(Error::Other("unexpected ppi".to_owned())); - } - - if buf[..n] != hello_msg { - return Err(Error::Other("received data mismatch".to_owned())); - } - pair.drive(); - - Ok(()) -} - -fn close_association_pair(_pair: &mut Pair, _client_ch: AssociationHandle, _server_ch: AssociationHandle, _si: u16) { - /*TODO: - // Close client - tokio::spawn(async move { - client.close().await?; - let _ = handshake0ch_tx.send(()).await; - let _ = closed_rx0.recv().await; - - Result::<()>::Ok(()) - }); - - // Close server - tokio::spawn(async move { - server.close().await?; - let _ = handshake1ch_tx.send(()).await; - let _ = closed_rx1.recv().await; - - Result::<()>::Ok(()) - }); - */ -} - -#[test] -fn test_assoc_reliable_simple() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - let msg: Bytes = Bytes::from_static(b"ABC"); - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(0, a.buffered_amount(), "incorrect bufferedAmount"); - } - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&msg, PayloadProtocolIdentifier::Binary)?; - assert_eq!(msg.len(), n, "unexpected length of received data"); - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(msg.len(), a.buffered_amount(), "incorrect bufferedAmount"); - } - - pair.drive(); - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - assert_eq!(n, msg.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(0, a.buffered_amount(), "incorrect bufferedAmount"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reliable_ordered_reordered() -> Result<()> { - // let _guard = subscribe(); - - let si: u16 = 2; - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(0, a.buffered_amount(), "incorrect bufferedAmount"); - } - - sbuf[0..4].copy_from_slice(&0u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.client.drive(pair.time, pair.server.addr); - pair.client.delay_outbound(); // Delay it - - sbuf[0..4].copy_from_slice(&1u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.client.drive(pair.time, pair.server.addr); - pair.client.finish_delay(); // Reorder it - - pair.drive(); - - let mut buf = vec![0u8; 2000]; - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 0, - "unexpected received data" - ); - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 1, - "unexpected received data" - ); - - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reliable_ordered_fragmented_then_defragmented() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 3; - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - let mut sbufl = vec![0u8; 2000]; - for (i, b) in sbufl.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - pair.client_stream(client_ch, si)? - .set_reliability_params(false, ReliabilityType::Reliable, 0)?; - pair.server_stream(server_ch, si)? - .set_reliability_params(false, ReliabilityType::Reliable, 0)?; - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbufl.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbufl.len(), n, "unexpected length of received data"); - - pair.drive(); - - let mut rbuf = vec![0u8; 2000]; - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut rbuf)?; - assert_eq!(n, sbufl.len(), "unexpected length of received data"); - assert_eq!(&rbuf[..n], &sbufl, "unexpected received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reliable_unordered_fragmented_then_defragmented() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 4; - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - let sbufl = vec![0u8; 2000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - pair.client_stream(client_ch, si)? - .set_reliability_params(true, ReliabilityType::Reliable, 0)?; - pair.server_stream(server_ch, si)? - .set_reliability_params(true, ReliabilityType::Reliable, 0)?; - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbufl.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbufl.len(), n, "unexpected length of received data"); - - pair.drive(); - - let mut rbuf = vec![0u8; 2000]; - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut rbuf)?; - assert_eq!(n, sbufl.len(), "unexpected length of received data"); - assert_eq!(&rbuf[..n], &sbufl, "unexpected received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reliable_unordered_ordered() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 5; - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - pair.client_stream(client_ch, si)? - .set_reliability_params(true, ReliabilityType::Reliable, 0)?; - pair.server_stream(server_ch, si)? - .set_reliability_params(true, ReliabilityType::Reliable, 0)?; - - sbuf[0..4].copy_from_slice(&0u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.client.drive(pair.time, pair.server.addr); - pair.client.delay_outbound(); // Delay it - - sbuf[0..4].copy_from_slice(&1u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.client.drive(pair.time, pair.server.addr); - pair.client.finish_delay(); // Reorder it - - pair.drive(); - - let mut buf = vec![0u8; 2000]; - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 1, - "unexpected received data" - ); - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 0, - "unexpected received data" - ); - - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reliable_retransmission() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 6; - let msg1: Bytes = Bytes::from_static(b"ABC"); - let msg2: Bytes = Bytes::from_static(b"DEFG"); - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - { - let a = pair.client_conn_mut(client_ch); - a.rto_mgr.set_rto(100, true); - } - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&msg1, PayloadProtocolIdentifier::Binary)?; - assert_eq!(msg1.len(), n, "unexpected length of received data"); - pair.drive_client(); // send data to server - pair.server.inbound.clear(); // Lose it - debug!("dropping packet"); - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&msg2, PayloadProtocolIdentifier::Binary)?; - assert_eq!(msg2.len(), n, "unexpected length of received data"); - - pair.drive(); - - let mut buf = vec![0u8; 32]; - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, msg1.len(), "unexpected length of received data"); - assert_eq!(&buf[..n], &msg1, "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, msg2.len(), "unexpected length of received data"); - assert_eq!(&buf[..n], &msg2, "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - let sent = pair.client_stream(client_ch, si)?.stats()?; - let received = pair.server_stream(server_ch, si)?.stats()?; - assert_eq!((sent.messages_sent, sent.bytes_sent), (2, 7)); - assert_eq!((received.messages_received, received.bytes_received), (2, 7)); - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reliable_short_buffer() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - let msg: Bytes = Bytes::from_static(b"Hello"); - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(0, a.buffered_amount(), "incorrect bufferedAmount"); - } - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&msg, PayloadProtocolIdentifier::Binary)?; - assert_eq!(msg.len(), n, "unexpected length of received data"); - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(msg.len(), a.buffered_amount(), "incorrect bufferedAmount"); - } - - pair.drive(); - - let mut buf = vec![0u8; 3]; - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let result = chunks.read(&mut buf); - assert!(result.is_err(), "expected error to be io.ErrShortBuffer"); - if let Err(err) = result { - assert_eq!(Error::ErrShortBuffer, err, "expected error to be io.ErrShortBuffer"); - } - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(0, a.buffered_amount(), "incorrect bufferedAmount"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_unreliable_rexmit_ordered_no_fragment() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // When we set the reliability value to 0 [times], then it will cause - // the chunk to be abandoned immediately after the first transmission. - pair.client_stream(client_ch, si)? - .set_reliability_params(false, ReliabilityType::Rexmit, 0)?; - pair.server_stream(server_ch, si)? - .set_reliability_params(false, ReliabilityType::Rexmit, 0)?; // doesn't matter - - //br.drop_next_nwrites(0, 1).await; // drop the first packet (second one should be sacked) - - sbuf[0..4].copy_from_slice(&0u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.drive_client(); // send data to server - pair.server.inbound.clear(); // Lose it - debug!("dropping packet"); - - sbuf[0..4].copy_from_slice(&1u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - - debug!("flush_buffers"); - pair.drive(); - - let mut buf = vec![0u8; 2000]; - - debug!("read_sctp"); - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 1, - "unexpected received data" - ); - - debug!("process"); - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_unreliable_rexmit_ordered_fragment() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - let mut sbuf = vec![0u8; 2000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - // lock RTO value at 100 [msec] - let a = pair.client_conn_mut(client_ch); - a.rto_mgr.set_rto(100, true); - } - // When we set the reliability value to 0 [times], then it will cause - // the chunk to be abandoned immediately after the first transmission. - pair.client_stream(client_ch, si)? - .set_reliability_params(false, ReliabilityType::Rexmit, 0)?; - pair.server_stream(server_ch, si)? - .set_reliability_params(false, ReliabilityType::Rexmit, 0)?; // doesn't matter - - //br.drop_next_nwrites(0, 1).await; // drop the first packet (second one should be sacked) - - sbuf[0..4].copy_from_slice(&0u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.drive_client(); // send data to server - pair.server.inbound.clear(); // Lose it - - sbuf[0..4].copy_from_slice(&1u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - - //tracing::debug!("flush_buffers"); - pair.drive(); - - let mut buf = vec![0u8; 2000]; - - //tracing::debug!("read_sctp"); - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 1, - "unexpected received data" - ); - - //tracing::debug!("process"); - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_unreliable_rexmit_unordered_no_fragment() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 2; - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // When we set the reliability value to 0 [times], then it will cause - // the chunk to be abandoned immediately after the first transmission. - pair.client_stream(client_ch, si)? - .set_reliability_params(true, ReliabilityType::Rexmit, 0)?; - pair.server_stream(server_ch, si)? - .set_reliability_params(true, ReliabilityType::Rexmit, 0)?; // doesn't matter - - //br.drop_next_nwrites(0, 1).await; // drop the first packet (second one should be sacked) - - sbuf[0..4].copy_from_slice(&0u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.drive_client(); // send data to server - pair.server.inbound.clear(); // Lose it - - sbuf[0..4].copy_from_slice(&1u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - - //tracing::debug!("flush_buffers"); - pair.drive(); - - let mut buf = vec![0u8; 2000]; - - //tracing::debug!("read_sctp"); - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 1, - "unexpected received data" - ); - - //tracing::debug!("process"); - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_unreliable_rexmit_unordered_fragment() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - let mut sbuf = vec![0u8; 2000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // When we set the reliability value to 0 [times], then it will cause - // the chunk to be abandoned immediately after the first transmission. - pair.client_stream(client_ch, si)? - .set_reliability_params(true, ReliabilityType::Rexmit, 0)?; - pair.server_stream(server_ch, si)? - .set_reliability_params(true, ReliabilityType::Rexmit, 0)?; // doesn't matter - - sbuf[0..4].copy_from_slice(&0u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.client.drive(pair.time, pair.server.addr); - pair.client.outbound.clear(); - //debug!("outbound len={}", pair.client.outbound.len()); - - sbuf[0..4].copy_from_slice(&1u32.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - - pair.drive(); - - let mut buf = vec![0u8; 2000]; - - //tracing::debug!("read_sctp"); - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - 1, - "unexpected received data" - ); - - //tracing::debug!("process"); - pair.drive(); - - { - let q = &pair - .client_conn_mut(client_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(!q.is_readable(), "should no longer be readable"); - assert_eq!(0, q.unordered.len(), "should be nothing in the unordered queue"); - assert_eq!( - 0, - q.unordered_chunks.len(), - "should be nothing in the unorderedChunks list" - ); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_pending_timed_expiry_window_stall() -> Result<()> { - for unordered in [false, true] { - for initial_ssn in [1, u16::MAX] { - let (mut pair, client, server) = create_association_pair(AckMode::NoDelay, 0)?; - establish_session_pair(&mut pair, client, server, 3)?; - pair.client_conn_mut(client) - .streams - .get_mut(&3) - .unwrap() - .sequence_number = initial_ssn; - pair.server_conn_mut(server) - .streams - .get_mut(&3) - .unwrap() - .reassembly_queue - .next_ssn = initial_ssn; - let now = pair.time; - // Leave reliable DATA in flight so the stalled window cannot send a probe. - pair.client_conn_mut(client) - .open_stream(4, PayloadProtocolIdentifier::Binary)? - .write(b"blocker")?; - pair.client.drive(now, pair.server.addr); - let old_cwnd = pair.client_conn_mut(client).cwnd; - pair.client_conn_mut(client).cwnd = 7; - pair.client_stream(client, 3)? - .set_reliability_params(unordered, ReliabilityType::Timed, 10)?; - while pair.client_conn_mut(client).poll().is_some() {} - let old = vec![42; 3000]; - pair.client_stream(client, 3)?.write(&old)?; - // Start the lifetime while congestion credit still prevents transmission. - pair.client.drive(now, pair.server.addr); - pair.client.drive(now + Duration::from_millis(9), pair.server.addr); - assert_eq!(pair.client_stream(client, 3)?.buffered_amount()?, old.len()); - // Changing the stream policy cannot extend an accepted message's lifetime. - pair.client_stream(client, 3)? - .set_reliability_params(unordered, ReliabilityType::Reliable, 0)?; - // Exact deadline expiry precedes the first TSN assignment even with a closed window. - pair.client.drive(now + Duration::from_millis(10), pair.server.addr); - assert_eq!(pair.client_stream(client, 3)?.buffered_amount()?, 0); - pair.client.drive(now + Duration::from_millis(11), pair.server.addr); - let mut low_events = 0; - while let Some(event) = pair.client_conn_mut(client).poll() { - if matches!(event, Event::Stream(StreamEvent::BufferedAmountLow { id: 3 })) { - low_events += 1; - } - } - assert_eq!(low_events, 1, "expiry releases buffer credit exactly once"); - pair.time = now + Duration::from_millis(20); - pair.client_conn_mut(client).cwnd = old_cwnd; - pair.client_stream(client, 3)? - .set_reliability_params(unordered, ReliabilityType::Reliable, 0)?; - pair.client_stream(client, 3)?.write(b"fresh")?; - pair.drive(); - let chunks = pair.server_stream(server, 3)?.read()?.expect("fresh message"); - let mut data = vec![0; chunks.len()]; - chunks.read(&mut data)?; - assert_eq!(data, b"fresh"); - assert!(pair.server_stream(server, 3)?.read()?.is_none()); - assert_eq!(pair.client_stream(client, 3)?.buffered_amount()?, 0); - } - } - Ok(()) -} - -//TODO: TestAssocT1InitTimer -//TODO: TestAssocT1CookieTimer -//TODO: TestAssocT3RtxTimer - -/*FIXME -// 1) Send 4 packets. drop the first one. -// 2) Last 3 packet will be received, which triggers fast-retransmission -// 3) The first one is retransmitted, which makes s1 readable -// Above should be done before RTO occurs (fast recovery) -#[test] -fn test_assoc_congestion_control_fast_retransmission() -> Result<()> { - let _guard = subscribe(); - - let si: u16 = 6; - let mut sbuf = vec![0u8; 1000]; - for i in 0..sbuf.len() { - sbuf[i] = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::Normal, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - //br.drop_next_nwrites(0, 1).await; // drop the first packet (second one should be sacked) - - for i in 0..4u32 { - sbuf[0..4].copy_from_slice(&i.to_be_bytes()); - let n = pair.client_stream(client_ch, si)?.write_sctp( - &Bytes::from(sbuf.clone()), - PayloadProtocolIdentifier::Binary, - )?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.client.drive(pair.time, pair.server.addr); - if i == 0 { - //drop the first packet - pair.client.outbound.clear(); - } - } - - // process packets for 500 msec, assuming that the fast retrans/recover - // should complete within 500 msec. - /*for _ in 0..50 { - br.tick().await; - tokio::time::sleep(Duration::from_millis(10)).await; - }*/ - debug!("advance 500ms"); - pair.time += Duration::from_millis(500); - pair.step(); - - let mut buf = vec![0u8; 3000]; - - // Try to read all 4 packets - for i in 0..4 { - { - let q = &pair - .server_conn_mut(server_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - assert!(q.is_readable(), "should be readable at {}", i); - } - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - i, - "unexpected received data" - ); - } - - pair.drive(); - //br.process().await; - - { - let a = pair.client_conn_mut(client_ch); - assert!(!a.in_fast_recovery, "should not be in fast-recovery"); - debug!("nSACKs : {}", a.stats.get_num_sacks()); - debug!("nFastRetrans: {}", a.stats.get_num_fast_retrans()); - - assert_eq!(1, a.stats.get_num_fast_retrans(), "should be 1"); - } - { - let b = pair.server_conn_mut(server_ch); - debug!("nDATAs : {}", b.stats.get_num_datas()); - debug!("nAckTimeouts: {}", b.stats.get_num_ack_timeouts()); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -}*/ - -#[test] -fn test_assoc_congestion_control_congestion_avoidance() -> Result<()> { - //let _guard = subscribe(); - - let max_receive_buffer_size: u32 = 64 * 1024; - let si: u16 = 6; - let n_packets_to_send: u32 = 2000; - - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::Normal, max_receive_buffer_size)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - pair.client_conn_mut(client_ch).stats.reset(); - pair.server_conn_mut(server_ch).stats.reset(); - } - - for i in 0..n_packets_to_send { - sbuf[0..4].copy_from_slice(&i.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - } - pair.drive_client(); - //debug!("pair.drive_client() done"); - - let mut rbuf = vec![0u8; 3000]; - - // Repeat calling br.Tick() until the buffered amount becomes 0 - let mut n_packets_received = 0u32; - while pair.client_conn_mut(client_ch).buffered_amount() > 0 && n_packets_received < n_packets_to_send { - /*println!("timestamp: {:?}", pair.time); - println!( - "buffered_amount {}, pair.server.inbound {}, n_packets_received {}, n_packets_to_send {}", - pair.client_conn_mut(client_ch).buffered_amount(), - pair.server.inbound.len(), - n_packets_received, - n_packets_to_send - );*/ - - pair.step(); - - while let Some(chunks) = pair.server_stream(server_ch, si)?.read_sctp()? { - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut rbuf)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - assert_eq!( - n_packets_received, - u32::from_be_bytes([rbuf[0], rbuf[1], rbuf[2], rbuf[3]]), - "unexpected length of received data" - ); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - n_packets_received += 1; - } - - //pair.drive_client(); - } - - pair.drive(); - //println!("timestamp: {:?}", pair.time); - - assert_eq!( - n_packets_received, n_packets_to_send, - "unexpected num of packets received" - ); - - { - let a = pair.client_conn_mut(client_ch); - - assert!(!a.in_fast_recovery, "should not be in fast-recovery"); - assert!(a.cwnd > a.ssthresh, "should be in congestion avoidance mode"); - assert!( - a.ssthresh >= max_receive_buffer_size, - "{} should not be less than the initial size of 128KB {}", - a.ssthresh, - max_receive_buffer_size - ); - - debug!("nSACKs : {}", a.stats.get_num_sacks()); - debug!("nT3Timeouts: {}", a.stats.get_num_t3timeouts()); - - assert!( - a.stats.get_num_sacks() <= n_packets_to_send as u64 / 2, - "too many sacks" - ); - assert_eq!(0, a.stats.get_num_t3timeouts(), "should be no retransmit"); - } - { - assert_eq!( - 0, - pair.server_conn_mut(server_ch) - .streams - .get(&si) - .unwrap() - .get_num_bytes_in_reassembly_queue(), - "reassembly queue should be empty" - ); - - let b = pair.server_conn_mut(server_ch); - - debug!("nDATAs : {}", b.stats.get_num_datas()); - - assert_eq!( - n_packets_to_send as u64, - b.stats.get_num_datas(), - "packet count mismatch" - ); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_congestion_control_slow_reader() -> Result<()> { - //let _guard = subscribe(); - - let max_receive_buffer_size: u32 = 64 * 1024; - let si: u16 = 6; - let n_packets_to_send: u32 = 130; - - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::Normal, max_receive_buffer_size)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - for i in 0..n_packets_to_send { - sbuf[0..4].copy_from_slice(&i.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - } - pair.drive_client(); - - let mut rbuf = vec![0u8; 3000]; - - // 1. First forward packets to receiver until rwnd becomes 0 - // 2. Wait until the sender's cwnd becomes 1*MTU (RTO occurred) - // 3. Stat reading a1's data - let mut n_packets_received = 0u32; - let mut has_rtoed = false; - while pair.client_conn_mut(client_ch).buffered_amount() > 0 && n_packets_received < n_packets_to_send { - /*println!( - "buffered_amount {}, pair.server.inbound {}, n_packets_received {}, n_packets_to_send {}", - pair.client_conn_mut(client_ch).buffered_amount(), - pair.server.inbound.len(), - n_packets_received, - n_packets_to_send - );*/ - - if !has_rtoed { - let rwnd = pair.server_conn_mut(server_ch).get_my_receiver_window_credit(); - let cwnd = pair.client_conn_mut(client_ch).cwnd; - let cmtu = pair.client_conn_mut(client_ch).mtu; - if cwnd > cmtu || rwnd > 0 { - // Do not read until a1.getMyReceiverWindowCredit() becomes zero - pair.step(); - continue; - } - - has_rtoed = true; - } - - while let Some(chunks) = pair.server_stream(server_ch, si)?.read_sctp()? { - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut rbuf)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - assert_eq!( - n_packets_received, - u32::from_be_bytes([rbuf[0], rbuf[1], rbuf[2], rbuf[3]]), - "unexpected length of received data" - ); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - n_packets_received += 1; - } - - pair.step(); - } - - pair.drive(); - - assert_eq!( - n_packets_received, n_packets_to_send, - "unexpected num of packets received" - ); - assert_eq!( - 0, - pair.server_conn_mut(server_ch) - .streams - .get(&si) - .unwrap() - .get_num_bytes_in_reassembly_queue(), - "reassembly queue should be empty" - ); - - { - let a = pair.client_conn_mut(client_ch); - debug!("nSACKs : {}", a.stats.get_num_sacks()); - } - { - let b = pair.server_conn_mut(server_ch); - debug!("nDATAs : {}", b.stats.get_num_datas()); - debug!("nAckTimeouts: {}", b.stats.get_num_ack_timeouts()); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_delayed_ack() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 6; - let mut sbuf = vec![0u8; 1000]; - let mut rbuf = vec![0u8; 1500]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::AlwaysDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - pair.client_conn_mut(client_ch).stats.reset(); - pair.server_conn_mut(server_ch).stats.reset(); - } - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.drive_client(); - - // Repeat calling br.Tick() until the buffered amount becomes 0 - let since = pair.time; - let mut n_packets_received = 0; - while pair.client_conn_mut(client_ch).buffered_amount() > 0 { - pair.step(); - - while let Some(chunks) = pair.server_stream(server_ch, si)?.read_sctp()? { - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut rbuf)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - - n_packets_received += 1; - } - } - let delay = (pair.time.duration_since(since).as_millis() as f64) / 1000.0; - debug!("received in {} seconds", delay); - assert!(delay >= 0.2, "should be >= 200msec"); - - pair.drive(); - - assert_eq!(n_packets_received, 1, "unexpected num of packets received"); - assert_eq!( - 0, - pair.server_conn_mut(server_ch) - .streams - .get(&si) - .unwrap() - .get_num_bytes_in_reassembly_queue(), - "reassembly queue should be empty" - ); - - let a_num_sacks = { - let a = pair.client_conn_mut(client_ch); - debug!("nSACKs : {}", a.stats.get_num_sacks()); - assert_eq!(0, a.stats.get_num_t3timeouts(), "should be no retransmit"); - a.stats.get_num_sacks() - }; - - { - let b = pair.server_conn_mut(server_ch); - - debug!("nDATAs : {}", b.stats.get_num_datas()); - debug!("nAckTimeouts: {}", b.stats.get_num_ack_timeouts()); - - assert_eq!(1, b.stats.get_num_datas(), "DATA chunk count mismatch"); - assert_eq!( - a_num_sacks, - b.stats.get_num_datas(), - "sack count should be equal to the number of data chunks" - ); - assert_eq!(1, b.stats.get_num_ack_timeouts(), "ackTimeout count mismatch"); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reset_close_one_way() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - let msg: Bytes = Bytes::from_static(b"ABC"); - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(0, a.buffered_amount(), "incorrect bufferedAmount"); - } - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&msg, PayloadProtocolIdentifier::Binary)?; - assert_eq!(msg.len(), n, "unexpected length of received data"); - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(msg.len(), a.buffered_amount(), "incorrect bufferedAmount"); - } - pair.step(); - - let mut buf = vec![0u8; 32]; - - while pair.server_stream(server_ch, si).is_ok() { - debug!("s1.read_sctp begin"); - match pair.server_stream(server_ch, si)?.read_sctp() { - Ok(chunks_opt) => { - if let Some(chunks) = chunks_opt { - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - debug!("s1.read_sctp done with {:?}", &buf[..n]); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!(n, msg.len(), "unexpected length of received data"); - } - - debug!("s0.close"); - pair.client_stream(client_ch, si)?.stop()?; // send reset - - pair.step(); - } - Err(err) => { - debug!("s1.read_sctp err {:?}", err); - break; - } - } - } - - pair.drive(); - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_reset_close_both_ways() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - let msg: Bytes = Bytes::from_static(b"ABC"); - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(0, a.buffered_amount(), "incorrect bufferedAmount"); - } - - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&msg, PayloadProtocolIdentifier::Binary)?; - assert_eq!(msg.len(), n, "unexpected length of received data"); - { - let a = pair.client_conn_mut(client_ch); - assert_eq!(msg.len(), a.buffered_amount(), "incorrect bufferedAmount"); - } - pair.step(); - - let mut buf = vec![0u8; 32]; - - while pair.server_stream(server_ch, si).is_ok() || pair.client_stream(client_ch, si).is_ok() { - if pair.server_stream(server_ch, si).is_ok() { - debug!("s1.read_sctp begin"); - match pair.server_stream(server_ch, si)?.read_sctp() { - Ok(chunks_opt) => { - if let Some(chunks) = chunks_opt { - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - debug!("s1.read_sctp done with {:?}", &buf[..n]); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!(n, msg.len(), "unexpected length of received data"); - } - } - Err(err) => { - debug!("s1.read_sctp err {:?}", err); - break; - } - } - } - - if pair.client_stream(client_ch, si).is_ok() { - debug!("s0.read_sctp begin"); - match pair.client_stream(client_ch, si)?.read_sctp() { - Ok(chunks_opt) => { - if let Some(chunks) = chunks_opt { - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - debug!("s0.read_sctp done with {:?}", &buf[..n]); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!(n, msg.len(), "unexpected length of received data"); - } - } - Err(err) => { - debug!("s0.read_sctp err {:?}", err); - break; - } - } - } - - if pair.client_stream(client_ch, si).is_ok() { - pair.client_stream(client_ch, si)?.stop()?; // send reset - } - if pair.server_stream(server_ch, si).is_ok() { - pair.server_stream(server_ch, si)?.stop()?; // send reset - } - - pair.step(); - } - - pair.drive(); - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_assoc_abort() -> Result<()> { - //let _guard = subscribe(); - - let si: u16 = 1; - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - let transmit = { - let abort = ChunkAbort { - error_causes: vec![ErrorCauseProtocolViolation { - code: PROTOCOL_VIOLATION, - ..Default::default() - }], - }; - - let packet = pair - .client_conn_mut(client_ch) - .create_packet(vec![Box::new(abort)]) - .marshal()?; - - Transmit { - now: pair.time, - remote: pair.server.addr, - ecn: None, - local_ip: None, - payload: Payload::RawEncode(vec![packet]), - } - }; - - // Both associations are established - assert_eq!(AssociationState::Established, pair.client_conn_mut(client_ch).state()); - assert_eq!(AssociationState::Established, pair.server_conn_mut(server_ch).state()); - - debug!("send ChunkAbort"); - pair.client.outbound.push_back(transmit); - - pair.drive(); - - // The receiving association should be closed because it got an ABORT - assert_eq!(AssociationState::Established, pair.client_conn_mut(client_ch).state()); - assert_eq!(AssociationState::Closed, pair.server_conn_mut(server_ch).state()); - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -#[test] -fn test_association_handle_packet_before_init() -> Result<()> { - //let _guard = subscribe(); - - let tests = vec![ - ( - "InitAck", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::new(ChunkInit { - is_ack: true, - initiate_tag: 1, - num_inbound_streams: 1, - num_outbound_streams: 1, - advertised_receiver_window_credit: 1500, - ..Default::default() - })], - }, - ), - ( - "Abort", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::::default()], - }, - ), - ( - "CoockeEcho", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::::default()], - }, - ), - ( - "HeartBeat", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::::default()], - }, - ), - ( - "PayloadData", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::::default()], - }, - ), - ( - "Sack", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::new(ChunkSelectiveAck { - cumulative_tsn_ack: 1000, - advertised_receiver_window_credit: 1500, - gap_ack_blocks: vec![GapAckBlock { start: 100, end: 200 }], - ..Default::default() - })], - }, - ), - ( - "Reconfig", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::new(ChunkReconfig { - param_a: Some(Box::::default()), - param_b: Some(Box::::default()), - })], - }, - ), - ( - "ForwardTSN", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::new(ChunkForwardTsn { - new_cumulative_tsn: 100, - ..Default::default() - })], - }, - ), - ( - "Error", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::::default()], - }, - ), - ( - "Shutdown", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::::default()], - }, - ), - ( - "ShutdownAck", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::new(ChunkShutdownAck)], - }, - ), - ( - "ShutdownComplete", - Packet { - common_header: CommonHeader { - source_port: 1, - destination_port: 1, - verification_tag: 0, - }, - chunks: vec![Box::new(ChunkShutdownComplete)], - }, - ), - ]; - - let remote = SocketAddr::from_str("0.0.0.0:0").unwrap(); - - for (name, packet) in tests { - debug!("testing {}", name); - - //let (a_conn, charlie_conn) = pipe(); - let config = Arc::new(TransportConfig::default()); - let mut a = Association::new(None, config, 1400, 0, remote, None, Instant::now()); - - let packet = packet.marshal()?; - a.handle_event(AssociationEvent(AssociationEventInner::Datagram(Transmit { - now: Instant::now(), - remote, - ecn: None, - local_ip: None, - payload: Payload::RawEncode(vec![packet]), - }))); - - a.close()?; - } - - Ok(()) -} - -// This test reproduces an issue related to having regular messages (regular acks) which keep -// rescheduling the T3RTX timer before it can ever fire. -#[test] -fn test_old_rtx_on_regular_acks() -> Result<()> { - let si: u16 = 6; - let mut sbuf = vec![0u8; 1000]; - for (i, b) in sbuf.iter_mut().enumerate() { - *b = (i & 0xff) as u8; - } - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::Normal, 0)?; - pair.latency = Duration::from_millis(500); - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // Send 20 packet at a regular interval that is < RTO - for i in 0..20u32 { - println!("sending packet {}", i); - sbuf[0..4].copy_from_slice(&i.to_be_bytes()); - let n = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from(sbuf.clone()), PayloadProtocolIdentifier::Binary)?; - assert_eq!(sbuf.len(), n, "unexpected length of received data"); - pair.client.drive(pair.time, pair.server.addr); - - // drop a few transmits - if (5..10).contains(&i) { - pair.client.outbound.clear(); - } - - pair.drive_client(); - pair.drive_server(); - pair.time += Duration::from_millis(500); - } - - pair.drive_client(); - pair.drive_server(); - - let mut buf = vec![0u8; 3000]; - - // All packets must readable correctly - for i in 0..20 { - { - let q = &pair - .server_conn_mut(server_ch) - .streams - .get(&si) - .unwrap() - .reassembly_queue; - println!("q.is_readable()={}", q.is_readable()); - assert!(q.is_readable(), "should be readable at {}", i); - } - - let chunks = pair.server_stream(server_ch, si)?.read_sctp()?.unwrap(); - let (n, ppi) = (chunks.len(), chunks.ppi); - chunks.read(&mut buf)?; - assert_eq!(n, sbuf.len(), "unexpected length of received data"); - assert_eq!(ppi, PayloadProtocolIdentifier::Binary, "unexpected ppi"); - assert_eq!( - u32::from_be_bytes([buf[0], buf[1], buf[2], buf[3]]), - i, - "unexpected received data" - ); - } - - close_association_pair(&mut pair, client_ch, server_ch, si); - - Ok(()) -} - -/* -TODO: The following tests will be moved to sctp-async tests: -struct FakeEchoConn { - wr_tx: Mutex>>, - rd_rx: Mutex>>, - bytes_sent: AtomicUsize, - bytes_received: AtomicUsize, -} - -impl FakeEchoConn { - fn new() -> impl Conn + AsAny { - let (wr_tx, rd_rx) = mpsc::channel(1); - FakeEchoConn { - wr_tx: Mutex::new(wr_tx), - rd_rx: Mutex::new(rd_rx), - bytes_sent: AtomicUsize::new(0), - bytes_received: AtomicUsize::new(0), - } - } -} - -trait AsAny { - fn as_any(&self) -> &(dyn std::any::Any + Send + Sync); -} - -impl AsAny for FakeEchoConn { - fn as_any(&self) -> &(dyn std::any::Any + Send + Sync) { - self - } -} - -type UResult = std::result::Result; - -#[async_trait] -impl Conn for FakeEchoConn { - fn connect(&self, _addr: SocketAddr) -> UResult<()> { - Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into()) - } - - fn recv(&self, b: &mut [u8]) -> UResult { - let mut rd_rx = self.rd_rx.lock().await; - let v = match rd_rx.recv().await { - Some(v) => v, - None => { - return Err(io::Error::new(io::ErrorKind::UnexpectedEof, "Unexpected EOF").into()) - } - }; - let l = std::cmp::min(v.len(), b.len()); - b[..l].copy_from_slice(&v[..l]); - self.bytes_received.fetch_add(l, Ordering::SeqCst); - Ok(l) - } - - fn recv_from(&self, _buf: &mut [u8]) -> UResult<(usize, SocketAddr)> { - Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into()) - } - - fn send(&self, b: &[u8]) -> UResult { - let wr_tx = self.wr_tx.lock().await; - match wr_tx.send(b.to_vec()).await { - Ok(_) => {} - Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err.to_string()).into()), - }; - self.bytes_sent.fetch_add(b.len(), Ordering::SeqCst); - Ok(b.len()) - } - - fn send_to(&self, _buf: &[u8], _target: SocketAddr) -> UResult { - Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into()) - } - - fn local_addr(&self) -> UResult { - Err(io::Error::new(io::ErrorKind::AddrNotAvailable, "Addr Not Available").into()) - } - - fn remote_addr(&self) -> Option { - None - } - - fn close(&self) -> UResult<()> { - Ok(()) - } -} - -//use std::io::Write; - -#[test] -fn test_stats() -> Result<()> { - /*env_logger::Builder::new() - .format(|buf, record| { - writeln!( - buf, - "{}:{} [{}] {} - {}", - record.file().unwrap_or("unknown"), - record.line().unwrap_or(0), - record.level(), - chrono::Local::now().format("%H:%M:%S.%6f"), - record.args() - ) - }) - .filter(None, tracing::LevelFilter::Trace) - .init();*/ - - let conn = Arc::new(FakeEchoConn::new()); - let a = Association::client(Config { - net_conn: Arc::clone(&conn) as Arc, - max_receive_buffer_size: 0, - max_message_size: 0, - name: "client".to_owned(), - }) - .await?; - - if let Some(conn) = conn.as_any().downcast_ref::() { - assert_eq!( - conn.bytes_received.load(Ordering::SeqCst), - a.bytes_received() - ); - assert_eq!(conn.bytes_sent.load(Ordering::SeqCst), a.bytes_sent()); - } else { - assert!(false, "must be FakeEchoConn"); - } - - Ok(()) -} - -fn create_assocs() -> Result<(Association, Association)> { - let addr1 = SocketAddr::from_str("0.0.0.0:0").unwrap(); - let addr2 = SocketAddr::from_str("0.0.0.0:0").unwrap(); - - let udp1 = UdpSocket::bind(addr1).await.unwrap(); - let udp2 = UdpSocket::bind(addr2).await.unwrap(); - - udp1.connect(udp2.local_addr().unwrap()).await.unwrap(); - udp2.connect(udp1.local_addr().unwrap()).await.unwrap(); - - let (a1chan_tx, mut a1chan_rx) = mpsc::channel(1); - let (a2chan_tx, mut a2chan_rx) = mpsc::channel(1); - - tokio::spawn(async move { - let a = Association::client(Config { - net_conn: Arc::new(udp1), - max_receive_buffer_size: 0, - max_message_size: 0, - name: "client".to_owned(), - }) - .await?; - - let _ = a1chan_tx.send(a).await; - - Result::<()>::Ok(()) - }); - - tokio::spawn(async move { - let a = Association::server(Config { - net_conn: Arc::new(udp2), - max_receive_buffer_size: 0, - max_message_size: 0, - name: "server".to_owned(), - }) - .await?; - - let _ = a2chan_tx.send(a).await; - - Result::<()>::Ok(()) - }); - - let timer1 = tokio::time::sleep(Duration::from_secs(1)); - tokio::pin!(timer1); - let a1 = tokio::select! { - _ = timer1.as_mut() =>{ - assert!(false,"timed out waiting for a1"); - return Err(Error::Other("timed out waiting for a1".to_owned()).into()); - }, - a1 = a1chan_rx.recv() => { - a1.unwrap() - } - }; - - let timer2 = tokio::time::sleep(Duration::from_secs(1)); - tokio::pin!(timer2); - let a2 = tokio::select! { - _ = timer2.as_mut() =>{ - assert!(false,"timed out waiting for a2"); - return Err(Error::Other("timed out waiting for a2".to_owned()).into()); - }, - a2 = a2chan_rx.recv() => { - a2.unwrap() - } - }; - - Ok((a1, a2)) -} - -//use std::io::Write; -//TODO: remove this conditional test -#[cfg(not(target_os = "windows"))] -#[test] -fn test_association_shutdown() -> Result<()> { - /*env_logger::Builder::new() - .format(|buf, record| { - writeln!( - buf, - "{}:{} [{}] {} - {}", - record.file().unwrap_or("unknown"), - record.line().unwrap_or(0), - record.level(), - chrono::Local::now().format("%H:%M:%S.%6f"), - record.args() - ) - }) - .filter(None, tracing::LevelFilter::Trace) - .init();*/ - - let (a1, a2) = create_assocs().await?; - - let s11 = a1.open_stream(1, PayloadProtocolIdentifier::String).await?; - let s21 = a2.open_stream(1, PayloadProtocolIdentifier::String).await?; - - let test_data = Bytes::from_static(b"test"); - - let n = s11.write(&test_data).await?; - assert_eq!(test_data.len(), n); - - let mut buf = vec![0u8; test_data.len()]; - let n = s21.read(&mut buf).await?; - assert_eq!(test_data.len(), n); - assert_eq!(&test_data, &buf[0..n]); - - if let Ok(result) = tokio::time::timeout(Duration::from_secs(1), a1.shutdown()).await { - assert!(result.is_ok(), "shutdown should be ok"); - } else { - assert!(false, "shutdown timeout"); - } - - { - let mut close_loop_ch_rx = a2.close_loop_ch_rx.lock().await; - - // Wait for close read loop channels to prevent flaky tests. - let timer2 = tokio::time::sleep(Duration::from_secs(1)); - tokio::pin!(timer2); - tokio::select! { - _ = timer2.as_mut() =>{ - assert!(false,"timed out waiting for a2 read loop to close"); - }, - _ = close_loop_ch_rx.recv() => { - tracing::debug!("recv a2.close_loop_ch_rx"); - } - }; - } - Ok(()) -} - - -fn test_association_shutdown_during_write() -> Result<()> { - //let _guard = subscribe(); - - let (a1, a2) = create_assocs().await?; - - let s11 = a1.open_stream(1, PayloadProtocolIdentifier::String).await?; - let s21 = a2.open_stream(1, PayloadProtocolIdentifier::String).await?; - - let (writing_done_tx, mut writing_done_rx) = mpsc::channel::<()>(1); - let ss21 = Arc::clone(&s21); - tokio::spawn(async move { - let mut i = 0; - while ss21.write(&Bytes::from(vec![i])).await.is_ok() { - if i == 255 { - i = 0; - } else { - i += 1; - } - - if i % 100 == 0 { - tokio::time::sleep(Duration::from_millis(20)).await; - } - } - - drop(writing_done_tx); - }); - - let test_data = Bytes::from_static(b"test"); - - let n = s11.write(&test_data).await?; - assert_eq!(test_data.len(), n); - - let mut buf = vec![0u8; test_data.len()]; - let n = s21.read(&mut buf).await?; - assert_eq!(test_data.len(), n); - assert_eq!(&test_data, &buf[0..n]); - - { - let mut close_loop_ch_rx = a1.close_loop_ch_rx.lock().await; - tokio::select! { - res = tokio::time::timeout(Duration::from_secs(1), a1.shutdown()) => { - if let Ok(result) = res { - assert!(result.is_ok(), "shutdown should be ok"); - } else { - assert!(false, "shutdown timeout"); - } - } - _ = writing_done_rx.recv() => { - tracing::debug!("writing_done_rx"); - let result = close_loop_ch_rx.recv().await; - tracing::debug!("a1.close_loop_ch_rx.recv: {:?}", result); - }, - }; - } - - { - let mut close_loop_ch_rx = a2.close_loop_ch_rx.lock().await; - // Wait for close read loop channels to prevent flaky tests. - let timer2 = tokio::time::sleep(Duration::from_secs(1)); - tokio::pin!(timer2); - tokio::select! { - _ = timer2.as_mut() =>{ - assert!(false,"timed out waiting for a2 read loop to close"); - }, - _ = close_loop_ch_rx.recv() => { - tracing::debug!("recv a2.close_loop_ch_rx"); - } - }; - } - - Ok(()) -}*/ - -#[test] -fn test_assoc_reset_duplicate_reconfig_request() -> Result<()> { - let si: u16 = 1; - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // Client initiates reset of stream 1 - pair.client_stream(client_ch, si)?.stop()?; - - // Drive client to generate the reconfig packet, which lands in server's inbound - pair.drive_client(); - - // Capture the raw packet bytes before the server processes them. - // These contain the ChunkReconfig with the ParamOutgoingResetRequest. - let captured_packets: Vec<_> = pair.server.inbound.iter().cloned().collect(); - - // Let the entire reset flow complete - pair.drive(); - - // Verify stream 1 is gone on the server - assert!( - pair.server_stream(server_ch, si).is_err(), - "stream 1 should be removed after reset" - ); - - // Server opens a new stream 1 - let _ = pair - .server_conn_mut(server_ch) - .open_stream(si, PayloadProtocolIdentifier::Binary)?; - assert!(pair.server_stream(server_ch, si).is_ok(), "new stream 1 should exist"); - - // Inject the captured reconfig packets again (simulating retransmission) - for packet in captured_packets { - pair.server.inbound.push_back(packet); - } - - // Process the injected packets - pair.drive(); - - // The new stream 1 must NOT be destroyed by the duplicate reconfig request - assert!( - pair.server_stream(server_ch, si).is_ok(), - "new stream 1 should NOT be destroyed by duplicate reconfig request" - ); - - Ok(()) -} - -/// Verify that a retransmission of a RE-CONFIG request that was initially -/// InProgress and then completed via TSN advance (not via handle_reconfig_param) -/// does not destroy a reused stream. This exercises the case where -/// max_completed_reconfig_rsn must be updated in the TSN-advance loop. -#[test] -fn test_assoc_reset_inprogress_completed_via_tsn_advance_then_retransmit() -> Result<()> { - let si: u16 = 1; - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // Write data so my_next_tsn advances on the client; the RECONFIG - // sender_last_tsn will include this TSN. - let _ = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from_static(b"payload"), PayloadProtocolIdentifier::Binary)?; - - // Drive client to generate the DATA packet(s). - pair.drive_client(); - - // Withhold the DATA packets from the server (simulate loss). - let withheld: Vec<_> = pair.server.inbound.drain(..).collect(); - - // Client initiates reset of stream 1. - pair.client_stream(client_ch, si)?.stop()?; - - // Drive client to generate EOS data + RECONFIG packets. - pair.drive_client(); - - // Separate RECONFIG-bearing packets from DATA-only packets. - let (reconfig_packets, data_packets): (Vec<_>, Vec<_>) = pair.server.inbound.drain(..).partition(|(_, _, raw)| { - let mut offset = 12usize; - while offset + 4 <= raw.len() { - if raw[offset] == 130 { - return true; - } - let chunk_len = u16::from_be_bytes([raw[offset + 2], raw[offset + 3]]) as usize; - if chunk_len < 4 { - break; - } - offset += (chunk_len + 3) & !3; - } - false - }); - - assert!(!reconfig_packets.is_empty(), "expected a RECONFIG packet"); - - // Step 1: Deliver only the RECONFIG. Server hasn't seen the withheld - // DATA so peer_last_tsn < sender_last_tsn → InProgress. - for pkt in &reconfig_packets { - pair.server.inbound.push_back(pkt.clone()); - } - pair.drive_server(); - - assert!( - pair.server_stream(server_ch, si).is_ok(), - "stream should survive InProgress reset" - ); - - // Step 2: Now deliver the withheld DATA + the other data packets. - // The TSN-advance loop in handle_data will complete the pending - // reconfig request (removing it from reconfig_requests). - // Crucially, this does NOT go through handle_reconfig_param, so - // max_completed_reconfig_rsn is only updated if the TSN-advance - // path does it. - for pkt in withheld { - pair.server.inbound.push_back(pkt); - } - for pkt in data_packets { - pair.server.inbound.push_back(pkt); - } - pair.drive(); - - // The boundary DATA must remain readable even though the reset completed. - // Draining it retires the old stream generation. - let boundary_data = pair - .server_stream(server_ch, si)? - .read()? - .expect("boundary DATA should survive the reset"); - assert_eq!(boundary_data.len(), b"payload".len()); - - assert!( - pair.server_stream(server_ch, si).is_err(), - "stream should retire after its boundary DATA is drained" - ); - - // Step 3: Reopen stream 1 with the same ID. - let _ = pair - .server_conn_mut(server_ch) - .open_stream(si, PayloadProtocolIdentifier::Binary)?; - assert!(pair.server_stream(server_ch, si).is_ok(), "new stream 1 should exist"); - - // Step 4: Replay the original RECONFIG (simulating a late retransmission). - // If the watermark was not updated during the TSN-advance completion, - // this will bypass the dedup guard and destroy the new stream. - for pkt in reconfig_packets { - pair.server.inbound.push_back(pkt); - } - pair.drive(); - - // The new stream 1 must survive. - assert!( - pair.server_stream(server_ch, si).is_ok(), - "new stream 1 should NOT be destroyed by retransmitted reconfig \ - after InProgress completion via TSN advance" - ); - - Ok(()) -} - -/// Verify that a retransmission of an InProgress RE-CONFIG request is -/// re-evaluated (not falsely deduplicated) so the reset completes once -/// the outstanding TSN is finally received. -#[test] -fn test_assoc_reset_inprogress_reconfig_retransmission() -> Result<()> { - let si: u16 = 1; - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // Write data so my_next_tsn advances on the client; the RECONFIG - // sender_last_tsn will include this TSN. - let _ = pair - .client_stream(client_ch, si)? - .write_sctp(&Bytes::from_static(b"payload"), PayloadProtocolIdentifier::Binary)?; - - // Drive client to generate the DATA packet(s). - pair.drive_client(); - - // Withhold the DATA packets from the server (simulate loss). - let withheld: Vec<_> = pair.server.inbound.drain(..).collect(); - - // Client initiates reset of stream 1. - pair.client_stream(client_ch, si)?.stop()?; - - // Drive client to generate EOS data + RECONFIG packets. - pair.drive_client(); - - // Separate RECONFIG-bearing packets from DATA-only packets. - // Chunk type is the first byte after the 12-byte common header. - let (reconfig_packets, data_packets): (Vec<_>, Vec<_>) = pair.server.inbound.drain(..).partition(|(_, _, raw)| { - // Scan all chunks in the packet for CT_RECONFIG (130). - let mut offset = 12usize; - while offset + 4 <= raw.len() { - if raw[offset] == 130 { - return true; - } - let chunk_len = u16::from_be_bytes([raw[offset + 2], raw[offset + 3]]) as usize; - if chunk_len < 4 { - break; - } - offset += (chunk_len + 3) & !3; // pad to 4-byte boundary - } - false - }); - - assert!(!reconfig_packets.is_empty(), "expected a RECONFIG packet"); - - // Deliver only the RECONFIG packets. The server hasn't seen the withheld - // DATA so peer_last_tsn < sender_last_tsn → InProgress. - for pkt in &reconfig_packets { - pair.server.inbound.push_back(pkt.clone()); - } - pair.drive_server(); - - // Stream should still exist (reset is InProgress, not completed). - assert!( - pair.server_stream(server_ch, si).is_ok(), - "stream should survive InProgress reset" - ); - - // Inject the RECONFIG again (simulating retransmission) together with - // the withheld DATA so the TSN can finally advance. - for pkt in reconfig_packets { - pair.server.inbound.push_back(pkt); - } - for pkt in withheld { - pair.server.inbound.push_back(pkt); - } - for pkt in data_packets { - pair.server.inbound.push_back(pkt); - } - - // Let everything settle. - pair.drive(); - - // The boundary DATA must remain readable even though the reset completed. - // Draining it retires the old stream generation. - let boundary_data = pair - .server_stream(server_ch, si)? - .read()? - .expect("boundary DATA should survive the reset"); - assert_eq!(boundary_data.len(), b"payload".len()); - - assert!( - pair.server_stream(server_ch, si).is_err(), - "stream should retire after its boundary DATA is drained" - ); - - Ok(()) -} - -#[test] -fn test_assoc_open_stream_rejects_pending_reset_id() -> Result<()> { - let si: u16 = 1; - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // SERVER initiates reset of stream 1. When the client processes the server's - // incoming RE-CONFIG, it removes stream 1 from self.streams and generates its - // own outgoing RE-CONFIG (stored in self.reconfigs) awaiting acknowledgment. - pair.server_stream(server_ch, si)?.stop()?; - - // Drive server to generate and deliver the RE-CONFIG to the client's inbound - pair.drive_server(); - - // Drive client to process the server's RE-CONFIG. This removes stream 1 from - // the client's stream table and creates a pending outgoing RE-CONFIG. - pair.drive_client(); - - // Client's stream 1 is removed, but the outgoing RE-CONFIG is still pending. - // open_stream should reject this stream ID. - assert!( - pair.client_stream(client_ch, si).is_err(), - "stream 1 should be removed from client" - ); - match pair - .client_conn_mut(client_ch) - .open_stream(si, PayloadProtocolIdentifier::Binary) - { - Err(Error::ErrStreamResetPending) => {} - other => panic!("expected ErrStreamResetPending, got {:?}", other.err()), - } - - // Let the full RE-CONFIG exchange complete - pair.drive(); - - // Now the RE-CONFIG is acknowledged, stream 1 should be available for reuse - let _ = pair - .client_conn_mut(client_ch) - .open_stream(si, PayloadProtocolIdentifier::Binary)?; - assert!( - pair.client_stream(client_ch, si).is_ok(), - "stream 1 should be available after RE-CONFIG is acknowledged" - ); - - Ok(()) -} - -#[test] -fn test_assoc_reconfig_failure_keeps_stream_quarantined() -> Result<()> { - let si: u16 = 1; - - let (mut pair, client_ch, server_ch) = create_association_pair(AckMode::NoDelay, 0)?; - establish_session_pair(&mut pair, client_ch, server_ch, si)?; - - // SERVER initiates reset of stream 1. When the client processes the incoming - // RE-CONFIG it removes stream 1 from self.streams and generates its own - // outgoing RE-CONFIG (stored in self.reconfigs). - pair.server_stream(server_ch, si)?.stop()?; - - // Drive server to send the RE-CONFIG to client - pair.drive_server(); - - // Drive client to process the incoming RE-CONFIG - pair.drive_client(); - - // Drop any packets the client sent so the server never ACKs the client's - // outgoing RE-CONFIG. - pair.server.inbound.clear(); - - // Verify open_stream is blocked by the pending outgoing RE-CONFIG - match pair - .client_conn_mut(client_ch) - .open_stream(si, PayloadProtocolIdentifier::Binary) - { - Err(Error::ErrStreamResetPending) => {} - Err(e) => panic!("expected ErrStreamResetPending, got Err({:?})", e), - Ok(_) => panic!("expected ErrStreamResetPending, got Ok"), - } - - // Advance time through MAX_INIT_RETRANS (8) retransmissions + 1 to trigger - // failure. Each iteration jumps 61 seconds (> RTO_MAX of 60s) to guarantee - // the Reconfig timer fires every time. We discard all outbound packets so - // the Reconfig is never acknowledged. - for _ in 0..10 { - pair.time += Duration::from_secs(61); - pair.drive_client(); - pair.server.inbound.clear(); - } - - assert!( - core::iter::from_fn(|| pair.client_conn_mut(client_ch).poll()).any(|event| matches!( - event, - Event::Stream(StreamEvent::ResetFailed { - id, - reason: StreamResetError::Failed, - }) if id == si - )), - "reset retransmission exhaustion should emit a terminal failure event" - ); - - // The in-flight request is abandoned, but without a terminal success the - // stream ID remains quarantined and must not be reused. - assert!(matches!( - pair.client_conn_mut(client_ch) - .open_stream(si, PayloadProtocolIdentifier::Binary), - Err(Error::ErrStreamResetPending) - )); - - Ok(()) -} - -#[test] -fn test_configured_sctp_ports_complete_handshake() -> Result<()> { - let mut pair = Pair::default(); - let config = ClientConfig { - transport: Arc::new(TransportConfig::default().with_local_port(41234).with_remote_port(9899)), - ..Default::default() - }; - - let (client_ch, server_ch) = pair.connect_with(config); - establish_session_pair(&mut pair, client_ch, server_ch, 1) -} - -#[test] -fn test_connect_rejects_zero_sctp_port() { - let remote: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - for (local_port, remote_port) in [(0, 5000), (5000, 0)] { - for use_snap in [false, true] { - let transport = TransportConfig::default() - .with_local_port(local_port) - .with_remote_port(remote_port); - let mut config = ClientConfig { - transport: Arc::new(transport), - ..Default::default() - }; - if use_snap { - let local_init = generate_snap_token(&config.transport).unwrap(); - let remote_init = generate_snap_token(&config.transport).unwrap(); - config = config.with_snap(local_init, remote_init); - } - - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - assert_matches!(endpoint.connect(config, remote), Err(ConnectError::InvalidSctpPort)); - } - } -} - -#[test] -fn test_snap_connect_established_and_transmit_uses_peer_verification_tag() { - let now = Instant::now(); - - let local_transport = TransportConfig::default(); - let remote_transport = TransportConfig::default(); - - let local_init_bytes = generate_snap_token(&local_transport).expect("generate local init"); - let remote_init_bytes = generate_snap_token(&remote_transport).expect("generate remote init"); - - // Parse remote to check verification tag later - let remote_init = ChunkInit::unmarshal(&remote_init_bytes).expect("unmarshal remote INIT chunk"); - - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let client_config = ClientConfig::new().with_snap(local_init_bytes, remote_init_bytes); - let (_ch, mut assoc) = endpoint - .connect(client_config, remote_addr) - .expect("SNAP connect should succeed"); - - assert_eq!(assoc.state(), AssociationState::Established); - assert_matches!(assoc.poll(), Some(Event::Connected)); - - // Ensure outbound packets use the peer's initiate_tag as the verification tag. - let mut stream = assoc - .open_stream(1, PayloadProtocolIdentifier::Binary) - .expect("open stream"); - let msg = Bytes::from_static(b"hello"); - stream - .write_sctp(&msg, PayloadProtocolIdentifier::Binary) - .expect("write_sctp"); - - let transmit = assoc - .poll_transmit(now) - .expect("expected at least one outbound datagram"); - let Payload::RawEncode(datagrams) = transmit.payload else { - panic!("expected RawEncode transmit"); - }; - assert!(!datagrams.is_empty(), "expected at least one outbound packet"); - - let pkt = Packet::unmarshal(&datagrams[0]).expect("unmarshal outbound packet"); - assert_eq!( - pkt.common_header.verification_tag, remote_init.initiate_tag, - "outbound packet should use peer initiate_tag as verification_tag" - ); -} - -#[test] -fn test_server_accepts_init_with_supported_address_types() { - let now = Instant::now(); - let mut endpoint = Endpoint::new( - Arc::new(EndpointConfig::default()), - Some(Arc::new(ServerConfig::default())), - ); - let remote: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - let init = ChunkInit { - initiate_tag: 0x1122_3344, - advertised_receiver_window_credit: 1500, - num_outbound_streams: 1, - num_inbound_streams: 1, - initial_tsn: 1, - params: vec![Box::new(ParamSupportedAddressTypes { - address_types: vec![ParamType::Ipv4Addr, ParamType::Ipv6Addr], - })], - ..Default::default() - }; - let packet = Packet { - common_header: CommonHeader { - source_port: 5000, - destination_port: 5000, - verification_tag: 0, - }, - chunks: vec![Box::new(init)], - }; - - let (_, DatagramEvent::NewAssociation(mut association)) = endpoint - .handle(now, remote, None, None, packet.marshal().unwrap()) - .expect("INIT should create an association") - else { - panic!("expected a new association"); - }; - - let transmit = association.poll_transmit(now).expect("server should respond to INIT"); - let Payload::RawEncode(datagrams) = transmit.payload else { - panic!("expected encoded INIT ACK"); - }; - let response = Packet::unmarshal(&datagrams[0]).expect("valid INIT ACK packet"); - let init_ack = response.chunks[0] - .as_any() - .downcast_ref::() - .expect("server should send INIT ACK"); - assert!(init_ack.is_ack); -} - -#[test] -fn test_server_retransmitted_init_routes_to_existing_association() { - let now = Instant::now(); - - let mut endpoint = Endpoint::new( - Arc::new(EndpointConfig::default()), - Some(Arc::new(ServerConfig::default())), - ); - - let remote: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - let init_tag: u32 = 0x1122_3344; - - let init = ChunkInit { - is_ack: false, - initiate_tag: init_tag, - ..Default::default() - }; - - let pkt = Packet { - common_header: CommonHeader { - source_port: 5000, - destination_port: 5000, - verification_tag: 0, - }, - chunks: vec![Box::new(init)], - }; - - let bytes = pkt.marshal().expect("marshal INIT packet"); - - let (ch1, ev1) = endpoint - .handle(now, remote, None, None, bytes.clone()) - .expect("first INIT should be handled"); - assert!( - matches!(ev1, DatagramEvent::NewAssociation(_)), - "first INIT should create a new association" - ); - - // Same INIT retransmitted: should route to the same association handle. - let (ch2, ev2) = endpoint - .handle(now, remote, None, None, bytes) - .expect("retransmitted INIT should be handled"); - assert_eq!(ch2, ch1, "retransmitted INIT should map to same association"); - assert!( - matches!(ev2, DatagramEvent::AssociationEvent(_)), - "retransmitted INIT should be routed to existing association" - ); -} - -#[test] -fn test_snap_rejects_invalid_remote_bytes() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let client_config = ClientConfig::new().with_snap(local_init, Bytes::from_static(b"nope")); - let res = endpoint.connect(client_config, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Remote, - .. - })) - ), - "invalid remote bytes should fail with ParseFailed" - ); -} - -#[test] -fn test_snap_rejects_invalid_local_bytes() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let remote_init = generate_snap_token(&TransportConfig::default()).expect("remote init"); - let client_config = ClientConfig::new().with_snap(Bytes::from_static(b"nope"), remote_init); - let res = endpoint.connect(client_config, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Local, - .. - })) - ), - "invalid local bytes should fail with ParseFailed" - ); -} - -#[test] -fn test_snap_rejects_remote_init_ack() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let remote_init_ack = ChunkInit { - is_ack: true, - initiate_tag: 1, - ..Default::default() - }; - let remote_bytes = remote_init_ack.marshal().expect("marshal remote INIT-ACK"); - - let client_config = ClientConfig::new().with_snap(local_init, remote_bytes); - let res = endpoint.connect(client_config, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::InvalidInitAck { side: SnapSide::Remote })) - ), - "remote INIT-ACK should be rejected" - ); -} - -#[test] -fn test_snap_rejects_remote_init_with_zero_initiate_tag() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let remote_init = ChunkInit { - is_ack: false, - initiate_tag: 0, - ..Default::default() - }; - let remote_bytes = remote_init.marshal().expect("marshal remote INIT"); - - let client_config = ClientConfig::new().with_snap(local_init, remote_bytes); - let res = endpoint.connect(client_config, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ZeroInitiateTag { - side: SnapSide::Remote - })) - ), - "remote INIT with initiate_tag=0 should be rejected" - ); -} - -#[test] -fn test_snap_partial_config_falls_back_to_handshake() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - // Only local_sctp_init set, remote missing - should fall back to normal handshake - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let client_config = ClientConfig { - local_sctp_init: Some(local_init), - ..Default::default() - }; - let (_ch, assoc) = endpoint - .connect(client_config, remote_addr) - .expect("partial SNAP config should fall back to handshake"); - assert_eq!( - assoc.state(), - AssociationState::CookieWait, - "should use normal handshake when only local init provided" - ); - - // Only remote_sctp_init set, local missing - should fall back to normal handshake - let remote_init = generate_snap_token(&TransportConfig::default()).expect("remote init"); - let client_config = ClientConfig { - remote_sctp_init: Some(remote_init), - ..Default::default() - }; - let (_ch, assoc) = endpoint - .connect(client_config, remote_addr) - .expect("partial SNAP config should fall back to handshake"); - assert_eq!( - assoc.state(), - AssociationState::CookieWait, - "should use normal handshake when only remote init provided" - ); -} - -#[test] -fn test_snap_rejects_reused_local_init() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - // Generate a single local init - reusing it causes a collision - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - - let remote1 = generate_snap_token(&TransportConfig::default()).expect("remote init 1"); - let remote2 = generate_snap_token(&TransportConfig::default()).expect("remote init 2"); - - // First connect succeeds - let cfg1 = ClientConfig::new().with_snap(local_init.clone(), remote1); - let res1 = endpoint.connect(cfg1, remote_addr); - assert!(res1.is_ok(), "first SNAP connect should succeed"); - - // Second connect with same local_init collides on local_aid - let cfg2 = ClientConfig::new().with_snap(local_init, remote2); - let res2 = endpoint.connect(cfg2, remote_addr); - assert!( - matches!(res2, Err(ConnectError::Snap(SnapError::AidCollision { .. }))), - "second SNAP connect should fail due to AID collision" - ); -} - -#[test] -fn test_snap_rejects_local_init_ack() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let remote_init = generate_snap_token(&TransportConfig::default()).expect("remote init"); - let local_init_ack = ChunkInit { - is_ack: true, - initiate_tag: 1, - ..Default::default() - }; - let local_bytes = local_init_ack.marshal().expect("marshal local INIT-ACK"); - - let client_config = ClientConfig::new().with_snap(local_bytes, remote_init); - let res = endpoint.connect(client_config, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::InvalidInitAck { side: SnapSide::Local })) - ), - "local INIT-ACK should be rejected" - ); -} - -#[test] -fn test_snap_rejects_local_init_with_zero_initiate_tag() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let remote_init = generate_snap_token(&TransportConfig::default()).expect("remote init"); - let local_init = ChunkInit { - is_ack: false, - initiate_tag: 0, - ..Default::default() - }; - let local_bytes = local_init.marshal().expect("marshal local INIT"); - - let client_config = ClientConfig::new().with_snap(local_bytes, remote_init); - let res = endpoint.connect(client_config, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ZeroInitiateTag { side: SnapSide::Local })) - ), - "local INIT with initiate_tag=0 should be rejected" - ); -} - -// --------------------------------------------------------------------------- -// SNAP hardening tests: size limits, truncated / empty / oversized input, -// wrong chunk types, RFC field validation, round-trip token consistency. -// --------------------------------------------------------------------------- - -#[test] -fn test_snap_rejects_empty_bytes() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let valid = generate_snap_token(&TransportConfig::default()).expect("valid init"); - - // Empty remote - let cfg = ClientConfig::new().with_snap(valid.clone(), Bytes::new()); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Remote, - .. - })) - ), - "empty remote bytes should fail parsing" - ); - - // Empty local - let cfg = ClientConfig::new().with_snap(Bytes::new(), valid); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Local, - .. - })) - ), - "empty local bytes should fail parsing" - ); -} - -#[test] -fn test_snap_rejects_truncated_bytes() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let valid = generate_snap_token(&TransportConfig::default()).expect("valid init"); - - // Truncate to just 10 bytes - not enough for INIT header + fixed fields - let truncated = valid.slice(..10.min(valid.len())); - - let cfg = ClientConfig::new().with_snap(valid.clone(), truncated.clone()); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Remote, - .. - })) - ), - "truncated remote bytes should fail parsing" - ); - - let cfg = ClientConfig::new().with_snap(truncated, valid); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Local, - .. - })) - ), - "truncated local bytes should fail parsing" - ); -} - -#[test] -fn test_snap_rejects_oversized_bytes() { - use crate::vendor::sctp_proto::config::MAX_SNAP_INIT_BYTES; - - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let valid = generate_snap_token(&TransportConfig::default()).expect("valid init"); - let oversized = Bytes::from(vec![0u8; MAX_SNAP_INIT_BYTES + 1]); - - // Oversized remote - let cfg = ClientConfig::new().with_snap(valid.clone(), oversized.clone()); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::OversizedInit { - side: SnapSide::Remote, - .. - })) - ), - "oversized remote bytes should be rejected" - ); - - // Oversized local - let cfg = ClientConfig::new().with_snap(oversized, valid); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::OversizedInit { - side: SnapSide::Local, - .. - })) - ), - "oversized local bytes should be rejected" - ); -} - -#[test] -fn test_snap_rejects_remote_init_zero_inbound_streams() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let bad_remote = ChunkInit { - is_ack: false, - initiate_tag: 0xDEAD_BEEF, - initial_tsn: 1, - num_outbound_streams: 1, - num_inbound_streams: 0, // RFC violation - advertised_receiver_window_credit: 65535, - ..Default::default() - }; - let remote_bytes = bad_remote.marshal().expect("marshal bad remote INIT"); - - let cfg = ClientConfig::new().with_snap(local_init, remote_bytes); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::InvalidInit { - side: SnapSide::Remote, - .. - })) - ), - "remote INIT with num_inbound_streams=0 should be rejected: got {:?}", - res - ); -} - -#[test] -fn test_snap_rejects_remote_init_zero_outbound_streams() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let bad_remote = ChunkInit { - is_ack: false, - initiate_tag: 0xDEAD_BEEF, - initial_tsn: 1, - num_outbound_streams: 0, // RFC violation - num_inbound_streams: 1, - advertised_receiver_window_credit: 65535, - ..Default::default() - }; - let remote_bytes = bad_remote.marshal().expect("marshal bad remote INIT"); - - let cfg = ClientConfig::new().with_snap(local_init, remote_bytes); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::InvalidInit { - side: SnapSide::Remote, - .. - })) - ), - "remote INIT with num_outbound_streams=0 should be rejected: got {:?}", - res - ); -} - -#[test] -fn test_snap_rejects_remote_init_small_arwnd() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let bad_remote = ChunkInit { - is_ack: false, - initiate_tag: 0xDEAD_BEEF, - initial_tsn: 1, - num_outbound_streams: 1, - num_inbound_streams: 1, - advertised_receiver_window_credit: 100, // RFC says >= 1500 - ..Default::default() - }; - let remote_bytes = bad_remote.marshal().expect("marshal bad remote INIT"); - - let cfg = ClientConfig::new().with_snap(local_init, remote_bytes); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::InvalidInit { - side: SnapSide::Remote, - .. - })) - ), - "remote INIT with a_rwnd < 1500 should be rejected: got {:?}", - res - ); -} - -#[test] -fn test_snap_rejects_local_init_zero_inbound_streams() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let remote_init = generate_snap_token(&TransportConfig::default()).expect("remote init"); - let bad_local = ChunkInit { - is_ack: false, - initiate_tag: 0xCAFE_BABE, - initial_tsn: 1, - num_outbound_streams: 1, - num_inbound_streams: 0, - advertised_receiver_window_credit: 65535, - ..Default::default() - }; - let local_bytes = bad_local.marshal().expect("marshal bad local INIT"); - - let cfg = ClientConfig::new().with_snap(local_bytes, remote_init); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::InvalidInit { - side: SnapSide::Local, - .. - })) - ), - "local INIT with num_inbound_streams=0 should be rejected: got {:?}", - res - ); -} - -#[test] -fn test_snap_rejects_local_init_small_arwnd() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let remote_init = generate_snap_token(&TransportConfig::default()).expect("remote init"); - let bad_local = ChunkInit { - is_ack: false, - initiate_tag: 0xCAFE_BABE, - initial_tsn: 1, - num_outbound_streams: 1, - num_inbound_streams: 1, - advertised_receiver_window_credit: 0, - ..Default::default() - }; - let local_bytes = bad_local.marshal().expect("marshal bad local INIT"); - - let cfg = ClientConfig::new().with_snap(local_bytes, remote_init); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::InvalidInit { - side: SnapSide::Local, - .. - })) - ), - "local INIT with a_rwnd=0 should be rejected: got {:?}", - res - ); -} - -#[test] -fn test_snap_generate_token_roundtrip_is_valid() { - let config = TransportConfig::default(); - let bytes = generate_snap_token(&config).expect("generate token"); - - assert!( - bytes.len() <= crate::vendor::sctp_proto::config::MAX_SNAP_INIT_BYTES, - "generated token should be within MAX_SNAP_INIT_BYTES" - ); - - let init = ChunkInit::unmarshal(&bytes).expect("unmarshal generated token"); - assert!(!init.is_ack, "generated token should be INIT, not INIT-ACK"); - assert_ne!(init.initiate_tag, 0, "initiate_tag must not be zero"); - assert_ne!(init.initial_tsn, 0, "initial_tsn must not be zero"); - assert_eq!(init.num_outbound_streams, u16::MAX); - assert_eq!(init.num_inbound_streams, u16::MAX); - assert_eq!(init.advertised_receiver_window_credit, config.max_receive_buffer_size()); - - // check() should pass for a token we generated ourselves - init.check().expect("check() should pass on generated token"); -} - -#[test] -fn test_snap_generate_token_unique_per_call() { - let config = TransportConfig::default(); - let t1 = generate_snap_token(&config).expect("token 1"); - let t2 = generate_snap_token(&config).expect("token 2"); - assert_ne!(t1, t2, "two generated tokens should differ (random values)"); - - let i1 = ChunkInit::unmarshal(&t1).expect("parse t1"); - let i2 = ChunkInit::unmarshal(&t2).expect("parse t2"); - assert_ne!(i1.initiate_tag, i2.initiate_tag, "initiate_tags should differ"); -} - -#[test] -fn test_snap_rejects_wrong_chunk_type_bytes() { - use crate::vendor::sctp_proto::chunk::Chunk; - use crate::vendor::sctp_proto::chunk::chunk_selective_ack::ChunkSelectiveAck; - - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let valid = generate_snap_token(&TransportConfig::default()).expect("valid init"); - - // Build a SACK chunk and try to use it as a SNAP INIT - let sack = ChunkSelectiveAck { - cumulative_tsn_ack: 1, - advertised_receiver_window_credit: 65535, - gap_ack_blocks: vec![], - duplicate_tsn: vec![], - }; - let sack_bytes = sack.marshal().expect("marshal SACK"); - - let cfg = ClientConfig::new().with_snap(valid, sack_bytes); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Remote, - .. - })) - ), - "SACK bytes should fail to parse as INIT: got {:?}", - res - ); -} - -#[test] -fn test_snap_rejects_both_sides_empty() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let cfg = ClientConfig::new().with_snap(Bytes::new(), Bytes::new()); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!(res, Err(ConnectError::Snap(SnapError::ParseFailed { .. }))), - "two empty byte slices should fail" - ); -} - -#[test] -fn test_snap_rejects_random_garbage_bytes() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let valid = generate_snap_token(&TransportConfig::default()).expect("valid init"); - - // 50 bytes of pseudo-random garbage - let garbage = Bytes::from(vec![0xAB; 50]); - - let cfg = ClientConfig::new().with_snap(valid.clone(), garbage.clone()); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Remote, - .. - })) - ), - "garbage remote bytes should fail: got {:?}", - res - ); - - let cfg = ClientConfig::new().with_snap(garbage, valid); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!( - res, - Err(ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Local, - .. - })) - ), - "garbage local bytes should fail: got {:?}", - res - ); -} - -#[test] -fn test_snap_identical_local_and_remote_init() { - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let token = generate_snap_token(&TransportConfig::default()).expect("token"); - - let cfg = ClientConfig::new().with_snap(token.clone(), token); - let res = endpoint.connect(cfg, remote_addr); - assert!( - matches!(res, Err(ConnectError::Snap(SnapError::AidCollision { .. }))), - "same token for both sides should collide: got {:?}", - res - ); -} - -#[test] -fn test_snap_end_to_end_bidirectional_data() { - // Two endpoints, both using Endpoint::connect with SNAP, exchanging data - // through the full Endpoint::handle pipeline. - let endpoint_config = Arc::new(EndpointConfig::default()); - let transport = TransportConfig::default(); - - let init_a = generate_snap_token(&transport).expect("init A"); - let init_b = generate_snap_token(&transport).expect("init B"); - - let addr_a: SocketAddr = SocketAddr::new(Ipv6Addr::LOCALHOST.into(), CLIENT_PORTS.lock().unwrap().next().unwrap()); - let addr_b: SocketAddr = SocketAddr::new(Ipv6Addr::LOCALHOST.into(), CLIENT_PORTS.lock().unwrap().next().unwrap()); - - // Both sides are clients (no server config) - this is the SNAP model. - let mut ep_a = Endpoint::new(endpoint_config.clone(), None); - let mut ep_b = Endpoint::new(endpoint_config, None); - - let cfg_a = ClientConfig::new().with_snap(init_a.clone(), init_b.clone()); - let (ch_a, mut assoc_a) = ep_a.connect(cfg_a, addr_b).expect("SNAP connect A"); - - let cfg_b = ClientConfig::new().with_snap(init_b, init_a); - let (ch_b, mut assoc_b) = ep_b.connect(cfg_b, addr_a).expect("SNAP connect B"); - - // Both should be established immediately. - assert_eq!(assoc_a.state(), AssociationState::Established); - assert_eq!(assoc_b.state(), AssociationState::Established); - assert_matches!(assoc_a.poll(), Some(Event::Connected)); - assert_matches!(assoc_b.poll(), Some(Event::Connected)); - - let now = Instant::now(); - - // A writes to B. - let si = 1u16; - let msg_a = Bytes::from_static(b"hello from A"); - let mut stream_a = assoc_a - .open_stream(si, PayloadProtocolIdentifier::Binary) - .expect("open stream A"); - stream_a - .write_sctp(&msg_a, PayloadProtocolIdentifier::Binary) - .expect("write A"); - - // Pump transmits from A into B via Endpoint::handle. - while let Some(transmit) = assoc_a.poll_transmit(now) { - if let Payload::RawEncode(datagrams) = transmit.payload { - for dgram in datagrams { - if let Some((handle, event)) = ep_b.handle(now, addr_a, None, None, dgram) { - assert_eq!(handle, ch_b); - if let DatagramEvent::AssociationEvent(ev) = event { - assoc_b.handle_event(ev); - } - } - } - } - } - - // B should now have data. - let accepted = assoc_b.accept_stream().expect("accept stream on B"); - assert_eq!(accepted.stream_identifier, si); - - let mut buf = vec![0u8; 64]; - let chunks = assoc_b - .stream(si) - .expect("get stream B") - .read_sctp() - .expect("read B") - .expect("expected data"); - let n = chunks.read(&mut buf).expect("read payload"); - assert_eq!(&buf[..n], b"hello from A"); - - // B writes back to A. - let msg_b = Bytes::from_static(b"hello from B"); - assoc_b - .stream(si) - .expect("get stream B for write") - .write_sctp(&msg_b, PayloadProtocolIdentifier::Binary) - .expect("write B"); - - // Pump transmits from B into A. - while let Some(transmit) = assoc_b.poll_transmit(now) { - if let Payload::RawEncode(datagrams) = transmit.payload { - for dgram in datagrams { - if let Some((handle, event)) = ep_a.handle(now, addr_b, None, None, dgram) { - assert_eq!(handle, ch_a); - if let DatagramEvent::AssociationEvent(ev) = event { - assoc_a.handle_event(ev); - } - } - } - } - } - - // A should now have data back from B. - let chunks = assoc_a - .stream(si) - .expect("get stream A") - .read_sctp() - .expect("read A") - .expect("expected data from B"); - let n = chunks.read(&mut buf).expect("read payload from B"); - assert_eq!(&buf[..n], b"hello from B"); -} - -#[test] -fn test_snap_association_drains_cleanly() { - // Verify that a SNAP association, once drained, properly cleans up both - // association_ids and association_ids_init in the endpoint. - let mut endpoint = Endpoint::new(Arc::new(EndpointConfig::default()), None); - let remote_addr: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - - let local_init = generate_snap_token(&TransportConfig::default()).expect("local init"); - let remote_init = generate_snap_token(&TransportConfig::default()).expect("remote init"); - - let local_tag = ChunkInit::unmarshal(&local_init).expect("parse local").initiate_tag; - let remote_tag = ChunkInit::unmarshal(&remote_init).expect("parse remote").initiate_tag; - - let cfg = ClientConfig::new().with_snap(local_init, remote_init); - let (ch, _assoc) = endpoint.connect(cfg, remote_addr).expect("SNAP connect"); - - // Endpoint should have entries in both routing tables. - assert!( - endpoint.association_ids.contains_key(&local_tag), - "local_tag should be in association_ids" - ); - assert!( - endpoint.association_ids_init.contains_key(&remote_tag), - "remote_tag should be in association_ids_init" - ); - - // Simulate draining: send the Drained endpoint event. - let drain_event = EndpointEvent(EndpointEventInner::Drained); - endpoint.handle_event(ch, drain_event); - - // Both routing tables should be cleaned up. - assert!( - !endpoint.association_ids.contains_key(&local_tag), - "local_tag should be removed from association_ids after drain" - ); - assert!( - !endpoint.association_ids_init.contains_key(&remote_tag), - "remote_tag should be removed from association_ids_init after drain" - ); -} - -#[test] -#[ignore = "manual end-to-end transfer measurement"] -fn measure_queue_transfer() { - for (name, transfer) in [ - ("unfragmented", test_assoc_reliable_simple as fn() -> Result<()>), - ("fragmented", test_assoc_reliable_ordered_fragmented_then_defragmented), - ] { - let mut samples = Vec::new(); - for _ in 0..21 { - let start = Instant::now(); - transfer().unwrap(); - samples.push(start.elapsed().as_nanos()); - } - samples.sort_unstable(); - std::println!( - "{name}: median={} ns min={} max={}", - samples[10], - samples[0], - samples[20] - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/endpoint/mod.rs b/rs/moq-webrtc/src/vendor/sctp_proto/endpoint/mod.rs deleted file mode 100644 index b8cf2434502..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/endpoint/mod.rs +++ /dev/null @@ -1,688 +0,0 @@ -#[cfg(test)] -mod endpoint_test; - -use core::fmt; -use core::iter; -use core::net::{IpAddr, SocketAddr}; -use core::ops::{Index, IndexMut}; -use std::boxed::Box; -use std::collections::HashMap; -use std::collections::VecDeque; -use std::string::{String, ToString}; -use std::sync::Arc; -use std::time::Instant; - -use crate::vendor::sctp_proto::chunk::{chunk_init::ChunkInit, chunk_type::CT_INIT}; -use crate::vendor::sctp_proto::config::MAX_SNAP_INIT_BYTES; -use crate::vendor::sctp_proto::config::{ClientConfig, EndpointConfig, ServerConfig, TransportConfig}; -use crate::vendor::sctp_proto::packet::PartialDecode; -use crate::vendor::sctp_proto::shared::AssociationEvent; -use crate::vendor::sctp_proto::shared::{AssociationEventInner, AssociationId}; -use crate::vendor::sctp_proto::shared::{EndpointEvent, EndpointEventInner}; -use crate::vendor::sctp_proto::util::{AssociationIdGenerator, RandomAssociationIdGenerator}; -use crate::vendor::sctp_proto::{EcnCodepoint, Payload, Transmit}; -use crate::vendor::sctp_proto::{association::Association, chunk::Chunk}; - -use bytes::Bytes; -use rand::{SeedableRng, rngs::StdRng}; -use rustc_hash::FxHashMap; -use slab::Slab; -use thiserror::Error; -use tracing::{debug, trace, warn}; - -/// The main entry point to the library -/// -/// This object performs no I/O whatsoever. Instead, it generates a stream of packets to send via -/// `poll_transmit`, and consumes incoming packets and association-generated events via `handle` and -/// `handle_event`. -pub struct Endpoint { - rng: StdRng, - transmits: VecDeque, - /// Identifies associations based on the INIT Dst AID the peer utilized - /// - /// Uses a standard `HashMap` to protect against hash collision attacks. - association_ids_init: HashMap, - /// Identifies associations based on locally created CIDs - /// - /// Uses a cheaper hash function since keys are locally created - association_ids: FxHashMap, - - associations: Slab, - local_cid_generator: Box, - config: Arc, - server_config: Option>, - /// Whether incoming associations should be unconditionally rejected by a server - /// - /// Equivalent to a `ServerConfig.accept_buffer` of `0`, but can - /// be changed after the endpoint is constructed. - reject_new_associations: bool, -} - -impl fmt::Debug for Endpoint { - fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { - fmt.debug_struct("Endpoint") - .field("rng", &self.rng) - .field("transmits", &self.transmits) - .field("association_ids_initial", &self.association_ids_init) - .field("association_ids", &self.association_ids) - .field("associations", &self.associations) - .field("config", &self.config) - .field("server_config", &self.server_config) - .field("reject_new_associations", &self.reject_new_associations) - .finish() - } -} - -impl Endpoint { - /// Create a new endpoint - /// - /// Returns `Err` if the configuration is invalid. - pub fn new(config: Arc, server_config: Option>) -> Self { - let rng = { - let mut base = rand::rng(); - StdRng::from_rng(&mut base) - }; - Self { - rng, - transmits: VecDeque::new(), - association_ids_init: HashMap::default(), - association_ids: FxHashMap::default(), - associations: Slab::new(), - local_cid_generator: (config.aid_generator_factory.as_ref())(), - reject_new_associations: false, - config, - server_config, - } - } - - /// Get the next packet to transmit - #[must_use] - pub fn poll_transmit(&mut self) -> Option { - self.transmits.pop_front() - } - - /// Replace the server configuration, affecting new incoming associations only - pub fn set_server_config(&mut self, server_config: Option>) { - self.server_config = server_config; - } - - /// Process `EndpointEvent`s emitted from related `Association`s - /// - /// In turn, processing this event may return a `AssociationEvent` for the same `Association`. - pub fn handle_event(&mut self, ch: AssociationHandle, event: EndpointEvent) -> Option { - match event.0 { - EndpointEventInner::Drained => { - let conn = self.associations.remove(ch.0); - self.association_ids_init.remove(&conn.init_cid); - for cid in conn.loc_cids.values() { - self.association_ids.remove(cid); - } - } - } - None - } - - /// Process an incoming UDP datagram - pub fn handle( - &mut self, - now: Instant, - remote: SocketAddr, - local_ip: Option, - ecn: Option, - data: Bytes, - ) -> Option<(AssociationHandle, DatagramEvent)> { - let partial_decode = match PartialDecode::unmarshal(&data) { - Ok(x) => x, - Err(err) => { - trace!("malformed header: {}", err); - return None; - } - }; - - // - // Handle packet on existing association, if any - // - let dst_cid = partial_decode.common_header.verification_tag; - let known_ch = if dst_cid > 0 { - self.association_ids.get(&dst_cid).cloned() - } else { - //TODO: improve INIT handling for DoS attack - if partial_decode.first_chunk_type == CT_INIT { - if let Some(dst_cid) = partial_decode.initiate_tag { - self.association_ids_init.get(&dst_cid).cloned() - } else { - None - } - } else { - None - } - }; - - if let Some(ch) = known_ch { - return Some(( - ch, - DatagramEvent::AssociationEvent(AssociationEvent(AssociationEventInner::Datagram(Transmit { - now, - remote, - ecn, - payload: Payload::PartialDecode(partial_decode), - local_ip, - }))), - )); - } - - // - // Potentially create a new association - // - self.handle_first_packet(now, remote, local_ip, ecn, partial_decode) - .map(|(ch, a)| (ch, DatagramEvent::NewAssociation(a))) - } - - /// Initiate an association. - /// - /// If SNAP tokens (INIT chunks) are provided via [`ClientConfig::with_snap`], - /// the association will skip the SCTP 4-way handshake (RFC 4960 Section 5.1) - /// and immediately transition to the ESTABLISHED state. - /// - /// Both `local_sctp_init` and `remote_sctp_init` must be provided for SNAP; - /// use [`generate_snap_token`](crate::vendor::sctp_proto::generate_snap_token) to create the - /// local token. - /// - /// If only one side is set (e.g. the peer does not support SNAP), the - /// association falls back to the normal SCTP handshake. - /// - /// **Note:** When using SNAP, **both** peers must call [`Endpoint::connect`] - /// (there is no server-side SNAP via [`Endpoint::handle`]). Each peer - /// generates its own token via [`generate_snap_token`](crate::vendor::sctp_proto::generate_snap_token), - /// exchanges it with the remote peer through a signaling channel (e.g., - /// SDP `a=sctp-init`), and then calls `connect` with `with_snap(local, remote)`. - /// - /// See [draft-hancke-tsvwg-snap-01](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). - pub fn connect( - &mut self, - config: ClientConfig, - remote: SocketAddr, - ) -> Result<(AssociationHandle, Association), ConnectError> { - if self.is_full() { - return Err(ConnectError::TooManyAssociations); - } - if remote.port() == 0 { - return Err(ConnectError::InvalidRemoteAddress(remote)); - } - if config.transport.local_port() == 0 || config.transport.remote_port() == 0 { - return Err(ConnectError::InvalidSctpPort); - } - - match (config.local_sctp_init, config.remote_sctp_init) { - (Some(local_init), Some(remote_init)) => { - self.connect_with_snap(config.transport, remote, local_init, remote_init) - } - (partial_local, partial_remote) => { - if partial_local.is_some() || partial_remote.is_some() { - warn!( - "partial SNAP config: both local_sctp_init and \ - remote_sctp_init must be set; falling back to normal handshake" - ); - } - let remote_aid = RandomAssociationIdGenerator::new().generate_aid(); - let local_aid = self.new_aid(); - - Ok(self.add_association( - remote_aid, - local_aid, - remote, - None, - Instant::now(), - None, - config.transport, - )) - } - } - } - - /// Create an association using SNAP (out-of-band exchanged INIT chunks). - fn connect_with_snap( - &mut self, - transport: Arc, - remote: SocketAddr, - local_snap_bytes: Bytes, - remote_snap_bytes: Bytes, - ) -> Result<(AssociationHandle, Association), ConnectError> { - // Enforce a size ceiling on raw INIT bytes before parsing. - if local_snap_bytes.len() > MAX_SNAP_INIT_BYTES { - return Err(ConnectError::Snap(SnapError::OversizedInit { - side: SnapSide::Local, - len: local_snap_bytes.len(), - })); - } - if remote_snap_bytes.len() > MAX_SNAP_INIT_BYTES { - return Err(ConnectError::Snap(SnapError::OversizedInit { - side: SnapSide::Remote, - len: remote_snap_bytes.len(), - })); - } - - let local_init = ChunkInit::unmarshal(&local_snap_bytes).map_err(|err| { - ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Local, - reason: err.to_string(), - }) - })?; - let remote_init = ChunkInit::unmarshal(&remote_snap_bytes).map_err(|err| { - ConnectError::Snap(SnapError::ParseFailed { - side: SnapSide::Remote, - reason: err.to_string(), - }) - })?; - - // Validate both chunks are INIT (not INIT-ACK) - if local_init.is_ack { - return Err(ConnectError::Snap(SnapError::InvalidInitAck { side: SnapSide::Local })); - } - if remote_init.is_ack { - return Err(ConnectError::Snap(SnapError::InvalidInitAck { side: SnapSide::Remote })); - } - - let local_aid = local_init.initiate_tag; - let remote_aid = remote_init.initiate_tag; - - // RFC 4960 Section 3.3.2: The Initiate Tag MUST NOT take the value 0. - if local_aid == 0 { - return Err(ConnectError::Snap(SnapError::ZeroInitiateTag { side: SnapSide::Local })); - } - if remote_aid == 0 { - return Err(ConnectError::Snap(SnapError::ZeroInitiateTag { - side: SnapSide::Remote, - })); - } - - // initial_tsn=0 is degenerate: wrapping_sub(1) yields u32::MAX for - // peer_last_tsn, which would accept nearly all incoming TSNs. - if local_init.initial_tsn == 0 { - return Err(ConnectError::Snap(SnapError::ZeroInitialTsn { side: SnapSide::Local })); - } - if remote_init.initial_tsn == 0 { - return Err(ConnectError::Snap(SnapError::ZeroInitialTsn { side: SnapSide::Remote })); - } - - // RFC 4960 §3.3.2 / §5.1: validate stream counts, a_rwnd, etc. - local_init.check().map_err(|err| { - ConnectError::Snap(SnapError::InvalidInit { - side: SnapSide::Local, - reason: err.to_string(), - }) - })?; - remote_init.check().map_err(|err| { - ConnectError::Snap(SnapError::InvalidInit { - side: SnapSide::Remote, - reason: err.to_string(), - }) - })?; - - // Check for collision BEFORE allocating any resources. - if local_aid == remote_aid { - return Err(ConnectError::Snap(SnapError::AidCollision { - kind: AidCollisionKind::LocalEqualsRemote, - aid: local_aid, - })); - } - if self.association_ids.contains_key(&local_aid) { - return Err(ConnectError::Snap(SnapError::AidCollision { - kind: AidCollisionKind::LocalInAssociationIds, - aid: local_aid, - })); - } - if self.association_ids.contains_key(&remote_aid) { - return Err(ConnectError::Snap(SnapError::AidCollision { - kind: AidCollisionKind::RemoteInAssociationIds, - aid: remote_aid, - })); - } - if self.association_ids_init.contains_key(&remote_aid) { - return Err(ConnectError::Snap(SnapError::AidCollision { - kind: AidCollisionKind::RemoteInAssociationIdsInit, - aid: remote_aid, - })); - } - if self.association_ids_init.contains_key(&local_aid) { - return Err(ConnectError::Snap(SnapError::AidCollision { - kind: AidCollisionKind::LocalInAssociationIdsInit, - aid: local_aid, - })); - } - - let conn = Association::new_with_out_of_band_init( - transport, - self.config.get_max_payload_size(), - remote, - None, - local_init, - remote_init, - ) - .map_err(|err| ConnectError::Snap(SnapError::AssociationFailed(err.to_string())))?; - - let id = self.associations.insert(AssociationMeta { - init_cid: remote_aid, - cids_issued: 1, - loc_cids: iter::once((0, local_aid)).collect(), - initial_remote: remote, - }); - - let ch = AssociationHandle(id); - self.association_ids.insert(local_aid, ch); - self.association_ids_init.insert(remote_aid, ch); - - debug!( - "Created SNAP association: local_aid={:#x} remote_aid={:#x}", - local_aid, remote_aid - ); - - Ok((ch, conn)) - } - - fn new_aid(&mut self) -> AssociationId { - loop { - let aid = self.local_cid_generator.generate_aid(); - if !self.association_ids.contains_key(&aid) { - break aid; - } - } - } - - fn handle_first_packet( - &mut self, - now: Instant, - remote: SocketAddr, - local_ip: Option, - ecn: Option, - partial_decode: PartialDecode, - ) -> Option<(AssociationHandle, Association)> { - if partial_decode.first_chunk_type != CT_INIT - || (partial_decode.first_chunk_type == CT_INIT && partial_decode.initiate_tag.is_none()) - { - debug!("refusing first packet with Non-INIT or emtpy initial_tag INIT"); - return None; - } - - let server_config = self.server_config.as_ref().unwrap(); - - if self.associations.len() >= server_config.concurrent_associations as usize - || self.reject_new_associations - || self.is_full() - { - debug!("refusing association"); - //TODO: self.initial_close(); - return None; - } - - let server_config = server_config.clone(); - let transport_config = server_config.transport.clone(); - - let remote_aid = *partial_decode.initiate_tag.as_ref().unwrap(); - let local_aid = self.new_aid(); - - let (ch, mut conn) = self.add_association( - remote_aid, - local_aid, - remote, - local_ip, - now, - Some(server_config), - transport_config, - ); - - // Map the peer's INIT Initiate Tag so that retransmitted INITs (which use - // verification_tag=0) can be routed to the association created for the first INIT. - self.association_ids_init.insert(remote_aid, ch); - - conn.handle_event(AssociationEvent(AssociationEventInner::Datagram(Transmit { - now, - remote, - ecn, - payload: Payload::PartialDecode(partial_decode), - local_ip, - }))); - - Some((ch, conn)) - } - - #[allow(clippy::too_many_arguments)] - fn add_association( - &mut self, - remote_aid: AssociationId, - local_aid: AssociationId, - remote_addr: SocketAddr, - local_ip: Option, - now: Instant, - server_config: Option>, - transport_config: Arc, - ) -> (AssociationHandle, Association) { - let conn = Association::new( - server_config, - transport_config, - self.config.get_max_payload_size(), - local_aid, - remote_addr, - local_ip, - now, - ); - - let id = self.associations.insert(AssociationMeta { - init_cid: remote_aid, - cids_issued: 1, - loc_cids: iter::once((0, local_aid)).collect(), - initial_remote: remote_addr, - }); - - let ch = AssociationHandle(id); - self.association_ids.insert(local_aid, ch); - - (ch, conn) - } - - /// Unconditionally reject future incoming associations - pub fn reject_new_associations(&mut self) { - self.reject_new_associations = true; - } - - /// Access the configuration used by this endpoint - pub fn config(&self) -> &EndpointConfig { - &self.config - } - - /// Whether we've used up 3/4 of the available AID space - fn is_full(&self) -> bool { - (((u32::MAX >> 1) + (u32::MAX >> 2)) as usize) < self.association_ids.len() - } -} - -#[derive(Debug)] -pub(crate) struct AssociationMeta { - init_cid: AssociationId, - /// Number of local association IDs. - cids_issued: u64, - loc_cids: FxHashMap, - /// Remote address the association began with - /// - /// Only needed to support associations with zero-length AIDs, which cannot migrate, so we don't - /// bother keeping it up to date. - initial_remote: SocketAddr, -} - -/// Internal identifier for an `Association` currently associated with an endpoint -#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd)] -pub struct AssociationHandle(pub usize); - -impl From for usize { - fn from(x: AssociationHandle) -> usize { - x.0 - } -} - -impl Index for Slab { - type Output = AssociationMeta; - fn index(&self, ch: AssociationHandle) -> &AssociationMeta { - &self[ch.0] - } -} - -impl IndexMut for Slab { - fn index_mut(&mut self, ch: AssociationHandle) -> &mut AssociationMeta { - &mut self[ch.0] - } -} - -/// Event resulting from processing a single datagram -#[allow(clippy::large_enum_variant)] // Not passed around extensively -pub enum DatagramEvent { - /// The datagram is redirected to its `Association` - AssociationEvent(AssociationEvent), - /// The datagram has resulted in starting a new `Association` - NewAssociation(Association), -} - -/// Errors in the parameters being used to create a new association -/// -/// These arise before any I/O has been performed. -#[non_exhaustive] -#[derive(Debug, Error, Clone, PartialEq, Eq)] -pub enum ConnectError { - /// The endpoint can no longer create new associations - /// - /// Indicates that a necessary component of the endpoint has been dropped or otherwise disabled. - #[error("endpoint stopping")] - EndpointStopping, - /// The number of active associations on the local endpoint is at the limit - /// - /// Try using longer association IDs. - #[error("too many associations")] - TooManyAssociations, - /// The domain name supplied was malformed - #[error("invalid DNS name: {0}")] - InvalidDnsName(String), - /// The remote [`SocketAddr`] supplied was malformed - /// - /// Examples include attempting to connect to port 0, or using an inappropriate address family. - #[error("invalid remote address: {0}")] - InvalidRemoteAddress(SocketAddr), - /// The configured SCTP source or destination port is zero. - #[error("SCTP source and destination ports must be nonzero")] - InvalidSctpPort, - /// No default client configuration was set up - /// - /// Use `Endpoint::connect_with` to specify a client configuration. - #[error("no default client config")] - NoDefaultClientConfig, - /// Out-of-band SNAP setup error. - #[error("SNAP error: {0}")] - Snap(#[from] SnapError), -} - -/// Which peer's token (INIT chunk) caused a [`SnapError`]. -#[non_exhaustive] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum SnapSide { - /// The locally-generated token. - Local, - /// The remote peer's token. - Remote, -} - -impl fmt::Display for SnapSide { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - SnapSide::Local => f.write_str("local"), - SnapSide::Remote => f.write_str("remote"), - } - } -} - -/// Which routing table detected an association-ID collision in [`SnapError::AidCollision`]. -#[non_exhaustive] -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AidCollisionKind { - /// The local and remote association IDs are equal. - LocalEqualsRemote, - /// The local AID is already present in `association_ids`. - LocalInAssociationIds, - /// The remote AID is already present in `association_ids`. - RemoteInAssociationIds, - /// The remote AID is already present in `association_ids_init`. - RemoteInAssociationIdsInit, - /// The local AID is already present in `association_ids_init`. - LocalInAssociationIdsInit, -} - -impl fmt::Display for AidCollisionKind { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - AidCollisionKind::LocalEqualsRemote => f.write_str("local_aid equals remote_aid"), - AidCollisionKind::LocalInAssociationIds => f.write_str("local_aid in association_ids"), - AidCollisionKind::RemoteInAssociationIds => f.write_str("remote_aid in association_ids"), - AidCollisionKind::RemoteInAssociationIdsInit => f.write_str("remote_aid in association_ids_init"), - AidCollisionKind::LocalInAssociationIdsInit => f.write_str("local_aid in association_ids_init"), - } - } -} - -/// Specific errors that can occur during SNAP (out-of-band token) setup. -/// -/// These are not part of the stable API - match on [`ConnectError::Snap`] -/// and use the `Display` impl for user-facing messages. -#[non_exhaustive] -#[derive(Debug, Error, Clone, PartialEq, Eq)] -pub enum SnapError { - /// Failed to parse token (INIT chunk) bytes. - #[error("failed to parse {side} SNAP token: {reason}")] - ParseFailed { - /// Which side's token failed to parse. - side: SnapSide, - /// The underlying parse error message. - reason: String, - }, - /// The provided bytes were an INIT-ACK, not an INIT. - #[error("invalid {side} SNAP token: expected INIT, got INIT-ACK")] - InvalidInitAck { - /// Which side provided an INIT-ACK instead of an INIT. - side: SnapSide, - }, - /// The token's `initiate_tag` is zero (RFC 4960 §3.3.2 violation). - #[error("{side} SNAP token has zero initiate_tag")] - ZeroInitiateTag { - /// Which side has the zero tag. - side: SnapSide, - }, - /// The token's `initial_tsn` is zero. - #[error("{side} SNAP token has zero initial_tsn")] - ZeroInitialTsn { - /// Which side has the zero TSN. - side: SnapSide, - }, - /// An association ID collision was detected. - #[error("SNAP collision: {kind} {aid:#x} already in use")] - AidCollision { - /// Which routing table collided. - kind: AidCollisionKind, - /// The colliding association ID. - aid: u32, - }, - /// The token (INIT chunk) bytes exceed the maximum allowed size. - #[error("{side} SNAP token too large: {len} bytes (max {max})", max = MAX_SNAP_INIT_BYTES)] - OversizedInit { - /// Which side sent oversized bytes. - side: SnapSide, - /// Actual byte length. - len: usize, - }, - /// The parsed token (INIT chunk) failed RFC 4960 validation. - #[error("invalid {side} SNAP token: {reason}")] - InvalidInit { - /// Which side has the invalid token. - side: SnapSide, - /// The underlying validation error message. - reason: String, - }, - /// Association creation failed. - #[error("failed to create SNAP association: {0}")] - AssociationFailed(String), -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/error.rs b/rs/moq-webrtc/src/vendor/sctp_proto/error.rs deleted file mode 100644 index 6c76a7c3d48..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/error.rs +++ /dev/null @@ -1,241 +0,0 @@ -use thiserror::Error; - -use std::string::String; - -pub type Result = core::result::Result; - -/// Errors triggered during SCTP association operation -#[derive(Debug, Error, Eq, Clone, PartialEq)] -#[non_exhaustive] -pub enum Error { - #[error("raw is too small for a SCTP chunk")] - ErrChunkHeaderTooSmall, - #[error("not enough data left in SCTP packet to satisfy requested length")] - ErrChunkHeaderNotEnoughSpace, - #[error("chunk PADDING is non-zero at offset")] - ErrChunkHeaderPaddingNonZero, - #[error("chunk has invalid length")] - ErrChunkHeaderInvalidLength, - - #[error("ChunkType is not of type ABORT")] - ErrChunkTypeNotAbort, - #[error("failed build Abort Chunk")] - ErrBuildAbortChunkFailed, - #[error("ChunkType is not of type COOKIEACK")] - ErrChunkTypeNotCookieAck, - #[error("ChunkType is not of type COOKIEECHO")] - ErrChunkTypeNotCookieEcho, - #[error("ChunkType is not of type ctError")] - ErrChunkTypeNotCt, - #[error("failed build Error Chunk")] - ErrBuildErrorChunkFailed, - #[error("failed to marshal stream")] - ErrMarshalStreamFailed, - #[error("chunk too short")] - ErrChunkTooShort, - #[error("ChunkType is not of type ForwardTsn")] - ErrChunkTypeNotForwardTsn, - #[error("ChunkType is not of type HEARTBEAT")] - ErrChunkTypeNotHeartbeat, - #[error("ChunkType is not of type HEARTBEATACK")] - ErrChunkTypeNotHeartbeatAck, - #[error("heartbeat is not long enough to contain Heartbeat Info")] - ErrHeartbeatNotLongEnoughInfo, - #[error("failed to parse param type")] - ErrParseParamTypeFailed, - #[error("heartbeat should only have HEARTBEAT param")] - ErrHeartbeatParam, - #[error("failed unmarshalling param in Heartbeat Chunk")] - ErrHeartbeatChunkUnmarshal, - #[error("unimplemented")] - ErrUnimplemented, - #[error("heartbeat Ack must have one param")] - ErrHeartbeatAckParams, - #[error("heartbeat Ack must have one param, and it should be a HeartbeatInfo")] - ErrHeartbeatAckNotHeartbeatInfo, - #[error("unable to marshal parameter for Heartbeat Ack")] - ErrHeartbeatAckMarshalParam, - - #[error("raw is too small for error cause")] - ErrErrorCauseTooSmall, - - #[error("unhandled ParamType: {typ}")] - ErrParamTypeUnhandled { typ: u16 }, - - #[error("unexpected ParamType")] - ErrParamTypeUnexpected, - - #[error("param header too short")] - ErrParamHeaderTooShort, - #[error("param self reported length is shorter than header length")] - ErrParamHeaderSelfReportedLengthShorter, - #[error("param self reported length is longer than header length")] - ErrParamHeaderSelfReportedLengthLonger, - #[error("failed to parse param type")] - ErrParamHeaderParseFailed, - - #[error("packet to short")] - ErrParamPacketTooShort, - #[error("outgoing SSN reset request parameter too short")] - ErrSsnResetRequestParamTooShort, - #[error("outgoing SSN reset request parameter has an invalid length")] - ErrSsnResetRequestParamInvalidLength, - #[error("reconfig response parameter too short")] - ErrReconfigRespParamTooShort, - #[error("supported address types parameter has an invalid length")] - ErrSupportedAddressTypesParamInvalidLength, - #[error("invalid algorithm type")] - ErrInvalidAlgorithmType, - - #[error("failed to parse param type")] - ErrInitChunkParseParamTypeFailed, - #[error("failed unmarshalling param in Init Chunk")] - ErrInitChunkUnmarshalParam, - #[error("unable to marshal parameter for INIT/INITACK")] - ErrInitAckMarshalParam, - - #[error("ChunkType is not of type INIT")] - ErrChunkTypeNotTypeInit, - #[error("chunk Value isn't long enough for mandatory parameters exp")] - ErrChunkValueNotLongEnough, - #[error("ChunkType of type INIT flags must be all 0")] - ErrChunkTypeInitFlagZero, - #[error("failed to unmarshal INIT body")] - ErrChunkTypeInitUnmarshalFailed, - #[error("failed marshaling INIT common data")] - ErrChunkTypeInitMarshalFailed, - #[error("ChunkType of type INIT ACK InitiateTag must not be 0")] - ErrChunkTypeInitInitiateTagZero, - #[error("INIT ACK inbound stream request must be > 0")] - ErrInitInboundStreamRequestZero, - #[error("INIT ACK outbound stream request must be > 0")] - ErrInitOutboundStreamRequestZero, - #[error("INIT ACK Advertised Receiver Window Credit (a_rwnd) must be >= 1500")] - ErrInitAdvertisedReceiver1500, - - #[error("packet is smaller than the header size")] - ErrChunkPayloadSmall, - #[error("ChunkType is not of type PayloadData")] - ErrChunkTypeNotPayloadData, - #[error("ChunkType is not of type Reconfig")] - ErrChunkTypeNotReconfig, - #[error("ChunkReconfig has invalid ParamA")] - ErrChunkReconfigInvalidParamA, - #[error("ChunkReconfig has an unsupported parameter combination")] - ErrChunkReconfigInvalidParamCombination, - - #[error("failed to parse param type")] - ErrChunkParseParamTypeFailed, - #[error("unable to marshal parameter A for reconfig")] - ErrChunkMarshalParamAReconfigFailed, - #[error("unable to marshal parameter B for reconfig")] - ErrChunkMarshalParamBReconfigFailed, - - #[error("ChunkType is not of type SACK")] - ErrChunkTypeNotSack, - #[error("SACK Chunk size is not large enough to contain header")] - ErrSackSizeNotLargeEnoughInfo, - - #[error("invalid chunk size")] - ErrInvalidChunkSize, - #[error("ChunkType is not of type SHUTDOWN")] - ErrChunkTypeNotShutdown, - - #[error("ChunkType is not of type SHUTDOWN-ACK")] - ErrChunkTypeNotShutdownAck, - #[error("ChunkType is not of type SHUTDOWN-COMPLETE")] - ErrChunkTypeNotShutdownComplete, - - #[error("raw is smaller than the minimum length for a SCTP packet")] - ErrPacketRawTooSmall, - #[error("unable to parse SCTP chunk, not enough data for complete header")] - ErrParseSctpChunkNotEnoughData, - #[error("failed to unmarshal, contains unknown chunk type")] - ErrUnmarshalUnknownChunkType, - #[error("checksum mismatch theirs")] - ErrChecksumMismatch, - - #[error("unexpected chunk popped (unordered)")] - ErrUnexpectedChuckPoppedUnordered, - #[error("unexpected chunk popped (ordered)")] - ErrUnexpectedChuckPoppedOrdered, - #[error("unexpected q state (should've been selected)")] - ErrUnexpectedQState, - #[error("receive buffer exhausted during message reassembly")] - ErrReceiveBufferExhausted, - #[error("try again")] - ErrTryAgain, - - #[error("abort chunk, with following errors: {0}")] - ErrAbortChunk(String), - #[error("shutdown called in non-Established state")] - ErrShutdownNonEstablished, - #[error("association closed before connecting")] - ErrAssociationClosedBeforeConn, - #[error("association init failed")] - ErrAssociationInitFailed, - #[error("association handshake closed")] - ErrAssociationHandshakeClosed, - #[error("silently discard")] - ErrSilentlyDiscard, - #[error("the init not stored to send")] - ErrInitNotStoredToSend, - #[error("cookieEcho not stored to send")] - ErrCookieEchoNotStoredToSend, - #[error("sctp packet must not have a source port of 0")] - ErrSctpPacketSourcePortZero, - #[error("sctp packet must not have a destination port of 0")] - ErrSctpPacketDestinationPortZero, - #[error("init chunk must not be bundled with any other chunk")] - ErrInitChunkBundled, - #[error("init chunk expects a verification tag of 0 on the packet when out-of-the-blue")] - ErrInitChunkVerifyTagNotZero, - #[error("todo: handle Init when in state")] - ErrHandleInitState, - #[error("no cookie in InitAck")] - ErrInitAckNoCookie, - #[error("there already exists a stream with identifier")] - ErrStreamAlreadyExist, - #[error("stream ID has a pending RE-CONFIG and cannot be reused yet")] - ErrStreamResetPending, - #[error("Failed to create a stream with identifier")] - ErrStreamCreateFailed, - #[error("unable to be popped from inflight queue TSN")] - ErrInflightQueueTsnPop, - #[error("requested non-existent TSN")] - ErrTsnRequestNotExist, - #[error("sending reset packet in non-Established state")] - ErrResetPacketInStateNotExist, - #[error("unexpected parameter type")] - ErrParameterType, - #[error("sending payload data in non-Established state")] - ErrPayloadDataStateNotExist, - #[error("unhandled chunk type")] - ErrChunkTypeUnhandled, - #[error("handshake failed (INIT ACK)")] - ErrHandshakeInitAck, - #[error("handshake failed (COOKIE ECHO)")] - ErrHandshakeCookieEcho, - - #[error("outbound packet larger than maximum message size")] - ErrOutboundPacketTooLarge, - #[error("inbound packet larger than maximum message size")] - ErrInboundPacketTooLarge, - #[error("Stream closed")] - ErrStreamClosed, - #[error("Stream not existed")] - ErrStreamNotExisted, - #[error("Short buffer to be filled")] - ErrShortBuffer, - #[error("Io EOF")] - ErrEof, - #[error("Invalid SystemTime")] - ErrInvalidSystemTime, - #[error("Net Conn read error")] - ErrNetConnRead, - #[error("Max Data Channel ID")] - ErrMaxDataChannelID, - - #[error("{0}")] - Other(String), -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/lib.rs b/rs/moq-webrtc/src/vendor/sctp_proto/lib.rs deleted file mode 100644 index 391fd7eda76..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/lib.rs +++ /dev/null @@ -1,183 +0,0 @@ -//! Low-level protocol logic for the SCTP protocol -//! -//! sctp-proto contains a fully deterministic implementation of SCTP protocol logic. It contains -//! no networking code and does not get any relevant timestamps from the operating system. Most -//! users may want to use the futures-based sctp-async API instead. -//! -//! The main entry point is [Endpoint], which manages associations for a single socket. Use -//! [Endpoint::connect] to initiate outgoing associations, or provide a [ServerConfig] to -//! accept incoming ones. Incoming UDP datagrams are fed to [Endpoint::handle], which either -//! creates a new [Association] or returns an event to pass to an existing one. -//! -//! [Association] holds the protocol state for a single SCTP association. It produces -//! [Event]s and outgoing packets via polling methods ([Association::poll], -//! [Association::poll_transmit]). Each association contains multiple [Stream]s for -//! reading and writing data. -//! -//! [Endpoint]: https://docs.rs/sctp-proto/latest/sctp_proto/struct.Endpoint.html -//! [Endpoint::connect]: https://docs.rs/sctp-proto/latest/sctp_proto/struct.Endpoint.html#method.connect -//! [Endpoint::handle]: https://docs.rs/sctp-proto/latest/sctp_proto/struct.Endpoint.html#method.handle -//! [ServerConfig]: https://docs.rs/sctp-proto/latest/sctp_proto/struct.ServerConfig.html -//! [Association]: https://docs.rs/sctp-proto/latest/sctp_proto/struct.Association.html -//! [Association::poll]: https://docs.rs/sctp-proto/latest/sctp_proto/struct.Association.html#method.poll -//! [Association::poll_transmit]: -//! https://docs.rs/sctp-proto/latest/sctp_proto/struct.Association.html#method.poll_transmit -//! [Event]: https://docs.rs/sctp-proto/latest/sctp_proto/enum.Event.html -//! [Stream]: https://docs.rs/sctp-proto/latest/sctp_proto/struct.Stream.html -//! -//! ## Status -//! -//! This crate is maintained by the [str0m] project, which has been using it since -//! January 2023. Other consumers include [ex_sctp] for Elixir WebRTC. The crate -//! is kept in sync with [rtc-sctp] where possible to share bug fixes. -//! -//! Originally written by Rain Liu as a Sans-IO implementation of SCTP for the -//! webrtc-rs ecosystem, this crate predates `rtc-sctp` in the `webrtc-rs/rtc` -//! monorepo, which was later derived from this work. Maintenance was transferred -//! to the str0m maintainers in January 2026. -//! -//! [str0m]: https://crates.io/crates/str0m -//! [ex_sctp]: https://github.com/elixir-webrtc/ex_sctp -//! [rtc-sctp]: https://github.com/webrtc-rs/rtc/tree/master/rtc-sctp - -#![allow(dead_code)] -#![allow(clippy::bool_to_int_with_if)] -#![forbid(unsafe_code)] - -use bytes::Bytes; -use core::fmt; -use core::net::{IpAddr, SocketAddr}; -use core::ops; -use std::time::Instant; -use std::vec::Vec; - -mod association; -pub use crate::vendor::sctp_proto::association::Association; -pub use crate::vendor::sctp_proto::association::AssociationError; -pub use crate::vendor::sctp_proto::association::Event; -pub use crate::vendor::sctp_proto::association::stats::AssociationStats; -pub use crate::vendor::sctp_proto::association::stream::{ - DataChannelStats, ReliabilityType, Stream, StreamEvent, StreamId, StreamResetError, StreamState, -}; - -pub(crate) mod chunk; -pub use crate::vendor::sctp_proto::chunk::ErrorCauseCode; -pub use crate::vendor::sctp_proto::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier}; - -mod config; -pub use crate::vendor::sctp_proto::config::{ - ClientConfig, DEFAULT_SCTP_PORT, EndpointConfig, MAX_SNAP_INIT_BYTES, ServerConfig, TransportConfig, - generate_snap_token, -}; - -mod endpoint; -pub use crate::vendor::sctp_proto::endpoint::{ - AidCollisionKind, AssociationHandle, ConnectError, DatagramEvent, Endpoint, SnapError, SnapSide, -}; - -mod error; -pub use crate::vendor::sctp_proto::error::Error; - -mod packet; - -mod shared; -pub use crate::vendor::sctp_proto::shared::{AssociationEvent, AssociationId, EcnCodepoint, EndpointEvent}; - -pub(crate) mod param; - -pub(crate) mod queue; -pub use crate::vendor::sctp_proto::queue::reassembly_queue::{Chunk, Chunks}; - -pub(crate) mod util; - -/// Whether an endpoint was the initiator of an association -#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Default)] -pub enum Side { - /// The initiator of an association - #[default] - Client = 0, - /// The acceptor of an association - Server = 1, -} - -impl fmt::Display for Side { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - Side::Client => "Client", - Side::Server => "Server", - }; - write!(f, "{}", s) - } -} - -impl Side { - #[inline] - /// Shorthand for `self == Side::Client` - pub fn is_client(self) -> bool { - self == Side::Client - } - - #[inline] - /// Shorthand for `self == Side::Server` - pub fn is_server(self) -> bool { - self == Side::Server - } -} - -impl ops::Not for Side { - type Output = Side; - fn not(self) -> Side { - match self { - Side::Client => Side::Server, - Side::Server => Side::Client, - } - } -} - -use crate::vendor::sctp_proto::packet::PartialDecode; - -/// Payload in Incoming/outgoing Transmit -#[derive(Debug)] -pub enum Payload { - PartialDecode(PartialDecode), - RawEncode(Vec), -} - -/// Incoming/outgoing Transmit -#[derive(Debug)] -pub struct Transmit { - /// Received/Sent time - pub now: Instant, - /// The socket this datagram should be sent to - pub remote: SocketAddr, - /// Explicit congestion notification bits to set on the packet - pub ecn: Option, - /// Optional local IP address for the datagram - pub local_ip: Option, - /// Payload of the datagram - pub payload: Payload, -} - -#[cfg(test)] -mod test { - use std::sync::Arc; - - use super::*; - - #[test] - fn ensure_send_sync() { - fn is_send_sync(_a: impl Send + Sync) {} - - let c = EndpointConfig::new(); - let e = Endpoint::new(Arc::new(c), None); - is_send_sync(e); - - let a = Association::default(); - is_send_sync(a); - } -} - -#[cfg(test)] -mod tests { - mod partial_reliability; -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/packet.rs b/rs/moq-webrtc/src/vendor/sctp_proto/packet.rs deleted file mode 100644 index 09d0b490f80..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/packet.rs +++ /dev/null @@ -1,481 +0,0 @@ -use crate::vendor::sctp_proto::chunk::Chunk; -use crate::vendor::sctp_proto::chunk::chunk_abort::ChunkAbort; -use crate::vendor::sctp_proto::chunk::chunk_cookie_ack::ChunkCookieAck; -use crate::vendor::sctp_proto::chunk::chunk_cookie_echo::ChunkCookieEcho; -use crate::vendor::sctp_proto::chunk::chunk_error::ChunkError; -use crate::vendor::sctp_proto::chunk::chunk_forward_tsn::ChunkForwardTsn; -use crate::vendor::sctp_proto::chunk::chunk_header::*; -use crate::vendor::sctp_proto::chunk::chunk_heartbeat::ChunkHeartbeat; -use crate::vendor::sctp_proto::chunk::chunk_i_forward_tsn::ChunkIForwardTsn; -use crate::vendor::sctp_proto::chunk::chunk_init::ChunkInit; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::ChunkPayloadData; -use crate::vendor::sctp_proto::chunk::chunk_reconfig::ChunkReconfig; -use crate::vendor::sctp_proto::chunk::chunk_selective_ack::ChunkSelectiveAck; -use crate::vendor::sctp_proto::chunk::chunk_shutdown::ChunkShutdown; -use crate::vendor::sctp_proto::chunk::chunk_shutdown_ack::ChunkShutdownAck; -use crate::vendor::sctp_proto::chunk::chunk_shutdown_complete::ChunkShutdownComplete; -use crate::vendor::sctp_proto::chunk::chunk_type::*; -use crate::vendor::sctp_proto::error::{Error, Result}; -use crate::vendor::sctp_proto::util::*; - -use bytes::{Buf, BufMut, Bytes, BytesMut}; -use core::fmt; -use std::boxed::Box; -use std::vec; -use std::vec::Vec; - -///Packet represents an SCTP packet, defined in https://tools.ietf.org/html/rfc4960#section-3 -///An SCTP packet is composed of a common header and chunks. A chunk -///contains either control information or user data. -/// -/// -///SCTP Packet Format -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Common Header | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Chunk #1 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| ... | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Chunk #n | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -/// -/// -///SCTP Common Header Format -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Source Value Number | Destination Value Number | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Verification Tag | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Checksum | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -pub(crate) const PACKET_HEADER_SIZE: usize = 12; -const INITIATE_TAG_LENGTH: usize = 4; - -#[derive(Default, Debug)] -pub(crate) struct CommonHeader { - pub(crate) source_port: u16, - pub(crate) destination_port: u16, - pub(crate) verification_tag: u32, -} - -#[derive(Default, Debug)] -pub struct PartialDecode { - pub(crate) common_header: CommonHeader, - pub(crate) remaining: Bytes, - pub(crate) first_chunk_type: ChunkType, - pub(crate) initiate_tag: Option, - pub(crate) cookie: Option, -} - -impl PartialDecode { - pub(crate) fn unmarshal(raw: &Bytes) -> Result { - if raw.len() < PACKET_HEADER_SIZE { - return Err(Error::ErrPacketRawTooSmall); - } - - let reader = &mut raw.clone(); - - let source_port = reader.get_u16(); - let destination_port = reader.get_u16(); - let verification_tag = reader.get_u32(); - let their_checksum = reader.get_u32_le(); - let our_checksum = generate_packet_checksum(raw); - - if their_checksum != our_checksum { - return Err(Error::ErrChecksumMismatch); - } - - if reader.remaining() < CHUNK_HEADER_SIZE { - return Err(Error::ErrParseSctpChunkNotEnoughData); - } - - let header = ChunkHeader::unmarshal(reader)?; - reader.advance(CHUNK_HEADER_SIZE); - - let mut initiate_tag = None; - let mut cookie = None; - match header.typ { - CT_INIT | CT_INIT_ACK => { - if header.value_length() < INITIATE_TAG_LENGTH { - return Err(Error::ErrChunkValueNotLongEnough); - } - initiate_tag = Some(reader.get_u32()); - } - CT_COOKIE_ECHO => { - let end = PACKET_HEADER_SIZE + CHUNK_HEADER_SIZE + header.value_length(); - if end > raw.len() { - return Err(Error::ErrChunkValueNotLongEnough); - } - cookie = Some(raw.slice(PACKET_HEADER_SIZE + CHUNK_HEADER_SIZE..end)); - } - _ => {} - } - - Ok(PartialDecode { - common_header: CommonHeader { - source_port, - destination_port, - verification_tag, - }, - remaining: raw.slice(PACKET_HEADER_SIZE..), - first_chunk_type: header.typ, - initiate_tag, - cookie, - }) - } - - pub(crate) fn finish(self) -> Result { - let mut chunks = vec![]; - let mut offset = 0; - loop { - // Exact match, no more chunks - if offset == self.remaining.len() { - break; - } else if offset + CHUNK_HEADER_SIZE > self.remaining.len() { - return Err(Error::ErrParseSctpChunkNotEnoughData); - } - - let ct = ChunkType(self.remaining[offset]); - let c: Box = match ct { - CT_INIT => Box::new(ChunkInit::unmarshal(&self.remaining.slice(offset..))?), - CT_INIT_ACK => Box::new(ChunkInit::unmarshal(&self.remaining.slice(offset..))?), - CT_ABORT => Box::new(ChunkAbort::unmarshal(&self.remaining.slice(offset..))?), - CT_COOKIE_ECHO => Box::new(ChunkCookieEcho::unmarshal(&self.remaining.slice(offset..))?), - CT_COOKIE_ACK => Box::new(ChunkCookieAck::unmarshal(&self.remaining.slice(offset..))?), - CT_HEARTBEAT => Box::new(ChunkHeartbeat::unmarshal(&self.remaining.slice(offset..))?), - CT_PAYLOAD_DATA => Box::new(ChunkPayloadData::unmarshal(&self.remaining.slice(offset..))?), - CT_SACK => Box::new(ChunkSelectiveAck::unmarshal(&self.remaining.slice(offset..))?), - CT_RECONFIG => Box::new(ChunkReconfig::unmarshal(&self.remaining.slice(offset..))?), - CT_FORWARD_TSN => Box::new(ChunkForwardTsn::unmarshal(&self.remaining.slice(offset..))?), - CT_I_FORWARD_TSN => Box::new(ChunkIForwardTsn::unmarshal(&self.remaining.slice(offset..))?), - CT_ERROR => Box::new(ChunkError::unmarshal(&self.remaining.slice(offset..))?), - CT_SHUTDOWN => Box::new(ChunkShutdown::unmarshal(&self.remaining.slice(offset..))?), - CT_SHUTDOWN_ACK => Box::new(ChunkShutdownAck::unmarshal(&self.remaining.slice(offset..))?), - CT_SHUTDOWN_COMPLETE => Box::new(ChunkShutdownComplete::unmarshal(&self.remaining.slice(offset..))?), - _ => return Err(Error::ErrUnmarshalUnknownChunkType), - }; - - let chunk_value_padding = get_padding_size(c.value_length()); - offset += CHUNK_HEADER_SIZE + c.value_length() + chunk_value_padding; - chunks.push(c); - } - - Ok(Packet { - common_header: self.common_header, - chunks, - }) - } -} - -#[derive(Default, Debug)] -pub(crate) struct Packet { - pub(crate) common_header: CommonHeader, - pub(crate) chunks: Vec>, -} - -/// makes packet printable -impl fmt::Display for Packet { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut res = format!( - "Packet: - source_port: {} - destination_port: {} - verification_tag: {} - ", - self.common_header.source_port, self.common_header.destination_port, self.common_header.verification_tag, - ); - for chunk in &self.chunks { - res += format!("Chunk: {}", chunk).as_str(); - } - write!(f, "{}", res) - } -} - -impl Packet { - pub(crate) fn unmarshal(raw: &Bytes) -> Result { - if raw.len() < PACKET_HEADER_SIZE { - return Err(Error::ErrPacketRawTooSmall); - } - - let reader = &mut raw.clone(); - - let source_port = reader.get_u16(); - let destination_port = reader.get_u16(); - let verification_tag = reader.get_u32(); - let their_checksum = reader.get_u32_le(); - let our_checksum = generate_packet_checksum(raw); - - if their_checksum != our_checksum { - return Err(Error::ErrChecksumMismatch); - } - - let mut chunks = vec![]; - let mut offset = PACKET_HEADER_SIZE; - loop { - // Exact match, no more chunks - if offset == raw.len() { - break; - } else if offset + CHUNK_HEADER_SIZE > raw.len() { - return Err(Error::ErrParseSctpChunkNotEnoughData); - } - - let ct = ChunkType(raw[offset]); - let c: Box = match ct { - CT_INIT => Box::new(ChunkInit::unmarshal(&raw.slice(offset..))?), - CT_INIT_ACK => Box::new(ChunkInit::unmarshal(&raw.slice(offset..))?), - CT_ABORT => Box::new(ChunkAbort::unmarshal(&raw.slice(offset..))?), - CT_COOKIE_ECHO => Box::new(ChunkCookieEcho::unmarshal(&raw.slice(offset..))?), - CT_COOKIE_ACK => Box::new(ChunkCookieAck::unmarshal(&raw.slice(offset..))?), - CT_HEARTBEAT => Box::new(ChunkHeartbeat::unmarshal(&raw.slice(offset..))?), - CT_PAYLOAD_DATA => Box::new(ChunkPayloadData::unmarshal(&raw.slice(offset..))?), - CT_SACK => Box::new(ChunkSelectiveAck::unmarshal(&raw.slice(offset..))?), - CT_RECONFIG => Box::new(ChunkReconfig::unmarshal(&raw.slice(offset..))?), - CT_FORWARD_TSN => Box::new(ChunkForwardTsn::unmarshal(&raw.slice(offset..))?), - CT_I_FORWARD_TSN => Box::new(ChunkIForwardTsn::unmarshal(&raw.slice(offset..))?), - CT_ERROR => Box::new(ChunkError::unmarshal(&raw.slice(offset..))?), - CT_SHUTDOWN => Box::new(ChunkShutdown::unmarshal(&raw.slice(offset..))?), - CT_SHUTDOWN_ACK => Box::new(ChunkShutdownAck::unmarshal(&raw.slice(offset..))?), - CT_SHUTDOWN_COMPLETE => Box::new(ChunkShutdownComplete::unmarshal(&raw.slice(offset..))?), - _ => return Err(Error::ErrUnmarshalUnknownChunkType), - }; - - let chunk_value_padding = get_padding_size(c.value_length()); - offset += CHUNK_HEADER_SIZE + c.value_length() + chunk_value_padding; - chunks.push(c); - } - - Ok(Packet { - common_header: CommonHeader { - source_port, - destination_port, - verification_tag, - }, - chunks, - }) - } - - pub(crate) fn marshal_to(&self, writer: &mut BytesMut) -> Result { - // Populate static headers - // 8-12 is Checksum which will be populated when packet is complete - writer.put_u16(self.common_header.source_port); - writer.put_u16(self.common_header.destination_port); - writer.put_u32(self.common_header.verification_tag); - - // This is where the checksum will be written - let checksum_pos = writer.len(); - writer.extend_from_slice(&[0, 0, 0, 0]); - - // Populate chunks - for c in &self.chunks { - c.marshal_to(writer)?; - - let padding_needed = get_padding_size(writer.len()); - if padding_needed != 0 { - // padding needed if < 4 because we pad to 4 - writer.extend_from_slice(&[0u8; PADDING_MULTIPLE][..padding_needed]); - } - } - - let mut digest = ISCSI_CRC.digest(); - digest.update(writer); - let checksum = digest.finalize(); - - // Checksum is already in BigEndian - // Using LittleEndian stops it from being flipped - let checksum_place = &mut writer[checksum_pos..checksum_pos + 4]; - checksum_place.copy_from_slice(&checksum.to_le_bytes()); - - Ok(writer.len()) - } - - pub(crate) fn marshal(&self) -> Result { - let mut buf = BytesMut::with_capacity(PACKET_HEADER_SIZE); - self.marshal_to(&mut buf)?; - Ok(buf.freeze()) - } -} - -impl Packet { - pub(crate) fn check_packet(&self) -> Result<()> { - // All packets must adhere to these rules - - // This is the SCTP sender's port number. It can be used by the - // receiver in combination with the source IP address, the SCTP - // destination port, and possibly the destination IP address to - // identify the association to which this packet belongs. The port - // number 0 MUST NOT be used. - if self.common_header.source_port == 0 { - return Err(Error::ErrSctpPacketSourcePortZero); - } - - // This is the SCTP port number to which this packet is destined. - // The receiving host will use this port number to de-multiplex the - // SCTP packet to the correct receiving endpoint/application. The - // port number 0 MUST NOT be used. - if self.common_header.destination_port == 0 { - return Err(Error::ErrSctpPacketDestinationPortZero); - } - - // Check values on the packet that are specific to a particular chunk type - for c in &self.chunks { - if let Some(ci) = c.as_any().downcast_ref::() { - if !ci.is_ack { - // An INIT or INIT ACK chunk MUST NOT be bundled with any other chunk. - // They MUST be the only chunks present in the SCTP packets that carry - // them. - if self.chunks.len() != 1 { - return Err(Error::ErrInitChunkBundled); - } - - // A packet containing an INIT chunk MUST have a zero Verification - // Tag. - if self.common_header.verification_tag != 0 { - return Err(Error::ErrInitChunkVerifyTagNotZero); - } - } - } - } - - Ok(()) - } -} - -#[cfg(test)] -mod test { - use super::*; - - #[test] - fn test_packet_unmarshal() -> Result<()> { - let result = Packet::unmarshal(&Bytes::new()); - assert!( - result.is_err(), - "Unmarshal should fail when a packet is too small to be SCTP" - ); - - let header_only = Bytes::from_static(&[0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0x06, 0xa9, 0x00, 0xe1]); - let pkt = Packet::unmarshal(&header_only)?; - //assert!(result.o(), "Unmarshal failed for SCTP packet with no chunks: {}", result); - assert_eq!( - pkt.common_header.source_port, 5000, - "Unmarshal passed for SCTP packet, but got incorrect source port exp: {} act: {}", - 5000, pkt.common_header.source_port - ); - assert_eq!( - pkt.common_header.destination_port, 5000, - "Unmarshal passed for SCTP packet, but got incorrect destination port exp: {} act: {}", - 5000, pkt.common_header.destination_port - ); - assert_eq!( - pkt.common_header.verification_tag, 0, - "Unmarshal passed for SCTP packet, but got incorrect verification tag exp: {} act: {}", - 0, pkt.common_header.verification_tag - ); - - let raw_chunk = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0x81, 0x46, 0x9d, 0xfc, 0x01, 0x00, 0x00, 0x56, 0x55, 0xb9, - 0x64, 0xa5, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0xe8, 0x6d, 0x10, 0x30, 0xc0, 0x00, 0x00, 0x04, - 0x80, 0x08, 0x00, 0x09, 0xc0, 0x0f, 0xc1, 0x80, 0x82, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x24, 0x9f, 0xeb, - 0xbb, 0x5c, 0x50, 0xc9, 0xbf, 0x75, 0x9c, 0xb1, 0x2c, 0x57, 0x4f, 0xa4, 0x5a, 0x51, 0xba, 0x60, 0x17, 0x78, - 0x27, 0x94, 0x5c, 0x31, 0xe6, 0x5d, 0x5b, 0x09, 0x47, 0xe2, 0x22, 0x06, 0x80, 0x04, 0x00, 0x06, 0x00, 0x01, - 0x00, 0x00, 0x80, 0x03, 0x00, 0x06, 0x80, 0xc1, 0x00, 0x00, - ]); - - Packet::unmarshal(&raw_chunk)?; - - Ok(()) - } - - #[test] - fn test_packet_marshal() -> Result<()> { - let header_only = Bytes::from_static(&[0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0x06, 0xa9, 0x00, 0xe1]); - let pkt = Packet::unmarshal(&header_only)?; - let header_only_marshaled = pkt.marshal()?; - assert_eq!( - header_only, header_only_marshaled, - "Unmarshal/Marshaled header only packet did not match \ - \nheaderOnly: {:?} \nheader_only_marshaled {:?}", - header_only, header_only_marshaled - ); - - Ok(()) - } - - /*fn BenchmarkPacketGenerateChecksum(b *testing.B) { - var data [1024]byte - - for i := 0; i < b.N; i++ { - _ = generatePacketChecksum(data[:]) - } - }*/ - - #[test] - fn test_partial_decode_init_chunk() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0x81, 0x46, 0x9d, 0xfc, 0x01, 0x00, 0x00, 0x56, 0x55, 0xb9, - 0x64, 0xa5, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0xe8, 0x6d, 0x10, 0x30, 0xc0, 0x00, 0x00, 0x04, - 0x80, 0x08, 0x00, 0x09, 0xc0, 0x0f, 0xc1, 0x80, 0x82, 0x00, 0x00, 0x00, 0x80, 0x02, 0x00, 0x24, 0x9f, 0xeb, - 0xbb, 0x5c, 0x50, 0xc9, 0xbf, 0x75, 0x9c, 0xb1, 0x2c, 0x57, 0x4f, 0xa4, 0x5a, 0x51, 0xba, 0x60, 0x17, 0x78, - 0x27, 0x94, 0x5c, 0x31, 0xe6, 0x5d, 0x5b, 0x09, 0x47, 0xe2, 0x22, 0x06, 0x80, 0x04, 0x00, 0x06, 0x00, 0x01, - 0x00, 0x00, 0x80, 0x03, 0x00, 0x06, 0x80, 0xc1, 0x00, 0x00, - ]); - let pkt = PartialDecode::unmarshal(&raw_pkt)?; - - assert_eq!(pkt.first_chunk_type, CT_INIT); - if let Some(initiate_tag) = pkt.initiate_tag { - assert_eq!( - initiate_tag, 1438213285, - "Unmarshal passed for SCTP packet, but got incorrect initiate tag exp: {} act: {}", - 1438213285, initiate_tag - ); - } - - Ok(()) - } - - #[test] - fn test_partial_decode_init_ack() -> Result<()> { - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0xce, 0x15, 0x79, 0xa2, 0x96, 0x19, 0xe8, 0xb2, 0x02, 0x00, 0x00, 0x1c, 0xeb, 0x81, - 0x4e, 0x01, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x08, 0x00, 0x50, 0xdf, 0x90, 0xd9, 0x00, 0x07, 0x00, 0x08, - 0x94, 0x06, 0x2f, 0x93, - ]); - let pkt = PartialDecode::unmarshal(&raw_pkt)?; - - assert_eq!(pkt.first_chunk_type, CT_INIT_ACK); - if let Some(initiate_tag) = pkt.initiate_tag { - assert_eq!( - initiate_tag, 3951119873u32, - "Unmarshal passed for SCTP packet, but got incorrect initiate tag exp: {} act: {}", - 3951119873u32, initiate_tag - ); - } - - Ok(()) - } - - #[test] - fn test_partial_decode_finish_init_trailing_param_without_value() -> Result<()> { - // An INIT whose last parameter carries no value, decoded through the - // same two steps an association performs on an inbound datagram. - let raw_pkt = Bytes::from_static(&[ - 0x13, 0x88, 0x13, 0x88, 0x00, 0x00, 0x00, 0x00, 0x92, 0x57, 0x55, 0xc7, 0x01, 0x00, 0x00, 0x20, 0x12, 0x34, - 0x56, 0x78, 0x00, 0x02, 0x00, 0x00, 0x04, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x01, 0x80, 0x08, 0x00, 0x08, - 0x82, 0xc0, 0x40, 0xc2, 0xc0, 0x00, 0x00, 0x04, - ]); - - let partial = PartialDecode::unmarshal(&raw_pkt)?; - assert_eq!(partial.first_chunk_type, CT_INIT); - assert_eq!(partial.initiate_tag, Some(0x1234_5678)); - - let pkt = partial.finish()?; - assert_eq!(pkt.chunks.len(), 1, "expected a single INIT chunk"); - - Ok(()) - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/mod.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/mod.rs deleted file mode 100644 index b899ee6eb98..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/mod.rs +++ /dev/null @@ -1,92 +0,0 @@ -#[cfg(test)] -mod param_test; - -pub(crate) mod param_chunk_list; -pub(crate) mod param_forward_tsn_supported; -pub(crate) mod param_header; -pub(crate) mod param_heartbeat_info; -pub(crate) mod param_outgoing_reset_request; -pub(crate) mod param_random; -pub(crate) mod param_reconfig_response; -pub(crate) mod param_requested_hmac_algorithm; -pub(crate) mod param_state_cookie; -pub(crate) mod param_supported_address_types; -pub(crate) mod param_supported_extensions; -pub(crate) mod param_type; -pub(crate) mod param_uknown; - -use crate::vendor::sctp_proto::error::{Error, Result}; -use crate::vendor::sctp_proto::param::param_chunk_list::ParamChunkList; -use crate::vendor::sctp_proto::param::param_forward_tsn_supported::ParamForwardTsnSupported; -use crate::vendor::sctp_proto::param::param_heartbeat_info::ParamHeartbeatInfo; -use crate::vendor::sctp_proto::param::param_outgoing_reset_request::ParamOutgoingResetRequest; -use crate::vendor::sctp_proto::param::param_random::ParamRandom; -use crate::vendor::sctp_proto::param::param_reconfig_response::ParamReconfigResponse; -use crate::vendor::sctp_proto::param::param_requested_hmac_algorithm::ParamRequestedHmacAlgorithm; -use crate::vendor::sctp_proto::param::param_state_cookie::ParamStateCookie; -use crate::vendor::sctp_proto::param::param_supported_address_types::ParamSupportedAddressTypes; -use crate::vendor::sctp_proto::param::param_supported_extensions::ParamSupportedExtensions; -use param_header::*; -use param_type::*; - -use bytes::{Buf, Bytes, BytesMut}; -use core::{any::Any, fmt}; -use std::boxed::Box; - -use self::param_uknown::ParamUnknown; - -pub(crate) trait Param: fmt::Display + fmt::Debug { - fn header(&self) -> ParamHeader; - fn unmarshal(raw: &Bytes) -> Result - where - Self: Sized; - fn marshal_to(&self, buf: &mut BytesMut) -> Result; - fn value_length(&self) -> usize; - fn clone_to(&self) -> Box; - fn as_any(&self) -> &(dyn Any + Send + Sync); - - fn marshal(&self) -> Result { - let capacity = PARAM_HEADER_LENGTH + self.value_length(); - let mut buf = BytesMut::with_capacity(capacity); - self.marshal_to(&mut buf)?; - Ok(buf.freeze()) - } -} - -impl Clone for Box { - fn clone(&self) -> Box { - self.clone_to() - } -} - -pub(crate) fn build_param(raw_param: &Bytes) -> Result> { - if raw_param.len() < PARAM_HEADER_LENGTH { - return Err(Error::ErrParamHeaderTooShort); - } - let reader = &mut raw_param.slice(..2); - let raw_type = reader.get_u16(); - let t: ParamType = raw_type.into(); - match t { - ParamType::ForwardTsnSupp => Ok(Box::new(ParamForwardTsnSupported::unmarshal(raw_param)?)), - ParamType::SupportedExt => Ok(Box::new(ParamSupportedExtensions::unmarshal(raw_param)?)), - ParamType::Random => Ok(Box::new(ParamRandom::unmarshal(raw_param)?)), - ParamType::ReqHmacAlgo => Ok(Box::new(ParamRequestedHmacAlgorithm::unmarshal(raw_param)?)), - ParamType::ChunkList => Ok(Box::new(ParamChunkList::unmarshal(raw_param)?)), - ParamType::StateCookie => Ok(Box::new(ParamStateCookie::unmarshal(raw_param)?)), - ParamType::SupportedAddrTypes => Ok(Box::new(ParamSupportedAddressTypes::unmarshal(raw_param)?)), - ParamType::HeartbeatInfo => Ok(Box::new(ParamHeartbeatInfo::unmarshal(raw_param)?)), - ParamType::OutSsnResetReq => Ok(Box::new(ParamOutgoingResetRequest::unmarshal(raw_param)?)), - ParamType::ReconfigResp => Ok(Box::new(ParamReconfigResponse::unmarshal(raw_param)?)), - _ => { - // According to RFC https://datatracker.ietf.org/doc/html/rfc4960#section-3.2.1 - let stop_processing = ((raw_type >> 15) & 0x01) == 0; - if stop_processing { - Err(Error::ErrParamTypeUnhandled { typ: raw_type }) - } else { - // We still might need to report this param as unrecognized. - // This depends on the context though. - Ok(Box::new(ParamUnknown::unmarshal(raw_param)?)) - } - } - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_chunk_list.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_chunk_list.rs deleted file mode 100644 index 62d304896c7..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_chunk_list.rs +++ /dev/null @@ -1,72 +0,0 @@ -use super::{param_header::*, param_type::*, *}; -use crate::vendor::sctp_proto::chunk::chunk_type::*; - -use bytes::BufMut; -use std::string::{String, ToString}; -use std::vec::Vec; - -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamChunkList { - pub(crate) chunk_types: Vec, -} - -impl fmt::Display for ParamChunkList { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} {}", - self.header(), - self.chunk_types - .iter() - .map(|ct| ct.to_string()) - .collect::>() - .join(" ") - ) - } -} - -impl Param for ParamChunkList { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::ChunkList, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - - if header.typ != ParamType::ChunkList { - return Err(Error::ErrParamTypeUnexpected); - } - - let reader = &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - - let mut chunk_types = vec![]; - while reader.has_remaining() { - chunk_types.push(ChunkType(reader.get_u8())); - } - - Ok(ParamChunkList { chunk_types }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - for ct in &self.chunk_types { - buf.put_u8(ct.0); - } - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - self.chunk_types.len() - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_forward_tsn_supported.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_forward_tsn_supported.rs deleted file mode 100644 index fb9e2f56037..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_forward_tsn_supported.rs +++ /dev/null @@ -1,49 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -/// At the initialization of the association, the sender of the INIT or -/// INIT ACK chunk MAY include this OPTIONAL parameter to inform its peer -/// that it is able to support the Forward TSN chunk -/// -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Parameter Type = 49152 | Parameter Length = 4 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamForwardTsnSupported; - -impl fmt::Display for ParamForwardTsnSupported { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header()) - } -} - -impl Param for ParamForwardTsnSupported { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::ForwardTsnSupp, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let _ = ParamHeader::unmarshal(raw)?; - Ok(ParamForwardTsnSupported {}) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - 0 - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_header.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_header.rs deleted file mode 100644 index 01c7b055b15..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_header.rs +++ /dev/null @@ -1,62 +0,0 @@ -use super::{param_type::*, *}; - -use bytes::BufMut; - -#[derive(Debug, Clone, PartialEq)] -pub(crate) struct ParamHeader { - pub(crate) typ: ParamType, - pub(crate) value_length: u16, -} - -pub(crate) const PARAM_HEADER_LENGTH: usize = 4; - -/// String makes paramHeader printable -impl fmt::Display for ParamHeader { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.typ) - } -} - -impl Param for ParamHeader { - fn header(&self) -> ParamHeader { - self.clone() - } - - fn unmarshal(raw: &Bytes) -> Result { - if raw.len() < PARAM_HEADER_LENGTH { - return Err(Error::ErrParamHeaderTooShort); - } - - let reader = &mut raw.clone(); - - let typ: ParamType = reader.get_u16().into(); - - let len = reader.get_u16() as usize; - if len < PARAM_HEADER_LENGTH || raw.len() < len { - return Err(Error::ErrParamHeaderTooShort); - } - - Ok(ParamHeader { - typ, - value_length: (len - PARAM_HEADER_LENGTH) as u16, - }) - } - - fn marshal_to(&self, writer: &mut BytesMut) -> Result { - writer.put_u16(self.typ.into()); - writer.put_u16(self.value_length + PARAM_HEADER_LENGTH as u16); - Ok(writer.len()) - } - - fn value_length(&self) -> usize { - self.value_length as usize - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_heartbeat_info.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_heartbeat_info.rs deleted file mode 100644 index ca07f5deb3c..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_heartbeat_info.rs +++ /dev/null @@ -1,45 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamHeartbeatInfo { - pub(crate) heartbeat_information: Bytes, -} - -impl fmt::Display for ParamHeartbeatInfo { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} {:?}", self.header(), self.heartbeat_information) - } -} - -impl Param for ParamHeartbeatInfo { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::HeartbeatInfo, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - let heartbeat_information = raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - Ok(ParamHeartbeatInfo { heartbeat_information }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - buf.extend(self.heartbeat_information.clone()); - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - self.heartbeat_information.len() - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_outgoing_reset_request.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_outgoing_reset_request.rs deleted file mode 100644 index e8e11f6ba70..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_outgoing_reset_request.rs +++ /dev/null @@ -1,122 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -use bytes::BufMut; -use std::vec::Vec; - -pub(crate) const PARAM_OUTGOING_RESET_REQUEST_STREAM_IDENTIFIERS_OFFSET: usize = 12; - -///This parameter is used by the sender to request the reset of some or -///all outgoing streams. -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Parameter Type = 13 | Parameter Length = 16 + 2 * N | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Re-configuration Request Sequence Number | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Re-configuration Response Sequence Number | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Sender's Last Assigned TSN | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Stream Number 1 (optional) | Stream Number 2 (optional) | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| ...... | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Stream Number N-1 (optional) | Stream Number N (optional) | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamOutgoingResetRequest { - /// reconfig_request_sequence_number is used to identify the request. It is a monotonically - /// increasing number that is initialized to the same value as the - /// initial TSN. It is increased by 1 whenever sending a new Re- - /// configuration Request Parameter. - pub(crate) reconfig_request_sequence_number: u32, - /// When this Outgoing SSN Reset Request Parameter is sent in response - /// to an Incoming SSN Reset Request Parameter, this parameter is also - /// an implicit response to the incoming request. This field then - /// holds the Re-configuration Request Sequence Number of the incoming - /// request. In other cases, it holds the next expected - /// Re-configuration Request Sequence Number minus 1. - pub(crate) reconfig_response_sequence_number: u32, - /// This value holds the next TSN minus 1 -- in other words, the last - /// TSN that this sender assigned. - pub(crate) sender_last_tsn: u32, - /// This optional field, if included, is used to indicate specific - /// streams that are to be reset. If no streams are listed, then all - /// streams are to be reset. - pub(crate) stream_identifiers: Vec, -} - -impl fmt::Display for ParamOutgoingResetRequest { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} {} {} {} {:?}", - self.header(), - self.reconfig_request_sequence_number, - self.reconfig_response_sequence_number, - self.sender_last_tsn, - self.stream_identifiers - ) - } -} - -impl Param for ParamOutgoingResetRequest { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::OutSsnResetReq, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - if header.value_length() < PARAM_OUTGOING_RESET_REQUEST_STREAM_IDENTIFIERS_OFFSET { - return Err(Error::ErrSsnResetRequestParamTooShort); - } - if (header.value_length() - PARAM_OUTGOING_RESET_REQUEST_STREAM_IDENTIFIERS_OFFSET) % 2 != 0 { - return Err(Error::ErrSsnResetRequestParamInvalidLength); - } - - let reader = &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - let reconfig_request_sequence_number = reader.get_u32(); - let reconfig_response_sequence_number = reader.get_u32(); - let sender_last_tsn = reader.get_u32(); - - let lim = (header.value_length() - PARAM_OUTGOING_RESET_REQUEST_STREAM_IDENTIFIERS_OFFSET) / 2; - let mut stream_identifiers = vec![]; - for _ in 0..lim { - stream_identifiers.push(reader.get_u16()); - } - - Ok(ParamOutgoingResetRequest { - reconfig_request_sequence_number, - reconfig_response_sequence_number, - sender_last_tsn, - stream_identifiers, - }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - buf.put_u32(self.reconfig_request_sequence_number); - buf.put_u32(self.reconfig_response_sequence_number); - buf.put_u32(self.sender_last_tsn); - for sid in &self.stream_identifiers { - buf.put_u16(*sid); - } - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - PARAM_OUTGOING_RESET_REQUEST_STREAM_IDENTIFIERS_OFFSET + self.stream_identifiers.len() * 2 - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_random.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_random.rs deleted file mode 100644 index 33bfbac32c6..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_random.rs +++ /dev/null @@ -1,45 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamRandom { - pub(crate) random_data: Bytes, -} - -impl fmt::Display for ParamRandom { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{} {:?}", self.header(), self.random_data) - } -} - -impl Param for ParamRandom { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::Random, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - let random_data = raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - Ok(ParamRandom { random_data }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - buf.extend(self.random_data.clone()); - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - self.random_data.len() - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_reconfig_response.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_reconfig_response.rs deleted file mode 100644 index b24594ff33a..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_reconfig_response.rs +++ /dev/null @@ -1,132 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -use bytes::BufMut; - -#[derive(Debug, Copy, Clone, PartialEq)] -#[repr(C)] -#[derive(Default)] -pub(crate) enum ReconfigResult { - SuccessNop = 0, - SuccessPerformed = 1, - Denied = 2, - ErrorWrongSsn = 3, - ErrorRequestAlreadyInProgress = 4, - ErrorBadSequenceNumber = 5, - InProgress = 6, - #[default] - Unknown, -} - -impl fmt::Display for ReconfigResult { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - ReconfigResult::SuccessNop => "0: Success - Nothing to do", - ReconfigResult::SuccessPerformed => "1: Success - Performed", - ReconfigResult::Denied => "2: Denied", - ReconfigResult::ErrorWrongSsn => "3: Error - Wrong SSN", - ReconfigResult::ErrorRequestAlreadyInProgress => "4: Error - Request already in progress", - ReconfigResult::ErrorBadSequenceNumber => "5: Error - Bad Sequence Number", - ReconfigResult::InProgress => "6: In progress", - _ => "Unknown ReconfigResult", - }; - write!(f, "{}", s) - } -} - -impl From for ReconfigResult { - fn from(v: u32) -> ReconfigResult { - match v { - 0 => ReconfigResult::SuccessNop, - 1 => ReconfigResult::SuccessPerformed, - 2 => ReconfigResult::Denied, - 3 => ReconfigResult::ErrorWrongSsn, - 4 => ReconfigResult::ErrorRequestAlreadyInProgress, - 5 => ReconfigResult::ErrorBadSequenceNumber, - 6 => ReconfigResult::InProgress, - _ => ReconfigResult::Unknown, - } - } -} - -///This parameter is used by the receiver of a Re-configuration Request -///Parameter to respond to the request. -/// -///0 1 2 3 -///0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Parameter Type = 16 | Parameter Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Re-configuration Response Sequence Number | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Result | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Sender's Next TSN (optional) | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Receiver's Next TSN (optional) | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamReconfigResponse { - /// This value is copied from the request parameter and is used by the - /// receiver of the Re-configuration Response Parameter to tie the - /// response to the request. - pub(crate) reconfig_response_sequence_number: u32, - /// This value describes the result of the processing of the request. - pub(crate) result: ReconfigResult, -} - -impl fmt::Display for ParamReconfigResponse { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} {} {}", - self.header(), - self.reconfig_response_sequence_number, - self.result - ) - } -} - -impl Param for ParamReconfigResponse { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::ReconfigResp, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - if header.value_length() < 8 { - return Err(Error::ErrReconfigRespParamTooShort); - } - - let reader = &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - - let reconfig_response_sequence_number = reader.get_u32(); - let result = reader.get_u32().into(); - - Ok(ParamReconfigResponse { - reconfig_response_sequence_number, - result, - }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - buf.put_u32(self.reconfig_response_sequence_number); - buf.put_u32(self.result as u32); - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - 8 - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_requested_hmac_algorithm.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_requested_hmac_algorithm.rs deleted file mode 100644 index 31d159f45b6..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_requested_hmac_algorithm.rs +++ /dev/null @@ -1,110 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -use bytes::BufMut; -use std::string::{String, ToString}; -use std::vec::Vec; - -#[derive(Debug, Copy, Clone, PartialEq)] -#[repr(C)] -pub(crate) enum HmacAlgorithm { - HmacResv1 = 0, - HmacSha128 = 1, - HmacResv2 = 2, - HmacSha256 = 3, - Unknown, -} - -impl fmt::Display for HmacAlgorithm { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - HmacAlgorithm::HmacResv1 => "HMAC Reserved (0x00)", - HmacAlgorithm::HmacSha128 => "HMAC SHA-128", - HmacAlgorithm::HmacResv2 => "HMAC Reserved (0x02)", - HmacAlgorithm::HmacSha256 => "HMAC SHA-256", - _ => "Unknown HMAC Algorithm", - }; - write!(f, "{}", s) - } -} - -impl From for HmacAlgorithm { - fn from(v: u16) -> HmacAlgorithm { - match v { - 0 => HmacAlgorithm::HmacResv1, - 1 => HmacAlgorithm::HmacSha128, - 2 => HmacAlgorithm::HmacResv2, - 3 => HmacAlgorithm::HmacSha256, - _ => HmacAlgorithm::Unknown, - } - } -} - -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamRequestedHmacAlgorithm { - pub(crate) available_algorithms: Vec, -} - -impl fmt::Display for ParamRequestedHmacAlgorithm { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} {}", - self.header(), - self.available_algorithms - .iter() - .map(|ct| ct.to_string()) - .collect::>() - .join(" "), - ) - } -} - -impl Param for ParamRequestedHmacAlgorithm { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::ReqHmacAlgo, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - - let reader = &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - - let mut available_algorithms = vec![]; - let mut offset = 0; - while offset + 1 < header.value_length() { - let a: HmacAlgorithm = reader.get_u16().into(); - if a == HmacAlgorithm::HmacSha128 || a == HmacAlgorithm::HmacSha256 { - available_algorithms.push(a); - } else { - return Err(Error::ErrInvalidAlgorithmType); - } - - offset += 2; - } - - Ok(ParamRequestedHmacAlgorithm { available_algorithms }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - for a in &self.available_algorithms { - buf.put_u16(*a as u16); - } - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - 2 * self.available_algorithms.len() - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_state_cookie.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_state_cookie.rs deleted file mode 100644 index 208b8ccf868..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_state_cookie.rs +++ /dev/null @@ -1,60 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -use rand::RngExt; - -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamStateCookie { - pub(crate) cookie: Bytes, -} - -/// String makes paramStateCookie printable -impl fmt::Display for ParamStateCookie { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}: {:?}", self.header(), self.cookie) - } -} - -impl Param for ParamStateCookie { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::StateCookie, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - let cookie = raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - Ok(ParamStateCookie { cookie }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - buf.extend(self.cookie.clone()); - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - self.cookie.len() - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} - -impl ParamStateCookie { - pub(crate) fn new() -> Self { - let mut cookie = BytesMut::new(); - cookie.resize(32, 0); - rand::rng().fill(cookie.as_mut()); - - ParamStateCookie { - cookie: cookie.freeze(), - } - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_address_types.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_address_types.rs deleted file mode 100644 index 97d024524ed..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_address_types.rs +++ /dev/null @@ -1,79 +0,0 @@ -use super::{param_header::*, param_type::*, *}; - -use bytes::BufMut; -use std::vec::Vec; - -///The sender of INIT uses this parameter to list all the address types -///it can support. Each entry is the type value of the corresponding -///address TLV, that is, `ParamType::Ipv4Addr`, `ParamType::Ipv6Addr` -///or `ParamType::HostNameAddr`. -/// -/// 0 1 2 3 -/// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Type = 12 | Length | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| Address Type #1 | Address Type #2 | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -///| ...... | -///+-+-+-+-+-+-+-+-+-+-+-+-+-+-++-+-+-+-+-+-+-+-+-+-+-+-+-+-++-+-+-+ - -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamSupportedAddressTypes { - pub(crate) address_types: Vec, -} - -impl fmt::Display for ParamSupportedAddressTypes { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "{}", self.header())?; - for t in &self.address_types { - write!(f, " {t}")?; - } - Ok(()) - } -} - -impl Param for ParamSupportedAddressTypes { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::SupportedAddrTypes, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - - if header.value_length() % 2 != 0 { - return Err(Error::ErrSupportedAddressTypesParamInvalidLength); - } - - let reader = &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - let mut address_types = Vec::with_capacity(reader.remaining() / 2); - while reader.has_remaining() { - address_types.push(ParamType::from(reader.get_u16())); - } - - Ok(ParamSupportedAddressTypes { address_types }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - for t in &self.address_types { - buf.put_u16(u16::from(*t)); - } - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - self.address_types.len() * 2 - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_extensions.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_extensions.rs deleted file mode 100644 index c402bb1ffe8..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_supported_extensions.rs +++ /dev/null @@ -1,68 +0,0 @@ -use super::{param_header::*, param_type::*, *}; -use crate::vendor::sctp_proto::chunk::chunk_type::*; - -use bytes::BufMut; -use std::string::{String, ToString}; -use std::vec::Vec; - -#[derive(Default, Debug, Clone, PartialEq)] -pub(crate) struct ParamSupportedExtensions { - pub(crate) chunk_types: Vec, -} - -impl fmt::Display for ParamSupportedExtensions { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!( - f, - "{} {}", - self.header(), - self.chunk_types - .iter() - .map(|ct| ct.to_string()) - .collect::>() - .join(" "), - ) - } -} - -impl Param for ParamSupportedExtensions { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::SupportedExt, - value_length: self.value_length() as u16, - } - } - - fn unmarshal(raw: &Bytes) -> Result { - let header = ParamHeader::unmarshal(raw)?; - - let reader = &mut raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - - let mut chunk_types = vec![]; - while reader.has_remaining() { - chunk_types.push(ChunkType(reader.get_u8())); - } - - Ok(ParamSupportedExtensions { chunk_types }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> Result { - self.header().marshal_to(buf)?; - for ct in &self.chunk_types { - buf.put_u8(ct.0); - } - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - self.chunk_types.len() - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_test.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_test.rs deleted file mode 100644 index 075a7c13733..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_test.rs +++ /dev/null @@ -1,330 +0,0 @@ -use std::string::ToString; -use std::vec; - -use super::*; - -/////////////////////////////////////////////////////////////////// -//param_type_test -/////////////////////////////////////////////////////////////////// -use super::param_type::*; - -#[test] -fn test_parse_param_type_success() -> Result<()> { - let tests = vec![ - (Bytes::from_static(&[0x0, 0x1]), ParamType::HeartbeatInfo), - (Bytes::from_static(&[0x0, 0xd]), ParamType::OutSsnResetReq), - ]; - - for (mut binary, expected) in tests { - let pt: ParamType = binary.get_u16().into(); - assert_eq!(expected, pt); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//param_header_test -/////////////////////////////////////////////////////////////////// -use super::param_header::*; - -static PARAM_HEADER_BYTES: Bytes = Bytes::from_static(&[0x0, 0x1, 0x0, 0x4]); - -#[test] -fn test_param_header_success() -> Result<()> { - let tests = vec![( - PARAM_HEADER_BYTES.clone(), - ParamHeader { - typ: ParamType::HeartbeatInfo, - value_length: 0, - }, - )]; - - for (binary, parsed) in tests { - let actual = ParamHeader::unmarshal(&binary)?; - assert_eq!(parsed, actual); - let b = actual.marshal()?; - assert_eq!(binary, b); - } - - Ok(()) -} - -#[test] -fn test_param_header_unmarshal_failure() -> Result<()> { - let tests = vec![ - ("header too short", PARAM_HEADER_BYTES.slice(..2)), - // {"wrong param type", []byte{0x0, 0x0, 0x0, 0x4}}, // Not possible to fail parseParamType atm. - ( - "reported length below header length", - Bytes::from_static(&[0x0, 0xd, 0x0, 0x3]), - ), - ("wrong reported length", CHUNK_RECONFIG_PARAM_A.slice(0..4)), - ]; - - for (name, binary) in tests { - let result = ParamHeader::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//param_forward_tsn_supported_test -/////////////////////////////////////////////////////////////////// -use super::param_forward_tsn_supported::*; - -static PARAM_FORWARD_TSN_SUPPORTED_BYTES: Bytes = Bytes::from_static(&[0xc0, 0x0, 0x0, 0x4]); - -#[test] -fn test_param_forward_tsn_supported_success() -> Result<()> { - let tests = vec![(PARAM_FORWARD_TSN_SUPPORTED_BYTES.clone(), ParamForwardTsnSupported {})]; - - for (binary, parsed) in tests { - let actual = ParamForwardTsnSupported::unmarshal(&binary)?; - assert_eq!(parsed, actual); - let b = actual.marshal()?; - assert_eq!(binary, b); - } - - Ok(()) -} - -#[test] -fn test_param_forward_tsn_supported_failure() -> Result<()> { - let tests = vec![("param too short", Bytes::from_static(&[0x0, 0xd, 0x0]))]; - - for (name, binary) in tests { - let result = ParamForwardTsnSupported::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//param_outgoing_reset_request_test -/////////////////////////////////////////////////////////////////// -use super::param_outgoing_reset_request::*; - -static CHUNK_RECONFIG_PARAM_A: Bytes = Bytes::from_static(&[ - 0x0, 0xd, 0x0, 0x16, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0x0, 0x4, 0x0, 0x5, 0x0, 0x6, -]); -static CHUNK_RECONFIG_PARAM_B: Bytes = Bytes::from_static(&[ - 0x0, 0xd, 0x0, 0x10, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, -]); - -#[test] -fn test_param_outgoing_reset_request_success() -> Result<()> { - let tests = vec![ - ( - CHUNK_RECONFIG_PARAM_A.clone(), - ParamOutgoingResetRequest { - reconfig_request_sequence_number: 1, - reconfig_response_sequence_number: 2, - sender_last_tsn: 3, - stream_identifiers: vec![4, 5, 6], - }, - ), - ( - CHUNK_RECONFIG_PARAM_B.clone(), - ParamOutgoingResetRequest { - reconfig_request_sequence_number: 1, - reconfig_response_sequence_number: 2, - sender_last_tsn: 3, - stream_identifiers: vec![], - }, - ), - ]; - - for (binary, parsed) in tests { - let actual = ParamOutgoingResetRequest::unmarshal(&binary)?; - assert_eq!(parsed, actual); - let b = actual.marshal()?; - assert_eq!(binary, b); - } - - Ok(()) -} - -#[test] -fn test_param_outgoing_reset_request_failure() -> Result<()> { - let tests = vec![ - ("packet too short", CHUNK_RECONFIG_PARAM_A.slice(..8)), - ("param too short", Bytes::from_static(&[0x0, 0xd, 0x0, 0x4])), - ( - "odd stream identifier bytes", - Bytes::from_static(&[ - 0x0, 0xd, 0x0, 0x11, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0, 0x3, 0xff, - ]), - ), - ]; - - for (name, binary) in tests { - let result = ParamOutgoingResetRequest::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//param_reconfig_response_test -/////////////////////////////////////////////////////////////////// -use super::param_reconfig_response::*; - -static CHUNK_RECONFIG_RESPONCE: Bytes = - Bytes::from_static(&[0x0, 0x10, 0x0, 0xc, 0x0, 0x0, 0x0, 0x1, 0x0, 0x0, 0x0, 0x1]); - -#[test] -fn test_param_reconfig_response_success() -> Result<()> { - let tests = vec![( - CHUNK_RECONFIG_RESPONCE.clone(), - ParamReconfigResponse { - reconfig_response_sequence_number: 1, - result: ReconfigResult::SuccessPerformed, - }, - )]; - - for (binary, parsed) in tests { - let actual = ParamReconfigResponse::unmarshal(&binary)?; - assert_eq!(parsed, actual); - let b = actual.marshal()?; - assert_eq!(binary, b); - } - - Ok(()) -} - -#[test] -fn test_param_reconfig_response_failure() -> Result<()> { - let tests = vec![ - ("packet too short", CHUNK_RECONFIG_RESPONCE.slice(..8)), - ("param too short", Bytes::from_static(&[0x0, 0x10, 0x0, 0x4])), - ]; - - for (name, binary) in tests { - let result = ParamReconfigResponse::unmarshal(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -#[test] -fn test_reconfig_result_stringer() -> Result<()> { - let tests = vec![ - (ReconfigResult::SuccessNop, "0: Success - Nothing to do"), - (ReconfigResult::SuccessPerformed, "1: Success - Performed"), - (ReconfigResult::Denied, "2: Denied"), - (ReconfigResult::ErrorWrongSsn, "3: Error - Wrong SSN"), - ( - ReconfigResult::ErrorRequestAlreadyInProgress, - "4: Error - Request already in progress", - ), - (ReconfigResult::ErrorBadSequenceNumber, "5: Error - Bad Sequence Number"), - (ReconfigResult::InProgress, "6: In progress"), - ]; - - for (result, expected) in tests { - let actual = result.to_string(); - assert_eq!(expected, actual, "Test case {}", expected); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//param_test -/////////////////////////////////////////////////////////////////// - -#[test] -fn test_build_param_success() -> Result<()> { - let tests = vec![CHUNK_RECONFIG_PARAM_A.clone()]; - - for binary in tests { - let p = build_param(&binary)?; - let b = p.marshal()?; - assert_eq!(binary, b); - } - - Ok(()) -} - -#[test] -fn test_build_param_failure() -> Result<()> { - let tests = vec![ - ("invalid ParamType", Bytes::from_static(&[0x0, 0x0])), - ("build failure", CHUNK_RECONFIG_PARAM_A.slice(..8)), - ]; - - for (name, binary) in tests { - let result = build_param(&binary); - assert!(result.is_err(), "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//param_supported_address_types_test -/////////////////////////////////////////////////////////////////// -use super::param_supported_address_types::*; - -static PARAM_SUPPORTED_ADDRESS_TYPES_BYTES: Bytes = Bytes::from_static(&[0x0, 0xc, 0x0, 0x6, 0x0, 0x5]); - -#[test] -fn test_param_supported_address_types_success() -> Result<()> { - let tests = vec![ - ( - PARAM_SUPPORTED_ADDRESS_TYPES_BYTES.clone(), - ParamSupportedAddressTypes { - address_types: vec![ParamType::Ipv4Addr], - }, - ), - ( - Bytes::from_static(&[0x0, 0xc, 0x0, 0x8, 0x0, 0x5, 0x0, 0x6]), - ParamSupportedAddressTypes { - address_types: vec![ParamType::Ipv4Addr, ParamType::Ipv6Addr], - }, - ), - ( - Bytes::from_static(&[0x0, 0xc, 0x0, 0x8, 0x0, 0x5, 0x0, 0xb]), - ParamSupportedAddressTypes { - address_types: vec![ParamType::Ipv4Addr, ParamType::HostNameAddr], - }, - ), - ( - Bytes::from_static(&[0x0, 0xc, 0x0, 0x8, 0x0, 0x5, 0x9, 0x9]), - ParamSupportedAddressTypes { - address_types: vec![ParamType::Ipv4Addr, ParamType::Unknown { param_type: 0x0909 }], - }, - ), - ]; - - for (binary, parsed) in tests { - let actual = ParamSupportedAddressTypes::unmarshal(&binary)?; - assert_eq!(parsed, actual); - let b = actual.marshal()?; - assert_eq!(binary, b); - } - - Ok(()) -} - -#[test] -fn test_param_supported_address_types_failure() -> Result<()> { - let tests = vec![( - "odd reported length", - Bytes::from_static(&[0x0, 0xc, 0x0, 0x5, 0x5, 0x0, 0x0, 0x0]), - Error::ErrSupportedAddressTypesParamInvalidLength, - )]; - - for (name, binary, expected) in tests { - let result = ParamSupportedAddressTypes::unmarshal(&binary); - assert_eq!(Err(expected), result, "expected unmarshal: {} to fail.", name); - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_type.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_type.rs deleted file mode 100644 index b74be3fb3af..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_type.rs +++ /dev/null @@ -1,164 +0,0 @@ -use core::fmt; - -/// paramType represents a SCTP INIT/INITACK parameter -#[derive(Debug, Copy, Clone, PartialEq)] -#[repr(C)] -pub(crate) enum ParamType { - HeartbeatInfo, - /// Heartbeat Info [RFCRFC4960] - Ipv4Addr, - /// IPv4 IP [RFCRFC4960] - Ipv6Addr, - /// IPv6 IP [RFCRFC4960] - StateCookie, - /// State Cookie [RFCRFC4960] - UnrecognizedParam, - /// Unrecognized Parameters [RFCRFC4960] - CookiePreservative, - /// Cookie Preservative [RFCRFC4960] - HostNameAddr, - /// Host Name IP [RFCRFC4960] - SupportedAddrTypes, - /// Supported IP Types [RFCRFC4960] - OutSsnResetReq, - /// Outgoing SSN Reset Request Parameter [RFCRFC6525] - IncSsnResetReq, - /// Incoming SSN Reset Request Parameter [RFCRFC6525] - SsnTsnResetReq, - /// SSN/TSN Reset Request Parameter [RFCRFC6525] - ReconfigResp, - /// Re-configuration Response Parameter [RFCRFC6525] - AddOutStreamsReq, - /// Add Outgoing Streams Request Parameter [RFCRFC6525] - AddIncStreamsReq, - /// Add Incoming Streams Request Parameter [RFCRFC6525] - Random, - /// Random (0x8002) [RFCRFC4805] - ChunkList, - /// Chunk List (0x8003) [RFCRFC4895] - ReqHmacAlgo, - /// Requested HMAC Algorithm Parameter (0x8004) [RFCRFC4895] - Padding, - /// Padding (0x8005) - SupportedExt, - /// Supported Extensions (0x8008) [RFCRFC5061] - ForwardTsnSupp, - /// Forward TSN supported (0xC000) [RFCRFC3758] - AddIpAddr, - /// Add IP IP (0xC001) [RFCRFC5061] - DelIpaddr, - /// Delete IP IP (0xC002) [RFCRFC5061] - ErrClauseInd, - /// Error Cause Indication (0xC003) [RFCRFC5061] - SetPriAddr, - /// Set Primary IP (0xC004) [RFCRFC5061] - SuccessInd, - /// Success Indication (0xC005) [RFCRFC5061] - AdaptLayerInd, - /// Adaptation Layer Indication (0xC006) [RFCRFC5061] - Unknown { - param_type: u16, - }, -} - -impl fmt::Display for ParamType { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let s = match *self { - ParamType::HeartbeatInfo => "Heartbeat Info", - ParamType::Ipv4Addr => "IPv4 IP", - ParamType::Ipv6Addr => "IPv6 IP", - ParamType::StateCookie => "State Cookie", - ParamType::UnrecognizedParam => "Unrecognized Parameters", - ParamType::CookiePreservative => "Cookie Preservative", - ParamType::HostNameAddr => "Host Name IP", - ParamType::SupportedAddrTypes => "Supported IP Types", - ParamType::OutSsnResetReq => "Outgoing SSN Reset Request Parameter", - ParamType::IncSsnResetReq => "Incoming SSN Reset Request Parameter", - ParamType::SsnTsnResetReq => "SSN/TSN Reset Request Parameter", - ParamType::ReconfigResp => "Re-configuration Response Parameter", - ParamType::AddOutStreamsReq => "Add Outgoing Streams Request Parameter", - ParamType::AddIncStreamsReq => "Add Incoming Streams Request Parameter", - ParamType::Random => "Random", - ParamType::ChunkList => "Chunk List", - ParamType::ReqHmacAlgo => "Requested HMAC Algorithm Parameter", - ParamType::Padding => "Padding", - ParamType::SupportedExt => "Supported Extensions", - ParamType::ForwardTsnSupp => "Forward TSN supported", - ParamType::AddIpAddr => "Add IP IP", - ParamType::DelIpaddr => "Delete IP IP", - ParamType::ErrClauseInd => "Error Cause Indication", - ParamType::SetPriAddr => "Set Primary IP", - ParamType::SuccessInd => "Success Indication", - ParamType::AdaptLayerInd => "Adaptation Layer Indication", - _ => "Unknown ParamType", - }; - write!(f, "{}", s) - } -} - -impl From for ParamType { - fn from(v: u16) -> ParamType { - match v { - 1 => ParamType::HeartbeatInfo, - 5 => ParamType::Ipv4Addr, - 6 => ParamType::Ipv6Addr, - 7 => ParamType::StateCookie, - 8 => ParamType::UnrecognizedParam, - 9 => ParamType::CookiePreservative, - 11 => ParamType::HostNameAddr, - 12 => ParamType::SupportedAddrTypes, - 13 => ParamType::OutSsnResetReq, - 14 => ParamType::IncSsnResetReq, - 15 => ParamType::SsnTsnResetReq, - 16 => ParamType::ReconfigResp, - 17 => ParamType::AddOutStreamsReq, - 18 => ParamType::AddIncStreamsReq, - 32770 => ParamType::Random, - 32771 => ParamType::ChunkList, - 32772 => ParamType::ReqHmacAlgo, - 32773 => ParamType::Padding, - 32776 => ParamType::SupportedExt, - 49152 => ParamType::ForwardTsnSupp, - 49153 => ParamType::AddIpAddr, - 49154 => ParamType::DelIpaddr, - 49155 => ParamType::ErrClauseInd, - 49156 => ParamType::SetPriAddr, - 49157 => ParamType::SuccessInd, - _ => ParamType::Unknown { param_type: v }, - } - } -} - -impl From for u16 { - fn from(v: ParamType) -> u16 { - match v { - ParamType::HeartbeatInfo => 1, - ParamType::Ipv4Addr => 5, - ParamType::Ipv6Addr => 6, - ParamType::StateCookie => 7, - ParamType::UnrecognizedParam => 8, - ParamType::CookiePreservative => 9, - ParamType::HostNameAddr => 11, - ParamType::SupportedAddrTypes => 12, - ParamType::OutSsnResetReq => 13, - ParamType::IncSsnResetReq => 14, - ParamType::SsnTsnResetReq => 15, - ParamType::ReconfigResp => 16, - ParamType::AddOutStreamsReq => 17, - ParamType::AddIncStreamsReq => 18, - ParamType::Random => 32770, - ParamType::ChunkList => 32771, - ParamType::ReqHmacAlgo => 32772, - ParamType::Padding => 32773, - ParamType::SupportedExt => 32776, - ParamType::ForwardTsnSupp => 49152, - ParamType::AddIpAddr => 49153, - ParamType::DelIpaddr => 49154, - ParamType::ErrClauseInd => 49155, - ParamType::SetPriAddr => 49156, - ParamType::SuccessInd => 49157, - ParamType::AdaptLayerInd => 49158, - ParamType::Unknown { param_type, .. } => param_type, - } - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_uknown.rs b/rs/moq-webrtc/src/vendor/sctp_proto/param/param_uknown.rs deleted file mode 100644 index c62f6275a76..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/param/param_uknown.rs +++ /dev/null @@ -1,67 +0,0 @@ -use core::any::Any; -use core::fmt::{Debug, Display, Formatter}; -use std::boxed::Box; - -use bytes::{Bytes, BytesMut}; - -use crate::vendor::sctp_proto::param::Param; -use crate::vendor::sctp_proto::param::param_header::{PARAM_HEADER_LENGTH, ParamHeader}; -use crate::vendor::sctp_proto::param::param_type::ParamType; - -/// This type is meant to represent ANY parameter for -/// un/remarshaling purposes, where we do not have a more specific -/// type for it. This means we do not really understand the semantics -/// of the param but can represent it. -/// -/// This is useful for usage in e.g.`ParamUnrecognized` where we want -/// to report some unrecognized params back to the sender. -#[derive(Clone, Debug, PartialEq, Eq)] -pub struct ParamUnknown { - typ: u16, - value: Bytes, -} - -impl Display for ParamUnknown { - fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result { - write!(f, "ParamUnknown( {} {:?} )", self.header(), self.value) - } -} - -impl Param for ParamUnknown { - fn header(&self) -> ParamHeader { - ParamHeader { - typ: ParamType::Unknown { param_type: self.typ }, - value_length: self.value.len() as u16, - } - } - - fn as_any(&self) -> &(dyn Any + Send + Sync) { - self - } - - fn unmarshal(raw: &Bytes) -> crate::vendor::sctp_proto::error::Result - where - Self: Sized, - { - let header = ParamHeader::unmarshal(raw)?; - let value = raw.slice(PARAM_HEADER_LENGTH..PARAM_HEADER_LENGTH + header.value_length()); - Ok(Self { - typ: header.typ.into(), - value, - }) - } - - fn marshal_to(&self, buf: &mut BytesMut) -> crate::vendor::sctp_proto::error::Result { - self.header().marshal_to(buf)?; - buf.extend(self.value.clone()); - Ok(buf.len()) - } - - fn value_length(&self) -> usize { - self.value.len() - } - - fn clone_to(&self) -> Box { - Box::new(self.clone()) - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/queue/mod.rs b/rs/moq-webrtc/src/vendor/sctp_proto/queue/mod.rs deleted file mode 100644 index 28092dfef88..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/queue/mod.rs +++ /dev/null @@ -1,7 +0,0 @@ -#[cfg(test)] -mod queue_test; - -pub(crate) mod outbound_queue; -pub(crate) mod payload_queue; -pub(crate) mod pending_queue; -pub(crate) mod reassembly_queue; diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue.rs b/rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue.rs deleted file mode 100644 index 68febec49f8..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue.rs +++ /dev/null @@ -1,204 +0,0 @@ -use std::time::Instant; -use std::vec::Vec; - -use super::payload_queue::PayloadQueue; -use super::pending_queue::PendingQueue; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::ChunkPayloadData; - -#[cfg(test)] -#[path = "outbound_queue_test.rs"] -mod tests; - -/// Coordinates the existing flat pending queue and TSN-indexed flight queue. -/// Message tags identify siblings without retaining a per-message allocation -/// or requiring their TSNs to be consecutive. Only abandonment scans siblings. -#[derive(Debug, Default)] -pub(crate) struct OutboundQueue { - pending: PendingQueue, - inflight: PayloadQueue, - next_message_id: u64, - next_unstarted_message_id: u64, -} - -impl OutboundQueue { - pub(crate) fn next_message_id(&self) -> u64 { - self.next_message_id - } - - pub(crate) fn push(&mut self, chunks: Vec) { - if chunks.is_empty() { - return; - } - let message_id = self.next_message_id; - // Never alias a still-queued message, even on counter exhaustion. - self.next_message_id = message_id.checked_add(1).expect("message ID exhausted"); - for mut chunk in chunks { - chunk.message_id = message_id; - self.pending.push(chunk); - } - } - - pub(crate) fn peek_pending(&self) -> Option<&ChunkPayloadData> { - self.pending.peek() - } - - pub(crate) fn start_timed_messages(&mut self, now: Instant) { - if self.next_unstarted_message_id != self.next_message_id { - self.pending.start_timed_messages(self.next_unstarted_message_id, now); - self.next_unstarted_message_id = self.next_message_id; - } - } - - /// Discard an expired, entirely unsent head message without allocating a TSN. - pub(crate) fn expire_pending(&mut self, now: Instant) -> Option<(u16, bool, usize)> { - let chunk = self.pending.peek()?; - if !chunk.beginning_fragment - || chunk.user_data.is_empty() - || chunk.payload_type == crate::vendor::sctp_proto::PayloadProtocolIdentifier::Dcep - || !chunk.deadline.is_some_and(|deadline| now >= deadline) - { - return None; - } - let stream = chunk.stream_identifier; - let unordered = chunk.unordered; - let message_id = chunk.message_id; - let bytes = self.pending.remove_message(message_id, |_| {}); - if !unordered { - self.pending.compact_ordered_ssns(stream); - } - Some((stream, unordered, bytes)) - } - - /// Assign the next TSN and retain the chunk in the hash-indexed flight queue. - pub(crate) fn send_next(&mut self, next_tsn: &mut u32, now: Instant) -> Option { - self.start_timed_messages(now); - let c = self.pending.peek()?; - let mut chunk = self.pending.pop(c.beginning_fragment, c.unordered)?; - chunk.tsn = *next_tsn; - *next_tsn = next_tsn.wrapping_add(1); - chunk.since = Some(now); - chunk.nsent = 1; - self.inflight.push_no_check(chunk.clone()); - Some(chunk) - } - - pub(crate) fn get(&self, tsn: u32) -> Option<&ChunkPayloadData> { - self.inflight.get(tsn) - } - - pub(crate) fn get_mut(&mut self, tsn: u32) -> Option<&mut ChunkPayloadData> { - self.inflight.get_mut(tsn) - } - - pub(crate) fn pop(&mut self, tsn: u32) -> Option { - self.inflight.pop(tsn) - } - - pub(crate) fn mark_as_acked(&mut self, tsn: u32) -> usize { - self.inflight.mark_as_acked(tsn) - } - - pub(crate) fn is_abandoned(&self, tsn: u32) -> bool { - self.inflight.get(tsn).is_some_and(|c| c.abandoned) - } - - /// Mark every sibling, irrespective of its TSN, and release pending payload. - /// Reserve a terminal TSN for the unsent tail so FORWARD-TSN advances even if every - /// transmitted fragment arrived but its SACK was lost. Return buffer credit - /// to release; TSN reservation and cursor advancement happen together here. - pub(crate) fn abandon(&mut self, tsn: u32, next_tsn: &mut u32) -> Option<(u16, usize)> { - let chunk = self.inflight.get(tsn)?; - let stream = chunk.stream_identifier; - let message_id = chunk.message_id; - if chunk.abandoned { - return Some((stream, 0)); - } - self.abandon_message(message_id, stream, next_tsn) - } - - /// A cumulatively acknowledged prefix may no longer have an inflight anchor. - pub(crate) fn expire_pending_tail(&mut self, now: Instant, next_tsn: &mut u32) -> Option<(u16, u64, usize)> { - let chunk = self.pending.peek()?; - if chunk.beginning_fragment - || chunk.payload_type == crate::vendor::sctp_proto::PayloadProtocolIdentifier::Dcep - || !chunk.deadline.is_some_and(|deadline| now >= deadline) - { - return None; - } - let message_id = chunk.message_id; - self.abandon_message(message_id, chunk.stream_identifier, next_tsn) - .map(|(id, bytes)| (id, message_id, bytes)) - } - - fn abandon_message(&mut self, message_id: u64, stream: u16, next_tsn: &mut u32) -> Option<(u16, usize)> { - let inflight_bytes = self.inflight.abandon_message(message_id); - let mut terminal = None; - let bytes = self.pending.remove_message(message_id, |mut chunk| { - chunk.user_data.clear(); - terminal = Some(chunk); - }); - if let Some(mut chunk) = terminal { - // These bytes have never been assigned TSNs or transmitted. One - // empty terminal marker suffices to skip the whole tail, avoiding - // an inflight map entry for every discarded fragment. - chunk.tsn = *next_tsn; - *next_tsn = next_tsn.wrapping_add(1); - chunk.beginning_fragment = false; - chunk.ending_fragment = true; - chunk.abandoned = true; - chunk.retransmit = false; - self.inflight.push_no_check(chunk); - } - Some((stream, bytes + inflight_bytes)) - } - - /// Expired messages with outstanding DATA or an unsent tail. Fully delivered - /// messages are excluded. Collect before abandonment mutates the queues so - /// expiry is independent of send limits. - pub(crate) fn expired_inflight(&self, now: Instant) -> Vec { - self.inflight - .sorted - .iter() - .copied() - .filter(|tsn| { - self.inflight.get(*tsn).is_some_and(|c| { - !c.abandoned - && c.deadline.is_some_and(|deadline| now >= deadline) - && (!c.acked || self.pending.contains_message(c.message_id)) - }) - }) - .collect() - } - - pub(crate) fn mark_all_to_retransmit(&mut self) { - self.inflight.mark_all_to_retransmit(); - } - - pub(crate) fn pending_contains_stream(&self, stream: u16) -> bool { - self.pending.contains_stream(stream) - } - - pub(crate) fn pending_len(&self) -> usize { - self.pending.len() - } - - pub(crate) fn pending_bytes(&self) -> usize { - self.pending.get_num_bytes() - } - - pub(crate) fn earliest_outstanding_tsn(&self) -> Option { - self.inflight - .sorted - .iter() - .copied() - .find(|tsn| self.inflight.get(*tsn).is_some_and(|c| !c.acked && !c.abandoned)) - } - - pub(crate) fn inflight_len(&self) -> usize { - self.inflight.len() - } - - pub(crate) fn inflight_bytes(&self) -> usize { - self.inflight.get_num_bytes() - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue_test.rs b/rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue_test.rs deleted file mode 100644 index 95840e3384b..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/queue/outbound_queue_test.rs +++ /dev/null @@ -1,331 +0,0 @@ -use super::*; -use bytes::Bytes; - -fn message(stream: u16, unordered: bool, fragments: usize) -> Vec { - (0..fragments) - .map(|i| ChunkPayloadData { - stream_identifier: stream, - unordered, - beginning_fragment: i == 0, - ending_fragment: i + 1 == fragments, - user_data: Bytes::from_static(b"fragment"), - ..Default::default() - }) - .collect() -} - -#[test] -fn unordered_priority_and_message_selection_survive_prefix_ack() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - q.push(message(1, false, 3)); - q.push(message(2, false, 1)); - q.push(message(3, true, 1)); - q.push(message(4, true, 1)); - assert_eq!(q.pending_len(), 6); - assert_eq!(q.pending_bytes(), 48); - - for (tsn, stream) in [(10, 3), (11, 4), (12, 1)] { - assert_eq!(q.peek_pending().unwrap().stream_identifier, stream); - assert_eq!(q.send_next(&mut { tsn }, now).unwrap().stream_identifier, stream); - q.pop(tsn).unwrap(); - } - // The entire sent prefix is gone, but the selected message must survive. - assert_eq!(q.inflight_len(), 0); - assert_eq!(q.inflight_bytes(), 0); - assert!(!q.peek_pending().unwrap().beginning_fragment); - assert!(q.pending_contains_stream(1)); - assert!(q.pending_contains_stream(2)); - assert!(!q.pending_contains_stream(3)); - q.push(message(5, true, 1)); - for (tsn, stream) in [(13, 1), (14, 1), (15, 5), (16, 2)] { - let c = q.send_next(&mut { tsn }, now).unwrap(); - assert_eq!(c.stream_identifier, stream); - assert_eq!(q.get(tsn).unwrap().tsn, tsn); - assert!(q.get(tsn.wrapping_sub(1)).is_none()); - q.pop(tsn).unwrap(); - } - assert!(q.peek_pending().is_none()); - assert!(q.send_next(&mut { 17 }, now).is_none()); - assert_eq!(q.pending_bytes(), 0); - assert_eq!(q.pending_len(), 0); - assert_eq!(q.inflight_bytes(), 0); - assert_eq!(q.inflight_len(), 0); -} - -#[test] -fn abandonment_discards_pending_tail_and_does_not_alias_unordered_messages() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - // Both messages deliberately have the same stream and SSN. - q.push(message(7, true, 5)); - q.push(message(7, true, 1)); - for tsn in 1..=3 { - q.send_next(&mut { tsn }, now).unwrap(); - } - q.pop(1).unwrap(); - assert_eq!(q.mark_as_acked(3), 8); - assert_eq!(q.mark_as_acked(3), 0); - assert_eq!(q.inflight_bytes(), 8); - let mut next_tsn = 4; - assert_eq!(q.abandon(2, &mut next_tsn), Some((7, 24))); - assert_eq!(next_tsn, 5); - assert!(q.is_abandoned(2)); - assert!(q.is_abandoned(3)); - assert!(!q.is_abandoned(1)); - assert_eq!(q.pending_len(), 1); - assert_eq!(q.pending_bytes(), 8); - assert_eq!(q.abandon(3, &mut next_tsn), Some((7, 0)), "release each byte only once"); - - // One terminal TSN skips the unsent tail without retaining its fragments. - assert!(q.is_abandoned(4)); - assert!(q.get(4).unwrap().user_data.is_empty()); - assert_eq!(q.get(4).unwrap().nsent, 0); - assert!(!q.get(4).unwrap().retransmit); - assert!(q.get(5).is_none()); - let next = q.send_next(&mut { next_tsn }, now).unwrap(); - assert!(next.beginning_fragment && next.ending_fragment); - assert!(!q.is_abandoned(5)); - assert!(!q.pending_contains_stream(7)); - for tsn in 2..=5 { - q.pop(tsn).unwrap(); - } - assert_eq!(q.inflight_len(), 0); - assert_eq!(q.inflight_bytes(), 0); -} - -#[test] -fn retransmission_excludes_pending_acked_and_abandoned_fragments() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - q.push(message(1, false, 2)); - q.push(message(2, false, 3)); - for tsn in 1..=4 { - q.send_next(&mut { tsn }, now).unwrap(); - } - q.mark_all_to_retransmit(); - assert_eq!(q.mark_as_acked(2), 8); - assert_eq!(q.abandon(1, &mut 5), Some((1, 8))); - q.mark_all_to_retransmit(); - for tsn in 1..=4 { - assert_eq!(q.get(tsn).unwrap().retransmit, tsn >= 3); - } - assert!(!q.peek_pending().unwrap().retransmit); - assert!(q.get(5).is_none(), "pending chunks have no TSN yet"); - assert_eq!(q.inflight_bytes(), 16); - assert_eq!(q.pending_bytes(), 8); - q.get_mut(3).unwrap().nsent += 1; - assert_eq!(q.get(3).unwrap().nsent, 2); - assert_eq!(q.get(4).unwrap().nsent, 1); -} - -#[test] -fn tsn_lookup_and_retirement_across_wraparound() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - let first = u32::MAX - 4; - for stream in 0..4 { - q.push(message(stream, false, 3)); - } - for i in 0..12 { - q.send_next(&mut { first.wrapping_add(i) }, now).unwrap(); - } - assert!(q.get(first.wrapping_sub(1)).is_none()); - assert!(q.get(first.wrapping_add(12)).is_none()); - assert!(q.pop(first.wrapping_add(1)).is_none()); - assert_eq!(q.abandon(u32::MAX, &mut 7), Some((1, 24))); - for i in 0..12 { - let tsn = first.wrapping_add(i); - for remaining in i..12 { - let next = first.wrapping_add(remaining); - assert_eq!(q.get(next).unwrap().stream_identifier, (remaining / 3) as u16); - assert_eq!(q.is_abandoned(next), (3..6).contains(&remaining)); - } - assert_eq!(q.pop(tsn).unwrap().tsn, tsn); - assert!(q.get(tsn).is_none()); - assert_eq!(q.inflight_len(), (11 - i) as usize); - assert_eq!( - q.inflight_bytes(), - ((i + 1)..12).filter(|n| !(3..6).contains(n)).count() * 8 - ); - } - assert_eq!(q.inflight_len(), 0); -} - -#[test] -fn tsn_lookup_after_repeated_insertions_and_removals() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - // Keep several messages in flight while repeatedly retiring and adding - // messages, checking lookup after repeated insertions and removals. - for tsn in 0..128u32 { - q.push(message(tsn as u16, false, 1)); - q.send_next(&mut { tsn }, now).unwrap(); - if tsn >= 8 { - q.pop(tsn - 8).unwrap(); - } - for outstanding in tsn.saturating_sub(7)..=tsn { - assert_eq!(q.get(outstanding).unwrap().stream_identifier, outstanding as u16); - } - } - for tsn in 120..128 { - q.pop(tsn).unwrap(); - } - assert_eq!(q.inflight_len(), 0); -} - -#[test] -fn reserving_abandoned_tail_tsns_crosses_wraparound() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - q.push(message(1, false, 4)); - q.push(message(2, false, 1)); - q.send_next(&mut { u32::MAX - 1 }, now).unwrap(); - let mut next_tsn = u32::MAX; - assert_eq!(q.abandon(u32::MAX - 1, &mut next_tsn), Some((1, 32))); - assert_eq!(next_tsn, 0); - assert_eq!(q.inflight_len(), 2); - assert_eq!(q.inflight_bytes(), 0); - q.mark_all_to_retransmit(); - for tsn in [u32::MAX - 1, u32::MAX] { - assert!(q.is_abandoned(tsn)); - assert!(!q.get(tsn).unwrap().retransmit); - } - q.send_next(&mut next_tsn, now).unwrap(); - assert_eq!(q.get(0).unwrap().stream_identifier, 2); - assert!(!q.is_abandoned(0)); - for tsn in [u32::MAX - 1, u32::MAX, 0] { - q.pop(tsn).unwrap(); - } - assert_eq!(q.inflight_bytes(), 0); - assert_eq!(q.inflight_len(), 0); -} - -#[test] -fn empty_message_does_not_block_scheduling() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - q.push(message(1, true, 0)); - assert!(q.peek_pending().is_none()); - assert!(q.send_next(&mut { 1 }, now).is_none()); - assert!(q.get(1).is_none()); - assert_eq!(q.abandon(1, &mut 1), None); - assert_eq!(q.mark_as_acked(1), 0); - q.push(message(2, false, 1)); - assert_eq!(q.send_next(&mut { 1 }, now).unwrap().stream_identifier, 2); - assert_eq!(q.pop(1).unwrap().stream_identifier, 2); - assert_eq!(q.pending_len(), 0); - assert_eq!(q.inflight_len(), 0); -} - -#[test] -fn abandonment_matches_interleaved_fragments_by_message_tag() { - let mut q = OutboundQueue::default(); - // Exercise the storage independently of the current non-interleaving DATA - // scheduler. Stream ID, SSN, and unordered flag deliberately match. - let first = u32::MAX - 2; - for (i, (mut a, mut b)) in message(7, true, 3).into_iter().zip(message(7, true, 3)).enumerate() { - a.message_id = 10; - b.message_id = 11; - a.tsn = first.wrapping_add(2 * i as u32); - b.tsn = a.tsn.wrapping_add(1); - q.inflight.push_no_check(a); - q.inflight.push_no_check(b); - } - q.mark_all_to_retransmit(); - let mut next_tsn = first.wrapping_add(6); - assert_eq!(q.abandon(first.wrapping_add(2), &mut next_tsn), Some((7, 24))); - assert_eq!(next_tsn, first.wrapping_add(6)); - for i in 0..6 { - let tsn = first.wrapping_add(i); - assert_eq!(q.is_abandoned(tsn), i % 2 == 0); - assert_eq!(q.get(tsn).unwrap().retransmit, i % 2 != 0); - assert_eq!(q.get(tsn).unwrap().message_id, 10 + u64::from(i % 2)); - } - for i in 0..6 { - q.pop(first.wrapping_add(i)).unwrap(); - } - assert_eq!(q.inflight_len(), 0); - assert_eq!(q.inflight_bytes(), 0); -} - -#[test] -fn removing_other_message_tail_preserves_pending_selection() { - let now = Instant::now(); - let mut q = OutboundQueue::default(); - q.push(message(1, false, 3)); - q.send_next(&mut 1, now).unwrap(); - // Model an independently started message whose remaining fragments are - // waiting behind the selected message in the flat pending queues. - let mut other = message(2, true, 3).into_iter(); - let mut first = other.next().unwrap(); - first.message_id = 1; - first.tsn = 2; - q.inflight.push_no_check(first); - for mut chunk in other { - chunk.message_id = 1; - q.pending.push(chunk); - } - q.next_message_id = 2; - q.send_next(&mut 3, now).unwrap(); - let mut next_tsn = 4; - assert_eq!(q.abandon(2, &mut next_tsn), Some((2, 24))); - assert_eq!(next_tsn, 5); - assert_eq!(q.pending_len(), 1); - let remaining = q.send_next(&mut next_tsn, now).unwrap(); - assert_eq!(remaining.stream_identifier, 1); - assert!(!remaining.beginning_fragment); - assert!(remaining.ending_fragment); - assert!(!remaining.abandoned); -} - -#[test] -fn pending_expiry_deadlines_ssn_wrap_and_exemptions() { - use core::time::Duration; - let now = Instant::now(); - for unordered in [false, true] { - for delay in [ - Duration::ZERO, - Duration::from_millis(10), - Duration::from_secs(u32::MAX as u64), - ] { - let mut q = OutboundQueue::default(); - let mut expired = message(1, unordered, 3); - for c in &mut expired { - c.deadline = Some(now + delay); - c.stream_sequence_number = u16::MAX; - } - q.push(expired); - q.push(message(1, unordered, 1)); - if !delay.is_zero() { - assert!(q.expire_pending(now).is_none()); - } - assert_eq!(q.expire_pending(now + delay), Some((1, unordered, 24))); - assert_eq!(q.pending_bytes(), 8); - assert!(q.expire_pending(now + delay).is_none()); - let mut tsn = 99; - let fresh = q.send_next(&mut tsn, now + delay).unwrap(); - assert_eq!(fresh.tsn, 99); - assert_eq!(tsn, 100); - assert_eq!(fresh.stream_sequence_number, if unordered { 0 } else { u16::MAX }); - } - } - for exemption in 0..3 { - let mut q = OutboundQueue::default(); - let mut chunks = message(1, false, 2); - for c in &mut chunks { - c.deadline = Some(now); - if exemption == 0 { - c.payload_type = crate::vendor::sctp_proto::PayloadProtocolIdentifier::Dcep; - } - if exemption == 1 { - c.user_data.clear(); - } - } - q.push(chunks); - if exemption == 2 { - q.send_next(&mut 10, now).unwrap(); - } - assert!(q.expire_pending(now).is_none()); - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/queue/payload_queue.rs b/rs/moq-webrtc/src/vendor/sctp_proto/queue/payload_queue.rs deleted file mode 100644 index 2ee34494f4c..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/queue/payload_queue.rs +++ /dev/null @@ -1,199 +0,0 @@ -use crate::vendor::sctp_proto::chunk::chunk_payload_data::ChunkPayloadData; -use crate::vendor::sctp_proto::chunk::chunk_selective_ack::GapAckBlock; -use crate::vendor::sctp_proto::util::*; - -use std::collections::HashMap; -use std::collections::VecDeque; -use std::string::String; -use std::vec::Vec; - -#[derive(Default, Debug)] -pub(crate) struct PayloadQueue { - // length: usize, - chunk_map: HashMap, - pub(crate) sorted: VecDeque, - dup_tsn: Vec, - n_bytes: usize, -} - -impl PayloadQueue { - pub(crate) fn new() -> Self { - PayloadQueue::default() - } - - pub(crate) fn update_sorted_keys(&mut self) { - self.sorted.make_contiguous().sort_by(|a, b| { - if sna32lt(*a, *b) { - core::cmp::Ordering::Less - } else { - core::cmp::Ordering::Greater - } - }); - } - - pub(crate) fn can_push(&self, p: &ChunkPayloadData, cumulative_tsn: u32) -> bool { - !(self.chunk_map.contains_key(&p.tsn) || sna32lte(p.tsn, cumulative_tsn)) - } - - pub(crate) fn push_no_check(&mut self, p: ChunkPayloadData) { - self.n_bytes += p.user_data.len(); - self.sorted.push_back(p.tsn); - self.chunk_map.insert(p.tsn, p); - //self.length += 1; - self.update_sorted_keys(); - } - - /// push pushes a payload data. If the payload data is already in our queue or - /// older than our cumulative_tsn marker, it will be recored as duplications, - /// which can later be retrieved using popDuplicates. - pub(crate) fn push(&mut self, p: ChunkPayloadData, cumulative_tsn: u32) -> bool { - let ok = self.chunk_map.contains_key(&p.tsn); - if ok || sna32lte(p.tsn, cumulative_tsn) { - // Found the packet, log in dups - self.dup_tsn.push(p.tsn); - return false; - } - - self.n_bytes += p.user_data.len(); - self.sorted.push_back(p.tsn); - self.chunk_map.insert(p.tsn, p); - //self.length += 1; - self.update_sorted_keys(); - - true - } - - /// pop pops only if the oldest chunk's TSN matches the given TSN. - pub(crate) fn pop(&mut self, tsn: u32) -> Option { - if !self.sorted.is_empty() && tsn == self.sorted[0] { - self.sorted.pop_front(); - if let Some(c) = self.chunk_map.remove(&tsn) { - //self.length -= 1; - self.n_bytes = self.n_bytes.saturating_sub(c.user_data.len()); - return Some(c); - } - } - - None - } - - /// Removes every queued chunk with a TSN at or before `cumulative_tsn`. - /// - /// Used when a FORWARD-TSN moves the cumulative TSN point past chunks the - /// peer abandoned. The cost is proportional to the number of queued chunks, - /// not to the size of the TSN jump: `cumulative_tsn` comes off the wire and - /// may be up to 2^31 ahead of the current point. - pub(crate) fn pop_up_to(&mut self, cumulative_tsn: u32) { - let chunk_map = &mut self.chunk_map; - let n_bytes = &mut self.n_bytes; - self.sorted.retain(|tsn| { - if sna32lte(*tsn, cumulative_tsn) { - if let Some(c) = chunk_map.remove(tsn) { - *n_bytes = n_bytes.saturating_sub(c.user_data.len()); - } - false - } else { - true - } - }); - } - - /// get returns reference to chunkPayloadData with the given TSN value. - pub(crate) fn get(&self, tsn: u32) -> Option<&ChunkPayloadData> { - self.chunk_map.get(&tsn) - } - - pub(crate) fn get_mut(&mut self, tsn: u32) -> Option<&mut ChunkPayloadData> { - self.chunk_map.get_mut(&tsn) - } - - /// Abandon siblings by identity, including nonconsecutive TSNs. - pub(crate) fn abandon_message(&mut self, message_id: u64) -> usize { - let mut released = 0; - for chunk in self.chunk_map.values_mut() { - if chunk.message_id == message_id { - released += chunk.user_data.len(); - chunk.user_data.clear(); - chunk.abandoned = true; - chunk.retransmit = false; - } - } - self.n_bytes -= released; - released - } - - pub(crate) fn mark_all_to_retransmit(&mut self) { - for chunk in self.chunk_map.values_mut() { - if !chunk.acked && !chunk.abandoned { - chunk.retransmit = true; - } - } - } - - /// popDuplicates returns an array of TSN values that were found duplicate. - pub(crate) fn pop_duplicates(&mut self) -> Vec { - core::mem::take(&mut self.dup_tsn) - } - - /// Gap offsets are nonzero u16 distances, not wrapping sequence numbers. - /// Farther TSNs remain queued for reporting once the cumulative TSN advances. - pub(crate) fn get_gap_ack_blocks(&self, cumulative_tsn: u32) -> Vec { - let mut gap_ack_blocks: Vec = vec![]; - for tsn in &self.sorted { - let Ok(offset) = u16::try_from(tsn.wrapping_sub(cumulative_tsn)) else { - continue; - }; - if offset == 0 { - continue; - } - - match gap_ack_blocks.last_mut() { - Some(block) if block.end.checked_add(1) == Some(offset) => block.end = offset, - _ => gap_ack_blocks.push(GapAckBlock { - start: offset, - end: offset, - }), - } - } - - gap_ack_blocks - } - - pub(crate) fn get_gap_ack_blocks_string(&self, cumulative_tsn: u32) -> String { - let mut s = format!("cumTSN={}", cumulative_tsn); - for b in self.get_gap_ack_blocks(cumulative_tsn) { - s += format!(",{}-{}", b.start, b.end).as_str(); - } - s - } - - pub(crate) fn mark_as_acked(&mut self, tsn: u32) -> usize { - if let Some(c) = self.chunk_map.get_mut(&tsn) { - c.acked = true; - c.retransmit = false; - let n = c.user_data.len(); - self.n_bytes -= n; - c.user_data.clear(); - n - } else { - 0 - } - } - - pub(crate) fn get_last_tsn_received(&self) -> Option<&u32> { - self.sorted.back() - } - - pub(crate) fn get_num_bytes(&self) -> usize { - self.n_bytes - } - - pub(crate) fn len(&self) -> usize { - //assert_eq!(self.chunk_map.len(), self.length); - self.chunk_map.len() - } - - pub(crate) fn is_empty(&self) -> bool { - self.len() == 0 - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/queue/pending_queue.rs b/rs/moq-webrtc/src/vendor/sctp_proto/queue/pending_queue.rs deleted file mode 100644 index 9ad254183c1..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/queue/pending_queue.rs +++ /dev/null @@ -1,179 +0,0 @@ -use crate::vendor::sctp_proto::chunk::chunk_payload_data::ChunkPayloadData; - -use core::time::Duration; -use std::collections::VecDeque; -use std::time::Instant; - -/// pendingBaseQueue -pub(crate) type PendingBaseQueue = VecDeque; - -/// pendingQueue -#[derive(Debug, Default)] -pub(crate) struct PendingQueue { - unordered_queue: PendingBaseQueue, - ordered_queue: PendingBaseQueue, - queue_len: usize, - n_bytes: usize, - selected: bool, - unordered_is_selected: bool, -} - -impl PendingQueue { - pub(crate) fn new() -> Self { - PendingQueue::default() - } - - pub(crate) fn push(&mut self, c: ChunkPayloadData) { - self.n_bytes += c.user_data.len(); - if c.unordered { - self.unordered_queue.push_back(c); - } else { - self.ordered_queue.push_back(c); - } - self.queue_len += 1; - } - - /// Start lifetimes for the newly queued suffix using the next transmit poll's time. - /// Both queues retain message-ID order, so old pending messages need no rescan. - pub(crate) fn start_timed_messages(&mut self, first_message_id: u64, now: Instant) { - for queue in [&mut self.ordered_queue, &mut self.unordered_queue] { - for chunk in queue - .iter_mut() - .rev() - .take_while(|chunk| chunk.message_id >= first_message_id) - { - if chunk.deadline.is_some() - || chunk.payload_type == crate::vendor::sctp_proto::PayloadProtocolIdentifier::Dcep - { - continue; - } - if let Some((crate::vendor::sctp_proto::ReliabilityType::Timed, lifetime)) = chunk.reliability { - chunk.deadline = now.checked_add(Duration::from_millis(u64::from(lifetime))); - } - } - } - } - - pub(crate) fn peek(&self) -> Option<&ChunkPayloadData> { - if self.selected { - if self.unordered_is_selected { - return self.unordered_queue.front(); - } else { - return self.ordered_queue.front(); - } - } - - let c = self.unordered_queue.front(); - - if c.is_some() { - return c; - } - - self.ordered_queue.front() - } - - pub(crate) fn pop(&mut self, beginning_fragment: bool, unordered: bool) -> Option { - let popped = if self.selected { - let popped = if self.unordered_is_selected { - self.unordered_queue.pop_front() - } else { - self.ordered_queue.pop_front() - }; - if let Some(p) = &popped { - if p.ending_fragment { - self.selected = false; - } - } - popped - } else { - if !beginning_fragment { - return None; - } - if unordered { - let popped = { self.unordered_queue.pop_front() }; - if let Some(p) = &popped { - if !p.ending_fragment { - self.selected = true; - self.unordered_is_selected = true; - } - } - popped - } else { - let popped = { self.ordered_queue.pop_front() }; - if let Some(p) = &popped { - if !p.ending_fragment { - self.selected = true; - self.unordered_is_selected = false; - } - } - popped - } - }; - - if let Some(p) = &popped { - self.n_bytes -= p.user_data.len(); - self.queue_len -= 1; - } - - popped - } - - /// Close the SSN gap after removing an entirely unsent ordered message. - pub(crate) fn compact_ordered_ssns(&mut self, stream_identifier: u16) { - for chunk in &mut self.ordered_queue { - if chunk.stream_identifier == stream_identifier { - chunk.stream_sequence_number = chunk.stream_sequence_number.wrapping_sub(1); - } - } - } - - pub(crate) fn get_num_bytes(&self) -> usize { - self.n_bytes - } - - /// Remove a message without allocating a temporary collection. Selection - /// persists when removing a different message from the pending queues. - pub(crate) fn remove_message(&mut self, message_id: u64, mut on_remove: impl FnMut(ChunkPayloadData)) -> usize { - if self.selected && self.peek().is_some_and(|c| c.message_id == message_id) { - self.selected = false; - } - let mut removed_bytes = 0; - let mut removed_chunks = 0; - for queue in [&mut self.ordered_queue, &mut self.unordered_queue] { - queue.retain_mut(|chunk| { - if chunk.message_id != message_id { - return true; - } - removed_bytes += chunk.user_data.len(); - removed_chunks += 1; - on_remove(core::mem::take(chunk)); - false - }); - } - self.n_bytes -= removed_bytes; - self.queue_len -= removed_chunks; - removed_bytes - } - - pub(crate) fn len(&self) -> usize { - self.queue_len - } - - pub(crate) fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub(crate) fn contains_message(&self, message_id: u64) -> bool { - self.unordered_queue - .iter() - .chain(self.ordered_queue.iter()) - .any(|chunk| chunk.message_id == message_id) - } - - pub(crate) fn contains_stream(&self, stream_identifier: u16) -> bool { - self.unordered_queue - .iter() - .chain(self.ordered_queue.iter()) - .any(|chunk| chunk.stream_identifier == stream_identifier) - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/queue/queue_test.rs b/rs/moq-webrtc/src/vendor/sctp_proto/queue/queue_test.rs deleted file mode 100644 index 144041ad9b0..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/queue/queue_test.rs +++ /dev/null @@ -1,1293 +0,0 @@ -use crate::vendor::sctp_proto::error::{Error, Result}; - -use bytes::{Bytes, BytesMut}; -use std::vec::Vec; - -/////////////////////////////////////////////////////////////////// -//payload_queue_test -/////////////////////////////////////////////////////////////////// -use super::payload_queue::*; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier}; -use crate::vendor::sctp_proto::chunk::chunk_selective_ack::GapAckBlock; - -fn make_payload(tsn: u32, n_bytes: usize) -> ChunkPayloadData { - ChunkPayloadData { - tsn, - user_data: { - let mut b = BytesMut::new(); - b.resize(n_bytes, 0); - b.freeze() - }, - ..Default::default() - } -} - -#[test] -fn test_payload_queue_push_no_check() -> Result<()> { - let mut pq = PayloadQueue::new(); - - pq.push_no_check(make_payload(0, 10)); - assert_eq!(10, pq.get_num_bytes(), "total bytes mismatch"); - assert_eq!(1, pq.len(), "item count mismatch"); - pq.push_no_check(make_payload(1, 11)); - assert_eq!(21, pq.get_num_bytes(), "total bytes mismatch"); - assert_eq!(2, pq.len(), "item count mismatch"); - pq.push_no_check(make_payload(2, 12)); - assert_eq!(33, pq.get_num_bytes(), "total bytes mismatch"); - assert_eq!(3, pq.len(), "item count mismatch"); - - for i in 0..3 { - assert!(!pq.sorted.is_empty(), "should not be empty"); - let c = pq.pop(i); - assert!(c.is_some(), "pop should succeed"); - if let Some(c) = c { - assert_eq!(i, c.tsn, "TSN should match"); - } - } - - assert_eq!(0, pq.get_num_bytes(), "total bytes mismatch"); - assert_eq!(0, pq.len(), "item count mismatch"); - - assert!(pq.sorted.is_empty(), "should be empty"); - pq.push_no_check(make_payload(3, 13)); - assert_eq!(13, pq.get_num_bytes(), "total bytes mismatch"); - pq.push_no_check(make_payload(4, 14)); - assert_eq!(27, pq.get_num_bytes(), "total bytes mismatch"); - - for i in 3..5 { - assert!(!pq.sorted.is_empty(), "should not be empty"); - let c = pq.pop(i); - assert!(c.is_some(), "pop should succeed"); - if let Some(c) = c { - assert_eq!(i, c.tsn, "TSN should match"); - } - } - - assert_eq!(0, pq.get_num_bytes(), "total bytes mismatch"); - assert_eq!(0, pq.len(), "item count mismatch"); - - Ok(()) -} - -#[test] -fn test_payload_queue_get_gap_ack_block() -> Result<()> { - let mut pq = PayloadQueue::new(); - - pq.push(make_payload(1, 0), 0); - pq.push(make_payload(2, 0), 0); - pq.push(make_payload(3, 0), 0); - pq.push(make_payload(4, 0), 0); - pq.push(make_payload(5, 0), 0); - pq.push(make_payload(6, 0), 0); - - let gab1 = [GapAckBlock { start: 1, end: 6 }]; - let gab2 = pq.get_gap_ack_blocks(0); - assert!(!gab2.is_empty()); - assert_eq!(gab2.len(), 1); - - assert_eq!(gab1[0].start, gab2[0].start); - assert_eq!(gab1[0].end, gab2[0].end); - - pq.push(make_payload(8, 0), 0); - pq.push(make_payload(9, 0), 0); - - let gab1 = [GapAckBlock { start: 1, end: 6 }, GapAckBlock { start: 8, end: 9 }]; - let gab2 = pq.get_gap_ack_blocks(0); - assert!(!gab2.is_empty()); - assert_eq!(gab2.len(), 2); - - assert_eq!(gab1[0].start, gab2[0].start); - assert_eq!(gab1[0].end, gab2[0].end); - assert_eq!(gab1[1].start, gab2[1].start); - assert_eq!(gab1[1].end, gab2[1].end); - - Ok(()) -} - -#[test] -fn test_payload_queue_gap_ack_blocks_wraparound() { - for cumulative_tsn in [0, u32::MAX - 2, u32::MAX] { - let mut pq = PayloadQueue::new(); - for offset in [6, 4, 2, 3] { - assert!(pq.push(make_payload(cumulative_tsn.wrapping_add(offset), 1), cumulative_tsn)); - } - - let gaps: Vec<_> = pq - .get_gap_ack_blocks(cumulative_tsn) - .iter() - .map(|gap| (gap.start, gap.end)) - .collect(); - assert_eq!(gaps, [(2, 4), (6, 6)], "cumulative TSN {cumulative_tsn}"); - } -} - -#[test] -fn test_payload_queue_gap_ack_blocks_at_u16_limit() { - for cumulative_tsn in [0, u32::MAX - 1] { - let mut pq = PayloadQueue::new(); - for offset in [2, 65_534, 65_535, 65_536, 65_537] { - assert!(pq.push(make_payload(cumulative_tsn.wrapping_add(offset), 1), cumulative_tsn)); - } - - let gaps: Vec<_> = pq - .get_gap_ack_blocks(cumulative_tsn) - .iter() - .map(|gap| (gap.start, gap.end)) - .collect(); - assert_eq!(gaps, [(2, 2), (65_534, 65_535)], "cumulative TSN {cumulative_tsn}"); - assert_eq!(pq.len(), 5); - assert_eq!(pq.get_num_bytes(), 5); - } -} - -#[test] -fn test_payload_queue_gap_ack_blocks_retain_unrepresentable_offsets() { - for cumulative_tsn in [0, u32::MAX - 1] { - for offset in [65_536, 65_537, (1 << 31) - 1] { - let mut pq = PayloadQueue::new(); - let tsn = cumulative_tsn.wrapping_add(offset); - assert!(pq.push(make_payload(tsn, 1), cumulative_tsn)); - assert!(pq.get_gap_ack_blocks(cumulative_tsn).is_empty()); - assert_eq!(pq.len(), 1); - assert_eq!(pq.get_num_bytes(), 1); - assert!(pq.get(tsn).is_some()); - - let advanced_tsn = cumulative_tsn.wrapping_add(offset - 2); - let gaps: Vec<_> = pq - .get_gap_ack_blocks(advanced_tsn) - .iter() - .map(|gap| (gap.start, gap.end)) - .collect(); - assert_eq!(gaps, [(2, 2)]); - } - } -} - -#[test] -fn test_payload_queue_get_last_tsn_received() -> Result<()> { - let mut pq = PayloadQueue::new(); - - // empty queie should return false - let ok = pq.get_last_tsn_received(); - assert!(ok.is_none(), "should be none"); - - let ok = pq.push(make_payload(20, 0), 0); - assert!(ok, "should be true"); - let tsn = pq.get_last_tsn_received(); - assert!(tsn.is_some(), "should be false"); - assert_eq!(Some(&20), tsn, "should match"); - - // append should work - let ok = pq.push(make_payload(21, 0), 0); - assert!(ok, "should be true"); - let tsn = pq.get_last_tsn_received(); - assert!(tsn.is_some(), "should be false"); - assert_eq!(Some(&21), tsn, "should match"); - - // check if sorting applied - let ok = pq.push(make_payload(19, 0), 0); - assert!(ok, "should be true"); - let tsn = pq.get_last_tsn_received(); - assert!(tsn.is_some(), "should be false"); - assert_eq!(Some(&21), tsn, "should match"); - - Ok(()) -} - -#[test] -fn test_payload_queue_mark_all_to_retransmit() -> Result<()> { - let mut pq = PayloadQueue::new(); - - for i in 0..3 { - pq.push(make_payload(i + 1, 10), 0); - } - pq.mark_as_acked(2); - pq.mark_all_to_retransmit(); - - let c = pq.get(1); - assert!(c.is_some(), "should be true"); - assert!(c.unwrap().retransmit, "should be marked as retransmit"); - let c = pq.get(2); - assert!(c.is_some(), "should be true"); - assert!(!c.unwrap().retransmit, "should NOT be marked as retransmit"); - let c = pq.get(3); - assert!(c.is_some(), "should be true"); - assert!(c.unwrap().retransmit, "should be marked as retransmit"); - - Ok(()) -} - -#[test] -fn test_payload_queue_reset_retransmit_flag_on_ack() -> Result<()> { - let mut pq = PayloadQueue::new(); - - for i in 0..4 { - pq.push(make_payload(i + 1, 10), 0); - } - - pq.mark_all_to_retransmit(); - pq.mark_as_acked(2); // should cancel retransmission for TSN 2 - pq.mark_as_acked(4); // should cancel retransmission for TSN 4 - - let c = pq.get(1); - assert!(c.is_some(), "should be true"); - assert!(c.unwrap().retransmit, "should be marked as retransmit"); - let c = pq.get(2); - assert!(c.is_some(), "should be true"); - assert!(!c.unwrap().retransmit, "should NOT be marked as retransmit"); - let c = pq.get(3); - assert!(c.is_some(), "should be true"); - assert!(c.unwrap().retransmit, "should be marked as retransmit"); - let c = pq.get(4); - assert!(c.is_some(), "should be true"); - assert!(!c.unwrap().retransmit, "should NOT be marked as retransmit"); - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//pending_queue_test -/////////////////////////////////////////////////////////////////// -use super::pending_queue::*; - -const NO_FRAGMENT: usize = 0; -const FRAG_BEGIN: usize = 1; -const FRAG_MIDDLE: usize = 2; -const FRAG_END: usize = 3; - -fn make_data_chunk(tsn: u32, unordered: bool, frag: usize) -> ChunkPayloadData { - let mut b = false; - let mut e = false; - - match frag { - NO_FRAGMENT => { - b = true; - e = true; - } - FRAG_BEGIN => { - b = true; - } - FRAG_END => e = true, - _ => {} - }; - - ChunkPayloadData { - tsn, - unordered, - beginning_fragment: b, - ending_fragment: e, - user_data: { - let mut b = BytesMut::new(); - b.resize(10, 0); // always 10 bytes - b.freeze() - }, - ..Default::default() - } -} - -#[test] -fn test_pending_base_queue_push_and_pop() -> Result<()> { - let mut pq = PendingBaseQueue::new(); - pq.push_back(make_data_chunk(0, false, NO_FRAGMENT)); - pq.push_back(make_data_chunk(1, false, NO_FRAGMENT)); - pq.push_back(make_data_chunk(2, false, NO_FRAGMENT)); - - for i in 0..3 { - let c = pq.get(i); - assert!(c.is_some(), "should not be none"); - assert_eq!(i as u32, c.unwrap().tsn, "TSN should match"); - } - - for i in 0..3 { - let c = pq.pop_front(); - assert!(c.is_some(), "should not be none"); - assert_eq!(i, c.unwrap().tsn, "TSN should match"); - } - - pq.push_back(make_data_chunk(3, false, NO_FRAGMENT)); - pq.push_back(make_data_chunk(4, false, NO_FRAGMENT)); - - for i in 3..5 { - let c = pq.pop_front(); - assert!(c.is_some(), "should not be none"); - assert_eq!(i, c.unwrap().tsn, "TSN should match"); - } - Ok(()) -} - -#[test] -fn test_pending_base_queue_out_of_bounce() -> Result<()> { - let mut pq = PendingBaseQueue::new(); - assert!(pq.pop_front().is_none(), "should be none"); - assert!(pq.front().is_none(), "should be none"); - - pq.push_back(make_data_chunk(0, false, NO_FRAGMENT)); - assert!(pq.get(1).is_none(), "should be none"); - - Ok(()) -} - -// NOTE: TSN is not used in pendingQueue in the actual usage. -// Following tests use TSN field as a chunk ID. -#[test] -fn test_pending_queue_push_and_pop() -> Result<()> { - let mut pq = PendingQueue::new(); - pq.push(make_data_chunk(0, false, NO_FRAGMENT)); - assert_eq!(10, pq.get_num_bytes(), "total bytes mismatch"); - pq.push(make_data_chunk(1, false, NO_FRAGMENT)); - assert_eq!(20, pq.get_num_bytes(), "total bytes mismatch"); - pq.push(make_data_chunk(2, false, NO_FRAGMENT)); - assert_eq!(30, pq.get_num_bytes(), "total bytes mismatch"); - - for i in 0..3 { - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(i, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error: {}", i); - } - - assert_eq!(0, pq.get_num_bytes(), "total bytes mismatch"); - - pq.push(make_data_chunk(3, false, NO_FRAGMENT)); - assert_eq!(10, pq.get_num_bytes(), "total bytes mismatch"); - pq.push(make_data_chunk(4, false, NO_FRAGMENT)); - assert_eq!(20, pq.get_num_bytes(), "total bytes mismatch"); - - for i in 3..5 { - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(i, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error: {}", i); - } - - assert_eq!(0, pq.get_num_bytes(), "total bytes mismatch"); - - Ok(()) -} - -#[test] -fn test_pending_queue_unordered_wins() -> Result<()> { - let mut pq = PendingQueue::new(); - - pq.push(make_data_chunk(0, false, NO_FRAGMENT)); - assert_eq!(10, pq.get_num_bytes(), "total bytes mismatch"); - pq.push(make_data_chunk(1, true, NO_FRAGMENT)); - assert_eq!(20, pq.get_num_bytes(), "total bytes mismatch"); - pq.push(make_data_chunk(2, false, NO_FRAGMENT)); - assert_eq!(30, pq.get_num_bytes(), "total bytes mismatch"); - pq.push(make_data_chunk(3, true, NO_FRAGMENT)); - assert_eq!(40, pq.get_num_bytes(), "total bytes mismatch"); - - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(1, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error"); - - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(3, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error"); - - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(0, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error"); - - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(2, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error"); - - assert_eq!(0, pq.get_num_bytes(), "total bytes mismatch"); - - Ok(()) -} - -#[test] -fn test_pending_queue_fragments() -> Result<()> { - let mut pq = PendingQueue::new(); - pq.push(make_data_chunk(0, false, FRAG_BEGIN)); - pq.push(make_data_chunk(1, false, FRAG_MIDDLE)); - pq.push(make_data_chunk(2, false, FRAG_END)); - pq.push(make_data_chunk(3, true, FRAG_BEGIN)); - pq.push(make_data_chunk(4, true, FRAG_MIDDLE)); - pq.push(make_data_chunk(5, true, FRAG_END)); - - let expects = vec![3, 4, 5, 0, 1, 2]; - - for exp in expects { - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(exp, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error: {}", exp); - } - - Ok(()) -} - -// Once decided ordered or unordered, the decision should persist until -// it pops a chunk with ending_fragment flags set to true. -#[test] -fn test_pending_queue_selection_persistence() -> Result<()> { - let mut pq = PendingQueue::new(); - pq.push(make_data_chunk(0, false, FRAG_BEGIN)); - - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(0, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error: {}", 0); - - pq.push(make_data_chunk(1, true, NO_FRAGMENT)); - pq.push(make_data_chunk(2, false, FRAG_MIDDLE)); - pq.push(make_data_chunk(3, false, FRAG_END)); - - let expects = vec![2, 3, 1]; - - for exp in expects { - let c = pq.peek(); - assert!(c.is_some(), "peek error"); - let c = c.unwrap(); - assert_eq!(exp, c.tsn, "TSN should match"); - let (beginning_fragment, unordered) = (c.beginning_fragment, c.unordered); - let result = pq.pop(beginning_fragment, unordered); - assert!(result.is_some(), "should not error: {}", exp); - } - - Ok(()) -} - -/////////////////////////////////////////////////////////////////// -//reassembly_queue_test -/////////////////////////////////////////////////////////////////// -use super::reassembly_queue::*; - -#[test] -fn test_reassembly_queue_ordered_fragments() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - tsn: 1, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - ending_fragment: true, - tsn: 2, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"DEFG"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "chunk set should be complete"); - assert_eq!(7, rq.get_num_bytes(), "num bytes mismatch"); - - let mut buf = vec![0u8; 16]; - - if let Some(chunks) = rq.read() { - let n = chunks.read(&mut buf)?; - assert_eq!(7, n, "should received 7 bytes"); - assert_eq!(0, rq.get_num_bytes(), "num bytes mismatch"); - assert_eq!(chunks.ppi, org_ppi, "should have valid ppi"); - assert_eq!(&buf[..n], b"ABCDEFG", "data should match"); - } else { - panic!(); - } - - Ok(()) -} - -#[test] -fn test_reassembly_queue_unordered_fragments() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - beginning_fragment: true, - tsn: 1, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - tsn: 2, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"DEFG"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(7, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - ending_fragment: true, - tsn: 3, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"H"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "chunk set should be complete"); - assert_eq!(8, rq.get_num_bytes(), "num bytes mismatch"); - - let mut buf = vec![0u8; 16]; - - if let Some(chunks) = rq.read() { - let n = chunks.read(&mut buf)?; - assert_eq!(8, n, "should received 8 bytes"); - assert_eq!(0, rq.get_num_bytes(), "num bytes mismatch"); - assert_eq!(chunks.ppi, org_ppi, "should have valid ppi"); - assert_eq!(&buf[..n], b"ABCDEFGH", "data should match"); - } else { - panic!(); - } - - Ok(()) -} - -#[test] -fn test_reassembly_queue_ordered_and_unordered_fragments() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - let org_ppi = PayloadProtocolIdentifier::Binary; - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - ending_fragment: true, - tsn: 1, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "chunk set should be complete"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - beginning_fragment: true, - ending_fragment: true, - tsn: 2, - stream_sequence_number: 1, - user_data: Bytes::from_static(b"DEF"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "chunk set should be complete"); - assert_eq!(6, rq.get_num_bytes(), "num bytes mismatch"); - - // - // Now we have two complete chunks ready to read in the reassemblyQueue. - // - - let mut buf = vec![0u8; 16]; - - // Should read unordered chunks first - if let Some(chunks) = rq.read() { - let n = chunks.read(&mut buf)?; - assert_eq!(3, n, "should received 3 bytes"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - assert_eq!(chunks.ppi, org_ppi, "should have valid ppi"); - assert_eq!(&buf[..n], b"DEF", "data should match"); - } else { - panic!(); - } - - // Next should read ordered chunks - if let Some(chunks) = rq.read() { - let n = chunks.read(&mut buf)?; - assert_eq!(3, n, "should received 3 bytes"); - assert_eq!(0, rq.get_num_bytes(), "num bytes mismatch"); - assert_eq!(chunks.ppi, org_ppi, "should have valid ppi"); - assert_eq!(&buf[..n], b"ABC", "data should match"); - } else { - panic!(); - } - - Ok(()) -} - -#[test] -fn test_reassembly_queue_unordered_complete_skips_incomplete() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - beginning_fragment: true, - tsn: 10, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"IN"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(2, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - ending_fragment: true, - tsn: 12, // <- incongiguous - stream_sequence_number: 1, - user_data: Bytes::from_static(b"COMPLETE"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(10, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - beginning_fragment: true, - ending_fragment: true, - tsn: 13, - stream_sequence_number: 1, - user_data: Bytes::from_static(b"GOOD"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "chunk set should be complete"); - assert_eq!(14, rq.get_num_bytes(), "num bytes mismatch"); - - // - // Now we have two complete chunks ready to read in the reassemblyQueue. - // - - let mut buf = vec![0u8; 16]; - - // Should pick the one that has "GOOD" - if let Some(chunks) = rq.read() { - let n = chunks.read(&mut buf)?; - assert_eq!(4, n, "should receive 4 bytes"); - assert_eq!(10, rq.get_num_bytes(), "num bytes mismatch"); - assert_eq!(chunks.ppi, org_ppi, "should have valid ppi"); - assert_eq!(&buf[..n], b"GOOD", "data should match"); - } else { - panic!(); - } - - Ok(()) -} - -#[test] -fn test_reassembly_queue_ignores_chunk_with_wrong_si() -> Result<()> { - let mut rq = ReassemblyQueue::new(123, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - stream_identifier: 124, - beginning_fragment: true, - ending_fragment: true, - tsn: 10, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"IN"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk should be ignored"); - assert_eq!(0, rq.get_num_bytes(), "num bytes mismatch"); - Ok(()) -} - -#[test] -fn test_reassembly_queue_ignores_chunk_with_stale_ssn() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - rq.next_ssn = 7; // forcibly set expected SSN to 7 - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - ending_fragment: true, - tsn: 10, - stream_sequence_number: 6, // <-- stale - user_data: Bytes::from_static(b"IN"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk should not be ignored"); - assert_eq!(0, rq.get_num_bytes(), "num bytes mismatch"); - - Ok(()) -} - -#[test] -fn test_reassembly_queue_should_fail_to_read_incomplete_chunk() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - tsn: 123, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"IN"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "the set should not be complete"); - assert_eq!(2, rq.get_num_bytes(), "num bytes mismatch"); - - let result = rq.read(); - assert!(result.is_none(), "read() should not succeed"); - assert_eq!(2, rq.get_num_bytes(), "num bytes mismatch"); - - Ok(()) -} - -#[test] -fn test_reassembly_queue_should_fail_to_read_if_the_nex_ssn_is_not_ready() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - ending_fragment: true, - tsn: 123, - stream_sequence_number: 1, - user_data: Bytes::from_static(b"IN"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "the set should be complete"); - assert_eq!(2, rq.get_num_bytes(), "num bytes mismatch"); - - let result = rq.read(); - assert!(result.is_none(), "read() should not succeed"); - assert_eq!(2, rq.get_num_bytes(), "num bytes mismatch"); - - Ok(()) -} - -#[test] -fn test_reassembly_queue_detect_buffer_too_short() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - ending_fragment: true, - tsn: 123, - stream_sequence_number: 0, - user_data: Bytes::from_static(b"0123456789"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "the set should be complete"); - assert_eq!(10, rq.get_num_bytes(), "num bytes mismatch"); - - let mut buf = vec![0u8; 8]; // <- passing buffer too short - if let Some(chunks) = rq.read() { - let result = chunks.read(&mut buf); - assert!(result.is_err(), "read() should not succeed"); - if let Err(err) = result { - assert_eq!(Error::ErrShortBuffer, err, "read() should not succeed"); - } - assert_eq!(0, rq.get_num_bytes(), "num bytes mismatch"); - } else { - panic!(); - } - - Ok(()) -} - -#[test] -fn test_reassembly_queue_forward_tsn_for_ordered_framents() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let ssn_complete = 5u16; - let ssn_dropped = 6u16; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - ending_fragment: true, - tsn: 10, - stream_sequence_number: ssn_complete, - user_data: Bytes::from_static(b"123"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(complete, "chunk set should be complete"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - tsn: 11, - stream_sequence_number: ssn_dropped, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(6, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - tsn: 12, - stream_sequence_number: ssn_dropped, - user_data: Bytes::from_static(b"DEF"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(9, rq.get_num_bytes(), "num bytes mismatch"); - - rq.forward_tsn_for_ordered(ssn_dropped); - - assert_eq!(1, rq.ordered.len(), "there should be one chunk left"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - - Ok(()) -} - -#[test] -fn test_reassembly_queue_forward_tsn_for_unordered_framents() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - - let org_ppi = PayloadProtocolIdentifier::Binary; - - let ssn_dropped = 6u16; - let ssn_kept = 7u16; - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - beginning_fragment: true, - tsn: 11, - stream_sequence_number: ssn_dropped, - user_data: Bytes::from_static(b"ABC"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - tsn: 12, - stream_sequence_number: ssn_dropped, - user_data: Bytes::from_static(b"DEF"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(6, rq.get_num_bytes(), "num bytes mismatch"); - - let chunk = ChunkPayloadData { - payload_type: org_ppi, - unordered: true, - tsn: 14, - beginning_fragment: true, - stream_sequence_number: ssn_kept, - user_data: Bytes::from_static(b"SOS"), - ..Default::default() - }; - - let complete = rq.push(chunk).expect("chunk to be queued"); - assert!(!complete, "chunk set should not be complete yet"); - assert_eq!(9, rq.get_num_bytes(), "num bytes mismatch"); - - // At this point, there are 3 chunks in the rq.unorderedChunks. - // This call should remove chunks with tsn equals to 13 or older. - rq.forward_tsn_for_unordered(13); - - // As a result, there should be one chunk (tsn=14) - assert_eq!(1, rq.unordered_chunks.len(), "there should be one chunk kept"); - assert_eq!(3, rq.get_num_bytes(), "num bytes mismatch"); - - Ok(()) -} - -#[test] -fn test_chunk_set_empty_chunk_set() -> Result<()> { - let cset = Chunks::new(0, PayloadProtocolIdentifier::default(), vec![]); - assert!(!cset.is_complete(), "empty chunkSet cannot be complete"); - Ok(()) -} - -#[test] -fn test_chunk_set_push_dup_chunks_to_chunk_set() -> Result<()> { - let mut cset = Chunks::new(0, PayloadProtocolIdentifier::default(), vec![]); - cset.push(ChunkPayloadData { - tsn: 100, - beginning_fragment: true, - ..Default::default() - }); - let complete = cset.push(ChunkPayloadData { - tsn: 100, - ending_fragment: true, - ..Default::default() - }); - assert!(!complete, "chunk with dup TSN is not complete"); - assert_eq!(1, cset.chunks.len(), "chunk with dup TSN should be ignored"); - Ok(()) -} - -#[test] -fn test_chunk_set_incomplete_chunk_set_no_beginning() -> Result<()> { - let cset = Chunks::new(0, PayloadProtocolIdentifier::default(), vec![]); - assert!(!cset.is_complete(), "chunkSet not starting with B=1 cannot be complete"); - Ok(()) -} - -#[test] -fn test_chunk_set_incomplete_chunk_set_no_contiguous_tsn() -> Result<()> { - let cset = Chunks::new( - 0, - PayloadProtocolIdentifier::default(), - vec![ - ChunkPayloadData { - tsn: 100, - beginning_fragment: true, - ..Default::default() - }, - ChunkPayloadData { - tsn: 101, - ..Default::default() - }, - ChunkPayloadData { - tsn: 103, - ending_fragment: true, - ..Default::default() - }, - ], - ); - assert!( - !cset.is_complete(), - "chunkSet not starting with incontiguous tsn cannot be complete" - ); - Ok(()) -} - -#[test] -fn test_reassembly_queue_ssn_overflow() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - let org_ppi = PayloadProtocolIdentifier::Binary; - - for stream_sequence_number in 0..=u16::MAX { - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - ending_fragment: true, - tsn: 10, - stream_sequence_number, - user_data: Bytes::from_static(b"123"), - ..Default::default() - }; - assert!(rq.push(chunk).expect("chunk to be queued")); - assert!(rq.read().is_some()); - } - - Ok(()) -} - -#[test] -fn test_reassembly_queue_ssn_overflow_in_forward_tsn_for_ordered() -> Result<()> { - let mut rq = ReassemblyQueue::new(0, 65536); - let org_ppi = PayloadProtocolIdentifier::Binary; - - for stream_sequence_number in 0..u16::MAX { - let chunk = ChunkPayloadData { - payload_type: org_ppi, - beginning_fragment: true, - ending_fragment: true, - tsn: 10, - stream_sequence_number, - user_data: Bytes::from_static(b"123"), - ..Default::default() - }; - assert!(rq.push(chunk).expect("chunk to be queued")); - assert!(rq.read().is_some()); - } - rq.forward_tsn_for_ordered(u16::MAX); - - Ok(()) -} - -#[test] -fn test_chunk_set_wrap() { - let cset = Chunks::new( - 0, - PayloadProtocolIdentifier::default(), - vec![ - ChunkPayloadData { - tsn: u32::MAX - 1, - beginning_fragment: true, - ..Default::default() - }, - ChunkPayloadData { - tsn: u32::MAX, - ..Default::default() - }, - ChunkPayloadData { - tsn: 0, - ending_fragment: true, - ..Default::default() - }, - ], - ); - - assert!(cset.is_complete(), "chunkSet with wrapping TSNs is not complete"); -} - -#[test] -fn test_reassembly_queue_wrap_find_complete() { - let mut rq = ReassemblyQueue::new(0, 65535); - - assert!( - rq.push(ChunkPayloadData { - tsn: u32::MAX - 1, - unordered: true, - beginning_fragment: true, - ..Default::default() - }) - .is_ok() - ); - assert!( - rq.push(ChunkPayloadData { - tsn: u32::MAX, - unordered: true, - ..Default::default() - }) - .is_ok() - ); - assert!( - rq.push(ChunkPayloadData { - tsn: 0, - unordered: true, - ending_fragment: true, - ..Default::default() - }) - .is_ok() - ); - - assert_eq!(rq.unordered.len(), 1, "chunkSet with wrapping TSNs is not complete"); -} - -#[test] -fn test_reassembly_queue_max_message_size() { - let mut rq = ReassemblyQueue::new(0, 65536); - rq.max_message_size = 15; - - assert_eq!( - rq.push(ChunkPayloadData { - tsn: 100, - beginning_fragment: true, - unordered: true, - user_data: Bytes::from_owner([0; 5]), - ..Default::default() - }), - Ok(false) - ); - assert_eq!( - rq.push(ChunkPayloadData { - tsn: 102, - ending_fragment: true, - unordered: true, - user_data: Bytes::from_owner([0; 5]), - ..Default::default() - }), - Ok(false) - ); - assert_eq!( - rq.push(ChunkPayloadData { - tsn: 103, - beginning_fragment: true, - unordered: true, - user_data: Bytes::from_owner([0; 5]), - ..Default::default() - }), - Ok(false) - ); - assert_eq!( - rq.push(ChunkPayloadData { - tsn: 104, - unordered: true, - user_data: Bytes::from_owner([0; 5]), - ..Default::default() - }), - Ok(false) - ); - assert_eq!( - rq.push(ChunkPayloadData { - tsn: 101, - unordered: true, - user_data: Bytes::from_owner([0; 5]), - ..Default::default() - }), - Ok(true) - ); -} - -// Run with --release --ignored --nocapture --test-threads=1. -#[test] -#[ignore = "manual queue drain measurement"] -fn measure_queue_drain() { - use core::hint::black_box; - use std::time::Instant; - - for n in [128u32, 1024, 4096] { - for kind in ["payload", "ordered", "unordered"] { - let mut samples = Vec::new(); - for _ in 0..21 { - let mut pq = PayloadQueue::new(); - let mut rq = ReassemblyQueue::new(0, 65536); - for i in 0..n { - let p = ChunkPayloadData { - stream_sequence_number: i as u16, - beginning_fragment: true, - ending_fragment: true, - unordered: kind == "unordered", - ..make_payload(i, 16) - }; - if kind == "payload" { - pq.push_no_check(p); - } else { - rq.push(p).unwrap(); - } - } - let start = Instant::now(); - for i in 0..n { - if kind == "payload" { - black_box(pq.pop(i).unwrap()); - } else { - black_box(rq.read().unwrap()); - } - } - samples.push(start.elapsed().as_nanos()); - assert_eq!(pq.get_num_bytes(), 0); - assert_eq!(rq.get_num_bytes(), 0); - } - samples.sort_unstable(); - std::println!( - "{kind} n={n}: median={} ns min={} max={}", - samples[10], - samples[0], - samples[20] - ); - } - } -} - -#[test] -fn test_queue_front_pop_then_reorder_across_wrap() -> Result<()> { - let mut pq = PayloadQueue::new(); - let mut rq = ReassemblyQueue::new(0, 65536); - rq.next_ssn = u16::MAX - 1; - for tsn in [u32::MAX - 1, u32::MAX] { - pq.push_no_check(make_payload(tsn, 16)); - rq.push(ChunkPayloadData { - stream_sequence_number: tsn as u16, - beginning_fragment: true, - ending_fragment: true, - ..make_payload(tsn, 16) - })?; - } - assert_eq!(pq.pop(u32::MAX - 1).unwrap().tsn, u32::MAX - 1); - assert_eq!(rq.read().unwrap().ssn, u16::MAX - 1); - for tsn in [1, 0] { - pq.push_no_check(make_payload(tsn, 16)); - rq.push(ChunkPayloadData { - stream_sequence_number: tsn as u16, - beginning_fragment: true, - ending_fragment: true, - ..make_payload(tsn, 16) - })?; - } - assert_eq!(pq.get_last_tsn_received(), Some(&1)); - let gaps = pq.get_gap_ack_blocks(u32::MAX - 1); - assert_eq!(gaps.len(), 1); - assert_eq!((gaps[0].start, gaps[0].end), (1, 3)); - for tsn in [u32::MAX, 0, 1] { - assert_eq!(pq.pop(tsn).unwrap().tsn, tsn); - assert_eq!(rq.read().unwrap().ssn, tsn as u16); - } - assert!(pq.pop(2).is_none()); - assert!(rq.read().is_none()); - assert_eq!(pq.get_num_bytes(), 0); - assert_eq!(rq.get_num_bytes(), 0); - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/queue/reassembly_queue.rs b/rs/moq-webrtc/src/vendor/sctp_proto/queue/reassembly_queue.rs deleted file mode 100644 index 08b8f3676c5..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/queue/reassembly_queue.rs +++ /dev/null @@ -1,606 +0,0 @@ -use crate::vendor::sctp_proto::StreamId; -use crate::vendor::sctp_proto::chunk::chunk_payload_data::{ChunkPayloadData, PayloadProtocolIdentifier}; -use crate::vendor::sctp_proto::error::{Error, Result}; -use crate::vendor::sctp_proto::util::*; - -use bytes::{Bytes, BytesMut}; -use core::cmp::Ordering; -use std::collections::VecDeque; -use std::vec::Vec; - -fn sort_chunks_by_tsn(c: &mut [ChunkPayloadData]) { - c.sort_by(|a, b| { - if sna32lt(a.tsn, b.tsn) { - Ordering::Less - } else { - Ordering::Greater - } - }); -} - -fn sort_chunks_by_ssn(c: &mut [Chunks]) { - c.sort_by(|a, b| { - if sna16lt(a.ssn, b.ssn) { - Ordering::Less - } else { - Ordering::Greater - } - }); -} - -/// A chunk of data from the stream -#[derive(Debug, PartialEq)] -pub struct Chunk { - /// The contents of the chunk - pub bytes: Bytes, -} - -/// Chunks is a set of chunks that share the same SSN -#[derive(Default, Debug, Clone)] -pub struct Chunks { - /// used only with the ordered chunks - pub(crate) ssn: u16, - pub ppi: PayloadProtocolIdentifier, - pub chunks: Vec, - offset: usize, - index: usize, -} - -impl Chunks { - pub fn is_empty(&self) -> bool { - self.len() == 0 - } - - pub fn len(&self) -> usize { - let mut l = 0; - for c in &self.chunks { - l += c.user_data.len(); - } - l - } - - // Concat all fragments into the buffer - pub fn read(&self, buf: &mut [u8]) -> Result { - let mut n_written = 0; - for c in &self.chunks { - let to_copy = c.user_data.len(); - let n = core::cmp::min(to_copy, buf.len() - n_written); - buf[n_written..n_written + n].copy_from_slice(&c.user_data[..n]); - n_written += n; - if n < to_copy { - return Err(Error::ErrShortBuffer); - } - } - Ok(n_written) - } - - pub fn next(&mut self, max_length: usize) -> Option { - if self.index >= self.chunks.len() { - return None; - } - - let mut buf = BytesMut::with_capacity(max_length); - - let mut n_written = 0; - while self.index < self.chunks.len() { - let to_copy = self.chunks[self.index].user_data[self.offset..].len(); - let n = core::cmp::min(to_copy, max_length - n_written); - buf.extend_from_slice(&self.chunks[self.index].user_data[self.offset..self.offset + n]); - n_written += n; - if n < to_copy { - self.offset += n; - return Some(Chunk { bytes: buf.freeze() }); - } - self.index += 1; - self.offset = 0; - } - - Some(Chunk { bytes: buf.freeze() }) - } - - pub(crate) fn new(ssn: u16, ppi: PayloadProtocolIdentifier, chunks: Vec) -> Self { - Chunks { - ssn, - ppi, - chunks, - offset: 0, - index: 0, - } - } - - pub(crate) fn push(&mut self, chunk: ChunkPayloadData) -> bool { - // check if dup - for c in &self.chunks { - if c.tsn == chunk.tsn { - return false; - } - } - - // append and sort - self.chunks.push(chunk); - sort_chunks_by_tsn(&mut self.chunks); - - // Check if we now have a complete set - self.is_complete() - } - - pub(crate) fn is_complete(&self) -> bool { - // Condition for complete set - // 0. Has at least one chunk. - // 1. Begins with beginningFragment set to true - // 2. Ends with endingFragment set to true - // 3. TSN monotinically increase by 1 from beginning to end - - // 0. - let n_chunks = self.chunks.len(); - if n_chunks == 0 { - return false; - } - - // 1. - if !self.chunks[0].beginning_fragment { - return false; - } - - // 2. - if !self.chunks[n_chunks - 1].ending_fragment { - return false; - } - - // 3. - let mut last_tsn = 0u32; - for (i, c) in self.chunks.iter().enumerate() { - if i > 0 { - // Fragments must have contiguous TSN - // From RFC 4960 Section 3.3.1: - // When a user message is fragmented into multiple chunks, the TSNs are - // used by the receiver to reassemble the message. This means that the - // TSNs for each fragment of a fragmented user message MUST be strictly - // sequential. - if c.tsn != last_tsn.wrapping_add(1) { - // mid or end fragment is missing - return false; - } - } - - last_tsn = c.tsn; - } - - true - } - - fn is_missing_tsn_at_or_before(&self, cumulative_tsn: u32) -> bool { - let Some(first) = self.chunks.first() else { - return false; - }; - if !first.beginning_fragment && sna32lte(first.tsn.wrapping_sub(1), cumulative_tsn) { - return true; - } - if self.chunks.windows(2).any(|pair| { - let missing_tsn = pair[0].tsn.wrapping_add(1); - missing_tsn != pair[1].tsn && sna32lte(missing_tsn, cumulative_tsn) - }) { - return true; - } - - let last = self.chunks.last().expect("a first chunk exists"); - !last.ending_fragment && sna32lte(last.tsn.wrapping_add(1), cumulative_tsn) - } -} - -#[derive(Default, Debug)] -pub(crate) struct ReassemblyQueue { - pub(crate) si: StreamId, - pub(crate) next_ssn: u16, - /// expected SSN for next ordered chunk - pub(crate) ordered: VecDeque, - pub(crate) unordered: VecDeque, - pub(crate) unordered_chunks: Vec, - pub(crate) n_bytes: usize, - pub(crate) max_message_size: u32, -} - -impl ReassemblyQueue { - /// From RFC 4960 Sec 6.5: - /// The Stream Sequence Number in all the streams MUST start from 0 when - /// the association is Established. Also, when the Stream Sequence - /// Number reaches the value 65535 the next Stream Sequence Number MUST - /// be set to 0. - pub(crate) fn new(si: StreamId, max_message_size: u32) -> Self { - ReassemblyQueue { - si, - next_ssn: 0, // From RFC 4960 Sec 6.5: - ordered: VecDeque::new(), - unordered: VecDeque::new(), - unordered_chunks: vec![], - n_bytes: 0, - max_message_size, - } - } - - pub(crate) fn push(&mut self, chunk: ChunkPayloadData) -> Result { - if chunk.stream_identifier != self.si { - return Ok(false); - } - - if chunk.unordered { - // Check if adding this chunk would exceed limit for unordered - let projected_size = self.calculate_unordered_message_size(&chunk); - if projected_size > self.max_message_size as usize { - return Err(Error::ErrInboundPacketTooLarge); - } - - // First, insert into unordered_chunks array - //atomic.AddUint64(&r.n_bytes, uint64(len(chunk.userData))) - self.n_bytes += chunk.user_data.len(); - self.unordered_chunks.push(chunk); - sort_chunks_by_tsn(&mut self.unordered_chunks); - - // Scan unordered_chunks that are contiguous (in TSN) - // If found, append the complete set to the unordered array - if let Some(cset) = self.find_complete_unordered_chunk_set() { - self.unordered.push_back(cset); - return Ok(true); - } - - Ok(false) - } else { - // Check if adding this chunk would exceed limit for ordered - let projected_size = self.calculate_ordered_message_size(&chunk); - if projected_size > self.max_message_size as usize { - return Err(Error::ErrInboundPacketTooLarge); - } - - // This is an ordered chunk - if sna16lt(chunk.stream_sequence_number, self.next_ssn) { - return Ok(false); - } - - self.n_bytes += chunk.user_data.len(); - - // Check if a chunkSet with the SSN already exists - for s in &mut self.ordered { - if s.ssn == chunk.stream_sequence_number { - return Ok(s.push(chunk)); - } - } - - // If not found, create a new chunkSet - let mut cset = Chunks::new(chunk.stream_sequence_number, chunk.payload_type, vec![]); - let unordered = chunk.unordered; - let ok = cset.push(chunk); - self.ordered.push_back(cset); - if !unordered { - sort_chunks_by_ssn(self.ordered.make_contiguous()); - } - - Ok(ok) - } - } - - fn calculate_ordered_message_size(&self, new_chunk: &ChunkPayloadData) -> usize { - let ssn = new_chunk.stream_sequence_number; - let existing: usize = self.ordered.iter().find(|s| s.ssn == ssn).map(|s| s.len()).unwrap_or(0); - existing + new_chunk.user_data.len() - } - - fn calculate_unordered_message_size(&self, new_chunk: &ChunkPayloadData) -> usize { - // For unordered, calculate size of contiguous chunk set this belongs to - // This is more complex - need to find the message boundary - - // first find the set of TSNs that preceeds this chunk - let prefix = if new_chunk.beginning_fragment { - 0 - } else if let Some(mut p) = self - .unordered_chunks - .iter() - .rposition(|f| f.tsn == new_chunk.tsn.wrapping_sub(1)) - { - let mut cnt = 0; - let mut tsn = new_chunk.tsn; - loop { - if self.unordered_chunks[p].tsn == tsn.wrapping_sub(1) { - cnt += self.unordered_chunks[p].user_data.len(); - tsn = self.unordered_chunks[p].tsn; - } else { - break; - } - - if self.unordered_chunks[p].beginning_fragment || (p == 0) { - break; - } - p -= 1; - } - cnt - } else { - 0 - }; - - // next find the set of TSNs that succeeds this chunk - let suffix = if new_chunk.ending_fragment { - 0 - } else if let Some(mut p) = self - .unordered_chunks - .iter() - .rposition(|f| f.tsn == new_chunk.tsn.wrapping_add(1)) - { - let mut cnt = 0; - let mut tsn = new_chunk.tsn; - while p < self.unordered_chunks.len() { - if self.unordered_chunks[p].tsn == tsn.wrapping_add(1) { - cnt += self.unordered_chunks[p].user_data.len(); - tsn = self.unordered_chunks[p].tsn; - } else { - break; - } - - if self.unordered_chunks[p].ending_fragment { - break; - } - p += 1; - } - cnt - } else { - 0 - }; - - // now sum the lengths together - prefix + new_chunk.user_data.len() + suffix - } - - pub(crate) fn find_complete_unordered_chunk_set(&mut self) -> Option { - let mut start_idx = -1isize; - let mut n_chunks = 0usize; - let mut last_tsn = 0u32; - let mut found = false; - - for (i, c) in self.unordered_chunks.iter().enumerate() { - // seek beginning - if c.beginning_fragment { - start_idx = i as isize; - n_chunks = 1; - last_tsn = c.tsn; - - if c.ending_fragment { - found = true; - break; - } - continue; - } - - if start_idx < 0 { - continue; - } - - // Check if contiguous in TSN - if c.tsn != last_tsn.wrapping_add(1) { - start_idx = -1; - continue; - } - - last_tsn = c.tsn; - n_chunks += 1; - - if c.ending_fragment { - found = true; - break; - } - } - - if !found { - return None; - } - - // Extract the range of chunks - let chunks: Vec = self - .unordered_chunks - .drain(start_idx as usize..(start_idx as usize) + n_chunks) - .collect(); - Some(Chunks::new(0, chunks[0].payload_type, chunks)) - } - - pub(crate) fn is_readable(&self) -> bool { - // Check unordered first - if !self.unordered.is_empty() { - // The chunk sets in r.unordered should all be complete. - return true; - } - - // Check ordered sets - if !self.ordered.is_empty() { - let cset = &self.ordered[0]; - if cset.is_complete() && sna16lte(cset.ssn, self.next_ssn) { - return true; - } - } - false - } - - pub(crate) fn read(&mut self) -> Option { - // Check unordered first - let chunks = if !self.unordered.is_empty() { - self.unordered.pop_front()? - } else if !self.ordered.is_empty() { - // Now, check ordered - let chunks = &self.ordered[0]; - if !chunks.is_complete() { - return None; - } - if sna16gt(chunks.ssn, self.next_ssn) { - return None; - } - if chunks.ssn == self.next_ssn { - self.next_ssn = self.next_ssn.wrapping_add(1); - } - self.ordered.pop_front()? - } else { - return None; - }; - - self.subtract_num_bytes(chunks.len()); - - Some(chunks) - } - - /// Use last_ssn to locate a chunkSet then remove it if the set has - /// not been complete - pub(crate) fn forward_tsn_for_ordered(&mut self, last_ssn: u16) { - let num_bytes = self - .ordered - .iter() - .filter(|s| sna16lte(s.ssn, last_ssn) && !s.is_complete()) - .fold(0, |n, s| n + s.chunks.iter().fold(0, |acc, c| acc + c.user_data.len())); - self.subtract_num_bytes(num_bytes); - - self.ordered.retain(|s| !sna16lte(s.ssn, last_ssn) || s.is_complete()); - - // Finally, forward next_ssn - if sna16lte(self.next_ssn, last_ssn) { - self.next_ssn = last_ssn.wrapping_add(1); - } - } - - /// Apply an ordered Forward-TSN retained across a stream reset without - /// crossing into messages whose TSNs are newer than its cumulative point. - pub(crate) fn forward_tsn_for_ordered_bounded(&mut self, last_ssn: u16, new_cumulative_tsn: u32) { - let first_unaffected_ssn = self - .ordered - .iter() - .filter(|chunks| { - sna16lte(chunks.ssn, last_ssn) - && if chunks.is_complete() { - chunks.chunks.iter().any(|chunk| sna32gt(chunk.tsn, new_cumulative_tsn)) - } else { - !chunks.is_missing_tsn_at_or_before(new_cumulative_tsn) - } - }) - .map(|chunks| chunks.ssn) - .reduce( - |first, candidate| { - if sna16lt(candidate, first) { candidate } else { first } - }, - ); - - let is_abandoned_partial = |chunks: &&Chunks| { - sna16lte(chunks.ssn, last_ssn) - && !chunks.is_complete() - && chunks.is_missing_tsn_at_or_before(new_cumulative_tsn) - }; - let num_bytes = self - .ordered - .iter() - .filter(is_abandoned_partial) - .flat_map(|chunks| chunks.chunks.iter()) - .map(|chunk| chunk.user_data.len()) - .sum(); - self.subtract_num_bytes(num_bytes); - self.ordered.retain(|chunks| { - !sna16lte(chunks.ssn, last_ssn) - || chunks.is_complete() - || !chunks.is_missing_tsn_at_or_before(new_cumulative_tsn) - }); - - let next_ssn = first_unaffected_ssn.unwrap_or_else(|| last_ssn.wrapping_add(1)); - if sna16lt(self.next_ssn, next_ssn) { - self.next_ssn = next_ssn; - } - } - - /// The highest prefix of an ambiguous deferred ordered skip that has - /// enough TSN context to advance without overtaking a missing successor. - pub(crate) fn applicable_forward_tsn_for_ordered_bounded( - &self, - last_ssn: u16, - new_cumulative_tsn: u32, - peer_last_tsn: u32, - ) -> Option { - if sna16gt(self.next_ssn, last_ssn) { - return Some(last_ssn); - } - - let is_covered = |chunks: &Chunks| { - if chunks.is_complete() { - chunks - .chunks - .iter() - .all(|chunk| sna32lte(chunk.tsn, new_cumulative_tsn)) - } else { - chunks.is_missing_tsn_at_or_before(new_cumulative_tsn) - } - }; - if self - .ordered - .iter() - .any(|chunks| chunks.ssn == last_ssn && (chunks.ssn == self.next_ssn || is_covered(chunks))) - { - return Some(last_ssn); - } - - let has_resolved_later_tsn = self - .ordered - .iter() - .filter(|chunks| chunks.ssn == last_ssn || sna16gt(chunks.ssn, last_ssn)) - .flat_map(|chunks| chunks.chunks.iter()) - .map(|chunk| chunk.tsn) - .reduce( - |first, candidate| { - if sna32lt(candidate, first) { candidate } else { first } - }, - ) - .is_some_and(|first_tsn| sna32lte(first_tsn, peer_last_tsn)); - if has_resolved_later_tsn { - return Some(last_ssn); - } - - self.ordered - .iter() - .filter(|chunks| { - (chunks.ssn == self.next_ssn || sna16gt(chunks.ssn, self.next_ssn)) - && sna16lt(chunks.ssn, last_ssn) - && (is_covered(chunks) - || chunks - .chunks - .first() - .is_some_and(|chunk| sna32lte(chunk.tsn, peer_last_tsn))) - }) - .map(|chunks| chunks.ssn) - .reduce( - |last, candidate| { - if sna16gt(candidate, last) { candidate } else { last } - }, - ) - } - - /// Remove all fragments in the unordered sets that contains chunks - /// equal to or older than `new_cumulative_tsn`. - /// We know all sets in the r.unordered are complete ones. - /// Just remove chunks that are equal to or older than new_cumulative_tsn - /// from the unordered_chunks - pub(crate) fn forward_tsn_for_unordered(&mut self, new_cumulative_tsn: u32) { - let mut last_idx: isize = -1; - for (i, c) in self.unordered_chunks.iter().enumerate() { - if sna32gt(c.tsn, new_cumulative_tsn) { - break; - } - last_idx = i as isize; - } - if last_idx >= 0 { - for i in 0..(last_idx + 1) as usize { - self.subtract_num_bytes(self.unordered_chunks[i].user_data.len()); - } - self.unordered_chunks.drain(..(last_idx + 1) as usize); - } - } - - pub(crate) fn subtract_num_bytes(&mut self, n_bytes: usize) { - if self.n_bytes >= n_bytes { - self.n_bytes -= n_bytes; - } else { - self.n_bytes = 0; - } - } - - pub(crate) fn get_num_bytes(&self) -> usize { - self.n_bytes - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/shared.rs b/rs/moq-webrtc/src/vendor/sctp_proto/shared.rs deleted file mode 100644 index 5d66eef2a58..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/shared.rs +++ /dev/null @@ -1,80 +0,0 @@ -use crate::vendor::sctp_proto::Transmit; - -/// Events sent from an Endpoint to an Association -#[derive(Debug)] -pub struct AssociationEvent(pub(crate) AssociationEventInner); - -#[derive(Debug)] -pub(crate) enum AssociationEventInner { - /// A datagram has been received for the Association - Datagram(Transmit), - // New Association identifiers have been issued for the Association - //NewIdentifiers(Vec, Instant), -} - -/// Events sent from an Association to an Endpoint -#[derive(Debug)] -pub struct EndpointEvent(pub(crate) EndpointEventInner); - -impl EndpointEvent { - /// Construct an event that indicating that a `Association` will no longer emit events - /// - /// Useful for notifying an `Endpoint` that a `Association` has been destroyed outside of the - /// usual state machine flow, e.g. when being dropped by the user. - pub fn drained() -> Self { - Self(EndpointEventInner::Drained) - } - - /// Determine whether this is the last event a `Association` will emit - /// - /// Useful for determining when association-related event loop state can be freed. - pub fn is_drained(&self) -> bool { - self.0 == EndpointEventInner::Drained - } -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub(crate) enum EndpointEventInner { - /// The association has been drained - Drained, - /*// The association needs association identifiers - NeedIdentifiers(Instant, u64), - /// Stop routing Association ID for this sequence number to the Association - /// When `bool == true`, a new Association ID will be issued to peer - RetireAssociationId(Instant, u64, bool),*/ -} - -/// Protocol-level identifier for an Association. -/// -/// Mainly useful for identifying this Association's packets on the wire with tools like Wireshark. -pub type AssociationId = u32; - -/// Explicit congestion notification codepoint -#[repr(u8)] -#[derive(Debug, Copy, Clone, Eq, PartialEq)] -pub enum EcnCodepoint { - Ect0 = 0b10, - Ect1 = 0b01, - Ce = 0b11, -} - -impl EcnCodepoint { - /// Create new object from the given bits - pub fn from_bits(x: u8) -> Option { - use self::EcnCodepoint::*; - Some(match x & 0b11 { - 0b10 => Ect0, - 0b01 => Ect1, - 0b11 => Ce, - _ => { - return None; - } - }) - } -} - -#[derive(Debug, Copy, Clone)] -pub struct IssuedAid { - pub sequence: u64, - pub id: AssociationId, -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/tests/partial_reliability.rs b/rs/moq-webrtc/src/vendor/sctp_proto/tests/partial_reliability.rs deleted file mode 100644 index 41059c612f1..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/tests/partial_reliability.rs +++ /dev/null @@ -1,630 +0,0 @@ -use crate::vendor::sctp_proto::{Association, AssociationHandle, ClientConfig, DatagramEvent}; -use crate::vendor::sctp_proto::{Endpoint, EndpointConfig, Payload, PayloadProtocolIdentifier}; -use crate::vendor::sctp_proto::{ReliabilityType, TransportConfig, generate_snap_token}; -use bytes::Bytes; -use std::net::SocketAddr; -use std::sync::Arc; -use std::time::{Duration, Instant}; - -struct Peer { - ep: Endpoint, - assoc: Association, - handle: AssociationHandle, - addr: SocketAddr, -} -impl Peer { - fn receive(&mut self, now: Instant, remote: SocketAddr, bytes: Bytes) { - let (_, e) = self - .ep - .handle(now, remote, None, None, bytes) - .expect("routable SCTP packet"); - match e { - DatagramEvent::AssociationEvent(e) => self.assoc.handle_event(e), - _ => panic!("unexpected association"), - } - } - fn drain(&mut self, now: Instant) -> Vec { - let mut out = Vec::new(); - loop { - while let Some(e) = self.assoc.poll_endpoint_event() { - if let Some(e) = self.ep.handle_event(self.handle, e) { - self.assoc.handle_event(e); - } - } - while self.assoc.poll().is_some() {} - let Some(t) = self.assoc.poll_transmit(now).or_else(|| self.ep.poll_transmit()) else { - break; - }; - match t.payload { - Payload::RawEncode(p) => out.extend(p), - _ => panic!("outgoing parse payload"), - } - } - out - } - fn messages(&mut self) -> Vec> { - let mut out = Vec::new(); - while let Some(chunks) = self.assoc.stream(0).unwrap().read().unwrap() { - let mut data = vec![0; chunks.len()]; - chunks.read(&mut data).unwrap(); - out.push(data); - } - out - } -} -fn pairs(reliability: ReliabilityType) -> (Peer, Peer) { - let tc = Arc::new(TransportConfig::default()); - let ta = generate_snap_token(&tc).unwrap(); - let tb = generate_snap_token(&tc).unwrap(); - let addr_a: SocketAddr = "127.0.0.1:5000".parse().unwrap(); - let addr_b: SocketAddr = "127.0.0.1:5001".parse().unwrap(); - let mut ep_a = Endpoint::new(Arc::new(EndpointConfig::new()), None); - let mut ep_b = Endpoint::new(Arc::new(EndpointConfig::new()), None); - let (ha, mut a) = ep_a - .connect(ClientConfig::new().with_snap(ta.clone(), tb.clone()), addr_b) - .unwrap(); - let (hb, mut b) = ep_b.connect(ClientConfig::new().with_snap(tb, ta), addr_a).unwrap(); - for assoc in [&mut a, &mut b] { - assoc - .open_stream(0, PayloadProtocolIdentifier::Binary) - .unwrap() - .set_reliability_params(true, reliability, 0) - .unwrap(); - } - ( - Peer { - ep: ep_a, - assoc: a, - handle: ha, - addr: addr_a, - }, - Peer { - ep: ep_b, - assoc: b, - handle: hb, - addr: addr_b, - }, - ) -} -fn chunks(bytes: &[u8]) -> Vec<(u8, Option)> { - let mut result = Vec::new(); - let mut i = 12; - while i + 4 <= bytes.len() { - let ty = bytes[i]; - let len = u16::from_be_bytes(bytes[i + 2..i + 4].try_into().unwrap()) as usize; - let seq = if [0, 3, 192].contains(&ty) && len >= 8 { - Some(u32::from_be_bytes(bytes[i + 4..i + 8].try_into().unwrap())) - } else { - None - }; - result.push((ty, seq)); - if len < 4 { - break; - } - i += (len + 3) & !3; - } - result -} - -fn simulate(reliability: ReliabilityType) { - use std::collections::VecDeque; - let (mut a, mut b) = pairs(reliability); - let base = Instant::now(); - let mut ab = VecDeque::<(u64, Bytes)>::new(); - let mut ba = VecDeque::<(u64, Bytes)>::new(); - let mut counts = [[0usize; 3]; 15]; // DATA, FORWARD-TSN, SACK - let mut sent = 0; - let mut received = 0; - for ms in 0..15000u64 { - let now = base + Duration::from_millis(ms); - a.assoc.handle_timeout(now); - b.assoc.handle_timeout(now); - if ms < 10000 && ms % 17 == 0 { - a.assoc.stream(0).unwrap().write(b"game packet").unwrap(); - sent += 1; - } - loop { - let mut did = false; - if ab.front().is_some_and(|(due, _)| *due <= ms) { - let (_, p) = ab.pop_front().unwrap(); - b.receive(now, a.addr, p); - did = true; - } - for p in b.drain(now) { - for (ty, _) in chunks(&p) { - if ty == 3 { - counts[ms as usize / 1000][2] += 1; - } - } - ba.push_back((ms + 50, p)); - } - received += b.messages().len(); - if ba.front().is_some_and(|(due, _)| *due <= ms) { - let (_, p) = ba.pop_front().unwrap(); - a.receive(now, b.addr, p); - did = true; - } - for p in a.drain(now) { - for (ty, _) in chunks(&p) { - match ty { - 0 => counts[ms as usize / 1000][0] += 1, - 192 => counts[ms as usize / 1000][1] += 1, - _ => {} - } - } - ab.push_back((ms + 50, p)); - } - if !did { - break; - } - } - } - println!("mode={reliability:?}, sent={sent}, received={received}, counts DATA/FWD/SACK each second:"); - for (i, c) in counts.iter().enumerate() { - println!("{}: {:?}", i, c); - } - assert_eq!( - sent, received, - "zero-drop ordered IP path should deliver every original DATA" - ); - assert!( - counts.iter().all(|c| c[1] == 0), - "unlost DATA must never generate FORWARD-TSN" - ); - assert!(counts[14].iter().all(|n| *n == 0), "settles once source traffic stops"); -} -#[test] -fn zero_retransmits_does_not_amplify_acknowledgements() { - simulate(ReliabilityType::Reliable); - simulate(ReliabilityType::Rexmit); -} - -#[test] -fn retransmit_limit_is_applied_when_recovery_is_needed() { - for limit in [0, 1, 2] { - let (mut a, mut b) = pairs(ReliabilityType::Rexmit); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(true, ReliabilityType::Rexmit, limit) - .unwrap(); - let base = Instant::now(); - a.assoc.stream(0).unwrap().write(b"intentionally dropped").unwrap(); - let mut data = 0; - let mut forwarded = false; - // Deliberately drop DATA and deliver control packets. Drive real timeout - // recovery: maxRTX counts retransmissions, not the first transmission. - for ms in 0..30000u64 { - let now = base + Duration::from_millis(ms); - a.assoc.handle_timeout(now); - b.assoc.handle_timeout(now); - for packet in a.drain(now) { - let types = chunks(&packet); - if types.iter().any(|(ty, _)| *ty == 0) { - data += 1; - } else { - forwarded |= types.iter().any(|(ty, _)| *ty == 192); - b.receive(now, a.addr, packet); - } - } - for packet in b.drain(now) { - a.receive(now, b.addr, packet); - } - } - assert_eq!(data, 1 + limit, "maxRTX={limit}"); - assert!(forwarded, "abandoned DATA must advance without another incoming SACK"); - } -} - -fn run(reorder: bool) { - let (mut a, mut b) = pairs(ReliabilityType::Rexmit); - let base = Instant::now(); - let mut transmissions = Vec::new(); - for (ms, name) in [(0, "first"), (10, "second"), (20, "held")] { - a.assoc.stream(0).unwrap().write(name.as_bytes()).unwrap(); - let packets = a.drain(base + Duration::from_millis(ms)); - for p in &packets { - println!("{ms}ms A send {name}: {:?}", chunks(p)); - } - assert_eq!(packets.len(), 1); - transmissions.push(packets[0].clone()); - } - let mut sacks = Vec::new(); - for (i, ms) in [(0, 50), (1, 60)] { - b.receive(base + Duration::from_millis(ms), a.addr, transmissions[i].clone()); - sacks.extend(b.drain(base + Duration::from_millis(ms))); - } - assert_eq!(b.messages(), vec![b"first".to_vec(), b"second".to_vec()]); - if !reorder { - b.receive(base + Duration::from_millis(70), a.addr, transmissions[2].clone()); - } - assert!(!sacks.is_empty(), "initial data must generate SACK"); - for p in sacks { - println!("110ms A receives {:?}", chunks(&p)); - a.receive(base + Duration::from_millis(110), b.addr, p); - } - let forwards = a.drain(base + Duration::from_millis(110)); - assert!( - !forwards.iter().any(|p| chunks(p).iter().any(|(ty, _)| *ty == 192)), - "original DATA remains in flight until recovery is needed" - ); - for p in forwards { - println!("160ms B receives {:?}", chunks(&p)); - b.receive(base + Duration::from_millis(160), a.addr, p); - } - if reorder { - println!("170ms B receives delayed original DATA {:?}", chunks(&transmissions[2])); - b.receive(base + Duration::from_millis(170), a.addr, transmissions[2].clone()); - } - let got = b.messages(); - println!( - "reorder={reorder}: held message delivered={} (no network packet was dropped)", - !got.is_empty() - ); - assert_eq!(got, vec![b"held".to_vec()]); -} - -#[test] -fn delayed_original_data_is_not_abandoned_by_an_older_sack() { - run(false); - run(true); -} - -#[test] -fn fragmented_zero_retransmits_abandons_pending_tails_and_releases_credit() { - use std::collections::{HashMap, VecDeque}; - for unordered in [false, true] { - for size in [3000, 24000] { - let (mut a, mut b) = pairs(ReliabilityType::Rexmit); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(unordered, ReliabilityType::Rexmit, 0) - .unwrap(); - let base = Instant::now(); - a.assoc.stream(0).unwrap().write(&vec![7; size]).unwrap(); - a.assoc.stream(0).unwrap().write(b"following message").unwrap(); - let mut ab = VecDeque::<(u64, Bytes)>::new(); - let mut ba = VecDeque::<(u64, Bytes)>::new(); - let mut transmissions = HashMap::::new(); - let mut dropped = false; - let mut forwarded = false; - let mut messages = Vec::new(); - for ms in 0..10000u64 { - let now = base + Duration::from_millis(ms); - a.assoc.handle_timeout(now); - b.assoc.handle_timeout(now); - while ab.front().is_some_and(|(due, _)| *due <= ms) { - let (_, packet) = ab.pop_front().unwrap(); - b.receive(now, a.addr, packet); - } - for packet in b.drain(now) { - ba.push_back((ms + 50, packet)); - } - messages.extend(b.messages()); - while ba.front().is_some_and(|(due, _)| *due <= ms) { - let (_, packet) = ba.pop_front().unwrap(); - a.receive(now, b.addr, packet); - } - for packet in a.drain(now) { - let types = chunks(&packet); - for (ty, tsn) in &types { - if *ty == 0 { - *transmissions.entry(tsn.unwrap()).or_default() += 1; - } - forwarded |= *ty == 192; - } - if !dropped && types.iter().any(|(ty, _)| *ty == 0) { - dropped = true; - } else { - ab.push_back((ms + 50, packet)); - } - } - } - assert!(forwarded); - assert!( - transmissions.values().all(|n| *n == 1), - "RTX0 retransmitted a fragment: size={size}, unordered={unordered}" - ); - assert_eq!( - messages, - vec![b"following message".to_vec()], - "size={size}, unordered={unordered}" - ); - assert_eq!( - a.assoc.stream(0).unwrap().buffered_amount().unwrap(), - 0, - "abandonment must release both pending and acknowledged prefix bytes" - ); - } - } -} - -#[test] -fn fragment_retry_limits_and_lost_forward_recovery() { - use std::collections::{HashMap, VecDeque}; - for unordered in [false, true] { - for size in [3000, 24000] { - for limit in [0, 1, 2] { - let (mut a, mut b) = pairs(ReliabilityType::Rexmit); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(unordered, ReliabilityType::Rexmit, limit) - .unwrap(); - let base = Instant::now(); - a.assoc.stream(0).unwrap().write(&vec![7; size]).unwrap(); - a.assoc.stream(0).unwrap().write(b"following message").unwrap(); - let mut ab = VecDeque::<(u64, Bytes)>::new(); - let mut ba = VecDeque::<(u64, Bytes)>::new(); - let mut transmissions = HashMap::::new(); - let mut first_tsn = None; - let mut forward_drops = 0; - let mut messages = Vec::new(); - for ms in 0..90000u64 { - let now = base + Duration::from_millis(ms); - a.assoc.handle_timeout(now); - b.assoc.handle_timeout(now); - while ab.front().is_some_and(|(due, _)| *due <= ms) { - let (_, packet) = ab.pop_front().unwrap(); - b.receive(now, a.addr, packet); - } - for packet in b.drain(now) { - ba.push_back((ms + 50, packet)); - } - messages.extend(b.messages()); - while ba.front().is_some_and(|(due, _)| *due <= ms) { - let (_, packet) = ba.pop_front().unwrap(); - a.receive(now, b.addr, packet); - } - for packet in a.drain(now) { - let types = chunks(&packet); - for (ty, tsn) in &types { - if *ty == 0 { - first_tsn.get_or_insert(tsn.unwrap()); - *transmissions.entry(tsn.unwrap()).or_default() += 1; - } - } - if types.iter().any(|(ty, tsn)| *ty == 0 && *tsn == first_tsn) { - continue; - } - if types.iter().any(|(ty, _)| *ty == 192) && forward_drops < 2 { - forward_drops += 1; - continue; - } - ab.push_back((ms + 50, packet)); - } - } - assert_eq!(transmissions[&first_tsn.unwrap()], (1 + limit) as usize); - assert!(transmissions.values().all(|n| *n <= (1 + limit) as usize)); - assert_eq!(forward_drops, 2); - assert_eq!(messages, vec![b"following message".to_vec()]); - assert_eq!(a.assoc.stream(0).unwrap().buffered_amount().unwrap(), 0); - } - } - } -} - -#[test] -fn lost_prefix_sacks_do_not_strand_the_next_ordered_message() { - let (mut a, mut b) = pairs(ReliabilityType::Rexmit); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(false, ReliabilityType::Rexmit, 0) - .unwrap(); - let now = Instant::now(); - a.assoc.stream(0).unwrap().write(&vec![7; 24000]).unwrap(); - a.assoc.stream(0).unwrap().write(b"following message").unwrap(); - // Deliver every fragment allowed by the initial congestion window, but - // lose the SACKs. The receiver holds an incomplete, contiguous prefix. - for packet in a.drain(now) { - b.receive(now, a.addr, packet); - } - assert!(b.messages().is_empty()); - assert!(!b.drain(now).is_empty()); - - let mut received = Vec::new(); - let mut forwarded = false; - for ms in 1..10000 { - let now = now + Duration::from_millis(ms); - a.assoc.handle_timeout(now); - b.assoc.handle_timeout(now); - for packet in a.drain(now) { - forwarded |= chunks(&packet).iter().any(|(ty, _)| *ty == 192); - b.receive(now, a.addr, packet); - } - for packet in b.drain(now) { - // Lose prefix SACKs, including delayed ones. Once recovery starts, - // deliver all traffic in both directions without further loss. - if forwarded { - a.receive(now, b.addr, packet); - } - } - received.extend(b.messages()); - } - assert!(forwarded, "the sender must abandon the message on timeout"); - assert_eq!(a.assoc.stream(0).unwrap().buffered_amount().unwrap(), 0); - assert_eq!(received, vec![b"following message".to_vec()]); -} - -#[test] -fn unordered_abandonment_preserves_next_ordered_message() { - let (mut a, mut b) = pairs(ReliabilityType::Rexmit); - let base = Instant::now(); - a.assoc.stream(0).unwrap().write(b"lost unordered").unwrap(); - let mut forwarded = false; - for ms in 0..30000 { - let now = base + Duration::from_millis(ms); - a.assoc.handle_timeout(now); - for packet in a.drain(now) { - let types = chunks(&packet); - if types.iter().any(|(ty, _)| *ty == 0) { - continue; - } - forwarded |= types.iter().any(|(ty, _)| *ty == 192); - b.receive(now, a.addr, packet); - } - for packet in b.drain(now) { - a.receive(now, b.addr, packet); - } - if forwarded { - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(false, ReliabilityType::Reliable, 0) - .unwrap(); - a.assoc.stream(0).unwrap().write(b"ordered successor").unwrap(); - for packet in a.drain(now) { - b.receive(now, a.addr, packet); - } - assert_eq!(b.messages(), vec![b"ordered successor".to_vec()]); - break; - } - } - assert!(forwarded); -} - -#[test] -fn timed_streams_accept_existing_write_methods_after_idle() { - for unordered in [false, true] { - for method in 0..5 { - let (mut a, mut b) = pairs(ReliabilityType::Timed); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(unordered, ReliabilityType::Timed, 10) - .unwrap(); - let base = Instant::now(); - assert!(a.drain(base).is_empty()); - let now = base + Duration::from_secs(3600); - let data = Bytes::from_static(b"timed message"); - let mut stream = a.assoc.stream(0).unwrap(); - let written = match method { - 0 => stream.write(&data), - 1 => stream.write_with_ppi(&data, PayloadProtocolIdentifier::Binary), - 2 => stream.write_sctp(&data, PayloadProtocolIdentifier::Binary), - 3 => stream.write_chunk(&data), - 4 => stream.write_chunks(&mut [data.clone()]), - _ => unreachable!(), - }; - assert_eq!(written.unwrap(), data.len()); - for packet in a.drain(now) { - b.receive(now, a.addr, packet); - } - assert_eq!(b.messages(), vec![data.to_vec()]); - } - } -} - -#[test] -fn zero_lifetime_timed_writes_preserve_following_ordered_delivery() { - for unordered in [false, true] { - let (mut a, mut b) = pairs(ReliabilityType::Timed); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(unordered, ReliabilityType::Timed, 0) - .unwrap(); - a.assoc.stream(0).unwrap().write(&vec![7; 3000]).unwrap(); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(false, ReliabilityType::Reliable, 0) - .unwrap(); - a.assoc.stream(0).unwrap().write(b"following message").unwrap(); - let now = Instant::now(); - for packet in a.drain(now) { - b.receive(now, a.addr, packet); - } - assert_eq!(b.messages(), vec![b"following message".to_vec()]); - assert_eq!( - a.assoc.stream(0).unwrap().buffered_amount().unwrap(), - b"following message".len() - ); - } -} - -#[test] -fn fragmented_timed_messages_expire_through_loss_and_reordering() { - use std::collections::{HashMap, VecDeque}; - for unordered in [false, true] { - for size in [3000, 24000] { - let (mut a, mut b) = pairs(ReliabilityType::Rexmit); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(unordered, ReliabilityType::Timed, 10) - .unwrap(); - let base = Instant::now(); - a.assoc.stream(0).unwrap().write(&vec![7; size]).unwrap(); - a.assoc - .stream(0) - .unwrap() - .set_reliability_params(unordered, ReliabilityType::Reliable, 0) - .unwrap(); - a.assoc.stream(0).unwrap().write(b"following message").unwrap(); - let mut ab = VecDeque::<(u64, Bytes)>::new(); - let mut ba = VecDeque::<(u64, Bytes)>::new(); - let mut transmissions = HashMap::::new(); - let mut dropped = false; - let mut dropped_forward = false; - let mut forwarded = false; - let mut messages = Vec::new(); - for ms in 0..10000u64 { - let now = base + Duration::from_millis(ms); - a.assoc.handle_timeout(now); - b.assoc.handle_timeout(now); - while ab.front().is_some_and(|(due, _)| *due <= ms) { - let (_, packet) = ab.pop_front().unwrap(); - b.receive(now, a.addr, packet); - } - for packet in b.drain(now) { - ba.push_back((ms + 50, packet)); - } - messages.extend(b.messages()); - while ba.front().is_some_and(|(due, _)| *due <= ms) { - let (_, packet) = ba.pop_front().unwrap(); - a.receive(now, b.addr, packet); - } - // Reverse each outbound batch to exercise reordered fragments. - for packet in a.drain(now).into_iter().rev() { - let types = chunks(&packet); - let mut offset = 12; - while offset + 4 <= packet.len() { - let length = u16::from_be_bytes([packet[offset + 2], packet[offset + 3]]) as usize; - if packet[offset] == 0 && length > 16 && packet[offset + 16] == 7 { - let tsn = u32::from_be_bytes(packet[offset + 4..offset + 8].try_into().unwrap()); - *transmissions.entry(tsn).or_default() += 1; - assert!(ms < 10, "expired timed DATA reached the wire at {ms}ms"); - } - offset += (length + 3) & !3; - } - forwarded |= types.iter().any(|(ty, _)| *ty == 192); - if !dropped && types.iter().any(|(ty, _)| *ty == 0) { - dropped = true; - } else if !dropped_forward && types.iter().any(|(ty, _)| *ty == 192) { - dropped_forward = true; - } else { - ab.push_back((ms + 50, packet)); - } - } - } - assert!(forwarded && dropped_forward); - assert!( - transmissions.values().all(|n| *n == 1), - "timed message retransmitted after expiry: size={size}, unordered={unordered}" - ); - assert_eq!( - messages, - vec![b"following message".to_vec()], - "size={size}, unordered={unordered}" - ); - assert_eq!( - a.assoc.stream(0).unwrap().buffered_amount().unwrap(), - 0, - "abandonment must release both pending and acknowledged prefix bytes" - ); - } - } -} diff --git a/rs/moq-webrtc/src/vendor/sctp_proto/util.rs b/rs/moq-webrtc/src/vendor/sctp_proto/util.rs deleted file mode 100644 index b426d94be55..00000000000 --- a/rs/moq-webrtc/src/vendor/sctp_proto/util.rs +++ /dev/null @@ -1,394 +0,0 @@ -use crate::vendor::sctp_proto::shared::AssociationId; - -use bytes::Bytes; -use core::time::Duration; -use crc::{CRC_32_ISCSI, Crc, Table}; -use std::borrow::ToOwned; - -/// This function is non-inline to prevent the optimizer from looking inside it. -#[inline(never)] -fn constant_time_ne(a: &[u8], b: &[u8]) -> u8 { - assert!(a.len() == b.len()); - - // These useless slices make the optimizer elide the bounds checks. - // See the comment in clone_from_slice() added on Rust commit 6a7bc47. - let len = a.len(); - let a = &a[..len]; - let b = &b[..len]; - - let mut tmp = 0; - for i in 0..len { - tmp |= a[i] ^ b[i]; - } - tmp // The compare with 0 must happen outside this function. -} - -/// Compares byte strings in constant time. -pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool { - a.len() == b.len() && constant_time_ne(a, b) == 0 -} - -/// Generates association id for incoming associations -pub trait AssociationIdGenerator: Send + Sync { - /// Generates a new AID - /// - /// Association IDs MUST NOT contain any information that can be used by - /// an external observer (that is, one that does not cooperate with the - /// issuer) to correlate them with other Association IDs for the same - /// Association. - fn generate_aid(&mut self) -> AssociationId; - - /// Returns the lifetime of generated Association IDs - /// - /// Association IDs will be retired after the returned `Duration`, if any. Assumed to be constant. - fn aid_lifetime(&self) -> Option; -} - -/// Generates purely random Association IDs of a certain length -#[derive(Default, Debug, Clone, Copy)] -pub struct RandomAssociationIdGenerator { - lifetime: Option, -} - -impl RandomAssociationIdGenerator { - /// Initialize Random AID generator - pub fn new() -> Self { - RandomAssociationIdGenerator::default() - } - - /// Set the lifetime of CIDs created by this generator - pub fn set_lifetime(&mut self, d: Duration) -> &mut Self { - self.lifetime = Some(d); - self - } -} - -impl AssociationIdGenerator for RandomAssociationIdGenerator { - fn generate_aid(&mut self) -> AssociationId { - rand::random::() - } - - fn aid_lifetime(&self) -> Option { - self.lifetime - } -} - -pub(crate) const PADDING_MULTIPLE: usize = 4; - -pub(crate) fn get_padding_size(len: usize) -> usize { - (PADDING_MULTIPLE - (len % PADDING_MULTIPLE)) % PADDING_MULTIPLE -} - -/// Allocate and zero this data once. -/// We need to use it for the checksum and don't want to allocate/clear each time. -pub(crate) static FOUR_ZEROES: Bytes = Bytes::from_static(&[0, 0, 0, 0]); -pub(crate) const ISCSI_CRC: Crc> = Crc::>::new(&CRC_32_ISCSI); - -/// Fastest way to do a crc32 without allocating. -pub(crate) fn generate_packet_checksum(raw: &Bytes) -> u32 { - let mut digest = ISCSI_CRC.digest(); - digest.update(&raw[0..8]); - digest.update(&FOUR_ZEROES[..]); - digest.update(&raw[12..]); - digest.finalize() -} - -/// A [`BytesSource`] implementation for `&'a mut [Bytes]` -/// -/// The type allows to dequeue [`Bytes`] chunks from an array of chunks, up to -/// a configured limit. -pub struct BytesArray<'a> { - /// The wrapped slice of `Bytes` - chunks: &'a mut [Bytes], - /// The amount of chunks consumed from this source - consumed: usize, - length: usize, -} - -impl<'a> BytesArray<'a> { - pub fn from_chunks(chunks: &'a mut [Bytes]) -> Self { - let mut length = 0; - for chunk in chunks.iter() { - length += chunk.len(); - } - - Self { - chunks, - consumed: 0, - length, - } - } -} - -impl<'a> BytesSource for BytesArray<'a> { - fn pop_chunk(&mut self, limit: usize) -> (Bytes, usize) { - // The loop exists to skip empty chunks while still marking them as - // consumed - let mut chunks_consumed = 0; - - while self.consumed < self.chunks.len() { - let chunk = &mut self.chunks[self.consumed]; - - if chunk.len() <= limit { - let chunk = core::mem::take(chunk); - self.consumed += 1; - chunks_consumed += 1; - if chunk.is_empty() { - continue; - } - return (chunk, chunks_consumed); - } else if limit > 0 { - let chunk = chunk.split_to(limit); - return (chunk, chunks_consumed); - } else { - break; - } - } - - (Bytes::new(), chunks_consumed) - } - - fn has_remaining(&self) -> bool { - self.consumed < self.length - } - - fn remaining(&self) -> usize { - self.length - self.consumed - } -} - -/// A [`BytesSource`] implementation for `&[u8]` -/// -/// The type allows to dequeue a single [`Bytes`] chunk, which will be lazily -/// created from a reference. This allows to defer the allocation until it is -/// known how much data needs to be copied. -pub struct ByteSlice<'a> { - /// The wrapped byte slice - data: &'a [u8], -} - -impl<'a> ByteSlice<'a> { - pub fn from_slice(data: &'a [u8]) -> Self { - Self { data } - } -} - -impl<'a> BytesSource for ByteSlice<'a> { - fn pop_chunk(&mut self, limit: usize) -> (Bytes, usize) { - let limit = limit.min(self.data.len()); - if limit == 0 { - return (Bytes::new(), 0); - } - - let chunk = Bytes::from(self.data[..limit].to_owned()); - self.data = &self.data[chunk.len()..]; - - let chunks_consumed = if self.data.is_empty() { 1 } else { 0 }; - (chunk, chunks_consumed) - } - - fn has_remaining(&self) -> bool { - !self.data.is_empty() - } - - fn remaining(&self) -> usize { - self.data.len() - } -} - -/// A source of one or more buffers which can be converted into `Bytes` buffers on demand -/// -/// The purpose of this data type is to defer conversion as long as possible, -/// so that no heap allocation is required in case no data is writable. -pub trait BytesSource { - /// Returns the next chunk from the source of owned chunks. - /// - /// This method will consume parts of the source. - /// Calling it will yield `Bytes` elements up to the configured `limit`. - /// - /// The method returns a tuple: - /// - The first item is the yielded `Bytes` element. The element will be - /// empty if the limit is zero or no more data is available. - /// - The second item returns how many complete chunks inside the source had - /// had been consumed. This can be less than 1, if a chunk inside the - /// source had been truncated in order to adhere to the limit. It can also - /// be more than 1, if zero-length chunks had been skipped. - fn pop_chunk(&mut self, limit: usize) -> (Bytes, usize); - - fn has_remaining(&self) -> bool; - - fn remaining(&self) -> usize; -} - -/// Serial Number Arithmetic (RFC 1982) -#[inline] -pub(crate) fn sna32lt(i1: u32, i2: u32) -> bool { - (i1 < i2 && i2 - i1 < 1 << 31) || (i1 > i2 && i1 - i2 > 1 << 31) -} - -#[inline] -pub(crate) fn sna32lte(i1: u32, i2: u32) -> bool { - i1 == i2 || sna32lt(i1, i2) -} - -#[inline] -pub(crate) fn sna32gt(i1: u32, i2: u32) -> bool { - (i1 < i2 && (i2 - i1) >= 1 << 31) || (i1 > i2 && (i1 - i2) <= 1 << 31) -} - -#[inline] -pub(crate) fn sna32gte(i1: u32, i2: u32) -> bool { - i1 == i2 || sna32gt(i1, i2) -} - -#[inline] -pub(crate) fn sna32eq(i1: u32, i2: u32) -> bool { - i1 == i2 -} - -#[inline] -pub(crate) fn sna16lt(i1: u16, i2: u16) -> bool { - (i1 < i2 && (i2 - i1) < 1 << 15) || (i1 > i2 && (i1 - i2) > 1 << 15) -} - -#[inline] -pub(crate) fn sna16lte(i1: u16, i2: u16) -> bool { - i1 == i2 || sna16lt(i1, i2) -} - -#[inline] -pub(crate) fn sna16gt(i1: u16, i2: u16) -> bool { - (i1 < i2 && (i2 - i1) >= 1 << 15) || (i1 > i2 && (i1 - i2) <= 1 << 15) -} - -#[inline] -pub(crate) fn sna16gte(i1: u16, i2: u16) -> bool { - i1 == i2 || sna16gt(i1, i2) -} - -#[inline] -pub(crate) fn sna16eq(i1: u16, i2: u16) -> bool { - i1 == i2 -} - -#[cfg(test)] -mod test { - use crate::vendor::sctp_proto::error::Result; - - use super::*; - - const DIV: isize = 16; - - #[test] - fn test_serial_number_arithmetic32bit() -> Result<()> { - const SERIAL_BITS: u32 = 32; - const INTERVAL: u32 = ((1u64 << (SERIAL_BITS as u64)) / (DIV as u64)) as u32; - const MAX_FORWARD_DISTANCE: u32 = 1 << ((SERIAL_BITS - 1) - 1); - const MAX_BACKWARD_DISTANCE: u32 = 1 << (SERIAL_BITS - 1); - - for i in 0..DIV as u32 { - let s1 = i * INTERVAL; - let s2f = s1.checked_add(MAX_FORWARD_DISTANCE); - let s2b = s1.checked_add(MAX_BACKWARD_DISTANCE); - - if let (Some(s2f), Some(s2b)) = (s2f, s2b) { - assert!(sna32lt(s1, s2f), "s1 < s2 should be true: s1={} s2={}", s1, s2f); - assert!(!sna32lt(s1, s2b), "s1 < s2 should be false: s1={} s2={}", s1, s2b); - - assert!(!sna32gt(s1, s2f), "s1 > s2 should be false: s1={} s2={}", s1, s2f); - assert!(sna32gt(s1, s2b), "s1 > s2 should be true: s1={} s2={}", s1, s2b); - - assert!(sna32lte(s1, s2f), "s1 <= s2 should be true: s1={} s2={}", s1, s2f); - assert!(!sna32lte(s1, s2b), "s1 <= s2 should be false: s1={} s2={}", s1, s2b); - - assert!(!sna32gte(s1, s2f), "s1 >= s2 should be fales: s1={} s2={}", s1, s2f); - assert!(sna32gte(s1, s2b), "s1 >= s2 should be true: s1={} s2={}", s1, s2b); - - assert!(sna32eq(s2b, s2b), "s2 == s2 should be true: s2={} s2={}", s2b, s2b); - assert!(sna32lte(s2b, s2b), "s2 == s2 should be true: s2={} s2={}", s2b, s2b); - assert!(sna32gte(s2b, s2b), "s2 == s2 should be true: s2={} s2={}", s2b, s2b); - } - - if let Some(s1add1) = s1.checked_add(1) { - assert!( - !sna32eq(s1, s1add1), - "s1 == s1+1 should be false: s1={} s1+1={}", - s1, - s1add1 - ); - } - - if let Some(s1sub1) = s1.checked_sub(1) { - assert!( - !sna32eq(s1, s1sub1), - "s1 == s1-1 hould be false: s1={} s1-1={}", - s1, - s1sub1 - ); - } - - assert!(sna32eq(s1, s1), "s1 == s1 should be true: s1={} s2={}", s1, s1); - assert!(sna32lte(s1, s1), "s1 == s1 should be true: s1={} s2={}", s1, s1); - - assert!(sna32gte(s1, s1), "s1 == s1 should be true: s1={} s2={}", s1, s1); - } - - Ok(()) - } - - #[test] - fn test_serial_number_arithmetic16bit() -> Result<()> { - const SERIAL_BITS: u16 = 16; - const INTERVAL: u16 = ((1u64 << (SERIAL_BITS as u64)) / (DIV as u64)) as u16; - const MAX_FORWARD_DISTANCE: u16 = 1 << ((SERIAL_BITS - 1) - 1); - const MAX_BACKWARD_DISTANCE: u16 = 1 << (SERIAL_BITS - 1); - - for i in 0..DIV as u16 { - let s1 = i * INTERVAL; - let s2f = s1.checked_add(MAX_FORWARD_DISTANCE); - let s2b = s1.checked_add(MAX_BACKWARD_DISTANCE); - - if let (Some(s2f), Some(s2b)) = (s2f, s2b) { - assert!(sna16lt(s1, s2f), "s1 < s2 should be true: s1={} s2={}", s1, s2f); - assert!(!sna16lt(s1, s2b), "s1 < s2 should be false: s1={} s2={}", s1, s2b); - - assert!(!sna16gt(s1, s2f), "s1 > s2 should be fales: s1={} s2={}", s1, s2f); - assert!(sna16gt(s1, s2b), "s1 > s2 should be true: s1={} s2={}", s1, s2b); - - assert!(sna16lte(s1, s2f), "s1 <= s2 should be true: s1={} s2={}", s1, s2f); - assert!(!sna16lte(s1, s2b), "s1 <= s2 should be false: s1={} s2={}", s1, s2b); - - assert!(!sna16gte(s1, s2f), "s1 >= s2 should be fales: s1={} s2={}", s1, s2f); - assert!(sna16gte(s1, s2b), "s1 >= s2 should be true: s1={} s2={}", s1, s2b); - - assert!(sna16eq(s2b, s2b), "s2 == s2 should be true: s2={} s2={}", s2b, s2b); - assert!(sna16lte(s2b, s2b), "s2 == s2 should be true: s2={} s2={}", s2b, s2b); - assert!(sna16gte(s2b, s2b), "s2 == s2 should be true: s2={} s2={}", s2b, s2b); - } - - assert!(sna16eq(s1, s1), "s1 == s1 should be true: s1={} s2={}", s1, s1); - - if let Some(s1add1) = s1.checked_add(1) { - assert!( - !sna16eq(s1, s1add1), - "s1 == s1+1 should be false: s1={} s1+1={}", - s1, - s1add1 - ); - } - if let Some(s1sub1) = s1.checked_sub(1) { - assert!( - !sna16eq(s1, s1sub1), - "s1 == s1-1 hould be false: s1={} s1-1={}", - s1, - s1sub1 - ); - } - - assert!(sna16lte(s1, s1), "s1 == s1 should be true: s1={} s2={}", s1, s1); - assert!(sna16gte(s1, s1), "s1 == s1 should be true: s1={} s2={}", s1, s1); - } - - Ok(()) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/change/direct.rs b/rs/moq-webrtc/src/vendor/str0m/change/direct.rs index 0968894a0a0..cd2deca7063 100644 --- a/rs/moq-webrtc/src/vendor/str0m/change/direct.rs +++ b/rs/moq-webrtc/src/vendor/str0m/change/direct.rs @@ -4,14 +4,12 @@ use crate::vendor::str0m::Candidate; use crate::vendor::str0m::IceCreds; use crate::vendor::str0m::Rtc; use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::channel::ChannelId; use crate::vendor::str0m::crypto::Fingerprint; use crate::vendor::str0m::crypto::dtls::ProtocolVersion; use crate::vendor::str0m::media::{Media, MediaKind}; use crate::vendor::str0m::poll::RtcMut; use crate::vendor::str0m::rtp_::MidRid; use crate::vendor::str0m::rtp_::{Mid, Rid, Ssrc}; -use crate::vendor::str0m::sctp::{ChannelConfig, SctpInitData}; use crate::vendor::str0m::streams::{DEFAULT_RTX_CACHE_DURATION, DEFAULT_RTX_RATIO_CAP, StreamRx, StreamTx}; /// Direct change strategy. @@ -126,61 +124,6 @@ impl<'a> DirectApi<'a> { self.rtc.init_dtls(active) } - /// Start the SCTP over DTLS. - /// - /// When `client` is `true`, this side initiates the SCTP association as the - /// connecting party. - pub fn start_sctp(&mut self, client: bool) { - self.rtc - .try_init_sctp(client, None, None) - .expect("starting SCTP should be infallible") - } - - /// Start SCTP over DTLS using out-of-band SCTP INIT data. - /// - /// This is used for SNAP (SCTP Negotiation Acceleration Protocol), which - /// allows skipping the 4-way SCTP handshake entirely once both peers have - /// exchanged their SCTP INIT chunks out of band. - /// - /// The `sctp_init_data` must contain: - /// - /// 1. A local INIT chunk generated by calling - /// [`SctpInitData::local_init_chunk()`]. - /// 2. The remote INIT chunk set via [`SctpInitData::set_remote_init_chunk()`]. - /// - /// This method returns an error unless both the local and remote INIT - /// chunks are present. - /// - /// This method is the SNAP-specific alternative to [`Self::start_sctp()`]. - /// - /// # Example - /// ```ignore - /// use crate::vendor::str0m::channel::SctpInitData; - /// - /// let mut init_data = SctpInitData::new(); - /// let local_init = init_data.local_init_chunk().unwrap(); - /// // ... exchange local_init via signaling, receive remote_init ... - /// init_data.set_remote_init_chunk(remote_init); - /// rtc.direct_api().start_sctp_with_snap(false, init_data)?; - /// ``` - pub fn start_sctp_with_snap(&mut self, client: bool, sctp_init_data: SctpInitData) -> Result<(), RtcError> { - self.rtc.try_init_sctp(client, Some(sctp_init_data), None) - } - - /// Create a new data channel. - pub fn create_data_channel(&mut self, config: ChannelConfig) -> ChannelId { - let id = self.rtc.chan.new_channel(&config); - self.rtc.chan.confirm(id, config); - id - } - - /// Close a data channel. - pub fn close_data_channel(&mut self, channel_id: ChannelId) { - // One arming deref, then split-borrow the real `&mut Rtc`. - let rtc = &mut *self.rtc; - rtc.chan.close_channel(channel_id, &mut rtc.sctp); - } - /// Set whether to enable ice-lite. pub fn set_ice_lite(&mut self, ice_lite: bool) { self.rtc.ice.set_ice_lite(ice_lite); @@ -196,22 +139,6 @@ impl<'a> DirectApi<'a> { self.rtc.session.streams.new_ssrc() } - /// Get the str0m `ChannelId` by an `sctp_stream_id`. - /// - /// This is useful when using out of band negotiated sctp stream id in - /// [`Self::create_data_channel()`] - pub fn channel_id_by_sctp_stream_id(&self, id: u16) -> Option { - self.rtc.chan.channel_id_by_stream_id(id) - } - - /// Get the `sctp_stream_id` from a str0m `ChannelId`. - /// - /// This is useful when using out of band negotiated sctp stream id in - /// [`Self::create_data_channel()`] - pub fn sctp_stream_id_by_channel_id(&self, id: ChannelId) -> Option { - self.rtc.chan.stream_id_by_channel_id(id) - } - /// Create a new `Media`. /// /// All streams belong to a media identified by a `mid`. This creates the media without diff --git a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs b/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs index 94f7a4a69da..0951d00a620 100644 --- a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs +++ b/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs @@ -2,12 +2,10 @@ use std::fmt; use std::ops::{Deref, DerefMut}; -use std::slice::Iter; use tracing::{debug, warn}; use crate::vendor::str0m::Rtc; use crate::vendor::str0m::RtcError; -use crate::vendor::str0m::channel::ChannelId; use crate::vendor::str0m::crypto::Fingerprint; use crate::vendor::str0m::format::CodecConfig; use crate::vendor::str0m::format::PayloadParams; @@ -17,8 +15,6 @@ use crate::vendor::str0m::poll::RtcMut; use crate::vendor::str0m::rtp_::MidRid; use crate::vendor::str0m::rtp_::Rid; use crate::vendor::str0m::rtp_::{Direction, Extension, ExtensionMap, Mid, Pt, Ssrc}; -use crate::vendor::str0m::sctp::ChannelConfig; -use crate::vendor::str0m::sctp::RtcSctp; use crate::vendor::str0m::sdp::{self, MediaAttribute, MediaLine, MediaType, Msid, Sdp}; use crate::vendor::str0m::sdp::{Proto, SessionAttribute, Setup, SimulcastGroups}; use crate::vendor::str0m::session::Session; @@ -118,30 +114,9 @@ impl<'a> SdpApi<'a> { // Ensure setup=active/passive is corresponding remote and init dtls. init_dtls(&mut self.rtc, &offer)?; - let remote_max_message_size = extract_max_message_size(offer.media_lines.iter()); - - // Extract a=sctp-init from remote offer before apply_offer consumes it. - let remote_sctp_init = offer.sctp_init().map(|v| v.to_owned()); - - let has_snap = process_remote_sctp_init(&mut self.rtc.sctp, remote_sctp_init.as_deref())?; - - // Modify session with offer. + // Modify session with offer. An m=application line is answered rejected. apply_offer(&mut self.rtc.session, offer)?; - // Handle potentially new m=application line. - let client = self.rtc.dtls.is_active().expect("DTLS active to be set"); - - // Generate local sctp-init for the answer: - // When the remote included a=sctp-init, we reciprocate (§5.4). - if has_snap && !self.rtc.sctp.is_inited() && !self.rtc.sctp.ensure_local_snap_init() { - warn!("Failed to generate SNAP INIT chunk, degrading to non-SNAP"); - } - - if self.rtc.session.app().is_some() { - let init_data = self.rtc.sctp.build_snap_init_data(); - self.rtc.try_init_sctp(client, init_data, remote_max_message_size)?; - } - let params = AsSdpParams::new(&self.rtc, None); let sdp = as_sdp(&self.rtc.session, params); @@ -171,7 +146,7 @@ impl<'a> SdpApi<'a> { /// /// rtc.sdp_api().accept_answer(pending, answer).unwrap(); /// ``` - pub fn accept_answer(mut self, mut pending: SdpPendingOffer, answer: SdpAnswer) -> Result<(), RtcError> { + pub fn accept_answer(mut self, pending: SdpPendingOffer, answer: SdpAnswer) -> Result<(), RtcError> { debug!("Accept answer"); // Ensure we don't use the wrong changes below. We must use that of pending. @@ -199,40 +174,9 @@ impl<'a> SdpApi<'a> { } } - // Extract a=sctp-init from remote answer before apply_answer consumes it. - let remote_sctp_init = answer.sctp_init().map(|v| v.to_owned()); - - let expected_snap_answer = !self.rtc.sctp.is_inited() && self.rtc.sctp.local_sctp_init_for_sdp().is_some(); - - // Validate or cache the remote value before mutating the session. This - // keeps a bad re-offer/re-answer from partially applying local state. - let has_snap = process_remote_sctp_init(&mut self.rtc.sctp, remote_sctp_init.as_deref())?; - - // Split out new channels, since that is not handled by the Session. - let new_channels = pending.changes.take_new_channels(); - - let remote_max_message_size = extract_max_message_size(answer.media_lines.iter()); - // Modify session with answer apply_answer(&mut self.rtc.session, pending.changes, answer)?; - // Handle potentially new m=application line. - let client = self.rtc.dtls.is_active().expect("DTLS to be inited"); - - if expected_snap_answer && !has_snap { - debug!("Remote answer did not accept SNAP, falling back to regular SCTP handshake"); - self.rtc.sctp.disable_pending_snap(); - } - - if self.rtc.session.app().is_some() { - let init_data = self.rtc.sctp.build_snap_init_data(); - self.rtc.try_init_sctp(client, init_data, remote_max_message_size)?; - } - - for (id, config) in new_channels { - self.rtc.chan.confirm(id, config); - } - Ok(()) } @@ -392,74 +336,6 @@ impl<'a> SdpApi<'a> { } } - /// Add a new reliable ordered data channel and get the `id` that will be used. - /// - /// Use `add_channel_with_config` when unreliable or unordered data channels are preferred. - /// - /// The first ever data channel added to a WebRTC session results in a media - /// of a special "application" type in the SDP. The m-line is for a SCTP association over - /// DTLS, and all data channels are multiplexed over this single association. - /// - /// That means only the first ever `add_channel` will result in an [`SdpOffer`]. - /// Consecutive channels will be opened without needing a negotiation. - /// - /// The label is used to identify the data channel to the remote peer. This is mostly - /// useful when multiple channels are in use at the same time. - /// - /// ```ignore - /// # #[cfg(any())] { - /// # use std::time::Instant; - /// # use crate::vendor::str0m::Rtc; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let mut changes = rtc.sdp_api(); - /// - /// let cid = changes.add_channel("my special channel".to_string()); - /// # } - /// ``` - pub fn add_channel(&mut self, label: String) -> ChannelId { - self.add_channel_with_config(ChannelConfig { - label, - ..Default::default() - }) - } - - /// Add a new data channel with a given configuration and get the `id` that will be used. - /// - /// Refer to `add_channel` for more details. - /// - /// ```ignore - /// # #[cfg(any())] { - /// # use std::time::Instant; - /// # use crate::vendor::str0m::{channel::{ChannelConfig, Reliability}, Rtc}; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let mut changes = rtc.sdp_api(); - /// - /// let cid = changes.add_channel_with_config(ChannelConfig { - /// label: "my special channel".to_string(), - /// reliability: Reliability::MaxRetransmits{ retransmits: 0 }, - /// ordered: false, - /// ..Default::default() - /// }); - /// # } - /// ``` - pub fn add_channel_with_config(&mut self, config: ChannelConfig) -> ChannelId { - let has_media = self.rtc.session.app().is_some(); - let changes_contains_add_app = self.changes.contains_add_app(); - - if !has_media && !changes_contains_add_app { - let mid = self.new_mid(); - self.changes.0.push(Change::AddApp(mid)); - } - - let id = self.rtc.chan.new_channel(&config); - - self.changes.0.push(Change::AddChannel((id, config))); - - id - } - /// Perform an ICE restart. /// /// Only one ICE restart can be pending at the time. Calling this repeatedly removes any other @@ -486,9 +362,7 @@ impl<'a> SdpApi<'a> { /// not happening straight away, and the caller is expected to do a negotiation with the remote /// peer and apply the answer using [`SdpPendingOffer`]. /// - /// In case this returns `None`, there either were no changes, or the changes could be applied - /// without doing a negotiation. Specifically for additional [`SdpApi::add_channel()`] - /// after the first, there is no negotiation needed. + /// In case this returns `None`, there were no changes. /// /// The [`SdpPendingOffer`] is valid until the next time we call this function, at which /// point using it will raise an error. Using [`SdpApi::accept_offer()`] will also invalidate @@ -511,27 +385,19 @@ impl<'a> SdpApi<'a> { let change_id = self.rtc.next_change_id(); - let requires_negotiation = self.changes.0.iter().any(requires_negotiation); - - if requires_negotiation { - let offer = create_offer(&mut self.rtc, &self.changes); - let pending = SdpPendingOffer { - change_id, - changes: self.changes, - }; - debug!("Create offer"); - Some((offer, pending)) - } else { - debug!("Apply direct changes"); - apply_direct_changes(&mut self.rtc, self.changes); - None - } + let offer = create_offer(&mut self.rtc, &self.changes); + let pending = SdpPendingOffer { + change_id, + changes: self.changes, + }; + debug!("Create offer"); + Some((offer, pending)) } } /// Pending offer from a previous [`Rtc::sdp_api()`] call. /// -/// Represents one local negotiation change set, which can contain multiple media or channel +/// Represents one local negotiation change set, which can contain multiple media /// changes, and allows accepting its remote answer. It is not a queue of pending negotiations. /// Creating another offer with [`SdpApi::apply()`] invalidates it, as does calling /// [`SdpApi::accept_offer()`]. Invalidated changes cannot be reapplied through this token. @@ -583,8 +449,6 @@ impl Changes { #[allow(clippy::large_enum_variant)] pub(crate) enum Change { AddMedia(AddMedia), - AddApp(Mid), - AddChannel((ChannelId, ChannelConfig)), Direction(Mid, Direction), IceRestart(IceCreds, bool), } @@ -621,25 +485,6 @@ impl DerefMut for Changes { } } -fn requires_negotiation(c: &Change) -> bool { - match c { - Change::IceRestart(_, _) => true, - Change::AddMedia(_) => true, - Change::AddApp(_) => true, - Change::AddChannel(_) => false, - Change::Direction(_, _) => true, - } -} - -fn apply_direct_changes(rtc: &mut Rtc, mut changes: Changes) { - // Split out new channels, since that is not handled by the Session. - let new_channels = changes.take_new_channels(); - - for (id, config) in new_channels { - rtc.chan.confirm(id, config); - } -} - fn create_offer(rtc: &mut Rtc, changes: &Changes) -> SdpOffer { if !rtc.dtls.is_inited() { // The side that makes the first offer is the controlling side, unless they @@ -647,15 +492,6 @@ fn create_offer(rtc: &mut Rtc, changes: &Changes) -> SdpOffer { rtc.ice.set_controlling(!rtc.ice.ice_lite()); } - // Generate local sctp-init for SNAP if enabled and we have/will have an app m-line. - if rtc.sctp.snap_enabled() - && (rtc.session.app().is_some() || changes.contains_add_app()) - && !rtc.sctp.is_inited() - && !rtc.sctp.ensure_local_snap_init() - { - warn!("Failed to generate SNAP INIT chunk, degrading to non-SNAP"); - } - let params = AsSdpParams::new(rtc, Some(changes)); let sdp = as_sdp(&rtc.session, params); @@ -724,57 +560,6 @@ fn init_dtls(rtc: &mut Rtc, remote_sdp: &Sdp) -> Result<(), RtcError> { Ok(()) } -/// Shared logic for processing a remote `a=sctp-init` attribute from an offer or answer. -/// -/// Returns `true` if this is a new SNAP negotiation (remote init was accepted), -/// `false` otherwise. -/// -/// The remote init bytes are stored in `RtcSctp.snap_init` for §5.6 -/// re-offer validation. -/// -/// When the remote includes `a=sctp-init`, we always accept and reciprocate - -/// Section 5.4 of draft-hancke-tsvwg-snap says the answerer MAY include the -/// attribute, and doing so is beneficial. -/// -/// When an initial answer omits or rejects `a=sctp-init`, callers are expected -/// to fall back to a regular SCTP handshake. -fn process_remote_sctp_init(sctp: &mut RtcSctp, remote_init: Option<&str>) -> Result { - if let Some(remote_init_str) = remote_init { - if sctp.is_inited() { - // §5.6: SCTP already established - remote MUST re-send the - // same sctp-init value on subsequent offers/answers. - match sctp.snap_remote_init_string() { - Some(cached) if cached == remote_init_str => { - debug!("Remote re-sent expected a=sctp-init for established association"); - } - Some(_) => { - return Err(RtcError::RemoteSdp( - "Changed a=sctp-init for existing SCTP association".into(), - )); - } - None => { - // SCTP was established without SNAP but the remote is now - // sending a=sctp-init. We can't transition to SNAP - // mid-session, so just ignore it. - debug!("Ignoring a=sctp-init for non-SNAP established SCTP association"); - } - } - Ok(false) - } else if sctp.set_remote_snap_init_string(remote_init_str) { - Ok(true) - } else { - debug!("Ignoring malformed a=sctp-init"); - Ok(false) - } - } else if sctp.is_snap_established() { - Err(RtcError::RemoteSdp( - "Missing a=sctp-init for established SNAP SCTP association".into(), - )) - } else { - Ok(false) - } -} - fn as_sdp(session: &Session, params: AsSdpParams) -> Sdp { let (media_lines, mids, stream_ids) = { let mut v = as_media_lines(session); @@ -817,17 +602,6 @@ fn as_sdp(session: &Session, params: AsSdpParams) -> Sdp { }) .collect::>(); - for line in &mut lines { - if line.typ.is_channel() { - line.attrs - .push(MediaAttribute::MaxMessageSize(params.local_max_message_size as usize)); - // Add a=sctp-init to the application m-line if SNAP is configured. - if let Some(sctp_init) = ¶ms.local_sctp_init { - line.attrs.push(sdp::MediaAttribute::SctpInit(sctp_init.clone())); - } - } - } - if let Some(pending) = params.pending { pending.apply_to(&mut lines); } @@ -1311,23 +1085,6 @@ fn update_media( } } -fn extract_max_message_size(mut media_lines: Iter) -> Option { - if let Some(app_line) = media_lines.find(|m| m.typ.is_channel()) { - if let Some(max_size) = app_line.max_message_size() { - // RFC 8841 §6.1: a value of 0 means the peer can receive a message of - // any size, subject to local capacity. Represent that as the maximum. - let max_size = if max_size == 0 { - u32::MAX - } else { - u32::try_from(max_size).unwrap_or(u32::MAX) - }; - return Some(max_size); - } - } - - None -} - trait AsSdpMediaLine { fn mid(&self) -> Mid; fn msid(&self) -> Option<&Msid>; @@ -1363,11 +1120,11 @@ impl AsSdpMediaLine for (Mid, usize) { _params: &[PayloadParams], ) -> MediaLine { attrs.push(MediaAttribute::Mid(self.0)); - attrs.push(MediaAttribute::SctpPort(5000)); + // No SCTP runs here, so a remote data channel line is always rejected. MediaLine { typ: sdp::MediaType::Application, - disabled: false, + disabled: true, proto: Proto::Sctp, pts: vec![], bw: None, @@ -1396,11 +1153,6 @@ impl AsSdpMediaLine for Media { exts: &ExtensionMap, params: &[PayloadParams], ) -> MediaLine { - if self.app_tmp { - let app = (self.mid(), self.index()); - return app.as_media_line(attrs, ssrcs_tx, exts, params); - } - attrs.push(MediaAttribute::Mid(self.mid())); let audio = self.kind() == MediaKind::Audio; @@ -1512,8 +1264,6 @@ struct AsSdpParams<'a, 'b> { pub fingerprint: &'a Fingerprint, pub setup: Setup, pub pending: Option<&'b Changes>, - pub local_sctp_init: Option, - pub local_max_message_size: u32, } impl<'a, 'b> AsSdpParams<'a, 'b> { @@ -1561,8 +1311,6 @@ impl<'a, 'b> AsSdpParams<'a, 'b> { fingerprint: rtc.dtls.local_fingerprint(), setup, pending, - local_sctp_init: rtc.sctp.local_sctp_init_for_sdp(), - local_max_message_size: rtc.sctp.local_max_message_size(), } } @@ -1595,38 +1343,10 @@ impl Changes { fn has_mid(&self, mid: Mid) -> bool { self.0.iter().any(|c| match c { Change::AddMedia(v) => v.mid == mid, - Change::AddApp(v) => *v == mid, - Change::AddChannel(_) | Change::Direction(_, _) | Change::IceRestart(_, _) => false, + Change::Direction(_, _) | Change::IceRestart(_, _) => false, }) } - pub fn contains_add_app(&self) -> bool { - for i in 0..self.0.len() { - if matches!(&self.0[i], Change::AddApp(_)) { - return true; - } - } - false - } - - pub fn take_new_channels(&mut self) -> Vec<(ChannelId, ChannelConfig)> { - let mut v = vec![]; - - if self.0.is_empty() { - return v; - } - - for i in (0..self.0.len()).rev() { - if matches!(&self.0[i], Change::AddChannel(_)) { - if let Change::AddChannel(id) = self.0.remove(i) { - v.push(id); - } - } - } - - v - } - /// Tests the given lines (from answer) corresponds to changes. fn ensure_correct_answer(&self, lines: &[(usize, &MediaLine)]) -> Option { if self.count_new_medias() != lines.len() { @@ -1652,15 +1372,6 @@ impl Changes { } continue 'next; } - AddApp(v) if *v == mid => { - if !l.typ.is_channel() { - return Some(format!( - "Answer m-line for mid ({}) is not a data channel: {:?}", - mid, l.typ - )); - } - continue 'next; - } _ => {} } } @@ -1672,10 +1383,7 @@ impl Changes { } fn count_new_medias(&self) -> usize { - self.0 - .iter() - .filter(|c| matches!(c, Change::AddMedia(_) | Change::AddApp(_))) - .count() + self.0.iter().filter(|c| matches!(c, Change::AddMedia(_))).count() } pub fn as_new_medias<'a, 'b: 'a>( @@ -1685,8 +1393,8 @@ impl Changes { exts: &'b ExtensionMap, ) -> impl Iterator + 'a { // Use a separate counter that only advances for entries that actually produce - // an m-line (AddMedia / AddApp). Non-media entries (Direction, IceRestart, - // AddChannel) must not consume an index slot, otherwise the resulting m-line + // an m-line (AddMedia). Non-media entries (Direction, IceRestart) + // must not consume an index slot, otherwise the resulting m-line // indices would be non-contiguous and out of sync with their array positions. let mut media_idx = 0usize; self.0.iter().filter_map(move |c| { @@ -1738,7 +1446,6 @@ impl Change { Some(Media::from_add_media(add)) } - AddApp(mid) => Some(Media::from_app_tmp(*mid, index)), _ => None, } } @@ -1857,11 +1564,11 @@ mod test { let mut rtc2 = Rtc::new(now); let mut change1 = rtc1.sdp_api(); - change1.add_channel("ch1".into()); + change1.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer1, pending1) = change1.apply().unwrap(); let mut change2 = rtc2.sdp_api(); - change2.add_channel("ch2".into()); + change2.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer2, _) = change2.apply().unwrap(); // invalidates pending1 @@ -1874,9 +1581,8 @@ mod test { } // The indices assigned to Media objects by as_new_medias() must be contiguous starting - // from index_start. Only entries that produce m-lines (AddMedia / AddApp) should - // consume an index slot – non-media entries (AddChannel, Direction, IceRestart) must - // not advance the counter. + // from index_start. Only entries that produce m-lines (AddMedia) should consume an + // index slot – non-media entries (Direction, IceRestart) must not advance the counter. // // We test this by building a Changes vector directly and inspecting the indices // returned by as_new_medias(). @@ -1885,67 +1591,81 @@ mod test { crate::vendor::str0m::init_crypto_default(); let now = Instant::now(); - let mut rtc = Rtc::new(now); + let rtc = Rtc::new(now); + + let add = |mid: Mid, kind: MediaKind| { + Change::AddMedia(AddMedia { + mid, + cname: "test".into(), + msid: Msid { + stream_id: "stream".into(), + track_id: "track".into(), + }, + kind, + dir: Direction::SendOnly, + ssrcs: vec![], + simulcast: None, + pts: vec![], + exts: ExtensionMap::empty(), + index: 0, // will be overwritten by as_new_media() + }) + }; - // Build a Changes vector that interleaves non-media entries with media entries. - // The non-media AddChannel entry must not consume an index slot. - // - // Changes = [AddApp(mid0), AddChannel(id, cfg), AddMedia(audio)] - // - // index_start = 0 (fresh session) - // Expected indices: AddApp → 0, AddMedia(audio) → 1 - // Buggy indices: AddApp → 0, AddMedia(audio) → 2 + // Changes = [AddMedia(audio), IceRestart, AddMedia(video)] let mut changes = Changes::default(); - let mid_app = rtc.new_mid(); - changes.0.push(Change::AddApp(mid_app)); - let mid_audio = rtc.new_mid(); - let chan_id = rtc.chan.new_channel(&ChannelConfig { - label: "ch".into(), - ..Default::default() - }); - changes.0.push(Change::AddChannel(( - chan_id, - ChannelConfig { - label: "ch".into(), - ..Default::default() - }, - ))); - changes.0.push(Change::AddMedia(AddMedia { - mid: mid_audio, - cname: "test".into(), - msid: Msid { - stream_id: "stream".into(), - track_id: "track".into(), - }, - kind: MediaKind::Audio, - dir: Direction::SendOnly, - ssrcs: vec![], - simulcast: None, - pts: vec![], - exts: ExtensionMap::empty(), - index: 0, // will be overwritten by as_new_media() - })); + changes.0.push(add(rtc.new_mid(), MediaKind::Audio)); + changes.0.push(Change::IceRestart(IceCreds::new(), true)); + changes.0.push(add(rtc.new_mid(), MediaKind::Video)); let config = CodecConfig::new_with_defaults(); let exts = ExtensionMap::standard(); let medias: Vec = changes.as_new_medias(0, &config, &exts).collect(); - // Should produce two Media objects: one for AddApp, one for AddMedia(audio). assert_eq!(medias.len(), 2, "Expected 2 media-producing entries"); - - // The first m-line is AddApp at index 0. - assert_eq!(medias[0].index(), 0, "AddApp should have index 0"); - - // The second m-line is Audio. It must get the contiguous index 1, not 2 (which - // would result from counting the non-media AddChannel entry as a slot). + assert_eq!(medias[0].index(), 0, "AddMedia(audio) should have index 0"); + // Index 2 would result from counting the non-media IceRestart entry as a slot. assert_eq!( medias[1].index(), 1, - "AddMedia(audio) should have contiguous index 1, not 2" + "AddMedia(video) should have contiguous index 1, not 2" ); } + /// No SCTP runs here, so an offered data channel is answered rejected and left out of + /// the BUNDLE group, while the media beside it is accepted. + #[test] + fn an_offered_data_channel_is_answered_rejected() { + crate::vendor::str0m::init_crypto_default(); + + let now = Instant::now(); + let mut offerer = Rtc::new(now); + let mut change = offerer.sdp_api(); + let audio = change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + let (offer, _) = change.apply().unwrap(); + let offer = offer.to_sdp_string().replace( + &format!("a=group:BUNDLE {audio}\r\n"), + &format!("a=group:BUNDLE {audio} dc\r\n"), + ) + "m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ + c=IN IP4 0.0.0.0\r\n\ + a=mid:dc\r\n\ + a=sctp-port:5000\r\n"; + let offer = SdpOffer::from_sdp_string(&offer).expect("offer with a data channel"); + + let answer = Rtc::new(now).sdp_api().accept_offer(offer).unwrap(); + + let app = answer.media_lines.iter().find(|m| m.typ.is_channel()).unwrap(); + assert!(app.disabled, "the data channel was accepted"); + let media = answer.media_lines.iter().find(|m| m.mid() == audio).unwrap(); + assert!(!media.disabled, "the audio was rejected"); + let answer = answer.to_sdp_string(); + assert!( + answer.contains("m=application 0 UDP/DTLS/SCTP webrtc-datachannel\r\n"), + "{answer}" + ); + assert!(answer.contains(&format!("a=group:BUNDLE {audio}\r\n")), "{answer}"); + } + #[test] fn twcc_negotiation_uses_first_media_section_for_each_pt() { crate::vendor::str0m::init_crypto_default(); @@ -2294,214 +2014,4 @@ mod test { // No space at the end assert_eq!(count_lines(&line_string, "a=rid:no_attrs send"), 1); } - - #[test] - fn test_local_max_message_size_advertised() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut rtc = Rtc::new(now); - - // Create an offer with a data channel - let mut change = rtc.sdp_api(); - change.add_channel("test-channel".into()); - let (offer, _) = change.apply().unwrap(); - - // Find the application m-line in the offer - let app_line = offer - .media_lines - .iter() - .find(|m| m.typ.is_channel()) - .expect("should have application m-line"); - - // Verify that max-message-size attribute is present and matches LOCAL_MAX_MESSAGE_SIZE - let max_size = app_line - .max_message_size() - .expect("max-message-size attribute should be present"); - - assert_eq!( - max_size, - crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE as usize, - "max-message-size should match LOCAL_MAX_MESSAGE_SIZE constant" - ); - - // Also verify it's in the SDP string output - let sdp_string = offer.to_sdp_string(); - let expected_line = format!( - "a=max-message-size:{}", - crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE - ); - assert!( - sdp_string.contains(&expected_line), - "SDP should contain max-message-size attribute with LOCAL_MAX_MESSAGE_SIZE value" - ); - } - - #[test] - fn test_remote_max_message_size_parsing() { - // Parse SDP with max-message-size attribute and verify value is extracted correctly - let sdp = "v=0\r\n\ - o=- 0 0 IN IP4 172.17.0.1\r\n\ - s=-\r\n\ - c=IN IP4 172.17.0.1\r\n\ - t=0 0\r\n\ - a=group:BUNDLE 0\r\n\ - a=fingerprint:sha-256 B4:12:1C:7C:7D:ED:F1:FA:61:07:57:9C:29:BE:58:E3:BC:41:E7:13:8E:7D\ - :D3:9D:1F:94:6E:A5:23:46:94:23\r\n\ - m=application 9999 UDP/DTLS/SCTP webrtc-datachannel\r\n\ - a=mid:0\r\n\ - a=ice-ufrag:test\r\n\ - a=ice-pwd:testpassword1234\r\n\ - a=setup:actpass\r\n\ - a=sctp-port:5000\r\n\ - a=max-message-size:131072\r\n\ - "; - - let offer = SdpOffer::from_sdp_string(sdp).expect("should parse"); - - // Find the application m-line - let app_line = offer - .media_lines - .iter() - .find(|m| m.typ.is_channel()) - .expect("should have application m-line"); - - assert_eq!( - app_line.max_message_size(), - Some(131072), - "max-message-size should be parsed as 131072" - ); - } - - #[test] - fn test_remote_max_message_size_applied() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let custom_max_size1 = 98304u32; - let custom_max_size2 = 131072u32; - let mut rtc1 = Rtc::builder().set_sctp_max_message_size(custom_max_size1).build(now); - let mut rtc2 = Rtc::builder().set_sctp_max_message_size(custom_max_size2).build(now); - - // Create an offer from rtc1 with a channel - let mut change1 = rtc1.sdp_api(); - change1.add_channel("test-channel".into()); - let (offer1, pending1) = change1.apply().unwrap(); - - let offer_sdp = offer1.to_sdp_string(); - assert!(offer_sdp.contains(&format!("a=max-message-size:{custom_max_size1}\r\n"))); - let offer = SdpOffer::from_sdp_string(&offer_sdp).unwrap(); - let answer = rtc2.sdp_api().accept_offer(offer).unwrap(); - - // Verify that rtc2's SCTP send limit is set to the custom value from rtc1's offer - assert_eq!( - rtc2.sctp.remote_max_message_size(), - custom_max_size1, - "rtc2 should have remote max message size set to rtc1's advertised value" - ); - - // Now verify the reverse: rtc1 accepts rtc2's answer and applies its max-message-size - let answer_sdp = answer.to_sdp_string(); - assert!(answer_sdp.contains(&format!("a=max-message-size:{custom_max_size2}\r\n"))); - let answer = SdpAnswer::from_sdp_string(&answer_sdp).unwrap(); - - rtc1.sdp_api().accept_answer(pending1, answer).unwrap(); - - assert_eq!( - rtc1.sctp.remote_max_message_size(), - custom_max_size2, - "rtc1 should have remote max message size set to rtc2's advertised value" - ); - - let mut change = rtc1.sdp_api(); - change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let (offer, pending) = change.apply().unwrap(); - assert_eq!( - offer - .media_lines - .iter() - .find(|m| m.typ.is_channel()) - .unwrap() - .max_message_size(), - Some(custom_max_size1 as usize) - ); - let answer = rtc2.sdp_api().accept_offer(offer).unwrap(); - assert_eq!( - answer - .media_lines - .iter() - .find(|m| m.typ.is_channel()) - .unwrap() - .max_message_size(), - Some(custom_max_size2 as usize) - ); - rtc1.sdp_api().accept_answer(pending, answer).unwrap(); - } - - #[test] - fn test_remote_max_message_size_zero_means_unbounded() { - // RFC 8841 §6.1: a=max-message-size:0 means the peer can receive a message - // of any size, so we represent it as u32::MAX rather than passing 0 through - // (which would reject every non-empty outbound message in sctp-proto). - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut rtc1 = Rtc::new(now); - let mut rtc2 = Rtc::new(now); - - let mut change1 = rtc1.sdp_api(); - change1.add_channel("test-channel".into()); - let (offer1, _pending1) = change1.apply().unwrap(); - - let sdp_string = offer1.to_sdp_string(); - let modified_sdp = sdp_string.replace( - &format!( - "a=max-message-size:{}", - crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE - ), - "a=max-message-size:0", - ); - - let modified_offer = SdpOffer::from_sdp_string(&modified_sdp).expect("modified SDP should parse"); - - rtc2.sdp_api().accept_offer(modified_offer).unwrap(); - - assert_eq!( - rtc2.sctp.remote_max_message_size(), - u32::MAX, - "a=max-message-size:0 should be treated as unbounded (u32::MAX)" - ); - } - - #[test] - fn test_remote_max_message_size_too_large_clamps_to_unbounded() { - crate::vendor::str0m::init_crypto_default(); - - let now = Instant::now(); - let mut rtc1 = Rtc::new(now); - let mut rtc2 = Rtc::new(now); - - let mut change1 = rtc1.sdp_api(); - change1.add_channel("test-channel".into()); - let (offer1, _pending1) = change1.apply().unwrap(); - - let sdp_string = offer1.to_sdp_string(); - let modified_sdp = sdp_string.replace( - &format!( - "a=max-message-size:{}", - crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE - ), - "a=max-message-size:4294967296", - ); - - let modified_offer = SdpOffer::from_sdp_string(&modified_sdp).expect("modified SDP should parse"); - - rtc2.sdp_api().accept_offer(modified_offer).unwrap(); - - assert_eq!( - rtc2.sctp.remote_max_message_size(), - u32::MAX, - "a=max-message-size larger than u32::MAX should be treated as unbounded" - ); - } } diff --git a/rs/moq-webrtc/src/vendor/str0m/channel.rs b/rs/moq-webrtc/src/vendor/str0m/channel.rs deleted file mode 100644 index 7f8f39d2695..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/channel.rs +++ /dev/null @@ -1,772 +0,0 @@ -//! Data channel related types. - -use std::{fmt, str, time::Instant}; -use tracing::{debug, warn}; - -use crate::vendor::str0m::poll::{RtcMut, Wake}; -use crate::vendor::str0m::sctp::RtcSctp; -use crate::vendor::str0m::util::already_happened; -use crate::vendor::str0m::{Rtc, RtcError}; - -pub use crate::vendor::str0m::sctp::ChannelConfig; -pub use crate::vendor::str0m::sctp::Reliability; -pub use crate::vendor::str0m::sctp::SctpInitData; - -/// Identifier of a data channel. -/// -/// This is NOT the SCTP stream id. -// Deliberately not Deref or From to avoid this Id being created outside of this module. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct ChannelId(usize); - -/// Data channel data from remote peer. -/// -/// This is obtained via [`Event::ChannelData`][crate::vendor::str0m::Event::ChannelData]. -#[derive(PartialEq, Eq)] -pub struct ChannelData { - /// Identifier of the channel this data was sent on. - /// - /// The channel would have been previously announced via - /// [`Event::ChannelOpen`][crate::vendor::str0m::Event::ChannelOpen]. - pub id: ChannelId, - - /// Tells whether the sender sent this data as binary or text. - pub binary: bool, - - /// The actual data sent. If `binary` is false, this can be converted to text. - pub data: Vec, -} - -/// Channel for sending data to the remote peer. -/// -/// Get this handle from [`Rtc::channel()`][crate::vendor::str0m::Rtc::channel()]. -pub struct Channel<'a> { - sctp_stream_id: u16, - // `RtcMut` arms the readiness on mutable deref only; see [`crate::vendor::str0m::poll`]. - rtc: RtcMut<'a>, -} - -impl<'a> Channel<'a> { - pub(crate) fn new(sctp_stream_id: u16, rtc: &'a mut Rtc) -> Self { - Channel { - rtc: RtcMut::new(rtc), - sctp_stream_id, - } - } - - /// Write data to the remote peer and indicate whether it's text or binary. - /// - /// Returns true or false whether the buffer was accepted or not. - #[must_use = "Whether the buffer was accepted by the write()"] - pub fn write(&mut self, binary: bool, buf: &[u8]) -> Result { - // If it's not available, don't accept. - let available = self.rtc.sctp.available(); - if buf.len() > available { - return Ok(false); - } - - // Try write. - let written = self.rtc.sctp.write(self.sctp_stream_id, binary, buf)?; - - // Invariant: if available calculation is correct, we should have accepted. - assert_eq!(written, buf.len(), "Data channel write() less than entire buffer"); - - Ok(true) - } - - /// Get the amount of buffered data. - /// - /// Returns 0 if the channel is closed or encountered some error. This is to - /// be similar to the [RTCPeerConnection equivalent][buff] - /// - /// [buff]: https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/bufferedAmount - pub fn buffered_amount(&mut self) -> usize { - self.rtc.sctp.buffered_amount(self.sctp_stream_id) - } - - /// Set the threshold to emit an - /// [`Event::ChannelBufferedAmountLow`][crate::vendor::str0m::Event::ChannelBufferedAmountLow] - /// - /// Setting this on a closed or broken channel does not show an error. This is - /// be similar to the [RTCPeerConnection equivalent][buff] - /// - /// [buff]: https://developer.mozilla.org/en-US/docs/Web/API/RTCDataChannel/bufferedAmountLowThreshold - pub fn set_buffered_amount_low_threshold(&mut self, threshold: usize) { - self.rtc - .sctp - .set_buffered_amount_low_threshold(self.sctp_stream_id, threshold); - } - - /// Get the channel config. - /// - /// The config is not available in every case depending on whether the channel was - /// negotiated in- or out of band. - /// - /// # In-band negotiation (the usual case) - /// - /// For (regular) in-band negotiation (DCEP, Data Channel Establishment Protocol), this - /// returns `None` until the DCEP handshake completes. The config is guaranteed to be - /// available when [`Event::ChannelOpen`][crate::vendor::str0m::Event::ChannelOpen] is emitted. - /// - /// # Out-of-band negotiation - /// - /// Returns `None` when the remote side created the data channel connection without using - /// DCEP. This is called out-of-band negotiation, where the remote peer opens a stream - /// but doesn't send the channel configuration through the DCEP protocol messages. - /// - /// For locally created out-of-band channels, the config is always available since it - /// was provided during channel creation. - /// - /// In str0m, DCEP is disabled by setting the `negotiated` field to `Some(stream_id)` in - /// [`ChannelConfig`]. This corresponds to the `negotiated: true` property in the - /// browser's [`createDataChannel()`][n] dictionary. - /// - /// [n]: https://developer.mozilla.org/en-US/docs/Web/API/RTCPeerConnection/createDataChannel#negotiated - pub fn config(&self) -> Option<&ChannelConfig> { - self.rtc.sctp.config(self.sctp_stream_id) - } -} - -impl fmt::Debug for ChannelData { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - let mut ds = f.debug_struct("ChannelData"); - - ds.field("id", &self.id); - ds.field("binary", &self.binary); - - let len = &self.data.len(); - if self.binary { - ds.field("data", len); - } else { - match str::from_utf8(&self.data) { - Ok(s) => { - const MAX_LINE_WIDTH: usize = 79; - const REST_OF_LINE_WIDTH: usize = - "ChannelData { id: ChannelId(0), binary: false, data: \"\" }".len(); - const TUPLE_WIDTH: usize = "(xxx, ..)".len(); - const DATA_WIDTH: usize = MAX_LINE_WIDTH - REST_OF_LINE_WIDTH; - const PREFIX_WIDTH: usize = DATA_WIDTH - TUPLE_WIDTH; - if s.is_ascii() { - if len > &DATA_WIDTH { - let trunc: String = s.chars().take(PREFIX_WIDTH).collect(); - ds.field("data", &format_args!("({}, \"{}\"..)", len, trunc)); - } else { - ds.field("data", &s); - } - } else { - ds.field("data", len); - } - } - Err(e) => { - ds.field("data", &format_args!("{:?}", (len, &e))); - } - } - } - - ds.finish() - } -} - -#[derive(Debug, Default)] -pub(crate) struct ChannelHandler { - allocations: Vec, - next_channel_id: usize, - /// Stream IDs of closed channels whose reset handshake is still - /// outstanding, excluded from allocation until it completes. - closed_stream_ids: Vec, -} - -#[derive(Debug)] -struct ChannelAllocation { - id: ChannelId, - - /// Stream id, when it is known. This might be delayed awaiting sctp initialization to - /// know if we are client or server, or awaiting the reset handshake of a previous - /// incarnation of a negotiated id. - sctp_stream_id: Option, - - /// The out-of-band negotiated stream id the user asked for. Promoted to - /// `sctp_stream_id` once reset which was holding it completes. - negotiated_stream_id: Option, - - /// Holds the config until it is used in handle_timeout. - config: Option, -} - -impl ChannelHandler { - pub fn new_channel(&mut self, config: &ChannelConfig) -> ChannelId { - let id = self.next_channel_id(); - - // Out-of-band negotiated means the user names the stream id - // instead of us allocating one. We record it as a request in - // and leave `sctp_stream_id` unset. - let negotiated_stream_id = config.negotiated; - if let Some(sctp_stream_id) = negotiated_stream_id { - let exists = self - .allocations - .iter() - .any(|a| a.sctp_stream_id == Some(sctp_stream_id) || a.negotiated_stream_id == Some(sctp_stream_id)); - assert!(!exists, "sctp_stream_id ({}) exists already", sctp_stream_id); - } - - let alloc = ChannelAllocation { - id, - sctp_stream_id: None, - negotiated_stream_id, - // The config is none until we confirm we definitely want this channel. - config: None, - }; - - debug!("Allocate channel id: {:?}", id); - self.allocations.push(alloc); - - id - } - - pub fn confirm(&mut self, id: ChannelId, config: ChannelConfig) { - let a = self - .allocations - .iter_mut() - .find(|a| a.id == id) - .expect("Entry for issued channel id"); - a.config = Some(config); - } - - /// For translating sctp stream id to ChannelId. Any event out of sctp goes via this. - pub fn channel_id_by_stream_id(&self, sctp_stream_id: u16) -> Option { - self.allocations - .iter() - .find(|a| a.sctp_stream_id == Some(sctp_stream_id)) - .map(|a| a.id) - } - - /// Look up sctp stream id for channel id. - pub fn stream_id_by_channel_id(&self, id: ChannelId) -> Option { - self.allocations - .iter() - .find(|a| a.id == id) - .and_then(|a| a.sctp_stream_id) - } - - pub(crate) fn handle_timeout(&mut self, _now: Instant, sctp: &mut RtcSctp, wake: &mut Wake) { - if !sctp.is_inited() || (!self.need_allocation() && !self.need_open()) { - // No allocation or open can progress, including ids held for a reset. - wake.no_events(); - wake.no_timeout(); - return; - } - - // Allocate sctp channel ids for ones that are missing. - self.do_allocations(sctp); - - // After do_allocations so we get a channel for any confirmed. - if self.need_open() { - // Opening channels drives SCTP and can affect both signals. - self.open_channels(sctp); - } else { - // Allocating ids cannot produce output, but can remove our immediate timeout. - wake.no_events(); - } - } - - /// Allocate next available `ChannelId`. - fn next_channel_id(&mut self) -> ChannelId { - let id = self.next_channel_id; - self.next_channel_id += 1; - - ChannelId(id) - } - - /// Whether a stream id is held back awaiting a reset completion. - fn is_held(&self, sctp_stream_id: u16) -> bool { - self.closed_stream_ids.contains(&sctp_stream_id) - } - - fn need_allocation(&self) -> bool { - self.allocations.iter().any(|a| { - a.sctp_stream_id.is_none() - // A negotiated id that is still held cannot be allocated yet. - && a.negotiated_stream_id.is_none_or(|want| !self.is_held(want)) - }) - } - - fn need_open(&self) -> bool { - self.allocations - .iter() - .any(|a| a.config.is_some() && a.sctp_stream_id.is_some()) - } - - // Do automatic allocations of sctp stream id. - fn do_allocations(&mut self, sctp: &RtcSctp) { - if !self.need_allocation() { - return; - } - - // RFC 8831 - // Unless otherwise defined or negotiated, the - // streams are picked based on the DTLS role (the client picks even - // stream identifiers, and the server picks odd stream identifiers). - let base = if sctp.is_client() { 0 } else { 1 }; - - let mut taken: Vec = self - .allocations - .iter() - .filter_map(|a| a.sctp_stream_id) - .chain(self.closed_stream_ids.iter().copied()) - .collect(); - - for a in &mut self.allocations { - if a.sctp_stream_id.is_some() { - continue; - } - - // Out-of-band negotiated. The user picked the id, all we do is wait until - // no closed generation of it is still awaiting its reset handshake. - if let Some(want) = a.negotiated_stream_id { - if taken.contains(&want) { - debug!("Negotiated stream id {} still held, retry later", want); - continue; - } - - debug!("Associate negotiated stream id {:?} => {}", a.id, want); - a.sctp_stream_id = Some(want); - taken.push(want); - continue; - } - - // We need to allocate. Walk this parity's ids until we find a free one. - // - // A remote peer can fill every id (sctp-proto enforces no stream-count), - // the next allocation could overflow, instead fail the allocation gracefully. - let mut proposed = base; - while taken.contains(&proposed) { - match proposed.checked_add(2) { - Some(next) => proposed = next, - None => break, // id space for this parity is exhausted - } - } - - if taken.contains(&proposed) { - // Exhausted, the loop broke on overflow, leave the channel - // unallocated, it is retried on the next timeout. - warn!("SCTP stream id space exhausted, cannot allocate {:?}", a.id); - continue; - } - - // Found the next free. - debug!("Associate stream id {:?} => {}", a.id, proposed); - a.sctp_stream_id = Some(proposed); - taken.push(proposed); - } - } - - // Actually open channels. - fn open_channels(&mut self, sctp: &mut RtcSctp) { - for a in &mut self.allocations { - // The stream id must be known before the config is taken. A negotiated - // channel waiting out a previous incarnation's reset has no id yet, and - // consuming its config here would leave nothing to open it with once the - // id is released. - let Some(sctp_stream_id) = a.sctp_stream_id else { - continue; - }; - let Some(config) = a.config.take() else { - continue; - }; - - debug!("Open stream for: {:?}", a.id); - sctp.open_stream(sctp_stream_id, config); - } - } - - pub fn poll_timeout(&self, sctp: &RtcSctp) -> Option { - if sctp.is_inited() && (self.need_allocation() || self.need_open()) { - Some(already_happened()) - } else { - None - } - } - - pub fn ensure_channel_id_for(&mut self, sctp_stream_id: u16) { - let exists = self - .allocations - .iter() - .any(|a| a.sctp_stream_id == Some(sctp_stream_id)); - - if !exists { - let id = self.next_channel_id(); - let alloc = ChannelAllocation { - id, - sctp_stream_id: Some(sctp_stream_id), - negotiated_stream_id: None, - config: None, - }; - self.allocations.push(alloc); - } - } - - // NB: Maybe this should still be &mut self or even `self` to prove singular ownership - pub fn close_channel(&self, id: ChannelId, sctp: &mut RtcSctp) { - if let Some(sctp_stream_id) = self - .allocations - .iter() - .find(|a| a.id == id) - .and_then(|s| s.sctp_stream_id) - { - sctp.close_stream(sctp_stream_id); - } - } - - /// The reset handshake for a held stream ID completed, release it for - /// reallocation immediately. - /// - /// Completions are reported per stream generation, so the same id can be held - /// more than once when resets overlap. Release a single generation, the id only - /// becomes reusable once every one of them has completed. - pub fn stream_reset_complete(&mut self, stream_id: u16) { - if let Some(pos) = self.closed_stream_ids.iter().position(|c| *c == stream_id) { - self.closed_stream_ids.remove(pos); - } - } - - /// The association is gone, so no reset can ever complete on it. - /// The held IDs belong to an association nobody will send on again. - pub fn association_lost(&mut self) { - self.closed_stream_ids.clear(); - } - - /// Remove a closed channel. - pub fn remove_channel(&mut self, id: ChannelId, reset_pending: bool) { - let stream_id = self - .allocations - .iter() - .find(|a| a.id == id) - .and_then(|a| a.sctp_stream_id); - - if let (true, Some(stream_id)) = (reset_pending, stream_id) { - self.closed_stream_ids.push(stream_id); - } - - self.allocations.retain(|a| a.id != id) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::vendor::str0m::poll::Readiness; - - #[test] - fn readiness_channel_timeout_without_work_does_not_wake() { - let now = Instant::now(); - for initialized in [false, true] { - let mut sctp = RtcSctp::new(crate::vendor::str0m::io::DATAGRAM_MTU_TARGET, 65536); - if initialized { - sctp.init(false, now, None, None).unwrap(); - } - let mut handler = ChannelHandler::default(); - let before = handler.poll_timeout(&sctp); - let mut readiness = Readiness::idle(); - handler.handle_timeout(now, &mut sctp, &mut readiness.wake()); - assert!(!readiness.wants_events()); - assert!(!readiness.wants_timeout()); - assert_eq!(handler.poll_timeout(&sctp), before); - assert!(sctp.poll().is_none()); - } - } - - #[test] - fn readiness_channel_allocation_only_moves_timeout() { - let now = Instant::now(); - let mut sctp = RtcSctp::new(crate::vendor::str0m::io::DATAGRAM_MTU_TARGET, 65536); - sctp.init(false, now, None, None).unwrap(); - let mut handler = ChannelHandler::default(); - let id = handler.new_channel(&ChannelConfig::default()); - assert!(handler.poll_timeout(&sctp).is_some()); - let mut readiness = Readiness::idle(); - handler.handle_timeout(now, &mut sctp, &mut readiness.wake()); - assert!(!readiness.wants_events()); - assert!(readiness.wants_timeout()); - assert!(handler.stream_id_by_channel_id(id).is_some()); - assert!(handler.poll_timeout(&sctp).is_none()); - assert!(sctp.poll().is_none()); - - // Confirming opens the stream and must retain both signals. - handler.confirm(id, ChannelConfig::default()); - let mut readiness = Readiness::idle(); - handler.handle_timeout(now, &mut sctp, &mut readiness.wake()); - assert!(readiness.wants_events()); - assert!(readiness.wants_timeout()); - assert!(sctp.config(handler.stream_id_by_channel_id(id).unwrap()).is_some()); - } - - #[test] - fn channel_id_allocation() { - let mut handler = ChannelHandler::default(); - - // allocate first channel, get unique id - assert_eq!(handler.new_channel(&Default::default()), ChannelId(0)); - - // allocate second channel, get unique id - assert_eq!(handler.new_channel(&Default::default()), ChannelId(1)); - - // free channel 0, allocate two more channels and verify that the - // new channels have unique IDs. - handler.remove_channel(ChannelId(0), true); - assert_eq!(handler.new_channel(&Default::default()), ChannelId(2)); - assert_eq!(handler.new_channel(&Default::default()), ChannelId(3)); - } - - #[test] - fn stream_id_held_until_reset_complete() { - let mut handler = ChannelHandler::default(); - - // Simulate two channels with known stream IDs (as if do_allocations ran - // for a client: even IDs 0, 2). - let id0 = handler.new_channel(&Default::default()); - let _id1 = handler.new_channel(&Default::default()); - // Manually set stream IDs as do_allocations would. - handler.allocations[0].sctp_stream_id = Some(0); - handler.allocations[1].sctp_stream_id = Some(2); - - // Close channel 0 (stream ID 0) with its reset outstanding. It should be held. - handler.remove_channel(id0, true); - assert_eq!(handler.closed_stream_ids, vec![0]); - - // Build the taken list as do_allocations does - stream 0 is held. - let _id2 = handler.new_channel(&Default::default()); - let taken: Vec = handler - .allocations - .iter() - .filter_map(|a| a.sctp_stream_id) - .chain(handler.closed_stream_ids.iter().copied()) - .collect(); - assert!(taken.contains(&0), "stream 0 should be held"); - assert!(taken.contains(&2), "stream 2 should be active"); - - // The completion signal is the only thing that releases it. - handler.stream_reset_complete(0); - assert!(handler.closed_stream_ids.is_empty()); - - let taken_after: Vec = handler - .allocations - .iter() - .filter_map(|a| a.sctp_stream_id) - .chain(handler.closed_stream_ids.iter().copied()) - .collect(); - assert!( - !taken_after.contains(&0), - "stream 0 should be available after reset completion" - ); - } - - #[test] - fn negotiated_stream_id_cannot_overlap_held_generation() { - let sctp = RtcSctp::new(1200, crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE); - let mut handler = ChannelHandler::default(); - let config = ChannelConfig { - negotiated: Some(4), - ..Default::default() - }; - - // The old generation was granted the id it asked for. - let old = handler.new_channel(&config); - handler.do_allocations(&sctp); - assert_eq!(handler.stream_id_by_channel_id(old), Some(4)); - - handler.remove_channel(old, true); - assert_eq!(handler.closed_stream_ids, vec![4]); - - // A replacement asking for the same id may be declared, but must stall - // without the id until the old reset completes. - let _replacement = handler.new_channel(&config); - handler.do_allocations(&sctp); - - let overlaps_held_generation = handler.allocations.iter().any(|allocation| { - handler - .closed_stream_ids - .iter() - .any(|closed| allocation.sctp_stream_id == Some(*closed)) - }); - - assert!( - !overlaps_held_generation, - "a negotiated ID must remain unavailable until its old reset completes" - ); - } - - #[test] - fn negotiated_stream_keeps_config_while_waiting_for_reset() { - let mut sctp = RtcSctp::new(1200, crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE); - let mut handler = ChannelHandler::default(); - let config = ChannelConfig { - label: "replacement".into(), - negotiated: Some(4), - ..Default::default() - }; - - handler.closed_stream_ids.push(4); - let replacement = handler.new_channel(&config); - handler.confirm(replacement, config); - - handler.do_allocations(&sctp); - handler.open_channels(&mut sctp); - - let allocation = handler - .allocations - .iter() - .find(|allocation| allocation.id == replacement) - .unwrap(); - assert!( - allocation.config.is_some(), - "a negotiated channel must retain its config while its stream id is held" - ); - - handler.stream_reset_complete(4); - handler.do_allocations(&sctp); - handler.open_channels(&mut sctp); - - assert_eq!( - sctp.config(4).map(|config| config.label.as_str()), - Some("replacement"), - "the negotiated channel must open once the old reset completes" - ); - } - - #[test] - fn negotiated_stream_waiting_for_reset_does_not_spin_timeout() { - let now = Instant::now(); - let mut sctp = RtcSctp::new(1200, crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE); - sctp.init(true, now, None, None).unwrap(); - - let mut handler = ChannelHandler::default(); - let config = ChannelConfig { - negotiated: Some(4), - ..Default::default() - }; - - handler.closed_stream_ids.push(4); - let replacement = handler.new_channel(&config); - handler.confirm(replacement, config); - let mut readiness = Readiness::idle(); - handler.handle_timeout(now, &mut sctp, &mut readiness.wake()); - assert!(!readiness.wants_events()); - assert!(!readiness.wants_timeout()); - - assert_eq!( - handler.poll_timeout(&sctp), - None, - "a channel that cannot open until network input arrives must not request an immediate timeout" - ); - } - - #[test] - fn one_reset_completion_releases_only_one_stream_generation() { - let mut handler = ChannelHandler::default(); - - // sctp-proto 0.10.3 reports reset completion per stream generation. - // Two outstanding generations of the same stream id therefore need two - // completion events before the id is reusable. - handler.closed_stream_ids.extend([4, 4]); - - handler.stream_reset_complete(4); - - assert_eq!( - handler.closed_stream_ids, - vec![4], - "the first completion must not release a newer pending generation" - ); - } - - #[test] - fn stream_id_remains_held_without_reset_completion() { - let sctp = RtcSctp::new(1200, crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE); - let mut handler = ChannelHandler::default(); - - let id = handler.new_channel(&Default::default()); - handler.allocations[0].sctp_stream_id = Some(0); - handler.remove_channel(id, true); - - // There is no timer that can release the id. - for _ in 0..100 { - handler.do_allocations(&sctp); - } - - assert_eq!( - handler.closed_stream_ids, - vec![0], - "elapsed time alone cannot make an SCTP stream ID safe to reuse" - ); - } - - #[test] - fn stream_id_not_held_when_no_reset_is_pending() { - let mut handler = ChannelHandler::default(); - - let id0 = handler.new_channel(&Default::default()); - handler.allocations[0].sctp_stream_id = Some(0); - - // The stream never made it into the association, so no reset was started and - // no completion will ever arrive. Holding the id would leak it forever. - handler.remove_channel(id0, false); - assert!(handler.closed_stream_ids.is_empty()); - } - - #[test] - fn association_lost_releases_held_stream_ids() { - let mut handler = ChannelHandler::default(); - - let id0 = handler.new_channel(&Default::default()); - handler.allocations[0].sctp_stream_id = Some(0); - handler.remove_channel(id0, true); - assert_eq!(handler.closed_stream_ids, vec![0]); - - // No reset can complete on a dead association, nothing holds the id back. - handler.association_lost(); - assert!(handler.closed_stream_ids.is_empty()); - } - - /// A remote peer decides which SCTP stream ids exist on the association, and - /// `ensure_channel_id_for()` gives every one of them an allocation. A peer that - /// opens every id of our parity therefore leaves `do_allocations()` with no free - /// id to hand out. - /// - /// The allocator walks `proposed += 2` with no upper bound. Past 65535 that is a - /// debug-build overflow panic, and in release it wraps back to `base` and spins - /// forever inside `do_allocations()`, hanging the whole event loop. - /// - /// Failing to allocate is fine, str0m retries on the next timeout. Panicking or - /// hanging is not. - #[test] - fn stream_id_space_exhausted_by_remote() { - let sctp = RtcSctp::new(1200, crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE); - let base: u16 = if sctp.is_client() { 0 } else { 1 }; - - let mut handler = ChannelHandler { - closed_stream_ids: (base..=u16::MAX).step_by(2).collect(), - ..Default::default() - }; - - // What the peer did: claim every stream id of our parity. Going through - // `ensure_channel_id_for()` for each is the realistic route but is quadratic, - // so seed the equivalent state directly. - assert_eq!(handler.closed_stream_ids.len(), 32768); - - // Now the local application asks for a data channel. - let id = handler.new_channel(&Default::default()); - - handler.do_allocations(&sctp); - - let alloc = handler - .allocations - .iter() - .find(|a| a.id == id) - .expect("the allocation entry to still be there"); - - assert!( - alloc.sctp_stream_id.is_none(), - "no id can be allocated when the peer holds the whole parity" - ); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/config.rs b/rs/moq-webrtc/src/vendor/str0m/config.rs index 8143a55f91f..e4aefdd8f7b 100644 --- a/rs/moq-webrtc/src/vendor/str0m/config.rs +++ b/rs/moq-webrtc/src/vendor/str0m/config.rs @@ -47,12 +47,9 @@ pub struct RtcConfig { pub(crate) pause_threshold: Duration, pub(crate) send_buffer_audio: usize, pub(crate) send_buffer_video: usize, - pub(crate) sctp_max_buffered_amount: usize, - pub(crate) sctp_max_message_size: u32, pub(crate) rtp_mode: bool, pub(crate) enable_raw_packets: bool, pub(crate) vp9_packetizer_mode: Vp9PacketizerMode, - pub(crate) snap_enabled: bool, pub(crate) mtu: RangeInclusive, } @@ -524,69 +521,6 @@ impl RtcConfig { self.send_buffer_video } - /// Sets how many bytes the data channels can buffer for sending, summed over all channels. - /// - /// [`Channel::write()`][crate::vendor::str0m::channel::Channel::write()] does not accept a message (returns - /// `false`) that would take the total [buffered amount][crate::vendor::str0m::channel::Channel::buffered_amount()] - /// above this limit. A message larger than the limit is never accepted. - /// - /// Written data counts as buffered until the remote peer acknowledges it, including after it - /// has been sent. The limit therefore also caps the data in flight, and with it the data - /// channel throughput at about this many bytes per round trip. The SCTP congestion window - /// and the remote peer's advertised receive window can limit the data in flight further. - /// - /// Raising the limit helps a sender whose data rate times the round trip time exceeds it. - /// Beyond what the network path holds, a higher limit only adds queueing delay, and accepted - /// data is kept in memory until it is acknowledged. - /// - /// Defaults to 128 KiB. - pub fn set_sctp_max_buffered_amount(mut self, bytes: usize) -> Self { - self.sctp_max_buffered_amount = bytes; - self - } - - /// Returns how many bytes the data channels can buffer for sending. - /// - /// ```ignore - /// # use crate::vendor::str0m::Rtc; - /// let config = Rtc::builder(); - /// - /// // Defaults to 128 KiB. - /// assert_eq!(config.sctp_max_buffered_amount(), 128 * 1024); - /// ``` - pub fn sctp_max_buffered_amount(&self) -> usize { - self.sctp_max_buffered_amount - } - - /// Sets the maximum data channel message size this peer can receive, in bytes. - /// - /// This limit is advertised in SDP as `a=max-message-size` and applied to SCTP, - /// including when using the direct API or SNAP. It does not change the remote - /// peer's receive limit or the local send buffer limit. - /// - /// The SCTP receive storage budget is at least 1 MiB and large enough to - /// reassemble one message at this limit. Storage is allocated as data arrives. - /// - /// A value of 0 advertises unlimited message size, subject to local capacity. - /// Internally, both the message limit and receive storage budget are `u32::MAX`. - /// - /// Defaults to 256 KiB. - pub fn set_sctp_max_message_size(mut self, bytes: u32) -> Self { - self.sctp_max_message_size = bytes; - self - } - - /// Returns the maximum data channel message size this peer can receive, in bytes. - /// - /// ```ignore - /// # use crate::vendor::str0m::RtcConfig; - /// let config = RtcConfig::new().set_sctp_max_message_size(512 * 1024); - /// assert_eq!(config.sctp_max_message_size(), 512 * 1024); - /// ``` - pub fn sctp_max_message_size(&self) -> u32 { - self.sctp_max_message_size - } - /// Make the entire Rtc be in RTP mode. /// /// This means all media, read from [`RtpPacket`][crate::vendor::str0m::rtp::RtpPacket] and written to @@ -622,29 +556,6 @@ impl RtcConfig { self } - /// Enable SNAP (SCTP Negotiation Acceleration Protocol). - /// - /// When enabled, the `a=sctp-init` attribute is included in outgoing SDP - /// offers, allowing the SCTP association to skip the 4-way handshake - /// and go directly to established state. This saves up to two network - /// round-trip times when establishing data channels. - /// - /// If the remote answer does not accept SNAP, str0m logs a warning and - /// falls back to the regular SCTP handshake. - /// - /// When this is `false`, outgoing SDP offers will not include `a=sctp-init`. - /// However, incoming offers that contain `a=sctp-init` will still be - /// reciprocated in answers, since str0m always supports the extension at - /// the protocol level (per §5.4 of draft-hancke-tsvwg-snap). - /// - /// See [draft-hancke-tsvwg-snap](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). - /// - /// Default: `false` - pub fn set_snap_enabled(mut self, enabled: bool) -> Self { - self.snap_enabled = enabled; - self - } - /// Set the MTU as a `target..=warn` inclusive range. /// /// * `*range.start()` is the **target** MTU: the size str0m aims for when @@ -738,12 +649,9 @@ impl Default for RtcConfig { pause_threshold: Duration::from_millis(1500), send_buffer_audio: 50, send_buffer_video: 1000, - sctp_max_buffered_amount: crate::vendor::str0m::sctp::DEFAULT_MAX_BUFFERED_AMOUNT, - sctp_max_message_size: crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE, rtp_mode: false, enable_raw_packets: false, vp9_packetizer_mode: Vp9PacketizerMode::default(), - snap_enabled: false, mtu: DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN, } } @@ -753,18 +661,6 @@ impl Default for RtcConfig { mod tests { use super::*; - #[test] - fn sctp_max_message_size_round_trips() { - assert_eq!( - RtcConfig::default().sctp_max_message_size(), - crate::vendor::str0m::sctp::LOCAL_MAX_MESSAGE_SIZE - ); - for bytes in [0, 32 * 1024, 512 * 1024, u32::MAX] { - let config = RtcConfig::new().set_sctp_max_message_size(bytes); - assert_eq!(config.clone().sctp_max_message_size(), bytes); - } - } - #[test] fn default_mtu_is_datagram_mtu_target() { let cfg = RtcConfig::default(); diff --git a/rs/moq-webrtc/src/vendor/str0m/error.rs b/rs/moq-webrtc/src/vendor/str0m/error.rs index ca40d25a51d..d3cbf8b9fc1 100644 --- a/rs/moq-webrtc/src/vendor/str0m/error.rs +++ b/rs/moq-webrtc/src/vendor/str0m/error.rs @@ -9,8 +9,6 @@ pub use crate::vendor::str0m::crypto::DtlsError; pub use crate::vendor::str0m::io::NetError; pub use crate::vendor::str0m::packet::{PacketError, Vp8DescriptorError, Vp8PatchError}; pub use crate::vendor::str0m::rtp_::RtpError; -pub use crate::vendor::str0m::sctp::ProtoError; -pub use crate::vendor::str0m::sctp::SctpError; pub use crate::vendor::str0m::sdp::SdpError; use crate::vendor::str0m::{Direction, KeyframeRequestKind, Mid, Pt, Rid}; @@ -68,9 +66,6 @@ pub enum RtcError { /// ICE agent errors. Ice(IceError), - /// SCTP (data channel engine) errors. - Sctp(SctpError), - /// [`crate::vendor::str0m::change::SdpApi`] was not done in a correct order. /// /// For [`crate::vendor::str0m::change::SdpApi`]: @@ -112,7 +107,6 @@ impl fmt::Display for RtcError { } RtcError::Net(err) => write!(f, "{}", err), RtcError::Ice(err) => write!(f, "{}", err), - RtcError::Sctp(err) => write!(f, "{}", err), RtcError::ChangesOutOfOrder => write!(f, "Changes made out of order"), RtcError::WriteWithoutPoll => write!(f, "Consecutive calls to write() without poll_output() in between"), } @@ -129,7 +123,6 @@ impl Error for RtcError { RtcError::Packet(_, _, err) => Some(err), RtcError::Net(err) => Some(err), RtcError::Ice(err) => Some(err), - RtcError::Sctp(err) => Some(err), _ => None, } } @@ -171,9 +164,3 @@ impl From for RtcError { RtcError::Ice(err) } } - -impl From for RtcError { - fn from(err: SctpError) -> Self { - RtcError::Sctp(err) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/lib.rs b/rs/moq-webrtc/src/vendor/str0m/lib.rs index b750ca9de11..f9f531a6b94 100644 --- a/rs/moq-webrtc/src/vendor/str0m/lib.rs +++ b/rs/moq-webrtc/src/vendor/str0m/lib.rs @@ -133,7 +133,6 @@ //! //! - `Rtc::handle_input` - feeding a network packet or a timeout //! - `Writer::write` / `Writer::request_keyframe` - sending media -//! - `Channel::write` - sending data channel data //! - `SdpApi::apply` / `DirectApi::*` - negotiation //! - `Rtc::add_local_candidate` / `Rtc::add_remote_candidate` //! @@ -155,7 +154,7 @@ //! packet, or the application wanting to perform a mutation (e.g. //! write media). //! 2. **Perform that ONE mutation** - feed `Input` to `handle_input`, or -//! call into a writer / channel / SDP API. +//! call into a writer / SDP API. //! 3. **Poll** `Rtc::poll_output`. //! 4. **Handle** the output: `Output::Transmit` is sent on the socket, //! `Output::Event` is dispatched to the application, `Output::Timeout` @@ -193,7 +192,7 @@ //! //! // Step 4: hand the event to the application and keep draining. //! // Events are mainly incoming media data from the remote peer, -//! // but also data channel data and statistics. +//! // but also statistics. //! Output::Event(e) => { //! if e == Event::IceConnectionStateChange(IceConnectionState::Disconnected) { //! return; @@ -372,13 +371,13 @@ //! //! Output from the `Rtc` instance can be grouped into three kinds. //! -//! 1. Events (such as receiving media or data channel data). +//! 1. Events (such as receiving media). //! 2. Network output. Data to be sent, typically from a UDP socket. //! 3. Timeouts. Indicates when the instance next expects a time input. //! //! Input to the `Rtc` instance is: //! -//! 1. User operations (such as sending media or data channel data). +//! 1. User operations (such as sending media). //! 2. Network input. Typically read from a UDP socket. //! 3. Timeouts. As obtained from the output above. //! @@ -543,7 +542,7 @@ //! | Peer Connection API | :x: | :white_check_mark: | //! | SDP | :white_check_mark: | :white_check_mark: | //! | ICE | :white_check_mark: | :white_check_mark: | -//! | Data Channels | :white_check_mark: | :white_check_mark: | +//! | Data Channels | :x: | :white_check_mark: | //! | Send/Recv Reports | :white_check_mark: | :white_check_mark: | //! | Transport Wide CC | :white_check_mark: | :white_check_mark: | //! | Bandwidth Estimation | :x: | :white_check_mark: | @@ -779,17 +778,11 @@ pub mod bwe { } } -mod sctp; -use sctp::{RtcSctp, SctpEvent, SctpInitData}; - mod sdp; pub mod format; use format::CodecConfig; -pub mod channel; -use channel::{Channel, ChannelData, ChannelHandler, ChannelId}; - pub mod media; use media::SenderFeedback; use media::{Direction, Media, Mid, Pt, Rid, Writer}; @@ -865,8 +858,6 @@ pub struct Rtc { dtls_connected: bool, dtls_buf: Vec, next_dtls_timeout: Option, - sctp: RtcSctp, - chan: ChannelHandler, session: Session, remote_fingerprint: Option, remote_addrs: Vec, @@ -933,31 +924,6 @@ pub enum Event { ///. Currently only covers a change of direction. MediaChanged(MediaChanged), - // =================== Data channel related events =================== - - /// A data channel has opened. - /// - /// The string is the channel label which is set by the opening peer and can - /// be used to identify the purpose of the channel when there are more than one. - /// - /// The negotiation is to set up an SCTP association via DTLS. Subsequent data - /// channels reuse the same association. - /// - /// Upon this event, the [`Channel`] can be obtained via [`Rtc::channel()`]. - /// - /// For [`SdpApi`]: The first ever data channel results in an SDP - /// negotiation, and this events comes at the end of that. - ChannelOpen(ChannelId, String), - - /// Incoming data channel data from the remote peer. - ChannelData(ChannelData), - - /// A data channel has been closed. - ChannelClose(ChannelId), - - /// A data channel's buffered amount has dropped below the configured threshold. - ChannelBufferedAmountLow(ChannelId), - // =================== BWE related events =================== /// A bitrate the remote peer asked for. @@ -981,7 +947,7 @@ pub enum Event { /// Incoming RTP data. RtpPacket(RtpPacket), - /// The remote DTLS connection or SCTP association has closed. + /// The remote DTLS connection has closed. /// /// When this event is emitted, `Rtc` starts local shutdown signals and /// remains alive only while [`Rtc::poll_output()`] drains pending local @@ -1057,16 +1023,6 @@ pub enum Reason { /// Includes checking candidate pairs and various cleanups. Ice, - /// The SCTP subsystem. - /// - /// Things like handling retransmissions and keep-alive checks. - Sctp, - - /// Data channels. - /// - /// Scheduled when we need to open allocations using SCTP. - Channel, - /// Regular RTP feedback. /// /// Receiver reports (RR) and sender reports (SR). @@ -1179,12 +1135,6 @@ impl Rtc { crypto provider that supports certificate generation.", ); - let mut sctp = RtcSctp::new(*mtu.start(), config.sctp_max_message_size); - if config.snap_enabled { - sctp.enable_snap(); - } - sctp.set_max_buffered_amount(config.sctp_max_buffered_amount); - Ok(Rtc { state: RtcState::Alive, ice, @@ -1200,8 +1150,6 @@ impl Rtc { dtls_buf: vec![0; 2000], next_dtls_timeout: None, session, - sctp, - chan: ChannelHandler::default(), remote_fingerprint: None, remote_addrs: vec![], send_addr: None, @@ -1227,8 +1175,7 @@ impl Rtc { /// /// During shutdown, this remains `true` until [`Rtc::poll_output()`] /// has drained pending local close output. App-facing operations such as - /// [`Rtc::writer()`] and [`Rtc::channel()`] are unavailable during that - /// closing drain. + /// [`Rtc::writer()`] is unavailable during that closing drain. /// /// ```ignore /// # use std::time::Instant; @@ -1433,23 +1380,6 @@ impl Rtc { Ok(()) } - fn try_init_sctp( - &mut self, - client: bool, - sctp_init_data: Option, - remote_max_message_size: Option, - ) -> Result<(), RtcError> { - // If we got an m=application line, ensure we have negotiated the - // SCTP association with the other side. - if self.sctp.is_inited() { - return Ok(()); - } - - self.sctp - .init(client, self.last_now, sctp_init_data, remote_max_message_size)?; - Ok(()) - } - /// Creates a new Mid that is not in the session already. pub(crate) fn new_mid(&self) -> Mid { loop { @@ -1476,21 +1406,13 @@ impl Rtc { /// /// See [`Rtc`] instance documentation for how this is expected to be used in a loop. pub fn poll_output(&mut self) -> Result { - // SCTP packets fed into DTLS require another pass. Loop here so a large - // batch does not grow the stack with one recursive call per packet. - let o = loop { - if let Some(o) = self.do_poll_output()? { - break o; - } - }; + let o = self.do_poll_output()?; match &o { Output::Event(e) => match e { - Event::ChannelData(_) - | Event::MediaData(_) + Event::MediaData(_) | Event::RtpPacket(_) | Event::SenderFeedback(_) - | Event::ChannelBufferedAmountLow(_) | Event::EgressBitrateEstimate(_) | Event::KeyframeRequest(_) => { trace!("{:?}", e) @@ -1509,15 +1431,14 @@ impl Rtc { drop(self.readiness.wake()); } - // Returns None when polling must restart after handling an SCTP packet. - fn do_poll_output(&mut self) -> Result, RtcError> { + fn do_poll_output(&mut self) -> Result { if self.state == RtcState::Closed { self.last_timeout_reason = Reason::NotHappening; - return Ok(Some(Output::Timeout(not_happening()))); + return Ok(Output::Timeout(not_happening())); } if !self.readiness.wants_events() { - return Ok(Some(Output::Timeout(self.poll_timeout()))); + return Ok(Output::Timeout(self.poll_timeout())); } while let Some(e) = self.ice.poll_event() { @@ -1526,7 +1447,7 @@ impl Rtc { // } IceAgentEvent::IceConnectionStateChange(v) => { - return Ok(Some(Output::Event(Event::IceConnectionStateChange(v)))); + return Ok(Output::Event(Event::IceConnectionStateChange(v))); } IceAgentEvent::DiscoveredRecv { proto, source } => { debug!("ICE remote address: {:?}/{:?}", Pii(source), proto); @@ -1627,8 +1548,9 @@ impl Rtc { return Err(RtcError::RemoteSdp("no a=fingerprint before dtls".into())); } } + // SCTP, which this build does not run: application m-lines are rejected. DtlsOutput::ApplicationData(data) => { - self.sctp.handle_input(self.last_now, data); + trace!("Dropping {} bytes of DTLS application data", data.len()); } DtlsOutput::Timeout(t) => { self.next_dtls_timeout = Some(t); @@ -1636,7 +1558,7 @@ impl Rtc { } DtlsOutput::CloseNotify => { self.start_close()?; - return Ok(Some(Output::Event(Event::Closed))); + return Ok(Output::Event(Event::Closed)); } other => { return Err(RtcError::Dtls(DtlsError::Io(std::io::Error::other(format!( @@ -1647,98 +1569,20 @@ impl Rtc { } if just_connected { - return Ok(Some(Output::Event(Event::Connected))); - } - - while let Some(e) = self.sctp.poll() { - match e { - SctpEvent::Transmit { mut packets } => { - if let Some(v) = packets.front() { - if let Err(e) = self.dtls.handle_input(v) { - if is_would_block(&e) { - self.sctp.push_back_transmit(packets); - break; - } else if self.state == RtcState::Closing { - debug!("Dropping SCTP transmit while closing after DTLS error: {e}"); - packets.pop_front(); - if !packets.is_empty() { - self.sctp.push_back_transmit(packets); - } - return Ok(None); - } else { - return Err(e.into()); - } - } - - packets.pop_front(); - // If there are still packets, they are sent on next - // poll_output() - if !packets.is_empty() { - self.sctp.push_back_transmit(packets); - } - - // Run again since this would feed the DTLS subsystem - // to produce a packet now. - return Ok(None); - } - } - SctpEvent::Open { id, label } => { - self.chan.ensure_channel_id_for(id); - let id = self.chan.channel_id_by_stream_id(id).unwrap(); - return Ok(Some(Output::Event(Event::ChannelOpen(id, label)))); - } - SctpEvent::Close { - id: stream_id, - reset_pending, - } => { - let Some(channel_id) = self.chan.channel_id_by_stream_id(stream_id) else { - warn!("Drop ChannelClose event for id: {:?}", stream_id); - continue; - }; - // When a reset is outstanding, remove_channel holds the stream id - // back from reallocation until the handshake completes. - self.chan.remove_channel(channel_id, reset_pending); - return Ok(Some(Output::Event(Event::ChannelClose(channel_id)))); - } - SctpEvent::StreamResetComplete { id } => { - // The reset handshake completed, the stream id can be used again. - self.chan.stream_reset_complete(id); - continue; - } - SctpEvent::AssociationLost => { - self.chan.association_lost(); - self.start_close()?; - return Ok(Some(Output::Event(Event::Closed))); - } - SctpEvent::Data { id, binary, data } => { - let Some(id) = self.chan.channel_id_by_stream_id(id) else { - warn!("Drop ChannelData event for id: {:?}", id); - continue; - }; - let cd = ChannelData { id, binary, data }; - return Ok(Some(Output::Event(Event::ChannelData(cd)))); - } - SctpEvent::BufferedAmountLow { id } => { - let Some(id) = self.chan.channel_id_by_stream_id(id) else { - warn!("Drop BufferedAmountLow for id: {:?}", id); - continue; - }; - return Ok(Some(Output::Event(Event::ChannelBufferedAmountLow(id)))); - } - } + return Ok(Output::Event(Event::Connected)); } if let Some(ev) = self.session.poll_event() { - return Ok(Some(Output::Event(ev))); + return Ok(Output::Event(ev)); } // Some polling needs to bubble up errors. if let Some(ev) = self.session.poll_event_fallible(self.last_now)? { - return Ok(Some(Output::Event(ev))); + return Ok(Output::Event(ev)); } if let Some(v) = self.ice.poll_transmit() { - return Ok(Some(Output::Transmit(v))); + return Ok(Output::Transmit(v)); } if let Some(send) = &self.send_addr { @@ -1754,7 +1598,7 @@ impl Rtc { destination: send.destination, contents, }; - return Ok(Some(Output::Transmit(t))); + return Ok(Output::Transmit(t)); } } else { // Don't allow accumulated feedback to build up indefinitely @@ -1763,7 +1607,7 @@ impl Rtc { self.readiness.clear_events(); - Ok(Some(Output::Timeout(self.poll_timeout()))) + Ok(Output::Timeout(self.poll_timeout())) } // Called only after the output pipeline has drained. @@ -1779,9 +1623,7 @@ impl Rtc { let time_and_reason = (None, Reason::NotHappening) .soonest((self.next_dtls_timeout, Reason::DTLS)) .soonest((ice_timeout, Reason::Ice)) - .soonest(self.session.poll_timeout()) - .soonest((self.sctp.poll_timeout(), Reason::Sctp)) - .soonest((self.chan.poll_timeout(&self.sctp), Reason::Channel)); + .soonest(self.session.poll_timeout()); let time = time_and_reason.0.unwrap_or_else(not_happening); self.cached_timeout = time.max(self.last_now); @@ -1919,7 +1761,7 @@ impl Rtc { /// Starts local shutdown. /// - /// The `Rtc` instance schedules RTCP BYE, requests SCTP shutdown, and sends + /// The `Rtc` instance schedules RTCP BYE and sends /// DTLS close_notify without waiting for remote replies. It enters a closing /// drain state where app-facing operations stop, but [`Rtc::poll_output()`] /// continues polling until pending local close output has drained. Once the @@ -1939,7 +1781,6 @@ impl Rtc { if self.state != RtcState::Closing { self.session.close_rtp(); - self.sctp.close()?; self.state = RtcState::Closing; } @@ -1987,8 +1828,6 @@ impl Rtc { // independently as each statement ends. let Rtc { ice, - sctp, - chan, session, readiness, .. @@ -1999,8 +1838,6 @@ impl Rtc { ice.handle_timeout(now); drop(readiness.wake()); - sctp.handle_timeout(now, &mut readiness.wake()); - chan.handle_timeout(now, sctp, &mut readiness.wake()); session.handle_timeout(now, &mut readiness.wake())?; Ok(()) @@ -2043,36 +1880,6 @@ impl Rtc { Ok(()) } - /// Obtain handle for writing to a data channel. - /// - /// This is first available when a [`ChannelId`] is advertised via [`Event::ChannelOpen`]. - /// The function returns `None` also for IDs from [`SdpApi::add_channel()`]. - /// - /// Incoming channel data is via the [`Event::ChannelData`] event. - /// - /// ```ignore - /// # use std::time::Instant; - /// # use crate::vendor::str0m::{Rtc, channel::ChannelId}; - /// let mut rtc = Rtc::new(Instant::now()); - /// - /// let cid: ChannelId = todo!(); // obtain channel id from Event::ChannelOpen - /// let channel = rtc.channel(cid).unwrap(); - /// // TODO write data channel data. - /// ``` - pub fn channel(&mut self, id: ChannelId) -> Option> { - if self.state != RtcState::Alive { - return None; - } - - let sctp_stream_id = self.chan.stream_id_by_channel_id(id)?; - - if !self.sctp.is_open(sctp_stream_id) { - return None; - } - - Some(Channel::new(sctp_stream_id, self)) - } - fn is_correct_change_id(&self, change_id: usize) -> bool { self.change_counter == change_id + 1 } @@ -2098,9 +1905,6 @@ impl PartialEq for Event { (Self::IceConnectionStateChange(l0), Self::IceConnectionStateChange(r0)) => l0 == r0, (Self::MediaAdded(m0), Self::MediaAdded(m1)) => m0 == m1, (Self::MediaData(m1), Self::MediaData(m2)) => m1 == m2, - (Self::ChannelOpen(l0, l1), Self::ChannelOpen(r0, r1)) => l0 == r0 && l1 == r1, - (Self::ChannelData(l0), Self::ChannelData(r0)) => l0 == r0, - (Self::ChannelClose(l0), Self::ChannelClose(r0)) => l0 == r0, _ => false, } } @@ -2146,7 +1950,7 @@ mod test { assert!(n < 530); } - /// A passive answerer has no DTLS or SCTP timer before the peer speaks, so a + /// A passive answerer has no DTLS timer before the peer speaks, so a /// trickled candidate must still start its checks when driven only on the /// timeouts it asks for. #[test] @@ -2156,7 +1960,7 @@ mod test { let mut offerer = Rtc::new(start); let mut change = offerer.sdp_api(); - change.add_channel("data".into()); + change.add_media(media::MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer, _pending) = change.apply().unwrap(); let mut answerer = Rtc::new(start); diff --git a/rs/moq-webrtc/src/vendor/str0m/media/mod.rs b/rs/moq-webrtc/src/vendor/str0m/media/mod.rs index 7d8818a3f75..c5d2a8b606b 100644 --- a/rs/moq-webrtc/src/vendor/str0m/media/mod.rs +++ b/rs/moq-webrtc/src/vendor/str0m/media/mod.rs @@ -141,11 +141,6 @@ pub struct Media { pub(crate) need_open_event: bool, pub(crate) need_changed_event: bool, - - /// When converting media lines to SDP, it's easier to represent the app m-line - /// as a Media. This field is true when we do that. No Session::medias will have - /// this set to true – they only exist temporarily. - pub(crate) app_tmp: bool, } #[derive(Debug)] @@ -597,7 +592,6 @@ impl Default for Media { Self { mid: Mid::new(), index: 0, - app_tmp: false, cname: Id::<20>::random().to_string(), msid: Msid::random(), kind: MediaKind::Video, @@ -661,15 +655,6 @@ impl Media { } } - pub(crate) fn from_app_tmp(mid: Mid, index: usize) -> Media { - Media { - mid, - index, - app_tmp: true, - ..Default::default() - } - } - pub(crate) fn from_direct_api(mid: Mid, index: usize, kind: MediaKind, exts: ExtensionMap) -> Media { Media { mid, diff --git a/rs/moq-webrtc/src/vendor/str0m/poll.rs b/rs/moq-webrtc/src/vendor/str0m/poll.rs index 45845902e07..273988e8f9a 100644 --- a/rs/moq-webrtc/src/vendor/str0m/poll.rs +++ b/rs/moq-webrtc/src/vendor/str0m/poll.rs @@ -18,7 +18,7 @@ //! `Rtc` holds no knowledge of which mutation affects what. //! //! The app-facing API wrappers ([`DirectApi`][crate::vendor::str0m::change::DirectApi], -//! [`SdpApi`][crate::vendor::str0m::change::SdpApi], [`Channel`][crate::vendor::str0m::channel::Channel]) +//! [`SdpApi`][crate::vendor::str0m::change::SdpApi]) //! hold an [`RtcMut`] instead of `&mut Rtc`. It arms //! the readiness on *mutable* deref only, so a `&mut self` method that mutates //! re-polls the tree while a `&self` reader never does - and neither has to diff --git a/rs/moq-webrtc/src/vendor/str0m/sctp/dcep.rs b/rs/moq-webrtc/src/vendor/str0m/sctp/dcep.rs deleted file mode 100644 index 0cc9f14d398..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sctp/dcep.rs +++ /dev/null @@ -1,122 +0,0 @@ -use std::str::from_utf8; - -use crate::vendor::sctp_proto::ReliabilityType; - -use super::SctpError as Error; - -// 0 1 2 3 -// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Message Type | Channel Type | Priority | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Reliability Parameter | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// | Label Length | Protocol Length | -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// \ / -// | Label | -// / \ -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ -// \ / -// | Protocol | -// / \ -// +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - -/// Data channel establishment protocol. -/// RFC 8832 -#[derive(Clone, Debug)] -pub struct DcepOpen { - pub unordered: bool, - pub channel_type: ReliabilityType, - pub priority: u16, - pub reliability_parameter: u32, - pub label: String, - pub protocol: String, -} - -impl TryFrom<&[u8]> for DcepOpen { - type Error = Error; - - fn try_from(buf: &[u8]) -> Result { - if buf.len() < 12 { - return Err(Error::DcepOpenTooSmall); - } - - if buf[0] != 0x03 { - return Err(Error::DcepIncorrectMessageType); - } - - let unordered = buf[1] & 0x80 > 0; - let channel_type: ReliabilityType = (buf[1] & 0x7f).into(); - let priority = u16::from_be_bytes([buf[2], buf[3]]); - let reliability_parameter = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]); - let len_label = u16::from_be_bytes([buf[8], buf[9]]) as usize; - let len_proto = u16::from_be_bytes([buf[10], buf[11]]) as usize; - - if buf.len() < 12 + len_label + len_proto { - return Err(Error::DcepOpenTooSmall); - } - - let buf = &buf[12..]; - let label = from_utf8(&buf[0..len_label]) - .map_err(|_| Error::DcepBadUtf8)? - .to_string(); - - let buf = &buf[len_label..]; - let protocol = from_utf8(&buf[0..len_proto]) - .map_err(|_| Error::DcepBadUtf8)? - .to_string(); - - Ok(DcepOpen { - unordered, - channel_type, - priority, - reliability_parameter, - label, - protocol, - }) - } -} - -impl DcepOpen { - pub fn marshal_to(&self, buf: &mut [u8]) -> usize { - buf[0] = 0x03; - buf[1] = (self.channel_type as u8) | if self.unordered { 0x80 } else { 0x00 }; - buf[2..4].copy_from_slice(&self.priority.to_be_bytes()); - buf[4..8].copy_from_slice(&self.reliability_parameter.to_be_bytes()); - let bytes_label = self.label.as_bytes(); - let bytes_proto = self.protocol.as_bytes(); - buf[8..10].copy_from_slice(&(bytes_label.len() as u16).to_be_bytes()); - buf[10..12].copy_from_slice(&(bytes_proto.len() as u16).to_be_bytes()); - let buf = &mut buf[12..]; - buf[..bytes_label.len()].copy_from_slice(bytes_label); - let buf = &mut buf[bytes_label.len()..]; - buf[..bytes_proto.len()].copy_from_slice(bytes_proto); - 12 + bytes_label.len() + bytes_proto.len() - } -} - -pub struct DcepAck; - -impl TryFrom<&[u8]> for DcepAck { - type Error = Error; - - fn try_from(buf: &[u8]) -> Result { - if buf.is_empty() { - return Err(Error::DcepOpenTooSmall); - } - - if buf[0] != 0x02 { - return Err(Error::DcepIncorrectMessageType); - } - - Ok(DcepAck) - } -} - -impl DcepAck { - pub fn marshal_to(&self, buf: &mut [u8]) -> usize { - buf[0] = 0x02; - 1 - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/sctp/error.rs b/rs/moq-webrtc/src/vendor/str0m/sctp/error.rs deleted file mode 100644 index b5683bc08ec..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sctp/error.rs +++ /dev/null @@ -1,55 +0,0 @@ -use crate::vendor::sctp_proto::Error as ProtoError; -use std::error::Error; -use std::fmt; - -/// Errors from the SCTP subsystem. -#[derive(Debug, Eq, Clone, PartialEq)] -pub enum SctpError { - /// Some protocol error as wrapped from the sctp_proto crate. - Proto(ProtoError), - - /// Stream was not ready and we tried to write. - WriteBeforeEstablished, - - /// The initial DCEP is not valid. - DcepOpenTooSmall, - - /// The initial DCEP is not the correct message type. - DcepIncorrectMessageType, - - /// The initial DCEP cant be read as utf-8. - DcepBadUtf8, - - /// Invalid SNAP token in SCTP INIT string. - InvalidSnap, -} - -impl fmt::Display for SctpError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - SctpError::Proto(err) => write!(f, "{}", err), - SctpError::WriteBeforeEstablished => { - write!(f, "Write on a stream before it was established") - } - SctpError::DcepOpenTooSmall => write!(f, "DCEP open message too small"), - SctpError::DcepIncorrectMessageType => write!(f, "DCEP incorrect message type"), - SctpError::DcepBadUtf8 => write!(f, "DCEP bad UTF-8 string"), - SctpError::InvalidSnap => write!(f, "Invalid SNAP token"), - } - } -} - -impl Error for SctpError { - fn source(&self) -> Option<&(dyn Error + 'static)> { - match self { - SctpError::Proto(err) => Some(err), - _ => None, - } - } -} - -impl From for SctpError { - fn from(err: ProtoError) -> Self { - SctpError::Proto(err) - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/sctp/mod.rs b/rs/moq-webrtc/src/vendor/str0m/sctp/mod.rs deleted file mode 100644 index 62eb286b38d..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sctp/mod.rs +++ /dev/null @@ -1,1825 +0,0 @@ -#![allow(clippy::new_without_default)] - -use std::collections::{HashSet, VecDeque}; -use std::fmt; -use std::net::SocketAddr; -use std::panic::UnwindSafe; -use std::sync::Arc; -use std::time::{Duration, Instant}; -use tracing::{debug, trace, warn}; - -use crate::vendor::sctp_proto::{Association, AssociationHandle, DatagramEvent}; -use crate::vendor::sctp_proto::{Endpoint, EndpointConfig, Stream, StreamEvent, Transmit}; -use crate::vendor::sctp_proto::{Event, Payload, PayloadProtocolIdentifier, ServerConfig}; - -use snap::{b64_encode, webrtc_transport_config}; - -use crate::vendor::str0m::poll::Wake; - -pub use crate::vendor::sctp_proto::Error as ProtoError; -use crate::vendor::sctp_proto::ReliabilityType; - -mod snap; -pub use snap::SctpInitData; - -mod dcep; -use dcep::DcepAck; -use dcep::DcepOpen; - -mod error; -pub use error::SctpError; - -/// Default bytes that can be buffered inside str0m across all streams. -/// -/// Configured by `RtcConfig::set_sctp_max_buffered_amount`. -pub(crate) const DEFAULT_MAX_BUFFERED_AMOUNT: usize = 128 * 1024; - -/// Default maximum message size we advertise in SDP (what we can receive). -pub const LOCAL_MAX_MESSAGE_SIZE: u32 = 256 * 1024; - -/// Default max message size if remote doesn't advertise -pub const DEFAULT_REMOTE_MAX_MESSAGE_SIZE: u32 = 64 * 1024; - -pub(crate) struct RtcSctp { - state: RtcSctpState, - endpoint: Endpoint, - fake_addr: SocketAddr, - handle: AssociationHandle, - assoc: Option, - // Sorted by `id` so lookups can binary search. Keep it that way. - entries: Vec, - // Stream ids that still owe a `StreamEvent::ResetComplete`, - // thos ids needs to be held back from reuse. - reset_pending: HashSet, - // Completed resets awaiting delivery to the caller. - // Used to guarantee emission ordering, ResetComplete must - // be sent after Close. - reset_complete: VecDeque, - pushed_back_transmit: Option>>, - last_now: Instant, - client: bool, - local_max_message_size: u32, - remote_max_message_size: u32, - snap_enabled: bool, - snap_init: Option, - /// Bytes that can be buffered across all streams before `available()` is 0. - max_buffered_amount: usize, - #[cfg(test)] - max_payload_size: usize, -} - -/// This is okay because there is no way for a user of Rtc to interact with the Sctp subsystem -/// in a way that would allow them to observe a potentially broken invariant when catching a panic. -impl UnwindSafe for RtcSctp {} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum RtcSctpState { - Uninited, - AwaitRemoteAssociation, - AwaitAssociationEstablished, - Established, -} - -impl RtcSctpState { - pub fn propagate_endpoint_to_assoc(&self) -> bool { - matches!( - self, - RtcSctpState::AwaitAssociationEstablished | RtcSctpState::Established - ) - } -} - -#[derive(Debug)] -struct StreamEntry { - /// Config as provided when opening the channel. This is None if we discover - /// the channel from the remote peer before getting a DcepOpen or local open_stream. - config: Option, - /// Current state - state: StreamEntryState, - /// Actual stream id. Negotiated or automatically allocated. - id: u16, - /// If we are to close this entry. - do_close: bool, - /// Deadline for retrying `open_stream` when it fails. - open_deadline: Option, - /// If the queued outgoing data drops below this threshold, Rtc is to emit an - /// event to the user. - buffered_threshold: BufferedThresholdConfig, -} - -#[derive(Debug)] -/// Tracks the `buffered_amount_low_threshold` for a stream. -/// -/// Lets us defer applying user changes to the underlying SCTP -/// stream until the next poll cycle, without first querying the current -/// configured value. -enum BufferedThresholdConfig { - /// No threshold has been set or it was cleared after an error. - Unconfigured, - /// A user-requested threshold to apply on the next poll. - Desired(usize), - /// The threshold value currently configured in the SCTP stream. - Configured(usize), -} - -impl BufferedThresholdConfig { - pub fn set(&mut self, v: usize) { - let is_change = match self { - BufferedThresholdConfig::Unconfigured => true, - BufferedThresholdConfig::Desired(w) if v != *w => true, - BufferedThresholdConfig::Configured(x) if v != *x => true, - _ => false, - }; - if is_change { - *self = BufferedThresholdConfig::Desired(v); - } - } -} - -pub(crate) enum SctpEvent { - Transmit { - packets: VecDeque>, - }, - Open { - id: u16, - label: String, - }, - Close { - id: u16, - /// Whether a reset handshake is outstanding for this stream id. - reset_pending: bool, - }, - /// The reset handshake for a closed stream completed and sctp-proto emitted - /// StreamEvent::ResetComplete. The stream id is now safe to be used again. - /// - /// Always reported after the `Close` for the same id. - StreamResetComplete { - id: u16, - }, - Data { - id: u16, - binary: bool, - data: Vec, - }, - BufferedAmountLow { - id: u16, - }, - AssociationLost, -} - -/// These are the possible paths: -/// ```text -/// local inited, in-band AwaitOpen -> AwaitDcepAck -> Open -/// local inited, out-of-band AwaitOpen -> Open -/// remote inited, in-band AwaitConfig -> (receive dcep) -> Open -/// remote inited, out-of-band AwaitConfig -> (open_stream) -> Open -/// ``` -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -enum StreamEntryState { - /// A new stream declared locally, not discovered from remote. - AwaitOpen, - /// A new stream, discovered from remote. It can either be in-band or out-of band - /// We will either receive DcepOpen in-band, or a open_stream() call out-of-band. - AwaitConfig, - /// If we have sent DcepOpen and are waiting for the ack. - AwaitDcepAck, - /// Stream is open, ready to send data. - Open, - /// If some error occurs. - Closed, -} - -/// (Low level) configuration for a data channel. -#[derive(Debug, Clone, PartialEq, Eq, Hash)] -pub struct ChannelConfig { - /// The label to use for the user to identify the channel. - pub label: String, - /// Whether channel is guaranteed ordered delivery of messages. - pub ordered: bool, - /// The reliability setting, which can allow to drop messages. - pub reliability: Reliability, - /// Whether channel is negotiated in-band (DCEP) or out-of-band. - /// None means in-band negotiated. Some(stream_id) means out-of-band. - pub negotiated: Option, - /// Protocol name. - /// - /// Defaults to "" - pub protocol: String, -} - -impl Default for ChannelConfig { - fn default() -> Self { - Self { - label: Default::default(), - ordered: true, - reliability: Default::default(), - negotiated: Default::default(), - protocol: Default::default(), - } - } -} - -/// Reliability setting of a data channel. -#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)] -pub enum Reliability { - /// Packets are delivered in order, with retransmits. - #[default] - Reliable, - /// Packets delivered out of order with a max lifetime. - MaxPacketLifetime { - /// The lifetime of a packet in milliseconds. - lifetime: u16, - }, - /// Packets delivered out of order with a max number of retransmits. - MaxRetransmits { - /// Number of retransmits before giving up. - retransmits: u16, - }, -} - -impl StreamEntry { - fn set_state(&mut self, state: StreamEntryState) -> bool { - if self.state == state { - return false; - } - debug!("Stream {:?} -> {:?}", self.state, state); - self.state = state; - true - } - - #[must_use] - fn configure_reliability(&mut self, stream: &mut Stream) -> bool { - let dcep: DcepOpen = self.config.as_ref().expect("config to be set").into(); - - let ret = stream.set_reliability_params(dcep.unordered, dcep.channel_type, dcep.reliability_parameter); - - if let Err(e) = ret { - warn!("Failed to set reliability params on stream {}: {:?}", self.id, e); - self.do_close = true; - return false; - } - - true - } -} - -/// SCTP framing per outgoing datagram: 12-byte common header + ~16-byte DATA -/// chunk header + some extra. -const SCTP_OVERHEAD: usize = 40; - -/// How long `open_stream` keeps retrying when blocked by a transient error -/// which could happen during reset handshake (RFC 6525). -/// Past this the peer is considered broken and the open gives up. -const STREAM_OPEN_TIMEOUT: Duration = Duration::from_secs(10); - -/// Backstop poll interval while an open is retrying. Retries are normally -/// driven by the network input that unblocks them, -/// either the reciprocal reset or RECONFIG-RESPONSE arriving. -/// This interval guarantees progress in case of absence of the latter messages. -const STREAM_OPEN_RETRY_INTERVAL: Duration = Duration::from_millis(500); - -/// Empirical: SCTP `max_payload_size` of 1200 has produced 1277-byte DTLS-wrapped -/// datagrams (77 bytes combined SCTP + DTLS overhead). -const _: () = assert!( - crate::vendor::str0m::io::MAX_DTLS_OVERHEAD + SCTP_OVERHEAD >= 80, - "MAX_DTLS_OVERHEAD + SCTP_OVERHEAD must cover observed 77-byte SCTP-over-DTLS overhead" -); - -impl RtcSctp { - pub fn new(mtu: usize, local_max_message_size: u32) -> Self { - let mut config = EndpointConfig::default(); - let max_payload = mtu - .saturating_sub(crate::vendor::str0m::io::MAX_DTLS_OVERHEAD) - .saturating_sub(SCTP_OVERHEAD); - config.max_payload_size(max_payload as u32); - #[cfg(test)] - let max_payload_size = max_payload; - let mut server_config = ServerConfig::default(); - server_config.transport = webrtc_transport_config(local_max_message_size); - let endpoint = Endpoint::new(Arc::new(config), Some(Arc::new(server_config))); - let fake_addr = "1.1.1.1:5000".parse().unwrap(); - - RtcSctp { - state: RtcSctpState::Uninited, - endpoint, - fake_addr, - handle: AssociationHandle(0), // temporary - assoc: None, - entries: Vec::new(), - reset_pending: HashSet::new(), - reset_complete: VecDeque::new(), - pushed_back_transmit: None, - last_now: Instant::now(), // placeholder until init() - client: false, - local_max_message_size, - remote_max_message_size: DEFAULT_REMOTE_MAX_MESSAGE_SIZE, - snap_enabled: false, - snap_init: None, - max_buffered_amount: DEFAULT_MAX_BUFFERED_AMOUNT, - #[cfg(test)] - max_payload_size, - } - } - - #[cfg(test)] - pub(crate) fn max_payload_size(&self) -> usize { - self.max_payload_size - } - - pub fn is_inited(&self) -> bool { - self.state != RtcSctpState::Uninited - } - - pub fn is_closing(&self) -> bool { - self.assoc.as_ref().is_some_and(|a| a.is_closing()) - } - - pub fn is_closed(&self) -> bool { - self.assoc.as_ref().is_none_or(|a| a.is_closed()) - } - - pub fn init( - &mut self, - client: bool, - now: Instant, - sctp_init_data: Option, - remote_max_message_size: Option, - ) -> Result<(), SctpError> { - if self.state != RtcSctpState::Uninited { - return Err(SctpError::Proto(ProtoError::Other("SCTP already initialized".into()))); - } - - self.client = client; - self.last_now = now; - - if let Some(max_msg_size) = remote_max_message_size { - self.remote_max_message_size = max_msg_size; - } - - if let Some(snap_data) = sctp_init_data { - // SNAP path: both local and remote INIT chunks must be present. - if snap_data.local_init.is_none() || snap_data.remote_init.is_none() { - return Err(SctpError::Proto(ProtoError::Other( - "SNAP requires both local and remote SCTP INIT chunks".into(), - ))); - } - - let config = snap_data.into_client_config(self.local_max_message_size); - debug!( - "New {} association (out-of-band: true)", - if client { "local" } else { "server" }, - ); - let (handle, mut assoc) = self - .endpoint - .connect(config, self.fake_addr) - .map_err(|e| SctpError::Proto(ProtoError::Other(e.to_string())))?; - assoc.set_max_send_message_size(self.remote_max_message_size); - self.handle = handle; - self.assoc = Some(assoc); - - // With SNAP, both sides exchanged INIT chunks out-of-band. The - // sctp-proto association is already in established state (via - // `with_snap`). We set our state to Established immediately - // even though DTLS may not be connected yet. This is safe - // because the `dtls_connected` guard in `do_poll_output` - // prevents any SCTP packets from flowing until the DTLS - // handshake completes. - set_state(&mut self.state, RtcSctpState::Established); - } else if client { - // Normal client path: initiate the SCTP association. - let config = SctpInitData::default().into_client_config(self.local_max_message_size); - - debug!("New local association (out-of-band: false)"); - let (handle, mut assoc) = self - .endpoint - .connect(config, self.fake_addr) - .map_err(|e| SctpError::Proto(ProtoError::Other(e.to_string())))?; - assoc.set_max_send_message_size(self.remote_max_message_size); - self.handle = handle; - self.assoc = Some(assoc); - set_state(&mut self.state, RtcSctpState::AwaitAssociationEstablished); - } else { - // Normal server path: wait for the remote to initiate. - set_state(&mut self.state, RtcSctpState::AwaitRemoteAssociation); - } - - Ok(()) - } - - pub fn is_client(&self) -> bool { - self.client - } - - pub fn local_max_message_size(&self) -> u32 { - self.local_max_message_size - } - - /// Enable SNAP by pre-populating the init data. - pub fn enable_snap(&mut self) { - self.snap_enabled = true; - self.snap_init.get_or_insert_with(SctpInitData::new); - } - - pub fn set_max_buffered_amount(&mut self, max_buffered_amount: usize) { - self.max_buffered_amount = max_buffered_amount; - } - - /// Whether local offers should opt in to SNAP. - pub fn snap_enabled(&self) -> bool { - self.snap_enabled - } - - /// Ensure the local SNAP INIT chunk is generated. Returns `false` if - /// generation failed (degrades to non-SNAP). - pub fn ensure_local_snap_init(&mut self) -> bool { - let init_data = self.snap_init.get_or_insert_with(SctpInitData::new); - if init_data.local_init_chunk().is_err() { - self.snap_init = None; - false - } else { - true - } - } - - /// Discard pending SNAP negotiation state before SCTP starts. - /// - /// This preserves local opt-in for future offers. - pub fn disable_pending_snap(&mut self) { - if !self.is_inited() { - self.snap_init = None; - } - } - - /// Get the local INIT chunk as a base64 string for SDP, if applicable. - /// - /// Returns `None` when: - /// - SNAP is not active - /// - SCTP is established without SNAP (non-SNAP association) - pub fn local_sctp_init_for_sdp(&self) -> Option { - let d = self.snap_init.as_ref()?; - if self.is_inited() && d.remote_init.is_none() { - // Established non-SNAP association - MUST NOT inject sctp-init. - return None; - } - d.local_init.as_ref().map(|b| b64_encode(b)) - } - - /// Get the cached remote INIT string, if set. - pub fn snap_remote_init_string(&self) -> Option { - self.snap_init.as_ref().and_then(|d| d.remote_init_string()) - } - - /// Whether this is an established SNAP association (has remote init). - pub fn is_snap_established(&self) -> bool { - self.is_inited() && self.snap_init.as_ref().and_then(|d| d.remote_init.as_ref()).is_some() - } - - /// Set the remote SNAP INIT from a base64 string. Returns `Ok(true)` if - /// accepted, `Ok(false)` on decode error (degrades to non-SNAP). - pub fn set_remote_snap_init_string(&mut self, value: &str) -> bool { - let init_data = self.snap_init.get_or_insert_with(SctpInitData::new); - match init_data.set_remote_init_string(value) { - Ok(()) => true, - Err(_) => { - self.disable_pending_snap(); - false - } - } - } - - /// Build a cloned `SctpInitData` for passing to `init()`, if both local - /// and remote INIT chunks are present. - pub fn build_snap_init_data(&self) -> Option { - let d = self.snap_init.as_ref()?; - if d.local_init.is_none() || d.remote_init.is_none() { - return None; - } - Some(d.clone()) - } - - /// Opens a new stream. - pub fn open_stream(&mut self, id: u16, config: ChannelConfig) { - // The channel might already have arrived via SCTP, and if it is negotiated out-of-band - // we are waiting for the configuration. - let entry = stream_entry(&mut self.entries, id, StreamEntryState::AwaitOpen, "open_stream"); - - let in_band = config.negotiated.is_none(); - - // Stream should not already have a config, we are either waiting for DcepOpen, or this is - // out-of-band configuration, in which case this call is setting the config. - if entry.config.is_some() { - warn!("Stream is already configured: {}", id); - entry.do_close = true; - return; - } else { - entry.config = Some(config); - } - - // If we are in AwaitConfig, the stream was discovered from the remote peer before - // we got to do open_stream. This means we _must_ be in the out-of-band track, - // since we shouldn't call open_stream on remotely started in-band. - if entry.state == StreamEntryState::AwaitConfig { - if in_band { - warn!("open_stream in-band negotiation for remote stream: {}", id); - entry.do_close = true; - } else { - // out-of-band where remote started. We can go to Open, but must configure the local - // stream for it first. - - // The stream can already be gone even though our entry is - // still AwaitConfig. Close the channel gracefully instead of panicking. - let Some(assoc) = self.assoc.as_mut() else { - entry.do_close = true; - return; - }; - let Ok(mut stream) = assoc.stream(entry.id) else { - entry.do_close = true; - return; - }; - - if !entry.configure_reliability(&mut stream) { - return; - } - - entry.set_state(StreamEntryState::Open); - } - } - } - - /// Close stream. - pub fn close_stream(&mut self, id: u16) { - if let Some(entry) = entry_by_id_mut(&mut self.entries, id) { - entry.do_close = true; - - // Explicitly close the sctp stream to allow re-use of the same id. - let _ = self.sctp_propagate_close(id); - } - } - - pub fn close(&mut self) -> Result<(), SctpError> { - let Some(assoc) = &mut self.assoc else { - return Ok(()); - }; - - if assoc.is_closing() || assoc.is_closed() { - return Ok(()); - } - - Ok(assoc.shutdown()?) - } - - pub fn is_open(&self, id: u16) -> bool { - if self.state != RtcSctpState::Established { - return false; - } - - let Some(rec) = entry_by_id(&self.entries, id) else { - return false; - }; - - rec.state == StreamEntryState::Open - } - - // TODO: fix sctp-proto so we don't need &mut here. - pub fn available(&mut self) -> usize { - let Some(assoc) = &mut self.assoc else { - return 0; - }; - - // The amount currently buffered. - let total: usize = self - .entries - .iter() - .filter_map(|e| assoc.stream(e.id).ok().and_then(|s| s.buffered_amount().ok())) - .sum(); - - self.max_buffered_amount.saturating_sub(total) - } - - pub fn write(&mut self, id: u16, binary: bool, buf: &[u8]) -> Result { - if self.state != RtcSctpState::Established || self.is_closing() || self.is_closed() { - return Err(SctpError::WriteBeforeEstablished); - } - - let assoc = self.assoc.as_mut().ok_or(SctpError::WriteBeforeEstablished)?; - - let rec = entry_by_id(&self.entries, id).expect("stream entry for write"); - - if rec.state != StreamEntryState::Open { - return Err(SctpError::WriteBeforeEstablished); - } - - let mut stream = assoc.stream(id)?; - - let ppi = if binary { - if buf.is_empty() { - PayloadProtocolIdentifier::BinaryEmpty - } else { - PayloadProtocolIdentifier::Binary - } - } else if buf.is_empty() { - PayloadProtocolIdentifier::StringEmpty - } else { - PayloadProtocolIdentifier::String - }; - - Ok(stream.write_with_ppi(buf, ppi)?) - } - - pub fn buffered_amount(&mut self, id: u16) -> usize { - let Some(assoc) = self.assoc.as_mut() else { - return 0; - }; - - let Ok(stream) = assoc.stream(id) else { - return 0; - }; - - stream.buffered_amount().unwrap_or(0) - } - - pub fn set_buffered_amount_low_threshold(&mut self, id: u16, threshold: usize) { - let entry = entry_by_id_mut(&mut self.entries, id).expect("stream entry for valid channel id"); - - // This update will be propagated on next poll. - entry.buffered_threshold.set(threshold); - } - - pub fn handle_input(&mut self, now: Instant, data: &[u8]) { - trace!("Handle input: {}", data.len()); - - // TODO, remove Bytes in sctp and just use &[u8]. - let data = data.to_vec().into(); - let r = self.endpoint.handle(now, self.fake_addr, None, None, data); - - let Some((handle, event)) = r else { - return; - }; - - match event { - DatagramEvent::NewAssociation(a) => { - // In slow or unreliable networks from browsers (use 3g or slow 4g) settings. - // The browser resends a new associations and str0m would override the previously - // acked association. Webrtc should use only 1 association. - if self.assoc.is_some() { - return; - } - debug!("New remote association"); - // Remote side initiated the association - self.assoc = Some(a); - self.handle = handle; - set_state(&mut self.state, RtcSctpState::AwaitAssociationEstablished); - } - DatagramEvent::AssociationEvent(event) => { - self.assoc.as_mut().expect("association for event").handle_event(event); - } - } - } - - pub fn handle_timeout(&mut self, now: Instant, wake: &mut Wake) { - if self.state == RtcSctpState::Uninited { - // Need to call `init()` before any timeouts are accepted. - wake.no_events(); - wake.no_timeout(); - return; - } - - self.last_now = now; - - // Remove closed entries. - self.entries.retain(|e| e.state != StreamEntryState::Closed); - - let Some(assoc) = &mut self.assoc else { - // No association can produce output. Keep the timer wake because - // advancing last_now can move the stream-open retry deadline. - wake.no_events(); - return; - }; - - assoc.handle_timeout(now); - - // propagate events between endpoint and association. - while let Some(e) = assoc.poll_endpoint_event() { - if let Some(ae) = self.endpoint.handle_event(self.handle, e) { - assoc.handle_event(ae); - } - } - } - - pub fn poll(&mut self) -> Option { - let r = self.do_poll(); - - if let Some(r) = &r { - trace!("Poll {:?}", r); - } - - r - } - - pub fn do_poll(&mut self) -> Option { - // Handshakes, DCEP writes, and deferred stream closes can leave more work. - // Restart until that work is drained before reporting None: the RTC caches - // an idle result. Each restart advances a handshake or opens/closes a stream; - // use a loop so draining many channels does not grow the stack. - 'restart: loop { - if self.state == RtcSctpState::Uninited { - // Need to call `init()` before any polling starts. - return None; - } - - // Remove closed entries. handle_timeout() also does this, but the - // remote can reuse a stream id (its reset handshake completed) before - // our next timeout. - self.entries.retain(|e| e.state != StreamEntryState::Closed); - - if let Some(t) = self.pushed_back_transmit.take() { - return Some(SctpEvent::Transmit { packets: t }); - } - - while let Some(t) = self.poll_transmit() { - let Some(buf) = transmit_to_vec(t) else { - continue; - }; - - return Some(SctpEvent::Transmit { packets: buf }); - } - - // Don't progress to move data between association and endpoint until we have an - // association we want to drive forward. - if !self.state.propagate_endpoint_to_assoc() { - return None; - } - - let assoc = self.assoc.as_mut()?; - - while let Some(e) = assoc.poll() { - if let Event::Connected = e { - assoc.set_max_send_message_size(self.remote_max_message_size); - set_state(&mut self.state, RtcSctpState::Established); - continue 'restart; - } - - if let Event::AssociationLost { ref reason } = e { - debug!("Association lost, reason: {}", reason); - // No reset can complete on a dead association. - self.reset_pending.clear(); - self.reset_complete.clear(); - return Some(SctpEvent::AssociationLost); - } - - if let Event::Stream(se) = e { - match se { - StreamEvent::Readable { id } | StreamEvent::Writable { id } => { - stream_entry( - &mut self.entries, - id, - StreamEntryState::AwaitConfig, - "readable/writable", - ); - } - StreamEvent::Finished { id } | StreamEvent::Stopped { id, .. } => { - // sctp-proto unregistered it when a reset arrived. - // Id reuse is signalled separately by StreamEvent::ResetComplete. - // - // sctp-proto arms that completion here, so from now on a reset - // is outstanding for the id even if we never closed it locally. - self.reset_pending.insert(id); - - // Only a live entry has anything to drop. Closed entries and - // missing ones already went through Close, and an AwaitOpen - // entry is a new incarnation waiting on the same id, it must - // not be killed by the old pending teardown. - if let Some(entry) = entry_by_id_mut(&mut self.entries, id) { - if entry.state != StreamEntryState::Closed && entry.state != StreamEntryState::AwaitOpen - { - debug!("Stream {} finished", id); - entry.do_close = true; - } - } - } - StreamEvent::ResetComplete { id } => { - // The reset handshake for this id has fully completed. - debug!("Stream {} reset complete", id); - self.reset_pending.remove(&id); - self.reset_complete.push_back(id); - } - StreamEvent::BufferedAmountLow { id } => { - return Some(SctpEvent::BufferedAmountLow { id }); - } - _ => {} - } - } - } - - // Must wait for association state to be established before opening streams. - if self.state != RtcSctpState::Established { - return None; - } - - for entry in self.entries.iter_mut() { - let want_open = entry.state == StreamEntryState::AwaitOpen; - - if want_open { - debug!("Open stream {}", entry.id); - match assoc.open_stream(entry.id, PayloadProtocolIdentifier::Unknown) { - Ok(mut s) => { - entry.open_deadline = None; - - if !entry.configure_reliability(&mut s) { - entry.set_state(StreamEntryState::Closed); - let stream_id = entry.id; - let reset_pending = self.sctp_propagate_close(stream_id); - return Some(SctpEvent::Close { - id: stream_id, - reset_pending, - }); - } - - let config = entry.config.as_ref().expect("config if AwaitOpen"); - let in_band = config.negotiated.is_none(); - - if in_band { - let dcep: DcepOpen = config.into(); - let mut buf = vec![0; 1500]; - let n = dcep.marshal_to(&mut buf); - buf.truncate(n); - - match s.write_with_ppi(&buf, PayloadProtocolIdentifier::Dcep) { - Ok(l) => { - assert!(n == l); - entry.set_state(StreamEntryState::AwaitDcepAck); - - // Start over with polling, since we might have caused - // some network traffic by writing the DcepOpen. - continue 'restart; - } - Err(e) => { - warn!("Failed to write DCEP open on stream {}: {:?}", entry.id, e); - entry.do_close = true; - entry.set_state(StreamEntryState::Closed); - let stream_id = entry.id; - let reset_pending = self.sctp_propagate_close(stream_id); - return Some(SctpEvent::Close { - id: stream_id, - reset_pending, - }); - } - } - } - - // Continuing means we are opening the stream out-of-band. - } - Err(e @ (ProtoError::ErrStreamAlreadyExist | ProtoError::ErrStreamResetPending)) => { - let config = entry.config.as_ref().expect("config if AwaitOpen"); - let in_band = config.negotiated.is_none(); - - // ErrStreamAlreadyExist has two causes: - // - the remote created it by sending on it first - // - a previous incarnation of the id is still registered, - // reset handshake hasn't finished - let stale_incarnation = matches!(e, ProtoError::ErrStreamAlreadyExist) - && assoc - .stream(entry.id) - .map(|s| !s.is_readable() && !s.is_writable()) - .unwrap_or(false); - - if in_band || stale_incarnation || matches!(e, ProtoError::ErrStreamResetPending) { - // RFC 6525 reset handshake for a previous - // incarnation of this stream id hasn't finished yet - // - // - AlreadyExist clears when the remote's reciprocal reset arrives - // - ResetPending when the RECONFIG-RESPONSE arrives (silently) - // - // In both cases, stay in AwaitOpen and retry until past the deadline. - let deadline = *entry.open_deadline.get_or_insert(self.last_now + STREAM_OPEN_TIMEOUT); - - if self.last_now < deadline { - debug!("Stream {} open blocked ({:?}), will retry", entry.id, e); - continue; - } - - debug!("Opening stream {} failed after retries: {:?}", entry.id, e); - entry.do_close = true; - entry.set_state(StreamEntryState::Closed); - let stream_id = entry.id; - let reset_pending = self.sctp_propagate_close(stream_id); - return Some(SctpEvent::Close { - id: stream_id, - reset_pending, - }); - } - - // Continuing means we are adopting the live out-of-band stream the - // remote created. It skipped the Ok branch above, so reliability - // params haven't been applied to it yet. - let mut stream = assoc.stream(entry.id).expect("stream that exists"); - if !entry.configure_reliability(&mut stream) { - entry.set_state(StreamEntryState::Closed); - let stream_id = entry.id; - let reset_pending = self.sctp_propagate_close(stream_id); - return Some(SctpEvent::Close { - id: stream_id, - reset_pending, - }); - } - } - Err(e) => { - warn!("Opening stream {} failed: {:?}", entry.id, e); - entry.do_close = true; - entry.set_state(StreamEntryState::Closed); - let stream_id = entry.id; - let reset_pending = self.sctp_propagate_close(stream_id); - return Some(SctpEvent::Close { - id: stream_id, - reset_pending, - }); - } - } - - // Consider out-of-band stream open. - let config = entry.config.as_ref().expect("config if AwaitOpen"); - let in_band = config.negotiated.is_none(); - assert!(!in_band); - - let label = config.label.clone(); - entry.set_state(StreamEntryState::Open); - - return Some(SctpEvent::Open { id: entry.id, label }); - } - - if entry.do_close && entry.state != StreamEntryState::Closed { - entry.set_state(StreamEntryState::Closed); - let stream_id = entry.id; - let reset_pending = self.sctp_propagate_close(stream_id); - return Some(SctpEvent::Close { - id: stream_id, - reset_pending, - }); - } - - let mut stream = match assoc.stream(entry.id) { - Ok(v) => v, - Err(e) => { - // This is expected on browser refresh or similar abrupt shutdown. - debug!("Getting stream {} failed: {:?}", entry.id, e); - entry.do_close = true; - continue 'restart; - } - }; - - // Propagate the desired buffered threshold. - // The idea is to only do this if the user has changed the value for it without - // incurring the cost of looking up the currently confifured value. - if let BufferedThresholdConfig::Desired(x) = entry.buffered_threshold { - if let Err(e) = stream.set_buffered_amount_low_threshold(x) { - debug!("Setting buffered_amount_low_threshold failed: {:?}", e); - entry.do_close = true; - entry.buffered_threshold = BufferedThresholdConfig::Unconfigured; - continue 'restart; - } - - entry.buffered_threshold = BufferedThresholdConfig::Configured(x); - } - match stream_read_data(&mut stream) { - Ok(Some((buf, ppi))) => { - if ppi != PayloadProtocolIdentifier::Dcep { - // This is the normal path for incoming data. - let buf = ppi_adjust_buf(buf, ppi); - let binary = matches!( - ppi, - PayloadProtocolIdentifier::Binary | PayloadProtocolIdentifier::BinaryEmpty - ); - return Some(SctpEvent::Data { - id: entry.id, - binary, - data: buf, - }); - } - - // It's Dcep, either a DcepOpen or DcepAck. - match entry.state { - // We are in AwaitConfig state which means we are either going to get it via - // the DcepOpen, or by an out-of-band configuration via open_stream. - // This indicates we are doing in-band. - StreamEntryState::AwaitConfig => { - let dcep: DcepOpen = match buf.as_slice().try_into() { - Ok(v) => v, - Err(e) => { - warn!("Failed to read incoming DCEP {}: {:?}", entry.id, e); - entry.do_close = true; - continue 'restart; - } - }; - - if entry.config.is_none() { - entry.config = Some((&dcep).into()); - } else { - warn!("Received DcepOpen for configured stream: {}", entry.id); - } - - // Apply DcepOpen's reliability parameters to the sctp-proto stream. - // Without this, the DCEP-receiving side of an in-band channel sends - // with stream defaults: ordered and fully reliable. - if !entry.configure_reliability(&mut stream) { - continue 'restart; - } - - let mut obuf = [0]; - DcepAck.marshal_to(&mut obuf); - match stream.write_with_ppi(&obuf, PayloadProtocolIdentifier::Dcep) { - Ok(l) => { - assert!(obuf.len() == l); - entry.set_state(StreamEntryState::Open); - - return Some(SctpEvent::Open { - id: entry.id, - label: dcep.label, - }); - } - Err(e) => { - warn!("Failed to write DCEP ack on stream {}: {:?}", entry.id, e); - entry.do_close = true; - entry.set_state(StreamEntryState::Closed); - let stream_id = entry.id; - let reset_pending = self.sctp_propagate_close(stream_id); - return Some(SctpEvent::Close { - id: stream_id, - reset_pending, - }); - } - } - } - StreamEntryState::AwaitDcepAck => { - let res: Result = buf.as_slice().try_into(); - - if let Err(e) = res { - warn!("Failed to read incoming DCEP ACK {}: {:?}", entry.id, e); - entry.do_close = true; - continue 'restart; - } - - entry.set_state(StreamEntryState::Open); - let config = entry.config.as_ref().expect("config when DcepAck"); - - return Some(SctpEvent::Open { - id: entry.id, - label: config.label.clone(), - }); - } - _ => { - warn!( - "Stream {} in wrong state when receiving DCEP: {:?}", - entry.id, entry.state - ); - entry.do_close = true; - continue 'restart; - } - } - } - Ok(None) => continue, - Err(_) => { - entry.do_close = true; - continue 'restart; - } - } - } - - // Reset completions are reported last. Reaching here means the entry loop had - // no `Close` left to emit, so the close for a released id has been delivered. - if let Some(id) = self.reset_complete.pop_front() { - return Some(SctpEvent::StreamResetComplete { id }); - } - - return None; - } - } - - pub fn poll_timeout(&mut self) -> Option { - let assoc_timeout = self.assoc.as_mut().and_then(|a| a.poll_timeout()); - - // Wakeup backstop for entries whose open_stream() is being retried. - // - // Normally no wakeup is needed: a blocked open re-attempts on the - // next do_poll(), and the packet that unblocks it (the peer's - // RECONFIG-RESPONSE or reset) itself triggers handle_input() and that poll. - // - // Returning a wakeup while any entry retries guarantees the open - // either resolves or fails within STREAM_OPEN_TIMEOUT. - let retry_timeout = self - .entries - .iter() - .any(|e| e.state == StreamEntryState::AwaitOpen && e.open_deadline.is_some()) - .then(|| self.last_now + STREAM_OPEN_RETRY_INTERVAL); - - match (assoc_timeout, retry_timeout) { - (Some(a), Some(r)) => Some(a.min(r)), - (a, r) => a.or(r), - } - } - - pub fn push_back_transmit(&mut self, data: VecDeque>) { - trace!("Push back transmit: {}", data.len()); - assert!(self.pushed_back_transmit.is_none()); - self.pushed_back_transmit = Some(data); - } - - fn poll_transmit(&mut self) -> Option { - if let Some(t) = self.endpoint.poll_transmit() { - return Some(t); - } - - if let Some(t) = self.assoc.as_mut()?.poll_transmit(self.last_now) { - return Some(t); - } - - None - } - - pub fn config(&self, sctp_stream_id: u16) -> Option<&ChannelConfig> { - entry_by_id(&self.entries, sctp_stream_id).and_then(|s| s.config.as_ref()) - } - - /// Close the sctp stream to allow re-use of the same id. - /// - /// Returns whether a reset handshake is outstanding for `stream_id`. - fn sctp_propagate_close(&mut self, stream_id: u16) -> bool { - let did_reset = match self.assoc.as_mut().map(|assoc| assoc.stream(stream_id)) { - // `close()` only fails on the reset, which needs an established - // association. Closing a channel while the association is shutting down - // therefore queues nothing and no completion will ever arrive. - Some(Ok(mut stream)) => stream.close().is_ok(), - // No stream to reset. - _ => false, - }; - - if did_reset { - self.reset_pending.insert(stream_id); - } - - self.reset_pending.contains(&stream_id) - } - - #[cfg(test)] - pub(crate) fn remote_max_message_size(&self) -> u32 { - self.remote_max_message_size - } -} - -fn transmit_to_vec(t: Transmit) -> Option>> { - let Payload::RawEncode(v) = t.payload else { - return None; - }; - - Some(v.into_iter().map(|b| b.to_vec()).collect()) -} - -fn set_state(current_state: &mut RtcSctpState, state: RtcSctpState) { - if *current_state != state { - debug!("{:?} => {:?}", current_state, state); - *current_state = state; - } -} - -fn entry_index(entries: &[StreamEntry], id: u16) -> Result { - entries.binary_search_by_key(&id, |e| e.id) -} - -fn entry_by_id(entries: &[StreamEntry], id: u16) -> Option<&StreamEntry> { - entry_index(entries, id).ok().map(|i| &entries[i]) -} - -fn entry_by_id_mut(entries: &mut [StreamEntry], id: u16) -> Option<&mut StreamEntry> { - entry_index(entries, id).ok().map(|i| &mut entries[i]) -} - -fn stream_entry<'a>( - entries: &'a mut Vec, - id: u16, - initial_state: StreamEntryState, - reason: &'static str, -) -> &'a mut StreamEntry { - let idx = match entry_index(entries, id) { - Ok(idx) => idx, - Err(idx) => { - debug!("New stream {} ({:?}): {}", id, initial_state, reason); - entries.insert( - idx, - StreamEntry { - config: None, - state: initial_state, - id, - do_close: false, - open_deadline: None, - buffered_threshold: BufferedThresholdConfig::Unconfigured, - }, - ); - idx - } - }; - - &mut entries[idx] -} - -fn stream_read_data(stream: &mut Stream) -> Result, PayloadProtocolIdentifier)>, SctpError> { - let Some(chunks) = stream.read()? else { - return Ok(None); - }; - - let n = chunks.len(); - let mut buf = vec![0; n]; - - let l = chunks.read(&mut buf)?; - assert!(l == n); - - use PayloadProtocolIdentifier::*; - match chunks.ppi { - Dcep | String | Binary => {} // keep as is - StringEmpty | BinaryEmpty => buf.clear(), - _ => { - return Err(SctpError::Proto(ProtoError::Other( - "Unknown PayloadProtocolIdentifier".into(), - ))); - } - } - - Ok(Some((buf, chunks.ppi))) -} - -fn ppi_adjust_buf(mut buf: Vec, ppi: PayloadProtocolIdentifier) -> Vec { - match ppi { - PayloadProtocolIdentifier::StringEmpty | PayloadProtocolIdentifier::BinaryEmpty => { - buf.clear(); - buf - } - _ => buf, - } -} - -impl fmt::Debug for SctpEvent { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match self { - Self::Transmit { packets } => f.debug_struct("Transmit").field("packets", &packets.len()).finish(), - Self::Open { id, label } => f.debug_struct("Open").field("id", id).field("label", label).finish(), - Self::Close { id, reset_pending } => f - .debug_struct("Close") - .field("id", id) - .field("reset_pending", reset_pending) - .finish(), - Self::StreamResetComplete { id } => f.debug_struct("StreamResetComplete").field("id", id).finish(), - Self::Data { id, binary, data } => f - .debug_struct("Data") - .field("id", id) - .field("binary", binary) - .field("data", &data.len()) - .finish(), - Self::BufferedAmountLow { id } => f.debug_struct("BufferedAmountLow").field("id", id).finish(), - Self::AssociationLost => f.debug_struct("AssociationLost").finish(), - } - } -} - -impl From<&ChannelConfig> for DcepOpen { - fn from(v: &ChannelConfig) -> Self { - let (channel_type, reliability_parameter) = (&v.reliability).into(); - DcepOpen { - unordered: !v.ordered, - channel_type, - reliability_parameter, - priority: 0, - label: v.label.clone(), - protocol: v.protocol.clone(), - } - } -} - -impl From<&Reliability> for (ReliabilityType, u32) { - fn from(v: &Reliability) -> Self { - match v { - Reliability::Reliable => (ReliabilityType::Reliable, 0), - Reliability::MaxPacketLifetime { lifetime } => (ReliabilityType::Timed, *lifetime as u32), - Reliability::MaxRetransmits { retransmits } => (ReliabilityType::Rexmit, *retransmits as u32), - } - } -} - -impl From<&DcepOpen> for ChannelConfig { - fn from(v: &DcepOpen) -> Self { - ChannelConfig { - label: v.label.clone(), - ordered: !v.unordered, - reliability: (v.channel_type, v.reliability_parameter).into(), - negotiated: None, - protocol: v.protocol.clone(), - } - } -} - -impl From<(ReliabilityType, u32)> for Reliability { - fn from((r, p): (ReliabilityType, u32)) -> Self { - match r { - ReliabilityType::Reliable => Reliability::Reliable, - ReliabilityType::Rexmit => Reliability::MaxRetransmits { retransmits: p as u16 }, - ReliabilityType::Timed => Reliability::MaxPacketLifetime { lifetime: p as u16 }, - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - - use crate::vendor::str0m::poll::Readiness; - - #[test] - fn readiness_uninitialized_sctp_timeout_does_not_wake() { - let now = Instant::now(); - let mut sctp = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - let mut readiness = Readiness::idle(); - sctp.handle_timeout(now, &mut readiness.wake()); - assert!(!readiness.wants_events()); - assert!(!readiness.wants_timeout()); - assert!(sctp.poll_timeout().is_none()); - assert!(sctp.poll().is_none()); - } - - #[test] - fn readiness_passive_sctp_timeout_does_not_wake_events() { - let now = Instant::now(); - let mut sctp = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - sctp.init(false, now, None, None).unwrap(); - assert!(sctp.assoc.is_none()); - let mut readiness = Readiness::idle(); - sctp.handle_timeout(now, &mut readiness.wake()); - assert!(!readiness.wants_events()); - assert!(readiness.wants_timeout()); - assert!(sctp.poll().is_none()); - } - - #[test] - fn readiness_sctp_retransmission_keeps_both_signals() { - let now = Instant::now(); - let mut sctp = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - sctp.init(true, now, None, None).unwrap(); - while sctp.poll().is_some() {} - let deadline = sctp.poll_timeout().unwrap(); - let mut readiness = Readiness::idle(); - sctp.handle_timeout(deadline, &mut readiness.wake()); - assert!(readiness.wants_events()); - assert!(readiness.wants_timeout()); - assert!(matches!(sctp.poll(), Some(SctpEvent::Transmit { .. }))); - assert!(sctp.poll_timeout().unwrap() > deadline); - } - - /// Insert an entry directly, keeping `entries` sorted by id. - fn insert_entry(entries: &mut Vec, entry: StreamEntry) { - let idx = entry_index(entries, entry.id).expect_err("entry should not already exist"); - entries.insert(idx, entry); - } - use crate::vendor::str0m_proto::DATAGRAM_MTU_TARGET; - - #[test] - fn partial_snap_init_requires_both_chunks() { - let now = Instant::now(); - let mut sctp = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - let mut init_data = SctpInitData::new(); - - init_data.local_init_chunk().unwrap(); - - let err = sctp.init(true, now, Some(init_data), None).unwrap_err(); - assert!( - err.to_string() - .contains("SNAP requires both local and remote SCTP INIT chunks") - ); - } - - #[test] - fn malformed_remote_snap_does_not_disable_local_opt_in() { - let mut sctp = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - sctp.enable_snap(); - - assert!(!sctp.set_remote_snap_init_string("!!!not-valid-base64!!!")); - assert!(sctp.snap_enabled()); - assert!(sctp.ensure_local_snap_init()); - assert!(sctp.local_sctp_init_for_sdp().is_some()); - } - - /// Helper to connect a client and server RtcSctp pair to Established state. - fn connect_client_server() -> (RtcSctp, RtcSctp) { - let now = Instant::now(); - let mut client = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - let mut server = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - - client.init(true, now, None, None).unwrap(); - server.init(false, now, None, None).unwrap(); - - // Exchange packets until both are Established. - for _ in 0..20 { - // Drain client transmits -> feed to server - while let Some(t) = client.poll_transmit() { - if let Some(bufs) = transmit_to_vec(t) { - for buf in bufs { - server.handle_input(now, &buf); - } - } - } - // Process server events - while let Some(e) = server.do_poll() { - if let SctpEvent::Transmit { packets } = e { - for buf in packets { - client.handle_input(now, &buf); - } - } - } - - // Drain server transmits -> feed to client - while let Some(t) = server.poll_transmit() { - if let Some(bufs) = transmit_to_vec(t) { - for buf in bufs { - client.handle_input(now, &buf); - } - } - } - // Process client events - while let Some(e) = client.do_poll() { - if let SctpEvent::Transmit { packets } = e { - for buf in packets { - server.handle_input(now, &buf); - } - } - } - - // Check if both established - if client.state == RtcSctpState::Established && server.state == RtcSctpState::Established { - break; - } - } - - assert_eq!(client.state, RtcSctpState::Established); - assert_eq!(server.state, RtcSctpState::Established); - - (client, server) - } - - fn assert_close_before_idle(sctp: &mut RtcSctp, id: u16) { - for _ in 0..100 { - match sctp.poll() { - Some(SctpEvent::Close { - id: closed, - reset_pending, - }) => { - assert_eq!(closed, id); - assert!(reset_pending, "the malformed stream must start a reset"); - return; - } - Some(_) => {} - None => panic!("SCTP reported idle before draining the deferred close"), - } - } - panic!("SCTP did not finish draining"); - } - - fn transfer_transmits(from: &mut RtcSctp, to: &mut RtcSctp) { - while let Some(t) = from.poll_transmit() { - if let Some(packets) = transmit_to_vec(t) { - for packet in packets { - to.handle_input(to.last_now, &packet); - } - } - } - } - - #[test] - fn malformed_dcep_open_closes_before_idle() { - let (mut client, mut server) = connect_client_server(); - // Send an actual SCTP DATA chunk with an invalid DCEP OPEN body. - client - .assoc - .as_mut() - .unwrap() - .open_stream(0, PayloadProtocolIdentifier::Dcep) - .unwrap() - .write_with_ppi(&[0xff], PayloadProtocolIdentifier::Dcep) - .unwrap(); - transfer_transmits(&mut client, &mut server); - assert_close_before_idle(&mut server, 0); - } - - #[test] - fn unexpected_dcep_on_open_stream_closes_before_idle() { - let (mut client, mut server) = connect_client_server(); - let config = ChannelConfig { - negotiated: Some(0), - ..Default::default() - }; - client.open_stream(0, config.clone()); - server.open_stream(0, config); - assert!(matches!(client.poll(), Some(SctpEvent::Open { id: 0, .. }))); - assert!(matches!(server.poll(), Some(SctpEvent::Open { id: 0, .. }))); - client - .assoc - .as_mut() - .unwrap() - .stream(0) - .unwrap() - .write_with_ppi(&[2], PayloadProtocolIdentifier::Dcep) - .unwrap(); - transfer_transmits(&mut client, &mut server); - assert_close_before_idle(&mut server, 0); - } - - #[test] - fn malformed_dcep_ack_closes_before_idle() { - let (mut client, mut server) = connect_client_server(); - client.open_stream(0, ChannelConfig::default()); - while let Some(event) = client.poll() { - if let SctpEvent::Transmit { packets } = event { - for packet in packets { - server.handle_input(server.last_now, &packet); - } - } - } - assert_eq!( - entry_by_id_mut(&mut client.entries, 0).unwrap().state, - StreamEntryState::AwaitDcepAck - ); - // Bypass the server's DCEP handler to return a malformed ACK over SCTP. - server - .assoc - .as_mut() - .unwrap() - .stream(0) - .unwrap() - .write_with_ppi(&[0xff], PayloadProtocolIdentifier::Dcep) - .unwrap(); - transfer_transmits(&mut server, &mut client); - assert_close_before_idle(&mut client, 0); - } - - /// A stream the remote opened can be gone from the association by the time the - /// application configures it. - /// - /// `StreamEntryState::AwaitConfig` is set when a `Readable`/`Writable` event - /// arrives - /// for an id we have no config for. If the peer then resets that stream, sctp-proto - /// unregisters it during `handle_input()`, while our entry stays `AwaitConfig` until - /// the reset event is drained in a later `do_poll()`. - #[test] - fn open_stream_out_of_band_after_remote_reset() { - let (mut client, _server) = connect_client_server(); - - let stream_id: u16 = 3; - assert!( - client.assoc.as_mut().unwrap().stream(stream_id).is_err(), - "the association must not have this stream for the test to mean anything" - ); - - insert_entry( - &mut client.entries, - StreamEntry { - config: None, - state: StreamEntryState::AwaitConfig, - id: stream_id, - do_close: false, - open_deadline: None, - buffered_threshold: BufferedThresholdConfig::Unconfigured, - }, - ); - - client.open_stream( - stream_id, - ChannelConfig { - label: "negotiated".to_string(), - ordered: true, - reliability: Reliability::Reliable, - negotiated: Some(stream_id), - protocol: String::new(), - }, - ); - - let entry = client - .entries - .iter() - .find(|e| e.id == stream_id) - .expect("entry to still exist"); - - assert!( - entry.do_close, - "a stream that vanished from the association should be marked for close" - ); - assert_ne!( - entry.state, - StreamEntryState::Open, - "must not go Open when there is no underlying stream" - ); - } - - /// Regression test: when `assoc.open_stream()` returns `ErrStreamAlreadyExist` - /// for an in-band (DCEP) data channel, the entry must eventually transition to - /// Closed and emit `SctpEvent::Close`. The error is transient (a reset - /// handshake could clear it), so the entry retries first - but bounded by - /// `STREAM_OPEN_TIMEOUT`, not the infinite loop this once was. - #[test] - fn err_stream_already_exist_in_band_returns_close() { - let (mut client, _server) = connect_client_server(); - - let stream_id: u16 = 0; - - // Pre-create the stream in the association so the next open_stream() with the - // same ID will return ErrStreamAlreadyExist. - let assoc = client.assoc.as_mut().unwrap(); - assoc - .open_stream(stream_id, PayloadProtocolIdentifier::Unknown) - .expect("first open_stream should succeed"); - - // Manually add an entry in AwaitOpen state with in-band config (negotiated: None). - // This simulates a locally-initiated in-band channel whose stream ID conflicts - // with one already opened by the remote peer. - insert_entry( - &mut client.entries, - StreamEntry { - config: Some(ChannelConfig { - label: "test".to_string(), - ordered: true, - reliability: Reliability::Reliable, - negotiated: None, // in-band - protocol: String::new(), - }), - state: StreamEntryState::AwaitOpen, - id: stream_id, - do_close: false, - open_deadline: None, - buffered_threshold: BufferedThresholdConfig::Unconfigured, - }, - ); - - // The first poll retries instead of failing (arms the deadline). - let event = client.do_poll(); - assert!( - event.is_none(), - "expected retry (no event) for stream {stream_id}, got {event:?}" - ); - - // Past the deadline the open gives up and closes. - let later = Instant::now() + STREAM_OPEN_TIMEOUT + Duration::from_secs(1); - let mut readiness = crate::vendor::str0m::poll::Readiness::armed(); - client.handle_timeout(later, &mut readiness.wake()); - let event = client.do_poll(); - - assert!( - matches!(&event, Some(SctpEvent::Close { id, .. }) if *id == stream_id), - "expected SctpEvent::Close for stream {stream_id}, got {event:?}" - ); - - // Verify entry transitioned to Closed. - let entry = entry_by_id(&client.entries, stream_id).unwrap(); - assert_eq!(entry.state, StreamEntryState::Closed); - } - - #[test] - fn negotiated_reuse_does_not_report_open_for_old_closed_stream() { - let (mut client, _server) = connect_client_server(); - let stream_id = 0; - - let assoc = client.assoc.as_mut().unwrap(); - let mut old = assoc - .open_stream(stream_id, PayloadProtocolIdentifier::Unknown) - .expect("old stream should open"); - old.close().expect("old stream should start closing"); - - insert_entry( - &mut client.entries, - StreamEntry { - config: Some(ChannelConfig { - label: "replacement".to_string(), - ordered: true, - reliability: Reliability::Reliable, - negotiated: Some(stream_id), - protocol: String::new(), - }), - state: StreamEntryState::AwaitOpen, - id: stream_id, - do_close: false, - open_deadline: None, - buffered_threshold: BufferedThresholdConfig::Unconfigured, - }, - ); - - for _ in 0..10 { - match client.do_poll() { - Some(SctpEvent::Open { id, .. }) if id == stream_id => { - panic!("replacement was reported open while the old stream still exists") - } - Some(_) => {} - None => break, - } - } - } - - #[test] - fn close_is_reported_before_reset_complete_when_events_are_batched() { - let now = Instant::now(); - let (mut client, mut server) = connect_client_server(); - let stream_id = 0; - let config = ChannelConfig { - label: "batched-close".to_string(), - negotiated: Some(stream_id), - ..Default::default() - }; - - client.open_stream(stream_id, config.clone()); - server.open_stream(stream_id, config); - assert!(matches!( - client.do_poll(), - Some(SctpEvent::Open { id, .. }) if id == stream_id - )); - assert!(matches!( - server.do_poll(), - Some(SctpEvent::Open { id, .. }) if id == stream_id - )); - - client.close_stream(stream_id); - - // Move all reset packets in both directions without polling client - // application events. This batches Finished and ResetComplete in the - // association event queue, which is valid for a sans-I/O caller. - for _ in 0..4 { - while let Some(transmit) = client.poll_transmit() { - for packet in transmit_to_vec(transmit).unwrap() { - server.handle_input(now, &packet); - } - } - while let Some(transmit) = server.poll_transmit() { - for packet in transmit_to_vec(transmit).unwrap() { - client.handle_input(now, &packet); - } - } - } - - for _ in 0..10 { - match client.do_poll() { - Some(SctpEvent::Close { id, .. }) if id == stream_id => return, - Some(SctpEvent::StreamResetComplete { id }) if id == stream_id => { - panic!("ResetComplete was reported before Close") - } - Some(_) => {} - None => break, - } - } - - panic!("stream close was not reported"); - } - - /// Regression test: the DCEP-receiving side of an in-band channel must apply - /// the DcepOpen reliability parameters (here: unordered) to its sctp-proto - /// stream, instead of sending with stream defaults (ordered, fully reliable). - #[test] - fn dcep_receiver_applies_reliability_params() { - let now = Instant::now(); - let (mut client, mut server) = connect_client_server(); - - // Drain `from`, feeding packets to `to` and returning the raw bytes. - let pump = |from: &mut RtcSctp, to: &mut RtcSctp| { - let mut wire = vec![]; - while let Some(e) = from.do_poll() { - if let SctpEvent::Transmit { packets } = e { - for p in packets { - to.handle_input(now, &p); - wire.extend(p); - } - } - } - wire - }; - - // Client opens an unordered in-band (DCEP) channel; once the handshake is - // pumped through, the server (DCEP receiver) sends data back. - client.open_stream( - 0, - ChannelConfig { - ordered: false, - ..Default::default() - }, - ); - pump(&mut client, &mut server); // DcepOpen - pump(&mut server, &mut client); // DcepAck, server side now open - let payload = b"from dcep receiver"; - server.write(0, true, payload).unwrap(); - - // The 16-byte DATA chunk header puts the flags byte 15 bytes before the - // payload it carries. 0x04 is the U (unordered) flag. - let wire = pump(&mut server, &mut client); - let pos = wire.windows(payload.len()).position(|w| w == payload).unwrap(); - assert!(wire[pos - 15] & 0x04 != 0, "DCEP receiver should send unordered"); - } - - #[test] - fn max_payload_size_matches_mtu_minus_overhead() { - let overhead = crate::vendor::str0m::io::MAX_DTLS_OVERHEAD + SCTP_OVERHEAD; - - let default_sctp = RtcSctp::new(DATAGRAM_MTU_TARGET, LOCAL_MAX_MESSAGE_SIZE); - assert_eq!(default_sctp.max_payload_size(), DATAGRAM_MTU_TARGET - overhead); - - let small_sctp = RtcSctp::new(900, LOCAL_MAX_MESSAGE_SIZE); - assert_eq!(small_sctp.max_payload_size(), 900 - overhead); - } -} diff --git a/rs/moq-webrtc/src/vendor/str0m/sctp/snap.rs b/rs/moq-webrtc/src/vendor/str0m/sctp/snap.rs deleted file mode 100644 index 52dc6305983..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/sctp/snap.rs +++ /dev/null @@ -1,177 +0,0 @@ -//! SNAP (SCTP Negotiation Acceleration Protocol) types. -//! -//! See [draft-hancke-tsvwg-snap](https://datatracker.ietf.org/doc/draft-hancke-tsvwg-snap/). - -use std::sync::Arc; - -use crate::vendor::sctp_proto::{ClientConfig, TransportConfig, generate_snap_token}; -use base64ct::{Base64, Encoding}; - -use super::{LOCAL_MAX_MESSAGE_SIZE, SctpError as Error}; - -/// Build the WebRTC transport config with unlimited retransmits. -/// -/// For WebRTC, we never want to give up retransmitting init and data packets. -/// The connectivity is in ICE, and SCTP should not give up until ICE gives up. -pub(super) fn webrtc_transport_config(local_max_message_size: u32) -> Arc { - let max_receive_message_size = if local_max_message_size == 0 { - u32::MAX - } else { - local_max_message_size - }; - // SCTP delivers whole messages, so reassembly needs room for one message. - // Retain the default 1 MiB receive budget unless the message limit is larger. - let max_receive_buffer_size = max_receive_message_size.max(1024 * 1024); - Arc::new( - TransportConfig::default() - .with_max_init_retransmits(None) - .with_max_data_retransmits(None) - .with_max_receive_buffer_size(max_receive_buffer_size) - .with_max_receive_message_size(max_receive_message_size), - ) -} - -/// Out-of-band SCTP INIT data for SNAP negotiation. -/// -/// Holds the local and remote SCTP INIT chunks exchanged via signaling -/// (e.g. SDP `a=sctp-init`). When both are present, the SCTP association -/// skips the 4-way handshake and goes directly to established state. -/// -/// Typical flow: -/// -/// 1. Create `SctpInitData`. -/// 2. Call [`Self::local_init_chunk()`] and signal the returned bytes. -/// 3. Receive the peer's INIT bytes over signaling. -/// 4. Call [`Self::set_remote_init_chunk()`]. -/// 5. Pass the populated value to -/// [`DirectApi::start_sctp_with_snap()`][crate::vendor::str0m::change::DirectApi::start_sctp_with_snap]. -/// -/// The local INIT chunk is lazily generated and cached on first access. -/// -/// # Example -/// ```ignore -/// use crate::vendor::str0m::channel::SctpInitData; -/// -/// let mut data = SctpInitData::new(); -/// -/// // Get local INIT chunk to send to remote peer -/// let local_init = data.local_init_chunk().expect("valid chunk"); -/// -/// // Later, set the remote INIT chunk received from peer -/// // data.set_remote_init_chunk(remote_init_bytes); -/// ``` -#[derive(Debug, Clone)] -pub struct SctpInitData { - pub(crate) transport: Arc, - pub(crate) local_init: Option>, - pub(crate) remote_init: Option>, -} - -impl Default for SctpInitData { - fn default() -> Self { - SctpInitData { - transport: webrtc_transport_config(LOCAL_MAX_MESSAGE_SIZE), - local_init: None, - remote_init: None, - } - } -} - -impl SctpInitData { - /// Creates new default SCTP INIT data. - /// - /// By default, max init and data retransmits are set to `None` (unlimited), - /// which is recommended for WebRTC where connectivity is managed by ICE. - pub fn new() -> Self { - Self::default() - } - - /// Get the local INIT chunk bytes for out-of-band signaling. - /// - /// This generates a fresh INIT chunk using the transport config parameters. - /// The result can be exchanged with the remote peer via a signaling channel, - /// allowing both sides to skip the SCTP 4-way handshake. - /// - /// The generated bytes are cached so subsequent calls return the same INIT. - /// - /// If you plan to call `start_sctp_with_snap()`, call this method first so - /// the local INIT is captured in the `SctpInitData` you pass in. - pub fn local_init_chunk(&mut self) -> Result, Error> { - if let Some(init) = &self.local_init { - return Ok(init.clone()); - } - let init = generate_snap_token(&self.transport)?.to_vec(); - self.local_init = Some(init.clone()); - Ok(init) - } - - /// Get the local INIT chunk as a base64-encoded string for out-of-band signaling. - /// - /// This generates a fresh INIT chunk using the transport config parameters. - /// The result can be exchanged with the remote peer via a signaling channel, - /// allowing both sides to skip the SCTP 4-way handshake. - /// - /// The generated bytes are cached so subsequent calls return the same string. - /// - /// If you plan to call `start_sctp_with_snap()`, call this method first so - /// the local INIT is captured in the `SctpInitData` you pass in. - pub fn local_init_string(&mut self) -> Result { - self.local_init_chunk().map(|c| b64_encode(&c)) - } - - /// Check if remote INIT chunk has been configured for out-of-band signaling. - pub fn has_remote_init_chunk(&self) -> bool { - self.remote_init.is_some() - } - - /// Get the remote INIT chunk as a base64-encoded string, if set. - pub fn remote_init_string(&self) -> Option { - self.remote_init.as_ref().map(|b| b64_encode(b)) - } - - /// Set the remote INIT chunk for out-of-band signaling. - /// - /// When both local and remote INIT chunks are exchanged via a signaling - /// channel, the SCTP association can skip the 4-way handshake and go - /// directly to established state. - /// - /// This must be called before starting SCTP with SNAP. - pub fn set_remote_init_chunk(&mut self, value: Vec) { - self.remote_init = Some(value); - } - - /// Set the remote INIT chunk from a base64-encoded string. - /// - /// Convenience method for signaling channels that exchange strings (e.g. SDP). - pub fn set_remote_init_string(&mut self, value: &str) -> Result<(), Error> { - let mut buf = vec![0u8; value.len()]; - let len = Base64::decode(value, &mut buf).map_err(|_| Error::InvalidSnap)?.len(); - buf.truncate(len); - self.set_remote_init_chunk(buf); - Ok(()) - } - - /// Build a `ClientConfig` from this data, consuming it. - /// - /// Only used internally by [`super::RtcSctp::init()`] to feed sctp-proto. - pub(crate) fn into_client_config(self, local_max_message_size: u32) -> ClientConfig { - let mut config = ClientConfig::new(); - config.transport = webrtc_transport_config(local_max_message_size); - match (self.local_init, self.remote_init) { - (Some(local), Some(remote)) => { - config = config.with_snap(local.into(), remote.into()); - } - (Some(_), None) | (None, Some(_)) => { - unreachable!("SNAP requires both local and remote INIT chunks"); - } - (None, None) => {} - } - config - } -} - -pub(super) fn b64_encode(data: &[u8]) -> String { - let mut buf = vec![0u8; Base64::encoded_len(data)]; - let encoded = Base64::encode(data, &mut buf).expect("buffer sized correctly"); - encoded.to_string() -} diff --git a/rs/moq-webrtc/src/vendor/str0m/sdp/data.rs b/rs/moq-webrtc/src/vendor/str0m/sdp/data.rs index c19eb1c40d5..37cda0411c3 100644 --- a/rs/moq-webrtc/src/vendor/str0m/sdp/data.rs +++ b/rs/moq-webrtc/src/vendor/str0m/sdp/data.rs @@ -85,16 +85,6 @@ impl Sdp { candidates.into_iter() } - /// Get the `a=sctp-init` value from the application m-line, if present. - /// - /// Returns the base64-encoded SCTP INIT value. - pub(crate) fn sctp_init(&self) -> Option<&str> { - self.media_lines - .iter() - .find(|m| m.typ.is_channel()) - .and_then(|m| m.sctp_init()) - } - pub(crate) fn setup(&self) -> Option { self.session .setup() @@ -299,19 +289,6 @@ impl MediaLine { .expect("missing a=mid") } - /// Get the sctp-init attribute value (base64-encoded string). - /// - /// Returns `None` if no `a=sctp-init` attribute is present. - pub fn sctp_init(&self) -> Option<&str> { - self.attrs.iter().find_map(|a| { - if let MediaAttribute::SctpInit(v) = a { - Some(v.as_str()) - } else { - None - } - }) - } - pub fn msid(&self) -> Option { self.attrs.iter().find_map(|a| { if let MediaAttribute::Msid(m) = a { @@ -697,17 +674,6 @@ impl MediaLine { v } - - /// Get the max-message-size attribute value, if present - pub fn max_message_size(&self) -> Option { - self.attrs.iter().find_map(|a| { - if let MediaAttribute::MaxMessageSize(size) = a { - Some(*size) - } else { - None - } - }) - } } #[derive(Debug, Clone, PartialEq, Eq)] diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/api-errors.rs b/rs/moq-webrtc/src/vendor/str0m/tests/api-errors.rs index 62310bee216..d2c26dd038f 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/api-errors.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/api-errors.rs @@ -23,7 +23,7 @@ fn api_disconnect_and_is_alive() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -180,7 +180,7 @@ fn api_ice_state_change_events() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -226,7 +226,7 @@ fn api_connected_event() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/common.rs b/rs/moq-webrtc/src/vendor/str0m/tests/common.rs index 4792b30791a..291319b5271 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/common.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/common.rs @@ -498,9 +498,6 @@ pub fn connect_l_r_with_rtc(rtc1: Rtc, rtc2: Rtc) -> (TestRtc, TestRtc) { l.direct_api().start_dtls(true).unwrap(); r.direct_api().start_dtls(false).unwrap(); - l.direct_api().start_sctp(true); - r.direct_api().start_sctp(false); - loop { if l.is_connected() || r.is_connected() { break; @@ -537,70 +534,6 @@ pub fn h265_data() -> PcapData { load_pcap_data(include_bytes!("data/h265.pcap")) } -// --------------------------------------------------------------------------- -// SNAP (SCTP Negotiation Acceleration Protocol) test helpers -// --------------------------------------------------------------------------- - -/// Extract the `a=sctp-init:` from an SDP string, if present. -pub fn extract_sctp_init(sdp: &str) -> Option { - sdp.lines() - .find(|l| l.starts_with("a=sctp-init:")) - .map(|l| l.trim_start_matches("a=sctp-init:").to_string()) -} - -/// Replace the `a=sctp-init:` attribute value in an SDP string. -/// -/// Preserves original line endings (`\r\n`). -pub fn replace_sctp_init(sdp: &str, replacement: &str) -> String { - let mut result = String::with_capacity(sdp.len()); - // split("\r\n") produces an extra empty element after a trailing CRLF; - // skip it to avoid appending a spurious double-CRLF at the end. - for line in sdp.split("\r\n") { - if line.is_empty() && result.ends_with("\r\n") { - continue; - } - if line.starts_with("a=sctp-init:") { - result.push_str(&format!("a=sctp-init:{replacement}\r\n")); - } else { - result.push_str(line); - result.push_str("\r\n"); - } - } - result -} - -/// Remove the `a=sctp-init:` attribute from an SDP string. -/// -/// Preserves original line endings (`\r\n`). -pub fn remove_sctp_init(sdp: &str) -> String { - let mut result = String::with_capacity(sdp.len()); - // split("\r\n") produces an extra empty element after a trailing CRLF; - // skip it to avoid appending a spurious double-CRLF at the end. - for line in sdp.split("\r\n") { - if line.is_empty() && result.ends_with("\r\n") { - continue; - } - if !line.starts_with("a=sctp-init:") { - result.push_str(line); - result.push_str("\r\n"); - } - } - result -} - -/// Generate SNAP init data for out-of-band SCTP negotiation. -/// -/// Returns `Some((local_init_bytes, SctpInitData))` when `use_snap` is true, `None` otherwise. -pub fn snap_init_data(use_snap: bool) -> Option<(Vec, crate::vendor::str0m::channel::SctpInitData)> { - if use_snap { - let mut data = crate::vendor::str0m::channel::SctpInitData::new(); - let local_init = data.local_init_chunk().expect("generate_snap_token should not fail"); - Some((local_init, data)) - } else { - None - } -} - pub fn load_pcap_data(data: &[u8]) -> PcapData { let reader = Cursor::new(data); let mut r = PcapReader::new(reader).expect("pcap reader"); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/config-validation.rs b/rs/moq-webrtc/src/vendor/str0m/tests/config-validation.rs index ec63281db70..92cf60fdfd3 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/config-validation.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/config-validation.rs @@ -249,9 +249,6 @@ fn config_fingerprint_verification_disabled() -> Result<(), RtcError> { l.direct_api().start_dtls(true).unwrap(); r.direct_api().start_dtls(false).unwrap(); - l.direct_api().start_sctp(true); - r.direct_api().start_sctp(false); - // Connection should succeed despite corrupted fingerprints loop { if l.is_connected() && r.is_connected() { @@ -293,7 +290,7 @@ fn config_clone_multiple_instances() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data-channel-direct.rs b/rs/moq-webrtc/src/vendor/str0m/tests/data-channel-direct.rs deleted file mode 100644 index b64decaea83..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/data-channel-direct.rs +++ /dev/null @@ -1,123 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::channel::ChannelConfig; -use crate::vendor::str0m::{Candidate, Event, RtcConfig, RtcError}; -use tracing::info_span; - -use super::common; -use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; - -#[test] -pub fn data_channel_direct() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - - let rtc_r = RtcConfig::new().set_ice_lite(true).build(Instant::now()); - let mut r = TestRtc::new_with_rtc(info_span!("R"), rtc_r); - - let host1 = Candidate::host((Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp")?; - let host2 = Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp")?; - l.add_local_candidate(host1.clone()).unwrap(); - l.add_remote_candidate(host2.clone()); - r.add_local_candidate(host2).unwrap(); - r.add_remote_candidate(host1); - - let finger_l = l.direct_api().local_dtls_fingerprint().clone(); - let finger_r = r.direct_api().local_dtls_fingerprint().clone(); - - l.direct_api().set_remote_fingerprint(finger_r); - r.direct_api().set_remote_fingerprint(finger_l); - - let creds_l = l.direct_api().local_ice_credentials(); - let creds_r = r.direct_api().local_ice_credentials(); - - l.direct_api().set_remote_ice_credentials(creds_r); - r.direct_api().set_remote_ice_credentials(creds_l); - - l.direct_api().set_ice_controlling(true); - r.direct_api().set_ice_controlling(false); - - l.direct_api().start_dtls(true).unwrap(); - r.direct_api().start_dtls(false).unwrap(); - - l.direct_api().start_sctp(true); - r.direct_api().start_sctp(false); - - let config = ChannelConfig { - negotiated: Some(1), - label: "my-chan".into(), - ..Default::default() - }; - let cid = l.direct_api().create_data_channel(config.clone()); - r.direct_api().create_data_channel(config); - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - loop { - if let Some(mut chan) = l.channel(cid) { - chan.write(false, "Hello world! ".as_bytes()).expect("to write string"); - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - l.direct_api().close_data_channel(cid); - - loop { - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(12) { - break; - } - } - - assert!( - l.events - .iter() - .any(|(_, event)| event == &Event::ChannelOpen(cid, "my-chan".into())) - ); - assert!(r.events.len() > 120); - assert!(l.events.iter().any(|(_, event)| event == &Event::ChannelClose(cid))); - - // Assert that ChannelOpen happens quickly after IceConnectionStateChange(Completed) - let ice_completed_time = l - .events - .iter() - .find_map(|(t, e)| match e { - Event::IceConnectionStateChange(crate::vendor::str0m::IceConnectionState::Completed) => Some(*t), - _ => None, - }) - .expect("IceConnectionStateChange(Completed) event"); - let channel_open_time = l - .events - .iter() - .find_map(|(t, e)| match e { - Event::ChannelOpen(_, _) => Some(*t), - _ => None, - }) - .expect("ChannelOpen event"); - let channel_open_delay = channel_open_time.duration_since(ice_completed_time); - assert!( - channel_open_delay < Duration::from_millis(250), - "ChannelOpen should happen within 250ms of ICE completing, but took {:?}", - channel_open_delay - ); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/data-channel.rs b/rs/moq-webrtc/src/vendor/str0m/tests/data-channel.rs deleted file mode 100644 index 373864388c9..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/data-channel.rs +++ /dev/null @@ -1,902 +0,0 @@ -use std::net::Ipv4Addr; -use std::time::{Duration, Instant}; - -use crate::vendor::netem::NetemConfig; -use crate::vendor::str0m::channel::{ChannelConfig, ChannelId}; -use crate::vendor::str0m::{Event, Input, Output, Rtc, RtcConfig, RtcError}; - -use super::common; -use common::{Peer, TestRtc, connect_l_r, connect_l_r_with_rtc}; -use common::{init_crypto_default, init_log, progress}; - -/// Poll one peer while deliberately withholding all of its network output. -/// -/// This models an application that keeps driving its local RTC while packets -/// to the peer are delayed. Public events are returned to the test; transmits -/// are dropped instead of being handed to the remote `TestRtc`. -fn poll_without_delivering_network(rtc: &mut TestRtc, now: Instant) -> Result, RtcError> { - rtc.rtc.handle_input(Input::Timeout(now))?; - - let mut events = vec![]; - loop { - match rtc.rtc.poll_output()? { - Output::Event(event) => events.push(event), - Output::Transmit(_) => {} - Output::Timeout(_) => return Ok(events), - } - } -} - -#[test] -pub fn data_channel() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("My little channel".into()); - change.add_channel("My little channel 2".into()); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - loop { - if let Some(mut chan) = l.channel(cid) { - chan.write(false, "Hello world! ".as_bytes()).expect("to write string"); - } - - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - - assert!(r.events.len() > 120); - - Ok(()) -} - -#[test] -fn data_channel_configured_max_message_size() -> Result<(), RtcError> { - init_crypto_default(); - - for snap in [false, true] { - for (left_limit, right_limit) in [ - (32 * 1024, 48 * 1024), - (384 * 1024, 512 * 1024), - (2 * 1024 * 1024, 3 * 1024 * 1024), - (0, 384 * 1024), - ] { - let now = Instant::now(); - let build = |limit| { - Rtc::builder() - .set_snap_enabled(snap) - .set_sctp_max_message_size(limit) - .set_sctp_max_buffered_amount(4 * 1024 * 1024) - .build(now) - }; - let mut l = TestRtc::new_with_rtc(tracing::info_span!("L"), build(left_limit)); - let mut r = TestRtc::new_with_rtc(tracing::info_span!("R"), build(right_limit)); - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("custom-limit".into()); - let (offer, pending) = change.apply().unwrap(); - let offer_sdp = offer.to_sdp_string(); - assert!(offer_sdp.contains(&format!("a=max-message-size:{left_limit}\r\n"))); - assert_eq!(offer_sdp.contains("a=sctp-init:"), snap); - let answer = r.sdp_api().accept_offer(offer)?; - assert!( - answer - .to_sdp_string() - .contains(&format!("a=max-message-size:{right_limit}\r\n")) - ); - l.sdp_api().accept_answer(pending, answer)?; - - while l.channel(cid).is_none() || r.channel(cid).is_none() { - progress(&mut l, &mut r)?; - assert!(l.duration() < Duration::from_secs(10), "channel should open"); - } - - let to_right = vec![1; right_limit as usize]; - let to_left = vec![ - 2; - if left_limit == 0 { - 2 * 1024 * 1024 - } else { - left_limit as usize - } - ]; - assert!( - l.channel(cid) - .unwrap() - .write(true, &vec![0; right_limit as usize + 1]) - .is_err() - ); - if left_limit != 0 { - assert!( - r.channel(cid) - .unwrap() - .write(true, &vec![0; left_limit as usize + 1]) - .is_err() - ); - } - assert!(l.channel(cid).unwrap().write(true, &to_right)?); - assert!(r.channel(cid).unwrap().write(true, &to_left)?); - - loop { - progress(&mut l, &mut r)?; - let left_received = l - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == to_left)); - let right_received = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == to_right)); - if left_received && right_received { - break; - } - assert!( - l.duration() < Duration::from_secs(20), - "messages at the configured receive limits should arrive (SNAP: {snap})" - ); - } - } - } - Ok(()) -} - -/// Closing a data channel must propagate to the remote peer (via the SCTP -/// stream reset handshake), and once the handshake completes the freed stream -/// id must be reusable by a new in-band channel. -#[test] -pub fn data_channel_close_reopen() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("churn".into()); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Wait until both sides see the channel open. - loop { - progress(&mut l, &mut r)?; - - let l_open = l - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelOpen(id, _) if *id == cid)); - let r_open = r.events.iter().any(|(_, e)| matches!(e, Event::ChannelOpen(_, _))); - - if l_open && r_open { - break; - } - assert!( - l.duration() < Duration::from_secs(10), - "first channel should open on both sides" - ); - } - - let stream_id = l - .direct_api() - .sctp_stream_id_by_channel_id(cid) - .expect("stream id for open channel"); - - // Close locally. The reset handshake must inform the remote, which - // previously never received ChannelClose. - l.direct_api().close_data_channel(cid); - - loop { - progress(&mut l, &mut r)?; - - let l_closed = l - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelClose(id) if *id == cid)); - let r_closed = r.events.iter().any(|(_, e)| matches!(e, Event::ChannelClose(_))); - - if l_closed && r_closed { - break; - } - assert!( - l.duration() < Duration::from_secs(20), - "both sides should see ChannelClose" - ); - } - - // The reset handshake finishes with round-trips (reciprocal reset and - // RECONFIG-RESPONSEs) that carry no public events, so there is nothing to - // wait on here. Creating the next channel immediately is fine: its stream - // id allocation happens on a later timeout, by which time the handshake - // rounds have been ferried through. The stream id assertion below fails - // loudly if the allocator did not release the id in time. - let cid2 = l.direct_api().create_data_channel(ChannelConfig { - label: "churn2".into(), - ..Default::default() - }); - assert_ne!(cid, cid2); - - loop { - progress(&mut l, &mut r)?; - - let l_open = l - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelOpen(id, label) if *id == cid2 && label == "churn2")); - let r_open = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelOpen(_, label) if label == "churn2")); - - if l_open && r_open { - break; - } - assert!( - l.duration() < Duration::from_secs(30), - "reopened channel should open on both sides" - ); - } - - // The freed stream id must have been reused, proving the allocator - // released it when the reset handshake completed. - assert_eq!( - l.direct_api().sctp_stream_id_by_channel_id(cid2), - Some(stream_id), - "reopened channel should reuse the freed stream id" - ); - - // Data flows on the reopened channel. - loop { - if let Some(mut chan) = l.channel(cid2) { - chan.write(false, b"hello again").expect("write to succeed"); - } - - progress(&mut l, &mut r)?; - - let got_data = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(d) if d.data.as_slice() == b"hello again")); - if got_data { - break; - } - assert!( - l.duration() < Duration::from_secs(40), - "data should flow on the reopened channel" - ); - } - - Ok(()) -} - -#[test] -pub fn negotiated_reuse_waits_for_reset_before_channel_open() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - let stream_id = 10; - let config = ChannelConfig { - label: "old-generation".into(), - negotiated: Some(stream_id), - ..Default::default() - }; - let old_l = l.direct_api().create_data_channel(config.clone()); - let _old_r = r.direct_api().create_data_channel(config); - - loop { - progress(&mut l, &mut r)?; - let left_open = l - .events - .iter() - .any(|(_, event)| matches!(event, Event::ChannelOpen(id, _) if *id == old_l)); - let right_open = r - .events - .iter() - .any(|(_, event)| matches!(event, Event::ChannelOpen(_, _))); - if left_open && right_open { - break; - } - assert!( - l.duration() < Duration::from_secs(10), - "negotiated channel should open on both peers" - ); - } - - l.events.clear(); - l.direct_api().close_data_channel(old_l); - - // Process the local close, but withhold its RE-CONFIG packets. The old - // SCTP stream therefore still exists and its reset cannot be complete. - let close_at = l.last; - let close_events = poll_without_delivering_network(&mut l, close_at)?; - assert!( - close_events - .iter() - .any(|event| matches!(event, Event::ChannelClose(id) if *id == old_l)), - "the old local channel should close" - ); - - let replacement = l.direct_api().create_data_channel(ChannelConfig { - label: "replacement".into(), - negotiated: Some(stream_id), - ..Default::default() - }); - let replacement_events = poll_without_delivering_network(&mut l, close_at + Duration::from_millis(1))?; - - assert!( - !replacement_events - .iter() - .any(|event| matches!(event, Event::ChannelOpen(id, _) if *id == replacement)), - "a negotiated replacement must not open before the old reset completes" - ); - - Ok(()) -} - -#[test] -pub fn unconfirmed_reset_keeps_stream_id_reserved() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let (mut l, mut r) = connect_l_r(); - let old = l.direct_api().create_data_channel(ChannelConfig::default()); - - loop { - progress(&mut l, &mut r)?; - if l.events - .iter() - .any(|(_, event)| matches!(event, Event::ChannelOpen(id, _) if *id == old)) - { - break; - } - assert!(l.duration() < Duration::from_secs(10), "first channel should open"); - } - - let old_stream_id = l - .direct_api() - .sctp_stream_id_by_channel_id(old) - .expect("old channel should have a stream ID"); - l.direct_api().close_data_channel(old); - - // Drop all local reset traffic and advance well past the close. No peer response - // has made the old ID safe during this interval, so it stays reserved. - let close_at = l.last; - let close_events = poll_without_delivering_network(&mut l, close_at)?; - assert!( - close_events - .iter() - .any(|event| matches!(event, Event::ChannelClose(id) if *id == old)), - "the old local channel should close" - ); - poll_without_delivering_network(&mut l, close_at + Duration::from_secs(31))?; - - let replacement = l.direct_api().create_data_channel(ChannelConfig::default()); - poll_without_delivering_network(&mut l, close_at + Duration::from_secs(31) + Duration::from_millis(1))?; - - let replacement_stream_id = l - .direct_api() - .sctp_stream_id_by_channel_id(replacement) - .expect("replacement should have a stream ID"); - assert_ne!( - replacement_stream_id, old_stream_id, - "elapsed time cannot make an unconfirmed reset safe; another free ID should be used" - ); - - Ok(()) -} - -/// Connects two peers built from `config` over the direct API and opens an out-of-band -/// negotiated channel on both, so no DCEP message occupies the send buffer. -fn connect_with_channel(config: impl Fn(RtcConfig) -> RtcConfig) -> Result<(TestRtc, TestRtc, ChannelId), RtcError> { - let build = |peer: Peer| { - let mut builder = Rtc::builder(); - if let Some(crypto) = peer.crypto_provider() { - builder = builder.set_crypto_provider(crypto); - } - config(builder).build(Instant::now()) - }; - let (mut l, mut r) = connect_l_r_with_rtc(build(Peer::Left), build(Peer::Right)); - - let channel = ChannelConfig { - label: "data".into(), - negotiated: Some(1), - ..Default::default() - }; - let cid = l.direct_api().create_data_channel(channel.clone()); - r.direct_api().create_data_channel(channel); - - loop { - progress(&mut l, &mut r)?; - let l_open = l - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelOpen(id, _) if *id == cid)); - let r_open = r.events.iter().any(|(_, e)| matches!(e, Event::ChannelOpen(_, _))); - if l_open && r_open { - return Ok((l, r, cid)); - } - assert!( - l.duration() < Duration::from_secs(10), - "channel should open on both peers" - ); - } -} - -/// Bytes of `ChannelData` the peer has received so far. -fn received_bytes(rtc: &TestRtc) -> usize { - rtc.events - .iter() - .filter_map(|(_, e)| match e { - Event::ChannelData(d) => Some(d.data.len()), - _ => None, - }) - .sum() -} - -#[test] -fn data_channel_direct_configured_receive_limit() -> Result<(), RtcError> { - init_crypto_default(); - - const LIMIT: usize = 32 * 1024; - let (mut l, mut r, cid) = connect_with_channel(|config| config.set_sctp_max_message_size(LIMIT as u32))?; - - let message = vec![1; LIMIT]; - assert!(l.channel(cid).unwrap().write(true, &message)?); - assert!(r.channel(cid).unwrap().write(true, &message)?); - while received_bytes(&l) < LIMIT || received_bytes(&r) < LIMIT { - progress(&mut l, &mut r)?; - assert!(l.duration() < Duration::from_secs(10)); - } - - // The direct API has no SDP, so send limits remain at the 64 KiB default. - // Messages above our configured receive limit must still be dropped. - let oversized = vec![2; LIMIT + 1]; - assert!(l.channel(cid).unwrap().write(true, &oversized)?); - assert!(r.channel(cid).unwrap().write(true, &oversized)?); - let start = l.duration(); - while l.duration() - start < Duration::from_secs(1) { - progress(&mut l, &mut r)?; - } - for rtc in [&l, &r] { - assert_eq!(received_bytes(rtc), LIMIT); - assert!( - rtc.events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == message)) - ); - } - Ok(()) -} - -/// Keeps the send buffer full of 60 KiB messages for 3 seconds, then checks that all -/// of them arrive. This makes SCTP hand DTLS many packets at once. -fn keep_send_buffer_full(config: impl Fn(RtcConfig) -> RtcConfig) -> Result<(), RtcError> { - let (mut l, mut r, cid) = connect_with_channel(config)?; - - let message = vec![0; 60 * 1024]; - let mut accepted = 0; - let start = l.duration(); - while l.duration() - start < Duration::from_secs(3) { - let mut chan = l.channel(cid).expect("open channel"); - while chan.write(true, &message)? { - accepted += message.len(); - } - progress(&mut l, &mut r)?; - } - - while received_bytes(&r) < accepted { - progress(&mut l, &mut r)?; - assert!( - l.duration() - start < Duration::from_secs(10), - "accepted data should reach the remote peer" - ); - } - assert_eq!(received_bytes(&r), accepted); - - Ok(()) -} - -/// Handing DTLS the packets one stack frame per packet overflowed the stack of a debug -/// build. -#[test] -pub fn data_channel_full_send_buffer() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - keep_send_buffer_full(|config| config) -} - -/// Writes 16 KiB messages without polling in between until `Channel::write` refuses -/// one. Nothing is sent or acknowledged meanwhile, so the accepted bytes are exactly -/// what the send buffer limit allows. Then checks that all of them arrive. -fn fill_send_buffer(max_buffered_amount: Option) -> Result { - const MESSAGE: usize = 16 * 1024; - - let (mut l, mut r, cid) = connect_with_channel(|config| match max_buffered_amount { - Some(bytes) => config.set_sctp_max_buffered_amount(bytes), - None => config, - })?; - - let mut chan = l.channel(cid).expect("open channel"); - let mut accepted = 0; - while accepted < 64 * MESSAGE && chan.write(true, &[0; MESSAGE])? { - accepted += MESSAGE; - } - - let start = l.duration(); - while received_bytes(&r) < accepted { - progress(&mut l, &mut r)?; - assert!( - l.duration() - start < Duration::from_secs(10), - "accepted data should reach the remote peer" - ); - } - - Ok(accepted) -} - -#[test] -pub fn data_channel_max_buffered_amount() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - // The default limit is unchanged. - assert_eq!(fill_send_buffer(None)?, 128 * 1024); - - // A raised limit lets more than the default be buffered. - assert_eq!(fill_send_buffer(Some(512 * 1024))?, 512 * 1024); - - Ok(()) -} - -#[test] -pub fn data_channel_full_large_send_buffer() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - keep_send_buffer_full(|config| config.set_sctp_max_buffered_amount(4 * 1024 * 1024)) -} - -#[test] -pub fn data_channel_flood() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("My little channel".into()); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - loop { - if l.is_connected() || r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - while l.channel(cid).is_none() { - progress(&mut l, &mut r)?; - } - - r.set_netem(NetemConfig::new().latency(Duration::from_millis(1000))); - - let mut count = 0; - - for _ in 0..10_000 { - let mut chan = l.channel(cid).unwrap(); - let did_write = chan.write(true, &[0u8; 1400]).expect("to write string"); - if did_write { - count += 1; - } - progress(&mut l, &mut r)?; - } - - loop { - progress(&mut l, &mut r)?; - - if l.duration() > Duration::from_secs(10) { - break; - } - } - assert!(count > 9000, "Too few events: {}", count); - - Ok(()) -} - -#[test] -pub fn channel_config_inband() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Create in-band negotiated channel (DCEP) - let mut change = l.sdp_api(); - let cid = change.add_channel("DCEP Channel".into()); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Wait for connection - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - let mut l_channel_opened = false; - let mut r_channel_opened = false; - let mut l_config_available_on_open = false; - let mut r_config_available_on_open = false; - - // Process events and verify config availability immediately when ChannelOpen is fired - loop { - progress(&mut l, &mut r)?; - - // Check L side events and collect channel ID if found - let mut l_found_id = None; - for (_, event) in &l.events { - if let Event::ChannelOpen(id, label) = event { - if *id == cid && label == "DCEP Channel" { - l_channel_opened = true; - l_found_id = Some(*id); - break; - } - } - } - - // Check R side events and collect channel ID if found - let mut r_found_id = None; - for (_, event) in &r.events { - if let Event::ChannelOpen(id, label) = event { - if label == "DCEP Channel" { - r_channel_opened = true; - r_found_id = Some(*id); - break; - } - } - } - - // Verify config is available immediately when ChannelOpen is emitted - if let Some(id) = l_found_id { - if let Some(channel) = l.channel(id) { - l_config_available_on_open = channel.config().is_some(); - } - } - - if let Some(id) = r_found_id { - if let Some(channel) = r.channel(id) { - r_config_available_on_open = channel.config().is_some(); - } - } - - if (l_channel_opened && r_channel_opened) || l.duration() > Duration::from_secs(10) { - break; - } - } - - assert!(l_channel_opened, "L side should receive ChannelOpen event"); - assert!(r_channel_opened, "R side should receive ChannelOpen event"); - assert!( - l_config_available_on_open, - "L side config should be available on ChannelOpen" - ); - assert!( - r_config_available_on_open, - "R side config should be available on ChannelOpen" - ); - - Ok(()) -} - -#[test] -pub fn channel_config_outband_local() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Enable SCTP by adding a temporary channel (will be removed) - let mut change_l = l.sdp_api(); - let _temp_cid = change_l.add_channel("temp".into()); - let (offer, pending) = change_l.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Wait for connection - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Wait for SCTP to be established first - loop { - progress(&mut l, &mut r)?; - - // Check for SCTP connection via any channel events - let connected = l.events.iter().any(|(_, e)| matches!(e, Event::ChannelOpen(_, _))) - || r.events.iter().any(|(_, e)| matches!(e, Event::ChannelOpen(_, _))); - - if connected || l.duration() > Duration::from_secs(5) { - break; - } - } - - // Create out-of-band negotiated channel on both sides - let config = ChannelConfig { - negotiated: Some(10), - label: "OutOfBand Local".into(), - ..Default::default() - }; - - let cid_l = l.direct_api().create_data_channel(config.clone()); - let cid_r = r.direct_api().create_data_channel(config); - - // Allow some time for channels to be established - for _ in 0..10 { - progress(&mut l, &mut r)?; - } - - // Verify config is immediately available for locally created out-of-band channels - let l_channel = l.channel(cid_l).expect("L channel should be available"); - let r_channel = r.channel(cid_r).expect("R channel should be available"); - - assert!( - l_channel.config().is_some(), - "L side config should be immediately available for local out-of-band channel" - ); - assert!( - r_channel.config().is_some(), - "R side config should be immediately available for local out-of-band channel" - ); - - let l_config = l_channel.config().unwrap(); - let r_config = r_channel.config().unwrap(); - - assert_eq!(l_config.label, "OutOfBand Local"); - assert_eq!(r_config.label, "OutOfBand Local"); - assert_eq!(l_config.negotiated, Some(10)); - assert_eq!(r_config.negotiated, Some(10)); - - Ok(()) -} - -#[test] -pub fn channel_config_with_protocol() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let _temp_cid = change.add_channel("temp".into()); - let (offer, pending) = change.apply().unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Wait for connection - loop { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let max = l.last.max(r.last); - l.last = max; - r.last = max; - - // Wait for SCTP to be established - loop { - progress(&mut l, &mut r)?; - let connected = l.events.iter().any(|(_, e)| matches!(e, Event::ChannelOpen(_, _))); - if connected || l.duration() > Duration::from_secs(5) { - break; - } - } - - // Create channels with custom protocol - let custom_protocol = "my-custom-protocol"; - let config = ChannelConfig { - negotiated: Some(20), - protocol: custom_protocol.into(), - ..Default::default() - }; - - let cid_l = l.direct_api().create_data_channel(config.clone()); - let cid_r = r.direct_api().create_data_channel(config); - - for _ in 0..10 { - progress(&mut l, &mut r)?; - } - - // Verify protocol is correctly set on both sides - let l_channel = l.channel(cid_l).unwrap(); - let r_channel = r.channel(cid_r).unwrap(); - let l_config = l_channel.config().unwrap(); - let r_config = r_channel.config().unwrap(); - - assert_eq!(l_config.protocol, custom_protocol); - assert_eq!(r_config.protocol, custom_protocol); - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-close.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-close.rs index 581732bed44..dd26657ef7b 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-close.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-close.rs @@ -46,8 +46,6 @@ fn direct_pair_with_config(configure: impl Fn(RtcConfig) -> RtcConfig) -> (TestR l.direct_api().start_dtls(true).unwrap(); r.direct_api().start_dtls(false).unwrap(); - l.direct_api().start_sctp(true); - r.direct_api().start_sctp(false); progress_until(&mut l, &mut r, "DTLS handshake", |l, r| { l.is_connected() && r.is_connected() diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs index 4b505d28c48..69c51616c35 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-fingerprint.rs @@ -7,6 +7,7 @@ use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use crate::vendor::str0m::crypto::{CryptoProvider, Fingerprint, Sha1Provider}; +use crate::vendor::str0m::media::{Direction, MediaKind}; use crate::vendor::str0m::{Candidate, RtcConfig, RtcError}; use tracing::info_span; @@ -166,7 +167,7 @@ fn stronger_fingerprint_mismatch_must_be_rejected() { r.add_local_candidate(Candidate::host((Ipv4Addr::new(2, 2, 2, 2), 2000).into(), "udp").unwrap()) .unwrap(); let mut change = l.sdp_api(); - change.add_channel("test".into()); + change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer, pending) = change.apply().unwrap(); let answer = r.sdp_api().accept_offer(offer).unwrap(); let sdp = answer.to_sdp_string(); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-retransmit.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-retransmit.rs index c205d244b1a..b01273d3bec 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-retransmit.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-retransmit.rs @@ -261,8 +261,6 @@ fn dtls_handshake_completes_under_packet_loss() { l.direct_api().start_dtls(true).unwrap(); r.direct_api().start_dtls(false).unwrap(); - l.direct_api().start_sctp(true); - r.direct_api().start_sctp(false); // Drive both sides forward. The DTLS default connect timeout is 10s, // so a bounded iteration cap that allows well past that is enough to diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-security.rs b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-security.rs index 50ab915d49b..4ec43879022 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/dtls-security.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/dtls-security.rs @@ -5,6 +5,7 @@ use std::time::{Duration, Instant}; use crate::vendor::str0m::Rtc; use crate::vendor::str0m::RtcError; +use crate::vendor::str0m::media::{Direction, MediaKind}; use super::common; use common::{Peer, TestRtc, init_crypto_default, init_log, progress}; @@ -92,7 +93,7 @@ fn dtls_with_ice_lite() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -138,7 +139,7 @@ fn dtls_pregenerated_certificate() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/flappy-ice-state.rs b/rs/moq-webrtc/src/vendor/str0m/tests/flappy-ice-state.rs index 539fc295c2f..84f944de688 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/flappy-ice-state.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/flappy-ice-state.rs @@ -2,6 +2,7 @@ use std::net::Ipv4Addr; use std::time::{Duration, Instant}; use crate::vendor::str0m::RtcConfig; +use crate::vendor::str0m::media::{Direction, MediaKind}; use crate::vendor::str0m::{Event, RtcError}; use tracing::info_span; @@ -22,7 +23,7 @@ pub fn flappy_ice_lite_state() -> Result<(), RtcError> { r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); let mut change = l.sdp_api(); - let _ = change.add_channel("My little channel".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer, pending) = change.apply().unwrap(); let answer = r.rtc.sdp_api().accept_offer(offer)?; diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs b/rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs deleted file mode 100644 index 0eba35e1011..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/handshake-direct.rs +++ /dev/null @@ -1,752 +0,0 @@ -use std::net::{Ipv4Addr, SocketAddr}; -use std::sync::Arc; -use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::mpsc::{self, Receiver, Sender}; -use std::thread; -use std::time::{Duration, Instant}; - -use crate::vendor::str0m::channel::{ChannelConfig, ChannelId, Reliability}; -use crate::vendor::str0m::config::Fingerprint; -use crate::vendor::str0m::crypto::dtls::ProtocolVersion; -use crate::vendor::str0m::ice::IceCreds; -use crate::vendor::str0m::net::{Protocol, Receive}; -use crate::vendor::str0m::{Candidate, Event, IceConnectionState, Input, Output, Rtc, RtcConfig, RtcError}; -use tracing::{Span, info_span}; - -use super::common; -use common::{Peer, init_crypto_default, init_log, snap_init_data}; - -/// Maximum total packets expected when using SNAP. -/// -/// SNAP skips the 4-way SCTP handshake (INIT, INIT-ACK, COOKIE-ECHO, -/// COOKIE-ACK), so the total packet count should be well under this limit. -/// The exact number depends on ICE/DTLS setup specifics. -const MAX_SNAP_PACKETS: usize = 20; - -/// Pre-negotiated data channel SCTP stream ID -const DATA_CHANNEL_ID: u16 = 0; - -/// Set to `true` to save packet captures to `target/pcap/` for Wireshark analysis. -const SAVE_PCAP: bool = false; - -/// Standard direct API handshake (no SNAP). -#[test] -pub fn handshake_direct_api() -> Result<(), RtcError> { - run_direct_handshake(false) -} - -/// Direct API handshake with SNAP (out-of-band SCTP INIT exchange, skips 4-way handshake). -#[test] -pub fn handshake_direct_api_snap() -> Result<(), RtcError> { - run_direct_handshake(true) -} - -/// Returns the name of the default crypto provider, matching -/// `crate::vendor::str0m::crypto::from_feature_flags()`. -fn default_crypto_name() -> &'static str { - "rind" -} - -/// Shared implementation for both standard and SNAP direct API handshake tests. -fn run_direct_handshake(use_snap: bool) -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let test_start = Instant::now(); - - let client_crypto_name = std::env::var("L_CRYPTO").unwrap_or_else(|_| default_crypto_name().into()); - let server_crypto_name = std::env::var("R_CRYPTO").unwrap_or_else(|_| default_crypto_name().into()); - - println!( - "\n=== Test: client={}, server={} ===", - client_crypto_name, server_crypto_name - ); - - // Channels for communication between threads - let (client_tx, server_rx) = mpsc::channel::(); - let (server_tx, client_rx) = mpsc::channel::(); - - let client_packets_sent = Arc::new(AtomicUsize::new(0)); - let server_packets_sent = Arc::new(AtomicUsize::new(0)); - let client_packets_sent_clone = client_packets_sent.clone(); - let server_packets_sent_clone = server_packets_sent.clone(); - - let client_addr: SocketAddr = (Ipv4Addr::new(192, 168, 1, 1), 5000).into(); - let server_addr: SocketAddr = (Ipv4Addr::new(192, 168, 1, 2), 5001).into(); - - // Test name for pcap files - let test_name = if use_snap { - "handshake_direct_api_snap" - } else { - "handshake_direct_api" - }; - - // Spawn server thread - // Returns (packets, Result) so pcap is available even on failure. - let server_handle = thread::spawn(move || -> (Vec, Result) { - let span = info_span!("SERVER"); - let _guard = span.enter(); - let mut timing = TimingReport::new(); - let mut packets = Vec::new(); - - let result = (|| -> Result { - // Initialize server (is_client = false) - let (mut rtc, local_creds, local_fingerprint) = init_rtc(false, server_addr, Peer::Right, &mut timing)?; - - // If SNAP, generate local SCTP INIT for out-of-band exchange - let snap = snap_init_data(use_snap); - let local_sctp_init = snap.as_ref().map(|(init, _)| init.clone()); - - // Send server's credentials to client - server_tx - .send(Message::Credentials { - ice_ufrag: local_creds.ufrag.clone(), - ice_pwd: local_creds.pass.clone(), - dtls_fingerprint: local_fingerprint, - sctp_init: local_sctp_init, - }) - .expect("Failed to send server credentials"); - - // Wait for client's credentials - let (remote_ice_ufrag, remote_ice_pwd, remote_fingerprint, remote_sctp_init) = - match server_rx.recv_timeout(Duration::from_secs(5)) { - Ok(Message::Credentials { - ice_ufrag, - ice_pwd, - dtls_fingerprint, - sctp_init, - }) => { - timing.got_offer = Some(Instant::now()); - (ice_ufrag, ice_pwd, dtls_fingerprint, sctp_init) - } - Ok(_) => panic!("Server expected Credentials, got something else"), - Err(e) => panic!("Server failed to receive credentials: {:?}", e), - }; - - // Configure with remote credentials (is_client = false) - configure_rtc( - &mut rtc, - false, - client_addr, - IceCreds { - ufrag: remote_ice_ufrag, - pass: remote_ice_pwd, - }, - remote_fingerprint, - snap.map(|(_, d)| d), - remote_sctp_init, - )?; - timing.sent_answer = Some(Instant::now()); - - // Run the event loop with message exchange - run_rtc_loop_with_exchange( - &mut rtc, - &mut timing, - false, - RtcLoopIo { - span: &span, - incoming: &server_rx, - outgoing: &server_tx, - packets: &mut packets, - packets_sent: &server_packets_sent_clone, - }, - )?; - - timing.dtls_protocol_version = rtc.direct_api().dtls_protocol_version(); - - Ok(timing) - })(); - - (packets, result) - }); - - // Spawn client thread - // Returns (packets, Result) so pcap is available even on failure. - let client_handle = thread::spawn(move || -> (Vec, Result) { - let span = info_span!("CLIENT"); - let _guard = span.enter(); - let mut timing = TimingReport::new(); - let mut packets = Vec::new(); - - let result = (|| -> Result { - // Initialize client (is_client = true) - let (mut rtc, local_creds, local_fingerprint) = init_rtc(true, client_addr, Peer::Left, &mut timing)?; - - // If SNAP, generate local SCTP INIT for out-of-band exchange - let snap = snap_init_data(use_snap); - let local_sctp_init = snap.as_ref().map(|(init, _)| init.clone()); - - // Wait for server's credentials first - let (remote_ice_ufrag, remote_ice_pwd, remote_fingerprint, remote_sctp_init) = - match client_rx.recv_timeout(Duration::from_secs(5)) { - Ok(Message::Credentials { - ice_ufrag, - ice_pwd, - dtls_fingerprint, - sctp_init, - }) => (ice_ufrag, ice_pwd, dtls_fingerprint, sctp_init), - Ok(_) => panic!("Client expected Credentials, got something else"), - Err(e) => panic!("Client failed to receive server credentials: {:?}", e), - }; - - // Send client's credentials to server - client_tx - .send(Message::Credentials { - ice_ufrag: local_creds.ufrag.clone(), - ice_pwd: local_creds.pass.clone(), - dtls_fingerprint: local_fingerprint, - sctp_init: local_sctp_init, - }) - .expect("Failed to send client credentials"); - timing.sent_offer = Some(Instant::now()); - - // Configure with remote credentials (is_client = true) - configure_rtc( - &mut rtc, - true, - server_addr, - IceCreds { - ufrag: remote_ice_ufrag, - pass: remote_ice_pwd, - }, - remote_fingerprint, - snap.map(|(_, d)| d), - remote_sctp_init, - )?; - timing.got_answer = Some(Instant::now()); - - // Run the event loop with message exchange - run_rtc_loop_with_exchange( - &mut rtc, - &mut timing, - true, - RtcLoopIo { - span: &span, - incoming: &client_rx, - outgoing: &client_tx, - packets: &mut packets, - packets_sent: &client_packets_sent_clone, - }, - )?; - - timing.dtls_protocol_version = rtc.direct_api().dtls_protocol_version(); - - Ok(timing) - })(); - - (packets, result) - }); - - // Wait for both threads to complete - let (server_packets, server_result) = server_handle.join().expect("Server thread panicked"); - let (client_packets, client_result) = client_handle.join().expect("Client thread panicked"); - - // Save pcap files BEFORE checking errors so we capture failing handshakes - if SAVE_PCAP { - let pcap_dir = std::path::Path::new("target/pcap"); - std::fs::create_dir_all(pcap_dir).expect("Failed to create target/pcap directory"); - - let client_path = pcap_dir.join(format!("{test_name}_client.pcap")); - let server_path = pcap_dir.join(format!("{test_name}_server.pcap")); - - write_pcap(&client_path, &client_packets).expect("Failed to write client pcap"); - write_pcap(&server_path, &server_packets).expect("Failed to write server pcap"); - - println!(" PCAP saved: {}", client_path.display()); - println!(" PCAP saved: {}", server_path.display()); - } - - let server_timing = server_result.expect("Server returned error"); - let client_timing = client_result.expect("Client returned error"); - - let total_time = test_start.elapsed(); - let variant = if use_snap { "SNAP" } else { "standard" }; - - client_timing.print(&format!("CLIENT ({})", variant)); - server_timing.print(&format!("SERVER ({})", variant)); - - println!( - "\n=== Total Test Time ({}): {:.3}ms ===", - variant, - total_time.as_secs_f64() * 1000.0 - ); - - let client_sent = client_packets_sent.load(Ordering::SeqCst); - let server_sent = server_packets_sent.load(Ordering::SeqCst); - let total_packets = client_sent + server_sent; - println!("\n=== Packet Counts ({}) ===", variant); - println!(" Client packets sent: {}", client_sent); - println!(" Server packets sent: {}", server_sent); - println!(" Total packets: {}", total_packets); - - if use_snap { - // SNAP skips the 4-way SCTP handshake, so it must use strictly fewer - // packets than a standard connection. - assert!( - total_packets < MAX_SNAP_PACKETS, - "SNAP should use fewer packets, got {total_packets}" - ); - } - - // Verify the exchange happened - assert!(client_timing.sent_data.is_some(), "Client should have sent data"); - assert!( - client_timing.received_data.is_some(), - "Client should have received reply" - ); - assert!( - server_timing.received_data.is_some(), - "Server should have received data" - ); - assert!(server_timing.sent_data.is_some(), "Server should have sent reply"); - - // Only DTLS 1.2 is supported. - let expected = ProtocolVersion::DTLS1_2; - assert_eq!( - client_timing.dtls_protocol_version, - Some(expected), - "Client negotiated DTLS version mismatch" - ); - assert_eq!( - server_timing.dtls_protocol_version, - Some(expected), - "Server negotiated DTLS version mismatch" - ); - - Ok(()) -} - -/// Initialize an Rtc instance configured for client or server role. -/// -/// Returns the Rtc instance and the local ICE credentials/DTLS fingerprint for exchange. -fn init_rtc( - is_client: bool, - local_addr: SocketAddr, - peer: Peer, - timing: &mut TimingReport, -) -> Result<(Rtc, IceCreds, String), RtcError> { - let ice_creds = IceCreds::new(); - - let mut rtc_config = RtcConfig::new().set_local_ice_credentials(ice_creds.clone()); - if !is_client { - rtc_config = rtc_config.set_ice_lite(true); - } - if let Some(crypto) = peer.crypto_provider() { - rtc_config = rtc_config.set_crypto_provider(crypto); - } - let mut rtc = rtc_config.build(Instant::now()); - timing.rtc_built = Some(Instant::now()); - - let fingerprint = rtc.direct_api().local_dtls_fingerprint().to_string(); - - let local_candidate = Candidate::host(local_addr, "udp")?; - rtc.add_local_candidate(local_candidate); - - Ok((rtc, ice_creds, fingerprint)) -} - -/// Configure the Rtc instance with remote credentials and start DTLS/SCTP. -/// -/// If `local_init_data` and `remote_sctp_init` are both provided, SNAP is used -/// to skip the 4-way SCTP handshake. -/// -/// `local_init_data` is expected to already contain the local INIT chunk from -/// `local_init_chunk()`. This function adds the remote INIT chunk and then calls -/// `start_sctp_with_snap()`. If either side of that exchange is missing, it -/// falls back to the normal `start_sctp()` path. -fn configure_rtc( - rtc: &mut Rtc, - is_client: bool, - remote_addr: SocketAddr, - remote_ice_credentials: IceCreds, - remote_fingerprint: String, - local_init_data: Option, - remote_sctp_init: Option>, -) -> Result<(), RtcError> { - let remote_candidate = Candidate::host(remote_addr, "udp")?; - rtc.add_remote_candidate(remote_candidate); - - // Build SctpInitData with remote INIT if both sides provided SNAP data - let sctp_init_data = match (local_init_data, remote_sctp_init) { - (Some(mut data), Some(remote_init)) => { - data.set_remote_init_chunk(remote_init); - Some(data) - } - _ => None, - }; - - { - let mut direct_api = rtc.direct_api(); - - direct_api.set_ice_lite(!is_client); - direct_api.set_ice_controlling(is_client); - - direct_api.set_remote_ice_credentials(remote_ice_credentials); - - let fingerprint: Fingerprint = remote_fingerprint.parse().expect("Failed to parse remote fingerprint"); - direct_api.set_remote_fingerprint(fingerprint); - - direct_api.start_dtls(is_client)?; - - if let Some(sctp_init_data) = sctp_init_data { - direct_api.start_sctp_with_snap(is_client, sctp_init_data)?; - } else { - direct_api.start_sctp(is_client); - } - - direct_api.create_data_channel(ChannelConfig { - label: "test-channel".into(), - negotiated: Some(DATA_CHANNEL_ID), - ordered: true, - reliability: Reliability::Reliable, - protocol: "".into(), - }); - } - - rtc.handle_input(Input::Timeout(Instant::now()))?; - - Ok(()) -} - -/// Messages exchanged between client and server threads. -#[derive(Debug)] -enum Message { - /// ICE, DTLS, and optionally SCTP credentials exchange - Credentials { - ice_ufrag: String, - ice_pwd: String, - dtls_fingerprint: String, - /// SCTP INIT chunk for SNAP (`None` when not using SNAP) - sctp_init: Option>, - }, - /// RTP/DTLS/SCTP packet - Packet { - proto: Protocol, - source: SocketAddr, - destination: SocketAddr, - contents: Vec, - }, - /// Signal to exit (sent by client to server) - Exit, -} - -/// Timing report for major events -#[derive(Debug, Default)] -struct TimingReport { - start: Option, - rtc_built: Option, - sent_offer: Option, - got_offer: Option, - sent_answer: Option, - got_answer: Option, - ice_checking: Option, - ice_completed: Option, - channel_open: Option, - sent_data: Option, - received_data: Option, - dtls_protocol_version: Option, -} - -impl TimingReport { - fn new() -> Self { - Self { - start: Some(Instant::now()), - ..Default::default() - } - } - - fn print(&self, name: &str) { - let start = self.start.unwrap(); - println!("\n=== {} Timing Report ===", name); - if let Some(t) = self.rtc_built { - println!(" Rtc built: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.sent_offer { - println!(" Sent offer: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.got_offer { - println!(" Got offer: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.sent_answer { - println!(" Sent answer: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.got_answer { - println!(" Got answer: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.ice_checking { - println!(" ICE Checking: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.ice_completed { - println!(" ICE Completed: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.channel_open { - println!(" Channel Open: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.sent_data { - println!(" Sent data: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - if let Some(t) = self.received_data { - println!(" Received data: {:>8.3}ms", (t - start).as_secs_f64() * 1000.0); - } - } -} - -/// State for managing message exchange -#[derive(Debug, PartialEq)] -enum DataExchangeState { - WaitingForChannelOpen, - ChannelOpen, - SentMessage, - Complete, -} - -struct RtcLoopIo<'a> { - span: &'a Span, - incoming: &'a Receiver, - outgoing: &'a Sender, - packets: &'a mut Vec, - packets_sent: &'a AtomicUsize, -} - -/// Run the Rtc event loop with message exchange capability -fn run_rtc_loop_with_exchange( - rtc: &mut Rtc, - timing: &mut TimingReport, - is_client: bool, - io: RtcLoopIo<'_>, -) -> Result<(), RtcError> { - let mut state = DataExchangeState::WaitingForChannelOpen; - let mut channel_id: Option = None; - let role = if is_client { "CLIENT" } else { "SERVER" }; - - loop { - if state == DataExchangeState::Complete { - break; - } - - if timing.start.unwrap().elapsed() > Duration::from_secs(10) { - println!("[{}] Overall timeout reached", role); - break; - } - - let timeout = loop { - match io.span.in_scope(|| rtc.poll_output())? { - Output::Timeout(t) => break t, - Output::Transmit(t) => { - let data = t.contents.to_vec(); - io.packets_sent.fetch_add(1, Ordering::SeqCst); - if SAVE_PCAP { - io.packets.push(PcapPacket { - src: t.source, - dst: t.destination, - data: data.clone(), - }); - } - // Send packet to other peer - let _ = io.outgoing.send(Message::Packet { - proto: t.proto, - source: t.source, - destination: t.destination, - contents: data, - }); - } - Output::Event(e) => { - handle_event(rtc, &e, timing, is_client, &mut state, &mut channel_id, io.outgoing); - if state == DataExchangeState::Complete { - return Ok(()); - } - } - } - }; - - let now = Instant::now(); - let wait = timeout.saturating_duration_since(now); - println!("[{}] poll_output returned timeout in {:?}", role, wait); - - match io.incoming.recv_timeout(wait) { - Ok(Message::Packet { - proto, - source, - destination, - contents, - }) => { - println!("[{}] Received packet ({} bytes)", role, contents.len()); - if SAVE_PCAP { - io.packets.push(PcapPacket { - src: source, - dst: destination, - data: contents.clone(), - }); - } - let receive = Receive { - proto, - source, - destination, - contents: contents.as_slice().try_into()?, - }; - io.span - .in_scope(|| rtc.handle_input(Input::Receive(Instant::now(), receive)))?; - } - Ok(Message::Exit) => { - println!("[{}] Received Exit signal", role); - state = DataExchangeState::Complete; - } - Ok(_) => { - unreachable!("Unexpected message type"); - } - Err(mpsc::RecvTimeoutError::Timeout) => { - println!("[{}] Timeout fired, calling handle_input(Timeout)", role); - io.span.in_scope(|| rtc.handle_input(Input::Timeout(Instant::now())))?; - } - Err(mpsc::RecvTimeoutError::Disconnected) => { - println!("[{}] Channel disconnected", role); - break; - } - } - } - - Ok(()) -} - -fn handle_event( - rtc: &mut Rtc, - event: &Event, - timing: &mut TimingReport, - is_client: bool, - state: &mut DataExchangeState, - channel_id: &mut Option, - outgoing: &Sender, -) { - match event { - Event::IceConnectionStateChange(ice_state) => match ice_state { - IceConnectionState::Checking if timing.ice_checking.is_none() => { - timing.ice_checking = Some(Instant::now()); - } - IceConnectionState::Completed => { - timing.ice_completed = Some(Instant::now()); - } - _ => {} - }, - Event::ChannelOpen(cid, label) => { - println!( - "[{}] Channel opened: {:?} - {}", - if is_client { "CLIENT" } else { "SERVER" }, - cid, - label - ); - timing.channel_open = Some(Instant::now()); - *channel_id = Some(*cid); - *state = DataExchangeState::ChannelOpen; - - // Client sends first message - if is_client { - if let Some(mut chan) = rtc.channel(*cid) { - chan.write(true, b"sixseven").expect("Failed to write"); - println!("[CLIENT] Sent 'sixseven'"); - timing.sent_data = Some(Instant::now()); - *state = DataExchangeState::SentMessage; - } - } - } - Event::ChannelData(data) => { - let msg = String::from_utf8_lossy(&data.data); - println!( - "[{}] Received data: '{}'", - if is_client { "CLIENT" } else { "SERVER" }, - msg - ); - if is_client { - if msg == "sevenofnine" { - println!("[CLIENT] Got reply 'sevenofnine' - sending Exit and completing"); - timing.received_data = Some(Instant::now()); - let _ = outgoing.send(Message::Exit); - *state = DataExchangeState::Complete; - } - } else if msg == "sixseven" { - timing.received_data = Some(Instant::now()); - let cid = data.id; - if let Some(mut chan) = rtc.channel(cid) { - chan.write(true, b"sevenofnine").expect("Failed to write"); - println!("[SERVER] Sent reply 'sevenofnine'"); - timing.sent_data = Some(Instant::now()); - *state = DataExchangeState::SentMessage; - } - } - } - _ => {} - } -} - -// --- PCAP support --- - -/// A captured packet for pcap output. -struct PcapPacket { - src: SocketAddr, - dst: SocketAddr, - data: Vec, -} - -/// Write packets to a pcap file using the standard pcap format. -/// Uses raw IPv4 link type so Wireshark can dissect the UDP/DTLS layers. -fn write_pcap(path: &std::path::Path, packets: &[PcapPacket]) -> std::io::Result<()> { - use std::io::Write; - - let mut f = std::fs::File::create(path)?; - - // Global header (24 bytes) - // magic_number, version_major, version_minor, thiszone, sigfigs, snaplen, network - f.write_all(&0xa1b2c3d4u32.to_le_bytes())?; // magic - f.write_all(&2u16.to_le_bytes())?; // version major - f.write_all(&4u16.to_le_bytes())?; // version minor - f.write_all(&0i32.to_le_bytes())?; // thiszone - f.write_all(&0u32.to_le_bytes())?; // sigfigs - f.write_all(&65535u32.to_le_bytes())?; // snaplen - f.write_all(&228u32.to_le_bytes())?; // LINKTYPE_IPV4 (228 = raw IPv4) - - for (i, pkt) in packets.iter().enumerate() { - // Build a minimal IPv4 + UDP frame around the payload - let udp_len = 8 + pkt.data.len(); - let ip_total_len = 20 + udp_len; - - // IPv4 header (20 bytes, no options) - let mut ip_header = [0u8; 20]; - ip_header[0] = 0x45; // version=4, IHL=5 - ip_header[1] = 0; // DSCP/ECN - ip_header[2..4].copy_from_slice(&(ip_total_len as u16).to_be_bytes()); - ip_header[4..6].copy_from_slice(&(i as u16).to_be_bytes()); // identification - ip_header[8] = 64; // TTL - ip_header[9] = 17; // protocol = UDP - // checksum left as 0 (Wireshark will flag but still parse) - if let SocketAddr::V4(a) = pkt.src { - ip_header[12..16].copy_from_slice(&a.ip().octets()); - } - if let SocketAddr::V4(a) = pkt.dst { - ip_header[16..20].copy_from_slice(&a.ip().octets()); - } - - // UDP header (8 bytes) - let mut udp_header = [0u8; 8]; - udp_header[0..2].copy_from_slice(&pkt.src.port().to_be_bytes()); - udp_header[2..4].copy_from_slice(&pkt.dst.port().to_be_bytes()); - udp_header[4..6].copy_from_slice(&(udp_len as u16).to_be_bytes()); - // checksum left as 0 - - let frame_len = ip_total_len as u32; - - // Packet record header (16 bytes) - // Use packet index as fake timestamp (1ms apart) - let ts_sec = i as u32; - let ts_usec = 0u32; - f.write_all(&ts_sec.to_le_bytes())?; - f.write_all(&ts_usec.to_le_bytes())?; - f.write_all(&frame_len.to_le_bytes())?; // incl_len - f.write_all(&frame_len.to_le_bytes())?; // orig_len - - // Frame data - f.write_all(&ip_header)?; - f.write_all(&udp_header)?; - f.write_all(&pkt.data)?; - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-candidates.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-candidates.rs index 5d00234b5f6..d89eb6cf25b 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-candidates.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/ice-candidates.rs @@ -6,6 +6,7 @@ use std::time::{Duration, Instant}; use crate::vendor::str0m::RtcConfig; use crate::vendor::str0m::RtcError; use crate::vendor::str0m::ice::IceCreds; +use crate::vendor::str0m::media::{Direction, MediaKind}; use tracing::info_span; use super::common; @@ -26,7 +27,7 @@ fn ice_candidate_types_host_only() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -47,156 +48,6 @@ fn ice_candidate_types_host_only() -> Result<(), RtcError> { Ok(()) } -/// Test trickle ICE - connect with relay candidates, then trickle in host candidates. -/// Verifies that ICE switches to the better (host) candidates after they're added. -#[test] -fn ice_trickle_incremental_candidates() -> Result<(), RtcError> { - use crate::vendor::str0m::{Candidate, Output}; - use std::net::SocketAddr; - - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - // Define addresses for relay and host candidates - // Relay addresses (TURN allocated addresses, lower priority) - let l_relay_addr: SocketAddr = (Ipv4Addr::new(10, 0, 0, 1), 10000).into(); - let r_relay_addr: SocketAddr = (Ipv4Addr::new(10, 0, 0, 2), 20000).into(); - - // Local addresses (base addresses for relay candidates) - let l_local_addr: SocketAddr = (Ipv4Addr::new(192, 168, 1, 1), 1000).into(); - let r_local_addr: SocketAddr = (Ipv4Addr::new(192, 168, 1, 2), 2000).into(); - - // Host addresses (higher priority, will be trickled later) - let l_host_addr: SocketAddr = (Ipv4Addr::new(1, 1, 1, 1), 1000).into(); - let r_host_addr: SocketAddr = (Ipv4Addr::new(2, 2, 2, 2), 2000).into(); - - // Create relay candidates (lower priority than host) - let l_relay = Candidate::relayed(l_relay_addr, l_local_addr, "udp").unwrap(); - let r_relay = Candidate::relayed(r_relay_addr, r_local_addr, "udp").unwrap(); - - // Add relay candidates initially - l.rtc.add_local_candidate(l_relay.clone()).unwrap(); - r.rtc.add_local_candidate(r_relay.clone()).unwrap(); - - // Exchange relay candidates - l.rtc.add_remote_candidate(r_relay.clone()); - r.rtc.add_remote_candidate(l_relay.clone()); - - // Create offer/answer - let (offer, pending) = l.span.in_scope(|| { - let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); - change.apply().unwrap() - }); - - let answer = r.span.in_scope(|| r.rtc.sdp_api().accept_offer(offer))?; - l.span.in_scope(|| l.rtc.sdp_api().accept_answer(pending, answer))?; - - // Connect using relay candidates - loop { - if l.is_connected() && r.is_connected() { - break; - } - if l.duration() > Duration::from_secs(5) { - panic!("Failed to connect with relay candidates"); - } - progress(&mut l, &mut r)?; - } - - // Get the data channel id - let channel_id = l - .events - .iter() - .find_map(|(_, e)| { - if let crate::vendor::str0m::Event::ChannelOpen(id, _) = e { - Some(*id) - } else { - None - } - }) - .expect("Should have opened a data channel"); - - // Send data to trigger a Transmit and capture the source address - l.rtc.channel(channel_id).unwrap().write(true, b"test").unwrap(); - - let mut initial_send_addr: Option = None; - l.rtc - .handle_input(crate::vendor::str0m::Input::Timeout(l.last)) - .unwrap(); - loop { - match l.rtc.poll_output() { - Ok(Output::Transmit(t)) => { - initial_send_addr = Some(t.source); - break; - } - Ok(Output::Timeout(_)) => break, - Ok(_) => continue, - Err(e) => return Err(e), - } - } - - let initial_send_addr = initial_send_addr.expect("Should have a Transmit after sending data"); - assert_eq!( - initial_send_addr, l_relay_addr, - "Initial send address should be relay candidate" - ); - - // Now trickle in host candidates (higher priority) - let l_host = Candidate::host(l_host_addr, "udp").unwrap(); - let r_host = Candidate::host(r_host_addr, "udp").unwrap(); - - let l_host_added = l.rtc.add_local_candidate(l_host.clone()).unwrap().clone(); - let r_host_added = r.rtc.add_local_candidate(r_host.clone()).unwrap().clone(); - - // Exchange host candidates between peers (simulating trickle ICE signaling) - l.rtc.add_remote_candidate(r_host_added); - r.rtc.add_remote_candidate(l_host_added); - - // Progress to allow ICE to discover and switch to better candidates - for _ in 0..100 { - progress(&mut l, &mut r)?; - } - - // Send data again and capture the new source address - should have switched to host - l.rtc.channel(channel_id).unwrap().write(true, b"test2").unwrap(); - - let mut final_send_addr: Option = None; - l.rtc - .handle_input(crate::vendor::str0m::Input::Timeout(l.last)) - .unwrap(); - loop { - match l.rtc.poll_output() { - Ok(Output::Transmit(t)) => { - final_send_addr = Some(t.source); - break; - } - Ok(Output::Timeout(_)) => break, - Ok(_) => continue, - Err(e) => return Err(e), - } - } - - let final_send_addr = final_send_addr.expect("Should have a Transmit after sending data post-trickle"); - - // Verify that ICE switched from relay to host candidates - assert_eq!( - final_send_addr, l_host_addr, - "After trickle, send address should switch to host candidate" - ); - - // Verify the switch actually happened - assert_ne!( - initial_send_addr, final_send_addr, - "Send address should have changed from relay ({}) to host ({})", - initial_send_addr, final_send_addr - ); - - Ok(()) -} - /// Test custom ICE credentials via set_local_ice_credentials(). #[test] fn ice_custom_credentials() -> Result<(), RtcError> { @@ -225,7 +76,7 @@ fn ice_custom_credentials() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -281,7 +132,7 @@ fn ice_stun_timeout_initial_rto() -> Result<(), RtcError> { // Set up SDP exchange let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -371,7 +222,7 @@ fn ice_stun_timeout_max_rto() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -470,7 +321,7 @@ fn ice_stun_max_retransmits() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); @@ -543,7 +394,7 @@ fn ice_lite_mode() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("test".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-lite-connectivity.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-lite-connectivity.rs index 43160ab2778..e92c1b4dbcc 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-lite-connectivity.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/ice-lite-connectivity.rs @@ -2,6 +2,7 @@ use std::net::Ipv4Addr; use std::time::{Duration, Instant}; use crate::vendor::netem::NetemConfig; +use crate::vendor::str0m::media::{Direction, MediaKind}; use crate::vendor::str0m::{Event, IceConnectionState, RtcConfig, RtcError}; use tracing::info_span; @@ -24,7 +25,7 @@ pub fn ice_lite_premature_disconnect() -> Result<(), RtcError> { r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); let mut change = l.sdp_api(); - change.add_channel("ch".into()); + change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer, pending) = change.apply().unwrap(); let answer = r.sdp_api().accept_offer(offer)?; l.sdp_api().accept_answer(pending, answer)?; diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-remote-binding-keepalive.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-remote-binding-keepalive.rs index 27cda1577ae..ecbadb5a2ea 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-remote-binding-keepalive.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/ice-remote-binding-keepalive.rs @@ -2,6 +2,7 @@ use std::net::Ipv4Addr; use std::time::Duration; use crate::vendor::netem::NetemConfig; +use crate::vendor::str0m::media::{Direction, MediaKind}; use crate::vendor::str0m::{Event, IceConnectionState, RtcError}; use super::common; @@ -31,7 +32,7 @@ pub fn pair_kept_alive_by_remote_binding_requests() -> Result<(), RtcError> { r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); let mut change = l.sdp_api(); - change.add_channel("ch".into()); + change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer, pending) = change.apply().unwrap(); let answer = r.sdp_api().accept_offer(offer)?; l.sdp_api().accept_answer(pending, answer)?; diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/ice-restart.rs b/rs/moq-webrtc/src/vendor/str0m/tests/ice-restart.rs index 427e9903940..40b012f3697 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/ice-restart.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/ice-restart.rs @@ -3,6 +3,7 @@ use std::time::{Duration, Instant}; use crate::vendor::str0m::RtcConfig; use crate::vendor::str0m::RtcError; +use crate::vendor::str0m::media::{Direction, MediaKind}; use tracing::info_span; use super::common; @@ -23,7 +24,7 @@ pub fn ice_restart() -> Result<(), RtcError> { let (offer, pending) = l.span.in_scope(|| { let mut change = l.rtc.sdp_api(); - let _ = change.add_channel("My little channel".into()); + let _ = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); change.apply().unwrap() }); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/mod.rs b/rs/moq-webrtc/src/vendor/str0m/tests/mod.rs index 8cf71433c6c..26a6547ea85 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/mod.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/mod.rs @@ -15,10 +15,6 @@ mod config_validation; mod contiguous; #[path = "crypto-compliance.rs"] mod crypto_compliance; -#[path = "data-channel.rs"] -mod data_channel; -#[path = "data-channel-direct.rs"] -mod data_channel_direct; mod dlrr; #[path = "dtls-close.rs"] mod dtls_close; @@ -34,8 +30,6 @@ mod dtls_security; mod early_rtx_padding; #[path = "flappy-ice-state.rs"] mod flappy_ice_state; -#[path = "handshake-direct.rs"] -mod handshake_direct; #[path = "ice-candidates.rs"] mod ice_candidates; #[path = "ice-lite-connectivity.rs"] @@ -63,8 +57,6 @@ mod network_conditions; mod no_local_media_added; #[path = "no-pre-ice-feedback.rs"] mod no_pre_ice_feedback; -#[path = "partial-init.rs"] -mod partial_init; #[path = "pli-feedback.rs"] mod pli_feedback; #[path = "poll-scaling.rs"] diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/mtu-compliance.rs b/rs/moq-webrtc/src/vendor/str0m/tests/mtu-compliance.rs index b50490e5836..23aeab22b16 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/mtu-compliance.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/mtu-compliance.rs @@ -8,7 +8,7 @@ use crate::vendor::str0m::{DATAGRAM_MTU_TARGET_MAX, DATAGRAM_MTU_TARGET_MIN, Eve use super::common; use common::{Peer, TestRtc, init_crypto_default, init_log, progress_strict_mtu}; -/// End-to-end MTU compliance: walk a full ICE/DTLS/SCTP/SRTP session and +/// End-to-end MTU compliance: walk a full ICE/DTLS/SRTP session and /// assert every outgoing datagram on either side has `len() <= mtu`. The /// check fires inside the test pump via [`progress_strict_mtu`], so any /// oversized datagram fails the test at the source. @@ -26,10 +26,8 @@ fn run_mtu_compliance(mtu: usize) -> Result<(), RtcError> { l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - // Add an audio m-line and a data channel in the same offer. let mut change = l.sdp_api(); let audio_mid = change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); - let cid = change.add_channel("mtu-test".into()); let (offer, pending) = change.apply().unwrap(); let answer = r.rtc.sdp_api().accept_offer(offer)?; l.rtc.sdp_api().accept_answer(pending, answer)?; @@ -46,21 +44,6 @@ fn run_mtu_compliance(mtu: usize) -> Result<(), RtcError> { l.last = max; r.last = max; - // Wait for the data channel to open on L. - while l.channel(cid).is_none() { - progress_strict_mtu(&mut l, &mut r, mtu)?; - } - - // Small data-channel send. - l.channel(cid) - .unwrap() - .write(false, b"hello mtu world") - .expect("small write"); - - // Large data-channel send to exercise SCTP fragmentation. - let big = vec![0xCDu8; 32 * 1024]; - l.channel(cid).unwrap().write(true, &big).expect("large write"); - // Audio writes (Opus) at typical 20 ms cadence. let params = l.params_opus(); assert_eq!(params.spec().codec, Codec::Opus); @@ -77,15 +60,15 @@ fn run_mtu_compliance(mtu: usize) -> Result<(), RtcError> { progress_strict_mtu(&mut l, &mut r, mtu)?; } - // Sanity: r received the small + part of the large data-channel send. - let chan_events = r + // Sanity: r received the audio. + let media_events = r .events .iter() - .filter(|(_, e)| matches!(e, Event::ChannelData(_))) + .filter(|(_, e)| matches!(e, Event::MediaData(_))) .count(); assert!( - chan_events >= 1, - "expected at least one ChannelData event at r, got {chan_events}" + media_events >= 1, + "expected at least one MediaData event at r, got {media_events}" ); Ok(()) diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/partial-init.rs b/rs/moq-webrtc/src/vendor/str0m/tests/partial-init.rs deleted file mode 100644 index 185bedce5c3..00000000000 --- a/rs/moq-webrtc/src/vendor/str0m/tests/partial-init.rs +++ /dev/null @@ -1,19 +0,0 @@ -use std::time::Instant; - -use crate::vendor::str0m::{Output, Rtc, RtcError}; - -/// Regression test for a panic when SCTP was started and attempted to transmit data before DTLS was started. -#[test] -pub fn sctp_without_dtls() -> Result<(), RtcError> { - let mut rtc = Rtc::new(Instant::now()); - - rtc.direct_api().start_sctp(true); - loop { - // Internally, SCTP is polled for output and returns a `Transmit`, which is passed to DTLS. - if matches!(rtc.poll_output()?, Output::Timeout(_)) { - break; - } - } - - Ok(()) -} diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-negotiation.rs b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-negotiation.rs index 036e2b8201f..15105c0a05d 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-negotiation.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-negotiation.rs @@ -20,7 +20,6 @@ use common::init_crypto_default; use common::init_log; use common::negotiate; use common::progress; -use common::{extract_sctp_init, remove_sctp_init, replace_sctp_init}; use tracing::Span; use tracing::info_span; @@ -807,565 +806,6 @@ fn answer_msid_is_not_taken_from_the_offer() { ); } -// --------------------------------------------------------------------------- -// SNAP (SCTP Negotiation Acceleration Protocol) tests -// --------------------------------------------------------------------------- - -/// Both sides enable SNAP - offer and answer must contain `a=sctp-init`, -/// and a data-channel message round-trips successfully. -#[test] -fn snap_sdp_both_sides_enabled() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().set_snap_enabled(true).build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Manual offer/answer so we can inspect the SDP. - let mut change = l.sdp_api(); - let cid = change.add_channel("snap-test".into()); - let (offer, pending) = change.apply().unwrap(); - - let offer_sdp = offer.to_sdp_string(); - assert!( - extract_sctp_init(&offer_sdp).is_some(), - "Offer must contain a=sctp-init when SNAP is enabled" - ); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - let answer_sdp = answer.to_sdp_string(); - assert!( - extract_sctp_init(&answer_sdp).is_some(), - "Answer must contain a=sctp-init when both sides enable SNAP" - ); - - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Drive to connected. - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // Send a data-channel message and verify receipt. - l.channel(cid).unwrap().write(false, b"hello-snap").unwrap(); - - for _ in 0..200 { - progress(&mut l, &mut r)?; - } - - let received = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == b"hello-snap")); - assert!(received, "Right side must receive data-channel message"); - - Ok(()) -} - -/// Only the offerer enables SNAP. The answerer should reciprocate by including -/// `a=sctp-init` in its answer (per the draft, an endpoint that receives -/// `a=sctp-init` should respond with one). -#[test] -fn snap_sdp_offerer_only_enabled() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc( - info_span!("R"), - Rtc::builder().build(now), // SNAP not explicitly enabled - ); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("snap-offerer-only".into()); - let (offer, pending) = change.apply().unwrap(); - - let offer_sdp = offer.to_sdp_string(); - assert!( - extract_sctp_init(&offer_sdp).is_some(), - "Offer must contain a=sctp-init" - ); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - let answer_sdp = answer.to_sdp_string(); - assert!( - extract_sctp_init(&answer_sdp).is_some(), - "Answerer should reciprocate a=sctp-init even without snap_enabled" - ); - - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Drive to connected and verify data channel works. - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - l.channel(cid).unwrap().write(false, b"offerer-snap").unwrap(); - - for _ in 0..200 { - progress(&mut l, &mut r)?; - } - - let received = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == b"offerer-snap")); - assert!(received, "Data channel must work with offerer-only SNAP"); - - Ok(()) -} - -#[test] -fn snap_sdp_missing_answer_falls_back_to_regular_handshake() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().set_snap_enabled(true).build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("snap-fallback".into()); - let (offer, pending) = change.apply().unwrap(); - let offer_sdp = offer.to_sdp_string(); - - assert!( - extract_sctp_init(&offer_sdp).is_some(), - "Offer must contain a=sctp-init" - ); - - let stripped_offer = remove_sctp_init(&offer_sdp); - let stripped_offer = SdpOffer::from_sdp_string(&stripped_offer).unwrap(); - - let answer = r.rtc.sdp_api().accept_offer(stripped_offer)?; - let answer_sdp = answer.to_sdp_string(); - assert!( - extract_sctp_init(&answer_sdp).is_none(), - "Answer must omit a=sctp-init when the remote does not negotiate SNAP" - ); - - l.rtc.sdp_api().accept_answer(pending, answer)?; - - let mut ready = false; - for _ in 0..200 { - if l.is_connected() && r.is_connected() && l.channel(cid).is_some() { - ready = true; - break; - } - progress(&mut l, &mut r)?; - } - - assert!( - ready, - "Fallback path must establish both peers and the local data channel" - ); - - l.channel(cid) - .expect("local channel to exist after fallback") - .write(false, b"snap-fallback-msg") - .unwrap(); - - for _ in 0..200 { - progress(&mut l, &mut r)?; - } - - let received = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == b"snap-fallback-msg")); - assert!(received, "Data channel must work after SNAP falls back to regular SCTP"); - - Ok(()) -} - -/// Neither side enables SNAP - SDP must NOT contain `a=sctp-init`, and the -/// normal SCTP 4-way handshake is used instead. -#[test] -fn snap_sdp_neither_enabled() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("no-snap".into()); - let (offer, pending) = change.apply().unwrap(); - - let offer_sdp = offer.to_sdp_string(); - assert!( - extract_sctp_init(&offer_sdp).is_none(), - "Offer must NOT contain a=sctp-init when SNAP is disabled" - ); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - let answer_sdp = answer.to_sdp_string(); - assert!( - extract_sctp_init(&answer_sdp).is_none(), - "Answer must NOT contain a=sctp-init when SNAP is disabled" - ); - - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Normal handshake should still work. - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - l.channel(cid).unwrap().write(false, b"no-snap-msg").unwrap(); - - for _ in 0..200 { - progress(&mut l, &mut r)?; - } - - let received = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == b"no-snap-msg")); - assert!(received, "Data channel must work without SNAP"); - - Ok(()) -} - -/// Section 5.6: Re-offer after SNAP establishment must re-send the same `a=sctp-init` -/// values. Verify that a re-negotiation preserves the cached `sctp-init` and -/// the data channel keeps working. -#[test] -fn snap_sdp_renegotiation_preserves_sctp_init() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().set_snap_enabled(true).build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Initial offer/answer with SNAP. - let mut change = l.sdp_api(); - let cid = change.add_channel("snap-renego".into()); - let (offer, pending) = change.apply().unwrap(); - - let initial_offer_init = extract_sctp_init(&offer.to_sdp_string()).expect("Initial offer must contain a=sctp-init"); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - let initial_answer_init = - extract_sctp_init(&answer.to_sdp_string()).expect("Initial answer must contain a=sctp-init"); - - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Drive to connected. - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // Send a message before re-negotiation. - l.channel(cid).unwrap().write(false, b"before-renego").unwrap(); - for _ in 0..100 { - progress(&mut l, &mut r)?; - } - - // Re-offer: add a video track to trigger re-negotiation. - let mut change = l.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - let (re_offer, re_pending) = change.apply().unwrap(); - - let re_offer_init = extract_sctp_init(&re_offer.to_sdp_string()); - assert_eq!( - re_offer_init.as_deref(), - Some(initial_offer_init.as_str()), - "Re-offer must contain the same a=sctp-init as the initial offer (Section 5.6)" - ); - - let re_answer = r.rtc.sdp_api().accept_offer(re_offer)?; - let re_answer_init = extract_sctp_init(&re_answer.to_sdp_string()); - assert_eq!( - re_answer_init.as_deref(), - Some(initial_answer_init.as_str()), - "Re-answer must contain the same a=sctp-init as the initial answer (Section 5.6)" - ); - - l.rtc.sdp_api().accept_answer(re_pending, re_answer)?; - - // Verify data channel still works after re-negotiation. - l.channel(cid).unwrap().write(false, b"after-renego").unwrap(); - for _ in 0..200 { - progress(&mut l, &mut r)?; - } - - let received_after = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == b"after-renego")); - assert!(received_after, "Data channel must survive re-negotiation with SNAP"); - - Ok(()) -} - -#[test] -fn snap_sdp_renegotiation_changed_sctp_init_rejected() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().set_snap_enabled(true).build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - change.add_channel("snap-change-reject".into()); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - let (re_offer, _re_pending) = change.apply().unwrap(); - - let re_offer_sdp = re_offer.to_sdp_string(); - let tampered = replace_sctp_init(&re_offer_sdp, "AQ=="); - let tampered_offer = SdpOffer::from_sdp_string(&tampered).unwrap(); - - let err = r.rtc.sdp_api().accept_offer(tampered_offer).unwrap_err(); - assert!( - err.to_string() - .contains("Changed a=sctp-init for existing SCTP association"), - "unexpected error: {err}" - ); - - Ok(()) -} - -#[test] -fn snap_sdp_renegotiation_missing_sctp_init_rejected() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().set_snap_enabled(true).build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - change.add_channel("snap-missing-reject".into()); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - let mut change = l.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - let (re_offer, re_pending) = change.apply().unwrap(); - - let re_answer = r.rtc.sdp_api().accept_offer(re_offer)?; - let re_answer_sdp = re_answer.to_sdp_string(); - let tampered = remove_sctp_init(&re_answer_sdp); - let tampered_answer = crate::vendor::str0m::change::SdpAnswer::from_sdp_string(&tampered).unwrap(); - - let err = l.rtc.sdp_api().accept_answer(re_pending, tampered_answer).unwrap_err(); - assert!( - err.to_string() - .contains("Missing a=sctp-init for established SNAP SCTP association"), - "unexpected error: {err}" - ); - - Ok(()) -} - -/// Only the answerer enables SNAP - the offer has no `a=sctp-init`, so the -/// answerer must NOT inject one either. Normal 4-way handshake is used. -#[test] -fn snap_sdp_answerer_only_enabled() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc( - info_span!("L"), - Rtc::builder().build(now), // SNAP disabled - ); - let mut r = TestRtc::new_with_rtc( - info_span!("R"), - Rtc::builder().set_snap_enabled(true).build(now), // SNAP enabled - ); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let cid = change.add_channel("answerer-only".into()); - let (offer, pending) = change.apply().unwrap(); - - let offer_sdp = offer.to_sdp_string(); - assert!( - extract_sctp_init(&offer_sdp).is_none(), - "Offer must NOT contain a=sctp-init when offerer has SNAP disabled" - ); - - let answer = r.rtc.sdp_api().accept_offer(offer)?; - let answer_sdp = answer.to_sdp_string(); - assert!( - extract_sctp_init(&answer_sdp).is_none(), - "Answer must NOT contain a=sctp-init when the offer didn't include one" - ); - - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Normal handshake should work. - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - l.channel(cid).unwrap().write(false, b"answerer-only-msg").unwrap(); - - for _ in 0..200 { - progress(&mut l, &mut r)?; - } - - let received = r - .events - .iter() - .any(|(_, e)| matches!(e, Event::ChannelData(data) if data.data == b"answerer-only-msg")); - assert!(received, "Data channel must work when only answerer has SNAP enabled"); - - Ok(()) -} - -/// Malformed base64 in `a=sctp-init` is silently ignored by the SDP parser -/// (treated as an unknown attribute). The answerer should proceed without SNAP. -#[test] -fn snap_sdp_malformed_base64_ignored() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().set_snap_enabled(true).build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - let mut change = l.sdp_api(); - let _cid = change.add_channel("bad-b64".into()); - let (offer, _pending) = change.apply().unwrap(); - - let offer_sdp = offer.to_sdp_string(); - // Replace the valid base64 with garbage - it's parsed as a string, but fails - // to decode at runtime, causing SNAP to gracefully degrade. - let tampered = replace_sctp_init(&offer_sdp, "!!!not-valid-base64!!!"); - let tampered_offer = SdpOffer::from_sdp_string(&tampered).unwrap(); - - // The answerer should NOT reciprocate since the sctp-init failed to decode. - let answer = r.rtc.sdp_api().accept_offer(tampered_offer)?; - let answer_sdp = answer.to_sdp_string(); - assert!( - extract_sctp_init(&answer_sdp).is_none(), - "Answer must NOT contain a=sctp-init when the offer's was malformed" - ); - - Ok(()) -} - -/// Reverse direction: R re-offers with a tampered `a=sctp-init` and L -/// (the original offerer) rejects it when processing the answer. -#[test] -fn snap_sdp_renegotiation_reverse_direction_changed_sctp_init_rejected() -> Result<(), RtcError> { - init_log(); - init_crypto_default(); - - let now = Instant::now(); - let mut l = TestRtc::new_with_rtc(info_span!("L"), Rtc::builder().set_snap_enabled(true).build(now)); - let mut r = TestRtc::new_with_rtc(info_span!("R"), Rtc::builder().set_snap_enabled(true).build(now)); - - l.add_host_candidate((Ipv4Addr::new(1, 1, 1, 1), 1000).into()); - r.add_host_candidate((Ipv4Addr::new(2, 2, 2, 2), 2000).into()); - - // Initial offer/answer from L -> R. - let mut change = l.sdp_api(); - change.add_channel("snap-reverse".into()); - let (offer, pending) = change.apply().unwrap(); - let answer = r.rtc.sdp_api().accept_offer(offer)?; - l.rtc.sdp_api().accept_answer(pending, answer)?; - - // Drive to connected. - for _ in 0..1000 { - if l.is_connected() && r.is_connected() { - break; - } - progress(&mut l, &mut r)?; - } - - // R re-offers (reverse direction). - let mut change = r.sdp_api(); - change.add_media(MediaKind::Video, Direction::SendRecv, None, None, None); - let (re_offer, re_pending) = change.apply().unwrap(); - - // L answers the re-offer normally. - let re_answer = l.rtc.sdp_api().accept_offer(re_offer)?; - - // Tamper with the answer's sctp-init before R processes it. - let re_answer_sdp = re_answer.to_sdp_string(); - let tampered = replace_sctp_init(&re_answer_sdp, "AQ=="); - let tampered_answer = crate::vendor::str0m::change::SdpAnswer::from_sdp_string(&tampered).unwrap(); - - let err = r.rtc.sdp_api().accept_answer(re_pending, tampered_answer).unwrap_err(); - assert!( - err.to_string() - .contains("Changed a=sctp-init for existing SCTP association"), - "unexpected error: {err}" - ); - - Ok(()) -} - fn with_params( span_l: Span, params_l: &[PayloadParams], diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-unique-mids.rs b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-unique-mids.rs index 47cb64d8075..4d3deed2030 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/sdp-unique-mids.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/sdp-unique-mids.rs @@ -35,25 +35,6 @@ fn add_audio(change: &mut SdpApi) -> Mid { change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None) } -#[test] -pub fn media_and_channel_in_one_offer_get_distinct_mids() { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - let mids = offer(&mut l, &mut r, |change| { - let expected = repeat_next_mid(); - assert_eq!(add_audio(change), expected); - repeat_next_mid(); - change.add_channel("data".into()); - }); - - assert_eq!(mids.len(), 2); - assert_ne!(mids[0], mids[1]); -} - #[test] pub fn two_media_in_one_offer_get_distinct_mids() { init_log(); @@ -76,31 +57,6 @@ pub fn two_media_in_one_offer_get_distinct_mids() { assert!(r.rtc.media(added[1]).is_some()); } -#[test] -pub fn media_offered_after_channel_avoids_its_mid() { - init_log(); - init_crypto_default(); - - let mut l = TestRtc::new(Peer::Left); - let mut r = TestRtc::new(Peer::Right); - - let channel_mid = repeat_next_mid(); - negotiate(&mut l, &mut r, |change| { - change.add_channel("data".into()); - }); - - let mut audio = None; - let mids = offer(&mut l, &mut r, |change| { - repeat_next_mid(); - audio = Some(add_audio(change)); - }); - - let audio = audio.unwrap(); - assert_ne!(audio, channel_mid); - assert_eq!(mids, [channel_mid.to_string(), audio.to_string()]); - assert!(r.rtc.media(audio).is_some()); -} - fn share_first_mid(sdp: &str) -> (String, String) { let mids: Vec<&str> = sdp .lines() @@ -134,7 +90,7 @@ pub fn offer_with_duplicate_mids_is_rejected() { let mut change = l.rtc.sdp_api(); add_audio(&mut change); - change.add_channel("data".into()); + add_audio(&mut change); let (offer, _pending) = change.apply().unwrap(); let (sdp, mid) = share_first_mid(&offer.to_sdp_string()); @@ -154,7 +110,7 @@ pub fn answer_with_duplicate_mids_is_rejected() { let mut change = l.rtc.sdp_api(); let audio = add_audio(&mut change); - change.add_channel("data".into()); + add_audio(&mut change); let (offer, pending) = change.apply().unwrap(); let answer = r.rtc.sdp_api().accept_offer(offer).unwrap(); diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/simulcast-rid-mapping.rs b/rs/moq-webrtc/src/vendor/str0m/tests/simulcast-rid-mapping.rs index 46efe1cb4f3..f8d653009c0 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/simulcast-rid-mapping.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/simulcast-rid-mapping.rs @@ -263,7 +263,7 @@ fn assert_all_rids_mapped( } Signalling::Renegotiated { glare } => { let mut change = l.sdp_api(); - change.add_channel("signaling".into()); + change.add_media(MediaKind::Audio, Direction::SendRecv, None, None, None); let (offer, pending) = change.apply().unwrap(); let answer = r.rtc.sdp_api().accept_offer(offer)?; l.rtc.sdp_api().accept_answer(pending, answer)?; diff --git a/rs/moq-webrtc/src/vendor/str0m/tests/stale-network-time-after-pause.rs b/rs/moq-webrtc/src/vendor/str0m/tests/stale-network-time-after-pause.rs index 2076b9d5dbe..7c85f5b6da6 100644 --- a/rs/moq-webrtc/src/vendor/str0m/tests/stale-network-time-after-pause.rs +++ b/rs/moq-webrtc/src/vendor/str0m/tests/stale-network-time-after-pause.rs @@ -41,8 +41,6 @@ fn connect_direct() -> Result<(TestRtc, TestRtc), RtcError> { l.direct_api().start_dtls(true)?; r.direct_api().start_dtls(false)?; - l.direct_api().start_sctp(true); - r.direct_api().start_sctp(false); while !l.is_connected() || !r.is_connected() { progress(&mut l, &mut r)?; diff --git a/rs/workspace-hack/Cargo.toml b/rs/workspace-hack/Cargo.toml index 361ef843c47..478af714887 100644 --- a/rs/workspace-hack/Cargo.toml +++ b/rs/workspace-hack/Cargo.toml @@ -27,7 +27,6 @@ publish = false anyhow = { version = "1", features = ["backtrace"] } base64 = { version = "0.23" } bytemuck = { version = "1", default-features = false, features = ["derive", "extern_crate_alloc", "min_const_generics"] } -byteorder = { version = "1" } bytes = { version = "1", features = ["serde"] } camino = { version = "1", default-features = false, features = ["serde1"] } chrono = { version = "0.4", features = ["serde"] } @@ -54,13 +53,11 @@ futures-task = { version = "0.3", default-features = false, features = ["std"] } futures-util = { version = "0.3", features = ["channel", "io", "sink"] } hashbrown = { version = "0.17", default-features = false, features = ["default-hasher", "inline-more"] } hex = { version = "0.4" } -hmac = { version = "0.12", default-features = false, features = ["reset"] } hyper = { version = "1", features = ["full"] } hyper-util = { version = "0.1", features = ["server-auto", "service", "tokio"] } indexmap = { version = "2", features = ["serde"] } log = { version = "0.4", default-features = false, features = ["std"] } -md-5-93f6ce9d446188ac = { package = "md-5", version = "0.10" } -md-5-a6292c17cd707f01 = { package = "md-5", version = "0.11" } +md-5 = { version = "0.11" } memchr = { version = "2" } mio = { version = "1", features = ["net", "os-ext"] } nom-181b0d20215bb231 = { package = "nom", version = "8" } @@ -84,7 +81,6 @@ serde_core = { version = "1", features = ["alloc", "rc"] } serde_json = { version = "1", features = ["float_roundtrip", "preserve_order", "raw_value", "unbounded_depth"] } serde_spanned = { version = "1", default-features = false, features = ["serde", "std"] } serde_with = { version = "3", features = ["base64", "hex", "json"] } -sha2 = { version = "0.10" } siphasher = { version = "1" } slab = { version = "0.4" } smallvec = { version = "1", default-features = false, features = ["const_new", "union", "write"] } @@ -113,7 +109,6 @@ zeroize = { version = "1", features = ["derive"] } anyhow = { version = "1", features = ["backtrace"] } base64 = { version = "0.23" } bytemuck = { version = "1", default-features = false, features = ["derive", "extern_crate_alloc", "min_const_generics"] } -byteorder = { version = "1" } bytes = { version = "1", features = ["serde"] } camino = { version = "1", default-features = false, features = ["serde1"] } cc = { version = "1", default-features = false, features = ["parallel"] } @@ -143,13 +138,11 @@ futures-task = { version = "0.3", default-features = false, features = ["std"] } futures-util = { version = "0.3", features = ["channel", "io", "sink"] } hashbrown = { version = "0.17", default-features = false, features = ["default-hasher", "inline-more"] } hex = { version = "0.4" } -hmac = { version = "0.12", default-features = false, features = ["reset"] } hyper = { version = "1", features = ["full"] } hyper-util = { version = "0.1", features = ["server-auto", "service", "tokio"] } indexmap = { version = "2", features = ["serde"] } log = { version = "0.4", default-features = false, features = ["std"] } -md-5-93f6ce9d446188ac = { package = "md-5", version = "0.10" } -md-5-a6292c17cd707f01 = { package = "md-5", version = "0.11" } +md-5 = { version = "0.11" } memchr = { version = "2" } mio = { version = "1", features = ["net", "os-ext"] } nom-181b0d20215bb231 = { package = "nom", version = "8" } @@ -175,7 +168,6 @@ serde_core = { version = "1", features = ["alloc", "rc"] } serde_json = { version = "1", features = ["float_roundtrip", "preserve_order", "raw_value", "unbounded_depth"] } serde_spanned = { version = "1", default-features = false, features = ["serde", "std"] } serde_with = { version = "3", features = ["base64", "hex", "json"] } -sha2 = { version = "0.10" } siphasher = { version = "1" } slab = { version = "0.4" } smallvec = { version = "1", default-features = false, features = ["const_new", "union", "write"] } diff --git a/sh/gh/nightly.sh b/sh/gh/nightly.sh index bee2cd79b60..ab99a75f200 100755 --- a/sh/gh/nightly.sh +++ b/sh/gh/nightly.sh @@ -109,7 +109,7 @@ case "$1" in nextest just rs bench-tests --no-fail-fast --run-ignored only \ -p moq-audio -p moq-mux -p moq-c -p moq-relay -p moq-cli -p moq-ffi \ --features moq-audio/playback --lib --bin moq \ - -E 'test(benchmark_mixer_callbacks) | test(benchmark_resampler) | test(benchmark_raw_audio) | test(benchmark_damage_pid_fanout) | test(benchmark_pes_staging) | test(benchmark_handles) | test(benchmark_stun_sources) | test(benchmark_stream_import) | test(benchmark_timebase_reservation_fanout)' + -E 'test(benchmark_mixer_callbacks) | test(benchmark_resampler) | test(benchmark_raw_audio) | test(benchmark_damage_pid_fanout) | test(benchmark_pes_staging) | test(benchmark_handles) | test(benchmark_stream_import) | test(benchmark_timebase_reservation_fanout)' ;; # Measured Cargo bench targets, all in the bench profile. A paired run builds and # measures each group twice, so the groups split across jobs to fit an hour each. @@ -169,7 +169,6 @@ case "$1" in javascript qmux-record just js qmux-record-bench javascript qmux-datagrams just js qmux-datagrams-bench javascript cmaf just js cmaf-bench - javascript p2p just js p2p-bench javascript e2ee just js e2ee-bench javascript json-stream just js json-stream-bench javascript signals just js signals-bench diff --git a/sh/rs/select.sh b/sh/rs/select.sh index c45df0449c5..0c30ba2997e 100755 --- a/sh/rs/select.sh +++ b/sh/rs/select.sh @@ -203,8 +203,6 @@ case "$action" in features+=(moq-video/capture moq-audio/capture moq-audio/playback) fi if wants moq-cli; then features+=(moq-cli/play moq-cli/openh264); fi - # The WebRTC data channel's hostile-input tests, such as mDNS backpressure. - if wants moq-webrtc; then features+=(moq-webrtc/p2p); fi # The relay's io_uring listener, Linux-only. A moq-uring change selects # the relay too, as its dependent. if [[ "$(uname -s)" == Linux ]] && wants moq-relay; then features+=(moq-relay/io-uring); fi diff --git a/sh/rs/select.test.py b/sh/rs/select.test.py index 405aacbfc86..0d143278f0a 100644 --- a/sh/rs/select.test.py +++ b/sh/rs/select.test.py @@ -73,7 +73,7 @@ def selected(self, *paths, action="lint", github_actions=False): return calls.read_text().splitlines() if calls.exists() else [] def test_nextest_launcher_selects_workspace(self): - features = [*DEVICE_FEATURES.split(), "moq-webrtc/p2p", *(["moq-relay/io-uring"] if LINUX else [])] + features = [*DEVICE_FEATURES.split(), *(["moq-relay/io-uring"] if LINUX else [])] features += [feature for feature in target_features() if feature not in features] for github_actions in (False, True): for action in ("check", "check-test", "lint", "test"): @@ -176,13 +176,6 @@ def test_device_features_join_the_one_test_build(self): self.assertEqual(len(calls), 1, calls) # The targets' required features follow the device ones. self.assertIn(f" --features {features}", calls[0]) - # moq-webrtc's data channel transport is off by default too. - calls = self.selected("rs/moq-webrtc/src/p2p/mod.rs", action="test") - self.assertEqual(len(calls), 1, calls) - self.assertIn(" moq-webrtc/p2p", calls[0]) - # So is a change to qmux, which only that optional feature pulls in. - calls = self.selected("rs/qmux/src/lib.rs", action="test") - self.assertTrue(any(" moq-webrtc/p2p" in call for call in calls), calls) # A dependency of the media crates still runs both their device tests. calls = self.selected("rs/moq-audio/src/lib.rs", action="test") self.assertIn("--package moq-video --package moq-audio", calls[0]) diff --git a/test/justfile b/test/justfile index 23bb2a28c40..070c538f528 100644 --- a/test/justfile +++ b/test/justfile @@ -323,8 +323,3 @@ qmux: cargo build --locked --quiet --manifest-path ../rs/qmux/Cargo.toml --example interop-server --example interop-client uv run --no-project python ../sh/js/install.py frozen cd .. && QMUX_INTEROP_BIN={{ quote(qmux_examples) }} bun test ./test/qmux/interop.test.ts - -# Complete MoQ SETUP and transfer a frame over a real browser data-channel pair. -p2p: - uv run --no-project python ../sh/js/install.py frozen - cd p2p && bash ../../sh/local.sh bun test ./transport.browser.ts diff --git a/test/p2p/index.html b/test/p2p/index.html deleted file mode 100644 index 51f28a623eb..00000000000 --- a/test/p2p/index.html +++ /dev/null @@ -1,2 +0,0 @@ - -MoQ P2P transport test diff --git a/test/p2p/package.json b/test/p2p/package.json deleted file mode 100644 index 17af5584104..00000000000 --- a/test/p2p/package.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "name": "@moq/p2p-test", - "private": true, - "type": "module", - "scripts": { - "check": "tsc --noEmit" - }, - "dependencies": { - "@moq/net": "workspace:*", - "@moq/p2p": "workspace:*" - }, - "devDependencies": { - "@types/bun": "^1.4.4", - "@typescript/lib-dom": "npm:@types/web@^0.0.358", - "playwright": "1.64.1", - "typescript": "7.0.2", - "vite": "^8.3.6" - } -} diff --git a/test/p2p/src/main.ts b/test/p2p/src/main.ts deleted file mode 100644 index 317f35209b0..00000000000 --- a/test/p2p/src/main.ts +++ /dev/null @@ -1,125 +0,0 @@ -import * as Moq from "@moq/net"; -import { Transport } from "@moq/p2p"; - -export interface Report { - client: string; - server: string; - version: string; - bytes: number; - /** The subscriber's close error, or null for a clean close. */ - closed: string | null; - peerStates: string[]; -} - -declare global { - interface Window { - checkTransport(): Promise; - } -} - -async function gathered(peer: RTCPeerConnection) { - if (peer.iceGatheringState === "complete") return; - await new Promise((resolve) => { - const changed = () => { - if (peer.iceGatheringState !== "complete") return; - peer.removeEventListener("icegatheringstatechange", changed); - resolve(); - }; - peer.addEventListener("icegatheringstatechange", changed); - changed(); - }); -} - -window.checkTransport = async () => { - const left = new RTCPeerConnection({ iceServers: [] }); - const right = new RTCPeerConnection({ iceServers: [] }); - const protocol = "moq-lite-07-wip"; - const transport = Transport.connect({ peer: left, protocol }); - const incoming = new Promise((resolve, reject) => { - right.addEventListener( - "datachannel", - ({ channel }) => { - try { - resolve(Transport.accept({ peer: right, channel, protocol })); - } catch (error) { - channel.close(); - reject(error); - } - }, - { once: true }, - ); - }); - const publishing = new Moq.Origin.Producer(); - const consuming = new Moq.Origin.Producer(); - const path = Moq.Path.from("peer/data"); - const broadcastRoute = publishing.route(path); - const broadcast = broadcastRoute.broadcast; - const track = broadcast.createTrack("data", { timescale: Moq.Time.Timescale.MILLI }); - let client: Awaited> | undefined; - let server: Awaited> | undefined; - try { - await left.setLocalDescription(await left.createOffer()); - await gathered(left); - if (!left.localDescription) throw new Error("missing offer"); - await right.setRemoteDescription(left.localDescription); - await right.setLocalDescription(await right.createAnswer()); - await gathered(right); - if (!right.localDescription) throw new Error("missing answer"); - await left.setRemoteDescription(right.localDescription); - const accepted = await incoming; - const url = new URL("https://peer.invalid/"); - [client, server] = await Promise.all([ - Moq.Connection.connect({ url, transport, consume: consuming }), - Moq.Connection.accept({ url, transport: accepted, publish: publishing.consume() }), - ]); - const request = consuming.request(path); - try { - while (!request.active.peek()) await request.active.changed(); - const active = request.active.peek(); - if (!active) throw new Error("broadcast disappeared"); - const subscriber = active.track("data").subscribe().ordered(); - try { - const demand = track.demand().wanted; - while (demand.peek() === undefined) await demand.changed(); - const payload = Uint8Array.from({ length: 256 * 1024 }, (_, i) => i % 251); - track.writeFrame({ payload, timestamp: Moq.Time.Timestamp.now() }); - const frame = await subscriber.readFrame(); - if ( - !frame || - frame.payload.byteLength !== payload.byteLength || - frame.payload.some((value, i) => value !== payload[i]) - ) { - throw new Error("data-channel frame payload changed"); - } - subscriber.close(); - // Closing both ends at once makes the publisher's drain race the subscriber's - // close, so the publisher closes and the subscriber observes its clean close. - await server.close(); - const closed = await client.closed; - return { - client: client.transport, - server: server.transport, - version: client.version, - bytes: frame.payload.byteLength, - closed: closed?.message ?? null, - peerStates: [left.signalingState, right.signalingState], - }; - } finally { - subscriber.close(); - } - } finally { - request.close(); - } - } finally { - client?.abort(); - server?.abort(); - transport.close(); - track.finish(); - track.close(); - broadcast.close(); - publishing.close(); - consuming.close(); - left.close(); - right.close(); - } -}; diff --git a/test/p2p/transport.browser.ts b/test/p2p/transport.browser.ts deleted file mode 100644 index d03e8102e1c..00000000000 --- a/test/p2p/transport.browser.ts +++ /dev/null @@ -1,57 +0,0 @@ -/** Real RTCDataChannel SETUP and media transfer through the public MoQ API. @module */ -import { afterAll, beforeAll, expect, test } from "bun:test"; -import { mkdtempSync, rmSync } from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { type Browser, chromium } from "playwright"; -import { build } from "vite"; -import type { Report } from "./src/main.ts"; - -let dist: string; -let server: ReturnType; -let browser: Browser; - -beforeAll(async () => { - dist = mkdtempSync(join(tmpdir(), "moq-p2p-")); - await build({ - configFile: false, - root: import.meta.dir, - logLevel: "warn", - build: { target: "esnext", outDir: dist, emptyOutDir: true }, - }); - server = Bun.serve({ - port: 0, - hostname: "127.0.0.1", - async fetch(req) { - const path = new URL(req.url).pathname; - const file = Bun.file(join(dist, path === "/" ? "index.html" : path)); - return (await file.exists()) ? new Response(file) : new Response("not found", { status: 404 }); - }, - }); - browser = await chromium.launch({ channel: "chromium", headless: true }); -}, 120_000); - -afterAll(async () => { - await browser?.close(); - server?.stop(); - if (dist) rmSync(dist, { recursive: true, force: true }); -}); - -test("two peer connections complete MoQ SETUP and transfer a frame without a relay", async () => { - const page = await browser.newPage(); - const errors: string[] = []; - page.on("pageerror", (error) => errors.push(error.message)); - try { - await page.goto(`http://127.0.0.1:${server.port}/`); - const report: Report = await page.evaluate(() => window.checkTransport()); - expect(report.client).toBe("webrtc"); - expect(report.server).toBe("webrtc"); - expect(report.version).toBe("moq-lite-07-wip"); - expect(report.bytes).toBe(256 * 1024); - expect(report.closed).toBeNull(); - expect(report.peerStates).toEqual(["stable", "stable"]); - expect(errors).toEqual([]); - } finally { - await page.close(); - } -}, 60_000); diff --git a/test/p2p/tsconfig.json b/test/p2p/tsconfig.json deleted file mode 100644 index 60699cb84ee..00000000000 --- a/test/p2p/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../../js/tsconfig.json", - "compilerOptions": { "types": ["bun", "vite/client"], "noEmit": true }, - "include": ["transport.browser.ts", "src"] -} From 7185e13366c861262bab4909975563ae26b0c5a2 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 14 Nov 2026 13:00:18 -0800 Subject: [PATCH 2/3] fix(moq-webrtc): candidates go on the first accepted BUNDLE line An offer that puts its data channel first had every candidate on the rejected line, which is out of the BUNDLE group. Co-Authored-By: Claude Opus 5.5 --- rs/moq-webrtc/src/vendor/str0m/change/sdp.rs | 51 ++++++++++++++++++-- 1 file changed, 47 insertions(+), 4 deletions(-) diff --git a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs b/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs index 0951d00a620..8e1220a3c59 100644 --- a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs +++ b/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs @@ -583,10 +583,8 @@ fn as_sdp(session: &Session, params: AsSdpParams) -> Sdp { let mut lines = v .iter() .map(|m| { - // Candidates should only be in the first BUNDLE mid - let include_candidates = m.index() == 0; - - let attrs = params.media_attributes(include_candidates); + // Candidates go on the first accepted line, added below. + let attrs = params.media_attributes(false); // Already made send stream SSRCs let mut ssrcs = session.streams.ssrcs_tx(m.mid()); @@ -606,6 +604,14 @@ fn as_sdp(session: &Session, params: AsSdpParams) -> Sdp { pending.apply_to(&mut lines); } + // Candidates belong in the first BUNDLE mid, which is the first accepted line: a + // rejected line ahead of it, such as an offered data channel, is out of the group. + let first = lines.iter().position(|l| !l.disabled).unwrap_or(0); + if let Some(line) = lines.get_mut(first) { + let candidates = params.candidates.iter().map(|c| MediaAttribute::Candidate(c.clone())); + line.attrs.splice(0..0, candidates); + } + // Mids go into the session part of the SDP. // Rejected (disabled) m-lines must not be part of the BUNDLE group. let mids = lines.iter().filter(|l| !l.disabled).map(|l| l.mid()).collect(); @@ -1666,6 +1672,43 @@ mod test { assert!(answer.contains(&format!("a=group:BUNDLE {audio}\r\n")), "{answer}"); } + /// An offer that puts its data channel first still gets the answer's candidates on the + /// accepted media, since the rejected data channel line is out of the BUNDLE group. + #[test] + fn candidates_skip_a_rejected_first_line() { + crate::vendor::str0m::init_crypto_default(); + + let now = Instant::now(); + let mut offerer = Rtc::new(now); + let mut change = offerer.sdp_api(); + let audio = change.add_media(MediaKind::Audio, Direction::SendOnly, None, None, None); + let (offer, _) = change.apply().unwrap(); + let offer = offer.to_sdp_string(); + let (session, media) = offer.split_at(offer.find("m=audio").unwrap()); + let session = session.replace( + &format!("a=group:BUNDLE {audio}\r\n"), + &format!("a=group:BUNDLE dc {audio}\r\n"), + ); + let offer = format!( + "{session}m=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\n\ + c=IN IP4 0.0.0.0\r\n\ + a=mid:dc\r\n\ + a=sctp-port:5000\r\n{media}" + ); + let offer = SdpOffer::from_sdp_string(&offer).expect("offer with a data channel first"); + + let mut answerer = Rtc::new(now); + let candidate = Candidate::host((std::net::Ipv4Addr::new(1, 1, 1, 1), 1000).into(), "udp").unwrap(); + answerer.add_local_candidate(candidate).unwrap(); + let answer = answerer.sdp_api().accept_offer(offer).unwrap(); + + let has_candidate = |m: &MediaLine| m.attrs.iter().any(|a| matches!(a, MediaAttribute::Candidate(_))); + assert!(answer.media_lines[0].disabled, "the data channel was accepted"); + assert!(!has_candidate(&answer.media_lines[0]), "a candidate sits on the rejected line"); + assert_eq!(answer.media_lines[1].mid(), audio); + assert!(has_candidate(&answer.media_lines[1]), "the accepted audio has no candidate"); + } + #[test] fn twcc_negotiation_uses_first_media_section_for_each_pt() { crate::vendor::str0m::init_crypto_default(); From cb327eac5eefe7e6009f9a21b8023b353a690920 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Sat, 14 Nov 2026 13:09:15 -0800 Subject: [PATCH 3/3] style: rustfmt Co-Authored-By: Claude Opus 5.5 --- rs/moq-webrtc/src/vendor/str0m/change/sdp.rs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs b/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs index 8e1220a3c59..72bb13ccee2 100644 --- a/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs +++ b/rs/moq-webrtc/src/vendor/str0m/change/sdp.rs @@ -1704,9 +1704,15 @@ mod test { let has_candidate = |m: &MediaLine| m.attrs.iter().any(|a| matches!(a, MediaAttribute::Candidate(_))); assert!(answer.media_lines[0].disabled, "the data channel was accepted"); - assert!(!has_candidate(&answer.media_lines[0]), "a candidate sits on the rejected line"); + assert!( + !has_candidate(&answer.media_lines[0]), + "a candidate sits on the rejected line" + ); assert_eq!(answer.media_lines[1].mid(), audio); - assert!(has_candidate(&answer.media_lines[1]), "the accepted audio has no candidate"); + assert!( + has_candidate(&answer.media_lines[1]), + "the accepted audio has no candidate" + ); } #[test]