Compare commits
56 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fd4285aff0 | |||
| a86a689b1f | |||
| 27b7f2bf1d | |||
| 54bc9f5faf | |||
| 33b7b90b65 | |||
| 81ddf64bee | |||
| 7a6afed575 | |||
| 0d3a9a7917 | |||
| b62443ef28 | |||
| e1abd7d060 | |||
| 7983833ba6 | |||
| 514565dbd7 | |||
| 284bf7cc17 | |||
| e4fdca794b | |||
| 73deb851ae | |||
| 813a0ab8c4 | |||
| 3794ed0e7f | |||
| 89de3210be | |||
| 3e09dbc09a | |||
| 07ccff4241 | |||
| a3c8cea7a6 | |||
| beeb72cec8 | |||
| c21e68565b | |||
| 66a6e98cf2 | |||
| 8125949db2 | |||
| d62aa8f581 | |||
| 6f13976ba5 | |||
| 61296102d1 | |||
| bd91a1007e | |||
| 30a7b90034 | |||
| 27b26a992b | |||
| a939821124 | |||
| 0f2edc66c9 | |||
| e67daea536 | |||
| 2740d3dd45 | |||
| 8d0bebfbc3 | |||
| b57e97a38b | |||
| da1f3afd52 | |||
| 948f446a13 | |||
| 71e34e8d9d | |||
| 9c59b69bf0 | |||
| 240190041d | |||
| f3ad3afe00 | |||
| ecc9908082 | |||
| fbfcd588a5 | |||
| fea864d16e | |||
| 38a455a717 | |||
| e4ca1509c8 | |||
| d0fe9a906c | |||
| b261d7ddc9 | |||
| 9d94b66975 | |||
| 7326767f37 | |||
| 8bc8b4f7ab | |||
| ff62498c9e | |||
| f72babc5b5 | |||
| ccfcdcc36c |
@@ -11,3 +11,4 @@ fuzz/corpus/
|
|||||||
*.h265
|
*.h265
|
||||||
*.pcap
|
*.pcap
|
||||||
*.pcapng
|
*.pcapng
|
||||||
|
*.proptest-regressions
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
|
|||||||
### Rules that never bend
|
### Rules that never bend
|
||||||
- Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c)
|
- Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c)
|
||||||
into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements.
|
into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements.
|
||||||
|
- Also allowed for the wire format, with attribution (Mark, 2026-11-25): stock ENet (MIT), tokio-enet (BSD-2),
|
||||||
|
fec-rs (BSD-2). GPL code stays off limits.
|
||||||
- Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only.
|
- Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only.
|
||||||
- Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed).
|
- Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed).
|
||||||
- Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever.
|
- Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever.
|
||||||
@@ -28,3 +30,9 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
|
|||||||
- Commits: `[<crate>] <Feature>: <description>`, `[repo]` for repo-wide changes. No AI attribution in commits, PRs or tags.
|
- Commits: `[<crate>] <Feature>: <description>`, `[repo]` for repo-wide changes. No AI attribution in commits, PRs or tags.
|
||||||
- No binaries, captures or test videos in git.
|
- No binaries, captures or test videos in git.
|
||||||
- Cargo builds: the machine-wide `CARGO_HOME` config sends the build dir to `D:\cargo-build`. Never set `CARGO_TARGET_DIR`.
|
- Cargo builds: the machine-wide `CARGO_HOME` config sends the build dir to `D:\cargo-build`. Never set `CARGO_TARGET_DIR`.
|
||||||
|
- Never start a build or a test run (cargo, npm/pnpm, Gradle, dotnet, Playwright, e2e, emulator, Fabrica runs) while this
|
||||||
|
PC's CPU or RAM is more than 90 % used, or any drive the work writes to (D:, E:, F:) is more than 95 % used
|
||||||
|
(Mark, 2026-11-25: "CPU, RAM and disk all 90%"; drives raised to 95 % on 2026-11-29). Check first. If any is over,
|
||||||
|
don't start; wait and check again later. Don't stop other sessions' work to make room.
|
||||||
|
- The limits gate builds and tests only. Merging, writing docs or CLAUDE.md and finishing a job never wait for the load
|
||||||
|
(Mark, 2026-11-29: "No merge you can do even on 100 percent CPU same as writing to claude.md and finishing job").
|
||||||
|
|||||||
Generated
+78
-51
@@ -55,6 +55,12 @@ version = "1.8.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "2.13.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "block-buffer"
|
name = "block-buffer"
|
||||||
version = "0.12.1"
|
version = "0.12.1"
|
||||||
@@ -89,6 +95,17 @@ version = "1.0.5"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "chacha20"
|
||||||
|
version = "0.10.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"cpufeatures",
|
||||||
|
"rand_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cipher"
|
name = "cipher"
|
||||||
version = "0.5.2"
|
version = "0.5.2"
|
||||||
@@ -112,6 +129,12 @@ version = "0.10.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "core_detect"
|
||||||
|
version = "1.0.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cpubits"
|
name = "cpubits"
|
||||||
version = "0.1.1"
|
version = "0.1.1"
|
||||||
@@ -135,7 +158,6 @@ checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cpubits",
|
"cpubits",
|
||||||
"ctutils",
|
"ctutils",
|
||||||
"getrandom",
|
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
"serdect",
|
"serdect",
|
||||||
@@ -148,7 +170,6 @@ version = "0.2.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom",
|
|
||||||
"hybrid-array",
|
"hybrid-array",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
]
|
]
|
||||||
@@ -225,6 +246,8 @@ dependencies = [
|
|||||||
"aes",
|
"aes",
|
||||||
"aes-gcm",
|
"aes-gcm",
|
||||||
"cbc",
|
"cbc",
|
||||||
|
"peak_alloc",
|
||||||
|
"proptest",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
"rsa",
|
"rsa",
|
||||||
"sha2",
|
"sha2",
|
||||||
@@ -302,6 +325,12 @@ dependencies = [
|
|||||||
"autocfg",
|
"autocfg",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "peak_alloc"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ccc90935a8dd139fdf341762773687a1e361d3f54b396a55d9dd1f7001e484bb"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "pem-rfc7468"
|
name = "pem-rfc7468"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
@@ -351,6 +380,22 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proptest"
|
||||||
|
version = "1.12.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b8530004ccb15eae51c7e40009fbe317f341f804db54dc033eec1c50be28cfa0"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"chacha20",
|
||||||
|
"core_detect",
|
||||||
|
"num-traits",
|
||||||
|
"rand",
|
||||||
|
"rand_xorshift",
|
||||||
|
"regex-syntax",
|
||||||
|
"unarray",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "quote"
|
name = "quote"
|
||||||
version = "1.0.47"
|
version = "1.0.47"
|
||||||
@@ -366,12 +411,37 @@ version = "6.0.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand"
|
||||||
|
version = "0.10.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom",
|
||||||
|
"rand_core",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rand_core"
|
name = "rand_core"
|
||||||
version = "0.10.1"
|
version = "0.10.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_xorshift"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "60aa6af80be32871323012e02e6e65f8a7cc7890931ae421d217ad8fe0df2ccf"
|
||||||
|
dependencies = [
|
||||||
|
"rand_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "regex-syntax"
|
||||||
|
version = "0.8.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "rsa"
|
name = "rsa"
|
||||||
version = "0.10.0"
|
version = "0.10.0"
|
||||||
@@ -432,17 +502,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "sha1"
|
|
||||||
version = "0.11.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"cpufeatures",
|
|
||||||
"digest",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha2"
|
name = "sha2"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -496,33 +555,18 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
|
|
||||||
dependencies = [
|
|
||||||
"tls_codec_derive",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec_derive"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unarray"
|
||||||
|
version = "0.1.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.27"
|
version = "1.0.27"
|
||||||
@@ -547,10 +591,7 @@ checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"const-oid",
|
"const-oid",
|
||||||
"der",
|
"der",
|
||||||
"sha1",
|
|
||||||
"signature",
|
|
||||||
"spki",
|
"spki",
|
||||||
"tls_codec",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -558,17 +599,3 @@ name = "zeroize"
|
|||||||
version = "1.9.2"
|
version = "1.9.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
||||||
dependencies = [
|
|
||||||
"zeroize_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "zeroize_derive"
|
|
||||||
version = "1.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|||||||
@@ -18,6 +18,14 @@ Rubylight or moonlight-common-c was opened, pasted or ported. See [`docs/CLEAN_R
|
|||||||
cargo test --workspace
|
cargo test --workspace
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Status: `stream-v0.1.0`
|
||||||
|
|
||||||
|
Written from the Wolf protocol docs and the approved permissive sources (stock ENet, tokio-enet, fec-rs). **Interop is
|
||||||
|
unverified**: this release has not yet talked to a real Sunshine host. Ten details that block interop (U1, U2, U4–U10,
|
||||||
|
U17 in [`docs/PROTOCOL.md`](docs/PROTOCOL.md)) are settled live on Arena Domi's Play remotely Day 1, and a
|
||||||
|
`stream-v0.1.x` patch is expected. Evidence for this release: 242 tests, a mutation pass (24 of 24 caught,
|
||||||
|
[`docs/MUTATION.md`](docs/MUTATION.md)), and 25 fuzz targets with 0 crashes ([`docs/HANDOVER.md`](docs/HANDOVER.md)).
|
||||||
|
|
||||||
| Path | What |
|
| Path | What |
|
||||||
| :-- | :-- |
|
| :-- | :-- |
|
||||||
| `crates/domistream` | the crate: one module per protocol part (see its rustdoc) |
|
| `crates/domistream` | the crate: one module per protocol part (see its rustdoc) |
|
||||||
|
|||||||
@@ -14,10 +14,16 @@ workspace = true
|
|||||||
# Crypto: RustCrypto only, pure Rust, all MIT OR Apache-2.0 (fits CPAL-1.0). Chosen in Phase A, used in Phase B.
|
# Crypto: RustCrypto only, pure Rust, all MIT OR Apache-2.0 (fits CPAL-1.0). Chosen in Phase A, used in Phase B.
|
||||||
[dependencies]
|
[dependencies]
|
||||||
aes = "0.9" # AES-128 block cipher (pairing ECB)
|
aes = "0.9" # AES-128 block cipher (pairing ECB)
|
||||||
aes-gcm = "0.11" # control and video AES-128-GCM
|
aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"] } # control and video AES-128-GCM; no getrandom, randomness only through RandomSource
|
||||||
cbc = "0.2" # audio AES-128-CBC
|
cbc = "0.2" # audio AES-128-CBC
|
||||||
sha2 = "0.11" # pairing SHA-256
|
sha2 = "0.11" # pairing SHA-256
|
||||||
rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigint, constant time)
|
rsa = { version = "0.10", default-features = false, features = ["std", "encoding", "pkcs1v15"] } # client key, PKCS#1 v1.5 SHA-256; no getrandom: randomness only through RandomSource
|
||||||
x509-cert = { version = "0.3", features = ["builder", "pem"] } # client certificate, host certificate parsing
|
x509-cert = { version = "0.3", default-features = false } # host and client certificate parsing (our own DER writer builds the client certificate)
|
||||||
rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits
|
rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits
|
||||||
zeroize = "1.8" # wipe keys on drop
|
zeroize = "1.8" # wipe keys on drop
|
||||||
|
|
||||||
|
# Tests only. proptest without fork/timeout (no subprocesses, no threads); peak_alloc (MIT) is a counting global
|
||||||
|
# allocator, so tests can check that parsers never allocate past their caps without any unsafe code of ours.
|
||||||
|
[dev-dependencies]
|
||||||
|
proptest = { version = "1.12", default-features = false, features = ["std"] }
|
||||||
|
peak_alloc = "0.3"
|
||||||
|
|||||||
@@ -3,14 +3,25 @@
|
|||||||
//!
|
//!
|
||||||
//! **Opus decoding is not here.** A packet that cannot be rebuilt becomes [`AudioEvent::Lost`]; the platform
|
//! **Opus decoding is not here.** A packet that cannot be rebuilt becomes [`AudioEvent::Lost`]; the platform
|
||||||
//! conceals it.
|
//! conceals it.
|
||||||
|
//!
|
||||||
|
//! Parity packets are keyed by their FEC header's base sequence number, never by their own RTP sequence number,
|
||||||
|
//! which overlaps the next block's data. The parity covers the (encrypted) payloads of the four data packets.
|
||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
|
||||||
use crate::{Instant, Result, SessionKeys};
|
use cbc::cipher::block_padding::Pkcs7;
|
||||||
|
use cbc::cipher::{BlockModeDecrypt, BlockModeEncrypt, KeyIvInit};
|
||||||
|
|
||||||
|
use crate::fec::ReedSolomon;
|
||||||
|
use crate::util::malformed;
|
||||||
|
use crate::{Error, Instant, Result, SessionKeys};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
pub mod packetizer;
|
||||||
|
|
||||||
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
|
pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet};
|
||||||
|
pub use packetizer::{AudioPacketizer, AudioPacketizerConfig, AudioParity};
|
||||||
|
|
||||||
/// Data packets per FEC block.
|
/// Data packets per FEC block.
|
||||||
pub const DATA_SHARDS: usize = 4;
|
pub const DATA_SHARDS: usize = 4;
|
||||||
@@ -18,39 +29,78 @@ pub const DATA_SHARDS: usize = 4;
|
|||||||
pub const PARITY_SHARDS: usize = 2;
|
pub const PARITY_SHARDS: usize = 2;
|
||||||
/// Maximum blocks kept while waiting for missing packets.
|
/// Maximum blocks kept while waiting for missing packets.
|
||||||
pub const MAX_BLOCKS_IN_FLIGHT: usize = 8;
|
pub const MAX_BLOCKS_IN_FLIGHT: usize = 8;
|
||||||
|
/// Packets further than this ahead of the next expected one are dropped (a stray, not a gap to wait for).
|
||||||
|
pub const MAX_PACKETS_AHEAD: u16 = 1024;
|
||||||
|
|
||||||
/// AES-128-CBC for audio payloads: IV = `u32 BE (rikeyid + sequence) ‖ 12 zero bytes`, PKCS#7 padding.
|
/// AES-128-CBC for audio payloads: IV = `u32 BE (rikeyid + sequence) ‖ 12 zero bytes`, PKCS#7 padding.
|
||||||
/// `Debug` never prints the key.
|
/// `Debug` never prints the key.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AudioCipher {
|
pub struct AudioCipher {
|
||||||
key: [u8; 16],
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
rikeyid: u32,
|
rikeyid: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AudioCipher {
|
impl AudioCipher {
|
||||||
/// A cipher for the session's keys.
|
/// A cipher for the session's keys.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new(keys: &SessionKeys) -> Self {
|
pub fn new(keys: &SessionKeys) -> Self {
|
||||||
Self { key: keys.rikey, rikeyid: keys.rikeyid }
|
Self { key: zeroize::Zeroizing::new(keys.rikey), rikeyid: keys.rikeyid }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The IV for RTP sequence number `sequence`.
|
/// The IV for RTP sequence number `sequence` (the sum wraps).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn iv(&self, sequence: u16) -> Result<[u8; 16]> {
|
pub fn iv(&self, sequence: u16) -> Result<[u8; 16]> {
|
||||||
let _ = (sequence, self.rikeyid);
|
let mut iv = [0u8; 16];
|
||||||
Err(crate::Error::Unimplemented)
|
let [a, b, c, d] = self.rikeyid.wrapping_add(u32::from(sequence)).to_be_bytes();
|
||||||
|
iv[0] = a;
|
||||||
|
iv[1] = b;
|
||||||
|
iv[2] = c;
|
||||||
|
iv[3] = d;
|
||||||
|
Ok(iv)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decrypts one payload.
|
/// Decrypts one payload.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a length that is not a positive multiple of 16, [`crate::Error::Crypto`] for
|
/// [`Error::Malformed`] for a length that is not a positive multiple of 16, [`Error::Crypto`] for bad padding.
|
||||||
/// bad padding. Phase A: always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn decrypt(&self, sequence: u16, ciphertext: &[u8]) -> Result<Vec<u8>> {
|
pub fn decrypt(&self, sequence: u16, ciphertext: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (sequence, ciphertext, &self.key);
|
if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("audio ciphertext length"));
|
||||||
|
}
|
||||||
|
let iv = self.iv(sequence)?;
|
||||||
|
let mut buf = ciphertext.to_vec();
|
||||||
|
let len = cbc::Decryptor::<aes::Aes128>::new((&*self.key).into(), &iv.into())
|
||||||
|
.decrypt_padded::<Pkcs7>(&mut buf)
|
||||||
|
.map_err(|_| Error::Crypto)?
|
||||||
|
.len();
|
||||||
|
buf.truncate(len);
|
||||||
|
Ok(buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AudioCipher {
|
||||||
|
/// Encrypts one payload (host side), the exact mirror of [`Self::decrypt`]: AES-128-CBC with the IV of
|
||||||
|
/// [`Self::iv`] and PKCS#7 padding, so the ciphertext is the plaintext length rounded up to the next multiple of
|
||||||
|
/// 16, always 1 to 16 bytes longer (`docs/PROTOCOL.md` 6.3).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`] (checked before anything is allocated),
|
||||||
|
/// [`Error::Crypto`] if the cipher refuses (never for a buffer sized as here).
|
||||||
|
pub fn encrypt(&self, sequence: u16, plaintext: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
crate::util::cap("audio plaintext", packet::MAX_AUDIO_PACKET_BYTES, plaintext.len())?;
|
||||||
|
let iv = self.iv(sequence)?;
|
||||||
|
let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16];
|
||||||
|
for (dst, src) in buf.iter_mut().zip(plaintext) {
|
||||||
|
*dst = *src;
|
||||||
|
}
|
||||||
|
let len = cbc::Encryptor::<aes::Aes128>::new((&*self.key).into(), &iv.into())
|
||||||
|
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
|
||||||
|
.map_err(|_| Error::Crypto)?
|
||||||
|
.len();
|
||||||
|
buf.truncate(len);
|
||||||
|
Ok(buf)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,52 +166,352 @@ pub struct AudioStats {
|
|||||||
pub lost: u64,
|
pub lost: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One received or rebuilt data packet.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct Data {
|
||||||
|
/// The payload as sent (ciphertext when encrypted): the FEC shard.
|
||||||
|
shard: Vec<u8>,
|
||||||
|
opus: Vec<u8>,
|
||||||
|
timestamp_ms: u32,
|
||||||
|
arrived: Instant,
|
||||||
|
recovered: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct Parity {
|
||||||
|
shard: Vec<u8>,
|
||||||
|
base_timestamp: u32,
|
||||||
|
arrived: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Block {
|
||||||
|
data: [Option<Data>; DATA_SHARDS],
|
||||||
|
parity: [Option<Parity>; PARITY_SHARDS],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Block {
|
||||||
|
fn earliest_after(&self, index: usize) -> Option<Instant> {
|
||||||
|
let data = self.data.iter().skip(index + 1).flatten().map(|d| d.arrived);
|
||||||
|
let parity = self.parity.iter().flatten().map(|p| p.arrived);
|
||||||
|
data.chain(parity).min()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The audio receiver.
|
/// The audio receiver.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct AudioDepacketizer {
|
pub struct AudioDepacketizer {
|
||||||
|
config: AudioConfig,
|
||||||
|
code: Option<ReedSolomon>,
|
||||||
|
next: Option<u16>,
|
||||||
|
blocks: HashMap<u16, Block>,
|
||||||
|
events: VecDeque<AudioEvent>,
|
||||||
stats: AudioStats,
|
stats: AudioStats,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fn block_base(seq: u16) -> u16 {
|
||||||
|
seq & !3
|
||||||
|
}
|
||||||
|
|
||||||
impl AudioDepacketizer {
|
impl AudioDepacketizer {
|
||||||
/// A receiver for one stream.
|
/// A receiver for one stream.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS. Phase A: always
|
/// [`Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn new(config: AudioConfig) -> Result<Self> {
|
pub fn new(config: AudioConfig) -> Result<Self> {
|
||||||
let _ = config;
|
if config.packet_duration_ms == 0 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("audio packet duration"));
|
||||||
|
}
|
||||||
|
let code = match config.fec {
|
||||||
|
AudioFec::Disabled => None,
|
||||||
|
AudioFec::ParityMatrix(m) => Some(ReedSolomon::with_parity_matrix(DATA_SHARDS, PARITY_SHARDS, &m)?),
|
||||||
|
};
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
code,
|
||||||
|
next: None,
|
||||||
|
blocks: HashMap::new(),
|
||||||
|
events: VecDeque::new(),
|
||||||
|
stats: AudioStats::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drop_packet(&mut self) -> Result<()> {
|
||||||
|
self.stats.packets_dropped += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one datagram from the audio port. Bad, duplicate and too-old packets are counted and dropped; only an
|
/// Feeds one datagram from the audio port. Bad, duplicate and too-old packets are counted and dropped; only an
|
||||||
/// oversized datagram is an error.
|
/// oversized datagram is an error.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`]. Phase A: always
|
/// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
crate::util::cap("audio datagram", packet::MAX_AUDIO_PACKET_BYTES, datagram.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let Ok(p) = parse_audio_packet(datagram) else { return self.drop_packet() };
|
||||||
|
match p {
|
||||||
|
AudioPacket::Data { rtp, payload } => {
|
||||||
|
let seq = rtp.sequence;
|
||||||
|
if !self.admit(seq, seq) {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
let opus = match &self.config.cipher {
|
||||||
|
Some(c) => match c.decrypt(seq, payload) {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(_) => return self.drop_packet(),
|
||||||
|
},
|
||||||
|
None => payload.to_vec(),
|
||||||
|
};
|
||||||
|
let slot = self.blocks.entry(block_base(seq)).or_default().data.get_mut(usize::from(seq & 3));
|
||||||
|
match slot {
|
||||||
|
Some(s) if s.is_none() => {
|
||||||
|
*s = Some(Data {
|
||||||
|
shard: payload.to_vec(),
|
||||||
|
opus,
|
||||||
|
timestamp_ms: rtp.timestamp,
|
||||||
|
arrived: now,
|
||||||
|
recovered: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => return self.drop_packet(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AudioPacket::Parity { fec, parity, .. } => {
|
||||||
|
let base = fec.base_sequence;
|
||||||
|
if base & 3 != 0 || fec.payload_type != packet::AUDIO_PAYLOAD_TYPE {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
if self.code.is_none() {
|
||||||
|
self.stats.packets += 1;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if !self.admit(base, base.wrapping_add(3)) {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
let slot = self.blocks.entry(base).or_default().parity.get_mut(usize::from(fec.shard_index));
|
||||||
|
match slot {
|
||||||
|
Some(s) if s.is_none() => {
|
||||||
|
*s = Some(Parity { shard: parity.to_vec(), base_timestamp: fec.base_timestamp, arrived: now });
|
||||||
|
}
|
||||||
|
_ => return self.drop_packet(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.stats.packets += 1;
|
||||||
|
self.advance(now);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a packet covering `first..=last` may be stored: not entirely in the past, not too far ahead. A packet
|
||||||
|
/// ahead of the block window first moves the window up (the blocks it passes are emitted or reported lost).
|
||||||
|
fn admit(&mut self, first: u16, last: u16) -> bool {
|
||||||
|
let next = *self.next.get_or_insert(block_base(first));
|
||||||
|
if last.wrapping_sub(next) >= 0x8000 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let ahead = first.wrapping_sub(next);
|
||||||
|
if (MAX_PACKETS_AHEAD..0x8000).contains(&ahead) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let window = (MAX_BLOCKS_IN_FLIGHT * DATA_SHARDS) as u16;
|
||||||
|
if block_base(first).wrapping_sub(block_base(next)) < 0x8000
|
||||||
|
&& block_base(first).wrapping_sub(block_base(next)) >= window
|
||||||
|
{
|
||||||
|
self.flush_until(block_base(first).wrapping_sub(window - DATA_SHARDS as u16));
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits or reports lost every sequence number before `target`, at once.
|
||||||
|
fn flush_until(&mut self, target: u16) {
|
||||||
|
while let Some(n) = self.next {
|
||||||
|
if target.wrapping_sub(n) == 0 || target.wrapping_sub(n) >= 0x8000 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if !self.emit_if_available(n) {
|
||||||
|
self.events.push_back(AudioEvent::Lost { sequence: n });
|
||||||
|
self.stats.lost += 1;
|
||||||
|
self.step(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits `n` if it was received or can be rebuilt now.
|
||||||
|
fn emit_if_available(&mut self, n: u16) -> bool {
|
||||||
|
let base = block_base(n);
|
||||||
|
let index = usize::from(n & 3);
|
||||||
|
let present = |s: &Self| s.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some);
|
||||||
|
if present(self) || (self.recover(base) && present(self)) {
|
||||||
|
self.emit_present(n, base, index);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits in sequence order: received packets at once; a missing packet waits for the jitter budget
|
||||||
|
/// (`loss_timeout`), since a late packet beats a rebuilt one, and is then rebuilt or reported lost.
|
||||||
|
fn advance(&mut self, now: Instant) {
|
||||||
|
let timeout = self.config.loss_timeout;
|
||||||
|
while let Some(n) = self.next {
|
||||||
|
let base = block_base(n);
|
||||||
|
let index = usize::from(n & 3);
|
||||||
|
if self.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some) {
|
||||||
|
self.emit_present(n, base, index);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(start) = self.earliest_after(n, base, index) else { return };
|
||||||
|
if start.saturating_add(timeout) > now {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self.emit_if_available(n) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
self.events.push_back(AudioEvent::Lost { sequence: n });
|
||||||
|
self.stats.lost += 1;
|
||||||
|
self.step(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_present(&mut self, n: u16, base: u16, index: usize) {
|
||||||
|
// The shard stays in the block: a later packet of the same block may still need it to be rebuilt.
|
||||||
|
if let Some(d) = self.blocks.get_mut(&base).and_then(|b| b.data.get_mut(index)).and_then(Option::as_mut) {
|
||||||
|
if d.recovered {
|
||||||
|
self.stats.recovered += 1;
|
||||||
|
}
|
||||||
|
let opus = core::mem::take(&mut d.opus);
|
||||||
|
self.events.push_back(AudioEvent::Packet {
|
||||||
|
sequence: n,
|
||||||
|
timestamp_ms: d.timestamp_ms,
|
||||||
|
opus,
|
||||||
|
recovered: d.recovered,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.step(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves past `n`, dropping its block once its last data packet is done.
|
||||||
|
fn step(&mut self, n: u16) {
|
||||||
|
if n & 3 == 3 {
|
||||||
|
self.blocks.remove(&block_base(n));
|
||||||
|
}
|
||||||
|
self.next = Some(n.wrapping_add(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The earliest arrival of anything stored after sequence `n`: when the wait for `n` began.
|
||||||
|
fn earliest_after(&self, n: u16, base: u16, index: usize) -> Option<Instant> {
|
||||||
|
let own = self.blocks.get(&base).and_then(|b| b.earliest_after(index));
|
||||||
|
let later = self
|
||||||
|
.blocks
|
||||||
|
.iter()
|
||||||
|
.filter(|(b, _)| b.wrapping_sub(base) != 0 && b.wrapping_sub(n) < 0x8000)
|
||||||
|
.filter_map(|(_, blk)| {
|
||||||
|
blk.data.iter().flatten().map(|d| d.arrived).chain(blk.parity.iter().flatten().map(|p| p.arrived)).min()
|
||||||
|
})
|
||||||
|
.min();
|
||||||
|
match (own, later) {
|
||||||
|
(Some(a), Some(b)) => Some(a.min(b)),
|
||||||
|
(a, b) => a.or(b),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebuilds the missing data packets of block `base` when FEC is on and 4 equal-length shards are there.
|
||||||
|
fn recover(&mut self, base: u16) -> bool {
|
||||||
|
let Some(code) = &self.code else { return false };
|
||||||
|
let Some(block) = self.blocks.get(&base) else { return false };
|
||||||
|
let len = block
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|d| d.shard.len())
|
||||||
|
.next()
|
||||||
|
.or_else(|| block.parity.iter().flatten().map(|p| p.shard.len()).next());
|
||||||
|
let Some(len) = len else { return false };
|
||||||
|
let mut shards: Vec<Option<Vec<u8>>> = block
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.as_ref().filter(|d| d.shard.len() == len).map(|d| d.shard.clone()))
|
||||||
|
.chain(block.parity.iter().map(|p| p.as_ref().filter(|p| p.shard.len() == len).map(|p| p.shard.clone())))
|
||||||
|
.collect();
|
||||||
|
if shards.iter().flatten().count() < DATA_SHARDS || block.data.iter().all(Option::is_some) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if code.reconstruct(&mut shards).is_err() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let base_ts = block
|
||||||
|
.parity
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|p| p.base_timestamp)
|
||||||
|
.next()
|
||||||
|
.or_else(|| {
|
||||||
|
block.data.iter().enumerate().find_map(|(i, d)| {
|
||||||
|
d.as_ref()
|
||||||
|
.map(|d| d.timestamp_ms.wrapping_sub(i as u32 * u32::from(self.config.packet_duration_ms)))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.unwrap_or(0);
|
||||||
|
let duration = u32::from(self.config.packet_duration_ms);
|
||||||
|
let mut rebuilt = Vec::new();
|
||||||
|
for (i, shard) in shards.into_iter().take(DATA_SHARDS).enumerate() {
|
||||||
|
if block.data.get(i).is_some_and(Option::is_some) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(shard) = shard else { continue };
|
||||||
|
let seq = base.wrapping_add(i as u16);
|
||||||
|
let opus = match &self.config.cipher {
|
||||||
|
Some(c) => match c.decrypt(seq, &shard) {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(_) => continue,
|
||||||
|
},
|
||||||
|
None => shard.clone(),
|
||||||
|
};
|
||||||
|
rebuilt.push((
|
||||||
|
i,
|
||||||
|
Data {
|
||||||
|
shard,
|
||||||
|
opus,
|
||||||
|
timestamp_ms: base_ts.wrapping_add(i as u32 * duration),
|
||||||
|
arrived: Instant::ZERO,
|
||||||
|
recovered: true,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let any = !rebuilt.is_empty();
|
||||||
|
if let Some(block) = self.blocks.get_mut(&base) {
|
||||||
|
for (i, d) in rebuilt {
|
||||||
|
if let Some(slot) = block.data.get_mut(i) {
|
||||||
|
*slot = Some(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
any
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<AudioEvent> {
|
pub fn poll_event(&mut self) -> Option<AudioEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When a missing packet times out.
|
/// When a missing packet times out.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
let n = self.next?;
|
||||||
|
let base = block_base(n);
|
||||||
|
let index = usize::from(n & 3);
|
||||||
|
if self.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.earliest_after(n, base, index).map(|t| t.saturating_add(self.config.loss_timeout))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reports timed-out packets as lost.
|
/// Reports timed-out packets as lost.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
self.advance(now);
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Counters.
|
/// Counters.
|
||||||
|
|||||||
@@ -52,9 +52,34 @@ pub enum AudioPacket<'a> {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_AUDIO_PACKET_BYTES`], [`crate::Error::Truncated`] for a cut header or an
|
/// [`crate::Error::TooLarge`] over [`MAX_AUDIO_PACKET_BYTES`], [`crate::Error::Truncated`] for a cut header or an
|
||||||
/// empty payload, [`crate::Error::UnexpectedValue`] for another payload type or a parity shard index above 1.
|
/// empty payload, [`crate::Error::UnexpectedValue`] for another RTP version or payload type, or a parity shard
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// index above 1.
|
||||||
pub fn parse_audio_packet(packet: &[u8]) -> crate::Result<AudioPacket<'_>> {
|
pub fn parse_audio_packet(packet: &[u8]) -> crate::Result<AudioPacket<'_>> {
|
||||||
let _ = packet;
|
use crate::util::{byte, need, u16_be, u32_be};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "audio packet";
|
||||||
|
crate::util::cap(W, MAX_AUDIO_PACKET_BYTES, packet.len())?;
|
||||||
|
let rtp = crate::rtp::parse_rtp_header(packet)?;
|
||||||
|
let at = crate::rtp::RTP_HEADER_LEN;
|
||||||
|
match rtp.payload_type {
|
||||||
|
AUDIO_PAYLOAD_TYPE => {
|
||||||
|
need(W, at + 1, packet.len())?;
|
||||||
|
Ok(AudioPacket::Data { rtp, payload: packet.get(at..).unwrap_or(&[]) })
|
||||||
|
}
|
||||||
|
AUDIO_FEC_PAYLOAD_TYPE => {
|
||||||
|
need(W, at + AUDIO_FEC_HEADER_LEN + 1, packet.len())?;
|
||||||
|
let shard_index = byte(W, packet, at)?;
|
||||||
|
if shard_index > 1 {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "audio parity shard", value: shard_index.into() });
|
||||||
|
}
|
||||||
|
let fec = AudioFecHeader {
|
||||||
|
shard_index,
|
||||||
|
payload_type: byte(W, packet, at + 1)?,
|
||||||
|
base_sequence: u16_be(W, packet, at + 2)?,
|
||||||
|
base_timestamp: u32_be(W, packet, at + 4)?,
|
||||||
|
ssrc: u32_be(W, packet, at + 8)?,
|
||||||
|
};
|
||||||
|
Ok(AudioPacket::Parity { rtp, fec, parity: packet.get(at + AUDIO_FEC_HEADER_LEN..).unwrap_or(&[]) })
|
||||||
|
}
|
||||||
|
other => Err(crate::Error::UnexpectedValue { what: "audio payload type", value: other.into() }),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
//! The audio send path, host side (`docs/PROTOCOL.md` 6.2, 6.3): one Opus packet → one RTP datagram, the mirror of
|
||||||
|
//! [`super::AudioDepacketizer`] and tested against it.
|
||||||
|
//!
|
||||||
|
//! Each datagram is the 12-byte RTP header (byte 0 `0x80`, payload type 97, sequence BE, timestamp BE in
|
||||||
|
//! milliseconds, SSRC 0) followed by the Opus packet, AES-128-CBC encrypted with [`AudioCipher::encrypt`] when a
|
||||||
|
//! cipher is set (6.3: IV from `rikeyid + sequence`, PKCS#7). Sequence numbers count up by one per packet and the
|
||||||
|
//! timestamp by the packet duration, both wrapping.
|
||||||
|
//!
|
||||||
|
//! **No parity packets** (6.4): the audio parity matrix is UNKNOWN U16, and the only value seen has GPL provenance,
|
||||||
|
//! so [`AudioParity`] has a single variant, [`AudioParity::None`], and clients conceal lost packets. The enum is
|
||||||
|
//! `#[non_exhaustive]` and [`AudioPacketizer::packetize`] returns a list of datagrams, so a measured matrix can be
|
||||||
|
//! added later as a new variant that appends the 2 parity datagrams after every block's 4th data packet without
|
||||||
|
//! changing callers. Blocks start at sequence numbers that are multiples of 4 (6.4), so `first_sequence` must be one
|
||||||
|
//! already (the client's receiver also counts from the first packet's block start).
|
||||||
|
|
||||||
|
use super::AudioCipher;
|
||||||
|
use super::packet::{AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES};
|
||||||
|
use crate::Result;
|
||||||
|
use crate::rtp::RTP_HEADER_LEN;
|
||||||
|
use crate::util::{cap, malformed, need};
|
||||||
|
|
||||||
|
/// Byte 0 of every audio RTP header: version 2, no padding, extension or CSRC (`docs/PROTOCOL.md` 6.2).
|
||||||
|
pub const AUDIO_RTP_BYTE0: u8 = 0x80;
|
||||||
|
/// Largest Opus packet sent in the clear: the receiver's datagram cap minus the RTP header.
|
||||||
|
pub const MAX_OPUS_PLAIN_BYTES: usize = MAX_AUDIO_PACKET_BYTES - RTP_HEADER_LEN;
|
||||||
|
/// Largest Opus packet sent encrypted: PKCS#7 always adds 1 to 16 bytes, and the ciphertext must fit the cap.
|
||||||
|
pub const MAX_OPUS_ENCRYPTED_BYTES: usize = MAX_OPUS_PLAIN_BYTES / 16 * 16 - 1;
|
||||||
|
|
||||||
|
/// Which audio parity packets are sent (`docs/PROTOCOL.md` 6.4).
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum AudioParity {
|
||||||
|
/// None: the parity matrix is UNKNOWN U16 (GPL-provenance, unsettled), so clients conceal lost packets.
|
||||||
|
#[default]
|
||||||
|
None,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Settings of the audio sender.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct AudioPacketizerConfig {
|
||||||
|
/// Encrypt payloads with this cipher (audio encryption negotiated, or always: UNKNOWN U17).
|
||||||
|
pub cipher: Option<AudioCipher>,
|
||||||
|
/// Packet duration in milliseconds (`x-nv-aqos.packetDuration`): the timestamp step.
|
||||||
|
pub packet_duration_ms: u8,
|
||||||
|
/// Parity packets.
|
||||||
|
pub parity: AudioParity,
|
||||||
|
/// RTP sequence number of the first packet: a multiple of 4, the start of an FEC block (6.4).
|
||||||
|
pub first_sequence: u16,
|
||||||
|
/// RTP timestamp (milliseconds) of the first packet.
|
||||||
|
pub first_timestamp_ms: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audio sender of one stream.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct AudioPacketizer {
|
||||||
|
config: AudioPacketizerConfig,
|
||||||
|
next_sequence: u16,
|
||||||
|
next_timestamp_ms: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AudioPacketizer {
|
||||||
|
/// A sender for one stream.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`crate::Error::Malformed`] for a zero packet duration or a `first_sequence` that is not a multiple of 4: FEC
|
||||||
|
/// blocks start at multiples of 4 (6.4), and the client's receiver counts from the start of the first packet's
|
||||||
|
/// block, so a stream starting mid-block would show it 1 to 3 phantom losses.
|
||||||
|
pub fn new(config: AudioPacketizerConfig) -> Result<Self> {
|
||||||
|
if config.packet_duration_ms == 0 {
|
||||||
|
return Err(malformed("audio packet duration"));
|
||||||
|
}
|
||||||
|
if !config.first_sequence.is_multiple_of(4) {
|
||||||
|
return Err(malformed("audio first sequence is not a block start (a multiple of 4)"));
|
||||||
|
}
|
||||||
|
Ok(Self { next_sequence: config.first_sequence, next_timestamp_ms: config.first_timestamp_ms, config })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest Opus packet accepted: [`MAX_OPUS_ENCRYPTED_BYTES`] with a cipher, else [`MAX_OPUS_PLAIN_BYTES`].
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_opus_len(&self) -> usize {
|
||||||
|
if self.config.cipher.is_some() { MAX_OPUS_ENCRYPTED_BYTES } else { MAX_OPUS_PLAIN_BYTES }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Packetizes one Opus packet into the datagrams to send now, in order: today exactly one (no parity, see
|
||||||
|
/// [`AudioParity`]). On error nothing changes (sequence number, timestamp).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`crate::Error::Truncated`] for an empty packet (Opus packets carry at least their TOC byte, RFC 6716),
|
||||||
|
/// [`crate::Error::TooLarge`] over [`Self::max_opus_len`] (checked before anything is allocated),
|
||||||
|
/// [`crate::Error::Crypto`] if the cipher refuses.
|
||||||
|
pub fn packetize(&mut self, opus: &[u8]) -> Result<Vec<Vec<u8>>> {
|
||||||
|
const W: &str = "opus packet";
|
||||||
|
need(W, 1, opus.len())?;
|
||||||
|
cap(W, self.max_opus_len(), opus.len())?;
|
||||||
|
let (sequence, timestamp) = (self.next_sequence, self.next_timestamp_ms);
|
||||||
|
let mut packet = Vec::with_capacity(RTP_HEADER_LEN + opus.len() + 16);
|
||||||
|
packet.extend_from_slice(&[AUDIO_RTP_BYTE0, AUDIO_PAYLOAD_TYPE]);
|
||||||
|
packet.extend_from_slice(&sequence.to_be_bytes());
|
||||||
|
packet.extend_from_slice(×tamp.to_be_bytes());
|
||||||
|
packet.extend_from_slice(&0u32.to_be_bytes()); // SSRC 0
|
||||||
|
match &self.config.cipher {
|
||||||
|
Some(c) => packet.extend_from_slice(&c.encrypt(sequence, opus)?),
|
||||||
|
None => packet.extend_from_slice(opus),
|
||||||
|
}
|
||||||
|
let datagrams = match self.config.parity {
|
||||||
|
AudioParity::None => vec![packet],
|
||||||
|
};
|
||||||
|
self.next_sequence = sequence.wrapping_add(1);
|
||||||
|
self.next_timestamp_ms = timestamp.wrapping_add(u32::from(self.config.packet_duration_ms));
|
||||||
|
Ok(datagrams)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The RTP sequence number of the next packet.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn next_sequence(&self) -> u16 {
|
||||||
|
self.next_sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The RTP timestamp (milliseconds) of the next packet.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn next_timestamp_ms(&self) -> u32 {
|
||||||
|
self.next_timestamp_ms
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,7 +8,11 @@
|
|||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
|
||||||
use crate::Result;
|
use aes_gcm::Aes128Gcm;
|
||||||
|
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||||||
|
|
||||||
|
use crate::util::{array, cap, malformed, u16_le, u32_le};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Type field of an encrypted frame.
|
/// Type field of an encrypted frame.
|
||||||
pub const ENCRYPTED_FRAME_TYPE: u16 = 0x0001;
|
pub const ENCRYPTED_FRAME_TYPE: u16 = 0x0001;
|
||||||
@@ -35,10 +39,20 @@ pub enum Direction {
|
|||||||
/// The nonce for sequence number `sequence` in `direction`.
|
/// The nonce for sequence number `sequence` in `direction`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> {
|
pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> {
|
||||||
let _ = (sequence, direction);
|
let mut n = [0u8; NONCE_LEN];
|
||||||
Err(crate::Error::Unimplemented)
|
let [a, b, c, d] = sequence.to_le_bytes();
|
||||||
|
n[0] = a;
|
||||||
|
n[1] = b;
|
||||||
|
n[2] = c;
|
||||||
|
n[3] = d;
|
||||||
|
n[10] = match direction {
|
||||||
|
Direction::ClientToHost => b'C',
|
||||||
|
Direction::HostToClient => b'H',
|
||||||
|
};
|
||||||
|
n[11] = b'C';
|
||||||
|
Ok(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A frame split into its fields, not yet decrypted.
|
/// A frame split into its fields, not yet decrypted.
|
||||||
@@ -55,45 +69,78 @@ pub struct EncryptedFrame<'a> {
|
|||||||
/// Splits a frame (one ENet packet) into its fields. The length field must match the bytes present exactly.
|
/// Splits a frame (one ENet packet) into its fields. The length field must match the bytes present exactly.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`crate::Error::Truncated`] under [`MIN_FRAME_BYTES`],
|
/// [`Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`Error::Truncated`] under [`MIN_FRAME_BYTES`],
|
||||||
/// [`crate::Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`crate::Error::Malformed`]
|
/// [`Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`Error::Malformed`] for a length
|
||||||
/// for a length that does not match. Phase A: always [`crate::Error::Unimplemented`].
|
/// that does not match.
|
||||||
pub fn parse_encrypted_frame(frame: &[u8]) -> Result<EncryptedFrame<'_>> {
|
pub fn parse_encrypted_frame(frame: &[u8]) -> Result<EncryptedFrame<'_>> {
|
||||||
let _ = frame;
|
const W: &str = "control frame";
|
||||||
Err(crate::Error::Unimplemented)
|
cap(W, MAX_FRAME_BYTES, frame.len())?;
|
||||||
|
crate::util::need(W, MIN_FRAME_BYTES, frame.len())?;
|
||||||
|
let kind = u16_le(W, frame, 0)?;
|
||||||
|
if kind != ENCRYPTED_FRAME_TYPE {
|
||||||
|
return Err(Error::UnexpectedValue { what: "control frame type", value: kind.into() });
|
||||||
|
}
|
||||||
|
if usize::from(u16_le(W, frame, 2)?) != frame.len() - 4 {
|
||||||
|
return Err(malformed("control frame length"));
|
||||||
|
}
|
||||||
|
Ok(EncryptedFrame {
|
||||||
|
sequence: u32_le(W, frame, 4)?,
|
||||||
|
tag: array::<GCM_TAG_LEN>(W, frame, 8)?,
|
||||||
|
ciphertext: frame.get(FRAME_HEADER_LEN..).unwrap_or(&[]),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key.
|
/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ControlCipher {
|
pub struct ControlCipher {
|
||||||
key: [u8; 16],
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ControlCipher {
|
impl ControlCipher {
|
||||||
/// A cipher for `rikey`.
|
/// A cipher for `rikey`.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new(rikey: [u8; 16]) -> Self {
|
pub fn new(rikey: [u8; 16]) -> Self {
|
||||||
Self { key: rikey }
|
Self { key: zeroize::Zeroizing::new(rikey) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn aead(&self) -> Aes128Gcm {
|
||||||
|
Aes128Gcm::new((&*self.key).into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encrypts one message (plaintext = type, length, body) into a whole frame.
|
/// Encrypts one message (plaintext = type, length, body) into a whole frame.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]. Phase A: always
|
/// [`Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]; [`Error::Crypto`] if sealing fails.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result<Vec<u8>> {
|
pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (sequence, direction, plaintext, &self.key);
|
cap("control frame", MAX_FRAME_BYTES, FRAME_HEADER_LEN.saturating_add(plaintext.len()))?;
|
||||||
Err(crate::Error::Unimplemented)
|
let n = nonce(sequence, direction)?;
|
||||||
|
let mut body = plaintext.to_vec();
|
||||||
|
let tag = self
|
||||||
|
.aead()
|
||||||
|
.encrypt_inout_detached(&n.into(), b"", body.as_mut_slice().into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
let len = u16::try_from(4 + GCM_TAG_LEN + body.len()).map_err(|_| malformed("control frame length"))?;
|
||||||
|
let mut out = Vec::with_capacity(FRAME_HEADER_LEN + body.len());
|
||||||
|
out.extend_from_slice(&ENCRYPTED_FRAME_TYPE.to_le_bytes());
|
||||||
|
out.extend_from_slice(&len.to_le_bytes());
|
||||||
|
out.extend_from_slice(&sequence.to_le_bytes());
|
||||||
|
out.extend_from_slice(tag.as_slice());
|
||||||
|
out.extend_from_slice(&body);
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks and decrypts one frame; returns its sequence number and the plaintext message.
|
/// Checks and decrypts one frame; returns its sequence number and the plaintext message.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Parser errors as [`parse_encrypted_frame`]; [`crate::Error::Crypto`] when the tag does not verify. Phase A:
|
/// Parser errors as [`parse_encrypted_frame`]; [`Error::Crypto`] when the tag does not verify.
|
||||||
/// always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec<u8>)> {
|
pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec<u8>)> {
|
||||||
let _ = (direction, frame);
|
let f = parse_encrypted_frame(frame)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let n = nonce(f.sequence, direction)?;
|
||||||
|
let mut body = f.ciphertext.to_vec();
|
||||||
|
self.aead()
|
||||||
|
.decrypt_inout_detached(&n.into(), b"", body.as_mut_slice().into(), &f.tag.into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
Ok((f.sequence, body))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
use crate::Result;
|
use crate::Result;
|
||||||
use crate::input::InputEvent;
|
use crate::input::InputEvent;
|
||||||
|
use crate::util::{byte, cap, malformed, need, u16_le, u32_be};
|
||||||
|
|
||||||
/// Length of the message header (type + length).
|
/// Length of the message header (type + length).
|
||||||
pub const MESSAGE_HEADER_LEN: usize = 4;
|
pub const MESSAGE_HEADER_LEN: usize = 4;
|
||||||
@@ -48,14 +49,37 @@ pub enum MessageType {
|
|||||||
TriggerEffect = 0x5503,
|
TriggerEffect = 0x5503,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl MessageType {
|
||||||
|
const ALL: [Self; 16] = [
|
||||||
|
Self::StartA,
|
||||||
|
Self::StartB,
|
||||||
|
Self::InvalidateRefFrames,
|
||||||
|
Self::IdrFrame,
|
||||||
|
Self::LossStats,
|
||||||
|
Self::FrameStats,
|
||||||
|
Self::InputData,
|
||||||
|
Self::PeriodicPing,
|
||||||
|
Self::Termination,
|
||||||
|
Self::TerminationExtended,
|
||||||
|
Self::HdrMode,
|
||||||
|
Self::RumbleData,
|
||||||
|
Self::RumbleTriggers,
|
||||||
|
Self::MotionEvent,
|
||||||
|
Self::RgbLed,
|
||||||
|
Self::TriggerEffect,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
impl TryFrom<u16> for MessageType {
|
impl TryFrom<u16> for MessageType {
|
||||||
type Error = crate::Error;
|
type Error = crate::Error;
|
||||||
|
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] for an unknown code. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::UnexpectedValue`] for an unknown code.
|
||||||
fn try_from(code: u16) -> Result<Self> {
|
fn try_from(code: u16) -> Result<Self> {
|
||||||
let _ = code;
|
Self::ALL
|
||||||
Err(crate::Error::Unimplemented)
|
.into_iter()
|
||||||
|
.find(|t| *t as u16 == code)
|
||||||
|
.ok_or(crate::Error::UnexpectedValue { what: "control message type", value: code.into() })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,11 +96,16 @@ pub struct RawMessage<'a> {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
/// [`crate::Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
||||||
/// [`MESSAGE_HEADER_LEN`], [`crate::Error::Malformed`] for a length that does not match. Phase A: always
|
/// [`MESSAGE_HEADER_LEN`], [`crate::Error::Malformed`] for a length that does not match.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_message(message: &[u8]) -> Result<RawMessage<'_>> {
|
pub fn parse_message(message: &[u8]) -> Result<RawMessage<'_>> {
|
||||||
let _ = message;
|
const W: &str = "control message";
|
||||||
Err(crate::Error::Unimplemented)
|
cap(W, MAX_MESSAGE_BYTES, message.len())?;
|
||||||
|
need(W, MESSAGE_HEADER_LEN, message.len())?;
|
||||||
|
let message_type = u16_le(W, message, 0)?;
|
||||||
|
if usize::from(u16_le(W, message, 2)?) != message.len() - MESSAGE_HEADER_LEN {
|
||||||
|
return Err(malformed("control message length"));
|
||||||
|
}
|
||||||
|
Ok(RawMessage { message_type, body: message.get(MESSAGE_HEADER_LEN..).unwrap_or(&[]) })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Motion sensor kinds of `MOTION_EVENT`.
|
/// Motion sensor kinds of `MOTION_EVENT`.
|
||||||
@@ -169,14 +198,70 @@ pub enum HostMessage {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Interprets a decrypted message from the host.
|
fn exact(body: &[u8], len: usize, what: &'static str) -> Result<()> {
|
||||||
|
if body.len() == len { Ok(()) } else { Err(malformed(what)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Interprets a decrypted message from the host. Bodies are little-endian (UNKNOWN U23), except the extended
|
||||||
|
/// termination code (big-endian).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`parse_message`]; [`crate::Error::Malformed`] when a known type's body has the wrong length;
|
/// As [`parse_message`]; [`crate::Error::Malformed`] when a known type's body has the wrong length;
|
||||||
/// [`crate::Error::UnexpectedValue`] for an unknown motion kind. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::UnexpectedValue`] for an unknown motion kind.
|
||||||
pub fn parse_host_message(message: &[u8]) -> Result<HostMessage> {
|
pub fn parse_host_message(message: &[u8]) -> Result<HostMessage> {
|
||||||
let _ = message;
|
const W: &str = "host message";
|
||||||
Err(crate::Error::Unimplemented)
|
let raw = parse_message(message)?;
|
||||||
|
let b = raw.body;
|
||||||
|
let u16_at = |at: usize| u16_le(W, b, at);
|
||||||
|
Ok(match raw.message_type {
|
||||||
|
0x010b => {
|
||||||
|
exact(b, 10, "rumble body")?;
|
||||||
|
HostMessage::Rumble { controller: u16_at(4)?, low_frequency: u16_at(6)?, high_frequency: u16_at(8)? }
|
||||||
|
}
|
||||||
|
0x5500 => {
|
||||||
|
exact(b, 6, "trigger rumble body")?;
|
||||||
|
HostMessage::RumbleTriggers { controller: u16_at(0)?, left: u16_at(2)?, right: u16_at(4)? }
|
||||||
|
}
|
||||||
|
0x5501 => {
|
||||||
|
exact(b, 5, "motion event body")?;
|
||||||
|
let kind = match byte(W, b, 4)? {
|
||||||
|
1 => MotionKind::Accelerometer,
|
||||||
|
2 => MotionKind::Gyroscope,
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "motion kind", value: other.into() }),
|
||||||
|
};
|
||||||
|
HostMessage::MotionEvent { controller: u16_at(0)?, rate_hz: u16_at(2)?, kind }
|
||||||
|
}
|
||||||
|
0x5502 => {
|
||||||
|
exact(b, 5, "rgb led body")?;
|
||||||
|
HostMessage::RgbLed { controller: u16_at(0)?, r: byte(W, b, 2)?, g: byte(W, b, 3)?, b: byte(W, b, 4)? }
|
||||||
|
}
|
||||||
|
0x0109 => {
|
||||||
|
exact(b, 4, "termination body")?;
|
||||||
|
HostMessage::Termination { error_code: Some(u32_be(W, b, 0)?) }
|
||||||
|
}
|
||||||
|
0x0100 => HostMessage::Termination { error_code: None },
|
||||||
|
0x010e => {
|
||||||
|
let enabled = byte(W, b, 0).map_err(|_| malformed("hdr mode body"))? != 0;
|
||||||
|
let metadata = match b.len() {
|
||||||
|
1 => None,
|
||||||
|
31 => {
|
||||||
|
let v = |i: usize| u16_le(W, b, 1 + 2 * i);
|
||||||
|
Some(HdrMetadata {
|
||||||
|
display_primaries: [(v(0)?, v(1)?), (v(2)?, v(3)?), (v(4)?, v(5)?)],
|
||||||
|
white_point: (v(6)?, v(7)?),
|
||||||
|
max_display_luminance: v(8)?,
|
||||||
|
min_display_luminance: v(9)?,
|
||||||
|
max_content_light_level: v(10)?,
|
||||||
|
max_frame_average_light_level: v(11)?,
|
||||||
|
max_full_frame_luminance: v(12)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("hdr mode body")),
|
||||||
|
};
|
||||||
|
HostMessage::HdrMode { enabled, metadata }
|
||||||
|
}
|
||||||
|
other => HostMessage::Other { message_type: other, body_len: b.len() },
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A message to the host.
|
/// A message to the host.
|
||||||
@@ -204,9 +289,26 @@ pub enum ClientMessage {
|
|||||||
/// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`].
|
/// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN; input errors as
|
/// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN (U10: START_A, START_B,
|
||||||
/// [`crate::input::encode_input`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// PERIODIC_PING, IDR request; refused rather than guessed); input errors as [`crate::input::encode_input`].
|
||||||
pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
|
pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
|
||||||
let _ = message;
|
match message {
|
||||||
Err(crate::Error::Unimplemented)
|
ClientMessage::InvalidateRefFrames { first, last } => {
|
||||||
|
let mut m = Vec::with_capacity(28);
|
||||||
|
m.extend_from_slice(&(MessageType::InvalidateRefFrames as u16).to_le_bytes());
|
||||||
|
m.extend_from_slice(&24u16.to_le_bytes());
|
||||||
|
m.extend_from_slice(&first.to_le_bytes());
|
||||||
|
m.extend_from_slice(&[0; 4]);
|
||||||
|
m.extend_from_slice(&last.to_le_bytes());
|
||||||
|
m.extend_from_slice(&[0; 12]);
|
||||||
|
Ok(m)
|
||||||
|
}
|
||||||
|
ClientMessage::Input(e) => crate::input::encode_input(e),
|
||||||
|
ClientMessage::StartA
|
||||||
|
| ClientMessage::StartB
|
||||||
|
| ClientMessage::PeriodicPing
|
||||||
|
| ClientMessage::RequestIdrFrame => {
|
||||||
|
Err(crate::Error::Unsupported { what: "a control message whose body is still UNKNOWN (U10)" })
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,9 @@
|
|||||||
//! [`HostMessage`]s.
|
//! [`HostMessage`]s.
|
||||||
|
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
use crate::enet::EnetConfig;
|
use crate::enet::{Delivery, EnetClient, EnetConfig, EnetEvent};
|
||||||
use crate::{Instant, RandomSource, Result};
|
use crate::{Instant, RandomSource, Result};
|
||||||
|
|
||||||
pub mod frame;
|
pub mod frame;
|
||||||
@@ -54,71 +55,113 @@ pub enum ControlEvent {
|
|||||||
/// One control stream.
|
/// One control stream.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ControlStream {
|
pub struct ControlStream {
|
||||||
next_sequence: u32,
|
enet: EnetClient,
|
||||||
|
cipher: ControlCipher,
|
||||||
|
/// Next sequence number to seal with; `u32::MAX + 1` once the space is used up.
|
||||||
|
next_sequence: u64,
|
||||||
|
/// Highest host sequence number accepted so far.
|
||||||
|
last_host_sequence: Option<u32>,
|
||||||
|
events: VecDeque<ControlEvent>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ControlStream {
|
impl ControlStream {
|
||||||
/// Starts connecting.
|
/// Starts connecting.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`crate::enet::EnetClient::connect`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// As [`crate::enet::EnetClient::connect`].
|
||||||
pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = (config, now, rng);
|
Ok(Self {
|
||||||
Err(crate::Error::Unimplemented)
|
enet: EnetClient::connect(config.enet, now, rng)?,
|
||||||
|
cipher: ControlCipher::new(config.rikey),
|
||||||
|
next_sequence: 0,
|
||||||
|
last_host_sequence: None,
|
||||||
|
events: VecDeque::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves ENet events into control events, opening every host frame.
|
||||||
|
fn drain(&mut self) {
|
||||||
|
while let Some(e) = self.enet.poll_event() {
|
||||||
|
let event = match e {
|
||||||
|
EnetEvent::Connected => ControlEvent::Connected,
|
||||||
|
EnetEvent::Disconnected { .. } => ControlEvent::Disconnected,
|
||||||
|
EnetEvent::TimedOut => ControlEvent::TimedOut,
|
||||||
|
EnetEvent::Received { data, .. } => self.open(&data),
|
||||||
|
};
|
||||||
|
self.events.push_back(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens one host frame. A frame that fails, or whose number is not above the last accepted one, is dropped
|
||||||
|
/// without touching the replay state; a frame that opens moves it forward even if its message is unknown.
|
||||||
|
fn open(&mut self, frame: &[u8]) -> ControlEvent {
|
||||||
|
let Ok((sequence, plain)) = self.cipher.open(Direction::HostToClient, frame) else {
|
||||||
|
return ControlEvent::Dropped;
|
||||||
|
};
|
||||||
|
if self.last_host_sequence.is_some_and(|last| sequence <= last) {
|
||||||
|
return ControlEvent::Dropped;
|
||||||
|
}
|
||||||
|
self.last_host_sequence = Some(sequence);
|
||||||
|
parse_host_message(&plain).map_or(ControlEvent::Dropped, ControlEvent::Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one datagram from the control port.
|
/// Feeds one datagram from the control port.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`crate::enet::EnetClient::handle_datagram`]. Bad frames inside a good datagram are not errors; they
|
/// As [`crate::enet::EnetClient::handle_datagram`]. Bad frames inside a good datagram are not errors; they
|
||||||
/// become [`ControlEvent::Dropped`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// become [`ControlEvent::Dropped`].
|
||||||
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
let r = self.enet.handle_datagram(now, datagram);
|
||||||
Err(crate::Error::Unimplemented)
|
self.drain();
|
||||||
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Seals and queues a message (reliable, channel 0 unless measurement says otherwise).
|
/// Seals and queues a message (reliable, channel 0 unless measurement says otherwise).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`message::encode_client_message`] and [`crate::enet::EnetClient::send`]; [`crate::Error::Closed`] once
|
/// As [`message::encode_client_message`] and [`crate::enet::EnetClient::send`]; [`crate::Error::Closed`] once
|
||||||
/// the sequence space is used up (2^32 messages). Phase A: always [`crate::Error::Unimplemented`].
|
/// the sequence space is used up (2^32 messages).
|
||||||
pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> {
|
pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> {
|
||||||
let _ = (now, message, self.next_sequence);
|
let plain = message::encode_client_message(message)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let sequence = u32::try_from(self.next_sequence).map_err(|_| crate::Error::Closed)?;
|
||||||
|
let frame = self.cipher.seal(sequence, Direction::ClientToHost, &plain)?;
|
||||||
|
self.enet.send(now, 0, Delivery::Reliable, &frame)?;
|
||||||
|
self.next_sequence += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next datagram to send.
|
/// The next datagram to send.
|
||||||
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
||||||
let _ = now;
|
self.enet.poll_transmit(now)
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<ControlEvent> {
|
pub fn poll_event(&mut self) -> Option<ControlEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When [`Self::handle_timeout`] is due.
|
/// When [`Self::handle_timeout`] is due.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
self.enet.poll_timeout()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Advances timers (ENet, periodic ping).
|
/// Advances timers (ENet). `PERIODIC_PING` is not sent while its body is UNKNOWN (U10); ENet's own pings keep
|
||||||
|
/// the connection alive.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// As [`crate::enet::EnetClient::handle_timeout`].
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
let r = self.enet.handle_timeout(now);
|
||||||
Err(crate::Error::Unimplemented)
|
self.drain();
|
||||||
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Closes the stream gracefully.
|
/// Closes the stream gracefully.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Closed`] when already closed. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Closed`] when already closed.
|
||||||
pub fn close(&mut self, now: Instant) -> Result<()> {
|
pub fn close(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
self.enet.disconnect(now, 0)
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,18 @@
|
|||||||
//! while let Some(e) = peer.poll_event() { … }
|
//! while let Some(e) = peer.poll_event() { … }
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Reliable packets are delivered in order per channel; duplicates and stale sequence numbers are acknowledged but
|
||||||
|
//! never delivered twice; sequence numbers too far ahead are dropped. Fragments are reassembled with every length
|
||||||
|
//! checked against [`MAX_PACKET_BYTES`] before memory is reserved.
|
||||||
|
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
|
use std::collections::{BTreeMap, VecDeque};
|
||||||
|
|
||||||
use crate::{Instant, RandomSource, Result};
|
use protocol::{Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_DATAGRAM_BYTES, MIN_MTU, NO_PEER_ID};
|
||||||
|
|
||||||
|
use crate::util::malformed;
|
||||||
|
use crate::{Error, Instant, RandomSource, Result};
|
||||||
|
|
||||||
pub mod protocol;
|
pub mod protocol;
|
||||||
|
|
||||||
@@ -24,6 +32,25 @@ pub const MAX_PACKET_BYTES: usize = 64 * 1024;
|
|||||||
pub const MAX_SEND_QUEUE: usize = 1024;
|
pub const MAX_SEND_QUEUE: usize = 1024;
|
||||||
/// Maximum number of reliable commands waiting for an acknowledgement.
|
/// Maximum number of reliable commands waiting for an acknowledgement.
|
||||||
pub const MAX_IN_FLIGHT: usize = 256;
|
pub const MAX_IN_FLIGHT: usize = 256;
|
||||||
|
/// Reliable sequence numbers accepted ahead of the next expected one (7 of ENet's 4096-wide windows).
|
||||||
|
pub const RELIABLE_WINDOW: u16 = 0x7000;
|
||||||
|
/// Out-of-order reliable commands kept per channel while waiting for a gap to fill.
|
||||||
|
pub const MAX_PENDING_PER_CHANNEL: usize = 1024;
|
||||||
|
/// Packets being reassembled at once; the oldest is dropped when another starts.
|
||||||
|
pub const MAX_REASSEMBLIES: usize = 4;
|
||||||
|
/// Acknowledgements kept for sending; beyond this the oldest are dropped (the host retransmits).
|
||||||
|
pub const MAX_PENDING_ACKS: usize = 4096;
|
||||||
|
|
||||||
|
/// Channel id of connection-level commands.
|
||||||
|
const CONNECTION_CHANNEL: u8 = 0xFF;
|
||||||
|
/// Our peer id towards the host (we are the only peer of this client).
|
||||||
|
const LOCAL_PEER_ID: u16 = 0;
|
||||||
|
/// Window size we offer (ENet's maximum, as for unlimited bandwidth).
|
||||||
|
const WINDOW_SIZE: u32 = 65_536;
|
||||||
|
/// Retransmission timeout before any round trip is measured (stock ENet's initial round-trip time).
|
||||||
|
const INITIAL_RTO: Duration = Duration::from_millis(500);
|
||||||
|
const MIN_RTO: Duration = Duration::from_millis(100);
|
||||||
|
const MAX_RTO: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
/// How a packet is delivered.
|
/// How a packet is delivered.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -86,79 +113,614 @@ pub enum EnetEvent {
|
|||||||
TimedOut,
|
TimedOut,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A reliable command in the sequence stream of a channel, as it will be processed in order.
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum Pending {
|
||||||
|
Data(Vec<u8>),
|
||||||
|
Fragment(Fragment),
|
||||||
|
/// A command that occupies its sequence number but carries nothing usable (a lying fragment).
|
||||||
|
Skip,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Channel {
|
||||||
|
/// Last reliable sequence number we sent.
|
||||||
|
out_reliable: u16,
|
||||||
|
/// Last unreliable sequence number we sent.
|
||||||
|
out_unreliable: u16,
|
||||||
|
/// Last reliable sequence number delivered from the host.
|
||||||
|
in_reliable: u16,
|
||||||
|
/// Last unreliable sequence number delivered from the host.
|
||||||
|
in_unreliable: Option<u16>,
|
||||||
|
pending: BTreeMap<u16, Pending>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Reassembly {
|
||||||
|
channel: u8,
|
||||||
|
start: u16,
|
||||||
|
count: u32,
|
||||||
|
total: u32,
|
||||||
|
got: Vec<bool>,
|
||||||
|
received: u32,
|
||||||
|
data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct InFlight {
|
||||||
|
command: Command,
|
||||||
|
first_sent: Instant,
|
||||||
|
sent_at: Instant,
|
||||||
|
rto: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A command waiting to be sent; `ends_packet` marks the last command of a user packet (for the queue cap).
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Outgoing {
|
||||||
|
command: Command,
|
||||||
|
ends_packet: bool,
|
||||||
|
}
|
||||||
|
|
||||||
/// The ENet client peer.
|
/// The ENet client peer.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct EnetClient {
|
pub struct EnetClient {
|
||||||
|
config: EnetConfig,
|
||||||
state: EnetState,
|
state: EnetState,
|
||||||
|
connect_id: u32,
|
||||||
|
host_peer_id: u16,
|
||||||
|
out_session: u8,
|
||||||
|
in_session: u8,
|
||||||
|
channel_count: u8,
|
||||||
|
mtu: usize,
|
||||||
|
connection_out_reliable: u16,
|
||||||
|
unsequenced_group: u16,
|
||||||
|
channels: Vec<Channel>,
|
||||||
|
outgoing: VecDeque<Outgoing>,
|
||||||
|
queued_packets: usize,
|
||||||
|
resend: VecDeque<Command>,
|
||||||
|
acks: VecDeque<Command>,
|
||||||
|
in_flight: Vec<InFlight>,
|
||||||
|
reassemblies: Vec<Reassembly>,
|
||||||
|
events: VecDeque<EnetEvent>,
|
||||||
|
last_send: Instant,
|
||||||
|
srtt: Option<Duration>,
|
||||||
|
rttvar: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ms16(t: Instant) -> u16 {
|
||||||
|
((t.as_micros() / 1000) & 0xFFFF) as u16
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EnetClient {
|
impl EnetClient {
|
||||||
/// Starts connecting: queues the connect datagram. The connect id comes from `rng`.
|
/// Starts connecting: queues the connect datagram. The connect id comes from `rng`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a config outside ENet's limits. Phase A: always
|
/// [`Error::Malformed`] for a config outside ENet's limits (MTU 576..=4096, at least one channel).
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = (config, now, rng);
|
if config.mtu < MIN_MTU || usize::from(config.mtu) > MAX_DATAGRAM_BYTES || config.channel_count == 0 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("enet config"));
|
||||||
|
}
|
||||||
|
let mut id = [0u8; 4];
|
||||||
|
rng.fill(&mut id);
|
||||||
|
let connect_id = u32::from_le_bytes(id);
|
||||||
|
let mut c = Self {
|
||||||
|
config,
|
||||||
|
state: EnetState::Connecting,
|
||||||
|
connect_id,
|
||||||
|
host_peer_id: NO_PEER_ID,
|
||||||
|
out_session: 0,
|
||||||
|
in_session: 0,
|
||||||
|
channel_count: config.channel_count,
|
||||||
|
mtu: usize::from(config.mtu),
|
||||||
|
connection_out_reliable: 0,
|
||||||
|
unsequenced_group: 0,
|
||||||
|
channels: (0..config.channel_count).map(|_| Channel::default()).collect(),
|
||||||
|
outgoing: VecDeque::new(),
|
||||||
|
queued_packets: 0,
|
||||||
|
resend: VecDeque::new(),
|
||||||
|
acks: VecDeque::new(),
|
||||||
|
in_flight: Vec::new(),
|
||||||
|
reassemblies: Vec::new(),
|
||||||
|
events: VecDeque::new(),
|
||||||
|
last_send: now,
|
||||||
|
srtt: None,
|
||||||
|
rttvar: Duration::ZERO,
|
||||||
|
};
|
||||||
|
let params = ConnectParams {
|
||||||
|
outgoing_peer_id: LOCAL_PEER_ID,
|
||||||
|
incoming_session_id: 0xFF,
|
||||||
|
outgoing_session_id: 0xFF,
|
||||||
|
mtu: u32::from(config.mtu),
|
||||||
|
window_size: WINDOW_SIZE,
|
||||||
|
channel_count: u32::from(config.channel_count),
|
||||||
|
incoming_bandwidth: 0,
|
||||||
|
outgoing_bandwidth: 0,
|
||||||
|
packet_throttle_interval: 5000,
|
||||||
|
packet_throttle_acceleration: 2,
|
||||||
|
packet_throttle_deceleration: 2,
|
||||||
|
connect_id,
|
||||||
|
};
|
||||||
|
c.queue_connection_command(CommandBody::Connect { params, data: config.connect_data });
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn queue_connection_command(&mut self, body: CommandBody) {
|
||||||
|
self.connection_out_reliable = self.connection_out_reliable.wrapping_add(1);
|
||||||
|
let command = Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: CONNECTION_CHANNEL,
|
||||||
|
reliable_sequence: self.connection_out_reliable,
|
||||||
|
body,
|
||||||
|
};
|
||||||
|
self.outgoing.push_back(Outgoing { command, ends_packet: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rto(&self) -> Duration {
|
||||||
|
match self.srtt {
|
||||||
|
None => INITIAL_RTO,
|
||||||
|
Some(s) => (s + 4 * self.rttvar).clamp(MIN_RTO, MAX_RTO),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close(&mut self, event: EnetEvent) {
|
||||||
|
self.state = EnetState::Disconnected;
|
||||||
|
self.events.push_back(event);
|
||||||
|
self.outgoing.clear();
|
||||||
|
self.queued_packets = 0;
|
||||||
|
self.resend.clear();
|
||||||
|
self.in_flight.clear();
|
||||||
|
self.reassemblies.clear();
|
||||||
|
for ch in &mut self.channels {
|
||||||
|
ch.pending.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one received datagram. Datagrams for another peer id or session are dropped without error.
|
/// Feeds one received datagram. Datagrams for another peer id or session are dropped without error.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Parser errors as [`protocol::parse_datagram`]; [`crate::Error::TooLarge`] when a reassembly would exceed
|
/// Parser errors as [`protocol::parse_datagram`]; [`Error::TooLarge`] when a fragment announces more than
|
||||||
/// [`MAX_PACKET_BYTES`]; [`crate::Error::Closed`] after `Disconnected`. A malformed datagram never changes the
|
/// [`MAX_PACKET_BYTES`]; [`Error::Closed`] after `Disconnected`. A malformed datagram never changes the
|
||||||
/// connection state. Phase A: always [`crate::Error::Unimplemented`].
|
/// connection state.
|
||||||
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
if self.state == EnetState::Disconnected {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::Closed);
|
||||||
|
}
|
||||||
|
let d = protocol::parse_datagram(datagram)?;
|
||||||
|
if d.peer_id != LOCAL_PEER_ID {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if self.state != EnetState::Connecting && d.session_id != self.in_session {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let sent_time = d.sent_time.unwrap_or(0);
|
||||||
|
let mut first_error = None;
|
||||||
|
for c in d.commands {
|
||||||
|
if self.state == EnetState::Disconnected {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Err(e) = self.command(now, sent_time, c) {
|
||||||
|
first_error.get_or_insert(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
first_error.map_or(Ok(()), Err)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Queues a packet. Packets larger than the MTU are fragmented.
|
fn ack(&mut self, channel: u8, seq: u16, sent_time: u16) {
|
||||||
|
if self.acks.len() >= MAX_PENDING_ACKS {
|
||||||
|
self.acks.pop_front();
|
||||||
|
}
|
||||||
|
self.acks.push_back(Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: seq,
|
||||||
|
body: CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: sent_time },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command(&mut self, now: Instant, sent_time: u16, c: Command) -> Result<()> {
|
||||||
|
let (channel, seq) = (c.channel_id, c.reliable_sequence);
|
||||||
|
match c.body {
|
||||||
|
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
|
||||||
|
self.acknowledged(now, channel, received_reliable_sequence, received_sent_time);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::VerifyConnect(p) => {
|
||||||
|
if c.acknowledge {
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
}
|
||||||
|
if self.state == EnetState::Connecting && p.connect_id == self.connect_id {
|
||||||
|
self.host_peer_id = p.outgoing_peer_id & protocol::MAX_PEER_ID;
|
||||||
|
self.out_session = p.incoming_session_id & 0x3;
|
||||||
|
self.in_session = p.outgoing_session_id & 0x3;
|
||||||
|
let count = u8::try_from(p.channel_count.clamp(1, 255)).unwrap_or(1);
|
||||||
|
self.channel_count = self.channel_count.min(count);
|
||||||
|
let mtu = usize::try_from(p.mtu).unwrap_or(MAX_DATAGRAM_BYTES);
|
||||||
|
self.mtu = self.mtu.min(mtu).max(usize::from(MIN_MTU));
|
||||||
|
self.in_flight.retain(|f| !matches!(f.command.body, CommandBody::Connect { .. }));
|
||||||
|
self.state = EnetState::Connected;
|
||||||
|
self.events.push_back(EnetEvent::Connected);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::Disconnect { data } => {
|
||||||
|
if c.acknowledge {
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
}
|
||||||
|
self.close(EnetEvent::Disconnected { data });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {
|
||||||
|
if c.acknowledge {
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::Connect { .. } => Ok(()),
|
||||||
|
CommandBody::SendReliable(data) => self.reliable(channel, seq, sent_time, Pending::Data(data)),
|
||||||
|
CommandBody::SendFragment(f) => {
|
||||||
|
let check = check_fragment(seq, &f);
|
||||||
|
let pending = match &check {
|
||||||
|
Ok(()) => Pending::Fragment(f),
|
||||||
|
Err(_) => Pending::Skip,
|
||||||
|
};
|
||||||
|
self.reliable(channel, seq, sent_time, pending)?;
|
||||||
|
check
|
||||||
|
}
|
||||||
|
CommandBody::SendUnreliable { unreliable_sequence, data } => {
|
||||||
|
if self.state == EnetState::Connected
|
||||||
|
&& channel < self.channel_count
|
||||||
|
&& let Some(ch) = self.channels.get_mut(usize::from(channel))
|
||||||
|
{
|
||||||
|
let newer = ch
|
||||||
|
.in_unreliable
|
||||||
|
.is_none_or(|last| (1..0x8000).contains(&unreliable_sequence.wrapping_sub(last)));
|
||||||
|
if newer {
|
||||||
|
ch.in_unreliable = Some(unreliable_sequence);
|
||||||
|
self.events.push_back(EnetEvent::Received { channel, data });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::SendUnsequenced { data, .. } => {
|
||||||
|
if self.state == EnetState::Connected && channel < self.channel_count {
|
||||||
|
self.events.push_back(EnetEvent::Received { channel, data });
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::SendUnreliableFragment(_) => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reliable command on a data channel: acknowledged, ordered, then processed in sequence.
|
||||||
|
fn reliable(&mut self, channel: u8, seq: u16, sent_time: u16, pending: Pending) -> Result<()> {
|
||||||
|
if self.state != EnetState::Connected || channel >= self.channel_count {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return Ok(()) };
|
||||||
|
let next = ch.in_reliable.wrapping_add(1);
|
||||||
|
let distance = seq.wrapping_sub(next);
|
||||||
|
if distance >= 0x8000 {
|
||||||
|
// Already delivered: a retransmission. Acknowledge again, deliver nothing.
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if distance >= RELIABLE_WINDOW || ch.pending.len() >= MAX_PENDING_PER_CHANNEL {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
ch.pending.entry(seq).or_insert(pending);
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
self.deliver_in_order(channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver_in_order(&mut self, channel: u8) -> Result<()> {
|
||||||
|
loop {
|
||||||
|
let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return Ok(()) };
|
||||||
|
let next = ch.in_reliable.wrapping_add(1);
|
||||||
|
let Some(p) = ch.pending.remove(&next) else { return Ok(()) };
|
||||||
|
ch.in_reliable = next;
|
||||||
|
match p {
|
||||||
|
Pending::Data(data) => self.events.push_back(EnetEvent::Received { channel, data }),
|
||||||
|
Pending::Fragment(f) => self.fragment(channel, f),
|
||||||
|
Pending::Skip => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fragment(&mut self, channel: u8, f: Fragment) {
|
||||||
|
let idx = match self.reassemblies.iter().position(|r| r.channel == channel && r.start == f.start_sequence) {
|
||||||
|
Some(i) => i,
|
||||||
|
None => {
|
||||||
|
if self.reassemblies.len() >= MAX_REASSEMBLIES {
|
||||||
|
self.reassemblies.remove(0);
|
||||||
|
}
|
||||||
|
let (Ok(count), Ok(total)) = (usize::try_from(f.fragment_count), usize::try_from(f.total_length))
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.reassemblies.push(Reassembly {
|
||||||
|
channel,
|
||||||
|
start: f.start_sequence,
|
||||||
|
count: f.fragment_count,
|
||||||
|
total: f.total_length,
|
||||||
|
got: vec![false; count],
|
||||||
|
received: 0,
|
||||||
|
data: vec![0; total],
|
||||||
|
});
|
||||||
|
self.reassemblies.len() - 1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let Some(r) = self.reassemblies.get_mut(idx) else { return };
|
||||||
|
if r.count != f.fragment_count || r.total != f.total_length {
|
||||||
|
self.reassemblies.remove(idx);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (Ok(number), Ok(offset)) = (usize::try_from(f.fragment_number), usize::try_from(f.fragment_offset)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(seen) = r.got.get_mut(number) else { return };
|
||||||
|
if *seen {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(dest) = r.data.get_mut(offset..offset + f.data.len()) else { return };
|
||||||
|
dest.copy_from_slice(&f.data);
|
||||||
|
*seen = true;
|
||||||
|
r.received += 1;
|
||||||
|
if r.received == r.count {
|
||||||
|
let done = self.reassemblies.remove(idx);
|
||||||
|
self.events.push_back(EnetEvent::Received { channel, data: done.data });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acknowledged(&mut self, now: Instant, channel: u8, seq: u16, sent_time: u16) {
|
||||||
|
let before = self.in_flight.len();
|
||||||
|
let mut acked_disconnect = false;
|
||||||
|
self.in_flight.retain(|f| {
|
||||||
|
let hit = f.command.channel_id == channel && f.command.reliable_sequence == seq;
|
||||||
|
if hit && matches!(f.command.body, CommandBody::Disconnect { .. }) {
|
||||||
|
acked_disconnect = true;
|
||||||
|
}
|
||||||
|
!hit
|
||||||
|
});
|
||||||
|
self.resend.retain(|c| !(c.channel_id == channel && c.reliable_sequence == seq));
|
||||||
|
if self.in_flight.len() < before {
|
||||||
|
let sample = ms16(now).wrapping_sub(sent_time);
|
||||||
|
if sample < 10_000 {
|
||||||
|
let sample = Duration::from_millis(u64::from(sample));
|
||||||
|
match self.srtt {
|
||||||
|
None => {
|
||||||
|
self.srtt = Some(sample);
|
||||||
|
self.rttvar = sample / 2;
|
||||||
|
}
|
||||||
|
Some(s) => {
|
||||||
|
let diff = s.abs_diff(sample);
|
||||||
|
self.rttvar = (self.rttvar * 3 + diff) / 4;
|
||||||
|
self.srtt = Some((s * 7 + sample) / 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if acked_disconnect && self.state == EnetState::Disconnecting {
|
||||||
|
self.state = EnetState::Disconnected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Queues a packet. Packets larger than one command within the MTU are fragmented.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::State`] unless connected, [`crate::Error::UnexpectedValue`] for a channel outside the
|
/// [`Error::State`] unless connected, [`Error::UnexpectedValue`] for a channel outside the negotiated count,
|
||||||
/// negotiated count, [`crate::Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue. Phase A: always
|
/// [`Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue ([`MAX_SEND_QUEUE`] packets).
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> {
|
pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> {
|
||||||
let _ = (now, channel, delivery, data);
|
let _ = now;
|
||||||
Err(crate::Error::Unimplemented)
|
if self.state != EnetState::Connected {
|
||||||
|
return Err(Error::State { expected: "enet connected" });
|
||||||
|
}
|
||||||
|
if channel >= self.channel_count {
|
||||||
|
return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() });
|
||||||
|
}
|
||||||
|
crate::util::cap("enet packet", MAX_PACKET_BYTES, data.len())?;
|
||||||
|
crate::util::cap("enet send queue", MAX_SEND_QUEUE, self.queued_packets + 1)?;
|
||||||
|
// Header with sent time (4) plus the command header and its fields.
|
||||||
|
let single = self.mtu.saturating_sub(4 + 6);
|
||||||
|
let piece = self.mtu.saturating_sub(4 + 24).max(1);
|
||||||
|
let Some(ch) = self.channels.get_mut(usize::from(channel)) else {
|
||||||
|
return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() });
|
||||||
|
};
|
||||||
|
let mut commands = Vec::new();
|
||||||
|
match delivery {
|
||||||
|
Delivery::Reliable | Delivery::Unreliable if data.len() > single => {
|
||||||
|
let count = data.len().div_ceil(piece);
|
||||||
|
let start = ch.out_reliable.wrapping_add(1);
|
||||||
|
let total = u32::try_from(data.len()).unwrap_or(u32::MAX);
|
||||||
|
for (n, chunk) in data.chunks(piece).enumerate() {
|
||||||
|
ch.out_reliable = ch.out_reliable.wrapping_add(1);
|
||||||
|
let f = Fragment {
|
||||||
|
start_sequence: start,
|
||||||
|
fragment_count: u32::try_from(count).unwrap_or(u32::MAX),
|
||||||
|
fragment_number: u32::try_from(n).unwrap_or(u32::MAX),
|
||||||
|
total_length: total,
|
||||||
|
fragment_offset: u32::try_from(n * piece).unwrap_or(u32::MAX),
|
||||||
|
data: chunk.to_vec(),
|
||||||
|
};
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: ch.out_reliable,
|
||||||
|
body: CommandBody::SendFragment(f),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Delivery::Reliable => {
|
||||||
|
ch.out_reliable = ch.out_reliable.wrapping_add(1);
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: ch.out_reliable,
|
||||||
|
body: CommandBody::SendReliable(data.to_vec()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Delivery::Unreliable => {
|
||||||
|
ch.out_unreliable = ch.out_unreliable.wrapping_add(1);
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: ch.out_reliable,
|
||||||
|
body: CommandBody::SendUnreliable { unreliable_sequence: ch.out_unreliable, data: data.to_vec() },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Delivery::Unsequenced => {
|
||||||
|
if data.len() > single {
|
||||||
|
return Err(Error::TooLarge { what: "enet unsequenced packet", max: single, actual: data.len() });
|
||||||
|
}
|
||||||
|
self.unsequenced_group = self.unsequenced_group.wrapping_add(1);
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: 0,
|
||||||
|
body: CommandBody::SendUnsequenced {
|
||||||
|
unsequenced_group: self.unsequenced_group,
|
||||||
|
data: data.to_vec(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let last = commands.len().saturating_sub(1);
|
||||||
|
for (i, command) in commands.into_iter().enumerate() {
|
||||||
|
self.outgoing.push_back(Outgoing { command, ends_packet: i == last });
|
||||||
|
}
|
||||||
|
self.queued_packets += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts a graceful disconnect.
|
/// Starts a graceful disconnect.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Closed`] when already disconnected. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Closed`] when already disconnected or disconnecting.
|
||||||
pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> {
|
pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> {
|
||||||
let _ = (now, data);
|
let _ = now;
|
||||||
Err(crate::Error::Unimplemented)
|
if matches!(self.state, EnetState::Disconnected | EnetState::Disconnecting) {
|
||||||
|
return Err(Error::Closed);
|
||||||
|
}
|
||||||
|
self.queue_connection_command(CommandBody::Disconnect { data });
|
||||||
|
self.state = EnetState::Disconnecting;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next datagram to send, at most [`protocol::MAX_DATAGRAM_BYTES`] (acknowledgements, retransmissions,
|
/// The next datagram to send, at most the MTU (acknowledgements, retransmissions, queued packets, pings).
|
||||||
/// queued packets, pings).
|
|
||||||
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
||||||
let _ = now;
|
let budget = self.mtu;
|
||||||
None
|
let mut size = 4;
|
||||||
|
let mut commands: Vec<Command> = Vec::new();
|
||||||
|
let fits = |size: usize, c: &Command, n: usize| {
|
||||||
|
n < protocol::MAX_COMMANDS_PER_DATAGRAM && size + protocol::command_size(c) <= budget
|
||||||
|
};
|
||||||
|
while let Some(a) = self.acks.front() {
|
||||||
|
if !fits(size, a, commands.len()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size += protocol::command_size(a);
|
||||||
|
if let Some(a) = self.acks.pop_front() {
|
||||||
|
commands.push(a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.state != EnetState::Disconnected {
|
||||||
|
let rto = self.rto();
|
||||||
|
while let Some(c) = self.resend.front() {
|
||||||
|
if !fits(size, c, commands.len()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size += protocol::command_size(c);
|
||||||
|
if let Some(c) = self.resend.pop_front() {
|
||||||
|
if let Some(f) = self.in_flight.iter_mut().find(|f| {
|
||||||
|
f.command.channel_id == c.channel_id && f.command.reliable_sequence == c.reliable_sequence
|
||||||
|
}) {
|
||||||
|
f.sent_at = now;
|
||||||
|
}
|
||||||
|
commands.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while let Some(o) = self.outgoing.front() {
|
||||||
|
if !fits(size, &o.command, commands.len()) || self.in_flight.len() >= MAX_IN_FLIGHT {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size += protocol::command_size(&o.command);
|
||||||
|
let Some(o) = self.outgoing.pop_front() else { break };
|
||||||
|
if o.ends_packet {
|
||||||
|
self.queued_packets = self.queued_packets.saturating_sub(1);
|
||||||
|
}
|
||||||
|
if o.command.acknowledge {
|
||||||
|
self.in_flight.push(InFlight { command: o.command.clone(), first_sent: now, sent_at: now, rto });
|
||||||
|
}
|
||||||
|
commands.push(o.command);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if commands.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.last_send = now;
|
||||||
|
let peer_id = if self.state == EnetState::Connecting { NO_PEER_ID } else { self.host_peer_id };
|
||||||
|
let d = Datagram { peer_id, session_id: self.out_session, sent_time: Some(ms16(now)), commands };
|
||||||
|
protocol::encode_datagram(&d).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<EnetEvent> {
|
pub fn poll_event(&mut self) -> Option<EnetEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever.
|
/// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
if self.state == EnetState::Disconnected {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let flight = self
|
||||||
|
.in_flight
|
||||||
|
.iter()
|
||||||
|
.flat_map(|f| [f.sent_at.saturating_add(f.rto), f.first_sent.saturating_add(self.config.timeout)])
|
||||||
|
.min();
|
||||||
|
// Also while packets are only queued: the caller then still gets a deadline, and the data goes out with the
|
||||||
|
// next poll_transmit at the latest.
|
||||||
|
let ping = (self.state == EnetState::Connected && self.in_flight.is_empty())
|
||||||
|
.then(|| self.last_send.saturating_add(self.config.ping_interval));
|
||||||
|
match (flight, ping) {
|
||||||
|
(Some(a), Some(b)) => Some(a.min(b)),
|
||||||
|
(a, b) => a.or(b),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Advances timers: retransmits, pings, or gives up with [`EnetEvent::TimedOut`].
|
/// Advances timers: retransmits, pings, or gives up with [`EnetEvent::TimedOut`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
if self.state == EnetState::Disconnected {
|
||||||
Err(crate::Error::Unimplemented)
|
return Ok(());
|
||||||
|
}
|
||||||
|
let timeout = self.config.timeout;
|
||||||
|
if self.in_flight.iter().any(|f| f.first_sent.saturating_add(timeout) <= now) {
|
||||||
|
self.close(EnetEvent::TimedOut);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
for f in &mut self.in_flight {
|
||||||
|
if f.sent_at.saturating_add(f.rto) <= now
|
||||||
|
&& !self
|
||||||
|
.resend
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.channel_id == f.command.channel_id && c.reliable_sequence == f.command.reliable_sequence)
|
||||||
|
{
|
||||||
|
f.rto = (f.rto * 2).min(MAX_RTO);
|
||||||
|
f.sent_at = now;
|
||||||
|
self.resend.push_back(f.command.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.state == EnetState::Connected
|
||||||
|
&& self.in_flight.is_empty()
|
||||||
|
&& self.outgoing.is_empty()
|
||||||
|
&& self.last_send.saturating_add(self.config.ping_interval) <= now
|
||||||
|
{
|
||||||
|
self.queue_connection_command(CommandBody::Ping);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Connection state.
|
/// Connection state.
|
||||||
@@ -170,6 +732,20 @@ impl EnetClient {
|
|||||||
/// Smoothed round-trip time, once measured.
|
/// Smoothed round-trip time, once measured.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn round_trip_time(&self) -> Option<Duration> {
|
pub fn round_trip_time(&self) -> Option<Duration> {
|
||||||
None
|
self.srtt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The checks a fragment must pass before any memory is reserved for it.
|
||||||
|
fn check_fragment(seq: u16, f: &Fragment) -> Result<()> {
|
||||||
|
let total = usize::try_from(f.total_length).unwrap_or(usize::MAX);
|
||||||
|
crate::util::cap("enet fragmented packet", MAX_PACKET_BYTES, total)?;
|
||||||
|
let offset = usize::try_from(f.fragment_offset).unwrap_or(usize::MAX);
|
||||||
|
let sound = f.fragment_count >= 1
|
||||||
|
&& f.fragment_number < f.fragment_count
|
||||||
|
&& usize::try_from(f.fragment_count).is_ok_and(|c| c <= total.max(1))
|
||||||
|
&& !f.data.is_empty()
|
||||||
|
&& offset.checked_add(f.data.len()).is_some_and(|end| end <= total)
|
||||||
|
&& u32::from(seq.wrapping_sub(f.start_sequence)) == f.fragment_number;
|
||||||
|
if sound { Ok(()) } else { Err(malformed("enet fragment")) }
|
||||||
|
}
|
||||||
|
|||||||
@@ -193,24 +193,260 @@ pub struct Datagram {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Parses one datagram strictly: every length checked against the bytes present, unknown command numbers and
|
/// Parses one datagram strictly: every length checked against the bytes present, unknown command numbers and
|
||||||
/// compressed datagrams refused.
|
/// compressed datagrams refused. The unsequenced flag and the two unused command bits are not kept.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`],
|
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`],
|
||||||
/// [`crate::Error::Truncated`] for a cut command, [`crate::Error::UnexpectedValue`] for an unknown command or the
|
/// [`crate::Error::Truncated`] for a cut header, command or data, [`crate::Error::UnexpectedValue`] for an unknown
|
||||||
/// compressed flag, [`crate::Error::Malformed`] for a data length that does not match. Phase A: always
|
/// command or the compressed flag.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_datagram(datagram: &[u8]) -> crate::Result<Datagram> {
|
pub fn parse_datagram(datagram: &[u8]) -> crate::Result<Datagram> {
|
||||||
let _ = datagram;
|
use crate::util::{byte, cap, slice, u16_be, u32_be};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "enet datagram";
|
||||||
|
cap(W, MAX_DATAGRAM_BYTES, datagram.len())?;
|
||||||
|
let raw = u16_be(W, datagram, 0)?;
|
||||||
|
if raw & HEADER_FLAG_COMPRESSED != 0 {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "enet compressed datagram", value: raw.into() });
|
||||||
|
}
|
||||||
|
let mut pos = 2;
|
||||||
|
let sent_time = if raw & HEADER_FLAG_SENT_TIME != 0 {
|
||||||
|
pos = 4;
|
||||||
|
Some(u16_be(W, datagram, 2)?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let mut commands = Vec::new();
|
||||||
|
while pos < datagram.len() {
|
||||||
|
cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, commands.len() + 1)?;
|
||||||
|
let command = byte(W, datagram, pos)?;
|
||||||
|
let channel_id = byte(W, datagram, pos + 1)?;
|
||||||
|
let reliable_sequence = u16_be(W, datagram, pos + 2)?;
|
||||||
|
let kind = command & 0x0F;
|
||||||
|
let at = pos + 4;
|
||||||
|
let u32_at = |off: usize| u32_be(W, datagram, at + off);
|
||||||
|
let data_of = |len_at: usize, data_at: usize| -> crate::Result<(Vec<u8>, usize)> {
|
||||||
|
let len = usize::from(u16_be(W, datagram, at + len_at)?);
|
||||||
|
Ok((slice(W, datagram, at + data_at, len)?.to_vec(), at + data_at + len))
|
||||||
|
};
|
||||||
|
let params = || -> crate::Result<ConnectParams> {
|
||||||
|
Ok(ConnectParams {
|
||||||
|
outgoing_peer_id: u16_be(W, datagram, at)?,
|
||||||
|
incoming_session_id: byte(W, datagram, at + 2)?,
|
||||||
|
outgoing_session_id: byte(W, datagram, at + 3)?,
|
||||||
|
mtu: u32_at(4)?,
|
||||||
|
window_size: u32_at(8)?,
|
||||||
|
channel_count: u32_at(12)?,
|
||||||
|
incoming_bandwidth: u32_at(16)?,
|
||||||
|
outgoing_bandwidth: u32_at(20)?,
|
||||||
|
packet_throttle_interval: u32_at(24)?,
|
||||||
|
packet_throttle_acceleration: u32_at(28)?,
|
||||||
|
packet_throttle_deceleration: u32_at(32)?,
|
||||||
|
connect_id: u32_at(36)?,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let fragment = || -> crate::Result<(Fragment, usize)> {
|
||||||
|
let start_sequence = u16_be(W, datagram, at)?;
|
||||||
|
let fragment_count = u32_at(4)?;
|
||||||
|
let fragment_number = u32_at(8)?;
|
||||||
|
let total_length = u32_at(12)?;
|
||||||
|
let fragment_offset = u32_at(16)?;
|
||||||
|
let (data, end) = data_of(2, 20)?;
|
||||||
|
Ok((Fragment { start_sequence, fragment_count, fragment_number, total_length, fragment_offset, data }, end))
|
||||||
|
};
|
||||||
|
let (body, end) = match kind {
|
||||||
|
1 => (
|
||||||
|
CommandBody::Acknowledge {
|
||||||
|
received_reliable_sequence: u16_be(W, datagram, at)?,
|
||||||
|
received_sent_time: u16_be(W, datagram, at + 2)?,
|
||||||
|
},
|
||||||
|
at + 4,
|
||||||
|
),
|
||||||
|
2 => {
|
||||||
|
let p = params()?;
|
||||||
|
(CommandBody::Connect { params: p, data: u32_at(40)? }, at + 44)
|
||||||
|
}
|
||||||
|
3 => (CommandBody::VerifyConnect(params()?), at + 40),
|
||||||
|
4 => (CommandBody::Disconnect { data: u32_at(0)? }, at + 4),
|
||||||
|
5 => (CommandBody::Ping, at),
|
||||||
|
6 => {
|
||||||
|
let (data, end) = data_of(0, 2)?;
|
||||||
|
(CommandBody::SendReliable(data), end)
|
||||||
|
}
|
||||||
|
7 => {
|
||||||
|
let unreliable_sequence = u16_be(W, datagram, at)?;
|
||||||
|
let (data, end) = data_of(2, 4)?;
|
||||||
|
(CommandBody::SendUnreliable { unreliable_sequence, data }, end)
|
||||||
|
}
|
||||||
|
8 => {
|
||||||
|
let (f, end) = fragment()?;
|
||||||
|
(CommandBody::SendFragment(f), end)
|
||||||
|
}
|
||||||
|
9 => {
|
||||||
|
let unsequenced_group = u16_be(W, datagram, at)?;
|
||||||
|
let (data, end) = data_of(2, 4)?;
|
||||||
|
(CommandBody::SendUnsequenced { unsequenced_group, data }, end)
|
||||||
|
}
|
||||||
|
10 => (CommandBody::BandwidthLimit { incoming: u32_at(0)?, outgoing: u32_at(4)? }, at + 8),
|
||||||
|
11 => (
|
||||||
|
CommandBody::ThrottleConfigure {
|
||||||
|
interval: u32_at(0)?,
|
||||||
|
acceleration: u32_at(4)?,
|
||||||
|
deceleration: u32_at(8)?,
|
||||||
|
},
|
||||||
|
at + 12,
|
||||||
|
),
|
||||||
|
12 => {
|
||||||
|
let (f, end) = fragment()?;
|
||||||
|
(CommandBody::SendUnreliableFragment(f), end)
|
||||||
|
}
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "enet command", value: other.into() }),
|
||||||
|
};
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: command & COMMAND_FLAG_ACKNOWLEDGE != 0,
|
||||||
|
channel_id,
|
||||||
|
reliable_sequence,
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
pos = end;
|
||||||
|
}
|
||||||
|
Ok(Datagram { peer_id: raw & MAX_PEER_ID, session_id: ((raw >> 12) & 0x3) as u8, sent_time, commands })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The command number of a body.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn kind_of(body: &CommandBody) -> CommandKind {
|
||||||
|
match body {
|
||||||
|
CommandBody::Acknowledge { .. } => CommandKind::Acknowledge,
|
||||||
|
CommandBody::Connect { .. } => CommandKind::Connect,
|
||||||
|
CommandBody::VerifyConnect(_) => CommandKind::VerifyConnect,
|
||||||
|
CommandBody::Disconnect { .. } => CommandKind::Disconnect,
|
||||||
|
CommandBody::Ping => CommandKind::Ping,
|
||||||
|
CommandBody::SendReliable(_) => CommandKind::SendReliable,
|
||||||
|
CommandBody::SendUnreliable { .. } => CommandKind::SendUnreliable,
|
||||||
|
CommandBody::SendFragment(_) => CommandKind::SendFragment,
|
||||||
|
CommandBody::SendUnsequenced { .. } => CommandKind::SendUnsequenced,
|
||||||
|
CommandBody::BandwidthLimit { .. } => CommandKind::BandwidthLimit,
|
||||||
|
CommandBody::ThrottleConfigure { .. } => CommandKind::ThrottleConfigure,
|
||||||
|
CommandBody::SendUnreliableFragment(_) => CommandKind::SendUnreliableFragment,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes one command takes on the wire.
|
||||||
|
#[must_use]
|
||||||
|
pub fn command_size(c: &Command) -> usize {
|
||||||
|
4 + match &c.body {
|
||||||
|
CommandBody::Acknowledge { .. } | CommandBody::Disconnect { .. } => 4,
|
||||||
|
CommandBody::Connect { .. } => 44,
|
||||||
|
CommandBody::VerifyConnect(_) => 40,
|
||||||
|
CommandBody::Ping => 0,
|
||||||
|
CommandBody::SendReliable(d) => 2 + d.len(),
|
||||||
|
CommandBody::SendUnreliable { data, .. } | CommandBody::SendUnsequenced { data, .. } => 4 + data.len(),
|
||||||
|
CommandBody::SendFragment(f) | CommandBody::SendUnreliableFragment(f) => 20 + f.data.len(),
|
||||||
|
CommandBody::BandwidthLimit { .. } => 8,
|
||||||
|
CommandBody::ThrottleConfigure { .. } => 12,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_params(out: &mut Vec<u8>, p: &ConnectParams) {
|
||||||
|
out.extend_from_slice(&p.outgoing_peer_id.to_be_bytes());
|
||||||
|
out.push(p.incoming_session_id);
|
||||||
|
out.push(p.outgoing_session_id);
|
||||||
|
for v in [
|
||||||
|
p.mtu,
|
||||||
|
p.window_size,
|
||||||
|
p.channel_count,
|
||||||
|
p.incoming_bandwidth,
|
||||||
|
p.outgoing_bandwidth,
|
||||||
|
p.packet_throttle_interval,
|
||||||
|
p.packet_throttle_acceleration,
|
||||||
|
p.packet_throttle_deceleration,
|
||||||
|
p.connect_id,
|
||||||
|
] {
|
||||||
|
out.extend_from_slice(&v.to_be_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn data_len(data: &[u8]) -> crate::Result<u16> {
|
||||||
|
u16::try_from(data.len()).map_err(|_| crate::Error::TooLarge {
|
||||||
|
what: "enet command data",
|
||||||
|
max: usize::from(u16::MAX),
|
||||||
|
actual: data.len(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serializes one datagram.
|
/// Serializes one datagram.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`]. Phase A: always
|
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`],
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Malformed`] for a peer id over [`MAX_PEER_ID`] or a session id over 3.
|
||||||
pub fn encode_datagram(datagram: &Datagram) -> crate::Result<Vec<u8>> {
|
pub fn encode_datagram(datagram: &Datagram) -> crate::Result<Vec<u8>> {
|
||||||
let _ = datagram;
|
use crate::util::cap;
|
||||||
Err(crate::Error::Unimplemented)
|
cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, datagram.commands.len())?;
|
||||||
|
if datagram.peer_id > MAX_PEER_ID || datagram.session_id > 3 {
|
||||||
|
return Err(crate::util::malformed("enet peer or session id"));
|
||||||
|
}
|
||||||
|
let header_len = if datagram.sent_time.is_some() { 4 } else { 2 };
|
||||||
|
let size = datagram.commands.iter().map(command_size).fold(header_len, usize::saturating_add);
|
||||||
|
cap("enet datagram", MAX_DATAGRAM_BYTES, size)?;
|
||||||
|
let mut out = Vec::with_capacity(size);
|
||||||
|
let mut header = datagram.peer_id | (u16::from(datagram.session_id) << 12);
|
||||||
|
if datagram.sent_time.is_some() {
|
||||||
|
header |= HEADER_FLAG_SENT_TIME;
|
||||||
|
}
|
||||||
|
out.extend_from_slice(&header.to_be_bytes());
|
||||||
|
if let Some(t) = datagram.sent_time {
|
||||||
|
out.extend_from_slice(&t.to_be_bytes());
|
||||||
|
}
|
||||||
|
for c in &datagram.commands {
|
||||||
|
let mut command = kind_of(&c.body) as u8;
|
||||||
|
if c.acknowledge {
|
||||||
|
command |= COMMAND_FLAG_ACKNOWLEDGE;
|
||||||
|
}
|
||||||
|
if matches!(c.body, CommandBody::SendUnsequenced { .. }) {
|
||||||
|
command |= COMMAND_FLAG_UNSEQUENCED;
|
||||||
|
}
|
||||||
|
out.push(command);
|
||||||
|
out.push(c.channel_id);
|
||||||
|
out.extend_from_slice(&c.reliable_sequence.to_be_bytes());
|
||||||
|
match &c.body {
|
||||||
|
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
|
||||||
|
out.extend_from_slice(&received_reliable_sequence.to_be_bytes());
|
||||||
|
out.extend_from_slice(&received_sent_time.to_be_bytes());
|
||||||
|
}
|
||||||
|
CommandBody::Connect { params, data } => {
|
||||||
|
put_params(&mut out, params);
|
||||||
|
out.extend_from_slice(&data.to_be_bytes());
|
||||||
|
}
|
||||||
|
CommandBody::VerifyConnect(params) => put_params(&mut out, params),
|
||||||
|
CommandBody::Disconnect { data } => out.extend_from_slice(&data.to_be_bytes()),
|
||||||
|
CommandBody::Ping => {}
|
||||||
|
CommandBody::SendReliable(data) => {
|
||||||
|
out.extend_from_slice(&data_len(data)?.to_be_bytes());
|
||||||
|
out.extend_from_slice(data);
|
||||||
|
}
|
||||||
|
CommandBody::SendUnreliable { unreliable_sequence: s, data }
|
||||||
|
| CommandBody::SendUnsequenced { unsequenced_group: s, data } => {
|
||||||
|
out.extend_from_slice(&s.to_be_bytes());
|
||||||
|
out.extend_from_slice(&data_len(data)?.to_be_bytes());
|
||||||
|
out.extend_from_slice(data);
|
||||||
|
}
|
||||||
|
CommandBody::SendFragment(f) | CommandBody::SendUnreliableFragment(f) => {
|
||||||
|
out.extend_from_slice(&f.start_sequence.to_be_bytes());
|
||||||
|
out.extend_from_slice(&data_len(&f.data)?.to_be_bytes());
|
||||||
|
for v in [f.fragment_count, f.fragment_number, f.total_length, f.fragment_offset] {
|
||||||
|
out.extend_from_slice(&v.to_be_bytes());
|
||||||
|
}
|
||||||
|
out.extend_from_slice(&f.data);
|
||||||
|
}
|
||||||
|
CommandBody::BandwidthLimit { incoming, outgoing } => {
|
||||||
|
out.extend_from_slice(&incoming.to_be_bytes());
|
||||||
|
out.extend_from_slice(&outgoing.to_be_bytes());
|
||||||
|
}
|
||||||
|
CommandBody::ThrottleConfigure { interval, acceleration, deceleration } => {
|
||||||
|
for v in [interval, acceleration, deceleration] {
|
||||||
|
out.extend_from_slice(&v.to_be_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ pub type Result<T> = core::result::Result<T, Error>;
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// Phase A: the API exists, the logic does not yet.
|
/// A part of the API that has no implementation (none today; kept so callers and tests can name it).
|
||||||
Unimplemented,
|
Unimplemented,
|
||||||
/// Input is larger than the parser's `MAX_*` constant. Checked before anything is allocated.
|
/// Input is larger than the parser's `MAX_*` constant. Checked before anything is allocated.
|
||||||
TooLarge {
|
TooLarge {
|
||||||
|
|||||||
+316
-30
@@ -4,22 +4,200 @@
|
|||||||
//! `data` of the `data + parity` shards rebuild the rest. Every byte position is coded on its own, so all shards of
|
//! `data` of the `data + parity` shards rebuild the rest. Every byte position is coded on its own, so all shards of
|
||||||
//! a block have the same length.
|
//! a block have the same length.
|
||||||
//!
|
//!
|
||||||
//! Two matrices are needed: video (`ReedSolomon::new`, construction UNKNOWN U14) and audio (a fixed 2 × 4 parity
|
//! Two matrices are needed: video ([`ReedSolomon::new`]: the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`, from
|
||||||
//! matrix, UNKNOWN U16, passed in with [`ReedSolomon::with_parity_matrix`] until it is measured).
|
//! fec-rs, U14 settled pending the Day 1 check) and audio (a fixed 2 × 4 parity matrix, UNKNOWN U16, passed in
|
||||||
|
//! with [`ReedSolomon::with_parity_matrix`] until it is measured).
|
||||||
|
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Maximum shards in one block (data + parity).
|
/// Maximum shards in one block (data + parity).
|
||||||
pub const MAX_SHARDS: usize = 255;
|
pub const MAX_SHARDS: usize = 255;
|
||||||
/// Maximum length of one shard, in bytes.
|
/// Maximum length of one shard, in bytes.
|
||||||
pub const MAX_SHARD_BYTES: usize = 4096;
|
pub const MAX_SHARD_BYTES: usize = 4096;
|
||||||
|
|
||||||
|
/// Square submatrices checked exhaustively for the MDS property; bigger matrices get the 1 × 1 and, if cheap
|
||||||
|
/// enough, the 2 × 2 checks only.
|
||||||
|
const MDS_EXHAUSTIVE_BUDGET: u64 = 200_000;
|
||||||
|
const MDS_PAIRS_BUDGET: u64 = 1_000_000;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ GF(2^8)
|
||||||
|
|
||||||
|
/// `EXP[i] = 2^i` (doubled so a sum of two logarithms needs no reduction) and `LOG[x] = log2(x)`.
|
||||||
|
#[allow(clippy::indexing_slicing, reason = "compile-time table: any out-of-bounds index fails the build")]
|
||||||
|
const fn tables() -> ([u8; 512], [u8; 256]) {
|
||||||
|
let mut exp = [0u8; 512];
|
||||||
|
let mut log = [0u8; 256];
|
||||||
|
let mut x: u16 = 1;
|
||||||
|
let mut i = 0;
|
||||||
|
while i < 255 {
|
||||||
|
exp[i] = x as u8;
|
||||||
|
log[x as usize] = i as u8;
|
||||||
|
x <<= 1;
|
||||||
|
if x & 0x100 != 0 {
|
||||||
|
x ^= 0x11D;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
while i < 512 {
|
||||||
|
exp[i] = exp[i - 255];
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
(exp, log)
|
||||||
|
}
|
||||||
|
|
||||||
|
const TABLES: ([u8; 512], [u8; 256]) = tables();
|
||||||
|
|
||||||
|
fn log(x: u8) -> usize {
|
||||||
|
usize::from(TABLES.1.get(usize::from(x)).copied().unwrap_or(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exp(i: usize) -> u8 {
|
||||||
|
TABLES.0.get(i).copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mul(a: u8, b: u8) -> u8 {
|
||||||
|
if a == 0 || b == 0 { 0 } else { exp(log(a) + log(b)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multiplicative inverse; `inv(0)` is 0 (never used as a divisor).
|
||||||
|
fn inv(a: u8) -> u8 {
|
||||||
|
if a == 0 { 0 } else { exp(255 - log(a)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `dst ^= c · src`, byte by byte.
|
||||||
|
fn mul_add(dst: &mut [u8], src: &[u8], c: u8) {
|
||||||
|
if c == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let lc = log(c);
|
||||||
|
for (d, &s) in dst.iter_mut().zip(src) {
|
||||||
|
if s != 0 {
|
||||||
|
*d ^= exp(lc + log(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inverse of a row-major `n × n` matrix by Gauss-Jordan elimination; `None` when singular.
|
||||||
|
fn invert(mut a: Vec<u8>, n: usize) -> Option<Vec<u8>> {
|
||||||
|
let mut out = vec![0u8; n * n];
|
||||||
|
for i in 0..n {
|
||||||
|
*out.get_mut(i * n + i)? = 1;
|
||||||
|
}
|
||||||
|
for col in 0..n {
|
||||||
|
let pivot = (col..n).find(|&r| a.get(r * n + col).is_some_and(|v| *v != 0))?;
|
||||||
|
if pivot != col {
|
||||||
|
for c in 0..n {
|
||||||
|
a.swap(pivot * n + c, col * n + c);
|
||||||
|
out.swap(pivot * n + c, col * n + c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let scale = inv(*a.get(col * n + col)?);
|
||||||
|
for c in 0..n {
|
||||||
|
let v = a.get_mut(col * n + c)?;
|
||||||
|
*v = mul(*v, scale);
|
||||||
|
let w = out.get_mut(col * n + c)?;
|
||||||
|
*w = mul(*w, scale);
|
||||||
|
}
|
||||||
|
for r in 0..n {
|
||||||
|
if r == col {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let factor = *a.get(r * n + col)?;
|
||||||
|
if factor == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for c in 0..n {
|
||||||
|
let ac = mul(factor, *a.get(col * n + c)?);
|
||||||
|
*a.get_mut(r * n + c)? ^= ac;
|
||||||
|
let oc = mul(factor, *out.get(col * n + c)?);
|
||||||
|
*out.get_mut(r * n + c)? ^= oc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `n choose k`, saturating.
|
||||||
|
fn choose(n: usize, k: usize) -> u64 {
|
||||||
|
let mut r: u64 = 1;
|
||||||
|
for i in 0..k.min(n) {
|
||||||
|
// Exact while it fits (r * (n - i) is divisible by i + 1); once it saturates it stays saturated.
|
||||||
|
r = match r.checked_mul(n.saturating_sub(i) as u64) {
|
||||||
|
Some(v) => v / (i as u64 + 1),
|
||||||
|
None => return u64::MAX,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if k > n { 0 } else { r }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All `size`-element subsets of `0..n`, in lexicographic order, passed to `f` until it returns false.
|
||||||
|
fn each_subset(n: usize, size: usize, mut f: impl FnMut(&[usize]) -> bool) -> bool {
|
||||||
|
if size > n {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let mut idx: Vec<usize> = (0..size).collect();
|
||||||
|
loop {
|
||||||
|
if !f(&idx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// The rightmost position that can still move right.
|
||||||
|
let Some(i) = (0..size).rev().find(|&i| idx.get(i).is_some_and(|&v| v < n - size + i)) else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let start = idx.get(i).copied().unwrap_or(0) + 1;
|
||||||
|
for (off, slot) in idx.iter_mut().enumerate().skip(i) {
|
||||||
|
*slot = start + (off - i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `[I; P]` is MDS, i.e. every square submatrix of `P` is invertible (see the budgets above).
|
||||||
|
fn is_mds(p: &[u8], data: usize, parity: usize) -> bool {
|
||||||
|
if p.contains(&0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let total: u64 = (2..=data.min(parity))
|
||||||
|
.map(|s| choose(data, s).saturating_mul(choose(parity, s)))
|
||||||
|
.fold(0u64, u64::saturating_add);
|
||||||
|
let max_size = if total <= MDS_EXHAUSTIVE_BUDGET {
|
||||||
|
data.min(parity)
|
||||||
|
} else if choose(data, 2).saturating_mul(choose(parity, 2)) <= MDS_PAIRS_BUDGET {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
};
|
||||||
|
for s in 2..=max_size {
|
||||||
|
let ok = each_subset(parity, s, |rows| {
|
||||||
|
each_subset(data, s, |cols| {
|
||||||
|
let sub: Vec<u8> = rows
|
||||||
|
.iter()
|
||||||
|
.flat_map(|&r| cols.iter().map(move |&c| p.get(r * data + c).copied().unwrap_or(0)))
|
||||||
|
.collect();
|
||||||
|
invert(sub, s).is_some()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if !ok {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ the code
|
||||||
|
|
||||||
/// Parity shards for `data_shards` at `fec_percentage`: `ceil(data × percentage / 100)`.
|
/// Parity shards for `data_shards` at `fec_percentage`: `ceil(data × percentage / 100)`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] when `data_shards` is 0 or the result would exceed [`MAX_SHARDS`]. Phase A:
|
/// [`Error::UnexpectedValue`] when `data_shards` is 0 or data + parity would exceed [`MAX_SHARDS`].
|
||||||
/// always [`crate::Error::Unimplemented`].
|
pub fn parity_count(data_shards: usize, fec_percentage: u8) -> Result<usize> {
|
||||||
pub fn parity_count(data_shards: usize, fec_percentage: u8) -> crate::Result<usize> {
|
let k = u64::try_from(data_shards).unwrap_or(u64::MAX);
|
||||||
let _ = (data_shards, fec_percentage);
|
let m = k.saturating_mul(u64::from(fec_percentage)).div_ceil(100);
|
||||||
Err(crate::Error::Unimplemented)
|
let m = usize::try_from(m).unwrap_or(usize::MAX);
|
||||||
|
if data_shards == 0 || data_shards.saturating_add(m) > MAX_SHARDS {
|
||||||
|
return Err(Error::UnexpectedValue { what: "fec shard count", value: k });
|
||||||
|
}
|
||||||
|
Ok(m)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One code: shard counts and its parity matrix.
|
/// One code: shard counts and its parity matrix.
|
||||||
@@ -31,25 +209,50 @@ pub struct ReedSolomon {
|
|||||||
parity_matrix: Vec<u8>,
|
parity_matrix: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn check_counts(data_shards: usize, parity_shards: usize) -> Result<()> {
|
||||||
|
let sum = data_shards.checked_add(parity_shards);
|
||||||
|
if data_shards == 0 || parity_shards == 0 || sum.is_none_or(|s| s > MAX_SHARDS) {
|
||||||
|
return Err(Error::UnexpectedValue {
|
||||||
|
what: "fec shard counts",
|
||||||
|
value: u64::try_from(data_shards).unwrap_or(u64::MAX),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
impl ReedSolomon {
|
impl ReedSolomon {
|
||||||
/// The code GameStream video uses for `data_shards` + `parity_shards` (UNKNOWN U14: construction).
|
/// The code GameStream video uses for `data_shards` + `parity_shards`: parity row `j` is the Cauchy row
|
||||||
|
/// `1 / ((parity_shards + i) XOR j)` (`docs/PROTOCOL.md` 5.3).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] when either count is 0 or the sum exceeds [`MAX_SHARDS`]. Phase A: always
|
/// [`Error::UnexpectedValue`] when either count is 0 or the sum exceeds [`MAX_SHARDS`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn new(data_shards: usize, parity_shards: usize) -> Result<Self> {
|
||||||
pub fn new(data_shards: usize, parity_shards: usize) -> crate::Result<Self> {
|
check_counts(data_shards, parity_shards)?;
|
||||||
let _ = (data_shards, parity_shards);
|
let mut parity_matrix = Vec::with_capacity(data_shards * parity_shards);
|
||||||
Err(crate::Error::Unimplemented)
|
for j in 0..parity_shards {
|
||||||
|
for i in 0..data_shards {
|
||||||
|
// parity + i <= 254 and j < parity, so the XOR is never zero.
|
||||||
|
parity_matrix.push(inv(((parity_shards + i) ^ j) as u8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self { data_shards, parity_shards, parity_matrix })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A code with an explicit parity matrix (`parity_shards × data_shards`, row-major). The matrix must make every
|
/// A code with an explicit parity matrix (`parity_shards × data_shards`, row-major). The matrix must make every
|
||||||
/// square submatrix of `[I; P]` invertible, or some loss patterns cannot be rebuilt; this is checked.
|
/// square submatrix of `[I; P]` invertible, or some loss patterns cannot be rebuilt; this is checked
|
||||||
|
/// exhaustively for small matrices and by its 1 × 1 and 2 × 2 minors for large ones.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`Self::new`]; [`crate::Error::Malformed`] for a matrix of the wrong size or one that is not MDS.
|
/// As [`Self::new`]; [`Error::Malformed`] for a matrix of the wrong size or one that is not MDS.
|
||||||
pub fn with_parity_matrix(data_shards: usize, parity_shards: usize, parity_matrix: &[u8]) -> crate::Result<Self> {
|
pub fn with_parity_matrix(data_shards: usize, parity_shards: usize, parity_matrix: &[u8]) -> Result<Self> {
|
||||||
let _ = (data_shards, parity_shards, parity_matrix);
|
check_counts(data_shards, parity_shards)?;
|
||||||
Err(crate::Error::Unimplemented)
|
if parity_matrix.len() != data_shards * parity_shards {
|
||||||
|
return Err(malformed("fec parity matrix size"));
|
||||||
|
}
|
||||||
|
if !is_mds(parity_matrix, data_shards, parity_shards) {
|
||||||
|
return Err(malformed("fec parity matrix is not MDS"));
|
||||||
|
}
|
||||||
|
Ok(Self { data_shards, parity_shards, parity_matrix: parity_matrix.to_vec() })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Number of data shards.
|
/// Number of data shards.
|
||||||
@@ -70,26 +273,109 @@ impl ReedSolomon {
|
|||||||
&self.parity_matrix
|
&self.parity_matrix
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn coefficient(&self, row: usize, col: usize) -> u8 {
|
||||||
|
self.parity_matrix.get(row * self.data_shards + col).copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One parity row over the given data shards.
|
||||||
|
fn parity_row(&self, row: usize, data: &[&[u8]], len: usize) -> Vec<u8> {
|
||||||
|
let mut out = vec![0u8; len];
|
||||||
|
for (i, d) in data.iter().enumerate() {
|
||||||
|
mul_add(&mut out, d, self.coefficient(row, i));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Computes the parity shards from the data shards. `shards` holds `data + parity` buffers of equal length;
|
/// Computes the parity shards from the data shards. `shards` holds `data + parity` buffers of equal length;
|
||||||
/// the parity ones are overwritten.
|
/// the parity ones are overwritten.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for the wrong shard count or unequal lengths, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for the wrong shard count or unequal lengths, [`Error::TooLarge`] over
|
||||||
/// [`MAX_SHARD_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`MAX_SHARD_BYTES`].
|
||||||
pub fn encode(&self, shards: &mut [Vec<u8>]) -> crate::Result<()> {
|
pub fn encode(&self, shards: &mut [Vec<u8>]) -> Result<()> {
|
||||||
let _ = shards;
|
if shards.len() != self.data_shards + self.parity_shards {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("fec shard count"));
|
||||||
|
}
|
||||||
|
let len = shards.first().map_or(0, Vec::len);
|
||||||
|
if shards.iter().any(|s| s.len() != len) {
|
||||||
|
return Err(malformed("fec shards of unequal length"));
|
||||||
|
}
|
||||||
|
cap("fec shard", MAX_SHARD_BYTES, len)?;
|
||||||
|
let (data, parity) = shards.split_at_mut(self.data_shards);
|
||||||
|
let data: Vec<&[u8]> = data.iter().map(Vec::as_slice).collect();
|
||||||
|
for (j, p) in parity.iter_mut().enumerate() {
|
||||||
|
*p = self.parity_row(j, &data, len);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rebuilds missing shards in place. `shards` holds `data + parity` entries, `None` for lost ones; on success
|
/// Rebuilds missing shards in place. `shards` holds `data + parity` entries, `None` for lost ones; on success
|
||||||
/// every entry is `Some`.
|
/// every entry is `Some`, and present entries are never changed.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for the wrong count or unequal lengths, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for the wrong count, unequal lengths, or a singular system (a matrix that was not
|
||||||
/// [`MAX_SHARD_BYTES`], [`crate::Error::Truncated`] when fewer than `data` shards are present. Phase A: always
|
/// MDS), [`Error::TooLarge`] over [`MAX_SHARD_BYTES`], [`Error::Truncated`] when fewer than `data` shards are
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// present.
|
||||||
pub fn reconstruct(&self, shards: &mut [Option<Vec<u8>>]) -> crate::Result<()> {
|
pub fn reconstruct(&self, shards: &mut [Option<Vec<u8>>]) -> Result<()> {
|
||||||
let _ = shards;
|
let k = self.data_shards;
|
||||||
Err(crate::Error::Unimplemented)
|
if shards.len() != k + self.parity_shards {
|
||||||
|
return Err(malformed("fec shard count"));
|
||||||
|
}
|
||||||
|
let len = shards.iter().flatten().next().map_or(0, Vec::len);
|
||||||
|
if shards.iter().flatten().any(|s| s.len() != len) {
|
||||||
|
return Err(malformed("fec shards of unequal length"));
|
||||||
|
}
|
||||||
|
cap("fec shard", MAX_SHARD_BYTES, len)?;
|
||||||
|
let present = shards.iter().flatten().count();
|
||||||
|
if present < k {
|
||||||
|
return Err(Error::Truncated { what: "fec shards", needed: k, actual: present });
|
||||||
|
}
|
||||||
|
let missing: Vec<usize> = (0..k).filter(|&i| shards.get(i).is_some_and(Option::is_none)).collect();
|
||||||
|
if !missing.is_empty() {
|
||||||
|
let rows: Vec<usize> = (0..self.parity_shards)
|
||||||
|
.filter(|&j| shards.get(k + j).is_some_and(Option::is_some))
|
||||||
|
.take(missing.len())
|
||||||
|
.collect();
|
||||||
|
let e = missing.len();
|
||||||
|
let a: Vec<u8> = rows
|
||||||
|
.iter()
|
||||||
|
.flat_map(|&r| missing.iter().map(move |&c| (r, c)))
|
||||||
|
.map(|(r, c)| self.coefficient(r, c))
|
||||||
|
.collect();
|
||||||
|
let a_inv = invert(a, e).ok_or(malformed("fec system is singular (matrix not MDS)"))?;
|
||||||
|
// rhs_r = parity_r - sum over present data of P[r][i] * d_i
|
||||||
|
let mut rhs: Vec<Vec<u8>> = Vec::with_capacity(e);
|
||||||
|
for &r in &rows {
|
||||||
|
let mut v = shards.get(k + r).and_then(Option::as_ref).cloned().unwrap_or_default();
|
||||||
|
for i in (0..k).filter(|i| !missing.contains(i)) {
|
||||||
|
if let Some(Some(d)) = shards.get(i) {
|
||||||
|
mul_add(&mut v, d, self.coefficient(r, i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rhs.push(v);
|
||||||
|
}
|
||||||
|
for (c, &slot) in missing.iter().enumerate() {
|
||||||
|
let mut out = vec![0u8; len];
|
||||||
|
for (r, v) in rhs.iter().enumerate() {
|
||||||
|
mul_add(&mut out, v, a_inv.get(c * e + r).copied().unwrap_or(0));
|
||||||
|
}
|
||||||
|
if let Some(s) = shards.get_mut(slot) {
|
||||||
|
*s = Some(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let parity_missing: Vec<usize> =
|
||||||
|
(0..self.parity_shards).filter(|&j| shards.get(k + j).is_some_and(Option::is_none)).collect();
|
||||||
|
if !parity_missing.is_empty() {
|
||||||
|
let data: Vec<&[u8]> = shards.iter().take(k).flatten().map(Vec::as_slice).collect();
|
||||||
|
let rebuilt: Vec<(usize, Vec<u8>)> =
|
||||||
|
parity_missing.iter().map(|&j| (j, self.parity_row(j, &data, len))).collect();
|
||||||
|
for (j, p) in rebuilt {
|
||||||
|
if let Some(s) = shards.get_mut(k + j) {
|
||||||
|
*s = Some(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
|
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{cap, malformed, parse_u32};
|
||||||
|
|
||||||
/// Maximum size of an applist body, in bytes.
|
/// Maximum size of an applist body, in bytes.
|
||||||
pub const MAX_APPLIST_BYTES: usize = 1024 * 1024;
|
pub const MAX_APPLIST_BYTES: usize = 1024 * 1024;
|
||||||
/// Maximum number of apps accepted in one list.
|
/// Maximum number of apps accepted in one list.
|
||||||
@@ -18,13 +21,28 @@ pub struct App {
|
|||||||
pub hdr_supported: bool,
|
pub hdr_supported: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses an applist body. Apps keep the host's order; duplicate ids are refused.
|
/// Parses an applist body. Apps keep the host's order; duplicate ids are refused; other elements are ignored.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_APPLIST_BYTES`], [`MAX_APPS`] or [`MAX_APP_TITLE_BYTES`],
|
/// [`crate::Error::TooLarge`] over [`MAX_APPLIST_BYTES`], [`MAX_APPS`] or [`MAX_APP_TITLE_BYTES`],
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for an `App` without `ID` or
|
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for an `App` without `ID` or
|
||||||
/// `AppTitle`. Phase A: always [`crate::Error::Unimplemented`].
|
/// `AppTitle`, a bad `ID`, or a duplicate `ID`.
|
||||||
pub fn parse_app_list(body: &[u8]) -> crate::Result<Vec<App>> {
|
pub fn parse_app_list(body: &[u8]) -> Result<Vec<App>> {
|
||||||
let _ = body;
|
let doc = super::document(body, MAX_APPLIST_BYTES, "applist")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let count = doc.root.children.iter().filter(|c| c.name == "App").count();
|
||||||
|
cap("applist apps", MAX_APPS, count)?;
|
||||||
|
let mut apps: Vec<App> = Vec::with_capacity(count);
|
||||||
|
let mut ids = std::collections::BTreeSet::new();
|
||||||
|
for e in doc.root.children.iter().filter(|c| c.name == "App") {
|
||||||
|
let title = e.child("AppTitle").ok_or(malformed("applist: App without AppTitle"))?;
|
||||||
|
cap("applist AppTitle", MAX_APP_TITLE_BYTES, title.text.len())?;
|
||||||
|
let id = e.child("ID").ok_or(malformed("applist: App without ID"))?;
|
||||||
|
let id = parse_u32("applist ID", &id.text)?;
|
||||||
|
if !ids.insert(id) {
|
||||||
|
return Err(malformed("applist: duplicate ID"));
|
||||||
|
}
|
||||||
|
let hdr_supported = e.child("IsHdrSupported").is_some_and(|h| h.text == "1");
|
||||||
|
apps.push(App { id, title: title.text.clone(), hdr_supported });
|
||||||
|
}
|
||||||
|
Ok(apps)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
//! `GET /launch` and `GET /resume` (`docs/PROTOCOL.md` 1.4).
|
//! `GET /launch` and `GET /resume` (`docs/PROTOCOL.md` 1.4).
|
||||||
|
|
||||||
use super::HttpRequest;
|
use super::{HttpRequest, Scheme, build, check_unique_id};
|
||||||
use crate::SessionKeys;
|
use crate::util::{cap, check_rtsp_url, hex_encode, malformed};
|
||||||
|
use crate::{Result, SessionKeys};
|
||||||
|
|
||||||
/// Maximum size of a launch or resume answer, in bytes.
|
/// Maximum size of a launch or resume answer, in bytes.
|
||||||
pub const MAX_LAUNCH_RESPONSE_BYTES: usize = 16 * 1024;
|
pub const MAX_LAUNCH_RESPONSE_BYTES: usize = 16 * 1024;
|
||||||
@@ -19,6 +20,35 @@ pub enum AudioLayout {
|
|||||||
Surround71,
|
Surround71,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl AudioLayout {
|
||||||
|
/// Channel count.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn channels(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::Stereo => 2,
|
||||||
|
Self::Surround51 => 6,
|
||||||
|
Self::Surround71 => 8,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The speaker mask (WAVE channel-mask bits: FL FR, + FC LFE BL BR, + SL SR). Stereo's `0x3` matches the
|
||||||
|
/// documented default `surroundAudioInfo` 0x30002 (source M); the surround masks are the standard layouts (U4).
|
||||||
|
#[must_use]
|
||||||
|
pub const fn channel_mask(self) -> u32 {
|
||||||
|
match self {
|
||||||
|
Self::Stereo => 0x0003,
|
||||||
|
Self::Surround51 => 0x003F,
|
||||||
|
Self::Surround71 => 0x063F,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `surroundAudioInfo`: `(channel_mask << 16) | channel_count`.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn surround_audio_info(self) -> u32 {
|
||||||
|
(self.channel_mask() << 16) | self.channels() as u32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// What to launch and how.
|
/// What to launch and how.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct LaunchParams {
|
pub struct LaunchParams {
|
||||||
@@ -50,20 +80,43 @@ pub struct LaunchResponse {
|
|||||||
/// Builds `GET /launch` (HTTPS).
|
/// Builds `GET /launch` (HTTPS).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a zero size or frame rate, or a bad `unique_id`. Phase A: always
|
/// [`crate::Error::Malformed`] for a zero size or frame rate, or a bad `unique_id`.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn launch_request(params: &LaunchParams, unique_id: &str) -> Result<HttpRequest> {
|
||||||
pub fn launch_request(params: &LaunchParams, unique_id: &str) -> crate::Result<HttpRequest> {
|
check_unique_id(unique_id)?;
|
||||||
let _ = (params, unique_id);
|
if params.width == 0 || params.height == 0 || params.fps == 0 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("launch mode"));
|
||||||
|
}
|
||||||
|
let app = params.app_id.to_string();
|
||||||
|
let mode = format!("{}x{}x{}", params.width, params.height, params.fps);
|
||||||
|
let rikey = hex_encode(¶ms.keys.rikey);
|
||||||
|
let rikeyid = params.keys.rikeyid.to_string();
|
||||||
|
let hdr = if params.hdr { "1" } else { "0" };
|
||||||
|
let audio = params.audio.surround_audio_info().to_string();
|
||||||
|
Ok(build(
|
||||||
|
Scheme::Https,
|
||||||
|
"/launch",
|
||||||
|
&[
|
||||||
|
("uniqueid", unique_id),
|
||||||
|
("appid", &app),
|
||||||
|
("mode", &mode),
|
||||||
|
("rikey", &rikey),
|
||||||
|
("rikeyid", &rikeyid),
|
||||||
|
("hdrMode", hdr),
|
||||||
|
("surroundAudioInfo", &audio),
|
||||||
|
],
|
||||||
|
None,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /resume` (HTTPS) with fresh keys.
|
/// Builds `GET /resume` (HTTPS) with fresh keys.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`launch_request`].
|
/// As [`launch_request`].
|
||||||
pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = (keys, unique_id);
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let rikey = hex_encode(&keys.rikey);
|
||||||
|
let rikeyid = keys.rikeyid.to_string();
|
||||||
|
Ok(build(Scheme::Https, "/resume", &[("uniqueid", unique_id), ("rikey", &rikey), ("rikeyid", &rikeyid)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a launch or resume answer.
|
/// Parses a launch or resume answer.
|
||||||
@@ -71,8 +124,17 @@ pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> crate::Result<Http
|
|||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_LAUNCH_RESPONSE_BYTES`] or [`MAX_SESSION_URL_BYTES`],
|
/// [`crate::Error::TooLarge`] over [`MAX_LAUNCH_RESPONSE_BYTES`] or [`MAX_SESSION_URL_BYTES`],
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `sessionUrl0` that is not an
|
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `sessionUrl0` that is not an
|
||||||
/// `rtsp://host:port` URL. Phase A: always [`crate::Error::Unimplemented`].
|
/// `rtsp://host:port` URL.
|
||||||
pub fn parse_launch_response(body: &[u8]) -> crate::Result<LaunchResponse> {
|
pub fn parse_launch_response(body: &[u8]) -> Result<LaunchResponse> {
|
||||||
let _ = body;
|
let doc = super::document(body, MAX_LAUNCH_RESPONSE_BYTES, "launch answer")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let game_session = doc.root.child("gamesession").is_some_and(|g| g.text == "1");
|
||||||
|
let session_url = match doc.root.child("sessionUrl0") {
|
||||||
|
None => None,
|
||||||
|
Some(e) => {
|
||||||
|
cap("sessionUrl0", MAX_SESSION_URL_BYTES, e.text.len())?;
|
||||||
|
check_rtsp_url("sessionUrl0", &e.text)?;
|
||||||
|
Some(e.text.clone())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(LaunchResponse { game_session, session_url })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,9 @@
|
|||||||
|
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{malformed, percent_encode};
|
||||||
|
|
||||||
pub mod applist;
|
pub mod applist;
|
||||||
pub mod launch;
|
pub mod launch;
|
||||||
pub mod serverinfo;
|
pub mod serverinfo;
|
||||||
@@ -47,49 +50,79 @@ pub struct HttpRequest {
|
|||||||
pub timeout: Option<Duration>,
|
pub timeout: Option<Duration>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks a client `uniqueid`: 1..=[`MAX_UNIQUE_ID_BYTES`] of letters, digits, `-` and `_` (our own ids are hex).
|
||||||
|
pub(crate) fn check_unique_id(unique_id: &str) -> Result<()> {
|
||||||
|
if unique_id.is_empty()
|
||||||
|
|| unique_id.len() > MAX_UNIQUE_ID_BYTES
|
||||||
|
|| !unique_id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
{
|
||||||
|
return Err(malformed("uniqueid"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `path?k=v&…` with every value percent-encoded.
|
||||||
|
pub(crate) fn build(scheme: Scheme, path: &str, params: &[(&str, &str)], timeout: Option<Duration>) -> HttpRequest {
|
||||||
|
let mut s = String::from(path);
|
||||||
|
for (i, (k, v)) in params.iter().enumerate() {
|
||||||
|
s.push(if i == 0 { '?' } else { '&' });
|
||||||
|
s.push_str(k);
|
||||||
|
s.push('=');
|
||||||
|
s.push_str(&percent_encode(v));
|
||||||
|
}
|
||||||
|
HttpRequest { scheme, path_and_query: s, timeout }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses `body` as XML after checking it against `max` bytes, and refuses a non-200 status.
|
||||||
|
pub(crate) fn document(body: &[u8], max: usize, what: &'static str) -> Result<xml::Document> {
|
||||||
|
crate::util::cap(what, max, body.len())?;
|
||||||
|
let d = xml::parse(body)?;
|
||||||
|
if d.status_code != 200 {
|
||||||
|
return Err(crate::Error::HostStatus { code: d.status_code });
|
||||||
|
}
|
||||||
|
Ok(d)
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds `GET /serverinfo` for this client.
|
/// Builds `GET /serverinfo` for this client.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for an empty or oversized `unique_id`. Phase A: always
|
/// [`crate::Error::Malformed`] for an empty, oversized or non-alphanumeric `unique_id`.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn server_info_request(scheme: Scheme, unique_id: &str) -> Result<HttpRequest> {
|
||||||
pub fn server_info_request(scheme: Scheme, unique_id: &str) -> crate::Result<HttpRequest> {
|
check_unique_id(unique_id)?;
|
||||||
let _ = (scheme, unique_id);
|
Ok(build(scheme, "/serverinfo", &[("uniqueid", unique_id)], None))
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /applist` (HTTPS).
|
/// Builds `GET /applist` (HTTPS).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`server_info_request`].
|
/// As [`server_info_request`].
|
||||||
pub fn app_list_request(unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn app_list_request(unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = unique_id;
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(build(Scheme::Https, "/applist", &[("uniqueid", unique_id)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /cancel` (HTTPS): quits the app running on the host.
|
/// Builds `GET /cancel` (HTTPS): quits the app running on the host.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`server_info_request`].
|
/// As [`server_info_request`].
|
||||||
pub fn cancel_request(unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn cancel_request(unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = unique_id;
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(build(Scheme::Https, "/cancel", &[("uniqueid", unique_id)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /unpair` (HTTPS): the host forgets this client.
|
/// Builds `GET /unpair` (HTTPS): the host forgets this client.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`server_info_request`].
|
/// As [`server_info_request`].
|
||||||
pub fn unpair_request(unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn unpair_request(unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = unique_id;
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(build(Scheme::Https, "/unpair", &[("uniqueid", unique_id)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks a plain `<root status_code="200"/>` answer (cancel, unpair).
|
/// Checks a plain `<root status_code="200"/>` answer (cancel, unpair).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 status, parser errors as [`xml::parse`]. Phase A: always
|
/// [`crate::Error::HostStatus`] for a non-200 status, parser errors as [`xml::parse`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn parse_status_response(body: &[u8]) -> Result<()> {
|
||||||
pub fn parse_status_response(body: &[u8]) -> crate::Result<()> {
|
document(body, xml::MAX_XML_BYTES, "status answer").map(|_| ())
|
||||||
let _ = body;
|
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
//! `GET /serverinfo` (`docs/PROTOCOL.md` 1.2).
|
//! `GET /serverinfo` (`docs/PROTOCOL.md` 1.2).
|
||||||
|
|
||||||
|
use super::xml::Element;
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{cap, hex_decode, malformed, parse_dec, parse_u16, parse_u32};
|
||||||
|
|
||||||
/// Maximum size of a serverinfo body, in bytes.
|
/// Maximum size of a serverinfo body, in bytes.
|
||||||
pub const MAX_SERVERINFO_BYTES: usize = 64 * 1024;
|
pub const MAX_SERVERINFO_BYTES: usize = 64 * 1024;
|
||||||
/// Maximum length of any string field in serverinfo, in bytes.
|
/// Maximum length of any string field in serverinfo, in bytes.
|
||||||
@@ -40,19 +44,86 @@ impl ServerInfo {
|
|||||||
/// Whether the host reports a running app (`state` ends in `_BUSY` or `currentgame != 0`).
|
/// Whether the host reports a running app (`state` ends in `_BUSY` or `currentgame != 0`).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today; the `Result` leaves room for stricter state checks.
|
||||||
pub fn is_busy(&self) -> crate::Result<bool> {
|
pub fn is_busy(&self) -> Result<bool> {
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(self.state.ends_with("_BUSY") || self.current_game != 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The text of field `name` if present, after the field cap; `None` when missing.
|
||||||
|
fn field<'a>(root: &'a Element, name: &str) -> Result<Option<&'a str>> {
|
||||||
|
match root.child(name) {
|
||||||
|
Some(e) => {
|
||||||
|
cap("serverinfo field", MAX_SERVERINFO_FIELD_BYTES, e.text.len())?;
|
||||||
|
Ok(Some(e.text.as_str()))
|
||||||
|
}
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Present and non-empty.
|
||||||
|
fn non_empty<'a>(root: &'a Element, name: &str) -> Result<Option<&'a str>> {
|
||||||
|
Ok(field(root, name)?.filter(|t| !t.is_empty()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_mac(s: &str) -> Result<[u8; 6]> {
|
||||||
|
let mut out = [0u8; 6];
|
||||||
|
let mut parts = s.split(':');
|
||||||
|
for slot in &mut out {
|
||||||
|
let part = parts.next().filter(|p| p.len() == 2).ok_or(malformed("serverinfo mac"))?;
|
||||||
|
let b = hex_decode("serverinfo mac", part)?;
|
||||||
|
*slot = b.first().copied().ok_or(malformed("serverinfo mac"))?;
|
||||||
|
}
|
||||||
|
if parts.next().is_some() {
|
||||||
|
return Err(malformed("serverinfo mac"));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
/// Parses a serverinfo body.
|
/// Parses a serverinfo body.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_SERVERINFO_BYTES`], [`crate::Error::HostStatus`] for a non-200 answer,
|
/// [`crate::Error::TooLarge`] over [`MAX_SERVERINFO_BYTES`] or [`MAX_SERVERINFO_FIELD_BYTES`],
|
||||||
/// [`crate::Error::Malformed`] for a missing required element (`hostname`, `uniqueid`, `HttpsPort`) or a bad
|
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a missing required element
|
||||||
/// number. Phase A: always [`crate::Error::Unimplemented`].
|
/// (`hostname`, `uniqueid`, `HttpsPort`) or a bad number.
|
||||||
pub fn parse_server_info(body: &[u8]) -> crate::Result<ServerInfo> {
|
pub fn parse_server_info(body: &[u8]) -> Result<ServerInfo> {
|
||||||
let _ = body;
|
let doc = super::document(body, MAX_SERVERINFO_BYTES, "serverinfo")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let r = &doc.root;
|
||||||
|
// Cap every field first, so an oversized field is TooLarge whatever else is wrong.
|
||||||
|
for c in &r.children {
|
||||||
|
cap("serverinfo field", MAX_SERVERINFO_FIELD_BYTES, c.text.len())?;
|
||||||
|
}
|
||||||
|
let hostname = non_empty(r, "hostname")?.ok_or(malformed("serverinfo: no hostname"))?.to_owned();
|
||||||
|
let unique_id = non_empty(r, "uniqueid")?.ok_or(malformed("serverinfo: no uniqueid"))?.to_owned();
|
||||||
|
let https_port =
|
||||||
|
parse_u16("serverinfo HttpsPort", field(r, "HttpsPort")?.ok_or(malformed("serverinfo: no HttpsPort"))?)?;
|
||||||
|
let http_port = non_empty(r, "ExternalPort")?.map(|p| parse_u16("serverinfo ExternalPort", p)).transpose()?;
|
||||||
|
let mac = non_empty(r, "mac")?.map(parse_mac).transpose()?;
|
||||||
|
let max_luma_pixels_hevc =
|
||||||
|
non_empty(r, "MaxLumaPixelsHEVC")?.map(|v| parse_dec("serverinfo MaxLumaPixelsHEVC", v)).transpose()?;
|
||||||
|
let codec_mode_support = non_empty(r, "ServerCodecModeSupport")?
|
||||||
|
.map(|v| parse_u32("serverinfo ServerCodecModeSupport", v))
|
||||||
|
.transpose()?;
|
||||||
|
let paired = match non_empty(r, "PairStatus")? {
|
||||||
|
None | Some("0") => false,
|
||||||
|
Some("1") => true,
|
||||||
|
Some(_) => return Err(malformed("serverinfo PairStatus")),
|
||||||
|
};
|
||||||
|
let current_game =
|
||||||
|
non_empty(r, "currentgame")?.map(|v| parse_u32("serverinfo currentgame", v)).transpose()?.unwrap_or(0);
|
||||||
|
Ok(ServerInfo {
|
||||||
|
hostname,
|
||||||
|
app_version: field(r, "appversion")?.unwrap_or_default().to_owned(),
|
||||||
|
gfe_version: non_empty(r, "GfeVersion")?.map(str::to_owned),
|
||||||
|
unique_id,
|
||||||
|
https_port,
|
||||||
|
http_port,
|
||||||
|
mac,
|
||||||
|
local_ip: non_empty(r, "LocalIP")?.map(str::to_owned),
|
||||||
|
max_luma_pixels_hevc,
|
||||||
|
codec_mode_support,
|
||||||
|
paired,
|
||||||
|
current_game,
|
||||||
|
state: field(r, "state")?.unwrap_or_default().to_owned(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
//! A small, strict XML reader for the host's answers: one `<root status_code="…">` element with nested
|
//! A small, strict XML reader for the host's answers: one `<root status_code="…">` element with nested
|
||||||
//! elements and text. No DTD, no entities beyond the five predefined ones and numeric character references,
|
//! elements and text. No DTD, no entities beyond the five predefined ones and numeric character references,
|
||||||
//! no processing instructions except a leading XML declaration, no namespaces.
|
//! no processing instructions except a leading XML declaration, no comments, no CDATA, no namespaces.
|
||||||
|
//!
|
||||||
|
//! The reader is iterative (an explicit stack), so nesting cannot exhaust the call stack, and every cap is checked
|
||||||
|
//! before the memory it guards is used.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
|
||||||
/// Maximum size of any XML body accepted, in bytes.
|
/// Maximum size of any XML body accepted, in bytes.
|
||||||
pub const MAX_XML_BYTES: usize = 1024 * 1024;
|
pub const MAX_XML_BYTES: usize = 1024 * 1024;
|
||||||
@@ -13,6 +19,9 @@ pub const MAX_XML_TEXT_BYTES: usize = 64 * 1024;
|
|||||||
/// Maximum number of attributes on one element.
|
/// Maximum number of attributes on one element.
|
||||||
pub const MAX_XML_ATTRIBUTES: usize = 8;
|
pub const MAX_XML_ATTRIBUTES: usize = 8;
|
||||||
|
|
||||||
|
/// Longest entity or character reference body accepted (`#x10FFFF` is 8).
|
||||||
|
const MAX_ENTITY_LEN: usize = 10;
|
||||||
|
|
||||||
/// One element: its name, attributes, text (concatenated, unescaped, not trimmed) and child elements.
|
/// One element: its name, attributes, text (concatenated, unescaped, not trimmed) and child elements.
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
pub struct Element {
|
pub struct Element {
|
||||||
@@ -26,6 +35,20 @@ pub struct Element {
|
|||||||
pub children: Vec<Element>,
|
pub children: Vec<Element>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Element {
|
||||||
|
/// The first child with this name.
|
||||||
|
#[must_use]
|
||||||
|
pub fn child(&self, name: &str) -> Option<&Element> {
|
||||||
|
self.children.iter().find(|c| c.name == name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value of the first attribute with this name.
|
||||||
|
#[must_use]
|
||||||
|
pub fn attribute(&self, name: &str) -> Option<&str> {
|
||||||
|
self.attributes.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A parsed host answer.
|
/// A parsed host answer.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct Document {
|
pub struct Document {
|
||||||
@@ -41,8 +64,268 @@ pub struct Document {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_XML_BYTES`] or any other cap, [`crate::Error::Malformed`] for anything that
|
/// [`crate::Error::TooLarge`] over [`MAX_XML_BYTES`] or any other cap, [`crate::Error::Malformed`] for anything that
|
||||||
/// is not well-formed or uses a refused feature. Phase A: always [`crate::Error::Unimplemented`].
|
/// is not well-formed or uses a refused feature.
|
||||||
pub fn parse(body: &[u8]) -> crate::Result<Document> {
|
pub fn parse(body: &[u8]) -> Result<Document> {
|
||||||
let _ = body;
|
cap("xml document", MAX_XML_BYTES, body.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let text = core::str::from_utf8(body).map_err(|_| malformed("xml: not UTF-8"))?;
|
||||||
|
let root = Reader { s: text, b: text.as_bytes(), pos: 0, elements: 0 }.document()?;
|
||||||
|
if root.name != "root" {
|
||||||
|
return Err(malformed("xml: root element is not `root`"));
|
||||||
|
}
|
||||||
|
let code = root.attribute("status_code").ok_or(malformed("xml: no status_code"))?;
|
||||||
|
let status_code = crate::util::parse_u32("xml status_code", code)?;
|
||||||
|
let status_message = root.attribute("status_message").map(str::to_owned);
|
||||||
|
Ok(Document { status_code, status_message, root })
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Reader<'a> {
|
||||||
|
s: &'a str,
|
||||||
|
b: &'a [u8],
|
||||||
|
pos: usize,
|
||||||
|
elements: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_name_start(c: u8) -> bool {
|
||||||
|
c.is_ascii_alphabetic() || c == b'_'
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_name_char(c: u8) -> bool {
|
||||||
|
c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_space(c: u8) -> bool {
|
||||||
|
matches!(c, b' ' | b'\t' | b'\r' | b'\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Reader<'_> {
|
||||||
|
fn peek(&self) -> Option<u8> {
|
||||||
|
self.b.get(self.pos).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peek_at(&self, ahead: usize) -> Option<u8> {
|
||||||
|
self.b.get(self.pos.saturating_add(ahead)).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rest(&self) -> &[u8] {
|
||||||
|
self.b.get(self.pos..).unwrap_or(&[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skip_ws(&mut self) -> bool {
|
||||||
|
let start = self.pos;
|
||||||
|
while self.peek().is_some_and(is_space) {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
self.pos > start
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expect(&mut self, c: u8, what: &'static str) -> Result<()> {
|
||||||
|
if self.peek() == Some(c) {
|
||||||
|
self.pos += 1;
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(malformed(what))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&mut self) -> Result<String> {
|
||||||
|
let start = self.pos;
|
||||||
|
if !self.peek().is_some_and(is_name_start) {
|
||||||
|
return Err(malformed("xml: bad name"));
|
||||||
|
}
|
||||||
|
while self.peek().is_some_and(is_name_char) {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
if self.peek() == Some(b':') {
|
||||||
|
return Err(malformed("xml: namespaces are refused"));
|
||||||
|
}
|
||||||
|
self.s.get(start..self.pos).map(str::to_owned).ok_or(malformed("xml: bad name"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The optional leading `<?xml …?>`, only at byte 0.
|
||||||
|
fn declaration(&mut self) -> Result<()> {
|
||||||
|
if self.rest().starts_with(b"<?xml") && self.peek_at(5).is_some_and(|c| is_space(c) || c == b'?') {
|
||||||
|
let end = self.rest().windows(2).position(|w| w == b"?>").ok_or(malformed("xml: unclosed declaration"))?;
|
||||||
|
self.pos += end + 2;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attach(stack: &mut [Element], root: &mut Option<Element>, element: Element) {
|
||||||
|
match stack.last_mut() {
|
||||||
|
Some(parent) => parent.children.push(element),
|
||||||
|
None => *root = Some(element),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn document(mut self) -> Result<Element> {
|
||||||
|
self.declaration()?;
|
||||||
|
self.skip_ws();
|
||||||
|
let mut stack: Vec<Element> = Vec::new();
|
||||||
|
let mut root: Option<Element> = None;
|
||||||
|
while let Some(c) = self.peek() {
|
||||||
|
if c == b'<' {
|
||||||
|
if root.is_some() {
|
||||||
|
return Err(malformed("xml: content after the root element"));
|
||||||
|
}
|
||||||
|
match self.peek_at(1) {
|
||||||
|
Some(b'/') => {
|
||||||
|
self.pos += 2;
|
||||||
|
let name = self.name()?;
|
||||||
|
self.skip_ws();
|
||||||
|
self.expect(b'>', "xml: bad end tag")?;
|
||||||
|
let done = stack.pop().ok_or(malformed("xml: end tag without start"))?;
|
||||||
|
if done.name != name {
|
||||||
|
return Err(malformed("xml: mismatched end tag"));
|
||||||
|
}
|
||||||
|
Self::attach(&mut stack, &mut root, done);
|
||||||
|
}
|
||||||
|
Some(b'!' | b'?') => return Err(malformed("xml: DTD, comment, CDATA or PI refused")),
|
||||||
|
_ => {
|
||||||
|
self.pos += 1;
|
||||||
|
let (element, closed) = self.start_tag()?;
|
||||||
|
self.elements += 1;
|
||||||
|
cap("xml elements", MAX_XML_ELEMENTS, self.elements)?;
|
||||||
|
cap("xml depth", MAX_XML_DEPTH, stack.len() + 1)?;
|
||||||
|
if closed {
|
||||||
|
Self::attach(&mut stack, &mut root, element);
|
||||||
|
} else {
|
||||||
|
stack.push(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let already = stack.last().map_or(0, |t| t.text.len());
|
||||||
|
let text = self.text(already)?;
|
||||||
|
match stack.last_mut() {
|
||||||
|
Some(top) => top.text.push_str(&text),
|
||||||
|
None => {
|
||||||
|
if !text.bytes().all(is_space) {
|
||||||
|
return Err(malformed("xml: text outside the root element"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !stack.is_empty() {
|
||||||
|
return Err(malformed("xml: unclosed element"));
|
||||||
|
}
|
||||||
|
root.ok_or(malformed("xml: no root element"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After `<`: name, attributes, `>` or `/>`. Returns the element and whether it was self-closing.
|
||||||
|
fn start_tag(&mut self) -> Result<(Element, bool)> {
|
||||||
|
let name = self.name()?;
|
||||||
|
let mut attributes: Vec<(String, String)> = Vec::new();
|
||||||
|
loop {
|
||||||
|
let had_ws = self.skip_ws();
|
||||||
|
match self.peek() {
|
||||||
|
Some(b'>') => {
|
||||||
|
self.pos += 1;
|
||||||
|
return Ok((Element { name, attributes, ..Element::default() }, false));
|
||||||
|
}
|
||||||
|
Some(b'/') => {
|
||||||
|
self.pos += 1;
|
||||||
|
self.expect(b'>', "xml: bad self-closing tag")?;
|
||||||
|
return Ok((Element { name, attributes, ..Element::default() }, true));
|
||||||
|
}
|
||||||
|
Some(_) if had_ws => {
|
||||||
|
let key = self.name()?;
|
||||||
|
if key == "xmlns" {
|
||||||
|
return Err(malformed("xml: namespaces are refused"));
|
||||||
|
}
|
||||||
|
self.skip_ws();
|
||||||
|
self.expect(b'=', "xml: attribute without =")?;
|
||||||
|
self.skip_ws();
|
||||||
|
let value = self.attribute_value()?;
|
||||||
|
if attributes.iter().any(|(k, _)| *k == key) {
|
||||||
|
return Err(malformed("xml: duplicate attribute"));
|
||||||
|
}
|
||||||
|
attributes.push((key, value));
|
||||||
|
cap("xml attributes", MAX_XML_ATTRIBUTES, attributes.len())?;
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("xml: bad start tag")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attribute_value(&mut self) -> Result<String> {
|
||||||
|
let quote = self.peek().filter(|q| *q == b'"' || *q == b'\'').ok_or(malformed("xml: unquoted attribute"))?;
|
||||||
|
self.pos += 1;
|
||||||
|
let mut out = String::new();
|
||||||
|
loop {
|
||||||
|
let start = self.pos;
|
||||||
|
while self.peek().is_some_and(|c| c != quote && c != b'&' && c != b'<') {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, out.len().saturating_add(self.pos - start))?;
|
||||||
|
out.push_str(self.s.get(start..self.pos).ok_or(malformed("xml: bad attribute"))?);
|
||||||
|
match self.peek() {
|
||||||
|
Some(c) if c == quote => {
|
||||||
|
self.pos += 1;
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
Some(b'&') => {
|
||||||
|
out.push(self.entity()?);
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, out.len())?;
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("xml: bad attribute value")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text up to the next `<` (or the end), unescaped, capped together with the `already` bytes of the element.
|
||||||
|
fn text(&mut self, already: usize) -> Result<String> {
|
||||||
|
let mut out = String::new();
|
||||||
|
loop {
|
||||||
|
let start = self.pos;
|
||||||
|
while self.peek().is_some_and(|c| c != b'<' && c != b'&') {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, already.saturating_add(out.len()).saturating_add(self.pos - start))?;
|
||||||
|
out.push_str(self.s.get(start..self.pos).ok_or(malformed("xml: bad text"))?);
|
||||||
|
if self.peek() == Some(b'&') {
|
||||||
|
out.push(self.entity()?);
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, already.saturating_add(out.len()))?;
|
||||||
|
} else {
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// At `&`: one of the five entities or a character reference, ending in `;`.
|
||||||
|
fn entity(&mut self) -> Result<char> {
|
||||||
|
self.pos += 1;
|
||||||
|
let len = self
|
||||||
|
.rest()
|
||||||
|
.iter()
|
||||||
|
.take(MAX_ENTITY_LEN + 1)
|
||||||
|
.position(|&c| c == b';')
|
||||||
|
.ok_or(malformed("xml: entity without ;"))?;
|
||||||
|
let body = self.s.get(self.pos..self.pos + len).ok_or(malformed("xml: bad entity"))?;
|
||||||
|
self.pos += len + 1;
|
||||||
|
let c = match body {
|
||||||
|
"lt" => '<',
|
||||||
|
"gt" => '>',
|
||||||
|
"amp" => '&',
|
||||||
|
"quot" => '"',
|
||||||
|
"apos" => '\'',
|
||||||
|
_ => {
|
||||||
|
let code = if let Some(hex) = body.strip_prefix("#x") {
|
||||||
|
if hex.is_empty() || hex.len() > 8 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||||
|
return Err(malformed("xml: bad character reference"));
|
||||||
|
}
|
||||||
|
u32::from_str_radix(hex, 16).map_err(|_| malformed("xml: bad character reference"))?
|
||||||
|
} else if let Some(dec) = body.strip_prefix('#') {
|
||||||
|
crate::util::parse_u32("xml character reference", dec)?
|
||||||
|
} else {
|
||||||
|
return Err(malformed("xml: unknown entity"));
|
||||||
|
};
|
||||||
|
if code == 0 {
|
||||||
|
return Err(malformed("xml: NUL character reference"));
|
||||||
|
}
|
||||||
|
char::from_u32(code).ok_or(malformed("xml: invalid character reference"))?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,14 +53,38 @@ pub enum InputType {
|
|||||||
ControllerBattery = 0x5500_0007,
|
ControllerBattery = 0x5500_0007,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl InputType {
|
||||||
|
const ALL: [Self; 17] = [
|
||||||
|
Self::KeyDown,
|
||||||
|
Self::KeyUp,
|
||||||
|
Self::MouseMoveAbs,
|
||||||
|
Self::MouseMoveRel,
|
||||||
|
Self::MouseButtonDown,
|
||||||
|
Self::MouseButtonUp,
|
||||||
|
Self::MouseScroll,
|
||||||
|
Self::ControllerMulti,
|
||||||
|
Self::Haptics,
|
||||||
|
Self::Utf8Text,
|
||||||
|
Self::MouseHScroll,
|
||||||
|
Self::Touch,
|
||||||
|
Self::Pen,
|
||||||
|
Self::ControllerArrival,
|
||||||
|
Self::ControllerTouch,
|
||||||
|
Self::ControllerMotion,
|
||||||
|
Self::ControllerBattery,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
impl TryFrom<u32> for InputType {
|
impl TryFrom<u32> for InputType {
|
||||||
type Error = crate::Error;
|
type Error = crate::Error;
|
||||||
|
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] for an unknown code. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::UnexpectedValue`] for an unknown code.
|
||||||
fn try_from(code: u32) -> crate::Result<Self> {
|
fn try_from(code: u32) -> crate::Result<Self> {
|
||||||
let _ = code;
|
Self::ALL
|
||||||
Err(crate::Error::Unimplemented)
|
.into_iter()
|
||||||
|
.find(|t| *t as u32 == code)
|
||||||
|
.ok_or(crate::Error::UnexpectedValue { what: "input type", value: code.into() })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,24 +168,192 @@ pub enum InputEvent {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `0x0206 LE ‖ length LE ‖ size BE ‖ input type LE ‖ data`.
|
||||||
|
fn frame(input_type: InputType, data: &[u8]) -> crate::Result<Vec<u8>> {
|
||||||
|
let size = 4 + data.len();
|
||||||
|
crate::util::cap("input message", MAX_INPUT_MESSAGE_BYTES, 8 + size)?;
|
||||||
|
let mut m = Vec::with_capacity(8 + size);
|
||||||
|
m.extend_from_slice(&0x0206u16.to_le_bytes());
|
||||||
|
m.extend_from_slice(&u16::try_from(4 + size).unwrap_or(u16::MAX).to_le_bytes());
|
||||||
|
m.extend_from_slice(&u32::try_from(size).unwrap_or(u32::MAX).to_be_bytes());
|
||||||
|
m.extend_from_slice(&(input_type as u32).to_le_bytes());
|
||||||
|
m.extend_from_slice(data);
|
||||||
|
Ok(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_controller(controller: u8) -> crate::Result<()> {
|
||||||
|
if controller > gamepad::MAX_CONTROLLER_NUMBER {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "controller number", value: controller.into() });
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Serializes an event into a whole `INPUT_DATA` message.
|
/// Serializes an event into a whole `INPUT_DATA` message.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] for a controller number above 15. Phase A: always
|
/// [`crate::Error::UnexpectedValue`] for a controller number above 15.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn encode_input(event: &InputEvent) -> crate::Result<Vec<u8>> {
|
pub fn encode_input(event: &InputEvent) -> crate::Result<Vec<u8>> {
|
||||||
let _ = event;
|
match *event {
|
||||||
Err(crate::Error::Unimplemented)
|
InputEvent::MouseMoveRel { dx, dy } => {
|
||||||
|
frame(InputType::MouseMoveRel, &[dx.to_be_bytes(), dy.to_be_bytes()].concat())
|
||||||
|
}
|
||||||
|
InputEvent::MouseMoveAbs { x, y, width, height } => frame(
|
||||||
|
InputType::MouseMoveAbs,
|
||||||
|
&[x.to_be_bytes(), y.to_be_bytes(), [0, 0], width.to_be_bytes(), height.to_be_bytes()].concat(),
|
||||||
|
),
|
||||||
|
InputEvent::MouseButton { pressed, button } => {
|
||||||
|
frame(if pressed { InputType::MouseButtonDown } else { InputType::MouseButtonUp }, &[button as u8])
|
||||||
|
}
|
||||||
|
InputEvent::Key { pressed, flags, key_code, modifiers } => {
|
||||||
|
let [lo, hi] = key_code.to_le_bytes();
|
||||||
|
frame(if pressed { InputType::KeyDown } else { InputType::KeyUp }, &[flags, lo, hi, modifiers, 0, 0])
|
||||||
|
}
|
||||||
|
InputEvent::Scroll { amount } => {
|
||||||
|
let [a, b] = amount.to_be_bytes();
|
||||||
|
frame(InputType::MouseScroll, &[a, b, a, b, 0, 0])
|
||||||
|
}
|
||||||
|
InputEvent::HScroll { amount } => frame(InputType::MouseHScroll, &amount.to_be_bytes()),
|
||||||
|
InputEvent::Gamepad(g) => {
|
||||||
|
check_controller(g.controller)?;
|
||||||
|
let mut d = Vec::with_capacity(gamepad::CONTROLLER_MULTI_DATA_LEN);
|
||||||
|
d.extend_from_slice(&0x001Au16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&u16::from(g.controller).to_le_bytes());
|
||||||
|
d.extend_from_slice(&g.active_mask.to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0014u16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 & 0xFFFF) as u16).to_le_bytes());
|
||||||
|
d.push(g.left_trigger);
|
||||||
|
d.push(g.right_trigger);
|
||||||
|
for v in [g.left_stick_x, g.left_stick_y, g.right_stick_x, g.right_stick_y] {
|
||||||
|
d.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
d.extend_from_slice(&0x009Cu16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 >> 16) as u16).to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0055u16.to_le_bytes());
|
||||||
|
frame(InputType::ControllerMulti, &d)
|
||||||
|
}
|
||||||
|
InputEvent::ControllerArrival { controller, kind, capabilities, supported_buttons } => {
|
||||||
|
check_controller(controller)?;
|
||||||
|
let mut d = vec![controller, kind as u8, capabilities.0];
|
||||||
|
d.extend_from_slice(&supported_buttons.0.to_le_bytes());
|
||||||
|
frame(InputType::ControllerArrival, &d)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a whole `INPUT_DATA` message (inverse of [`encode_input`]).
|
/// Parses a whole `INPUT_DATA` message (inverse of [`encode_input`]). Bytes the layout fixes at zero or at a
|
||||||
|
/// copy (scroll `amount2`, key padding) are not checked; the `CONTROLLER_MULTI` constants are.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_INPUT_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
/// [`crate::Error::TooLarge`] over [`MAX_INPUT_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
||||||
/// [`INPUT_HEADER_LEN`], [`crate::Error::Malformed`] when the length or size field does not match, the data length
|
/// [`INPUT_HEADER_LEN`], [`crate::Error::Malformed`] when the type, length or size field does not match, the data
|
||||||
/// is wrong for the type, or a constant differs; [`crate::Error::Unsupported`] for a type whose layout is UNKNOWN.
|
/// length is wrong for the type, or a constant differs; [`crate::Error::UnexpectedValue`] for an unknown type, a
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// button, controller number or controller kind out of range; [`crate::Error::Unsupported`] for a type whose
|
||||||
|
/// layout is UNKNOWN.
|
||||||
pub fn parse_input(message: &[u8]) -> crate::Result<InputEvent> {
|
pub fn parse_input(message: &[u8]) -> crate::Result<InputEvent> {
|
||||||
let _ = message;
|
use crate::util::{byte, i16_from, malformed, u16_le, u32_be, u32_le};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "input message";
|
||||||
|
crate::util::cap(W, MAX_INPUT_MESSAGE_BYTES, message.len())?;
|
||||||
|
crate::util::need(W, INPUT_HEADER_LEN, message.len())?;
|
||||||
|
if u16_le(W, message, 0)? != 0x0206 {
|
||||||
|
return Err(malformed("input message type"));
|
||||||
|
}
|
||||||
|
if usize::from(u16_le(W, message, 2)?) != message.len() - 4 {
|
||||||
|
return Err(malformed("input message length"));
|
||||||
|
}
|
||||||
|
if usize::try_from(u32_be(W, message, 4)?).ok() != Some(message.len() - 8) {
|
||||||
|
return Err(malformed("input message size"));
|
||||||
|
}
|
||||||
|
let input_type = InputType::try_from(u32_le(W, message, 8)?)?;
|
||||||
|
let d = message.get(INPUT_HEADER_LEN..).unwrap_or(&[]);
|
||||||
|
let want = |len: usize| if d.len() == len { Ok(()) } else { Err(malformed("input data length")) };
|
||||||
|
let be = |at: usize| crate::util::u16_be(W, d, at);
|
||||||
|
let le = |at: usize| u16_le(W, d, at);
|
||||||
|
Ok(match input_type {
|
||||||
|
InputType::MouseMoveRel => {
|
||||||
|
want(4)?;
|
||||||
|
InputEvent::MouseMoveRel { dx: i16_from(be(0)?), dy: i16_from(be(2)?) }
|
||||||
|
}
|
||||||
|
InputType::MouseMoveAbs => {
|
||||||
|
want(10)?;
|
||||||
|
InputEvent::MouseMoveAbs { x: i16_from(be(0)?), y: i16_from(be(2)?), width: be(6)?, height: be(8)? }
|
||||||
|
}
|
||||||
|
InputType::MouseButtonDown | InputType::MouseButtonUp => {
|
||||||
|
want(1)?;
|
||||||
|
let button = match byte(W, d, 0)? {
|
||||||
|
1 => MouseButton::Left,
|
||||||
|
2 => MouseButton::Middle,
|
||||||
|
3 => MouseButton::Right,
|
||||||
|
4 => MouseButton::Side,
|
||||||
|
5 => MouseButton::Extra,
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "mouse button", value: other.into() }),
|
||||||
|
};
|
||||||
|
InputEvent::MouseButton { pressed: input_type == InputType::MouseButtonDown, button }
|
||||||
|
}
|
||||||
|
InputType::KeyDown | InputType::KeyUp => {
|
||||||
|
want(6)?;
|
||||||
|
InputEvent::Key {
|
||||||
|
pressed: input_type == InputType::KeyDown,
|
||||||
|
flags: byte(W, d, 0)?,
|
||||||
|
key_code: le(1)?,
|
||||||
|
modifiers: byte(W, d, 3)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputType::MouseScroll => {
|
||||||
|
want(6)?;
|
||||||
|
InputEvent::Scroll { amount: i16_from(be(0)?) }
|
||||||
|
}
|
||||||
|
InputType::MouseHScroll => {
|
||||||
|
want(2)?;
|
||||||
|
InputEvent::HScroll { amount: i16_from(be(0)?) }
|
||||||
|
}
|
||||||
|
InputType::ControllerMulti => {
|
||||||
|
want(gamepad::CONTROLLER_MULTI_DATA_LEN)?;
|
||||||
|
if le(0)? != 0x001A || le(6)? != 0x0014 || le(20)? != 0x009C || le(24)? != 0x0055 {
|
||||||
|
return Err(malformed("controller state constant"));
|
||||||
|
}
|
||||||
|
let controller = le(2)?;
|
||||||
|
let controller = u8::try_from(controller)
|
||||||
|
.ok()
|
||||||
|
.filter(|c| *c <= gamepad::MAX_CONTROLLER_NUMBER)
|
||||||
|
.ok_or(crate::Error::UnexpectedValue { what: "controller number", value: controller.into() })?;
|
||||||
|
InputEvent::Gamepad(GamepadState {
|
||||||
|
controller,
|
||||||
|
active_mask: le(4)?,
|
||||||
|
buttons: ButtonFlags(u32::from(le(8)?) | (u32::from(le(22)?) << 16)),
|
||||||
|
left_trigger: byte(W, d, 10)?,
|
||||||
|
right_trigger: byte(W, d, 11)?,
|
||||||
|
left_stick_x: i16_from(le(12)?),
|
||||||
|
left_stick_y: i16_from(le(14)?),
|
||||||
|
right_stick_x: i16_from(le(16)?),
|
||||||
|
right_stick_y: i16_from(le(18)?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
InputType::ControllerArrival => {
|
||||||
|
want(7)?;
|
||||||
|
let controller = byte(W, d, 0)?;
|
||||||
|
check_controller(controller)?;
|
||||||
|
let kind = match byte(W, d, 1)? {
|
||||||
|
0 => ControllerKind::Unknown,
|
||||||
|
1 => ControllerKind::Xbox,
|
||||||
|
2 => ControllerKind::PlayStation,
|
||||||
|
3 => ControllerKind::Nintendo,
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "controller kind", value: other.into() }),
|
||||||
|
};
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller,
|
||||||
|
kind,
|
||||||
|
capabilities: ControllerCapabilities(byte(W, d, 2)?),
|
||||||
|
supported_buttons: ButtonFlags(u32_le(W, d, 3)?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputType::Haptics
|
||||||
|
| InputType::Utf8Text
|
||||||
|
| InputType::Touch
|
||||||
|
| InputType::Pen
|
||||||
|
| InputType::ControllerTouch
|
||||||
|
| InputType::ControllerMotion
|
||||||
|
| InputType::ControllerBattery => {
|
||||||
|
return Err(crate::Error::Unsupported { what: "an input type whose layout is UNKNOWN (U21)" });
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,13 @@ impl SessionKeys {
|
|||||||
/// Draws a fresh key and key id from `rng`.
|
/// Draws a fresh key and key id from `rng`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today; the `Result` leaves room for a fallible source.
|
||||||
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = rng;
|
let mut rikey = [0u8; RIKEY_LEN];
|
||||||
Err(crate::Error::Unimplemented)
|
rng.fill(&mut rikey);
|
||||||
|
let mut id = [0u8; 4];
|
||||||
|
rng.fill(&mut id);
|
||||||
|
Ok(Self { rikey, rikeyid: u32::from_le_bytes(id) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
//! DomiStream: a sans-I/O GameStream client (the protocol Sunshine hosts and Moonlight clients speak), for
|
//! DomiStream: a sans-I/O GameStream client (the protocol Sunshine hosts and Moonlight clients speak), for
|
||||||
//! Arena Domi TV and the other Play remotely clients.
|
//! Arena Domi TV and the other Play remotely clients.
|
||||||
//!
|
//!
|
||||||
//! **Phase A.** This crate holds the public API only. Every function that does protocol work returns
|
//! Interop with real hosts is unverified: the blocking UNKNOWNs of `docs/PROTOCOL.md` are settled live on Day 1.
|
||||||
//! [`Error::Unimplemented`] (or `None` for `poll_*` functions); QA writes the mandatory tests against these
|
//! Where the protocol is UNKNOWN, the Wolf-documented behaviour is implemented and kept easy to change.
|
||||||
//! signatures before the logic lands. Plain data (constants, enum codes, field structs) is final.
|
|
||||||
//!
|
//!
|
||||||
//! # Shape
|
//! # Shape
|
||||||
//!
|
//!
|
||||||
@@ -27,8 +26,8 @@
|
|||||||
//! | [`input`] | input and gamepad packets (section 4) |
|
//! | [`input`] | input and gamepad packets (section 4) |
|
||||||
//! | [`rtp`] | the RTP header shared by video and audio |
|
//! | [`rtp`] | the RTP header shared by video and audio |
|
||||||
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) |
|
||||||
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) |
|
//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5); the host's packetizer |
|
||||||
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) |
|
//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6); the host's packetizer |
|
||||||
//!
|
//!
|
||||||
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
|
//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV).
|
||||||
|
|
||||||
@@ -48,6 +47,7 @@ pub mod pairing;
|
|||||||
pub mod rtp;
|
pub mod rtp;
|
||||||
pub mod rtsp;
|
pub mod rtsp;
|
||||||
pub mod time;
|
pub mod time;
|
||||||
|
mod util;
|
||||||
pub mod video;
|
pub mod video;
|
||||||
|
|
||||||
pub use entropy::RandomSource;
|
pub use entropy::RandomSource;
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
//! The pure cryptographic steps of pairing (`docs/PROTOCOL.md` 1.5), public so QA can test them against
|
//! The pure cryptographic steps of pairing (`docs/PROTOCOL.md` 1.5), public so QA can test them against
|
||||||
//! independent vectors (for example Python `hashlib` + `cryptography` with fixed test keys).
|
//! independent vectors (for example Python `hashlib` + `cryptography` with fixed test keys).
|
||||||
|
|
||||||
use super::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN};
|
use aes::Aes128;
|
||||||
|
use aes::cipher::{BlockCipherDecrypt, BlockCipherEncrypt, KeyInit};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
use super::{CHALLENGE_LEN, HASH_LEN, MAX_SIGNATURE_BYTES, Pin, SALT_LEN, SECRET_LEN};
|
||||||
use crate::Result;
|
use crate::Result;
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
|
||||||
/// AES-128 key used for every encrypted pairing value.
|
/// AES-128 key used for every encrypted pairing value.
|
||||||
pub type PairingKey = [u8; 16];
|
pub type PairingKey = [u8; 16];
|
||||||
@@ -10,20 +15,40 @@ pub type PairingKey = [u8; 16];
|
|||||||
/// `K = SHA-256(salt ‖ PIN digits)[0..16]`.
|
/// `K = SHA-256(salt ‖ PIN digits)[0..16]`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today; the `Result` keeps the signature uniform with the other steps.
|
||||||
pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result<PairingKey> {
|
pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result<PairingKey> {
|
||||||
let _ = (salt, pin);
|
let mut h = Sha256::new();
|
||||||
Err(crate::Error::Unimplemented)
|
h.update(salt);
|
||||||
|
h.update(pin.as_bytes());
|
||||||
|
let digest = h.finalize();
|
||||||
|
let mut key = [0u8; 16];
|
||||||
|
key.copy_from_slice(digest.get(..16).ok_or(malformed("sha-256 output"))?);
|
||||||
|
Ok(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ecb(key: &PairingKey, data: &[u8], encrypt: bool) -> Result<Vec<u8>> {
|
||||||
|
if data.is_empty() || !data.len().is_multiple_of(16) {
|
||||||
|
return Err(malformed("aes-ecb input is not whole blocks"));
|
||||||
|
}
|
||||||
|
let cipher = Aes128::new(key.into());
|
||||||
|
let mut out = data.to_vec();
|
||||||
|
for chunk in out.as_chunks_mut::<16>().0 {
|
||||||
|
let block: &mut aes::Block = chunk.into();
|
||||||
|
if encrypt {
|
||||||
|
cipher.encrypt_block(block);
|
||||||
|
} else {
|
||||||
|
cipher.decrypt_block(block);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AES-128-ECB encryption without padding.
|
/// AES-128-ECB encryption without padding.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] when `data` is not a whole number of 16-byte blocks. Phase A: always
|
/// [`crate::Error::Malformed`] when `data` is not a whole, non-zero number of 16-byte blocks.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (key, data);
|
ecb(key, data, true)
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AES-128-ECB decryption without padding.
|
/// AES-128-ECB decryption without padding.
|
||||||
@@ -31,8 +56,7 @@ pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
|||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`ecb_encrypt`].
|
/// As [`ecb_encrypt`].
|
||||||
pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (key, data);
|
ecb(key, data, false)
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `SHA-256(challenge ‖ cert_signature ‖ secret)`: the host's proof `H_s` (with the client challenge, the host
|
/// `SHA-256(challenge ‖ cert_signature ‖ secret)`: the host's proof `H_s` (with the client challenge, the host
|
||||||
@@ -40,32 +64,46 @@ pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
|||||||
/// certificate's signature and the client secret).
|
/// certificate's signature and the client secret).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] for a signature over [`super::MAX_SIGNATURE_BYTES`]. Phase A: always
|
/// [`crate::Error::TooLarge`] for a signature over [`MAX_SIGNATURE_BYTES`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn proof_hash(
|
pub fn proof_hash(
|
||||||
challenge: &[u8; CHALLENGE_LEN],
|
challenge: &[u8; CHALLENGE_LEN],
|
||||||
cert_signature: &[u8],
|
cert_signature: &[u8],
|
||||||
secret: &[u8; SECRET_LEN],
|
secret: &[u8; SECRET_LEN],
|
||||||
) -> Result<[u8; HASH_LEN]> {
|
) -> Result<[u8; HASH_LEN]> {
|
||||||
let _ = (challenge, cert_signature, secret);
|
cap("certificate signature", MAX_SIGNATURE_BYTES, cert_signature.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let mut h = Sha256::new();
|
||||||
|
h.update(challenge);
|
||||||
|
h.update(cert_signature);
|
||||||
|
h.update(secret);
|
||||||
|
let mut out = [0u8; HASH_LEN];
|
||||||
|
out.copy_from_slice(&h.finalize());
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Splits a decrypted `challengeresponse` (48 bytes) into the host proof `H_s` and the host challenge `S_c`.
|
/// Splits a decrypted `challengeresponse` (48 bytes) into the host proof `H_s` and the host challenge `S_c`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] unless exactly 48 bytes. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Malformed`] unless exactly 48 bytes.
|
||||||
pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> {
|
pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> {
|
||||||
let _ = decrypted;
|
if decrypted.len() != HASH_LEN + CHALLENGE_LEN {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("challengeresponse is not 48 bytes"));
|
||||||
|
}
|
||||||
|
let hash = crate::util::array::<HASH_LEN>("challengeresponse", decrypted, 0)?;
|
||||||
|
let challenge = crate::util::array::<CHALLENGE_LEN>("challengeresponse", decrypted, HASH_LEN)?;
|
||||||
|
Ok((hash, challenge))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Splits a `pairingsecret` into the host secret (16 bytes) and its signature (the rest).
|
/// Splits a `pairingsecret` into the host secret (16 bytes) and its signature (the rest).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] when shorter than 17 bytes, [`crate::Error::TooLarge`] when the signature is over
|
/// [`crate::Error::Malformed`] when shorter than 17 bytes, [`crate::Error::TooLarge`] when the signature is over
|
||||||
/// [`super::MAX_SIGNATURE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`MAX_SIGNATURE_BYTES`].
|
||||||
pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> {
|
pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> {
|
||||||
let _ = pairing_secret;
|
if pairing_secret.len() <= SECRET_LEN {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("pairingsecret too short"));
|
||||||
|
}
|
||||||
|
let signature = pairing_secret.get(SECRET_LEN..).unwrap_or(&[]);
|
||||||
|
cap("pairingsecret signature", MAX_SIGNATURE_BYTES, signature.len())?;
|
||||||
|
let secret = crate::util::array::<SECRET_LEN>("pairingsecret", pairing_secret, 0)?;
|
||||||
|
Ok((secret, signature))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,16 @@
|
|||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
|
||||||
use crate::{RandomSource, Result};
|
use rsa::pkcs1v15::{Signature, SigningKey, VerifyingKey};
|
||||||
|
use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
|
||||||
|
use rsa::signature::{SignatureEncoding, Signer, Verifier};
|
||||||
|
use rsa::{PrivateKey, PublicKey};
|
||||||
|
use sha2::Sha256;
|
||||||
|
use x509_cert::Certificate;
|
||||||
|
use x509_cert::der::{Decode, Encode};
|
||||||
|
|
||||||
|
use crate::util::{base64_decode, base64_pem_lines, cap, ct_eq, malformed};
|
||||||
|
use crate::{Error, RandomSource, Result};
|
||||||
|
|
||||||
/// Maximum size of a certificate in PEM form, in bytes.
|
/// Maximum size of a certificate in PEM form, in bytes.
|
||||||
pub const MAX_CERT_PEM_BYTES: usize = 16 * 1024;
|
pub const MAX_CERT_PEM_BYTES: usize = 16 * 1024;
|
||||||
@@ -12,6 +21,13 @@ pub const MAX_CERT_DER_BYTES: usize = 12 * 1024;
|
|||||||
pub const MAX_KEY_DER_BYTES: usize = 8 * 1024;
|
pub const MAX_KEY_DER_BYTES: usize = 8 * 1024;
|
||||||
/// RSA modulus size of keys this client generates.
|
/// RSA modulus size of keys this client generates.
|
||||||
pub const CLIENT_KEY_BITS: usize = 2048;
|
pub const CLIENT_KEY_BITS: usize = 2048;
|
||||||
|
/// Maximum length of a generated certificate's common name, in bytes.
|
||||||
|
pub const MAX_COMMON_NAME_BYTES: usize = 64;
|
||||||
|
/// Validity of a generated certificate: 20 years of 365.25 days.
|
||||||
|
pub const CLIENT_CERT_VALIDITY_SECS: i64 = 20 * 31_557_600;
|
||||||
|
|
||||||
|
/// OID 1.2.840.113549.1.1.1, rsaEncryption.
|
||||||
|
const RSA_ENCRYPTION: &str = "1.2.840.113549.1.1.1";
|
||||||
|
|
||||||
/// The client's long-lived identity towards GameStream hosts: a self-signed RSA-2048 / SHA-256 X.509 certificate
|
/// The client's long-lived identity towards GameStream hosts: a self-signed RSA-2048 / SHA-256 X.509 certificate
|
||||||
/// and its private key. Generated once per device and kept by the platform layer (never in logs; the key belongs
|
/// and its private key. Generated once per device and kept by the platform layer (never in logs; the key belongs
|
||||||
@@ -19,9 +35,116 @@ pub const CLIENT_KEY_BITS: usize = 2048;
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ClientIdentity {
|
pub struct ClientIdentity {
|
||||||
cert_der: Vec<u8>,
|
cert_der: Vec<u8>,
|
||||||
key_pkcs8_der: Vec<u8>,
|
key_pkcs8_der: zeroize::Zeroizing<Vec<u8>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A parsed certificate with an RSA key.
|
||||||
|
fn parse_rsa_cert(der: &[u8]) -> Result<(Certificate, PublicKey)> {
|
||||||
|
let cert = Certificate::from_der(der).map_err(|_| malformed("x509 certificate"))?;
|
||||||
|
let spki = cert.tbs_certificate().subject_public_key_info();
|
||||||
|
if spki.algorithm.oid.to_string() != RSA_ENCRYPTION {
|
||||||
|
return Err(malformed("certificate key is not RSA"));
|
||||||
|
}
|
||||||
|
let spki_der = spki.to_der().map_err(|_| malformed("certificate key"))?;
|
||||||
|
let key = PublicKey::from_public_key_der(&spki_der).map_err(|_| malformed("certificate RSA key"))?;
|
||||||
|
Ok((cert, key))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signature_bytes(cert: &Certificate) -> Vec<u8> {
|
||||||
|
cert.signature().raw_bytes().to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adapts our [`RandomSource`] to the RustCrypto RNG traits (infallible, cryptographic by contract).
|
||||||
|
struct Rng<'a>(&'a mut dyn RandomSource);
|
||||||
|
|
||||||
|
impl rand_core::TryRng for Rng<'_> {
|
||||||
|
type Error = core::convert::Infallible;
|
||||||
|
|
||||||
|
fn try_next_u32(&mut self) -> core::result::Result<u32, Self::Error> {
|
||||||
|
let mut b = [0u8; 4];
|
||||||
|
self.0.fill(&mut b);
|
||||||
|
Ok(u32::from_le_bytes(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_next_u64(&mut self) -> core::result::Result<u64, Self::Error> {
|
||||||
|
let mut b = [0u8; 8];
|
||||||
|
self.0.fill(&mut b);
|
||||||
|
Ok(u64::from_le_bytes(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> core::result::Result<(), Self::Error> {
|
||||||
|
self.0.fill(dst);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rand_core::TryCryptoRng for Rng<'_> {}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ DER writer
|
||||||
|
|
||||||
|
/// One DER TLV.
|
||||||
|
fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
|
||||||
|
let mut out = vec![tag];
|
||||||
|
let len = content.len();
|
||||||
|
if len < 0x80 {
|
||||||
|
out.push(len as u8);
|
||||||
|
} else {
|
||||||
|
let bytes = len.to_be_bytes();
|
||||||
|
let skip = bytes.iter().take_while(|b| **b == 0).count();
|
||||||
|
let used = bytes.get(skip..).unwrap_or(&[]);
|
||||||
|
out.push(0x80 | used.len() as u8);
|
||||||
|
out.extend_from_slice(used);
|
||||||
|
}
|
||||||
|
out.extend_from_slice(content);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seq(parts: &[&[u8]]) -> Vec<u8> {
|
||||||
|
tlv(0x30, &parts.concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Civil date from days since 1970-01-01 (proleptic Gregorian).
|
||||||
|
fn civil(days: i64) -> (i64, u32, u32) {
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z.rem_euclid(146_097);
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||||
|
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||||
|
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||||
|
(year, month, day)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RFC 5280 time: UTCTime for 1950..=2049, GeneralizedTime otherwise.
|
||||||
|
fn x509_time(unix: i64) -> Result<Vec<u8>> {
|
||||||
|
if unix < 0 {
|
||||||
|
return Err(malformed("certificate time before 1970"));
|
||||||
|
}
|
||||||
|
let (year, month, day) = civil(unix.div_euclid(86_400));
|
||||||
|
if year > 9999 {
|
||||||
|
return Err(malformed("certificate time after 9999"));
|
||||||
|
}
|
||||||
|
let secs = unix.rem_euclid(86_400);
|
||||||
|
let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60);
|
||||||
|
if year < 2050 {
|
||||||
|
Ok(tlv(0x17, format!("{:02}{month:02}{day:02}{h:02}{m:02}{s:02}Z", year % 100).as_bytes()))
|
||||||
|
} else {
|
||||||
|
Ok(tlv(0x18, format!("{year:04}{month:02}{day:02}{h:02}{m:02}{s:02}Z").as_bytes()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `SEQ { SET { SEQ { id-at-commonName, UTF8String } } }`.
|
||||||
|
fn name(common_name: &str) -> Vec<u8> {
|
||||||
|
let atv = seq(&[&[0x06, 0x03, 0x55, 0x04, 0x03], &tlv(0x0C, common_name.as_bytes())]);
|
||||||
|
seq(&[&tlv(0x31, &atv)])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// sha256WithRSAEncryption, NULL parameters.
|
||||||
|
const SHA256_WITH_RSA: [u8; 15] =
|
||||||
|
[0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00];
|
||||||
|
|
||||||
impl ClientIdentity {
|
impl ClientIdentity {
|
||||||
/// Generates a new key and self-signed certificate.
|
/// Generates a new key and self-signed certificate.
|
||||||
///
|
///
|
||||||
@@ -30,21 +153,56 @@ impl ClientIdentity {
|
|||||||
/// TV); call it once per device.
|
/// TV); call it once per device.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for an empty or oversized `common_name`. Phase A: always
|
/// [`Error::Malformed`] for an empty, oversized or control-character `common_name`, or a time before 1970;
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// [`Error::Crypto`] if key generation fails.
|
||||||
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
|
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
|
||||||
let _ = (rng, common_name, not_before_unix);
|
if common_name.is_empty()
|
||||||
Err(crate::Error::Unimplemented)
|
|| common_name.len() > MAX_COMMON_NAME_BYTES
|
||||||
|
|| common_name.chars().any(char::is_control)
|
||||||
|
{
|
||||||
|
return Err(malformed("certificate common name"));
|
||||||
|
}
|
||||||
|
let not_before = x509_time(not_before_unix)?;
|
||||||
|
let not_after = x509_time(not_before_unix.saturating_add(CLIENT_CERT_VALIDITY_SECS))?;
|
||||||
|
let mut serial = [0u8; 16];
|
||||||
|
rng.fill(&mut serial);
|
||||||
|
if let Some(first) = serial.first_mut() {
|
||||||
|
// Positive and with a non-zero top byte, so the INTEGER is 16 bytes, minimal.
|
||||||
|
*first = (*first & 0x7F) | 0x40;
|
||||||
|
}
|
||||||
|
let key = PrivateKey::new(&mut Rng(rng), CLIENT_KEY_BITS).map_err(|_| Error::Crypto)?;
|
||||||
|
let spki = key.to_public_key().to_public_key_der().map_err(|_| Error::Crypto)?;
|
||||||
|
let subject = name(common_name);
|
||||||
|
let tbs = seq(&[
|
||||||
|
&[0xA0, 0x03, 0x02, 0x01, 0x02],
|
||||||
|
&tlv(0x02, &serial),
|
||||||
|
&SHA256_WITH_RSA,
|
||||||
|
&subject,
|
||||||
|
&seq(&[¬_before, ¬_after]),
|
||||||
|
&subject,
|
||||||
|
spki.as_bytes(),
|
||||||
|
]);
|
||||||
|
let signature = SigningKey::<Sha256>::new(key.clone()).try_sign(&tbs).map_err(|_| Error::Crypto)?.to_vec();
|
||||||
|
let bits = [&[0u8][..], &signature].concat();
|
||||||
|
let cert = seq(&[&tbs, &SHA256_WITH_RSA, &tlv(0x03, &bits)]);
|
||||||
|
let pkcs8 = key.to_pkcs8_der().map_err(|_| Error::Crypto)?;
|
||||||
|
Self::from_der(&cert, pkcs8.as_bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads a stored identity. Checks that the key matches the certificate.
|
/// Loads a stored identity. Checks that the key matches the certificate.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`crate::Error::Malformed`]
|
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`Error::Malformed`] for bad DER, a
|
||||||
/// for bad DER or a key that does not match. Phase A: always [`crate::Error::Unimplemented`].
|
/// certificate without an RSA key, or a key that does not match.
|
||||||
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
|
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
|
||||||
let _ = (cert_der, key_pkcs8_der);
|
cap("client certificate", MAX_CERT_DER_BYTES, cert_der.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
cap("client key", MAX_KEY_DER_BYTES, key_pkcs8_der.len())?;
|
||||||
|
let (_, public) = parse_rsa_cert(cert_der)?;
|
||||||
|
let key = PrivateKey::from_pkcs8_der(key_pkcs8_der).map_err(|_| malformed("client key"))?;
|
||||||
|
if key.to_public_key() != public {
|
||||||
|
return Err(malformed("client key does not match its certificate"));
|
||||||
|
}
|
||||||
|
Ok(Self { cert_der: cert_der.to_vec(), key_pkcs8_der: zeroize::Zeroizing::new(key_pkcs8_der.to_vec()) })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The certificate, DER.
|
/// The certificate, DER.
|
||||||
@@ -62,26 +220,27 @@ impl ClientIdentity {
|
|||||||
/// The certificate as PEM text (what pairing step 1 sends, hex-encoded).
|
/// The certificate as PEM text (what pairing step 1 sends, hex-encoded).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn cert_pem(&self) -> Result<String> {
|
pub fn cert_pem(&self) -> Result<String> {
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(format!("-----BEGIN CERTIFICATE-----\n{}-----END CERTIFICATE-----\n", base64_pem_lines(&self.cert_der)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The raw `signatureValue` bytes of the certificate (input to the pairing proofs).
|
/// The raw `signatureValue` bytes of the certificate (input to the pairing proofs).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] if the stored certificate no longer parses (it was checked when loaded).
|
||||||
pub fn cert_signature(&self) -> Result<Vec<u8>> {
|
pub fn cert_signature(&self) -> Result<Vec<u8>> {
|
||||||
Err(crate::Error::Unimplemented)
|
parse_rsa_cert(&self.cert_der).map(|(c, _)| signature_bytes(&c))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key.
|
/// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Crypto`] if signing fails.
|
||||||
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
|
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = data;
|
let key = PrivateKey::from_pkcs8_der(&self.key_pkcs8_der).map_err(|_| Error::Crypto)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let sig = SigningKey::<Sha256>::new(key).try_sign(data).map_err(|_| Error::Crypto)?;
|
||||||
|
Ok(sig.to_vec())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,24 +260,34 @@ pub struct ServerCert {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ServerCert {
|
impl ServerCert {
|
||||||
/// Parses the PEM the host sent (already hex-decoded). Exactly one `CERTIFICATE` block.
|
/// Parses the PEM the host sent (already hex-decoded): exactly one `CERTIFICATE` block and nothing but
|
||||||
|
/// whitespace around it.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`crate::Error::Malformed`] for anything that is
|
/// [`Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`Error::Malformed`] for anything that is not one
|
||||||
/// not one well-formed X.509 certificate with an RSA key. Phase A: always [`crate::Error::Unimplemented`].
|
/// well-formed X.509 certificate with an RSA key.
|
||||||
pub fn from_pem(pem: &[u8]) -> Result<Self> {
|
pub fn from_pem(pem: &[u8]) -> Result<Self> {
|
||||||
let _ = pem;
|
const BEGIN: &[u8] = b"-----BEGIN CERTIFICATE-----";
|
||||||
Err(crate::Error::Unimplemented)
|
const END: &[u8] = b"-----END CERTIFICATE-----";
|
||||||
|
cap("host certificate PEM", MAX_CERT_PEM_BYTES, pem.len())?;
|
||||||
|
let trimmed = pem.trim_ascii();
|
||||||
|
let body =
|
||||||
|
trimmed.strip_prefix(BEGIN).and_then(|b| b.strip_suffix(END)).ok_or(malformed("host certificate PEM"))?;
|
||||||
|
if body.windows(5).any(|w| w == b"-----") {
|
||||||
|
return Err(malformed("host certificate PEM holds more than one block"));
|
||||||
|
}
|
||||||
|
let der = base64_decode("host certificate PEM", body)?;
|
||||||
|
Self::from_der(&der)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads a stored certificate.
|
/// Loads a stored certificate.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`crate::Error::Malformed`] otherwise. Phase A:
|
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
|
||||||
/// always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn from_der(der: &[u8]) -> Result<Self> {
|
pub fn from_der(der: &[u8]) -> Result<Self> {
|
||||||
let _ = der;
|
cap("host certificate", MAX_CERT_DER_BYTES, der.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
parse_rsa_cert(der)?;
|
||||||
|
Ok(Self { der: der.to_vec() })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The certificate, DER.
|
/// The certificate, DER.
|
||||||
@@ -130,27 +299,28 @@ impl ServerCert {
|
|||||||
/// The raw `signatureValue` bytes (input to the pairing proofs).
|
/// The raw `signatureValue` bytes (input to the pairing proofs).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] if the stored certificate no longer parses.
|
||||||
pub fn signature(&self) -> Result<Vec<u8>> {
|
pub fn signature(&self) -> Result<Vec<u8>> {
|
||||||
Err(crate::Error::Unimplemented)
|
parse_rsa_cert(&self.der).map(|(c, _)| signature_bytes(&c))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Verifies an RSASSA-PKCS1-v1_5 / SHA-256 `signature` over `data` with the certificate's public key.
|
/// Verifies an RSASSA-PKCS1-v1_5 / SHA-256 `signature` over `data` with the certificate's public key.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Crypto`] when it does not verify. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Crypto`] when it does not verify.
|
||||||
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
|
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
|
||||||
let _ = (data, signature);
|
let (_, key) = parse_rsa_cert(&self.der)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let sig = Signature::try_from(signature).map_err(|_| Error::Crypto)?;
|
||||||
|
VerifyingKey::<Sha256>::new(key).verify(data, &sig).map_err(|_| Error::Crypto)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// TLS pinning: whether the certificate a host presents over HTTPS (DER) is exactly this one, compared in
|
/// TLS pinning: whether the certificate a host presents over HTTPS (DER) is exactly this one, compared in
|
||||||
/// constant time. The platform's TLS verifier calls this and nothing else to accept the host.
|
/// constant time. The platform's TLS verifier calls this and nothing else to accept the host.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`].
|
||||||
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
|
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
|
||||||
let _ = presented_der;
|
cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(ct_eq(&self.der, presented_der))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,12 +11,14 @@
|
|||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Each [`PairingSession::handle_response`] consumes one HTTP answer body and returns the next request to send,
|
//! Each [`PairingSession::handle_response`] consumes one HTTP answer body and returns the next request to send,
|
||||||
//! or the finished [`PairedHost`].
|
//! or the finished [`PairedHost`]. Every answer must carry the element of its own step; an answer meant for another
|
||||||
|
//! step fails the session, so replayed or reordered answers can never skip a check.
|
||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
|
||||||
use crate::http::HttpRequest;
|
use crate::http::{HttpRequest, MAX_DEVICE_NAME_BYTES, Scheme, build, check_unique_id};
|
||||||
use crate::{RandomSource, Result};
|
use crate::util::{ct_eq, hex_decode, hex_encode, malformed};
|
||||||
|
use crate::{Error, RandomSource, Result};
|
||||||
|
|
||||||
pub mod crypto;
|
pub mod crypto;
|
||||||
pub mod identity;
|
pub mod identity;
|
||||||
@@ -37,28 +39,47 @@ pub const PIN_LEN: usize = 4;
|
|||||||
pub const MAX_PAIR_RESPONSE_BYTES: usize = 64 * 1024;
|
pub const MAX_PAIR_RESPONSE_BYTES: usize = 64 * 1024;
|
||||||
/// Maximum size of a signature accepted from the host (RSA-8192), in bytes.
|
/// Maximum size of a signature accepted from the host (RSA-8192), in bytes.
|
||||||
pub const MAX_SIGNATURE_BYTES: usize = 1024;
|
pub const MAX_SIGNATURE_BYTES: usize = 1024;
|
||||||
|
/// How long the caller should wait for the step 1 answer: the host holds it until the PIN is entered.
|
||||||
|
pub const STEP1_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(120);
|
||||||
|
|
||||||
/// A 4-digit GameStream PIN.
|
/// A 4-digit GameStream PIN.
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct Pin([u8; PIN_LEN]);
|
pub struct Pin([u8; PIN_LEN]);
|
||||||
|
|
||||||
impl Pin {
|
impl Pin {
|
||||||
/// Draws a uniformly random PIN (no modulo bias).
|
/// Draws a uniformly random PIN (rejection sampling, no modulo bias).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = rng;
|
let mut digits = [0u8; PIN_LEN];
|
||||||
Err(crate::Error::Unimplemented)
|
for d in &mut digits {
|
||||||
|
loop {
|
||||||
|
let mut b = [0u8; 1];
|
||||||
|
rng.fill(&mut b);
|
||||||
|
let [v] = b;
|
||||||
|
// 250 = 25 × 10: values 250..=255 would favour digits 0-5.
|
||||||
|
if v < 250 {
|
||||||
|
*d = b'0' + v % 10;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self(digits))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses exactly four ASCII digits.
|
/// Parses exactly four ASCII digits.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for anything else. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] for anything else.
|
||||||
pub fn from_digits(digits: &str) -> Result<Self> {
|
pub fn from_digits(digits: &str) -> Result<Self> {
|
||||||
let _ = digits;
|
let b = digits.as_bytes();
|
||||||
Err(crate::Error::Unimplemented)
|
if b.len() != PIN_LEN || !b.iter().all(u8::is_ascii_digit) {
|
||||||
|
return Err(malformed("PIN"));
|
||||||
|
}
|
||||||
|
let mut out = [0u8; PIN_LEN];
|
||||||
|
out.copy_from_slice(b);
|
||||||
|
Ok(Self(out))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The four ASCII digits.
|
/// The four ASCII digits.
|
||||||
@@ -140,17 +161,41 @@ pub struct PairResponse {
|
|||||||
/// Parses one pairing answer.
|
/// Parses one pairing answer.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`crate::Error::HostStatus`] for a non-200
|
/// [`Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`Error::HostStatus`] for a non-200 answer,
|
||||||
/// answer, [`crate::Error::Malformed`] for bad hex or a missing `paired`. Phase A: always
|
/// [`Error::Malformed`] for bad hex or a missing or bad `paired`.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_pair_response(body: &[u8]) -> Result<PairResponse> {
|
pub fn parse_pair_response(body: &[u8]) -> Result<PairResponse> {
|
||||||
let _ = body;
|
let doc = crate::http::document(body, MAX_PAIR_RESPONSE_BYTES, "pairing answer")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let r = &doc.root;
|
||||||
|
let paired = match r.child("paired").map(|p| p.text.as_str()) {
|
||||||
|
Some("1") => true,
|
||||||
|
Some("0") => false,
|
||||||
|
_ => return Err(malformed("pairing answer: paired")),
|
||||||
|
};
|
||||||
|
let hex_field = |name: &str| -> Result<Option<Vec<u8>>> {
|
||||||
|
r.child(name).map(|e| hex_decode("pairing answer hex", &e.text)).transpose()
|
||||||
|
};
|
||||||
|
Ok(PairResponse {
|
||||||
|
paired,
|
||||||
|
plain_cert: hex_field("plaincert")?,
|
||||||
|
challenge_response: hex_field("challengeresponse")?,
|
||||||
|
pairing_secret: hex_field("pairingsecret")?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A failed step: why, and the error to return.
|
||||||
|
type StepError = (PairingFailure, Error);
|
||||||
|
|
||||||
/// One pairing attempt with one host.
|
/// One pairing attempt with one host.
|
||||||
pub struct PairingSession {
|
pub struct PairingSession {
|
||||||
state: PairingState,
|
state: PairingState,
|
||||||
|
unique_id: String,
|
||||||
|
device_name: String,
|
||||||
|
cert_der: Vec<u8>,
|
||||||
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
|
server_cert: Option<ServerCert>,
|
||||||
|
client_challenge: [u8; CHALLENGE_LEN],
|
||||||
|
host_proof: [u8; HASH_LEN],
|
||||||
|
client_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PairingSession {
|
impl PairingSession {
|
||||||
@@ -159,8 +204,7 @@ impl PairingSession {
|
|||||||
/// `unique_id` is this client's id (stable per device), `device_name` is shown on the host.
|
/// `unique_id` is this client's id (stable per device), `device_name` is shown on the host.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a bad `unique_id` or `device_name`. Phase A: always
|
/// [`Error::Malformed`] for a bad `unique_id` or `device_name` (empty, too long, control characters).
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn start(
|
pub fn start(
|
||||||
identity: &ClientIdentity,
|
identity: &ClientIdentity,
|
||||||
unique_id: &str,
|
unique_id: &str,
|
||||||
@@ -168,8 +212,47 @@ impl PairingSession {
|
|||||||
pin: Pin,
|
pin: Pin,
|
||||||
rng: &mut dyn RandomSource,
|
rng: &mut dyn RandomSource,
|
||||||
) -> Result<(Self, HttpRequest)> {
|
) -> Result<(Self, HttpRequest)> {
|
||||||
let _ = (identity, unique_id, device_name, pin, rng);
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
if device_name.is_empty()
|
||||||
|
|| device_name.len() > MAX_DEVICE_NAME_BYTES
|
||||||
|
|| device_name.chars().any(char::is_control)
|
||||||
|
{
|
||||||
|
return Err(malformed("device name"));
|
||||||
|
}
|
||||||
|
let mut salt = [0u8; SALT_LEN];
|
||||||
|
rng.fill(&mut salt);
|
||||||
|
let key = crypto::derive_key(&salt, &pin)?;
|
||||||
|
let session = Self {
|
||||||
|
state: PairingState::AwaitServerCert,
|
||||||
|
unique_id: unique_id.to_owned(),
|
||||||
|
device_name: device_name.to_owned(),
|
||||||
|
cert_der: identity.cert_der().to_vec(),
|
||||||
|
key: zeroize::Zeroizing::new(key),
|
||||||
|
server_cert: None,
|
||||||
|
client_challenge: [0; CHALLENGE_LEN],
|
||||||
|
host_proof: [0; HASH_LEN],
|
||||||
|
client_secret: zeroize::Zeroizing::new([0; SECRET_LEN]),
|
||||||
|
};
|
||||||
|
let cert = hex_encode(identity.cert_pem()?.as_bytes());
|
||||||
|
let salt = hex_encode(&salt);
|
||||||
|
let req = session.request(
|
||||||
|
Scheme::Http,
|
||||||
|
&[("phrase", "getservercert"), ("salt", &salt), ("clientcert", &cert)],
|
||||||
|
Some(STEP1_TIMEOUT),
|
||||||
|
);
|
||||||
|
Ok((session, req))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request(&self, scheme: Scheme, extra: &[(&str, &str)], timeout: Option<core::time::Duration>) -> HttpRequest {
|
||||||
|
let mut params: Vec<(&str, &str)> =
|
||||||
|
vec![("uniqueid", &self.unique_id), ("devicename", &self.device_name), ("updateState", "1")];
|
||||||
|
params.extend_from_slice(extra);
|
||||||
|
build(scheme, "/pair", ¶ms, timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fail(&mut self, why: PairingFailure, error: Error) -> Result<PairingStep> {
|
||||||
|
self.state = PairingState::Failed(why);
|
||||||
|
Err(error)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds the answer to the last request: its HTTP status and body. `identity` must be the one passed to
|
/// Feeds the answer to the last request: its HTTP status and body. `identity` must be the one passed to
|
||||||
@@ -177,9 +260,9 @@ impl PairingSession {
|
|||||||
/// randomness for steps 2 and 3.
|
/// randomness for steps 2 and 3.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as
|
/// [`Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as
|
||||||
/// [`parse_pair_response`], [`crate::Error::State`] after `Paired` or `Failed`, [`crate::Error::Malformed`] for
|
/// [`parse_pair_response`], [`Error::State`] after `Paired` or `Failed`, [`Error::Malformed`] for a different
|
||||||
/// a different identity than at the start. Phase A: always [`crate::Error::Unimplemented`].
|
/// identity than at the start.
|
||||||
pub fn handle_response(
|
pub fn handle_response(
|
||||||
&mut self,
|
&mut self,
|
||||||
identity: &ClientIdentity,
|
identity: &ClientIdentity,
|
||||||
@@ -187,8 +270,89 @@ impl PairingSession {
|
|||||||
body: &[u8],
|
body: &[u8],
|
||||||
rng: &mut dyn RandomSource,
|
rng: &mut dyn RandomSource,
|
||||||
) -> Result<PairingStep> {
|
) -> Result<PairingStep> {
|
||||||
let _ = (identity, http_status, body, rng);
|
if matches!(self.state, PairingState::Paired | PairingState::Failed(_)) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::State { expected: "a pairing step in progress" });
|
||||||
|
}
|
||||||
|
if identity.cert_der() != self.cert_der.as_slice() {
|
||||||
|
return Err(malformed("pairing: a different identity than at the start"));
|
||||||
|
}
|
||||||
|
if http_status != 200 {
|
||||||
|
return self.fail(PairingFailure::HostStatus, Error::HostStatus { code: u32::from(http_status) });
|
||||||
|
}
|
||||||
|
let answer = match parse_pair_response(body) {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(e @ Error::HostStatus { .. }) => return self.fail(PairingFailure::HostStatus, e),
|
||||||
|
Err(e) => return self.fail(PairingFailure::MalformedAnswer, e),
|
||||||
|
};
|
||||||
|
if !answer.paired {
|
||||||
|
return self.fail(PairingFailure::HostRefused, Error::PairingRefused);
|
||||||
|
}
|
||||||
|
match self.step(identity, answer, rng) {
|
||||||
|
Ok(step) => Ok(step),
|
||||||
|
Err((why, e)) => self.fail(why, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step(
|
||||||
|
&mut self,
|
||||||
|
identity: &ClientIdentity,
|
||||||
|
answer: PairResponse,
|
||||||
|
rng: &mut dyn RandomSource,
|
||||||
|
) -> core::result::Result<PairingStep, StepError> {
|
||||||
|
let bad = |e: Error| (PairingFailure::MalformedAnswer, e);
|
||||||
|
match self.state {
|
||||||
|
PairingState::AwaitServerCert => {
|
||||||
|
let pem = answer.plain_cert.ok_or_else(|| bad(malformed("pairing: no plaincert")))?;
|
||||||
|
let cert = ServerCert::from_pem(&pem).map_err(bad)?;
|
||||||
|
self.server_cert = Some(cert);
|
||||||
|
rng.fill(&mut self.client_challenge);
|
||||||
|
let enc = crypto::ecb_encrypt(&self.key, &self.client_challenge).map_err(bad)?;
|
||||||
|
self.state = PairingState::AwaitChallengeResponse;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Http, &[("clientchallenge", &hex_encode(&enc))], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitChallengeResponse => {
|
||||||
|
let cr = answer.challenge_response.ok_or_else(|| bad(malformed("pairing: no challengeresponse")))?;
|
||||||
|
let plain = crypto::ecb_decrypt(&self.key, &cr).map_err(bad)?;
|
||||||
|
let (host_proof, server_challenge) = crypto::split_challenge_response(&plain).map_err(bad)?;
|
||||||
|
self.host_proof = host_proof;
|
||||||
|
rng.fill(&mut *self.client_secret);
|
||||||
|
let client_sig = identity.cert_signature().map_err(bad)?;
|
||||||
|
let client_proof =
|
||||||
|
crypto::proof_hash(&server_challenge, &client_sig, &self.client_secret).map_err(bad)?;
|
||||||
|
let enc = crypto::ecb_encrypt(&self.key, &client_proof).map_err(bad)?;
|
||||||
|
self.state = PairingState::AwaitPairingSecret;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Http, &[("serverchallengeresp", &hex_encode(&enc))], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitPairingSecret => {
|
||||||
|
let ps = answer.pairing_secret.ok_or_else(|| bad(malformed("pairing: no pairingsecret")))?;
|
||||||
|
let (secret, signature) = crypto::split_pairing_secret(&ps).map_err(bad)?;
|
||||||
|
let cert = self.server_cert.as_ref().ok_or_else(|| bad(malformed("pairing: no host certificate")))?;
|
||||||
|
cert.verify(&secret, signature)
|
||||||
|
.map_err(|_| (PairingFailure::BadHostSignature, Error::PairingRefused))?;
|
||||||
|
let host_sig = cert.signature().map_err(bad)?;
|
||||||
|
let expected = crypto::proof_hash(&self.client_challenge, &host_sig, &secret).map_err(bad)?;
|
||||||
|
if !ct_eq(&expected, &self.host_proof) {
|
||||||
|
return Err((PairingFailure::ProofMismatch, Error::PairingRefused));
|
||||||
|
}
|
||||||
|
let sig = identity.sign(&*self.client_secret).map_err(bad)?;
|
||||||
|
let value = [&self.client_secret[..], &sig].concat();
|
||||||
|
self.state = PairingState::AwaitClientSecretAck;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Http, &[("clientpairingsecret", &hex_encode(&value))], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitClientSecretAck => {
|
||||||
|
self.state = PairingState::AwaitPairChallenge;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Https, &[("phrase", "pairchallenge")], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitPairChallenge => {
|
||||||
|
let server_cert =
|
||||||
|
self.server_cert.clone().ok_or_else(|| bad(malformed("pairing: no host certificate")))?;
|
||||||
|
self.state = PairingState::Paired;
|
||||||
|
Ok(PairingStep::Paired(PairedHost { server_cert }))
|
||||||
|
}
|
||||||
|
PairingState::Paired | PairingState::Failed(_) => {
|
||||||
|
Err((PairingFailure::MalformedAnswer, Error::State { expected: "a pairing step in progress" }))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where the handshake is.
|
/// Where the handshake is.
|
||||||
|
|||||||
@@ -26,8 +26,18 @@ pub struct RtpHeader {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Truncated`] for fewer than 12 bytes, [`crate::Error::UnexpectedValue`] for another RTP version.
|
/// [`crate::Error::Truncated`] for fewer than 12 bytes, [`crate::Error::UnexpectedValue`] for another RTP version.
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_rtp_header(packet: &[u8]) -> crate::Result<RtpHeader> {
|
pub fn parse_rtp_header(packet: &[u8]) -> crate::Result<RtpHeader> {
|
||||||
let _ = packet;
|
const W: &str = "rtp header";
|
||||||
Err(crate::Error::Unimplemented)
|
crate::util::need(W, RTP_HEADER_LEN, packet.len())?;
|
||||||
|
let flags = crate::util::byte(W, packet, 0)?;
|
||||||
|
if flags >> 6 != 2 {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "rtp version", value: (flags >> 6).into() });
|
||||||
|
}
|
||||||
|
Ok(RtpHeader {
|
||||||
|
flags,
|
||||||
|
payload_type: crate::util::byte(W, packet, 1)?,
|
||||||
|
sequence: crate::util::u16_be(W, packet, 2)?,
|
||||||
|
timestamp: crate::util::u32_be(W, packet, 4)?,
|
||||||
|
ssrc: crate::util::u32_be(W, packet, 8)?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,20 @@
|
|||||||
//! answers with [`super::RtspFramer`], and feeds each whole answer to [`RtspClient::handle_response`] until it
|
//! answers with [`super::RtspFramer`], and feeds each whole answer to [`RtspClient::handle_response`] until it
|
||||||
//! returns [`RtspProgress::Ready`].
|
//! returns [`RtspProgress::Ready`].
|
||||||
|
|
||||||
use super::sdp::{EncryptionFlags, HostCapabilities, OpusConfig};
|
use super::sdp::{self, EncryptionFlags, HostCapabilities, OpusConfig};
|
||||||
|
use super::{Method, RtspRequest, RtspResponse, parse_response};
|
||||||
use crate::http::launch::AudioLayout;
|
use crate::http::launch::AudioLayout;
|
||||||
|
use crate::util::{check_rtsp_url, malformed, parse_u16};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// `X-GS-ClientVersion` sent with every request (the value in Wolf's example, UNKNOWN U5).
|
||||||
|
pub const CLIENT_VERSION: &str = "14";
|
||||||
|
/// What the client sends to the video and audio ports to open the NAT path (Moonshine accepts it; U8).
|
||||||
|
pub const PING_PAYLOAD: &[u8] = b"PING";
|
||||||
|
/// SETUP targets (Moonshine's example form `streamid=control/13/0`; UNKNOWN U5).
|
||||||
|
const SETUP_TARGETS: [&str; 3] = ["streamid=audio/0/0", "streamid=video/0/0", "streamid=control/13/0"];
|
||||||
|
/// `Transport` value of the SETUP requests (not interpreted by the hosts we know of; U5).
|
||||||
|
const TRANSPORT: &str = "unicast;X-GS-ClientPort=50000-50001";
|
||||||
|
|
||||||
/// Video codecs.
|
/// Video codecs.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -113,6 +125,15 @@ pub enum RtspProgress {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct RtspClient {
|
pub struct RtspClient {
|
||||||
state: RtspClientState,
|
state: RtspClientState,
|
||||||
|
url: String,
|
||||||
|
config: StreamConfig,
|
||||||
|
cseq: u32,
|
||||||
|
/// The request to hand out, and whether one was handed out and is not answered yet.
|
||||||
|
pending: Option<Vec<u8>>,
|
||||||
|
outstanding: bool,
|
||||||
|
host: Option<HostCapabilities>,
|
||||||
|
ports: [u16; 3],
|
||||||
|
session_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RtspClient {
|
impl RtspClient {
|
||||||
@@ -120,27 +141,164 @@ impl RtspClient {
|
|||||||
/// is ready in [`Self::poll_request`].
|
/// is ready in [`Self::poll_request`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame
|
/// [`Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame
|
||||||
/// rate, bitrate or packet size. Phase A: always [`crate::Error::Unimplemented`].
|
/// rate, bitrate or packet size.
|
||||||
pub fn new(session_url: &str, config: StreamConfig) -> crate::Result<Self> {
|
pub fn new(session_url: &str, config: StreamConfig) -> Result<Self> {
|
||||||
let _ = (session_url, config);
|
check_rtsp_url("rtsp session URL", session_url)?;
|
||||||
Err(crate::Error::Unimplemented)
|
if config.width == 0
|
||||||
|
|| config.height == 0
|
||||||
|
|| config.fps == 0
|
||||||
|
|| config.bitrate_kbps == 0
|
||||||
|
|| config.packet_size == 0
|
||||||
|
|| config.audio_packet_duration_ms == 0
|
||||||
|
{
|
||||||
|
return Err(malformed("rtsp stream config"));
|
||||||
|
}
|
||||||
|
let mut c = Self {
|
||||||
|
state: RtspClientState::Options,
|
||||||
|
url: session_url.to_owned(),
|
||||||
|
config,
|
||||||
|
cseq: 0,
|
||||||
|
pending: None,
|
||||||
|
outstanding: false,
|
||||||
|
host: None,
|
||||||
|
ports: [0; 3],
|
||||||
|
session_id: None,
|
||||||
|
};
|
||||||
|
let url = c.url.clone();
|
||||||
|
c.queue(Method::Options, &url, Vec::new(), Vec::new())?;
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn queue(&mut self, method: Method, target: &str, mut extra: Vec<(String, String)>, body: Vec<u8>) -> Result<()> {
|
||||||
|
self.cseq = self.cseq.wrapping_add(1);
|
||||||
|
let mut headers = vec![("CSeq".to_owned(), self.cseq.to_string())];
|
||||||
|
headers.push(("X-GS-ClientVersion".to_owned(), CLIENT_VERSION.to_owned()));
|
||||||
|
if let Some(s) = &self.session_id {
|
||||||
|
headers.push(("Session".to_owned(), s.clone()));
|
||||||
|
}
|
||||||
|
headers.append(&mut extra);
|
||||||
|
if !body.is_empty() {
|
||||||
|
headers.push(("Content-Length".to_owned(), body.len().to_string()));
|
||||||
|
}
|
||||||
|
let req = RtspRequest { method, target: target.to_owned(), headers, body };
|
||||||
|
self.pending = Some(req.encode()?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next request to write, if one is due. Each is returned once.
|
/// The next request to write, if one is due. Each is returned once.
|
||||||
pub fn poll_request(&mut self) -> Option<Vec<u8>> {
|
pub fn poll_request(&mut self) -> Option<Vec<u8>> {
|
||||||
None
|
let req = self.pending.take();
|
||||||
|
if req.is_some() {
|
||||||
|
self.outstanding = true;
|
||||||
|
}
|
||||||
|
req
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one whole answer (see [`super::RtspFramer`]).
|
/// Feeds one whole answer (see [`super::RtspFramer`]).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `CSeq` that does not
|
/// [`Error::HostStatus`] for a non-200 answer, [`Error::Malformed`] for a `CSeq` that does not match or a bad
|
||||||
/// match or a bad payload, [`crate::Error::Unsupported`] when the host lacks something required,
|
/// payload, [`Error::Unsupported`] when the host lacks something required, [`Error::State`] when no request is
|
||||||
/// [`crate::Error::State`] when no request is outstanding. Phase A: always [`crate::Error::Unimplemented`].
|
/// outstanding. Every error but `State` moves the client to [`RtspClientState::Failed`].
|
||||||
pub fn handle_response(&mut self, message: &[u8]) -> crate::Result<RtspProgress> {
|
pub fn handle_response(&mut self, message: &[u8]) -> Result<RtspProgress> {
|
||||||
let _ = message;
|
if !self.outstanding || matches!(self.state, RtspClientState::Ready | RtspClientState::Failed) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::State { expected: "an RTSP request outstanding" });
|
||||||
|
}
|
||||||
|
self.outstanding = false;
|
||||||
|
match self.advance(message) {
|
||||||
|
Ok(p) => Ok(p),
|
||||||
|
Err(e) => {
|
||||||
|
self.state = RtspClientState::Failed;
|
||||||
|
self.pending = None;
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn advance(&mut self, message: &[u8]) -> Result<RtspProgress> {
|
||||||
|
let r = parse_response(message)?;
|
||||||
|
let cseq = r.header("CSeq").ok_or(malformed("rtsp answer without CSeq"))?;
|
||||||
|
if crate::util::parse_u32("rtsp CSeq", cseq)? != self.cseq {
|
||||||
|
return Err(malformed("rtsp answer to another request (CSeq)"));
|
||||||
|
}
|
||||||
|
if r.status != 200 {
|
||||||
|
return Err(Error::HostStatus { code: u32::from(r.status) });
|
||||||
|
}
|
||||||
|
let url = self.url.clone();
|
||||||
|
match self.state {
|
||||||
|
RtspClientState::Options => {
|
||||||
|
self.queue(Method::Describe, &url, vec![("Accept".into(), "application/sdp".into())], Vec::new())?;
|
||||||
|
self.state = RtspClientState::Describe;
|
||||||
|
}
|
||||||
|
RtspClientState::Describe => {
|
||||||
|
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(&r.body)?)?;
|
||||||
|
sdp::negotiated_encryption(&self.config, &host)?;
|
||||||
|
self.host = Some(host);
|
||||||
|
self.setup(0)?;
|
||||||
|
self.state = RtspClientState::SetupAudio;
|
||||||
|
}
|
||||||
|
RtspClientState::SetupAudio | RtspClientState::SetupVideo | RtspClientState::SetupControl => {
|
||||||
|
let index = match self.state {
|
||||||
|
RtspClientState::SetupAudio => 0,
|
||||||
|
RtspClientState::SetupVideo => 1,
|
||||||
|
_ => 2,
|
||||||
|
};
|
||||||
|
let port = server_port(&r)?;
|
||||||
|
if let Some(slot) = self.ports.get_mut(index) {
|
||||||
|
*slot = port;
|
||||||
|
}
|
||||||
|
if let Some(s) = r.header("Session") {
|
||||||
|
let id = s.split(';').next().unwrap_or("").trim();
|
||||||
|
if !id.is_empty() {
|
||||||
|
self.session_id = Some(id.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if index < 2 {
|
||||||
|
self.setup(index + 1)?;
|
||||||
|
self.state = if index == 0 { RtspClientState::SetupVideo } else { RtspClientState::SetupControl };
|
||||||
|
} else {
|
||||||
|
let host = self.host.as_ref().ok_or(Error::State { expected: "DESCRIBE answered" })?;
|
||||||
|
let body = sdp::build_announce(&self.config, host)?;
|
||||||
|
let target = SETUP_TARGETS.get(2).copied().unwrap_or("streamid=control/13/0");
|
||||||
|
self.queue(
|
||||||
|
Method::Announce,
|
||||||
|
target,
|
||||||
|
vec![("Content-type".into(), "application/sdp".into())],
|
||||||
|
body,
|
||||||
|
)?;
|
||||||
|
self.state = RtspClientState::Announce;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RtspClientState::Announce => {
|
||||||
|
self.queue(Method::Play, &url, Vec::new(), Vec::new())?;
|
||||||
|
self.state = RtspClientState::Play;
|
||||||
|
}
|
||||||
|
RtspClientState::Play => {
|
||||||
|
let host = self.host.clone().ok_or(Error::State { expected: "DESCRIBE answered" })?;
|
||||||
|
let encryption = sdp::negotiated_encryption(&self.config, &host)?;
|
||||||
|
let [audio, video, control] = self.ports;
|
||||||
|
let stream = NegotiatedStream {
|
||||||
|
ports: StreamPorts { audio, video, control },
|
||||||
|
encryption,
|
||||||
|
opus: host.opus_for(self.config.audio.channels()),
|
||||||
|
host,
|
||||||
|
session_id: self.session_id.clone(),
|
||||||
|
ping_payload: PING_PAYLOAD.to_vec(),
|
||||||
|
};
|
||||||
|
self.state = RtspClientState::Ready;
|
||||||
|
return Ok(RtspProgress::Ready(stream));
|
||||||
|
}
|
||||||
|
RtspClientState::Ready | RtspClientState::Failed => {
|
||||||
|
return Err(Error::State { expected: "an RTSP request outstanding" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(RtspProgress::Continue)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup(&mut self, index: usize) -> Result<()> {
|
||||||
|
let target = SETUP_TARGETS.get(index).copied().ok_or(Error::State { expected: "a SETUP stream" })?;
|
||||||
|
self.queue(Method::Setup, target, vec![("Transport".into(), TRANSPORT.into())], Vec::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where the negotiation is.
|
/// Where the negotiation is.
|
||||||
@@ -149,3 +307,19 @@ impl RtspClient {
|
|||||||
self.state
|
self.state
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `server_port=N` from the `Transport` header (other `;` parts ignored), N in 1..=65535.
|
||||||
|
fn server_port(r: &RtspResponse) -> Result<u16> {
|
||||||
|
let t = r.header("Transport").ok_or(malformed("rtsp SETUP answer without Transport"))?;
|
||||||
|
let v = t
|
||||||
|
.split(';')
|
||||||
|
.find_map(|p| p.trim().strip_prefix("server_port="))
|
||||||
|
.ok_or(malformed("rtsp Transport without server_port"))?;
|
||||||
|
// `server_port=a-b` names a range; the first port is the one used.
|
||||||
|
let first = v.split('-').next().unwrap_or("");
|
||||||
|
let port = parse_u16("rtsp server_port", first)?;
|
||||||
|
if port == 0 {
|
||||||
|
return Err(malformed("rtsp server_port 0"));
|
||||||
|
}
|
||||||
|
Ok(port)
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
|
//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP,
|
||||||
//! and the client state machine.
|
//! the client state machine and the host's session ([`server`], section 2.5).
|
||||||
|
|
||||||
pub mod client;
|
pub mod client;
|
||||||
pub mod sdp;
|
pub mod sdp;
|
||||||
|
pub mod server;
|
||||||
|
|
||||||
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
||||||
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
||||||
|
pub use server::{HostOffer, RtspServer, RtspServerState, ServerConfig, ServerEvent, ServerReply};
|
||||||
|
|
||||||
|
use crate::util::{cap, malformed, parse_dec};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Default RTSP port.
|
/// Default RTSP port.
|
||||||
pub const DEFAULT_RTSP_PORT: u16 = 48010;
|
pub const DEFAULT_RTSP_PORT: u16 = 48010;
|
||||||
@@ -16,6 +21,9 @@ pub const MAX_RTSP_LINE_BYTES: usize = 4096;
|
|||||||
/// Maximum number of header lines in one message.
|
/// Maximum number of header lines in one message.
|
||||||
pub const MAX_RTSP_HEADERS: usize = 64;
|
pub const MAX_RTSP_HEADERS: usize = 64;
|
||||||
|
|
||||||
|
/// The only protocol version spoken.
|
||||||
|
const VERSION: &str = "RTSP/1.0";
|
||||||
|
|
||||||
/// The methods this client sends.
|
/// The methods this client sends.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub enum Method {
|
pub enum Method {
|
||||||
@@ -31,6 +39,24 @@ pub enum Method {
|
|||||||
Play,
|
Play,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Method {
|
||||||
|
/// The method token.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Options => "OPTIONS",
|
||||||
|
Self::Describe => "DESCRIBE",
|
||||||
|
Self::Setup => "SETUP",
|
||||||
|
Self::Announce => "ANNOUNCE",
|
||||||
|
Self::Play => "PLAY",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_token(t: &str) -> Option<Self> {
|
||||||
|
[Self::Options, Self::Describe, Self::Setup, Self::Announce, Self::Play].into_iter().find(|m| m.as_str() == t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// An RTSP request.
|
/// An RTSP request.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct RtspRequest {
|
pub struct RtspRequest {
|
||||||
@@ -44,15 +70,44 @@ pub struct RtspRequest {
|
|||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_token(b: u8) -> bool {
|
||||||
|
b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
|
||||||
|
}
|
||||||
|
|
||||||
impl RtspRequest {
|
impl RtspRequest {
|
||||||
/// Serializes the request (CRLF line ends, empty line, payload). Refuses CR or LF inside a target, header
|
/// Serializes the request (CRLF line ends, empty line, payload) with exactly the given headers. Refuses CR or
|
||||||
/// name or value.
|
/// LF inside a target, header name or value, whitespace in the target, and header names that are not tokens.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a forbidden character, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for a forbidden character, [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`].
|
||||||
/// [`MAX_RTSP_MESSAGE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||||
pub fn encode(&self) -> crate::Result<Vec<u8>> {
|
if self.target.is_empty() || self.target.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("rtsp target"));
|
||||||
|
}
|
||||||
|
let mut out = format!("{} {} {VERSION}\r\n", self.method.as_str(), self.target);
|
||||||
|
for (name, value) in &self.headers {
|
||||||
|
if name.is_empty() || !name.bytes().all(is_token) {
|
||||||
|
return Err(malformed("rtsp header name"));
|
||||||
|
}
|
||||||
|
if value.bytes().any(|b| b == b'\r' || b == b'\n') {
|
||||||
|
return Err(malformed("rtsp header value"));
|
||||||
|
}
|
||||||
|
out.push_str(name);
|
||||||
|
out.push_str(": ");
|
||||||
|
out.push_str(value);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
out.push_str("\r\n");
|
||||||
|
let mut bytes = out.into_bytes();
|
||||||
|
cap("rtsp request", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
|
||||||
|
bytes.extend_from_slice(&self.body);
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first header with this name, compared case-insensitively.
|
||||||
|
#[must_use]
|
||||||
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
|
header(&self.headers, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,76 +124,255 @@ pub struct RtspResponse {
|
|||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
|
||||||
|
headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
impl RtspResponse {
|
impl RtspResponse {
|
||||||
/// The first header with this name, compared case-insensitively.
|
/// The first header with this name, compared case-insensitively.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn header(&self, name: &str) -> Option<&str> {
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
header(&self.headers, name)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Serializes the response (`RTSP/1.0 <status> <reason>`, CRLF line ends, empty line, payload) with exactly the
|
||||||
|
/// given headers. The host side's mirror of [`RtspRequest::encode`].
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for a status outside 100..=999, CR, LF or another control character in the reason, a
|
||||||
|
/// header name that is not a token, or CR or LF in a header value; [`Error::TooLarge`] over
|
||||||
|
/// [`MAX_RTSP_MESSAGE_BYTES`].
|
||||||
|
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||||
|
if !(100..=999).contains(&self.status) || self.reason.bytes().any(|b| b.is_ascii_control()) {
|
||||||
|
return Err(malformed("rtsp status line"));
|
||||||
|
}
|
||||||
|
let mut out = format!("{VERSION} {} {}\r\n", self.status, self.reason);
|
||||||
|
for (name, value) in &self.headers {
|
||||||
|
if name.is_empty() || !name.bytes().all(is_token) {
|
||||||
|
return Err(malformed("rtsp header name"));
|
||||||
|
}
|
||||||
|
if value.bytes().any(|b| b == b'\r' || b == b'\n') {
|
||||||
|
return Err(malformed("rtsp header value"));
|
||||||
|
}
|
||||||
|
out.push_str(name);
|
||||||
|
out.push_str(": ");
|
||||||
|
out.push_str(value);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
out.push_str("\r\n");
|
||||||
|
let mut bytes = out.into_bytes();
|
||||||
|
cap("rtsp response", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
|
||||||
|
bytes.extend_from_slice(&self.body);
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A message split into start line, headers and payload.
|
||||||
|
struct Message {
|
||||||
|
start: String,
|
||||||
|
headers: Vec<(String, String)>,
|
||||||
|
body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One CRLF-terminated line at `pos`: (line without CRLF, position after CRLF). `None` when no LF follows.
|
||||||
|
fn line(data: &[u8], pos: usize) -> Result<Option<(&str, usize)>> {
|
||||||
|
let rest = data.get(pos..).unwrap_or(&[]);
|
||||||
|
let Some(lf) = rest.iter().take(MAX_RTSP_LINE_BYTES + 2).position(|&b| b == b'\n') else {
|
||||||
|
if rest.len() > MAX_RTSP_LINE_BYTES + 1 {
|
||||||
|
return Err(Error::TooLarge { what: "rtsp line", max: MAX_RTSP_LINE_BYTES, actual: rest.len() });
|
||||||
|
}
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let raw = rest.get(..lf).unwrap_or(&[]);
|
||||||
|
let text = raw.strip_suffix(b"\r").ok_or(malformed("rtsp line without CRLF"))?;
|
||||||
|
cap("rtsp line", MAX_RTSP_LINE_BYTES, text.len())?;
|
||||||
|
if text.contains(&b'\r') {
|
||||||
|
return Err(malformed("rtsp: CR inside a line"));
|
||||||
|
}
|
||||||
|
let text = core::str::from_utf8(text).map_err(|_| malformed("rtsp: not UTF-8"))?;
|
||||||
|
Ok(Some((text, pos + lf + 1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses headers from `pos` up to the empty line: (headers, position of the payload).
|
||||||
|
fn headers_from(data: &[u8], mut pos: usize) -> Result<(Vec<(String, String)>, usize)> {
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
loop {
|
||||||
|
let (text, next) = line(data, pos)?.ok_or(Error::Truncated {
|
||||||
|
what: "rtsp headers",
|
||||||
|
needed: data.len().saturating_add(2),
|
||||||
|
actual: data.len(),
|
||||||
|
})?;
|
||||||
|
pos = next;
|
||||||
|
if text.is_empty() {
|
||||||
|
return Ok((headers, pos));
|
||||||
|
}
|
||||||
|
let (name, value) = text.split_once(':').ok_or(malformed("rtsp header without :"))?;
|
||||||
|
if name.is_empty() || !name.bytes().all(is_token) {
|
||||||
|
return Err(malformed("rtsp header name"));
|
||||||
|
}
|
||||||
|
headers.push((name.to_owned(), value.trim_matches([' ', '\t']).to_owned()));
|
||||||
|
cap("rtsp headers", MAX_RTSP_HEADERS, headers.len())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The message's Content-Length, if any: strict digits, all copies equal, within the cap.
|
||||||
|
fn content_length(headers: &[(String, String)], head_len: usize) -> Result<Option<usize>> {
|
||||||
|
let mut found: Option<u64> = None;
|
||||||
|
for (_, v) in headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("content-length")) {
|
||||||
|
let n = parse_dec("rtsp Content-Length", v)?;
|
||||||
|
if found.is_some_and(|f| f != n) {
|
||||||
|
return Err(malformed("rtsp: two different Content-Length values"));
|
||||||
|
}
|
||||||
|
found = Some(n);
|
||||||
|
}
|
||||||
|
let Some(n) = found else { return Ok(None) };
|
||||||
|
let total = usize::try_from(n).unwrap_or(usize::MAX).saturating_add(head_len);
|
||||||
|
cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, total)?;
|
||||||
|
Ok(Some(total - head_len))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn split_message(msg: &[u8]) -> Result<Message> {
|
||||||
|
cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, msg.len())?;
|
||||||
|
let (start, pos) = line(msg, 0)?.ok_or(malformed("rtsp: no start line"))?;
|
||||||
|
if start.is_empty() {
|
||||||
|
return Err(malformed("rtsp: empty start line"));
|
||||||
|
}
|
||||||
|
let start = start.to_owned();
|
||||||
|
let (headers, body_at) = headers_from(msg, pos)?;
|
||||||
|
let rest = msg.get(body_at..).unwrap_or(&[]);
|
||||||
|
let body = match content_length(&headers, body_at)? {
|
||||||
|
None => rest.to_vec(),
|
||||||
|
Some(n) if rest.len() < n => {
|
||||||
|
return Err(Error::Truncated { what: "rtsp payload", needed: body_at + n, actual: msg.len() });
|
||||||
|
}
|
||||||
|
Some(n) if rest.len() > n => return Err(malformed("rtsp: bytes after the payload")),
|
||||||
|
Some(_) => rest.to_vec(),
|
||||||
|
};
|
||||||
|
Ok(Message { start, headers, body })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses one complete response (as cut by [`RtspFramer`]).
|
/// Parses one complete response (as cut by [`RtspFramer`]).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`],
|
/// [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`],
|
||||||
/// [`crate::Error::Malformed`] for a bad start line, header line or `Content-Length`. Phase A: always
|
/// [`Error::Malformed`] for a bad start line, header line or `Content-Length`, [`Error::Truncated`] when the headers
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// or the payload end early.
|
||||||
pub fn parse_response(message: &[u8]) -> crate::Result<RtspResponse> {
|
pub fn parse_response(message: &[u8]) -> Result<RtspResponse> {
|
||||||
let _ = message;
|
let m = split_message(message)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let rest = m.start.strip_prefix("RTSP/1.0 ").ok_or(malformed("rtsp: not an RTSP/1.0 response"))?;
|
||||||
|
let (code, reason) = rest.split_once(' ').unwrap_or((rest, ""));
|
||||||
|
if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_digit()) {
|
||||||
|
return Err(malformed("rtsp status code"));
|
||||||
|
}
|
||||||
|
let status = crate::util::parse_u16("rtsp status code", code)?;
|
||||||
|
Ok(RtspResponse { status, reason: reason.to_owned(), headers: m.headers, body: m.body })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses one complete request. Not used by the client; here for the fuzz harness and the Lumen host (Day 3).
|
/// Parses one complete request. Not used by the client; here for the fuzz harness and the Lumen host (Day 3).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`parse_response`], plus [`crate::Error::UnexpectedValue`] for an unknown method.
|
/// As [`parse_response`], plus [`Error::UnexpectedValue`] for an unknown method.
|
||||||
pub fn parse_request(message: &[u8]) -> crate::Result<RtspRequest> {
|
pub fn parse_request(message: &[u8]) -> Result<RtspRequest> {
|
||||||
let _ = message;
|
let m = split_message(message)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let mut parts = m.start.splitn(3, ' ');
|
||||||
|
let (Some(method), Some(target), Some(version)) = (parts.next(), parts.next(), parts.next()) else {
|
||||||
|
return Err(malformed("rtsp request line"));
|
||||||
|
};
|
||||||
|
if method.is_empty() || target.is_empty() || version != VERSION {
|
||||||
|
return Err(malformed("rtsp request line"));
|
||||||
|
}
|
||||||
|
let method = Method::from_token(method).ok_or(Error::UnexpectedValue { what: "rtsp method", value: 0 })?;
|
||||||
|
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cuts the TCP byte stream from the host into whole messages.
|
/// Cuts a TCP byte stream into whole messages.
|
||||||
///
|
///
|
||||||
/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when
|
/// A message ends after its headers plus `Content-Length` payload bytes. Without `Content-Length`, a framer made
|
||||||
/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than
|
/// with [`RtspFramer::new`] (the client reading the host's answers) ends the message when the host closes the
|
||||||
/// [`MAX_RTSP_MESSAGE_BYTES`].
|
/// connection ([`RtspFramer::finish`]) (UNKNOWN U5); one made with [`RtspFramer::for_requests`] (the host reading
|
||||||
|
/// a client's requests) takes a missing `Content-Length` as zero, as RFC 2326 section 4.4 says, so the message
|
||||||
|
/// ends at the empty line (`docs/PROTOCOL.md` 2.5). Never buffers more than [`MAX_RTSP_MESSAGE_BYTES`].
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
pub struct RtspFramer {
|
pub struct RtspFramer {
|
||||||
buffer: Vec<u8>,
|
buffer: Vec<u8>,
|
||||||
|
/// A missing `Content-Length` means "no payload" (requests) instead of "until close" (answers).
|
||||||
|
missing_length_is_zero: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RtspFramer {
|
impl RtspFramer {
|
||||||
/// An empty framer.
|
/// An empty framer for the host's answers (client side).
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new() -> Self {
|
pub const fn new() -> Self {
|
||||||
Self { buffer: Vec::new() }
|
Self { buffer: Vec::new(), missing_length_is_zero: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An empty framer for a client's requests (host side): a request without `Content-Length` has no payload.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn for_requests() -> Self {
|
||||||
|
Self { buffer: Vec::new(), missing_length_is_zero: true }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Appends received bytes.
|
/// Appends received bytes.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] when the unfinished message would exceed [`MAX_RTSP_MESSAGE_BYTES`]. Phase A:
|
/// [`Error::TooLarge`] when the buffered bytes would exceed [`MAX_RTSP_MESSAGE_BYTES`] (nothing is appended).
|
||||||
/// always [`crate::Error::Unimplemented`].
|
pub fn push(&mut self, bytes: &[u8]) -> Result<()> {
|
||||||
pub fn push(&mut self, bytes: &[u8]) -> crate::Result<()> {
|
cap("rtsp stream", MAX_RTSP_MESSAGE_BYTES, self.buffer.len().saturating_add(bytes.len()))?;
|
||||||
let _ = bytes;
|
self.buffer.extend_from_slice(bytes);
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the buffered header section ends and the message's Content-Length, if the headers are complete.
|
||||||
|
fn head(&self) -> Result<Option<(usize, Option<usize>)>> {
|
||||||
|
let Some(end) = self.buffer.windows(4).position(|w| w == b"\r\n\r\n") else { return Ok(None) };
|
||||||
|
let head_len = end + 4;
|
||||||
|
let head = self.buffer.get(..head_len).unwrap_or(&[]);
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
for raw in head.split(|&b| b == b'\n').skip(1) {
|
||||||
|
let text = core::str::from_utf8(raw.strip_suffix(b"\r").unwrap_or(raw)).unwrap_or("");
|
||||||
|
if let Some((n, v)) = text.split_once(':')
|
||||||
|
&& n.eq_ignore_ascii_case("content-length")
|
||||||
|
{
|
||||||
|
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let length = content_length(&headers, head_len)?;
|
||||||
|
Ok(Some((head_len, if self.missing_length_is_zero { Some(length.unwrap_or(0)) } else { length })))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Takes the next complete message, if one is buffered.
|
/// Takes the next complete message, if one is buffered.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a bad `Content-Length`. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] for a bad `Content-Length`, [`Error::TooLarge`] when it announces a message over the cap.
|
||||||
pub fn next_message(&mut self) -> crate::Result<Option<Vec<u8>>> {
|
pub fn next_message(&mut self) -> Result<Option<Vec<u8>>> {
|
||||||
Err(crate::Error::Unimplemented)
|
match self.head()? {
|
||||||
|
Some((head, Some(len))) if self.buffer.len() >= head + len => {
|
||||||
|
let rest = self.buffer.split_off(head + len);
|
||||||
|
Ok(Some(core::mem::replace(&mut self.buffer, rest)))
|
||||||
|
}
|
||||||
|
_ => Ok(None),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The host closed the connection: returns what is buffered as the last message, if anything.
|
/// The host closed the connection: returns what is buffered as the last message, if anything.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Truncated`] when a `Content-Length` promised more. Phase A: always
|
/// [`Error::Truncated`] when the headers never ended or a `Content-Length` promised more.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn finish(&mut self) -> Result<Option<Vec<u8>>> {
|
||||||
pub fn finish(&mut self) -> crate::Result<Option<Vec<u8>>> {
|
if self.buffer.is_empty() {
|
||||||
Err(crate::Error::Unimplemented)
|
return Ok(None);
|
||||||
|
}
|
||||||
|
match self.head()? {
|
||||||
|
None => Err(Error::Truncated {
|
||||||
|
what: "rtsp headers at close",
|
||||||
|
needed: self.buffer.len().saturating_add(4),
|
||||||
|
actual: self.buffer.len(),
|
||||||
|
}),
|
||||||
|
Some((head, Some(len))) if self.buffer.len() < head + len => {
|
||||||
|
Err(Error::Truncated { what: "rtsp payload at close", needed: head + len, actual: self.buffer.len() })
|
||||||
|
}
|
||||||
|
Some(_) => Ok(Some(core::mem::take(&mut self.buffer))),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bytes buffered but not yet returned.
|
/// Bytes buffered but not yet returned.
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4).
|
//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4).
|
||||||
|
|
||||||
use super::client::StreamConfig;
|
use super::client::{StreamConfig, VideoCodec};
|
||||||
|
use crate::util::{cap, malformed, parse_u8, parse_u32};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Maximum size of an SDP payload, in bytes.
|
/// Maximum size of an SDP payload, in bytes.
|
||||||
pub const MAX_SDP_BYTES: usize = 32 * 1024;
|
pub const MAX_SDP_BYTES: usize = 32 * 1024;
|
||||||
@@ -29,14 +31,39 @@ impl Sdp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses an SDP payload. Lines end in LF or CRLF.
|
/// Parses an SDP payload. Lines end in LF or CRLF; empty lines are skipped.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`crate::Error::Malformed`] for a line
|
/// [`Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`Error::Malformed`] for a payload that is not
|
||||||
/// that is not UTF-8 or has no `=`. Phase A: always [`crate::Error::Unimplemented`].
|
/// UTF-8 or a line without `=` or with an empty type.
|
||||||
pub fn parse_sdp(payload: &[u8]) -> crate::Result<Sdp> {
|
pub fn parse_sdp(payload: &[u8]) -> Result<Sdp> {
|
||||||
let _ = payload;
|
cap("sdp", MAX_SDP_BYTES, payload.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let text = core::str::from_utf8(payload).map_err(|_| malformed("sdp: not UTF-8"))?;
|
||||||
|
let mut sdp = Sdp::default();
|
||||||
|
let mut lines = 0usize;
|
||||||
|
for raw in text.split('\n') {
|
||||||
|
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lines += 1;
|
||||||
|
cap("sdp lines", MAX_SDP_LINES, lines)?;
|
||||||
|
let (kind, value) = line.split_once('=').ok_or(malformed("sdp line without ="))?;
|
||||||
|
if kind.is_empty() {
|
||||||
|
return Err(malformed("sdp line with an empty type"));
|
||||||
|
}
|
||||||
|
if kind == "a" {
|
||||||
|
let (name, value) = value.split_once(':').unwrap_or((value, ""));
|
||||||
|
sdp.attributes.push((name.to_owned(), value.to_owned()));
|
||||||
|
} else {
|
||||||
|
let mut chars = kind.chars();
|
||||||
|
match (chars.next(), chars.next()) {
|
||||||
|
(Some(c), None) => sdp.other.push((c, value.to_owned())),
|
||||||
|
_ => sdp.other.push(('\0', line.to_owned())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(sdp)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encryption flag bits of `x-ss-general.encryptionSupported` / `encryptionEnabled`.
|
/// Encryption flag bits of `x-ss-general.encryptionSupported` / `encryptionEnabled`.
|
||||||
@@ -50,6 +77,12 @@ impl EncryptionFlags {
|
|||||||
pub const VIDEO: u8 = 0x02;
|
pub const VIDEO: u8 = 0x02;
|
||||||
/// Audio AES-CBC.
|
/// Audio AES-CBC.
|
||||||
pub const AUDIO: u8 = 0x04;
|
pub const AUDIO: u8 = 0x04;
|
||||||
|
|
||||||
|
/// Whether every bit of `flags` is set.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn contains(self, flags: u8) -> bool {
|
||||||
|
self.0 & flags == flags
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feature flag bits of `x-ss-general.featureFlags`.
|
/// Feature flag bits of `x-ss-general.featureFlags`.
|
||||||
@@ -76,16 +109,41 @@ pub struct OpusConfig {
|
|||||||
pub mapping: Vec<u8>,
|
pub mapping: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl OpusConfig {
|
||||||
|
/// Plain stereo: 2 channels, 1 coupled stream, mapping 0 1 (Wolf's `21101`).
|
||||||
|
#[must_use]
|
||||||
|
pub fn stereo() -> Self {
|
||||||
|
Self { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 1] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Parses one `surround-params` value (single digits: channels, streams, coupled, then one mapping digit per
|
/// Parses one `surround-params` value (single digits: channels, streams, coupled, then one mapping digit per
|
||||||
/// channel), e.g. `21101`.
|
/// channel), e.g. `21101`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules
|
/// [`Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules
|
||||||
/// (`coupled ≤ streams`, `streams + coupled ≤ 255`, mapping entries `< streams + coupled`). Phase A: always
|
/// (`1 ≤ channels ≤ 8`, `streams ≥ 1`, `coupled ≤ streams`, mapping entries `< streams + coupled`).
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn parse_surround_params(value: &str) -> Result<OpusConfig> {
|
||||||
pub fn parse_surround_params(value: &str) -> crate::Result<OpusConfig> {
|
let digits: Vec<u8> = value
|
||||||
let _ = value;
|
.bytes()
|
||||||
Err(crate::Error::Unimplemented)
|
.map(|b| if b.is_ascii_digit() { Some(b - b'0') } else { None })
|
||||||
|
.collect::<Option<Vec<u8>>>()
|
||||||
|
.ok_or(malformed("surround-params"))?;
|
||||||
|
let (&channels, &streams, &coupled) = match digits.as_slice() {
|
||||||
|
[c, s, k, ..] => (c, s, k),
|
||||||
|
_ => return Err(malformed("surround-params")),
|
||||||
|
};
|
||||||
|
let mapping = digits.get(3..).unwrap_or(&[]);
|
||||||
|
if channels == 0
|
||||||
|
|| usize::from(channels) > MAX_AUDIO_CHANNELS
|
||||||
|
|| streams == 0
|
||||||
|
|| coupled > streams
|
||||||
|
|| mapping.len() != usize::from(channels)
|
||||||
|
|| mapping.iter().any(|&m| m >= streams + coupled)
|
||||||
|
{
|
||||||
|
return Err(malformed("surround-params"));
|
||||||
|
}
|
||||||
|
Ok(OpusConfig { channels, streams, coupled_streams: coupled, mapping: mapping.to_vec() })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the host offers, read from the DESCRIBE payload.
|
/// What the host offers, read from the DESCRIBE payload.
|
||||||
@@ -107,20 +165,99 @@ impl HostCapabilities {
|
|||||||
/// Reads the capabilities from a DESCRIBE payload.
|
/// Reads the capabilities from a DESCRIBE payload.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a present attribute with a bad value, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for a present attribute with a bad value, [`Error::TooLarge`] over
|
||||||
/// [`MAX_OPUS_CONFIGS`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`MAX_OPUS_CONFIGS`].
|
||||||
pub fn from_sdp(sdp: &Sdp) -> crate::Result<Self> {
|
pub fn from_sdp(sdp: &Sdp) -> Result<Self> {
|
||||||
let _ = sdp;
|
let mut caps = Self::default();
|
||||||
Err(crate::Error::Unimplemented)
|
if let Some(v) = sdp.attribute("x-ss-general.encryptionSupported") {
|
||||||
|
caps.encryption_supported = EncryptionFlags(parse_u8("sdp encryptionSupported", v)?);
|
||||||
}
|
}
|
||||||
|
if let Some(v) = sdp.attribute("x-ss-general.featureFlags") {
|
||||||
|
caps.feature_flags = FeatureFlags(parse_u32("sdp featureFlags", v)?);
|
||||||
|
}
|
||||||
|
caps.reference_frame_invalidation = sdp.attribute("x-nv-video[0].refPicInvalidation") == Some("1");
|
||||||
|
caps.av1 = sdp
|
||||||
|
.attributes
|
||||||
|
.iter()
|
||||||
|
.any(|(n, v)| n == "rtpmap" && v.split_whitespace().nth(1).is_some_and(|c| c.starts_with("AV1/")));
|
||||||
|
for (_, v) in sdp.attributes.iter().filter(|(n, _)| n == "fmtp") {
|
||||||
|
let Some(params) = v.strip_prefix("97 ") else { continue };
|
||||||
|
for p in params.split(';').map(str::trim) {
|
||||||
|
if let Some(digits) = p.strip_prefix("surround-params=") {
|
||||||
|
caps.opus_configs.push(parse_surround_params(digits)?);
|
||||||
|
cap("sdp opus configurations", MAX_OPUS_CONFIGS, caps.opus_configs.len())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(caps)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first configuration with `channels` channels, or plain stereo when the host lists none for it.
|
||||||
|
#[must_use]
|
||||||
|
pub fn opus_for(&self, channels: u8) -> OpusConfig {
|
||||||
|
self.opus_configs.iter().find(|c| c.channels == channels).cloned().unwrap_or_else(OpusConfig::stereo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `x-nv-vqos[0].bitStreamFormat` values: 0 H.264, 1 HEVC, 2 AV1 as a host reads them (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
const fn bitstream_format(codec: VideoCodec) -> u8 {
|
||||||
|
match codec {
|
||||||
|
VideoCodec::H264 => 0,
|
||||||
|
VideoCodec::Hevc => 1,
|
||||||
|
VideoCodec::Av1 => 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The encryption flags an ANNOUNCE turns on: what both sides support. Control V2 is required.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Unsupported`] when the host or the client config lacks control V2 encryption.
|
||||||
|
pub fn negotiated_encryption(config: &StreamConfig, host: &HostCapabilities) -> Result<EncryptionFlags> {
|
||||||
|
let flags = EncryptionFlags(config.encryption.0 & host.encryption_supported.0);
|
||||||
|
if !flags.contains(EncryptionFlags::CONTROL_V2) {
|
||||||
|
return Err(Error::Unsupported { what: "control stream encryption (V2)" });
|
||||||
|
}
|
||||||
|
Ok(flags)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the ANNOUNCE payload for `config`, turning on the encryption flags both sides support.
|
/// Builds the ANNOUNCE payload for `config`, turning on the encryption flags both sides support.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Unsupported`] when the host lacks control V2 encryption or the requested codec. Phase A: always
|
/// [`Error::Unsupported`] when the host lacks control V2 encryption or the requested codec.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> Result<Vec<u8>> {
|
||||||
pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> crate::Result<Vec<u8>> {
|
let enabled = negotiated_encryption(config, host)?;
|
||||||
let _ = (config, host);
|
if config.codec == VideoCodec::Av1 && !host.av1 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::Unsupported { what: "AV1 video" });
|
||||||
|
}
|
||||||
|
let channels = config.audio.channels();
|
||||||
|
let attrs: [(&str, String); 19] = [
|
||||||
|
("x-nv-video[0].clientViewportWd", config.width.to_string()),
|
||||||
|
("x-nv-video[0].clientViewportHt", config.height.to_string()),
|
||||||
|
("x-nv-video[0].maxFPS", config.fps.to_string()),
|
||||||
|
("x-nv-video[0].packetSize", config.packet_size.to_string()),
|
||||||
|
("x-nv-video[0].maxNumReferenceFrames", if config.reference_frame_invalidation { "0" } else { "1" }.into()),
|
||||||
|
("x-nv-video[0].refPicInvalidation", u8::from(config.reference_frame_invalidation).to_string()),
|
||||||
|
("x-nv-video[0].dynamicRangeMode", u8::from(config.hdr).to_string()),
|
||||||
|
("x-nv-video[0].encoderCscMode", if config.hdr { "5" } else { "0" }.into()),
|
||||||
|
("x-nv-vqos[0].bitStreamFormat", bitstream_format(config.codec).to_string()),
|
||||||
|
("x-nv-vqos[0].fec.minRequiredFecPackets", config.min_fec_packets.to_string()),
|
||||||
|
("x-nv-vqos[0].qosTrafficType", "5".into()),
|
||||||
|
("x-ml-video.configuredBitrateKbps", config.bitrate_kbps.to_string()),
|
||||||
|
("x-nv-aqos.packetDuration", config.audio_packet_duration_ms.to_string()),
|
||||||
|
("x-nv-aqos.qosTrafficType", "4".into()),
|
||||||
|
("x-nv-audio.surround.enable", u8::from(channels > 2).to_string()),
|
||||||
|
("x-nv-audio.surround.numChannels", channels.to_string()),
|
||||||
|
("x-nv-audio.surround.channelMask", config.audio.channel_mask().to_string()),
|
||||||
|
("x-ss-video[0].chromaSamplingType", "0".into()),
|
||||||
|
("x-ss-general.encryptionEnabled", enabled.0.to_string()),
|
||||||
|
];
|
||||||
|
let mut out = String::from("v=0\r\n");
|
||||||
|
for (name, value) in &attrs {
|
||||||
|
out.push_str("a=");
|
||||||
|
out.push_str(name);
|
||||||
|
out.push(':');
|
||||||
|
out.push_str(value);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
Ok(out.into_bytes())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,338 @@
|
|||||||
|
//! The ANNOUNCE payload on the host side (`docs/PROTOCOL.md` 2.4, 2.5): a strict parser of the client's SDP into a
|
||||||
|
//! typed [`StreamConfig`], and the matching writer.
|
||||||
|
//!
|
||||||
|
//! The payload is hostile input. The parser caps the payload size, the number of lines, the length of each line and
|
||||||
|
//! the number of `a=` attributes before it looks at any of them, allocates nothing while it reads, refuses a known
|
||||||
|
//! attribute that appears twice, range-checks every number, and counts (then ignores) attributes it does not know.
|
||||||
|
|
||||||
|
use crate::rtsp::client::VideoCodec;
|
||||||
|
use crate::rtsp::sdp::{EncryptionFlags, MAX_AUDIO_CHANNELS};
|
||||||
|
use crate::util::{cap, malformed, parse_dec};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// Maximum size of an ANNOUNCE payload, in bytes (the SDP cap of `docs/PROTOCOL.md` 2.3).
|
||||||
|
pub const MAX_ANNOUNCE_BYTES: usize = crate::rtsp::sdp::MAX_SDP_BYTES;
|
||||||
|
/// Maximum number of non-empty lines in an ANNOUNCE payload.
|
||||||
|
pub const MAX_ANNOUNCE_LINES: usize = 1024;
|
||||||
|
/// Maximum length of one line, in bytes, without its line end.
|
||||||
|
pub const MAX_ANNOUNCE_LINE_BYTES: usize = 1024;
|
||||||
|
/// Maximum number of `a=` attributes, known or not.
|
||||||
|
pub const MAX_ANNOUNCE_ATTRIBUTES: usize = 512;
|
||||||
|
|
||||||
|
/// Largest width or height accepted, in pixels (our cap, not the protocol's).
|
||||||
|
pub const MAX_DIMENSION: u32 = 16_384;
|
||||||
|
/// Largest frame rate accepted (our cap, not the protocol's).
|
||||||
|
pub const MAX_FPS: u32 = 1000;
|
||||||
|
/// Smallest video `packetSize` a host accepts (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
pub const MIN_PACKET_SIZE: u16 = 200;
|
||||||
|
/// Largest video `packetSize`: one stream packet in one IPv6 UDP datagram (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
pub const MAX_PACKET_SIZE: u16 = 65_471;
|
||||||
|
/// Largest bitrate in kbit/s: the value times 1000 must fit in a `u32` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
pub const MAX_BITRATE_KBPS: u32 = 4_294_967;
|
||||||
|
/// Longest audio packet in milliseconds: the longest Opus packet (RFC 6716 section 3.2.5).
|
||||||
|
pub const MAX_AUDIO_PACKET_DURATION_MS: u8 = 120;
|
||||||
|
|
||||||
|
/// Chroma subsampling, `x-ss-video[0].chromaSamplingType` (`docs/PROTOCOL.md` 2.5 \[M\]).
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
|
pub enum ChromaSampling {
|
||||||
|
/// 4:2:0, value 0 (the default).
|
||||||
|
#[default]
|
||||||
|
Yuv420,
|
||||||
|
/// 4:4:4, value 1.
|
||||||
|
Yuv444,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The audio layout the client asks for (`x-nv-audio.surround.*`, `docs/PROTOCOL.md` 2.5).
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct SurroundSettings {
|
||||||
|
/// `x-nv-audio.surround.enable`: 0 or 1, default 0. When off, a Moonshine-like host takes the layout from the
|
||||||
|
/// launch call's `surroundAudioInfo` instead of `channels` and `channel_mask` \[M\].
|
||||||
|
pub enabled: bool,
|
||||||
|
/// `x-nv-audio.surround.numChannels`: 1..=8, default 2 \[M\].
|
||||||
|
pub channels: u8,
|
||||||
|
/// `x-nv-audio.surround.channelMask`: the speaker mask, kept as sent; default `0x3` \[M\].
|
||||||
|
pub channel_mask: u32,
|
||||||
|
/// `x-nv-audio.surround.AudioQuality`: 0 or 1, default 1 (high quality) \[M\].
|
||||||
|
pub high_quality: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for SurroundSettings {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self { enabled: false, channels: 2, channel_mask: 0x3, high_quality: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a client asked for in ANNOUNCE, typed and range-checked (`docs/PROTOCOL.md` 2.4, 2.5).
|
||||||
|
///
|
||||||
|
/// Values whose meaning is not settled are kept as the raw number the client sent.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct StreamConfig {
|
||||||
|
/// `x-nv-video[0].clientViewportWd`, required, 1..=[`MAX_DIMENSION`].
|
||||||
|
pub width: u32,
|
||||||
|
/// `x-nv-video[0].clientViewportHt`, required, 1..=[`MAX_DIMENSION`].
|
||||||
|
pub height: u32,
|
||||||
|
/// `x-nv-video[0].maxFPS`, required, 1..=[`MAX_FPS`].
|
||||||
|
pub max_fps: u32,
|
||||||
|
/// `x-nv-video[0].packetSize`, required, [`MIN_PACKET_SIZE`]..=[`MAX_PACKET_SIZE`].
|
||||||
|
pub packet_size: u16,
|
||||||
|
/// `x-ml-video.configuredBitrateKbps`, required, 1..=[`MAX_BITRATE_KBPS`].
|
||||||
|
pub bitrate_kbps: u32,
|
||||||
|
/// `x-nv-vqos[0].bitStreamFormat`, required: 0 H.264, 1 HEVC, 2 AV1 \[M\]; anything else is refused.
|
||||||
|
pub codec: VideoCodec,
|
||||||
|
/// `x-nv-vqos[0].fec.minRequiredFecPackets`, required, 0..=255.
|
||||||
|
pub min_fec_packets: u8,
|
||||||
|
/// `x-nv-vqos[0].qosTrafficType`, required, kept as sent (a Moonshine-like host turns QoS off for 0 \[M\]).
|
||||||
|
pub video_qos_traffic_type: u32,
|
||||||
|
/// `x-nv-aqos.packetDuration`, required, 1..=[`MAX_AUDIO_PACKET_DURATION_MS`] milliseconds.
|
||||||
|
pub audio_packet_duration_ms: u8,
|
||||||
|
/// `x-nv-aqos.qosTrafficType`, required, kept as sent.
|
||||||
|
pub audio_qos_traffic_type: u32,
|
||||||
|
/// `x-nv-video[0].maxNumReferenceFrames`, default 1 \[M\]. Kept raw: what 0 means has GPL provenance only
|
||||||
|
/// (\[M*\], `docs/PROTOCOL.md` 2.4), so it is not interpreted here.
|
||||||
|
pub max_reference_frames: u32,
|
||||||
|
/// `x-nv-video[0].refPicInvalidation`, 0 or 1. Default 0 (the client cannot invalidate, so the host sends an
|
||||||
|
/// IDR frame on loss, which always works): UNKNOWN U6, settled by measurement.
|
||||||
|
pub reference_frame_invalidation: bool,
|
||||||
|
/// `x-nv-video[0].dynamicRangeMode`, default 0, kept raw. Moonshine reads 0 as SDR \[M\]; no other value has a
|
||||||
|
/// settled meaning: UNKNOWN U6, settled by measurement.
|
||||||
|
pub dynamic_range_mode: u32,
|
||||||
|
/// `x-nv-video[0].encoderCscMode`, default 0, kept raw. Its bit layout has GPL provenance only (\[M*\]):
|
||||||
|
/// UNKNOWN U6, settled by measurement (`docs/LUMEN-HOST-PLAN.md` 1.3).
|
||||||
|
pub encoder_csc_mode: u32,
|
||||||
|
/// `x-ss-video[0].chromaSamplingType`, 0 or 1, default 0 (4:2:0) \[M\].
|
||||||
|
pub chroma: ChromaSampling,
|
||||||
|
/// `x-ss-general.encryptionEnabled`, 0..=255, default 0 \[M\]; bits as in `docs/PROTOCOL.md` 2.3. Kept as sent;
|
||||||
|
/// [`super::RtspServer`] refuses bits the host did not offer.
|
||||||
|
pub encryption: EncryptionFlags,
|
||||||
|
/// `x-nv-audio.surround.*`.
|
||||||
|
pub surround: SurroundSettings,
|
||||||
|
/// `a=` attributes the parser does not know: counted, otherwise ignored (UNKNOWN U6). Not written by
|
||||||
|
/// [`write_announce`].
|
||||||
|
pub unknown_attributes: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses an ANNOUNCE payload (SDP lines, LF or CRLF, empty lines skipped) into a [`StreamConfig`].
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] over [`MAX_ANNOUNCE_BYTES`], [`MAX_ANNOUNCE_LINES`], [`MAX_ANNOUNCE_LINE_BYTES`] or
|
||||||
|
/// [`MAX_ANNOUNCE_ATTRIBUTES`]; [`Error::Malformed`] for a payload that is not UTF-8, a line without `=`, an empty
|
||||||
|
/// line type, a control character, a known attribute given twice, a required attribute missing or a number that is
|
||||||
|
/// not plain decimal; [`Error::UnexpectedValue`] for a number outside its range.
|
||||||
|
pub fn parse_announce(payload: &[u8]) -> Result<StreamConfig> {
|
||||||
|
cap("announce", MAX_ANNOUNCE_BYTES, payload.len())?;
|
||||||
|
let text = core::str::from_utf8(payload).map_err(|_| malformed("announce: not UTF-8"))?;
|
||||||
|
let mut values: [Option<&str>; ATTRIBUTES.len()] = [None; ATTRIBUTES.len()];
|
||||||
|
let mut lines = 0usize;
|
||||||
|
let mut attributes = 0usize;
|
||||||
|
let mut unknown = 0u32;
|
||||||
|
for raw in text.split('\n') {
|
||||||
|
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||||
|
cap("announce line", MAX_ANNOUNCE_LINE_BYTES, line.len())?;
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lines += 1;
|
||||||
|
cap("announce lines", MAX_ANNOUNCE_LINES, lines)?;
|
||||||
|
if line.bytes().any(|b| b.is_ascii_control() && b != b'\t') {
|
||||||
|
return Err(malformed("announce: control character in a line"));
|
||||||
|
}
|
||||||
|
let (kind, rest) = line.split_once('=').ok_or(malformed("announce: line without ="))?;
|
||||||
|
if kind.is_empty() {
|
||||||
|
return Err(malformed("announce: line with an empty type"));
|
||||||
|
}
|
||||||
|
// Only `a=` lines carry settings; `v=`, `o=`, `s=`, `t=`, `m=` and bare lines are not read.
|
||||||
|
if kind != "a" {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
attributes += 1;
|
||||||
|
cap("announce attributes", MAX_ANNOUNCE_ATTRIBUTES, attributes)?;
|
||||||
|
let (name, value) = rest.split_once(':').unwrap_or((rest, ""));
|
||||||
|
match ATTRIBUTES.iter().position(|a| a.name == name).and_then(|i| values.get_mut(i)) {
|
||||||
|
Some(Some(_)) => return Err(malformed("announce: an attribute given twice")),
|
||||||
|
Some(slot) => *slot = Some(value.trim_matches([' ', '\t'])),
|
||||||
|
None => unknown = unknown.saturating_add(1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let a = Values(&values);
|
||||||
|
let codec = match a.required(BIT_STREAM_FORMAT, 0, 2)? {
|
||||||
|
0 => VideoCodec::H264,
|
||||||
|
1 => VideoCodec::Hevc,
|
||||||
|
_ => VideoCodec::Av1,
|
||||||
|
};
|
||||||
|
Ok(StreamConfig {
|
||||||
|
width: narrow(a.required(VIEWPORT_WD, 1, u64::from(MAX_DIMENSION))?)?,
|
||||||
|
height: narrow(a.required(VIEWPORT_HT, 1, u64::from(MAX_DIMENSION))?)?,
|
||||||
|
max_fps: narrow(a.required(MAX_FPS_ATTR, 1, u64::from(MAX_FPS))?)?,
|
||||||
|
packet_size: narrow(a.required(PACKET_SIZE, u64::from(MIN_PACKET_SIZE), u64::from(MAX_PACKET_SIZE))?)?,
|
||||||
|
bitrate_kbps: narrow(a.required(BITRATE, 1, u64::from(MAX_BITRATE_KBPS))?)?,
|
||||||
|
codec,
|
||||||
|
min_fec_packets: narrow(a.required(MIN_FEC_PACKETS, 0, u64::from(u8::MAX))?)?,
|
||||||
|
video_qos_traffic_type: narrow(a.required(VIDEO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||||
|
audio_packet_duration_ms: narrow(a.required(PACKET_DURATION, 1, u64::from(MAX_AUDIO_PACKET_DURATION_MS))?)?,
|
||||||
|
audio_qos_traffic_type: narrow(a.required(AUDIO_QOS, 0, u64::from(u32::MAX))?)?,
|
||||||
|
max_reference_frames: narrow(a.optional(MAX_REFERENCE_FRAMES, 1, 0, u64::from(u32::MAX))?)?,
|
||||||
|
reference_frame_invalidation: a.optional(REF_PIC_INVALIDATION, 0, 0, 1)? == 1,
|
||||||
|
dynamic_range_mode: narrow(a.optional(DYNAMIC_RANGE_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||||
|
encoder_csc_mode: narrow(a.optional(ENCODER_CSC_MODE, 0, 0, u64::from(u32::MAX))?)?,
|
||||||
|
chroma: if a.optional(CHROMA_SAMPLING, 0, 0, 1)? == 1 {
|
||||||
|
ChromaSampling::Yuv444
|
||||||
|
} else {
|
||||||
|
ChromaSampling::Yuv420
|
||||||
|
},
|
||||||
|
encryption: EncryptionFlags(narrow(a.optional(ENCRYPTION_ENABLED, 0, 0, u64::from(u8::MAX))?)?),
|
||||||
|
surround: SurroundSettings {
|
||||||
|
enabled: a.optional(SURROUND_ENABLE, 0, 0, 1)? == 1,
|
||||||
|
channels: narrow(a.optional(SURROUND_CHANNELS, 2, 1, MAX_AUDIO_CHANNELS as u64)?)?,
|
||||||
|
channel_mask: narrow(a.optional(SURROUND_MASK, 0x3, 0, u64::from(u32::MAX))?)?,
|
||||||
|
high_quality: a.optional(AUDIO_QUALITY, 1, 0, 1)? == 1,
|
||||||
|
},
|
||||||
|
unknown_attributes: unknown,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes `config` as an ANNOUNCE payload (`v=0`, then every known attribute, CRLF line ends) that
|
||||||
|
/// [`parse_announce`] reads back as the same config (with `unknown_attributes` 0).
|
||||||
|
#[must_use]
|
||||||
|
pub fn write_announce(config: &StreamConfig) -> Vec<u8> {
|
||||||
|
let codec: u8 = match config.codec {
|
||||||
|
VideoCodec::H264 => 0,
|
||||||
|
VideoCodec::Hevc => 1,
|
||||||
|
VideoCodec::Av1 => 2,
|
||||||
|
};
|
||||||
|
let chroma: u8 = match config.chroma {
|
||||||
|
ChromaSampling::Yuv420 => 0,
|
||||||
|
ChromaSampling::Yuv444 => 1,
|
||||||
|
};
|
||||||
|
let s = &config.surround;
|
||||||
|
let values: [(usize, u64); ATTRIBUTES.len()] = [
|
||||||
|
(VIEWPORT_WD, u64::from(config.width)),
|
||||||
|
(VIEWPORT_HT, u64::from(config.height)),
|
||||||
|
(MAX_FPS_ATTR, u64::from(config.max_fps)),
|
||||||
|
(PACKET_SIZE, u64::from(config.packet_size)),
|
||||||
|
(BITRATE, u64::from(config.bitrate_kbps)),
|
||||||
|
(BIT_STREAM_FORMAT, u64::from(codec)),
|
||||||
|
(MIN_FEC_PACKETS, u64::from(config.min_fec_packets)),
|
||||||
|
(VIDEO_QOS, u64::from(config.video_qos_traffic_type)),
|
||||||
|
(PACKET_DURATION, u64::from(config.audio_packet_duration_ms)),
|
||||||
|
(AUDIO_QOS, u64::from(config.audio_qos_traffic_type)),
|
||||||
|
(MAX_REFERENCE_FRAMES, u64::from(config.max_reference_frames)),
|
||||||
|
(REF_PIC_INVALIDATION, u64::from(config.reference_frame_invalidation)),
|
||||||
|
(DYNAMIC_RANGE_MODE, u64::from(config.dynamic_range_mode)),
|
||||||
|
(ENCODER_CSC_MODE, u64::from(config.encoder_csc_mode)),
|
||||||
|
(CHROMA_SAMPLING, u64::from(chroma)),
|
||||||
|
(ENCRYPTION_ENABLED, u64::from(config.encryption.0)),
|
||||||
|
(SURROUND_ENABLE, u64::from(s.enabled)),
|
||||||
|
(SURROUND_CHANNELS, u64::from(s.channels)),
|
||||||
|
(SURROUND_MASK, u64::from(s.channel_mask)),
|
||||||
|
(AUDIO_QUALITY, u64::from(s.high_quality)),
|
||||||
|
];
|
||||||
|
let mut out = String::with_capacity(1024);
|
||||||
|
out.push_str("v=0\r\n");
|
||||||
|
for (index, value) in values {
|
||||||
|
if let Some(attribute) = ATTRIBUTES.get(index) {
|
||||||
|
out.push_str("a=");
|
||||||
|
out.push_str(attribute.name);
|
||||||
|
out.push(':');
|
||||||
|
out.push_str(&value.to_string());
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One attribute the host reads (`docs/PROTOCOL.md` 2.4, 2.5).
|
||||||
|
struct Attribute {
|
||||||
|
/// The SDP attribute name.
|
||||||
|
name: &'static str,
|
||||||
|
/// The error text when a required attribute is missing; `None` for attributes with a default.
|
||||||
|
missing: Option<&'static str>,
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn required(name: &'static str, missing: &'static str) -> Attribute {
|
||||||
|
Attribute { name, missing: Some(missing) }
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn defaulted(name: &'static str) -> Attribute {
|
||||||
|
Attribute { name, missing: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
const VIEWPORT_WD: usize = 0;
|
||||||
|
const VIEWPORT_HT: usize = 1;
|
||||||
|
const MAX_FPS_ATTR: usize = 2;
|
||||||
|
const PACKET_SIZE: usize = 3;
|
||||||
|
const BITRATE: usize = 4;
|
||||||
|
const BIT_STREAM_FORMAT: usize = 5;
|
||||||
|
const MIN_FEC_PACKETS: usize = 6;
|
||||||
|
const VIDEO_QOS: usize = 7;
|
||||||
|
const PACKET_DURATION: usize = 8;
|
||||||
|
const AUDIO_QOS: usize = 9;
|
||||||
|
const MAX_REFERENCE_FRAMES: usize = 10;
|
||||||
|
const REF_PIC_INVALIDATION: usize = 11;
|
||||||
|
const DYNAMIC_RANGE_MODE: usize = 12;
|
||||||
|
const ENCODER_CSC_MODE: usize = 13;
|
||||||
|
const CHROMA_SAMPLING: usize = 14;
|
||||||
|
const ENCRYPTION_ENABLED: usize = 15;
|
||||||
|
const SURROUND_ENABLE: usize = 16;
|
||||||
|
const SURROUND_CHANNELS: usize = 17;
|
||||||
|
const SURROUND_MASK: usize = 18;
|
||||||
|
const AUDIO_QUALITY: usize = 19;
|
||||||
|
|
||||||
|
/// Every attribute read, in the order of the index constants above. The required set is the one a known host
|
||||||
|
/// refuses to stream without (`docs/PROTOCOL.md` 2.5 \[M\]); the others have the defaults documented on
|
||||||
|
/// [`StreamConfig`].
|
||||||
|
const ATTRIBUTES: [Attribute; 20] = [
|
||||||
|
required("x-nv-video[0].clientViewportWd", "announce: x-nv-video[0].clientViewportWd missing"),
|
||||||
|
required("x-nv-video[0].clientViewportHt", "announce: x-nv-video[0].clientViewportHt missing"),
|
||||||
|
required("x-nv-video[0].maxFPS", "announce: x-nv-video[0].maxFPS missing"),
|
||||||
|
required("x-nv-video[0].packetSize", "announce: x-nv-video[0].packetSize missing"),
|
||||||
|
required("x-ml-video.configuredBitrateKbps", "announce: x-ml-video.configuredBitrateKbps missing"),
|
||||||
|
required("x-nv-vqos[0].bitStreamFormat", "announce: x-nv-vqos[0].bitStreamFormat missing"),
|
||||||
|
required("x-nv-vqos[0].fec.minRequiredFecPackets", "announce: x-nv-vqos[0].fec.minRequiredFecPackets missing"),
|
||||||
|
required("x-nv-vqos[0].qosTrafficType", "announce: x-nv-vqos[0].qosTrafficType missing"),
|
||||||
|
required("x-nv-aqos.packetDuration", "announce: x-nv-aqos.packetDuration missing"),
|
||||||
|
required("x-nv-aqos.qosTrafficType", "announce: x-nv-aqos.qosTrafficType missing"),
|
||||||
|
defaulted("x-nv-video[0].maxNumReferenceFrames"),
|
||||||
|
defaulted("x-nv-video[0].refPicInvalidation"),
|
||||||
|
defaulted("x-nv-video[0].dynamicRangeMode"),
|
||||||
|
defaulted("x-nv-video[0].encoderCscMode"),
|
||||||
|
defaulted("x-ss-video[0].chromaSamplingType"),
|
||||||
|
defaulted("x-ss-general.encryptionEnabled"),
|
||||||
|
defaulted("x-nv-audio.surround.enable"),
|
||||||
|
defaulted("x-nv-audio.surround.numChannels"),
|
||||||
|
defaulted("x-nv-audio.surround.channelMask"),
|
||||||
|
defaulted("x-nv-audio.surround.AudioQuality"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// The values found, one slot per entry of [`ATTRIBUTES`].
|
||||||
|
struct Values<'a, 'b>(&'a [Option<&'b str>; ATTRIBUTES.len()]);
|
||||||
|
|
||||||
|
impl Values<'_, '_> {
|
||||||
|
/// The attribute's number in `lo..=hi`, or `default` when it is absent.
|
||||||
|
fn optional(&self, index: usize, default: u64, lo: u64, hi: u64) -> Result<u64> {
|
||||||
|
let name = ATTRIBUTES.get(index).map_or("announce attribute", |a| a.name);
|
||||||
|
match self.0.get(index).copied().flatten() {
|
||||||
|
None => Ok(default),
|
||||||
|
Some(text) => {
|
||||||
|
let value = parse_dec(name, text)?;
|
||||||
|
if value < lo || value > hi {
|
||||||
|
return Err(Error::UnexpectedValue { what: name, value });
|
||||||
|
}
|
||||||
|
Ok(value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The attribute's number in `lo..=hi`; refused when absent.
|
||||||
|
fn required(&self, index: usize, lo: u64, hi: u64) -> Result<u64> {
|
||||||
|
if self.0.get(index).copied().flatten().is_none() {
|
||||||
|
let what = ATTRIBUTES.get(index).and_then(|a| a.missing).unwrap_or("announce: attribute missing");
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
self.optional(index, 0, lo, hi)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A range-checked number into its field type (cannot fail after the range check; never panics either way).
|
||||||
|
fn narrow<T: TryFrom<u64>>(value: u64) -> Result<T> {
|
||||||
|
T::try_from(value).map_err(|_| Error::UnexpectedValue { what: "announce number", value })
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
//! The DESCRIBE answer (`docs/PROTOCOL.md` 2.3, 2.5): what the host offers, written as the SDP lines the client
|
||||||
|
//! reads with [`crate::rtsp::HostCapabilities::from_sdp`].
|
||||||
|
|
||||||
|
use crate::rtsp::sdp::{EncryptionFlags, FeatureFlags, MAX_OPUS_CONFIGS, OpusConfig, parse_surround_params};
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// The `sprop-parameter-sets` line a known host sends; its value is not used by clients (`docs/PROTOCOL.md` 2.3).
|
||||||
|
const SPROP_LINE: &str = "sprop-parameter-sets=AAAAAU";
|
||||||
|
|
||||||
|
/// What the host offers: written into the DESCRIBE answer, and checked against the client's ANNOUNCE.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct HostOffer {
|
||||||
|
/// `x-ss-general.featureFlags` (pen/touch, controller touch).
|
||||||
|
pub feature_flags: FeatureFlags,
|
||||||
|
/// `x-ss-general.encryptionSupported`.
|
||||||
|
pub encryption_supported: EncryptionFlags,
|
||||||
|
/// `x-nv-video[0].refPicInvalidation:1`: the host can invalidate reference frames.
|
||||||
|
pub reference_frame_invalidation: bool,
|
||||||
|
/// H.264: `a=fmtp:96 packetization-mode=1`.
|
||||||
|
pub h264: bool,
|
||||||
|
/// HEVC. No DESCRIBE line is known for it (a host advertises it in serverinfo, `docs/PROTOCOL.md` 1.2, U25);
|
||||||
|
/// used only to check ANNOUNCE.
|
||||||
|
pub hevc: bool,
|
||||||
|
/// AV1: `a=rtpmap:98 AV1/90000`.
|
||||||
|
pub av1: bool,
|
||||||
|
/// HDR. No DESCRIBE line is known for it (serverinfo again); used only to check ANNOUNCE: without it, a
|
||||||
|
/// `dynamicRangeMode` other than 0 (SDR \[M\]) is refused.
|
||||||
|
pub hdr: bool,
|
||||||
|
/// 4:4:4 chroma. No DESCRIBE line is known; used only to check ANNOUNCE.
|
||||||
|
pub yuv444: bool,
|
||||||
|
/// One `a=fmtp:97 surround-params=…` line each, in order (at most
|
||||||
|
/// [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]). The mappings are written as given: whether a host must rotate the
|
||||||
|
/// 5.1/7.1 normal-quality mappings is UNKNOWN U26.
|
||||||
|
pub opus_configs: Vec<OpusConfig>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the DESCRIBE payload for `offer`, in the line order a known host uses (`docs/PROTOCOL.md` 2.5 \[M\]):
|
||||||
|
/// feature flags, encryption, `sprop-parameter-sets`, reference invalidation, AV1, H.264, then one
|
||||||
|
/// `surround-params` line per Opus configuration. CRLF line ends.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for an Opus configuration that the client's `surround-params` parser would refuse (more
|
||||||
|
/// than 8 channels, a mapping entry or count above 9, a wrong mapping length, no streams, more coupled streams than
|
||||||
|
/// streams); [`Error::TooLarge`] over [`crate::rtsp::sdp::MAX_OPUS_CONFIGS`]; [`Error::Unsupported`] when no codec
|
||||||
|
/// is offered.
|
||||||
|
pub fn build_describe(offer: &HostOffer) -> Result<Vec<u8>> {
|
||||||
|
if !(offer.h264 || offer.hevc || offer.av1) {
|
||||||
|
return Err(Error::Unsupported { what: "a video codec in the host offer" });
|
||||||
|
}
|
||||||
|
cap("describe opus configurations", MAX_OPUS_CONFIGS, offer.opus_configs.len())?;
|
||||||
|
let mut out = String::with_capacity(256 + 48 * offer.opus_configs.len());
|
||||||
|
let mut line = |text: &str| {
|
||||||
|
out.push_str(text);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
};
|
||||||
|
line(&format!("a=x-ss-general.featureFlags:{}", offer.feature_flags.0));
|
||||||
|
line(&format!("a=x-ss-general.encryptionSupported:{}", offer.encryption_supported.0));
|
||||||
|
line(SPROP_LINE);
|
||||||
|
if offer.reference_frame_invalidation {
|
||||||
|
line("a=x-nv-video[0].refPicInvalidation:1");
|
||||||
|
}
|
||||||
|
if offer.av1 {
|
||||||
|
line("a=rtpmap:98 AV1/90000");
|
||||||
|
}
|
||||||
|
if offer.h264 {
|
||||||
|
line("a=fmtp:96 packetization-mode=1");
|
||||||
|
}
|
||||||
|
for config in &offer.opus_configs {
|
||||||
|
line(&format!("a=fmtp:97 surround-params={}", surround_digits(config)?));
|
||||||
|
}
|
||||||
|
Ok(out.into_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `surround-params` digits for `config` (`docs/PROTOCOL.md` 2.3): channel count, stream count, coupled count, then
|
||||||
|
/// one mapping digit per channel. The client's own parser checks the result, so nothing it refuses is written.
|
||||||
|
fn surround_digits(config: &OpusConfig) -> Result<String> {
|
||||||
|
let mut digits = String::with_capacity(3 + config.mapping.len());
|
||||||
|
for n in [config.channels, config.streams, config.coupled_streams].iter().chain(&config.mapping) {
|
||||||
|
let d = char::from_digit(u32::from(*n), 10).ok_or(malformed("surround-params: a value above 9"))?;
|
||||||
|
digits.push(d);
|
||||||
|
}
|
||||||
|
parse_surround_params(&digits)?;
|
||||||
|
Ok(digits)
|
||||||
|
}
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
//! The host's RTSP session (`docs/PROTOCOL.md` 2.2, 2.5), the mirror of [`super::client`]: OPTIONS → DESCRIBE →
|
||||||
|
//! SETUP audio, video and control (any order, each once) → ANNOUNCE → PLAY.
|
||||||
|
//!
|
||||||
|
//! The caller accepts TCP on the RTSP port, cuts each connection's bytes with [`super::RtspFramer::for_requests`],
|
||||||
|
//! feeds every whole request to [`RtspServer::handle_request`], writes the [`ServerReply`] back, and reads
|
||||||
|
//! [`ServerEvent`]s from [`RtspServer::poll_event`]. One [`RtspServer`] belongs to one launched session, not to one
|
||||||
|
//! TCP connection: a client may open a connection per request (UNKNOWN U5, `docs/PROTOCOL.md` 2.5), so the caller
|
||||||
|
//! routes every connection of that session to the same machine.
|
||||||
|
//!
|
||||||
|
//! Every request gets an answer. A request that is malformed, out of order or for another session gets an RTSP error
|
||||||
|
//! status and leaves the state unchanged; [`ServerReply::error`] says why, and the caller decides whether to close the
|
||||||
|
//! connection. Nothing here panics on any input.
|
||||||
|
|
||||||
|
mod announce;
|
||||||
|
mod describe;
|
||||||
|
|
||||||
|
pub use announce::{
|
||||||
|
ChromaSampling, MAX_ANNOUNCE_ATTRIBUTES, MAX_ANNOUNCE_BYTES, MAX_ANNOUNCE_LINE_BYTES, MAX_ANNOUNCE_LINES,
|
||||||
|
MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE, MIN_PACKET_SIZE,
|
||||||
|
StreamConfig, SurroundSettings, parse_announce, write_announce,
|
||||||
|
};
|
||||||
|
pub use describe::{HostOffer, build_describe};
|
||||||
|
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
|
use super::client::{StreamPorts, VideoCodec};
|
||||||
|
use super::sdp::EncryptionFlags;
|
||||||
|
use super::{MAX_RTSP_HEADERS, MAX_RTSP_MESSAGE_BYTES, Method, RtspRequest, RtspResponse, parse_request};
|
||||||
|
use crate::util::{hex_encode, malformed, parse_u32};
|
||||||
|
use crate::{Error, RandomSource, Result};
|
||||||
|
|
||||||
|
/// `timeout` of the `Session` header in SETUP answers, in seconds (`docs/PROTOCOL.md` 2.2 \[M\]).
|
||||||
|
pub const DEFAULT_SESSION_TIMEOUT_SECS: u32 = 90;
|
||||||
|
/// Random bytes in a session id (RFC 2326 section 3.4: at least eight octets, chosen at random); written as hex.
|
||||||
|
pub const SESSION_ID_BYTES: usize = 8;
|
||||||
|
|
||||||
|
/// How the host answers.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ServerConfig {
|
||||||
|
/// The UDP ports answered to SETUP audio, video and control (`Transport: server_port=<port>`).
|
||||||
|
pub ports: StreamPorts,
|
||||||
|
/// What DESCRIBE offers and ANNOUNCE is checked against.
|
||||||
|
pub offer: HostOffer,
|
||||||
|
/// Encryption the client must turn on in ANNOUNCE (Lumen: at least control V2); must be offered.
|
||||||
|
pub required_encryption: EncryptionFlags,
|
||||||
|
/// Refuse requests after the first SETUP that carry no `Session` header. Off by default: whether clients echo
|
||||||
|
/// it is UNKNOWN U5, and a known host does not read it (`docs/PROTOCOL.md` 2.5). A `Session` that is present is
|
||||||
|
/// always checked.
|
||||||
|
pub require_session_header: bool,
|
||||||
|
/// `timeout` in the `Session` header, seconds, 1.. ([`DEFAULT_SESSION_TIMEOUT_SECS`]).
|
||||||
|
pub session_timeout_secs: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which request the session expects next.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum RtspServerState {
|
||||||
|
/// OPTIONS.
|
||||||
|
Options,
|
||||||
|
/// DESCRIBE.
|
||||||
|
Describe,
|
||||||
|
/// SETUP of the streams not set up yet.
|
||||||
|
Setup,
|
||||||
|
/// ANNOUNCE.
|
||||||
|
Announce,
|
||||||
|
/// PLAY.
|
||||||
|
Play,
|
||||||
|
/// PLAY answered: the streams start. Only OPTIONS is still answered with 200.
|
||||||
|
Playing,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What the session tells the caller.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub enum ServerEvent {
|
||||||
|
/// ANNOUNCE accepted: the stream settings the client asked for.
|
||||||
|
Announced(StreamConfig),
|
||||||
|
/// PLAY accepted: start the streams (video and audio wait for the client's PING, control for ENet).
|
||||||
|
PlayRequested,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The answer to one request.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct ServerReply {
|
||||||
|
/// The whole RTSP answer to write to the connection.
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
/// Its status code (200, or 400, 451, 454, 455 or 501).
|
||||||
|
pub status: u16,
|
||||||
|
/// Why the request was refused; `None` with status 200.
|
||||||
|
pub error: Option<Error>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The host side of one session's RTSP negotiation.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RtspServer {
|
||||||
|
config: ServerConfig,
|
||||||
|
session_id: String,
|
||||||
|
/// The DESCRIBE payload, built once from the offer.
|
||||||
|
describe: Vec<u8>,
|
||||||
|
state: RtspServerState,
|
||||||
|
/// SETUP answered for audio, video, control.
|
||||||
|
set_up: [bool; 3],
|
||||||
|
/// A SETUP was answered, so the session id is known to the client.
|
||||||
|
session_issued: bool,
|
||||||
|
announced: Option<StreamConfig>,
|
||||||
|
/// At most two events ever (one ANNOUNCE, one PLAY).
|
||||||
|
events: VecDeque<ServerEvent>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Public` in the OPTIONS answer (RFC 2326 section 10.1 example form).
|
||||||
|
const PUBLIC: &str = "OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY";
|
||||||
|
/// The streams of SETUP, in the order of `RtspServer::set_up` (`docs/PROTOCOL.md` 2.2).
|
||||||
|
const STREAMS: [&str; 3] = ["audio", "video", "control"];
|
||||||
|
|
||||||
|
/// The CSeq, headers and payload of a 200 answer.
|
||||||
|
type Answer = (u32, Vec<(String, String)>, Vec<u8>);
|
||||||
|
|
||||||
|
/// A refused request: the status, the CSeq to echo if one was readable, and why.
|
||||||
|
struct Refusal {
|
||||||
|
status: u16,
|
||||||
|
cseq: Option<u32>,
|
||||||
|
error: Error,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RtspServer {
|
||||||
|
/// Checks `config` and draws a fresh session id from `rng`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for a zero port or session timeout, or required encryption the offer lacks; any error
|
||||||
|
/// of [`build_describe`] for the offer.
|
||||||
|
pub fn new(config: ServerConfig, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
|
let p = config.ports;
|
||||||
|
if p.audio == 0 || p.video == 0 || p.control == 0 {
|
||||||
|
return Err(malformed("rtsp server: stream port 0"));
|
||||||
|
}
|
||||||
|
if config.session_timeout_secs == 0 {
|
||||||
|
return Err(malformed("rtsp server: session timeout 0"));
|
||||||
|
}
|
||||||
|
if !config.offer.encryption_supported.contains(config.required_encryption.0) {
|
||||||
|
return Err(malformed("rtsp server: required encryption is not offered"));
|
||||||
|
}
|
||||||
|
let describe = build_describe(&config.offer)?;
|
||||||
|
let mut id = [0u8; SESSION_ID_BYTES];
|
||||||
|
rng.fill(&mut id);
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
session_id: hex_encode(&id),
|
||||||
|
describe,
|
||||||
|
state: RtspServerState::Options,
|
||||||
|
set_up: [false; 3],
|
||||||
|
session_issued: false,
|
||||||
|
announced: None,
|
||||||
|
events: VecDeque::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Answers one whole request (see [`super::RtspFramer::for_requests`]). Never panics; a refusal leaves the
|
||||||
|
/// state as it was.
|
||||||
|
pub fn handle_request(&mut self, message: &[u8]) -> ServerReply {
|
||||||
|
match self.answer(message) {
|
||||||
|
Ok((cseq, headers, body)) => reply(200, Some(cseq), headers, body, None),
|
||||||
|
Err(r) => reply(r.status, r.cseq, Vec::new(), Vec::new(), Some(r.error)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The headers and payload of a 200 answer, or why the request is refused.
|
||||||
|
fn answer(&mut self, message: &[u8]) -> core::result::Result<Answer, Refusal> {
|
||||||
|
let request = parse_request(message).map_err(|error| {
|
||||||
|
let status = if matches!(error, Error::UnexpectedValue { what: "rtsp method", .. }) { 501 } else { 400 };
|
||||||
|
Refusal { status, cseq: salvage_cseq(message), error }
|
||||||
|
})?;
|
||||||
|
let cseq = request_cseq(&request).map_err(|error| Refusal { status: 400, cseq: None, error })?;
|
||||||
|
let refuse = |status: u16, error: Error| Refusal { status, cseq: Some(cseq), error };
|
||||||
|
self.check_session(&request).map_err(|(status, error)| refuse(status, error))?;
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
let mut body = Vec::new();
|
||||||
|
match request.method {
|
||||||
|
Method::Options => {
|
||||||
|
// OPTIONS may come at any time and changes nothing else (RFC 2326 section 10.1).
|
||||||
|
if self.state == RtspServerState::Options {
|
||||||
|
self.state = RtspServerState::Describe;
|
||||||
|
}
|
||||||
|
headers.push(("Public".to_owned(), PUBLIC.to_owned()));
|
||||||
|
}
|
||||||
|
Method::Describe => {
|
||||||
|
self.expect(RtspServerState::Describe, "DESCRIBE after OPTIONS").map_err(|e| refuse(455, e))?;
|
||||||
|
headers.push(("Content-Type".to_owned(), "application/sdp".to_owned()));
|
||||||
|
body.clone_from(&self.describe);
|
||||||
|
self.state = RtspServerState::Setup;
|
||||||
|
}
|
||||||
|
Method::Setup => {
|
||||||
|
self.expect(RtspServerState::Setup, "SETUP after DESCRIBE").map_err(|e| refuse(455, e))?;
|
||||||
|
// A Transport header must be present; its value is not interpreted (`docs/PROTOCOL.md` 2.2 [M]).
|
||||||
|
if request.header("Transport").is_none() {
|
||||||
|
return Err(refuse(400, malformed("rtsp SETUP without Transport")));
|
||||||
|
}
|
||||||
|
let index = setup_stream(&request.target).map_err(|e| refuse(400, e))?;
|
||||||
|
let port = self.port(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||||
|
let slot = self.set_up.get_mut(index).ok_or(refuse(400, malformed("rtsp SETUP stream")))?;
|
||||||
|
if *slot {
|
||||||
|
return Err(refuse(455, Error::State { expected: "one SETUP per stream" }));
|
||||||
|
}
|
||||||
|
*slot = true;
|
||||||
|
self.session_issued = true;
|
||||||
|
if self.set_up.iter().all(|done| *done) {
|
||||||
|
self.state = RtspServerState::Announce;
|
||||||
|
}
|
||||||
|
let session = format!("{};timeout = {}", self.session_id, self.config.session_timeout_secs);
|
||||||
|
headers.push(("Session".to_owned(), session));
|
||||||
|
headers.push(("Transport".to_owned(), format!("server_port={port}")));
|
||||||
|
}
|
||||||
|
Method::Announce => {
|
||||||
|
self.expect(RtspServerState::Announce, "ANNOUNCE after the three SETUPs")
|
||||||
|
.map_err(|e| refuse(455, e))?;
|
||||||
|
let config = parse_announce(&request.body).map_err(|e| refuse(400, e))?;
|
||||||
|
self.check_offer(&config).map_err(|e| refuse(451, e))?;
|
||||||
|
self.events.push_back(ServerEvent::Announced(config.clone()));
|
||||||
|
self.announced = Some(config);
|
||||||
|
self.state = RtspServerState::Play;
|
||||||
|
}
|
||||||
|
Method::Play => {
|
||||||
|
self.expect(RtspServerState::Play, "PLAY after ANNOUNCE").map_err(|e| refuse(455, e))?;
|
||||||
|
self.events.push_back(ServerEvent::PlayRequested);
|
||||||
|
self.state = RtspServerState::Playing;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((cseq, headers, body))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expect(&self, state: RtspServerState, expected: &'static str) -> Result<()> {
|
||||||
|
if self.state == state { Ok(()) } else { Err(Error::State { expected }) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The UDP port answered for stream `index` (audio, video, control).
|
||||||
|
fn port(&self, index: usize) -> Option<u16> {
|
||||||
|
let p = self.config.ports;
|
||||||
|
[p.audio, p.video, p.control].get(index).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Session` checks (`docs/PROTOCOL.md` 2.5): a present id must be the one issued in SETUP; a missing one is
|
||||||
|
/// refused only when the config asks for it.
|
||||||
|
fn check_session(&self, request: &RtspRequest) -> core::result::Result<(), (u16, Error)> {
|
||||||
|
let mut ids = request
|
||||||
|
.headers
|
||||||
|
.iter()
|
||||||
|
.filter(|(n, _)| n.eq_ignore_ascii_case("session"))
|
||||||
|
.map(|(_, v)| v.split(';').next().unwrap_or("").trim_matches([' ', '\t']));
|
||||||
|
let first = ids.next();
|
||||||
|
if let Some(id) = first
|
||||||
|
&& ids.any(|other| other != id)
|
||||||
|
{
|
||||||
|
return Err((400, malformed("rtsp: two different Session headers")));
|
||||||
|
}
|
||||||
|
match first {
|
||||||
|
Some(id) if !self.session_issued || id != self.session_id => {
|
||||||
|
Err((454, malformed("rtsp: Session is not this session's id")))
|
||||||
|
}
|
||||||
|
None if self.config.require_session_header && self.session_issued && request.method != Method::Options => {
|
||||||
|
Err((454, malformed("rtsp: Session missing")))
|
||||||
|
}
|
||||||
|
_ => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What ANNOUNCE asks for must be in the offer.
|
||||||
|
fn check_offer(&self, config: &StreamConfig) -> Result<()> {
|
||||||
|
let offer = &self.config.offer;
|
||||||
|
let codec_offered = match config.codec {
|
||||||
|
VideoCodec::H264 => offer.h264,
|
||||||
|
VideoCodec::Hevc => offer.hevc,
|
||||||
|
VideoCodec::Av1 => offer.av1,
|
||||||
|
};
|
||||||
|
if !codec_offered {
|
||||||
|
return Err(Error::Unsupported { what: "the requested video codec" });
|
||||||
|
}
|
||||||
|
if config.encryption.0 & !offer.encryption_supported.0 != 0 {
|
||||||
|
return Err(Error::Unsupported { what: "encryption the host did not offer" });
|
||||||
|
}
|
||||||
|
if !config.encryption.contains(self.config.required_encryption.0) {
|
||||||
|
return Err(Error::Unsupported { what: "a stream without the encryption the host requires" });
|
||||||
|
}
|
||||||
|
// 0 is SDR (`docs/PROTOCOL.md` 2.5 [M]); any other value is "not SDR", without a settled meaning (U6).
|
||||||
|
if config.dynamic_range_mode != 0 && !offer.hdr {
|
||||||
|
return Err(Error::Unsupported { what: "HDR" });
|
||||||
|
}
|
||||||
|
if config.chroma == ChromaSampling::Yuv444 && !offer.yuv444 {
|
||||||
|
return Err(Error::Unsupported { what: "4:4:4 chroma" });
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The next event, if any.
|
||||||
|
pub fn poll_event(&mut self) -> Option<ServerEvent> {
|
||||||
|
self.events.pop_front()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which request the session expects next.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn state(&self) -> RtspServerState {
|
||||||
|
self.state
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session id sent in SETUP answers.
|
||||||
|
#[must_use]
|
||||||
|
pub fn session_id(&self) -> &str {
|
||||||
|
&self.session_id
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The accepted ANNOUNCE, once there is one.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn announced(&self) -> Option<&StreamConfig> {
|
||||||
|
self.announced.as_ref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The configuration the session answers with.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn config(&self) -> &ServerConfig {
|
||||||
|
&self.config
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The reason phrase of each status the session sends (RFC 2326 section 7.1.1).
|
||||||
|
const fn reason(status: u16) -> &'static str {
|
||||||
|
match status {
|
||||||
|
200 => "OK",
|
||||||
|
400 => "Bad Request",
|
||||||
|
451 => "Parameter Not Understood",
|
||||||
|
454 => "Session Not Found",
|
||||||
|
455 => "Method Not Valid in This State",
|
||||||
|
501 => "Not Implemented",
|
||||||
|
_ => "Internal Server Error",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the answer: `CSeq` first (when known), the given headers, then `Content-Length` (always, so the client's
|
||||||
|
/// framer never has to wait for the connection to close, `docs/PROTOCOL.md` 2.1 U5).
|
||||||
|
fn reply(
|
||||||
|
status: u16,
|
||||||
|
cseq: Option<u32>,
|
||||||
|
extra: Vec<(String, String)>,
|
||||||
|
body: Vec<u8>,
|
||||||
|
error: Option<Error>,
|
||||||
|
) -> ServerReply {
|
||||||
|
let mut headers = Vec::with_capacity(extra.len() + 2);
|
||||||
|
if let Some(c) = cseq {
|
||||||
|
headers.push(("CSeq".to_owned(), c.to_string()));
|
||||||
|
}
|
||||||
|
headers.extend(extra);
|
||||||
|
headers.push(("Content-Length".to_owned(), body.len().to_string()));
|
||||||
|
match (RtspResponse { status, reason: reason(status).to_owned(), headers, body }).encode() {
|
||||||
|
Ok(bytes) => ServerReply { bytes, status, error },
|
||||||
|
// Only an answer over the message cap could fail, and none is that large; answer 500 rather than panic.
|
||||||
|
Err(e) => ServerReply {
|
||||||
|
bytes: b"RTSP/1.0 500 Internal Server Error\r\nContent-Length: 0\r\n\r\n".to_vec(),
|
||||||
|
status: 500,
|
||||||
|
error: Some(e),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The request's CSeq: present, plain decimal `u32`, every copy equal.
|
||||||
|
fn request_cseq(request: &RtspRequest) -> Result<u32> {
|
||||||
|
let mut found = None;
|
||||||
|
for (_, v) in request.headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("cseq")) {
|
||||||
|
let n = parse_u32("rtsp CSeq", v)?;
|
||||||
|
if found.is_some_and(|f| f != n) {
|
||||||
|
return Err(malformed("rtsp: two different CSeq values"));
|
||||||
|
}
|
||||||
|
found = Some(n);
|
||||||
|
}
|
||||||
|
found.ok_or(malformed("rtsp request without CSeq"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The CSeq of a request that did not parse, if a header line says it plainly, so the refusal can still echo it.
|
||||||
|
/// Reads at most the header section, at most [`MAX_RTSP_HEADERS`] lines, and allocates nothing.
|
||||||
|
fn salvage_cseq(message: &[u8]) -> Option<u32> {
|
||||||
|
let head = message.get(..message.len().min(MAX_RTSP_MESSAGE_BYTES))?;
|
||||||
|
for raw in head.split(|&b| b == b'\n').skip(1).take(MAX_RTSP_HEADERS) {
|
||||||
|
let line = raw.strip_suffix(b"\r").unwrap_or(raw);
|
||||||
|
if line.is_empty() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let Ok(text) = core::str::from_utf8(line) else { continue };
|
||||||
|
if let Some((name, value)) = text.split_once(':')
|
||||||
|
&& name.eq_ignore_ascii_case("cseq")
|
||||||
|
{
|
||||||
|
return parse_u32("rtsp CSeq", value.trim_matches([' ', '\t'])).ok();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stream a SETUP target names: exactly one `streamid=` followed by `audio`, `video` or `control`, ended by
|
||||||
|
/// `/`, `?`, `&`, `;` or the end (`docs/PROTOCOL.md` 2.2 \[M\], 2.5). Index into [`STREAMS`].
|
||||||
|
fn setup_stream(target: &str) -> Result<usize> {
|
||||||
|
let mut parts = target.split("streamid=");
|
||||||
|
parts.next();
|
||||||
|
let after = parts.next().ok_or(malformed("rtsp SETUP target without streamid"))?;
|
||||||
|
if parts.next().is_some() {
|
||||||
|
return Err(malformed("rtsp SETUP target with two streamid"));
|
||||||
|
}
|
||||||
|
let name = after.split(['/', '?', '&', ';']).next().unwrap_or("");
|
||||||
|
STREAMS.iter().position(|s| *s == name).ok_or(malformed("rtsp SETUP streamid"))
|
||||||
|
}
|
||||||
@@ -0,0 +1,259 @@
|
|||||||
|
//! Small strict helpers shared by the parsers. Nothing here indexes without a bound check.
|
||||||
|
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// `Error::Malformed`.
|
||||||
|
pub(crate) const fn malformed(what: &'static str) -> Error {
|
||||||
|
Error::Malformed { what }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Error::TooLarge` when `actual > max`.
|
||||||
|
pub(crate) const fn cap(what: &'static str, max: usize, actual: usize) -> Result<()> {
|
||||||
|
if actual > max { Err(Error::TooLarge { what, max, actual }) } else { Ok(()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Error::Truncated` when `actual < needed`.
|
||||||
|
pub(crate) const fn need(what: &'static str, needed: usize, actual: usize) -> Result<()> {
|
||||||
|
if actual < needed { Err(Error::Truncated { what, needed, actual }) } else { Ok(()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes `start..start + len` of `data`, or `Truncated`.
|
||||||
|
pub(crate) fn slice<'a>(what: &'static str, data: &'a [u8], start: usize, len: usize) -> Result<&'a [u8]> {
|
||||||
|
let end = start.checked_add(len).ok_or(malformed(what))?;
|
||||||
|
data.get(start..end).ok_or(Error::Truncated { what, needed: end, actual: data.len() })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fixed-size array at `start`.
|
||||||
|
pub(crate) fn array<const N: usize>(what: &'static str, data: &[u8], start: usize) -> Result<[u8; N]> {
|
||||||
|
let s = slice(what, data, start, N)?;
|
||||||
|
let mut out = [0u8; N];
|
||||||
|
out.copy_from_slice(s);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u16_le(what: &'static str, data: &[u8], at: usize) -> Result<u16> {
|
||||||
|
array::<2>(what, data, at).map(u16::from_le_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u16_be(what: &'static str, data: &[u8], at: usize) -> Result<u16> {
|
||||||
|
array::<2>(what, data, at).map(u16::from_be_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u32_le(what: &'static str, data: &[u8], at: usize) -> Result<u32> {
|
||||||
|
array::<4>(what, data, at).map(u32::from_le_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u32_be(what: &'static str, data: &[u8], at: usize) -> Result<u32> {
|
||||||
|
array::<4>(what, data, at).map(u32::from_be_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reinterprets 16 bits as a signed value (two's complement).
|
||||||
|
pub(crate) const fn i16_from(v: u16) -> i16 {
|
||||||
|
i16::from_ne_bytes(v.to_ne_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn byte(what: &'static str, data: &[u8], at: usize) -> Result<u8> {
|
||||||
|
data.get(at).copied().ok_or(Error::Truncated { what, needed: at.saturating_add(1), actual: data.len() })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A strict decimal number: ASCII digits only, at least one, no sign, no spaces, no overflow.
|
||||||
|
pub(crate) fn parse_dec(what: &'static str, s: &str) -> Result<u64> {
|
||||||
|
if s.is_empty() || s.len() > 20 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let mut v: u64 = 0;
|
||||||
|
for b in s.bytes() {
|
||||||
|
if !b.is_ascii_digit() {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
v = v.checked_mul(10).and_then(|v| v.checked_add(u64::from(b - b'0'))).ok_or(malformed(what))?;
|
||||||
|
}
|
||||||
|
Ok(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_u32(what: &'static str, s: &str) -> Result<u32> {
|
||||||
|
u32::try_from(parse_dec(what, s)?).map_err(|_| malformed(what))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_u16(what: &'static str, s: &str) -> Result<u16> {
|
||||||
|
u16::try_from(parse_dec(what, s)?).map_err(|_| malformed(what))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_u8(what: &'static str, s: &str) -> Result<u8> {
|
||||||
|
u8::try_from(parse_dec(what, s)?).map_err(|_| malformed(what))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lower-case hex.
|
||||||
|
pub(crate) fn hex_encode(bytes: &[u8]) -> String {
|
||||||
|
const DIGITS: &[u8; 16] = b"0123456789abcdef";
|
||||||
|
let mut s = String::with_capacity(bytes.len() * 2);
|
||||||
|
for b in bytes {
|
||||||
|
for nibble in [b >> 4, b & 0x0F] {
|
||||||
|
s.push(char::from(DIGITS.get(usize::from(nibble)).copied().unwrap_or(b'0')));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_digit(c: u8) -> Option<u8> {
|
||||||
|
match c {
|
||||||
|
b'0'..=b'9' => Some(c - b'0'),
|
||||||
|
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||||
|
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict hex of either case: even length, digits only.
|
||||||
|
pub(crate) fn hex_decode(what: &'static str, s: &str) -> Result<Vec<u8>> {
|
||||||
|
let b = s.as_bytes();
|
||||||
|
if !b.len().is_multiple_of(2) {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let mut out = Vec::with_capacity(b.len() / 2);
|
||||||
|
for [h, l] in b.as_chunks::<2>().0 {
|
||||||
|
match (hex_digit(*h), hex_digit(*l)) {
|
||||||
|
(Some(h), Some(l)) => out.push((h << 4) | l),
|
||||||
|
_ => return Err(malformed(what)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Percent-encodes everything but RFC 3986 unreserved characters.
|
||||||
|
pub(crate) fn percent_encode(s: &str) -> String {
|
||||||
|
const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
|
||||||
|
let mut out = String::with_capacity(s.len());
|
||||||
|
for b in s.bytes() {
|
||||||
|
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
|
||||||
|
out.push(char::from(b));
|
||||||
|
} else {
|
||||||
|
out.push('%');
|
||||||
|
out.push(char::from(DIGITS.get(usize::from(b >> 4)).copied().unwrap_or(b'0')));
|
||||||
|
out.push(char::from(DIGITS.get(usize::from(b & 0x0F)).copied().unwrap_or(b'0')));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
|
||||||
|
/// Standard base64 with padding, wrapped at 64 characters per line (PEM).
|
||||||
|
pub(crate) fn base64_pem_lines(bytes: &[u8]) -> String {
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 4 / 3 + bytes.len() / 48 + 4);
|
||||||
|
let mut line = 0;
|
||||||
|
for chunk in bytes.chunks(3) {
|
||||||
|
let b0 = chunk.first().copied().unwrap_or(0);
|
||||||
|
let b1 = chunk.get(1).copied().unwrap_or(0);
|
||||||
|
let b2 = chunk.get(2).copied().unwrap_or(0);
|
||||||
|
let n = (u32::from(b0) << 16) | (u32::from(b1) << 8) | u32::from(b2);
|
||||||
|
let sym = |shift: u32| char::from(B64.get(((n >> shift) & 0x3F) as usize).copied().unwrap_or(b'A'));
|
||||||
|
out.push(sym(18));
|
||||||
|
out.push(sym(12));
|
||||||
|
out.push(if chunk.len() > 1 { sym(6) } else { '=' });
|
||||||
|
out.push(if chunk.len() > 2 { sym(0) } else { '=' });
|
||||||
|
line += 4;
|
||||||
|
if line == 64 {
|
||||||
|
out.push('\n');
|
||||||
|
line = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if line != 0 {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict standard base64: the 64 symbols, `=` padding only at the end, ASCII whitespace ignored, length a multiple
|
||||||
|
/// of 4 symbols, zero bits in the unused tail.
|
||||||
|
pub(crate) fn base64_decode(what: &'static str, s: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
let mut vals: Vec<u8> = Vec::with_capacity(s.len());
|
||||||
|
let mut pad = 0usize;
|
||||||
|
for &c in s {
|
||||||
|
if c.is_ascii_whitespace() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == b'=' {
|
||||||
|
pad += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if pad > 0 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let v = B64.iter().position(|&x| x == c).ok_or(malformed(what))?;
|
||||||
|
vals.push(u8::try_from(v).map_err(|_| malformed(what))?);
|
||||||
|
}
|
||||||
|
if pad > 2 || !(vals.len() + pad).is_multiple_of(4) {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let mut out = Vec::with_capacity(vals.len() * 3 / 4);
|
||||||
|
let mut acc = 0u32;
|
||||||
|
let mut bits = 0u32;
|
||||||
|
for v in &vals {
|
||||||
|
// At most 13 pending bits: keep 14 so the shift never overflows.
|
||||||
|
acc = ((acc << 6) | u32::from(*v)) & 0x3FFF;
|
||||||
|
bits += 6;
|
||||||
|
if bits >= 8 {
|
||||||
|
bits -= 8;
|
||||||
|
out.push(((acc >> bits) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if acc & ((1 << bits) - 1) != 0 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Constant-time equality (time depends on the lengths only).
|
||||||
|
pub(crate) fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||||
|
if a.len() != b.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `rtsp://host:port` with a non-empty host of letters, digits, `.`, `-` (or a bracketed IPv6 literal) and a port
|
||||||
|
/// 1..=65535.
|
||||||
|
pub(crate) fn check_rtsp_url(what: &'static str, url: &str) -> Result<(String, u16)> {
|
||||||
|
let rest = url.strip_prefix("rtsp://").ok_or(malformed(what))?;
|
||||||
|
let (host, port) = rest.rsplit_once(':').ok_or(malformed(what))?;
|
||||||
|
let host_ok = if let Some(inner) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
|
||||||
|
!inner.is_empty() && inner.bytes().all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.')
|
||||||
|
} else {
|
||||||
|
!host.is_empty() && host.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
|
||||||
|
};
|
||||||
|
if !host_ok {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let port = parse_u16(what, port)?;
|
||||||
|
if port == 0 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
Ok((host.to_owned(), port))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn base64_round_trip() {
|
||||||
|
for n in 0..70usize {
|
||||||
|
let data: Vec<u8> = (0..n).map(|i| (i * 37) as u8).collect();
|
||||||
|
let text = base64_pem_lines(&data);
|
||||||
|
assert_eq!(base64_decode("t", text.as_bytes()).unwrap(), data);
|
||||||
|
}
|
||||||
|
assert!(base64_decode("t", b"QQ=A").is_err());
|
||||||
|
assert!(base64_decode("t", b"QR==").is_err(), "non-zero tail bits");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hex_and_numbers() {
|
||||||
|
assert_eq!(hex_decode("t", "0aFf").unwrap(), vec![0x0A, 0xFF]);
|
||||||
|
assert!(hex_decode("t", "0").is_err() && hex_decode("t", "0x").is_err());
|
||||||
|
assert_eq!(parse_dec("t", "18446744073709551615").unwrap(), u64::MAX);
|
||||||
|
assert!(parse_dec("t", "18446744073709551616").is_err());
|
||||||
|
assert!(parse_dec("t", "+1").is_err() && parse_dec("t", "").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,16 +1,29 @@
|
|||||||
//! The video receive path (`docs/PROTOCOL.md` section 5): decrypt (if negotiated) → parse → group by frame and
|
//! The video receive path (`docs/PROTOCOL.md` section 5): decrypt (if negotiated) → parse → group by frame and
|
||||||
//! FEC block → rebuild lost data shards → reassemble the frame → hand the Annex-B bitstream to the platform decoder.
|
//! FEC block → rebuild lost data shards → reassemble the frame → hand the Annex-B bitstream to the platform decoder.
|
||||||
//!
|
//!
|
||||||
//! Lost frames become [`VideoEvent::FrameLost`], which the caller answers on the control stream with
|
//! Frames come out strictly in frame order, each at most once and byte-exact; a frame that cannot be completed is
|
||||||
|
//! reported in a [`VideoEvent::FrameLost`] range, which the caller answers on the control stream with
|
||||||
//! `INVALIDATE_REF_FRAMES` (when the host supports it) or an IDR request.
|
//! `INVALIDATE_REF_FRAMES` (when the host supports it) or an IDR request.
|
||||||
|
//!
|
||||||
|
//! Only a shard's payload is used: the RTP and NV header bytes of a shard rebuilt by FEC are garbage (the host
|
||||||
|
//! writes parity headers after computing parity), so a shard's place comes from its FEC fields alone.
|
||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||||
|
|
||||||
use crate::{Instant, Result};
|
use aes_gcm::Aes128Gcm;
|
||||||
|
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||||||
|
|
||||||
|
use crate::fec::ReedSolomon;
|
||||||
|
use crate::util::{array, cap, malformed, need};
|
||||||
|
use crate::{Error, Instant, Result};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
pub mod packetizer;
|
||||||
|
|
||||||
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet};
|
pub use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet};
|
||||||
|
pub use packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig};
|
||||||
|
|
||||||
/// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16.
|
/// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16.
|
||||||
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
||||||
@@ -18,29 +31,75 @@ pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
|||||||
pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
|
pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
|
||||||
/// Maximum frames being assembled at once; older ones are declared lost.
|
/// Maximum frames being assembled at once; older ones are declared lost.
|
||||||
pub const MAX_FRAMES_IN_FLIGHT: usize = 8;
|
pub const MAX_FRAMES_IN_FLIGHT: usize = 8;
|
||||||
|
/// Packets for frames further than this ahead of the next expected frame are dropped.
|
||||||
|
pub const MAX_FRAMES_AHEAD: u32 = 1024;
|
||||||
|
/// Finished frames remembered, so their late parity packets are not counted as drops but replays are.
|
||||||
|
const RECENT_FRAMES: usize = 32;
|
||||||
|
|
||||||
/// AES-128-GCM for encrypted video packets (`docs/PROTOCOL.md` 7). `Debug` never prints the key.
|
/// AES-128-GCM for encrypted video packets (`docs/PROTOCOL.md` 7). `Debug` never prints the key.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct VideoCipher {
|
pub struct VideoCipher {
|
||||||
key: [u8; 16],
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VideoCipher {
|
impl VideoCipher {
|
||||||
/// A cipher for `rikey`.
|
/// A cipher for `rikey`.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new(rikey: [u8; 16]) -> Self {
|
pub fn new(rikey: [u8; 16]) -> Self {
|
||||||
Self { key: rikey }
|
Self { key: zeroize::Zeroizing::new(rikey) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decrypts one encrypted packet (`IV ‖ frame number ‖ tag ‖ ciphertext`) into the plaintext packet.
|
/// Decrypts one encrypted packet (`IV ‖ frame number ‖ tag ‖ ciphertext`) into the plaintext packet.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under the
|
/// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Truncated`] under the prefix,
|
||||||
/// prefix, [`crate::Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`crate::Error::Crypto`] for a bad
|
/// [`Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`Error::Crypto`] for a bad tag.
|
||||||
/// tag. Phase A: always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn decrypt(&self, packet: &[u8]) -> Result<Vec<u8>> {
|
pub fn decrypt(&self, packet: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (packet, &self.key);
|
const W: &str = "encrypted video packet";
|
||||||
Err(crate::Error::Unimplemented)
|
cap(W, packet::MAX_VIDEO_PACKET_BYTES, packet.len())?;
|
||||||
|
need(W, ENCRYPTION_PREFIX_LEN, packet.len())?;
|
||||||
|
let iv = array::<12>(W, packet, 0)?;
|
||||||
|
if iv.get(11) != Some(&b'V') {
|
||||||
|
return Err(malformed("video IV byte 11 is not 'V'"));
|
||||||
|
}
|
||||||
|
let tag = array::<16>(W, packet, 16)?;
|
||||||
|
let mut body = packet.get(ENCRYPTION_PREFIX_LEN..).unwrap_or(&[]).to_vec();
|
||||||
|
Aes128Gcm::new((&*self.key).into())
|
||||||
|
.decrypt_inout_detached(&iv.into(), b"", body.as_mut_slice().into(), &tag.into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
Ok(body)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VideoCipher {
|
||||||
|
/// Seals one plaintext packet (host side), the exact mirror of [`Self::decrypt`]: IV = `counter` as 8 bytes LE,
|
||||||
|
/// 3 zero bytes, `'V'`; output `IV ‖ frame number u32 LE ‖ tag ‖ ciphertext` (`docs/PROTOCOL.md` 7, UNKNOWN
|
||||||
|
/// U19 against Sunshine). The caller must never reuse a `counter` under one key: the packetizer counts from 0
|
||||||
|
/// per session, and the `'V'` byte keeps video nonces apart from control's (`'C'`).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] when the sealed packet would exceed [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Crypto`]
|
||||||
|
/// if the cipher refuses (never for packets within the cap).
|
||||||
|
pub fn encrypt(&self, counter: u64, frame_number: u32, packet: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
let sealed = packet.len().saturating_add(ENCRYPTION_PREFIX_LEN);
|
||||||
|
cap("sealed video packet", packet::MAX_VIDEO_PACKET_BYTES, sealed)?;
|
||||||
|
let mut iv = [0u8; 12];
|
||||||
|
for (dst, src) in iv.iter_mut().zip(counter.to_le_bytes()) {
|
||||||
|
*dst = src;
|
||||||
|
}
|
||||||
|
if let Some(last) = iv.last_mut() {
|
||||||
|
*last = b'V';
|
||||||
|
}
|
||||||
|
let mut body = packet.to_vec();
|
||||||
|
let tag = Aes128Gcm::new((&*self.key).into())
|
||||||
|
.encrypt_inout_detached(&iv.into(), b"", body.as_mut_slice().into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
let mut out = Vec::with_capacity(sealed);
|
||||||
|
out.extend_from_slice(&iv);
|
||||||
|
out.extend_from_slice(&frame_number.to_le_bytes());
|
||||||
|
out.extend_from_slice(tag.as_slice());
|
||||||
|
out.extend_from_slice(&body);
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,7 +117,7 @@ pub struct VideoConfig {
|
|||||||
/// Decrypt packets with this cipher when video encryption was negotiated.
|
/// Decrypt packets with this cipher when video encryption was negotiated.
|
||||||
pub cipher: Option<VideoCipher>,
|
pub cipher: Option<VideoCipher>,
|
||||||
/// How long to wait for missing shards of a frame before declaring it lost.
|
/// How long to wait for missing shards of a frame before declaring it lost.
|
||||||
pub frame_timeout: core::time::Duration,
|
pub frame_timeout: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One complete frame for the decoder.
|
/// One complete frame for the decoder.
|
||||||
@@ -109,9 +168,34 @@ pub struct VideoStats {
|
|||||||
pub frames_lost: u64,
|
pub frames_lost: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Block {
|
||||||
|
data_shards: u16,
|
||||||
|
parity_shards: u16,
|
||||||
|
fec_percentage: u8,
|
||||||
|
shards: BTreeMap<u16, Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Pending {
|
||||||
|
first_packet_at: Instant,
|
||||||
|
rtp_timestamp: u32,
|
||||||
|
last_block: u8,
|
||||||
|
blocks: [Option<Block>; packet::MAX_FEC_BLOCKS],
|
||||||
|
/// Every shard seen, by (block, shard index).
|
||||||
|
seen: BTreeSet<(u8, u16)>,
|
||||||
|
complete: Option<VideoFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
/// The video receiver.
|
/// The video receiver.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct VideoDepacketizer {
|
pub struct VideoDepacketizer {
|
||||||
|
config: VideoConfig,
|
||||||
|
payload_len: usize,
|
||||||
|
next_frame: Option<u32>,
|
||||||
|
frames: HashMap<u32, Pending>,
|
||||||
|
recent: VecDeque<(u32, BTreeSet<(u8, u16)>)>,
|
||||||
|
events: VecDeque<VideoEvent>,
|
||||||
stats: VideoStats,
|
stats: VideoStats,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,42 +203,227 @@ impl VideoDepacketizer {
|
|||||||
/// A receiver for one stream.
|
/// A receiver for one stream.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a `packet_size` below the NV header size or above what fits in
|
/// [`Error::Malformed`] for a `packet_size` not above the NV header size or above what fits in
|
||||||
/// [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`packet::MAX_VIDEO_PACKET_BYTES`].
|
||||||
pub fn new(config: VideoConfig) -> Result<Self> {
|
pub fn new(config: VideoConfig) -> Result<Self> {
|
||||||
let _ = config;
|
let size = usize::from(config.packet_size);
|
||||||
Err(crate::Error::Unimplemented)
|
if size <= packet::NV_HEADER_LEN || size + packet::VIDEO_RTP_LEN > packet::MAX_VIDEO_PACKET_BYTES {
|
||||||
|
return Err(malformed("video packet_size"));
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
payload_len: size - packet::NV_HEADER_LEN,
|
||||||
|
config,
|
||||||
|
next_frame: None,
|
||||||
|
frames: HashMap::new(),
|
||||||
|
recent: VecDeque::new(),
|
||||||
|
events: VecDeque::new(),
|
||||||
|
stats: VideoStats::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drop_packet(&mut self) -> Result<()> {
|
||||||
|
self.stats.packets_dropped += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one datagram from the video port. Bad, duplicate and too-old packets are counted and dropped; only
|
/// Feeds one datagram from the video port. Bad, duplicate and too-old packets are counted and dropped; only
|
||||||
/// an oversized datagram is an error.
|
/// an oversized datagram is an error.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always
|
/// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
cap("video datagram", packet::MAX_VIDEO_PACKET_BYTES, datagram.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let plain;
|
||||||
|
let bytes = match &self.config.cipher {
|
||||||
|
Some(c) => match c.decrypt(datagram) {
|
||||||
|
Ok(p) => {
|
||||||
|
plain = p;
|
||||||
|
plain.as_slice()
|
||||||
|
}
|
||||||
|
Err(_) => return self.drop_packet(),
|
||||||
|
},
|
||||||
|
None => datagram,
|
||||||
|
};
|
||||||
|
let Ok(p) = parse_video_packet(bytes) else { return self.drop_packet() };
|
||||||
|
if p.payload.len() != self.payload_len {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
let frame = p.nv.frame_index;
|
||||||
|
let next = *self.next_frame.get_or_insert(frame);
|
||||||
|
let ahead = frame.wrapping_sub(next);
|
||||||
|
let shard = (p.nv.fec.block_index, p.nv.fec.shard_index);
|
||||||
|
if ahead >= 1 << 31 {
|
||||||
|
// Before the next frame: late parity of a finished frame is fine, anything seen before is a replay.
|
||||||
|
let late = self.recent.iter_mut().find(|(f, _)| *f == frame).is_some_and(|(_, seen)| seen.insert(shard));
|
||||||
|
if late {
|
||||||
|
self.stats.packets += 1;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
if ahead >= MAX_FRAMES_AHEAD {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
if !self.frames.contains_key(&frame) {
|
||||||
|
while self.frames.len() >= MAX_FRAMES_IN_FLIGHT {
|
||||||
|
self.give_up_head(now);
|
||||||
|
}
|
||||||
|
if self.next_frame.is_some_and(|n| frame.wrapping_sub(n) >= 1 << 31) {
|
||||||
|
// The forced advance passed this frame.
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
self.frames.insert(
|
||||||
|
frame,
|
||||||
|
Pending {
|
||||||
|
first_packet_at: now,
|
||||||
|
rtp_timestamp: p.rtp.timestamp,
|
||||||
|
last_block: p.nv.fec.last_block_index,
|
||||||
|
blocks: [None, None, None, None],
|
||||||
|
seen: BTreeSet::new(),
|
||||||
|
complete: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let accepted = self.store(frame, &p, now);
|
||||||
|
if !accepted {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
self.stats.packets += 1;
|
||||||
|
self.advance(now);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores one packet in its frame; false for a duplicate or a packet that contradicts the frame's FEC layout.
|
||||||
|
fn store(&mut self, frame: u32, p: &VideoPacket<'_>, now: Instant) -> bool {
|
||||||
|
let payload_len = self.payload_len;
|
||||||
|
let Some(f) = self.frames.get_mut(&frame) else { return false };
|
||||||
|
let fec = p.nv.fec;
|
||||||
|
if fec.last_block_index != f.last_block || !f.seen.insert((fec.block_index, fec.shard_index)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if f.complete.is_some() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let Some(slot) = f.blocks.get_mut(usize::from(fec.block_index)) else { return false };
|
||||||
|
let block = slot.get_or_insert_with(|| Block {
|
||||||
|
data_shards: fec.data_shards,
|
||||||
|
parity_shards: crate::fec::parity_count(usize::from(fec.data_shards), fec.fec_percentage)
|
||||||
|
.ok()
|
||||||
|
.and_then(|m| u16::try_from(m).ok())
|
||||||
|
.unwrap_or(0),
|
||||||
|
fec_percentage: fec.fec_percentage,
|
||||||
|
shards: BTreeMap::new(),
|
||||||
|
});
|
||||||
|
if block.data_shards != fec.data_shards || block.fec_percentage != fec.fec_percentage {
|
||||||
|
f.seen.remove(&(fec.block_index, fec.shard_index));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
block.shards.insert(fec.shard_index, p.payload.to_vec());
|
||||||
|
let complete = (0..=usize::from(f.last_block)).all(|b| {
|
||||||
|
f.blocks.get(b).and_then(Option::as_ref).is_some_and(|blk| blk.shards.len() >= usize::from(blk.data_shards))
|
||||||
|
});
|
||||||
|
if complete {
|
||||||
|
match assemble(f, frame, payload_len, now) {
|
||||||
|
Some((v, recovered)) => {
|
||||||
|
self.stats.shards_recovered += u64::from(recovered);
|
||||||
|
f.complete = Some(v);
|
||||||
|
for b in &mut f.blocks {
|
||||||
|
*b = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// Rebuilt but unusable: it can never complete; the timeout reports it lost.
|
||||||
|
for b in &mut f.blocks {
|
||||||
|
*b = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lose(&mut self, first: u32, last: u32) {
|
||||||
|
self.events.push_back(VideoEvent::FrameLost { first, last });
|
||||||
|
let span = last.wrapping_sub(first);
|
||||||
|
self.stats.frames_lost += u64::from(span) + 1;
|
||||||
|
self.frames.retain(|&f, _| f.wrapping_sub(first) > span);
|
||||||
|
self.next_frame = Some(last.wrapping_add(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver(&mut self, frame: u32) {
|
||||||
|
if let Some(mut f) = self.frames.remove(&frame) {
|
||||||
|
if let Some(v) = f.complete.take() {
|
||||||
|
self.events.push_back(VideoEvent::Frame(v));
|
||||||
|
self.stats.frames += 1;
|
||||||
|
}
|
||||||
|
if self.recent.len() >= RECENT_FRAMES {
|
||||||
|
self.recent.pop_front();
|
||||||
|
}
|
||||||
|
self.recent.push_back((frame, core::mem::take(&mut f.seen)));
|
||||||
|
}
|
||||||
|
self.next_frame = Some(frame.wrapping_add(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pending frame closest after `next`, as (frame index, distance).
|
||||||
|
fn lowest_pending(&self, next: u32) -> Option<(u32, u32)> {
|
||||||
|
self.frames.keys().map(|&f| (f, f.wrapping_sub(next))).min_by_key(|&(_, d)| d)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivers or gives up frames at the head while it is complete or has timed out.
|
||||||
|
fn advance(&mut self, now: Instant) {
|
||||||
|
let timeout = self.config.frame_timeout;
|
||||||
|
while let Some(next) = self.next_frame {
|
||||||
|
match self.frames.get(&next) {
|
||||||
|
Some(f) if f.complete.is_some() => self.deliver(next),
|
||||||
|
Some(f) if f.first_packet_at.saturating_add(timeout) <= now => self.lose(next, next),
|
||||||
|
Some(_) => return,
|
||||||
|
None => {
|
||||||
|
let Some((lowest, _)) = self.lowest_pending(next) else { return };
|
||||||
|
let expired =
|
||||||
|
self.frames.get(&lowest).is_some_and(|f| f.first_packet_at.saturating_add(timeout) <= now);
|
||||||
|
if !expired {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.lose(next, lowest.wrapping_sub(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frees one slot: delivers the head if complete, else declares it (or the gap before the oldest frame) lost.
|
||||||
|
fn give_up_head(&mut self, now: Instant) {
|
||||||
|
let Some(next) = self.next_frame else { return };
|
||||||
|
match self.frames.get(&next) {
|
||||||
|
Some(f) if f.complete.is_some() => self.deliver(next),
|
||||||
|
Some(_) => self.lose(next, next),
|
||||||
|
None => match self.lowest_pending(next) {
|
||||||
|
Some((lowest, _)) => self.lose(next, lowest.wrapping_sub(1)),
|
||||||
|
None => return,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
self.advance(now);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<VideoEvent> {
|
pub fn poll_event(&mut self) -> Option<VideoEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When an incomplete frame times out.
|
/// When an incomplete frame times out.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
let next = self.next_frame?;
|
||||||
|
let head = self.frames.get(&next).map(|_| next).or_else(|| self.lowest_pending(next).map(|(f, _)| f))?;
|
||||||
|
self.frames.get(&head).map(|f| f.first_packet_at.saturating_add(self.config.frame_timeout))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declares timed-out frames lost.
|
/// Declares timed-out frames lost.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
self.advance(now);
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Counters.
|
/// Counters.
|
||||||
@@ -163,3 +432,59 @@ impl VideoDepacketizer {
|
|||||||
self.stats
|
self.stats
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Builds the frame of a pending entry whose every block has enough shards: rebuilds missing data shards, joins the
|
||||||
|
/// data in block order and trims the frame header and padding. `None` when the result is unusable.
|
||||||
|
fn assemble(f: &Pending, frame_index: u32, payload_len: usize, now: Instant) -> Option<(VideoFrame, u16)> {
|
||||||
|
let mut data: Vec<u8> = Vec::new();
|
||||||
|
let mut recovered: u16 = 0;
|
||||||
|
let mut shards_total = 0usize;
|
||||||
|
for b in 0..=usize::from(f.last_block) {
|
||||||
|
let block = f.blocks.get(b)?.as_ref()?;
|
||||||
|
let k = usize::from(block.data_shards);
|
||||||
|
let m = usize::from(block.parity_shards);
|
||||||
|
shards_total += k;
|
||||||
|
if data.len().saturating_add(k * payload_len) > MAX_FRAME_BYTES + payload_len {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let missing = (0..block.data_shards).filter(|i| !block.shards.contains_key(i)).count();
|
||||||
|
if missing == 0 {
|
||||||
|
for i in 0..block.data_shards {
|
||||||
|
data.extend_from_slice(block.shards.get(&i)?);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let code = ReedSolomon::new(k, m).ok()?;
|
||||||
|
let mut shards: Vec<Option<Vec<u8>>> =
|
||||||
|
(0..k + m).map(|i| u16::try_from(i).ok().and_then(|i| block.shards.get(&i).cloned())).collect();
|
||||||
|
code.reconstruct(&mut shards).ok()?;
|
||||||
|
for s in shards.iter().take(k) {
|
||||||
|
data.extend_from_slice(s.as_ref()?);
|
||||||
|
}
|
||||||
|
recovered = recovered.saturating_add(u16::try_from(missing).unwrap_or(u16::MAX));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let header = packet::parse_frame_header(&data).ok()?;
|
||||||
|
let last = usize::try_from(header.last_payload_len).unwrap_or(0);
|
||||||
|
let end = if (1..=payload_len).contains(&last) && shards_total >= 1 {
|
||||||
|
(shards_total - 1) * payload_len + last
|
||||||
|
} else {
|
||||||
|
// The header does not say where the frame ends (Wolf's constant, U13): trim the zero padding.
|
||||||
|
data.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1)
|
||||||
|
};
|
||||||
|
let bitstream = data.get(packet::FRAME_HEADER_LEN..end)?.to_vec();
|
||||||
|
if bitstream.len() > MAX_FRAME_BYTES {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((
|
||||||
|
VideoFrame {
|
||||||
|
frame_index,
|
||||||
|
header,
|
||||||
|
bitstream,
|
||||||
|
rtp_timestamp: f.rtp_timestamp,
|
||||||
|
first_packet_at: f.first_packet_at,
|
||||||
|
completed_at: now,
|
||||||
|
recovered_shards: recovered,
|
||||||
|
},
|
||||||
|
recovered,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|||||||
@@ -72,16 +72,46 @@ pub struct VideoPacket<'a> {
|
|||||||
pub payload: &'a [u8],
|
pub payload: &'a [u8],
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses one plaintext video packet. Checks the FEC fields are consistent (`shard_index < data + parity`,
|
/// Parses one plaintext video packet. Checks the FEC fields are consistent (`data_shards > 0`, data + parity
|
||||||
/// `block_index <= last_block_index`, `data_shards > 0`).
|
/// `<= 255` with parity `= ceil(data × percentage / 100)`, `shard_index < data + parity`,
|
||||||
|
/// `block_index <= last_block_index`).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under
|
/// [`crate::Error::TooLarge`] over [`MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under
|
||||||
/// [`PAYLOAD_OFFSET`], [`crate::Error::Malformed`] for inconsistent FEC fields. Phase A: always
|
/// [`PAYLOAD_OFFSET`], [`crate::Error::UnexpectedValue`] for an RTP version other than 2,
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Malformed`] for inconsistent FEC fields.
|
||||||
pub fn parse_video_packet(packet: &[u8]) -> crate::Result<VideoPacket<'_>> {
|
pub fn parse_video_packet(packet: &[u8]) -> crate::Result<VideoPacket<'_>> {
|
||||||
let _ = packet;
|
use crate::util::{byte, malformed, u32_le};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "video packet";
|
||||||
|
crate::util::cap(W, MAX_VIDEO_PACKET_BYTES, packet.len())?;
|
||||||
|
crate::util::need(W, PAYLOAD_OFFSET, packet.len())?;
|
||||||
|
let rtp = crate::rtp::parse_rtp_header(packet)?;
|
||||||
|
let nv = VIDEO_RTP_LEN;
|
||||||
|
let fec_info = u32_le(W, packet, nv + 12)?;
|
||||||
|
let blocks = byte(W, packet, nv + 11)?;
|
||||||
|
let fec = FecInfo {
|
||||||
|
shard_index: ((fec_info >> 12) & 0x3FF) as u16,
|
||||||
|
data_shards: ((fec_info >> 22) & 0x3FF) as u16,
|
||||||
|
fec_percentage: ((fec_info >> 4) & 0xFF) as u8,
|
||||||
|
block_index: (blocks >> 4) & 0x3,
|
||||||
|
last_block_index: (blocks >> 6) & 0x3,
|
||||||
|
};
|
||||||
|
let parity = crate::fec::parity_count(usize::from(fec.data_shards), fec.fec_percentage)
|
||||||
|
.map_err(|_| malformed("video fec shard counts"))?;
|
||||||
|
if usize::from(fec.shard_index) >= usize::from(fec.data_shards) + parity || fec.block_index > fec.last_block_index {
|
||||||
|
return Err(malformed("video fec fields"));
|
||||||
|
}
|
||||||
|
Ok(VideoPacket {
|
||||||
|
rtp,
|
||||||
|
nv: NvVideoHeader {
|
||||||
|
stream_packet_index: u32_le(W, packet, nv)?,
|
||||||
|
frame_index: u32_le(W, packet, nv + 4)?,
|
||||||
|
flags: VideoFlags(byte(W, packet, nv + 8)?),
|
||||||
|
multi_fec_flags: byte(W, packet, nv + 10)?,
|
||||||
|
fec,
|
||||||
|
},
|
||||||
|
payload: packet.get(PAYLOAD_OFFSET..).unwrap_or(&[]),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Frame types in the frame header.
|
/// Frame types in the frame header.
|
||||||
@@ -116,8 +146,22 @@ pub struct FrameHeader {
|
|||||||
/// Parses the frame header at the start of a frame's data (the rest is ignored here).
|
/// Parses the frame header at the start of a frame's data (the rest is ignored here).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Truncated`] under [`FRAME_HEADER_LEN`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Truncated`] under [`FRAME_HEADER_LEN`].
|
||||||
pub fn parse_frame_header(frame_data: &[u8]) -> crate::Result<FrameHeader> {
|
pub fn parse_frame_header(frame_data: &[u8]) -> crate::Result<FrameHeader> {
|
||||||
let _ = frame_data;
|
const W: &str = "video frame header";
|
||||||
Err(crate::Error::Unimplemented)
|
let raw = crate::util::array::<FRAME_HEADER_LEN>(W, frame_data, 0)?;
|
||||||
|
let [header_type, l0, l1, kind, a, b, c, d] = raw;
|
||||||
|
let frame_type = match kind {
|
||||||
|
1 => FrameType::Predicted,
|
||||||
|
2 => FrameType::Key,
|
||||||
|
5 => FrameType::Recovery,
|
||||||
|
other => FrameType::Other(other),
|
||||||
|
};
|
||||||
|
Ok(FrameHeader {
|
||||||
|
raw,
|
||||||
|
header_type,
|
||||||
|
processing_latency: u16::from_le_bytes([l0, l1]),
|
||||||
|
frame_type,
|
||||||
|
last_payload_len: u32::from_le_bytes([a, b, c, d]),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,391 @@
|
|||||||
|
//! The video send path, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7): one encoded access unit → the RTP + NV-header
|
||||||
|
//! datagrams of one frame, in FEC blocks with Reed-Solomon parity, optionally AES-128-GCM sealed.
|
||||||
|
//!
|
||||||
|
//! The mirror of [`super::VideoDepacketizer`], and tested against it:
|
||||||
|
//!
|
||||||
|
//! 1. Frame data = the 8-byte frame header ([`write_frame_header`], the structured reading of 5.2; UNKNOWN U13 is
|
||||||
|
//! open, so the writer is one small function) followed by the Annex-B bitstream, cut into `packetSize - 16`-byte
|
||||||
|
//! data shards, the last one zero-padded (5.2).
|
||||||
|
//! 2. The data shards are split into at most 4 FEC blocks ([`plan_fec_blocks`]); each block gets
|
||||||
|
//! `m = ceil(k × percentage / 100)` parity shards, with the percentage raised for the client's minimum parity
|
||||||
|
//! count and lowered only when a block would exceed 255 shards (5.3).
|
||||||
|
//! 3. Each data shard becomes a whole packet (RTP header, 4 reserved bytes, NV header, payload). Parity is computed
|
||||||
|
//! over these whole packets with [`crate::fec::ReedSolomon`] (the Cauchy matrix of 5.3), and only then are the
|
||||||
|
//! parity packets' RTP and NV header fields written over their first 32 bytes, exactly as 5.3 says.
|
||||||
|
//! 4. Sequence numbers run on across frames (one per datagram, data and parity alike, wrapping at 16 bits); the
|
||||||
|
//! stream packet index is the sequence number shifted left by 8 (5.2).
|
||||||
|
//! 5. With video encryption, every finished packet is sealed with [`VideoCipher::encrypt`] (FEC before
|
||||||
|
//! encryption, 7), with a per-session nonce counter that starts at 0.
|
||||||
|
//!
|
||||||
|
//! The input is trusted (our own encoder), but nothing here panics: sizes are capped with typed errors before
|
||||||
|
//! anything is allocated, and a refused frame changes no state.
|
||||||
|
//!
|
||||||
|
//! Choices of our own, not from a source (to be compared with a real host's capture): the block split (fewest
|
||||||
|
//! blocks that carry the requested parity; every block but the last has the same `k`), the percentage arithmetic
|
||||||
|
//! for the minimum parity count, and what happens to a frame too big for its parity (the parity is lowered, counted
|
||||||
|
//! in [`VideoPacketizerStats::fec_reduced_blocks`]).
|
||||||
|
|
||||||
|
use super::VideoCipher;
|
||||||
|
use super::packet::{
|
||||||
|
FRAME_HEADER_LEN, FrameType, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, NV_HEADER_LEN, PAYLOAD_OFFSET, VIDEO_RTP_LEN,
|
||||||
|
VideoFlags,
|
||||||
|
};
|
||||||
|
use super::{ENCRYPTION_PREFIX_LEN, MAX_FRAME_BYTES};
|
||||||
|
use crate::fec::{MAX_SHARDS, ReedSolomon};
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// The NV header's multi-FEC flags byte (`docs/PROTOCOL.md` 5.2, UNKNOWN U15: sent as documented, meaning unknown).
|
||||||
|
pub const MULTI_FEC_FLAGS: u8 = 0x10;
|
||||||
|
/// Byte 0 of the structured frame header (`docs/PROTOCOL.md` 5.2).
|
||||||
|
pub const FRAME_HEADER_TYPE: u8 = 0x01;
|
||||||
|
/// Byte 0 of every video RTP header: version 2, extension bit set (`docs/PROTOCOL.md` 5.2).
|
||||||
|
pub const VIDEO_RTP_BYTE0: u8 = 0x90;
|
||||||
|
/// Most data shards one frame can carry: [`MAX_FEC_BLOCKS`] blocks of at most [`MAX_SHARDS`] shards.
|
||||||
|
pub const MAX_DATA_SHARDS_PER_FRAME: usize = MAX_FEC_BLOCKS * MAX_SHARDS;
|
||||||
|
|
||||||
|
/// Settings of the video sender, from the client's ANNOUNCE (`docs/PROTOCOL.md` 2.4).
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct VideoPacketizerConfig {
|
||||||
|
/// Negotiated `packetSize`: NV header + payload. Each datagram is `packetSize + 16` bytes (+ 32 when sealed).
|
||||||
|
pub packet_size: u16,
|
||||||
|
/// Requested FEC percentage.
|
||||||
|
pub fec_percentage: u8,
|
||||||
|
/// Minimum parity packets per block (`x-nv-vqos[0].fec.minRequiredFecPackets`).
|
||||||
|
pub min_required_fec_packets: u8,
|
||||||
|
/// Seal every datagram with this cipher when video encryption was negotiated.
|
||||||
|
pub cipher: Option<VideoCipher>,
|
||||||
|
/// RTP sequence number of the first datagram.
|
||||||
|
pub first_sequence: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One encoded access unit from the encoder.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct EncodedFrame<'a> {
|
||||||
|
/// Frame index (NV header bytes 20-23).
|
||||||
|
pub frame_index: u32,
|
||||||
|
/// Frame type written into the frame header.
|
||||||
|
pub frame_type: FrameType,
|
||||||
|
/// RTP timestamp shared by every datagram of the frame (UNKNOWN U29: clock rate, probably 90 kHz).
|
||||||
|
pub rtp_timestamp: u32,
|
||||||
|
/// Host processing latency, frame header bytes 1-2 (unit UNKNOWN, U13).
|
||||||
|
pub processing_latency: u16,
|
||||||
|
/// The Annex-B bitstream, start codes included.
|
||||||
|
pub bitstream: &'a [u8],
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The FEC geometry of one block.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub struct FecBlock {
|
||||||
|
/// Data shards `k`.
|
||||||
|
pub data_shards: u16,
|
||||||
|
/// Parity shards `m = ceil(k × percentage / 100)`.
|
||||||
|
pub parity_shards: u16,
|
||||||
|
/// The percentage written into the block's FEC info (the receiver derives `m` from it).
|
||||||
|
pub fec_percentage: u8,
|
||||||
|
/// The requested parity (percentage and minimum count) did not fit in 255 shards and was lowered.
|
||||||
|
pub reduced: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counters.
|
||||||
|
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||||
|
pub struct VideoPacketizerStats {
|
||||||
|
/// Frames packetized.
|
||||||
|
pub frames: u64,
|
||||||
|
/// Datagrams produced (data + parity).
|
||||||
|
pub packets: u64,
|
||||||
|
/// Parity datagrams among them.
|
||||||
|
pub parity_packets: u64,
|
||||||
|
/// Blocks whose parity was lowered to fit 255 shards.
|
||||||
|
pub fec_reduced_blocks: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frame type byte of the structured frame header (`docs/PROTOCOL.md` 5.2).
|
||||||
|
const fn frame_type_byte(t: FrameType) -> u8 {
|
||||||
|
match t {
|
||||||
|
FrameType::Predicted => 1,
|
||||||
|
FrameType::Key => 2,
|
||||||
|
FrameType::Recovery => 5,
|
||||||
|
FrameType::Other(v) => v,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the 8-byte frame header in its structured form (`docs/PROTOCOL.md` 5.2): type `0x01`, processing latency
|
||||||
|
/// u16 LE, frame type, payload bytes in the last data shard u32 LE. UNKNOWN U13 (Wolf shows a constant instead) is
|
||||||
|
/// open; this is the form our client reads, and the only place to change if the capture says otherwise.
|
||||||
|
#[must_use]
|
||||||
|
pub fn write_frame_header(
|
||||||
|
frame_type: FrameType,
|
||||||
|
processing_latency: u16,
|
||||||
|
last_payload_len: u32,
|
||||||
|
) -> [u8; FRAME_HEADER_LEN] {
|
||||||
|
let [l0, l1] = processing_latency.to_le_bytes();
|
||||||
|
let [a, b, c, d] = last_payload_len.to_le_bytes();
|
||||||
|
[FRAME_HEADER_TYPE, l0, l1, frame_type_byte(frame_type), a, b, c, d]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parity of a block of `k` at percentage `p`: `ceil(k × p / 100)` (the receiver's formula, 5.3).
|
||||||
|
const fn parity_at(k: usize, p: usize) -> usize {
|
||||||
|
(k * p).div_ceil(100)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The parity the client asks for a block of `k`: the percentage's, but at least the minimum count.
|
||||||
|
fn target(k: usize, pct: u8, min: u8) -> usize {
|
||||||
|
let m = parity_at(k, usize::from(pct));
|
||||||
|
if m < usize::from(min) { usize::from(min) } else { m }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The least percentage, at or above `pct`, whose parity reaches the target, if it is an 8-bit value and keeps the
|
||||||
|
/// block within [`MAX_SHARDS`].
|
||||||
|
fn wished_percentage(k: usize, pct: u8, min: u8) -> Option<usize> {
|
||||||
|
if k == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let t = target(k, pct, min);
|
||||||
|
let p = if parity_at(k, usize::from(pct)) >= t {
|
||||||
|
usize::from(pct)
|
||||||
|
} else {
|
||||||
|
// The least p with k·p > 100·(t − 1), i.e. ceil(k·p / 100) ≥ t.
|
||||||
|
100 * (t - 1) / k + 1
|
||||||
|
};
|
||||||
|
(p <= usize::from(u8::MAX) && k + parity_at(k, p) <= MAX_SHARDS).then_some(p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The FEC geometry of one block of `k` data shards.
|
||||||
|
fn block(k: usize, pct: u8, min: u8) -> Result<FecBlock> {
|
||||||
|
let (p, reduced) = match wished_percentage(k, pct, min) {
|
||||||
|
Some(p) => (p, false),
|
||||||
|
// The most parity that fits: the largest p with k + ceil(k·p / 100) ≤ 255.
|
||||||
|
None => ((100 * MAX_SHARDS.saturating_sub(k) / k.max(1)).min(usize::from(u8::MAX)), true),
|
||||||
|
};
|
||||||
|
let to_u16 = |v: usize| u16::try_from(v).map_err(|_| malformed("video fec block"));
|
||||||
|
Ok(FecBlock {
|
||||||
|
data_shards: to_u16(k)?,
|
||||||
|
parity_shards: to_u16(parity_at(k, p))?,
|
||||||
|
fec_percentage: u8::try_from(p).map_err(|_| malformed("video fec percentage"))?,
|
||||||
|
reduced,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Splits a frame's `data_shards` into FEC blocks (`docs/PROTOCOL.md` 5.3): the fewest blocks (at most
|
||||||
|
/// [`MAX_FEC_BLOCKS`]) whose blocks can each carry the requested parity, where every block but the last carries
|
||||||
|
/// `ceil(data_shards / blocks)` data shards. Each block's percentage is the least one, at or above `fec_percentage`,
|
||||||
|
/// that gives `max(ceil(k × fec_percentage / 100), min_parity)` parity shards; when that cannot fit in
|
||||||
|
/// [`MAX_SHARDS`] shards (or an 8-bit percentage), the block gets the most parity that fits and is marked `reduced`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for 0 data shards, [`Error::TooLarge`] over [`MAX_DATA_SHARDS_PER_FRAME`].
|
||||||
|
pub fn plan_fec_blocks(data_shards: usize, fec_percentage: u8, min_parity: u8) -> Result<Vec<FecBlock>> {
|
||||||
|
if data_shards == 0 {
|
||||||
|
return Err(malformed("video frame without data shards"));
|
||||||
|
}
|
||||||
|
cap("video frame data shards", MAX_DATA_SHARDS_PER_FRAME, data_shards)?;
|
||||||
|
let blocks = (1..=MAX_FEC_BLOCKS)
|
||||||
|
.find(|&b| wished_percentage(data_shards.div_ceil(b), fec_percentage, min_parity).is_some())
|
||||||
|
.unwrap_or(MAX_FEC_BLOCKS);
|
||||||
|
let k_full = data_shards.div_ceil(blocks);
|
||||||
|
let count = data_shards.div_ceil(k_full);
|
||||||
|
let mut plan = Vec::with_capacity(count);
|
||||||
|
let mut left = data_shards;
|
||||||
|
while left > 0 {
|
||||||
|
let k = left.min(k_full);
|
||||||
|
plan.push(block(k, fec_percentage, min_parity)?);
|
||||||
|
left -= k;
|
||||||
|
}
|
||||||
|
Ok(plan)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 32 header bytes of one packet (`docs/PROTOCOL.md` 5.2).
|
||||||
|
struct Header {
|
||||||
|
sequence: u16,
|
||||||
|
timestamp: u32,
|
||||||
|
frame_index: u32,
|
||||||
|
flags: u8,
|
||||||
|
block: u8,
|
||||||
|
last_block: u8,
|
||||||
|
shard_index: u16,
|
||||||
|
data_shards: u16,
|
||||||
|
fec_percentage: u8,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Header {
|
||||||
|
fn bytes(&self) -> [u8; PAYLOAD_OFFSET] {
|
||||||
|
let fec_info = (u32::from(self.fec_percentage) << 4)
|
||||||
|
| ((u32::from(self.shard_index) & 0x3FF) << 12)
|
||||||
|
| ((u32::from(self.data_shards) & 0x3FF) << 22);
|
||||||
|
let parts: [&[u8]; 11] = [
|
||||||
|
&[VIDEO_RTP_BYTE0, 0], // RTP byte 0, payload type 0
|
||||||
|
&self.sequence.to_be_bytes(), // sequence, BE
|
||||||
|
&self.timestamp.to_be_bytes(), // timestamp, BE
|
||||||
|
&[0; 4], // SSRC 0
|
||||||
|
&[0; 4], // reserved
|
||||||
|
&(u32::from(self.sequence) << 8).to_le_bytes(), // stream packet index, LE
|
||||||
|
&self.frame_index.to_le_bytes(), // frame index, LE
|
||||||
|
&[self.flags, 0], // flags, reserved
|
||||||
|
&[MULTI_FEC_FLAGS], // multi-FEC flags (U15)
|
||||||
|
&[((self.block & 3) << 4) | ((self.last_block & 3) << 6)], // multi-FEC blocks
|
||||||
|
&fec_info.to_le_bytes(), // FEC info, LE
|
||||||
|
];
|
||||||
|
let mut out = [0u8; PAYLOAD_OFFSET];
|
||||||
|
for (dst, src) in out.iter_mut().zip(parts.iter().flat_map(|p| p.iter())) {
|
||||||
|
*dst = *src;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The video sender of one stream.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct VideoPacketizer {
|
||||||
|
config: VideoPacketizerConfig,
|
||||||
|
payload_len: usize,
|
||||||
|
next_sequence: u16,
|
||||||
|
/// Next GCM nonce counter (sealed streams only).
|
||||||
|
next_nonce: u64,
|
||||||
|
stats: VideoPacketizerStats,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VideoPacketizer {
|
||||||
|
/// A sender for one stream.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Malformed`] for a `packet_size` not above the NV header size, or one whose datagrams (sealed, when a
|
||||||
|
/// cipher is set) would not fit [`MAX_VIDEO_PACKET_BYTES`], the receiver's cap.
|
||||||
|
pub fn new(config: VideoPacketizerConfig) -> Result<Self> {
|
||||||
|
let size = usize::from(config.packet_size);
|
||||||
|
let sealed = if config.cipher.is_some() { ENCRYPTION_PREFIX_LEN } else { 0 };
|
||||||
|
if size <= NV_HEADER_LEN || size + VIDEO_RTP_LEN + sealed > MAX_VIDEO_PACKET_BYTES {
|
||||||
|
return Err(malformed("video packet_size"));
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
payload_len: size - NV_HEADER_LEN,
|
||||||
|
next_sequence: config.first_sequence,
|
||||||
|
config,
|
||||||
|
next_nonce: 0,
|
||||||
|
stats: VideoPacketizerStats::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The largest bitstream one frame can carry: [`MAX_DATA_SHARDS_PER_FRAME`] shards of payload, and the
|
||||||
|
/// receiver's [`MAX_FRAME_BYTES`], minus the frame header.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn max_bitstream_len(&self) -> usize {
|
||||||
|
let shards = MAX_DATA_SHARDS_PER_FRAME * self.payload_len;
|
||||||
|
let max = if shards < MAX_FRAME_BYTES { shards } else { MAX_FRAME_BYTES };
|
||||||
|
max - FRAME_HEADER_LEN
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Packetizes one frame into its datagrams, in send order: block 0's data shards then its parity, block 1, …
|
||||||
|
/// On error nothing changes (sequence numbers, nonce counter, stats).
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::TooLarge`] for a bitstream over [`Self::max_bitstream_len`] (checked before anything is allocated),
|
||||||
|
/// [`Error::State`] once the nonce counter of a sealed stream is exhausted (a new session key is needed).
|
||||||
|
pub fn packetize(&mut self, frame: &EncodedFrame<'_>) -> Result<Vec<Vec<u8>>> {
|
||||||
|
cap("video access unit", self.max_bitstream_len(), frame.bitstream.len())?;
|
||||||
|
let p = self.payload_len;
|
||||||
|
let data_len = FRAME_HEADER_LEN + frame.bitstream.len();
|
||||||
|
let n = data_len.div_ceil(p);
|
||||||
|
let plan = plan_fec_blocks(n, self.config.fec_percentage, self.config.min_required_fec_packets)?;
|
||||||
|
let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum();
|
||||||
|
let sealed = self.config.cipher.is_some();
|
||||||
|
if sealed && self.next_nonce.checked_add(total as u64).is_none() {
|
||||||
|
return Err(Error::State { expected: "a fresh session key (video nonce counter exhausted)" });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Frame data: header + bitstream, zero-padded to n whole shards (5.2).
|
||||||
|
let last_payload = data_len - (n - 1) * p;
|
||||||
|
let header =
|
||||||
|
write_frame_header(frame.frame_type, frame.processing_latency, u32::try_from(last_payload).unwrap_or(0));
|
||||||
|
let mut data = Vec::with_capacity(n * p);
|
||||||
|
data.extend_from_slice(&header);
|
||||||
|
data.extend_from_slice(frame.bitstream);
|
||||||
|
data.resize(n * p, 0);
|
||||||
|
|
||||||
|
let last_block = u8::try_from(plan.len() - 1).map_err(|_| malformed("video fec blocks"))?;
|
||||||
|
let mut sequence = self.next_sequence;
|
||||||
|
let mut next_header = |flags: u8, block: u8, shard_index: u16, b: &FecBlock| {
|
||||||
|
let h = Header {
|
||||||
|
sequence,
|
||||||
|
timestamp: frame.rtp_timestamp,
|
||||||
|
frame_index: frame.frame_index,
|
||||||
|
flags,
|
||||||
|
block,
|
||||||
|
last_block,
|
||||||
|
shard_index,
|
||||||
|
data_shards: b.data_shards,
|
||||||
|
fec_percentage: b.fec_percentage,
|
||||||
|
};
|
||||||
|
sequence = sequence.wrapping_add(1);
|
||||||
|
h.bytes()
|
||||||
|
};
|
||||||
|
|
||||||
|
let packet_len = PAYLOAD_OFFSET + p;
|
||||||
|
let mut out: Vec<Vec<u8>> = Vec::with_capacity(total);
|
||||||
|
let mut chunks = data.chunks(p);
|
||||||
|
let mut shard_no = 0usize;
|
||||||
|
let mut reduced = 0u64;
|
||||||
|
let mut parity_packets = 0u64;
|
||||||
|
for (bi, b) in plan.iter().enumerate() {
|
||||||
|
let block = u8::try_from(bi).map_err(|_| malformed("video fec blocks"))?;
|
||||||
|
let (k, m) = (usize::from(b.data_shards), usize::from(b.parity_shards));
|
||||||
|
reduced += u64::from(b.reduced);
|
||||||
|
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
|
||||||
|
for i in 0..k {
|
||||||
|
let mut flags = VideoFlags::PICTURE_DATA;
|
||||||
|
if shard_no == 0 {
|
||||||
|
flags |= VideoFlags::START_OF_FRAME;
|
||||||
|
}
|
||||||
|
if shard_no + 1 == n {
|
||||||
|
flags |= VideoFlags::END_OF_FRAME;
|
||||||
|
}
|
||||||
|
shard_no += 1;
|
||||||
|
let mut packet = Vec::with_capacity(packet_len);
|
||||||
|
packet.extend_from_slice(&next_header(flags, block, u16::try_from(i).unwrap_or(u16::MAX), b));
|
||||||
|
packet.extend_from_slice(chunks.next().ok_or(malformed("video frame shards"))?);
|
||||||
|
shards.push(packet);
|
||||||
|
}
|
||||||
|
if m > 0 {
|
||||||
|
// Parity over the whole data packets, headers included (5.3) ...
|
||||||
|
shards.resize_with(k + m, || vec![0u8; packet_len]);
|
||||||
|
ReedSolomon::new(k, m)?.encode(&mut shards)?;
|
||||||
|
// ... and only then the parity packets' own header fields, over their first 32 bytes.
|
||||||
|
for (j, parity) in shards.iter_mut().skip(k).enumerate() {
|
||||||
|
let h = next_header(0, block, u16::try_from(k + j).unwrap_or(u16::MAX), b);
|
||||||
|
if let Some(head) = parity.get_mut(..PAYLOAD_OFFSET) {
|
||||||
|
head.copy_from_slice(&h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
parity_packets += m as u64;
|
||||||
|
}
|
||||||
|
out.append(&mut shards);
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(cipher) = &self.config.cipher {
|
||||||
|
let mut nonce = self.next_nonce;
|
||||||
|
for packet in &mut out {
|
||||||
|
*packet = cipher.encrypt(nonce, frame.frame_index, packet)?;
|
||||||
|
nonce += 1;
|
||||||
|
}
|
||||||
|
self.next_nonce = nonce;
|
||||||
|
}
|
||||||
|
self.next_sequence = sequence;
|
||||||
|
self.stats.frames += 1;
|
||||||
|
self.stats.packets += out.len() as u64;
|
||||||
|
self.stats.parity_packets += parity_packets;
|
||||||
|
self.stats.fec_reduced_blocks += reduced;
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The RTP sequence number of the next datagram.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn next_sequence(&self) -> u16 {
|
||||||
|
self.next_sequence
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Counters.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn stats(&self) -> VideoPacketizerStats {
|
||||||
|
self.stats
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,293 @@
|
|||||||
|
//! "Caps every length before it allocates": with a counting global allocator (`peak_alloc`, no unsafe code of
|
||||||
|
//! ours), feeds every parser small inputs whose length fields lie (claim gigabytes) and arbitrary inputs, and checks
|
||||||
|
//! the peak heap growth stays within a bound tied to the input and the parser's caps, never to a claimed length.
|
||||||
|
//!
|
||||||
|
//! The counters are process-wide, so this file holds exactly one #[test] that runs everything in sequence.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use domistream::{Instant, SessionKeys};
|
||||||
|
use peak_alloc::PeakAlloc;
|
||||||
|
use proptest::prelude::*;
|
||||||
|
use proptest::test_runner::{Config, TestRunner};
|
||||||
|
|
||||||
|
#[global_allocator]
|
||||||
|
static ALLOC: PeakAlloc = PeakAlloc;
|
||||||
|
|
||||||
|
/// Heap bytes `f` needs at its peak, beyond what was in use when it started.
|
||||||
|
fn peak_of<R>(f: impl FnOnce() -> R) -> usize {
|
||||||
|
ALLOC.reset_peak_usage();
|
||||||
|
let before = ALLOC.current_usage();
|
||||||
|
let r = f();
|
||||||
|
let peak = ALLOC.peak_usage();
|
||||||
|
drop(r);
|
||||||
|
peak.saturating_sub(before)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The budget for a parser given `input` bytes: its output may be a few times the input, plus fixed slack. A parser
|
||||||
|
/// that trusts a lying length field blows far past this.
|
||||||
|
fn budget(input: usize) -> usize {
|
||||||
|
64 * input + 256 * 1024
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check(what: &str, input: &[u8], f: impl FnOnce(&[u8]) -> bool) {
|
||||||
|
let mut ran = false;
|
||||||
|
let used = peak_of(|| ran = f(input));
|
||||||
|
assert!(ran, "{what}: Unimplemented, so its allocation is not measured yet");
|
||||||
|
assert!(
|
||||||
|
used <= budget(input.len()),
|
||||||
|
"{what}: {used} bytes at peak for a {}-byte input (budget {})",
|
||||||
|
input.len(),
|
||||||
|
budget(input.len())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A parser under test: a name and a call that consumes the input.
|
||||||
|
type Parser = (&'static str, fn(&[u8]) -> bool);
|
||||||
|
/// A parser and the hostile input for it.
|
||||||
|
type Case = (&'static str, Vec<u8>, fn(&[u8]) -> bool);
|
||||||
|
|
||||||
|
fn lying_inputs() -> Vec<Case> {
|
||||||
|
let mut v: Vec<Case> = Vec::new();
|
||||||
|
|
||||||
|
// RTSP: Content-Length claims 4 GiB.
|
||||||
|
let rtsp = b"RTSP/1.0 200 OK\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec();
|
||||||
|
v.push(("rtsp response", rtsp.clone(), |b| common::implemented(&domistream::rtsp::parse_response(b))));
|
||||||
|
v.push((
|
||||||
|
"rtsp request",
|
||||||
|
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||||
|
|b| common::implemented(&domistream::rtsp::parse_request(b)),
|
||||||
|
));
|
||||||
|
v.push((
|
||||||
|
"rtsp server",
|
||||||
|
b"ANNOUNCE x RTSP/1.0\r\nCSeq: 1\r\nContent-Length: 4294967295\r\n\r\nabc".to_vec(),
|
||||||
|
rtsp_server_answers,
|
||||||
|
));
|
||||||
|
// ANNOUNCE: a number far past any range, then more unknown attributes than the cap allows.
|
||||||
|
let mut announce = b"a=x-nv-video[0].clientViewportWd:99999999999999999999999999999999\n".to_vec();
|
||||||
|
announce.extend_from_slice(&b"a=u:1\n".repeat(600));
|
||||||
|
v.push(("announce", announce, |b| common::implemented(&domistream::rtsp::server::parse_announce(b))));
|
||||||
|
v.push(("rtsp framer", rtsp, |b| {
|
||||||
|
let mut f = domistream::rtsp::RtspFramer::new();
|
||||||
|
let pushed = f.push(b);
|
||||||
|
let next = f.next_message();
|
||||||
|
let finished = f.finish();
|
||||||
|
common::implemented(&pushed) && common::implemented(&next) && common::implemented(&finished)
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ENet: data length 65535 with 3 bytes, fragment claiming 4 GiB and 4 billion fragments.
|
||||||
|
v.push(("enet reliable", vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1, 2, 3], |b| {
|
||||||
|
common::implemented(&domistream::enet::protocol::parse_datagram(b))
|
||||||
|
}));
|
||||||
|
let mut frag = vec![0x00, 0x01, 0x88, 0x00, 0x00, 0x01];
|
||||||
|
frag.extend_from_slice(&1u16.to_be_bytes()); // start sequence
|
||||||
|
frag.extend_from_slice(&10u16.to_be_bytes()); // data length
|
||||||
|
frag.extend_from_slice(&u32::MAX.to_be_bytes()); // fragment count
|
||||||
|
frag.extend_from_slice(&0u32.to_be_bytes()); // fragment number
|
||||||
|
frag.extend_from_slice(&u32::MAX.to_be_bytes()); // total length
|
||||||
|
frag.extend_from_slice(&0u32.to_be_bytes()); // offset
|
||||||
|
frag.extend_from_slice(&[0; 10]);
|
||||||
|
v.push(("enet fragment", frag, |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))));
|
||||||
|
|
||||||
|
// Control: frame and message length fields at 65535.
|
||||||
|
let mut frame = vec![0x01, 0x00, 0xFF, 0xFF, 0, 0, 0, 0];
|
||||||
|
frame.extend_from_slice(&[0; 16 + 8]);
|
||||||
|
v.push(("control frame", frame.clone(), |b| common::implemented(&domistream::control::parse_encrypted_frame(b))));
|
||||||
|
v.push(("control open", frame, |b| {
|
||||||
|
common::implemented(
|
||||||
|
&domistream::control::ControlCipher::new([1; 16]).open(domistream::control::Direction::HostToClient, b),
|
||||||
|
)
|
||||||
|
}));
|
||||||
|
v.push(("control message", vec![0x0b, 0x01, 0xFF, 0xFF, 1, 2], |b| {
|
||||||
|
common::implemented(&domistream::control::parse_host_message(b))
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Input: size field u32::MAX, length 65535.
|
||||||
|
v.push(("input", vec![0x06, 0x02, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0, 0, 0, 1, 2], |b| {
|
||||||
|
common::implemented(&domistream::input::parse_input(b))
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Video: 1023 data shards, frame header claiming a 4 GiB last payload.
|
||||||
|
let p = common::video_packet_bytes(1, 0, 0, 0x05, 0, common::fec_info(200, 0, 1023), &[0xFF; 48]);
|
||||||
|
v.push(("video packet", p.clone(), |b| common::implemented(&domistream::video::parse_video_packet(b))));
|
||||||
|
v.push(("frame header", vec![1, 0, 0, 2, 0xFF, 0xFF, 0xFF, 0xFF], |b| {
|
||||||
|
common::implemented(&domistream::video::packet::parse_frame_header(b))
|
||||||
|
}));
|
||||||
|
|
||||||
|
// Audio, XML, PEM, DER with lying lengths.
|
||||||
|
v.push((
|
||||||
|
"audio packet",
|
||||||
|
vec![0x80, 127, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
|
||||||
|
|b| common::implemented(&domistream::audio::parse_audio_packet(b)),
|
||||||
|
));
|
||||||
|
v.push(("xml", b"<root status_code=\"200\"><a>�</a></root>".to_vec(), |b| {
|
||||||
|
common::implemented(&domistream::http::xml::parse(b))
|
||||||
|
}));
|
||||||
|
let mut der = vec![0x30, 0x84, 0xFF, 0xFF, 0xFF, 0xFF];
|
||||||
|
der.extend_from_slice(&[0x30; 20]);
|
||||||
|
v.push(("server cert der", der.clone(), |b| common::implemented(&domistream::pairing::ServerCert::from_der(b))));
|
||||||
|
v.push(("client identity der", der, |b| common::implemented(&domistream::pairing::ClientIdentity::from_der(b, b))));
|
||||||
|
v.push(("pem", b"-----BEGIN CERTIFICATE-----\nMIT/////\n-----END CERTIFICATE-----\n".to_vec(), |b| {
|
||||||
|
common::implemented(&domistream::pairing::ServerCert::from_pem(b))
|
||||||
|
}));
|
||||||
|
v.push(("pairing secret", vec![0; 17], |b| {
|
||||||
|
common::implemented(&domistream::pairing::crypto::split_pairing_secret(b))
|
||||||
|
}));
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fresh host RTSP session answers `b`; false only for an `Unimplemented` answer.
|
||||||
|
fn rtsp_server_answers(b: &[u8]) -> bool {
|
||||||
|
let config = domistream::rtsp::ServerConfig {
|
||||||
|
ports: domistream::rtsp::StreamPorts { audio: 48000, video: 47998, control: 47999 },
|
||||||
|
offer: domistream::rtsp::HostOffer {
|
||||||
|
feature_flags: domistream::rtsp::sdp::FeatureFlags(3),
|
||||||
|
encryption_supported: domistream::rtsp::EncryptionFlags(7),
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
h264: true,
|
||||||
|
hevc: true,
|
||||||
|
av1: true,
|
||||||
|
hdr: false,
|
||||||
|
yuv444: false,
|
||||||
|
opus_configs: vec![domistream::rtsp::OpusConfig::stereo()],
|
||||||
|
},
|
||||||
|
required_encryption: domistream::rtsp::EncryptionFlags(1),
|
||||||
|
require_session_header: false,
|
||||||
|
session_timeout_secs: 90,
|
||||||
|
};
|
||||||
|
let Ok(mut s) = domistream::rtsp::RtspServer::new(config, &mut common::SeqRng::new(3)) else { return false };
|
||||||
|
s.handle_request(b).error != Some(domistream::Error::Unimplemented)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stateful receivers: the bound is their caps (frames or blocks in flight), never a claimed size.
|
||||||
|
fn depacketizer_checks() {
|
||||||
|
use domistream::video::{MAX_FRAME_BYTES, MAX_FRAMES_IN_FLIGHT, VideoConfig, VideoDepacketizer};
|
||||||
|
let cap = MAX_FRAMES_IN_FLIGHT * MAX_FRAME_BYTES + 1024 * 1024;
|
||||||
|
let used = peak_of(|| {
|
||||||
|
let mut d = VideoDepacketizer::new(VideoConfig {
|
||||||
|
packet_size: 1024,
|
||||||
|
cipher: None,
|
||||||
|
frame_timeout: core::time::Duration::from_millis(50),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
// One packet each of many frames that each announce 4 blocks of 255 shards.
|
||||||
|
for frame in 0..64u32 {
|
||||||
|
let mut p = common::video_packet_bytes(
|
||||||
|
frame as u16,
|
||||||
|
0,
|
||||||
|
frame,
|
||||||
|
0x05,
|
||||||
|
3 << 6,
|
||||||
|
common::fec_info(0, 0, 255),
|
||||||
|
&[0xAB; 1024 - 16],
|
||||||
|
);
|
||||||
|
p.resize(1024 + 16, 0);
|
||||||
|
let _ = d.push(Instant::ZERO, &p);
|
||||||
|
}
|
||||||
|
d
|
||||||
|
});
|
||||||
|
assert!(used <= cap, "video depacketizer: {used} bytes at peak (cap {cap})");
|
||||||
|
|
||||||
|
use domistream::audio::{AudioConfig, AudioDepacketizer, AudioFec, MAX_BLOCKS_IN_FLIGHT};
|
||||||
|
let cap = MAX_BLOCKS_IN_FLIGHT * 6 * domistream::audio::packet::MAX_AUDIO_PACKET_BYTES + 256 * 1024;
|
||||||
|
let used = peak_of(|| {
|
||||||
|
let mut d = AudioDepacketizer::new(AudioConfig {
|
||||||
|
cipher: Some(domistream::audio::AudioCipher::new(&SessionKeys { rikey: [1; 16], rikeyid: 0 })),
|
||||||
|
packet_duration_ms: 5,
|
||||||
|
fec: AudioFec::ParityMatrix(common::audio_test_matrix()),
|
||||||
|
loss_timeout: core::time::Duration::from_millis(40),
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
for seq in (0..2000u16).step_by(13) {
|
||||||
|
let mut p = vec![0x80, 97];
|
||||||
|
p.extend_from_slice(&seq.wrapping_mul(97).to_be_bytes());
|
||||||
|
p.extend_from_slice(&[0; 8]);
|
||||||
|
p.extend_from_slice(&[0x11; 2000]);
|
||||||
|
let _ = d.push(Instant::ZERO, &p);
|
||||||
|
}
|
||||||
|
d
|
||||||
|
});
|
||||||
|
assert!(used <= cap, "audio depacketizer: {used} bytes at peak (cap {cap})");
|
||||||
|
|
||||||
|
use domistream::enet::{EnetClient, EnetConfig, MAX_PACKET_BYTES};
|
||||||
|
let used = peak_of(|| {
|
||||||
|
let cfg = EnetConfig {
|
||||||
|
channel_count: 2,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: core::time::Duration::from_millis(500),
|
||||||
|
timeout: core::time::Duration::from_secs(10),
|
||||||
|
};
|
||||||
|
let mut c = EnetClient::connect(cfg, Instant::ZERO, &mut common::SeqRng::new(1)).unwrap();
|
||||||
|
// Fragments of 4 billion pieces and gigabyte totals, addressed to every peer id.
|
||||||
|
for peer in 0..64u16 {
|
||||||
|
let mut d = peer.to_be_bytes().to_vec();
|
||||||
|
d.extend_from_slice(&[0x88, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x04]);
|
||||||
|
d.extend_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
d.extend_from_slice(&7u32.to_be_bytes());
|
||||||
|
d.extend_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
d.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
d.extend_from_slice(&[1, 2, 3, 4]);
|
||||||
|
let _ = c.handle_datagram(Instant::ZERO, &d);
|
||||||
|
}
|
||||||
|
c
|
||||||
|
});
|
||||||
|
assert!(used <= 4 * MAX_PACKET_BYTES + 256 * 1024, "enet client: {used} bytes at peak");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parsers_never_allocate_past_their_caps() {
|
||||||
|
for (what, input, f) in lying_inputs() {
|
||||||
|
check(what, &input, f);
|
||||||
|
}
|
||||||
|
depacketizer_checks();
|
||||||
|
|
||||||
|
// Arbitrary inputs to every stateless parser.
|
||||||
|
let mut runner = TestRunner::new(Config { cases: 400, ..Config::default() });
|
||||||
|
let parsers: Vec<Parser> = vec![
|
||||||
|
("xml", |b| common::implemented(&domistream::http::xml::parse(b))),
|
||||||
|
("serverinfo", |b| common::implemented(&domistream::http::parse_server_info(b))),
|
||||||
|
("applist", |b| common::implemented(&domistream::http::parse_app_list(b))),
|
||||||
|
("launch", |b| common::implemented(&domistream::http::parse_launch_response(b))),
|
||||||
|
("pair response", |b| common::implemented(&domistream::pairing::parse_pair_response(b))),
|
||||||
|
("pem", |b| common::implemented(&domistream::pairing::ServerCert::from_pem(b))),
|
||||||
|
("der", |b| common::implemented(&domistream::pairing::ServerCert::from_der(b))),
|
||||||
|
("rtsp response", |b| common::implemented(&domistream::rtsp::parse_response(b))),
|
||||||
|
("rtsp request", |b| common::implemented(&domistream::rtsp::parse_request(b))),
|
||||||
|
("sdp", |b| common::implemented(&domistream::rtsp::sdp::parse_sdp(b))),
|
||||||
|
("announce", |b| common::implemented(&domistream::rtsp::server::parse_announce(b))),
|
||||||
|
("rtsp server", rtsp_server_answers),
|
||||||
|
("enet", |b| common::implemented(&domistream::enet::protocol::parse_datagram(b))),
|
||||||
|
("control frame", |b| common::implemented(&domistream::control::parse_encrypted_frame(b))),
|
||||||
|
("control message", |b| common::implemented(&domistream::control::parse_host_message(b))),
|
||||||
|
("input", |b| common::implemented(&domistream::input::parse_input(b))),
|
||||||
|
("rtp", |b| common::implemented(&domistream::rtp::parse_rtp_header(b))),
|
||||||
|
("video", |b| common::implemented(&domistream::video::parse_video_packet(b))),
|
||||||
|
("audio", |b| common::implemented(&domistream::audio::parse_audio_packet(b))),
|
||||||
|
("video decrypt", |b| common::implemented(&domistream::video::VideoCipher::new([2; 16]).decrypt(b))),
|
||||||
|
("audio decrypt", |b| {
|
||||||
|
common::implemented(
|
||||||
|
&domistream::audio::AudioCipher::new(&SessionKeys { rikey: [2; 16], rikeyid: 0 }).decrypt(0, b),
|
||||||
|
)
|
||||||
|
}),
|
||||||
|
];
|
||||||
|
for (what, f) in parsers {
|
||||||
|
runner
|
||||||
|
.run(&proptest::collection::vec(any::<u8>(), 0..1500), |data| {
|
||||||
|
let mut ran = false;
|
||||||
|
let used = peak_of(|| ran = f(&data));
|
||||||
|
prop_assert!(ran, "{}: Unimplemented", what);
|
||||||
|
prop_assert!(
|
||||||
|
used <= budget(data.len()),
|
||||||
|
"{}: {} bytes at peak for {} input bytes",
|
||||||
|
what,
|
||||||
|
used,
|
||||||
|
data.len()
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
})
|
||||||
|
.unwrap_or_else(|e| panic!("{what}: {e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,423 @@
|
|||||||
|
//! The audio depacketizer (`docs/PROTOCOL.md` 6): blocks of 4 data + 2 parity packets with a parity matrix passed
|
||||||
|
//! through the `AudioFec::ParityMatrix` hook (U16 is unmeasured, so any MDS matrix must work; the tests use a
|
||||||
|
//! Cauchy matrix and a second one), AES-128-CBC payloads, every loss pattern of a block, sequence wrap, duplicates,
|
||||||
|
//! reordering, far-past and far-future packets.
|
||||||
|
//!
|
||||||
|
//! Reading of PROTOCOL.md 6.2: a parity packet's RTP sequence "continues after the 4 data packets" (base + 4 +
|
||||||
|
//! shard), which overlaps the next block's data sequence numbers; the receiver must key parity by the FEC header's
|
||||||
|
//! base sequence and the payload type, never by the parity packet's RTP sequence.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use common::{AExpect, APkt, AudioHost, SeqRng, audio_test_matrix, subsets_of};
|
||||||
|
use domistream::audio::packet::MAX_AUDIO_PACKET_BYTES;
|
||||||
|
use domistream::audio::{AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioStats};
|
||||||
|
use domistream::{Error, Instant, SessionKeys};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"audio-test-key!!";
|
||||||
|
const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests
|
||||||
|
const DURATION: u32 = 5;
|
||||||
|
|
||||||
|
fn host(encrypt: bool, matrix: [u8; 8]) -> AudioHost {
|
||||||
|
AudioHost { key: KEY, rikeyid: RIKEYID, encrypt, matrix, duration_ms: DURATION, opus_len: 37 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config(encrypt: bool, fec: AudioFec) -> AudioConfig {
|
||||||
|
AudioConfig {
|
||||||
|
cipher: encrypt.then(|| AudioCipher::new(&SessionKeys { rikey: KEY, rikeyid: RIKEYID })),
|
||||||
|
packet_duration_ms: DURATION as u8,
|
||||||
|
fec,
|
||||||
|
loss_timeout: Duration::from_millis(40),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Run {
|
||||||
|
events: Vec<AudioEvent>,
|
||||||
|
stats: AudioStats,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(cfg: AudioConfig, datagrams: &[Vec<u8>]) -> Run {
|
||||||
|
let mut d = AudioDepacketizer::new(cfg).expect("AudioDepacketizer::new");
|
||||||
|
let mut now = 1_000_000u64;
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for g in datagrams {
|
||||||
|
d.push(Instant::from_micros(now), g).expect("push never fails within the size cap");
|
||||||
|
now += 10;
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _ in 0..64 {
|
||||||
|
now += 10_000_000;
|
||||||
|
d.handle_timeout(Instant::from_micros(now)).unwrap();
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
if d.poll_timeout().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Run { events, stats: d.stats() }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Want {
|
||||||
|
/// Arrived as sent.
|
||||||
|
Packet,
|
||||||
|
/// Lost and rebuilt by FEC.
|
||||||
|
Recovered,
|
||||||
|
/// Gone: reported lost.
|
||||||
|
Lost,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every data sequence number gets exactly one event, in stream order; packets are byte-exact with the right
|
||||||
|
/// timestamp; `recovered` is set exactly for rebuilt ones.
|
||||||
|
fn check(expect: &[AExpect], want: &[Want], r: &Run) {
|
||||||
|
let pos: HashMap<u16, usize> = expect.iter().enumerate().map(|(i, e)| (e.sequence, i)).collect();
|
||||||
|
let mut seen = vec![false; expect.len()];
|
||||||
|
let mut prev: Option<usize> = None;
|
||||||
|
for e in &r.events {
|
||||||
|
let (seq, i) = match e {
|
||||||
|
AudioEvent::Packet { sequence, .. } | AudioEvent::Lost { sequence } => (
|
||||||
|
*sequence,
|
||||||
|
*pos.get(sequence)
|
||||||
|
.unwrap_or_else(|| panic!("event for sequence {sequence} that was never a data packet")),
|
||||||
|
),
|
||||||
|
};
|
||||||
|
assert!(!seen[i], "two events for sequence {seq}");
|
||||||
|
assert!(prev.is_none_or(|p| i > p), "sequence {seq} out of order");
|
||||||
|
prev = Some(i);
|
||||||
|
seen[i] = true;
|
||||||
|
match (e, want[i]) {
|
||||||
|
(AudioEvent::Packet { timestamp_ms, opus, recovered, .. }, Want::Packet | Want::Recovered) => {
|
||||||
|
assert_eq!(opus, &expect[i].opus, "sequence {seq} corrupt");
|
||||||
|
assert_eq!(*timestamp_ms, expect[i].timestamp_ms, "sequence {seq} timestamp");
|
||||||
|
assert_eq!(*recovered, want[i] == Want::Recovered, "sequence {seq} recovered flag");
|
||||||
|
}
|
||||||
|
(AudioEvent::Lost { .. }, Want::Lost) => {}
|
||||||
|
(got, w) => panic!("sequence {seq}: want {w:?}, got {got:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i, s) in seen.iter().enumerate() {
|
||||||
|
assert!(s, "no event for sequence {} (want {:?})", expect[i].sequence, want[i]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What must come out of a block, given which of its 6 packets arrived.
|
||||||
|
fn block_want(arrived: &[bool; 6], fec: bool) -> [Want; 4] {
|
||||||
|
let count = arrived.iter().filter(|a| **a).count();
|
||||||
|
let mut w = [Want::Packet; 4];
|
||||||
|
for (i, slot) in w.iter_mut().enumerate() {
|
||||||
|
if !arrived[i] {
|
||||||
|
*slot = if fec && count >= 4 { Want::Recovered } else { Want::Lost };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
w
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Blocks `1..blocks-1` lose what `lose(block, index)` says; the first and last blocks arrive whole.
|
||||||
|
fn scenario(
|
||||||
|
h: &AudioHost,
|
||||||
|
seed: u64,
|
||||||
|
first_seq: u16,
|
||||||
|
blocks: usize,
|
||||||
|
fec: bool,
|
||||||
|
lose: impl Fn(usize, usize) -> bool,
|
||||||
|
) -> (Vec<AExpect>, Vec<Want>, Vec<Vec<u8>>) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, first_seq, 0x7000_0000, blocks);
|
||||||
|
let mut want = Vec::new();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for b in 0..blocks {
|
||||||
|
let mut arrived = [true; 6];
|
||||||
|
for p in packets.iter().filter(|p| p.block == b) {
|
||||||
|
if b != 0 && b + 1 != blocks && lose(b, p.index) {
|
||||||
|
arrived[p.index] = false;
|
||||||
|
} else {
|
||||||
|
datagrams.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
want.extend(block_want(&arrived, fec));
|
||||||
|
}
|
||||||
|
(expect, want, datagrams)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ every pattern
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_loss_pattern_of_a_block() {
|
||||||
|
// All 64 subsets of the 6 packets lost in the middle block, encrypted, with the Cauchy matrix.
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for size in 0..=6 {
|
||||||
|
for lost in subsets_of(6, size) {
|
||||||
|
let (expect, want, dg) = scenario(&h, 1, 0, 3, true, |b, i| b == 1 && lost.contains(&i));
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_loss_pattern_plaintext_and_another_matrix() {
|
||||||
|
// A second MDS matrix (rows 1,1,1,1 and 1,2,4,8) and no encryption.
|
||||||
|
let m = [1, 1, 1, 1, 1, 2, 4, 8];
|
||||||
|
let h = host(false, m);
|
||||||
|
for size in 0..=6 {
|
||||||
|
for lost in subsets_of(6, size) {
|
||||||
|
let (expect, want, dg) = scenario(&h, 2, 400, 3, true, |b, i| b == 1 && lost.contains(&i));
|
||||||
|
check(&expect, &want, &run(config(false, AudioFec::ParityMatrix(m)), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fec_disabled_reports_losses() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for lost in [vec![0usize], vec![3], vec![1, 2], vec![0, 4, 5]] {
|
||||||
|
let (expect, want, dg) = scenario(&h, 3, 8, 3, false, |b, i| b == 1 && lost.contains(&i));
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::Disabled), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_losses_over_many_blocks() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for (seed, pct) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50)] {
|
||||||
|
let mut rng = SeqRng::new(seed * 31);
|
||||||
|
let mask: Vec<bool> = (0..60 * 6).map(|_| rng.below(100) < pct).collect();
|
||||||
|
let (expect, want, dg) = scenario(&h, seed, 0, 60, true, |b, i| mask[b * 6 + i]);
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
|
||||||
|
check(&expect, &want, &r);
|
||||||
|
assert_eq!(r.stats.recovered, want.iter().filter(|w| **w == Want::Recovered).count() as u64);
|
||||||
|
assert_eq!(r.stats.lost, want.iter().filter(|w| **w == Want::Lost).count() as u64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ order and strays
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sequence_wraps() {
|
||||||
|
// Blocks from 0xFFF0 through 0x000F: data sequence 0xFFFF -> 0, base sequence wrap, rikeyid + seq wrap.
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let (expect, want, dg) = scenario(&h, 20, 0xFFF0, 8, true, |b, i| (b + i).is_multiple_of(5));
|
||||||
|
assert!(expect.iter().any(|e| e.sequence == 0xFFFF) && expect.iter().any(|e| e.sequence == 0));
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicates_are_dropped() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let (expect, want, dg) = scenario(&h, 21, 0, 10, true, |b, i| (b * 7 + i).is_multiple_of(6));
|
||||||
|
let doubled: Vec<Vec<u8>> = dg.iter().flat_map(|g| [g.clone(), g.clone()]).collect();
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &doubled);
|
||||||
|
check(&expect, &want, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= dg.len() as u64 / 2, "{:?}", r.stats);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered_within_and_across_blocks() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
for seed in 30..36u64 {
|
||||||
|
let (expect, want, mut dg) = scenario(&h, seed, 0, 12, true, |b, i| (b + i + seed as usize).is_multiple_of(7));
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut i = 6; // the first block stays first, so the stream has a known start
|
||||||
|
while i < dg.len() {
|
||||||
|
let end = (i + 9).min(dg.len());
|
||||||
|
rng.shuffle(&mut dg[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn far_past_and_far_future() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(40);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 1000, 0, 6);
|
||||||
|
let (old, _) = h.blocks(&mut SeqRng::new(41), 1000u16.wrapping_sub(400), 0, 1);
|
||||||
|
let (future, _) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1);
|
||||||
|
let mut dg: Vec<Vec<u8>> = packets.iter().filter(|p| p.block < 3).map(|p| p.bytes.clone()).collect();
|
||||||
|
dg.extend(old.iter().map(|p| p.bytes.clone()));
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block < 2).map(|p| p.bytes.clone())); // replays
|
||||||
|
dg.extend(future.iter().take(1).map(|p| p.bytes.clone()));
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block >= 3).map(|p| p.bytes.clone()));
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
|
||||||
|
assert!(r.stats.packets_dropped >= 6 + 12, "far-past block and replays dropped: {:?}", r.stats);
|
||||||
|
// No event is ever a corrupt packet, the far-past block never comes out, and the first blocks do, in order.
|
||||||
|
// (Whether the lone far-future packet is played or dropped is the receiver's choice.)
|
||||||
|
let (_, future_expect) = h.blocks(&mut SeqRng::new(42), 1000u16.wrapping_add(20_000), 0, 1);
|
||||||
|
let by_seq: HashMap<u16, &AExpect> = expect.iter().chain(&future_expect[..1]).map(|e| (e.sequence, e)).collect();
|
||||||
|
let mut first_blocks = 0;
|
||||||
|
for e in &r.events {
|
||||||
|
if let AudioEvent::Packet { sequence, opus, .. } = e {
|
||||||
|
assert!(!(600..604).contains(sequence), "far-past sequence {sequence} played");
|
||||||
|
let want = by_seq
|
||||||
|
.get(sequence)
|
||||||
|
.unwrap_or_else(|| panic!("a packet for sequence {sequence} that only strays carried"));
|
||||||
|
assert_eq!(opus, &want.opus);
|
||||||
|
if (1000..1012).contains(sequence) {
|
||||||
|
first_blocks += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(first_blocks, 12);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parity_of(packets: &[APkt], block: usize, index: usize) -> Vec<u8> {
|
||||||
|
packets.iter().find(|p| p.block == block && p.index == index).unwrap().bytes.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_parity_never_corrupts() {
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(50);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 0, 0, 3);
|
||||||
|
let mut hostile = Vec::new();
|
||||||
|
// Parity for block 1 with a base sequence that is not a multiple of 4.
|
||||||
|
let mut p = parity_of(&packets, 1, 4);
|
||||||
|
p[14..16].copy_from_slice(&5u16.to_be_bytes());
|
||||||
|
hostile.push(p);
|
||||||
|
// Parity shorter than the data shards.
|
||||||
|
let mut p = parity_of(&packets, 1, 5);
|
||||||
|
p.truncate(p.len() - 16);
|
||||||
|
hostile.push(p);
|
||||||
|
// Parity claiming to protect another payload type.
|
||||||
|
let mut p = parity_of(&packets, 1, 4);
|
||||||
|
p[13] = 96;
|
||||||
|
hostile.push(p);
|
||||||
|
// Block 1 loses data 0 and 1; only the hostile parity (and nothing else) is offered for it.
|
||||||
|
let mut dg: Vec<Vec<u8>> = packets.iter().filter(|p| p.block == 0).map(|p| p.bytes.clone()).collect();
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block == 1 && (2..4).contains(&p.index)).map(|p| p.bytes.clone()));
|
||||||
|
dg.extend(hostile);
|
||||||
|
dg.extend(packets.iter().filter(|p| p.block == 2).map(|p| p.bytes.clone()));
|
||||||
|
let mut want = vec![Want::Packet; 12];
|
||||||
|
want[4] = Want::Lost;
|
||||||
|
want[5] = Want::Lost;
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn undecryptable_data_is_dropped_and_rebuilt() {
|
||||||
|
// Copies of a data packet with a ciphertext of a wrong length or no payload: dropped, never output, and the
|
||||||
|
// packet is rebuilt from the rest of its block.
|
||||||
|
let h = host(true, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(60);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 0, 0, 3);
|
||||||
|
let mut dg: Vec<Vec<u8>> = Vec::new();
|
||||||
|
for p in &packets {
|
||||||
|
if p.block == 1 && p.index == 2 {
|
||||||
|
let mut empty = p.bytes.clone();
|
||||||
|
empty.truncate(12);
|
||||||
|
dg.push(empty);
|
||||||
|
let mut odd = p.bytes.clone();
|
||||||
|
odd.pop();
|
||||||
|
dg.push(odd);
|
||||||
|
} else {
|
||||||
|
dg.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut want = vec![Want::Packet; 12];
|
||||||
|
want[6] = Want::Recovered;
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg);
|
||||||
|
check(&expect, &want, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ API edges
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_refusals() {
|
||||||
|
assert_err!(
|
||||||
|
AudioDepacketizer::new(AudioConfig { packet_duration_ms: 0, ..config(true, AudioFec::Disabled) }),
|
||||||
|
Error::Malformed { .. }
|
||||||
|
);
|
||||||
|
let mut zero = audio_test_matrix();
|
||||||
|
zero[5] = 0;
|
||||||
|
for bad in [zero, [1; 8], [1, 2, 3, 4, 2, 4, 6, 8], [0; 8]] {
|
||||||
|
assert_err!(
|
||||||
|
AudioDepacketizer::new(config(true, AudioFec::ParityMatrix(bad))),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{bad:?} is not MDS"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(AudioDepacketizer::new(config(false, AudioFec::ParityMatrix(audio_test_matrix()))).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn push_sizes() {
|
||||||
|
let mut d = AudioDepacketizer::new(config(true, AudioFec::Disabled)).unwrap();
|
||||||
|
assert_too_large!(
|
||||||
|
d.push(Instant::ZERO, &vec![0x80; MAX_AUDIO_PACKET_BYTES + 1]),
|
||||||
|
MAX_AUDIO_PACKET_BYTES,
|
||||||
|
MAX_AUDIO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(d.push(Instant::ZERO, &vec![0x80; 1 << 20]), MAX_AUDIO_PACKET_BYTES, 1 << 20);
|
||||||
|
for g in [
|
||||||
|
vec![],
|
||||||
|
vec![0x80],
|
||||||
|
vec![0x80, 97, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
|
||||||
|
vec![0xFF; 40],
|
||||||
|
vec![0x80; MAX_AUDIO_PACKET_BYTES],
|
||||||
|
] {
|
||||||
|
assert_eq!(d.push(Instant::ZERO, &g), Ok(()));
|
||||||
|
}
|
||||||
|
assert_eq!(d.stats().packets_dropped, 5);
|
||||||
|
assert_eq!(d.poll_event(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_missing_packet_waits_for_the_loss_timeout() {
|
||||||
|
let h = host(false, audio_test_matrix());
|
||||||
|
let mut rng = SeqRng::new(70);
|
||||||
|
let (packets, expect) = h.blocks(&mut rng, 0, 0, 2);
|
||||||
|
let mut d = AudioDepacketizer::new(config(false, AudioFec::Disabled)).unwrap();
|
||||||
|
let t = Instant::from_micros(3_000_000);
|
||||||
|
// Data 0 and 2 of block 0: 0 comes out, 1 is missing, 2 waits behind it.
|
||||||
|
d.push(t, &packets[0].bytes).unwrap();
|
||||||
|
d.push(t, &packets[2].bytes).unwrap();
|
||||||
|
assert!(matches!(d.poll_event(), Some(AudioEvent::Packet { sequence: 0, .. })));
|
||||||
|
assert_eq!(d.poll_event(), None, "sequence 2 waits for 1");
|
||||||
|
let deadline = d.poll_timeout().expect("a deadline for sequence 1");
|
||||||
|
assert!(deadline > t && deadline <= t.saturating_add(Duration::from_millis(40)));
|
||||||
|
d.handle_timeout(t.saturating_add(Duration::from_millis(39))).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), None, "not before the loss timeout");
|
||||||
|
d.handle_timeout(t.saturating_add(Duration::from_millis(40))).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), Some(AudioEvent::Lost { sequence: 1 }));
|
||||||
|
match d.poll_event() {
|
||||||
|
Some(AudioEvent::Packet { sequence: 2, opus, recovered: false, .. }) => assert_eq!(opus, expect[2].opus),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Random loss masks and reordering over random lengths: exact, rebuilt or lost, never corrupt.
|
||||||
|
#[test]
|
||||||
|
fn generated_patterns(seed in any::<u64>(), first in 0u16..16_384, loss in 0usize..50, opus_len in 1usize..120) {
|
||||||
|
let mut h = host(true, audio_test_matrix());
|
||||||
|
h.opus_len = opus_len;
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mask: Vec<bool> = (0..20 * 6).map(|_| rng.below(100) < loss).collect();
|
||||||
|
let (expect, want, mut dg) = scenario(&h, seed, first * 4, 20, true, |b, i| mask[b * 6 + i]);
|
||||||
|
let mut i = 6;
|
||||||
|
while i < dg.len() {
|
||||||
|
let end = (i + 1 + rng.below(8)).min(dg.len());
|
||||||
|
rng.shuffle(&mut dg[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&expect, &want, &run(config(true, AudioFec::ParityMatrix(h.matrix)), &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..80), 0..60)) {
|
||||||
|
let r = run(config(true, AudioFec::ParityMatrix(audio_test_matrix())), &datagrams);
|
||||||
|
prop_assert!(r.events.len() <= datagrams.len() * 4 + 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,261 @@
|
|||||||
|
//! The audio packetizer, host side (`docs/PROTOCOL.md` 6.2, 6.3), checked against the client half: Opus packets
|
||||||
|
//! go through the crate's own `AudioDepacketizer` with the session keys and must come out identical, in order,
|
||||||
|
//! with the millisecond timestamps of 6.2, across sequence and timestamp wrap-around. A fixed vector checks one
|
||||||
|
//! datagram byte by byte; the cipher is checked against the openssl vectors. No parity packets are sent (U16).
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use common::SeqRng;
|
||||||
|
use domistream::audio::packet::{MAX_AUDIO_PACKET_BYTES, parse_audio_packet};
|
||||||
|
use domistream::audio::packetizer::{MAX_OPUS_ENCRYPTED_BYTES, MAX_OPUS_PLAIN_BYTES};
|
||||||
|
use domistream::audio::{
|
||||||
|
AudioCipher, AudioConfig, AudioDepacketizer, AudioEvent, AudioFec, AudioPacket, AudioPacketizer,
|
||||||
|
AudioPacketizerConfig, AudioParity,
|
||||||
|
};
|
||||||
|
use domistream::{Error, Instant, SessionKeys};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"audio-pack-key!!";
|
||||||
|
const RIKEYID: u32 = 0xFFFF_FFF0; // rikeyid + sequence wraps inside the tests
|
||||||
|
|
||||||
|
fn keys() -> SessionKeys {
|
||||||
|
SessionKeys { rikey: KEY, rikeyid: RIKEYID }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cfg(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizerConfig {
|
||||||
|
AudioPacketizerConfig {
|
||||||
|
cipher: encrypt.then(|| AudioCipher::new(&keys())),
|
||||||
|
packet_duration_ms: duration,
|
||||||
|
parity: AudioParity::None,
|
||||||
|
first_sequence,
|
||||||
|
first_timestamp_ms,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sender(encrypt: bool, first_sequence: u16, first_timestamp_ms: u32, duration: u8) -> AudioPacketizer {
|
||||||
|
AudioPacketizer::new(cfg(encrypt, first_sequence, first_timestamp_ms, duration)).expect("AudioPacketizer::new")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn receiver(encrypt: bool, duration: u8) -> AudioDepacketizer {
|
||||||
|
AudioDepacketizer::new(AudioConfig {
|
||||||
|
cipher: encrypt.then(|| AudioCipher::new(&keys())),
|
||||||
|
packet_duration_ms: duration,
|
||||||
|
fec: AudioFec::Disabled,
|
||||||
|
loss_timeout: Duration::from_millis(40),
|
||||||
|
})
|
||||||
|
.expect("AudioDepacketizer::new")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn receive(rx: &mut AudioDepacketizer, datagrams: &[Vec<u8>]) -> Vec<AudioEvent> {
|
||||||
|
let mut now = 1_000_000u64;
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for d in datagrams {
|
||||||
|
rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap");
|
||||||
|
now += 5_000;
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _ in 0..64 {
|
||||||
|
now += 1_000_000;
|
||||||
|
rx.handle_timeout(Instant::from_micros(now)).unwrap();
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
if rx.poll_timeout().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
events
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One Opus-sized payload: 1 to 1275 bytes (one Opus frame's maximum, RFC 6716), occasionally up to `max`.
|
||||||
|
fn opus(rng: &mut SeqRng, max: usize) -> Vec<u8> {
|
||||||
|
let len = if rng.below(20) == 0 { 1 + rng.below(max) } else { 1 + rng.below(1275) };
|
||||||
|
rng.bytes(len)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Packetizes `payloads` and returns (datagrams, the events a lossless receiver must report).
|
||||||
|
fn send(tx: &mut AudioPacketizer, payloads: &[Vec<u8>], duration: u8) -> (Vec<Vec<u8>>, Vec<AudioEvent>) {
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
let mut want = Vec::new();
|
||||||
|
for o in payloads {
|
||||||
|
let (seq, ts) = (tx.next_sequence(), tx.next_timestamp_ms());
|
||||||
|
let out = tx.packetize(o).expect("packetize");
|
||||||
|
assert_eq!(out.len(), 1, "AudioParity::None: one datagram per Opus packet, no parity");
|
||||||
|
assert_eq!(tx.next_sequence(), seq.wrapping_add(1));
|
||||||
|
assert_eq!(tx.next_timestamp_ms(), ts.wrapping_add(u32::from(duration)));
|
||||||
|
datagrams.extend(out);
|
||||||
|
want.push(AudioEvent::Packet { sequence: seq, timestamp_ms: ts, opus: o.clone(), recovered: false });
|
||||||
|
}
|
||||||
|
(datagrams, want)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ fixed vectors
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixed_vector_plaintext() {
|
||||||
|
let mut tx = sender(false, 0x0104, 0x0A0B_0C0D, 5);
|
||||||
|
let out = tx.packetize(&[0xFC, 0xFF, 0xFE]).unwrap();
|
||||||
|
#[rustfmt::skip]
|
||||||
|
let want = vec![
|
||||||
|
0x80, // RTP byte 0: version 2, no extension (6.2)
|
||||||
|
0x61, // payload type 97
|
||||||
|
0x01, 0x04, // sequence 0x0104, BE
|
||||||
|
0x0A, 0x0B, 0x0C, 0x0D, // timestamp (milliseconds), BE
|
||||||
|
0x00, 0x00, 0x00, 0x00, // SSRC 0
|
||||||
|
0xFC, 0xFF, 0xFE, // the Opus packet
|
||||||
|
];
|
||||||
|
assert_eq!(out, vec![want]);
|
||||||
|
assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), (0x0105, 0x0A0B_0C12));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixed_vector_encrypted() {
|
||||||
|
// Header as above; the payload is AES-128-CBC + PKCS#7 with IV = BE(rikeyid + sequence) || 12 zero bytes (6.3),
|
||||||
|
// here computed by the RustCrypto test oracle (itself checked against openssl in media.rs).
|
||||||
|
let mut tx = sender(true, 0x0020, 7, 10);
|
||||||
|
let opus = [0x11u8; 20];
|
||||||
|
let out = tx.packetize(&opus).unwrap();
|
||||||
|
let mut want = vec![0x80, 0x61, 0x00, 0x20, 0x00, 0x00, 0x00, 0x07, 0x00, 0x00, 0x00, 0x00];
|
||||||
|
want.extend(common::audio_encrypt(&KEY, RIKEYID, 0x0020, &opus));
|
||||||
|
assert_eq!(out, vec![want]);
|
||||||
|
assert_eq!(out[0].len(), 12 + 32, "20 bytes pad to 32");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_cipher_encrypt_matches_openssl_vectors() {
|
||||||
|
let v = common::audio_vectors();
|
||||||
|
for name in ["a_0", "a_1", "a_ffff", "a_wrap", "a_exact_block", "a_one_byte"] {
|
||||||
|
let rikeyid = v.u32_hex(&format!("{name}_rikeyid"));
|
||||||
|
let seq = u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap();
|
||||||
|
let c = AudioCipher::new(&SessionKeys { rikey: v.arr16("key"), rikeyid });
|
||||||
|
assert_eq!(
|
||||||
|
c.encrypt(seq, &v.bytes(&format!("{name}_plain"))).unwrap(),
|
||||||
|
v.bytes(&format!("{name}_cipher")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ round trips
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_encrypted_across_sequence_and_timestamp_wrap() {
|
||||||
|
let mut rng = SeqRng::new(1);
|
||||||
|
// Sequence 0xFF00 wraps after 256 packets; the timestamp wraps too; rikeyid + sequence wraps in the IV.
|
||||||
|
let mut tx = sender(true, 0xFF00, u32::MAX - 1000, 20);
|
||||||
|
let payloads: Vec<Vec<u8>> = (0..600).map(|_| opus(&mut rng, MAX_OPUS_ENCRYPTED_BYTES)).collect();
|
||||||
|
let (datagrams, want) = send(&mut tx, &payloads, 20);
|
||||||
|
assert_eq!(receive(&mut receiver(true, 20), &datagrams), want);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_plaintext() {
|
||||||
|
let mut rng = SeqRng::new(2);
|
||||||
|
let mut tx = sender(false, 0, 0, 5);
|
||||||
|
let payloads: Vec<Vec<u8>> = (0..300).map(|_| opus(&mut rng, MAX_OPUS_PLAIN_BYTES)).collect();
|
||||||
|
let (datagrams, want) = send(&mut tx, &payloads, 5);
|
||||||
|
for d in &datagrams {
|
||||||
|
assert!(matches!(parse_audio_packet(d), Ok(AudioPacket::Data { .. })));
|
||||||
|
}
|
||||||
|
assert_eq!(receive(&mut receiver(false, 5), &datagrams), want);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sequence_wraps_from_ffff_to_0() {
|
||||||
|
let mut tx = sender(true, 0xFFFC, 100, 10);
|
||||||
|
let mut seen = Vec::new();
|
||||||
|
for _ in 0..6 {
|
||||||
|
let d = tx.packetize(&[1, 2, 3]).unwrap().remove(0);
|
||||||
|
let Ok(AudioPacket::Data { rtp, .. }) = parse_audio_packet(&d) else { panic!("data packet") };
|
||||||
|
seen.push((rtp.sequence, rtp.timestamp));
|
||||||
|
}
|
||||||
|
assert_eq!(seen, vec![(0xFFFC, 100), (0xFFFD, 110), (0xFFFE, 120), (0xFFFF, 130), (0x0000, 140), (0x0001, 150)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lost_packets_are_reported_and_the_rest_arrive() {
|
||||||
|
let mut rng = SeqRng::new(3);
|
||||||
|
let mut tx = sender(true, 0x1000, 0, 5);
|
||||||
|
let payloads: Vec<Vec<u8>> = (0..200).map(|_| opus(&mut rng, 400)).collect();
|
||||||
|
let (datagrams, want) = send(&mut tx, &payloads, 5);
|
||||||
|
let mut kept = Vec::new();
|
||||||
|
let mut expect = Vec::new();
|
||||||
|
for (i, (d, w)) in datagrams.into_iter().zip(want).enumerate() {
|
||||||
|
if i > 0 && i < 199 && rng.below(10) == 0 {
|
||||||
|
let AudioEvent::Packet { sequence, .. } = w else { unreachable!() };
|
||||||
|
expect.push(AudioEvent::Lost { sequence });
|
||||||
|
} else {
|
||||||
|
kept.push(d);
|
||||||
|
expect.push(w);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(receive(&mut receiver(true, 5), &kept), expect);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ refusals
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn size_caps() {
|
||||||
|
assert_eq!(MAX_OPUS_PLAIN_BYTES, MAX_AUDIO_PACKET_BYTES - 12);
|
||||||
|
assert_eq!(MAX_OPUS_ENCRYPTED_BYTES, 2031, "2031 bytes pad to 2032; 12 + 2032 = 2044 <= 2048");
|
||||||
|
for (encrypt, max) in [(false, MAX_OPUS_PLAIN_BYTES), (true, MAX_OPUS_ENCRYPTED_BYTES)] {
|
||||||
|
let mut tx = sender(encrypt, 4, 50, 5);
|
||||||
|
assert_eq!(tx.max_opus_len(), max);
|
||||||
|
let state = (tx.next_sequence(), tx.next_timestamp_ms());
|
||||||
|
assert_err!(tx.packetize(&[]), Error::Truncated { .. }, "an Opus packet has at least its TOC byte");
|
||||||
|
assert_too_large!(tx.packetize(&vec![7; max + 1]), max, max + 1);
|
||||||
|
assert_too_large!(tx.packetize(&vec![7; 100_000]), max, 100_000);
|
||||||
|
assert_eq!((tx.next_sequence(), tx.next_timestamp_ms()), state, "a refused packet changes nothing");
|
||||||
|
// The largest packet fits the receiver's datagram cap and comes back.
|
||||||
|
let (datagrams, want) = send(&mut tx, &[vec![9; max], vec![8; 1]], 5);
|
||||||
|
assert!(datagrams[0].len() <= MAX_AUDIO_PACKET_BYTES);
|
||||||
|
assert_eq!(receive(&mut receiver(encrypt, 5), &datagrams), want);
|
||||||
|
}
|
||||||
|
let c = AudioCipher::new(&keys());
|
||||||
|
assert_too_large!(
|
||||||
|
c.encrypt(0, &vec![0; MAX_AUDIO_PACKET_BYTES + 1]),
|
||||||
|
MAX_AUDIO_PACKET_BYTES,
|
||||||
|
MAX_AUDIO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_refusals() {
|
||||||
|
assert_err!(AudioPacketizer::new(cfg(true, 0, 0, 0)), Error::Malformed { .. }, "zero packet duration");
|
||||||
|
// Blocks start at multiples of 4 (6.4), and the receiver counts from the first block's start: a stream that
|
||||||
|
// began at 5 would make it report 4 as lost.
|
||||||
|
for first in [1u16, 2, 3, 5, 0xFFFF] {
|
||||||
|
assert_err!(AudioPacketizer::new(cfg(true, first, 0, 5)), Error::Malformed { .. }, "first sequence {first}");
|
||||||
|
}
|
||||||
|
assert!(AudioPacketizer::new(cfg(true, 0xFFFC, 0, 5)).is_ok());
|
||||||
|
assert_eq!(AudioParity::default(), AudioParity::None);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ generated
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 64, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generated_round_trips(
|
||||||
|
seed in any::<u64>(),
|
||||||
|
first_sequence in any::<u16>(),
|
||||||
|
first_ts in any::<u32>(),
|
||||||
|
duration in 1u8..=40,
|
||||||
|
count in 1usize..80,
|
||||||
|
encrypt in any::<bool>(),
|
||||||
|
) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut tx = sender(encrypt, first_sequence & !3, first_ts, duration);
|
||||||
|
let max = tx.max_opus_len();
|
||||||
|
let payloads: Vec<Vec<u8>> = (0..count).map(|_| opus(&mut rng, max)).collect();
|
||||||
|
let (datagrams, want) = send(&mut tx, &payloads, duration);
|
||||||
|
prop_assert_eq!(receive(&mut receiver(encrypt, duration), &datagrams), want);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,716 @@
|
|||||||
|
//! Helpers shared by the integration tests: deterministic randomness, fixture loading, an independent GF(2^8)
|
||||||
|
//! reference, and builders for video and audio streams. Test code: panics are the way a test fails.
|
||||||
|
|
||||||
|
#![allow(dead_code, unreachable_pub, clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing)]
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
|
||||||
|
use domistream::RandomSource;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ assertions
|
||||||
|
|
||||||
|
/// Asserts that `$e` is `Err` matching `$p` (an `Error` pattern), printing the actual value otherwise.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! assert_err {
|
||||||
|
($e:expr, $p:pat) => {
|
||||||
|
match $e {
|
||||||
|
Err($p) => {}
|
||||||
|
other => panic!("expected Err({}), got {:?}", stringify!($p), other),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
($e:expr, $p:pat, $($ctx:tt)+) => {
|
||||||
|
match $e {
|
||||||
|
Err($p) => {}
|
||||||
|
other => panic!("expected Err({}), got {:?}: {}", stringify!($p), other, format!($($ctx)+)),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Asserts `Err(TooLarge { max, actual, .. })` with the given numbers.
|
||||||
|
#[macro_export]
|
||||||
|
macro_rules! assert_too_large {
|
||||||
|
($e:expr, $max:expr, $actual:expr) => {
|
||||||
|
match $e {
|
||||||
|
Err(domistream::Error::TooLarge { max, actual, .. }) => {
|
||||||
|
assert_eq!(max, $max, "TooLarge.max");
|
||||||
|
assert_eq!(actual, $actual, "TooLarge.actual");
|
||||||
|
}
|
||||||
|
other => panic!("expected Err(TooLarge {{ max: {}, actual: {} }}), got {:?}", $max, $actual, other),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/// False for `Err(Unimplemented)`. "Never panics" properties assert this on every result, so they cannot pass
|
||||||
|
/// against a stub that returns `Unimplemented` for everything.
|
||||||
|
pub fn implemented<T>(r: &domistream::Result<T>) -> bool {
|
||||||
|
!matches!(r, Err(domistream::Error::Unimplemented))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ randomness
|
||||||
|
|
||||||
|
/// A seeded, deterministic random source (splitmix64). Never for production.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct SeqRng(u64);
|
||||||
|
|
||||||
|
impl SeqRng {
|
||||||
|
pub fn new(seed: u64) -> Self {
|
||||||
|
Self(seed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn next_u64(&mut self) -> u64 {
|
||||||
|
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
|
||||||
|
let mut z = self.0;
|
||||||
|
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
|
||||||
|
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
|
||||||
|
z ^ (z >> 31)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Uniform in `0..n` (n > 0); bias is irrelevant for test data.
|
||||||
|
pub fn below(&mut self, n: usize) -> usize {
|
||||||
|
(self.next_u64() % n as u64) as usize
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bytes(&mut self, n: usize) -> Vec<u8> {
|
||||||
|
let mut v = vec![0; n];
|
||||||
|
self.fill(&mut v);
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `count` distinct indices from `0..n`, sorted.
|
||||||
|
pub fn subset(&mut self, n: usize, count: usize) -> Vec<usize> {
|
||||||
|
let mut all: Vec<usize> = (0..n).collect();
|
||||||
|
for i in 0..count.min(n) {
|
||||||
|
let j = i + self.below(n - i);
|
||||||
|
all.swap(i, j);
|
||||||
|
}
|
||||||
|
let mut chosen = all[..count.min(n)].to_vec();
|
||||||
|
chosen.sort_unstable();
|
||||||
|
chosen
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn shuffle<T>(&mut self, items: &mut [T]) {
|
||||||
|
for i in (1..items.len()).rev() {
|
||||||
|
let j = self.below(i + 1);
|
||||||
|
items.swap(i, j);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RandomSource for SeqRng {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
for chunk in dest.chunks_mut(8) {
|
||||||
|
let word = self.next_u64().to_le_bytes();
|
||||||
|
chunk.copy_from_slice(&word[..chunk.len()]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Hands out a fixed byte stream (a recorded transcript's randomness) and fails the test when the code under
|
||||||
|
/// test draws more than was recorded.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ScriptedRng {
|
||||||
|
bytes: Vec<u8>,
|
||||||
|
pos: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ScriptedRng {
|
||||||
|
pub fn new(bytes: Vec<u8>) -> Self {
|
||||||
|
Self { bytes, pos: 0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn drawn(&self) -> usize {
|
||||||
|
self.pos
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RandomSource for ScriptedRng {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
let end = self.pos + dest.len();
|
||||||
|
assert!(
|
||||||
|
end <= self.bytes.len(),
|
||||||
|
"the code drew {} random bytes but the recorded transcript holds only {} \
|
||||||
|
(fixture assumption: salt, then C, then secret_c, 16 bytes each)",
|
||||||
|
end,
|
||||||
|
self.bytes.len()
|
||||||
|
);
|
||||||
|
dest.copy_from_slice(&self.bytes[self.pos..end]);
|
||||||
|
self.pos = end;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ fixtures
|
||||||
|
|
||||||
|
pub fn hex(s: &str) -> Vec<u8> {
|
||||||
|
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
|
||||||
|
if s == "-" {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
assert!(s.len().is_multiple_of(2), "odd hex length");
|
||||||
|
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex digit")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_hex(b: &[u8]) -> String {
|
||||||
|
b.iter().map(|x| format!("{x:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn to_hex_upper(b: &[u8]) -> String {
|
||||||
|
b.iter().map(|x| format!("{x:02X}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `name = value` fixture file written by `tools/vectors/gen_vectors.py`.
|
||||||
|
pub struct Vectors(HashMap<String, String>);
|
||||||
|
|
||||||
|
impl Vectors {
|
||||||
|
pub fn parse(text: &str) -> Self {
|
||||||
|
let mut map = HashMap::new();
|
||||||
|
for line in text.lines() {
|
||||||
|
let line = line.trim();
|
||||||
|
if line.is_empty() || line.starts_with('#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let (k, v) = line.split_once(" = ").expect("fixture line `name = value`");
|
||||||
|
map.insert(k.to_string(), v.to_string());
|
||||||
|
}
|
||||||
|
Self(map)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn str(&self, name: &str) -> &str {
|
||||||
|
self.0.get(name).unwrap_or_else(|| panic!("fixture value `{name}` missing"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn bytes(&self, name: &str) -> Vec<u8> {
|
||||||
|
hex(self.str(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn arr16(&self, name: &str) -> [u8; 16] {
|
||||||
|
self.bytes(name).try_into().unwrap_or_else(|_| panic!("`{name}` is not 16 bytes"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn u32_hex(&self, name: &str) -> u32 {
|
||||||
|
u32::from_str_radix(self.str(name), 16).expect("hex u32")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pairing_vectors() -> Vectors {
|
||||||
|
Vectors::parse(include_str!("../fixtures/pairing.txt"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn control_vectors() -> Vectors {
|
||||||
|
Vectors::parse(include_str!("../fixtures/control_gcm.txt"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn video_vectors() -> Vectors {
|
||||||
|
Vectors::parse(include_str!("../fixtures/video_gcm.txt"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn audio_vectors() -> Vectors {
|
||||||
|
Vectors::parse(include_str!("../fixtures/audio_cbc.txt"))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub const HOST_CERT_PEM: &str = include_str!("../fixtures/test-only-host-cert.pem");
|
||||||
|
pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cert.pem");
|
||||||
|
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
|
||||||
|
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
|
||||||
|
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
|
||||||
|
|
||||||
|
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
|
||||||
|
pub fn base64_decode(s: &str) -> Vec<u8> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut acc = 0u32;
|
||||||
|
let mut bits = 0;
|
||||||
|
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
|
||||||
|
let v = match c {
|
||||||
|
b'A'..=b'Z' => c - b'A',
|
||||||
|
b'a'..=b'z' => c - b'a' + 26,
|
||||||
|
b'0'..=b'9' => c - b'0' + 52,
|
||||||
|
b'+' => 62,
|
||||||
|
b'/' => 63,
|
||||||
|
b'=' => break,
|
||||||
|
_ => panic!("not base64: {c:#x}"),
|
||||||
|
};
|
||||||
|
acc = (acc << 6) | u32::from(v);
|
||||||
|
bits += 6;
|
||||||
|
if bits >= 8 {
|
||||||
|
bits -= 8;
|
||||||
|
out.push((acc >> bits) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The DER inside every `-----BEGIN <label>-----` block of a PEM text.
|
||||||
|
pub fn pem_blocks(pem: &str, label: &str) -> Vec<Vec<u8>> {
|
||||||
|
let begin = format!("-----BEGIN {label}-----");
|
||||||
|
let end = format!("-----END {label}-----");
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut rest = pem;
|
||||||
|
while let Some(start) = rest.find(&begin) {
|
||||||
|
let after = &rest[start + begin.len()..];
|
||||||
|
let stop = after.find(&end).expect("PEM end line");
|
||||||
|
out.push(base64_decode(&after[..stop]));
|
||||||
|
rest = &after[stop + end.len()..];
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ HTTP helpers
|
||||||
|
|
||||||
|
/// Splits a `path?query` into the path and its decoded parameters, in order.
|
||||||
|
pub fn parse_query(path_and_query: &str) -> (String, Vec<(String, String)>) {
|
||||||
|
let (path, query) = path_and_query.split_once('?').unwrap_or((path_and_query, ""));
|
||||||
|
let params = query
|
||||||
|
.split('&')
|
||||||
|
.filter(|p| !p.is_empty())
|
||||||
|
.map(|p| {
|
||||||
|
let (k, v) = p.split_once('=').unwrap_or((p, ""));
|
||||||
|
(percent_decode(k), percent_decode(v))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
(path.to_string(), params)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn percent_decode(s: &str) -> String {
|
||||||
|
let b = s.as_bytes();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut i = 0;
|
||||||
|
while i < b.len() {
|
||||||
|
if b[i] == b'%' && i + 2 < b.len() {
|
||||||
|
let h = std::str::from_utf8(&b[i + 1..i + 3]).expect("utf8");
|
||||||
|
out.push(u8::from_str_radix(h, 16).expect("percent escape"));
|
||||||
|
i += 3;
|
||||||
|
} else if b[i] == b'+' {
|
||||||
|
out.push(b' ');
|
||||||
|
i += 1;
|
||||||
|
} else {
|
||||||
|
out.push(b[i]);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String::from_utf8(out).expect("decoded query is UTF-8")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The single value of `name`; fails when it is missing or repeated (parameter injection).
|
||||||
|
pub fn param<'a>(params: &'a [(String, String)], name: &str) -> &'a str {
|
||||||
|
let found: Vec<&(String, String)> = params.iter().filter(|(k, _)| k == name).collect();
|
||||||
|
assert_eq!(found.len(), 1, "query parameter `{name}` must appear exactly once in {params:?}");
|
||||||
|
&found[0].1
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `<root status_code="200">` + elements + `</root>`.
|
||||||
|
pub fn xml_root(status: u32, inner: &str) -> Vec<u8> {
|
||||||
|
format!("<root status_code=\"{status}\">{inner}</root>").into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A child element sequence of exactly `len` bytes (`len >= 7`): `<x>aaa…</x>` pieces of at most 207 bytes, so no
|
||||||
|
/// single text is long and the element count stays small.
|
||||||
|
pub fn xml_filler(len: usize) -> String {
|
||||||
|
assert!(len >= 7, "filler needs at least 7 bytes");
|
||||||
|
let mut out = String::with_capacity(len);
|
||||||
|
let mut remaining = len;
|
||||||
|
while remaining > 0 {
|
||||||
|
let piece = if remaining <= 207 {
|
||||||
|
remaining
|
||||||
|
} else if remaining - 207 >= 7 {
|
||||||
|
207
|
||||||
|
} else {
|
||||||
|
remaining - 7
|
||||||
|
};
|
||||||
|
out.push_str("<x>");
|
||||||
|
out.extend(std::iter::repeat_n('a', piece - 7));
|
||||||
|
out.push_str("</x>");
|
||||||
|
remaining -= piece;
|
||||||
|
}
|
||||||
|
assert_eq!(out.len(), len);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A document `<root status_code="200">{inner}{filler}</root>` of exactly `total` bytes.
|
||||||
|
pub fn xml_padded_to(inner: &str, total: usize) -> Vec<u8> {
|
||||||
|
let bare = xml_root(200, inner).len();
|
||||||
|
assert!(total >= bare + 7, "target {total} too small for {bare} + filler");
|
||||||
|
let doc = xml_root(200, &format!("{inner}{}", xml_filler(total - bare)));
|
||||||
|
assert_eq!(doc.len(), total);
|
||||||
|
doc
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All subsets of `0..n` with exactly `size` elements, in lexicographic order.
|
||||||
|
pub fn subsets_of(n: usize, size: usize) -> Vec<Vec<usize>> {
|
||||||
|
fn go(start: usize, n: usize, size: usize, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
|
||||||
|
if cur.len() == size {
|
||||||
|
out.push(cur.clone());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
for i in start..n {
|
||||||
|
cur.push(i);
|
||||||
|
go(i + 1, n, size, cur, out);
|
||||||
|
cur.pop();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
go(0, n, size, &mut Vec::new(), &mut out);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ GF(2^8)
|
||||||
|
|
||||||
|
/// An independent GF(2^8) reference with polynomial 0x11D (`docs/PROTOCOL.md` 5.3), from the field definition.
|
||||||
|
pub mod gf {
|
||||||
|
pub fn mul(mut a: u8, mut b: u8) -> u8 {
|
||||||
|
let mut p = 0u8;
|
||||||
|
while b != 0 {
|
||||||
|
if b & 1 != 0 {
|
||||||
|
p ^= a;
|
||||||
|
}
|
||||||
|
let carry = a & 0x80 != 0;
|
||||||
|
a <<= 1;
|
||||||
|
if carry {
|
||||||
|
a ^= 0x1D;
|
||||||
|
}
|
||||||
|
b >>= 1;
|
||||||
|
}
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn inv(a: u8) -> u8 {
|
||||||
|
assert!(a != 0, "no inverse of 0");
|
||||||
|
(1..=255u8).find(|&b| mul(a, b) == 1).expect("field inverse")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A `rows × cols` Cauchy matrix `1 / (x_i + y_j)` with `x_i = i`, `y_j = rows + j`: every square submatrix is
|
||||||
|
/// invertible, so `[I; C]` is MDS.
|
||||||
|
pub fn cauchy(rows: usize, cols: usize) -> Vec<u8> {
|
||||||
|
assert!(rows + cols <= 256);
|
||||||
|
let mut m = Vec::with_capacity(rows * cols);
|
||||||
|
for i in 0..rows {
|
||||||
|
for j in 0..cols {
|
||||||
|
m.push(inv((i as u8) ^ ((rows + j) as u8)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parity shards for `data` with a row-major `parity × data` matrix.
|
||||||
|
pub fn encode(matrix: &[u8], data: &[Vec<u8>], parity: usize) -> Vec<Vec<u8>> {
|
||||||
|
let k = data.len();
|
||||||
|
let len = data[0].len();
|
||||||
|
(0..parity)
|
||||||
|
.map(|r| (0..len).map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x]))).collect())
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ video
|
||||||
|
|
||||||
|
/// One video packet as the test host built it.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct VPkt {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub frame_index: u32,
|
||||||
|
pub block: u8,
|
||||||
|
pub shard_index: u16,
|
||||||
|
pub data_shards: u16,
|
||||||
|
pub parity_shards: u16,
|
||||||
|
pub is_parity: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a frame should come out as.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct VExpect {
|
||||||
|
pub frame_index: u32,
|
||||||
|
pub header: [u8; 8],
|
||||||
|
pub bitstream: Vec<u8>,
|
||||||
|
pub rtp_timestamp: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A test host that packetizes frames as `docs/PROTOCOL.md` 5.2-5.3 describe (Moonshine-style frame header).
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct VideoHost {
|
||||||
|
pub packet_size: u16,
|
||||||
|
pub next_sequence: u16,
|
||||||
|
pub timestamp: u32,
|
||||||
|
/// When set, parity is computed over data shards whose bytes 0-31 are replaced by this pattern (a host may
|
||||||
|
/// compute parity before writing headers), so a recovered shard's header is guaranteed garbage.
|
||||||
|
pub scramble_parity_headers: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl VideoHost {
|
||||||
|
pub fn new(packet_size: u16) -> Self {
|
||||||
|
Self { packet_size, next_sequence: 0, timestamp: 90_000, scramble_parity_headers: false }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn payload_len(&self) -> usize {
|
||||||
|
usize::from(self.packet_size) - 16
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An Annex-B bitstream of about `len` bytes that ends in a nonzero byte (so trimming the zero padding by
|
||||||
|
/// either the frame header's length or the content gives the same answer: UNKNOWN U13).
|
||||||
|
pub fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
|
||||||
|
let mut b = vec![0, 0, 0, 1, 0x65];
|
||||||
|
b.extend(rng.bytes(len.saturating_sub(6)));
|
||||||
|
b.push(0x80 | rng.bytes(1)[0]);
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Packetizes one frame into `blocks` FEC blocks at `fec_percentage`.
|
||||||
|
pub fn frame(
|
||||||
|
&mut self,
|
||||||
|
frame_index: u32,
|
||||||
|
bitstream: &[u8],
|
||||||
|
fec_percentage: u8,
|
||||||
|
blocks: usize,
|
||||||
|
) -> (Vec<VPkt>, VExpect) {
|
||||||
|
let payload_len = self.payload_len();
|
||||||
|
let total_len = 8 + bitstream.len();
|
||||||
|
let shards_total = total_len.div_ceil(payload_len);
|
||||||
|
let last_payload_len = total_len - (shards_total - 1) * payload_len;
|
||||||
|
let mut header = [0u8; 8];
|
||||||
|
header[0] = 0x01;
|
||||||
|
header[1..3].copy_from_slice(&7u16.to_le_bytes());
|
||||||
|
header[3] = 2; // key frame
|
||||||
|
header[4..8].copy_from_slice(&(last_payload_len as u32).to_le_bytes());
|
||||||
|
let mut data = header.to_vec();
|
||||||
|
data.extend_from_slice(bitstream);
|
||||||
|
data.resize(shards_total * payload_len, 0);
|
||||||
|
|
||||||
|
let blocks = blocks.clamp(1, 4).min(shards_total);
|
||||||
|
let base = shards_total / blocks;
|
||||||
|
let extra = shards_total % blocks;
|
||||||
|
let last_block = (blocks - 1) as u8;
|
||||||
|
let mut packets = Vec::new();
|
||||||
|
let mut shard_offset = 0;
|
||||||
|
for b in 0..blocks {
|
||||||
|
let k = base + usize::from(b < extra);
|
||||||
|
let m = (k * usize::from(fec_percentage)).div_ceil(100);
|
||||||
|
assert!(k + m <= 255, "test frame needs k + m <= 255");
|
||||||
|
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
|
||||||
|
for i in 0..k {
|
||||||
|
let global = shard_offset + i;
|
||||||
|
let mut flags = 0x01;
|
||||||
|
if global == 0 {
|
||||||
|
flags |= 0x04;
|
||||||
|
}
|
||||||
|
if global == shards_total - 1 {
|
||||||
|
flags |= 0x02;
|
||||||
|
}
|
||||||
|
let mut p = self.header(frame_index, flags, b as u8, last_block, i, k, fec_percentage);
|
||||||
|
p.extend_from_slice(&data[global * payload_len..(global + 1) * payload_len]);
|
||||||
|
shards.push(p);
|
||||||
|
}
|
||||||
|
if m > 0 {
|
||||||
|
let code = domistream::fec::ReedSolomon::new(k, m)
|
||||||
|
.expect("ReedSolomon::new for the test host (Phase A: Unimplemented)");
|
||||||
|
let shard_len = shards[0].len();
|
||||||
|
let mut work: Vec<Vec<u8>> = shards.clone();
|
||||||
|
if self.scramble_parity_headers {
|
||||||
|
for (i, s) in work.iter_mut().enumerate() {
|
||||||
|
for (x, byte) in s[..32].iter_mut().enumerate() {
|
||||||
|
*byte = (0xA5 ^ (i as u8).wrapping_mul(31) ^ (x as u8).wrapping_mul(7)) | 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
work.extend((0..m).map(|_| vec![0u8; shard_len]));
|
||||||
|
code.encode(&mut work).expect("ReedSolomon::encode for the test host");
|
||||||
|
for j in 0..m {
|
||||||
|
let mut p = self.header(frame_index, 0, b as u8, last_block, k + j, k, fec_percentage);
|
||||||
|
p.extend_from_slice(&work[k + j][32..]);
|
||||||
|
shards.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i, bytes) in shards.into_iter().enumerate() {
|
||||||
|
packets.push(VPkt {
|
||||||
|
bytes,
|
||||||
|
frame_index,
|
||||||
|
block: b as u8,
|
||||||
|
shard_index: i as u16,
|
||||||
|
data_shards: k as u16,
|
||||||
|
parity_shards: m as u16,
|
||||||
|
is_parity: i >= k,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
shard_offset += k;
|
||||||
|
}
|
||||||
|
let expect = VExpect { frame_index, header, bitstream: bitstream.to_vec(), rtp_timestamp: self.timestamp };
|
||||||
|
self.timestamp = self.timestamp.wrapping_add(1500);
|
||||||
|
(packets, expect)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RTP header + 4 reserved + NV header for the next sequence number (all packets of a frame share the
|
||||||
|
/// timestamp).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
fn header(
|
||||||
|
&mut self,
|
||||||
|
frame_index: u32,
|
||||||
|
flags: u8,
|
||||||
|
block: u8,
|
||||||
|
last_block: u8,
|
||||||
|
shard_index: usize,
|
||||||
|
data_shards: usize,
|
||||||
|
fec_percentage: u8,
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let seq = self.next_sequence;
|
||||||
|
self.next_sequence = self.next_sequence.wrapping_add(1);
|
||||||
|
let mut p = Vec::with_capacity(usize::from(self.packet_size) + 16);
|
||||||
|
p.extend_from_slice(&[0x90, 0x00]);
|
||||||
|
p.extend_from_slice(&seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&self.timestamp.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(&[0; 4]);
|
||||||
|
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
|
||||||
|
p.extend_from_slice(&frame_index.to_le_bytes());
|
||||||
|
p.push(flags);
|
||||||
|
p.push(0);
|
||||||
|
p.push(0x10);
|
||||||
|
p.push((block << 4) | (last_block << 6));
|
||||||
|
let fec_info = (u32::from(fec_percentage) << 4) | ((shard_index as u32) << 12) | ((data_shards as u32) << 22);
|
||||||
|
p.extend_from_slice(&fec_info.to_le_bytes());
|
||||||
|
p
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds one NV video packet by hand from the field table (`docs/PROTOCOL.md` 5.2).
|
||||||
|
#[allow(clippy::too_many_arguments)]
|
||||||
|
pub fn video_packet_bytes(
|
||||||
|
seq: u16,
|
||||||
|
timestamp: u32,
|
||||||
|
frame_index: u32,
|
||||||
|
flags: u8,
|
||||||
|
multi_fec_blocks: u8,
|
||||||
|
fec_info: u32,
|
||||||
|
payload: &[u8],
|
||||||
|
) -> Vec<u8> {
|
||||||
|
let mut p = vec![0x90, 0x00];
|
||||||
|
p.extend_from_slice(&seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(×tamp.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(&[0; 4]);
|
||||||
|
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
|
||||||
|
p.extend_from_slice(&frame_index.to_le_bytes());
|
||||||
|
p.extend_from_slice(&[flags, 0, 0x10, multi_fec_blocks]);
|
||||||
|
p.extend_from_slice(&fec_info.to_le_bytes());
|
||||||
|
p.extend_from_slice(payload);
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn fec_info(fec_percentage: u8, shard_index: u16, data_shards: u16) -> u32 {
|
||||||
|
(u32::from(fec_percentage) << 4) | (u32::from(shard_index) << 12) | (u32::from(data_shards) << 22)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// AES-128-GCM sealing of a plaintext video packet with the layout of `docs/PROTOCOL.md` 7, using RustCrypto as
|
||||||
|
/// the test oracle (checked against the .NET vectors in `media.rs`).
|
||||||
|
pub fn video_encrypt(key: &[u8; 16], counter: u64, frame_number: u32, plaintext: &[u8]) -> Vec<u8> {
|
||||||
|
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||||||
|
let cipher = aes_gcm::Aes128Gcm::new_from_slice(key).expect("key");
|
||||||
|
let mut iv = [0u8; 12];
|
||||||
|
iv[..8].copy_from_slice(&counter.to_le_bytes());
|
||||||
|
iv[11] = b'V';
|
||||||
|
let mut buf = plaintext.to_vec();
|
||||||
|
let tag = cipher.encrypt_inout_detached(&iv.into(), b"", buf.as_mut_slice().into()).expect("gcm encrypt");
|
||||||
|
let mut out = iv.to_vec();
|
||||||
|
out.extend_from_slice(&frame_number.to_le_bytes());
|
||||||
|
out.extend_from_slice(tag.as_slice());
|
||||||
|
out.extend_from_slice(&buf);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ audio
|
||||||
|
|
||||||
|
/// AES-128-CBC + PKCS#7 with the audio IV of `docs/PROTOCOL.md` 6.3 (`rikeyid + seq`, wrapping), RustCrypto as
|
||||||
|
/// the test oracle (checked against the openssl vectors in `media.rs`).
|
||||||
|
pub fn audio_encrypt(key: &[u8; 16], rikeyid: u32, seq: u16, plaintext: &[u8]) -> Vec<u8> {
|
||||||
|
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
|
||||||
|
let mut iv = [0u8; 16];
|
||||||
|
iv[..4].copy_from_slice(&rikeyid.wrapping_add(u32::from(seq)).to_be_bytes());
|
||||||
|
let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16];
|
||||||
|
buf[..plaintext.len()].copy_from_slice(plaintext);
|
||||||
|
let len = cbc::Encryptor::<aes::Aes128>::new(key.into(), &iv.into())
|
||||||
|
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
|
||||||
|
.expect("cbc encrypt")
|
||||||
|
.len();
|
||||||
|
buf.truncate(len);
|
||||||
|
buf
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One audio packet as the test host built it.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct APkt {
|
||||||
|
pub bytes: Vec<u8>,
|
||||||
|
pub sequence: u16,
|
||||||
|
pub block: usize,
|
||||||
|
/// 0..4 data, 4..6 parity.
|
||||||
|
pub index: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a data packet should come out as.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct AExpect {
|
||||||
|
pub sequence: u16,
|
||||||
|
pub timestamp_ms: u32,
|
||||||
|
pub opus: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parity packets' RTP sequence number: "continues after the 4 data packets" (PROTOCOL.md 6.2), read as
|
||||||
|
/// base + 4 + shard index. The depacketizer must key parity by the FEC header's base sequence, not by this.
|
||||||
|
pub fn audio_parity_rtp_sequence(base: u16, shard: u8) -> u16 {
|
||||||
|
base.wrapping_add(4).wrapping_add(u16::from(shard))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A test host for audio: blocks of 4 data + 2 parity packets (`docs/PROTOCOL.md` 6.2-6.4).
|
||||||
|
pub struct AudioHost {
|
||||||
|
pub key: [u8; 16],
|
||||||
|
pub rikeyid: u32,
|
||||||
|
pub encrypt: bool,
|
||||||
|
pub matrix: [u8; 8],
|
||||||
|
pub duration_ms: u32,
|
||||||
|
pub opus_len: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AudioHost {
|
||||||
|
/// `blocks` consecutive blocks starting at `first_seq` (a multiple of 4) and `first_ts`.
|
||||||
|
pub fn blocks(&self, rng: &mut SeqRng, first_seq: u16, first_ts: u32, blocks: usize) -> (Vec<APkt>, Vec<AExpect>) {
|
||||||
|
assert_eq!(first_seq % 4, 0);
|
||||||
|
let mut packets = Vec::new();
|
||||||
|
let mut expect = Vec::new();
|
||||||
|
for b in 0..blocks {
|
||||||
|
let base_seq = first_seq.wrapping_add((4 * b) as u16);
|
||||||
|
let base_ts = first_ts.wrapping_add(4 * b as u32 * self.duration_ms);
|
||||||
|
let mut shards = Vec::new();
|
||||||
|
for i in 0..4u16 {
|
||||||
|
let seq = base_seq.wrapping_add(i);
|
||||||
|
let ts = base_ts.wrapping_add(u32::from(i) * self.duration_ms);
|
||||||
|
let opus = rng.bytes(self.opus_len);
|
||||||
|
let payload =
|
||||||
|
if self.encrypt { audio_encrypt(&self.key, self.rikeyid, seq, &opus) } else { opus.clone() };
|
||||||
|
let mut p = vec![0x80, 97];
|
||||||
|
p.extend_from_slice(&seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&ts.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(&payload);
|
||||||
|
packets.push(APkt { bytes: p, sequence: seq, block: b, index: usize::from(i) });
|
||||||
|
expect.push(AExpect { sequence: seq, timestamp_ms: ts, opus });
|
||||||
|
shards.push(payload);
|
||||||
|
}
|
||||||
|
let parity = gf::encode(&self.matrix, &shards, 2);
|
||||||
|
for (j, par) in parity.iter().enumerate() {
|
||||||
|
let seq = audio_parity_rtp_sequence(base_seq, j as u8);
|
||||||
|
let mut p = vec![0x80, 127];
|
||||||
|
p.extend_from_slice(&seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.push(j as u8);
|
||||||
|
p.push(97);
|
||||||
|
p.extend_from_slice(&base_seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(par);
|
||||||
|
packets.push(APkt { bytes: p, sequence: seq, block: b, index: 4 + j });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
(packets, expect)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The 2 × 4 Cauchy parity matrix the audio tests pass through `AudioFec::ParityMatrix` (U16 is unmeasured; any
|
||||||
|
/// MDS matrix must work).
|
||||||
|
pub fn audio_test_matrix() -> [u8; 8] {
|
||||||
|
gf::cauchy(2, 4).try_into().expect("2x4")
|
||||||
|
}
|
||||||
@@ -0,0 +1,638 @@
|
|||||||
|
//! Control channel (`docs/PROTOCOL.md` 3.2, 3.3): nonce layout, AES-GCM frames against .NET vectors
|
||||||
|
//! (`tools/vectors/gcm_vectors.cs`), tampering, direction, replay and sequence wrap through [`ControlStream`], and the
|
||||||
|
//! message layouts.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use common::SeqRng;
|
||||||
|
use domistream::control::frame::{FRAME_HEADER_LEN, MAX_FRAME_BYTES, MIN_FRAME_BYTES, nonce};
|
||||||
|
use domistream::control::message::{MAX_MESSAGE_BYTES, MotionKind, encode_client_message};
|
||||||
|
use domistream::control::{
|
||||||
|
ClientMessage, ControlCipher, ControlConfig, ControlEvent, ControlStream, Direction, HostMessage, MessageType,
|
||||||
|
parse_encrypted_frame, parse_host_message, parse_message,
|
||||||
|
};
|
||||||
|
use domistream::enet::EnetConfig;
|
||||||
|
use domistream::enet::protocol::{Command, CommandBody, ConnectParams, Datagram, encode_datagram, parse_datagram};
|
||||||
|
use domistream::input::InputEvent;
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const NAMES: [&str; 10] = [
|
||||||
|
"c_ping_0",
|
||||||
|
"c_input_1",
|
||||||
|
"c_ping_ffff",
|
||||||
|
"c_ping_10000",
|
||||||
|
"c_ping_fffffffe",
|
||||||
|
"c_ping_ffffffff",
|
||||||
|
"h_rumble_0",
|
||||||
|
"h_rumble_7",
|
||||||
|
"h_termination_ffffffff",
|
||||||
|
"h_rgb_2a",
|
||||||
|
];
|
||||||
|
|
||||||
|
fn dir(v: &common::Vectors, name: &str) -> Direction {
|
||||||
|
match v.str(&format!("{name}_direction")) {
|
||||||
|
"C" => Direction::ClientToHost,
|
||||||
|
"H" => Direction::HostToClient,
|
||||||
|
other => panic!("direction {other}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ nonce
|
||||||
|
|
||||||
|
fn expected_nonce(seq: u32, direction: Direction) -> [u8; 12] {
|
||||||
|
let mut n = [0u8; 12];
|
||||||
|
n[..4].copy_from_slice(&seq.to_le_bytes());
|
||||||
|
n[10] = match direction {
|
||||||
|
Direction::ClientToHost => b'C',
|
||||||
|
Direction::HostToClient => b'H',
|
||||||
|
};
|
||||||
|
n[11] = b'C';
|
||||||
|
n
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn nonce_layout() {
|
||||||
|
// seq LE, then 6 zero bytes, then the direction byte, then 'C'.
|
||||||
|
assert_eq!(nonce(0, Direction::ClientToHost).unwrap(), [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, b'C', b'C']);
|
||||||
|
assert_eq!(nonce(1, Direction::HostToClient).unwrap(), [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, b'H', b'C']);
|
||||||
|
assert_eq!(
|
||||||
|
nonce(0x1234_5678, Direction::ClientToHost).unwrap(),
|
||||||
|
[0x78, 0x56, 0x34, 0x12, 0, 0, 0, 0, 0, 0, b'C', b'C']
|
||||||
|
);
|
||||||
|
for seq in [0xFFFF, 0x1_0000, 0xFFFF_FFFE, u32::MAX] {
|
||||||
|
for d in [Direction::ClientToHost, Direction::HostToClient] {
|
||||||
|
assert_eq!(nonce(seq, d).unwrap(), expected_nonce(seq, d), "{seq:#x} {d:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_ne!(nonce(5, Direction::ClientToHost).unwrap(), nonce(5, Direction::HostToClient).unwrap());
|
||||||
|
let v = common::control_vectors();
|
||||||
|
for name in NAMES {
|
||||||
|
let seq = v.u32_hex(&format!("{name}_sequence"));
|
||||||
|
assert_eq!(nonce(seq, dir(&v, name)).unwrap().to_vec(), v.bytes(&format!("{name}_nonce")), "{name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#[test]
|
||||||
|
fn nonce_matches_the_definition(seq in any::<u32>(), host in any::<bool>()) {
|
||||||
|
let d = if host { Direction::HostToClient } else { Direction::ClientToHost };
|
||||||
|
prop_assert_eq!(nonce(seq, d), Ok(expected_nonce(seq, d)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ seal / open
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seal_matches_dotnet_vectors() {
|
||||||
|
let v = common::control_vectors();
|
||||||
|
let c = ControlCipher::new(v.arr16("key"));
|
||||||
|
for name in NAMES {
|
||||||
|
let seq = v.u32_hex(&format!("{name}_sequence"));
|
||||||
|
let d = dir(&v, name);
|
||||||
|
let plain = v.bytes(&format!("{name}_plain"));
|
||||||
|
let frame = v.bytes(&format!("{name}_frame"));
|
||||||
|
assert_eq!(c.seal(seq, d, &plain).unwrap(), frame, "{name}");
|
||||||
|
assert_eq!(c.open(d, &frame).unwrap(), (seq, plain.clone()), "{name}");
|
||||||
|
let f = parse_encrypted_frame(&frame).unwrap();
|
||||||
|
assert_eq!(f.sequence, seq);
|
||||||
|
assert_eq!(f.ciphertext.len(), plain.len());
|
||||||
|
assert_eq!(f.tag.to_vec(), frame[8..24].to_vec());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn seal_open_round_trip() {
|
||||||
|
let c = ControlCipher::new([7; 16]);
|
||||||
|
for len in [4usize, 5, 16, 100, MAX_FRAME_BYTES - FRAME_HEADER_LEN] {
|
||||||
|
let plain: Vec<u8> = (0..len).map(|i| i as u8).collect();
|
||||||
|
for d in [Direction::ClientToHost, Direction::HostToClient] {
|
||||||
|
let f = c.seal(42, d, &plain).unwrap();
|
||||||
|
assert_eq!(f.len(), FRAME_HEADER_LEN + len);
|
||||||
|
assert_eq!(&f[..2], &[0x01, 0x00]);
|
||||||
|
assert_eq!(u16::from_le_bytes([f[2], f[3]]) as usize, f.len() - 4);
|
||||||
|
assert_eq!(c.open(d, &f).unwrap(), (42, plain.clone()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
match c.seal(0, Direction::ClientToHost, &vec![0; MAX_FRAME_BYTES - FRAME_HEADER_LEN + 1]) {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_FRAME_BYTES),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tampering_is_refused() {
|
||||||
|
let v = common::control_vectors();
|
||||||
|
let c = ControlCipher::new(v.arr16("key"));
|
||||||
|
let frame = v.bytes("h_rumble_7_frame");
|
||||||
|
let d = Direction::HostToClient;
|
||||||
|
for i in 4..frame.len() {
|
||||||
|
let mut t = frame.clone();
|
||||||
|
t[i] ^= 0x01;
|
||||||
|
// seq (4..8) changes the nonce, tag (8..24) and ciphertext (24..) break the tag.
|
||||||
|
assert_err!(c.open(d, &t), Error::Crypto, "byte {i} flipped");
|
||||||
|
}
|
||||||
|
let mut t = frame.clone();
|
||||||
|
t[2] ^= 1;
|
||||||
|
assert_err!(c.open(d, &t), Error::Malformed { .. }, "length field");
|
||||||
|
let mut t = frame.clone();
|
||||||
|
t[0] = 0x02;
|
||||||
|
assert_err!(c.open(d, &t), Error::UnexpectedValue { .. }, "type field");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_direction_and_wrong_key_are_refused() {
|
||||||
|
let v = common::control_vectors();
|
||||||
|
let c = ControlCipher::new(v.arr16("key"));
|
||||||
|
for name in NAMES {
|
||||||
|
let other = match dir(&v, name) {
|
||||||
|
Direction::ClientToHost => Direction::HostToClient,
|
||||||
|
Direction::HostToClient => Direction::ClientToHost,
|
||||||
|
};
|
||||||
|
assert_err!(c.open(other, &v.bytes(&format!("{name}_frame"))), Error::Crypto, "{name} opened the other way");
|
||||||
|
}
|
||||||
|
let mut key = v.arr16("key");
|
||||||
|
key[0] ^= 1;
|
||||||
|
assert_err!(ControlCipher::new(key).open(Direction::HostToClient, &v.bytes("h_rumble_0_frame")), Error::Crypto);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_parser_hostile_sizes() {
|
||||||
|
let frame_of = |total: usize| {
|
||||||
|
let mut f = vec![0x01, 0x00];
|
||||||
|
f.extend_from_slice(&((total - 4) as u16).to_le_bytes());
|
||||||
|
f.resize(total, 0xAB);
|
||||||
|
f
|
||||||
|
};
|
||||||
|
assert_err!(parse_encrypted_frame(&[]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_encrypted_frame(&[0x01]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_encrypted_frame(&frame_of(MIN_FRAME_BYTES)[..MIN_FRAME_BYTES - 1]), Error::Truncated { .. });
|
||||||
|
assert_err!(
|
||||||
|
parse_encrypted_frame(&frame_of(FRAME_HEADER_LEN)),
|
||||||
|
Error::Truncated { .. },
|
||||||
|
"no room for a message header"
|
||||||
|
);
|
||||||
|
assert_eq!(parse_encrypted_frame(&frame_of(MIN_FRAME_BYTES)).unwrap().ciphertext.len(), 4);
|
||||||
|
assert_eq!(
|
||||||
|
parse_encrypted_frame(&frame_of(MAX_FRAME_BYTES - 1)).unwrap().ciphertext.len(),
|
||||||
|
MAX_FRAME_BYTES - 1 - FRAME_HEADER_LEN
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
parse_encrypted_frame(&frame_of(MAX_FRAME_BYTES)).unwrap().ciphertext.len(),
|
||||||
|
MAX_FRAME_BYTES - FRAME_HEADER_LEN
|
||||||
|
);
|
||||||
|
let mut over = frame_of(MAX_FRAME_BYTES);
|
||||||
|
over.push(0);
|
||||||
|
assert_too_large!(parse_encrypted_frame(&over), MAX_FRAME_BYTES, MAX_FRAME_BYTES + 1);
|
||||||
|
assert_too_large!(parse_encrypted_frame(&vec![1; 1 << 20]), MAX_FRAME_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_parser_lying_lengths() {
|
||||||
|
let mut f = vec![0x01, 0x00, 0, 0, 1, 0, 0, 0];
|
||||||
|
f.extend_from_slice(&[0; 16]);
|
||||||
|
f.extend_from_slice(&[9; 10]);
|
||||||
|
for (len, why) in [
|
||||||
|
(f.len() - 4 + 1, "over by one"),
|
||||||
|
(f.len() - 4 - 1, "under by one"),
|
||||||
|
(0xFFFF, "max"),
|
||||||
|
(0, "zero"),
|
||||||
|
(20, "header only"),
|
||||||
|
] {
|
||||||
|
let mut t = f.clone();
|
||||||
|
t[2..4].copy_from_slice(&(len as u16).to_le_bytes());
|
||||||
|
assert_err!(parse_encrypted_frame(&t), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
let mut t = f.clone();
|
||||||
|
t[0..2].copy_from_slice(&0x0002u16.to_le_bytes());
|
||||||
|
assert_err!(parse_encrypted_frame(&t), Error::UnexpectedValue { .. });
|
||||||
|
t[0..2].copy_from_slice(&0x0100u16.to_le_bytes());
|
||||||
|
assert_err!(parse_encrypted_frame(&t), Error::UnexpectedValue { .. }, "big-endian 0x0001");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ messages
|
||||||
|
|
||||||
|
fn msg(ty: u16, body: &[u8]) -> Vec<u8> {
|
||||||
|
let mut m = ty.to_le_bytes().to_vec();
|
||||||
|
m.extend_from_slice(&(body.len() as u16).to_le_bytes());
|
||||||
|
m.extend_from_slice(body);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn message_split() {
|
||||||
|
let m = msg(0x010b, &[1, 2, 3]);
|
||||||
|
let r = parse_message(&m).unwrap();
|
||||||
|
assert_eq!(r.message_type, 0x010b);
|
||||||
|
assert_eq!(r.body, &[1, 2, 3]);
|
||||||
|
assert_eq!(parse_message(&msg(0x7777, &[])).unwrap().body, &[] as &[u8]);
|
||||||
|
assert_err!(parse_message(&[]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_message(&[0x0b, 0x01, 0x00]), Error::Truncated { .. });
|
||||||
|
let mut over = msg(0x010b, &[1, 2, 3]);
|
||||||
|
over[2] = 4;
|
||||||
|
assert_err!(parse_message(&over), Error::Malformed { .. }, "length over");
|
||||||
|
let mut under = msg(0x010b, &[1, 2, 3]);
|
||||||
|
under[2] = 2;
|
||||||
|
assert_err!(parse_message(&under), Error::Malformed { .. }, "length under");
|
||||||
|
let mut lie = msg(0x010b, &[1, 2, 3]);
|
||||||
|
lie[2..4].copy_from_slice(&0xFFFFu16.to_le_bytes());
|
||||||
|
assert_err!(parse_message(&lie), Error::Malformed { .. }, "length 65535");
|
||||||
|
let max = msg(0x7777, &vec![0; MAX_MESSAGE_BYTES - 4]);
|
||||||
|
assert_eq!(parse_message(&max).unwrap().body.len(), MAX_MESSAGE_BYTES - 4);
|
||||||
|
assert_too_large!(
|
||||||
|
parse_message(&msg(0x7777, &vec![0; MAX_MESSAGE_BYTES - 3])),
|
||||||
|
MAX_MESSAGE_BYTES,
|
||||||
|
MAX_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn message_type_codes() {
|
||||||
|
for (code, t) in [
|
||||||
|
(0x0305, MessageType::StartA),
|
||||||
|
(0x0307, MessageType::StartB),
|
||||||
|
(0x0301, MessageType::InvalidateRefFrames),
|
||||||
|
(0x0302, MessageType::IdrFrame),
|
||||||
|
(0x0201, MessageType::LossStats),
|
||||||
|
(0x0204, MessageType::FrameStats),
|
||||||
|
(0x0206, MessageType::InputData),
|
||||||
|
(0x0200, MessageType::PeriodicPing),
|
||||||
|
(0x0100, MessageType::Termination),
|
||||||
|
(0x0109, MessageType::TerminationExtended),
|
||||||
|
(0x010e, MessageType::HdrMode),
|
||||||
|
(0x010b, MessageType::RumbleData),
|
||||||
|
(0x5500, MessageType::RumbleTriggers),
|
||||||
|
(0x5501, MessageType::MotionEvent),
|
||||||
|
(0x5502, MessageType::RgbLed),
|
||||||
|
(0x5503, MessageType::TriggerEffect),
|
||||||
|
] {
|
||||||
|
assert_eq!(MessageType::try_from(code), Ok(t), "{code:#06x}");
|
||||||
|
assert_eq!(t as u16, code);
|
||||||
|
}
|
||||||
|
for code in [0u16, 0x0001, 0x0101, 0x5504, 0xFFFF] {
|
||||||
|
assert_err!(MessageType::try_from(code), Error::UnexpectedValue { .. }, "{code:#06x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_messages_from_the_field_tables() {
|
||||||
|
// Host event bodies are taken as little-endian (UNKNOWN U23), except the extended termination code (BE).
|
||||||
|
let cases = [
|
||||||
|
(
|
||||||
|
msg(0x010b, &[0, 0, 0, 0, 0x01, 0x00, 0xFF, 0x7F, 0x00, 0x80]),
|
||||||
|
HostMessage::Rumble { controller: 1, low_frequency: 0x7FFF, high_frequency: 0x8000 },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5500, &[0x02, 0x00, 0x34, 0x12, 0xCD, 0xAB]),
|
||||||
|
HostMessage::RumbleTriggers { controller: 2, left: 0x1234, right: 0xABCD },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5501, &[0x03, 0x00, 0xC8, 0x00, 0x01]),
|
||||||
|
HostMessage::MotionEvent { controller: 3, rate_hz: 200, kind: MotionKind::Accelerometer },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5501, &[0x03, 0x00, 0x00, 0x00, 0x02]),
|
||||||
|
HostMessage::MotionEvent { controller: 3, rate_hz: 0, kind: MotionKind::Gyroscope },
|
||||||
|
),
|
||||||
|
(
|
||||||
|
msg(0x5502, &[0x03, 0x00, 0x10, 0x20, 0xFF]),
|
||||||
|
HostMessage::RgbLed { controller: 3, r: 0x10, g: 0x20, b: 0xFF },
|
||||||
|
),
|
||||||
|
(msg(0x0109, &[0x80, 0x03, 0x00, 0x23]), HostMessage::Termination { error_code: Some(0x8003_0023) }),
|
||||||
|
(msg(0x0109, &[0x00, 0x00, 0x00, 0x01]), HostMessage::Termination { error_code: Some(1) }),
|
||||||
|
(msg(0x0100, &[]), HostMessage::Termination { error_code: None }),
|
||||||
|
(msg(0x010e, &[0x00]), HostMessage::HdrMode { enabled: false, metadata: None }),
|
||||||
|
(msg(0x7777, &[1, 2, 3]), HostMessage::Other { message_type: 0x7777, body_len: 3 }),
|
||||||
|
(msg(0x5503, &[9; 12]), HostMessage::Other { message_type: 0x5503, body_len: 12 }),
|
||||||
|
];
|
||||||
|
for (bytes, want) in cases {
|
||||||
|
assert_eq!(parse_host_message(&bytes), Ok(want.clone()), "{want:?}");
|
||||||
|
}
|
||||||
|
// HDR on with metadata.
|
||||||
|
let mut body = vec![0x01];
|
||||||
|
body.extend((1..=15u16).flat_map(|i| (i * 1000).to_le_bytes()));
|
||||||
|
match parse_host_message(&msg(0x010e, &body)).unwrap() {
|
||||||
|
HostMessage::HdrMode { enabled, metadata } => {
|
||||||
|
assert!(enabled);
|
||||||
|
let m = metadata.expect("31-byte body carries metadata");
|
||||||
|
assert_eq!(m.display_primaries[0], (1000, 2000), "first two u16 are the red primary");
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
// The plaintexts of the .NET vectors are messages too.
|
||||||
|
let v = common::control_vectors();
|
||||||
|
assert_eq!(
|
||||||
|
parse_host_message(&v.bytes("h_termination_ffffffff_plain")),
|
||||||
|
Ok(HostMessage::Termination { error_code: Some(0x8003_0023) })
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_messages_with_wrong_bodies() {
|
||||||
|
for (ty, len) in [
|
||||||
|
(0x010b, 9),
|
||||||
|
(0x010b, 11),
|
||||||
|
(0x5500, 5),
|
||||||
|
(0x5500, 7),
|
||||||
|
(0x5501, 4),
|
||||||
|
(0x5501, 6),
|
||||||
|
(0x5502, 4),
|
||||||
|
(0x5502, 6),
|
||||||
|
(0x0109, 3),
|
||||||
|
(0x0109, 5),
|
||||||
|
(0x010e, 0),
|
||||||
|
(0x010e, 10),
|
||||||
|
(0x010e, 32),
|
||||||
|
] {
|
||||||
|
assert_err!(
|
||||||
|
parse_host_message(&msg(ty, &vec![0x01; len])),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{ty:#06x} with {len} bytes"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
for kind in [0u8, 3, 0xFF] {
|
||||||
|
assert_err!(
|
||||||
|
parse_host_message(&msg(0x5501, &[0, 0, 1, 0, kind])),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"motion kind {kind}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert_err!(parse_host_message(&[0x0b, 0x01]), Error::Truncated { .. });
|
||||||
|
let mut lie = msg(0x010b, &[0; 10]);
|
||||||
|
lie[2] = 200;
|
||||||
|
assert_err!(parse_host_message(&lie), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_messages() {
|
||||||
|
let m = encode_client_message(&ClientMessage::InvalidateRefFrames { first: 5, last: 9 }).unwrap();
|
||||||
|
let mut want = vec![0x01, 0x03, 0x18, 0x00];
|
||||||
|
want.extend_from_slice(&5u32.to_le_bytes());
|
||||||
|
want.extend_from_slice(&[0; 4]);
|
||||||
|
want.extend_from_slice(&9u32.to_le_bytes());
|
||||||
|
want.extend_from_slice(&[0; 12]);
|
||||||
|
assert_eq!(m, want);
|
||||||
|
let ev = InputEvent::MouseMoveRel { dx: -1, dy: 0 };
|
||||||
|
assert_eq!(
|
||||||
|
encode_client_message(&ClientMessage::Input(ev.clone())).unwrap(),
|
||||||
|
domistream::input::encode_input(&ev).unwrap()
|
||||||
|
);
|
||||||
|
// Bodies still UNKNOWN (U10) are refused rather than guessed.
|
||||||
|
for m in [ClientMessage::StartA, ClientMessage::StartB, ClientMessage::PeriodicPing, ClientMessage::RequestIdrFrame]
|
||||||
|
{
|
||||||
|
assert_err!(encode_client_message(&m), Error::Unsupported { .. }, "{m:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn message_parsers_never_panic(data in proptest::collection::vec(any::<u8>(), 0..300)) {
|
||||||
|
let raw = parse_message(&data);
|
||||||
|
prop_assert!(common::implemented(&raw));
|
||||||
|
if let Ok(raw) = raw {
|
||||||
|
prop_assert_eq!(raw.body.len() + 4, data.len());
|
||||||
|
}
|
||||||
|
let host = parse_host_message(&data);
|
||||||
|
prop_assert!(common::implemented(&host));
|
||||||
|
if let Ok(HostMessage::Other { body_len, .. }) = host {
|
||||||
|
prop_assert_eq!(body_len + 4, data.len());
|
||||||
|
}
|
||||||
|
prop_assert!(common::implemented(&parse_encrypted_frame(&data)));
|
||||||
|
prop_assert!(common::implemented(&ControlCipher::new([3; 16]).open(Direction::HostToClient, &data)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn open_never_accepts_random_frames(seq in any::<u32>(), tag in proptest::array::uniform16(any::<u8>()), ct in proptest::collection::vec(any::<u8>(), 4..64)) {
|
||||||
|
let mut f = vec![0x01, 0x00];
|
||||||
|
f.extend_from_slice(&((4 + 16 + ct.len()) as u16).to_le_bytes());
|
||||||
|
f.extend_from_slice(&seq.to_le_bytes());
|
||||||
|
f.extend_from_slice(&tag);
|
||||||
|
f.extend_from_slice(&ct);
|
||||||
|
prop_assert_eq!(ControlCipher::new([3; 16]).open(Direction::HostToClient, &f), Err(Error::Crypto));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ control stream
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"control-test-key";
|
||||||
|
|
||||||
|
fn stream_config() -> ControlConfig {
|
||||||
|
ControlConfig {
|
||||||
|
enet: EnetConfig {
|
||||||
|
channel_count: 1,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
},
|
||||||
|
rikey: KEY,
|
||||||
|
ping_interval: Duration::from_millis(100),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Host {
|
||||||
|
stream: ControlStream,
|
||||||
|
to_client: u16,
|
||||||
|
reliable: u16,
|
||||||
|
now_ms: u64,
|
||||||
|
host: ControlCipher,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Host {
|
||||||
|
fn deliver(&mut self, frame: Vec<u8>) {
|
||||||
|
self.reliable = self.reliable.wrapping_add(1);
|
||||||
|
let c = Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: 0,
|
||||||
|
reliable_sequence: self.reliable,
|
||||||
|
body: CommandBody::SendReliable(frame),
|
||||||
|
};
|
||||||
|
self.now_ms += 1;
|
||||||
|
let d = encode_datagram(&Datagram {
|
||||||
|
peer_id: self.to_client,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(self.now_ms as u16),
|
||||||
|
commands: vec![c],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
self.stream.handle_datagram(Instant::from_micros(self.now_ms * 1000), &d).expect("a well-formed datagram");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver_sealed(&mut self, seq: u32, plain: &[u8]) {
|
||||||
|
let f = self.host.seal(seq, Direction::HostToClient, plain).unwrap();
|
||||||
|
self.deliver(f);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn events(&mut self) -> Vec<ControlEvent> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(e) = self.stream.poll_event() {
|
||||||
|
out.push(e);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frames the client sent on channel 0, opened.
|
||||||
|
fn sent_frames(&mut self) -> Vec<(u32, Vec<u8>)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(d) = self.stream.poll_transmit(Instant::from_micros(self.now_ms * 1000)) {
|
||||||
|
for c in parse_datagram(&d).unwrap().commands {
|
||||||
|
let data = match c.body {
|
||||||
|
CommandBody::SendReliable(data) if c.channel_id == 0 => data,
|
||||||
|
_ => continue,
|
||||||
|
};
|
||||||
|
out.push(self.host.open(Direction::ClientToHost, &data).expect("the client seals with 'C'"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn connected_stream() -> Host {
|
||||||
|
let mut stream =
|
||||||
|
ControlStream::connect(stream_config(), Instant::ZERO, &mut SeqRng::new(11)).expect("ControlStream::connect");
|
||||||
|
let d = parse_datagram(&stream.poll_transmit(Instant::ZERO).expect("connect datagram")).unwrap();
|
||||||
|
let (params, seq) = d
|
||||||
|
.commands
|
||||||
|
.iter()
|
||||||
|
.find_map(|c| match &c.body {
|
||||||
|
CommandBody::Connect { params, .. } => Some((*params, c.reliable_sequence)),
|
||||||
|
_ => None,
|
||||||
|
})
|
||||||
|
.expect("connect");
|
||||||
|
let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
|
||||||
|
let reply = encode_datagram(&Datagram {
|
||||||
|
peer_id: params.outgoing_peer_id,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(1),
|
||||||
|
commands: vec![
|
||||||
|
Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: 0xFF,
|
||||||
|
reliable_sequence: 0,
|
||||||
|
body: CommandBody::Acknowledge {
|
||||||
|
received_reliable_sequence: seq,
|
||||||
|
received_sent_time: d.sent_time.unwrap_or(0),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: 0xFF,
|
||||||
|
reliable_sequence: 1,
|
||||||
|
body: CommandBody::VerifyConnect(verify),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
stream.handle_datagram(Instant::from_micros(1000), &reply).unwrap();
|
||||||
|
let mut h =
|
||||||
|
Host { stream, to_client: params.outgoing_peer_id, reliable: 0, now_ms: 1, host: ControlCipher::new(KEY) };
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Connected]);
|
||||||
|
h
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rumble(controller: u16) -> (Vec<u8>, HostMessage) {
|
||||||
|
(
|
||||||
|
msg(0x010b, &[0, 0, 0, 0, controller as u8, 0, 1, 0, 2, 0]),
|
||||||
|
HostMessage::Rumble { controller, low_frequency: 1, high_frequency: 2 },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_frames_in_order_and_with_gaps() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
for (seq, c) in [(0u32, 1u16), (1, 2), (2, 3), (10, 4), (1000, 5)] {
|
||||||
|
let (m, want) = rumble(c);
|
||||||
|
h.deliver_sealed(seq, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want)], "seq {seq}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replayed_and_old_host_frames_are_dropped() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let (m, want) = rumble(1);
|
||||||
|
let f5 = h.host.seal(5, Direction::HostToClient, &m).unwrap();
|
||||||
|
h.deliver(f5.clone());
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want.clone())]);
|
||||||
|
// The very same frame again (new ENet command, so ENet itself delivers it): a replay.
|
||||||
|
h.deliver(f5);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "replayed seq 5");
|
||||||
|
// A valid frame with an older or equal number.
|
||||||
|
h.deliver_sealed(3, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "older seq 3");
|
||||||
|
h.deliver_sealed(5, &rumble(9).0);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "equal seq 5, other content");
|
||||||
|
// The stream continues.
|
||||||
|
h.deliver_sealed(6, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tampered_and_reflected_frames_are_dropped() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let (m, want) = rumble(1);
|
||||||
|
let mut bad = h.host.seal(0, Direction::HostToClient, &m).unwrap();
|
||||||
|
bad[30] ^= 0x10;
|
||||||
|
h.deliver(bad);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "bad tag");
|
||||||
|
// A frame sealed client-to-host (an attacker reflecting the client's own traffic).
|
||||||
|
let reflected = h.host.seal(1, Direction::ClientToHost, &m).unwrap();
|
||||||
|
h.deliver(reflected);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "wrong direction");
|
||||||
|
// A frame under another key.
|
||||||
|
let other = ControlCipher::new([0; 16]).seal(2, Direction::HostToClient, &m).unwrap();
|
||||||
|
h.deliver(other);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "wrong key");
|
||||||
|
// Not a frame at all.
|
||||||
|
h.deliver(vec![0xFF; 40]);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped], "garbage");
|
||||||
|
// A failed frame does not burn its sequence number: seq 0 is still accepted.
|
||||||
|
h.deliver_sealed(0, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want)]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_sequence_at_u32_wrap() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let (m, want) = rumble(1);
|
||||||
|
h.deliver_sealed(0xFFFF_FFFE, &m);
|
||||||
|
h.deliver_sealed(0xFFFF_FFFF, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Message(want.clone()), ControlEvent::Message(want)]);
|
||||||
|
// Nothing is greater than u32::MAX: a wrapped 0 is a replay, never accepted.
|
||||||
|
h.deliver_sealed(0, &m);
|
||||||
|
h.deliver_sealed(1, &m);
|
||||||
|
assert_eq!(h.events(), vec![ControlEvent::Dropped, ControlEvent::Dropped]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_frames_count_up_from_zero() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
let msgs = [
|
||||||
|
ClientMessage::InvalidateRefFrames { first: 1, last: 2 },
|
||||||
|
ClientMessage::Input(InputEvent::MouseMoveRel { dx: 3, dy: -4 }),
|
||||||
|
ClientMessage::Input(InputEvent::Scroll { amount: 120 }),
|
||||||
|
];
|
||||||
|
for m in &msgs {
|
||||||
|
h.stream.send(Instant::from_micros(2000), m).unwrap();
|
||||||
|
}
|
||||||
|
let sent = h.sent_frames();
|
||||||
|
assert_eq!(sent.len(), msgs.len());
|
||||||
|
for (i, ((seq, plain), m)) in sent.iter().zip(&msgs).enumerate() {
|
||||||
|
assert_eq!(*seq, i as u32, "sequence numbers start at 0 and never repeat (U11)");
|
||||||
|
assert_eq!(plain, &encode_client_message(m).unwrap());
|
||||||
|
}
|
||||||
|
assert_err!(h.stream.send(Instant::from_micros(2000), &ClientMessage::StartA), Error::Unsupported { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn closed_stream_refuses() {
|
||||||
|
let mut h = connected_stream();
|
||||||
|
h.stream.close(Instant::from_micros(3000)).unwrap();
|
||||||
|
assert_err!(h.stream.close(Instant::from_micros(3001)), Error::Closed);
|
||||||
|
}
|
||||||
@@ -0,0 +1,813 @@
|
|||||||
|
//! ENet (`docs/PROTOCOL.md` 3.1): the datagram codec against byte vectors built from the field definitions, hostile
|
||||||
|
//! datagrams, and the client peer driven by a scripted host: handshake, reliable sequence numbers at the 0xFFFF
|
||||||
|
//! wrap, duplicates, far-future and far-past, fragments with lying lengths, retransmission and timeouts.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use common::SeqRng;
|
||||||
|
use domistream::enet::protocol::{
|
||||||
|
Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, NO_PEER_ID,
|
||||||
|
encode_datagram, parse_datagram,
|
||||||
|
};
|
||||||
|
use domistream::enet::{Delivery, EnetClient, EnetConfig, EnetEvent, EnetState, MAX_PACKET_BYTES, MAX_SEND_QUEUE};
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
// ================================================================================================ codec vectors
|
||||||
|
|
||||||
|
fn cmd(acknowledge: bool, channel_id: u8, reliable_sequence: u16, body: CommandBody) -> Command {
|
||||||
|
Command { acknowledge, channel_id, reliable_sequence, body }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ping_vector() {
|
||||||
|
// peer 1, session 0, sent-time flag; ping with acknowledge flag on channel 0xFF, reliable sequence 1.
|
||||||
|
let bytes = [0x80, 0x01, 0x12, 0x34, 0x85, 0xFF, 0x00, 0x01];
|
||||||
|
let want = Datagram {
|
||||||
|
peer_id: 1,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(0x1234),
|
||||||
|
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping)],
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&bytes).unwrap(), want);
|
||||||
|
assert_eq!(encode_datagram(&want).unwrap(), bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn acknowledge_reliable_disconnect_vectors() {
|
||||||
|
// peer 0xABC, session 2, no sent time: 0x2ABC.
|
||||||
|
let mut bytes = vec![0x2A, 0xBC];
|
||||||
|
bytes.extend_from_slice(&[0x01, 0x00, 0x00, 0x05, 0x00, 0x07, 0x12, 0x34]); // acknowledge (8)
|
||||||
|
bytes.extend_from_slice(&[0x86, 0x00, 0x00, 0x02, 0x00, 0x03, 0xAA, 0xBB, 0xCC]); // send reliable (6 + 3)
|
||||||
|
bytes.extend_from_slice(&[0x84, 0xFF, 0x00, 0x03, 0x00, 0x00, 0x00, 0x2A]); // disconnect (8)
|
||||||
|
let want = Datagram {
|
||||||
|
peer_id: 0x0ABC,
|
||||||
|
session_id: 2,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![
|
||||||
|
cmd(false, 0, 5, CommandBody::Acknowledge { received_reliable_sequence: 7, received_sent_time: 0x1234 }),
|
||||||
|
cmd(true, 0, 2, CommandBody::SendReliable(vec![0xAA, 0xBB, 0xCC])),
|
||||||
|
cmd(true, 0xFF, 3, CommandBody::Disconnect { data: 42 }),
|
||||||
|
],
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&bytes).unwrap(), want);
|
||||||
|
assert_eq!(encode_datagram(&want).unwrap(), bytes);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn params(connect_id: u32) -> ConnectParams {
|
||||||
|
ConnectParams {
|
||||||
|
outgoing_peer_id: 3,
|
||||||
|
incoming_session_id: 0xFF,
|
||||||
|
outgoing_session_id: 0xFF,
|
||||||
|
mtu: 1400,
|
||||||
|
window_size: 32768,
|
||||||
|
channel_count: 2,
|
||||||
|
incoming_bandwidth: 0,
|
||||||
|
outgoing_bandwidth: 0,
|
||||||
|
packet_throttle_interval: 5000,
|
||||||
|
packet_throttle_acceleration: 2,
|
||||||
|
packet_throttle_deceleration: 2,
|
||||||
|
connect_id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frag(start: u16, count: u32, number: u32, total: u32, offset: u32, data: Vec<u8>) -> Fragment {
|
||||||
|
Fragment {
|
||||||
|
start_sequence: start,
|
||||||
|
fragment_count: count,
|
||||||
|
fragment_number: number,
|
||||||
|
total_length: total,
|
||||||
|
fragment_offset: offset,
|
||||||
|
data,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every command kind, with the total size PROTOCOL.md 3.1 gives for it.
|
||||||
|
fn every_command() -> Vec<(Command, usize)> {
|
||||||
|
vec![
|
||||||
|
(cmd(false, 0, 1, CommandBody::Acknowledge { received_reliable_sequence: 9, received_sent_time: 77 }), 8),
|
||||||
|
(cmd(true, 0xFF, 1, CommandBody::Connect { params: params(0xDEAD_BEEF), data: 0x1234_5678 }), 48),
|
||||||
|
(cmd(true, 0xFF, 1, CommandBody::VerifyConnect(params(0xDEAD_BEEF))), 44),
|
||||||
|
(cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 0 }), 8),
|
||||||
|
(cmd(true, 0xFF, 3, CommandBody::Ping), 4),
|
||||||
|
(cmd(true, 0, 4, CommandBody::SendReliable(vec![1, 2, 3, 4, 5])), 6 + 5),
|
||||||
|
(cmd(false, 1, 4, CommandBody::SendUnreliable { unreliable_sequence: 0xFFFF, data: vec![9; 7] }), 8 + 7),
|
||||||
|
(cmd(true, 0, 5, CommandBody::SendFragment(frag(5, 2, 0, 20, 0, vec![1; 10]))), 24 + 10),
|
||||||
|
(cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 513, data: vec![3; 2] }), 8 + 2),
|
||||||
|
(cmd(true, 0xFF, 6, CommandBody::BandwidthLimit { incoming: 1, outgoing: 2 }), 12),
|
||||||
|
(cmd(true, 0xFF, 7, CommandBody::ThrottleConfigure { interval: 5000, acceleration: 2, deceleration: 2 }), 16),
|
||||||
|
(cmd(false, 0, 8, CommandBody::SendUnreliableFragment(frag(8, 3, 2, 30, 20, vec![4; 10]))), 24 + 10),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_command_round_trips_with_its_wire_size() {
|
||||||
|
for (c, size) in every_command() {
|
||||||
|
for sent_time in [None, Some(0xBEEF)] {
|
||||||
|
let d = Datagram { peer_id: 7, session_id: 1, sent_time, commands: vec![c.clone()] };
|
||||||
|
let bytes = encode_datagram(&d).unwrap();
|
||||||
|
let header = if sent_time.is_some() { 4 } else { 2 };
|
||||||
|
assert_eq!(bytes.len(), header + size, "{:?}", c.body);
|
||||||
|
assert_eq!(bytes[header] & 0x0F, kind(&c.body), "command number of {:?}", c.body);
|
||||||
|
assert_eq!(bytes[header] & 0x80 != 0, c.acknowledge);
|
||||||
|
assert_eq!(parse_datagram(&bytes).unwrap(), d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let all = Datagram {
|
||||||
|
peer_id: 0x0FFF,
|
||||||
|
session_id: 3,
|
||||||
|
sent_time: Some(1),
|
||||||
|
commands: every_command().into_iter().map(|(c, _)| c).collect(),
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&encode_datagram(&all).unwrap()).unwrap(), all);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn kind(b: &CommandBody) -> u8 {
|
||||||
|
match b {
|
||||||
|
CommandBody::Acknowledge { .. } => 1,
|
||||||
|
CommandBody::Connect { .. } => 2,
|
||||||
|
CommandBody::VerifyConnect(_) => 3,
|
||||||
|
CommandBody::Disconnect { .. } => 4,
|
||||||
|
CommandBody::Ping => 5,
|
||||||
|
CommandBody::SendReliable(_) => 6,
|
||||||
|
CommandBody::SendUnreliable { .. } => 7,
|
||||||
|
CommandBody::SendFragment(_) => 8,
|
||||||
|
CommandBody::SendUnsequenced { .. } => 9,
|
||||||
|
CommandBody::BandwidthLimit { .. } => 10,
|
||||||
|
CommandBody::ThrottleConfigure { .. } => 11,
|
||||||
|
CommandBody::SendUnreliableFragment(_) => 12,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unsequenced_carries_its_flag() {
|
||||||
|
let d = Datagram {
|
||||||
|
peer_id: 0,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![cmd(false, 0, 0, CommandBody::SendUnsequenced { unsequenced_group: 1, data: vec![1] })],
|
||||||
|
};
|
||||||
|
let bytes = encode_datagram(&d).unwrap();
|
||||||
|
assert_eq!(bytes[2] & 0x40, 0x40, "unsequenced flag");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ hostile datagrams
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_truncation() {
|
||||||
|
for (bad, why) in [
|
||||||
|
(&[][..], "empty"),
|
||||||
|
(&[0x00][..], "one byte"),
|
||||||
|
(&[0x80, 0x01, 0x12][..], "sent-time flag, cut sent time"),
|
||||||
|
(&[0x00, 0x01, 0x85, 0xFF, 0x00][..], "cut command header"),
|
||||||
|
(&[0x00, 0x01, 0x01, 0x00, 0x00, 0x05, 0x00, 0x07][..], "cut acknowledge"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00][..], "cut data length"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x0A, 1, 2, 3][..], "data length over"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0xFF, 0xFF, 1][..], "data length 65535"),
|
||||||
|
(&[0x00, 0x01, 0x86, 0x00, 0x00, 0x01, 0x00, 0x01, 1, 2, 3][..], "data length under: 2 stray bytes"),
|
||||||
|
] {
|
||||||
|
assert_err!(parse_datagram(bad), Error::Truncated { .. }, "{why}");
|
||||||
|
}
|
||||||
|
// A connect cut at every length.
|
||||||
|
let full = encode_datagram(&Datagram {
|
||||||
|
peer_id: NO_PEER_ID,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(0),
|
||||||
|
commands: vec![every_command()[1].0.clone()],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
for cut in 5..full.len() {
|
||||||
|
assert_err!(parse_datagram(&full[..cut]), Error::Truncated { .. }, "connect cut at {cut}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_values() {
|
||||||
|
assert_err!(parse_datagram(&[0x40, 0x01, 0x85, 0xFF, 0x00, 0x01]), Error::UnexpectedValue { .. }, "compressed");
|
||||||
|
assert_err!(
|
||||||
|
parse_datagram(&[0xC0, 0x01, 0x00, 0x00, 0x85, 0xFF, 0x00, 0x01]),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"compressed + time"
|
||||||
|
);
|
||||||
|
for number in [0u8, 13, 14, 15] {
|
||||||
|
assert_err!(
|
||||||
|
parse_datagram(&[0x00, 0x01, 0x80 | number, 0xFF, 0x00, 0x01, 0, 0, 0, 0]),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"command {number}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// A good command followed by an unknown one: the whole datagram is refused.
|
||||||
|
assert_err!(
|
||||||
|
parse_datagram(&[0x00, 0x01, 0x85, 0xFF, 0x00, 0x01, 0x0E, 0x00, 0x00, 0x00]),
|
||||||
|
Error::UnexpectedValue { .. }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_sizes() {
|
||||||
|
let ping = [0x85, 0xFF, 0x00, 0x01];
|
||||||
|
let pings = |n: usize| {
|
||||||
|
let mut b = vec![0x00, 0x01];
|
||||||
|
for _ in 0..n {
|
||||||
|
b.extend_from_slice(&ping);
|
||||||
|
}
|
||||||
|
b
|
||||||
|
};
|
||||||
|
assert_eq!(parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM)).unwrap().commands.len(), MAX_COMMANDS_PER_DATAGRAM);
|
||||||
|
match parse_datagram(&pings(MAX_COMMANDS_PER_DATAGRAM + 1)) {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_COMMANDS_PER_DATAGRAM),
|
||||||
|
other => panic!("33 commands: {other:?}"),
|
||||||
|
}
|
||||||
|
// A reliable packet filling the datagram exactly; one byte more is over.
|
||||||
|
let reliable = |data: usize| {
|
||||||
|
let mut b = vec![0x00, 0x01, 0x86, 0x00, 0x00, 0x01];
|
||||||
|
b.extend_from_slice(&(data as u16).to_be_bytes());
|
||||||
|
b.extend(std::iter::repeat_n(0x5A, data));
|
||||||
|
b
|
||||||
|
};
|
||||||
|
let max_data = MAX_DATAGRAM_BYTES - 8;
|
||||||
|
assert_eq!(reliable(max_data).len(), MAX_DATAGRAM_BYTES);
|
||||||
|
assert!(parse_datagram(&reliable(max_data)).is_ok());
|
||||||
|
assert_eq!(parse_datagram(&reliable(max_data - 1)).unwrap().commands.len(), 1);
|
||||||
|
assert_too_large!(parse_datagram(&reliable(max_data + 1)), MAX_DATAGRAM_BYTES, MAX_DATAGRAM_BYTES + 1);
|
||||||
|
assert_too_large!(parse_datagram(&vec![0; 1 << 20]), MAX_DATAGRAM_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_refuses_oversized() {
|
||||||
|
let many = Datagram {
|
||||||
|
peer_id: 0,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![cmd(true, 0xFF, 1, CommandBody::Ping); MAX_COMMANDS_PER_DATAGRAM + 1],
|
||||||
|
};
|
||||||
|
assert!(matches!(encode_datagram(&many), Err(Error::TooLarge { .. })));
|
||||||
|
let big = Datagram {
|
||||||
|
peer_id: 0,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: None,
|
||||||
|
commands: vec![cmd(true, 0, 1, CommandBody::SendReliable(vec![0; MAX_DATAGRAM_BYTES]))],
|
||||||
|
};
|
||||||
|
assert!(matches!(encode_datagram(&big), Err(Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn body() -> impl Strategy<Value = CommandBody> {
|
||||||
|
let data = || proptest::collection::vec(any::<u8>(), 0..64);
|
||||||
|
let fragment = || {
|
||||||
|
(any::<u16>(), any::<u32>(), any::<u32>(), any::<u32>(), any::<u32>(), data())
|
||||||
|
.prop_map(|(a, b, c, d, e, f)| frag(a, b, c, d, e, f))
|
||||||
|
};
|
||||||
|
let cparams = || {
|
||||||
|
proptest::array::uniform12(any::<u32>()).prop_map(|a| ConnectParams {
|
||||||
|
outgoing_peer_id: (a[0] & 0xFFFF) as u16,
|
||||||
|
incoming_session_id: a[1] as u8,
|
||||||
|
outgoing_session_id: (a[1] >> 8) as u8,
|
||||||
|
mtu: a[2],
|
||||||
|
window_size: a[3],
|
||||||
|
channel_count: a[4],
|
||||||
|
incoming_bandwidth: a[5],
|
||||||
|
outgoing_bandwidth: a[6],
|
||||||
|
packet_throttle_interval: a[7],
|
||||||
|
packet_throttle_acceleration: a[8],
|
||||||
|
packet_throttle_deceleration: a[9],
|
||||||
|
connect_id: a[10],
|
||||||
|
})
|
||||||
|
};
|
||||||
|
prop_oneof![
|
||||||
|
(any::<u16>(), any::<u16>())
|
||||||
|
.prop_map(|(a, b)| CommandBody::Acknowledge { received_reliable_sequence: a, received_sent_time: b }),
|
||||||
|
(cparams(), any::<u32>()).prop_map(|(params, data)| CommandBody::Connect { params, data }),
|
||||||
|
cparams().prop_map(CommandBody::VerifyConnect),
|
||||||
|
any::<u32>().prop_map(|data| CommandBody::Disconnect { data }),
|
||||||
|
Just(CommandBody::Ping),
|
||||||
|
data().prop_map(CommandBody::SendReliable),
|
||||||
|
(any::<u16>(), data())
|
||||||
|
.prop_map(|(unreliable_sequence, data)| CommandBody::SendUnreliable { unreliable_sequence, data }),
|
||||||
|
fragment().prop_map(CommandBody::SendFragment),
|
||||||
|
(any::<u16>(), data())
|
||||||
|
.prop_map(|(unsequenced_group, data)| CommandBody::SendUnsequenced { unsequenced_group, data }),
|
||||||
|
(any::<u32>(), any::<u32>())
|
||||||
|
.prop_map(|(incoming, outgoing)| CommandBody::BandwidthLimit { incoming, outgoing }),
|
||||||
|
(any::<u32>(), any::<u32>(), any::<u32>()).prop_map(|(interval, acceleration, deceleration)| {
|
||||||
|
CommandBody::ThrottleConfigure { interval, acceleration, deceleration }
|
||||||
|
}),
|
||||||
|
fragment().prop_map(CommandBody::SendUnreliableFragment),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn datagram_round_trip(
|
||||||
|
peer_id in 0u16..=0x0FFF,
|
||||||
|
session_id in 0u8..4,
|
||||||
|
sent_time in proptest::option::of(any::<u16>()),
|
||||||
|
commands in proptest::collection::vec((any::<bool>(), any::<u8>(), any::<u16>(), body()), 1..8),
|
||||||
|
) {
|
||||||
|
let commands = commands.into_iter().map(|(a, ch, s, b)| cmd(a, ch, s, b)).collect();
|
||||||
|
let d = Datagram { peer_id, session_id, sent_time, commands };
|
||||||
|
let bytes = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
prop_assert!(bytes.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
prop_assert_eq!(parse_datagram(&bytes), Ok(d));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary bytes: no panic; a parsed datagram re-encodes to something that parses to the same value.
|
||||||
|
#[test]
|
||||||
|
fn datagram_parse_is_stable(data in proptest::collection::vec(any::<u8>(), 0..512)) {
|
||||||
|
let parsed = parse_datagram(&data);
|
||||||
|
prop_assert!(common::implemented(&parsed));
|
||||||
|
if let Ok(d) = parsed {
|
||||||
|
prop_assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM);
|
||||||
|
prop_assert!(d.peer_id <= 0x0FFF && d.session_id < 4);
|
||||||
|
let again = encode_datagram(&d).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
prop_assert_eq!(parse_datagram(&again), Ok(d));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ client peer
|
||||||
|
|
||||||
|
fn config() -> EnetConfig {
|
||||||
|
EnetConfig {
|
||||||
|
channel_count: 2,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0x0000_1234,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn at(ms: u64) -> Instant {
|
||||||
|
Instant::from_micros(ms * 1000)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The client and the scripted host's view of it.
|
||||||
|
struct Link {
|
||||||
|
client: EnetClient,
|
||||||
|
/// Peer id the host addresses the client with (from the client's connect).
|
||||||
|
to_client: u16,
|
||||||
|
/// Next reliable sequence the host uses per channel.
|
||||||
|
host_seq: [u16; 256],
|
||||||
|
now_ms: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Link {
|
||||||
|
fn host_datagram(&self, commands: Vec<Command>) -> Vec<u8> {
|
||||||
|
encode_datagram(&Datagram {
|
||||||
|
peer_id: self.to_client,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(self.now_ms as u16),
|
||||||
|
commands,
|
||||||
|
})
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn feed(&mut self, commands: Vec<Command>) -> domistream::Result<()> {
|
||||||
|
self.now_ms += 1;
|
||||||
|
let d = self.host_datagram(commands);
|
||||||
|
self.client.handle_datagram(at(self.now_ms), &d)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn reliable(&mut self, channel: u8, data: &[u8]) -> Command {
|
||||||
|
let s = &mut self.host_seq[usize::from(channel)];
|
||||||
|
*s = s.wrapping_add(1);
|
||||||
|
cmd(true, channel, *s, CommandBody::SendReliable(data.to_vec()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything the client wants to send now, parsed.
|
||||||
|
fn transmitted(&mut self) -> Vec<Datagram> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(d) = self.client.poll_transmit(at(self.now_ms)) {
|
||||||
|
assert!(d.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
out.push(parse_datagram(&d).expect("the client's datagrams parse"));
|
||||||
|
assert!(out.len() < 10_000, "poll_transmit never ends");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn events(&mut self) -> Vec<EnetEvent> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(e) = self.client.poll_event() {
|
||||||
|
out.push(e);
|
||||||
|
assert!(out.len() < 100_000, "poll_event never ends");
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn received(&mut self) -> Vec<Vec<u8>> {
|
||||||
|
self.events()
|
||||||
|
.into_iter()
|
||||||
|
.map(|e| match e {
|
||||||
|
EnetEvent::Received { data, .. } => data,
|
||||||
|
other => panic!("unexpected event {other:?}"),
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Starts a client and returns it with its connect command.
|
||||||
|
fn start() -> (EnetClient, Datagram, ConnectParams, u32, u16) {
|
||||||
|
let mut client = EnetClient::connect(config(), at(0), &mut SeqRng::new(5)).expect("EnetClient::connect");
|
||||||
|
assert_eq!(client.state(), EnetState::Connecting);
|
||||||
|
let d = parse_datagram(&client.poll_transmit(at(0)).expect("connect datagram")).unwrap();
|
||||||
|
let c =
|
||||||
|
d.commands.iter().find(|c| matches!(c.body, CommandBody::Connect { .. })).expect("a connect command").clone();
|
||||||
|
let (params, data) = match c.body {
|
||||||
|
CommandBody::Connect { params, data } => (params, data),
|
||||||
|
_ => unreachable!(),
|
||||||
|
};
|
||||||
|
(client, d.clone(), params, data, c.reliable_sequence)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A connected link: connect, then the host's acknowledge + verify connect.
|
||||||
|
fn connected() -> Link {
|
||||||
|
let (client, d, params, _, connect_seq) = start();
|
||||||
|
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
|
||||||
|
let verify = ConnectParams { outgoing_peer_id: 0, incoming_session_id: 0, outgoing_session_id: 0, ..params };
|
||||||
|
link.feed(vec![
|
||||||
|
cmd(
|
||||||
|
false,
|
||||||
|
0xFF,
|
||||||
|
0,
|
||||||
|
CommandBody::Acknowledge {
|
||||||
|
received_reliable_sequence: connect_seq,
|
||||||
|
received_sent_time: d.sent_time.unwrap_or(0),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify)),
|
||||||
|
])
|
||||||
|
.expect("verify connect");
|
||||||
|
assert_eq!(link.events(), vec![EnetEvent::Connected]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
link.transmitted();
|
||||||
|
link
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn connect_offers_the_config() {
|
||||||
|
let (_, d, params, data, _) = start();
|
||||||
|
assert_eq!(d.peer_id, NO_PEER_ID, "no peer id yet");
|
||||||
|
assert_eq!(params.mtu, u32::from(config().mtu));
|
||||||
|
assert_eq!(params.channel_count, u32::from(config().channel_count));
|
||||||
|
assert_eq!(data, config().connect_data);
|
||||||
|
let c = &d.commands[0];
|
||||||
|
assert!(c.acknowledge && c.channel_id == 0xFF, "connect is reliable, connection-level");
|
||||||
|
// The connect id comes from the caller's randomness.
|
||||||
|
let (_, _, p2, _, _) = start();
|
||||||
|
assert_eq!(p2.connect_id, params.connect_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn connect_refuses_configs_outside_enet_limits() {
|
||||||
|
for bad in [
|
||||||
|
EnetConfig { mtu: 575, ..config() },
|
||||||
|
EnetConfig { mtu: 4097, ..config() },
|
||||||
|
EnetConfig { mtu: 0, ..config() },
|
||||||
|
EnetConfig { channel_count: 0, ..config() },
|
||||||
|
] {
|
||||||
|
assert_err!(EnetClient::connect(bad, at(0), &mut SeqRng::new(1)), Error::Malformed { .. }, "{bad:?}");
|
||||||
|
}
|
||||||
|
for ok in [
|
||||||
|
EnetConfig { mtu: 576, ..config() },
|
||||||
|
EnetConfig { mtu: 4096, ..config() },
|
||||||
|
EnetConfig { channel_count: 255, ..config() },
|
||||||
|
] {
|
||||||
|
assert!(EnetClient::connect(ok, at(0), &mut SeqRng::new(1)).is_ok(), "{ok:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn verify_with_wrong_connect_id_does_not_connect() {
|
||||||
|
let (client, _, params, _, _) = start();
|
||||||
|
let mut link = Link { client, to_client: params.outgoing_peer_id, host_seq: [0; 256], now_ms: 0 };
|
||||||
|
let verify = ConnectParams {
|
||||||
|
connect_id: params.connect_id ^ 1,
|
||||||
|
outgoing_peer_id: 0,
|
||||||
|
incoming_session_id: 0,
|
||||||
|
outgoing_session_id: 0,
|
||||||
|
..params
|
||||||
|
};
|
||||||
|
let _ = link.feed(vec![cmd(true, 0xFF, 1, CommandBody::VerifyConnect(verify))]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connecting);
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn garbage_never_changes_state() {
|
||||||
|
let mut link = connected();
|
||||||
|
for bad in [&[][..], &[0x00][..], &[0x40, 0x00, 0x85, 0xFF, 0, 1][..], &[0x00, 0x00, 0x8F, 0, 0, 0][..]] {
|
||||||
|
assert!(link.client.handle_datagram(at(5), bad).is_err(), "{bad:?}");
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
link.client.handle_datagram(at(5), &vec![0; MAX_DATAGRAM_BYTES + 1]),
|
||||||
|
MAX_DATAGRAM_BYTES,
|
||||||
|
MAX_DATAGRAM_BYTES + 1
|
||||||
|
);
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn datagrams_for_another_peer_are_dropped() {
|
||||||
|
let mut link = connected();
|
||||||
|
let c = link.reliable(0, b"not for you");
|
||||||
|
let other = encode_datagram(&Datagram {
|
||||||
|
peer_id: link.to_client ^ 0x0001,
|
||||||
|
session_id: 0,
|
||||||
|
sent_time: Some(1),
|
||||||
|
commands: vec![c],
|
||||||
|
})
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(link.client.handle_datagram(at(9), &other), Ok(()));
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reliable_in_order_reordered_and_duplicated() {
|
||||||
|
let mut link = connected();
|
||||||
|
let a = link.reliable(0, b"one");
|
||||||
|
let b = link.reliable(0, b"two");
|
||||||
|
let c = link.reliable(0, b"three");
|
||||||
|
link.feed(vec![c.clone()]).unwrap();
|
||||||
|
link.feed(vec![b.clone()]).unwrap();
|
||||||
|
assert!(link.received().is_empty(), "nothing before sequence 1");
|
||||||
|
link.feed(vec![a.clone()]).unwrap();
|
||||||
|
assert_eq!(link.received(), vec![b"one".to_vec(), b"two".to_vec(), b"three".to_vec()]);
|
||||||
|
// Duplicates (retransmissions by the host) are acknowledged but never delivered twice.
|
||||||
|
link.feed(vec![a, b.clone(), c]).unwrap();
|
||||||
|
link.feed(vec![b]).unwrap();
|
||||||
|
assert!(link.received().is_empty());
|
||||||
|
let acks: usize = link
|
||||||
|
.transmitted()
|
||||||
|
.iter()
|
||||||
|
.flat_map(|d| &d.commands)
|
||||||
|
.filter(|c| matches!(c.body, CommandBody::Acknowledge { .. }))
|
||||||
|
.count();
|
||||||
|
assert!(acks >= 4, "duplicates are still acknowledged ({acks})");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reliable_sequence_wraps_at_0xffff() {
|
||||||
|
// 70 000 reliable packets, one per datagram: the sequence passes 0xFFFF -> 0 and order is kept.
|
||||||
|
let mut link = connected();
|
||||||
|
let total = 70_000u32;
|
||||||
|
let mut got = 0u32;
|
||||||
|
for i in 0..total {
|
||||||
|
let c = link.reliable(0, &i.to_le_bytes());
|
||||||
|
link.feed(vec![c]).unwrap();
|
||||||
|
for data in link.received() {
|
||||||
|
assert_eq!(data, got.to_le_bytes(), "packet {got} out of order");
|
||||||
|
got += 1;
|
||||||
|
}
|
||||||
|
link.transmitted();
|
||||||
|
}
|
||||||
|
assert_eq!(got, total);
|
||||||
|
assert_eq!(link.host_seq[0], (total % 65_536) as u16);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn far_future_and_far_past_are_dropped() {
|
||||||
|
let mut link = connected();
|
||||||
|
for i in 0..10u8 {
|
||||||
|
let c = link.reliable(0, &[i]);
|
||||||
|
link.feed(vec![c]).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(link.received().len(), 10);
|
||||||
|
let next = link.host_seq[0];
|
||||||
|
for seq in [next.wrapping_add(40_000), next.wrapping_add(0x8000), next.wrapping_sub(30_000), next.wrapping_sub(5)] {
|
||||||
|
let _ = link.feed(vec![cmd(true, 0, seq, CommandBody::SendReliable(b"evil".to_vec()))]);
|
||||||
|
assert!(link.received().is_empty(), "sequence {seq} (next {next}) must not be delivered");
|
||||||
|
}
|
||||||
|
// The stream continues normally.
|
||||||
|
let c = link.reliable(0, b"ok");
|
||||||
|
link.feed(vec![c]).unwrap();
|
||||||
|
assert_eq!(link.received(), vec![b"ok".to_vec()]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn channels_outside_the_negotiated_count_are_not_delivered() {
|
||||||
|
let mut link = connected();
|
||||||
|
let c = link.reliable(200, b"x");
|
||||||
|
let _ = link.feed(vec![c]);
|
||||||
|
assert!(link.received().is_empty());
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fragments(link: &mut Link, data: &[u8], piece: usize) -> Vec<Command> {
|
||||||
|
let count = data.len().div_ceil(piece) as u32;
|
||||||
|
let start = link.host_seq[0].wrapping_add(1);
|
||||||
|
(0..count)
|
||||||
|
.map(|n| {
|
||||||
|
link.host_seq[0] = link.host_seq[0].wrapping_add(1);
|
||||||
|
let off = n as usize * piece;
|
||||||
|
let chunk = data[off..(off + piece).min(data.len())].to_vec();
|
||||||
|
cmd(
|
||||||
|
true,
|
||||||
|
0,
|
||||||
|
link.host_seq[0],
|
||||||
|
CommandBody::SendFragment(frag(start, count, n, data.len() as u32, off as u32, chunk)),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fragments_reassemble_in_any_order() {
|
||||||
|
let mut link = connected();
|
||||||
|
let data: Vec<u8> = (0..3000u32).map(|i| (i * 7) as u8).collect();
|
||||||
|
let mut frags = fragments(&mut link, &data, 1000);
|
||||||
|
frags.swap(0, 2);
|
||||||
|
for f in frags {
|
||||||
|
link.feed(vec![f]).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(link.received(), vec![data]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fragments_with_lying_lengths() {
|
||||||
|
// Total length over the reassembly cap.
|
||||||
|
let mut link = connected();
|
||||||
|
link.host_seq[0] += 1;
|
||||||
|
let s = link.host_seq[0];
|
||||||
|
let r = link.feed(vec![cmd(
|
||||||
|
true,
|
||||||
|
0,
|
||||||
|
s,
|
||||||
|
CommandBody::SendFragment(frag(s, 2, 0, MAX_PACKET_BYTES as u32 + 1, 0, vec![0; 100])),
|
||||||
|
)]);
|
||||||
|
assert_too_large!(r, MAX_PACKET_BYTES, MAX_PACKET_BYTES + 1);
|
||||||
|
assert!(link.events().is_empty());
|
||||||
|
|
||||||
|
// Other lies: never delivered, never a panic, the connection survives.
|
||||||
|
for f in [
|
||||||
|
frag(0, 0, 0, 10, 0, vec![0; 10]), // zero fragments
|
||||||
|
frag(0, 2, 2, 20, 0, vec![0; 10]), // number >= count
|
||||||
|
frag(0, 2, 0, 20, 15, vec![0; 10]), // offset + length past total
|
||||||
|
frag(0, 2, 0, 5, 0, vec![0; 10]), // fragment longer than total
|
||||||
|
frag(0, u32::MAX, 0, 100, 0, vec![0; 10]), // absurd count for a small total
|
||||||
|
frag(0, 2, 0, u32::MAX, 0, vec![0; 10]), // absurd total
|
||||||
|
frag(0, 2, 1, 20, u32::MAX - 3, vec![0; 10]), // offset overflow
|
||||||
|
] {
|
||||||
|
let mut link = connected();
|
||||||
|
link.host_seq[0] += 1;
|
||||||
|
let s = link.host_seq[0];
|
||||||
|
let r =
|
||||||
|
link.feed(vec![cmd(true, 0, s, CommandBody::SendFragment(Fragment { start_sequence: s, ..f.clone() }))]);
|
||||||
|
assert!(link.events().is_empty(), "{f:?} -> {r:?}");
|
||||||
|
assert_eq!(link.client.state(), EnetState::Connected, "{f:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn send_rules() {
|
||||||
|
let (mut client, ..) = start();
|
||||||
|
assert_err!(client.send(at(1), 0, Delivery::Reliable, b"x"), Error::State { .. }, "before connected");
|
||||||
|
let mut link = connected();
|
||||||
|
assert_err!(link.client.send(at(2), 2, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. }, "channel 2 of 2");
|
||||||
|
assert_err!(link.client.send(at(2), 255, Delivery::Reliable, b"x"), Error::UnexpectedValue { .. });
|
||||||
|
match link.client.send(at(2), 0, Delivery::Reliable, &vec![0; MAX_PACKET_BYTES + 1]) {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_PACKET_BYTES),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn send_queue_is_capped() {
|
||||||
|
let mut link = connected();
|
||||||
|
for i in 0..MAX_SEND_QUEUE {
|
||||||
|
link.client.send(at(3), 0, Delivery::Reliable, &[i as u8]).unwrap_or_else(|e| panic!("packet {i}: {e:?}"));
|
||||||
|
}
|
||||||
|
match link.client.send(at(3), 0, Delivery::Reliable, b"one too many") {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, MAX_SEND_QUEUE),
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn large_sends_are_fragmented_within_the_mtu() {
|
||||||
|
let mut link = connected();
|
||||||
|
let data: Vec<u8> = (0..5000u32).map(|i| i as u8).collect();
|
||||||
|
link.client.send(at(4), 1, Delivery::Reliable, &data).unwrap();
|
||||||
|
let mut pieces = Vec::new();
|
||||||
|
while let Some(d) = link.client.poll_transmit(at(4)) {
|
||||||
|
assert!(d.len() <= usize::from(config().mtu), "datagram of {} over the MTU", d.len());
|
||||||
|
for c in parse_datagram(&d).unwrap().commands {
|
||||||
|
if let CommandBody::SendFragment(f) = c.body {
|
||||||
|
assert_eq!(c.channel_id, 1);
|
||||||
|
assert_eq!(f.total_length, 5000);
|
||||||
|
pieces.push(f);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pieces.sort_by_key(|f| f.fragment_number);
|
||||||
|
assert_eq!(pieces.len() as u32, pieces[0].fragment_count);
|
||||||
|
let mut whole = vec![0u8; 5000];
|
||||||
|
for f in &pieces {
|
||||||
|
whole[f.fragment_offset as usize..f.fragment_offset as usize + f.data.len()].copy_from_slice(&f.data);
|
||||||
|
}
|
||||||
|
assert_eq!(whole, data);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reliable_sends_are_retransmitted_until_acknowledged() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.client.send(at(10), 0, Delivery::Reliable, b"hello").unwrap();
|
||||||
|
let first = link.transmitted();
|
||||||
|
let sent = first
|
||||||
|
.iter()
|
||||||
|
.flat_map(|d| &d.commands)
|
||||||
|
.find(|c| c.body == CommandBody::SendReliable(b"hello".to_vec()))
|
||||||
|
.expect("sent")
|
||||||
|
.clone();
|
||||||
|
let when = link.client.poll_timeout().expect("a retransmission deadline");
|
||||||
|
link.now_ms = when.as_micros() / 1000 + 1;
|
||||||
|
link.client.handle_timeout(at(link.now_ms)).unwrap();
|
||||||
|
let again = link.transmitted();
|
||||||
|
assert!(
|
||||||
|
again
|
||||||
|
.iter()
|
||||||
|
.flat_map(|d| &d.commands)
|
||||||
|
.any(|c| c.reliable_sequence == sent.reliable_sequence && c.body == sent.body),
|
||||||
|
"retransmitted"
|
||||||
|
);
|
||||||
|
// Acknowledge it: no more retransmissions of that command.
|
||||||
|
link.feed(vec![cmd(
|
||||||
|
false,
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
CommandBody::Acknowledge { received_reliable_sequence: sent.reliable_sequence, received_sent_time: 10 },
|
||||||
|
)])
|
||||||
|
.unwrap();
|
||||||
|
for _ in 0..5 {
|
||||||
|
if let Some(t) = link.client.poll_timeout() {
|
||||||
|
link.now_ms = link.now_ms.max(t.as_micros() / 1000 + 1);
|
||||||
|
link.client.handle_timeout(at(link.now_ms)).unwrap();
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!link.transmitted().iter().flat_map(|d| &d.commands).any(|c| c.body == sent.body),
|
||||||
|
"acknowledged command sent again"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn silence_times_out() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.client.send(at(1), 0, Delivery::Reliable, b"anyone?").unwrap();
|
||||||
|
let end = at(1 + config().timeout.as_millis() as u64 * 4);
|
||||||
|
let mut guard = 0;
|
||||||
|
while link.client.state() != EnetState::Disconnected {
|
||||||
|
let t = link.client.poll_timeout().expect("a deadline while waiting for an acknowledgement");
|
||||||
|
assert!(t <= end, "no timeout by {end:?}");
|
||||||
|
link.client.handle_timeout(t).unwrap();
|
||||||
|
let _ = link.client.poll_transmit(t);
|
||||||
|
guard += 1;
|
||||||
|
assert!(guard < 10_000);
|
||||||
|
}
|
||||||
|
assert!(link.events().contains(&EnetEvent::TimedOut));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_disconnect_closes() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.feed(vec![cmd(true, 0xFF, 2, CommandBody::Disconnect { data: 7 })]).unwrap();
|
||||||
|
assert_eq!(link.events(), vec![EnetEvent::Disconnected { data: 7 }]);
|
||||||
|
assert_eq!(link.client.state(), EnetState::Disconnected);
|
||||||
|
let c = link.reliable(0, b"late");
|
||||||
|
assert_err!(link.feed(vec![c]), Error::Closed);
|
||||||
|
assert_err!(link.client.disconnect(at(100), 0), Error::Closed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_disconnect() {
|
||||||
|
let mut link = connected();
|
||||||
|
link.client.disconnect(at(5), 9).unwrap();
|
||||||
|
assert_eq!(link.client.state(), EnetState::Disconnecting);
|
||||||
|
let sent = link.transmitted();
|
||||||
|
assert!(sent.iter().flat_map(|d| &d.commands).any(|c| c.body == CommandBody::Disconnect { data: 9 }));
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// A connected client fed arbitrary datagrams never panics and never leaves Connected without a reason.
|
||||||
|
#[test]
|
||||||
|
fn client_survives_arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..200), 1..20)) {
|
||||||
|
let mut link = connected();
|
||||||
|
for d in datagrams {
|
||||||
|
let _ = link.client.handle_datagram(at(7), &d);
|
||||||
|
while link.client.poll_transmit(at(7)).is_some() {}
|
||||||
|
for e in link.events() {
|
||||||
|
if let EnetEvent::Received { data, .. } = e {
|
||||||
|
prop_assert!(data.len() <= MAX_PACKET_BYTES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,365 @@
|
|||||||
|
//! Reed-Solomon over GF(2^8) / 0x11D (`docs/PROTOCOL.md` 5.3, 6.4). The video construction is UNKNOWN U14, so the
|
||||||
|
//! tests check what any correct systematic MDS code must do: data passes through, every erasure pattern of at most
|
||||||
|
//! `m` shards is rebuilt byte-exact, more than `m` is refused. With an explicit matrix
|
||||||
|
//! (`with_parity_matrix`, a Cauchy matrix computed by the independent GF(2^8) reference in `common::gf`), the parity
|
||||||
|
//! bytes themselves are checked.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{SeqRng, gf};
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::fec::{MAX_SHARD_BYTES, MAX_SHARDS, ReedSolomon, parity_count};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
fn data_shards(rng: &mut SeqRng, k: usize, len: usize) -> Vec<Vec<u8>> {
|
||||||
|
(0..k).map(|_| rng.bytes(len)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Encodes `data` with `code`: data shards plus zeroed parity buffers, filled in place.
|
||||||
|
fn encoded(code: &ReedSolomon, data: &[Vec<u8>]) -> Vec<Vec<u8>> {
|
||||||
|
let len = data[0].len();
|
||||||
|
let mut shards: Vec<Vec<u8>> = data.to_vec();
|
||||||
|
shards.extend((0..code.parity_shards()).map(|_| vec![0u8; len]));
|
||||||
|
code.encode(&mut shards).expect("encode");
|
||||||
|
assert_eq!(&shards[..data.len()], data, "systematic: data shards pass through unchanged");
|
||||||
|
shards
|
||||||
|
}
|
||||||
|
|
||||||
|
fn erase(shards: &[Vec<u8>], lost: &[usize]) -> Vec<Option<Vec<u8>>> {
|
||||||
|
shards.iter().enumerate().map(|(i, s)| if lost.contains(&i) { None } else { Some(s.clone()) }).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_recovers(code: &ReedSolomon, full: &[Vec<u8>], lost: &[usize]) {
|
||||||
|
let mut s = erase(full, lost);
|
||||||
|
code.reconstruct(&mut s)
|
||||||
|
.unwrap_or_else(|e| panic!("k={} m={} lost {lost:?}: {e:?}", code.data_shards(), code.parity_shards()));
|
||||||
|
for (i, (got, want)) in s.iter().zip(full).enumerate() {
|
||||||
|
assert_eq!(
|
||||||
|
got.as_deref(),
|
||||||
|
Some(want.as_slice()),
|
||||||
|
"k={} m={} lost {lost:?}: shard {i}",
|
||||||
|
code.data_shards(),
|
||||||
|
code.parity_shards()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_refuses(code: &ReedSolomon, full: &[Vec<u8>], lost: &[usize]) {
|
||||||
|
let mut s = erase(full, lost);
|
||||||
|
assert_err!(
|
||||||
|
code.reconstruct(&mut s),
|
||||||
|
Error::Truncated { .. },
|
||||||
|
"k={} m={} lost {lost:?}",
|
||||||
|
code.data_shards(),
|
||||||
|
code.parity_shards()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn subsets(n: usize, size: usize) -> Vec<Vec<usize>> {
|
||||||
|
common::subsets_of(n, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ parameters
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parity_counts() {
|
||||||
|
for (k, pct, m) in [
|
||||||
|
(4usize, 50u8, 2usize),
|
||||||
|
(1, 1, 1),
|
||||||
|
(1, 100, 1),
|
||||||
|
(10, 0, 0),
|
||||||
|
(100, 100, 100),
|
||||||
|
(3, 33, 1),
|
||||||
|
(3, 34, 2),
|
||||||
|
(7, 20, 2),
|
||||||
|
(127, 100, 127),
|
||||||
|
(255, 0, 0),
|
||||||
|
(2, 255, 6),
|
||||||
|
] {
|
||||||
|
assert_eq!(parity_count(k, pct), Ok(m), "ceil({k} * {pct} / 100)");
|
||||||
|
}
|
||||||
|
assert_err!(parity_count(0, 50), Error::UnexpectedValue { .. });
|
||||||
|
assert_err!(parity_count(255, 200), Error::UnexpectedValue { .. }, "510 parity shards");
|
||||||
|
assert_err!(parity_count(200, 255), Error::UnexpectedValue { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn code_parameters() {
|
||||||
|
for (k, m) in [(0usize, 1usize), (1, 0), (0, 0), (255, 1), (1, 255), (200, 100), (usize::MAX, 1)] {
|
||||||
|
assert_err!(ReedSolomon::new(k, m), Error::UnexpectedValue { .. }, "k={k} m={m}");
|
||||||
|
}
|
||||||
|
for (k, m) in [(1usize, 1usize), (254, 1), (1, 254), (128, 127), (4, 2)] {
|
||||||
|
let c = ReedSolomon::new(k, m).unwrap_or_else(|e| panic!("k={k} m={m}: {e:?}"));
|
||||||
|
assert_eq!((c.data_shards(), c.parity_shards(), c.parity_matrix().len()), (k, m, k * m));
|
||||||
|
}
|
||||||
|
assert_eq!(MAX_SHARDS, 255);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_matrix_is_used_exactly() {
|
||||||
|
let mut rng = SeqRng::new(1);
|
||||||
|
for (k, m) in [(4usize, 2usize), (1, 1), (10, 4), (2, 6), (200, 55)] {
|
||||||
|
let matrix = gf::cauchy(m, k);
|
||||||
|
let code = ReedSolomon::with_parity_matrix(k, m, &matrix).unwrap();
|
||||||
|
assert_eq!(code.parity_matrix(), matrix.as_slice());
|
||||||
|
let data = data_shards(&mut rng, k, 33);
|
||||||
|
let full = encoded(&code, &data);
|
||||||
|
assert_eq!(
|
||||||
|
&full[k..],
|
||||||
|
gf::encode(&matrix, &data, m).as_slice(),
|
||||||
|
"k={k} m={m}: parity = matrix x data over GF(2^8)/0x11D"
|
||||||
|
);
|
||||||
|
check_recovers(&code, &full, &(0..m.min(k)).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
|
// A second MDS matrix (rows 1,1,1,1 and 1,2,4,8): every square submatrix is invertible.
|
||||||
|
let v = [1, 1, 1, 1, 1, 2, 4, 8];
|
||||||
|
let code = ReedSolomon::with_parity_matrix(4, 2, &v).unwrap();
|
||||||
|
let data = data_shards(&mut rng, 4, 5);
|
||||||
|
let full = encoded(&code, &data);
|
||||||
|
assert_eq!(&full[4..], gf::encode(&v, &data, 2).as_slice());
|
||||||
|
for size in 0..=2 {
|
||||||
|
for lost in subsets(6, size) {
|
||||||
|
check_recovers(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_matrix_refusals() {
|
||||||
|
let good = gf::cauchy(2, 4);
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(4, 2, &good[..7]), Error::Malformed { .. }, "short");
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[good.clone(), vec![1]].concat()),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"long"
|
||||||
|
);
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(4, 2, &[]), Error::Malformed { .. }, "empty");
|
||||||
|
let mut zero = good.clone();
|
||||||
|
zero[3] = 0;
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &zero),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"a zero entry: a 1x1 submatrix is singular"
|
||||||
|
);
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[1, 1, 1, 1, 1, 1, 1, 1]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"equal rows"
|
||||||
|
);
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[1, 2, 3, 4, 2, 4, 6, 8]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"row 2 = 2 x row 1"
|
||||||
|
);
|
||||||
|
assert_err!(
|
||||||
|
ReedSolomon::with_parity_matrix(4, 2, &[1, 2, 3, 4, 1, 2, 5, 6]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"a singular 2x2 minor (cols 0,1)"
|
||||||
|
);
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(0, 2, &[]), Error::UnexpectedValue { .. });
|
||||||
|
assert_err!(ReedSolomon::with_parity_matrix(255, 1, &vec![1; 255]), Error::UnexpectedValue { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ encode / reconstruct shapes
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_shape_errors() {
|
||||||
|
let code = ReedSolomon::new(4, 2).unwrap();
|
||||||
|
assert_err!(code.encode(&mut vec![vec![0u8; 8]; 5]), Error::Malformed { .. }, "5 shards for 4 + 2");
|
||||||
|
assert_err!(code.encode(&mut vec![vec![0u8; 8]; 7]), Error::Malformed { .. }, "7 shards");
|
||||||
|
let mut uneven = vec![vec![0u8; 8]; 6];
|
||||||
|
uneven[2].push(0);
|
||||||
|
assert_err!(code.encode(&mut uneven), Error::Malformed { .. }, "unequal lengths");
|
||||||
|
let mut uneven = vec![vec![0u8; 8]; 6];
|
||||||
|
uneven[5].pop();
|
||||||
|
assert_err!(code.encode(&mut uneven), Error::Malformed { .. }, "parity buffer of another length");
|
||||||
|
assert!(code.encode(&mut vec![vec![1u8; MAX_SHARD_BYTES]; 6]).is_ok());
|
||||||
|
assert_too_large!(code.encode(&mut vec![vec![1u8; MAX_SHARD_BYTES + 1]; 6]), MAX_SHARD_BYTES, MAX_SHARD_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reconstruct_shape_errors() {
|
||||||
|
let code = ReedSolomon::new(4, 2).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut SeqRng::new(2), 4, 8));
|
||||||
|
let mut s = erase(&full, &[0]);
|
||||||
|
s.pop();
|
||||||
|
assert_err!(code.reconstruct(&mut s), Error::Malformed { .. }, "5 entries");
|
||||||
|
let mut s = erase(&full, &[0]);
|
||||||
|
s[3].as_mut().unwrap().push(9);
|
||||||
|
assert_err!(code.reconstruct(&mut s), Error::Malformed { .. }, "unequal lengths");
|
||||||
|
let mut s: Vec<Option<Vec<u8>>> = vec![None; 6];
|
||||||
|
assert_err!(code.reconstruct(&mut s), Error::Truncated { .. }, "everything lost");
|
||||||
|
let mut s: Vec<Option<Vec<u8>>> = vec![Some(vec![0; MAX_SHARD_BYTES + 1]); 6];
|
||||||
|
s[0] = None;
|
||||||
|
assert_too_large!(code.reconstruct(&mut s), MAX_SHARD_BYTES, MAX_SHARD_BYTES + 1);
|
||||||
|
// Nothing lost: unchanged.
|
||||||
|
let mut s = erase(&full, &[]);
|
||||||
|
code.reconstruct(&mut s).unwrap();
|
||||||
|
assert!(s.iter().zip(&full).all(|(a, b)| a.as_deref() == Some(b.as_slice())));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ erasure patterns
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_pattern_small_codes_exhaustive() {
|
||||||
|
// k = 1..=8, m = 1..=4: every erasure pattern of size <= m recovers; every pattern of size m + 1 is refused.
|
||||||
|
let mut rng = SeqRng::new(3);
|
||||||
|
for k in 1..=8 {
|
||||||
|
for m in 1..=4 {
|
||||||
|
let code = ReedSolomon::new(k, m).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, 7));
|
||||||
|
for size in 0..=m {
|
||||||
|
for lost in subsets(k + m, size) {
|
||||||
|
check_recovers(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for lost in subsets(k + m, m + 1) {
|
||||||
|
check_refuses(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_pattern_wolf_example() {
|
||||||
|
// 4 KB at packetSize 1024 and 50 %: 4 data + 2 parity (PROTOCOL.md 5.3), full-size shards.
|
||||||
|
let mut rng = SeqRng::new(4);
|
||||||
|
let code = ReedSolomon::new(4, parity_count(4, 50).unwrap()).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, 4, 1024 + 16));
|
||||||
|
for size in 0..=2 {
|
||||||
|
for lost in subsets(6, size) {
|
||||||
|
check_recovers(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for size in 3..=6 {
|
||||||
|
for lost in subsets(6, size) {
|
||||||
|
check_refuses(&code, &full, &lost);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// k = 1..=255 - m for one m: one worst-case pattern of exactly m erasures (data first) and one random pattern
|
||||||
|
/// recover; m + 1 erasures are refused.
|
||||||
|
fn sweep(m: usize, seed: u64) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
for k in 1..=(MAX_SHARDS - m) {
|
||||||
|
let code = ReedSolomon::new(k, m).unwrap_or_else(|e| panic!("k={k} m={m}: {e:?}"));
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, 3));
|
||||||
|
let data_first: Vec<usize> = (0..m).collect();
|
||||||
|
check_recovers(&code, &full, &data_first);
|
||||||
|
check_recovers(&code, &full, &rng.subset(k + m, m));
|
||||||
|
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sweep_m1() {
|
||||||
|
sweep(1, 11);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m2() {
|
||||||
|
sweep(2, 12);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m3() {
|
||||||
|
sweep(3, 13);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m4() {
|
||||||
|
sweep(4, 14);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m8() {
|
||||||
|
sweep(8, 18);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m16() {
|
||||||
|
sweep(16, 116);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m64() {
|
||||||
|
sweep(64, 164);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m127() {
|
||||||
|
sweep(127, 1127);
|
||||||
|
}
|
||||||
|
#[test]
|
||||||
|
fn sweep_m254() {
|
||||||
|
sweep(254, 1254);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn large_codes_random_patterns() {
|
||||||
|
// The biggest blocks: many random patterns of every size up to m.
|
||||||
|
let mut rng = SeqRng::new(5);
|
||||||
|
for (k, m) in [(250usize, 5usize), (200, 55), (128, 127), (64, 191)] {
|
||||||
|
let code = ReedSolomon::new(k, m).unwrap();
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, 4));
|
||||||
|
for _ in 0..6 {
|
||||||
|
let size = 1 + rng.below(m);
|
||||||
|
check_recovers(&code, &full, &rng.subset(k + m, size));
|
||||||
|
}
|
||||||
|
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
|
||||||
|
check_refuses(&code, &full, &(0..k + m).collect::<Vec<_>>());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn explicit_matrix_sweep() {
|
||||||
|
// The independent Cauchy construction through the crate's decoder, every k for a few m.
|
||||||
|
let mut rng = SeqRng::new(6);
|
||||||
|
for m in [1usize, 2, 5] {
|
||||||
|
for k in (1..=(MAX_SHARDS - m)).step_by(7) {
|
||||||
|
let matrix = gf::cauchy(m, k);
|
||||||
|
let code = ReedSolomon::with_parity_matrix(k, m, &matrix).unwrap();
|
||||||
|
let data = data_shards(&mut rng, k, 2);
|
||||||
|
let mut full = data.clone();
|
||||||
|
full.extend(gf::encode(&matrix, &data, m));
|
||||||
|
check_recovers(&code, &full, &rng.subset(k + m, m));
|
||||||
|
check_refuses(&code, &full, &rng.subset(k + m, m + 1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_codes_and_patterns(k in 1usize..40, m in 1usize..12, len in 1usize..48, seed in any::<u64>(), lost_count in 0usize..16) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let code = ReedSolomon::new(k, m).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
let full = encoded(&code, &data_shards(&mut rng, k, len));
|
||||||
|
let lost = rng.subset(k + m, lost_count.min(k + m));
|
||||||
|
let mut s = erase(&full, &lost);
|
||||||
|
let r = code.reconstruct(&mut s);
|
||||||
|
if lost.len() <= m {
|
||||||
|
prop_assert!(r.is_ok(), "{:?}", r);
|
||||||
|
for (got, want) in s.iter().zip(&full) {
|
||||||
|
prop_assert_eq!(got.as_deref(), Some(want.as_slice()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
prop_assert!(matches!(r, Err(Error::Truncated { .. })), "{:?}", r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Corrupted (not erased) input never panics; reconstruction only fills the gaps.
|
||||||
|
#[test]
|
||||||
|
fn hostile_shards_never_panic(k in 1usize..10, m in 1usize..5, shards in proptest::collection::vec(proptest::option::of(proptest::collection::vec(any::<u8>(), 0..8)), 0..16)) {
|
||||||
|
let code = ReedSolomon::new(k, m).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
let mut s = shards.clone();
|
||||||
|
if code.reconstruct(&mut s).is_ok() {
|
||||||
|
prop_assert_eq!(s.len(), k + m);
|
||||||
|
for (before, after) in shards.iter().zip(&s) {
|
||||||
|
prop_assert!(after.is_some());
|
||||||
|
if let Some(b) = before {
|
||||||
|
prop_assert_eq!(Some(b), after.as_ref(), "present shards are never changed");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut v: Vec<Vec<u8>> = shards.into_iter().flatten().collect();
|
||||||
|
let _ = code.encode(&mut v);
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
|
||||||
|
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
|
||||||
|
# Audio payloads (PROTOCOL.md 6.3): AES-128-CBC + PKCS#7 by openssl
|
||||||
|
key = d05ec7c0d6467eb59891afa2d5bac8cd
|
||||||
|
|
||||||
|
# a_0
|
||||||
|
a_0_rikeyid = 00000000
|
||||||
|
a_0_sequence = 0000
|
||||||
|
a_0_iv = 00000000000000000000000000000000
|
||||||
|
a_0_plain = e2b07b75e63ca4ee1066e8c35f04cd3d6c0e3b49
|
||||||
|
a_0_cipher = bcb3ba283cbd9e6e21a85cb7c82a6b0b2b5ba88448b27b81b3b38d0da5873ee6
|
||||||
|
|
||||||
|
# a_1
|
||||||
|
a_1_rikeyid = 01020304
|
||||||
|
a_1_sequence = 0001
|
||||||
|
a_1_iv = 01020305000000000000000000000000
|
||||||
|
a_1_plain = 1ef35c80a79a71277c80985c68e71c17a68061f9
|
||||||
|
a_1_cipher = 8da792c5451bb13afad0326493d01dc0e1e86619675dcb93112c7fd03bb1f4e3
|
||||||
|
|
||||||
|
# a_ffff
|
||||||
|
a_ffff_rikeyid = 00000010
|
||||||
|
a_ffff_sequence = ffff
|
||||||
|
a_ffff_iv = 0001000f000000000000000000000000
|
||||||
|
a_ffff_plain = 8f86081f436a725c6e3538471be3a0e73fbd581c2254a0326de14ea410c5aed34a
|
||||||
|
a_ffff_cipher = d8d61d717b41e9fac495efa94161a5f2b9b834ad17a6cc29cd31c61ea48b123f8f2e148a245387e0fb8e44fdab45a3e6
|
||||||
|
|
||||||
|
# a_wrap
|
||||||
|
a_wrap_rikeyid = fffffffe
|
||||||
|
a_wrap_sequence = 0005
|
||||||
|
a_wrap_iv = 00000003000000000000000000000000
|
||||||
|
a_wrap_plain = 5f2be5a92e6267e05e915bbdd2e154f8
|
||||||
|
a_wrap_cipher = f66ad3bd1328dc4415f4437f9c7d4140514a24a63f6167b0e0d93e3e25d10b13
|
||||||
|
|
||||||
|
# a_exact_block
|
||||||
|
a_exact_block_rikeyid = 00000007
|
||||||
|
a_exact_block_sequence = 0064
|
||||||
|
a_exact_block_iv = 0000006b000000000000000000000000
|
||||||
|
a_exact_block_plain = d3965032409e8fbc2767e9e3209b153a363ad6d3c88c3d50b4625db697d421f4
|
||||||
|
a_exact_block_cipher = 77b8a7998781a734cfe433ad4c1384fa8656d619124824ef58a3a793a2761f9451f10846b539e9250f82e7dce83905f2
|
||||||
|
|
||||||
|
# a_one_byte
|
||||||
|
a_one_byte_rikeyid = 00000007
|
||||||
|
a_one_byte_sequence = 0065
|
||||||
|
a_one_byte_iv = 0000006c000000000000000000000000
|
||||||
|
a_one_byte_plain = 4a
|
||||||
|
a_one_byte_cipher = 13736f9bfb2042185802224de780c210
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
|
||||||
|
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
|
||||||
|
# Control frames (PROTOCOL.md 3.2): AES-128-GCM by .NET AesGcm
|
||||||
|
key = f5a83e5684dabb0e7c674717cd69805e
|
||||||
|
|
||||||
|
# c_ping_0
|
||||||
|
c_ping_0_sequence = 00000000
|
||||||
|
c_ping_0_direction = C
|
||||||
|
c_ping_0_nonce = 000000000000000000004343
|
||||||
|
c_ping_0_plain = 00020000
|
||||||
|
c_ping_0_frame = 0100180000000000bc758312dd6af89c112a8e1671c57118a0a42167
|
||||||
|
|
||||||
|
# c_input_1
|
||||||
|
c_input_1_sequence = 00000001
|
||||||
|
c_input_1_direction = C
|
||||||
|
c_input_1_nonce = 010000000000000000004343
|
||||||
|
c_input_1_plain = 06020c000000000807000000ffff0000
|
||||||
|
c_input_1_frame = 0100240001000000945d76e7f2792e2e1df2d0b8c98a09366e3234ba5ba2b1fd3ea3b339ec5f6b17
|
||||||
|
|
||||||
|
# c_ping_ffff
|
||||||
|
c_ping_ffff_sequence = 0000ffff
|
||||||
|
c_ping_ffff_direction = C
|
||||||
|
c_ping_ffff_nonce = ffff00000000000000004343
|
||||||
|
c_ping_ffff_plain = 00020000
|
||||||
|
c_ping_ffff_frame = 01001800ffff000006c5df5c8000b8dff6b6c6f5f60c7fb6417d8c2f
|
||||||
|
|
||||||
|
# c_ping_10000
|
||||||
|
c_ping_10000_sequence = 00010000
|
||||||
|
c_ping_10000_direction = C
|
||||||
|
c_ping_10000_nonce = 000001000000000000004343
|
||||||
|
c_ping_10000_plain = 00020000
|
||||||
|
c_ping_10000_frame = 01001800000001004f12b2df608fadbc587f1228f4e01e78714eaa59
|
||||||
|
|
||||||
|
# c_ping_fffffffe
|
||||||
|
c_ping_fffffffe_sequence = fffffffe
|
||||||
|
c_ping_fffffffe_direction = C
|
||||||
|
c_ping_fffffffe_nonce = feffffff0000000000004343
|
||||||
|
c_ping_fffffffe_plain = 00020000
|
||||||
|
c_ping_fffffffe_frame = 01001800feffffffba40d7311e6306d78196235981640015e0d2d244
|
||||||
|
|
||||||
|
# c_ping_ffffffff
|
||||||
|
c_ping_ffffffff_sequence = ffffffff
|
||||||
|
c_ping_ffffffff_direction = C
|
||||||
|
c_ping_ffffffff_nonce = ffffffff0000000000004343
|
||||||
|
c_ping_ffffffff_plain = 00020000
|
||||||
|
c_ping_ffffffff_frame = 01001800ffffffffa0beeb4b19262485ccd17558f12ecc4c0ebac660
|
||||||
|
|
||||||
|
# h_rumble_0
|
||||||
|
h_rumble_0_sequence = 00000000
|
||||||
|
h_rumble_0_direction = H
|
||||||
|
h_rumble_0_nonce = 000000000000000000004843
|
||||||
|
h_rumble_0_plain = 0b010a00000000000100ff7f0080
|
||||||
|
h_rumble_0_frame = 0100220000000000d217a640b6e026700af1848ab267de85c4a257fd47db295c80917d5fe1ba
|
||||||
|
|
||||||
|
# h_rumble_7
|
||||||
|
h_rumble_7_sequence = 00000007
|
||||||
|
h_rumble_7_direction = H
|
||||||
|
h_rumble_7_nonce = 070000000000000000004843
|
||||||
|
h_rumble_7_plain = 0b010a00000000000100ff7f0080
|
||||||
|
h_rumble_7_frame = 01002200070000003e865385552ebe576988fa1c307ad18596efab2054254f247169c571aeed
|
||||||
|
|
||||||
|
# h_termination_ffffffff
|
||||||
|
h_termination_ffffffff_sequence = ffffffff
|
||||||
|
h_termination_ffffffff_direction = H
|
||||||
|
h_termination_ffffffff_nonce = ffffffff0000000000004843
|
||||||
|
h_termination_ffffffff_plain = 0901040080030023
|
||||||
|
h_termination_ffffffff_frame = 01001c00ffffffff7f93a9df27f4323599666c9ff57ce9fdfdb84ee2a62ce07f
|
||||||
|
|
||||||
|
# h_rgb_2a
|
||||||
|
h_rgb_2a_sequence = 0000002a
|
||||||
|
h_rgb_2a_direction = H
|
||||||
|
h_rgb_2a_nonce = 2a0000000000000000004843
|
||||||
|
h_rgb_2a_plain = 0255050003001020ff
|
||||||
|
h_rgb_2a_frame = 01001d002a0000004031b5e4d1c986da2e435cbdb35b0534d5283b1ed36d35d93c
|
||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
|
||||||
|
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
|
||||||
|
# Pairing (PROTOCOL.md 1.5): SHA-256 hashlib, AES-ECB + RSA openssl
|
||||||
|
|
||||||
|
# Identities (DER, hex). PEM forms: test-only-*.pem next to this file.
|
||||||
|
host_cert_der = 308202f7308201dfa003020102021453ffa5e8f3bb59f51bc3f0b303a8b242f68a9225300d06092a864886f70d01010b050030243122302006035504030c19446f6d6953747265616d20746573742d6f6e6c7920686f7374301e170d3236313132353131353734385a170d3436313132303131353734385a30243122302006035504030c19446f6d6953747265616d20746573742d6f6e6c7920686f737430820122300d06092a864886f70d01010105000382010f003082010a0282010100f34e316da47362a0548d80770f204616f955b275b9289125281eab7f3c68c9ff0ebdffd042635aa1241890821abe8c29bc658654a7a4f9be7cf4f7a0bf3a2e6946b8ee268fdf81d07fc4824c49fdcf21dcd0219a99df621392e818e8d206ae5f5cd9ece75b677c5dcb7dbed654148fa2a16d52b59f0f6deeb64914763fcd764ffc66396b389cf0a34acceb8d1ec01dc9e4c402e2e056e622868cdfa92d6e8427e181424becf1a548d0aea546ecdd07bfb666a3bfe6f2174d106bffe0763d59bcbdbae2325a05437a6d37ba4c7d7fba6673e857ef992ac1435814b60bcbf117661b628cc55ebb9a989d211032e04ec8629d3b6e4b3fcfaa2f0214972e6da19f0f0203010001a321301f301d0603551d0e04160414df2bf26edc1b25c936cf0d8b36221c7358e7196a300d06092a864886f70d01010b0500038201010016068c20e1c05101f15aac904a4c63a885a8a1a196a8599e09a9d19cbd9b4c2cf55b6658f87cb3d176b0d79496be59ac9410fff55252d720452fb7a8f013153a4f30570dabbb3abe6f72fa8962c339d02a0211cb224520413be706cbe5d45fcc4d15db36ea04c3efbcde527418d20fbfe37a2272d72cf3ca67a430c5be66b9a204e4ebe2146aad59568d25a910eebbf926147a958fec9dcb516392218d63bb020ff56555cee446e48b7123c36ca860b7ace554d82c63a0561b0f46121f534b656c57b11d54e2061ee71fb1fd2a275f7bcf0c9de411fe71fb094d9625bf1ed7a8c3f89a1bd6843fd898cad82f2135a2c41a8d01eec80ca98fa89442e4d119aeaf
|
||||||
|
host_cert_signature = 16068c20e1c05101f15aac904a4c63a885a8a1a196a8599e09a9d19cbd9b4c2cf55b6658f87cb3d176b0d79496be59ac9410fff55252d720452fb7a8f013153a4f30570dabbb3abe6f72fa8962c339d02a0211cb224520413be706cbe5d45fcc4d15db36ea04c3efbcde527418d20fbfe37a2272d72cf3ca67a430c5be66b9a204e4ebe2146aad59568d25a910eebbf926147a958fec9dcb516392218d63bb020ff56555cee446e48b7123c36ca860b7ace554d82c63a0561b0f46121f534b656c57b11d54e2061ee71fb1fd2a275f7bcf0c9de411fe71fb094d9625bf1ed7a8c3f89a1bd6843fd898cad82f2135a2c41a8d01eec80ca98fa89442e4d119aeaf
|
||||||
|
client_cert_der = 308202fb308201e3a00302010202146ae17755afe25dccd90323fa8f53b1821c360779300d06092a864886f70d01010b050030263124302206035504030c1b446f6d6953747265616d20746573742d6f6e6c7920636c69656e74301e170d3236313132353131353734385a170d3436313132303131353734385a30263124302206035504030c1b446f6d6953747265616d20746573742d6f6e6c7920636c69656e7430820122300d06092a864886f70d01010105000382010f003082010a028201010094a302935bdedd0ed7824d746e28bea961712819f8cc1f4d8bb8b4bd9c6e620beb707f10da164cb295fef6b5cdcd03787f3b37de8e5c302be7b7605b5d92ea7adeaec6a593c9fb5804e25f66d7d67e2b59867105806ef7dc3280ca0a279ef1e86eaf41e959e6a5541d63ad33e4274264d32b66943c213cdb08f3ae05732e82e19ea4666be8219f17e7cf5d4b187bfdb21bd8d7d0819f3f510561514abe2ec5a1efdec85cccb5dc51385c8a8929c4a782d9792e01ddaa94b5f79d012af8aaf00e1f99acaefd671f91b11f3f6e83a623482a83147d6da18b0d6e4ed93f99b43e7ecf9e1b66ef6bca52b13f6eae3378fc683fa73bbe55fc141352e94a05b277bacf0203010001a321301f301d0603551d0e0416041440ef12a47352cc507a4a0d9d1e046076d27c6315300d06092a864886f70d01010b050003820101003fa87ccd4d90d25fcc44cf1ab755b436b506a09dc49faef6d051ea770cad2319687f86012d074aabeaf07e9aadaccf9605517f8af94ec0f081b526a25ba18db15c589c4f6fcb9716bb10c1f27ff29a732042de321305f56833fa329e351434607ac1943a00b0497f7bb06cc9cceccfdf6c311e9924183c211e2bf43444239995a9d93227d54af9468c8445d144ff2017d6e699c3ad0b80af7117d0914c2d51d0b282cc7bd8dade8df1912fa7594dae43b527b8dd34d2c4d74b93dc780e24c0d6e0989502903ef7710265c8b6e978babaf9a355067973a8c3b79aa491995384f60d426e9c67bfbec890610d2392d8b0f5664e30e7bc2304ff1d3a3b055f591c44
|
||||||
|
client_key_pkcs8_der = 308204bd020100300d06092a864886f70d0101010500048204a7308204a3020100028201010094a302935bdedd0ed7824d746e28bea961712819f8cc1f4d8bb8b4bd9c6e620beb707f10da164cb295fef6b5cdcd03787f3b37de8e5c302be7b7605b5d92ea7adeaec6a593c9fb5804e25f66d7d67e2b59867105806ef7dc3280ca0a279ef1e86eaf41e959e6a5541d63ad33e4274264d32b66943c213cdb08f3ae05732e82e19ea4666be8219f17e7cf5d4b187bfdb21bd8d7d0819f3f510561514abe2ec5a1efdec85cccb5dc51385c8a8929c4a782d9792e01ddaa94b5f79d012af8aaf00e1f99acaefd671f91b11f3f6e83a623482a83147d6da18b0d6e4ed93f99b43e7ecf9e1b66ef6bca52b13f6eae3378fc683fa73bbe55fc141352e94a05b277bacf0203010001028201000fc252c115f204a510b3678beb2c15bef6ae5d2e97c2e8a4bba62b3f9948d8cb63bc8b3459b31891acb69a28bf77b7a0fc78665d89e17b58045adc74037152bc11451d99ab9834366a5a27fc4af11a72752cfc69b56ace8bc1ad06fed9a1900b7144d2abaf94f53d7c5a37a07355b843e161ce1ff45a1fce275e52ba903243bd07b564065e2dbc9b5676b996013e486b7bfb1d186b6c1bda781d0279d8cecafb8e99e76fc7a26cee330d9662d4a89ea60f3f3caa3caede3d5a0cf0d561a1f6ffca1bf73607247aa5d316bfb8e9bda82974fb61a1d3efcf97d590b684c6032ae9141e81b17c50ae69990e6d39be5133fc8d86d76a937014cda22442e30d1608c902818100d04c3e3ce5acb9969cb6efaf092773a4ba19aa034c838b9734d1932c4a5b61459764f527a57dd03dff9f9dae75b69763a0775092f63ce49f65b2e24fc9c27705104bab333ebfbb55c39220de0b5543cc79e8bfd753bb52ed632c8001f5da0056554963406952297dfca5fa78a32db701a44f3701ba225c331e49d185a8aba35902818100b6ad0d4772743453a94ca1d34b05db2b697f9f70e5e09d6eea4740745bd15629d992c8cfafb6784228d92aced6a2288f72e03b249de31222e6c9f16174f84143d1ce21d4d11c985f99e5ce639d9911c4da8dd184cb03b12f2957e0ac9bc48ba0f858f68fdb2e8271a7d52594c3575cd774712a648f85571073ec1566997ad267028180269006f1b53f9df8413928f489c851038d24953219273d5f97fab8b97966a38283bdc0193fed23f16672c1797bf77add89e6acf718393bc63ac8bc57332e1a64c89889b06a0c8afd1cc0dfeedbc0445605b7ce5469ff032249bb0253da952a7cd13b4df1adcdf53a8adc9b9b5bf269b017204739bda100dac1dfbeb774fb99b9028181009274f5c38578b3072c21db502ac2fc2fb6fa721b32c23d96525063d5a65394302356f296c83a93f9ff03f5b53511775162f971916ee0418727df5a1e17887dd2e0dfd1f1ece16f2c9e97473c487b136aef0a6aa37b9c6f2eef879c02e733d1fa7181e9d3f61738cfe48e17fe480abfcda176a5555057c830d1afc28caa9a751b0281805304170f6fc7b08f45c848c534527fc4b210990589b060c02840b5c79d57589d83ef8f0d2c4551798346eda321bb3b6e0facf3f6d9e99e4dee87f35b9460bb4df7179713a3165b996980a1aaddf95146454841dc4fa9a08adbe417c47893270dd2af3abcad97e5a91ccf4e921fbd97928fadbeed4a86f78b88590bfa557de919
|
||||||
|
client_cert_signature = 3fa87ccd4d90d25fcc44cf1ab755b436b506a09dc49faef6d051ea770cad2319687f86012d074aabeaf07e9aadaccf9605517f8af94ec0f081b526a25ba18db15c589c4f6fcb9716bb10c1f27ff29a732042de321305f56833fa329e351434607ac1943a00b0497f7bb06cc9cceccfdf6c311e9924183c211e2bf43444239995a9d93227d54af9468c8445d144ff2017d6e699c3ad0b80af7117d0914c2d51d0b282cc7bd8dade8df1912fa7594dae43b527b8dd34d2c4d74b93dc780e24c0d6e0989502903ef7710265c8b6e978babaf9a355067973a8c3b79aa491995384f60d426e9c67bfbec890610d2392d8b0f5664e30e7bc2304ff1d3a3b055f591c44
|
||||||
|
rogue_cert_der = 308202f9308201e1a00302010202140413e99f50d883e0d804fec044ee90b64bf4f9a3300d06092a864886f70d01010b050030253123302106035504030c1a446f6d6953747265616d20746573742d6f6e6c7920726f677565301e170d3236313132353131353734385a170d3436313132303131353734385a30253123302106035504030c1a446f6d6953747265616d20746573742d6f6e6c7920726f67756530820122300d06092a864886f70d01010105000382010f003082010a0282010100bd30b5cd7eb6c6a2ea7b4f2786e69e1c68ea221bbae80c0e9778f50e3b93085da0f1fa1e461adde49d5af92c112d01a4ec4030f4ee699a00f98564b696a5826fa0563cef27b36af7cfaef35aecdaa698effce30e2065862bc428e238915f1cee5ea8caab79935fac83f3f3bbc7fb3e1fcbd0e58fa898bf3135009b924d5d5542f6acb40852066e0b9a5690426ec7ebde95e023c0aee16b7f02b9fdeadcb52a9cb4780290d38be12d65ee1d2b154c047ae1d9bda1e56afa62849c14143e11190b8f49443cde18365fea050688465b8a9af8c4eceb72970c753021c3ebcc992458aba8a6fd748c85c9df047119d2cebac0e2821c8786d2878a559190f46249f8610203010001a321301f301d0603551d0e04160414db730a3dc30b6edaaeec268b6166bb35e4fdfd34300d06092a864886f70d01010b050003820101009e97849350ca8ca8607aeb832f572b2a3df07ab9e7b310be0b6974086f11d93e64610d03d1f131548a22e8ed70d30a6f1bc67c56de7f5109da8bfb4356a294a43bc0edd63a571ecd0f7b7334fd31f89e4f739c7fdc79f98920ce10319cadaea3499cb4506398331136f5c3d223b43061d4302fb7410ab0260cd95623b6b364d29811104b662dee30892ef2a7f1d6b747aa2a9110b90f790bf5732c0b0d75f38a2aaf3cfe50634778b6ec788e639b9a9f00c5206531991888797279821656f3475b5d43364861a12a56151a5aa143cbbe983a1db6ba093df445c93e1177654a3abb88a7affa805d2dc5f3b33eb0ff9448f04e565e91191431cdbd0d15346d0b2d
|
||||||
|
rogue_key_pkcs8_der = 308204bd020100300d06092a864886f70d0101010500048204a7308204a30201000282010100bd30b5cd7eb6c6a2ea7b4f2786e69e1c68ea221bbae80c0e9778f50e3b93085da0f1fa1e461adde49d5af92c112d01a4ec4030f4ee699a00f98564b696a5826fa0563cef27b36af7cfaef35aecdaa698effce30e2065862bc428e238915f1cee5ea8caab79935fac83f3f3bbc7fb3e1fcbd0e58fa898bf3135009b924d5d5542f6acb40852066e0b9a5690426ec7ebde95e023c0aee16b7f02b9fdeadcb52a9cb4780290d38be12d65ee1d2b154c047ae1d9bda1e56afa62849c14143e11190b8f49443cde18365fea050688465b8a9af8c4eceb72970c753021c3ebcc992458aba8a6fd748c85c9df047119d2cebac0e2821c8786d2878a559190f46249f861020301000102820100123f7cc5a7a37708d73f920cb0b715488db90995ada33ca87aa53cd3c4dcc3798e70d08c737c1b6b75df04ba22a4f9ebdfaab85e2391d57c231521f7f7935abfac122d59eef5200beb8107317db7804aaf992f88590919d6265b4028af22e2ae3e3c9f21c77df6c433cd07b514ceafb90ee665020483c92b349ecca2a1aa2f3335bf1a4dcd1d441300ae17ea1766100c70c0c9424a1f4a0a7fc370d8f59ae035ce06346b3d7ee8dba5b4d6f24a0e2fb6fa0a67b801dd444377604df1685014e08d0ef969ef4ffb5c9d54226e724205b230572e883828aaab058036257600c5a79488d895b8ef642c83f4568212ebc1989f807bdd5a02d72dbf25f0d8116c28f102818100f9b5fe0019425036bd8df96f9294db7796fe9267f8c42ec1cca243dd94d734fe72c71e44ebb42d3b9f3fd015833ee8f163db04b26efccc3e0eddd81b0ee3d75d25380991129600de20b8d9f74986ea6e87ab6a1eda44b2814c792ee0f9ef41a60c98afe0064f2af3a38550274f95901039cec357b641b4b6818825766f8fc35902818100c1f48311a17b5d212e6c9d17ead7ef534027bda0dd2bf111029f2b3d14af0f4c03e910b48428f7fd4b96356334a9be7ee6d1cf33f121138e53b6ab1cc835d30b6e7341a924adde886e3255f3ce5463bdd6e325a835ac220eb13d225aab5eed48ae2177424db46cf4183fadf21ee0170b0c19709f28e517c5b62435b850d0e44902818100c13a63ff7d8c43f7e7fc69cd3d7734d0b8a5eb72cb1c3c3638fc4359be683d98bc067ad4c8339760f09cf78efe0d7b41f78c2e7948cb13dcddb22b1cdd0bcfc6431bb6c36cc7688a7a75b02cdbd7aba6b6131dbe1c1656af191719007c46f8dcde1874d7fce9dc09c63a4dc8ed9b856c18df776773202b0fa2f25052f287239902818078e13832ebcea3fb4320c4439cc4d9ceabe458c6023219bb3d441041b03b6eb0349bb4229d5f9f37493da3a661b30d1bb025c11aa144b918724a1d99019ab21ea4c6c67c7174bf858e10670b5d63b10a26fc4882ee788a7d57af3f52fd0d5b9b799337eda5da3631674f80ccaebb81010c986a5d77b2583f8bc64388cd2d73a902818057da5867c5776dcbd4c255290dc2f603b7672fe340f1739855df3f332d3287e14aeaad4585a7374df7e46962484a2824358996fecbdd028b8e0bdb0244fb5b0ebe7da580e08e928e40f43dc8742a946ec69455c497e36142334889c120372997fc4d275e444bcff13ea4b5585b8158e02a8baa48ace594227a17a2804060e802
|
||||||
|
|
||||||
|
# Session A: the client's randomness (rng stream = salt || client_challenge || client_secret)
|
||||||
|
pin = 4071
|
||||||
|
wrong_pin = 4072
|
||||||
|
salt = 0675c95e8a7e4c7acc568797397ed89e
|
||||||
|
client_challenge = d2b5889e7e822d424f97fba908b48fdd
|
||||||
|
client_secret = 7fd88cf5f73f75b9cb3cebd9265b394d
|
||||||
|
|
||||||
|
# Host values
|
||||||
|
server_challenge = 9b316d43ef0d7426e9c9d05aed472d9d
|
||||||
|
server_secret = a0433d1811811ebe4a616282e92d11cf
|
||||||
|
|
||||||
|
# Derived, step by step
|
||||||
|
key = 3d47dce112b5a7f2b2fcb584bc69a94d
|
||||||
|
step2_clientchallenge = aa8551207cc0c95332c3e1915e8f11ee
|
||||||
|
host_proof = dc4ab364cd3845b2e9c138c5583ca5f23a117d1fd57c27c9e93451841e53754c
|
||||||
|
step2_challengeresponse = 25e0d2926cdc57f171461f50e8345225a449a3382b015f052829c02ed0b73fd26481419e3e79b09c09f5d826abc522c5
|
||||||
|
client_proof = 72ce1283ca9781fb356a2f74009659803168351407dc80dfd376847b15921df5
|
||||||
|
step3_serverchallengeresp = 365a519f4ea9de5f91f7297ac15b707d5cda97deaa5b90060dd6e00b4057251a
|
||||||
|
server_secret_signature = 530848b0bcb5764e33796bbd3ecc64a80ff9b6668163b7e8db11dc31527fd06a4e932b544e5899ac20a80a9c0eda973dc0b3fdce20d0fba9d1687c53a5f548b80e1dfedcc8af569f29515a4c4ceacb39b06728eb7247ebbac735393120ddb9dc4822724538944510c9a27db64558121223ae88420053a319fd8b86a710b8548840f7078fe7d3931a8e7865fa6434439ae105a2fb837e192f99c0f4ae2462462724f9bee1d8070972fe4d5a5985feece913f944c7170cf6e0908f88a34e12cb4e441e8eda2cb7bb93354f4facdfed60467a9695c502bcbe6c25b514ba10d625e96586a28dccb3d066152b2147aed6f57c8676d2d6f36014f77e8e64ecb74a2b79
|
||||||
|
step3_pairingsecret = a0433d1811811ebe4a616282e92d11cf530848b0bcb5764e33796bbd3ecc64a80ff9b6668163b7e8db11dc31527fd06a4e932b544e5899ac20a80a9c0eda973dc0b3fdce20d0fba9d1687c53a5f548b80e1dfedcc8af569f29515a4c4ceacb39b06728eb7247ebbac735393120ddb9dc4822724538944510c9a27db64558121223ae88420053a319fd8b86a710b8548840f7078fe7d3931a8e7865fa6434439ae105a2fb837e192f99c0f4ae2462462724f9bee1d8070972fe4d5a5985feece913f944c7170cf6e0908f88a34e12cb4e441e8eda2cb7bb93354f4facdfed60467a9695c502bcbe6c25b514ba10d625e96586a28dccb3d066152b2147aed6f57c8676d2d6f36014f77e8e64ecb74a2b79
|
||||||
|
client_secret_signature = 67c7de68387431676d228bc37b37575c798dc530132100f4ffc3774c719c8adc2e55dc55065c56f9518f19bbc588c3f0d374a560dfd8d9ebac856c3402ecf631926fecffe4a9a78eb2ebb8aeb0c4de07710371534e31948adc324c59012397e0d8203444cd32213cdd0030302d97ed19a64cc5bf624fdfd5d63617b98dbbc39c18c27da15eb7da52f228f27c5613404ac1ca5438f55c657abec03a2a1d231121e582a269488422534a888cfe763a7ceaeb39b63d4e60a5c266060b7ca6770d0ab2e03c8282f9a0eabf6c62d4b59ad17fb90a2992f919d347c86842c5d95e3a221164714a9838a347599ce4555e34b6d7d29c20ec86d56adba11670da841ab784
|
||||||
|
step4_clientpairingsecret = 7fd88cf5f73f75b9cb3cebd9265b394d67c7de68387431676d228bc37b37575c798dc530132100f4ffc3774c719c8adc2e55dc55065c56f9518f19bbc588c3f0d374a560dfd8d9ebac856c3402ecf631926fecffe4a9a78eb2ebb8aeb0c4de07710371534e31948adc324c59012397e0d8203444cd32213cdd0030302d97ed19a64cc5bf624fdfd5d63617b98dbbc39c18c27da15eb7da52f228f27c5613404ac1ca5438f55c657abec03a2a1d231121e582a269488422534a888cfe763a7ceaeb39b63d4e60a5c266060b7ca6770d0ab2e03c8282f9a0eabf6c62d4b59ad17fb90a2992f919d347c86842c5d95e3a221164714a9838a347599ce4555e34b6d7d29c20ec86d56adba11670da841ab784
|
||||||
|
|
||||||
|
# Hostile host answers
|
||||||
|
step2_challengeresponse_wrong_pin = 75cd553a5eac50deb0cd3b3b203dc3ed16532f8401d157d331b4e00497edb4545e8c44238479d7c9446f79d866fc68c5
|
||||||
|
step2_challengeresponse_wrong_hash = 46a43219effaf5f645c5950e990647bc72c5a4691db568b39b719c20c463e31b6481419e3e79b09c09f5d826abc522c5
|
||||||
|
step2_challengeresponse_wrong_cert = 9d106087e89ef627ed88e13503a36079e7407bddc7a8e61988a546e8eab057636481419e3e79b09c09f5d826abc522c5
|
||||||
|
step3_pairingsecret_rogue_signature = a0433d1811811ebe4a616282e92d11cf246a7dee0b2b67ac82623108496917eeeb0bf4c1688def6a617f736763050739a078593782129ef9b0be272964eb24696e7dd43fbdf2bfea618f303f8d8678e10bcc82d6207553f2c67be08f75f202152f72444308b2b63e79cbb0c15ded19b2d21f808b0c1d7dd4b8384807ae360e16840d5a86a8a135e46fa9f20cee949ab29b8cc49944041ce14f3845c599a205af416414662e19fbe41090d913b5969b2a6fc8675004c02075339acc498eef1c1acbb0e7d88f119c6ee7e3984c79ac1594f88c09063395e324320053797b3a419c1570505e02502a3b244462f73f45736dfd57cd2af2ba4c0855bb6f335abf09bf0b65e9a9eecd56756c1b83cc54a8e3ee
|
||||||
|
|
||||||
|
# Session B: different randomness, for replaying session A's answers
|
||||||
|
salt_b = da0bbbd95453b0a976ae6630947d0a9d
|
||||||
|
client_challenge_b = f3af034962a9ab8b8ba94b522efeb099
|
||||||
|
client_secret_b = c27871ab54ea3f790a9532c003b78522
|
||||||
|
|
||||||
|
# ClientIdentity::sign over a fixed input (PKCS#1 v1.5 is deterministic)
|
||||||
|
sign_data = 446f6d6953747265616d20746573742d6f6e6c79207369676e696e6720696e707574
|
||||||
|
sign_data_client_signature = 7fd8b58d941c069341c02dc4ecde5e98cdc3d4bb7d117e3e77c116fb2fe69853454f820361f8309b04397155b928e44fd4bae6308832627e48be744bd42a4ee46deb8b3a459672a10e96fa58e7debf35fc86694669570483b8fbe04153058336b50b42fba55389ebbb07e0213ccb2606f2c0d12e4722fa299cc16208643ec1bc3d99d6ec79a51c2c70b754ed72e49b85ada460140985bf21d2ba621b14e7341574fab19d1b7d13a2330046f18a5e008dff10d2260d4c615db4bfd59f9795ac3ed24c9fa7231850f488c32a654d3614decf315bbc33e8a6a127bb5b1c0eb406d24585bc8fd7a37e29637cd847c1857454949017542f986026784aa5debd7b9285
|
||||||
|
|
||||||
|
# derive_key: SHA-256(salt || pin)[0..16]
|
||||||
|
derive_0_salt = f8b30d70e5b0008c08f810a5a8fc5df9
|
||||||
|
derive_0_pin = 0000
|
||||||
|
derive_0_key = b78936fa27b843afc14734e4048662ea
|
||||||
|
derive_1_salt = e7a045e0c6d09c8c974cdeaaf13af7df
|
||||||
|
derive_1_pin = 9999
|
||||||
|
derive_1_key = 7b3e5e69c7dcc9836ce8277767618a35
|
||||||
|
derive_2_salt = 9d75e745c278f4b605e582324a143a4c
|
||||||
|
derive_2_pin = 1234
|
||||||
|
derive_2_key = 2cafd262f85bdebbe1d3b9a5d718d2a5
|
||||||
|
derive_3_salt = fe703787a74ae00919c71af343882078
|
||||||
|
derive_3_pin = 4071
|
||||||
|
derive_3_key = 10a0275e93fa660865bc4d2185f701d3
|
||||||
|
|
||||||
|
# ecb: AES-128-ECB without padding
|
||||||
|
ecb_1_key = 47f07b74b1b7d34a6942bcd0c8c8d226
|
||||||
|
ecb_1_plain = 0bfb32813994563998633410daa23888
|
||||||
|
ecb_1_cipher = c640c02f95da13177fe0a9ab62c8a9a2
|
||||||
|
ecb_2_key = bba955b56d6b85f283f665f504465afe
|
||||||
|
ecb_2_plain = 612da985f348b205e410a05158f3bc3c7e4204cb09ef880749a0ff7758e88b6c
|
||||||
|
ecb_2_cipher = 25fac3e4d328d4eada87c90fcfabf0b9cd840b467ebfdcd0257b37e9a8fc0488
|
||||||
|
ecb_3_key = 650d6d2059045c6751dda639064eba49
|
||||||
|
ecb_3_plain = 9d0db75b8d10d73d581ae77b77eb287d297352212ca9c54632a3d462e77733849234e26b2bff700ab70c24f4d6889d09
|
||||||
|
ecb_3_cipher = 5dba0bdef7130719252bfb27f78cc36999bf162b8ab371a7bb13e4213ea1cd882b654936605b2b1075de8ab52d9c3084
|
||||||
|
ecb_4_key = cce40b2793a8875f3e87cbbdeba015c7
|
||||||
|
ecb_4_plain = 53f9b09390f41b244bbde180f5e7bf2f2c762aed0d4b47d75da1c44af32af83cf48a88418d4245b28d6802576b297e2f4636cc48cf325a2bfb36ef11dd2a94a5
|
||||||
|
ecb_4_cipher = 5c3091ff1960905cadcd7131e59567885f51f5b3654d4e1ba11f2dd3cb0515deec7e9ea9d2afbe40c8d5c7b5dc8b269f34d014763683ca9db600c98405e6f8e1
|
||||||
|
|
||||||
|
# proof_hash: SHA-256(challenge || signature || secret)
|
||||||
|
proof_0_challenge = abcad06bd4e492689cd5926df9100c27
|
||||||
|
proof_0_signature = -
|
||||||
|
proof_0_secret = 6ee4f062874e4c848d94f63d04160de7
|
||||||
|
proof_0_hash = 73ea89c8b23f1b28c9c55ae2e56e5f3898784d8c4682758eab6e36e6843f9374
|
||||||
|
proof_1_challenge = d115b311d27bc924561a6ef9b764c2fd
|
||||||
|
proof_1_signature = 07
|
||||||
|
proof_1_secret = a9772fa047ca1a8d23484457108d4516
|
||||||
|
proof_1_hash = 9aa6d607ded2d6fc7e4533d75cbb6208c6e1df818b8129a5e0bc997942c46845
|
||||||
|
proof_2_challenge = abf024597adc7b52fb17a9d8b7df5813
|
||||||
|
proof_2_signature = 838237fa0fca3fab1fd94adbadfe0de900a4924f1cfe101012d1251b48fab489c204c48e68084020fde01500c81bd4e971208b6a16b71d6e5b0a5d7d243a4a8caa59ce1623a0f7a43572849684a5cc9c356301c076a68e947db827d8449179362f67895d55ebb2764209c5b72772bc04a5032f3ca705249dada034ba6ef20e6c
|
||||||
|
proof_2_secret = e583442683d1be3b218e9c510a965500
|
||||||
|
proof_2_hash = 508761b918a82d13a90a2e400bbc0d6dc2cfaea457979a04a6b64faaf2101372
|
||||||
|
proof_3_challenge = 4076d9e84a76edda18afd13040dba441
|
||||||
|
proof_3_signature = ad7ca0c5cc82d13fa18cf31f153eda0a48fb9c87ae2efac89ee05fa3dd8cf35e026650404f3c2369c75636d8d7018f6bcbfaaaa7bc5f90b3ef5831ce0d9f31899c2302c0924d05a52524b43350f2ab3de7b4d2165c8dc629c1eaea8203fd975775d4ee2d82807383c038f273fc2d05de8804bf3f4d91412ad75d82bb981b652b8a4110f6789d63a35550f76884b8d89b3ebc2a682367027afca0dd3fd6aeb49f387baa4336f22481f4f7dbad9314a3d0c4209bd1eda5b3f72799f7e718f34a157799655d4d9cb5f4da8b8c2ed81b644fdec096670e46601f90b8ee28f22407ff3ca7c0426f55747412b92a07449eadb9d09a27f3355ca72789f790a3e5156e51
|
||||||
|
proof_3_secret = 51927fba549d832e503b2fe7e3334906
|
||||||
|
proof_3_hash = c3c9b78dd993581e9bb19ad496641ba817f67812b7f9e1ea77ec8e3023f3c980
|
||||||
|
proof_4_challenge = e20ad31b7f61b888d33f9a81b0bb5173
|
||||||
|
proof_4_signature = 05721bf7769763ceffaf7c3ddf001fe527a113e204dc499c30490efa021eb7ca0d6775bbdb1b43d606f4aae4478ffa8cc0ced04d87e337d219604dae2698cb569b954f4c81f8b1f10f3329c44c283673e3818fbce574bd0a0ebaab50630818d00c829eb4923795cd7ef1dfad3c8a20e263fa054d15655041cb5c5c9d168ec89d394eddf22b2fe3db603b83bdaac074448f0d96036b99bb88e0d3d4c6a252f4390c4d3bcca032105232311b89127eef24f6e3244c92d352bb68ddd21f89faa19380f67a1206c59fd15ec29f855971c3185fcdb7d2a6bdd1eaaa10cd9e6862eeedca09a2c34705fbe9519efda9e8f18e504a1d5bfd70e48ceffdd6feef8b4f05a43f86862afa6da3b8a1d55251533d32db1e123b969ecc821ab1e555362b33cd9bd587079b28b2ae0c8608832d1b375e74f2d83baa0e9e9448cd37b9d4211505b38458a8605e9e2ca56c45b095642325caf2a41881741b2c5a083f6ebb3a2e00b4b4c01e807f82a3fe70030a9da9debf1d176a802ed19aa0241c67d0741fe48dc85dd8baf42263a02d9d10156d2b058b5059d301ed5456bb0e2df9c5862dc7580e567bcbad6fca59837e66e15cb8941ccc423e810cb598982fef3ac71c75f51586ed4bd178f96ac144d64086b35ffa66334b2898fe326bcf97bc7ea7618daea38a00bf8df54e452da6bf60f3e94dcf41e73744041bf698c2c6c0ac26b8f4ac63db
|
||||||
|
proof_4_secret = 768514c2db82b020ffd805b94b829af9
|
||||||
|
proof_4_hash = 8c0f55414f6ee38be15638cee5e8058febd618a90e6d7492460d962e0567f8e9
|
||||||
|
proof_5_challenge = c033776eddbebfce3d438548b70783cf
|
||||||
|
proof_5_signature = 47a713bf31800d6c87996396d2a30efc61e85acc7814115e41364f2b3c30b6862a4da3258155eda966e9f5d2dda0e101a9b32bd9748494d6c83badc07c8b4387322de01c2e2544da5c62c9db8de7288734092672a3f6b53cf7998dc9e3ed19cf4123b677052107c4ac6c828efe5c43607677a1a557ca10e50e5a49cdb6a12738c1ac82bbcaf37d94fe9e23ba4ea2c61c9f6b0cba8be53d96b51bf1a45fd9f429e53bcc59d36e5ed2b0986b29814fcfe2ad81b7f7cbb814d0a6be50619ef3d0ad06b4bf0ceaf1d28b6022e0a8327b425f803ed5688f248faf527c9de2ca820aca1698e393ac4e9b63a743f0a600fe4c47dc39d62bb7493cf5441e0a727926117cbc56765c30a183959d02070cf0654bf4ce50ea1f227f03ab78663212c7a7069700dbaac44ecac8e64f00819dc5e356e3d28f26b4db128edc0bd43a131f96639283aef28ad69777f7f800b6a8cd566f7eca285e27a6a57f1193c7bbb151a908a157846d844fa95a62e99221655efc2041c2e03a290d1cbf7c42480e9dc190e173e3d06a678d0b3ddbf74907839a5cea86b6cd3ce8ec8b9325053873ca5b580e4f2706a70aec4eddd72bc1700b18486cb661abf1d6cf9200bcc0326c9cc7dcbcc82fbb76286709ef1886d649818cf24a7d8eeb7e31f5b6eebaeb253ce386f07590608bfce1ffdc7163972f6f1eed1f63c0b2a8def2e2b4a5998d3ffab67c42ab28e0889fd141032fa99758e97a871fb2d27f4e5da6e7ba2c018c79b9d4ff6ca7e5b5f433e4f2839c1dc32524ea2b11973e28540107b2d3dba3930efea47299b8188eb87c4faa4a8adbf3a5c5d8d601e0bb9f0b89ffd19a60d7f8ec1313adb84a618885a370d7a64c3bd7bffa5d7f70d97cd9c4d5b04421c239bcd798efea0e03d3916edb1de8bd6649a6bcc3e90885339cfd6b861b0470dac19508781bb01935d35649a532b74678213baae7e264c11168c393c11bc485e2d7a289905ef3c4f80184d34c6375fb22caa60e311b9d9bd1864cafddbc89038be39d5ba9816d5732ab42da5f805000069f79835acd96ea9e1b00b2b393a122a7d5a9d2a3c0ed892b050dfae37368f0123a3ffd8961054f5227976665641f41f8bd2b60187743cc3fc07505870b8024510b78970e861c79752f5711cc5e6e1b512b7ef84ff7515737c938a6d97d533bf85e6e36b2e67aaec72fa6c8410f585e72ed47df24b164a2aba65fd9c6587b075839f0fb2e8b3507d776255913d6b4ef1f0edc4d4a56fede42841e35c1838d6b2f0d9de38b1f2654b5c253a7c22fa7a08fcd109842c9a3ef1ccb3dd2980532643939e668f190f49fa51f3b49fafaa24f5645e4f4c8fe8e73e150dd88c636b23c1a125d391052d80128f6288e7f05e344d6706ddea5f228823a19bfb504fcd1da90fa82f29c6c21eb2301cd0d5bf048b588530cfeb81ee0a2aec0
|
||||||
|
proof_5_secret = c302d079cd10e6911a1ca96a15dd205e
|
||||||
|
proof_5_hash = 8db2e4a0d395918a37370efd4432132e929ad7fec0c2090d5aa0feef1b068ea1
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIC+zCCAeOgAwIBAgIUauF3Va/iXczZAyP6j1Oxghw2B3kwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwJjEkMCIGA1UEAwwbRG9taVN0cmVhbSB0ZXN0LW9ubHkgY2xpZW50MB4XDTI2
|
||||||
|
MTEyNTExNTc0OFoXDTQ2MTEyMDExNTc0OFowJjEkMCIGA1UEAwwbRG9taVN0cmVh
|
||||||
|
bSB0ZXN0LW9ubHkgY2xpZW50MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKC
|
||||||
|
AQEAlKMCk1ve3Q7Xgk10bii+qWFxKBn4zB9Ni7i0vZxuYgvrcH8Q2hZMspX+9rXN
|
||||||
|
zQN4fzs33o5cMCvnt2BbXZLqet6uxqWTyftYBOJfZtfWfitZhnEFgG733DKAygon
|
||||||
|
nvHobq9B6VnmpVQdY60z5CdCZNMrZpQ8ITzbCPOuBXMuguGepGZr6CGfF+fPXUsY
|
||||||
|
e/2yG9jX0IGfP1EFYVFKvi7Foe/eyFzMtdxROFyKiSnEp4LZeS4B3aqUtfedASr4
|
||||||
|
qvAOH5msrv1nH5GxHz9ug6YjSCqDFH1toYsNbk7ZP5m0Pn7Pnhtm72vKUrE/bq4z
|
||||||
|
ePxoP6c7vlX8FBNS6UoFsne6zwIDAQABoyEwHzAdBgNVHQ4EFgQUQO8SpHNSzFB6
|
||||||
|
Sg2dHgRgdtJ8YxUwDQYJKoZIhvcNAQELBQADggEBAD+ofM1NkNJfzETPGrdVtDa1
|
||||||
|
BqCdxJ+u9tBR6ncMrSMZaH+GAS0HSqvq8H6arazPlgVRf4r5TsDwgbUmoluhjbFc
|
||||||
|
WJxPb8uXFrsQwfJ/8ppzIELeMhMF9Wgz+jKeNRQ0YHrBlDoAsEl/e7Bsyczsz99s
|
||||||
|
MR6ZJBg8IR4r9DREI5mVqdkyJ9VK+UaMhEXRRP8gF9bmmcOtC4CvcRfQkUwtUdCy
|
||||||
|
gsx72NrejfGRL6dZTa5DtSe43TTSxNdLk9x4DiTA1uCYlQKQPvdxAmXItul4urr5
|
||||||
|
o1UGeXOow7eapJGZU4T2DUJunGe/vsiQYQ0jktiw9WZOMOe8IwT/HTo7BV9ZHEQ=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCUowKTW97dDteC
|
||||||
|
TXRuKL6pYXEoGfjMH02LuLS9nG5iC+twfxDaFkyylf72tc3NA3h/OzfejlwwK+e3
|
||||||
|
YFtdkup63q7GpZPJ+1gE4l9m19Z+K1mGcQWAbvfcMoDKCiee8ehur0HpWealVB1j
|
||||||
|
rTPkJ0Jk0ytmlDwhPNsI864Fcy6C4Z6kZmvoIZ8X589dSxh7/bIb2NfQgZ8/UQVh
|
||||||
|
UUq+LsWh797IXMy13FE4XIqJKcSngtl5LgHdqpS1950BKviq8A4fmayu/WcfkbEf
|
||||||
|
P26DpiNIKoMUfW2hiw1uTtk/mbQ+fs+eG2bva8pSsT9urjN4/Gg/pzu+VfwUE1Lp
|
||||||
|
SgWyd7rPAgMBAAECggEAD8JSwRXyBKUQs2eL6ywVvvauXS6Xwuiku6YrP5lI2Mtj
|
||||||
|
vIs0WbMYkay2mii/d7eg/HhmXYnhe1gEWtx0A3FSvBFFHZmrmDQ2alon/ErxGnJ1
|
||||||
|
LPxptWrOi8GtBv7ZoZALcUTSq6+U9T18Wjegc1W4Q+Fhzh/0Wh/OJ15SupAyQ70H
|
||||||
|
tWQGXi28m1Z2uZYBPkhre/sdGGtsG9p4HQJ52M7K+46Z52/HomzuMw2WYtSonqYP
|
||||||
|
PzyqPK7ePVoM8NVhofb/yhv3NgckeqXTFr+46b2oKXT7YaHT78+X1ZC2hMYDKukU
|
||||||
|
HoGxfFCuaZkObTm+UTP8jYbXapNwFM2iJELjDRYIyQKBgQDQTD485ay5lpy2768J
|
||||||
|
J3OkuhmqA0yDi5c00ZMsSlthRZdk9SelfdA9/5+drnW2l2Ogd1CS9jzkn2Wy4k/J
|
||||||
|
wncFEEurMz6/u1XDkiDeC1VDzHnov9dTu1LtYyyAAfXaAFZVSWNAaVIpffyl+nij
|
||||||
|
LbcBpE83AboiXDMeSdGFqKujWQKBgQC2rQ1HcnQ0U6lModNLBdsraX+fcOXgnW7q
|
||||||
|
R0B0W9FWKdmSyM+vtnhCKNkqztaiKI9y4DskneMSIubJ8WF0+EFD0c4h1NEcmF+Z
|
||||||
|
5c5jnZkRxNqN0YTLA7EvKVfgrJvEi6D4WPaP2y6CcafVJZTDV1zXdHEqZI+FVxBz
|
||||||
|
7BVmmXrSZwKBgCaQBvG1P534QTko9InIUQONJJUyGSc9X5f6uLl5ZqOCg73AGT/t
|
||||||
|
I/FmcsF5e/d63YnmrPcYOTvGOsi8VzMuGmTImImwagyK/RzA3+7bwERWBbfOVGn/
|
||||||
|
AyJJuwJT2pUqfNE7TfGtzfU6itybm1vyabAXIEc5vaEA2sHfvrd0+5m5AoGBAJJ0
|
||||||
|
9cOFeLMHLCHbUCrC/C+2+nIbMsI9llJQY9WmU5QwI1bylsg6k/n/A/W1NRF3UWL5
|
||||||
|
cZFu4EGHJ99aHheIfdLg39Hx7OFvLJ6XRzxIexNq7wpqo3ucby7vh5wC5zPR+nGB
|
||||||
|
6dP2FzjP5I4X/kgKv82hdqVVUFfIMNGvwoyqmnUbAoGAUwQXD2/HsI9FyEjFNFJ/
|
||||||
|
xLIQmQWJsGDAKEC1x51XWJ2D748NLEVReYNG7aMhuztuD6zz9tnpnk3uh/NblGC7
|
||||||
|
TfcXlxOjFluZaYChqt35UUZFSEHcT6mgitvkF8R4kycN0q86vK2X5akcz06SH72X
|
||||||
|
ko+tvu1KhveLiFkL+lV96Rk=
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIBZjCCAQ2gAwIBAgIUCcp/vRy2b7AOspBrIACXxnsnc5MwCgYIKoZIzj0EAwIw
|
||||||
|
IjEgMB4GA1UEAwwXRG9taVN0cmVhbSB0ZXN0LW9ubHkgRUMwHhcNMjYxMTI1MTE1
|
||||||
|
NzQ4WhcNNDYxMTIwMTE1NzQ4WjAiMSAwHgYDVQQDDBdEb21pU3RyZWFtIHRlc3Qt
|
||||||
|
b25seSBFQzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNuZD4n+3lhlp9jGS7X/
|
||||||
|
4LGuHRr8UtTj2G+flfq6x7d5kDShH2oDmh4UAGdBi34QNl6FE2JGyLs4O6Vd5WBk
|
||||||
|
3NejITAfMB0GA1UdDgQWBBTfus0Yc0ctMaFMWaTFYL8qjq+dBDAKBggqhkjOPQQD
|
||||||
|
AgNHADBEAiBY7+HZrI0lMSvAh7SP+8csdHlp1htEEz1nxLRVY4KVSwIgHkV8EwkN
|
||||||
|
yC7oIz36v0nG483KpHAQ4Ej8Wu4rfXgXxpk=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIC9zCCAd+gAwIBAgIUU/+l6PO7WfUbw/CzA6iyQvaKkiUwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwJDEiMCAGA1UEAwwZRG9taVN0cmVhbSB0ZXN0LW9ubHkgaG9zdDAeFw0yNjEx
|
||||||
|
MjUxMTU3NDhaFw00NjExMjAxMTU3NDhaMCQxIjAgBgNVBAMMGURvbWlTdHJlYW0g
|
||||||
|
dGVzdC1vbmx5IGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDz
|
||||||
|
TjFtpHNioFSNgHcPIEYW+VWydbkokSUoHqt/PGjJ/w69/9BCY1qhJBiQghq+jCm8
|
||||||
|
ZYZUp6T5vnz096C/Oi5pRrjuJo/fgdB/xIJMSf3PIdzQIZqZ32ITkugY6NIGrl9c
|
||||||
|
2eznW2d8Xct9vtZUFI+ioW1StZ8Pbe62SRR2P812T/xmOWs4nPCjSszrjR7AHcnk
|
||||||
|
xALi4FbmIoaM36ktboQn4YFCS+zxpUjQrqVG7N0Hv7Zmo7/m8hdNEGv/4HY9Wby9
|
||||||
|
uuIyWgVDem03ukx9f7pmc+hX75kqwUNYFLYLy/EXZhtijMVeu5qYnSEQMuBOyGKd
|
||||||
|
O25LP8+qLwIUly5toZ8PAgMBAAGjITAfMB0GA1UdDgQWBBTfK/Ju3BslyTbPDYs2
|
||||||
|
IhxzWOcZajANBgkqhkiG9w0BAQsFAAOCAQEAFgaMIOHAUQHxWqyQSkxjqIWooaGW
|
||||||
|
qFmeCanRnL2bTCz1W2ZY+Hyz0Xaw15SWvlmslBD/9VJS1yBFL7eo8BMVOk8wVw2r
|
||||||
|
uzq+b3L6iWLDOdAqAhHLIkUgQTvnBsvl1F/MTRXbNuoEw++83lJ0GNIPv+N6InLX
|
||||||
|
LPPKZ6Qwxb5muaIE5OviFGqtWVaNJakQ7rv5JhR6lY/snctRY5IhjWO7Ag/1ZVXO
|
||||||
|
5Ebki3Ejw2yoYLes5VTYLGOgVhsPRhIfU0tlbFexHVTiBh7nH7H9Kidfe88MneQR
|
||||||
|
/nH7CU2WJb8e16jD+Job1oQ/2JjK2C8hNaLEGo0B7sgMqY+olELk0Rmurw==
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDzTjFtpHNioFSN
|
||||||
|
gHcPIEYW+VWydbkokSUoHqt/PGjJ/w69/9BCY1qhJBiQghq+jCm8ZYZUp6T5vnz0
|
||||||
|
96C/Oi5pRrjuJo/fgdB/xIJMSf3PIdzQIZqZ32ITkugY6NIGrl9c2eznW2d8Xct9
|
||||||
|
vtZUFI+ioW1StZ8Pbe62SRR2P812T/xmOWs4nPCjSszrjR7AHcnkxALi4FbmIoaM
|
||||||
|
36ktboQn4YFCS+zxpUjQrqVG7N0Hv7Zmo7/m8hdNEGv/4HY9Wby9uuIyWgVDem03
|
||||||
|
ukx9f7pmc+hX75kqwUNYFLYLy/EXZhtijMVeu5qYnSEQMuBOyGKdO25LP8+qLwIU
|
||||||
|
ly5toZ8PAgMBAAECggEAdTyZTqauPrjY5TIgrHY1r75HD+3v4V9HEzTsGCwopiSz
|
||||||
|
mtPYKxUqx3jYKVG3x1dMiQ42kzYQpZKnLXbgyyQi1vGQDJkiPGWV7OroihAhL5y2
|
||||||
|
hMecckaUQLBKDC6rfTKqmtgbckO18tRTSG0bY3pg19GHFxKS6WFkZAuEw5Hs0/O4
|
||||||
|
M37ev3KYGhASPLXOgobfvQruQoVJg5OsX0Z6mJYXTB0iZDflUADp5QwgelcNU5ax
|
||||||
|
Ra+muHWfJFUuNn0cFH95yXT6Qprwg74f0tdY47i5RyPJQKfvY8GUG08o+ObTMK0I
|
||||||
|
y3lKMZZ27YcttNBpWmPbqipJPrcW05yUvGooKNDR8QKBgQD9vzrtuFcfIdo7TgqX
|
||||||
|
3MunamxU3JBPU5Ync439q+vsVsqwSTgmroeyMBXuLcgkxOWgvez6yx3qojJLw3LV
|
||||||
|
LZ46SInaEOG/VVfG/Hnq+QrFi5hOMEpdD12nueURRVWNoCOBHgyrS2ClGZnEEgDt
|
||||||
|
BanMGmJRSQ6+6gTyijweQq7meQKBgQD1dzqn5XL3zeJRpb7xqoXDiJByvsJErGQM
|
||||||
|
pYRF0MV7YpNjG9YUGmLLs7ACbfeXvXsoJbHg21ynOWVwEKAYuAWmlvUohz9KYA+i
|
||||||
|
eGHjTeseeb9pguib22+bWe8cxww7Lgn/hg7nO07DK4vSFePRKpR7iDDXFrLjm2vw
|
||||||
|
zuPmGC5vxwKBgDbLPKZo0Cdg4Ac+avswKqoUSSBqIJ+ApUQPp/HHVkLK2yoGJaH0
|
||||||
|
vki0KYgtSrLl8dAsMyhVBDjOnZ3OrtVp7GkZkOsOCjGO9E1757fd332ZD2KS+vvt
|
||||||
|
fYPimJyKJFdY5VHUc1fqBwyf4px8ZsbIGkqAyApVhGGllzvoreK685nBAoGBAL76
|
||||||
|
FZO9S/aKo5OcnfPOFSZtYN01l1XwviKswD3FUXBO4JcSeDvJz6Xm1oD9Z84SKPiy
|
||||||
|
YzOr1+lvGYHYHYc93X+gIXt3xoEqPd/NQ3OjEtPyKz9/D1T7pFi83vGH1/dPOY4p
|
||||||
|
kfzLwtrMTYuVZls9gqqd6kneKi41pQSFIwDJPY/PAoGAfGZIHMksLXjCiTQ9GH2p
|
||||||
|
1E4ZOf6M+9xp9Hhw1SL6RSOd6aeqmFgb1waFWytXGVokzLwug8N1CFt4G8m4akep
|
||||||
|
cXcqsWd3M4l+Rr7TM3cKrv+Hz9LcgvX7dRHsoQgJKgUIZs2WaxOY4NG81oEoOTuN
|
||||||
|
clPqmFUVDSKB5N95YxnPR7M=
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
@@ -0,0 +1,18 @@
|
|||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIC+TCCAeGgAwIBAgIUBBPpn1DYg+DYBP7ARO6Qtkv0+aMwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwJTEjMCEGA1UEAwwaRG9taVN0cmVhbSB0ZXN0LW9ubHkgcm9ndWUwHhcNMjYx
|
||||||
|
MTI1MTE1NzQ4WhcNNDYxMTIwMTE1NzQ4WjAlMSMwIQYDVQQDDBpEb21pU3RyZWFt
|
||||||
|
IHRlc3Qtb25seSByb2d1ZTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
|
||||||
|
AL0wtc1+tsai6ntPJ4bmnhxo6iIbuugMDpd49Q47kwhdoPH6HkYa3eSdWvksES0B
|
||||||
|
pOxAMPTuaZoA+YVktpalgm+gVjzvJ7Nq98+u81rs2qaY7/zjDiBlhivEKOI4kV8c
|
||||||
|
7l6oyqt5k1+sg/Pzu8f7Ph/L0OWPqJi/MTUAm5JNXVVC9qy0CFIGbguaVpBCbsfr
|
||||||
|
3pXgI8Cu4Wt/Arn96ty1Kpy0eAKQ04vhLWXuHSsVTAR64dm9oeVq+mKEnBQUPhEZ
|
||||||
|
C49JRDzeGDZf6gUGiEZbipr4xOzrcpcMdTAhw+vMmSRYq6im/XSMhcnfBHEZ0s66
|
||||||
|
wOKCHIeG0oeKVZGQ9GJJ+GECAwEAAaMhMB8wHQYDVR0OBBYEFNtzCj3DC27aruwm
|
||||||
|
i2FmuzXk/f00MA0GCSqGSIb3DQEBCwUAA4IBAQCel4STUMqMqGB664MvVysqPfB6
|
||||||
|
ueezEL4LaXQIbxHZPmRhDQPR8TFUiiLo7XDTCm8bxnxW3n9RCdqL+0NWopSkO8Dt
|
||||||
|
1jpXHs0Pe3M0/TH4nk9znH/cefmJIM4QMZytrqNJnLRQY5gzETb1w9IjtDBh1DAv
|
||||||
|
t0EKsCYM2VYjtrNk0pgREEtmLe4wiS7yp/HWt0eqKpEQuQ95C/VzLAsNdfOKKq88
|
||||||
|
/lBjR3i27HiOY5uanwDFIGUxmRiIeXJ5ghZW80dbXUM2SGGhKlYVGlqhQ8u+mDod
|
||||||
|
troJPfRFyT4Rd2VKOruIp6/6gF0txfOzPrD/lEjwTlZekRkUMc29DRU0bQst
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
-----BEGIN PRIVATE KEY-----
|
||||||
|
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC9MLXNfrbGoup7
|
||||||
|
TyeG5p4caOoiG7roDA6XePUOO5MIXaDx+h5GGt3knVr5LBEtAaTsQDD07mmaAPmF
|
||||||
|
ZLaWpYJvoFY87yezavfPrvNa7NqmmO/84w4gZYYrxCjiOJFfHO5eqMqreZNfrIPz
|
||||||
|
87vH+z4fy9Dlj6iYvzE1AJuSTV1VQvastAhSBm4LmlaQQm7H696V4CPAruFrfwK5
|
||||||
|
/erctSqctHgCkNOL4S1l7h0rFUwEeuHZvaHlavpihJwUFD4RGQuPSUQ83hg2X+oF
|
||||||
|
BohGW4qa+MTs63KXDHUwIcPrzJkkWKuopv10jIXJ3wRxGdLOusDighyHhtKHilWR
|
||||||
|
kPRiSfhhAgMBAAECggEAEj98xaejdwjXP5IMsLcVSI25CZWtozyoeqU808Tcw3mO
|
||||||
|
cNCMc3wba3XfBLoipPnr36q4XiOR1XwjFSH395Nav6wSLVnu9SAL64EHMX23gEqv
|
||||||
|
mS+IWQkZ1iZbQCivIuKuPjyfIcd99sQzzQe1FM6vuQ7mZQIEg8krNJ7MoqGqLzM1
|
||||||
|
vxpNzR1EEwCuF+oXZhAMcMDJQkofSgp/w3DY9ZrgNc4GNGs9fujbpbTW8koOL7b6
|
||||||
|
Cme4Ad1EQ3dgTfFoUBTgjQ75ae9P+1ydVCJuckIFsjBXLog4KKqrBYA2JXYAxaeU
|
||||||
|
iNiVuO9kLIP0VoIS68GYn4B73VoC1y2/JfDYEWwo8QKBgQD5tf4AGUJQNr2N+W+S
|
||||||
|
lNt3lv6SZ/jELsHMokPdlNc0/nLHHkTrtC07nz/QFYM+6PFj2wSybvzMPg7d2BsO
|
||||||
|
49ddJTgJkRKWAN4guNn3SYbqboerah7aRLKBTHku4PnvQaYMmK/gBk8q86OFUCdP
|
||||||
|
lZAQOc7DV7ZBtLaBiCV2b4/DWQKBgQDB9IMRoXtdIS5snRfq1+9TQCe9oN0r8REC
|
||||||
|
nys9FK8PTAPpELSEKPf9S5Y1YzSpvn7m0c8z8SETjlO2qxzINdMLbnNBqSSt3ohu
|
||||||
|
MlXzzlRjvdbjJag1rCIOsT0iWqte7UiuIXdCTbRs9Bg/rfIe4BcLDBlwnyjlF8W2
|
||||||
|
JDW4UNDkSQKBgQDBOmP/fYxD9+f8ac09dzTQuKXrcsscPDY4/ENZvmg9mLwGetTI
|
||||||
|
M5dg8Jz3jv4Ne0H3jC55SMsT3N2yKxzdC8/GQxu2w2zHaIp6dbAs29erprYTHb4c
|
||||||
|
FlavGRcZAHxG+NzeGHTX/OncCcY6Tcjtm4VsGN93Z3MgKw+i8lBS8ocjmQKBgHjh
|
||||||
|
ODLrzqP7QyDEQ5zE2c6r5FjGAjIZuz1EEEGwO26wNJu0Ip1fnzdJPaOmYbMNG7Al
|
||||||
|
wRqhRLkYckodmQGash6kxsZ8cXS/hY4QZwtdY7EKJvxIgu54in1Xrz9S/Q1bm3mT
|
||||||
|
N+2l2jYxZ0+AzK67gQEMmGpdd7JYP4vGQ4jNLXOpAoGAV9pYZ8V3bcvUwlUpDcL2
|
||||||
|
A7dnL+NA8XOYVd8/My0yh+FK6q1Fhac3TffkaWJISigkNYmW/svdAouOC9sCRPtb
|
||||||
|
Dr59pYDgjpKOQPQ9yHQqlG7GlFXEl+NhQjNIicEgNymX/E0nXkRLz/E+pLVYW4FY
|
||||||
|
4CqLqkis5ZQieheigEBg6AI=
|
||||||
|
-----END PRIVATE KEY-----
|
||||||
+20
@@ -0,0 +1,20 @@
|
|||||||
|
# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.
|
||||||
|
# Never a real host's or client's key. Do not edit by hand: change the script and run it again.
|
||||||
|
# Video packets (PROTOCOL.md 7): AES-128-GCM by .NET AesGcm
|
||||||
|
key = 3087d2f8aacc5739add080dd7fc924a4
|
||||||
|
|
||||||
|
# v_0
|
||||||
|
v_0_plain = f7d0644a408e95fa6d7161da4db5b01113030728d20c8dc583ba41fb9399b55c138ccf93bfb1816aa7c3b60efb77a5d8
|
||||||
|
v_0_packet = 00000000000000000000005600000000f2cb1e2e00026bd57ff480120baf7e9e1e87270a2ab54f90a18b8e27f5accc46e2a8f239d75caaf25790ce49c9a5ce99c47e09fe76f4a70bb244487f5a4810f0
|
||||||
|
|
||||||
|
# v_1
|
||||||
|
v_1_plain = a90afba6e31047d24f4f14b1cb81c6db02b2d299f0d8200fe27edda0fe21cee033c634c5349a9c8cb49650bf059d4754
|
||||||
|
v_1_packet = 01000000000000000000005600000000dd08edab787f9abe2a5b4f9fda9d9d0178ad4dd1a1a2deb38853e90e6aed3a56f303b2f0b9f31b0f40fdf0b0f5fee300957b6b4ba8afad3617a8cd227e68e058
|
||||||
|
|
||||||
|
# v_big_counter
|
||||||
|
v_big_counter_plain = 7fdd44c6e2e0ea29e71c28deba014e95313718ab54b11db92a5da93c9f1c1f710067b83b97e4ec0ac0284cd62c20f56059a6f602abeebd5e16ecb4c258423e32
|
||||||
|
v_big_counter_packet = 080706050403020100000056443322114e1be44271991d303ea62e0348d059b4e323f418f9e6989362c2d8b861ad1263b6081e01dc36d2c704bc54e79d0a2b795e3100383c1290405ae08bd6a48f5c35afe45f2bd6f7f7c327a7fb526f580d83
|
||||||
|
|
||||||
|
# v_1040
|
||||||
|
v_1040_plain = 6db2038ec91958faac7add888327646591a80cf0a27652fb433ce4194c6830405706ef40cab5a0dc25cee87c5a8b071bdca7b10c221ce9da6cd01f0ced6ecfa131d0debf06efaf0aa53cedf888a6bbf99e96e51797dfba233b6cccfb63802f0261851a1a6bfe072206f1162739223ca450ab8c1f83adefa0ae9442ea1b889ec8475a3ee74c5f55b4ac5f26362424f8ee951223307d72a0dd2dd96ee11a3e10579c34bc2118519a5b67bd17c3807630e50771d807435388b664276e4f13f961075940d1c571a6306e0f60b7eb2ffcb2965bd180406744903e6fd6326d86836dd2c1fa58c5e78f36b2b47eb5ae726b802ea22b6e7251ee1d96248e59ae57d007379e841d0c8dc834d81f5cffb750cb45da6281aa82c7ef8be8253c4faf099a1d8ce05f41f7f462524dc85325795c5c48be2988f1b9b66f3bcda74543d8ddc8fc19597c4183d705c90438cb93d8af18795d50f60cef208a845a5ddd896e61fa3b60fabd466da57736ba4e9e1905591a89aadeb4b49b52e580c8ca8aca2e589125140de93a9ae87e05547e55574400ae43ce1dc7bb535c361948a7fd3e23087a891d21f03635722681a96e675c82cfaf03addce349acb946574d78a63f9c547089004c355f7d825406ab11bec3d44a5d199cdf0777aaaf88a93894324beae0bec66ebd74ad9011b2b5c71c216dd9580658960287b040b414b096a10124473fb66f475f42384ff481b8723c5eb0398231613e239f9697d78491949800c73916e53424313530c0820591a820eaf7c29b361a46e960a3a8c7e5fdcc4c65234b36db1ee5d5801e031a36d490069ac54d31d17157fd2a46e61c9dbecf70844e28422f292d433ab51f02308f6848ac6417a505bfb78965d3564eea5de5e2fbe704e7f180fb8781db6c75d46b05f9902bf50a15e86d23070357f9fdd19f710e20811dafad4d6ba4ef20e5e565287e7db70093e03a244e8c5f11d23dd099c8274a3eff520aa0f5f7a71608e49cd41b10cf89ca9d561dc9622e952b449267f5b283d3c87b8ef558da78ccfd98277e9ca0cb354b09f2142cda5d4d15d8703e02857de3bc51cbddd86cd312d8f9afec663a383cbe43c250fc39b9897b475de0ef6850ab2fc899d201fc679595077b08b7da650af17d1ac30e054a8a55e7d741c44107cf66804d86a31d25b4b8ab194d327ee1d6b17edca12aee55f8c37979b8eb6f407ce7e4f393414eaf93ac18a367605c86169a430d1c829957bb4569f011796151b08dfb571312922fd5fc5da577980358f570d7f4f4e9f0ae56c43a7b2015f8f41e4eec6a26c24fd99f44632b2b961c37d4d0b878919b80a9179fb73ce0a9c799547d67aa7678d9da2d61068eb85e6058bde560844eb80433d82df523be4042c891c02209cdd7c4a40c19bf64040ee2454d677691d774e916a8043ee5ba206883aad21bc1d7ddefb50c7c3cd5f1a1cd06da4bbf0b24
|
||||||
|
v_1040_packet = 070000000000000000000056030000009f0960cb7d592ee72c1c45da2c30b7b5e56339239ca58b674eb8052fe093508e322d53e9fd6d4e452795b35c6b5cd94b1afbf488de7f36a90b944b95823099c8c216d41ec9261b9d2ad6a6fe516bd751ca31e3b85f4df7b9652b56faa8cf5231254197051b10bb6ee2c6fb6752f5999572e34c4649962647b0fc459abdde343b26dbeb19d82dad1bf7f8667ca2f025533816ad2d2eaf03979e1a53572b0355f27cfa936fb844c1e6dacdb25d3d93e4f84c96dc2dd3956e5101ffa4f014659107483dba9b9ae3aa9220e378ce1cd223be080c3ae94bed1781b5edb0a8521c329f6afd20758d91e92f7de997cdaa52d15803a501a76ea449f719c52ba6a21e962004a3963a6e333126a8f358385c5e8168b576a3d9d855d754e014ce69e126d4f12530faa090cabbe95df8f10ae2de9e33faa2e0d79ea0b529adc5de085b44b79788d1d7621bae91fcbe7b0d3a874c94d45f42068d9cfc8ea2b692edf624aa9da1e0747b972933bc4885dc7712edc89ff4f55b6ddfb686519ea2ebff377fed5727baed7f81a71d1a2178d447f3fb1055a8e0b5271bc75a54f951610af3c02d7d5e752f067c940e31cee57d77eb750a7f0d73b87a4f940531fbefc9275b2f9a10753f46dd6e8ef3f2d6232525a545f12224ec365349cc4c5cad05364b18a3291c9509d22c6445f9c7777edc298cb0a83d2a0328e3cfc2e6ccb2a94c8d5d1d97e309aace8ffb496771aa4dbf98f26f9d570dcb6f9e6561e399fb7a774c0c700c13e36a22bd002292c853d3066d954d2a91cba714d0b43b88adef6d2240ca5e878ad6d1fe7f0eba7bd32d4bb0c65ab16a51cc2c2ce732e40b8a5efeba0da3fa886e0ba82d3474a9c9141ae029e7b2c3a2ac117953f44525127871b60a7852317ac593584f680efb1355dc1da30d3efbd45b07a8b8de15aa36a6eb04db0ffd564db466724ab5794ddf9047af393aa49ce24ea3d75894db2f1fe9bcacb476c056ee1dc62737cf4ea86ecdff9355a62c406d22b748bcd4db6d74c3a587646368695150e4c0c09cfefff39a5e043f6c1ffc488821b91cd8ba89fe0f740870c766b2c9a97451a2aa25a141daf58621c8c87eaf4d8d986cd0d0db1431137b77498bc180444397f2bcecb0dfce9b0f48db7f77fb14a19764dba945126de708a37c8976d43876d02eb3b02b741a7e00115e4f53fbb8ec676011e1daa5da45f12f93413e84ae24ba0aa96b40b144f773d7e7f9ceaf9793794e28534419c24aee86bcba4251876ace0833e0d0c0291d0147f9cc0afd27b64daf387f421458463d0383194f37becb135d5bae8b2186a796f577404d155c3259ae336a090130b675811c84f358458dc8f0cda407dff4ef6aaaca874e8034725d6f7f36c954bfe397a33dd1bb64c65ef30485447ab46333299080e3c99e42be55e55f6713ab9a2f4b750b6bddcb6740bb82f7ed3f5391a1631cec7bce65b776f4f3393beea54a3fd12786a356664f3f
|
||||||
@@ -0,0 +1,689 @@
|
|||||||
|
//! Hostile input for the HTTP side (`docs/PROTOCOL.md` 1.1-1.4): the XML reader, serverinfo, applist, launch and
|
||||||
|
//! status answers, and the request builders. Every case asserts a specific result.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{param, parse_query, xml_padded_to, xml_root};
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::http::xml::{
|
||||||
|
self, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES,
|
||||||
|
};
|
||||||
|
use domistream::http::{self, Scheme};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
/// Asserts `Err(TooLarge { max, .. })` for caps where `actual` is a count the parser chooses how to report.
|
||||||
|
macro_rules! assert_cap {
|
||||||
|
($e:expr, $max:expr) => {
|
||||||
|
match $e {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
|
||||||
|
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ XML
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_minimal_documents() {
|
||||||
|
let d = xml::parse(br#"<root status_code="200"/>"#).unwrap();
|
||||||
|
assert_eq!(d.status_code, 200);
|
||||||
|
assert_eq!(d.status_message, None);
|
||||||
|
assert_eq!(d.root.name, "root");
|
||||||
|
assert!(d.root.children.is_empty());
|
||||||
|
|
||||||
|
let d = xml::parse(br#"<?xml version="1.0" encoding="utf-8"?><root status_code="200"></root>"#).unwrap();
|
||||||
|
assert_eq!(d.status_code, 200);
|
||||||
|
|
||||||
|
let d = xml::parse(br#"<root status_code="401" status_message="The client is not authorized"/>"#).unwrap();
|
||||||
|
assert_eq!(d.status_code, 401, "xml::parse reports the status; refusing it is the callers' job");
|
||||||
|
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_tree_text_and_attributes() {
|
||||||
|
let d = xml::parse(br#"<root status_code="200" a="1"><x k="v&w">t1<y/>t2</x><z><>&"'AB</z></root>"#)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(d.root.attributes, vec![("status_code".into(), "200".into()), ("a".into(), "1".into())]);
|
||||||
|
let x = &d.root.children[0];
|
||||||
|
assert_eq!(x.name, "x");
|
||||||
|
assert_eq!(x.attributes, vec![("k".into(), "v&w".into())]);
|
||||||
|
assert_eq!(x.text, "t1t2", "text is concatenated around child elements");
|
||||||
|
assert_eq!(x.children[0].name, "y");
|
||||||
|
assert_eq!(d.root.children[1].text, "<>&\"'AB");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_text_is_not_trimmed() {
|
||||||
|
let d = xml::parse(b"<root status_code=\"200\"><a> x \n</a></root>").unwrap();
|
||||||
|
assert_eq!(d.root.children[0].text, " x \n");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_empty_and_tiny_inputs() {
|
||||||
|
assert_err!(xml::parse(b""), Error::Malformed { .. });
|
||||||
|
assert_err!(xml::parse(b"<"), Error::Malformed { .. });
|
||||||
|
assert_err!(xml::parse(b"x"), Error::Malformed { .. });
|
||||||
|
assert_err!(xml::parse(b"<root"), Error::Malformed { .. });
|
||||||
|
assert_err!(xml::parse(b"<root status_code=\"200\">"), Error::Malformed { .. }, "unclosed root");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_refuses_non_documents() {
|
||||||
|
for (bad, why) in [
|
||||||
|
(&br#"<other status_code="200"/>"#[..], "root must be `root`"),
|
||||||
|
(br#"<root/>"#, "no status_code"),
|
||||||
|
(br#"<root status_code="abc"/>"#, "status_code not decimal"),
|
||||||
|
(br#"<root status_code=""/>"#, "empty status_code"),
|
||||||
|
(br#"<root status_code="99999999999"/>"#, "status_code over u32"),
|
||||||
|
(br#"<root status_code="-200"/>"#, "negative status_code"),
|
||||||
|
(br#"<root status_code=200/>"#, "unquoted attribute"),
|
||||||
|
(br#"<root status_code="200" status_code="200"/>"#, "duplicate attribute"),
|
||||||
|
(br#"<root status_code="200"><a></b></root>"#, "mismatched end tag"),
|
||||||
|
(br#"<root status_code="200"><a></root>"#, "unclosed child"),
|
||||||
|
(br#"<root status_code="200"/><root status_code="200"/>"#, "two roots"),
|
||||||
|
(br#"<root status_code="200"/>garbage"#, "text after the root"),
|
||||||
|
(br#"<root status_code="200">&unknown;</root>"#, "unknown entity"),
|
||||||
|
(br#"<root status_code="200">&</root>"#, "entity without ;"),
|
||||||
|
(br#"<root status_code="200">a & b</root>"#, "bare &"),
|
||||||
|
(br#"<root status_code="200">�</root>"#, "NUL character reference"),
|
||||||
|
(br#"<root status_code="200">�</root>"#, "surrogate character reference"),
|
||||||
|
(br#"<root status_code="200">�</root>"#, "character reference past Unicode"),
|
||||||
|
(br#"<root status_code="200">�</root>"#, "overflowing character reference"),
|
||||||
|
(br#"<root status_code="200">&#xZZ;</root>"#, "bad hex reference"),
|
||||||
|
(br#"<root status_code="200"><a b="<"/></root>"#, "< in attribute value"),
|
||||||
|
(br#"<!DOCTYPE root><root status_code="200"/>"#, "DTD"),
|
||||||
|
(
|
||||||
|
br#"<?xml version="1.0"?><!DOCTYPE r [<!ENTITY a "aaaa">]><root status_code="200">&a;</root>"#,
|
||||||
|
"entity declaration",
|
||||||
|
),
|
||||||
|
(br#"<root status_code="200"><?pi data?></root>"#, "processing instruction in the body"),
|
||||||
|
(br#" <?xml version="1.0"?><root status_code="200"/>"#, "XML declaration not at the start"),
|
||||||
|
(br#"<root xmlns:a="urn:x" status_code="200"><a:b/></root>"#, "namespaces"),
|
||||||
|
(b"<root status_code=\"200\">\xff\xfe</root>", "not UTF-8"),
|
||||||
|
(b"<root status_code=\"200\">\xc3</root>", "truncated UTF-8"),
|
||||||
|
(br#"<1root status_code="200"/>"#, "bad name"),
|
||||||
|
] {
|
||||||
|
assert_err!(xml::parse(bad), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_billion_laughs_is_refused_without_expansion() {
|
||||||
|
let mut doc = String::from("<?xml version=\"1.0\"?><!DOCTYPE lolz [<!ENTITY lol \"lol\">");
|
||||||
|
for i in 1..10 {
|
||||||
|
doc.push_str(&format!("<!ENTITY lol{i} \"{}\">", format!("&lol{};", i - 1).repeat(10)));
|
||||||
|
}
|
||||||
|
doc.push_str("]><root status_code=\"200\">&lol9;</root>");
|
||||||
|
assert_err!(xml::parse(doc.as_bytes()), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_size_boundaries() {
|
||||||
|
// max-1 and max are fine (a valid document of exactly that size), max+1 is refused before parsing.
|
||||||
|
for len in [MAX_XML_BYTES - 1, MAX_XML_BYTES] {
|
||||||
|
let d = xml::parse(&xml_padded_to("", len)).unwrap_or_else(|e| panic!("{len} bytes: {e:?}"));
|
||||||
|
assert_eq!(d.status_code, 200);
|
||||||
|
}
|
||||||
|
let over = xml_padded_to("", MAX_XML_BYTES + 1);
|
||||||
|
assert_too_large!(xml::parse(&over), MAX_XML_BYTES, MAX_XML_BYTES + 1);
|
||||||
|
// Huge: refused on size alone, whatever the content.
|
||||||
|
let huge = vec![b'<'; 4 * MAX_XML_BYTES];
|
||||||
|
assert_too_large!(xml::parse(&huge), MAX_XML_BYTES, 4 * MAX_XML_BYTES);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn nested(depth: usize) -> Vec<u8> {
|
||||||
|
// root is depth 1
|
||||||
|
let mut s = String::from("<root status_code=\"200\">");
|
||||||
|
for _ in 1..depth {
|
||||||
|
s.push_str("<a>");
|
||||||
|
}
|
||||||
|
for _ in 1..depth {
|
||||||
|
s.push_str("</a>");
|
||||||
|
}
|
||||||
|
s.push_str("</root>");
|
||||||
|
s.into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_depth_cap() {
|
||||||
|
let d = xml::parse(&nested(MAX_XML_DEPTH)).unwrap();
|
||||||
|
let mut e = &d.root;
|
||||||
|
let mut depth = 1;
|
||||||
|
while let Some(c) = e.children.first() {
|
||||||
|
e = c;
|
||||||
|
depth += 1;
|
||||||
|
}
|
||||||
|
assert_eq!(depth, MAX_XML_DEPTH);
|
||||||
|
assert_cap!(xml::parse(&nested(MAX_XML_DEPTH + 1)), MAX_XML_DEPTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_depth_bomb_does_not_recurse() {
|
||||||
|
// 300 000 open tags in under 1 MiB: a recursive parser overflows the stack; a strict one stops at depth 9.
|
||||||
|
let mut s = String::from("<root status_code=\"200\">");
|
||||||
|
s.push_str(&"<a>".repeat(300_000));
|
||||||
|
assert!(s.len() < MAX_XML_BYTES);
|
||||||
|
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
|
||||||
|
// A closed, well-formed bomb that fits under the size cap (100 000 opens + 100 000 closes, about 0.7 MB): still
|
||||||
|
// refused at depth 9, never parsed by recursion. (The earlier 300 000-pair version was 2.1 MB, over the size
|
||||||
|
// cap, so its depth check never ran: ruled wrong 2026-11-26.)
|
||||||
|
let mut closed = String::from("<root status_code=\"200\">");
|
||||||
|
closed.push_str(&"<a>".repeat(100_000));
|
||||||
|
closed.push_str(&"</a>".repeat(100_000));
|
||||||
|
closed.push_str("</root>");
|
||||||
|
assert!(closed.len() <= MAX_XML_BYTES, "{} bytes must fit the size cap", closed.len());
|
||||||
|
assert_cap!(xml::parse(closed.as_bytes()), MAX_XML_DEPTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_element_cap() {
|
||||||
|
let ok = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS - 1));
|
||||||
|
assert_eq!(xml::parse(&ok).unwrap().root.children.len(), MAX_XML_ELEMENTS - 1);
|
||||||
|
let over = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS));
|
||||||
|
assert_cap!(xml::parse(&over), MAX_XML_ELEMENTS);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_attribute_cap() {
|
||||||
|
let attrs = |n: usize| (1..n).map(|i| format!(" a{i}=\"{i}\"")).collect::<String>();
|
||||||
|
let ok = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES));
|
||||||
|
assert_eq!(xml::parse(ok.as_bytes()).unwrap().root.attributes.len(), MAX_XML_ATTRIBUTES);
|
||||||
|
let over = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES + 1));
|
||||||
|
assert_cap!(xml::parse(over.as_bytes()), MAX_XML_ATTRIBUTES);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn xml_text_cap_counts_unescaped_bytes() {
|
||||||
|
let ok = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES)));
|
||||||
|
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
|
||||||
|
let over = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES + 1)));
|
||||||
|
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
|
||||||
|
// 5 raw bytes per unescaped byte: the cap is on the result, not the input.
|
||||||
|
let ok = xml_root(200, &format!("<t>{}</t>", "&".repeat(MAX_XML_TEXT_BYTES)));
|
||||||
|
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
|
||||||
|
let over = xml_root(200, &format!("<t>{}</t>", "&".repeat(MAX_XML_TEXT_BYTES + 1)));
|
||||||
|
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ XML properties
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Tree {
|
||||||
|
name: String,
|
||||||
|
attrs: Vec<(String, String)>,
|
||||||
|
text: String,
|
||||||
|
children: Vec<Tree>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn escape(s: &str) -> String {
|
||||||
|
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn serialize(t: &Tree, out: &mut String) {
|
||||||
|
out.push('<');
|
||||||
|
out.push_str(&t.name);
|
||||||
|
for (k, v) in &t.attrs {
|
||||||
|
out.push_str(&format!(" {k}=\"{}\"", escape(v)));
|
||||||
|
}
|
||||||
|
out.push('>');
|
||||||
|
out.push_str(&escape(&t.text));
|
||||||
|
for c in &t.children {
|
||||||
|
serialize(c, out);
|
||||||
|
}
|
||||||
|
out.push_str(&format!("</{}>", t.name));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn same(e: &xml::Element, t: &Tree) -> bool {
|
||||||
|
e.name == t.name
|
||||||
|
&& e.attributes == t.attrs
|
||||||
|
&& e.text == t.text
|
||||||
|
&& e.children.len() == t.children.len()
|
||||||
|
&& e.children.iter().zip(&t.children).all(|(a, b)| same(a, b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tree(depth: u32) -> impl Strategy<Value = Tree> {
|
||||||
|
// No leading x/X: names starting with "xml" are reserved, and `xmlns` would be a namespace declaration.
|
||||||
|
let name = "[a-wA-W][a-zA-Z0-9_]{0,6}";
|
||||||
|
let text = "[ -~&<>\"'é]{0,12}";
|
||||||
|
let attrs = proptest::collection::btree_map("[a-w][a-z0-9]{0,4}", text, 0..3)
|
||||||
|
.prop_map(|m| m.into_iter().filter(|(k, _)| k != "status_code").collect::<Vec<_>>());
|
||||||
|
let leaf = (name, attrs.clone(), text).prop_map(|(name, attrs, text)| Tree {
|
||||||
|
name: name.to_string(),
|
||||||
|
attrs,
|
||||||
|
text,
|
||||||
|
children: vec![],
|
||||||
|
});
|
||||||
|
leaf.prop_recursive(depth, 24, 4, move |inner| {
|
||||||
|
("[a-wA-W][a-zA-Z0-9_]{0,6}", attrs.clone(), "[ -~]{0,8}", proptest::collection::vec(inner, 0..4))
|
||||||
|
.prop_map(|(name, attrs, text, children)| Tree { name, attrs, text, children })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Serialize a random tree (depth <= MAX_XML_DEPTH - 1 under root), parse it back, get the same tree.
|
||||||
|
#[test]
|
||||||
|
fn xml_round_trips_generated_trees(children in proptest::collection::vec(tree(5), 0..4), code in 100u32..600) {
|
||||||
|
let root = Tree {
|
||||||
|
name: "root".into(),
|
||||||
|
attrs: vec![("status_code".into(), code.to_string())],
|
||||||
|
text: String::new(),
|
||||||
|
children,
|
||||||
|
};
|
||||||
|
let mut s = String::new();
|
||||||
|
serialize(&root, &mut s);
|
||||||
|
let d = xml::parse(s.as_bytes()).map_err(|e| TestCaseError::fail(format!("{e:?} for {s}")))?;
|
||||||
|
prop_assert_eq!(d.status_code, code);
|
||||||
|
prop_assert!(same(&d.root, &root), "tree differs for {}", s);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary bytes: never panics; any success respects every cap.
|
||||||
|
#[test]
|
||||||
|
fn xml_never_panics_and_respects_caps(data in proptest::collection::vec(any::<u8>(), 0..2048)) {
|
||||||
|
let parsed = xml::parse(&data);
|
||||||
|
prop_assert!(common::implemented(&parsed));
|
||||||
|
if let Ok(d) = parsed {
|
||||||
|
fn walk(e: &xml::Element, depth: usize, count: &mut usize) -> bool {
|
||||||
|
*count += 1;
|
||||||
|
depth <= MAX_XML_DEPTH
|
||||||
|
&& e.attributes.len() <= MAX_XML_ATTRIBUTES
|
||||||
|
&& e.text.len() <= MAX_XML_TEXT_BYTES
|
||||||
|
&& e.children.iter().all(|c| walk(c, depth + 1, count))
|
||||||
|
}
|
||||||
|
let mut count = 0;
|
||||||
|
prop_assert!(walk(&d.root, 1, &mut count));
|
||||||
|
prop_assert!(count <= MAX_XML_ELEMENTS);
|
||||||
|
prop_assert_eq!(d.root.name.as_str(), "root");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mutating a valid document (one byte flipped, truncated) never panics, and truncation is always an error.
|
||||||
|
#[test]
|
||||||
|
fn xml_truncation_is_an_error(cut in 0usize..60) {
|
||||||
|
let doc = br#"<root status_code="200"><a k="v">text&</a><b/></root>"#;
|
||||||
|
let cut = cut.min(doc.len() - 1);
|
||||||
|
let r = xml::parse(&doc[..cut]);
|
||||||
|
prop_assert!(matches!(r, Err(Error::Malformed { .. } | Error::Truncated { .. })), "{:?}", r);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ serverinfo
|
||||||
|
|
||||||
|
const SERVERINFO: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">\n\
|
||||||
|
<hostname>LAB-PC</hostname>\n<appversion>7.1.431.-1</appversion>\n<GfeVersion>3.23.0.74</GfeVersion>\n\
|
||||||
|
<uniqueid>0123456789ABCDEF0123456789ABCDEF</uniqueid>\n<HttpsPort>47984</HttpsPort>\n\
|
||||||
|
<ExternalPort>47989</ExternalPort>\n<mac>00:11:22:aa:BB:ff</mac>\n<LocalIP>192.0.2.10</LocalIP>\n\
|
||||||
|
<MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC>\n<ServerCodecModeSupport>259</ServerCodecModeSupport>\n\
|
||||||
|
<SupportedDisplayMode></SupportedDisplayMode>\n<PairStatus>0</PairStatus>\n<currentgame>0</currentgame>\n\
|
||||||
|
<state>SUNSHINE_SERVER_FREE</state>\n</root>\n";
|
||||||
|
|
||||||
|
fn serverinfo_with(field: &str, value: Option<&str>) -> Vec<u8> {
|
||||||
|
let open = format!("<{field}>");
|
||||||
|
let close = format!("</{field}>");
|
||||||
|
let start = SERVERINFO.find(&open).unwrap_or_else(|| panic!("{field} in sample"));
|
||||||
|
let end = SERVERINFO[start..].find(&close).unwrap() + start + close.len();
|
||||||
|
let replacement = value.map(|v| format!("{open}{v}{close}")).unwrap_or_default();
|
||||||
|
format!("{}{}{}", &SERVERINFO[..start], replacement, &SERVERINFO[end..]).into_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_sample() {
|
||||||
|
let s = http::parse_server_info(SERVERINFO.as_bytes()).unwrap();
|
||||||
|
assert_eq!(s.hostname, "LAB-PC");
|
||||||
|
assert_eq!(s.app_version, "7.1.431.-1");
|
||||||
|
assert_eq!(s.gfe_version.as_deref(), Some("3.23.0.74"));
|
||||||
|
assert_eq!(s.unique_id, "0123456789ABCDEF0123456789ABCDEF");
|
||||||
|
assert_eq!(s.https_port, 47984);
|
||||||
|
assert_eq!(s.http_port, Some(47989));
|
||||||
|
assert_eq!(s.mac, Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]));
|
||||||
|
assert_eq!(s.local_ip.as_deref(), Some("192.0.2.10"));
|
||||||
|
assert_eq!(s.max_luma_pixels_hevc, Some(1_869_449_984));
|
||||||
|
assert_eq!(s.codec_mode_support, Some(259));
|
||||||
|
assert!(!s.paired);
|
||||||
|
assert_eq!(s.current_game, 0);
|
||||||
|
assert_eq!(s.state, "SUNSHINE_SERVER_FREE");
|
||||||
|
assert!(!s.is_busy().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_optional_fields() {
|
||||||
|
let s = http::parse_server_info(&serverinfo_with("mac", Some(""))).unwrap();
|
||||||
|
assert_eq!(s.mac, None, "empty mac is None");
|
||||||
|
let s = http::parse_server_info(&serverinfo_with("GfeVersion", None)).unwrap();
|
||||||
|
assert_eq!(s.gfe_version, None);
|
||||||
|
let s = http::parse_server_info(&serverinfo_with("ExternalPort", None)).unwrap();
|
||||||
|
assert_eq!(s.http_port, None);
|
||||||
|
let s = http::parse_server_info(&serverinfo_with("PairStatus", Some("1"))).unwrap();
|
||||||
|
assert!(s.paired);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_busy() {
|
||||||
|
let s = http::parse_server_info(&serverinfo_with("state", Some("SUNSHINE_SERVER_BUSY"))).unwrap();
|
||||||
|
assert!(s.is_busy().unwrap());
|
||||||
|
let s = http::parse_server_info(&serverinfo_with("currentgame", Some("881448767"))).unwrap();
|
||||||
|
assert_eq!(s.current_game, 881_448_767);
|
||||||
|
assert!(s.is_busy().unwrap());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_refuses_bad_fields() {
|
||||||
|
for field in ["hostname", "uniqueid", "HttpsPort"] {
|
||||||
|
assert_err!(http::parse_server_info(&serverinfo_with(field, None)), Error::Malformed { .. }, "missing {field}");
|
||||||
|
}
|
||||||
|
for (field, value) in [
|
||||||
|
("HttpsPort", "70000"),
|
||||||
|
("HttpsPort", "-1"),
|
||||||
|
("HttpsPort", ""),
|
||||||
|
("HttpsPort", "0x1F"),
|
||||||
|
("HttpsPort", " 47984"),
|
||||||
|
("ExternalPort", "65536"),
|
||||||
|
("currentgame", "abc"),
|
||||||
|
("currentgame", "4294967296"),
|
||||||
|
("MaxLumaPixelsHEVC", "1e9"),
|
||||||
|
("ServerCodecModeSupport", "-3"),
|
||||||
|
("mac", "00:11:22:33:44"),
|
||||||
|
("mac", "00:11:22:33:44:55:66"),
|
||||||
|
("mac", "zz:11:22:33:44:55"),
|
||||||
|
] {
|
||||||
|
assert_err!(
|
||||||
|
http::parse_server_info(&serverinfo_with(field, Some(value))),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{field}={value:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_field_cap() {
|
||||||
|
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES as MAX;
|
||||||
|
let ok = "h".repeat(MAX);
|
||||||
|
assert_eq!(http::parse_server_info(&serverinfo_with("hostname", Some(&ok))).unwrap().hostname, ok);
|
||||||
|
assert_cap!(http::parse_server_info(&serverinfo_with("hostname", Some(&"h".repeat(MAX + 1)))), MAX);
|
||||||
|
assert_cap!(http::parse_server_info(&serverinfo_with("state", Some(&"s".repeat(MAX + 1)))), MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn serverinfo_status_and_sizes() {
|
||||||
|
use domistream::http::serverinfo::MAX_SERVERINFO_BYTES as MAX;
|
||||||
|
assert_err!(http::parse_server_info(&xml_root(503, "")), Error::HostStatus { code: 503 });
|
||||||
|
assert_err!(http::parse_server_info(b""), Error::Malformed { .. });
|
||||||
|
assert_err!(http::parse_server_info(b"<"), Error::Malformed { .. });
|
||||||
|
let inner = SERVERINFO
|
||||||
|
.trim_start_matches("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">")
|
||||||
|
.trim_end_matches("</root>\n");
|
||||||
|
for len in [MAX - 1, MAX] {
|
||||||
|
let s = http::parse_server_info(&xml_padded_to(inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
||||||
|
assert_eq!(s.hostname, "LAB-PC");
|
||||||
|
}
|
||||||
|
assert_too_large!(http::parse_server_info(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
|
||||||
|
assert_too_large!(http::parse_server_info(&vec![b' '; 64 * MAX]), MAX, 64 * MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ applist
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn applist_sample() {
|
||||||
|
let body = xml_root(
|
||||||
|
200,
|
||||||
|
"<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>\
|
||||||
|
<App><AppTitle>Steam & Friends</AppTitle><ID>2</ID><IsHdrSupported>0</IsHdrSupported></App>\
|
||||||
|
<App><AppTitle>No HDR field</AppTitle><ID>3</ID></App>",
|
||||||
|
);
|
||||||
|
let apps = http::parse_app_list(&body).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
apps,
|
||||||
|
vec![
|
||||||
|
http::App { id: 881_448_767, title: "Desktop".into(), hdr_supported: true },
|
||||||
|
http::App { id: 2, title: "Steam & Friends".into(), hdr_supported: false },
|
||||||
|
http::App { id: 3, title: "No HDR field".into(), hdr_supported: false },
|
||||||
|
]
|
||||||
|
);
|
||||||
|
assert_eq!(http::parse_app_list(&xml_root(200, "")).unwrap(), vec![]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn applist_refuses_bad_apps() {
|
||||||
|
for (inner, why) in [
|
||||||
|
("<App><AppTitle>A</AppTitle></App>", "no ID"),
|
||||||
|
("<App><ID>1</ID></App>", "no AppTitle"),
|
||||||
|
("<App><AppTitle>A</AppTitle><ID>-1</ID></App>", "negative ID"),
|
||||||
|
("<App><AppTitle>A</AppTitle><ID>abc</ID></App>", "ID not decimal"),
|
||||||
|
("<App><AppTitle>A</AppTitle><ID>4294967296</ID></App>", "ID over u32"),
|
||||||
|
("<App><AppTitle>A</AppTitle><ID>1</ID></App><App><AppTitle>B</AppTitle><ID>1</ID></App>", "duplicate ID"),
|
||||||
|
] {
|
||||||
|
assert_err!(http::parse_app_list(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
assert_err!(http::parse_app_list(&xml_root(401, "")), Error::HostStatus { code: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn applist_caps() {
|
||||||
|
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
|
||||||
|
let app = |i: usize, title: &str| format!("<App><AppTitle>{title}</AppTitle><ID>{i}</ID></App>");
|
||||||
|
let t = "t".repeat(MAX_APP_TITLE_BYTES);
|
||||||
|
assert_eq!(http::parse_app_list(&xml_root(200, &app(1, &t))).unwrap()[0].title, t);
|
||||||
|
assert_cap!(
|
||||||
|
http::parse_app_list(&xml_root(200, &app(1, &"t".repeat(MAX_APP_TITLE_BYTES + 1)))),
|
||||||
|
MAX_APP_TITLE_BYTES
|
||||||
|
);
|
||||||
|
// Multi-byte titles: the cap is in bytes.
|
||||||
|
assert_cap!(
|
||||||
|
http::parse_app_list(&xml_root(200, &app(1, &"é".repeat(MAX_APP_TITLE_BYTES / 2 + 1)))),
|
||||||
|
MAX_APP_TITLE_BYTES
|
||||||
|
);
|
||||||
|
|
||||||
|
let list = |n: usize| (0..n).map(|i| app(i, "g")).collect::<String>();
|
||||||
|
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
|
||||||
|
assert_cap!(http::parse_app_list(&xml_root(200, &list(MAX_APPS + 1))), MAX_APPS);
|
||||||
|
|
||||||
|
let inner = app(1, "Desktop");
|
||||||
|
for len in [MAX_APPLIST_BYTES - 1, MAX_APPLIST_BYTES] {
|
||||||
|
let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
||||||
|
assert_eq!(apps.len(), 1, "unknown elements are ignored");
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
http::parse_app_list(&xml_padded_to(&inner, MAX_APPLIST_BYTES + 1)),
|
||||||
|
MAX_APPLIST_BYTES,
|
||||||
|
MAX_APPLIST_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(
|
||||||
|
http::parse_app_list(&vec![b'<'; 3 * MAX_APPLIST_BYTES]),
|
||||||
|
MAX_APPLIST_BYTES,
|
||||||
|
3 * MAX_APPLIST_BYTES
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ launch
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_response_sample() {
|
||||||
|
let r = http::parse_launch_response(&xml_root(
|
||||||
|
200,
|
||||||
|
"<sessionUrl0>rtsp://192.0.2.10:48010</sessionUrl0><gamesession>1</gamesession>",
|
||||||
|
))
|
||||||
|
.unwrap();
|
||||||
|
assert!(r.game_session);
|
||||||
|
assert_eq!(r.session_url.as_deref(), Some("rtsp://192.0.2.10:48010"));
|
||||||
|
|
||||||
|
let r = http::parse_launch_response(&xml_root(200, "<gamesession>1</gamesession>")).unwrap();
|
||||||
|
assert_eq!(r.session_url, None, "missing sessionUrl0 is None (UNKNOWN U4)");
|
||||||
|
let r = http::parse_launch_response(&xml_root(200, "<gamesession>0</gamesession>")).unwrap();
|
||||||
|
assert!(!r.game_session);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_response_refuses_bad_urls() {
|
||||||
|
for url in [
|
||||||
|
"http://192.0.2.10:48010",
|
||||||
|
"rtsp://192.0.2.10",
|
||||||
|
"rtsp://192.0.2.10:",
|
||||||
|
"rtsp://192.0.2.10:99999",
|
||||||
|
"rtsp://192.0.2.10:-1",
|
||||||
|
"rtsp://:48010",
|
||||||
|
"rtsp://192.0.2.10:48010\r\nCSeq: 9",
|
||||||
|
"rtsp://192.0.2.10:48a",
|
||||||
|
"",
|
||||||
|
] {
|
||||||
|
let body = xml_root(200, &format!("<sessionUrl0>{url}</sessionUrl0><gamesession>1</gamesession>"));
|
||||||
|
assert_err!(http::parse_launch_response(&body), Error::Malformed { .. }, "{url:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_response_caps() {
|
||||||
|
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES as MAX, MAX_SESSION_URL_BYTES as URL};
|
||||||
|
let prefix = "rtsp://";
|
||||||
|
let suffix = ":48010";
|
||||||
|
// A host name of DNS labels of 9 letters, so only the length is unusual.
|
||||||
|
let host = |n: usize| {
|
||||||
|
let len = n - prefix.len() - suffix.len();
|
||||||
|
(0..len).map(|i| if i % 10 == 9 && i + 1 < len { '.' } else { 'h' }).collect::<String>()
|
||||||
|
};
|
||||||
|
let ok = format!("{prefix}{}{suffix}", host(URL));
|
||||||
|
let r = http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{ok}</sessionUrl0>"))).unwrap();
|
||||||
|
assert_eq!(r.session_url.as_deref(), Some(ok.as_str()));
|
||||||
|
let over = format!("{prefix}{}{suffix}", host(URL + 1));
|
||||||
|
assert_cap!(http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{over}</sessionUrl0>"))), URL);
|
||||||
|
|
||||||
|
let inner = "<gamesession>1</gamesession>";
|
||||||
|
for len in [MAX - 1, MAX] {
|
||||||
|
assert!(http::parse_launch_response(&xml_padded_to(inner, len)).unwrap().game_session);
|
||||||
|
}
|
||||||
|
assert_too_large!(http::parse_launch_response(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
|
||||||
|
assert_too_large!(http::parse_launch_response(&vec![0u8; 1 << 20]), MAX, 1 << 20);
|
||||||
|
assert_err!(http::parse_launch_response(&xml_root(503, "")), Error::HostStatus { code: 503 });
|
||||||
|
assert_err!(http::parse_launch_response(b""), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn status_response() {
|
||||||
|
assert_eq!(http::parse_status_response(&xml_root(200, "")), Ok(()));
|
||||||
|
assert_err!(http::parse_status_response(&xml_root(404, "")), Error::HostStatus { code: 404 });
|
||||||
|
assert_err!(http::parse_status_response(b"OK"), Error::Malformed { .. });
|
||||||
|
assert_err!(http::parse_status_response(b""), Error::Malformed { .. });
|
||||||
|
assert_too_large!(http::parse_status_response(&vec![b' '; MAX_XML_BYTES + 1]), MAX_XML_BYTES, MAX_XML_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ requests
|
||||||
|
|
||||||
|
const UID: &str = "0123456789ABCDEF";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn simple_requests() {
|
||||||
|
let r = http::server_info_request(Scheme::Http, UID).unwrap();
|
||||||
|
assert_eq!(r.scheme, Scheme::Http);
|
||||||
|
let (path, q) = parse_query(&r.path_and_query);
|
||||||
|
assert_eq!(path, "/serverinfo");
|
||||||
|
assert_eq!(param(&q, "uniqueid"), UID);
|
||||||
|
assert_eq!(http::server_info_request(Scheme::Https, UID).unwrap().scheme, Scheme::Https);
|
||||||
|
|
||||||
|
for (r, want) in [
|
||||||
|
(http::app_list_request(UID).unwrap(), "/applist"),
|
||||||
|
(http::cancel_request(UID).unwrap(), "/cancel"),
|
||||||
|
(http::unpair_request(UID).unwrap(), "/unpair"),
|
||||||
|
] {
|
||||||
|
assert_eq!(r.scheme, Scheme::Https, "{want} goes over HTTPS");
|
||||||
|
let (path, q) = parse_query(&r.path_and_query);
|
||||||
|
assert_eq!(path, want);
|
||||||
|
assert_eq!(param(&q, "uniqueid"), UID);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn requests_refuse_bad_unique_ids() {
|
||||||
|
use domistream::http::MAX_UNIQUE_ID_BYTES as MAX;
|
||||||
|
for bad in [String::new(), "a".repeat(MAX + 1)] {
|
||||||
|
assert_err!(http::server_info_request(Scheme::Http, &bad), Error::Malformed { .. });
|
||||||
|
assert_err!(http::app_list_request(&bad), Error::Malformed { .. });
|
||||||
|
assert_err!(http::cancel_request(&bad), Error::Malformed { .. });
|
||||||
|
assert_err!(http::unpair_request(&bad), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
assert!(http::server_info_request(Scheme::Http, &"a".repeat(MAX)).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn requests_cannot_be_injected() {
|
||||||
|
// A unique id with query syntax is refused or encoded; it never adds a parameter.
|
||||||
|
for evil in ["a&uniqueid=b", "a#frag", "a b", "a\r\nX: y", "a=b", "%26"] {
|
||||||
|
match http::server_info_request(Scheme::Http, evil) {
|
||||||
|
Err(Error::Malformed { .. }) => {}
|
||||||
|
Ok(r) => {
|
||||||
|
let (path, q) = parse_query(&r.path_and_query);
|
||||||
|
assert_eq!(path, "/serverinfo");
|
||||||
|
assert_eq!(param(&q, "uniqueid"), evil);
|
||||||
|
assert!(!r.path_and_query.contains(['\r', '\n', ' ', '#']), "{:?}", r.path_and_query);
|
||||||
|
}
|
||||||
|
other => panic!("{evil:?}: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn launch_params() -> http::LaunchParams {
|
||||||
|
http::LaunchParams {
|
||||||
|
app_id: 881_448_767,
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
fps: 60,
|
||||||
|
keys: domistream::SessionKeys {
|
||||||
|
rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff",
|
||||||
|
rikeyid: 1_234_567,
|
||||||
|
},
|
||||||
|
hdr: false,
|
||||||
|
audio: http::launch::AudioLayout::Stereo,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_request_parameters() {
|
||||||
|
let r = http::launch::launch_request(&launch_params(), UID).unwrap();
|
||||||
|
assert_eq!(r.scheme, Scheme::Https);
|
||||||
|
let (path, q) = parse_query(&r.path_and_query);
|
||||||
|
assert_eq!(path, "/launch");
|
||||||
|
assert_eq!(param(&q, "uniqueid"), UID);
|
||||||
|
assert_eq!(param(&q, "appid"), "881448767");
|
||||||
|
assert_eq!(param(&q, "mode"), "1920x1080x60");
|
||||||
|
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
|
||||||
|
assert_eq!(param(&q, "rikeyid"), "1234567");
|
||||||
|
assert_eq!(param(&q, "hdrMode"), "0");
|
||||||
|
assert_eq!(param(&q, "surroundAudioInfo"), "196610", "stereo = 0x30002");
|
||||||
|
|
||||||
|
let mut p = launch_params();
|
||||||
|
p.hdr = true;
|
||||||
|
let (_, q) = parse_query(&http::launch::launch_request(&p, UID).unwrap().path_and_query);
|
||||||
|
assert_eq!(param(&q, "hdrMode"), "1");
|
||||||
|
|
||||||
|
for broken in [
|
||||||
|
http::LaunchParams { width: 0, ..launch_params() },
|
||||||
|
http::LaunchParams { height: 0, ..launch_params() },
|
||||||
|
http::LaunchParams { fps: 0, ..launch_params() },
|
||||||
|
] {
|
||||||
|
assert_err!(http::launch::launch_request(&broken, UID), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
assert_err!(http::launch::launch_request(&launch_params(), ""), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resume_request_parameters() {
|
||||||
|
let keys = launch_params().keys;
|
||||||
|
let r = http::launch::resume_request(&keys, UID).unwrap();
|
||||||
|
assert_eq!(r.scheme, Scheme::Https);
|
||||||
|
let (path, q) = parse_query(&r.path_and_query);
|
||||||
|
assert_eq!(path, "/resume");
|
||||||
|
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
|
||||||
|
assert_eq!(param(&q, "rikeyid"), "1234567");
|
||||||
|
assert_err!(http::launch::resume_request(&keys, ""), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn session_keys_are_fresh() {
|
||||||
|
let a = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
|
||||||
|
let b = domistream::SessionKeys::generate(&mut common::SeqRng::new(2)).unwrap();
|
||||||
|
let a2 = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
|
||||||
|
assert_eq!(a, a2, "keys come only from the caller's randomness");
|
||||||
|
assert_ne!(a.rikey, b.rikey);
|
||||||
|
assert_ne!(a.rikey, [0; 16]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,264 @@
|
|||||||
|
//! Repository rules that are checked by reading the crate itself: the sans-I/O guard (no sockets, clocks,
|
||||||
|
//! threads, files or OS randomness in `src/`), `forbid(unsafe_code)`, and that `Debug` never prints a secret.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// Things `src/` must never contain outside comments (CLAUDE.md "Sans-I/O"). The left side is matched with all
|
||||||
|
/// whitespace removed, so `std :: net` and `use std::{fs, net}` are caught too.
|
||||||
|
const FORBIDDEN: &[(&str, &str)] = &[
|
||||||
|
("std::net", "sockets"),
|
||||||
|
("Instant::now", "clock reads"),
|
||||||
|
("SystemTime::now", "clock reads"),
|
||||||
|
("std::time::Instant", "the std clock type (use crate::Instant)"),
|
||||||
|
("std::time::SystemTime", "the std clock type"),
|
||||||
|
("UNIX_EPOCH", "clock reads"),
|
||||||
|
("std::thread", "threads"),
|
||||||
|
("thread::spawn", "threads"),
|
||||||
|
("std::fs", "files"),
|
||||||
|
("File::open", "files"),
|
||||||
|
("File::create", "files"),
|
||||||
|
("std::process", "processes"),
|
||||||
|
("std::env::var", "environment reads"),
|
||||||
|
("OsRng", "OS randomness (randomness comes in through RandomSource)"),
|
||||||
|
("thread_rng", "OS randomness"),
|
||||||
|
("getrandom", "OS randomness"),
|
||||||
|
("rand::random", "OS randomness"),
|
||||||
|
("tokio", "async runtimes"),
|
||||||
|
("mio::", "async runtimes"),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Grouped imports `use std::{…}` naming a forbidden module.
|
||||||
|
const FORBIDDEN_IN_STD_GROUP: &[&str] = &["net", "fs", "thread", "process"];
|
||||||
|
|
||||||
|
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
|
||||||
|
for entry in std::fs::read_dir(dir).expect("read src dir") {
|
||||||
|
let path = entry.expect("dir entry").path();
|
||||||
|
if path.is_dir() {
|
||||||
|
rust_files(&path, out);
|
||||||
|
} else if path.extension().is_some_and(|e| e == "rs") {
|
||||||
|
out.push(path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The code of a file with `//` comments (line and doc comments) and `/* */` comments removed. String literals are
|
||||||
|
/// kept: a forbidden name inside a string still fails, on purpose.
|
||||||
|
fn strip_comments(src: &str) -> String {
|
||||||
|
let mut out = String::with_capacity(src.len());
|
||||||
|
let mut chars = src.chars().peekable();
|
||||||
|
let mut in_str = false;
|
||||||
|
while let Some(c) = chars.next() {
|
||||||
|
if in_str {
|
||||||
|
out.push(c);
|
||||||
|
if c == '\\' {
|
||||||
|
if let Some(n) = chars.next() {
|
||||||
|
out.push(n);
|
||||||
|
}
|
||||||
|
} else if c == '"' {
|
||||||
|
in_str = false;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
match (c, chars.peek()) {
|
||||||
|
('"', _) => {
|
||||||
|
in_str = true;
|
||||||
|
out.push(c);
|
||||||
|
}
|
||||||
|
('/', Some('/')) => {
|
||||||
|
for n in chars.by_ref() {
|
||||||
|
if n == '\n' {
|
||||||
|
out.push('\n');
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
('/', Some('*')) => {
|
||||||
|
chars.next();
|
||||||
|
let mut prev = ' ';
|
||||||
|
for n in chars.by_ref() {
|
||||||
|
if prev == '*' && n == '/' {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
prev = n;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => out.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn violations_in(code: &str) -> Vec<String> {
|
||||||
|
let squashed: String = code.chars().filter(|c| !c.is_whitespace()).collect();
|
||||||
|
let mut found = Vec::new();
|
||||||
|
for (needle, why) in FORBIDDEN {
|
||||||
|
if squashed.contains(needle) {
|
||||||
|
found.push(format!("`{needle}` ({why})"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut rest = squashed.as_str();
|
||||||
|
while let Some(i) = rest.find("std::{") {
|
||||||
|
let group = &rest[i + 6..];
|
||||||
|
let end = group.find('}').unwrap_or(group.len());
|
||||||
|
for item in group[..end].split(',') {
|
||||||
|
let head = item.split("::").next().unwrap_or("");
|
||||||
|
if FORBIDDEN_IN_STD_GROUP.contains(&head) {
|
||||||
|
found.push(format!("`std::{{{head}}}` (grouped import)"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rest = &group[end.min(group.len())..];
|
||||||
|
}
|
||||||
|
found
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn src_is_sans_io() {
|
||||||
|
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||||
|
let mut files = Vec::new();
|
||||||
|
rust_files(&src, &mut files);
|
||||||
|
assert!(files.len() >= 20, "expected the whole crate under {}", src.display());
|
||||||
|
let mut report = Vec::new();
|
||||||
|
for file in &files {
|
||||||
|
let code = strip_comments(&std::fs::read_to_string(file).expect("read source"));
|
||||||
|
for v in violations_in(&code) {
|
||||||
|
report.push(format!("{}: {v}", file.strip_prefix(&src).unwrap_or(file).display()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(report.is_empty(), "sans-I/O rule broken:\n{}", report.join("\n"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn guard_catches_what_it_should() {
|
||||||
|
// The guard itself must work, or `src_is_sans_io` proves nothing.
|
||||||
|
for bad in [
|
||||||
|
"use std::net::UdpSocket;",
|
||||||
|
"let t = std::time::Instant::now();",
|
||||||
|
"let t = Instant :: now();",
|
||||||
|
"let t = SystemTime::now();",
|
||||||
|
"std::thread::spawn(|| {});",
|
||||||
|
"let f = std::fs::read(\"x\");",
|
||||||
|
"use std::{fs, io};",
|
||||||
|
"use std::{io, net::TcpStream};",
|
||||||
|
"let mut r = rand::rngs::OsRng;",
|
||||||
|
"getrandom::fill(&mut b);",
|
||||||
|
] {
|
||||||
|
assert!(!violations_in(&strip_comments(bad)).is_empty(), "guard missed: {bad}");
|
||||||
|
}
|
||||||
|
for fine in [
|
||||||
|
"// no std::net here, only a comment",
|
||||||
|
"/// Docs may say Instant::now is forbidden.",
|
||||||
|
"/* std::fs in a block comment */ let x = 1;",
|
||||||
|
"use crate::Instant; let t = Instant::from_micros(5);",
|
||||||
|
"use std::{fmt, error};",
|
||||||
|
"use core::time::Duration;",
|
||||||
|
] {
|
||||||
|
assert!(violations_in(&strip_comments(fine)).is_empty(), "guard flagged: {fine}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_module_forbids_unsafe() {
|
||||||
|
let lib = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs")).expect("lib.rs");
|
||||||
|
assert!(lib.contains("#![forbid(unsafe_code)]"), "lib.rs must carry #![forbid(unsafe_code)]");
|
||||||
|
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
|
||||||
|
let mut files = Vec::new();
|
||||||
|
rust_files(&src, &mut files);
|
||||||
|
for file in files {
|
||||||
|
let code = strip_comments(&std::fs::read_to_string(&file).expect("read"));
|
||||||
|
assert_eq!(
|
||||||
|
code.matches("unsafe").count(),
|
||||||
|
code.matches("unsafe_code").count(),
|
||||||
|
"{}: `unsafe` in src",
|
||||||
|
file.display()
|
||||||
|
);
|
||||||
|
assert!(!code.contains("allow(unsafe_code)"), "{}: unsafe allowed", file.display());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ secrets
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = [0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6, 0x17, 0x28, 0x39, 0x4A, 0x5B, 0x6C, 0x7D, 0x8E, 0x9F, 0x10];
|
||||||
|
|
||||||
|
/// Every way the key could show up in a `Debug` string.
|
||||||
|
fn leaks_key(s: &str) -> bool {
|
||||||
|
let lower = s.to_lowercase();
|
||||||
|
lower.contains(&common::to_hex(&KEY))
|
||||||
|
|| lower.contains("161, 178")
|
||||||
|
|| lower.contains("0xa1, 0xb2")
|
||||||
|
|| lower.contains("a1b2c3")
|
||||||
|
|| s.contains("[161")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn debug_never_prints_keys() {
|
||||||
|
let keys = domistream::SessionKeys { rikey: KEY, rikeyid: 7 };
|
||||||
|
let control = domistream::control::ControlCipher::new(KEY);
|
||||||
|
let video = domistream::video::VideoCipher::new(KEY);
|
||||||
|
let audio = domistream::audio::AudioCipher::new(&keys);
|
||||||
|
let config = domistream::control::ControlConfig {
|
||||||
|
enet: domistream::enet::EnetConfig {
|
||||||
|
channel_count: 1,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: core::time::Duration::from_millis(500),
|
||||||
|
timeout: core::time::Duration::from_secs(10),
|
||||||
|
},
|
||||||
|
rikey: KEY,
|
||||||
|
ping_interval: core::time::Duration::from_millis(100),
|
||||||
|
};
|
||||||
|
for (what, s) in [
|
||||||
|
("SessionKeys", format!("{keys:?}")),
|
||||||
|
("ControlCipher", format!("{control:?}")),
|
||||||
|
("VideoCipher", format!("{video:?}")),
|
||||||
|
("AudioCipher", format!("{audio:?}")),
|
||||||
|
("ControlConfig", format!("{config:?}")),
|
||||||
|
(
|
||||||
|
"VideoConfig",
|
||||||
|
format!(
|
||||||
|
"{:?}",
|
||||||
|
domistream::video::VideoConfig {
|
||||||
|
packet_size: 1024,
|
||||||
|
cipher: Some(video.clone()),
|
||||||
|
frame_timeout: core::time::Duration::from_millis(100),
|
||||||
|
}
|
||||||
|
),
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert!(!leaks_key(&s), "{what} Debug leaks the key: {s}");
|
||||||
|
assert!(s.contains("redacted"), "{what} Debug should say the key is redacted: {s}");
|
||||||
|
}
|
||||||
|
// rikeyid is not secret: it may show.
|
||||||
|
assert!(format!("{keys:?}").contains('7'));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn debug_never_prints_the_pin_or_the_private_key() {
|
||||||
|
// Pin and ClientIdentity can only be made through the API (Phase A: Unimplemented, so these fail now).
|
||||||
|
let pin = domistream::pairing::Pin::from_digits("4071").expect("Pin::from_digits");
|
||||||
|
let s = format!("{pin:?}");
|
||||||
|
assert!(!s.contains("4071") && !s.contains("52, 48, 55, 49"), "Pin Debug leaks the PIN: {s}");
|
||||||
|
|
||||||
|
let v = common::pairing_vectors();
|
||||||
|
let key = v.bytes("client_key_pkcs8_der");
|
||||||
|
let identity = domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &key)
|
||||||
|
.expect("ClientIdentity::from_der");
|
||||||
|
let s = format!("{identity:?}");
|
||||||
|
assert!(s.contains("redacted"), "{s}");
|
||||||
|
let key_hex = common::to_hex(&key[key.len() - 32..]);
|
||||||
|
assert!(!s.to_lowercase().contains(&key_hex), "ClientIdentity Debug leaks key bytes");
|
||||||
|
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])), "ClientIdentity Debug leaks key bytes");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn error_display_has_no_secret_material() {
|
||||||
|
// Errors are fixed strings and numbers; make sure the variants that come out of crypto paths say nothing.
|
||||||
|
for e in [domistream::Error::Crypto, domistream::Error::PairingRefused] {
|
||||||
|
let s = format!("{e} {e:?}");
|
||||||
|
assert!(!leaks_key(&s), "{s}");
|
||||||
|
assert!(s.len() < 80, "crypto errors are deliberately short: {s}");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,466 @@
|
|||||||
|
//! INPUT_DATA (`docs/PROTOCOL.md` 4): vectors rebuilt from the field tables with our own builder, cross-checked
|
||||||
|
//! against the example bytes in PROTOCOL.md; encode, parse, equal; refusals of unknown types and wrong lengths.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::hex;
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::input::{
|
||||||
|
ButtonFlags, ControllerCapabilities, ControllerKind, GamepadState, INPUT_HEADER_LEN, InputEvent, InputType,
|
||||||
|
MAX_INPUT_MESSAGE_BYTES, MouseButton, encode_input, parse_input,
|
||||||
|
};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
/// `0x0206 LE ‖ length LE (= 4 + size) ‖ size BE (= 4 + data) ‖ input type LE ‖ data`.
|
||||||
|
fn input_message(input_type: u32, data: &[u8]) -> Vec<u8> {
|
||||||
|
let size = 4 + data.len();
|
||||||
|
let mut m = 0x0206u16.to_le_bytes().to_vec();
|
||||||
|
m.extend_from_slice(&((4 + size) as u16).to_le_bytes());
|
||||||
|
m.extend_from_slice(&(size as u32).to_be_bytes());
|
||||||
|
m.extend_from_slice(&input_type.to_le_bytes());
|
||||||
|
m.extend_from_slice(data);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
fn be16(v: i16) -> [u8; 2] {
|
||||||
|
v.to_be_bytes()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rel(dx: i16, dy: i16) -> Vec<u8> {
|
||||||
|
input_message(0x07, &[be16(dx), be16(dy)].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn abs(x: i16, y: i16, w: u16, h: u16) -> Vec<u8> {
|
||||||
|
input_message(0x05, &[&be16(x)[..], &be16(y), &[0, 0], &w.to_be_bytes(), &h.to_be_bytes()].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn button(down: bool, b: u8) -> Vec<u8> {
|
||||||
|
input_message(if down { 0x08 } else { 0x09 }, &[b])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(down: bool, flags: u8, code: u16, modifiers: u8) -> Vec<u8> {
|
||||||
|
input_message(if down { 0x03 } else { 0x04 }, &[&[flags][..], &code.to_le_bytes(), &[modifiers, 0, 0]].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn scroll(amount: i16) -> Vec<u8> {
|
||||||
|
// amount1 and amount2 both carry the amount, as in the PROTOCOL.md example; hosts read amount1.
|
||||||
|
input_message(0x0A, &[&be16(amount)[..], &be16(amount), &[0, 0]].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hscroll(amount: i16) -> Vec<u8> {
|
||||||
|
input_message(0x5500_0001, &be16(amount))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn gamepad(g: &GamepadState) -> Vec<u8> {
|
||||||
|
let mut d = Vec::new();
|
||||||
|
d.extend_from_slice(&0x001Au16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&u16::from(g.controller).to_le_bytes());
|
||||||
|
d.extend_from_slice(&g.active_mask.to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0014u16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 & 0xFFFF) as u16).to_le_bytes());
|
||||||
|
d.push(g.left_trigger);
|
||||||
|
d.push(g.right_trigger);
|
||||||
|
for v in [g.left_stick_x, g.left_stick_y, g.right_stick_x, g.right_stick_y] {
|
||||||
|
d.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
d.extend_from_slice(&0x009Cu16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 >> 16) as u16).to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0055u16.to_le_bytes());
|
||||||
|
assert_eq!(d.len(), 26);
|
||||||
|
input_message(0x0C, &d)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arrival: controller, type, capabilities, supported buttons (u32, taken as LE like the other gamepad fields:
|
||||||
|
/// PROTOCOL.md gives no byte order, UNKNOWN U22).
|
||||||
|
fn arrival(controller: u8, kind: u8, caps: u8, buttons: u32) -> Vec<u8> {
|
||||||
|
input_message(0x5500_0004, &[&[controller, kind, caps][..], &buttons.to_le_bytes()].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pad(controller: u8, mask: u16, ry: i16) -> GamepadState {
|
||||||
|
GamepadState { controller, active_mask: mask, right_stick_y: ry, ..GamepadState::default() }
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn builder_matches_the_protocol_md_examples() {
|
||||||
|
// Our field-table builder reproduces every example in PROTOCOL.md §4 byte for byte.
|
||||||
|
assert_eq!(rel(-1, 0), hex("06 02 0C 00 00 00 00 08 07 00 00 00 FF FF 00 00"));
|
||||||
|
assert_eq!(abs(1464, 528, 1919, 1079), hex("06 02 12 00 00 00 00 0E 05 00 00 00 05 B8 02 10 00 00 07 7F 04 37"));
|
||||||
|
assert_eq!(button(true, 1), hex("06 02 09 00 00 00 00 05 08 00 00 00 01"));
|
||||||
|
assert_eq!(key(true, 0, 0x80A4, 0x04), hex("06 02 0E 00 00 00 00 0A 03 00 00 00 00 A4 80 04 00 00"));
|
||||||
|
assert_eq!(scroll(-120), hex("06 02 0E 00 00 00 00 0A 0A 00 00 00 FF 88 FF 88 00 00"));
|
||||||
|
assert_eq!(hscroll(30), hex("06 02 0A 00 00 00 00 06 01 00 00 55 00 1E"));
|
||||||
|
assert_eq!(
|
||||||
|
gamepad(&pad(0, 1, -104)),
|
||||||
|
hex(
|
||||||
|
"06 02 22 00 00 00 00 1E 0C 00 00 00 1A 00 00 00 01 00 14 00 00 00 00 00 00 00 00 00 00 00 98 FF 9C 00 00 00 55 00"
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn vectors() -> Vec<(InputEvent, Vec<u8>)> {
|
||||||
|
let full = GamepadState {
|
||||||
|
controller: 15,
|
||||||
|
active_mask: 0x8001,
|
||||||
|
buttons: ButtonFlags(
|
||||||
|
ButtonFlags::A | ButtonFlags::DPAD_UP | ButtonFlags::HOME | ButtonFlags::PADDLE1 | ButtonFlags::MISC,
|
||||||
|
),
|
||||||
|
left_trigger: 0x80,
|
||||||
|
right_trigger: 0xFF,
|
||||||
|
left_stick_x: i16::MIN,
|
||||||
|
left_stick_y: i16::MAX,
|
||||||
|
right_stick_x: -1,
|
||||||
|
right_stick_y: 1,
|
||||||
|
};
|
||||||
|
vec![
|
||||||
|
(InputEvent::MouseMoveRel { dx: -1, dy: 0 }, rel(-1, 0)),
|
||||||
|
(InputEvent::MouseMoveRel { dx: i16::MIN, dy: i16::MAX }, rel(i16::MIN, i16::MAX)),
|
||||||
|
(InputEvent::MouseMoveAbs { x: 1464, y: 528, width: 1919, height: 1079 }, abs(1464, 528, 1919, 1079)),
|
||||||
|
(InputEvent::MouseMoveAbs { x: -5, y: 0, width: 0xFFFF, height: 1 }, abs(-5, 0, 0xFFFF, 1)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Left }, button(true, 1)),
|
||||||
|
(InputEvent::MouseButton { pressed: false, button: MouseButton::Left }, button(false, 1)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Middle }, button(true, 2)),
|
||||||
|
(InputEvent::MouseButton { pressed: false, button: MouseButton::Right }, button(false, 3)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Side }, button(true, 4)),
|
||||||
|
(InputEvent::MouseButton { pressed: true, button: MouseButton::Extra }, button(true, 5)),
|
||||||
|
(InputEvent::Key { pressed: true, flags: 0, key_code: 0x80A4, modifiers: 0x04 }, key(true, 0, 0x80A4, 0x04)),
|
||||||
|
(InputEvent::Key { pressed: false, flags: 0, key_code: 0x0041, modifiers: 0 }, key(false, 0, 0x0041, 0)),
|
||||||
|
(
|
||||||
|
InputEvent::Key { pressed: true, flags: 0xFF, key_code: 0xFFFF, modifiers: 0xFF },
|
||||||
|
key(true, 0xFF, 0xFFFF, 0xFF),
|
||||||
|
),
|
||||||
|
(InputEvent::Scroll { amount: -120 }, scroll(-120)),
|
||||||
|
(InputEvent::Scroll { amount: 120 }, scroll(120)),
|
||||||
|
(InputEvent::HScroll { amount: 30 }, hscroll(30)),
|
||||||
|
(InputEvent::HScroll { amount: -32768 }, hscroll(-32768)),
|
||||||
|
(InputEvent::Gamepad(pad(0, 1, -104)), gamepad(&pad(0, 1, -104))),
|
||||||
|
(InputEvent::Gamepad(pad(1, 0, 0)), gamepad(&pad(1, 0, 0))),
|
||||||
|
(InputEvent::Gamepad(full), gamepad(&full)),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 2,
|
||||||
|
kind: ControllerKind::PlayStation,
|
||||||
|
capabilities: ControllerCapabilities(0xFF),
|
||||||
|
supported_buttons: ButtonFlags(0x003F_FFFF),
|
||||||
|
},
|
||||||
|
arrival(2, 2, 0xFF, 0x003F_FFFF),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 0,
|
||||||
|
kind: ControllerKind::Unknown,
|
||||||
|
capabilities: ControllerCapabilities(ControllerCapabilities::RUMBLE),
|
||||||
|
supported_buttons: ButtonFlags(0),
|
||||||
|
},
|
||||||
|
arrival(0, 0, 0x02, 0),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 15,
|
||||||
|
kind: ControllerKind::Nintendo,
|
||||||
|
capabilities: ControllerCapabilities(0),
|
||||||
|
supported_buttons: ButtonFlags(ButtonFlags::A),
|
||||||
|
},
|
||||||
|
arrival(15, 3, 0, 0x1000),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 3,
|
||||||
|
kind: ControllerKind::Xbox,
|
||||||
|
capabilities: ControllerCapabilities(0x23),
|
||||||
|
supported_buttons: ButtonFlags(0xFFFF),
|
||||||
|
},
|
||||||
|
arrival(3, 1, 0x23, 0xFFFF),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_then_parse_then_equal() {
|
||||||
|
for (event, bytes) in vectors() {
|
||||||
|
assert_eq!(encode_input(&event).unwrap(), bytes, "encode {event:?}");
|
||||||
|
assert_eq!(parse_input(&bytes).unwrap(), event, "parse {event:?}");
|
||||||
|
assert_eq!(parse_input(&encode_input(&event).unwrap()).unwrap(), event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn input_type_codes() {
|
||||||
|
for (code, t) in [
|
||||||
|
(0x03, InputType::KeyDown),
|
||||||
|
(0x04, InputType::KeyUp),
|
||||||
|
(0x05, InputType::MouseMoveAbs),
|
||||||
|
(0x07, InputType::MouseMoveRel),
|
||||||
|
(0x08, InputType::MouseButtonDown),
|
||||||
|
(0x09, InputType::MouseButtonUp),
|
||||||
|
(0x0A, InputType::MouseScroll),
|
||||||
|
(0x0C, InputType::ControllerMulti),
|
||||||
|
(0x0D, InputType::Haptics),
|
||||||
|
(0x17, InputType::Utf8Text),
|
||||||
|
(0x5500_0001, InputType::MouseHScroll),
|
||||||
|
(0x5500_0002, InputType::Touch),
|
||||||
|
(0x5500_0003, InputType::Pen),
|
||||||
|
(0x5500_0004, InputType::ControllerArrival),
|
||||||
|
(0x5500_0005, InputType::ControllerTouch),
|
||||||
|
(0x5500_0006, InputType::ControllerMotion),
|
||||||
|
(0x5500_0007, InputType::ControllerBattery),
|
||||||
|
] {
|
||||||
|
assert_eq!(InputType::try_from(code), Ok(t), "{code:#x}");
|
||||||
|
}
|
||||||
|
for code in [0u32, 1, 2, 6, 0x0B, 0x0E, 0x16, 0x18, 0x5500_0000, 0x5500_0008, 0x0100_0007, u32::MAX] {
|
||||||
|
assert_err!(InputType::try_from(code), Error::UnexpectedValue { .. }, "{code:#x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_and_unsupported_types() {
|
||||||
|
for code in [0u32, 1, 6, 0x5500_0008, 0x0700_0000, u32::MAX] {
|
||||||
|
assert_err!(parse_input(&input_message(code, &[0; 4])), Error::UnexpectedValue { .. }, "type {code:#x}");
|
||||||
|
}
|
||||||
|
// Known types whose layout is UNKNOWN U21.
|
||||||
|
for code in [0x0D, 0x17, 0x5500_0002, 0x5500_0003, 0x5500_0005, 0x5500_0006, 0x5500_0007] {
|
||||||
|
assert_err!(parse_input(&input_message(code, &[0; 8])), Error::Unsupported { .. }, "type {code:#x}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_data_lengths() {
|
||||||
|
// (type, correct data length)
|
||||||
|
for (code, len) in [
|
||||||
|
(0x07u32, 4usize),
|
||||||
|
(0x05, 10),
|
||||||
|
(0x08, 1),
|
||||||
|
(0x09, 1),
|
||||||
|
(0x03, 6),
|
||||||
|
(0x04, 6),
|
||||||
|
(0x0A, 6),
|
||||||
|
(0x5500_0001, 2),
|
||||||
|
(0x0C, 26),
|
||||||
|
(0x5500_0004, 7),
|
||||||
|
] {
|
||||||
|
for wrong in [0, len - 1, len + 1, len + 16] {
|
||||||
|
let mut data = vec![0u8; wrong];
|
||||||
|
if code == 0x08 || code == 0x09 {
|
||||||
|
data.fill(1); // a valid button number, so only the length is wrong
|
||||||
|
}
|
||||||
|
assert_err!(
|
||||||
|
parse_input(&input_message(code, &data)),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"type {code:#x} with {wrong} bytes (wants {len})"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lying_length_and_size_fields() {
|
||||||
|
let good = rel(5, 5);
|
||||||
|
let cases: Vec<(Vec<u8>, &str)> = vec![
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[2] += 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"length over",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[2] -= 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"length under",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[2..4].copy_from_slice(&0xFFFFu16.to_le_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"length 65535",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[7] += 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size over",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[7] -= 1;
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size under",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[4..8].copy_from_slice(&u32::MAX.to_be_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size u32::MAX",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[4..8].copy_from_slice(&8u32.to_le_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"size written little-endian",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[0..2].copy_from_slice(&0x0207u16.to_le_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"not INPUT_DATA",
|
||||||
|
),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut m = good.clone();
|
||||||
|
m[0..2].copy_from_slice(&0x0206u16.to_be_bytes());
|
||||||
|
m
|
||||||
|
},
|
||||||
|
"message type big-endian",
|
||||||
|
),
|
||||||
|
([good.clone(), vec![0]].concat(), "trailing byte"),
|
||||||
|
];
|
||||||
|
for (m, why) in cases {
|
||||||
|
assert_err!(parse_input(&m), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hostile_sizes() {
|
||||||
|
assert_err!(parse_input(&[]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_input(&[0x06]), Error::Truncated { .. });
|
||||||
|
assert_err!(parse_input(&rel(1, 1)[..INPUT_HEADER_LEN - 1]), Error::Truncated { .. });
|
||||||
|
assert_err!(
|
||||||
|
parse_input(&input_message(0x07, &[])[..INPUT_HEADER_LEN]),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"header only: no data"
|
||||||
|
);
|
||||||
|
// max - 1, max, max + 1, huge: valid framing, data too long for any known type.
|
||||||
|
for len in [MAX_INPUT_MESSAGE_BYTES - 1, MAX_INPUT_MESSAGE_BYTES] {
|
||||||
|
let m = input_message(0x07, &vec![0; len - INPUT_HEADER_LEN]);
|
||||||
|
assert_eq!(m.len(), len);
|
||||||
|
assert_err!(parse_input(&m), Error::Malformed { .. }, "{len}");
|
||||||
|
}
|
||||||
|
let m = input_message(0x07, &vec![0; MAX_INPUT_MESSAGE_BYTES + 1 - INPUT_HEADER_LEN]);
|
||||||
|
assert_too_large!(parse_input(&m), MAX_INPUT_MESSAGE_BYTES, MAX_INPUT_MESSAGE_BYTES + 1);
|
||||||
|
assert_too_large!(parse_input(&vec![0; 1 << 20]), MAX_INPUT_MESSAGE_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_field_values() {
|
||||||
|
for b in [0u8, 6, 0xFF] {
|
||||||
|
assert_err!(parse_input(&button(true, b)), Error::UnexpectedValue { .. }, "button {b}");
|
||||||
|
}
|
||||||
|
let mut g = gamepad(&pad(16, 1, 0));
|
||||||
|
assert_err!(parse_input(&g), Error::UnexpectedValue { .. }, "controller 16");
|
||||||
|
for (offset, why) in [(12usize, "0x1A"), (18, "0x14"), (32, "0x9C"), (36, "0x55")] {
|
||||||
|
g = gamepad(&pad(0, 1, 0));
|
||||||
|
g[offset] ^= 0x01;
|
||||||
|
assert_err!(parse_input(&g), Error::Malformed { .. }, "constant {why} changed");
|
||||||
|
}
|
||||||
|
assert_err!(parse_input(&arrival(16, 1, 0, 0)), Error::UnexpectedValue { .. }, "arrival controller 16");
|
||||||
|
assert_err!(parse_input(&arrival(0, 4, 0, 0)), Error::UnexpectedValue { .. }, "controller kind 4");
|
||||||
|
|
||||||
|
for e in [
|
||||||
|
InputEvent::Gamepad(pad(16, 1, 0)),
|
||||||
|
InputEvent::Gamepad(pad(255, 1, 0)),
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller: 16,
|
||||||
|
kind: ControllerKind::Xbox,
|
||||||
|
capabilities: ControllerCapabilities(0),
|
||||||
|
supported_buttons: ButtonFlags(0),
|
||||||
|
},
|
||||||
|
] {
|
||||||
|
assert_err!(encode_input(&e), Error::UnexpectedValue { .. }, "{e:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn event() -> impl Strategy<Value = InputEvent> {
|
||||||
|
let button = prop_oneof![
|
||||||
|
Just(MouseButton::Left),
|
||||||
|
Just(MouseButton::Middle),
|
||||||
|
Just(MouseButton::Right),
|
||||||
|
Just(MouseButton::Side),
|
||||||
|
Just(MouseButton::Extra)
|
||||||
|
];
|
||||||
|
let kind = prop_oneof![
|
||||||
|
Just(ControllerKind::Unknown),
|
||||||
|
Just(ControllerKind::Xbox),
|
||||||
|
Just(ControllerKind::PlayStation),
|
||||||
|
Just(ControllerKind::Nintendo)
|
||||||
|
];
|
||||||
|
let gamepad = (0u8..=15, any::<u16>(), any::<u32>(), any::<u8>(), any::<u8>(), any::<[i16; 4]>()).prop_map(
|
||||||
|
|(c, m, b, l, r, s)| GamepadState {
|
||||||
|
controller: c,
|
||||||
|
active_mask: m,
|
||||||
|
buttons: ButtonFlags(b),
|
||||||
|
left_trigger: l,
|
||||||
|
right_trigger: r,
|
||||||
|
left_stick_x: s[0],
|
||||||
|
left_stick_y: s[1],
|
||||||
|
right_stick_x: s[2],
|
||||||
|
right_stick_y: s[3],
|
||||||
|
},
|
||||||
|
);
|
||||||
|
prop_oneof![
|
||||||
|
(any::<i16>(), any::<i16>()).prop_map(|(dx, dy)| InputEvent::MouseMoveRel { dx, dy }),
|
||||||
|
(any::<i16>(), any::<i16>(), any::<u16>(), any::<u16>())
|
||||||
|
.prop_map(|(x, y, width, height)| InputEvent::MouseMoveAbs { x, y, width, height }),
|
||||||
|
(any::<bool>(), button).prop_map(|(pressed, button)| InputEvent::MouseButton { pressed, button }),
|
||||||
|
(any::<bool>(), any::<u8>(), any::<u16>(), any::<u8>())
|
||||||
|
.prop_map(|(pressed, flags, key_code, modifiers)| InputEvent::Key { pressed, flags, key_code, modifiers }),
|
||||||
|
any::<i16>().prop_map(|amount| InputEvent::Scroll { amount }),
|
||||||
|
any::<i16>().prop_map(|amount| InputEvent::HScroll { amount }),
|
||||||
|
gamepad.prop_map(InputEvent::Gamepad),
|
||||||
|
(0u8..=15, kind, any::<u8>(), any::<u32>()).prop_map(|(controller, kind, c, b)| {
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller,
|
||||||
|
kind,
|
||||||
|
capabilities: ControllerCapabilities(c),
|
||||||
|
supported_buttons: ButtonFlags(b),
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 1024, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn any_event_round_trips(e in event()) {
|
||||||
|
let bytes = encode_input(&e).map_err(|err| TestCaseError::fail(format!("{err:?}")))?;
|
||||||
|
prop_assert!(bytes.len() <= MAX_INPUT_MESSAGE_BYTES);
|
||||||
|
prop_assert_eq!(&bytes[..2], &[0x06, 0x02]);
|
||||||
|
prop_assert_eq!(u16::from_le_bytes([bytes[2], bytes[3]]) as usize, bytes.len() - 4);
|
||||||
|
prop_assert_eq!(u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]) as usize, bytes.len() - 8);
|
||||||
|
prop_assert_eq!(parse_input(&bytes), Ok(e));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary bytes never panic; whatever parses re-encodes to an equal event.
|
||||||
|
#[test]
|
||||||
|
fn parse_is_stable(data in proptest::collection::vec(any::<u8>(), 0..64)) {
|
||||||
|
let parsed = parse_input(&data);
|
||||||
|
prop_assert!(common::implemented(&parsed));
|
||||||
|
if let Ok(e) = parsed {
|
||||||
|
let again = encode_input(&e).map_err(|err| TestCaseError::fail(format!("{err:?}")))?;
|
||||||
|
prop_assert_eq!(parse_input(&again), Ok(e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Valid framing around random data of every known type never panics.
|
||||||
|
#[test]
|
||||||
|
fn framed_random_data(code in prop_oneof![Just(3u32), Just(4), Just(5), Just(7), Just(8), Just(9), Just(0x0A), Just(0x0C), Just(0x5500_0001), Just(0x5500_0004)], data in proptest::collection::vec(any::<u8>(), 0..40)) {
|
||||||
|
prop_assert!(common::implemented(&parse_input(&input_message(code, &data))));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,389 @@
|
|||||||
|
//! Packet parsers and ciphers of the media streams (`docs/PROTOCOL.md` 5.2, 6.2, 6.3, 7): RTP header, video packet
|
||||||
|
//! and frame header, audio packet, video AES-GCM (.NET vectors) and audio AES-CBC (openssl vectors). Also checks the
|
||||||
|
//! RustCrypto test oracles in `common` against the same independent vectors.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{fec_info, video_packet_bytes};
|
||||||
|
use domistream::audio::packet::{AUDIO_FEC_HEADER_LEN, MAX_AUDIO_PACKET_BYTES};
|
||||||
|
use domistream::audio::{AudioCipher, AudioPacket, parse_audio_packet};
|
||||||
|
use domistream::rtp::{RTP_HEADER_LEN, parse_rtp_header};
|
||||||
|
use domistream::video::packet::{FRAME_HEADER_LEN, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header};
|
||||||
|
use domistream::video::{ENCRYPTION_PREFIX_LEN, FrameType, VideoCipher, parse_video_packet};
|
||||||
|
use domistream::{Error, SessionKeys};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
// ================================================================================================ RTP
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rtp_header() {
|
||||||
|
let h = parse_rtp_header(&[0x80, 0x61, 0x12, 0x34, 0x00, 0x00, 0x03, 0xE8, 0xCA, 0xFE, 0xBA, 0xBE]).unwrap();
|
||||||
|
assert_eq!((h.flags, h.payload_type, h.sequence, h.timestamp, h.ssrc), (0x80, 97, 0x1234, 1000, 0xCAFE_BABE));
|
||||||
|
let h = parse_rtp_header(&[0x90, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0, 0, 0, 0, 1, 2, 3]).unwrap();
|
||||||
|
assert_eq!((h.flags, h.sequence, h.timestamp), (0x90, 0xFFFF, u32::MAX), "the rest is ignored");
|
||||||
|
for len in [0usize, 1, RTP_HEADER_LEN - 1] {
|
||||||
|
match parse_rtp_header(&vec![0x80; len]) {
|
||||||
|
Err(Error::Truncated { needed, actual, .. }) => assert_eq!((needed, actual), (RTP_HEADER_LEN, len)),
|
||||||
|
other => panic!("{len} bytes: {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for first in [0x00u8, 0x40, 0xC0, 0x3F] {
|
||||||
|
let mut p = vec![first, 97];
|
||||||
|
p.resize(12, 0);
|
||||||
|
assert_err!(parse_rtp_header(&p), Error::UnexpectedValue { .. }, "version bits {first:#x}");
|
||||||
|
}
|
||||||
|
assert!(parse_rtp_header(&vec![0x80; 1 << 20]).is_ok(), "only the first 12 bytes matter");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ video packet
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_packet_fields() {
|
||||||
|
let payload: Vec<u8> = (0..48u8).collect();
|
||||||
|
let p = video_packet_bytes(0xABCD, 0x0102_0304, 77, 0x05, (1 << 4) | (2 << 6), fec_info(50, 3, 4), &payload);
|
||||||
|
let v = parse_video_packet(&p).unwrap();
|
||||||
|
assert_eq!(v.rtp.sequence, 0xABCD);
|
||||||
|
assert_eq!(v.rtp.timestamp, 0x0102_0304);
|
||||||
|
assert_eq!(v.rtp.flags, 0x90);
|
||||||
|
assert_eq!(v.nv.stream_packet_index, 0xABCD << 8);
|
||||||
|
assert_eq!(v.nv.frame_index, 77);
|
||||||
|
assert_eq!(v.nv.flags.0, 0x05);
|
||||||
|
assert_eq!(v.nv.multi_fec_flags, 0x10);
|
||||||
|
assert_eq!(v.nv.fec.shard_index, 3);
|
||||||
|
assert_eq!(v.nv.fec.data_shards, 4);
|
||||||
|
assert_eq!(v.nv.fec.fec_percentage, 50);
|
||||||
|
assert_eq!(v.nv.fec.block_index, 1);
|
||||||
|
assert_eq!(v.nv.fec.last_block_index, 2);
|
||||||
|
assert_eq!(v.payload, payload.as_slice());
|
||||||
|
// Parity shard 5 of 4 + 2 is in range.
|
||||||
|
assert!(parse_video_packet(&video_packet_bytes(1, 0, 0, 0, 0, fec_info(50, 5, 4), &payload)).is_ok());
|
||||||
|
// Bits 0-3 of fecInfo are not part of any field.
|
||||||
|
let p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(50, 0, 4) | 0xF, &payload);
|
||||||
|
let v = parse_video_packet(&p).unwrap();
|
||||||
|
assert_eq!((v.nv.fec.shard_index, v.nv.fec.data_shards, v.nv.fec.fec_percentage), (0, 4, 50));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_packet_hostile_sizes() {
|
||||||
|
let at = |len: usize| {
|
||||||
|
let mut p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(0, 0, 1), &[]);
|
||||||
|
p.resize(len, 0xEE);
|
||||||
|
p
|
||||||
|
};
|
||||||
|
for len in [0usize, 1, 16, PAYLOAD_OFFSET - 1] {
|
||||||
|
assert_err!(parse_video_packet(&at(len)[..len]), Error::Truncated { .. }, "{len}");
|
||||||
|
}
|
||||||
|
assert!(parse_video_packet(&at(PAYLOAD_OFFSET)).unwrap().payload.is_empty());
|
||||||
|
for len in [MAX_VIDEO_PACKET_BYTES - 1, MAX_VIDEO_PACKET_BYTES] {
|
||||||
|
assert_eq!(parse_video_packet(&at(len)).unwrap().payload.len(), len - PAYLOAD_OFFSET);
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
parse_video_packet(&at(MAX_VIDEO_PACKET_BYTES + 1)),
|
||||||
|
MAX_VIDEO_PACKET_BYTES,
|
||||||
|
MAX_VIDEO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(parse_video_packet(&at(1 << 20)), MAX_VIDEO_PACKET_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_packet_inconsistent_fec_fields() {
|
||||||
|
let pay = [0u8; 16];
|
||||||
|
for (blocks, info, why) in [
|
||||||
|
(0u8, fec_info(50, 0, 0), "zero data shards"),
|
||||||
|
(0, fec_info(50, 6, 4), "shard index past data + parity (4 + 2)"),
|
||||||
|
(0, fec_info(0, 4, 4), "parity index with 0 % FEC"),
|
||||||
|
(0, fec_info(50, 1023, 4), "shard index 1023"),
|
||||||
|
(0, fec_info(100, 0, 200), "200 + 200 shards > 255"),
|
||||||
|
(0, fec_info(0, 0, 1023), "1023 data shards > 255"),
|
||||||
|
((2 << 4) | (1 << 6), fec_info(50, 0, 4), "block index past last block index"),
|
||||||
|
(3 << 4, fec_info(50, 0, 4), "block 3 of block 0"),
|
||||||
|
] {
|
||||||
|
assert_err!(
|
||||||
|
parse_video_packet(&video_packet_bytes(1, 0, 0, 1, blocks, info, &pay)),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{why}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut p = video_packet_bytes(1, 0, 0, 1, 0, fec_info(0, 0, 1), &pay);
|
||||||
|
p[0] = 0x50;
|
||||||
|
assert_err!(parse_video_packet(&p), Error::UnexpectedValue { .. }, "RTP version 1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_header() {
|
||||||
|
// Moonshine-style fields.
|
||||||
|
let h = parse_frame_header(&[0x01, 0x34, 0x12, 0x02, 0x10, 0x00, 0x00, 0x00, 0xAA]).unwrap();
|
||||||
|
assert_eq!(h.raw, [0x01, 0x34, 0x12, 0x02, 0x10, 0x00, 0x00, 0x00]);
|
||||||
|
assert_eq!(
|
||||||
|
(h.header_type, h.processing_latency, h.frame_type, h.last_payload_len),
|
||||||
|
(0x01, 0x1234, FrameType::Key, 16)
|
||||||
|
);
|
||||||
|
for (b, t) in [
|
||||||
|
(1u8, FrameType::Predicted),
|
||||||
|
(2, FrameType::Key),
|
||||||
|
(5, FrameType::Recovery),
|
||||||
|
(0, FrameType::Other(0)),
|
||||||
|
(0x68, FrameType::Other(0x68)),
|
||||||
|
] {
|
||||||
|
assert_eq!(parse_frame_header(&[1, 0, 0, b, 0, 0, 0, 0]).unwrap().frame_type, t);
|
||||||
|
}
|
||||||
|
// Wolf's constant (UNKNOWN U13): parsed, raw kept.
|
||||||
|
let wolf = [0x01, 0x37, 0x63, 0x68, 0x61, 0x72, 0x73, 0x73];
|
||||||
|
let h = parse_frame_header(&wolf).unwrap();
|
||||||
|
assert_eq!(h.raw, wolf);
|
||||||
|
assert_eq!(h.last_payload_len, 0x7373_7261);
|
||||||
|
for len in 0..FRAME_HEADER_LEN {
|
||||||
|
assert_err!(parse_frame_header(&wolf[..len]), Error::Truncated { .. }, "{len}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ audio packet
|
||||||
|
|
||||||
|
fn audio_data(seq: u16, payload: &[u8]) -> Vec<u8> {
|
||||||
|
let mut p = vec![0x80, 97];
|
||||||
|
p.extend_from_slice(&seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&1000u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(payload);
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
fn audio_parity(shard: u8, pt: u8, base_seq: u16, base_ts: u32, parity: &[u8]) -> Vec<u8> {
|
||||||
|
let mut p = vec![0x80, 127];
|
||||||
|
p.extend_from_slice(&base_seq.wrapping_add(4).to_be_bytes());
|
||||||
|
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(&[shard, pt]);
|
||||||
|
p.extend_from_slice(&base_seq.to_be_bytes());
|
||||||
|
p.extend_from_slice(&base_ts.to_be_bytes());
|
||||||
|
p.extend_from_slice(&0x1122_3344u32.to_be_bytes());
|
||||||
|
p.extend_from_slice(parity);
|
||||||
|
p
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_packets() {
|
||||||
|
match parse_audio_packet(&audio_data(5, &[1, 2, 3])).unwrap() {
|
||||||
|
AudioPacket::Data { rtp, payload } => {
|
||||||
|
assert_eq!((rtp.payload_type, rtp.sequence, rtp.timestamp), (97, 5, 1000));
|
||||||
|
assert_eq!(payload, &[1, 2, 3]);
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
match parse_audio_packet(&audio_parity(1, 97, 0xFFFC, 0xDEAD_BEEF, &[9; 32])).unwrap() {
|
||||||
|
AudioPacket::Parity { rtp, fec, parity } => {
|
||||||
|
assert_eq!(rtp.payload_type, 127);
|
||||||
|
assert_eq!(
|
||||||
|
(fec.shard_index, fec.payload_type, fec.base_sequence, fec.base_timestamp, fec.ssrc),
|
||||||
|
(1, 97, 0xFFFC, 0xDEAD_BEEF, 0x1122_3344)
|
||||||
|
);
|
||||||
|
assert_eq!(parity, &[9; 32]);
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_packet_hostile() {
|
||||||
|
for pt in [0u8, 96, 98, 126] {
|
||||||
|
let mut p = audio_data(1, &[1]);
|
||||||
|
p[1] = pt;
|
||||||
|
assert_err!(parse_audio_packet(&p), Error::UnexpectedValue { .. }, "payload type {pt}");
|
||||||
|
}
|
||||||
|
assert_err!(
|
||||||
|
parse_audio_packet(&audio_parity(2, 97, 0, 0, &[1; 16])),
|
||||||
|
Error::UnexpectedValue { .. },
|
||||||
|
"parity shard 2"
|
||||||
|
);
|
||||||
|
assert_err!(parse_audio_packet(&audio_parity(0xFF, 97, 0, 0, &[1; 16])), Error::UnexpectedValue { .. });
|
||||||
|
for len in [0usize, 1, RTP_HEADER_LEN - 1, RTP_HEADER_LEN] {
|
||||||
|
assert_err!(parse_audio_packet(&audio_data(1, &[])[..len]), Error::Truncated { .. }, "data, {len} bytes");
|
||||||
|
}
|
||||||
|
let par = audio_parity(0, 97, 0, 0, &[]);
|
||||||
|
for len in [
|
||||||
|
RTP_HEADER_LEN,
|
||||||
|
RTP_HEADER_LEN + 1,
|
||||||
|
RTP_HEADER_LEN + AUDIO_FEC_HEADER_LEN - 1,
|
||||||
|
RTP_HEADER_LEN + AUDIO_FEC_HEADER_LEN,
|
||||||
|
] {
|
||||||
|
assert_err!(parse_audio_packet(&par[..len]), Error::Truncated { .. }, "parity, {len} bytes");
|
||||||
|
}
|
||||||
|
let at = |len: usize| audio_data(1, &vec![7; len - RTP_HEADER_LEN]);
|
||||||
|
for len in [MAX_AUDIO_PACKET_BYTES - 1, MAX_AUDIO_PACKET_BYTES] {
|
||||||
|
assert!(parse_audio_packet(&at(len)).is_ok(), "{len}");
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
parse_audio_packet(&at(MAX_AUDIO_PACKET_BYTES + 1)),
|
||||||
|
MAX_AUDIO_PACKET_BYTES,
|
||||||
|
MAX_AUDIO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(parse_audio_packet(&at(1 << 20)), MAX_AUDIO_PACKET_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ video cipher
|
||||||
|
|
||||||
|
const VIDEO: [&str; 4] = ["v_0", "v_1", "v_big_counter", "v_1040"];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_decrypt_matches_dotnet_vectors() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let c = VideoCipher::new(v.arr16("key"));
|
||||||
|
for name in VIDEO {
|
||||||
|
assert_eq!(
|
||||||
|
c.decrypt(&v.bytes(&format!("{name}_packet"))).unwrap(),
|
||||||
|
v.bytes(&format!("{name}_plain")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_oracle_matches_dotnet_vectors() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let key = v.arr16("key");
|
||||||
|
for (name, counter, frame) in
|
||||||
|
[("v_0", 0u64, 0u32), ("v_1", 1, 0), ("v_big_counter", 0x0102_0304_0506_0708, 0x1122_3344), ("v_1040", 7, 3)]
|
||||||
|
{
|
||||||
|
assert_eq!(
|
||||||
|
common::video_encrypt(&key, counter, frame, &v.bytes(&format!("{name}_plain"))),
|
||||||
|
v.bytes(&format!("{name}_packet")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_decrypt_refuses() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let c = VideoCipher::new(v.arr16("key"));
|
||||||
|
let p = v.bytes("v_1_packet");
|
||||||
|
for i in (0..11).chain(16..p.len()) {
|
||||||
|
let mut t = p.clone();
|
||||||
|
t[i] ^= 0x01;
|
||||||
|
assert_err!(c.decrypt(&t), Error::Crypto, "byte {i} flipped (IV, tag or ciphertext)");
|
||||||
|
}
|
||||||
|
let mut t = p.clone();
|
||||||
|
t[11] = b'v';
|
||||||
|
assert_err!(c.decrypt(&t), Error::Malformed { .. }, "IV byte 11 must be 'V'");
|
||||||
|
for len in [0usize, 1, ENCRYPTION_PREFIX_LEN - 1] {
|
||||||
|
assert_err!(c.decrypt(&p[..len]), Error::Truncated { .. }, "{len}");
|
||||||
|
}
|
||||||
|
let mut key = v.arr16("key");
|
||||||
|
key[15] ^= 0x80;
|
||||||
|
assert_err!(VideoCipher::new(key).decrypt(&p), Error::Crypto);
|
||||||
|
let mut big = p.clone();
|
||||||
|
big.resize(MAX_VIDEO_PACKET_BYTES + 1, 0);
|
||||||
|
assert_too_large!(c.decrypt(&big), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ audio cipher
|
||||||
|
|
||||||
|
const AUDIO: [&str; 6] = ["a_0", "a_1", "a_ffff", "a_wrap", "a_exact_block", "a_one_byte"];
|
||||||
|
|
||||||
|
fn audio_cipher(v: &common::Vectors, name: &str) -> (AudioCipher, u16) {
|
||||||
|
let keys = SessionKeys { rikey: v.arr16("key"), rikeyid: v.u32_hex(&format!("{name}_rikeyid")) };
|
||||||
|
(AudioCipher::new(&keys), u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_iv_and_decrypt_match_openssl_vectors() {
|
||||||
|
let v = common::audio_vectors();
|
||||||
|
for name in AUDIO {
|
||||||
|
let (c, seq) = audio_cipher(&v, name);
|
||||||
|
assert_eq!(
|
||||||
|
c.iv(seq).unwrap().to_vec(),
|
||||||
|
v.bytes(&format!("{name}_iv")),
|
||||||
|
"{name}: IV = BE(rikeyid + seq) || 12 zero, wrapping"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
c.decrypt(seq, &v.bytes(&format!("{name}_cipher"))).unwrap(),
|
||||||
|
v.bytes(&format!("{name}_plain")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_oracle_matches_openssl_vectors() {
|
||||||
|
let v = common::audio_vectors();
|
||||||
|
for name in AUDIO {
|
||||||
|
let rikeyid = v.u32_hex(&format!("{name}_rikeyid"));
|
||||||
|
let seq = u16::from_str_radix(v.str(&format!("{name}_sequence")), 16).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
common::audio_encrypt(&v.arr16("key"), rikeyid, seq, &v.bytes(&format!("{name}_plain"))),
|
||||||
|
v.bytes(&format!("{name}_cipher")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_decrypt_refuses() {
|
||||||
|
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::NoPadding};
|
||||||
|
let v = common::audio_vectors();
|
||||||
|
let (c, seq) = audio_cipher(&v, "a_0");
|
||||||
|
for len in [0usize, 1, 15, 17, 31] {
|
||||||
|
assert_err!(c.decrypt(seq, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
|
||||||
|
}
|
||||||
|
// Blocks whose decryption ends in bad PKCS#7 padding.
|
||||||
|
let iv = c.iv(seq).unwrap();
|
||||||
|
for last in [&[0u8][..], &[17], &[16, 16, 16, 15], &[2, 3]] {
|
||||||
|
let mut block = [0x41u8; 16];
|
||||||
|
block[16 - last.len()..].copy_from_slice(last);
|
||||||
|
let mut buf = block;
|
||||||
|
cbc::Encryptor::<aes::Aes128>::new((&v.arr16("key")).into(), &iv.into())
|
||||||
|
.encrypt_padded::<NoPadding>(&mut buf, 16)
|
||||||
|
.unwrap();
|
||||||
|
assert_err!(c.decrypt(seq, &buf), Error::Crypto, "padding ending {last:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 512, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn media_parsers_never_panic(data in proptest::collection::vec(any::<u8>(), 0..200)) {
|
||||||
|
let rtp = parse_rtp_header(&data);
|
||||||
|
let video = parse_video_packet(&data);
|
||||||
|
let frame = parse_frame_header(&data);
|
||||||
|
let audio = parse_audio_packet(&data);
|
||||||
|
prop_assert!(common::implemented(&rtp) && common::implemented(&video) && common::implemented(&frame) && common::implemented(&audio));
|
||||||
|
if let Ok(h) = rtp {
|
||||||
|
prop_assert!(data.len() >= RTP_HEADER_LEN);
|
||||||
|
prop_assert_eq!(h.flags >> 6, 2);
|
||||||
|
}
|
||||||
|
if let Ok(p) = video {
|
||||||
|
prop_assert_eq!(p.payload.len() + PAYLOAD_OFFSET, data.len());
|
||||||
|
prop_assert!(p.nv.fec.data_shards > 0);
|
||||||
|
prop_assert!(p.nv.fec.block_index <= p.nv.fec.last_block_index);
|
||||||
|
}
|
||||||
|
if let Ok(h) = frame {
|
||||||
|
prop_assert_eq!(&h.raw[..], &data[..FRAME_HEADER_LEN]);
|
||||||
|
}
|
||||||
|
match audio {
|
||||||
|
Ok(AudioPacket::Data { payload, .. }) => prop_assert!(!payload.is_empty()),
|
||||||
|
Ok(AudioPacket::Parity { fec, parity, .. }) => prop_assert!(!parity.is_empty() && fec.shard_index <= 1),
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
|
prop_assert!(common::implemented(&VideoCipher::new([1; 16]).decrypt(&data)));
|
||||||
|
let audio_cipher = AudioCipher::new(&SessionKeys { rikey: [1; 16], rikeyid: 0 });
|
||||||
|
prop_assert!(common::implemented(&audio_cipher.decrypt(0, &data)));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_round_trip_through_the_oracle(rikeyid in any::<u32>(), seq in any::<u16>(), plain in proptest::collection::vec(any::<u8>(), 0..100)) {
|
||||||
|
let key = [0x5Au8; 16];
|
||||||
|
let c = AudioCipher::new(&SessionKeys { rikey: key, rikeyid });
|
||||||
|
let ct = common::audio_encrypt(&key, rikeyid, seq, &plain);
|
||||||
|
prop_assert_eq!(c.decrypt(seq, &ct), Ok(plain));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_round_trip_through_the_oracle(counter in any::<u64>(), frame in any::<u32>(), plain in proptest::collection::vec(any::<u8>(), 32..300)) {
|
||||||
|
let key = [0xA5u8; 16];
|
||||||
|
let p = common::video_encrypt(&key, counter, frame, &plain);
|
||||||
|
prop_assert_eq!(VideoCipher::new(key).decrypt(&p), Ok(plain));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,865 @@
|
|||||||
|
//! Pairing (`docs/PROTOCOL.md` 1.5) against recorded vectors made by independent tools
|
||||||
|
//! (`tools/vectors/gen_vectors.py`: Python hashlib, the OpenSSL CLI). The keys are test-only.
|
||||||
|
//!
|
||||||
|
//! Recorded transcript assumption: the state machine draws its randomness as salt (step 1), then C (step 2), then
|
||||||
|
//! secret_c (step 3), 16 bytes each, and nothing else. [`common::ScriptedRng`] fails loudly if that changes.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use common::{
|
||||||
|
CLIENT_CERT_PEM, CLIENT_KEY_PEM, EC_CERT_PEM, HOST_CERT_PEM, ROGUE_CERT_PEM, ScriptedRng, SeqRng, Vectors, hex,
|
||||||
|
param, parse_query, pem_blocks, to_hex, to_hex_upper, xml_padded_to, xml_root,
|
||||||
|
};
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::http::{HttpRequest, Scheme};
|
||||||
|
use domistream::pairing::crypto;
|
||||||
|
use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES};
|
||||||
|
use domistream::pairing::{
|
||||||
|
ClientIdentity, MAX_PAIR_RESPONSE_BYTES, MAX_SIGNATURE_BYTES, PairingFailure, PairingSession, PairingState,
|
||||||
|
PairingStep, Pin, ServerCert, parse_pair_response,
|
||||||
|
};
|
||||||
|
|
||||||
|
const UID: &str = "0123456789ABCDEF";
|
||||||
|
const DEVICE: &str = "DomiStreamTestTV";
|
||||||
|
|
||||||
|
fn v() -> Vectors {
|
||||||
|
common::pairing_vectors()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client() -> ClientIdentity {
|
||||||
|
let v = v();
|
||||||
|
ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der"))
|
||||||
|
.expect("ClientIdentity::from_der(test-only client)")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rogue() -> ClientIdentity {
|
||||||
|
let v = v();
|
||||||
|
ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &v.bytes("rogue_key_pkcs8_der")).expect("rogue identity")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn pin() -> Pin {
|
||||||
|
Pin::from_digits(v().str("pin")).expect("Pin::from_digits")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rng_a() -> ScriptedRng {
|
||||||
|
let v = v();
|
||||||
|
ScriptedRng::new([v.bytes("salt"), v.bytes("client_challenge"), v.bytes("client_secret")].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rng_b() -> ScriptedRng {
|
||||||
|
let v = v();
|
||||||
|
ScriptedRng::new([v.bytes("salt_b"), v.bytes("client_challenge_b"), v.bytes("client_secret_b")].concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ host answers
|
||||||
|
|
||||||
|
fn answer(paired: bool, element: Option<(&str, &[u8])>) -> Vec<u8> {
|
||||||
|
let mut inner = format!("<paired>{}</paired>", u8::from(paired));
|
||||||
|
if let Some((name, value)) = element {
|
||||||
|
// Upper-case hex: the parser must accept both cases (PROTOCOL.md 1.1).
|
||||||
|
inner.push_str(&format!("<{name}>{}</{name}>", to_hex_upper(value)));
|
||||||
|
}
|
||||||
|
xml_root(200, &inner)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn resp1() -> Vec<u8> {
|
||||||
|
answer(true, Some(("plaincert", HOST_CERT_PEM.as_bytes())))
|
||||||
|
}
|
||||||
|
fn resp2() -> Vec<u8> {
|
||||||
|
answer(true, Some(("challengeresponse", &v().bytes("step2_challengeresponse"))))
|
||||||
|
}
|
||||||
|
fn resp3() -> Vec<u8> {
|
||||||
|
answer(true, Some(("pairingsecret", &v().bytes("step3_pairingsecret"))))
|
||||||
|
}
|
||||||
|
fn resp_ok() -> Vec<u8> {
|
||||||
|
answer(true, None)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The recorded host answers, in order.
|
||||||
|
fn transcript() -> Vec<Vec<u8>> {
|
||||||
|
vec![resp1(), resp2(), resp3(), resp_ok(), resp_ok()]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A session that has been fed the first `steps` recorded answers.
|
||||||
|
fn session_after(steps: usize) -> (PairingSession, ScriptedRng, ClientIdentity) {
|
||||||
|
let id = client();
|
||||||
|
let mut rng = rng_a();
|
||||||
|
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).expect("PairingSession::start");
|
||||||
|
for body in transcript().into_iter().take(steps) {
|
||||||
|
s.handle_response(&id, 200, &body, &mut rng).expect("recorded answer");
|
||||||
|
}
|
||||||
|
(s, rng, id)
|
||||||
|
}
|
||||||
|
|
||||||
|
const STATES: [PairingState; 5] = [
|
||||||
|
PairingState::AwaitServerCert,
|
||||||
|
PairingState::AwaitChallengeResponse,
|
||||||
|
PairingState::AwaitPairingSecret,
|
||||||
|
PairingState::AwaitClientSecretAck,
|
||||||
|
PairingState::AwaitPairChallenge,
|
||||||
|
];
|
||||||
|
|
||||||
|
fn sent(step: PairingStep) -> HttpRequest {
|
||||||
|
match step {
|
||||||
|
PairingStep::Send(r) => r,
|
||||||
|
PairingStep::Paired(p) => panic!("expected a request, pairing already finished: {p:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_param(req: &HttpRequest, name: &str) -> Vec<u8> {
|
||||||
|
let (path, q) = parse_query(&req.path_and_query);
|
||||||
|
assert_eq!(path, "/pair");
|
||||||
|
hex(param(&q, name))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Feeds `body` and checks the session fails into `Failed(reason)`.
|
||||||
|
fn expect_failure(
|
||||||
|
s: &mut PairingSession,
|
||||||
|
id: &ClientIdentity,
|
||||||
|
rng: &mut ScriptedRng,
|
||||||
|
status: u16,
|
||||||
|
body: &[u8],
|
||||||
|
reason: PairingFailure,
|
||||||
|
) {
|
||||||
|
let r = s.handle_response(id, status, body, rng);
|
||||||
|
assert!(r.is_err(), "expected a failure ({reason:?}), got {r:?}");
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(reason), "result was {r:?}");
|
||||||
|
// Failed is terminal.
|
||||||
|
assert_err!(s.handle_response(id, 200, &resp_ok(), rng), Error::State { .. });
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(reason));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ happy path
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recorded_transcript_walks_every_state() {
|
||||||
|
let v = v();
|
||||||
|
let id = client();
|
||||||
|
let mut rng = rng_a();
|
||||||
|
let (mut s, req1) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||||
|
assert_eq!(s.state(), PairingState::AwaitServerCert);
|
||||||
|
|
||||||
|
// Step 1 (HTTP): getservercert, salt, client certificate; blocks on the host, so a long timeout.
|
||||||
|
assert_eq!(req1.scheme, Scheme::Http);
|
||||||
|
assert!(
|
||||||
|
req1.timeout.is_some_and(|t| t >= core::time::Duration::from_secs(30)),
|
||||||
|
"step 1 timeout {:?}",
|
||||||
|
req1.timeout
|
||||||
|
);
|
||||||
|
let (path, q) = parse_query(&req1.path_and_query);
|
||||||
|
assert_eq!(path, "/pair");
|
||||||
|
assert_eq!(param(&q, "uniqueid"), UID);
|
||||||
|
assert_eq!(param(&q, "phrase"), "getservercert");
|
||||||
|
assert_eq!(hex(param(&q, "salt")), v.bytes("salt"));
|
||||||
|
let pem = String::from_utf8(hex(param(&q, "clientcert"))).expect("clientcert is PEM text");
|
||||||
|
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "clientcert is the identity's cert");
|
||||||
|
|
||||||
|
// Step 2: clientchallenge = E_K(C).
|
||||||
|
let req2 = sent(s.handle_response(&id, 200, &resp1(), &mut rng).unwrap());
|
||||||
|
assert_eq!(s.state(), PairingState::AwaitChallengeResponse);
|
||||||
|
assert_eq!(req2.scheme, Scheme::Http);
|
||||||
|
assert_eq!(hex_param(&req2, "clientchallenge"), v.bytes("step2_clientchallenge"));
|
||||||
|
assert_eq!(param(&parse_query(&req2.path_and_query).1, "uniqueid"), UID);
|
||||||
|
|
||||||
|
// Step 3: serverchallengeresp = E_K(H_c).
|
||||||
|
let req3 = sent(s.handle_response(&id, 200, &resp2(), &mut rng).unwrap());
|
||||||
|
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
|
||||||
|
assert_eq!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
|
||||||
|
|
||||||
|
// Step 4: clientpairingsecret = secret_c || Sign_client(secret_c), after checking the host's proof.
|
||||||
|
let req4 = sent(s.handle_response(&id, 200, &resp3(), &mut rng).unwrap());
|
||||||
|
assert_eq!(s.state(), PairingState::AwaitClientSecretAck);
|
||||||
|
assert_eq!(hex_param(&req4, "clientpairingsecret"), v.bytes("step4_clientpairingsecret"));
|
||||||
|
|
||||||
|
// Step 5 (HTTPS): pairchallenge.
|
||||||
|
let req5 = sent(s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap());
|
||||||
|
assert_eq!(s.state(), PairingState::AwaitPairChallenge);
|
||||||
|
assert_eq!(req5.scheme, Scheme::Https, "step 5 runs over HTTPS with the client certificate");
|
||||||
|
assert_eq!(param(&parse_query(&req5.path_and_query).1, "phrase"), "pairchallenge");
|
||||||
|
|
||||||
|
match s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap() {
|
||||||
|
PairingStep::Paired(host) => assert_eq!(host.server_cert.der(), v.bytes("host_cert_der").as_slice()),
|
||||||
|
PairingStep::Send(r) => panic!("expected Paired, got another request {r:?}"),
|
||||||
|
}
|
||||||
|
assert_eq!(s.state(), PairingState::Paired);
|
||||||
|
assert_eq!(rng.drawn(), 48, "salt + C + secret_c");
|
||||||
|
assert_err!(s.handle_response(&id, 200, &resp_ok(), &mut rng), Error::State { .. });
|
||||||
|
assert_eq!(s.state(), PairingState::Paired);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lower_case_hex_answers_work_too() {
|
||||||
|
let id = client();
|
||||||
|
let mut rng = rng_a();
|
||||||
|
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||||
|
for body in transcript() {
|
||||||
|
let lower = String::from_utf8(body).unwrap();
|
||||||
|
// Lower-case only the hex payloads (element names keep their case).
|
||||||
|
let mut out = String::new();
|
||||||
|
let mut in_text = false;
|
||||||
|
for c in lower.chars() {
|
||||||
|
match c {
|
||||||
|
'>' => {
|
||||||
|
in_text = true;
|
||||||
|
out.push(c);
|
||||||
|
}
|
||||||
|
'<' => {
|
||||||
|
in_text = false;
|
||||||
|
out.push(c);
|
||||||
|
}
|
||||||
|
_ if in_text => out.push(c.to_ascii_lowercase()),
|
||||||
|
_ => out.push(c),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.handle_response(&id, 200, out.as_bytes(), &mut rng).unwrap();
|
||||||
|
}
|
||||||
|
assert_eq!(s.state(), PairingState::Paired);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ no shortcuts
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn paired_needs_exactly_five_answers() {
|
||||||
|
// An answer carrying every element at once still moves one step at a time.
|
||||||
|
let v = v();
|
||||||
|
let all = xml_root(
|
||||||
|
200,
|
||||||
|
&format!(
|
||||||
|
"<paired>1</paired><plaincert>{}</plaincert><challengeresponse>{}</challengeresponse><pairingsecret>{}</pairingsecret>",
|
||||||
|
to_hex(HOST_CERT_PEM.as_bytes()),
|
||||||
|
to_hex(&v.bytes("step2_challengeresponse")),
|
||||||
|
to_hex(&v.bytes("step3_pairingsecret")),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
let id = client();
|
||||||
|
let mut rng = rng_a();
|
||||||
|
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||||
|
for (i, want) in STATES.iter().enumerate().skip(1) {
|
||||||
|
let step = s.handle_response(&id, 200, &all, &mut rng).unwrap();
|
||||||
|
assert!(matches!(step, PairingStep::Send(_)), "answer {} must not finish pairing", i);
|
||||||
|
assert_eq!(s.state(), *want, "after {i} answers");
|
||||||
|
}
|
||||||
|
assert!(matches!(s.handle_response(&id, 200, &all, &mut rng).unwrap(), PairingStep::Paired(_)));
|
||||||
|
assert_eq!(s.state(), PairingState::Paired);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_bare_paired_answer_cannot_skip_any_step() {
|
||||||
|
// `<paired>1</paired>` is all steps 4 and 5 need. Fed early, it must fail, never jump ahead.
|
||||||
|
for (steps, state) in STATES.iter().enumerate().take(3) {
|
||||||
|
let (mut s, mut rng, id) = session_after(steps);
|
||||||
|
assert_eq!(s.state(), *state);
|
||||||
|
expect_failure(&mut s, &id, &mut rng, 200, &resp_ok(), PairingFailure::MalformedAnswer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn out_of_order_answers_fail() {
|
||||||
|
// Each state fed an answer meant for another state (replayed or reordered by an attacker).
|
||||||
|
let cases: Vec<(usize, Vec<u8>)> =
|
||||||
|
vec![(0, resp2()), (0, resp3()), (1, resp1()), (1, resp3()), (2, resp1()), (2, resp2())];
|
||||||
|
for (steps, body) in cases {
|
||||||
|
let (mut s, mut rng, id) = session_after(steps);
|
||||||
|
expect_failure(&mut s, &id, &mut rng, 200, &body, PairingFailure::MalformedAnswer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replayed_answers_from_another_session_fail() {
|
||||||
|
// Session B (fresh randomness) fed session A's recorded answers: the host proof cannot match.
|
||||||
|
let id = client();
|
||||||
|
let mut rng = rng_b();
|
||||||
|
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
|
||||||
|
s.handle_response(&id, 200, &resp1(), &mut rng).unwrap();
|
||||||
|
s.handle_response(&id, 200, &resp2(), &mut rng).unwrap();
|
||||||
|
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
|
||||||
|
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replaying_the_same_answer_twice_fails() {
|
||||||
|
// Step 2's answer accepted, then replayed in place of step 3's.
|
||||||
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
|
expect_failure(&mut s, &id, &mut rng, 200, &resp2(), PairingFailure::MalformedAnswer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ hostile host
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_refusal_at_every_step() {
|
||||||
|
for steps in 0..5 {
|
||||||
|
let (mut s, mut rng, id) = session_after(steps);
|
||||||
|
let body = answer(false, None);
|
||||||
|
let r = s.handle_response(&id, 200, &body, &mut rng);
|
||||||
|
assert_err!(r, Error::PairingRefused, "step {}", steps + 1);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostRefused), "step {}", steps + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_status_errors_at_every_step() {
|
||||||
|
for steps in 0..5 {
|
||||||
|
let (mut s, mut rng, id) = session_after(steps);
|
||||||
|
let r = s.handle_response(&id, 200, &xml_root(500, "<paired>1</paired>"), &mut rng);
|
||||||
|
assert_err!(r, Error::HostStatus { code: 500 }, "step {}", steps + 1);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
|
||||||
|
|
||||||
|
let (mut s, mut rng, id) = session_after(steps);
|
||||||
|
let good = transcript().swap_remove(steps);
|
||||||
|
let r = s.handle_response(&id, 404, &good, &mut rng);
|
||||||
|
assert_err!(r, Error::HostStatus { code: 404 }, "HTTP 404 at step {}", steps + 1);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn malformed_answers_at_every_step() {
|
||||||
|
let bodies: Vec<Vec<u8>> = vec![
|
||||||
|
b"".to_vec(),
|
||||||
|
b"garbage".to_vec(),
|
||||||
|
b"<root status_code=\"200\"><paired>1</paired>".to_vec(),
|
||||||
|
xml_root(200, ""),
|
||||||
|
xml_root(200, "<paired>yes</paired>"),
|
||||||
|
xml_root(
|
||||||
|
200,
|
||||||
|
"<paired>1</paired><plaincert>zz</plaincert><challengeresponse>zz</challengeresponse><pairingsecret>zz</pairingsecret>",
|
||||||
|
),
|
||||||
|
xml_root(
|
||||||
|
200,
|
||||||
|
"<paired>1</paired><plaincert>abc</plaincert><challengeresponse>abc</challengeresponse><pairingsecret>abc</pairingsecret>",
|
||||||
|
),
|
||||||
|
];
|
||||||
|
for steps in 0..3 {
|
||||||
|
for body in &bodies {
|
||||||
|
let (mut s, mut rng, id) = session_after(steps);
|
||||||
|
expect_failure(&mut s, &id, &mut rng, 200, body, PairingFailure::MalformedAnswer);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_pin_is_a_proof_mismatch() {
|
||||||
|
let v = v();
|
||||||
|
let (mut s, mut rng, id) = session_after(1);
|
||||||
|
s.handle_response(
|
||||||
|
&id,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("challengeresponse", &v.bytes("step2_challengeresponse_wrong_pin")))),
|
||||||
|
&mut rng,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_host_hash_is_a_proof_mismatch() {
|
||||||
|
let v = v();
|
||||||
|
for name in ["step2_challengeresponse_wrong_hash", "step2_challengeresponse_wrong_cert"] {
|
||||||
|
let (mut s, mut rng, id) = session_after(1);
|
||||||
|
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &v.bytes(name)))), &mut rng).unwrap();
|
||||||
|
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
|
||||||
|
assert_err!(r, Error::PairingRefused, "{name}");
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "{name}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tampered_challenge_response() {
|
||||||
|
let v = v();
|
||||||
|
// Block 0 or 1 holds H_s: flipping it must end in ProofMismatch once the secret arrives.
|
||||||
|
for byte in [0usize, 17, 31] {
|
||||||
|
let mut cr = v.bytes("step2_challengeresponse");
|
||||||
|
cr[byte] ^= 0x01;
|
||||||
|
let (mut s, mut rng, id) = session_after(1);
|
||||||
|
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap();
|
||||||
|
assert_err!(s.handle_response(&id, 200, &resp3(), &mut rng), Error::PairingRefused);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "byte {byte}");
|
||||||
|
}
|
||||||
|
// Block 2 holds S_c: the client cannot see it, but it must feed S_c into H_c (so step 3 changes).
|
||||||
|
let mut cr = v.bytes("step2_challengeresponse");
|
||||||
|
cr[40] ^= 0x01;
|
||||||
|
let (mut s, mut rng, id) = session_after(1);
|
||||||
|
let req3 = sent(s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap());
|
||||||
|
assert_ne!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_challenge_response_sizes() {
|
||||||
|
let v = v();
|
||||||
|
let good = v.bytes("step2_challengeresponse");
|
||||||
|
let cases: Vec<Vec<u8>> = vec![
|
||||||
|
good[..32].to_vec(),
|
||||||
|
good[..47].to_vec(),
|
||||||
|
[good.clone(), vec![0; 1]].concat(),
|
||||||
|
[good.clone(), vec![0; 16]].concat(),
|
||||||
|
vec![],
|
||||||
|
];
|
||||||
|
for cr in cases {
|
||||||
|
let (mut s, mut rng, id) = session_after(1);
|
||||||
|
expect_failure(
|
||||||
|
&mut s,
|
||||||
|
&id,
|
||||||
|
&mut rng,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("challengeresponse", &cr))),
|
||||||
|
PairingFailure::MalformedAnswer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_host_signatures() {
|
||||||
|
let v = v();
|
||||||
|
// Signed by another key.
|
||||||
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
|
let r = s.handle_response(
|
||||||
|
&id,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("pairingsecret", &v.bytes("step3_pairingsecret_rogue_signature")))),
|
||||||
|
&mut rng,
|
||||||
|
);
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
|
||||||
|
|
||||||
|
// One bit of the signature flipped, the signature cut short, or zeroed.
|
||||||
|
let good = v.bytes("step3_pairingsecret");
|
||||||
|
let mut flipped = good.clone();
|
||||||
|
*flipped.last_mut().unwrap() ^= 0x80;
|
||||||
|
let mut zeroed = good.clone();
|
||||||
|
zeroed[16..].fill(0);
|
||||||
|
for ps in [flipped, good[..good.len() - 1].to_vec(), zeroed, [good[..16].to_vec(), vec![0x01]].concat()] {
|
||||||
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
|
let r = s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &ps))), &mut rng);
|
||||||
|
assert_err!(r, Error::PairingRefused);
|
||||||
|
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
|
||||||
|
}
|
||||||
|
|
||||||
|
// The secret itself changed: both checks fail; either reason is a refusal.
|
||||||
|
let mut secret = good.clone();
|
||||||
|
secret[0] ^= 1;
|
||||||
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
|
assert_err!(
|
||||||
|
s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &secret))), &mut rng),
|
||||||
|
Error::PairingRefused
|
||||||
|
);
|
||||||
|
assert!(matches!(
|
||||||
|
s.state(),
|
||||||
|
PairingState::Failed(PairingFailure::ProofMismatch | PairingFailure::BadHostSignature)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_pairing_secret_sizes() {
|
||||||
|
let v = v();
|
||||||
|
let secret = v.bytes("server_secret");
|
||||||
|
for ps in
|
||||||
|
[secret[..15].to_vec(), secret.clone(), [secret.clone(), vec![0x55; MAX_SIGNATURE_BYTES + 1]].concat(), vec![]]
|
||||||
|
{
|
||||||
|
let (mut s, mut rng, id) = session_after(2);
|
||||||
|
expect_failure(
|
||||||
|
&mut s,
|
||||||
|
&id,
|
||||||
|
&mut rng,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("pairingsecret", &ps))),
|
||||||
|
PairingFailure::MalformedAnswer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_host_certificates() {
|
||||||
|
let two = format!("{HOST_CERT_PEM}{ROGUE_CERT_PEM}");
|
||||||
|
let mut long = HOST_CERT_PEM.to_string();
|
||||||
|
long.push_str(&"\n".repeat(MAX_CERT_PEM_BYTES));
|
||||||
|
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() / 2];
|
||||||
|
for pem in [
|
||||||
|
"".to_string(),
|
||||||
|
"hello".to_string(),
|
||||||
|
EC_CERT_PEM.to_string(),
|
||||||
|
two,
|
||||||
|
CLIENT_KEY_PEM.to_string(),
|
||||||
|
cut.to_string(),
|
||||||
|
long,
|
||||||
|
] {
|
||||||
|
let (mut s, mut rng, id) = session_after(0);
|
||||||
|
expect_failure(
|
||||||
|
&mut s,
|
||||||
|
&id,
|
||||||
|
&mut rng,
|
||||||
|
200,
|
||||||
|
&answer(true, Some(("plaincert", pem.as_bytes()))),
|
||||||
|
PairingFailure::MalformedAnswer,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn identity_must_stay_the_same() {
|
||||||
|
let (mut s, mut rng, _) = session_after(1);
|
||||||
|
assert_err!(s.handle_response(&rogue(), 200, &resp2(), &mut rng), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn start_refuses_bad_names_and_injection() {
|
||||||
|
use domistream::http::{MAX_DEVICE_NAME_BYTES, MAX_UNIQUE_ID_BYTES};
|
||||||
|
let id = client();
|
||||||
|
for (uid, dev) in [
|
||||||
|
("", DEVICE),
|
||||||
|
(&*"a".repeat(MAX_UNIQUE_ID_BYTES + 1), DEVICE),
|
||||||
|
(UID, ""),
|
||||||
|
(UID, &*"d".repeat(MAX_DEVICE_NAME_BYTES + 1)),
|
||||||
|
] {
|
||||||
|
assert_err!(PairingSession::start(&id, uid, dev, pin(), &mut rng_a()), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
// A device name with query syntax is refused or encoded: never a second `phrase`.
|
||||||
|
for evil in ["tv&phrase=pairchallenge", "tv\r\nHost: x", "tv#x", "tv salt=00"] {
|
||||||
|
match PairingSession::start(&id, UID, evil, pin(), &mut rng_a()) {
|
||||||
|
Err(Error::Malformed { .. }) => {}
|
||||||
|
Ok((_, req)) => {
|
||||||
|
let (_, q) = parse_query(&req.path_and_query);
|
||||||
|
assert_eq!(param(&q, "phrase"), "getservercert");
|
||||||
|
assert_eq!(param(&q, "devicename"), evil);
|
||||||
|
assert!(!req.path_and_query.contains(['\r', '\n', ' ', '#']));
|
||||||
|
}
|
||||||
|
Err(e) => panic!("{evil:?}: {e:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ crypto vectors
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn derive_key_vectors() {
|
||||||
|
let v = v();
|
||||||
|
for i in 0..4 {
|
||||||
|
let salt: [u8; 16] = v.arr16(&format!("derive_{i}_salt"));
|
||||||
|
let p = Pin::from_digits(v.str(&format!("derive_{i}_pin"))).unwrap();
|
||||||
|
assert_eq!(crypto::derive_key(&salt, &p).unwrap().to_vec(), v.bytes(&format!("derive_{i}_key")), "vector {i}");
|
||||||
|
}
|
||||||
|
assert_eq!(crypto::derive_key(&v.arr16("salt"), &pin()).unwrap().to_vec(), v.bytes("key"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ecb_vectors() {
|
||||||
|
let v = v();
|
||||||
|
for blocks in 1..=4 {
|
||||||
|
let key = v.arr16(&format!("ecb_{blocks}_key"));
|
||||||
|
let plain = v.bytes(&format!("ecb_{blocks}_plain"));
|
||||||
|
let cipher = v.bytes(&format!("ecb_{blocks}_cipher"));
|
||||||
|
assert_eq!(crypto::ecb_encrypt(&key, &plain).unwrap(), cipher, "{blocks} blocks");
|
||||||
|
assert_eq!(crypto::ecb_decrypt(&key, &cipher).unwrap(), plain, "{blocks} blocks");
|
||||||
|
}
|
||||||
|
let key = v.arr16("key");
|
||||||
|
assert_eq!(crypto::ecb_encrypt(&key, &v.bytes("client_challenge")).unwrap(), v.bytes("step2_clientchallenge"));
|
||||||
|
for len in [1usize, 15, 17, 47] {
|
||||||
|
assert_err!(crypto::ecb_encrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
|
||||||
|
assert_err!(crypto::ecb_decrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn proof_hash_vectors() {
|
||||||
|
let v = v();
|
||||||
|
for i in 0..6 {
|
||||||
|
let h = crypto::proof_hash(
|
||||||
|
&v.arr16(&format!("proof_{i}_challenge")),
|
||||||
|
&v.bytes(&format!("proof_{i}_signature")),
|
||||||
|
&v.arr16(&format!("proof_{i}_secret")),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(h.to_vec(), v.bytes(&format!("proof_{i}_hash")), "vector {i}");
|
||||||
|
}
|
||||||
|
let h =
|
||||||
|
crypto::proof_hash(&v.arr16("client_challenge"), &v.bytes("host_cert_signature"), &v.arr16("server_secret"));
|
||||||
|
assert_eq!(h.unwrap().to_vec(), v.bytes("host_proof"));
|
||||||
|
let h =
|
||||||
|
crypto::proof_hash(&v.arr16("server_challenge"), &v.bytes("client_cert_signature"), &v.arr16("client_secret"));
|
||||||
|
assert_eq!(h.unwrap().to_vec(), v.bytes("client_proof"));
|
||||||
|
assert_too_large!(
|
||||||
|
crypto::proof_hash(&[0; 16], &vec![0; MAX_SIGNATURE_BYTES + 1], &[0; 16]),
|
||||||
|
MAX_SIGNATURE_BYTES,
|
||||||
|
MAX_SIGNATURE_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn split_helpers() {
|
||||||
|
let v = v();
|
||||||
|
let key = v.arr16("key");
|
||||||
|
let decrypted = crypto::ecb_decrypt(&key, &v.bytes("step2_challengeresponse")).unwrap();
|
||||||
|
let (h, sc) = crypto::split_challenge_response(&decrypted).unwrap();
|
||||||
|
assert_eq!(h.to_vec(), v.bytes("host_proof"));
|
||||||
|
assert_eq!(sc.to_vec(), v.bytes("server_challenge"));
|
||||||
|
for len in [0usize, 1, 32, 47, 49, 64] {
|
||||||
|
assert_err!(crypto::split_challenge_response(&vec![0; len]), Error::Malformed { .. }, "{len}");
|
||||||
|
}
|
||||||
|
|
||||||
|
let ps = v.bytes("step3_pairingsecret");
|
||||||
|
let (secret, sig) = crypto::split_pairing_secret(&ps).unwrap();
|
||||||
|
assert_eq!(secret.to_vec(), v.bytes("server_secret"));
|
||||||
|
assert_eq!(sig, v.bytes("server_secret_signature").as_slice());
|
||||||
|
assert_eq!(crypto::split_pairing_secret(&[7; 17]).unwrap().1, &[7]);
|
||||||
|
assert_eq!(crypto::split_pairing_secret(&vec![7; 16 + MAX_SIGNATURE_BYTES]).unwrap().1.len(), MAX_SIGNATURE_BYTES);
|
||||||
|
for len in [0usize, 1, 15, 16] {
|
||||||
|
assert_err!(crypto::split_pairing_secret(&vec![0; len]), Error::Malformed { .. }, "{len}");
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
crypto::split_pairing_secret(&vec![0; 16 + MAX_SIGNATURE_BYTES + 1]),
|
||||||
|
MAX_SIGNATURE_BYTES,
|
||||||
|
MAX_SIGNATURE_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ certificates
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_cert_from_recorded_pem() {
|
||||||
|
let v = v();
|
||||||
|
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
|
||||||
|
assert_eq!(c.der(), v.bytes("host_cert_der").as_slice());
|
||||||
|
assert_eq!(c.signature().unwrap(), v.bytes("host_cert_signature"));
|
||||||
|
assert_eq!(ServerCert::from_der(&v.bytes("host_cert_der")).unwrap(), c);
|
||||||
|
c.verify(&v.bytes("server_secret"), &v.bytes("server_secret_signature")).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_cert_verify_refuses() {
|
||||||
|
let v = v();
|
||||||
|
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
|
||||||
|
let secret = v.bytes("server_secret");
|
||||||
|
let sig = v.bytes("server_secret_signature");
|
||||||
|
let mut flipped = sig.clone();
|
||||||
|
flipped[100] ^= 0x04;
|
||||||
|
let rogue_sig = &v.bytes("step3_pairingsecret_rogue_signature")[16..];
|
||||||
|
let mut other = secret.clone();
|
||||||
|
other[15] ^= 1;
|
||||||
|
assert_err!(c.verify(&secret, &flipped), Error::Crypto);
|
||||||
|
assert_err!(c.verify(&secret, rogue_sig), Error::Crypto);
|
||||||
|
assert_err!(c.verify(&other, &sig), Error::Crypto);
|
||||||
|
assert_err!(c.verify(&secret, &sig[..255]), Error::Crypto);
|
||||||
|
assert_err!(c.verify(&secret, &[]), Error::Crypto);
|
||||||
|
assert_err!(c.verify(&secret, &[sig.clone(), vec![0]].concat()), Error::Crypto);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_cert_pinning() {
|
||||||
|
let v = v();
|
||||||
|
let der = v.bytes("host_cert_der");
|
||||||
|
let c = ServerCert::from_der(&der).unwrap();
|
||||||
|
assert_eq!(c.matches(&der), Ok(true));
|
||||||
|
let mut flipped = der.clone();
|
||||||
|
flipped[der.len() / 2] ^= 1;
|
||||||
|
assert_eq!(c.matches(&flipped), Ok(false));
|
||||||
|
assert_eq!(c.matches(&der[..der.len() - 1]), Ok(false));
|
||||||
|
assert_eq!(c.matches(&[der.clone(), vec![0]].concat()), Ok(false));
|
||||||
|
assert_eq!(c.matches(&v.bytes("rogue_cert_der")), Ok(false));
|
||||||
|
assert_eq!(c.matches(&[]), Ok(false));
|
||||||
|
assert_too_large!(c.matches(&vec![0; MAX_CERT_DER_BYTES + 1]), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_cert_hostile_pem() {
|
||||||
|
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() - 40];
|
||||||
|
let bad_b64 = HOST_CERT_PEM.replacen('M', "!", 3);
|
||||||
|
let two = format!("{HOST_CERT_PEM}{CLIENT_CERT_PEM}");
|
||||||
|
for (pem, why) in [
|
||||||
|
("", "empty"),
|
||||||
|
("x", "one byte"),
|
||||||
|
("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", "empty block"),
|
||||||
|
(cut, "cut"),
|
||||||
|
(&*bad_b64, "bad base64"),
|
||||||
|
(&*two, "two certificates"),
|
||||||
|
(CLIENT_KEY_PEM, "a private key"),
|
||||||
|
(EC_CERT_PEM, "not an RSA key"),
|
||||||
|
] {
|
||||||
|
assert_err!(ServerCert::from_pem(pem.as_bytes()), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
let mut big = HOST_CERT_PEM.as_bytes().to_vec();
|
||||||
|
big.resize(MAX_CERT_PEM_BYTES + 1, b'\n');
|
||||||
|
assert_too_large!(ServerCert::from_pem(&big), MAX_CERT_PEM_BYTES, MAX_CERT_PEM_BYTES + 1);
|
||||||
|
assert_too_large!(ServerCert::from_pem(&vec![b'A'; 1 << 24]), MAX_CERT_PEM_BYTES, 1 << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn server_cert_hostile_der() {
|
||||||
|
let der = v().bytes("host_cert_der");
|
||||||
|
for (bad, why) in [
|
||||||
|
(vec![], "empty"),
|
||||||
|
(vec![0x30], "one byte"),
|
||||||
|
(der[..der.len() - 1].to_vec(), "cut"),
|
||||||
|
([der.clone(), vec![0]].concat(), "trailing byte"),
|
||||||
|
(
|
||||||
|
{
|
||||||
|
let mut d = der.clone();
|
||||||
|
d[1] = 0x84; // outer length claims 4 length bytes: lies about the size
|
||||||
|
d
|
||||||
|
},
|
||||||
|
"lying length",
|
||||||
|
),
|
||||||
|
] {
|
||||||
|
assert_err!(ServerCert::from_der(&bad), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
let mut big = der.clone();
|
||||||
|
big.resize(MAX_CERT_DER_BYTES + 1, 0);
|
||||||
|
assert_too_large!(ServerCert::from_der(&big), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_identity_from_recorded_keys() {
|
||||||
|
let v = v();
|
||||||
|
let id = client();
|
||||||
|
assert_eq!(id.cert_der(), v.bytes("client_cert_der").as_slice());
|
||||||
|
assert_eq!(id.key_pkcs8_der(), v.bytes("client_key_pkcs8_der").as_slice());
|
||||||
|
assert_eq!(id.cert_signature().unwrap(), v.bytes("client_cert_signature"));
|
||||||
|
assert_eq!(
|
||||||
|
id.sign(&v.bytes("sign_data")).unwrap(),
|
||||||
|
v.bytes("sign_data_client_signature"),
|
||||||
|
"PKCS#1 v1.5 is deterministic"
|
||||||
|
);
|
||||||
|
assert_eq!(id.sign(&v.bytes("client_secret")).unwrap(), v.bytes("client_secret_signature"));
|
||||||
|
let pem = id.cert_pem().unwrap();
|
||||||
|
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")]);
|
||||||
|
assert_eq!(pem_blocks(CLIENT_CERT_PEM, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "fixture sanity");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_identity_refuses() {
|
||||||
|
use domistream::pairing::identity::MAX_KEY_DER_BYTES;
|
||||||
|
let v = v();
|
||||||
|
let cert = v.bytes("client_cert_der");
|
||||||
|
let key = v.bytes("client_key_pkcs8_der");
|
||||||
|
assert_err!(
|
||||||
|
ClientIdentity::from_der(&cert, &v.bytes("rogue_key_pkcs8_der")),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"key of another cert"
|
||||||
|
);
|
||||||
|
assert_err!(ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &key), Error::Malformed { .. });
|
||||||
|
assert_err!(ClientIdentity::from_der(&[], &key), Error::Malformed { .. });
|
||||||
|
assert_err!(ClientIdentity::from_der(&cert, &[]), Error::Malformed { .. });
|
||||||
|
assert_err!(ClientIdentity::from_der(&cert, &key[..key.len() - 1]), Error::Malformed { .. });
|
||||||
|
assert_err!(ClientIdentity::from_der(&cert, &cert), Error::Malformed { .. });
|
||||||
|
let mut big_cert = cert.clone();
|
||||||
|
big_cert.resize(MAX_CERT_DER_BYTES + 1, 0);
|
||||||
|
assert_too_large!(ClientIdentity::from_der(&big_cert, &key), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
|
||||||
|
let mut big_key = key.clone();
|
||||||
|
big_key.resize(MAX_KEY_DER_BYTES + 1, 0);
|
||||||
|
assert_too_large!(ClientIdentity::from_der(&cert, &big_key), MAX_KEY_DER_BYTES, MAX_KEY_DER_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_identity_generate() {
|
||||||
|
let id = ClientIdentity::generate(&mut SeqRng::new(0xD0D0), "Living Room TV", 1_764_000_000).unwrap();
|
||||||
|
let cert = ServerCert::from_der(id.cert_der()).expect("a generated cert is a valid RSA X.509 certificate");
|
||||||
|
let sig = id.sign(b"hello").unwrap();
|
||||||
|
assert_eq!(sig.len(), domistream::pairing::identity::CLIENT_KEY_BITS / 8);
|
||||||
|
cert.verify(b"hello", &sig).expect("the cert carries the identity's public key");
|
||||||
|
let again = ClientIdentity::from_der(id.cert_der(), id.key_pkcs8_der()).unwrap();
|
||||||
|
assert_eq!(again.cert_der(), id.cert_der());
|
||||||
|
assert!(id.cert_der().windows(14).any(|w| w == b"Living Room TV"), "CN in the certificate");
|
||||||
|
assert_eq!(id.cert_signature().unwrap(), cert.signature().unwrap());
|
||||||
|
|
||||||
|
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), "", 0), Error::Malformed { .. });
|
||||||
|
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), &"n".repeat(10_000), 0), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ PIN
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_from_digits() {
|
||||||
|
assert_eq!(Pin::from_digits("0000").unwrap().as_bytes(), b"0000");
|
||||||
|
assert_eq!(Pin::from_digits("4071").unwrap().as_bytes(), b"4071");
|
||||||
|
for bad in [
|
||||||
|
"",
|
||||||
|
"1",
|
||||||
|
"123",
|
||||||
|
"12345",
|
||||||
|
"12a4",
|
||||||
|
" 123",
|
||||||
|
"123 ",
|
||||||
|
"-123",
|
||||||
|
"+123",
|
||||||
|
"\u{0661}\u{0662}\u{0663}\u{0664}",
|
||||||
|
"1234",
|
||||||
|
"12\u{0}4",
|
||||||
|
] {
|
||||||
|
assert_err!(Pin::from_digits(bad), Error::Malformed { .. }, "{bad:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pin_generate_is_uniform_digits() {
|
||||||
|
let mut rng = SeqRng::new(42);
|
||||||
|
let mut counts = [[0u32; 10]; 4];
|
||||||
|
let draws = 4000;
|
||||||
|
for _ in 0..draws {
|
||||||
|
let p = Pin::generate(&mut rng).unwrap();
|
||||||
|
for (pos, d) in p.as_bytes().iter().enumerate() {
|
||||||
|
assert!(d.is_ascii_digit(), "{d:#x}");
|
||||||
|
counts[pos][usize::from(d - b'0')] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// 400 expected per digit and position; a 4-sigma band (sd ~ 19) catches modulo bias of a u8 draw (+20 %).
|
||||||
|
for (pos, row) in counts.iter().enumerate() {
|
||||||
|
for (digit, &n) in row.iter().enumerate() {
|
||||||
|
assert!((324..=476).contains(&n), "digit {digit} at position {pos}: {n} of {draws}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let a = Pin::generate(&mut SeqRng::new(9)).unwrap();
|
||||||
|
let b = Pin::generate(&mut SeqRng::new(9)).unwrap();
|
||||||
|
assert_eq!(a, b, "the PIN comes only from the caller's randomness");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ answer parser
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pair_response_parser() {
|
||||||
|
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><plaincert>4142</plaincert>")).unwrap();
|
||||||
|
assert!(r.paired);
|
||||||
|
assert_eq!(r.plain_cert.as_deref(), Some(&b"AB"[..]));
|
||||||
|
assert_eq!(r.challenge_response, None);
|
||||||
|
let r =
|
||||||
|
parse_pair_response(&xml_root(200, "<paired>0</paired><challengeresponse>aBcD</challengeresponse>")).unwrap();
|
||||||
|
assert!(!r.paired);
|
||||||
|
assert_eq!(r.challenge_response.as_deref(), Some(&[0xAB, 0xCD][..]));
|
||||||
|
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><pairingsecret>00ff</pairingsecret>")).unwrap();
|
||||||
|
assert_eq!(r.pairing_secret.as_deref(), Some(&[0x00, 0xFF][..]));
|
||||||
|
|
||||||
|
for (inner, why) in [
|
||||||
|
("", "no paired"),
|
||||||
|
("<plaincert>4142</plaincert>", "no paired"),
|
||||||
|
("<paired>1</paired><plaincert>414</plaincert>", "odd hex"),
|
||||||
|
("<paired>1</paired><plaincert>41 42</plaincert>", "space in hex"),
|
||||||
|
("<paired>1</paired><plaincert>4G</plaincert>", "not hex"),
|
||||||
|
("<paired>1</paired><challengeresponse>0x41</challengeresponse>", "0x prefix"),
|
||||||
|
] {
|
||||||
|
assert_err!(parse_pair_response(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
assert_err!(parse_pair_response(&xml_root(400, "<paired>0</paired>")), Error::HostStatus { code: 400 });
|
||||||
|
assert_err!(parse_pair_response(b""), Error::Malformed { .. });
|
||||||
|
assert_err!(parse_pair_response(b"<"), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pair_response_sizes() {
|
||||||
|
let inner = "<paired>1</paired>";
|
||||||
|
for len in [MAX_PAIR_RESPONSE_BYTES - 1, MAX_PAIR_RESPONSE_BYTES] {
|
||||||
|
assert!(parse_pair_response(&xml_padded_to(inner, len)).unwrap().paired, "{len}");
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
parse_pair_response(&xml_padded_to(inner, MAX_PAIR_RESPONSE_BYTES + 1)),
|
||||||
|
MAX_PAIR_RESPONSE_BYTES,
|
||||||
|
MAX_PAIR_RESPONSE_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(parse_pair_response(&vec![b'0'; 1 << 22]), MAX_PAIR_RESPONSE_BYTES, 1 << 22);
|
||||||
|
// A plaincert near the cap: the hex text is within MAX_XML_TEXT_BYTES and decodes to half its size.
|
||||||
|
let cert = vec![0x41u8; 30_000];
|
||||||
|
let r = parse_pair_response(&answer(true, Some(("plaincert", &cert)))).unwrap();
|
||||||
|
assert_eq!(r.plain_cert.unwrap().len(), 30_000);
|
||||||
|
}
|
||||||
@@ -0,0 +1,787 @@
|
|||||||
|
//! RTSP (`docs/PROTOCOL.md` 2): message parsers, the TCP framer (64 KiB cap), SDP and `surround-params`, the
|
||||||
|
//! ANNOUNCE builder and the client state machine, all with hostile input.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use domistream::Error;
|
||||||
|
use domistream::http::launch::AudioLayout;
|
||||||
|
use domistream::rtsp::client::VideoCodec;
|
||||||
|
use domistream::rtsp::sdp::{self, MAX_OPUS_CONFIGS, MAX_SDP_BYTES, MAX_SDP_LINES};
|
||||||
|
use domistream::rtsp::{
|
||||||
|
EncryptionFlags, HostCapabilities, MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES, Method,
|
||||||
|
RtspClient, RtspClientState, RtspFramer, RtspProgress, RtspRequest, StreamConfig, parse_request, parse_response,
|
||||||
|
};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
macro_rules! assert_cap {
|
||||||
|
($e:expr, $max:expr) => {
|
||||||
|
match $e {
|
||||||
|
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
|
||||||
|
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn response(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
|
||||||
|
let mut m = format!("RTSP/1.0 {status}\r\n");
|
||||||
|
for (k, v) in headers {
|
||||||
|
m.push_str(&format!("{k}: {v}\r\n"));
|
||||||
|
}
|
||||||
|
m.push_str("\r\n");
|
||||||
|
let mut m = m.into_bytes();
|
||||||
|
m.extend_from_slice(body);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A 200 answer padded with a body to exactly `total` bytes.
|
||||||
|
fn response_of_size(total: usize) -> Vec<u8> {
|
||||||
|
let probe = response("200 OK", &[("CSeq", "1"), ("Content-Length", "00000")], b"");
|
||||||
|
let body_len = total - probe.len();
|
||||||
|
let cl = format!("{body_len:05}");
|
||||||
|
let m = response("200 OK", &[("CSeq", "1"), ("Content-Length", &cl)], &vec![b'b'; body_len]);
|
||||||
|
assert_eq!(m.len(), total);
|
||||||
|
m
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ responses
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_sample() {
|
||||||
|
let r = parse_response(&response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello")).unwrap();
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
assert_eq!(r.reason, "OK");
|
||||||
|
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("Content-Length".into(), "5".into())]);
|
||||||
|
assert_eq!(r.body, b"hello");
|
||||||
|
assert_eq!(r.header("cseq"), Some("1"));
|
||||||
|
assert_eq!(r.header("CONTENT-LENGTH"), Some("5"));
|
||||||
|
|
||||||
|
// Without Content-Length the payload is everything after the headers (UNKNOWN U5).
|
||||||
|
let r = parse_response(&response("404 Not Found", &[("CSeq", "2")], b"rest")).unwrap();
|
||||||
|
assert_eq!(r.status, 404);
|
||||||
|
assert_eq!(r.reason, "Not Found");
|
||||||
|
assert_eq!(r.body, b"rest");
|
||||||
|
|
||||||
|
let r = parse_response(&response("200 OK", &[("content-length", "0")], b"")).unwrap();
|
||||||
|
assert!(r.body.is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_bad_start_lines() {
|
||||||
|
for bad in [
|
||||||
|
&b""[..],
|
||||||
|
b"R",
|
||||||
|
b"HTTP/1.1 200 OK\r\n\r\n",
|
||||||
|
b"RTSP/1.0 abc OK\r\n\r\n",
|
||||||
|
b"RTSP/1.0 2000 OK\r\n\r\n",
|
||||||
|
b"RTSP/1.0 -20 OK\r\n\r\n",
|
||||||
|
b"RTSP/1.0\r\n\r\n",
|
||||||
|
b"RTSP/2.0 200 OK\r\n\r\n",
|
||||||
|
b" RTSP/1.0 200 OK\r\n\r\n",
|
||||||
|
b"\r\n\r\n",
|
||||||
|
] {
|
||||||
|
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_bad_headers() {
|
||||||
|
for bad in [
|
||||||
|
&b"RTSP/1.0 200 OK\r\nno colon here\r\n\r\n"[..],
|
||||||
|
b"RTSP/1.0 200 OK\r\n: empty name\r\n\r\n",
|
||||||
|
b"RTSP/1.0 200 OK\r\nCSeq: \xff\xfe\r\n\r\n",
|
||||||
|
b"RTSP/1.0 200 OK\r\nCSeq: 1\rX: y\r\n\r\n",
|
||||||
|
] {
|
||||||
|
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
|
||||||
|
}
|
||||||
|
// Headers that never end.
|
||||||
|
assert_err!(parse_response(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n"), Error::Truncated { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_lying_content_length() {
|
||||||
|
// Over: claims more than is there.
|
||||||
|
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "10")], b"12345")), Error::Truncated { .. });
|
||||||
|
// Under: more bytes than it claims.
|
||||||
|
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "2")], b"12345")), Error::Malformed { .. });
|
||||||
|
for cl in ["abc", "-1", "+5", "5 5", "0x5", "", "5;"] {
|
||||||
|
assert_err!(
|
||||||
|
parse_response(&response("200 OK", &[("Content-Length", cl)], b"12345")),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{cl:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Two different lengths.
|
||||||
|
assert_err!(
|
||||||
|
parse_response(&response("200 OK", &[("Content-Length", "5"), ("Content-Length", "4")], b"12345")),
|
||||||
|
Error::Malformed { .. }
|
||||||
|
);
|
||||||
|
// Past the cap: refused as too large, not waited for.
|
||||||
|
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "65537")], b"")), MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "4294967295")], b"")), MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
// Past u64: a number that big is over the cap or not a number; either way refused, never wrapped.
|
||||||
|
let r = parse_response(&response("200 OK", &[("Content-Length", "99999999999999999999999")], b""));
|
||||||
|
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{r:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_header_flood() {
|
||||||
|
let names: Vec<String> = (0..=MAX_RTSP_HEADERS).map(|i| format!("X-H{i}")).collect();
|
||||||
|
let headers = |n: usize| names[..n].iter().map(|n| (n.as_str(), "v")).collect::<Vec<_>>();
|
||||||
|
assert_eq!(
|
||||||
|
parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS), b"")).unwrap().headers.len(),
|
||||||
|
MAX_RTSP_HEADERS
|
||||||
|
);
|
||||||
|
assert_cap!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS + 1), b"")), MAX_RTSP_HEADERS);
|
||||||
|
// A flood of empty-valued headers in under 64 KiB.
|
||||||
|
let flood: Vec<(String, &str)> = (0..5000).map(|i| (format!("F{i}"), "")).collect();
|
||||||
|
let flood: Vec<(&str, &str)> = flood.iter().map(|(k, v)| (k.as_str(), *v)).collect();
|
||||||
|
assert_cap!(parse_response(&response("200 OK", &flood, b"")), MAX_RTSP_HEADERS);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_line_cap() {
|
||||||
|
// "X: " + value, without CRLF.
|
||||||
|
let value = |line: usize| "v".repeat(line - 3);
|
||||||
|
let ok = value(MAX_RTSP_LINE_BYTES);
|
||||||
|
assert_eq!(parse_response(&response("200 OK", &[("X", &ok)], b"")).unwrap().header("x"), Some(ok.as_str()));
|
||||||
|
assert_cap!(
|
||||||
|
parse_response(&response("200 OK", &[("X", &value(MAX_RTSP_LINE_BYTES + 1))], b"")),
|
||||||
|
MAX_RTSP_LINE_BYTES
|
||||||
|
);
|
||||||
|
let reason = "r".repeat(MAX_RTSP_LINE_BYTES);
|
||||||
|
assert_cap!(parse_response(&response(&format!("200 {reason}"), &[], b"")), MAX_RTSP_LINE_BYTES);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn response_size_boundaries() {
|
||||||
|
for len in [MAX_RTSP_MESSAGE_BYTES - 1, MAX_RTSP_MESSAGE_BYTES] {
|
||||||
|
let r = parse_response(&response_of_size(len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
|
||||||
|
assert_eq!(r.status, 200);
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
parse_response(&response_of_size(MAX_RTSP_MESSAGE_BYTES + 1)),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES,
|
||||||
|
MAX_RTSP_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(parse_response(&vec![b'R'; 1 << 24]), MAX_RTSP_MESSAGE_BYTES, 1 << 24);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ requests
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn request_parse_and_encode() {
|
||||||
|
let raw = b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\nX-GS-ClientVersion: 14\r\n\r\n";
|
||||||
|
let r = parse_request(raw).unwrap();
|
||||||
|
assert_eq!(r.method, Method::Options);
|
||||||
|
assert_eq!(r.target, "rtsp://192.0.2.10:48010");
|
||||||
|
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("X-GS-ClientVersion".into(), "14".into())]);
|
||||||
|
assert!(r.body.is_empty());
|
||||||
|
assert_eq!(r.encode().unwrap(), raw.to_vec(), "encode emits exactly the given headers, CRLF, empty line");
|
||||||
|
|
||||||
|
let announce = RtspRequest {
|
||||||
|
method: Method::Announce,
|
||||||
|
target: "streamid=control/13/0".into(),
|
||||||
|
headers: vec![("CSeq".into(), "6".into()), ("Content-Length".into(), "6".into())],
|
||||||
|
body: b"v=0\r\n\r".to_vec(),
|
||||||
|
};
|
||||||
|
let bytes = announce.encode().unwrap();
|
||||||
|
assert!(bytes.starts_with(b"ANNOUNCE streamid=control/13/0 RTSP/1.0\r\n"));
|
||||||
|
assert_eq!(parse_request(&bytes).unwrap(), announce);
|
||||||
|
|
||||||
|
for (m, name) in [
|
||||||
|
(Method::Options, "OPTIONS"),
|
||||||
|
(Method::Describe, "DESCRIBE"),
|
||||||
|
(Method::Setup, "SETUP"),
|
||||||
|
(Method::Announce, "ANNOUNCE"),
|
||||||
|
(Method::Play, "PLAY"),
|
||||||
|
] {
|
||||||
|
let req =
|
||||||
|
RtspRequest { method: m, target: "x".into(), headers: vec![("CSeq".into(), "1".into())], body: vec![] };
|
||||||
|
assert!(req.encode().unwrap().starts_with(format!("{name} x RTSP/1.0\r\n").as_bytes()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn request_refuses_unknown_methods_and_bad_lines() {
|
||||||
|
for m in ["GET_PARAMETER", "TEARDOWN", "options", "GET", "PAUSE"] {
|
||||||
|
let raw = format!("{m} rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n");
|
||||||
|
assert_err!(parse_request(raw.as_bytes()), Error::UnexpectedValue { .. }, "{m}");
|
||||||
|
}
|
||||||
|
for bad in
|
||||||
|
[&b""[..], b"O", b"OPTIONS\r\n\r\n", b"OPTIONS rtsp://h:1\r\n\r\n", b"OPTIONS rtsp://h:1 RTSP/9.9\r\n\r\n"]
|
||||||
|
{
|
||||||
|
assert_err!(parse_request(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
|
||||||
|
}
|
||||||
|
assert_too_large!(
|
||||||
|
parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES,
|
||||||
|
MAX_RTSP_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encode_refuses_header_injection() {
|
||||||
|
let base = || RtspRequest {
|
||||||
|
method: Method::Setup,
|
||||||
|
target: "streamid=video/0/0".into(),
|
||||||
|
headers: vec![("CSeq".into(), "4".into())],
|
||||||
|
body: vec![],
|
||||||
|
};
|
||||||
|
let mut cases = Vec::new();
|
||||||
|
for evil in ["a\r\nX: y", "a\ny", "a\rb"] {
|
||||||
|
cases.push(RtspRequest { target: evil.into(), ..base() });
|
||||||
|
cases.push(RtspRequest { headers: vec![(evil.into(), "v".into())], ..base() });
|
||||||
|
cases.push(RtspRequest { headers: vec![("Transport".into(), evil.into())], ..base() });
|
||||||
|
}
|
||||||
|
cases.push(RtspRequest { headers: vec![("Bad:Name".into(), "v".into())], ..base() });
|
||||||
|
cases.push(RtspRequest { headers: vec![(String::new(), "v".into())], ..base() });
|
||||||
|
cases.push(RtspRequest { target: String::new(), ..base() });
|
||||||
|
for req in cases {
|
||||||
|
assert_err!(req.encode(), Error::Malformed { .. }, "{req:?}");
|
||||||
|
}
|
||||||
|
let big = RtspRequest { body: vec![0; MAX_RTSP_MESSAGE_BYTES], ..base() };
|
||||||
|
assert_cap!(big.encode(), MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn method() -> impl Strategy<Value = Method> {
|
||||||
|
prop_oneof![
|
||||||
|
Just(Method::Options),
|
||||||
|
Just(Method::Describe),
|
||||||
|
Just(Method::Setup),
|
||||||
|
Just(Method::Announce),
|
||||||
|
Just(Method::Play)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// encode then parse gives the request back.
|
||||||
|
#[test]
|
||||||
|
fn request_round_trip(
|
||||||
|
m in method(),
|
||||||
|
target in "[!-~]{1,40}",
|
||||||
|
headers in proptest::collection::vec(("[A-Za-z][A-Za-z0-9-]{0,15}", "[!-~]([ -~]{0,30}[!-~])?"), 0..10),
|
||||||
|
body in proptest::collection::vec(any::<u8>(), 0..200),
|
||||||
|
) {
|
||||||
|
let mut headers: Vec<(String, String)> =
|
||||||
|
headers.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("content-length")).collect();
|
||||||
|
headers.insert(0, ("CSeq".into(), "1".into()));
|
||||||
|
if !body.is_empty() {
|
||||||
|
headers.push(("Content-Length".into(), body.len().to_string()));
|
||||||
|
}
|
||||||
|
let req = RtspRequest { method: m, target, headers, body };
|
||||||
|
let bytes = req.encode().map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
prop_assert_eq!(parse_request(&bytes), Ok(req));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary bytes never panic, and a parsed response respects the caps.
|
||||||
|
#[test]
|
||||||
|
fn response_never_panics(data in proptest::collection::vec(any::<u8>(), 0..1024)) {
|
||||||
|
let parsed = parse_response(&data);
|
||||||
|
prop_assert!(common::implemented(&parsed));
|
||||||
|
if let Ok(r) = parsed {
|
||||||
|
prop_assert!(r.headers.len() <= MAX_RTSP_HEADERS);
|
||||||
|
prop_assert!(r.body.len() <= data.len());
|
||||||
|
prop_assert!(r.reason.len() <= MAX_RTSP_LINE_BYTES);
|
||||||
|
}
|
||||||
|
prop_assert!(common::implemented(&parse_request(&data)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ framer
|
||||||
|
|
||||||
|
fn drain(f: &mut RtspFramer) -> Vec<Vec<u8>> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
while let Some(m) = f.next_message().unwrap() {
|
||||||
|
out.push(m);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framer_cuts_messages() {
|
||||||
|
let a = response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello");
|
||||||
|
let b = response("200 OK", &[("CSeq", "2"), ("Content-Length", "0")], b"");
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
f.push(&[a.clone(), b.clone()].concat()).unwrap();
|
||||||
|
assert_eq!(drain(&mut f), vec![a.clone(), b.clone()]);
|
||||||
|
assert_eq!(f.buffered(), 0);
|
||||||
|
assert_eq!(f.finish(), Ok(None));
|
||||||
|
|
||||||
|
// One byte at a time: same messages, nothing early.
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
let stream = [a.clone(), b.clone()].concat();
|
||||||
|
let mut got = Vec::new();
|
||||||
|
for (i, byte) in stream.iter().enumerate() {
|
||||||
|
f.push(std::slice::from_ref(byte)).unwrap();
|
||||||
|
got.extend(drain(&mut f));
|
||||||
|
if i + 1 < a.len() {
|
||||||
|
assert!(got.is_empty(), "message returned before its last byte");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(got, vec![a, b]);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framer_partial_second_message_stays_buffered() {
|
||||||
|
let a = response("200 OK", &[("Content-Length", "2")], b"ok");
|
||||||
|
let partial = b"RTSP/1.0 200 OK\r\nCont";
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
f.push(&[a.clone(), partial.to_vec()].concat()).unwrap();
|
||||||
|
assert_eq!(f.next_message().unwrap(), Some(a));
|
||||||
|
assert_eq!(f.next_message().unwrap(), None);
|
||||||
|
assert_eq!(f.buffered(), partial.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framer_without_content_length_waits_for_close() {
|
||||||
|
let m = response("200 OK", &[("CSeq", "1")], b"payload until close");
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
f.push(&m).unwrap();
|
||||||
|
assert_eq!(f.next_message().unwrap(), None, "no Content-Length: the message ends at close (U5)");
|
||||||
|
assert_eq!(f.finish().unwrap(), Some(m));
|
||||||
|
assert_eq!(f.buffered(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framer_close_mid_body_is_truncated() {
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
f.push(&response("200 OK", &[("Content-Length", "10")], b"12345")).unwrap();
|
||||||
|
assert_eq!(f.next_message().unwrap(), None);
|
||||||
|
assert_err!(f.finish(), Error::Truncated { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framer_cap_64k_plus_one() {
|
||||||
|
// Bytes that never form a complete header section.
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES]).unwrap();
|
||||||
|
assert_eq!(f.next_message().unwrap(), None);
|
||||||
|
assert_eq!(f.buffered(), MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
assert_too_large!(f.push(b"a"), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
|
||||||
|
|
||||||
|
// One push over the cap.
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
assert_too_large!(
|
||||||
|
f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES + 1]),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES,
|
||||||
|
MAX_RTSP_MESSAGE_BYTES + 1
|
||||||
|
);
|
||||||
|
|
||||||
|
// A whole message of exactly the cap is fine.
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
let m = response_of_size(MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
f.push(&m).unwrap();
|
||||||
|
assert_eq!(f.next_message().unwrap(), Some(m));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pushes `bytes` and asks for a message; the first error from either call.
|
||||||
|
fn push_then_next(f: &mut RtspFramer, bytes: &[u8]) -> domistream::Result<Option<Vec<u8>>> {
|
||||||
|
f.push(bytes)?;
|
||||||
|
f.next_message()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framer_refuses_lying_content_length_early() {
|
||||||
|
// The header says the message will be over the cap: refused now, without waiting for (or buffering) it.
|
||||||
|
for cl in ["65537", "4294967295", "18446744073709551615"] {
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
let r = push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"x"));
|
||||||
|
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{cl}: {r:?}");
|
||||||
|
}
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
assert_cap!(
|
||||||
|
push_then_next(&mut f, &response("200 OK", &[("Content-Length", "65537")], b"")),
|
||||||
|
MAX_RTSP_MESSAGE_BYTES
|
||||||
|
);
|
||||||
|
for cl in ["abc", "-1", "1 2"] {
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
assert_err!(
|
||||||
|
push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"")),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"{cl}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn framer_empty_pushes() {
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
f.push(b"").unwrap();
|
||||||
|
assert_eq!(f.next_message().unwrap(), None);
|
||||||
|
assert_eq!(f.finish().unwrap(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Any chunking of a stream of messages yields the same messages.
|
||||||
|
#[test]
|
||||||
|
fn framer_is_chunking_invariant(bodies in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..300), 1..6), cuts in proptest::collection::vec(1usize..200, 1..50)) {
|
||||||
|
let msgs: Vec<Vec<u8>> = bodies.iter().enumerate()
|
||||||
|
.map(|(i, b)| response("200 OK", &[("CSeq", &i.to_string()), ("Content-Length", &b.len().to_string())], b))
|
||||||
|
.collect();
|
||||||
|
let stream = msgs.concat();
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
let mut got = Vec::new();
|
||||||
|
let mut pos = 0;
|
||||||
|
let mut cut = cuts.iter().cycle();
|
||||||
|
while pos < stream.len() {
|
||||||
|
let end = (pos + cut.next().copied().unwrap_or(1)).min(stream.len());
|
||||||
|
f.push(&stream[pos..end]).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
|
||||||
|
while let Some(m) = f.next_message().map_err(|e| TestCaseError::fail(format!("{e:?}")))? {
|
||||||
|
got.push(m);
|
||||||
|
}
|
||||||
|
prop_assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
pos = end;
|
||||||
|
}
|
||||||
|
prop_assert_eq!(got, msgs);
|
||||||
|
prop_assert_eq!(f.finish(), Ok(None));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ SDP
|
||||||
|
|
||||||
|
const DESCRIBE_SDP: &str = "v=0\r\no=- 0 14 IN IPv4 0.0.0.0\r\ns=Lab host\r\n\
|
||||||
|
a=x-ss-general.featureFlags:3\r\n\
|
||||||
|
a=x-ss-general.encryptionSupported:7\r\n\
|
||||||
|
a=x-nv-video[0].refPicInvalidation:1\r\n\
|
||||||
|
a=rtpmap:98 AV1/90000\r\n\
|
||||||
|
a=fmtp:96 packetization-mode=1\r\n\
|
||||||
|
sprop-parameter-sets=AAAAAU\r\n\
|
||||||
|
a=fmtp:97 surround-params=21101\r\n\
|
||||||
|
a=fmtp:97 surround-params=642012345\r\n\
|
||||||
|
a=fmtp:97 surround-params=85301234567\r\n\
|
||||||
|
a=recvonly\r\n";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sdp_sample() {
|
||||||
|
let s = sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap();
|
||||||
|
assert_eq!(s.attribute("x-ss-general.featureFlags"), Some("3"));
|
||||||
|
assert_eq!(s.attribute("rtpmap"), Some("98 AV1/90000"));
|
||||||
|
assert_eq!(s.attribute("fmtp"), Some("96 packetization-mode=1"), "first one wins");
|
||||||
|
assert_eq!(s.attribute("recvonly"), Some(""), "flag attribute");
|
||||||
|
assert_eq!(s.attributes.iter().filter(|(n, _)| n == "fmtp").count(), 4);
|
||||||
|
assert_eq!(s.other[0], ('v', "0".to_string()));
|
||||||
|
assert!(s.other.iter().any(|(t, v)| *t == '\0' && v.contains("sprop-parameter-sets")), "{:?}", s.other);
|
||||||
|
// LF-only line ends give the same result.
|
||||||
|
assert_eq!(sdp::parse_sdp(DESCRIBE_SDP.replace("\r\n", "\n").as_bytes()).unwrap(), s);
|
||||||
|
assert_eq!(sdp::parse_sdp(b"").unwrap(), sdp::Sdp::default());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sdp_hostile() {
|
||||||
|
for (bad, why) in [
|
||||||
|
(&b"v=0\r\nno equals sign\r\n"[..], "line without ="),
|
||||||
|
(b"a=x:\xff\r\n", "not UTF-8"),
|
||||||
|
(b"=x\r\n", "empty type"),
|
||||||
|
] {
|
||||||
|
assert_err!(sdp::parse_sdp(bad), Error::Malformed { .. }, "{why}");
|
||||||
|
}
|
||||||
|
let lines = |n: usize| "a=x:1\n".repeat(n);
|
||||||
|
assert_eq!(sdp::parse_sdp(lines(MAX_SDP_LINES).as_bytes()).unwrap().attributes.len(), MAX_SDP_LINES);
|
||||||
|
assert_cap!(sdp::parse_sdp(lines(MAX_SDP_LINES + 1).as_bytes()), MAX_SDP_LINES);
|
||||||
|
let sized = |n: usize| {
|
||||||
|
let mut s = "a=pad:".to_string();
|
||||||
|
s.push_str(&"p".repeat(n - s.len() - 1));
|
||||||
|
s.push('\n');
|
||||||
|
s
|
||||||
|
};
|
||||||
|
for n in [MAX_SDP_BYTES - 1, MAX_SDP_BYTES] {
|
||||||
|
assert!(sdp::parse_sdp(sized(n).as_bytes()).is_ok(), "{n}");
|
||||||
|
}
|
||||||
|
assert_too_large!(sdp::parse_sdp(sized(MAX_SDP_BYTES + 1).as_bytes()), MAX_SDP_BYTES, MAX_SDP_BYTES + 1);
|
||||||
|
assert_too_large!(sdp::parse_sdp(&vec![b'a'; 1 << 20]), MAX_SDP_BYTES, 1 << 20);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn surround_params() {
|
||||||
|
let c = sdp::parse_surround_params("21101").unwrap();
|
||||||
|
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.clone()), (2, 1, 1, vec![0, 1]));
|
||||||
|
let c = sdp::parse_surround_params("642012345").unwrap();
|
||||||
|
assert_eq!((c.channels, c.streams, c.coupled_streams), (6, 4, 2));
|
||||||
|
assert_eq!(c.mapping, vec![0, 1, 2, 3, 4, 5]);
|
||||||
|
let c = sdp::parse_surround_params("85301234567").unwrap();
|
||||||
|
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.len()), (8, 5, 3, 8));
|
||||||
|
let c = sdp::parse_surround_params("11000").unwrap_err();
|
||||||
|
assert!(matches!(c, Error::Malformed { .. }), "one channel needs one mapping digit, not two");
|
||||||
|
assert_eq!(sdp::parse_surround_params("1100").unwrap().mapping, vec![0]);
|
||||||
|
|
||||||
|
for (bad, why) in [
|
||||||
|
("", "empty"),
|
||||||
|
("2", "cut"),
|
||||||
|
("2110", "one mapping digit short"),
|
||||||
|
("211012", "one mapping digit too many"),
|
||||||
|
("21102", "mapping 2 >= streams + coupled"),
|
||||||
|
("21201", "coupled > streams"),
|
||||||
|
("01100", "zero channels"),
|
||||||
|
("20001", "zero streams"),
|
||||||
|
("2a101", "not a digit"),
|
||||||
|
("2 1101", "space"),
|
||||||
|
("9530123456789", "9 channels > MAX_AUDIO_CHANNELS"),
|
||||||
|
("-2110", "sign"),
|
||||||
|
] {
|
||||||
|
assert_err!(sdp::parse_surround_params(bad), Error::Malformed { .. }, "{why}: {bad:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn host_capabilities() {
|
||||||
|
let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
|
||||||
|
assert_eq!(caps.encryption_supported, EncryptionFlags(7));
|
||||||
|
assert_eq!(caps.feature_flags.0, 3);
|
||||||
|
assert!(caps.reference_frame_invalidation);
|
||||||
|
assert!(caps.av1);
|
||||||
|
assert_eq!(caps.opus_configs.len(), 3);
|
||||||
|
assert_eq!(caps.opus_configs[0].mapping, vec![0, 1]);
|
||||||
|
|
||||||
|
let none = HostCapabilities::from_sdp(&sdp::parse_sdp(b"v=0\n").unwrap()).unwrap();
|
||||||
|
assert_eq!(none, HostCapabilities::default());
|
||||||
|
|
||||||
|
for bad in [
|
||||||
|
"a=x-ss-general.encryptionSupported:x\n",
|
||||||
|
"a=x-ss-general.encryptionSupported:256\n",
|
||||||
|
"a=x-ss-general.featureFlags:-1\n",
|
||||||
|
"a=fmtp:97 surround-params=2110\n",
|
||||||
|
"a=fmtp:97 surround-params=\n",
|
||||||
|
] {
|
||||||
|
let s = sdp::parse_sdp(bad.as_bytes()).unwrap();
|
||||||
|
assert_err!(HostCapabilities::from_sdp(&s), Error::Malformed { .. }, "{bad:?}");
|
||||||
|
}
|
||||||
|
let many = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS + 1);
|
||||||
|
assert_cap!(HostCapabilities::from_sdp(&sdp::parse_sdp(many.as_bytes()).unwrap()), MAX_OPUS_CONFIGS);
|
||||||
|
let max = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS);
|
||||||
|
assert_eq!(
|
||||||
|
HostCapabilities::from_sdp(&sdp::parse_sdp(max.as_bytes()).unwrap()).unwrap().opus_configs.len(),
|
||||||
|
MAX_OPUS_CONFIGS
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn config() -> StreamConfig {
|
||||||
|
StreamConfig {
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
fps: 60,
|
||||||
|
bitrate_kbps: 20_000,
|
||||||
|
packet_size: 1024,
|
||||||
|
codec: VideoCodec::Hevc,
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
audio_packet_duration_ms: 5,
|
||||||
|
min_fec_packets: 2,
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
encryption: EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn announce_payload() {
|
||||||
|
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
|
||||||
|
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &host).unwrap()).expect("ANNOUNCE is valid SDP");
|
||||||
|
assert_eq!(s.attribute("x-nv-video[0].clientViewportWd"), Some("1920"));
|
||||||
|
assert_eq!(s.attribute("x-nv-video[0].clientViewportHt"), Some("1080"));
|
||||||
|
assert_eq!(s.attribute("x-nv-video[0].maxFPS"), Some("60"));
|
||||||
|
assert_eq!(s.attribute("x-nv-video[0].packetSize"), Some("1024"));
|
||||||
|
assert_eq!(s.attribute("x-ml-video.configuredBitrateKbps"), Some("20000"));
|
||||||
|
assert_eq!(s.attribute("x-nv-aqos.packetDuration"), Some("5"));
|
||||||
|
assert_eq!(s.attribute("x-nv-vqos[0].fec.minRequiredFecPackets"), Some("2"));
|
||||||
|
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
|
||||||
|
|
||||||
|
// Only what both sides support is turned on.
|
||||||
|
let mut partial = host.clone();
|
||||||
|
partial.encryption_supported = EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::AUDIO);
|
||||||
|
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &partial).unwrap()).unwrap();
|
||||||
|
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("5"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn announce_refuses_what_the_host_lacks() {
|
||||||
|
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
|
||||||
|
let mut no_v2 = host.clone();
|
||||||
|
no_v2.encryption_supported = EncryptionFlags(EncryptionFlags::VIDEO | EncryptionFlags::AUDIO);
|
||||||
|
assert_err!(sdp::build_announce(&config(), &no_v2), Error::Unsupported { .. });
|
||||||
|
let mut no_av1 = host.clone();
|
||||||
|
no_av1.av1 = false;
|
||||||
|
assert_err!(
|
||||||
|
sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &no_av1),
|
||||||
|
Error::Unsupported { .. }
|
||||||
|
);
|
||||||
|
assert!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &host).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ client
|
||||||
|
|
||||||
|
const URL: &str = "rtsp://192.0.2.10:48010";
|
||||||
|
|
||||||
|
fn describe_answer(cseq: u32, sdp: &str) -> Vec<u8> {
|
||||||
|
response("200 OK", &[("CSeq", &cseq.to_string()), ("Content-Length", &sdp.len().to_string())], sdp.as_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup_answer(cseq: u32, port: &str) -> Vec<u8> {
|
||||||
|
response(
|
||||||
|
"200 OK",
|
||||||
|
&[
|
||||||
|
("CSeq", &cseq.to_string()),
|
||||||
|
("Session", "DEADBEEFCAFE;timeout = 90"),
|
||||||
|
("Transport", &format!("server_port={port}")),
|
||||||
|
],
|
||||||
|
b"",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ok_answer(cseq: u32) -> Vec<u8> {
|
||||||
|
response("200 OK", &[("CSeq", &cseq.to_string())], b"")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn next_request(c: &mut RtspClient) -> RtspRequest {
|
||||||
|
let bytes = c.poll_request().expect("a request is due");
|
||||||
|
assert_eq!(c.poll_request(), None, "each request is returned once");
|
||||||
|
parse_request(&bytes).expect("the client's request parses")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn cseq(r: &RtspRequest) -> u32 {
|
||||||
|
r.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("cseq")).expect("CSeq").1.parse().expect("CSeq number")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_full_negotiation() {
|
||||||
|
let mut c = RtspClient::new(URL, config()).unwrap();
|
||||||
|
assert_eq!(c.state(), RtspClientState::Options);
|
||||||
|
let expect = [
|
||||||
|
(Method::Options, RtspClientState::Describe),
|
||||||
|
(Method::Describe, RtspClientState::SetupAudio),
|
||||||
|
(Method::Setup, RtspClientState::SetupVideo),
|
||||||
|
(Method::Setup, RtspClientState::SetupControl),
|
||||||
|
(Method::Setup, RtspClientState::Announce),
|
||||||
|
(Method::Announce, RtspClientState::Play),
|
||||||
|
];
|
||||||
|
let mut last_cseq = 0;
|
||||||
|
let streams = ["streamid=audio", "streamid=video", "streamid=control"];
|
||||||
|
for (i, (method, next_state)) in expect.iter().enumerate() {
|
||||||
|
let req = next_request(&mut c);
|
||||||
|
assert_eq!(req.method, *method, "request {i}");
|
||||||
|
let n = cseq(&req);
|
||||||
|
assert!(n > last_cseq, "CSeq counts up");
|
||||||
|
last_cseq = n;
|
||||||
|
if *method == Method::Setup {
|
||||||
|
assert!(req.target.contains(streams[i - 2]), "SETUP {} target {:?}", i - 2, req.target);
|
||||||
|
assert!(req.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("transport")), "SETUP has Transport");
|
||||||
|
}
|
||||||
|
if *method == Method::Announce {
|
||||||
|
let s = sdp::parse_sdp(&req.body).unwrap();
|
||||||
|
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
|
||||||
|
}
|
||||||
|
let answer = match i {
|
||||||
|
1 => describe_answer(n, DESCRIBE_SDP),
|
||||||
|
2 => setup_answer(n, "48000"),
|
||||||
|
3 => setup_answer(n, "47998"),
|
||||||
|
4 => setup_answer(n, "47999"),
|
||||||
|
_ => ok_answer(n),
|
||||||
|
};
|
||||||
|
assert_eq!(c.handle_response(&answer).unwrap(), RtspProgress::Continue);
|
||||||
|
assert_eq!(c.state(), *next_state);
|
||||||
|
}
|
||||||
|
let play = next_request(&mut c);
|
||||||
|
assert_eq!(play.method, Method::Play);
|
||||||
|
match c.handle_response(&ok_answer(cseq(&play))).unwrap() {
|
||||||
|
RtspProgress::Ready(n) => {
|
||||||
|
assert_eq!((n.ports.audio, n.ports.video, n.ports.control), (48000, 47998, 47999));
|
||||||
|
assert_eq!(n.encryption, EncryptionFlags(7));
|
||||||
|
assert_eq!(n.opus.mapping, vec![0, 1]);
|
||||||
|
assert_eq!(n.opus.channels, 2);
|
||||||
|
assert_eq!(n.session_id.as_deref(), Some("DEADBEEFCAFE"));
|
||||||
|
assert!(n.host.av1);
|
||||||
|
assert!(!n.ping_payload.is_empty());
|
||||||
|
}
|
||||||
|
RtspProgress::Continue => panic!("PLAY answered: expected Ready"),
|
||||||
|
}
|
||||||
|
assert_eq!(c.state(), RtspClientState::Ready);
|
||||||
|
assert_eq!(c.poll_request(), None);
|
||||||
|
assert_err!(c.handle_response(&ok_answer(last_cseq + 2)), Error::State { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs the negotiation, answering with `answers(i, cseq)`; returns the first error and the state then.
|
||||||
|
fn run_until_error(answers: impl Fn(usize, u32) -> Vec<u8>) -> (Error, RtspClientState) {
|
||||||
|
let mut c = RtspClient::new(URL, config()).unwrap();
|
||||||
|
for i in 0..7 {
|
||||||
|
let req = next_request(&mut c);
|
||||||
|
if let Err(e) = c.handle_response(&answers(i, cseq(&req))) {
|
||||||
|
return (e, c.state());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
panic!("negotiation finished without an error");
|
||||||
|
}
|
||||||
|
|
||||||
|
fn good(i: usize, n: u32) -> Vec<u8> {
|
||||||
|
match i {
|
||||||
|
1 => describe_answer(n, DESCRIBE_SDP),
|
||||||
|
2 => setup_answer(n, "48000"),
|
||||||
|
3 => setup_answer(n, "47998"),
|
||||||
|
4 => setup_answer(n, "47999"),
|
||||||
|
_ => ok_answer(n),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_refuses_hostile_answers() {
|
||||||
|
let (e, s) = run_until_error(|i, n| if i == 1 { ok_answer(n + 1) } else { good(i, n) });
|
||||||
|
assert!(matches!(e, Error::Malformed { .. }), "CSeq mismatch: {e:?}");
|
||||||
|
assert_eq!(s, RtspClientState::Failed);
|
||||||
|
|
||||||
|
let (e, s) =
|
||||||
|
run_until_error(
|
||||||
|
|i, n| if i == 1 { response("404 Not Found", &[("CSeq", &n.to_string())], b"") } else { good(i, n) },
|
||||||
|
);
|
||||||
|
assert_eq!(e, Error::HostStatus { code: 404 });
|
||||||
|
assert_eq!(s, RtspClientState::Failed);
|
||||||
|
|
||||||
|
let no_v2 = DESCRIBE_SDP.replace("encryptionSupported:7", "encryptionSupported:6");
|
||||||
|
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, &no_v2) } else { good(i, n) });
|
||||||
|
assert!(matches!(e, Error::Unsupported { .. }), "host without control V2: {e:?}");
|
||||||
|
|
||||||
|
for port in ["0", "70000", "abc", ""] {
|
||||||
|
let (e, s) = run_until_error(|i, n| if i == 3 { setup_answer(n, port) } else { good(i, n) });
|
||||||
|
assert!(matches!(e, Error::Malformed { .. }), "server_port={port:?}: {e:?}");
|
||||||
|
assert_eq!(s, RtspClientState::Failed);
|
||||||
|
}
|
||||||
|
let (e, _) = run_until_error(|i, n| if i == 2 { ok_answer(n) } else { good(i, n) });
|
||||||
|
assert!(matches!(e, Error::Malformed { .. }), "SETUP answer without Transport: {e:?}");
|
||||||
|
|
||||||
|
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, "v=0\nbroken line\n") } else { good(i, n) });
|
||||||
|
assert!(matches!(e, Error::Malformed { .. }), "bad SDP: {e:?}");
|
||||||
|
|
||||||
|
let (e, _) = run_until_error(|i, n| if i == 0 { b"garbage".to_vec() } else { good(i, n) });
|
||||||
|
assert!(matches!(e, Error::Malformed { .. }), "garbage: {e:?}");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_answer_without_request() {
|
||||||
|
let mut c = RtspClient::new(URL, config()).unwrap();
|
||||||
|
let req = next_request(&mut c);
|
||||||
|
c.handle_response(&ok_answer(cseq(&req))).unwrap();
|
||||||
|
// DESCRIBE is due but its answer arrives twice.
|
||||||
|
let d = next_request(&mut c);
|
||||||
|
c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)).unwrap();
|
||||||
|
assert_err!(c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)), Error::State { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn client_refuses_bad_setup() {
|
||||||
|
for url in
|
||||||
|
["http://192.0.2.10:48010", "rtsp://192.0.2.10", "rtsp://:48010", "", "rtsp://h:99999", "rtsp://h:1\r\nX: y"]
|
||||||
|
{
|
||||||
|
assert_err!(RtspClient::new(url, config()), Error::Malformed { .. }, "{url:?}");
|
||||||
|
}
|
||||||
|
for broken in [
|
||||||
|
StreamConfig { width: 0, ..config() },
|
||||||
|
StreamConfig { height: 0, ..config() },
|
||||||
|
StreamConfig { fps: 0, ..config() },
|
||||||
|
StreamConfig { bitrate_kbps: 0, ..config() },
|
||||||
|
StreamConfig { packet_size: 0, ..config() },
|
||||||
|
] {
|
||||||
|
assert_err!(RtspClient::new(URL, broken), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
}
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,670 @@
|
|||||||
|
//! The video depacketizer (`docs/PROTOCOL.md` 5) driven with generated loss patterns over multi-block frames:
|
||||||
|
//! random, bursty, all parity lost, all data lost but recoverable, last packet lost, reordered, duplicated,
|
||||||
|
//! sequence and frame index wraps, far-past and far-future packets, encryption. Every frame comes out byte-exact or
|
||||||
|
//! is reported in a `FrameLost` range; never a corrupt frame.
|
||||||
|
//!
|
||||||
|
//! The test host (`common::VideoHost`) packetizes as PROTOCOL.md 5.2-5.3 say, computes parity with the crate's own
|
||||||
|
//! `ReedSolomon::new` (U14 is unknown; `fec.rs` tests the code itself) and writes the parity packets' headers after
|
||||||
|
//! the parity, so bytes 0-31 of any recovered data shard are garbage.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet, HashMap};
|
||||||
|
|
||||||
|
use common::{SeqRng, VExpect, VPkt, VideoHost, fec_info, video_packet_bytes};
|
||||||
|
use domistream::video::packet::MAX_VIDEO_PACKET_BYTES;
|
||||||
|
use domistream::video::{MAX_FRAMES_IN_FLIGHT, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent, VideoStats};
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const PACKET_SIZE: u16 = 64; // payload 48 bytes, packet 80 bytes
|
||||||
|
const TIMEOUT: Duration = Duration::from_millis(50);
|
||||||
|
const KEY: [u8; 16] = *b"video-test-key!!";
|
||||||
|
|
||||||
|
fn config(cipher: bool) -> VideoConfig {
|
||||||
|
VideoConfig { packet_size: PACKET_SIZE, cipher: cipher.then(|| VideoCipher::new(KEY)), frame_timeout: TIMEOUT }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One frame of a scenario: its packets as sent and what must come out.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Frame {
|
||||||
|
packets: Vec<VPkt>,
|
||||||
|
expect: VExpect,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frames(rng: &mut SeqRng, host: &mut VideoHost, first_index: u32, n: usize, percentages: &[u8]) -> Vec<Frame> {
|
||||||
|
(0..n)
|
||||||
|
.map(|i| {
|
||||||
|
let len = 10 + rng.below(48 * 14);
|
||||||
|
let bitstream = VideoHost::bitstream(rng, len);
|
||||||
|
let pct = percentages[rng.below(percentages.len())];
|
||||||
|
let blocks = 1 + rng.below(4);
|
||||||
|
let (packets, expect) = host.frame(first_index.wrapping_add(i as u32), &bitstream, pct, blocks);
|
||||||
|
Frame { packets, expect }
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
enum Outcome {
|
||||||
|
Deliver,
|
||||||
|
Lose,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a frame can be rebuilt from the packets that arrive (by shard identity, duplicates counted once).
|
||||||
|
fn outcome(frame: &Frame, arrived: &[&VPkt]) -> Outcome {
|
||||||
|
let mut have: BTreeMap<u8, BTreeSet<u16>> = BTreeMap::new();
|
||||||
|
for p in arrived {
|
||||||
|
have.entry(p.block).or_default().insert(p.shard_index);
|
||||||
|
}
|
||||||
|
let blocks: BTreeMap<u8, u16> = frame.packets.iter().map(|p| (p.block, p.data_shards)).collect();
|
||||||
|
if blocks.iter().all(|(b, k)| have.get(b).map_or(0, BTreeSet::len) >= usize::from(*k)) {
|
||||||
|
Outcome::Deliver
|
||||||
|
} else {
|
||||||
|
Outcome::Lose
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Data shards a frame lost (what `recovered_shards` must say when it is delivered).
|
||||||
|
fn data_lost(frame: &Frame, arrived: &[&VPkt]) -> u16 {
|
||||||
|
let got: BTreeSet<(u8, u16)> = arrived.iter().map(|p| (p.block, p.shard_index)).collect();
|
||||||
|
frame.packets.iter().filter(|p| !p.is_parity && !got.contains(&(p.block, p.shard_index))).count() as u16
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Run {
|
||||||
|
events: Vec<VideoEvent>,
|
||||||
|
stats: VideoStats,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run_with(cipher: bool, datagrams: &[Vec<u8>]) -> Run {
|
||||||
|
let mut d = VideoDepacketizer::new(config(cipher)).expect("VideoDepacketizer::new");
|
||||||
|
let mut now = 1_000_000u64;
|
||||||
|
let mut events = Vec::new();
|
||||||
|
for g in datagrams {
|
||||||
|
d.push(Instant::from_micros(now), g).expect("push never fails for packets within the size cap");
|
||||||
|
now += 10;
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Flush: let every incomplete frame time out.
|
||||||
|
for _ in 0..64 {
|
||||||
|
now += 10_000_000;
|
||||||
|
d.handle_timeout(Instant::from_micros(now)).unwrap();
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
events.push(e);
|
||||||
|
}
|
||||||
|
if d.poll_timeout().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Run { events, stats: d.stats() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every Frame event is byte-exact, in order, at most once; every frame marked `Deliver` came out; every frame marked
|
||||||
|
/// `Lose` is in a FrameLost range; nothing is both.
|
||||||
|
fn check(frames: &[Frame], outcomes: &[Outcome], recovered: Option<&[u16]>, run: &Run) {
|
||||||
|
let pos: HashMap<u32, usize> = frames.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect();
|
||||||
|
let mut delivered = vec![false; frames.len()];
|
||||||
|
let mut lost = vec![false; frames.len()];
|
||||||
|
let mut last_pos: Option<usize> = None;
|
||||||
|
for e in &run.events {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => {
|
||||||
|
let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index));
|
||||||
|
let want = &frames[i].expect;
|
||||||
|
assert!(
|
||||||
|
f.bitstream == want.bitstream,
|
||||||
|
"frame {} corrupt: {} bytes, want {}",
|
||||||
|
f.frame_index,
|
||||||
|
f.bitstream.len(),
|
||||||
|
want.bitstream.len()
|
||||||
|
);
|
||||||
|
assert_eq!(f.header.raw, want.header, "frame {} header", f.frame_index);
|
||||||
|
assert_eq!(f.rtp_timestamp, want.rtp_timestamp, "frame {} timestamp", f.frame_index);
|
||||||
|
assert!(f.completed_at >= f.first_packet_at);
|
||||||
|
assert!(!delivered[i], "frame {} delivered twice", f.frame_index);
|
||||||
|
assert!(last_pos.is_none_or(|l| i > l), "frame {} out of order", f.frame_index);
|
||||||
|
if let Some(r) = recovered {
|
||||||
|
assert_eq!(f.recovered_shards, r[i], "frame {} recovered shards", f.frame_index);
|
||||||
|
}
|
||||||
|
last_pos = Some(i);
|
||||||
|
delivered[i] = true;
|
||||||
|
}
|
||||||
|
VideoEvent::FrameLost { first, last } => {
|
||||||
|
let span = last.wrapping_sub(*first);
|
||||||
|
assert!(span < 1 << 31, "FrameLost {first}..={last} is not a forward range");
|
||||||
|
for (i, f) in frames.iter().enumerate() {
|
||||||
|
if f.expect.frame_index.wrapping_sub(*first) <= span {
|
||||||
|
lost[i] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (i, f) in frames.iter().enumerate() {
|
||||||
|
let idx = f.expect.frame_index;
|
||||||
|
assert!(!(delivered[i] && lost[i]), "frame {idx} both delivered and reported lost");
|
||||||
|
match outcomes[i] {
|
||||||
|
Outcome::Deliver => {
|
||||||
|
assert!(delivered[i], "frame {idx} was recoverable but not delivered (lost: {})", lost[i])
|
||||||
|
}
|
||||||
|
Outcome::Lose => assert!(lost[i], "frame {idx} was not recoverable but not reported lost"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Runs a scenario where `keep(frame_number, packet_number_in_frame, packet)` decides what arrives (frames 0 and
|
||||||
|
/// last are always kept whole), optionally reordered and duplicated.
|
||||||
|
fn scenario(
|
||||||
|
seed: u64,
|
||||||
|
n: usize,
|
||||||
|
percentages: &[u8],
|
||||||
|
keep: impl Fn(&mut SeqRng, usize, usize, &VPkt) -> bool,
|
||||||
|
) -> (Vec<Frame>, Vec<Outcome>, Vec<u16>, Vec<Vec<u8>>) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, n, percentages);
|
||||||
|
let mut outcomes = Vec::new();
|
||||||
|
let mut recovered = Vec::new();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let arrived: Vec<&VPkt> = f
|
||||||
|
.packets
|
||||||
|
.iter()
|
||||||
|
.enumerate()
|
||||||
|
.filter(|(pi, p)| fi == 0 || fi == n - 1 || keep(&mut rng, fi, *pi, p))
|
||||||
|
.map(|(_, p)| p)
|
||||||
|
.collect();
|
||||||
|
outcomes.push(outcome(f, &arrived));
|
||||||
|
recovered.push(data_lost(f, &arrived));
|
||||||
|
datagrams.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
(fs, outcomes, recovered, datagrams)
|
||||||
|
}
|
||||||
|
|
||||||
|
const MIXED: &[u8] = &[0, 10, 20, 50, 100, 200];
|
||||||
|
|
||||||
|
// ================================================================================================ patterns
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_loss() {
|
||||||
|
let (fs, out, rec, dg) = scenario(1, 30, MIXED, |_, _, _, _| true);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
assert_eq!(r.stats.frames, 30);
|
||||||
|
assert_eq!(r.stats.frames_lost, 0);
|
||||||
|
assert_eq!(r.stats.shards_recovered, 0);
|
||||||
|
assert_eq!(r.stats.packets_dropped, 0);
|
||||||
|
assert_eq!(r.stats.packets, dg.len() as u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn random_loss() {
|
||||||
|
for (seed, p) in [(10u64, 5usize), (11, 15), (12, 30), (13, 50), (14, 15), (15, 30)] {
|
||||||
|
let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= p);
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
let delivered = out.iter().filter(|o| **o == Outcome::Deliver).count() as u64;
|
||||||
|
assert_eq!(r.stats.frames, delivered, "seed {seed}");
|
||||||
|
// At least the shards of delivered frames; blocks rebuilt inside frames that were lost anyway may add more.
|
||||||
|
assert!(
|
||||||
|
r.stats.shards_recovered
|
||||||
|
>= rec
|
||||||
|
.iter()
|
||||||
|
.zip(&out)
|
||||||
|
.filter(|(_, o)| **o == Outcome::Deliver)
|
||||||
|
.map(|(r, _)| u64::from(*r))
|
||||||
|
.sum::<u64>()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bursty_loss() {
|
||||||
|
for seed in 20..26u64 {
|
||||||
|
// One burst of 1..=8 consecutive packets per frame, at a random place.
|
||||||
|
let mut rng = SeqRng::new(seed * 7);
|
||||||
|
let bursts: Vec<(usize, usize)> = (0..40).map(|_| (rng.below(30), 1 + rng.below(8))).collect();
|
||||||
|
let (fs, out, rec, dg) = scenario(seed, 40, MIXED, move |_, fi, pi, _| {
|
||||||
|
let (start, len) = bursts[fi];
|
||||||
|
!(start..start + len).contains(&pi)
|
||||||
|
});
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
// A burst across a frame boundary: the tail of one frame and the head of the next.
|
||||||
|
let (fs, _, _, _) = scenario(27, 3, &[50], |_, _, _, _| true);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut arrived: Vec<Vec<&VPkt>> = vec![Vec::new(); 3];
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
for (pi, p) in f.packets.iter().enumerate() {
|
||||||
|
let tail = fi == 1 && pi + 2 >= f.packets.len();
|
||||||
|
let head = fi == 2 && pi < 2;
|
||||||
|
if !(tail || head) {
|
||||||
|
arrived[fi].push(p);
|
||||||
|
dg.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let out: Vec<Outcome> = fs.iter().zip(&arrived).map(|(f, a)| outcome(f, a)).collect();
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_parity_lost() {
|
||||||
|
let (fs, out, rec, dg) = scenario(30, 30, &[20, 50, 100], |_, _, _, p| !p.is_parity);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
assert!(rec.iter().all(|r| *r == 0));
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_data_lost_but_recoverable() {
|
||||||
|
// 100 % and 200 % FEC: every data shard of a frame lost, rebuilt from parity alone.
|
||||||
|
let (fs, out, rec, dg) = scenario(31, 20, &[100, 200], |_, _, _, p| p.is_parity);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
assert!(r.stats.shards_recovered > 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn last_packet_lost() {
|
||||||
|
// The last packet of each frame (its last parity packet, or the end-of-frame data packet without FEC).
|
||||||
|
let (fs, ..) = scenario(32, 30, MIXED, |_, _, _, _| true);
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
let mut outcomes = Vec::new();
|
||||||
|
let mut recovered = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let n = f.packets.len();
|
||||||
|
let arrived: Vec<&VPkt> =
|
||||||
|
f.packets.iter().take(if fi == 0 || fi + 1 == fs.len() { n } else { n - 1 }).collect();
|
||||||
|
outcomes.push(outcome(f, &arrived));
|
||||||
|
recovered.push(data_lost(f, &arrived));
|
||||||
|
datagrams.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
check(&fs, &outcomes, Some(&recovered), &run_with(false, &datagrams));
|
||||||
|
|
||||||
|
// The end-of-frame data packet itself (flags 0x02), with FEC to rebuild it.
|
||||||
|
let (fs, out, rec, dg) = scenario(33, 30, &[20, 50], |_, _, _, p| p.is_parity || p.bytes[24] & 0x02 == 0);
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
|
||||||
|
// ... and without FEC: lost.
|
||||||
|
let (fs, out, rec, dg) = scenario(34, 10, &[0], |_, _, _, p| p.bytes[24] & 0x02 == 0);
|
||||||
|
assert!(out[1..9].iter().all(|o| *o == Outcome::Lose));
|
||||||
|
check(&fs, &out, Some(&rec), &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered() {
|
||||||
|
for seed in 40..46u64 {
|
||||||
|
let (fs, out, _, mut dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10);
|
||||||
|
// Shuffle within windows spanning about two frames.
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let first_len = fs[0].packets.len();
|
||||||
|
let window = 24;
|
||||||
|
let mut i = first_len; // keep frame 0 first so the stream has a known start
|
||||||
|
while i < dg.len() {
|
||||||
|
let end = (i + window).min(dg.len());
|
||||||
|
rng.shuffle(&mut dg[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn duplicated() {
|
||||||
|
for seed in 50..54u64 {
|
||||||
|
let (fs, out, _, dg) = scenario(seed, 30, MIXED, move |rng, _, _, _| rng.below(100) >= 10);
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let mut with_dups = Vec::new();
|
||||||
|
let mut dups = 0u64;
|
||||||
|
for (i, g) in dg.iter().enumerate() {
|
||||||
|
with_dups.push(g.clone());
|
||||||
|
if i > 0 && rng.below(100) < 30 {
|
||||||
|
// Again now, and an earlier packet again later.
|
||||||
|
with_dups.push(g.clone());
|
||||||
|
with_dups.push(dg[rng.below(i)].clone());
|
||||||
|
dups += 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let r = run_with(false, &with_dups);
|
||||||
|
check(&fs, &out, None, &r);
|
||||||
|
assert!(
|
||||||
|
r.stats.packets_dropped >= dups / 2,
|
||||||
|
"duplicates are counted as dropped: {} of {dups}",
|
||||||
|
r.stats.packets_dropped
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered_and_duplicated_with_loss() {
|
||||||
|
for seed in 60..64u64 {
|
||||||
|
let (fs, out, _, dg) = scenario(seed, 40, MIXED, move |rng, _, _, _| rng.below(100) >= 20);
|
||||||
|
let mut rng = SeqRng::new(seed ^ 0xFF);
|
||||||
|
let mut mixed: Vec<Vec<u8>> = dg
|
||||||
|
.iter()
|
||||||
|
.flat_map(|g| if rng.below(5) == 0 { vec![g.clone(), g.clone()] } else { vec![g.clone()] })
|
||||||
|
.collect();
|
||||||
|
let start = fs[0].packets.len();
|
||||||
|
let mut i = start;
|
||||||
|
while i < mixed.len() {
|
||||||
|
let end = (i + 16).min(mixed.len());
|
||||||
|
rng.shuffle(&mut mixed[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &mixed));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ untrusted bytes 0-31
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn recovered_shard_headers_are_not_trusted() {
|
||||||
|
// Parity computed over data shards whose bytes 0-31 were scrambled: a rebuilt shard's RTP and NV header bytes
|
||||||
|
// are guaranteed garbage (wrong frame index, flags, FEC fields). Only its payload and its place from the shard
|
||||||
|
// index may be used.
|
||||||
|
let mut rng = SeqRng::new(70);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
host.scramble_parity_headers = true;
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut rec = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
// Lose the first data shard of every block (often the start-of-frame packet) and, where the budget allows,
|
||||||
|
// the end-of-frame packet.
|
||||||
|
let arrived: Vec<&VPkt> = f
|
||||||
|
.packets
|
||||||
|
.iter()
|
||||||
|
.filter(|p| {
|
||||||
|
fi == 0 || p.is_parity || (p.shard_index != 0 && !(p.bytes[24] & 0x02 != 0 && p.parity_shards >= 2))
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
rec.push(data_lost(f, &arrived));
|
||||||
|
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
assert!(out.iter().all(|o| *o == Outcome::Deliver));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
check(&fs, &out, Some(&rec), &r);
|
||||||
|
assert!(r.stats.shards_recovered >= 30);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ wraps and strays
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rtp_sequence_wraps_inside_frames() {
|
||||||
|
let mut rng = SeqRng::new(80);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
host.next_sequence = 0xFFE0;
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 20, &[20, 50]);
|
||||||
|
assert!(host.next_sequence < 0xFFE0, "the stream passed 0xFFFF -> 0");
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let arrived: Vec<&VPkt> =
|
||||||
|
f.packets.iter().enumerate().filter(|(pi, _)| fi == 0 || pi % 5 != 1).map(|(_, p)| p).collect();
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_index_wraps() {
|
||||||
|
let mut rng = SeqRng::new(81);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, u32::MAX - 5, 12, &[50]);
|
||||||
|
assert_eq!(fs[6].expect.frame_index, 0);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
// Frame 0 (the one after u32::MAX) is entirely lost; the others lose one packet.
|
||||||
|
let arrived: Vec<&VPkt> =
|
||||||
|
if f.expect.frame_index == 0 { vec![] } else { f.packets.iter().skip(usize::from(fi != 0)).collect() };
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
dg.extend(arrived.iter().map(|p| p.bytes.clone()));
|
||||||
|
}
|
||||||
|
assert_eq!(out[6], Outcome::Lose);
|
||||||
|
check(&fs, &out, None, &run_with(false, &dg));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn far_past_and_far_future_packets() {
|
||||||
|
let mut rng = SeqRng::new(82);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 5000, 10, &[50]);
|
||||||
|
let mut dg: Vec<Vec<u8>> = fs[..5].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect();
|
||||||
|
// A stray from long ago, a replay of an already delivered frame, and a lone packet from far ahead.
|
||||||
|
let mut stray = fs[0].packets[0].bytes.clone();
|
||||||
|
stray[20..24].copy_from_slice(&(5000u32 - 1000).to_le_bytes());
|
||||||
|
dg.push(stray);
|
||||||
|
dg.push(fs[1].packets[0].bytes.clone());
|
||||||
|
let mut future = fs[5].packets[0].bytes.clone();
|
||||||
|
future[20..24].copy_from_slice(&(5000u32 + 1_000_000).to_le_bytes());
|
||||||
|
dg.push(future);
|
||||||
|
dg.extend(fs[5..].iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())));
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
assert!(r.stats.packets_dropped >= 2, "the far-past stray and the replay are dropped: {:?}", r.stats);
|
||||||
|
// Whatever the far-future packet does, no frame comes out corrupt, none twice, and none out of order.
|
||||||
|
let pos: HashMap<u32, usize> = fs.iter().enumerate().map(|(i, f)| (f.expect.frame_index, i)).collect();
|
||||||
|
let mut seen = BTreeSet::new();
|
||||||
|
let mut prev = None;
|
||||||
|
for e in &r.events {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => {
|
||||||
|
let &i = pos.get(&f.frame_index).unwrap_or_else(|| panic!("frame {} was never sent", f.frame_index));
|
||||||
|
assert_eq!(f.bitstream, fs[i].expect.bitstream);
|
||||||
|
assert!(seen.insert(i));
|
||||||
|
assert!(prev.is_none_or(|l| i > l));
|
||||||
|
prev = Some(i);
|
||||||
|
}
|
||||||
|
VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(*first) < 1 << 31),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!((0..5).all(|i| seen.contains(&i)), "frames before the strays are delivered");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_packets_inside_a_frame_are_dropped_not_used() {
|
||||||
|
let mut rng = SeqRng::new(83);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 6, &[50]);
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
for f in &fs {
|
||||||
|
for p in &f.packets {
|
||||||
|
dg.push(p.bytes.clone());
|
||||||
|
}
|
||||||
|
// Junk carrying the frame's own index: short, long, with impossible FEC fields.
|
||||||
|
let mut short = f.packets[0].bytes.clone();
|
||||||
|
short.truncate(50);
|
||||||
|
let mut long = f.packets[0].bytes.clone();
|
||||||
|
long.extend_from_slice(&[0xEE; 7]);
|
||||||
|
let bad_fec = video_packet_bytes(0, 0, f.expect.frame_index, 0x01, 0, fec_info(50, 900, 2), &[0xEE; 48]);
|
||||||
|
dg.extend([short, long, bad_fec, vec![], vec![0x90]]);
|
||||||
|
}
|
||||||
|
let r = run_with(false, &dg);
|
||||||
|
let out = vec![Outcome::Deliver; fs.len()];
|
||||||
|
check(&fs, &out, None, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= 5 * fs.len() as u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ encryption
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encrypted_stream_with_loss_and_tampering() {
|
||||||
|
let mut rng = SeqRng::new(90);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 30, &[50, 100]);
|
||||||
|
let mut counter = 0u64;
|
||||||
|
let mut dg = Vec::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut tampered = 0u64;
|
||||||
|
for (fi, f) in fs.iter().enumerate() {
|
||||||
|
let mut arrived = Vec::new();
|
||||||
|
for (pi, p) in f.packets.iter().enumerate() {
|
||||||
|
let mut e = common::video_encrypt(&KEY, counter, f.expect.frame_index, &p.bytes);
|
||||||
|
counter += 1;
|
||||||
|
if fi != 0 && pi == 1 {
|
||||||
|
// A flipped ciphertext byte: the tag fails, the packet counts as lost.
|
||||||
|
let last = e.len() - 1;
|
||||||
|
e[last] ^= 0x01;
|
||||||
|
tampered += 1;
|
||||||
|
} else if fi != 0 && rng.below(100) < 10 {
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
arrived.push(p);
|
||||||
|
}
|
||||||
|
dg.push(e);
|
||||||
|
}
|
||||||
|
out.push(outcome(f, &arrived));
|
||||||
|
}
|
||||||
|
let r = run_with(true, &dg);
|
||||||
|
check(&fs, &out, None, &r);
|
||||||
|
assert!(r.stats.packets_dropped >= tampered);
|
||||||
|
// The same plaintext packets fed to a receiver that expects encryption are refused, not decoded.
|
||||||
|
let plain: Vec<Vec<u8>> = fs.iter().flat_map(|f| f.packets.iter().map(|p| p.bytes.clone())).collect();
|
||||||
|
let r = run_with(true, &plain);
|
||||||
|
assert!(r.events.iter().all(|e| !matches!(e, VideoEvent::Frame(_))));
|
||||||
|
assert_eq!(r.stats.packets_dropped, plain.len() as u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ API edges
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_bounds() {
|
||||||
|
for ps in [0u16, 1, 15] {
|
||||||
|
assert_err!(
|
||||||
|
VideoDepacketizer::new(VideoConfig { packet_size: ps, ..config(false) }),
|
||||||
|
Error::Malformed { .. },
|
||||||
|
"packet_size {ps}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let max = (MAX_VIDEO_PACKET_BYTES - 16) as u16;
|
||||||
|
assert!(VideoDepacketizer::new(VideoConfig { packet_size: max, ..config(false) }).is_ok());
|
||||||
|
assert_err!(VideoDepacketizer::new(VideoConfig { packet_size: max + 1, ..config(false) }), Error::Malformed { .. });
|
||||||
|
assert_err!(
|
||||||
|
VideoDepacketizer::new(VideoConfig { packet_size: u16::MAX, ..config(false) }),
|
||||||
|
Error::Malformed { .. }
|
||||||
|
);
|
||||||
|
assert!(VideoDepacketizer::new(VideoConfig { packet_size: 1024, ..config(true) }).is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn push_sizes() {
|
||||||
|
let mut d = VideoDepacketizer::new(config(false)).unwrap();
|
||||||
|
assert_too_large!(
|
||||||
|
d.push(Instant::ZERO, &vec![0; MAX_VIDEO_PACKET_BYTES + 1]),
|
||||||
|
MAX_VIDEO_PACKET_BYTES,
|
||||||
|
MAX_VIDEO_PACKET_BYTES + 1
|
||||||
|
);
|
||||||
|
assert_too_large!(d.push(Instant::ZERO, &vec![0; 1 << 20]), MAX_VIDEO_PACKET_BYTES, 1 << 20);
|
||||||
|
for g in [vec![], vec![0x90], vec![0; 31], vec![0xFF; 80], vec![0; MAX_VIDEO_PACKET_BYTES]] {
|
||||||
|
assert_eq!(d.push(Instant::ZERO, &g), Ok(()));
|
||||||
|
}
|
||||||
|
assert_eq!(d.stats().packets_dropped, 5);
|
||||||
|
assert_eq!(d.poll_event(), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn incomplete_frame_times_out() {
|
||||||
|
let mut rng = SeqRng::new(100);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, 2, &[0]);
|
||||||
|
let mut d = VideoDepacketizer::new(config(false)).unwrap();
|
||||||
|
let t0 = Instant::from_micros(5_000_000);
|
||||||
|
for p in &fs[0].packets {
|
||||||
|
d.push(t0, &p.bytes).unwrap();
|
||||||
|
}
|
||||||
|
match d.poll_event() {
|
||||||
|
Some(VideoEvent::Frame(f)) => {
|
||||||
|
assert_eq!(f.first_packet_at, t0);
|
||||||
|
assert_eq!(f.completed_at, t0);
|
||||||
|
assert_eq!(f.frame_index, 0);
|
||||||
|
}
|
||||||
|
other => panic!("{other:?}"),
|
||||||
|
}
|
||||||
|
assert_eq!(d.poll_timeout(), None, "nothing pending");
|
||||||
|
// Frame 1 without its last packet (no FEC): pending until its timeout.
|
||||||
|
let n = fs[1].packets.len();
|
||||||
|
let t1 = Instant::from_micros(6_000_000);
|
||||||
|
for p in &fs[1].packets[..n - 1] {
|
||||||
|
d.push(t1, &p.bytes).unwrap();
|
||||||
|
}
|
||||||
|
if n == 1 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
assert_eq!(d.poll_event(), None);
|
||||||
|
let deadline = d.poll_timeout().expect("a deadline for the incomplete frame");
|
||||||
|
assert!(deadline > t1 && deadline <= t1.saturating_add(TIMEOUT), "{deadline:?}");
|
||||||
|
d.handle_timeout(t1.saturating_add(TIMEOUT / 2)).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), None, "not before the timeout");
|
||||||
|
d.handle_timeout(t1.saturating_add(TIMEOUT)).unwrap();
|
||||||
|
assert_eq!(d.poll_event(), Some(VideoEvent::FrameLost { first: 1, last: 1 }));
|
||||||
|
assert_eq!(d.stats().frames_lost, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frames_in_flight_are_capped() {
|
||||||
|
// One packet each of many incomplete frames: the oldest are declared lost before any timeout.
|
||||||
|
let mut rng = SeqRng::new(101);
|
||||||
|
let mut host = VideoHost::new(PACKET_SIZE);
|
||||||
|
let fs = frames(&mut rng, &mut host, 0, MAX_FRAMES_IN_FLIGHT + 5, &[0]);
|
||||||
|
let mut d = VideoDepacketizer::new(config(false)).unwrap();
|
||||||
|
for p in &fs[0].packets {
|
||||||
|
d.push(Instant::ZERO, &p.bytes).unwrap();
|
||||||
|
}
|
||||||
|
let mut lost = BTreeSet::new();
|
||||||
|
for f in &fs[1..] {
|
||||||
|
if f.packets.len() < 2 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
d.push(Instant::ZERO, &f.packets[0].bytes).unwrap();
|
||||||
|
}
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
if let VideoEvent::FrameLost { first, last } = e {
|
||||||
|
lost.extend(first..=last);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(!lost.is_empty(), "more than MAX_FRAMES_IN_FLIGHT incomplete frames: the oldest must be given up");
|
||||||
|
assert!(!lost.contains(&0));
|
||||||
|
}
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 48, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Random frames, random loss, random reordering: exact or reported lost, never corrupt.
|
||||||
|
#[test]
|
||||||
|
fn generated_patterns(seed in any::<u64>(), loss in 0usize..60, window in 1usize..30, dup in 0usize..30) {
|
||||||
|
let (fs, out, _, dg) = scenario(seed, 16, MIXED, move |rng, _, _, _| rng.below(100) >= loss);
|
||||||
|
let mut rng = SeqRng::new(seed.rotate_left(17));
|
||||||
|
let mut mixed: Vec<Vec<u8>> = dg.iter().flat_map(|g| if rng.below(100) < dup { vec![g.clone(), g.clone()] } else { vec![g.clone()] }).collect();
|
||||||
|
let mut i = fs[0].packets.len();
|
||||||
|
while i < mixed.len() {
|
||||||
|
let end = (i + window).min(mixed.len());
|
||||||
|
rng.shuffle(&mut mixed[i..end]);
|
||||||
|
i = end;
|
||||||
|
}
|
||||||
|
check(&fs, &out, None, &run_with(false, &mixed));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Arbitrary datagrams never panic, and nothing that comes out is larger than the frame cap.
|
||||||
|
#[test]
|
||||||
|
fn arbitrary_datagrams(datagrams in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..120), 0..60)) {
|
||||||
|
let r = run_with(false, &datagrams);
|
||||||
|
for e in r.events {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => prop_assert!(f.bitstream.len() <= domistream::video::MAX_FRAME_BYTES),
|
||||||
|
VideoEvent::FrameLost { first, last } => prop_assert!(last.wrapping_sub(first) < 1 << 31),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,825 @@
|
|||||||
|
//! The video packetizer, host side (`docs/PROTOCOL.md` 5.2, 5.3, 7), checked against the client half: every frame
|
||||||
|
//! goes through the crate's own `VideoDepacketizer` and must come out identical and in order, also with up to `m`
|
||||||
|
//! packets of every block lost, reordered or duplicated; with more lost, the frame is reported lost, never corrupt.
|
||||||
|
//! Fixed vectors check one small frame byte by byte against the field table of 5.2, and the parity against an
|
||||||
|
//! independent GF(2^8) encoder with the Cauchy matrix of 5.3.
|
||||||
|
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
|
||||||
|
|
||||||
|
mod common;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use common::{SeqRng, gf};
|
||||||
|
use domistream::fec::parity_count;
|
||||||
|
use domistream::video::packet::{
|
||||||
|
FRAME_HEADER_LEN, MAX_FEC_BLOCKS, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header, parse_video_packet,
|
||||||
|
};
|
||||||
|
use domistream::video::packetizer::{
|
||||||
|
EncodedFrame, MAX_DATA_SHARDS_PER_FRAME, VideoPacketizer, VideoPacketizerConfig, VideoPacketizerStats,
|
||||||
|
plan_fec_blocks, write_frame_header,
|
||||||
|
};
|
||||||
|
use domistream::video::{
|
||||||
|
ENCRYPTION_PREFIX_LEN, FrameType, MAX_FRAME_BYTES, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent,
|
||||||
|
VideoFrame,
|
||||||
|
};
|
||||||
|
use domistream::{Error, Instant};
|
||||||
|
use proptest::prelude::*;
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"video-pack-key!!";
|
||||||
|
|
||||||
|
fn config(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizerConfig {
|
||||||
|
VideoPacketizerConfig {
|
||||||
|
packet_size,
|
||||||
|
fec_percentage: pct,
|
||||||
|
min_required_fec_packets: min,
|
||||||
|
cipher: encrypt.then(|| VideoCipher::new(KEY)),
|
||||||
|
first_sequence,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sender(packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> VideoPacketizer {
|
||||||
|
VideoPacketizer::new(config(packet_size, pct, min, encrypt, first_sequence)).expect("VideoPacketizer::new")
|
||||||
|
}
|
||||||
|
|
||||||
|
fn receiver(packet_size: u16, encrypt: bool) -> VideoDepacketizer {
|
||||||
|
VideoDepacketizer::new(VideoConfig {
|
||||||
|
packet_size,
|
||||||
|
cipher: encrypt.then(|| VideoCipher::new(KEY)),
|
||||||
|
frame_timeout: Duration::from_millis(50),
|
||||||
|
})
|
||||||
|
.expect("VideoDepacketizer::new")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A bitstream of exactly `len` bytes: a start code, then random bytes, every third frame with a zero tail (the
|
||||||
|
/// frame header's last-payload length, not the content, says where the frame ends).
|
||||||
|
fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
|
||||||
|
let mut b = rng.bytes(len);
|
||||||
|
for (dst, src) in b.iter_mut().zip([0u8, 0, 0, 1, 0x65]) {
|
||||||
|
*dst = src;
|
||||||
|
}
|
||||||
|
if rng.below(3) == 0 {
|
||||||
|
let tail = rng.below(len / 2 + 1);
|
||||||
|
for x in &mut b[len - tail..] {
|
||||||
|
*x = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
b
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One frame as sent.
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
struct Sent {
|
||||||
|
index: u32,
|
||||||
|
frame_type: FrameType,
|
||||||
|
latency: u16,
|
||||||
|
timestamp: u32,
|
||||||
|
bitstream: Vec<u8>,
|
||||||
|
datagrams: Vec<Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_bytes(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, bitstream: Vec<u8>) -> Sent {
|
||||||
|
let frame_type = [FrameType::Predicted, FrameType::Key, FrameType::Recovery][rng.below(3)];
|
||||||
|
let latency = rng.below(65_536) as u16;
|
||||||
|
let timestamp = rng.next_u64() as u32;
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: index,
|
||||||
|
frame_type,
|
||||||
|
rtp_timestamp: timestamp,
|
||||||
|
processing_latency: latency,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let datagrams = tx.packetize(&frame).expect("packetize");
|
||||||
|
Sent { index, frame_type, latency, timestamp, bitstream, datagrams }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send(tx: &mut VideoPacketizer, rng: &mut SeqRng, index: u32, len: usize) -> Sent {
|
||||||
|
let b = bitstream(rng, len);
|
||||||
|
send_bytes(tx, rng, index, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn plain(datagram: &[u8], encrypt: bool) -> Vec<u8> {
|
||||||
|
if encrypt { VideoCipher::new(KEY).decrypt(datagram).expect("decrypt our own datagram") } else { datagram.to_vec() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A datagram's place in its frame, read from its plaintext.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
struct Place {
|
||||||
|
block: u8,
|
||||||
|
shard: u16,
|
||||||
|
k: u16,
|
||||||
|
m: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn place(datagram: &[u8], encrypt: bool) -> Place {
|
||||||
|
let bytes = plain(datagram, encrypt);
|
||||||
|
let p = parse_video_packet(&bytes).expect("our own datagram parses");
|
||||||
|
let k = p.nv.fec.data_shards;
|
||||||
|
let m = parity_count(usize::from(k), p.nv.fec.fec_percentage).expect("consistent FEC fields") as u16;
|
||||||
|
Place { block: p.nv.fec.block_index, shard: p.nv.fec.shard_index, k, m }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Datagram positions of each block, and the block's parity count.
|
||||||
|
fn blocks_of(sent: &Sent, encrypt: bool) -> BTreeMap<u8, (Vec<usize>, usize)> {
|
||||||
|
let mut out: BTreeMap<u8, (Vec<usize>, usize)> = BTreeMap::new();
|
||||||
|
for (i, d) in sent.datagrams.iter().enumerate() {
|
||||||
|
let p = place(d, encrypt);
|
||||||
|
let e = out.entry(p.block).or_insert_with(|| (Vec::new(), usize::from(p.m)));
|
||||||
|
e.0.push(i);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The frame's datagrams with, in every block, a random subset of `extra(m)` lost (`extra = 0` keeps all).
|
||||||
|
fn with_loss(rng: &mut SeqRng, sent: &Sent, encrypt: bool, lose: impl Fn(&mut SeqRng, usize) -> usize) -> Vec<Vec<u8>> {
|
||||||
|
let mut keep = vec![true; sent.datagrams.len()];
|
||||||
|
for (positions, m) in blocks_of(sent, encrypt).values() {
|
||||||
|
let n = lose(rng, *m).min(positions.len());
|
||||||
|
for i in rng.subset(positions.len(), n) {
|
||||||
|
keep[positions[i]] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sent.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone()).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Out {
|
||||||
|
frames: Vec<VideoFrame>,
|
||||||
|
lost: Vec<(u32, u32)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drain(rx: &mut VideoDepacketizer, out: &mut Out) {
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => out.frames.push(f),
|
||||||
|
VideoEvent::FrameLost { first, last } => out.lost.push((first, last)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn receive(rx: &mut VideoDepacketizer, datagrams: &[Vec<u8>]) -> Out {
|
||||||
|
let mut now = 1_000_000u64;
|
||||||
|
let mut out = Out::default();
|
||||||
|
for d in datagrams {
|
||||||
|
rx.push(Instant::from_micros(now), d).expect("push never fails within the size cap");
|
||||||
|
now += 10;
|
||||||
|
drain(rx, &mut out);
|
||||||
|
}
|
||||||
|
for _ in 0..64 {
|
||||||
|
now += 10_000_000;
|
||||||
|
rx.handle_timeout(Instant::from_micros(now)).unwrap();
|
||||||
|
drain(rx, &mut out);
|
||||||
|
if rx.poll_timeout().is_none() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every frame not in `lost` came out identical and in order; every frame in `lost` is in a FrameLost range.
|
||||||
|
fn check(sent: &[Sent], lost: &[u32], out: &Out) {
|
||||||
|
let want: Vec<&Sent> = sent.iter().filter(|s| !lost.contains(&s.index)).collect();
|
||||||
|
assert_eq!(
|
||||||
|
out.frames.iter().map(|f| f.frame_index).collect::<Vec<_>>(),
|
||||||
|
want.iter().map(|s| s.index).collect::<Vec<_>>(),
|
||||||
|
"frames delivered (lost ranges {:?})",
|
||||||
|
out.lost
|
||||||
|
);
|
||||||
|
for (f, s) in out.frames.iter().zip(&want) {
|
||||||
|
assert!(
|
||||||
|
f.bitstream == s.bitstream,
|
||||||
|
"frame {} differs: {} bytes, want {}",
|
||||||
|
s.index,
|
||||||
|
f.bitstream.len(),
|
||||||
|
s.bitstream.len()
|
||||||
|
);
|
||||||
|
assert_eq!(f.header.header_type, 0x01, "frame {} header type", s.index);
|
||||||
|
assert_eq!(f.header.frame_type, s.frame_type, "frame {} type", s.index);
|
||||||
|
assert_eq!(f.header.processing_latency, s.latency, "frame {} latency", s.index);
|
||||||
|
assert_eq!(f.rtp_timestamp, s.timestamp, "frame {} timestamp", s.index);
|
||||||
|
}
|
||||||
|
for &l in lost {
|
||||||
|
assert!(
|
||||||
|
out.lost.iter().any(|&(a, b)| l.wrapping_sub(a) <= b.wrapping_sub(a)),
|
||||||
|
"frame {l} was not reported lost: {:?}",
|
||||||
|
out.lost
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks every field of every datagram of a frame against PROTOCOL.md 5.2/5.3 and returns the next sequence.
|
||||||
|
fn check_layout(s: &Sent, packet_size: u16, pct: u8, min: u8, encrypt: bool, first_sequence: u16) -> u16 {
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let n = (FRAME_HEADER_LEN + s.bitstream.len()).div_ceil(payload);
|
||||||
|
let plan = plan_fec_blocks(n, pct, min).expect("plan");
|
||||||
|
let total: usize = plan.iter().map(|b| usize::from(b.data_shards) + usize::from(b.parity_shards)).sum();
|
||||||
|
assert_eq!(s.datagrams.len(), total, "frame {}: datagram count", s.index);
|
||||||
|
let last_block = (plan.len() - 1) as u8;
|
||||||
|
let mut seq = first_sequence;
|
||||||
|
let mut it = s.datagrams.iter();
|
||||||
|
let mut data_seen = 0usize;
|
||||||
|
for (b, blk) in plan.iter().enumerate() {
|
||||||
|
let (k, m) = (usize::from(blk.data_shards), usize::from(blk.parity_shards));
|
||||||
|
assert_eq!(m, parity_count(k, blk.fec_percentage).unwrap(), "plan m = ceil(k * pct / 100)");
|
||||||
|
for shard in 0..k + m {
|
||||||
|
let d = it.next().expect("datagram");
|
||||||
|
let extra = if encrypt { ENCRYPTION_PREFIX_LEN } else { 0 };
|
||||||
|
assert_eq!(d.len(), usize::from(packet_size) + 16 + extra, "datagram length");
|
||||||
|
let bytes = plain(d, encrypt);
|
||||||
|
let p = parse_video_packet(&bytes).expect("parses");
|
||||||
|
assert_eq!(bytes[0], 0x90, "RTP byte 0");
|
||||||
|
assert_eq!(p.rtp.payload_type, 0);
|
||||||
|
assert_eq!(p.rtp.sequence, seq, "sequence numbers are consecutive");
|
||||||
|
assert_eq!(p.rtp.timestamp, s.timestamp);
|
||||||
|
assert_eq!(p.rtp.ssrc, 0);
|
||||||
|
assert_eq!(&bytes[12..16], &[0, 0, 0, 0], "reserved");
|
||||||
|
assert_eq!(p.nv.stream_packet_index, u32::from(seq) << 8, "stream packet index");
|
||||||
|
assert_eq!(p.nv.frame_index, s.index);
|
||||||
|
assert_eq!(bytes[25], 0, "reserved byte 25");
|
||||||
|
assert_eq!(p.nv.multi_fec_flags, 0x10, "multi-FEC flags (U15)");
|
||||||
|
assert_eq!(bytes[27] & 0x0F, 0, "multi-FEC blocks low bits");
|
||||||
|
assert_eq!(bytes[28] & 0x0F, 0, "FEC info low bits");
|
||||||
|
assert_eq!(p.nv.fec.block_index, b as u8);
|
||||||
|
assert_eq!(p.nv.fec.last_block_index, last_block);
|
||||||
|
assert_eq!(usize::from(p.nv.fec.shard_index), shard, "data first, then parity");
|
||||||
|
assert_eq!(usize::from(p.nv.fec.data_shards), k);
|
||||||
|
assert_eq!(p.nv.fec.fec_percentage, blk.fec_percentage);
|
||||||
|
let flags = p.nv.flags.0;
|
||||||
|
if shard < k {
|
||||||
|
let mut want = 0x01;
|
||||||
|
if data_seen == 0 {
|
||||||
|
want |= 0x04;
|
||||||
|
}
|
||||||
|
if data_seen == n - 1 {
|
||||||
|
want |= 0x02;
|
||||||
|
}
|
||||||
|
assert_eq!(flags, want, "frame {} data shard {data_seen} flags", s.index);
|
||||||
|
data_seen += 1;
|
||||||
|
} else {
|
||||||
|
assert_eq!(flags, 0, "parity flags");
|
||||||
|
}
|
||||||
|
seq = seq.wrapping_add(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(data_seen, n);
|
||||||
|
seq
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sizes(rng: &mut SeqRng, payload: usize, count: usize) -> Vec<usize> {
|
||||||
|
let max = MAX_DATA_SHARDS_PER_FRAME * payload - FRAME_HEADER_LEN;
|
||||||
|
// Around the shard boundaries: frame data (8 + len) of exactly one and two shards, and one byte either side.
|
||||||
|
let mut out = vec![0, 1];
|
||||||
|
for edge in [payload, 2 * payload] {
|
||||||
|
let at = edge.saturating_sub(FRAME_HEADER_LEN);
|
||||||
|
out.extend([at.saturating_sub(1), at, at + 1]);
|
||||||
|
}
|
||||||
|
while out.len() < count {
|
||||||
|
out.push(match rng.below(4) {
|
||||||
|
0 => rng.below(payload * 3),
|
||||||
|
1 => rng.below(payload * 40),
|
||||||
|
_ => rng.below(payload * 300),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
out.into_iter().map(|s| s.min(max)).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
const PACKET_SIZES: [u16; 9] = [17, 18, 20, 64, 100, 1024, 1040, 1408, 4080];
|
||||||
|
const PERCENTAGES: [u8; 8] = [0, 1, 10, 20, 50, 100, 200, 255];
|
||||||
|
|
||||||
|
// ================================================================================================ fixed vectors
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixed_vector_one_small_frame() {
|
||||||
|
// packetSize 32: 16 bytes of payload per datagram. Frame data = 8-byte header + 7-byte bitstream = 15 bytes,
|
||||||
|
// so one data shard (zero-padded to 16) and, at 100 %, ceil(1 * 100 / 100) = 1 parity shard.
|
||||||
|
let mut tx = sender(32, 100, 0, false, 0x1234);
|
||||||
|
let bitstream = [0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB];
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 7,
|
||||||
|
frame_type: FrameType::Key,
|
||||||
|
rtp_timestamp: 90_000,
|
||||||
|
processing_latency: 0x0102,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let out = tx.packetize(&frame).unwrap();
|
||||||
|
#[rustfmt::skip]
|
||||||
|
let payload: [u8; 16] = [
|
||||||
|
0x01, // frame header type
|
||||||
|
0x02, 0x01, // processing latency 0x0102, LE
|
||||||
|
0x02, // frame type: key
|
||||||
|
0x0F, 0x00, 0x00, 0x00, // last shard payload length 15, LE
|
||||||
|
0x00, 0x00, 0x00, 0x01, 0x65, 0xAA, 0xBB, // the bitstream
|
||||||
|
0x00, // zero padding to the full shard
|
||||||
|
];
|
||||||
|
#[rustfmt::skip]
|
||||||
|
let mut data = vec![
|
||||||
|
0x90, // RTP byte 0: version 2, extension bit
|
||||||
|
0x00, // payload type 0
|
||||||
|
0x12, 0x34, // sequence 0x1234, BE
|
||||||
|
0x00, 0x01, 0x5F, 0x90, // timestamp 90000, BE
|
||||||
|
0x00, 0x00, 0x00, 0x00, // SSRC 0
|
||||||
|
0x00, 0x00, 0x00, 0x00, // reserved
|
||||||
|
0x00, 0x34, 0x12, 0x00, // stream packet index 0x1234 << 8 = 0x00123400, LE
|
||||||
|
0x07, 0x00, 0x00, 0x00, // frame index 7, LE
|
||||||
|
0x07, // flags: picture data 0x01 | end of frame 0x02 | start of frame 0x04
|
||||||
|
0x00, // reserved
|
||||||
|
0x10, // multi-FEC flags (U15)
|
||||||
|
0x00, // multi-FEC blocks: this block 0 (bits 4-5), last block 0 (bits 6-7)
|
||||||
|
0x40, 0x06, 0x40, 0x00, // FEC info 0x00400640, LE: 100 << 4 | shard 0 << 12 | k 1 << 22
|
||||||
|
];
|
||||||
|
data.extend_from_slice(&payload);
|
||||||
|
#[rustfmt::skip]
|
||||||
|
let mut parity = vec![
|
||||||
|
0x90, 0x00, // RTP byte 0, payload type 0
|
||||||
|
0x12, 0x35, // sequence 0x1235: the parity packet takes the next number
|
||||||
|
0x00, 0x01, 0x5F, 0x90, // the frame's timestamp
|
||||||
|
0x00, 0x00, 0x00, 0x00, // SSRC 0
|
||||||
|
0x00, 0x00, 0x00, 0x00, // reserved
|
||||||
|
0x00, 0x35, 0x12, 0x00, // stream packet index 0x1235 << 8, LE
|
||||||
|
0x07, 0x00, 0x00, 0x00, // frame index 7
|
||||||
|
0x00, // flags 0 on parity packets
|
||||||
|
0x00, // reserved
|
||||||
|
0x10, // multi-FEC flags
|
||||||
|
0x00, // block 0 of 0
|
||||||
|
0x40, 0x16, 0x40, 0x00, // FEC info 0x00401640: 100 << 4 | shard 1 << 12 | k 1 << 22
|
||||||
|
];
|
||||||
|
// k = 1, m = 1: the Cauchy matrix is [[1 / ((1 + 0) XOR 0)]] = [[1]], so the parity is the data packet itself
|
||||||
|
// and its payload part equals the data payload.
|
||||||
|
parity.extend_from_slice(&payload);
|
||||||
|
assert_eq!(out, vec![data, parity]);
|
||||||
|
assert_eq!(tx.next_sequence(), 0x1236);
|
||||||
|
assert_eq!(tx.stats(), VideoPacketizerStats { frames: 1, packets: 2, parity_packets: 1, fec_reduced_blocks: 0 });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fixed_vector_cauchy_parity_k3_m1() {
|
||||||
|
// packetSize 20: 4 bytes of payload. 8 + 4 = 12 bytes of frame data = 3 data shards, last one full (4 bytes).
|
||||||
|
// At 33 %: m = ceil(3 * 33 / 100) = 1. PROTOCOL.md 5.3 gives P = [01 8e f4] for k = 3, m = 1.
|
||||||
|
let mut tx = sender(20, 33, 0, false, 0);
|
||||||
|
let bitstream = [0x00, 0x00, 0x01, 0x09];
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 0x0102_0304,
|
||||||
|
frame_type: FrameType::Predicted,
|
||||||
|
rtp_timestamp: 1,
|
||||||
|
processing_latency: 0xBEEF,
|
||||||
|
bitstream: &bitstream,
|
||||||
|
};
|
||||||
|
let out = tx.packetize(&frame).unwrap();
|
||||||
|
assert_eq!(out.len(), 4);
|
||||||
|
let shards: [[u8; 4]; 3] = [
|
||||||
|
[0x01, 0xEF, 0xBE, 0x01], // header type, latency 0xBEEF LE, predicted
|
||||||
|
[0x04, 0x00, 0x00, 0x00], // last shard payload length 4, LE
|
||||||
|
[0x00, 0x00, 0x01, 0x09], // bitstream
|
||||||
|
];
|
||||||
|
for (i, s) in shards.iter().enumerate() {
|
||||||
|
assert_eq!(&out[i][PAYLOAD_OFFSET..], s, "data shard {i}");
|
||||||
|
// FEC info: 33 << 4 | i << 12 | 3 << 22
|
||||||
|
let info = (33u32 << 4) | ((i as u32) << 12) | (3 << 22);
|
||||||
|
assert_eq!(&out[i][28..32], &info.to_le_bytes(), "FEC info of shard {i}");
|
||||||
|
}
|
||||||
|
let p = [0x01u8, 0x8E, 0xF4];
|
||||||
|
let want: Vec<u8> = (0..4).map(|x| (0..3).fold(0, |acc, i| acc ^ gf::mul(p[i], shards[i][x]))).collect();
|
||||||
|
assert_eq!(&out[3][PAYLOAD_OFFSET..], want.as_slice(), "parity = 01*d0 + 8e*d1 + f4*d2");
|
||||||
|
assert_eq!(&out[3][28..32], &((33u32 << 4) | (3 << 12) | (3 << 22)).to_le_bytes(), "parity FEC info");
|
||||||
|
assert_eq!(out[3][24], 0, "parity flags");
|
||||||
|
assert_eq!(&out[3][2..4], &3u16.to_be_bytes(), "parity sequence");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn frame_header_writer_round_trips() {
|
||||||
|
for (t, byte) in
|
||||||
|
[(FrameType::Predicted, 1u8), (FrameType::Key, 2), (FrameType::Recovery, 5), (FrameType::Other(9), 9)]
|
||||||
|
{
|
||||||
|
for (lat, last) in [(0u16, 1u32), (0xFFFF, 4064), (0x1234, 0x0A0B_0C0D)] {
|
||||||
|
let h = write_frame_header(t, lat, last);
|
||||||
|
let mut want = vec![0x01];
|
||||||
|
want.extend_from_slice(&lat.to_le_bytes());
|
||||||
|
want.push(byte);
|
||||||
|
want.extend_from_slice(&last.to_le_bytes());
|
||||||
|
assert_eq!(h.to_vec(), want);
|
||||||
|
let back = parse_frame_header(&h).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
(back.header_type, back.processing_latency, back.frame_type, back.last_payload_len),
|
||||||
|
(1, lat, t, last)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ the FEC plan
|
||||||
|
|
||||||
|
/// Parity the client asks for a block of `k`: `max(ceil(k * pct / 100), min)`.
|
||||||
|
fn target(k: usize, pct: u8, min: u8) -> usize {
|
||||||
|
(k * usize::from(pct)).div_ceil(100).max(usize::from(min))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parity a block of `k` gets at percentage `p` (the receiver's formula).
|
||||||
|
fn m_at(k: usize, p: usize) -> usize {
|
||||||
|
(k * p).div_ceil(100)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether the least percentage (at or above the request) that gives a block of `k` its target is an 8-bit value
|
||||||
|
/// and keeps the block within 255 shards. Parity comes in steps of `ceil(k * p / 100)`, so for `k > 100` the least
|
||||||
|
/// step can overshoot the target.
|
||||||
|
fn achievable(k: usize, pct: u8, min: u8) -> bool {
|
||||||
|
let t = target(k, pct, min);
|
||||||
|
let p = (usize::from(pct)..=255).find(|&p| m_at(k, p) >= t);
|
||||||
|
k <= 255 && p.is_some_and(|p| k + m_at(k, p) <= 255)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fec_plan_properties() {
|
||||||
|
for n in (1..=MAX_DATA_SHARDS_PER_FRAME).filter(|n| *n < 40 || n % 7 == 0 || *n > 1000) {
|
||||||
|
for pct in PERCENTAGES.into_iter().chain([3, 33, 34, 99]) {
|
||||||
|
for min in [0u8, 1, 2, 3, 4, 10, 255] {
|
||||||
|
let ctx = format!("n {n} pct {pct} min {min}");
|
||||||
|
let plan = plan_fec_blocks(n, pct, min).unwrap();
|
||||||
|
assert!((1..=MAX_FEC_BLOCKS).contains(&plan.len()), "{ctx}: {} blocks", plan.len());
|
||||||
|
assert_eq!(plan.iter().map(|b| usize::from(b.data_shards)).sum::<usize>(), n, "{ctx}");
|
||||||
|
let first_k = plan[0].data_shards;
|
||||||
|
for (i, b) in plan.iter().enumerate() {
|
||||||
|
let (k, m, p) =
|
||||||
|
(usize::from(b.data_shards), usize::from(b.parity_shards), usize::from(b.fec_percentage));
|
||||||
|
assert!(k >= 1 && k + m <= 255, "{ctx}: k {k} m {m}");
|
||||||
|
assert_eq!(m, parity_count(k, b.fec_percentage).unwrap(), "{ctx}: m follows from the percentage");
|
||||||
|
if i + 1 < plan.len() {
|
||||||
|
assert_eq!(b.data_shards, first_k, "{ctx}: every block but the last carries the same k");
|
||||||
|
} else {
|
||||||
|
assert!(b.data_shards <= first_k, "{ctx}");
|
||||||
|
}
|
||||||
|
let t = target(k, pct, min);
|
||||||
|
assert_eq!(
|
||||||
|
b.reduced,
|
||||||
|
!achievable(k, pct, min),
|
||||||
|
"{ctx}: reduced exactly when the target cannot fit"
|
||||||
|
);
|
||||||
|
if b.reduced {
|
||||||
|
// The most parity that fits: one percent more would not.
|
||||||
|
assert!(m < t, "{ctx}");
|
||||||
|
assert!(p == 255 || k + m_at(k, p + 1) > 255, "{ctx}: k {k} p {p}: not the most that fits");
|
||||||
|
} else {
|
||||||
|
// The least percentage, at or above the request, that gives the target.
|
||||||
|
assert!(m >= t && p >= usize::from(pct), "{ctx}: k {k} m {m} p {p}");
|
||||||
|
assert!(p == usize::from(pct) || m_at(k, p - 1) < t, "{ctx}: k {k} p {p}: raised too far");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Fewest blocks: one block fewer could not carry the frame with the requested parity.
|
||||||
|
if plan.len() > 1 && !plan[0].reduced {
|
||||||
|
let fewer = plan.len() - 1;
|
||||||
|
assert!(!achievable(n.div_ceil(fewer), pct, min), "{ctx}: {} blocks where {fewer} do", plan.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_err!(plan_fec_blocks(0, 20, 0), Error::Malformed { .. });
|
||||||
|
assert_too_large!(
|
||||||
|
plan_fec_blocks(MAX_DATA_SHARDS_PER_FRAME + 1, 0, 0),
|
||||||
|
MAX_DATA_SHARDS_PER_FRAME,
|
||||||
|
MAX_DATA_SHARDS_PER_FRAME + 1
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn minimum_parity_raises_the_written_percentage() {
|
||||||
|
// One data shard at 0 % with at least 2 parity packets: 101 % is the smallest percentage giving
|
||||||
|
// m = ceil(1 * 101 / 100) = 2.
|
||||||
|
let plan = plan_fec_blocks(1, 0, 2).unwrap();
|
||||||
|
assert_eq!((plan[0].data_shards, plan[0].parity_shards, plan[0].fec_percentage), (1, 2, 101));
|
||||||
|
// 3 shards, at least 2: 34 % (ceil(1.02) = 2), not 67 % (which would give 3).
|
||||||
|
let plan = plan_fec_blocks(3, 0, 2).unwrap();
|
||||||
|
assert_eq!((plan[0].parity_shards, plan[0].fec_percentage), (2, 34));
|
||||||
|
// Already enough: unchanged.
|
||||||
|
let plan = plan_fec_blocks(10, 50, 2).unwrap();
|
||||||
|
assert_eq!((plan[0].parity_shards, plan[0].fec_percentage, plan[0].reduced), (5, 50, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ round trips
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_random_sizes() {
|
||||||
|
for seed in 0..12u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size =
|
||||||
|
if seed < PACKET_SIZES.len() as u64 { PACKET_SIZES[seed as usize] } else { 17 + rng.below(4064) as u16 };
|
||||||
|
let pct = PERCENTAGES[rng.below(PERCENTAGES.len())];
|
||||||
|
let min = [0u8, 1, 2, 4][rng.below(4)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let first_sequence = rng.next_u64() as u16;
|
||||||
|
let mut tx = sender(packet_size, pct, min, false, first_sequence);
|
||||||
|
let mut seq = first_sequence;
|
||||||
|
let first_index = rng.next_u64() as u32;
|
||||||
|
let sent: Vec<Sent> = sizes(&mut rng, payload, 16)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, len)| send(&mut tx, &mut rng, first_index.wrapping_add(i as u32), len))
|
||||||
|
.collect();
|
||||||
|
for s in &sent {
|
||||||
|
seq = check_layout(s, packet_size, pct, min, false, seq);
|
||||||
|
}
|
||||||
|
assert_eq!(tx.next_sequence(), seq);
|
||||||
|
let all: Vec<Vec<u8>> = sent.iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
check(&sent, &[], &receive(&mut receiver(packet_size, false), &all));
|
||||||
|
let stats = tx.stats();
|
||||||
|
assert_eq!(stats.frames, sent.len() as u64);
|
||||||
|
assert_eq!(stats.packets, all.len() as u64);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_with_up_to_m_lost_per_block() {
|
||||||
|
for seed in 100..112u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())];
|
||||||
|
let pct = [10u8, 20, 50, 100, 200, 255][rng.below(6)];
|
||||||
|
let min = [0u8, 1, 2][rng.below(3)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, min, false, rng.next_u64() as u16);
|
||||||
|
let sent: Vec<Sent> = sizes(&mut rng, payload, 14)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, l)| send(&mut tx, &mut rng, i as u32, l))
|
||||||
|
.collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(with_loss(&mut rng, s, false, |r, m| if r.below(3) == 0 { m } else { r.below(m + 1) }));
|
||||||
|
}
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &datagrams);
|
||||||
|
check(&sent, &[], &out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_data_shard_lost_is_rebuilt_when_parity_covers_it() {
|
||||||
|
// 100 %: m = k, so the parity alone carries the frame.
|
||||||
|
let mut rng = SeqRng::new(7);
|
||||||
|
let mut tx = sender(64, 100, 0, false, 0);
|
||||||
|
let sent: Vec<Sent> = (0..6).map(|i| send(&mut tx, &mut rng, i, 48 * (1 + 5 * i as usize))).collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(s.datagrams.iter().filter(|d| place(d, false).shard >= place(d, false).k).cloned());
|
||||||
|
}
|
||||||
|
let out = receive(&mut receiver(64, false), &datagrams);
|
||||||
|
check(&sent, &[], &out);
|
||||||
|
assert!(out.frames.iter().all(|f| f.recovered_shards > 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn more_than_m_lost_reports_the_frame_lost() {
|
||||||
|
for seed in 200..216u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size = PACKET_SIZES[1 + rng.below(PACKET_SIZES.len() - 1)];
|
||||||
|
let pct = [0u8, 10, 20, 50, 100][rng.below(5)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, 0, false, 0xFFF0);
|
||||||
|
let sent: Vec<Sent> = (0..7)
|
||||||
|
.map(|i| {
|
||||||
|
let len = 1 + rng.below(payload * 30);
|
||||||
|
send(&mut tx, &mut rng, 1000 + i, len)
|
||||||
|
})
|
||||||
|
.collect();
|
||||||
|
let victim = 1 + rng.below(5);
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for (i, s) in sent.iter().enumerate() {
|
||||||
|
if i == victim {
|
||||||
|
// One block loses m + 1 packets, the others up to m.
|
||||||
|
let blocks = blocks_of(s, false);
|
||||||
|
let hit = *blocks.keys().nth(rng.below(blocks.len())).unwrap();
|
||||||
|
let mut keep = vec![true; s.datagrams.len()];
|
||||||
|
for (b, (positions, m)) in &blocks {
|
||||||
|
let n = if *b == hit { m + 1 } else { rng.below(m + 1) };
|
||||||
|
for j in rng.subset(positions.len(), n) {
|
||||||
|
keep[positions[j]] = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
datagrams.extend(s.datagrams.iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d.clone()));
|
||||||
|
} else {
|
||||||
|
datagrams.extend(s.datagrams.iter().cloned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &datagrams);
|
||||||
|
check(&sent, &[1000 + victim as u32], &out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn reordered_and_duplicated() {
|
||||||
|
for seed in 300..310u64 {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let packet_size = PACKET_SIZES[rng.below(PACKET_SIZES.len())];
|
||||||
|
let pct = [0u8, 20, 50][rng.below(3)];
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, 1, false, rng.next_u64() as u16);
|
||||||
|
let sent: Vec<Sent> = sizes(&mut rng, payload, 12)
|
||||||
|
.into_iter()
|
||||||
|
.enumerate()
|
||||||
|
.map(|(i, l)| send(&mut tx, &mut rng, i as u32, l))
|
||||||
|
.collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for pair in sent.chunks(2) {
|
||||||
|
// Two frames' datagrams interleaved in random order, with random duplicates.
|
||||||
|
let mut window: Vec<Vec<u8>> = pair.iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
let dups: Vec<Vec<u8>> =
|
||||||
|
(0..rng.below(window.len() + 1)).map(|_| window[rng.below(window.len())].clone()).collect();
|
||||||
|
window.extend(dups);
|
||||||
|
rng.shuffle(&mut window);
|
||||||
|
if datagrams.is_empty() {
|
||||||
|
// The receiver starts at the frame of the first datagram it sees: let that be frame 0's.
|
||||||
|
let first = window.iter().position(|d| pair[0].datagrams.contains(d));
|
||||||
|
window.swap(0, first.expect("a datagram of frame 0"));
|
||||||
|
}
|
||||||
|
datagrams.extend(window);
|
||||||
|
}
|
||||||
|
// And a few stale duplicates of earlier frames at the end.
|
||||||
|
for _ in 0..5 {
|
||||||
|
let s = &sent[rng.below(sent.len())];
|
||||||
|
datagrams.push(s.datagrams[rng.below(s.datagrams.len())].clone());
|
||||||
|
}
|
||||||
|
check(&sent, &[], &receive(&mut receiver(packet_size, false), &datagrams));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn sequence_numbers_continue_across_frames_and_wrap() {
|
||||||
|
let mut rng = SeqRng::new(9);
|
||||||
|
let mut tx = sender(64, 50, 0, false, 0xFFF0);
|
||||||
|
let mut seq = 0xFFF0u16;
|
||||||
|
let mut sent = Vec::new();
|
||||||
|
for i in 0..10u32 {
|
||||||
|
let s = send(&mut tx, &mut rng, (u32::MAX - 4).wrapping_add(i), 48 * 3);
|
||||||
|
seq = check_layout(&s, 64, 50, 0, false, seq);
|
||||||
|
sent.push(s);
|
||||||
|
}
|
||||||
|
assert!(seq < 0xFFF0, "the sequence wrapped");
|
||||||
|
assert_eq!(tx.next_sequence(), seq);
|
||||||
|
let all: Vec<Vec<u8>> = sent.iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
check(&sent, &[], &receive(&mut receiver(64, false), &all));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn parity_matches_an_independent_cauchy_encoder() {
|
||||||
|
// Parity over whole packets (5.3): bytes 32 on of parity j = sum_i 1 / ((m + i) XOR j) * data_i, with headers
|
||||||
|
// of the parity packets written afterwards.
|
||||||
|
let mut rng = SeqRng::new(11);
|
||||||
|
for (packet_size, pct, len) in [(64u16, 50u8, 48 * 9), (100, 20, 84 * 30), (1024, 100, 1008 * 4 + 3), (17, 255, 40)]
|
||||||
|
{
|
||||||
|
let mut tx = sender(packet_size, pct, 0, false, 0);
|
||||||
|
let s = send(&mut tx, &mut rng, 5, len);
|
||||||
|
for (positions, m) in blocks_of(&s, false).values() {
|
||||||
|
let k = positions.len() - m;
|
||||||
|
let data: Vec<Vec<u8>> = positions[..k].iter().map(|&i| s.datagrams[i].clone()).collect();
|
||||||
|
let matrix: Vec<u8> = (0..*m).flat_map(|j| (0..k).map(move |i| gf::inv(((m + i) ^ j) as u8))).collect();
|
||||||
|
let parity = gf::encode(&matrix, &data, *m);
|
||||||
|
for (j, &pos) in positions[k..].iter().enumerate() {
|
||||||
|
assert_eq!(&s.datagrams[pos][PAYLOAD_OFFSET..], &parity[j][PAYLOAD_OFFSET..], "parity {j}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn several_megabyte_frames() {
|
||||||
|
let mut rng = SeqRng::new(13);
|
||||||
|
let packet_size = 4080; // largest: 4064 bytes of payload, 4096-byte datagrams
|
||||||
|
let mut tx = sender(packet_size, 20, 2, false, 0);
|
||||||
|
let max = tx.max_bitstream_len();
|
||||||
|
assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * 4064 - FRAME_HEADER_LEN).min(MAX_FRAME_BYTES - FRAME_HEADER_LEN));
|
||||||
|
let big = send(&mut tx, &mut rng, 1, 3_000_000);
|
||||||
|
let lossy = with_loss(&mut rng, &big, false, |_, m| m);
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &lossy);
|
||||||
|
check(std::slice::from_ref(&big), &[], &out);
|
||||||
|
// The largest frame: 4 blocks of 255 data shards, no room for parity, so the FEC is lowered and counted.
|
||||||
|
let before = tx.stats().fec_reduced_blocks;
|
||||||
|
let largest = send(&mut tx, &mut rng, 2, max);
|
||||||
|
assert_eq!(tx.stats().fec_reduced_blocks - before, 4);
|
||||||
|
assert_eq!(largest.datagrams.len(), MAX_DATA_SHARDS_PER_FRAME);
|
||||||
|
let out = receive(&mut receiver(packet_size, false), &largest.datagrams);
|
||||||
|
check(std::slice::from_ref(&largest), &[], &out);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ encryption
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn video_cipher_encrypt_matches_dotnet_vectors() {
|
||||||
|
let v = common::video_vectors();
|
||||||
|
let c = VideoCipher::new(v.arr16("key"));
|
||||||
|
for (name, counter, frame) in
|
||||||
|
[("v_0", 0u64, 0u32), ("v_1", 1, 0), ("v_big_counter", 0x0102_0304_0506_0708, 0x1122_3344), ("v_1040", 7, 3)]
|
||||||
|
{
|
||||||
|
assert_eq!(
|
||||||
|
c.encrypt(counter, frame, &v.bytes(&format!("{name}_plain"))).unwrap(),
|
||||||
|
v.bytes(&format!("{name}_packet")),
|
||||||
|
"{name}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let too_big = vec![0u8; MAX_VIDEO_PACKET_BYTES - ENCRYPTION_PREFIX_LEN + 1];
|
||||||
|
assert_too_large!(c.encrypt(0, 0, &too_big), MAX_VIDEO_PACKET_BYTES, MAX_VIDEO_PACKET_BYTES + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn encrypted_stream_round_trips_with_loss() {
|
||||||
|
let mut rng = SeqRng::new(17);
|
||||||
|
let mut tx = sender(1024, 20, 1, true, 100);
|
||||||
|
let mut clear = sender(1024, 20, 1, false, 100);
|
||||||
|
let mut counter = 0u64;
|
||||||
|
let mut sent = Vec::new();
|
||||||
|
for i in 0..10u32 {
|
||||||
|
let len = rng.below(1008 * 12);
|
||||||
|
let b = bitstream(&mut rng, len);
|
||||||
|
let mut r2 = rng.clone();
|
||||||
|
let s = send_bytes(&mut tx, &mut rng, i, b.clone());
|
||||||
|
let c = send_bytes(&mut clear, &mut r2, i, b);
|
||||||
|
assert_eq!(s.datagrams.len(), c.datagrams.len());
|
||||||
|
for (d, p) in s.datagrams.iter().zip(&c.datagrams) {
|
||||||
|
// IV = 8-byte LE counter, 3 zero bytes, 'V'; then the frame number, LE (PROTOCOL.md 7).
|
||||||
|
assert_eq!(&d[..8], &counter.to_le_bytes(), "nonce counter");
|
||||||
|
assert_eq!(&d[8..12], &[0, 0, 0, b'V']);
|
||||||
|
assert_eq!(&d[12..16], &i.to_le_bytes(), "frame number");
|
||||||
|
assert_eq!(
|
||||||
|
&VideoCipher::new(KEY).decrypt(d).unwrap(),
|
||||||
|
p,
|
||||||
|
"FEC before encryption: the plaintext is the clear packet"
|
||||||
|
);
|
||||||
|
counter += 1;
|
||||||
|
}
|
||||||
|
sent.push(s);
|
||||||
|
}
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(with_loss(&mut rng, s, true, |r, m| r.below(m + 1)));
|
||||||
|
}
|
||||||
|
check(&sent, &[], &receive(&mut receiver(1024, true), &datagrams));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ refusals
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn config_refusals() {
|
||||||
|
for size in [0u16, 1, 16] {
|
||||||
|
assert_err!(VideoPacketizer::new(config(size, 20, 0, false, 0)), Error::Malformed { .. }, "{size}");
|
||||||
|
}
|
||||||
|
assert!(VideoPacketizer::new(config(17, 20, 0, false, 0)).is_ok());
|
||||||
|
assert!(VideoPacketizer::new(config(4080, 20, 0, false, 0)).is_ok());
|
||||||
|
assert_err!(VideoPacketizer::new(config(4081, 20, 0, false, 0)), Error::Malformed { .. });
|
||||||
|
// Sealed datagrams carry 32 more bytes and must stay within the receiver's cap too.
|
||||||
|
assert!(VideoPacketizer::new(config(4048, 20, 0, true, 0)).is_ok());
|
||||||
|
assert_err!(VideoPacketizer::new(config(4049, 20, 0, true, 0)), Error::Malformed { .. });
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn oversized_frame_is_refused_and_nothing_advances() {
|
||||||
|
for (packet_size, encrypt) in [(17u16, false), (64, true), (1024, false)] {
|
||||||
|
let mut rng = SeqRng::new(u64::from(packet_size));
|
||||||
|
let mut tx = sender(packet_size, 20, 0, encrypt, 77);
|
||||||
|
let max = tx.max_bitstream_len();
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
assert_eq!(max, (MAX_DATA_SHARDS_PER_FRAME * payload).min(MAX_FRAME_BYTES) - FRAME_HEADER_LEN);
|
||||||
|
let first = send(&mut tx, &mut rng, 0, 10);
|
||||||
|
let (seq, stats) = (tx.next_sequence(), tx.stats());
|
||||||
|
let big = vec![1u8; max + 1];
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 1,
|
||||||
|
frame_type: FrameType::Key,
|
||||||
|
rtp_timestamp: 0,
|
||||||
|
processing_latency: 0,
|
||||||
|
bitstream: &big,
|
||||||
|
};
|
||||||
|
assert_too_large!(tx.packetize(&frame), max, max + 1);
|
||||||
|
assert_eq!((tx.next_sequence(), tx.stats()), (seq, stats), "a refused frame changes nothing");
|
||||||
|
// The next frame follows on directly, and the receiver sees no gap (also no nonce reuse when sealed).
|
||||||
|
let second = send(&mut tx, &mut rng, 1, max);
|
||||||
|
let all: Vec<Vec<u8>> = [&first, &second].iter().flat_map(|s| s.datagrams.clone()).collect();
|
||||||
|
check(&[first, second], &[], &receive(&mut receiver(packet_size, encrypt), &all));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ================================================================================================ generated
|
||||||
|
|
||||||
|
proptest! {
|
||||||
|
#![proptest_config(ProptestConfig { cases: 32, ..ProptestConfig::default() })]
|
||||||
|
|
||||||
|
/// Any sizes, packet sizes, percentages and minimums; up to m lost per block; identical frames out.
|
||||||
|
#[test]
|
||||||
|
fn generated_round_trips(
|
||||||
|
seed in any::<u64>(),
|
||||||
|
packet_size in 17u16..1500,
|
||||||
|
pct in any::<u8>(),
|
||||||
|
min in 0u8..8,
|
||||||
|
frames in 1usize..6,
|
||||||
|
encrypt in any::<bool>(),
|
||||||
|
) {
|
||||||
|
let mut rng = SeqRng::new(seed);
|
||||||
|
let payload = usize::from(packet_size) - 16;
|
||||||
|
let mut tx = sender(packet_size, pct, min, encrypt, rng.next_u64() as u16);
|
||||||
|
let max = tx.max_bitstream_len();
|
||||||
|
let first = rng.next_u64() as u32;
|
||||||
|
let sent: Vec<Sent> = (0..frames)
|
||||||
|
.map(|i| { let len = rng.below(payload * 30).min(max); send(&mut tx, &mut rng, first.wrapping_add(i as u32), len) })
|
||||||
|
.collect();
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for s in &sent {
|
||||||
|
datagrams.extend(with_loss(&mut rng, s, encrypt, |r, m| r.below(m + 1)));
|
||||||
|
}
|
||||||
|
check(&sent, &[], &receive(&mut receiver(packet_size, encrypt), &datagrams));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -14,7 +14,9 @@ GPL-licensed implementation. This file says what may be read, what may not, and
|
|||||||
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
|
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
|
||||||
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
|
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
|
||||||
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
|
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
|
||||||
|
| Arena Domi Remote (Android, a GPL app built apart from Domi repos) and the official Moonlight PC app, as **clients of Lumen** | GPL-3.0 (we only run them) | Black-box peers (Mark, 2026-12-04, D2): lumen-host logs what they send to it. Same limits as the row above. Their workspaces and source are never opened; the Remote app's own workers drive it and hand over facts only. |
|
||||||
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
|
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
|
||||||
|
| Public OS and SDK documentation (Microsoft Learn; NVIDIA, AMD and Intel encoder SDK docs and API headers; libopus and ViGEm docs) | per vendor | Read for the host side (Lumen), facts in our own words, each page logged. Allowed in the Lumen host lead's brief of 2026-12-04. Never the source of GPL or LGPL projects that wrap these APIs. |
|
||||||
|
|
||||||
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution"
|
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution"
|
||||||
|
|
||||||
@@ -33,6 +35,10 @@ Never open, read, paste or port code from: **Sunshine, Moonlight (any client: Qt
|
|||||||
moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also
|
moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also
|
||||||
means their source files on GitHub. Their READMEs and wikis are fine for facts.
|
means their source files on GitHub. Their READMEs and wikis are fine for facts.
|
||||||
|
|
||||||
|
**For host work (Lumen), also forbidden** (Mark, 2026-12-04, decision D2 in [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md)):
|
||||||
|
the source of **OBS Studio** and **FFmpeg** (including any GPL or LGPL code that wraps NVENC, AMF, Quick Sync,
|
||||||
|
Desktop Duplication or WASAPI). Their documentation pages are fine for facts, like the READMEs above.
|
||||||
|
|
||||||
### Second-hand GPL facts
|
### Second-hand GPL facts
|
||||||
|
|
||||||
Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or
|
Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or
|
||||||
@@ -45,6 +51,8 @@ copied into DomiStream, and settled by our own measurement instead. Known cases:
|
|||||||
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
|
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
|
||||||
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
|
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
|
||||||
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
|
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
|
||||||
|
| `src/rtsp.rs` (read again as S-30) | `encoderCscMode` bit layout (comment cites Sunshine's colour-space function); `maxNumReferenceFrames` 0 = "host's choice" (comment cites moonlight-common-c); the 5.1/7.1 mapping rotation (comment cites GFE and Moonlight) | Not taken: the host parser keeps both numbers raw and writes the mappings as configured (PROTOCOL.md 2.5, U6, U26) |
|
||||||
|
| `src/session/stream/video/mod.rs` (S-31) | how the stored bitrate is reduced for FEC and audio (comment: "as Sunshine computes it") | Not taken; the parser hands over the client's bitrate unchanged |
|
||||||
|
|
||||||
## How code gets written
|
## How code gets written
|
||||||
|
|
||||||
@@ -80,3 +88,11 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
|
|||||||
| S-18 | 2026-11-25 | [fec-rs](https://github.com/hgaiser/fec-rs) at `402f41f970bb8c3ef7c88639821032e3b6460f63`: `LICENSE`, `README.md`, `build.rs` (field tables), `src/galois.rs` (`exp`), `src/matrix.rs` (`vandermonde`), `src/reed_solomon.rs` (`build_matrix`, `new`) | BSD-2. Field GF(2^8) with polynomial 0x11D, generator 2; systematic code whose parity rows are the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`. Its tests also contain the GPL-provenance audio matrix (not taken). |
|
| S-18 | 2026-11-25 | [fec-rs](https://github.com/hgaiser/fec-rs) at `402f41f970bb8c3ef7c88639821032e3b6460f63`: `LICENSE`, `README.md`, `build.rs` (field tables), `src/galois.rs` (`exp`), `src/matrix.rs` (`vandermonde`), `src/reed_solomon.rs` (`build_matrix`, `new`) | BSD-2. Field GF(2^8) with polynomial 0x11D, generator 2; systematic code whose parity rows are the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`. Its tests also contain the GPL-provenance audio matrix (not taken). |
|
||||||
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
|
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
|
||||||
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
|
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
|
||||||
|
| S-21 | 2026-11-30 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e` (same pin as S-9): `src/session/stream/control/mod.rs` again (client message parsing and the control loop), `src/session/stream/mod.rs` (`StreamConfig`), `src/session/stream/video/mod.rs` (PING handling), `src/config.rs` (nothing relevant); the repository tree listing | BSD-2. U10, as facts only: the host reads **no body** from START_B (0x0307), Ping (0x0200), LOSS_STATS, FRAME_STATS or the IDR request; START_A (0x0305) is not a type it knows; inside the encrypted frame an unknown type or a failed decryption is skipped, outside it an unknown type or a bad length ends the session; INVALIDATE_REF_FRAMES `first`/`last` at message bytes 4..8 and 12..16 (LE), short bodies mean "from 0"; each Ping resets a stop deadline, `StreamConfig.timeout` default 60 s; the client-to-host IV is `seq LE ‖ 6 zero ‖ 'C' 'C'`; host messages go reliable on channel 0; the video receiver waits for START_B and takes exactly the 4 bytes `PING`, each PING updating the client address. No value in these parts cites Sunshine or moonlight-common-c (the HDR payload's Sunshine note is the known S-9 case). Used for the probe's default bodies (all empty) and the PROTOCOL.md 3.3 facts. |
|
||||||
|
| S-22 | 2026-12-04 | Microsoft Learn: [DXGI 1.5 improvements](https://learn.microsoft.com/windows/win32/direct3ddxgi/dxgi-1-5-improvements), [IDXGIOutput5::DuplicateOutput1](https://learn.microsoft.com/windows/win32/api/dxgi1_5/nf-dxgi1_5-idxgioutput5-duplicateoutput1), [IDXGIOutput1::DuplicateOutput](https://learn.microsoft.com/windows/win32/api/dxgi1_2/nf-dxgi1_2-idxgioutput1-duplicateoutput), [Desktop duplication](https://learn.microsoft.com/windows-hardware/drivers/display/desktop-duplication-api), [HDR and advanced colour](https://learn.microsoft.com/windows/win32/direct3darticles/high-dynamic-range), [GraphicsCaptureSession](https://learn.microsoft.com/uwp/api/windows.graphics.capture.graphicscapturesession) (`IsBorderRequired`, `IsCursorCaptureEnabled`), [SendInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-sendinput), [MOUSEINPUT](https://learn.microsoft.com/windows/win32/api/winuser/ns-winuser-mouseinput), [Security considerations for assistive technologies](https://learn.microsoft.com/windows/win32/winauto/uiauto-securityoverview), [UAC policy for UIAccess in secure locations](https://learn.microsoft.com/windows/client-management/mdm/policy-csp-localpoliciessecurityoptions), [CreateSyntheticPointerDevice](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-createsyntheticpointerdevice), [InjectSyntheticPointerInput](https://learn.microsoft.com/windows/win32/api/winuser/nf-winuser-injectsyntheticpointerinput), [Loopback recording](https://learn.microsoft.com/windows/win32/coreaudio/loopback-recording), [AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS](https://learn.microsoft.com/windows/win32/api/audioclientactivationparams/ns-audioclientactivationparams-audioclient_process_loopback_params) | For [LUMEN-HOST-PLAN.md](LUMEN-HOST-PLAN.md): `DuplicateOutput1` takes a list of formats and can deliver HDR/WCG surfaces unconverted, the list should always hold `B8G8R8A8_UNORM`; E_ACCESSDENIED on the secure desktop unless LocalSystem; four duplicating processes per session by default; re-create after desktop switches and mode changes. WGC draws a border, removable only from build 20348 after user consent; cursor capture from 19041. `SendInput` is subject to UIPI and fails silently; absolute moves are 0..65535, `MOUSEEVENTF_VIRTUALDESK` maps to the whole virtual desktop; relative moves get pointer speed applied. UIAccess needs Authenticode signing, a secure install location and is meant for assistive technology. Synthetic touch/pen injection from Windows 10 1809. WASAPI loopback captures the render mix in shared mode; per-process loopback from build 20348. |
|
||||||
|
| S-23 | 2026-12-04 | NVIDIA [video-sdk-samples](https://github.com/NVIDIA/video-sdk-samples) at `aa3544d`: `Samples/NvCodec/NvEncoder/nvEncodeAPI.h` (API 8.1, sha256 `4d061c34…6042a`); NVIDIA [VideoProcessingFramework](https://github.com/NVIDIA/VideoProcessingFramework) at `e82364f`: `src/TC/third_party/nvEncodeAPI.h` (API 12.0, sha256 `067c5159…b4ad`); GitHub repository metadata of both | Both headers carry NVIDIA's MIT notice for the header file; the repositories are Apache-2.0 / unlicensed samples and the second is archived. Declarations used for the L0 spike shim (struct versions, preset and tuning enums, `NvEncGetEncodePresetConfigEx`, resource registration). No sample `.cpp` file was opened. |
|
||||||
|
| S-24 | 2026-12-04 | [NVENC Video Encoder API Programming Guide](https://docs.nvidia.com/video-technologies/video-codec-sdk/13.0/nvenc-video-encoder-api-prog-guide/index.html) (SDK 13.0) | Loading `nvEncodeAPI` at run time and `NvEncodeAPICreateInstance`; `NV_ENC_DEVICE_TYPE_DIRECTX` sessions; registering, mapping and unmapping D3D11 textures; tuning info (low latency, ultra low latency), presets P1-P7, CBR filler, forcing IDR, `NvEncInvalidateRefFrames`, intra refresh, look-ahead latency; lock/unlock of the bitstream; async mode only on Windows 10+ WDDM, recommended there; Main10 settings. |
|
||||||
|
| S-25 | 2026-12-04 | Licences via the GitHub and crates.io APIs and `COPYING` files: nefarius/ViGEmClient (MIT, archived), nefarius/ViGEmBus (BSD-3-Clause, archived), xiph/opus `COPYING` (BSD-style), crates `opus`, `audiopus_sys`, `vigem-client`, `nvidia-video-codec-sdk`, `nvenc`, `windows` | Licence and status only; no source files of these projects were opened. |
|
||||||
|
| S-30 | 2026-12-04 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc` (same pin as S-9): `src/rtsp.rs` again, read for the host side | BSD-2, facts only. One request per TCP connection, the note that Moonlight opens a connection per request; `CSeq` required (connection closed without it); no method order and no `Session` check; statuses 200/400/500 only; OPTIONS `Public`; SETUP needs `Transport` (400 without), stream from the first `streamid=` query segment, answer `Session: MoonshineSession;timeout = 90` and `Transport: server_port=<port>`; DESCRIBE line order and values (`featureFlags:3`, `encryptionSupported` 5 or 7, `sprop-parameter-sets=AAAAAU`, invalidation, AV1, H.264, surround lines); ANNOUNCE: the ten required attributes (400 when missing), the defaults of the optional ones (`maxNumReferenceFrames` 1, `dynamicRangeMode`/`chromaSamplingType`/`encoderCscMode`/`encryptionEnabled`/`surround.enable` 0, `numChannels` 2, `channelMask` 0x3, `AudioQuality` 1), `maxFPS` 0 refused, bitrate ×1000 must fit a u32, QoS off for `0`. The comments citing Sunshine, moonlight-common-c or GFE are logged as second-hand GPL facts above and not used. |
|
||||||
|
| S-31 | 2026-12-04 | Moonshine at `f184d5e`: `src/session/stream/mod.rs`, `src/session/stream/video/mod.rs`; the repository tree listing (GitHub API) | BSD-2, facts only. `bitStreamFormat` 0 H.264 (default), 1 HEVC, 2 AV1, others invalid; dynamic range 0 SDR (default), 1 HDR; chroma 0 4:2:0 (default), 1 4:4:4; valid video packet size 200..=65471 (one stream packet in an IPv6 UDP datagram), below 200 refused; FEC default 20 %. The bitrate comment citing Sunshine is logged above and not used. |
|
||||||
|
| S-32 | 2026-12-04 | [Wolf: RTSP](https://games-on-whales.github.io/wolf/stable/protocols/rtsp.html) again (as S-3); [RFC 2326](https://www.rfc-editor.org/rfc/rfc2326.txt) | Wolf: nothing new for the host (no per-method answers, no ANNOUNCE list). RFC 2326: reason phrases of 400, 451, 454, 455, 501 (7.1.1); a missing `Content-Length` means zero (4.4); OPTIONS may be sent at any time (10.1); session ids at least 8 random octets (3.4); `Public` as a comma-separated list (10.1 example). |
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# DomiStream — handover
|
||||||
|
|
||||||
|
## stream-v0.1.0 (2026-11-26)
|
||||||
|
|
||||||
|
The GameStream client, sans-I/O, for Arena Domi TV (Play remotely Day 1).
|
||||||
|
|
||||||
|
| Part | Module |
|
||||||
|
| :-- | :-- |
|
||||||
|
| pairing handshake (4-phase PIN exchange, client cert), serverinfo, app list, launch | `pairing`, `http` |
|
||||||
|
| RTSP client and framer, SDP | `rtsp` |
|
||||||
|
| ENet 1.3-compatible client peer | `enet` |
|
||||||
|
| control channel (AES-GCM, replay refusal), input and gamepad messages | `control`, `input` |
|
||||||
|
| RTP, Reed-Solomon FEC, video depacketizer (FEC recovery), Opus audio depacketizer (4 + 2 FEC) | `rtp`, `fec`, `video`, `audio` |
|
||||||
|
|
||||||
|
Evidence (worktree checks, 2026-11-26, every run gated on CPU, RAM and drives below 90 %):
|
||||||
|
- `cargo test --workspace`: **242 passed, 0 failed**. QA wrote the tests before the code; vectors come from OpenSSL
|
||||||
|
3.5, Python hashlib and .NET 10, with test-only keys.
|
||||||
|
- Mutation pass: **24 of 24 caught** (`docs/MUTATION.md`, rerunnable with `tools/mutation/mutate.py`).
|
||||||
|
- Fuzz: 25 targets × 60 s, **0 crashes**, from 59,665 (pairing_session) to 101 M (rtp_header) executions; then
|
||||||
|
pairing_session for 600 s: 574,761 runs, 0 crashes. Windows MSVC, SanitizerCoverage, libFuzzer (`fuzz/`).
|
||||||
|
- clippy `-D warnings`, fmt and rustdoc `-D warnings` are clean. `getrandom` is not in the dependency tree.
|
||||||
|
|
||||||
|
Open (see `docs/PROTOCOL.md` §UNKNOWN):
|
||||||
|
- **Interop unverified.** U1, U2, U4–U10 and U17 block a real stream; they are settled live on Play remotely Day 1
|
||||||
|
against the pinned Sunshine (Mark, 2026-11-25: "COntinue roadmap without the check"). Expect `stream-v0.1.x`.
|
||||||
|
- U16 (audio parity matrix: audio plays without it at zero loss) and U19 (video encryption layout).
|
||||||
|
- `tools/lab-relay` and its scripts were never run (`docs/LAB_CAPTURE.md`); they're kept for byte logs on Day 1.
|
||||||
|
- The live sitting is prepared: `tools/gs-probe` (a desktop probe client driving these state machines over real
|
||||||
|
sockets, built and unit-tested, never run against a host) and its run book `docs/LIVE-INTEROP.md`.
|
||||||
+4
-2
@@ -1,7 +1,9 @@
|
|||||||
# Lab capture: one GameStream session on Mark's PC
|
# Lab capture: one GameStream session on Mark's PC
|
||||||
|
|
||||||
Status: **plan, not run.** Mark allowed one capture (answer 16, 2026-11-25). Nothing below has been downloaded,
|
Status: **Not run.** Mark, 2026-11-25: "COntinue roadmap without the check". The relay and scripts are kept for byte
|
||||||
installed or started yet. The build lead relays the timeline (section 7) to Mark first.
|
logs during Day 1's live interop work; the scripts install nothing unless Mark approves a new step. The blocking
|
||||||
|
UNKNOWNs are settled live on Day 1 against the Sunshine that arena-host installs (Arena ROADMAP-REMOTE.md open
|
||||||
|
point 14).
|
||||||
|
|
||||||
Goal: settle the UNKNOWNs U1-U29 in [PROTOCOL.md](PROTOCOL.md) section 8 by watching **one** desktop stream between
|
Goal: settle the UNKNOWNs U1-U29 in [PROTOCOL.md](PROTOCOL.md) section 8 by watching **one** desktop stream between
|
||||||
the official Moonlight PC client and the pinned Sunshine, both on this PC, through **our own** logging relay.
|
the official Moonlight PC client and the pinned Sunshine, both on this PC, through **our own** logging relay.
|
||||||
|
|||||||
@@ -0,0 +1,324 @@
|
|||||||
|
# Live interop: the one sitting with Mark
|
||||||
|
|
||||||
|
Status: **prepared 2026-11-30, not run.** The probe (`tools/gs-probe`) is built and unit-tested and has never talked
|
||||||
|
to a host: no Sunshine existed when it was written.
|
||||||
|
|
||||||
|
This sitting settles the open UNKNOWNs of [PROTOCOL.md](PROTOCOL.md) §8 live, in one go, and answers the black-box
|
||||||
|
checks a GameStream client can answer from Arena `docs/PLAY-REMOTELY.md`. That list lives in its handover ("Next on
|
||||||
|
RESUME", item 3), §8 (the `pairing_id` call, the clients list) and §15 (the test-PC checks); §17 is the installer
|
||||||
|
spec and is not part of this sitting. The host is the pinned Sunshine
|
||||||
|
`v2026.914.233613`, installed by arena-host at Turn on to `E:\Apps\Sunshine` and bound to `192.168.100.140`. The
|
||||||
|
client is our probe, which runs DomiStream `stream-v0.1.0`'s state machines over real sockets from this PC. No
|
||||||
|
Moonlight, no TV and no other machine take part.
|
||||||
|
|
||||||
|
## 0. Hard limits
|
||||||
|
|
||||||
|
- **One address.** Every probe socket goes to `192.168.100.140`. If `sessionUrl0` names another host, the probe
|
||||||
|
records it and still connects only to .140.
|
||||||
|
- **No listening port on this PC.** During `launch` the probe has only three ephemeral UDP client sockets. Nothing
|
||||||
|
binds a fixed port.
|
||||||
|
- **Out folder:** `F:\build\play-remotely\live\<date>\` (E: is full). It is outside git and holds:
|
||||||
|
- `identity\`: the probe's test-only key and certificate, made on the first run;
|
||||||
|
- `runs\<utc>-<command>\`: one folder per command, with `log.jsonl` and the dumps.
|
||||||
|
|
||||||
|
It is deleted at the end (section 7).
|
||||||
|
- **Secrets:**
|
||||||
|
- The probe never prints its key and never logs the stream key (`rikey`), pairing salts, challenges or secrets.
|
||||||
|
- The PIN goes to the operator's terminal only, never to the log. Every log line is also scanned for the session
|
||||||
|
key's hex before it is written.
|
||||||
|
- Sunshine's API credentials stay in Custos: never typed, never on a command line, never in a log.
|
||||||
|
- **Nothing changes on Mark's PC** during the sitting: no Sunshine config, firewall, arena-host setting or install.
|
||||||
|
The only exceptions are the steps below that the run book names (pairing the probe, launching one game) and their
|
||||||
|
undo in section 7.
|
||||||
|
- **The stop-and-report rule** (section 6) wins over everything in this file.
|
||||||
|
|
||||||
|
## 1. What Mark sees
|
||||||
|
|
||||||
|
- **Nothing on his screen except:**
|
||||||
|
- Sunshine's own notifications, if any (for example when a client asks to pair, or a stream starts or ends);
|
||||||
|
- at `launch`, the game starting on his PC;
|
||||||
|
- at `quit`, the game closing.
|
||||||
|
- The probe runs in our terminal. No UAC prompt, no Custos card (Arena Domi was approved at Turn on), and no PIN is
|
||||||
|
shown to Mark.
|
||||||
|
- **Two things we cannot rule out before the sitting.** If either appears, Mark answers as below and we stop and
|
||||||
|
report:
|
||||||
|
- A **Windows Security Alert** for `probe.exe` when its UDP sockets first receive. Mark clicks **Cancel**.
|
||||||
|
- **Arena Domi's own first-stream toast** (PLAY-REMOTELY §7.4). It can appear if the Arena window is running when
|
||||||
|
Sunshine's prep-cmd hook reports the probe's stream. Mark dismisses it.
|
||||||
|
- **Mark's part:** be present, agree on the game for `launch` beforehand (a light one from the `apps` list), and keep
|
||||||
|
hands off mouse and keyboard while the stream runs (90 s for the first launch, about 30 s for any variant).
|
||||||
|
|
||||||
|
## 2. Before the sitting (without Mark)
|
||||||
|
|
||||||
|
| # | What | How |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| P1 | Probe built | `cd tools\gs-probe`, `CARGO_BUILD_BUILD_DIR=F:\build\play-remotely\cargo-build-probe`, `TEMP`/`TMP=F:\build\play-remotely\tmp\protocol`, load gate (CPU and RAM < 90 %, D: and F: < 95 %), then `cargo test --offline -j 2` and `cargo build --offline --release -j 2`. Binary: `tools\gs-probe\target\release\probe.exe`. |
|
||||||
|
| P2 | Sunshine as arena-host left it (read-only) | `Get-NetTCPConnection -State Listen \| ? LocalPort -in 47984,47989,47990,48010` shows each on `192.168.100.140` only: nothing on `0.0.0.0` or loopback on Day 1 (PLAY-REMOTELY §4). `Get-NetUDPEndpoint \| ? LocalPort -in 47998,47999,48000` is empty while idle (PLAY-REMOTELY §9). |
|
||||||
|
| P3 | Sunshine's API without seeing the credentials (**decided: a**, build lead 2026-11-30) | Needed for the PIN (step S2) and checks B1–B3. The host engineer writes a dev-only `sunshine-api <GET\|POST> <path> [json]` command in arena-host (Play remotely's own crate), behind a cargo feature that never ships. It takes the credentials from Custos (never typed, printed or logged), calls `https://192.168.100.140:47990` with arena-host's pinned client (§3, §4) and prints the answer with secrets redacted. Its first call also answers §15's "does `pc` cover a self-connection to .140". It must be built and checked before the sitting; this file writes the calls as `sunshine-api …`. |
|
||||||
|
| P4 | U10 bodies (**done** 2026-11-30, CLEAN_ROOM S-21) | Moonshine (BSD-2) reads **no body** from START_B, PERIODIC_PING or the IDR request, ignores LOSS_STATS and FRAME_STATS, and does not know START_A. Inside the encrypted frame, an unknown type is skipped, not fatal. Each PERIODIC_PING pushes its stop deadline out (60 s by default). Nothing taken has GPL provenance. The probe's defaults follow: START_A and START_B empty, PERIODIC_PING empty every 500 ms, an empty IDR request on frame loss. Table V holds what to try if Sunshine differs. |
|
||||||
|
| P5 | Game | Agree the `launch` game with Mark (a light one) and note its app id after S4. |
|
||||||
|
|
||||||
|
Shell variables used below (PowerShell):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$P = "F:\Akce\DomiStream-wt-probe\tools\gs-probe\target\release\probe.exe"
|
||||||
|
$O = "F:\build\play-remotely\live\2026-12-XX" # the sitting's date
|
||||||
|
$H = "192.168.100.140"
|
||||||
|
```
|
||||||
|
|
||||||
|
Exit codes: 0 done, 1 error, 2 bad command line, 3 **stop and report** (a `stop` record is in the log).
|
||||||
|
|
||||||
|
## 3. The sequence
|
||||||
|
|
||||||
|
Each step names the command, the UNKNOWNs it settles and what to look for. "Log" means that run's
|
||||||
|
`$O\runs\<utc>-<command>\log.jsonl` (format in section 4).
|
||||||
|
|
||||||
|
### S0. Preflight (read-only, 1 min)
|
||||||
|
|
||||||
|
- Run the P2 checks again.
|
||||||
|
- Sunshine's own traffic baseline (B4): `Get-NetTCPConnection -OwningProcess (Get-Process sunshine).Id` and
|
||||||
|
`Get-NetUDPEndpoint -OwningProcess …`. Note every remote address.
|
||||||
|
|
||||||
|
### S1. `& $P serverinfo --host $H --out $O`
|
||||||
|
|
||||||
|
- **Settles:** U25 (codec bits, from a host whose GPU we know: RTX 3090).
|
||||||
|
- **Look for:**
|
||||||
|
- `serverinfo.http` recv: status 200, the XML in full;
|
||||||
|
- the note with `parsed` and `codec_mode_support_bits`;
|
||||||
|
- `HttpsPort` (if it is not 47984, add `--https-port` to every later command);
|
||||||
|
- `appversion`, `state` (…`_FREE`), `PairStatus 0`.
|
||||||
|
- On the first run the probe generates its identity: log record `identity` (`generated a new …`).
|
||||||
|
|
||||||
|
### S2. `& $P pair --host $H --out $O`
|
||||||
|
|
||||||
|
- **Settles:**
|
||||||
|
- U1: the parameter names we send are accepted, and the order of steps 4 and 5;
|
||||||
|
- U2: our RSA-2048 self-signed certificate is accepted;
|
||||||
|
- U24: the TLS version and suite at step 5;
|
||||||
|
- with B1 and B2, PLAY-REMOTELY §8.
|
||||||
|
- **Procedure.** The probe prints `PIN for the operator: NNNN` and waits up to 120 s at step 1. Within that time:
|
||||||
|
1. **B1, the pending pairing.**
|
||||||
|
- Call each documented read-only GET of the pinned API docs (at least `sunshine-api GET /api/clients/list`).
|
||||||
|
- Look for an entry naming the probe's `uniqueid` (log record `identity`) or the device name
|
||||||
|
`DomiStream probe`.
|
||||||
|
- Read `E:\Apps\Sunshine\config\sunshine.log` (black-box: Sunshine's own log, read-only) for a line about the
|
||||||
|
incoming pairing and any id it names.
|
||||||
|
- Record which call or line shows the pending pairing and its `pairing_id`.
|
||||||
|
2. **Submit:** `sunshine-api POST /api/pin '{"pairing_id":"<id>","pin":"NNNN","name":"DomiStream probe"}'`. If no
|
||||||
|
`pairing_id` was found, try `{"pin":"NNNN","name":"DomiStream probe"}` once and record the answer. If that is
|
||||||
|
refused too: stop and report (B1 open, and pairing cannot go on).
|
||||||
|
3. The probe goes on by itself through steps 2–5 and ends with an HTTPS `serverinfo` (`PairStatus 1`).
|
||||||
|
- **Look for:**
|
||||||
|
- `pair.1` … `pair.5`: send and recv of each step (values redacted, names and order kept);
|
||||||
|
- `pair.1`'s `elapsed_ms` (the time until the PIN went in);
|
||||||
|
- the `host certificate sha256` note;
|
||||||
|
- `pair.5`'s `tls` (version, suite);
|
||||||
|
- `pair.done`;
|
||||||
|
- on failure, the `stop` record, with the step and the state it failed in.
|
||||||
|
- **B2:** `sunshine-api GET /api/clients/list` must show exactly one new client, named `DomiStream probe`. Record the
|
||||||
|
entry's fields: this is also B3's input.
|
||||||
|
|
||||||
|
### S3. `& $P apps --host $H --out $O`
|
||||||
|
|
||||||
|
- **Settles:** nothing new. It confirms HTTPS with the pinned certificate (U24 again).
|
||||||
|
- **Look for:** the agreed game's id (P5); `Desktop`, if listed, is the fallback.
|
||||||
|
|
||||||
|
### S4. `& $P launch <id> --host $H --out $O --seconds 90 --nudge-mouse`
|
||||||
|
|
||||||
|
90 s outlasts Moonshine's 60 s no-ping deadline. A stream that lives to the end shows Sunshine accepts the default
|
||||||
|
empty PERIODIC_PING, or does not need one within 90 s; `sunshine.log` tells which (U10). Variants use `--seconds 30`.
|
||||||
|
|
||||||
|
- **Mark sees** the game start.
|
||||||
|
- **Settles:**
|
||||||
|
|
||||||
|
| Area | UNKNOWNs |
|
||||||
|
| :-- | :-- |
|
||||||
|
| Launch | U4 |
|
||||||
|
| RTSP | U5, U6, U7, U26 |
|
||||||
|
| UDP setup | U8 |
|
||||||
|
| Control stream | U9, U10, U11 |
|
||||||
|
| Video | U13, U14, U15, U29; U19 only if the host offers video encryption |
|
||||||
|
| Audio | U17; data for U16 |
|
||||||
|
| Host events | U23, only if any arrive |
|
||||||
|
|
||||||
|
- **Look for**, in order:
|
||||||
|
|
||||||
|
| Record | Settles | What it shows |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| `launch` send/recv | U4 | Our parameter set accepted (`uniqueid, appid, mode, rikey=<redacted>, rikeyid, hdrMode, surroundAudioInfo`); `gamesession`, `sessionUrl0` |
|
||||||
|
| `rtsp.*` send/recv | U5 | Every request and answer in full; `end` (`Length` / `Closed` / `Idle`), `content_length_header`, and notes about new TCP connections |
|
||||||
|
| `rtsp.describe` recv | U26 | The SDP: every `surround-params` line, `encryptionSupported`, `featureFlags` |
|
||||||
|
| `rtsp.setup_*` recv | U5, U7 | Every header of the three answers (`Session`, `Transport`, anything extra) |
|
||||||
|
| `rtsp.announce` | U6 | 200 means our 19 attributes are accepted as they are |
|
||||||
|
| `ping` + `video.first` / `audio.first` | U8 | Payload `PING`; `pings_before` and the source port of the first packet |
|
||||||
|
| `control.datagram` (first 64 each way) | U9 | Decoded ENet: our connect, the host's verify connect (channel count, MTU, window, flags), anything stock 1.3 lacks (`unparsed: …` or `parse_error`) |
|
||||||
|
| `control.start_a`, `control.start_b` | U10 | What we sent (empty bodies by default). Video then flowing means the host accepted it |
|
||||||
|
| `control.periodic_ping` (first 3), `launch.summary` `control.ended` | U10 | The empty ping every 500 ms; `ended` null after 90 s means the pings kept the session alive |
|
||||||
|
| `control.host` | U10, U11, U23 | Every decrypted host message: type, sequence, body |
|
||||||
|
| `video.frame` (first 16) | U13 | `header_raw`: Wolf's constant `0137636861727373` or Moonshine's fields |
|
||||||
|
| `launch.summary` | U14 | `u14_*`: whole-packet parity matches (5.3 confirmed), or payload-only, or neither |
|
||||||
|
| `launch.summary` | U15 | `multi_fec_flags_u15` histogram |
|
||||||
|
| `launch.summary` | U29 | `u29_rtp_ticks_per_frame`, `u29_clock_hz_estimate` (90000 expected) |
|
||||||
|
| `launch.summary` | U17 | `u17_decrypting` vs `u17_plain`: the receiver that accepts the packets says whether audio is encrypted. Compare with bit 0x04 of `negotiated.encryption` |
|
||||||
|
| `launch.summary` | U19 | `decrypt_failures` is 0 when video encryption was negotiated |
|
||||||
|
| `audio.u16` | U16 | Matrix solved from `audio-packets.bin` (or later: `& $P solve-audio-fec <run>\audio-packets.bin`); `matrix_is_mds` |
|
||||||
|
| `launch.summary` counters | — | Video: `frames`, `decode_ready_frames`, `frames_lost`, `fec_recovered_shards`. Audio: data and parity packets, losses |
|
||||||
|
|
||||||
|
- **B3, per-device input:**
|
||||||
|
- The `--nudge-mouse` input is one relative move of +1 then −1 pixel after the first decodable frame:
|
||||||
|
harmless, and invisible to Mark.
|
||||||
|
- If the B2 entry has a per-client input field, an extra launch with that input turned off for the probe shows
|
||||||
|
whether Sunshine drops it (watch `sunshine.log`). That launch needs the build lead's OK: it changes a Sunshine
|
||||||
|
setting.
|
||||||
|
- If the entry has no such field, record "per-client: enable/disable only".
|
||||||
|
- **B4:** during the stream, list Sunshine's sockets again (S0). The three UDP ports appear, and no remote address
|
||||||
|
besides .140 shows up.
|
||||||
|
- **B5:** with arena-host running, the prep-cmd hook should report `start <game>` with
|
||||||
|
`SUNSHINE_CLIENT_NAME = DomiStream probe`, and arena-host should write its audit record "Play remotely started".
|
||||||
|
Record what happened.
|
||||||
|
- Then `& $P quit --host $H --out $O`: the game closes. B5 again: `end`.
|
||||||
|
|
||||||
|
**Variants (table V), only when S4 stops.** Each variant is one `launch` (with `quit` before the next). There are at
|
||||||
|
most 6 launches in the sitting, and the same variant is never tried twice.
|
||||||
|
|
||||||
|
| Symptom (log) | Variant |
|
||||||
|
| :-- | :-- |
|
||||||
|
| ANNOUNCE not 200 (U6) | `--encryption 1`, then `--codec hevc`, then `--packet-size 1392`. Attribute values beyond the CLI need a code change: stop and report |
|
||||||
|
| No verify connect, ENet `timed_out` (U9) | `--enet-channels 48`. Nothing else is known about the connect fields: stop and report |
|
||||||
|
| Connected, but the host ends the session right after START_A, or `sunshine.log` names an unknown control message (U10) | `--start-a none` (Moonshine has no START_A) |
|
||||||
|
| Connected but no video within 5 s of START_B (U10) | Read `sunshine.log` for what it says about START_B. If it names a body or a length, give that body with `--start-b <hex>` (one try). Otherwise stop and report: P4 found no body, and none is guessed |
|
||||||
|
| Video stops after N s, host disconnects (U10) | `--periodic-ping-ms 100`; if it still stops, `--periodic-ping none` (to see whether the empty ping is what the host refuses), then stop and report |
|
||||||
|
| Frames lost and never recovered (U10) | `--rfi`, if DESCRIBE has `refPicInvalidation`; else `--idr none`, to compare with the default empty request |
|
||||||
|
| Surround (U26), only if time allows | `--audio 5.1` |
|
||||||
|
|
||||||
|
### S5. U28, a refused pairing (optional, 2 min)
|
||||||
|
|
||||||
|
1. `& $P unpair --host $H --out $O`.
|
||||||
|
2. `& $P pair --host $H --out $O --wrong-pin`. The probe prints one PIN, uses another, and must stop at step 3 with
|
||||||
|
`ProofMismatch`.
|
||||||
|
3. Submit the printed PIN as in S2.
|
||||||
|
4. Look for:
|
||||||
|
- what `/api/pin` answers;
|
||||||
|
- whether B1's call still lists a pending pairing afterwards;
|
||||||
|
- whether the client list stays without the probe;
|
||||||
|
- whether a fresh `probe pair` works without any clean-up. That last point is U28's answer.
|
||||||
|
5. Leave it unpaired.
|
||||||
|
|
||||||
|
## 4. Reading the log
|
||||||
|
|
||||||
|
One JSON object per line, flushed as written:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"n":12,"t_ms":845.210,"step":"rtsp.setup_video","kind":"recv","u":["U5","U7"],"data":{…}}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`kind`:**
|
||||||
|
- `send`: what the probe sent;
|
||||||
|
- `recv`: what the host sent;
|
||||||
|
- `note`: an observation;
|
||||||
|
- `parse_error`: the parser's error plus the bytes that caused it (hex or text, capped at 4 KiB);
|
||||||
|
- `stop`: the stop-and-report rule fired;
|
||||||
|
- `summary`: the end-of-step counters.
|
||||||
|
- **`u`:** the UNKNOWNs the record bears on.
|
||||||
|
- **Filtering** (PowerShell):
|
||||||
|
`Get-Content log.jsonl | ConvertFrom-Json | ? { $_.u -contains 'U5' } | ConvertTo-Json -Depth 8`.
|
||||||
|
- **Run folder contents:**
|
||||||
|
- `video.h264` (or `.h265`): the first `--dump-frames` frames' Annex-B elementary stream, for `ffprobe` later.
|
||||||
|
The probe decodes nothing.
|
||||||
|
- `video-packets.bin`: plaintext video packets, `--dump-packets` of them.
|
||||||
|
- `audio-packets.bin`: audio datagrams as received.
|
||||||
|
|
||||||
|
The `.bin` files use the format in `tools/gs-probe/src/dump.rs`. **The video files hold frames of Mark's game:**
|
||||||
|
they never go into git and are deleted after analysis.
|
||||||
|
|
||||||
|
## 5. From the log to PROTOCOL.md and the code
|
||||||
|
|
||||||
|
1. **Facts first.** Each settled UNKNOWN gets its fact in PROTOCOL.md with the tag `[L2]` (live sitting, date,
|
||||||
|
Sunshine `v2026.914.233613`, probe commit). Add the tag to the tag table and the row to §8. An UNKNOWN that stays
|
||||||
|
open says why.
|
||||||
|
2. **Tests before code** (repo rule). Every fact becomes a unit test or vector in `crates/domistream`:
|
||||||
|
- structure and constants only;
|
||||||
|
- re-encrypted with keys generated in the test;
|
||||||
|
- never bytes of Mark's video.
|
||||||
|
3. **Where each U lands:**
|
||||||
|
|
||||||
|
| U | PROTOCOL.md | Code |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| U1, U28 | 1.5 | `pairing/mod.rs` (`request`, step order) |
|
||||||
|
| U2 | 1.5 | `pairing/identity.rs` (`generate`) |
|
||||||
|
| U4 | 1.4 | `http/launch.rs` (`launch_request`, the `sessionUrl0` default) |
|
||||||
|
| U5 | 2.1, 2.2 | `rtsp/mod.rs` (`RtspFramer`), `rtsp/client.rs` (`CLIENT_VERSION`, `SETUP_TARGETS`, `TRANSPORT`, `Session` echo, PLAY target) |
|
||||||
|
| U6 | 2.4 | `rtsp/sdp.rs` (`build_announce`) |
|
||||||
|
| U7 | 2.2 | `rtsp/client.rs` (`advance`, `NegotiatedStream`) |
|
||||||
|
| U8 | 5.1, 6.1 | `rtsp/client.rs` (`PING_PAYLOAD`); the ping interval in the platform layer's docs |
|
||||||
|
| U9 | 3.1 | the `EnetConfig` defaults the callers use (docs in `enet/mod.rs`); `enet/protocol.rs` only if the host sends something stock 1.3 lacks |
|
||||||
|
| U10 | 3.3 | `control/message.rs` (`encode_client_message`: START_A, START_B, PERIODIC_PING, IDR bodies instead of `Unsupported`), `control/mod.rs` (send PERIODIC_PING on `ping_interval`) |
|
||||||
|
| U11 | 3.2 | `control/mod.rs` (`next_sequence` start, replay rule) |
|
||||||
|
| U13, U15 | 5.2 | `video/packet.rs` (docs, `FrameHeader`) |
|
||||||
|
| U14 | 5.3 | `fec.rs`: confirmed, nothing to change (or stop and report if `u14_no_match`) |
|
||||||
|
| U16 | 6.4 | a `pub const` parity matrix in `audio/mod.rs`, used as `AudioFec::ParityMatrix` by the callers |
|
||||||
|
| U17 | 6.3 | `AudioConfig.cipher` policy (docs in `audio/mod.rs`) |
|
||||||
|
| U19 | 7 | `video/mod.rs` (`VideoCipher::decrypt`) |
|
||||||
|
| U23 | 3.3 | `control/message.rs` (host event bodies) |
|
||||||
|
| U25, U27 | 1.2, 1.1 | `http/serverinfo.rs`, `http/xml.rs` docs |
|
||||||
|
| U26 | 2.3 | `rtsp/sdp.rs` |
|
||||||
|
| U29 | 5.2 | `rtp.rs` / `video/mod.rs` docs |
|
||||||
|
|
||||||
|
4. **Re-run** clippy, fmt, rustdoc, the tests, the mutation script and the fuzz targets of the touched parsers (load
|
||||||
|
gate first).
|
||||||
|
5. **Re-run the probe** against Sunshine with the patched crate: `launch` with **no** variant flags must give
|
||||||
|
`decode_ready_frames > 0`, audio packets, and no `stop`. Then release `stream-v0.1.1` (HANDOVER).
|
||||||
|
6. **Arena:** B1–B5 answers go to Arena `docs/PLAY-REMOTELY.md` (handover, §8, §15). That file and arena-host are Play
|
||||||
|
remotely's own, so we write them; the seam files stay the Arena build lead's.
|
||||||
|
|
||||||
|
**Not settled by the probe:**
|
||||||
|
- U20, U21, U22: no keyboard, touch or gamepad input beyond the one mouse nudge.
|
||||||
|
- U24 beyond what rustls negotiates.
|
||||||
|
- U26 beyond stereo, unless the 5.1 variant runs.
|
||||||
|
- U19, if the host does not offer video encryption.
|
||||||
|
- U23, if no host event arrives.
|
||||||
|
|
||||||
|
`tools/lab-relay` cannot be used as it stands: its upstream must be loopback, and Sunshine listens on .140 only.
|
||||||
|
`--relay` is ready on the probe side if the build lead ever widens that rule. The probe's own log already holds the
|
||||||
|
plaintext of HTTP, HTTPS and RTSP, and the decrypted control messages.
|
||||||
|
|
||||||
|
## 6. Stop and report
|
||||||
|
|
||||||
|
**Stop** means: no further probe command, no Sunshine call beyond read-only GETs, no retry outside table V. Report to
|
||||||
|
the coordinator:
|
||||||
|
- the step;
|
||||||
|
- the log path and the record number `n`;
|
||||||
|
- what was expected;
|
||||||
|
- what was seen.
|
||||||
|
|
||||||
|
Then wait.
|
||||||
|
|
||||||
|
**Stop when:**
|
||||||
|
- a probe command exits with code 3 (a `stop` record), or with 1;
|
||||||
|
- anything appears on Mark's screen beyond section 1's list, or Mark asks to stop;
|
||||||
|
- any socket of the probe or of Sunshine talks to an address other than `192.168.100.140` or loopback;
|
||||||
|
- Sunshine crashes, restarts, or its notifications show an error;
|
||||||
|
- the game misbehaves, or the PC slows down noticeably;
|
||||||
|
- an answer fits none of the expectations above, even if the probe accepted it;
|
||||||
|
- table V is used up (6 launches), or a variant would need a code change, a Sunshine setting or an install;
|
||||||
|
- a secret shows up anywhere it should not (terminal, log, file name). Stop at once and delete the record.
|
||||||
|
|
||||||
|
## 7. Clean-up (same sitting)
|
||||||
|
|
||||||
|
1. `& $P quit --host $H --out $O`, if a game is still running.
|
||||||
|
2. `& $P unpair --host $H --out $O`, then B2 again: the client list no longer shows the probe.
|
||||||
|
3. Delete `$O\identity\` (the probe's test key).
|
||||||
|
4. **The run folders stay** until the facts are in PROTOCOL.md and the tests are in. Then they are deleted on the
|
||||||
|
build lead's word. `video.*` and `video-packets.bin` go first, right after the U13/U14/U15/U29 analysis.
|
||||||
|
5. Nothing to undo on Sunshine, arena-host or the firewall: nothing was changed.
|
||||||
|
|
||||||
|
## 8. Timeline for Mark (about 20 minutes)
|
||||||
|
|
||||||
|
| When | What happens | Mark |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| 0:00 | S0, S1: read-only checks, `serverinfo` | nothing |
|
||||||
|
| 0:02 | S2: the probe pairs (we submit the PIN through Sunshine's API). Sunshine may show a notification | nothing |
|
||||||
|
| 0:05 | S3, S4: the agreed game starts on his PC and streams to the probe for 90 s; then we close it | hands off mouse and keyboard while it runs |
|
||||||
|
| 0:07-0:15 | Variants, only if needed (up to 6 launches, each about 1 min) | same |
|
||||||
|
| 0:15 | S5 (optional), clean-up | nothing |
|
||||||
|
| later | Analysis offline; the game frames are deleted | nothing |
|
||||||
@@ -0,0 +1,568 @@
|
|||||||
|
# Lumen host: the plan
|
||||||
|
|
||||||
|
Status: **plan, 2026-12-04; Mark's go for phase one (L0 + L1) on 2026-12-04**, with all six decisions of section 8
|
||||||
|
accepted as proposed. Later milestones start after phase one is reported.
|
||||||
|
|
||||||
|
Goal (Mark, 2026-12-04): "move away from Sunshine". Today Arena Domi's Play remotely wraps Sunshine, a separate
|
||||||
|
GPL-3.0 program that Arena Domi installs and drives only through its local settings API. Lumen is Arena Domi's own
|
||||||
|
streaming host. It replaces Sunshine on the PC, so that Arena Domi Remote (Android), the Windows client and Arena
|
||||||
|
Domi TV stream from Lumen instead. Sunshine stays as a hidden fallback until Mark removes it.
|
||||||
|
|
||||||
|
This file is public, like the rest of DomiStream. It holds the architecture, the split between DomiStream and the
|
||||||
|
private Arena Domi repository, the milestones, the risks and the tests. Network addresses, the owner's devices beyond the
|
||||||
|
reference PC's hardware, and the private Play remotely design stay in Arena's `docs/ROADMAP-REMOTE.md` (section
|
||||||
|
"Lumen host").
|
||||||
|
|
||||||
|
Words used here:
|
||||||
|
- **host**: the PC that runs the game and streams it; **client**: the phone, TV or PC that shows it.
|
||||||
|
- **GameStream**: the protocol that Sunshine and the Moonlight-family clients speak, as described in
|
||||||
|
[PROTOCOL.md](PROTOCOL.md).
|
||||||
|
- **lumen-host**: the Windows program that is the Lumen host (section 1.1).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 0. Ground rules this plan keeps
|
||||||
|
|
||||||
|
- **Clean room** ([CLEAN_ROOM.md](CLEAN_ROOM.md)). No code of Sunshine, Moonlight (any client, including
|
||||||
|
moonlight-common-c), Apollo, Vibeshine, Rubylight or chiaki is opened, pasted or ported. That includes the GPL
|
||||||
|
fork that Arena Domi Remote is built from: its workspace is never opened by anyone working on Lumen, and nothing
|
||||||
|
of it enters a Domi repository. Host-side facts come from the Wolf docs, Moonshine (a BSD-2 host, see 6.1), stock
|
||||||
|
ENet, tokio-enet, fec-rs, public OS and SDK documentation, and our own measurements. Every source is logged in the
|
||||||
|
source log in the same PR that uses it.
|
||||||
|
- **Sans-I/O protocol code stays here**; sockets, TLS, the GPU, audio devices and input injection live in the
|
||||||
|
program that uses DomiStream (section 3).
|
||||||
|
- **Hostile input**: everything a client sends is parsed strictly, every length is capped before it allocates, and
|
||||||
|
every parser has a fuzz target.
|
||||||
|
- **No admin rights.** lumen-host runs as the signed-in user, never as a service or as SYSTEM. The only elevation
|
||||||
|
in the plan is the one Mark already allowed at "Turn on Play remotely", and whether Lumen's firewall rules may use
|
||||||
|
it is decided: D1, yes, the same single step.
|
||||||
|
- **Nothing leaves the PC by default.** lumen-host listens only on the addresses Play remotely allows; every
|
||||||
|
session start and stop is audit-recorded, like today.
|
||||||
|
- **No injection into a game process, no DirectX/Vulkan hooks, no reading game memory.** Lumen captures the display
|
||||||
|
the game is shown on and injects input through public Windows input APIs, like a keyboard, mouse or pad would.
|
||||||
|
- **Measure, don't guess.** Every latency claim comes from the harness (section 7.4).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Host architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
lumen-host (one process, signed-in user, medium integrity)
|
||||||
|
┌──────────────────────────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ capture ──► colour convert + scale ──► encode ──► packetize + FEC ──► pace ──► UDP video │
|
||||||
|
│ (DXGI dup., (GPU shader: FP16 scRGB (NVENC, (DomiStream │ │
|
||||||
|
│ FP16 or → NV12 BT.709 or P010 zero copy) host side) │ │
|
||||||
|
│ BGRA8) BT.2020 PQ, limited/full) │ │
|
||||||
|
│ WASAPI loopback ──► resample ──► Opus ──► packetize + FEC + AES-CBC ─────────► UDP audio │
|
||||||
|
│ control (ENet host + AES-GCM) ◄──► input mapper ──► SendInput / ViGEmBus / pointer inject │
|
||||||
|
│ HTTP/HTTPS (pairing, serverinfo, applist, launch) and RTSP (session setup), TLS via rustls │
|
||||||
|
│ session: launch game from Arena's library, watch it, game mode, audit, end │
|
||||||
|
└──────────────────────────────────────────────────────────────────────────────────────────┘
|
||||||
|
▲ arena-host (in Arena Domi): turns Lumen on/off, pairing gate, grants, which engine per device
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.1 Process model
|
||||||
|
|
||||||
|
- **One program, `lumen-host.exe`**, separate from the Arena Domi window and from the tray agent. A crash in it
|
||||||
|
never takes the window or the agent down, and it can be stopped cleanly.
|
||||||
|
- **Two states.** *Idle*: only the HTTP/HTTPS and RTSP listeners are open (a few sockets, no GPU, no audio device,
|
||||||
|
no threads busy), so a phone can see the PC and pair. *Streaming*: capture, encode, audio and input start when a
|
||||||
|
paired client launches a game, and stop when the session ends. One streaming session at a time in the first
|
||||||
|
version.
|
||||||
|
- **Started by Arena Domi**, never by Windows as a service. Who starts it at sign-in (the tray agent is the natural
|
||||||
|
owner, because it always runs) is decided: D4, the tray agent, once Lumen is the default.
|
||||||
|
- **Priorities**: the idle listeners run at below-normal priority. While streaming, the capture/encode thread and
|
||||||
|
the packet pacer register with the Multimedia Class Scheduler Service (no admin needed) and everything else stays
|
||||||
|
normal or below. The cost to the game is measured (section 7.4), not assumed.
|
||||||
|
|
||||||
|
### 1.2 Capture
|
||||||
|
|
||||||
|
| | DXGI Desktop Duplication (`IDXGIOutput5::DuplicateOutput1`) | Windows.Graphics.Capture |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| What it captures | a whole output (monitor), any game shown on it, fullscreen included | a monitor or one window |
|
||||||
|
| HDR | yes: pass a list of formats that includes `R16G16B16A16_FLOAT` and the FP16 scRGB desktop arrives without conversion | yes, by choosing the frame pool's pixel format |
|
||||||
|
| Capture border | none | a yellow border; it can be turned off only from Windows 10 build 20348 (`IsBorderRequired`) and after the user grants borderless access |
|
||||||
|
| Cursor | given separately (shape + position): we draw it, or not | `IsCursorCaptureEnabled` from Windows 10 2004 |
|
||||||
|
| Limits | E_ACCESSDENIED on the secure desktop (UAC prompt, lock screen) unless the process runs as LocalSystem; at most four duplicating processes per session by default; must be re-created after a mode change or a fullscreen switch | per-window capture survives window moves; needs the WinRT interop |
|
||||||
|
|
||||||
|
**Choice: Desktop Duplication first, Windows.Graphics.Capture as a later option** for single-window streaming on
|
||||||
|
Windows 11, where the border can be turned off. Reasons: the reference PC runs Windows 10 22H2 (build 19045), where
|
||||||
|
WGC would draw a yellow border over the game; duplication captures exclusive-fullscreen games; and it hands us FP16
|
||||||
|
directly. Sources: S-22 (section 9).
|
||||||
|
|
||||||
|
- **DPI awareness**: lumen-host is per-monitor DPI aware (v2). Measured in L0: without it `DuplicateOutput1`
|
||||||
|
fails with `DXGI_ERROR_UNSUPPORTED` and output sizes are DPI-virtualised.
|
||||||
|
- **Formats asked for**: `R16G16B16A16_FLOAT`, `R10G10B10A2_UNORM`, `B8G8R8A8_UNORM` (the last one always, as
|
||||||
|
Microsoft asks). The format that arrives decides the colour path (1.3).
|
||||||
|
- **Frames only on change**: duplication delivers a frame only when something changed. The pacer repeats the last
|
||||||
|
encoded frame (or sends nothing, if the client tolerates gaps; measured) so that the client sees its frame rate.
|
||||||
|
- **The secure desktop** (UAC prompt, lock screen, Ctrl+Alt+Del) cannot be captured without SYSTEM rights, and
|
||||||
|
input cannot reach it either (1.6). lumen-host keeps the stream alive and sends a still frame that says "Finish
|
||||||
|
this on the PC", then resumes when the desktop comes back (`EVENT_SYSTEM_DESKTOPSWITCH` / re-creating the
|
||||||
|
duplication). This is an accepted limitation of the no-admin rule, not a bug to fix later.
|
||||||
|
- **Which monitor** (the reference PC has a 1440p HDR primary display and a 2160p second display):
|
||||||
|
1. the monitor that shows the launched game's main window (found from the game's process, re-checked when the
|
||||||
|
window moves);
|
||||||
|
2. otherwise the client's own choice ("Stream this display", per device, in Settings → Play remotely);
|
||||||
|
3. otherwise the primary monitor.
|
||||||
|
A monitor switch during a stream re-creates the duplication and sends an IDR frame; the client keeps its
|
||||||
|
resolution.
|
||||||
|
- **Resolution**: the client asks for a size in ANNOUNCE. Lumen never changes the PC's display mode in the first
|
||||||
|
version (the owner's desktop stays as it is); it scales on the GPU in the colour pass (for example 2160p to 1080p
|
||||||
|
for a phone) and keeps the aspect ratio with black bars. A virtual display per client is roadmap Day 6.
|
||||||
|
- **GPU**: the duplication device is created on the adapter that drives the output. If the encoder is on another
|
||||||
|
adapter (laptops), one cross-adapter copy is made; on the reference PC both are the same GPU, so there is no copy.
|
||||||
|
|
||||||
|
### 1.3 Colour: SDR, HDR, limited or full range
|
||||||
|
|
||||||
|
The rule: **what the phone shows must look like what the PC shows**, for the same content, so the colour path is
|
||||||
|
explicit at every step and tested with patterns (7.5).
|
||||||
|
|
||||||
|
| Desktop (capture format) | Client asks for | Conversion on the GPU (one compute pass, fused with scaling and the cursor) | Encoder input | Signalled in the bitstream (VUI) |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| SDR (BGRA8, sRGB) | SDR | RGB → Y'CbCr BT.709, limited or full range | NV12 | BT.709 primaries, transfer and matrix; full-range flag as negotiated |
|
||||||
|
| HDR (FP16 scRGB, linear) | SDR | scale by the display's **SDR white level** (so SDR apps keep the brightness they have on the PC), tone-map highlights above SDR white with a fixed curve, encode with the sRGB/BT.709 transfer | NV12 | as above |
|
||||||
|
| HDR (FP16 scRGB) | HDR | linear BT.709 → BT.2020 primaries → PQ (SMPTE ST 2084), 10-bit | P010 | BT.2020, PQ, BT.2020 non-constant matrix; mastering metadata from the output's description (`IDXGIOutput6::GetDesc1`) |
|
||||||
|
| HDR10 game in `R10G10B10A2` | HDR | pass through when the output is already in BT.2020/PQ | P010 | as above |
|
||||||
|
|
||||||
|
- **Range**: the client tells the host its colour space and range in ANNOUNCE (`encoderCscMode`, PROTOCOL.md 2.4).
|
||||||
|
The bit meanings are **unknown** (U6 territory); they are settled by measurement: what Arena Domi Remote and our
|
||||||
|
own clients send for each of their settings, and how the decoded test pattern looks (7.5). Until a client's value
|
||||||
|
is understood, Lumen uses **BT.709 limited range** for SDR, the most common decoder default, and says so in the
|
||||||
|
stream's VUI, so a correct decoder shows correct colours either way.
|
||||||
|
- **HDR to the client** needs the host-to-client HDR message (`0x010e`, PROTOCOL.md 3.3). Its layout is
|
||||||
|
GPL-provenance ([M*]): it is **not** used from Moonshine's note; it is settled by our own measurement (6.2) before
|
||||||
|
Lumen sends HDR. Until then Lumen streams SDR to every client, tone-mapped as above.
|
||||||
|
- **Chroma**: 4:2:0 first. 4:4:4 (text mode) is roadmap Day 5.
|
||||||
|
- The SDR white level is read per display from Windows (`DisplayConfigGetDeviceInfo`, SDR white level), not
|
||||||
|
assumed.
|
||||||
|
|
||||||
|
### 1.4 Encode
|
||||||
|
|
||||||
|
- **NVENC first** (the reference PC has an NVIDIA Ampere GPU: H.264 and HEVC 8/10-bit encode; AV1 encode needs a
|
||||||
|
newer generation). AMD AMF and Intel Quick Sync come later behind the same `Encoder` trait, and Media Foundation's
|
||||||
|
hardware encoder is the generic fallback.
|
||||||
|
- **Zero copy**: the colour pass writes into a D3D11 texture that is registered with NVENC as an input resource, so
|
||||||
|
a frame never leaves the GPU between capture and the bitstream. The bitstream (a few kilobytes) is the only thing
|
||||||
|
read back to the CPU.
|
||||||
|
- **Low-latency settings** (named here as the NVENC programming guide names them; the guide is read and logged in
|
||||||
|
milestone L0 before any of this is written): ultra-low-latency tuning, no B-frames, no look-ahead, CBR with a VBV
|
||||||
|
of about one frame, an infinite GOP with IDR only on request, reference-frame invalidation when the client reports
|
||||||
|
a lost range (`INVALIDATE_REF_FRAMES`) and supports it, optional intra refresh instead of IDR frames, and slices
|
||||||
|
sized to the video packet size where that helps the FEC blocks.
|
||||||
|
- **Codec choice**: HEVC by default (smaller frames at the same quality, HDR possible), H.264 for clients without
|
||||||
|
HEVC; the client's ANNOUNCE (`bitStreamFormat`) decides, within what serverinfo advertised.
|
||||||
|
- **Bitrate**: from the client's request (`configuredBitrateKbps`), capped by what the encoder supports; adaptive
|
||||||
|
bitrate belongs to Lumen's own transport (roadmap Day 4).
|
||||||
|
- **Interface to NVENC**: NVIDIA's public API header and the driver's `nvEncodeAPI64.dll`, loaded at run time, so
|
||||||
|
nothing of NVIDIA ships in Arena Domi. The header is MIT-licensed by its own notice; L0 settled which one (section
|
||||||
|
10: API 12.0, because current drivers refuse the older API's presets). We do not read
|
||||||
|
the source of GPL or LGPL projects that wrap NVENC (FFmpeg, OBS Studio and the like); see 6.1.
|
||||||
|
|
||||||
|
### 1.5 Audio
|
||||||
|
|
||||||
|
- **Capture**: WASAPI loopback on the default render device (shared mode), which is the full mix the PC plays.
|
||||||
|
Per-process loopback (only the game, without voice chat or notifications) needs Windows 10 build 20348 or newer,
|
||||||
|
so it is an option for Windows 11 PCs, not the reference PC. Sources: S-22.
|
||||||
|
- **The PC keeps its own sound** in the first version (Lumen changes no audio setting). Muting the PC's speakers
|
||||||
|
while streaming is a later, opt-in choice.
|
||||||
|
- **Encode**: libopus (BSD-3-Clause) through a Rust binding whose licence is checked and logged; 48 kHz, stereo
|
||||||
|
first, 5.1/7.1 when the surround mapping is measured (U26). Frame duration from ANNOUNCE (`packetDuration`),
|
||||||
|
constant bitrate, because the audio FEC needs equally long packets (PROTOCOL.md 6.4).
|
||||||
|
- **Audio FEC** needs the parity matrix (U16), which is GPL-provenance. Lumen first sends audio **without** parity
|
||||||
|
packets and checks that every client plays it (6.2); the matrix is then measured and solved by us (PROTOCOL.md
|
||||||
|
U16) before parity is sent.
|
||||||
|
- **Audio encryption**: AES-128-CBC with the session key, as PROTOCOL.md 6.3 says (DomiStream already holds the
|
||||||
|
cipher; the host needs the encrypt side).
|
||||||
|
|
||||||
|
### 1.6 Input injection
|
||||||
|
|
||||||
|
Everything a client sends arrives as INPUT_DATA on the control channel (PROTOCOL.md section 4). DomiStream already
|
||||||
|
parses it (`input::parse_input`); lumen-host maps each event to a Windows call.
|
||||||
|
|
||||||
|
| Event | Windows call | Notes |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| Mouse relative move | `SendInput`, `MOUSEEVENTF_MOVE` | what games read (raw input). Windows applies the pointer-speed settings to relative moves on the desktop; games reading raw input get the raw delta |
|
||||||
|
| Mouse absolute move | `SendInput`, `MOUSEEVENTF_ABSOLUTE \| MOUSEEVENTF_VIRTUALDESK` | the client's position (in the stream's picture) is mapped to the streamed monitor's rectangle inside the virtual desktop, then to 0..65535. The mapping is a pure function with tests (letterboxing, scaling, monitors at negative coordinates) |
|
||||||
|
| Buttons, wheel, horizontal wheel | `SendInput` | wheel in multiples of 120, high-resolution deltas passed through |
|
||||||
|
| Keyboard | `SendInput` with **scan codes** (`KEYEVENTF_SCANCODE`) | many games read scan codes, not virtual keys. A pure table maps GameStream key codes (PROTOCOL.md 4, Wolf's key table) to scan codes. Text (UTF8_TEXT) goes as `KEYEVENTF_UNICODE` |
|
||||||
|
| Gamepad | **ViGEmBus** (Mark: "ViGEmBus for now"), through the MIT-licensed ViGEmClient library or a binding of it (licence logged) | one virtual Xbox 360 or DualShock 4 pad per client pad (CONTROLLER_ARRIVAL decides the type), rumble back to the client as RUMBLE_DATA. If ViGEmBus is not installed, pads are refused with a plain message, nothing else breaks. Our own virtual gamepad driver replaces it later (open point 13 of the roadmap) |
|
||||||
|
| Touch, pen (later) | `InjectSyntheticPointerInput` (Windows 10 1809+) | only when a client sends real touch (TOUCH/PEN layouts are U21); not needed for touch-to-mouse below |
|
||||||
|
|
||||||
|
**Touch-to-mouse, designed deliberately.** The 2026-12-04 evidence: the phone sent only *relative* mouse moves and
|
||||||
|
left-button press/release, never an absolute position. So a tap could not click where the finger was. The mapping
|
||||||
|
we want on every touch client:
|
||||||
|
|
||||||
|
| Gesture on the phone | What the PC gets |
|
||||||
|
| :-- | :-- |
|
||||||
|
| finger down and up without moving (tap) | absolute move to that point, left press, left release |
|
||||||
|
| long press (finger still for 500 ms; the threshold is tuned by tests) | absolute move to that point, right press, right release; the client vibrates once |
|
||||||
|
| one-finger drag after the finger moved | absolute moves while the finger moves, left held from the start (drag and drop) |
|
||||||
|
| two-finger drag | wheel (vertical) and horizontal wheel, in proportion to the distance, no button |
|
||||||
|
| two-finger tap | right click at the midpoint (desktop habit; optional) |
|
||||||
|
|
||||||
|
The gesture recogniser is **client-side** and pure, so it lives in DomiStream (`input::touch`, new) and every Arena
|
||||||
|
client uses the same code. It turns timed touch points into GameStream events (MOUSE_MOVE_ABS with the stream's
|
||||||
|
reference size, buttons, scroll); lumen-host only maps absolute positions correctly. For **Arena Domi Remote**,
|
||||||
|
which is a GPL app no Lumen worker may read, the same behaviour is handed over as a **written specification with
|
||||||
|
test cases** (gesture in, packets out), never as code, and its own workers implement it there. The input e2e
|
||||||
|
(7.3) checks the result against the PC, whatever client produced it.
|
||||||
|
|
||||||
|
**Integrity levels (UIPI).** `SendInput` reaches only windows of equal or lower integrity, and the failure is
|
||||||
|
silent. lumen-host runs at medium integrity, so:
|
||||||
|
- a game or launcher that runs **as administrator** gets no input from Lumen. lumen-host checks the foreground
|
||||||
|
window's process integrity when input starts failing to land and tells the client "This game runs as
|
||||||
|
administrator, so Arena Domi can't control it", once per session;
|
||||||
|
- the **secure desktop** (UAC prompts, lock screen) gets no input (and no capture, 1.2);
|
||||||
|
- `uiAccess` in the manifest would lift the first limit only for a signed program installed under Program Files,
|
||||||
|
and Microsoft reserves it for assistive technology. The plan does not use it (D6, accepted).
|
||||||
|
|
||||||
|
### 1.7 Sessions and launching games
|
||||||
|
|
||||||
|
Sunshine needs an app list written through its API and a hook program (`prep-cmd`) to learn when a game starts.
|
||||||
|
Lumen does not:
|
||||||
|
- **App list** = Arena Domi's visible library, read directly (the same mapping Play remotely uses today: Steam and
|
||||||
|
Epic by their launcher links, GOG and manual games by their `.exe` and folder; web games skipped). The ids clients
|
||||||
|
see are stable per game. Covers come from Arena Domi's own cover source, as today.
|
||||||
|
- **Desktop** is not in the list by default. It becomes a per-device choice ("Allow this device to see the whole
|
||||||
|
desktop"), off for TVs; phones use it with touch-to-mouse.
|
||||||
|
- **Launch**: lumen-host starts the game through the same launch path the Arena Domi window uses, watches for its
|
||||||
|
process and window (to pick the monitor, 1.2), turns game mode on, records "Play remotely started: <game> on
|
||||||
|
<device>" in the audit log, and starts the streams.
|
||||||
|
- **Quit game**: lumen-host asks the game to close (closes its main window), waits up to 10 seconds, and if it is
|
||||||
|
still running leaves it running and tells the client "The game is still open on the PC". It never kills a game
|
||||||
|
(unsaved progress). Ending the session turns game mode off and records "Play remotely ended".
|
||||||
|
- **Client gone without Quit** (TV switched off): the control channel times out (PROTOCOL.md 3.3: periodic pings),
|
||||||
|
the stream stops at once, the game keeps running, and the session ends after a grace period so the device can
|
||||||
|
come back (`resume`).
|
||||||
|
|
||||||
|
### 1.8 Network
|
||||||
|
|
||||||
|
- **GameStream first**, unchanged on the wire, so that clients that speak GameStream work without changes: our own
|
||||||
|
`gs-probe`, Arena Domi Remote, and Arena Domi TV (built on DomiStream). lumen-host speaks HTTP and HTTPS
|
||||||
|
(serverinfo, pairing, applist, launch, resume, cancel), RTSP (OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY), the ENet
|
||||||
|
control channel with AES-GCM, RTP video with Reed-Solomon FEC, and RTP Opus audio with AES-CBC.
|
||||||
|
- **Binding**: lumen-host binds every listening socket itself, to exactly the addresses Play remotely allows (the
|
||||||
|
Via Domi interface, loopback, and the home network only where Mark's decisions say so). Unlike Sunshine, Lumen can
|
||||||
|
bind several addresses at once, so the loopback/VPN forwarder planned for Sunshine is not needed for Lumen.
|
||||||
|
- **Beside Sunshine**: while both are installed, Lumen uses its own port base (Sunshine's default ports + 1000:
|
||||||
|
HTTP 48989, HTTPS 48984, RTSP 49010, video 48998, control 48999, audio 49000), so the two never collide.
|
||||||
|
A GameStream client learns the HTTPS port from serverinfo, the RTSP address from the launch answer and the stream
|
||||||
|
ports from RTSP (PROTOCOL.md sections 0, 1.2, 1.4; U4 and U5 say what is still to confirm), so a client only needs
|
||||||
|
"this PC on port 48989". Whether Arena Domi Remote accepts a host with a port is checked
|
||||||
|
black-box in L1 (risk R10). When Sunshine is gone, Lumen can take the standard ports.
|
||||||
|
- **Then Lumen's own transport** (roadmap Day 4, a separate plan): frame-aware packets, adaptive FEC, slice pacing,
|
||||||
|
an input lane and congestion control inside the Via Domi tunnel, chosen by Arena clients through a capability
|
||||||
|
flag, with GameStream as the fallback. Nothing in this plan's milestones depends on it.
|
||||||
|
|
||||||
|
### 1.9 Pairing: Tessera grants, no PIN for Arena clients
|
||||||
|
|
||||||
|
GameStream pairing proves, with a 4-digit PIN, that a client certificate belongs to someone the owner trusts. Arena
|
||||||
|
Domi already decides trust another way: every device holds its own key, and the PC's owner grants it Play remotely
|
||||||
|
with one click (no PIN, no code, Mark's decision). With Lumen, the host side of pairing is ours, so:
|
||||||
|
- **Arena clients (Arena Domi TV, our Windows and Android clients)**: the device's grant decides. The device sends
|
||||||
|
its signed pair request to Arena Domi as today; when the grant holds, lumen-host completes the GameStream pairing
|
||||||
|
for that device's client certificate itself, without a PIN anywhere (no PIN generated by the client to forward,
|
||||||
|
no submission to another program). A device that already holds a grant from the Sunshine days is accepted by
|
||||||
|
Lumen without asking the owner again.
|
||||||
|
- **Arena Domi Remote (today)**: it pairs the GameStream way. The owner types the 4 digits the phone shows into
|
||||||
|
Arena Domi's "Enter the code from your phone" box, exactly as with Sunshine today; lumen-host holds the pending
|
||||||
|
pairing and the box supplies its PIN. The same box, the same click count. Whether Arena Domi Remote should learn
|
||||||
|
the grant-based pairing instead was decided against (D5): it keeps the code box.
|
||||||
|
- **The host's identity**: the GameStream host certificate and its RSA key are made by lumen-host on first run and
|
||||||
|
the key is kept in Custos, never in a file. The PC's Play remotely signing key (Tessera) stays what it is.
|
||||||
|
- **Pairing state** (paired client certificates, which device they belong to) is public data on disk, each record
|
||||||
|
signed by the host key; an edited record fails its signature and is dropped.
|
||||||
|
- Clients paired with Sunshine are **not** imported into Lumen (that would mean reading Sunshine's state and
|
||||||
|
copying its identity). Each client pairs with Lumen once; for Arena clients that is invisible (the grant carries
|
||||||
|
over), for Arena Domi Remote it is one typed code.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Migration: Lumen beside Sunshine, then instead of it
|
||||||
|
|
||||||
|
| Stage | What changes | Who sees it |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| A. Beside | lumen-host runs on its own ports (1.8) next to Sunshine, turned on by a hidden developer switch. Only test clients use it | nobody |
|
||||||
|
| B. Per client | Arena Domi keeps an **engine per device** (`sunshine` or `lumen`). Arena Domi TV learns its engine and port from the "Find my PC" answer, so it switches with no action. Arena Domi Remote gets Lumen as a second entry for the same PC (or by its own update) | the owner, in Settings → Play remotely → Devices ("Streams with: Lumen") |
|
||||||
|
| C. Switch | a client moves to Lumen when Lumen passes **the same end-to-end suite** for that client as Sunshine does (7.6) and the harness shows Lumen's median and p95 at least as good (the roadmap's Day 3 gate). Order: gs-probe and the Windows client, then Arena Domi Remote, then Arena Domi TV | each switch is reported to Mark with its evidence |
|
||||||
|
| D. Default | Lumen is the default engine for every client. Sunshine is a hidden fallback under "Show expert options" (roadmap J4): still installed, used only for a device set to it | "Sunshine" appears only under expert options |
|
||||||
|
| E. Removal | when Mark says so, Arena Domi removes the Sunshine **it installed** with the existing single elevated step (it also removes the firewall rules named for Sunshine), and Lumen moves to the standard ports. A Sunshine that was on the PC before Arena Domi is left alone, as today | one UAC prompt, at Mark's request |
|
||||||
|
|
||||||
|
- **Fallback while both exist**: if lumen-host fails to start a session, Arena clients may retry on Sunshine
|
||||||
|
automatically (stages B to D), and the failure is reported, never hidden.
|
||||||
|
- **Uninstalling Arena Domi** removes lumen-host, its firewall rules (in the same single elevated step that removes
|
||||||
|
the others), its pairing records and its host key in Custos. Nothing of Lumen survives an uninstall.
|
||||||
|
- **Turning Play remotely off** stops lumen-host; the firewall rules stay until uninstall (Mark's rule for
|
||||||
|
Sunshine's rules, applied to Lumen's).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. What lives where
|
||||||
|
|
||||||
|
### 3.1 DomiStream (this repo, public, sans-I/O)
|
||||||
|
|
||||||
|
**Reused as it is** (already written and tested for the client): the pairing crypto (AES, SHA-256, RSA signatures,
|
||||||
|
certificate parsing and our DER writer), session keys, Reed-Solomon (`fec::ReedSolomon::encode` exists), RTP and
|
||||||
|
the video/audio packet headers, the control frame cipher and message codec, `input::parse_input` and the gamepad
|
||||||
|
messages, the RTSP request parser and framer, the SDP parser, the HTTP XML reader, the ENet wire structs, the clock
|
||||||
|
and randomness seams.
|
||||||
|
|
||||||
|
**Added** (each with tests written first, a fuzz target for each parser, and the mutation pass):
|
||||||
|
|
||||||
|
| Module (proposed) | What |
|
||||||
|
| :-- | :-- |
|
||||||
|
| `host::pairing` | the host's pairing state machine: the phases of PROTOCOL.md 1.5 from the other side (server challenge, checks of the client's hashes and signature, host signature), a pending-PIN slot fed by the caller |
|
||||||
|
| `host::http` | request-line and query parsing (strict, capped), and the XML answers: serverinfo, applist, launch/resume/cancel, pair, errors |
|
||||||
|
| `rtsp::server` | the host's RTSP session: request order, CSeq, SETUP ports, the DESCRIBE answer (SDP writer), a strict ANNOUNCE parser into a typed stream configuration |
|
||||||
|
| `enet::host` | the accepting side of ENet: connect, verify connect, reliable channel, ping and timeouts |
|
||||||
|
| `control::host` | the host side of the control channel: client-to-host decryption, host-to-client messages (rumble, HDR mode once measured, termination) |
|
||||||
|
| `video::packetizer` | an encoded frame → RTP + NV-header packets, FEC blocks with parity, optional encryption |
|
||||||
|
| `audio::packetizer` | Opus packets → RTP, AES-CBC, parity once U16 is settled |
|
||||||
|
| `input::touch` | the client-side gesture recogniser of 1.6 (pure, timed points in, events out) |
|
||||||
|
| `input::keymap` | GameStream key codes ↔ scan codes, as a pure table both sides can use |
|
||||||
|
| `pacing`, `harness` | the frame pacer's maths and the harness statistics (median, p95, clock offset) |
|
||||||
|
|
||||||
|
The client and host halves are tested **against each other in memory**: a DomiStream client and a DomiStream host
|
||||||
|
run a whole session in one test (pairing, RTSP, control, video with loss and FEC recovery, audio), with no socket.
|
||||||
|
That catches every asymmetric mistake before a real client is involved. The release that adds the host side is
|
||||||
|
`stream-v0.2.0`.
|
||||||
|
|
||||||
|
### 3.2 Arena Domi (private)
|
||||||
|
|
||||||
|
- **lumen-host's I/O**: sockets and TLS (rustls, server side, client certificates checked against the paired list),
|
||||||
|
capture, the colour pass, NVENC, WASAPI and Opus, input injection and ViGEmBus, launching and watching games,
|
||||||
|
pacing threads. Proposed home: inside `crates/arena-host` (the Play remotely crate), with `lumen-host.exe` as a
|
||||||
|
new binary of that crate. Each Windows API sits behind a trait (`Capturer`, `Encoder`, `AudioSource`, `Injector`,
|
||||||
|
`Pads`, `Launcher`) with a fake, so the logic is tested without a GPU or a desktop.
|
||||||
|
- **arena-host** keeps the pairing gate, grants, devices, the engine per device, the code box, audit records and
|
||||||
|
turning Lumen on and off.
|
||||||
|
- **Capture and encode** could instead live in DomiCapture (public, CPAL-1.0), which the roadmap names for the
|
||||||
|
zero-copy encode path and which Pictor Domi will share. That crate has no code yet and belongs to the Arena build
|
||||||
|
lead's plan; D3: capture/encode start in arena-host and move to DomiCapture at L4.
|
||||||
|
- What touches files outside Play remotely's agreed folders (installer, tray agent, shared seams) goes through the
|
||||||
|
Arena build lead, one small PR each, as agreed on 2026-11-25.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Risks, and how each is retired early
|
||||||
|
|
||||||
|
| # | Risk | Retired by | When |
|
||||||
|
| :-- | :-- | :-- | :-- |
|
||||||
|
| R1 | **Clean room.** The host side of GameStream is best documented in GPL code, and GPL-provenance values sit in permissive sources (the audio parity matrix, the HDR message layout) | Sources limited to section 0's list; Moonshine read as a host for facts only; GPL-provenance values never used until measured (6.2); every PR adds its source rows; the GPL Remote app's workers and Lumen's workers never share a workspace, code or review; each PR body carries a clean-room checklist (sources read, none forbidden, provenance of every constant) | every PR, from L0 |
|
||||||
|
| R2 | **Interop with real clients**: a host must accept exactly what clients send (U5, U6, U9, U10 from the host side) | the in-memory client↔host test (L1); Sunshine as a black-box oracle (our gs-probe's byte logs of what Sunshine sends); then the first real client (Arena Domi Remote in the Android emulator, black-box) against lumen-host's listeners at the end of L1, before any video work depends on it | L1 |
|
||||||
|
| R3 | **Audio FEC matrix (U16)** is GPL-provenance | send audio without parity and verify clients play it; solve the matrix from Sunshine's captured parity (our measurement) | L2, L6 |
|
||||||
|
| R4 | **Colours differ between phone and PC** (range, transfer, HDR) | SDR BT.709 limited by default with correct VUI; test patterns decoded on the client and compared (7.5); HDR only after the HDR message is measured | L4 |
|
||||||
|
| R5 | **Input that cannot land**: elevated games, the secure desktop (UIPI) | detect and tell the client; accepted as the price of "no admin rights" (D6) | L3 |
|
||||||
|
| R6 | **Firewall rules need admin**; inbound connections on a public-profile network are blocked without them | decision D1 before L5; until then the emulator connects over loopback, which needs no rule | L5 |
|
||||||
|
| R7 | **ViGEmBus** is a third-party driver that its authors no longer develop | used only if Mark installed it; pads are refused cleanly without it; our own driver later (roadmap open point 13) | L3 |
|
||||||
|
| R8 | **Anti-cheat** may dislike desktop capture, synthetic input or virtual pads | Lumen never touches the game process; a short list of games is tested before the switch (C) and any that refuse are listed in the client ("Streaming isn't allowed by this game") | L6 |
|
||||||
|
| R9 | **Cost to the game** (GPU time of the colour pass, NVENC sessions, CPU) | the harness reports the game's frame rate with and without streaming; target under 3 % loss, measured | L2, L6 |
|
||||||
|
| R10 | **A client that cannot use a non-standard port** | checked black-box in L1 (Arena Domi Remote with port 48989); if it fails, the fork's workers get a written requirement, or Lumen waits for stage E for that client | L1 |
|
||||||
|
| R11 | **Desktop Duplication limits**: at most four duplicating processes; Arena's own overlay capture, Sunshine and Lumen all duplicate | one Lumen session at a time; lumen-host releases its duplication when idle; the error (`DXGI_ERROR_NOT_CURRENTLY_AVAILABLE`) is reported in plain words | L2 |
|
||||||
|
| R12 | **Licences of the native pieces** (NVENC header, libopus, ViGEmClient, their Rust bindings) | each read and logged before it is added; only MIT, BSD, Apache, ISC, zlib or CPAL; NVIDIA's DLL is the driver's, never shipped | L0 |
|
||||||
|
| R13 | **Codec patents** if Arena Domi is sold (roadmap open point 9) | the encoder is the user's GPU's hardware; flagged to Mark, not decided here | before sale |
|
||||||
|
| R14 | **Estimates**: GameStream host work has unknowns we cannot see before real clients connect | milestones end in demos, each small; the plan is re-estimated after L1 with real numbers | L1 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Milestones
|
||||||
|
|
||||||
|
Estimates are working days of one engineer (with QA writing tests first, as DomiStream did), on this PC, gated by
|
||||||
|
the load rule. Each milestone ends in a demo Mark can see. Total: **about 18 days, 22 to 23 with a 25 % margin**.
|
||||||
|
|
||||||
|
| # | Milestone | Content | Days | Demo for Mark |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| L0 | Spikes | Read and log the NVENC programming guide and header licence, libopus and ViGEmClient licences. A throwaway Rust spike, run only with Mark present: duplicate the HDR desktop in FP16, convert to NV12 and P010 on the GPU, encode 10 s of HEVC with NVENC, write the file; time each step | 1 | a 10 s HEVC file of a test pattern window (SDR and HDR) and a table: capture, convert and encode time per frame |
|
||||||
|
| L1 | Host protocol + first contact | DomiStream host side of section 3.1 (pairing, HTTP, RTSP server, ANNOUNCE, ENet host, control host, both packetizers), the in-memory client↔host session test, fuzz targets. A lumen-host skeleton (listeners on loopback only, no capture) that Arena Domi Remote in the Android emulator can find, pair with (code box) and list games from | 4 | the emulator on this PC pairs with Lumen and shows Arena Domi's game list; test and fuzz report |
|
||||||
|
| L2 | First stream | Capture (SDR path, and FP16 → SDR), NVENC HEVC/H.264 low latency, pacing, WASAPI + Opus (no audio parity), keyboard and relative mouse, launch from the library, quit, game mode and audit; beside Sunshine on its own ports | 4 | a game streams from Lumen to the emulator, with sound and keyboard/mouse, while Sunshine is still installed |
|
||||||
|
| L3 | Input, all of it | absolute mouse mapping, wheel, scan-code keyboard, text, ViGEmBus pads with rumble, the touch-to-mouse spec and `input::touch`, UIPI detection; the input e2e (7.3) running green | 2 | a scripted tap, long press and two-finger scroll land at the right places in the Arena input probe; e2e report |
|
||||||
|
| L4 | Colour and displays | capture/encode move from arena-host to DomiCapture (D3); range/colour-space negotiation from measurement, HDR → SDR tone mapping checked, monitor choice and switching, GPU scaling; HDR to HDR clients only if the HDR message has been measured | 2 | test pattern on the PC and on the phone side by side, with the measured colour differences |
|
||||||
|
| L5 | Pairing and per-device engine | Tessera-grant pairing with no PIN for Arena clients, the code box for Arena Domi Remote, the engine per device, Lumen's binding on the allowed addresses, firewall rules (after D1), the installer seam | 2 | gs-probe pairs with Lumen with no PIN; the phone pairs with a code; Settings shows "Streams with: Lumen" |
|
||||||
|
| L6 | Harness and the Day 3 gate | the same-PC latency harness (7.4), Lumen against Sunshine, tuning (pacing, VBV, slices, priorities), the game's frame-rate cost, a 2-hour soak, audio parity once U16 is solved | 2 | the harness table: median and p95 for Lumen and Sunshine, and the gate answer |
|
||||||
|
| L7 | Switch-over | stage C for each client that passes, Sunshine as the hidden fallback (stage D), uninstall path checked | 1 | Arena Domi Remote and the Windows client streaming from Lumen by default; Sunshine only under expert options |
|
||||||
|
|
||||||
|
Not in these estimates: Arena Domi TV itself (it switches when it exists, because it is built on DomiStream),
|
||||||
|
Lumen's own transport (roadmap Day 4), AMF/Quick Sync, 4:4:4, a virtual display per client, and the iOS client
|
||||||
|
(5.2).
|
||||||
|
|
||||||
|
### 5.1 The first build phase (accepted: Mark's go, 2026-12-04)
|
||||||
|
|
||||||
|
**L0 + L1**: the spikes (to retire the GPU and licence risks while they are cheap) and the DomiStream host side
|
||||||
|
with the in-memory session test, ending with Arena Domi Remote in the emulator pairing with a Lumen skeleton over
|
||||||
|
loopback. Nothing touches Sunshine, the owner's desktop, mouse or windows, except the one L0 spike run with Mark
|
||||||
|
present. About 5 days.
|
||||||
|
|
||||||
|
### 5.2 Later client phase: iOS
|
||||||
|
|
||||||
|
Every Domi app eventually runs on Windows, Android and iOS (Mark, 2026-12-04). Lumen's host does not change for
|
||||||
|
iOS: an iOS client speaks GameStream (later Lumen's own transport) to the same lumen-host. The iOS client is its own
|
||||||
|
phase after the switch-over (L7): DomiStream compiles for `aarch64-apple-ios` (it is pure Rust with no I/O, so the
|
||||||
|
check is a build and the test suite on that target), VideoToolbox decodes, the same `input::touch` recogniser maps
|
||||||
|
gestures, and the client pairs through a Tessera grant like Arena's other clients, with no PIN. It is planned and
|
||||||
|
estimated when phase L7 is done; no Moonlight iOS code is read for it (the clean room covers every client).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Sources and measurements for the host side
|
||||||
|
|
||||||
|
### 6.1 What may be read
|
||||||
|
|
||||||
|
- Everything already allowed in [CLEAN_ROOM.md](CLEAN_ROOM.md), with one point made explicit: **Moonshine is a
|
||||||
|
host**, so its host-side code (BSD-2) is the most useful permissive reference for Lumen's state machines; it is
|
||||||
|
read for facts, logged, and never copied.
|
||||||
|
- Public OS and SDK documentation: Microsoft Learn (DXGI, Windows.Graphics.Capture, Core Audio, input, display
|
||||||
|
configuration), NVIDIA's Video Codec SDK documentation and API header, AMD AMF and Intel oneVPL documentation, the
|
||||||
|
libopus documentation, the ViGEm documentation, the Opus and RTP RFCs, ITU-R BT.709 / BT.2020 / BT.2100 and SMPTE
|
||||||
|
ST 2084.
|
||||||
|
- **Forbidden for host work** (D2, Mark 2026-12-04): the source of OBS Studio (GPL-2.0) and of FFmpeg (LGPL/GPL)
|
||||||
|
is not read either, because both contain encoder and capture code that would be tempting to port.
|
||||||
|
|
||||||
|
### 6.2 Measurements we make ourselves
|
||||||
|
|
||||||
|
- **Sunshine as a black-box oracle.** Our own `gs-probe` (a GameStream client) connects to the pinned Sunshine and
|
||||||
|
logs what it sends, as allowed today ([LIVE-INTEROP.md](LIVE-INTEROP.md)): headers, packet layouts, FEC parity
|
||||||
|
(to solve the audio matrix, U16), the HDR message bytes with HDR on (its layout), timings.
|
||||||
|
- **Clients as black boxes** (D2, accepted). Arena Domi Remote (in the Android emulator) and the official
|
||||||
|
Moonlight PC app connect to lumen-host, and lumen-host logs what they send: ANNOUNCE values per client setting
|
||||||
|
(range, codec, HDR), input packets per gesture, ENet details. We run the binaries and read our own logs; we never
|
||||||
|
open their source, disassemble or decompile them.
|
||||||
|
- Every fact found this way goes into PROTOCOL.md with a measurement tag, the date and the setup.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Test strategy
|
||||||
|
|
||||||
|
### 7.1 Tests first
|
||||||
|
|
||||||
|
- **DomiStream**: tests before code for every new parser and state machine (host pairing, HTTP requests, RTSP
|
||||||
|
server, ANNOUNCE, ENet host, control host), the packetizers and the gesture recogniser. Vectors come from
|
||||||
|
independent tools (OpenSSL, Python) and from the client half (round trips); property tests: packetize →
|
||||||
|
lose up to the parity count → depacketize gives the same frame; any gesture sequence gives balanced button
|
||||||
|
presses. Mutation pass as in [MUTATION.md](MUTATION.md).
|
||||||
|
- **Fuzzing**: one libFuzzer target per new parser (HTTP request and query, RTSP request, ANNOUNCE/SDP, ENet host
|
||||||
|
datagram, control client-to-host frame, INPUT_DATA already exists), 60 s each per release and a long run for the
|
||||||
|
pairing and ENet host targets, 0 crashes required.
|
||||||
|
- **arena-host / lumen-host**: the pure parts (coordinate mapping, key map, colour matrices and the tone curve,
|
||||||
|
engine choice, app list, quit logic) are unit-tested; the I/O sits behind traits with fakes, so a whole session
|
||||||
|
(control in, injector calls out) runs in a test without a desktop.
|
||||||
|
|
||||||
|
### 7.2 GPU tests
|
||||||
|
|
||||||
|
Capture → convert → encode → decode on the reference GPU with known patterns (colour bars, grey ramps, a PQ ramp),
|
||||||
|
compared numerically (PSNR and colour difference thresholds). They need the real GPU and desktop, so they are
|
||||||
|
`#[ignore]` by default and run only under the load rule, and only with Mark's agreement when they capture his
|
||||||
|
display.
|
||||||
|
|
||||||
|
### 7.3 The input e2e, from L2 on
|
||||||
|
|
||||||
|
The **Arena input probe** (our own tool: a window that logs every mouse, key, touch and pointer event with its
|
||||||
|
coordinates) is shown on the streamed display; a client streams it and sends scripted input; the probe's log is the
|
||||||
|
assertion.
|
||||||
|
|
||||||
|
| Step | Client | Expected in the probe log |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| tap at stream point (x, y) | emulator (adb tap) and gs-probe | left down and up at the mapped PC point, within 2 px |
|
||||||
|
| long press 800 ms | emulator (adb swipe from a point to itself) | right down and up at that point, no left click |
|
||||||
|
| two-finger drag up | emulator (an instrumentation test APK of our own that injects a two-pointer gesture) | wheel events with the right sign and no buttons |
|
||||||
|
| one-finger drag | emulator | left down, moves along the path, left up |
|
||||||
|
| typed text and key combos | gs-probe | the same characters and scan codes, in order |
|
||||||
|
| pad buttons and sticks | gs-probe | the virtual pad's state (the probe reads XInput) |
|
||||||
|
|
||||||
|
- **Two tiers.** The *hermetic* tier replaces `SendInput` with a recording fake and checks the calls; it runs in
|
||||||
|
every test run. The *live* tier injects for real, so it moves the PC's pointer: it runs only in a sitting agreed
|
||||||
|
with Mark (or in a Windows Sandbox or virtual machine, where the software encoder stands in for NVENC).
|
||||||
|
- The emulator connects over loopback, so no firewall rule and no network outside the PC are involved.
|
||||||
|
- Against Arena Domi Remote the gesture rows will fail until its workers implement the touch spec (1.6); the e2e is
|
||||||
|
how that is checked, and it is reported as a client gap, not hidden.
|
||||||
|
|
||||||
|
### 7.4 Latency harness, from L2 on
|
||||||
|
|
||||||
|
- **Same PC, one clock**: the client (gs-probe with hardware decode, later the emulator) sends a click at t0; the
|
||||||
|
probe flips a large patch from black to white on that click; the client timestamps the first decoded frame that
|
||||||
|
shows white (t1). t1 − t0 is the input-to-decoded latency, without the client's display. 200 samples per run,
|
||||||
|
alternating Lumen and Sunshine runs, median and p95 reported.
|
||||||
|
- **Inside lumen-host**: each frame carries timestamps for capture, convert done, encode done and last packet sent,
|
||||||
|
logged to a local trace, so a regression points at its stage.
|
||||||
|
- **Cost to the game**: the game's frame rate with and without a stream (Arena Domi's own frametime statistics).
|
||||||
|
- **Away from home** (Via Domi) needs two clocks: the harness maths in DomiStream estimates the offset; that is the
|
||||||
|
roadmap's Day 2/4 harness and is reused when it exists.
|
||||||
|
|
||||||
|
### 7.5 Colour tests
|
||||||
|
|
||||||
|
A colour-pattern window (bars, ramps, near-black steps, an SDR-white patch) is streamed; the client saves a decoded
|
||||||
|
frame; the PC saves the captured frame; both are converted to the same space and compared patch by patch. This
|
||||||
|
settles the range and colour-space values (1.3) per client.
|
||||||
|
|
||||||
|
### 7.6 The switch-over suite (one per client)
|
||||||
|
|
||||||
|
Pair → list games → launch → 60 s of video and audio → input e2e → quit → reconnect after a dropped connection →
|
||||||
|
pair removal refuses the client → a 2-hour soak without memory or handle growth. A client moves to Lumen (stage C)
|
||||||
|
when this suite passes on Lumen as it does on Sunshine, and the harness says Lumen is at least as fast.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. Decisions (Mark, 2026-12-04: all six accepted as proposed)
|
||||||
|
|
||||||
|
| # | Question | Decision |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| D1 | Lumen needs Windows firewall rules for `lumen-host.exe` on its ports, which needs admin | **Yes**: the existing single UAC step at "Turn on Play remotely" also creates Lumen's rules (scoped to `lumen-host.exe`, its ports and the allowed addresses). No new prompt. They stay until uninstall, like Sunshine's |
|
||||||
|
| D2 | Black-box logging of what clients send to Lumen; OBS Studio and FFmpeg sources | **Yes**: lumen-host may log what Arena Domi Remote and the official Moonlight PC app send to it (run and observe only, never source, disassembly or decompiling). **OBS Studio and FFmpeg source are forbidden for host work** ([CLEAN_ROOM.md](CLEAN_ROOM.md)) |
|
||||||
|
| D3 | Where capture and encode live | **arena-host first**, behind traits; they **move to DomiCapture at L4** |
|
||||||
|
| D4 | Who starts lumen-host at sign-in | **The tray agent**, once Lumen is the default engine (stage D). Before that, Arena Domi starts it when Play remotely uses Lumen |
|
||||||
|
| D5 | Arena Domi Remote: the code box or a no-PIN spec | **Keep the code box.** No grant-based pairing spec is published into the GPL app |
|
||||||
|
| D6 | Games running as administrator | **Accepted**: they get no input from Lumen, and the client shows a clear message ("This game runs as administrator, so Arena Domi can't control it") |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Sources used for this plan
|
||||||
|
|
||||||
|
Logged as S-22 in [CLEAN_ROOM.md](CLEAN_ROOM.md): Microsoft Learn pages on DXGI 1.5 and `DuplicateOutput1`,
|
||||||
|
Desktop Duplication, HDR and advanced colour, `GraphicsCaptureSession` (`IsBorderRequired`,
|
||||||
|
`IsCursorCaptureEnabled`), `SendInput` and `MOUSEINPUT`, the UIAccess security considerations and the UAC policy
|
||||||
|
for UIAccess, `CreateSyntheticPointerDevice` / `InjectSyntheticPointerInput`, and WASAPI loopback recording with
|
||||||
|
process loopback activation. Everything else here comes from this repository's own documents and the 2026-12-04
|
||||||
|
live evidence (the phone's input packets).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. L0 results (2026-12-04)
|
||||||
|
|
||||||
|
**Done:** the licence reading and the GPU spike. The spike is a throwaway Rust program with a small C shim over the
|
||||||
|
NVENC header, kept outside git. It showed no window, injected nothing and opened no socket. The desktop bitstreams
|
||||||
|
never left memory (nothing of the screen was written to disk); only two synthetic-pattern encodes were written, and
|
||||||
|
they stay outside git.
|
||||||
|
|
||||||
|
**Licences** (logged as S-23 to S-25 in [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
||||||
|
|
||||||
|
| Piece | Licence | Note |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| `nvEncodeAPI.h`, API **12.0**, from NVIDIA's own public repository (VideoProcessingFramework, Apache-2.0 repository, archived) | MIT (the header's own notice) | used. No account and no licence acceptance needed |
|
||||||
|
| `nvEncodeAPI.h`, API 8.1, NVIDIA's video-sdk-samples | MIT | **not usable**: the driver refuses its presets (below) |
|
||||||
|
| NVENC API 12.1 or newer headers | NVIDIA's SDK download (account and terms) | not needed for anything planned; if a later feature needs it, that download is Mark's decision |
|
||||||
|
| libopus | BSD-3-Clause style (Xiph COPYING) | for L2 |
|
||||||
|
| `opus` crate / `audiopus_sys` | Apache-2.0 or MIT / ISC | candidates for L2, chosen then |
|
||||||
|
| ViGEmClient | MIT (repository archived) | the client library for ViGEmBus |
|
||||||
|
| ViGEmBus | BSD-3-Clause (repository archived) | Mark installs it himself; never shipped |
|
||||||
|
| `vigem-client` crate | MIT | candidate binding for L3 |
|
||||||
|
| `windows` crate | MIT or Apache-2.0 | used by the spike |
|
||||||
|
|
||||||
|
**Measured on the reference PC** (RTX 3090, driver NVENC API maximum 13.1; primary 2560x1440 HDR; one run,
|
||||||
|
idle desktop):
|
||||||
|
|
||||||
|
| What | Result |
|
||||||
|
| :-- | :-- |
|
||||||
|
| Display state | both outputs report colour space `RGB_FULL_G2084_NONE_P2020` (HDR on); primary 10 bits per colour; peak 1499 nits, full frame 799; SDR white level 240 nits |
|
||||||
|
| Desktop Duplication | the HDR desktop arrives as `R16G16B16A16_FLOAT` (FP16 scRGB), as planned. **Needs per-monitor DPI awareness**: without it `DuplicateOutput1` returned `DXGI_ERROR_UNSUPPORTED` and the 4K output showed as 2560x1440 |
|
||||||
|
| NVENC with the API 8.1 header | `nvEncGetEncodePresetConfig` refuses the legacy low-latency preset (`NV_ENC_ERR_UNSUPPORTED_PARAM`) and initialisation without a preset fails (`NV_ENC_ERR_INVALID_PARAM`) |
|
||||||
|
| NVENC with the API 12.0 header | preset P1, tuning "ultra low latency", CBR 20 Mbit/s, VBV one frame, infinite GOP: works, 8-bit and 10-bit HEVC; the first access unit is VPS, SPS, PPS, IDR |
|
||||||
|
| Copy of the captured frame (GPU, waited) | 1.6 ms (one sample: the desktop was idle, so only one new frame arrived) |
|
||||||
|
| Colour pass FP16 → NV12 / P010, 2560x1440 (one compute dispatch, waited) | median 0.57 / 0.50 ms, p95 1.01 / 0.93 ms |
|
||||||
|
| NVENC HEVC 2560x1440, synchronous | 8-bit median 2.56 ms, p95 2.70 ms; 10-bit median 2.56 ms, p95 2.80 ms |
|
||||||
|
| NVENC HEVC 1920x1080 (pattern) | median 1.4 to 1.5 ms, p95 1.7 to 2.5 ms |
|
||||||
|
| Capture to bitstream, sum of medians, 1440p | about **4.7 ms** on the host |
|
||||||
|
|
||||||
|
What L0 did not settle (and where it is settled): capture timing under motion and at a game's frame rate (L2,
|
||||||
|
with the harness); whether the colour pass matches what a decoder shows (L4, the pattern files are the start);
|
||||||
|
the asynchronous NVENC mode, which NVIDIA recommends on Windows (L2).
|
||||||
|
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Mutation pass
|
||||||
|
|
||||||
|
Each row puts back one bug a test is meant to guard against (an exact edit to `crates/domistream/src`), runs the
|
||||||
|
test binary that should catch it, and reverts the edit. "Caught by" lists the tests that failed. All 24 rows were
|
||||||
|
caught; none failed to compile, so every row is a real behaviour change the tests saw.
|
||||||
|
|
||||||
|
- **When:** 2026-11-26, QA, on `feature/client` at `d62aa8f`. The baseline was 242/242 tests passing.
|
||||||
|
- **Driver:** [`tools/mutation/mutate.py`](../tools/mutation/mutate.py) holds the exact edits, so the pass can be
|
||||||
|
rerun: `python tools/mutation/mutate.py [M1 ...]`. Every cargo run goes through the resource gate (CPU, RAM and
|
||||||
|
drives below 90 %, `-j 2`).
|
||||||
|
|
||||||
|
| # | Area | Mutation | Test binary | Caught by | Result |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| M1 | XML cap | size cap off by one (refuses exactly `MAX_XML_BYTES`) | http | `xml_size_boundaries`, `applist_caps` | caught |
|
||||||
|
| M2 | XML cap | depth cap off by one (allows depth 9) | http | `xml_depth_cap`, `xml_depth_bomb_does_not_recurse` | caught |
|
||||||
|
| M3 | RTSP cap | header cap off by one (allows 65 headers) | rtsp | `response_header_flood` | caught |
|
||||||
|
| M4 | ENet cap | command cap off by one (allows 33 commands) | enet | `hostile_sizes` | caught |
|
||||||
|
| M5 | Input cap | message size cap removed | input | `hostile_sizes` | caught |
|
||||||
|
| M6 | Video cap | packet size cap off by one (accepts 4097 bytes) | media | `video_packet_hostile_sizes` | caught |
|
||||||
|
| M7 | Audio cap | packet size cap removed | media | `audio_packet_hostile` | caught |
|
||||||
|
| M8 | Lying length | control frame: a length field that claims less is accepted | control | `frame_parser_lying_lengths` | caught |
|
||||||
|
| M9 | Lying length | RTSP: bytes after `Content-Length` kept instead of refused | rtsp | `response_lying_content_length` | caught |
|
||||||
|
| M10 | Lying length | INPUT_DATA: the big-endian size field not checked | input | `lying_length_and_size_fields` | caught |
|
||||||
|
| M11 | ENet wrap | reliable delivery does not wrap at 0xFFFF (saturating "next") | enet | `reliable_sequence_wraps_at_0xffff` | caught |
|
||||||
|
| M12 | Control replay | a repeated sequence number accepted (`<` instead of `<=`) | control | `replayed_and_old_host_frames_are_dropped` | caught |
|
||||||
|
| M13 | Control replay | the replay check removed | control | `replayed_and_old_host_frames_are_dropped`, `host_sequence_at_u32_wrap` | caught |
|
||||||
|
| M14 | Nonce | direction bytes swapped (`'H'` client to host) | control | `nonce_layout`, `nonce_matches_the_definition`, `seal_matches_dotnet_vectors`, `wrong_direction_and_wrong_key_are_refused` | caught |
|
||||||
|
| M15 | GCM tag | control `open` ignores a failed tag check | control | `tampering_is_refused`, `tampered_and_reflected_frames_are_dropped`, `open_never_accepts_random_frames`, `wrong_direction_and_wrong_key_are_refused` | caught |
|
||||||
|
| M24 | GCM tag | video `decrypt` ignores a failed tag check | media | `video_decrypt_refuses` | caught |
|
||||||
|
| M16 | FEC index | a video parity shard stored one index too high | video | 12 tests, e.g. `random_loss`, `all_data_lost_but_recoverable`, `recovered_shard_headers_are_not_trusted`, `generated_patterns` | caught |
|
||||||
|
| M17 | Video header | bytes 0-31 of a rebuilt shard trusted (whole-packet shards, start-of-frame flag read from a rebuilt shard) | video | 9 tests, e.g. `recovered_shard_headers_are_not_trusted`, `all_data_lost_but_recoverable`, `random_loss` | caught |
|
||||||
|
| M18 | Audio parity | parity keyed by its own RTP sequence instead of the FEC header's base | audio | 9 tests, e.g. `every_loss_pattern_of_a_block`, `sequence_wraps`, `hostile_parity_never_corrupts` | caught |
|
||||||
|
| M19 | Pairing skip | no `pairingsecret`: proof and signature skipped, straight to step 4 | pairing | `a_bare_paired_answer_cannot_skip_any_step`, `out_of_order_answers_fail`, `replaying_the_same_answer_twice_fails` | caught |
|
||||||
|
| M20 | Signature | the host's signature over its secret not checked | pairing | `bad_host_signatures` | caught |
|
||||||
|
| M21 | Signature | `ServerCert::verify` accepts any signature | pairing | `bad_host_signatures`, `server_cert_verify_refuses` | caught |
|
||||||
|
| M22 | Sans-I/O | `std::time::Instant::now()` added in `src/time.rs` | hygiene | `src_is_sans_io` | caught |
|
||||||
|
| M23 | OS randomness | `getrandom` added as a dependency and used in `src/entropy.rs` | hygiene | `src_is_sans_io` | caught |
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- **M17.** The video receiver keeps only the payloads (bytes 32 on) of each shard and rebuilds from those, so as
|
||||||
|
written it cannot read a rebuilt shard's header. The mutation therefore first switches it to whole-packet shards,
|
||||||
|
then makes it trust one header field of a rebuilt shard. `recovered_shard_headers_are_not_trusted` and the other
|
||||||
|
loss tests catch it.
|
||||||
|
- **M23.** The mutation compiled, against the cached getrandom 0.4.3, and the guard caught the source use. Since
|
||||||
|
27b26a9 the dependency tree has no getrandom at all.
|
||||||
|
- **Missing tests.** No mutation got through, so none were added.
|
||||||
+97
-10
@@ -2,8 +2,9 @@
|
|||||||
|
|
||||||
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
|
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
|
||||||
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
|
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
|
||||||
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, Phase A (docs + API, no logic yet). U9 narrowed and U14 settled from the approved sources the same
|
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, implemented as stream-v0.1.0 per these docs and the approved sources; interop with a real host
|
||||||
day (sections 3.1, 5.3); the rest waits for the lab capture ([LAB_CAPTURE.md](LAB_CAPTURE.md)).
|
is unverified (the lab capture was not run, [LAB_CAPTURE.md](LAB_CAPTURE.md)). U9 narrowed and U14 settled from the
|
||||||
|
approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows the Wolf-documented behaviour.
|
||||||
|
|
||||||
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
||||||
|
|
||||||
@@ -220,6 +221,76 @@ SDP attribute lines `a=<name>:<value>`. Names the host reads [M]; values and the
|
|||||||
|
|
||||||
Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time.
|
Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time.
|
||||||
|
|
||||||
|
### 2.5 Host side (Lumen): `rtsp::server`
|
||||||
|
|
||||||
|
Facts from Moonshine's host code (`src/rtsp.rs`, `src/session/stream/video/mod.rs` at `f184d5e`, S-30, S-31) and
|
||||||
|
RFC 2326 (S-32); our own choices are marked as such.
|
||||||
|
|
||||||
|
**Connections and framing.** Moonshine reads one request per TCP connection and notes that Moonlight opens a
|
||||||
|
connection per request [M]. So the host's state belongs to the launched session, not to a connection: every
|
||||||
|
connection of that session feeds the same `RtspServer` (UNKNOWN U5 for other clients). A request without
|
||||||
|
`Content-Length` has no payload (RFC 2326 4.4); the host's framer (`RtspFramer::for_requests`) ends it at the empty
|
||||||
|
line. Every answer carries `Content-Length` (ours), so the client never waits for a close. Moonshine needs a parseable
|
||||||
|
`CSeq` and closes without an answer when it is missing [M]; we answer 400 and let the caller close.
|
||||||
|
|
||||||
|
**Order and statuses.** Moonshine checks no order and no `Session` [M]. We enforce 2.2: OPTIONS, DESCRIBE, the three
|
||||||
|
SETUPs (any order, each once: ours, U5), ANNOUNCE, PLAY. OPTIONS may come at any time and changes nothing else
|
||||||
|
(RFC 2326 10.1). Moonshine answers only 200, 400 and 500 [M]; we use the RFC 2326 7.1.1 codes: 400 malformed request
|
||||||
|
or ANNOUNCE payload, 451 a request the offer does not cover (codec, encryption bits, HDR, 4:4:4), 454 a `Session`
|
||||||
|
that is not this session's, 455 a method out of order, 501 an unknown method (TEARDOWN, GET_PARAMETER...). A refused
|
||||||
|
request changes no state; the caller decides whether to close.
|
||||||
|
|
||||||
|
**Session.** Moonshine sends the fixed id `MoonshineSession` and never reads it back [M]. We send a random id
|
||||||
|
(8 bytes from the caller's `RandomSource`, hex; RFC 2326 3.4 asks for at least 8 random octets) as
|
||||||
|
`Session: <id>;timeout = 90` [M]. A `Session` header that is present must carry that id (454 otherwise, and before
|
||||||
|
the first SETUP any id is wrong); a missing one is accepted unless the host config requires it (U5).
|
||||||
|
|
||||||
|
**Answers** [M]: OPTIONS `Public` (we list `OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY`; Moonshine leaves ANNOUNCE
|
||||||
|
out); DESCRIBE the SDP below; SETUP needs a `Transport` header (400 without), takes the stream from the first
|
||||||
|
`streamid=<audio|video|control>` of the target (400 otherwise) and answers `Session` and
|
||||||
|
`Transport: server_port=<port>`; ANNOUNCE and PLAY answer with no payload.
|
||||||
|
|
||||||
|
**DESCRIBE lines, in Moonshine's order** [M]: `a=x-ss-general.featureFlags:3`, `a=x-ss-general.encryptionSupported:`
|
||||||
|
5 or 7 (7 when video encryption is on), `sprop-parameter-sets=AAAAAU`, `a=x-nv-video[0].refPicInvalidation:1`,
|
||||||
|
`a=rtpmap:98 AV1/90000`, `a=fmtp:96 packetization-mode=1`, then one `a=fmtp:97 surround-params=` per Opus
|
||||||
|
configuration. Moonshine writes all of them unconditionally; our writer leaves out the invalidation, AV1 and H.264
|
||||||
|
lines when the host does not offer them. HEVC, HDR and 4:4:4 have no DESCRIBE line (serverinfo, 1.2, U25). Moonshine
|
||||||
|
rotates the 5.1/7.1 normal-quality mappings with a comment that cites GFE and Moonlight [M*]: not used, U26.
|
||||||
|
|
||||||
|
**ANNOUNCE as Moonshine reads it.** Missing or unparseable required attributes give 400 [M]; optional ones fall back
|
||||||
|
to their default [M]. Our parser keeps the required set and the defaults, refuses out-of-range values instead of
|
||||||
|
clamping, refuses a known attribute given twice, and counts unknown attributes.
|
||||||
|
|
||||||
|
| Attribute | Required? | Default | Accepted (ours unless tagged) | Meaning |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| `x-nv-video[0].clientViewportWd`, `…Ht` | yes [M] | | 1..=16384 | resolution |
|
||||||
|
| `x-nv-video[0].maxFPS` | yes [M] | | 1..=1000 (0 refused [M]) | frame rate |
|
||||||
|
| `x-nv-video[0].packetSize` | yes [M] | | 200..=65471 [M] (Moonshine clamps above its own cap; we refuse) | video packet size |
|
||||||
|
| `x-ml-video.configuredBitrateKbps` | yes [M] | | 1..=4294967 (×1000 must fit a u32 [M]) | bitrate |
|
||||||
|
| `x-nv-vqos[0].bitStreamFormat` | yes [M] | | 0 H.264, 1 HEVC, 2 AV1 [M]; others refused [M] | codec |
|
||||||
|
| `x-nv-vqos[0].fec.minRequiredFecPackets` | yes [M] | | 0..=255 | minimum parity per block |
|
||||||
|
| `x-nv-vqos[0].qosTrafficType`, `x-nv-aqos.qosTrafficType` | yes [M] | | any u32, kept raw (Moonshine: QoS off for `0` [M]) | DSCP class |
|
||||||
|
| `x-nv-aqos.packetDuration` | yes [M] | | 1..=120 ms (longest Opus packet, RFC 6716) | audio packet duration |
|
||||||
|
| `x-nv-video[0].maxNumReferenceFrames` | no | 1 [M] | any u32, raw (what 0 means is [M*]) | reference frames |
|
||||||
|
| `x-nv-video[0].refPicInvalidation` | no (Moonshine does not read it) | 0: UNKNOWN U6 | 0, 1 | client can invalidate |
|
||||||
|
| `x-nv-video[0].dynamicRangeMode` | no | 0 [M] | any u32, raw; Moonshine: 0 SDR, 1 HDR [M]; a non-zero value needs the host's HDR offer (ours) | U6 |
|
||||||
|
| `x-nv-video[0].encoderCscMode` | no | 0 [M] | any u32, raw; the bit layout is [M*] (Moonshine cites Sunshine) | U6 |
|
||||||
|
| `x-ss-video[0].chromaSamplingType` | no | 0 [M] | 0 4:2:0, 1 4:4:4 [M] | chroma |
|
||||||
|
| `x-ss-general.encryptionEnabled` | no | 0 [M] | 0..=255, only offered bits (ours) | 2.3 bits |
|
||||||
|
| `x-nv-audio.surround.enable` | no | 0 [M] | 0, 1 | when 0, the layout comes from launch's `surroundAudioInfo` [M] |
|
||||||
|
| `x-nv-audio.surround.numChannels` | no | 2 [M] | 1..=8 | channels |
|
||||||
|
| `x-nv-audio.surround.channelMask` | no | 0x3 [M] | any u32, raw | speaker mask |
|
||||||
|
| `x-nv-audio.surround.AudioQuality` | no | 1 [M] | 0, 1 | high quality |
|
||||||
|
|
||||||
|
`bitStreamFormat` 0/1/2 [M] confirms the values our client sends (`rtsp::sdp`, previously a judgment). Payload caps
|
||||||
|
(ours): 32 KiB, 1024 non-empty lines, 1024 bytes per line, 512 `a=` attributes; blanks around values are trimmed.
|
||||||
|
|
||||||
|
UNKNOWNs left for black-box measurement (Arena Domi Remote and the Moonlight PC app as Lumen's clients, decision D2):
|
||||||
|
U5 (connection per request, the SETUP target form, whether clients echo `Session`, whether every client starts with
|
||||||
|
OPTIONS), U6 (whether real clients always send the ten required attributes, `refPicInvalidation`'s default, the
|
||||||
|
meanings of `dynamicRangeMode` and `encoderCscMode` per client setting, whether `qosTrafficType` is always a number,
|
||||||
|
how many attributes a real ANNOUNCE has), U26 (mapping rotation).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 3. Control channel (ENet + AES-GCM)
|
## 3. Control channel (ENet + AES-GCM)
|
||||||
@@ -297,13 +368,13 @@ Every control message is wrapped [W4] (little-endian):
|
|||||||
|
|
||||||
| Type | Name | Direction | Body |
|
| Type | Name | Direction | Body |
|
||||||
| :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- |
|
||||||
| 0x0305 | START_A | client → host | UNKNOWN U10 |
|
| 0x0305 | START_A | client → host | UNKNOWN U10. Moonshine has no such type; inside the encrypted frame it skips an unknown type [M] |
|
||||||
| 0x0307 | START_B | client → host | UNKNOWN U10. The host starts video and audio when it arrives [M] |
|
| 0x0307 | START_B | client → host | Moonshine reads no body [M]. The host starts video and audio when it arrives [M]; Moonshine's video receiver (and so its PING handling) only runs from then on [M] |
|
||||||
| 0x0200 | PERIODIC_PING | client → host | UNKNOWN U10. Keeps the session alive; the host stops after a timeout without one [M] |
|
| 0x0200 | PERIODIC_PING | client → host | Moonshine reads no body [M]. Each one pushes the host's stop deadline out; Moonshine stops a stream after 60 s without one (its default) [M] |
|
||||||
| 0x0201 | LOSS_STATS | client → host | UNKNOWN U10 |
|
| 0x0201 | LOSS_STATS | client → host | Moonshine ignores it [M]; body UNKNOWN U10 |
|
||||||
| 0x0204 | FRAME_STATS | client → host | UNKNOWN U10 |
|
| 0x0204 | FRAME_STATS | client → host | Moonshine ignores it [M]; body UNKNOWN U10 |
|
||||||
| 0x0206 | INPUT_DATA | client → host | section 4 |
|
| 0x0206 | INPUT_DATA | client → host | section 4 |
|
||||||
| 0x0302 | IDR_FRAME (request) | client → host | UNKNOWN U10 (Moonshine ignores the body) |
|
| 0x0302 | IDR_FRAME (request) | client → host | Moonshine reads no body [M] |
|
||||||
| 0x0301 | INVALIDATE_REF_FRAMES | client → host | `first u32`, `reserved u32`, `last u32`, `reserved 12 bytes`, LE [M] |
|
| 0x0301 | INVALIDATE_REF_FRAMES | client → host | `first u32`, `reserved u32`, `last u32`, `reserved 12 bytes`, LE [M] |
|
||||||
| 0x0100 | TERMINATION | host → client | UNKNOWN U10 |
|
| 0x0100 | TERMINATION | host → client | UNKNOWN U10 |
|
||||||
| 0x0109 | TERMINATION (extended) | host → client | `error_code u32 BE`; `0x80030023` = graceful [M] |
|
| 0x0109 | TERMINATION (extended) | host → client | `error_code u32 BE`; `0x80030023` = graceful [M] |
|
||||||
@@ -316,6 +387,11 @@ Every control message is wrapped [W4] (little-endian):
|
|||||||
|
|
||||||
UNKNOWN U23: Wolf states "all data is little-endian" for the frame; we assume LE for the host event bodies too.
|
UNKNOWN U23: Wolf states "all data is little-endian" for the frame; we assume LE for the host event bodies too.
|
||||||
|
|
||||||
|
How Moonshine treats what a client sends on control [M]: a message whose type it does not know, or whose length field
|
||||||
|
does not match, **ends the session** when it arrives outside the encrypted frame; inside the encrypted frame the same
|
||||||
|
message is skipped, and so is a frame that fails decryption. Whether Sunshine reads bodies (and which) is what U10
|
||||||
|
still settles live: the probe sends empty bodies first ([LIVE-INTEROP.md](LIVE-INTEROP.md), table V).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Input and gamepad packets
|
## 4. Input and gamepad packets
|
||||||
@@ -462,6 +538,12 @@ Reed-Solomon erasure code over GF(2^8), polynomial `0x11D` [F] [W5]:
|
|||||||
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
|
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
|
||||||
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
|
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
|
||||||
captured parity bytes (offset 32 on) of every block.
|
captured parity bytes (offset 32 on) of every block.
|
||||||
|
- **Host side (Lumen, `video::packetizer`).** Our own choices, not from a source, until a capture compares them
|
||||||
|
with a real host: the fewest blocks (at most 4) in which every block can carry the requested parity within
|
||||||
|
`k + m <= 255`, every block but the last carrying `k = ceil(n / blocks)` data shards; per block the least
|
||||||
|
percentage, at or above the requested one, whose `m` reaches `minRequiredFecPackets`; a frame too big for that
|
||||||
|
gets the most parity that still fits (counted in the packetizer's stats). Data shards in order, then the block's
|
||||||
|
parity, block by block; RTP sequence numbers run on across frames, one per packet.
|
||||||
- The audio code is **not** this matrix (section 6.4).
|
- The audio code is **not** this matrix (section 6.4).
|
||||||
|
|
||||||
### 5.4 Feedback
|
### 5.4 Feedback
|
||||||
@@ -510,7 +592,8 @@ Every 4 data packets are followed by 2 parity packets [W6]. A block is the 4 dat
|
|||||||
start at a multiple of 4 [M]; the base sequence and timestamp in the FEC header are the first data packet's [M].
|
start at a multiple of 4 [M]; the base sequence and timestamp in the FEC header are the first data packet's [M].
|
||||||
Shards are the encrypted payloads (all 4 the same length, constant-bitrate Opus) [M]. A lost data packet is rebuilt
|
Shards are the encrypted payloads (all 4 the same length, constant-bitrate Opus) [M]. A lost data packet is rebuilt
|
||||||
from any 4 of the 6 packets; its RTP header comes from the base values (sequence = base + index, timestamp = base +
|
from any 4 of the 6 packets; its RTP header comes from the base values (sequence = base + index, timestamp = base +
|
||||||
index × duration) [M].
|
index × duration) [M]. DomiStream waits for the jitter budget (`loss_timeout`) before rebuilding a missing packet,
|
||||||
|
so a packet that arrives late is played as sent rather than as a rebuilt copy.
|
||||||
|
|
||||||
UNKNOWN U16 (blocks audio FEC): the parity matrix. It is a fixed 2 × 4 matrix over GF(2^8), **not** the default
|
UNKNOWN U16 (blocks audio FEC): the parity matrix. It is a fixed 2 × 4 matrix over GF(2^8), **not** the default
|
||||||
construction of the RS library Moonshine uses [M]. The only value we have seen carries GPL provenance and is not
|
construction of the RS library Moonshine uses [M]. The only value we have seen carries GPL provenance and is not
|
||||||
@@ -519,6 +602,10 @@ coefficients (each parity byte is a linear combination of the 4 data bytes at th
|
|||||||
parity row, so a handful of byte positions gives a unique solution). Until then, audio loss falls back to the
|
parity row, so a handful of byte positions gives a unique solution). Until then, audio loss falls back to the
|
||||||
platform's packet-loss concealment.
|
platform's packet-loss concealment.
|
||||||
|
|
||||||
|
Host side (Lumen, `audio::packetizer`): no parity packets until U16 is settled (`AudioParity::None`; the API leaves
|
||||||
|
room for a parity variant). The first sequence number is a multiple of 4, a block start, because our receiver counts
|
||||||
|
from the first packet's block start and would otherwise report the 1 to 3 numbers before it as lost.
|
||||||
|
|
||||||
### 6.5 Decoding
|
### 6.5 Decoding
|
||||||
|
|
||||||
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
|
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
|
||||||
@@ -567,7 +654,7 @@ client and Sunshine on a lab machine, not Mark's PC, his Sunshine or his TV); th
|
|||||||
| U7 | Extra headers in SETUP replies | B | capture |
|
| U7 | Extra headers in SETUP replies | B | capture |
|
||||||
| U8 | UDP ping payload and repeat interval | B | capture |
|
| U8 | UDP ping payload and repeat interval | B | capture |
|
||||||
| U9 | Narrowed (3.1): only what Sunshine's ENet may add when *sending*; the client's channel count, MTU, connect data | B | capture, decode with our parser |
|
| U9 | Narrowed (3.1): only what Sunshine's ENet may add when *sending*; the client's channel count, MTU, connect data | B | capture, decode with our parser |
|
||||||
| U10 | Bodies of START_A, START_B, PERIODIC_PING, LOSS_STATS, FRAME_STATS, IDR request, TERMINATION; ping interval | B | capture, decrypted with the session's `rikey` |
|
| U10 | Narrowed (3.3): Moonshine reads no body from START_B, PERIODIC_PING or the IDR request and ignores START_A, LOSS_STATS and FRAME_STATS; what Sunshine reads, the ping interval it needs, TERMINATION's body | B | live sitting: empty bodies first, then the hex variants |
|
||||||
| U11 | First control sequence number; host's replay rules | | capture |
|
| U11 | First control sequence number; host's replay rules | | capture |
|
||||||
| U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture |
|
| U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture |
|
||||||
| U14 | Video RS matrix: **settled** (5.3, Cauchy from fec-rs) | | capture confirms: our parity = captured parity |
|
| U14 | Video RS matrix: **settled** (5.3, Cauchy from fec-rs) | | capture confirms: our parity = captured parity |
|
||||||
|
|||||||
Generated
-52
@@ -153,7 +153,6 @@ checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cpubits",
|
"cpubits",
|
||||||
"ctutils",
|
"ctutils",
|
||||||
"getrandom",
|
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
"serdect",
|
"serdect",
|
||||||
@@ -166,7 +165,6 @@ version = "0.2.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom",
|
|
||||||
"hybrid-array",
|
"hybrid-array",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
]
|
]
|
||||||
@@ -280,7 +278,6 @@ dependencies = [
|
|||||||
"cfg-if",
|
"cfg-if",
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi",
|
"r-efi",
|
||||||
"rand_core",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -485,17 +482,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "sha1"
|
|
||||||
version = "0.11.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"cpufeatures",
|
|
||||||
"digest",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha2"
|
name = "sha2"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -555,27 +541,6 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
|
|
||||||
dependencies = [
|
|
||||||
"tls_codec_derive",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec_derive"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
@@ -606,10 +571,7 @@ checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"const-oid",
|
"const-oid",
|
||||||
"der",
|
"der",
|
||||||
"sha1",
|
|
||||||
"signature",
|
|
||||||
"spki",
|
"spki",
|
||||||
"tls_codec",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -617,17 +579,3 @@ name = "zeroize"
|
|||||||
version = "1.9.2"
|
version = "1.9.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
||||||
dependencies = [
|
|
||||||
"zeroize_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "zeroize_derive"
|
|
||||||
version = "1.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|||||||
+78
-1
@@ -1,4 +1,4 @@
|
|||||||
# Fuzz targets: one per DomiStream parser. Its own workspace, built only for fuzzing, never released.
|
# Fuzz targets: one per DomiStream parser and state machine; each asserts invariants (round trips, caps). Its own workspace, built only for fuzzing, never released.
|
||||||
#
|
#
|
||||||
# Linux, nightly, cargo-fuzz:
|
# Linux, nightly, cargo-fuzz:
|
||||||
# cargo fuzz run <target> -- -max_total_time=600
|
# cargo fuzz run <target> -- -max_total_time=600
|
||||||
@@ -155,3 +155,80 @@ path = "fuzz_targets/audio_packet.rs"
|
|||||||
test = false
|
test = false
|
||||||
doc = false
|
doc = false
|
||||||
bench = false
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "server_cert_der"
|
||||||
|
path = "fuzz_targets/server_cert_der.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "enet_client"
|
||||||
|
path = "fuzz_targets/enet_client.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "media_decrypt"
|
||||||
|
path = "fuzz_targets/media_decrypt.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "video_depacketizer"
|
||||||
|
path = "fuzz_targets/video_depacketizer.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "audio_depacketizer"
|
||||||
|
path = "fuzz_targets/audio_depacketizer.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "fec_reconstruct"
|
||||||
|
path = "fuzz_targets/fec_reconstruct.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "pairing_session"
|
||||||
|
path = "fuzz_targets/pairing_session.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rtsp_client"
|
||||||
|
path = "fuzz_targets/rtsp_client.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "video_packetizer_roundtrip"
|
||||||
|
path = "fuzz_targets/video_packetizer_roundtrip.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "rtsp_server"
|
||||||
|
path = "fuzz_targets/rtsp_server.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|
||||||
|
[[bin]]
|
||||||
|
name = "announce"
|
||||||
|
path = "fuzz_targets/announce.rs"
|
||||||
|
test = false
|
||||||
|
doc = false
|
||||||
|
bench = false
|
||||||
|
|||||||
@@ -0,0 +1,26 @@
|
|||||||
|
//! Fuzzes the host's ANNOUNCE parser (hostile client SDP).
|
||||||
|
//! Asserts invariants, not only "no panic": an accepted payload is within every range and cap, and writing it back
|
||||||
|
//! gives the same config.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::server::{
|
||||||
|
MAX_ANNOUNCE_ATTRIBUTES, MAX_AUDIO_PACKET_DURATION_MS, MAX_BITRATE_KBPS, MAX_DIMENSION, MAX_FPS, MAX_PACKET_SIZE,
|
||||||
|
MIN_PACKET_SIZE, StreamConfig, parse_announce, write_announce,
|
||||||
|
};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Ok(c) = parse_announce(data) else { return };
|
||||||
|
assert!((1..=MAX_DIMENSION).contains(&c.width) && (1..=MAX_DIMENSION).contains(&c.height));
|
||||||
|
assert!((1..=MAX_FPS).contains(&c.max_fps));
|
||||||
|
assert!((MIN_PACKET_SIZE..=MAX_PACKET_SIZE).contains(&c.packet_size));
|
||||||
|
assert!((1..=MAX_BITRATE_KBPS).contains(&c.bitrate_kbps));
|
||||||
|
assert!((1..=MAX_AUDIO_PACKET_DURATION_MS).contains(&c.audio_packet_duration_ms));
|
||||||
|
assert!((1..=8).contains(&c.surround.channels));
|
||||||
|
assert!(c.unknown_attributes as usize <= MAX_ANNOUNCE_ATTRIBUTES);
|
||||||
|
let again = parse_announce(&write_announce(&c)).expect("what was accepted writes back");
|
||||||
|
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
|
||||||
|
});
|
||||||
@@ -1,11 +1,24 @@
|
|||||||
//! Fuzzes `/applist` answers: never panics, whatever the bytes.
|
//! Fuzzes `/applist` answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": at most MAX_APPS apps, titles within the cap, ids unique.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::http::parse_app_list(data);
|
let r = domistream::http::parse_app_list(data);
|
||||||
|
if data.len() > MAX_APPLIST_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(apps) = r {
|
||||||
|
assert!(apps.len() <= MAX_APPS);
|
||||||
|
let mut ids: Vec<u32> = apps.iter().map(|a| a.id).collect();
|
||||||
|
ids.sort_unstable();
|
||||||
|
ids.dedup();
|
||||||
|
assert_eq!(ids.len(), apps.len(), "duplicate ids accepted");
|
||||||
|
assert!(apps.iter().all(|a| a.title.len() <= MAX_APP_TITLE_BYTES));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
//! Fuzzes the audio depacketizer with a sequence of datagrams (FEC on, a Cauchy test matrix).
|
||||||
|
//! Asserts invariants, not only "no panic": never two events for one sequence number in a short run; output stays bounded by the input.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::HashSet;
|
||||||
|
|
||||||
|
use domistream::Instant;
|
||||||
|
use domistream::audio::{AudioConfig, AudioDepacketizer, AudioEvent, AudioFec};
|
||||||
|
|
||||||
|
// 1 / (x ^ y) over GF(2^8)/0x11D with x in {0, 1} and y in {2, 3, 4, 5}: a 2 x 4 Cauchy matrix, the same one
|
||||||
|
// tests/common builds with gf::cauchy(2, 4).
|
||||||
|
const MATRIX: [u8; 8] = [0x8e, 0xf4, 0x47, 0xa7, 0xf4, 0x8e, 0xa7, 0x47];
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let cfg = AudioConfig {
|
||||||
|
cipher: None,
|
||||||
|
packet_duration_ms: 5,
|
||||||
|
fec: AudioFec::ParityMatrix(MATRIX),
|
||||||
|
loss_timeout: Duration::from_millis(20),
|
||||||
|
};
|
||||||
|
let Ok(mut d) = AudioDepacketizer::new(cfg) else { return };
|
||||||
|
let mut rest = data;
|
||||||
|
let mut us = 0u64;
|
||||||
|
let mut seen = HashSet::new();
|
||||||
|
let mut out_bytes = 0usize;
|
||||||
|
while let Some((&len, tail)) = rest.split_first() {
|
||||||
|
let len = usize::from(len).min(tail.len());
|
||||||
|
let (g, tail) = tail.split_at(len);
|
||||||
|
rest = tail;
|
||||||
|
us += 1000;
|
||||||
|
let _ = d.push(Instant::from_micros(us), g);
|
||||||
|
let _ = d.handle_timeout(Instant::from_micros(us));
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
let seq = match &e {
|
||||||
|
AudioEvent::Packet { sequence, opus, .. } => {
|
||||||
|
out_bytes += opus.len();
|
||||||
|
*sequence
|
||||||
|
}
|
||||||
|
AudioEvent::Lost { sequence } => *sequence,
|
||||||
|
};
|
||||||
|
assert!(seen.insert(seq), "two events for sequence {seq}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(out_bytes <= data.len() * 2, "FEC rebuilds packets, but not out of nothing");
|
||||||
|
});
|
||||||
@@ -1,11 +1,24 @@
|
|||||||
//! Fuzzes audio packets: never panics, whatever the bytes.
|
//! Fuzzes audio packets.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": payload types and shard indices are the ones PROTOCOL.md allows; payloads are never empty.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::audio::AudioPacket;
|
||||||
|
use domistream::audio::packet::{AUDIO_FEC_PAYLOAD_TYPE, AUDIO_PAYLOAD_TYPE, MAX_AUDIO_PACKET_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::audio::parse_audio_packet(data);
|
match domistream::audio::parse_audio_packet(data) {
|
||||||
|
Ok(AudioPacket::Data { rtp, payload }) => {
|
||||||
|
assert_eq!(rtp.payload_type, AUDIO_PAYLOAD_TYPE);
|
||||||
|
assert!(!payload.is_empty() && data.len() <= MAX_AUDIO_PACKET_BYTES);
|
||||||
|
}
|
||||||
|
Ok(AudioPacket::Parity { rtp, fec, parity }) => {
|
||||||
|
assert_eq!(rtp.payload_type, AUDIO_FEC_PAYLOAD_TYPE);
|
||||||
|
assert!(fec.shard_index <= 1 && !parity.is_empty());
|
||||||
|
}
|
||||||
|
Err(_) => {}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,27 @@
|
|||||||
//! Fuzzes encrypted control frames (outer fields): never panics, whatever the bytes.
|
//! Fuzzes encrypted control frames (outer fields), their opening, and seal/open round trips.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": the length field matches the bytes, random frames never pass the GCM tag, and seal then open gives the plaintext back.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::control::frame::{FRAME_HEADER_LEN, MAX_FRAME_BYTES, MIN_FRAME_BYTES};
|
||||||
|
use domistream::control::{ControlCipher, Direction, parse_encrypted_frame};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::control::parse_encrypted_frame(data);
|
if let Ok(f) = parse_encrypted_frame(data) {
|
||||||
|
assert!(data.len() >= MIN_FRAME_BYTES && data.len() <= MAX_FRAME_BYTES);
|
||||||
|
assert_eq!(f.ciphertext.len() + FRAME_HEADER_LEN, data.len());
|
||||||
|
assert_eq!(&f.tag[..], &data[8..24]);
|
||||||
|
// A fuzzer forging a GCM tag would be a finding of its own.
|
||||||
|
assert_eq!(ControlCipher::new([0x42; 16]).open(Direction::HostToClient, data), Err(domistream::Error::Crypto));
|
||||||
|
}
|
||||||
|
if data.len() >= 4 && data.len() + FRAME_HEADER_LEN <= MAX_FRAME_BYTES {
|
||||||
|
let c = ControlCipher::new([0x24; 16]);
|
||||||
|
let seq = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
|
||||||
|
let sealed = c.seal(seq, Direction::ClientToHost, data).expect("seal");
|
||||||
|
assert_eq!(c.open(Direction::ClientToHost, &sealed), Ok((seq, data.to_vec())));
|
||||||
|
assert!(c.open(Direction::HostToClient, &sealed).is_err());
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,23 @@
|
|||||||
//! Fuzzes decrypted control messages from the host: never panics, whatever the bytes.
|
//! Fuzzes decrypted control messages from the host.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": the split matches the length field; a host message always splits as a message; Other keeps the body length.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::control::{HostMessage, parse_host_message, parse_message};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::control::parse_host_message(data);
|
let raw = parse_message(data);
|
||||||
|
if let Ok(r) = raw {
|
||||||
|
assert_eq!(r.body.len() + 4, data.len());
|
||||||
|
assert_eq!(r.message_type, u16::from_le_bytes([data[0], data[1]]));
|
||||||
|
}
|
||||||
|
if let Ok(m) = parse_host_message(data) {
|
||||||
|
assert!(raw.is_ok(), "a host message must split as a message first");
|
||||||
|
if let HostMessage::Other { body_len, .. } = m {
|
||||||
|
assert_eq!(body_len + 4, data.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
//! Fuzzes the ENet client peer: a connecting peer fed a sequence of datagrams.
|
||||||
|
//! Asserts invariants, not only "no panic": never panics; delivered packets are within MAX_PACKET_BYTES; outgoing datagrams parse and stay within the MTU.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use domistream::enet::protocol::parse_datagram;
|
||||||
|
use domistream::enet::{EnetClient, EnetConfig, EnetEvent, MAX_PACKET_BYTES};
|
||||||
|
use domistream::{Instant, RandomSource};
|
||||||
|
|
||||||
|
struct Fixed;
|
||||||
|
impl RandomSource for Fixed {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
dest.fill(0x5A);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let cfg = EnetConfig {
|
||||||
|
channel_count: 2,
|
||||||
|
mtu: 1400,
|
||||||
|
connect_data: 0,
|
||||||
|
ping_interval: Duration::from_millis(500),
|
||||||
|
timeout: Duration::from_secs(10),
|
||||||
|
};
|
||||||
|
let Ok(mut c) = EnetClient::connect(cfg, Instant::ZERO, &mut Fixed) else { return };
|
||||||
|
// Datagrams separated by a 2-byte big-endian length; time advances 1 ms per datagram.
|
||||||
|
let mut rest = data;
|
||||||
|
let mut ms = 0u64;
|
||||||
|
while rest.len() >= 2 {
|
||||||
|
let len = usize::from(u16::from_be_bytes([rest[0], rest[1]])).min(rest.len() - 2);
|
||||||
|
let (d, tail) = rest[2..].split_at(len);
|
||||||
|
rest = tail;
|
||||||
|
ms += 1;
|
||||||
|
let now = Instant::from_micros(ms * 1000);
|
||||||
|
let _ = c.handle_datagram(now, d);
|
||||||
|
let _ = c.handle_timeout(now);
|
||||||
|
while let Some(out) = c.poll_transmit(now) {
|
||||||
|
assert!(out.len() <= usize::from(cfg.mtu));
|
||||||
|
parse_datagram(&out).expect("the client's own datagrams parse");
|
||||||
|
}
|
||||||
|
while let Some(e) = c.poll_event() {
|
||||||
|
if let EnetEvent::Received { data, .. } = e {
|
||||||
|
assert!(data.len() <= MAX_PACKET_BYTES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,11 +1,19 @@
|
|||||||
//! Fuzzes ENet datagrams: never panics, whatever the bytes.
|
//! Fuzzes ENet datagrams.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable and within the datagram and command caps.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::enet::protocol::{MAX_COMMANDS_PER_DATAGRAM, MAX_DATAGRAM_BYTES, encode_datagram, parse_datagram};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::enet::protocol::parse_datagram(data);
|
if let Ok(d) = parse_datagram(data) {
|
||||||
|
assert!(data.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
assert!(d.commands.len() <= MAX_COMMANDS_PER_DATAGRAM);
|
||||||
|
let bytes = encode_datagram(&d).expect("a parsed datagram encodes");
|
||||||
|
assert!(bytes.len() <= MAX_DATAGRAM_BYTES);
|
||||||
|
assert_eq!(parse_datagram(&bytes), Ok(d));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
//! Fuzzes Reed-Solomon reconstruction with fuzzer-chosen shapes and erasures.
|
||||||
|
//! Asserts invariants, not only "no panic": up to m erasures always rebuild the encoded data byte-exact; more are refused; hostile shard sets never panic.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::fec::ReedSolomon;
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if data.len() < 4 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let k = 1 + usize::from(data[0]) % 32;
|
||||||
|
let m = 1 + usize::from(data[1]) % 16;
|
||||||
|
let len = 1 + usize::from(data[2]) % 32;
|
||||||
|
let Ok(code) = ReedSolomon::new(k, m) else { return };
|
||||||
|
let body = &data[3..];
|
||||||
|
let mut shards: Vec<Vec<u8>> =
|
||||||
|
(0..k).map(|i| (0..len).map(|x| body[(i * len + x) % body.len()]).collect()).collect();
|
||||||
|
shards.extend((0..m).map(|_| vec![0; len]));
|
||||||
|
code.encode(&mut shards).expect("encode");
|
||||||
|
let mask = u32::from(body[body.len() - 1]);
|
||||||
|
let lost: Vec<usize> = (0..k + m).filter(|&i| (mask.rotate_left(i as u32) ^ (i as u32 * 7)) % 3 == 0).collect();
|
||||||
|
let mut s: Vec<Option<Vec<u8>>> =
|
||||||
|
shards.iter().enumerate().map(|(i, v)| (!lost.contains(&i)).then(|| v.clone())).collect();
|
||||||
|
let r = code.reconstruct(&mut s);
|
||||||
|
if lost.len() <= m {
|
||||||
|
r.expect("<= m erasures rebuild");
|
||||||
|
for (a, b) in s.iter().zip(&shards) {
|
||||||
|
assert_eq!(a.as_deref(), Some(b.as_slice()));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::Truncated { .. })));
|
||||||
|
}
|
||||||
|
// The raw bytes as a hostile shard set.
|
||||||
|
let mut hostile: Vec<Option<Vec<u8>>> = body.chunks(len).map(|c| (c[0] & 1 == 0).then(|| c.to_vec())).collect();
|
||||||
|
let _ = code.reconstruct(&mut hostile);
|
||||||
|
});
|
||||||
@@ -1,11 +1,18 @@
|
|||||||
//! Fuzzes INPUT_DATA messages: never panics, whatever the bytes.
|
//! Fuzzes INPUT_DATA messages.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable; an accepted message's length field matches.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::input::{MAX_INPUT_MESSAGE_BYTES, encode_input, parse_input};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::input::parse_input(data);
|
if let Ok(e) = parse_input(data) {
|
||||||
|
assert!(data.len() <= MAX_INPUT_MESSAGE_BYTES);
|
||||||
|
assert_eq!(usize::from(u16::from_le_bytes([data[2], data[3]])) + 4, data.len());
|
||||||
|
let bytes = encode_input(&e).expect("a parsed event encodes");
|
||||||
|
assert_eq!(parse_input(&bytes), Ok(e));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,23 @@
|
|||||||
//! Fuzzes `/launch` and `/resume` answers: never panics, whatever the bytes.
|
//! Fuzzes `/launch` and `/resume` answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": a session URL is within the cap, starts with rtsp:// and has no control characters.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES, MAX_SESSION_URL_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::http::parse_launch_response(data);
|
let r = domistream::http::parse_launch_response(data);
|
||||||
|
if data.len() > MAX_LAUNCH_RESPONSE_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(l) = r {
|
||||||
|
if let Some(url) = l.session_url {
|
||||||
|
assert!(url.len() <= MAX_SESSION_URL_BYTES);
|
||||||
|
assert!(url.starts_with("rtsp://"));
|
||||||
|
assert!(!url.chars().any(char::is_control));
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
//! Fuzzes the video (AES-GCM) and audio (AES-CBC) decryption of hostile packets.
|
||||||
|
//! Asserts invariants, not only "no panic": random video packets never pass the tag; audio output is shorter than its input, which is whole blocks.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::SessionKeys;
|
||||||
|
use domistream::audio::AudioCipher;
|
||||||
|
use domistream::video::VideoCipher;
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if let Ok(p) = VideoCipher::new([0x42; 16]).decrypt(data) {
|
||||||
|
panic!("forged video packet accepted: {} bytes", p.len());
|
||||||
|
}
|
||||||
|
let seq = data.first().map_or(0, |b| u16::from(*b));
|
||||||
|
if let Ok(p) = AudioCipher::new(&SessionKeys { rikey: [0x42; 16], rikeyid: 7 }).decrypt(seq, data) {
|
||||||
|
assert!(p.len() < data.len() && data.len() % 16 == 0);
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,11 +1,21 @@
|
|||||||
//! Fuzzes pairing answers: never panics, whatever the bytes.
|
//! Fuzzes pairing answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": decoded values are at most half the body (hex), oversize is TooLarge.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::pairing::MAX_PAIR_RESPONSE_BYTES;
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::pairing::parse_pair_response(data);
|
let r = domistream::pairing::parse_pair_response(data);
|
||||||
|
if data.len() > MAX_PAIR_RESPONSE_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(p) = r {
|
||||||
|
for v in [&p.plain_cert, &p.challenge_response, &p.pairing_secret].into_iter().flatten() {
|
||||||
|
assert!(v.len() * 2 <= data.len());
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
//! Fuzzes the pairing state machine: a session with the test-only identity fed fuzzer bodies at each step.
|
||||||
|
//! Asserts invariants, not only "no panic": a host that knows neither the PIN's key nor the host key never gets the session to Paired, and Failed is terminal.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::RandomSource;
|
||||||
|
use domistream::pairing::{ClientIdentity, PairingSession, PairingState, PairingStep, Pin};
|
||||||
|
|
||||||
|
const VECTORS: &str = include_str!("../../crates/domistream/tests/fixtures/pairing.txt");
|
||||||
|
|
||||||
|
fn value(name: &str) -> Vec<u8> {
|
||||||
|
let prefix = format!("{name} = ");
|
||||||
|
let line = VECTORS.lines().find(|l| l.starts_with(&prefix)).expect("fixture value");
|
||||||
|
let hex = &line[prefix.len()..];
|
||||||
|
(0..hex.len()).step_by(2).map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("hex")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Fixed;
|
||||||
|
impl RandomSource for Fixed {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
dest.fill(0x33);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Ok(id) = ClientIdentity::from_der(&value("client_cert_der"), &value("client_key_pkcs8_der")) else { return };
|
||||||
|
let Ok(pin) = Pin::from_digits("4071") else { return };
|
||||||
|
let Ok((mut s, _)) = PairingSession::start(&id, "0123456789ABCDEF", "fuzz", pin, &mut Fixed) else { return };
|
||||||
|
// Bodies separated by 0xFF bytes (never valid in the XML); the HTTP status is always 200.
|
||||||
|
for body in data.split(|b| *b == 0xFF).take(6) {
|
||||||
|
let before = s.state();
|
||||||
|
let r = s.handle_response(&id, 200, body, &mut Fixed);
|
||||||
|
assert!(!matches!(r, Ok(PairingStep::Paired(_))), "paired with a host that cannot know the PIN key");
|
||||||
|
if let PairingState::Failed(_) = before {
|
||||||
|
assert!(r.is_err());
|
||||||
|
assert_eq!(s.state(), before, "Failed is terminal");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Fuzzes the RTP header: never panics, whatever the bytes.
|
//! Fuzzes the RTP header.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": success means at least 12 bytes and version 2, with the fields read big-endian from the bytes.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
@@ -7,5 +7,11 @@
|
|||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::rtp::parse_rtp_header(data);
|
if let Ok(h) = domistream::rtp::parse_rtp_header(data) {
|
||||||
|
assert!(data.len() >= domistream::rtp::RTP_HEADER_LEN);
|
||||||
|
assert_eq!(h.flags >> 6, 2);
|
||||||
|
assert_eq!(h.flags, data[0]);
|
||||||
|
assert_eq!(h.sequence, u16::from_be_bytes([data[2], data[3]]));
|
||||||
|
assert_eq!(h.timestamp, u32::from_be_bytes([data[4], data[5], data[6], data[7]]));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//! Fuzzes the RTSP client state machine with hostile answers.
|
||||||
|
//! Asserts invariants, not only "no panic": the requests it emits always parse, and it never reports Ready before a full exchange.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::launch::AudioLayout;
|
||||||
|
use domistream::rtsp::client::VideoCodec;
|
||||||
|
use domistream::rtsp::{EncryptionFlags, RtspClient, RtspProgress, StreamConfig, parse_request};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let config = StreamConfig {
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
fps: 60,
|
||||||
|
bitrate_kbps: 20_000,
|
||||||
|
packet_size: 1024,
|
||||||
|
codec: VideoCodec::Hevc,
|
||||||
|
hdr: false,
|
||||||
|
audio: AudioLayout::Stereo,
|
||||||
|
audio_packet_duration_ms: 5,
|
||||||
|
min_fec_packets: 2,
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
encryption: EncryptionFlags(7),
|
||||||
|
};
|
||||||
|
let Ok(mut c) = RtspClient::new("rtsp://192.0.2.10:48010", config) else { return };
|
||||||
|
// Answers separated by NUL bytes.
|
||||||
|
for (answers, answer) in data.split(|b| *b == 0).take(8).enumerate() {
|
||||||
|
if let Some(req) = c.poll_request() {
|
||||||
|
parse_request(&req).expect("the client's requests parse");
|
||||||
|
}
|
||||||
|
if let Ok(RtspProgress::Ready(_)) = c.handle_response(answer) {
|
||||||
|
assert!(answers >= 6, "Ready after {} answers", answers + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,23 +1,37 @@
|
|||||||
//! Fuzzes the RTSP framer over a chunked byte stream: never panics, whatever the bytes.
|
//! Fuzzes the RTSP framer over a chunked byte stream.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": never buffers past the cap, and the messages do not depend on how the stream is chunked (chunked vs one push).
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::{MAX_RTSP_MESSAGE_BYTES, RtspFramer};
|
||||||
|
|
||||||
|
fn frame(stream: &[u8], chunk: usize) -> Option<Vec<Vec<u8>>> {
|
||||||
|
let mut f = RtspFramer::new();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for piece in stream.chunks(chunk) {
|
||||||
|
f.push(piece).ok()?;
|
||||||
|
assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES);
|
||||||
|
while let Some(m) = f.next_message().ok()? {
|
||||||
|
let _ = domistream::rtsp::parse_response(&m);
|
||||||
|
out.push(m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Some(last) = f.finish().ok()? {
|
||||||
|
out.push(last);
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
// First byte picks the chunk size, so libFuzzer explores message boundaries across pushes.
|
// First byte picks the chunk size, so libFuzzer explores message boundaries across pushes.
|
||||||
let Some((&chunk, rest)) = data.split_first() else { return };
|
let Some((&chunk, rest)) = data.split_first() else { return };
|
||||||
let chunk = usize::from(chunk).max(1);
|
let chunked = frame(rest, usize::from(chunk).max(1));
|
||||||
let mut framer = domistream::rtsp::RtspFramer::new();
|
let whole = frame(rest, rest.len().max(1));
|
||||||
for piece in rest.chunks(chunk) {
|
if let (Some(a), Some(b)) = (&chunked, &whole) {
|
||||||
if framer.push(piece).is_err() {
|
assert_eq!(a, b, "framing depends on chunking");
|
||||||
return;
|
assert!(a.iter().map(Vec::len).sum::<usize>() <= rest.len());
|
||||||
}
|
}
|
||||||
while let Ok(Some(message)) = framer.next_message() {
|
|
||||||
let _ = domistream::rtsp::parse_response(&message);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let _ = framer.finish();
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//! Fuzzes RTSP requests: never panics, whatever the bytes.
|
//! Fuzzes RTSP requests.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": parse -> encode -> parse is stable.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
@@ -7,5 +7,8 @@
|
|||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::rtsp::parse_request(data);
|
if let Ok(req) = domistream::rtsp::parse_request(data) {
|
||||||
|
let bytes = req.encode().expect("a parsed request encodes");
|
||||||
|
assert_eq!(domistream::rtsp::parse_request(&bytes), Ok(req));
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,22 @@
|
|||||||
//! Fuzzes RTSP responses: never panics, whatever the bytes.
|
//! Fuzzes RTSP responses.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": header count, line length and body within the caps.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::{MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::rtsp::parse_response(data);
|
let r = domistream::rtsp::parse_response(data);
|
||||||
|
if data.len() > MAX_RTSP_MESSAGE_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(m) = r {
|
||||||
|
assert!(m.headers.len() <= MAX_RTSP_HEADERS);
|
||||||
|
assert!(m.reason.len() <= MAX_RTSP_LINE_BYTES);
|
||||||
|
assert!(m.headers.iter().all(|(k, v)| k.len() + v.len() <= MAX_RTSP_LINE_BYTES));
|
||||||
|
assert!(m.body.len() <= data.len());
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,172 @@
|
|||||||
|
//! Fuzzes the host's RTSP session with arbitrary requests, optionally after a valid prefix of the negotiation so the
|
||||||
|
//! later states are reached too.
|
||||||
|
//! Asserts invariants, not only "no panic": every answer parses with a documented status, 200 exactly when nothing
|
||||||
|
//! was refused, the state only moves forward and never on a refusal, and the events come once each, in order.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::RandomSource;
|
||||||
|
use domistream::rtsp::client::VideoCodec;
|
||||||
|
use domistream::rtsp::sdp::FeatureFlags;
|
||||||
|
use domistream::rtsp::server::{ChromaSampling, StreamConfig, SurroundSettings, parse_announce, write_announce};
|
||||||
|
use domistream::rtsp::{
|
||||||
|
EncryptionFlags, HostOffer, OpusConfig, RtspFramer, RtspServer, RtspServerState, ServerConfig, ServerEvent,
|
||||||
|
StreamPorts, parse_response,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Fixed(u8);
|
||||||
|
|
||||||
|
impl RandomSource for Fixed {
|
||||||
|
fn fill(&mut self, dest: &mut [u8]) {
|
||||||
|
dest.fill(self.0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rank(s: RtspServerState) -> u8 {
|
||||||
|
match s {
|
||||||
|
RtspServerState::Options => 0,
|
||||||
|
RtspServerState::Describe => 1,
|
||||||
|
RtspServerState::Setup => 2,
|
||||||
|
RtspServerState::Announce => 3,
|
||||||
|
RtspServerState::Play => 4,
|
||||||
|
RtspServerState::Playing => 5,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn announce() -> StreamConfig {
|
||||||
|
StreamConfig {
|
||||||
|
width: 1920,
|
||||||
|
height: 1080,
|
||||||
|
max_fps: 60,
|
||||||
|
packet_size: 1024,
|
||||||
|
bitrate_kbps: 20_000,
|
||||||
|
codec: VideoCodec::Hevc,
|
||||||
|
min_fec_packets: 2,
|
||||||
|
video_qos_traffic_type: 5,
|
||||||
|
audio_packet_duration_ms: 5,
|
||||||
|
audio_qos_traffic_type: 4,
|
||||||
|
max_reference_frames: 0,
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
dynamic_range_mode: 0,
|
||||||
|
encoder_csc_mode: 0,
|
||||||
|
chroma: ChromaSampling::Yuv420,
|
||||||
|
encryption: EncryptionFlags(7),
|
||||||
|
surround: SurroundSettings::default(),
|
||||||
|
unknown_attributes: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The valid negotiation, one request each.
|
||||||
|
fn prelude(session: &str) -> Vec<Vec<u8>> {
|
||||||
|
let body = write_announce(&announce());
|
||||||
|
let mut v = vec![
|
||||||
|
b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\n\r\n".to_vec(),
|
||||||
|
b"DESCRIBE rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 2\r\n\r\n".to_vec(),
|
||||||
|
];
|
||||||
|
for (i, s) in ["audio", "video", "control"].iter().enumerate() {
|
||||||
|
v.push(
|
||||||
|
format!("SETUP streamid={s}/0/0 RTSP/1.0\r\nCSeq: {}\r\nSession: {session}\r\nTransport: x\r\n\r\n", i + 3)
|
||||||
|
.into_bytes(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let mut a = format!("ANNOUNCE streamid=control/13/0 RTSP/1.0\r\nCSeq: 6\r\nContent-Length: {}\r\n\r\n", body.len())
|
||||||
|
.into_bytes();
|
||||||
|
a.extend_from_slice(&body);
|
||||||
|
v.push(a);
|
||||||
|
v.push(b"PLAY rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 7\r\n\r\n".to_vec());
|
||||||
|
// The first SETUP carries no session: none was issued yet.
|
||||||
|
if let Some(first) = v.get_mut(2) {
|
||||||
|
*first = b"SETUP streamid=audio/0/0 RTSP/1.0\r\nCSeq: 3\r\nTransport: x\r\n\r\n".to_vec();
|
||||||
|
}
|
||||||
|
v
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Checker {
|
||||||
|
announced: u32,
|
||||||
|
played: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Checker {
|
||||||
|
fn feed(&mut self, s: &mut RtspServer, message: &[u8]) {
|
||||||
|
let before = s.state();
|
||||||
|
let reply = s.handle_request(message);
|
||||||
|
let r = parse_response(&reply.bytes).expect("every answer parses");
|
||||||
|
assert_eq!(r.status, reply.status);
|
||||||
|
assert!([200, 400, 451, 454, 455, 501].contains(&reply.status), "status {}", reply.status);
|
||||||
|
assert_eq!(reply.status == 200, reply.error.is_none());
|
||||||
|
assert!(rank(s.state()) >= rank(before), "state went back");
|
||||||
|
if reply.status != 200 {
|
||||||
|
assert_eq!(s.state(), before, "a refusal changed the state");
|
||||||
|
}
|
||||||
|
while let Some(e) = s.poll_event() {
|
||||||
|
match e {
|
||||||
|
ServerEvent::Announced(c) => {
|
||||||
|
assert_eq!(self.announced, 0);
|
||||||
|
self.announced += 1;
|
||||||
|
let again = parse_announce(&write_announce(&c)).expect("an accepted ANNOUNCE writes back");
|
||||||
|
assert_eq!(again, StreamConfig { unknown_attributes: 0, ..c });
|
||||||
|
}
|
||||||
|
ServerEvent::PlayRequested => {
|
||||||
|
assert_eq!((self.announced, self.played), (1, 0));
|
||||||
|
self.played += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(self.played == 1, s.state() == RtspServerState::Playing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Some((&mode, rest)) = data.split_first() else { return };
|
||||||
|
let config = ServerConfig {
|
||||||
|
ports: StreamPorts { audio: 48000, video: 47998, control: 47999 },
|
||||||
|
offer: HostOffer {
|
||||||
|
feature_flags: FeatureFlags(3),
|
||||||
|
encryption_supported: EncryptionFlags(7),
|
||||||
|
reference_frame_invalidation: true,
|
||||||
|
h264: true,
|
||||||
|
hevc: true,
|
||||||
|
av1: mode & 0x40 != 0,
|
||||||
|
hdr: mode & 0x80 != 0,
|
||||||
|
yuv444: false,
|
||||||
|
opus_configs: vec![OpusConfig::stereo()],
|
||||||
|
},
|
||||||
|
required_encryption: EncryptionFlags(1),
|
||||||
|
require_session_header: mode & 0x20 != 0,
|
||||||
|
session_timeout_secs: 90,
|
||||||
|
};
|
||||||
|
let mut s = RtspServer::new(config, &mut Fixed(mode)).expect("a valid config");
|
||||||
|
let mut check = Checker { announced: 0, played: 0 };
|
||||||
|
let session = s.session_id().to_string();
|
||||||
|
// Bits 2..=4: how many valid requests come first (0..=7).
|
||||||
|
for m in prelude(&session).iter().take(usize::from((mode >> 2) & 0x07)) {
|
||||||
|
check.feed(&mut s, m);
|
||||||
|
}
|
||||||
|
if mode & 0x01 == 0 {
|
||||||
|
// Messages separated by NUL bytes, each fed whole.
|
||||||
|
for m in rest.split(|b| *b == 0).take(32) {
|
||||||
|
check.feed(&mut s, m);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// A byte stream through the request framer.
|
||||||
|
let mut f = RtspFramer::for_requests();
|
||||||
|
for chunk in rest.chunks(if mode & 0x02 == 0 { 7 } else { 512 }) {
|
||||||
|
if f.push(chunk).is_err() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
loop {
|
||||||
|
match f.next_message() {
|
||||||
|
Ok(Some(m)) => check.feed(&mut s, &m),
|
||||||
|
Ok(None) => break,
|
||||||
|
Err(_) => return,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(Some(m)) = f.finish() {
|
||||||
|
check.feed(&mut s, &m);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,13 +1,32 @@
|
|||||||
//! Fuzzes SDP payloads and the host capabilities read from them: never panics, whatever the bytes.
|
//! Fuzzes SDP payloads, the host capabilities read from them, and `surround-params` values.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": line and config caps hold; every Opus config obeys RFC 7845's rules.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::rtsp::sdp::{self, MAX_AUDIO_CHANNELS, MAX_OPUS_CONFIGS, MAX_SDP_LINES, OpusConfig};
|
||||||
|
|
||||||
|
fn valid(c: &OpusConfig) {
|
||||||
|
assert!(c.channels >= 1 && usize::from(c.channels) <= MAX_AUDIO_CHANNELS);
|
||||||
|
assert!(c.coupled_streams <= c.streams && c.streams >= 1);
|
||||||
|
assert_eq!(c.mapping.len(), usize::from(c.channels));
|
||||||
|
let total = u16::from(c.streams) + u16::from(c.coupled_streams);
|
||||||
|
assert!(c.mapping.iter().all(|&m| u16::from(m) < total));
|
||||||
|
}
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
if let Ok(sdp) = domistream::rtsp::sdp::parse_sdp(data) {
|
if let Ok(s) = sdp::parse_sdp(data) {
|
||||||
let _ = domistream::rtsp::HostCapabilities::from_sdp(&sdp);
|
assert!(s.attributes.len() + s.other.len() <= MAX_SDP_LINES);
|
||||||
|
if let Ok(caps) = domistream::rtsp::HostCapabilities::from_sdp(&s) {
|
||||||
|
assert!(caps.opus_configs.len() <= MAX_OPUS_CONFIGS);
|
||||||
|
caps.opus_configs.iter().for_each(valid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let Ok(text) = core::str::from_utf8(data) {
|
||||||
|
if let Ok(c) = sdp::parse_surround_params(text) {
|
||||||
|
valid(&c);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//! Fuzzes stored certificates and identities (`ServerCert::from_der`, `ClientIdentity::from_der`).
|
||||||
|
//! Asserts invariants, not only "no panic": accepted DER round-trips; an identity never loads from a cert and key that do not match (first byte splits the input).
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::pairing::{ClientIdentity, ServerCert};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
if let Ok(c) = ServerCert::from_der(data) {
|
||||||
|
assert_eq!(c.der(), data);
|
||||||
|
assert_eq!(c.matches(data), Ok(true));
|
||||||
|
}
|
||||||
|
let Some((&split, rest)) = data.split_first() else { return };
|
||||||
|
let at = (usize::from(split) * rest.len()) / 255;
|
||||||
|
let (cert, key) = rest.split_at(at.min(rest.len()));
|
||||||
|
if let Ok(id) = ClientIdentity::from_der(cert, key) {
|
||||||
|
assert_eq!(id.cert_der(), cert);
|
||||||
|
let sig = id.sign(b"fuzz").expect("a loaded identity signs");
|
||||||
|
ServerCert::from_der(cert).expect("its cert loads").verify(b"fuzz", &sig).expect("key matches cert");
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,11 +1,24 @@
|
|||||||
//! Fuzzes the host certificate PEM (`plaincert`): never panics, whatever the bytes.
|
//! Fuzzes the host certificate PEM (`plaincert`).
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": an accepted PEM gives a DER that loads again, equals itself, pins itself, and has a signature.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::pairing::ServerCert;
|
||||||
|
use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::pairing::ServerCert::from_pem(data);
|
let r = ServerCert::from_pem(data);
|
||||||
|
if data.len() > MAX_CERT_PEM_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(c) = r {
|
||||||
|
assert!(c.der().len() <= MAX_CERT_DER_BYTES);
|
||||||
|
let again = ServerCert::from_der(c.der()).expect("the DER of an accepted PEM loads");
|
||||||
|
assert_eq!(again, c);
|
||||||
|
assert_eq!(c.matches(c.der()), Ok(true));
|
||||||
|
assert!(!c.signature().expect("signature").is_empty());
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,11 +1,26 @@
|
|||||||
//! Fuzzes `/serverinfo` answers: never panics, whatever the bytes.
|
//! Fuzzes `/serverinfo` answers.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": string fields within MAX_SERVERINFO_FIELD_BYTES, required fields non-empty, oversize is TooLarge.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::http::serverinfo::{MAX_SERVERINFO_BYTES, MAX_SERVERINFO_FIELD_BYTES};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::http::parse_server_info(data);
|
let r = domistream::http::parse_server_info(data);
|
||||||
|
if data.len() > MAX_SERVERINFO_BYTES {
|
||||||
|
assert!(matches!(r, Err(domistream::Error::TooLarge { .. })));
|
||||||
|
}
|
||||||
|
if let Ok(s) = r {
|
||||||
|
for f in [&s.hostname, &s.app_version, &s.unique_id, &s.state] {
|
||||||
|
assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES);
|
||||||
|
}
|
||||||
|
for f in [&s.gfe_version, &s.local_ip].into_iter().flatten() {
|
||||||
|
assert!(f.len() <= MAX_SERVERINFO_FIELD_BYTES);
|
||||||
|
}
|
||||||
|
assert!(!s.hostname.is_empty() && !s.unique_id.is_empty());
|
||||||
|
let _ = s.is_busy();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
//! Fuzzes the video depacketizer with a sequence of datagrams.
|
||||||
|
//! Asserts invariants, not only "no panic": frames stay within MAX_FRAME_BYTES and come out in increasing frame order; lost ranges are forward ranges.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use domistream::Instant;
|
||||||
|
use domistream::video::{MAX_FRAME_BYTES, VideoConfig, VideoDepacketizer, VideoEvent};
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let cfg = VideoConfig { packet_size: 64, cipher: None, frame_timeout: Duration::from_millis(20) };
|
||||||
|
let Ok(mut d) = VideoDepacketizer::new(cfg) else { return };
|
||||||
|
let mut rest = data;
|
||||||
|
let mut us = 0u64;
|
||||||
|
let mut prev: Option<u32> = None;
|
||||||
|
// Datagrams separated by a 1-byte length; time advances 1 ms per datagram.
|
||||||
|
while let Some((&len, tail)) = rest.split_first() {
|
||||||
|
let len = usize::from(len).min(tail.len());
|
||||||
|
let (g, tail) = tail.split_at(len);
|
||||||
|
rest = tail;
|
||||||
|
us += 1000;
|
||||||
|
let _ = d.push(Instant::from_micros(us), g);
|
||||||
|
let _ = d.handle_timeout(Instant::from_micros(us));
|
||||||
|
while let Some(e) = d.poll_event() {
|
||||||
|
match e {
|
||||||
|
VideoEvent::Frame(f) => {
|
||||||
|
assert!(f.bitstream.len() <= MAX_FRAME_BYTES);
|
||||||
|
if let Some(p) = prev {
|
||||||
|
assert!(f.frame_index.wrapping_sub(p).wrapping_sub(1) < 1 << 31, "frame order");
|
||||||
|
}
|
||||||
|
prev = Some(f.frame_index);
|
||||||
|
}
|
||||||
|
VideoEvent::FrameLost { first, last } => assert!(last.wrapping_sub(first) < 1 << 31),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
@@ -1,12 +1,25 @@
|
|||||||
//! Fuzzes video packets and the frame header: never panics, whatever the bytes.
|
//! Fuzzes video packets and the frame header.
|
||||||
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
|
//! Asserts invariants, not only "no panic": FEC fields are consistent on success, the payload is the rest of the packet, the frame header keeps its raw bytes.
|
||||||
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
#![no_main]
|
#![no_main]
|
||||||
|
|
||||||
use libfuzzer_sys::fuzz_target;
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use domistream::video::packet::{FRAME_HEADER_LEN, MAX_VIDEO_PACKET_BYTES, PAYLOAD_OFFSET, parse_frame_header};
|
||||||
|
|
||||||
fuzz_target!(|data: &[u8]| {
|
fuzz_target!(|data: &[u8]| {
|
||||||
let _ = domistream::video::parse_video_packet(data);
|
if let Ok(p) = domistream::video::parse_video_packet(data) {
|
||||||
let _ = domistream::video::packet::parse_frame_header(data);
|
assert!(data.len() >= PAYLOAD_OFFSET && data.len() <= MAX_VIDEO_PACKET_BYTES);
|
||||||
|
assert_eq!(p.payload.len() + PAYLOAD_OFFSET, data.len());
|
||||||
|
let f = p.nv.fec;
|
||||||
|
assert!(f.data_shards > 0 && f.block_index <= f.last_block_index && f.last_block_index < 4);
|
||||||
|
let m =
|
||||||
|
domistream::fec::parity_count(usize::from(f.data_shards), f.fec_percentage).expect("a consistent block");
|
||||||
|
assert!(usize::from(f.shard_index) < usize::from(f.data_shards) + m);
|
||||||
|
assert!(usize::from(f.data_shards) + m <= domistream::fec::MAX_SHARDS);
|
||||||
|
}
|
||||||
|
if let Ok(h) = parse_frame_header(data) {
|
||||||
|
assert_eq!(&h.raw[..], &data[..FRAME_HEADER_LEN]);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
//! Fuzzes the host's video packetizer against the client's depacketizer (`docs/PROTOCOL.md` 5.2, 5.3, 7).
|
||||||
|
//! Arbitrary frame bytes and parameters (packet size, FEC percentage, minimum parity, encryption, frame type,
|
||||||
|
//! latency) → packetize two frames → lose up to `m` packets of every block → depacketize: both frames must come back
|
||||||
|
//! byte-exact, in order, with their headers. Every valid configuration must be accepted and every frame within
|
||||||
|
//! `max_bitstream_len` packetized.
|
||||||
|
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
|
||||||
|
|
||||||
|
#![no_main]
|
||||||
|
|
||||||
|
use libfuzzer_sys::fuzz_target;
|
||||||
|
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::BTreeMap;
|
||||||
|
|
||||||
|
use domistream::Instant;
|
||||||
|
use domistream::fec::parity_count;
|
||||||
|
use domistream::video::packet::parse_video_packet;
|
||||||
|
use domistream::video::packetizer::{EncodedFrame, VideoPacketizer, VideoPacketizerConfig};
|
||||||
|
use domistream::video::{FrameType, VideoCipher, VideoConfig, VideoDepacketizer, VideoEvent};
|
||||||
|
|
||||||
|
const KEY: [u8; 16] = *b"fuzz-video-key!!";
|
||||||
|
|
||||||
|
/// xorshift64*, seeded from the input: which packets are lost.
|
||||||
|
struct Rng(u64);
|
||||||
|
|
||||||
|
impl Rng {
|
||||||
|
fn below(&mut self, n: usize) -> usize {
|
||||||
|
self.0 ^= self.0 >> 12;
|
||||||
|
self.0 ^= self.0 << 25;
|
||||||
|
self.0 ^= self.0 >> 27;
|
||||||
|
(self.0.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 33) as usize % n.max(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fuzz_target!(|data: &[u8]| {
|
||||||
|
let Some((head, body)) = data.split_first_chunk::<10>() else { return };
|
||||||
|
let [s0, s1, pct, min, flags, loss, split, l0, l1, first] = *head;
|
||||||
|
// 17..=4048: every packet size the receiver accepts, sealed or not.
|
||||||
|
let packet_size = 17 + u16::from_le_bytes([s0, s1]) % 4032;
|
||||||
|
let encrypt = flags & 1 != 0;
|
||||||
|
let frame_type = match (flags >> 1) & 3 {
|
||||||
|
0 => FrameType::Predicted,
|
||||||
|
1 => FrameType::Key,
|
||||||
|
2 => FrameType::Recovery,
|
||||||
|
_ => FrameType::Other((flags >> 3) | 0x08), // 8..=31: never a value with its own name (1, 2, 5)
|
||||||
|
};
|
||||||
|
let lossy = flags & 0x80 != 0;
|
||||||
|
let cipher = || encrypt.then(|| VideoCipher::new(KEY));
|
||||||
|
let config = VideoPacketizerConfig {
|
||||||
|
packet_size,
|
||||||
|
fec_percentage: pct,
|
||||||
|
min_required_fec_packets: min,
|
||||||
|
cipher: cipher(),
|
||||||
|
first_sequence: u16::from_le_bytes([first, s0]),
|
||||||
|
};
|
||||||
|
let mut tx = VideoPacketizer::new(config).expect("a valid configuration is accepted");
|
||||||
|
let mut rx =
|
||||||
|
VideoDepacketizer::new(VideoConfig { packet_size, cipher: cipher(), frame_timeout: Duration::from_millis(20) })
|
||||||
|
.expect("the receiver accepts the same packet size");
|
||||||
|
|
||||||
|
let cut = body.len() * usize::from(split) / 255;
|
||||||
|
let (a, b) = body.split_at(cut);
|
||||||
|
let frames = [a, b];
|
||||||
|
let mut rng = Rng(u64::from_le_bytes([s0, s1, pct, min, flags, loss, split, l0]) | 1);
|
||||||
|
let mut datagrams = Vec::new();
|
||||||
|
for (i, bitstream) in frames.iter().enumerate() {
|
||||||
|
assert!(bitstream.len() <= tx.max_bitstream_len(), "fuzz inputs stay far below the frame cap");
|
||||||
|
let frame = EncodedFrame {
|
||||||
|
frame_index: 0xFFFF_FFFF_u32.wrapping_add(i as u32),
|
||||||
|
frame_type,
|
||||||
|
rtp_timestamp: u32::from(l1) << 8,
|
||||||
|
processing_latency: u16::from_le_bytes([l0, l1]),
|
||||||
|
bitstream,
|
||||||
|
};
|
||||||
|
let out = tx.packetize(&frame).expect("a frame within the cap is packetized");
|
||||||
|
// Group by block (from the plaintext), then lose up to m of each block.
|
||||||
|
let mut blocks: BTreeMap<u8, (Vec<usize>, usize)> = BTreeMap::new();
|
||||||
|
for (j, d) in out.iter().enumerate() {
|
||||||
|
let plain = if encrypt { VideoCipher::new(KEY).decrypt(d).expect("our own seal opens") } else { d.clone() };
|
||||||
|
let p = parse_video_packet(&plain).expect("our own packet parses");
|
||||||
|
let m = parity_count(usize::from(p.nv.fec.data_shards), p.nv.fec.fec_percentage).expect("consistent FEC");
|
||||||
|
blocks.entry(p.nv.fec.block_index).or_insert_with(|| (Vec::new(), m)).0.push(j);
|
||||||
|
}
|
||||||
|
let mut keep = vec![true; out.len()];
|
||||||
|
if lossy {
|
||||||
|
for (positions, m) in blocks.values() {
|
||||||
|
let mut left = positions.clone();
|
||||||
|
for _ in 0..rng.below(m + 1).min(left.len()) {
|
||||||
|
let pick = left.swap_remove(rng.below(left.len()));
|
||||||
|
if let Some(k) = keep.get_mut(pick) {
|
||||||
|
*k = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Sent in order; every block keeps at least k packets, so frame 0 starts the receiver.
|
||||||
|
datagrams.extend(out.into_iter().zip(keep).filter(|(_, k)| *k).map(|(d, _)| d));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut us = 1_000u64;
|
||||||
|
let mut got = Vec::new();
|
||||||
|
for d in &datagrams {
|
||||||
|
rx.push(Instant::from_micros(us), d).expect("within the receiver's cap");
|
||||||
|
us += 10;
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
got.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for _ in 0..8 {
|
||||||
|
us += 1_000_000;
|
||||||
|
let _ = rx.handle_timeout(Instant::from_micros(us));
|
||||||
|
while let Some(e) = rx.poll_event() {
|
||||||
|
got.push(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert_eq!(got.len(), 2, "two frames out: {got:?}");
|
||||||
|
for (i, (e, want)) in got.iter().zip(frames).enumerate() {
|
||||||
|
let VideoEvent::Frame(f) = e else { panic!("frame {i} lost: {e:?}") };
|
||||||
|
assert_eq!(f.frame_index, 0xFFFF_FFFF_u32.wrapping_add(i as u32));
|
||||||
|
assert!(f.bitstream == want, "frame {i}: {} bytes out, {} in", f.bitstream.len(), want.len());
|
||||||
|
assert_eq!(f.header.frame_type, frame_type);
|
||||||
|
assert_eq!(f.header.processing_latency, u16::from_le_bytes([l0, l1]));
|
||||||
|
assert_eq!(f.rtp_timestamp, u32::from(l1) << 8);
|
||||||
|
}
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user