diff --git a/.gitignore b/.gitignore index 06cd9f3..7aa0c85 100644 --- a/.gitignore +++ b/.gitignore @@ -11,3 +11,4 @@ fuzz/corpus/ *.h265 *.pcap *.pcapng +*.proptest-regressions diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..b478107 --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,601 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common", + "inout", +] + +[[package]] +name = "aes" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc0fc36d7440d015b45468ba08a21e80e056ebbd014c611c6298bb7503e04bd1" +dependencies = [ + "cipher", + "cpubits", + "cpufeatures", +] + +[[package]] +name = "aes-gcm" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" +dependencies = [ + "aead", + "aes", + "cipher", + "ctr", + "ctutils", + "ghash", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", + "zeroize", +] + +[[package]] +name = "block-padding" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "cbc" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce2dc9ee5f88d11e0beb842c88b33c8a5cf0d1329c4b19494af42b07dbfe8896" +dependencies = [ + "cipher", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +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]] +name = "cipher" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" +dependencies = [ + "block-buffer", + "crypto-common", + "inout", +] + +[[package]] +name = "cmov" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a" + +[[package]] +name = "const-oid" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpubits" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b85f9c39137c3a891689859392b1bd49812121d0d61c9caf00d46ed5ce06ae" + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.7.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82" +dependencies = [ + "cpubits", + "ctutils", + "num-traits", + "rand_core", + "serdect", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", + "rand_core", +] + +[[package]] +name = "crypto-primes" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f" +dependencies = [ + "crypto-bigint", + "rand_core", +] + +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher", +] + +[[package]] +name = "ctutils" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f" +dependencies = [ + "cmov", +] + +[[package]] +name = "der" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004" +dependencies = [ + "const-oid", + "der_derive", + "flagset", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "der_derive" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "ctutils", + "zeroize", +] + +[[package]] +name = "domistream" +version = "0.1.0" +dependencies = [ + "aes", + "aes-gcm", + "cbc", + "peak_alloc", + "proptest", + "rand_core", + "rsa", + "sha2", + "x509-cert", + "zeroize", +] + +[[package]] +name = "flagset" +version = "0.4.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7ac824320a75a52197e8f2d787f6a38b6718bb6897a35142d749af3c0e8f4fe" + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "rand_core", +] + +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval", +] + +[[package]] +name = "hmac" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6303bc9732ae41b04cb554b844a762b4115a61bfaa81e3e83050991eeb56863f" +dependencies = [ + "digest", +] + +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + +[[package]] +name = "inout" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a580c13f0ffc335ef42dd3f6b1a41b726051c5e1656d9a3aa6fddb3c5dfbbf9" +dependencies = [ + "block-padding", + "hybrid-array", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "peak_alloc" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccc90935a8dd139fdf341762773687a1e361d3f54b396a55d9dd1f7001e484bb" + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + +[[package]] +name = "pkcs1" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6250dd7321adbe93d12b750aee0ced159fd13e77f625edcdf1cb6f83cd99f650" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der", + "spki", +] + +[[package]] +name = "polyval" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures", + "universal-hash", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "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]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +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]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +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]] +name = "rsa" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23e77fd77e0dea28b3011fd62d15445b7de7959333b0276d930e03be0f755699" +dependencies = [ + "const-oid", + "crypto-bigint", + "crypto-common", + "crypto-primes", + "digest", + "hmac", + "pkcs1", + "pkcs8", + "rand_core", + "sha2", + "signature", + "spki", + "zeroize", +] + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct", + "serde", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "spki" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ef958a98b9d5da290cfc78946e9f3e61e1e62a18db0d92cac0b83cc161491a9" +dependencies = [ + "base64ct", + "der", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unarray" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common", + "ctutils", +] + +[[package]] +name = "x509-cert" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417" +dependencies = [ + "const-oid", + "der", + "spki", +] + +[[package]] +name = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..c20750d --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,27 @@ +[workspace] +members = ["crates/domistream"] +# fuzz/ is its own workspace (cargo-fuzz layout), never part of this one. +exclude = ["fuzz"] +resolver = "3" + +[workspace.package] +version = "0.1.0" +edition = "2024" +rust-version = "1.89" +license = "CPAL-1.0" +repository = "https://gitea.marek-novak.cz/mnovak/DomiStream" +publish = false + +[workspace.lints.rust] +unsafe_code = "forbid" +missing_docs = "warn" +unreachable_pub = "warn" + +[workspace.lints.clippy] +# No panics on any input: these must never appear in library code. +unwrap_used = "deny" +expect_used = "deny" +panic = "deny" +todo = "deny" +unimplemented = "deny" +indexing_slicing = "warn" diff --git a/README.md b/README.md index e4c6e19..71feb8f 100644 --- a/README.md +++ b/README.md @@ -18,6 +18,21 @@ Rubylight or moonlight-common-c was opened, pasted or ported. See [`docs/CLEAN_R 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 | +| :-- | :-- | +| `crates/domistream` | the crate: one module per protocol part (see its rustdoc) | +| `fuzz/` | one libFuzzer target per parser, its own workspace (how to run: top of `fuzz/Cargo.toml`) | +| `docs/PROTOCOL.md` | the protocol as we speak it, with every UNKNOWN | +| `docs/CLEAN_ROOM.md` | allowed and forbidden sources, and the source log | + ## Licence DomiStream is licensed under the **Common Public Attribution License 1.0** (SPDX `CPAL-1.0`); see [LICENSE](LICENSE). diff --git a/crates/domistream/Cargo.toml b/crates/domistream/Cargo.toml new file mode 100644 index 0000000..df0f529 --- /dev/null +++ b/crates/domistream/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "domistream" +description = "Sans-I/O GameStream client protocol for Arena Domi Play remotely" +version.workspace = true +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[lints] +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. +[dependencies] +aes = "0.9" # AES-128 block cipher (pairing ECB) +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 +sha2 = "0.11" # pairing SHA-256 +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", 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 +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" diff --git a/crates/domistream/src/audio/mod.rs b/crates/domistream/src/audio/mod.rs new file mode 100644 index 0000000..49bcbe5 --- /dev/null +++ b/crates/domistream/src/audio/mod.rs @@ -0,0 +1,496 @@ +//! The audio receive path (`docs/PROTOCOL.md` section 6): parse → rebuild lost packets from the 4 + 2 FEC block → +//! decrypt (AES-128-CBC) → one Opus packet per RTP packet, in order, for the platform's Opus decoder. +//! +//! **Opus decoding is not here.** A packet that cannot be rebuilt becomes [`AudioEvent::Lost`]; the platform +//! 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 std::collections::{HashMap, VecDeque}; + +use cbc::cipher::block_padding::Pkcs7; +use cbc::cipher::{BlockModeDecrypt, KeyIvInit}; + +use crate::fec::ReedSolomon; +use crate::util::malformed; +use crate::{Error, Instant, Result, SessionKeys}; + +pub mod packet; + +pub use packet::{AudioFecHeader, AudioPacket, parse_audio_packet}; + +/// Data packets per FEC block. +pub const DATA_SHARDS: usize = 4; +/// Parity packets per FEC block. +pub const PARITY_SHARDS: usize = 2; +/// Maximum blocks kept while waiting for missing packets. +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. +/// `Debug` never prints the key. +#[derive(Clone)] +pub struct AudioCipher { + key: zeroize::Zeroizing<[u8; 16]>, + rikeyid: u32, +} + +impl AudioCipher { + /// A cipher for the session's keys. + #[must_use] + pub fn new(keys: &SessionKeys) -> Self { + Self { key: zeroize::Zeroizing::new(keys.rikey), rikeyid: keys.rikeyid } + } + + /// The IV for RTP sequence number `sequence` (the sum wraps). + /// + /// # Errors + /// None today. + pub fn iv(&self, sequence: u16) -> Result<[u8; 16]> { + let mut iv = [0u8; 16]; + 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. + /// + /// # Errors + /// [`Error::Malformed`] for a length that is not a positive multiple of 16, [`Error::Crypto`] for bad padding. + pub fn decrypt(&self, sequence: u16, ciphertext: &[u8]) -> Result> { + if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) { + return Err(malformed("audio ciphertext length")); + } + let iv = self.iv(sequence)?; + let mut buf = ciphertext.to_vec(); + let len = cbc::Decryptor::::new((&*self.key).into(), &iv.into()) + .decrypt_padded::(&mut buf) + .map_err(|_| Error::Crypto)? + .len(); + buf.truncate(len); + Ok(buf) + } +} + +impl fmt::Debug for AudioCipher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("AudioCipher()") + } +} + +/// How lost audio packets are rebuilt. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum AudioFec { + /// Parity packets are ignored; losses go to the platform's concealment. + Disabled, + /// Rebuild with this 2 × 4 parity matrix (row-major). The GameStream matrix is UNKNOWN U16 until measured. + ParityMatrix([u8; PARITY_SHARDS * DATA_SHARDS]), +} + +/// Settings of the audio receiver. +#[derive(Clone, Debug)] +pub struct AudioConfig { + /// Decrypt payloads with this cipher (audio encryption negotiated, or always: UNKNOWN U17). + pub cipher: Option, + /// Packet duration in milliseconds (`x-nv-aqos.packetDuration`). + pub packet_duration_ms: u8, + /// FEC mode. + pub fec: AudioFec, + /// How long to wait for a missing packet before reporting it lost (the jitter budget). + pub loss_timeout: core::time::Duration, +} + +/// What the receiver reports, in sequence order. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AudioEvent { + /// One decrypted Opus packet. + Packet { + /// RTP sequence number. + sequence: u16, + /// RTP timestamp (milliseconds). + timestamp_ms: u32, + /// The Opus packet. + opus: Vec, + /// Rebuilt by FEC. + recovered: bool, + }, + /// The packet with this sequence number is gone; the decoder conceals one packet duration. + Lost { + /// RTP sequence number. + sequence: u16, + }, +} + +/// Counters for the stats overlay. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct AudioStats { + /// Packets accepted. + pub packets: u64, + /// Packets refused (bad format, bad padding, duplicate, too old). + pub packets_dropped: u64, + /// Packets rebuilt by FEC. + pub recovered: u64, + /// Packets reported lost. + 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, + opus: Vec, + timestamp_ms: u32, + arrived: Instant, + recovered: bool, +} + +#[derive(Debug, Clone)] +struct Parity { + shard: Vec, + base_timestamp: u32, + arrived: Instant, +} + +#[derive(Debug, Default)] +struct Block { + data: [Option; DATA_SHARDS], + parity: [Option; PARITY_SHARDS], +} + +impl Block { + fn earliest_after(&self, index: usize) -> Option { + 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. +#[derive(Debug)] +pub struct AudioDepacketizer { + config: AudioConfig, + code: Option, + next: Option, + blocks: HashMap, + events: VecDeque, + stats: AudioStats, +} + +const fn block_base(seq: u16) -> u16 { + seq & !3 +} + +impl AudioDepacketizer { + /// A receiver for one stream. + /// + /// # Errors + /// [`Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS. + pub fn new(config: AudioConfig) -> Result { + if config.packet_duration_ms == 0 { + 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 + /// oversized datagram is an error. + /// + /// # Errors + /// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`]. + pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { + crate::util::cap("audio datagram", packet::MAX_AUDIO_PACKET_BYTES, datagram.len())?; + 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 { + 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>> = 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. + pub fn poll_event(&mut self) -> Option { + self.events.pop_front() + } + + /// When a missing packet times out. + #[must_use] + pub fn poll_timeout(&self) -> Option { + 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. + /// + /// # Errors + /// None today. + pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { + self.advance(now); + Ok(()) + } + + /// Counters. + #[must_use] + pub const fn stats(&self) -> AudioStats { + self.stats + } +} diff --git a/crates/domistream/src/audio/packet.rs b/crates/domistream/src/audio/packet.rs new file mode 100644 index 0000000..bfc1c05 --- /dev/null +++ b/crates/domistream/src/audio/packet.rs @@ -0,0 +1,85 @@ +//! The audio packet layout (`docs/PROTOCOL.md` 6.2): RTP header, then the Opus payload (payload type 97) or a +//! 12-byte FEC header plus parity (payload type 127). FEC header fields are big-endian. + +use crate::rtp::RtpHeader; + +/// Payload type of audio data packets. +pub const AUDIO_PAYLOAD_TYPE: u8 = 97; +/// Payload type of audio parity packets. +pub const AUDIO_FEC_PAYLOAD_TYPE: u8 = 127; +/// Length of the FEC header in parity packets. +pub const AUDIO_FEC_HEADER_LEN: usize = 12; +/// Maximum size of one audio packet, in bytes. +pub const MAX_AUDIO_PACKET_BYTES: usize = 2048; + +/// The FEC header of a parity packet. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct AudioFecHeader { + /// Parity shard index, 0 or 1. + pub shard_index: u8, + /// Payload type of the protected packets (97). + pub payload_type: u8, + /// Sequence number of the block's first data packet. + pub base_sequence: u16, + /// Timestamp of the block's first data packet. + pub base_timestamp: u32, + /// SSRC. + pub ssrc: u32, +} + +/// One audio packet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum AudioPacket<'a> { + /// Opus data (still encrypted when audio encryption is on). + Data { + /// RTP header. + rtp: RtpHeader, + /// Payload. + payload: &'a [u8], + }, + /// Parity. + Parity { + /// RTP header. + rtp: RtpHeader, + /// FEC header. + fec: AudioFecHeader, + /// Parity bytes. + parity: &'a [u8], + }, +} + +/// Parses one audio packet. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_AUDIO_PACKET_BYTES`], [`crate::Error::Truncated`] for a cut header or an +/// empty payload, [`crate::Error::UnexpectedValue`] for another RTP version or payload type, or a parity shard +/// index above 1. +pub fn parse_audio_packet(packet: &[u8]) -> crate::Result> { + use crate::util::{byte, need, u16_be, u32_be}; + 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() }), + } +} diff --git a/crates/domistream/src/control/frame.rs b/crates/domistream/src/control/frame.rs new file mode 100644 index 0000000..60bce62 --- /dev/null +++ b/crates/domistream/src/control/frame.rs @@ -0,0 +1,151 @@ +//! The AES-128-GCM frame around every control message (`docs/PROTOCOL.md` 3.2). +//! +//! ```text +//! 0 2 4 8 24 +//! | 0x0001 | len | seq (LE) | GCM tag (16) | ciphertext … | len = 4 + 16 + ciphertext +//! nonce = seq (LE, 4) ‖ 0 × 6 ‖ direction ('C' client→host, 'H' host→client) ‖ 'C' +//! ``` + +use core::fmt; + +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. +pub const ENCRYPTED_FRAME_TYPE: u16 = 0x0001; +/// GCM tag length. +pub const GCM_TAG_LEN: usize = 16; +/// Bytes before the ciphertext (type, length, sequence, tag). +pub const FRAME_HEADER_LEN: usize = 2 + 2 + 4 + GCM_TAG_LEN; +/// Smallest valid frame: header plus a 4-byte message header inside. +pub const MIN_FRAME_BYTES: usize = FRAME_HEADER_LEN + 4; +/// Maximum frame size accepted or produced, in bytes. +pub const MAX_FRAME_BYTES: usize = 4096; +/// GCM nonce length. +pub const NONCE_LEN: usize = 12; + +/// Which way a frame travels; selects byte 10 of the nonce. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Direction { + /// Client to host (`'C'`). + ClientToHost, + /// Host to client (`'H'`). + HostToClient, +} + +/// The nonce for sequence number `sequence` in `direction`. +/// +/// # Errors +/// None today. +pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> { + let mut n = [0u8; NONCE_LEN]; + 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. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct EncryptedFrame<'a> { + /// Sequence number. + pub sequence: u32, + /// GCM tag. + pub tag: [u8; GCM_TAG_LEN], + /// Ciphertext. + pub ciphertext: &'a [u8], +} + +/// Splits a frame (one ENet packet) into its fields. The length field must match the bytes present exactly. +/// +/// # Errors +/// [`Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`Error::Truncated`] under [`MIN_FRAME_BYTES`], +/// [`Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`Error::Malformed`] for a length +/// that does not match. +pub fn parse_encrypted_frame(frame: &[u8]) -> Result> { + const W: &str = "control frame"; + 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::(W, frame, 8)?, + ciphertext: frame.get(FRAME_HEADER_LEN..).unwrap_or(&[]), + }) +} + +/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key. +#[derive(Clone)] +pub struct ControlCipher { + key: zeroize::Zeroizing<[u8; 16]>, +} + +impl ControlCipher { + /// A cipher for `rikey`. + #[must_use] + pub fn new(rikey: [u8; 16]) -> Self { + 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. + /// + /// # Errors + /// [`Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]; [`Error::Crypto`] if sealing fails. + pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result> { + cap("control frame", MAX_FRAME_BYTES, FRAME_HEADER_LEN.saturating_add(plaintext.len()))?; + 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. + /// + /// # Errors + /// Parser errors as [`parse_encrypted_frame`]; [`Error::Crypto`] when the tag does not verify. + pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec)> { + let f = parse_encrypted_frame(frame)?; + 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)) + } +} + +impl fmt::Debug for ControlCipher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("ControlCipher()") + } +} diff --git a/crates/domistream/src/control/message.rs b/crates/domistream/src/control/message.rs new file mode 100644 index 0000000..d29f6d0 --- /dev/null +++ b/crates/domistream/src/control/message.rs @@ -0,0 +1,314 @@ +//! Control messages inside the encrypted frame (`docs/PROTOCOL.md` 3.3): `type u16 LE`, `length u16 LE`, body. + +use crate::Result; +use crate::input::InputEvent; +use crate::util::{byte, cap, malformed, need, u16_le, u32_be}; + +/// Length of the message header (type + length). +pub const MESSAGE_HEADER_LEN: usize = 4; +/// Maximum size of one decrypted message, in bytes. +pub const MAX_MESSAGE_BYTES: usize = super::frame::MAX_FRAME_BYTES - super::frame::FRAME_HEADER_LEN; +/// Length of the HDR metadata block in `HDR_MODE` (15 × u16). +pub const HDR_METADATA_LEN: usize = 30; + +/// Known message type codes. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u16)] +pub enum MessageType { + /// Start, part A (client → host). + StartA = 0x0305, + /// Start, part B (client → host); the host starts video and audio on it. + StartB = 0x0307, + /// Reference frame invalidation request (client → host). + InvalidateRefFrames = 0x0301, + /// IDR frame request (client → host). + IdrFrame = 0x0302, + /// Loss statistics (client → host). + LossStats = 0x0201, + /// Frame statistics (client → host). + FrameStats = 0x0204, + /// Input (client → host). + InputData = 0x0206, + /// Keep-alive (client → host). + PeriodicPing = 0x0200, + /// Termination (host → client). + Termination = 0x0100, + /// Termination with a 32-bit error code (host → client). + TerminationExtended = 0x0109, + /// HDR mode change (host → client). + HdrMode = 0x010e, + /// Rumble (host → client). + RumbleData = 0x010b, + /// Trigger rumble (host → client). + RumbleTriggers = 0x5500, + /// Start or stop motion events (host → client). + MotionEvent = 0x5501, + /// Controller LED colour (host → client). + RgbLed = 0x5502, + /// Adaptive trigger effect (host → client), layout UNKNOWN. + 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 for MessageType { + type Error = crate::Error; + + /// # Errors + /// [`crate::Error::UnexpectedValue`] for an unknown code. + fn try_from(code: u16) -> Result { + Self::ALL + .into_iter() + .find(|t| *t as u16 == code) + .ok_or(crate::Error::UnexpectedValue { what: "control message type", value: code.into() }) + } +} + +/// A message split into type and body, not interpreted. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct RawMessage<'a> { + /// Type code (possibly unknown). + pub message_type: u16, + /// Body, exactly `length` bytes. + pub body: &'a [u8], +} + +/// Splits a decrypted message. The length field must equal the bytes after the header. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`crate::Error::Truncated`] under +/// [`MESSAGE_HEADER_LEN`], [`crate::Error::Malformed`] for a length that does not match. +pub fn parse_message(message: &[u8]) -> Result> { + const W: &str = "control message"; + 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`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum MotionKind { + /// Accelerometer (1). + Accelerometer, + /// Gyroscope (2). + Gyroscope, +} + +/// HDR mastering metadata as sent in `HDR_MODE` (15 little-endian u16 fields, layout `[M*]`, unconfirmed). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct HdrMetadata { + /// Display primaries x/y for R, G, B. + pub display_primaries: [(u16, u16); 3], + /// White point x/y. + pub white_point: (u16, u16), + /// Maximum display luminance, nits. + pub max_display_luminance: u16, + /// Minimum display luminance, 1/10000 nit. + pub min_display_luminance: u16, + /// Maximum content light level, nits. + pub max_content_light_level: u16, + /// Maximum frame-average light level, nits. + pub max_frame_average_light_level: u16, + /// Maximum full-frame luminance, nits. + pub max_full_frame_luminance: u16, +} + +/// A message from the host. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum HostMessage { + /// Rumble a controller. + Rumble { + /// Controller number. + controller: u16, + /// Low-frequency motor. + low_frequency: u16, + /// High-frequency motor. + high_frequency: u16, + }, + /// Rumble the triggers. + RumbleTriggers { + /// Controller number. + controller: u16, + /// Left trigger. + left: u16, + /// Right trigger. + right: u16, + }, + /// Start (rate > 0) or stop (rate 0) sending motion events. + MotionEvent { + /// Controller number. + controller: u16, + /// Report rate, Hz. + rate_hz: u16, + /// Sensor. + kind: MotionKind, + }, + /// Set a controller's LED colour. + RgbLed { + /// Controller number. + controller: u16, + /// Red. + r: u8, + /// Green. + g: u8, + /// Blue. + b: u8, + }, + /// HDR turned on or off. + HdrMode { + /// HDR on. + enabled: bool, + /// Mastering metadata, if the body carries it. + metadata: Option, + }, + /// The host ended the session. + Termination { + /// Error code (extended form), `None` for the plain form. `0x80030023` = graceful. + error_code: Option, + }, + /// A known or unknown type this client does not interpret; kept for stats and logs. + Other { + /// Type code. + message_type: u16, + /// Body length (the body itself is not kept). + body_len: usize, + }, +} + +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 +/// As [`parse_message`]; [`crate::Error::Malformed`] when a known type's body has the wrong length; +/// [`crate::Error::UnexpectedValue`] for an unknown motion kind. +pub fn parse_host_message(message: &[u8]) -> Result { + const W: &str = "host message"; + 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. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ClientMessage { + /// `START_A` (body UNKNOWN U10). + StartA, + /// `START_B` (body UNKNOWN U10): the host starts video and audio. + StartB, + /// Keep-alive (body UNKNOWN U10). + PeriodicPing, + /// Ask for an IDR frame (body UNKNOWN U10). + RequestIdrFrame, + /// Ask the host to stop referencing frames `first..=last`. + InvalidateRefFrames { + /// First lost frame index. + first: u32, + /// Last lost frame index. + last: u32, + }, + /// User input. + Input(InputEvent), +} + +/// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`]. +/// +/// # Errors +/// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN (U10: START_A, START_B, +/// PERIODIC_PING, IDR request; refused rather than guessed); input errors as [`crate::input::encode_input`]. +pub fn encode_client_message(message: &ClientMessage) -> Result> { + match message { + 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)" }) + } + } +} diff --git a/crates/domistream/src/control/mod.rs b/crates/domistream/src/control/mod.rs new file mode 100644 index 0000000..c0ec5cc --- /dev/null +++ b/crates/domistream/src/control/mod.rs @@ -0,0 +1,167 @@ +//! The control stream (`docs/PROTOCOL.md` section 3): ENet underneath, AES-GCM frames, control messages. +//! +//! [`ControlStream`] ties them together: it connects the ENet peer, seals every [`ClientMessage`] with an +//! increasing sequence number, opens every host frame (dropping replays and frames that fail the tag), and reports +//! [`HostMessage`]s. + +use core::time::Duration; +use std::collections::VecDeque; + +use crate::enet::{Delivery, EnetClient, EnetConfig, EnetEvent}; +use crate::{Instant, RandomSource, Result}; + +pub mod frame; +pub mod message; + +pub use frame::{ControlCipher, Direction, EncryptedFrame, parse_encrypted_frame}; +pub use message::{ClientMessage, HostMessage, MessageType, parse_host_message, parse_message}; + +/// Settings of one control stream. `Debug` never prints the key. +#[derive(Clone, PartialEq, Eq)] +pub struct ControlConfig { + /// The ENet connection to offer. + pub enet: EnetConfig, + /// The session's `rikey`. + pub rikey: [u8; 16], + /// Send `PERIODIC_PING` this often (UNKNOWN U10). + pub ping_interval: Duration, +} + +impl core::fmt::Debug for ControlConfig { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("ControlConfig") + .field("enet", &self.enet) + .field("rikey", &"") + .field("ping_interval", &self.ping_interval) + .finish() + } +} + +/// What happened on the control stream. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ControlEvent { + /// ENet connected; the client sends `START_A`/`START_B` next. + Connected, + /// A message from the host. + Message(HostMessage), + /// A host frame failed its tag or came out of order and was dropped (counted, never fatal). + Dropped, + /// The host closed the stream. + Disconnected, + /// The host stopped answering. + TimedOut, +} + +/// One control stream. +#[derive(Debug)] +pub struct ControlStream { + 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, + events: VecDeque, +} + +impl ControlStream { + /// Starts connecting. + /// + /// # Errors + /// As [`crate::enet::EnetClient::connect`]. + pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result { + Ok(Self { + 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. + /// + /// # Errors + /// As [`crate::enet::EnetClient::handle_datagram`]. Bad frames inside a good datagram are not errors; they + /// become [`ControlEvent::Dropped`]. + pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { + let r = self.enet.handle_datagram(now, datagram); + self.drain(); + r + } + + /// Seals and queues a message (reliable, channel 0 unless measurement says otherwise). + /// + /// # Errors + /// As [`message::encode_client_message`] and [`crate::enet::EnetClient::send`]; [`crate::Error::Closed`] once + /// the sequence space is used up (2^32 messages). + pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> { + let plain = message::encode_client_message(message)?; + 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. + pub fn poll_transmit(&mut self, now: Instant) -> Option> { + self.enet.poll_transmit(now) + } + + /// The next event. + pub fn poll_event(&mut self) -> Option { + self.events.pop_front() + } + + /// When [`Self::handle_timeout`] is due. + #[must_use] + pub fn poll_timeout(&self) -> Option { + self.enet.poll_timeout() + } + + /// Advances timers (ENet). `PERIODIC_PING` is not sent while its body is UNKNOWN (U10); ENet's own pings keep + /// the connection alive. + /// + /// # Errors + /// As [`crate::enet::EnetClient::handle_timeout`]. + pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { + let r = self.enet.handle_timeout(now); + self.drain(); + r + } + + /// Closes the stream gracefully. + /// + /// # Errors + /// [`crate::Error::Closed`] when already closed. + pub fn close(&mut self, now: Instant) -> Result<()> { + self.enet.disconnect(now, 0) + } +} diff --git a/crates/domistream/src/enet/mod.rs b/crates/domistream/src/enet/mod.rs new file mode 100644 index 0000000..8448d93 --- /dev/null +++ b/crates/domistream/src/enet/mod.rs @@ -0,0 +1,751 @@ +//! A sans-I/O ENet 1.3 client peer, compatible with GameStream hosts (`docs/PROTOCOL.md` 3.1, +//! `docs/research/open-point-2.md`). +//! +//! One peer, one connection. The caller owns the UDP socket: +//! +//! ```text +//! loop { +//! while let Some(d) = peer.poll_transmit(now) { socket.send(&d) } +//! wait until a datagram arrives or peer.poll_timeout() +//! peer.handle_datagram(now, &d) or peer.handle_timeout(now) +//! 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 std::collections::{BTreeMap, VecDeque}; + +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; + +/// Maximum size of one reassembled packet, in bytes (control messages are small; this caps fragment memory). +pub const MAX_PACKET_BYTES: usize = 64 * 1024; +/// Maximum number of packets queued for sending before [`EnetClient::send`] refuses more. +pub const MAX_SEND_QUEUE: usize = 1024; +/// Maximum number of reliable commands waiting for an acknowledgement. +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. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Delivery { + /// Retransmitted until acknowledged, in order. + Reliable, + /// In order, may be lost, late packets dropped. + Unreliable, + /// May be lost, any order. + Unsequenced, +} + +/// Settings of the connection the client offers. All values are UNKNOWN U9 for Sunshine; tests set them +/// explicitly. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct EnetConfig { + /// Channels to open. + pub channel_count: u8, + /// MTU to offer (576..=4096). + pub mtu: u16, + /// The connect command's user data word. + pub connect_data: u32, + /// Send a ping when nothing was sent for this long. + pub ping_interval: Duration, + /// Give up when nothing was acknowledged for this long. + pub timeout: Duration, +} + +/// Connection state. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum EnetState { + /// Connect sent, waiting for verify connect. + Connecting, + /// Connected. + Connected, + /// Disconnect sent, waiting for its acknowledgement. + Disconnecting, + /// Closed (by either side or by timeout). + Disconnected, +} + +/// What happened. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum EnetEvent { + /// The host verified the connection. + Connected, + /// A packet arrived (reassembled, in order for reliable and unreliable delivery). + Received { + /// Channel. + channel: u8, + /// The packet. + data: Vec, + }, + /// The host closed the connection. + Disconnected { + /// The host's disconnect data word. + data: u32, + }, + /// The host stopped answering. + TimedOut, +} + +/// A reliable command in the sequence stream of a channel, as it will be processed in order. +#[derive(Debug)] +enum Pending { + Data(Vec), + 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, + pending: BTreeMap, +} + +#[derive(Debug)] +struct Reassembly { + channel: u8, + start: u16, + count: u32, + total: u32, + got: Vec, + received: u32, + data: Vec, +} + +#[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. +#[derive(Debug)] +pub struct EnetClient { + config: EnetConfig, + 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, + outgoing: VecDeque, + queued_packets: usize, + resend: VecDeque, + acks: VecDeque, + in_flight: Vec, + reassemblies: Vec, + events: VecDeque, + last_send: Instant, + srtt: Option, + rttvar: Duration, +} + +fn ms16(t: Instant) -> u16 { + ((t.as_micros() / 1000) & 0xFFFF) as u16 +} + +impl EnetClient { + /// Starts connecting: queues the connect datagram. The connect id comes from `rng`. + /// + /// # Errors + /// [`Error::Malformed`] for a config outside ENet's limits (MTU 576..=4096, at least one channel). + pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result { + if config.mtu < MIN_MTU || usize::from(config.mtu) > MAX_DATAGRAM_BYTES || config.channel_count == 0 { + 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. + /// + /// # Errors + /// Parser errors as [`protocol::parse_datagram`]; [`Error::TooLarge`] when a fragment announces more than + /// [`MAX_PACKET_BYTES`]; [`Error::Closed`] after `Disconnected`. A malformed datagram never changes the + /// connection state. + pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { + if self.state == EnetState::Disconnected { + 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) + } + + 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 + /// [`Error::State`] unless connected, [`Error::UnexpectedValue`] for a channel outside the negotiated count, + /// [`Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue ([`MAX_SEND_QUEUE`] packets). + pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> { + let _ = now; + 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. + /// + /// # Errors + /// [`Error::Closed`] when already disconnected or disconnecting. + pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> { + let _ = now; + 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 the MTU (acknowledgements, retransmissions, queued packets, pings). + pub fn poll_transmit(&mut self, now: Instant) -> Option> { + let budget = self.mtu; + let mut size = 4; + let mut commands: Vec = 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. + pub fn poll_event(&mut self) -> Option { + self.events.pop_front() + } + + /// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever. + #[must_use] + pub fn poll_timeout(&self) -> Option { + 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`]. + /// + /// # Errors + /// None today. + pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { + if self.state == EnetState::Disconnected { + 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. + #[must_use] + pub const fn state(&self) -> EnetState { + self.state + } + + /// Smoothed round-trip time, once measured. + #[must_use] + pub fn round_trip_time(&self) -> Option { + 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")) } +} diff --git a/crates/domistream/src/enet/protocol.rs b/crates/domistream/src/enet/protocol.rs new file mode 100644 index 0000000..a0247d0 --- /dev/null +++ b/crates/domistream/src/enet/protocol.rs @@ -0,0 +1,452 @@ +//! The ENet 1.3 datagram codec (`docs/PROTOCOL.md` 3.1). Multi-byte fields are big-endian. + +/// Maximum datagram size accepted or produced (ENet's maximum MTU). +pub const MAX_DATAGRAM_BYTES: usize = 4096; +/// Minimum MTU ENet allows. +pub const MIN_MTU: u16 = 576; +/// Maximum number of commands in one datagram. +pub const MAX_COMMANDS_PER_DATAGRAM: usize = 32; +/// Maximum channel count ENet allows. +pub const MAX_CHANNEL_COUNT: u8 = 255; +/// Maximum peer id ENet allows. +pub const MAX_PEER_ID: u16 = 0x0FFF; +/// Peer id meaning "no peer yet" (used in the connect datagram). +pub const NO_PEER_ID: u16 = MAX_PEER_ID; +/// Minimum ENet window size. +pub const MIN_WINDOW_SIZE: u32 = 4096; +/// Maximum ENet window size. +pub const MAX_WINDOW_SIZE: u32 = 65536; + +/// Header flag: the datagram carries `sent_time`. +pub const HEADER_FLAG_SENT_TIME: u16 = 1 << 15; +/// Header flag: the datagram is compressed (refused by this client). +pub const HEADER_FLAG_COMPRESSED: u16 = 1 << 14; +/// Command flag: the receiver must acknowledge. +pub const COMMAND_FLAG_ACKNOWLEDGE: u8 = 1 << 7; +/// Command flag: unsequenced delivery. +pub const COMMAND_FLAG_UNSEQUENCED: u8 = 1 << 6; + +/// ENet command numbers (low 4 bits of the command byte). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum CommandKind { + /// Acknowledge a reliable command. + Acknowledge = 1, + /// Open a connection. + Connect = 2, + /// Answer to connect. + VerifyConnect = 3, + /// Close. + Disconnect = 4, + /// Keep-alive. + Ping = 5, + /// Reliable data. + SendReliable = 6, + /// Unreliable sequenced data. + SendUnreliable = 7, + /// Reliable fragment. + SendFragment = 8, + /// Unsequenced data. + SendUnsequenced = 9, + /// Bandwidth limits. + BandwidthLimit = 10, + /// Throttle parameters. + ThrottleConfigure = 11, + /// Unreliable fragment. + SendUnreliableFragment = 12, +} + +/// Parameters of connect and verify connect. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct ConnectParams { + /// Sender's peer id for the receiver to use. + pub outgoing_peer_id: u16, + /// Session id for incoming traffic. + pub incoming_session_id: u8, + /// Session id for outgoing traffic. + pub outgoing_session_id: u8, + /// MTU. + pub mtu: u32, + /// Reliable window size. + pub window_size: u32, + /// Channel count. + pub channel_count: u32, + /// Incoming bandwidth, bytes/s, 0 = unlimited. + pub incoming_bandwidth: u32, + /// Outgoing bandwidth, bytes/s, 0 = unlimited. + pub outgoing_bandwidth: u32, + /// Throttle interval, ms. + pub packet_throttle_interval: u32, + /// Throttle acceleration. + pub packet_throttle_acceleration: u32, + /// Throttle deceleration. + pub packet_throttle_deceleration: u32, + /// Random id that ties verify connect to connect. + pub connect_id: u32, +} + +/// Fragment fields shared by reliable and unreliable fragments. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Fragment { + /// Sequence number of the first fragment. + pub start_sequence: u16, + /// Number of fragments. + pub fragment_count: u32, + /// This fragment's number. + pub fragment_number: u32, + /// Length of the whole packet. + pub total_length: u32, + /// This fragment's offset in the whole packet. + pub fragment_offset: u32, + /// This fragment's bytes. + pub data: Vec, +} + +/// One command with its 4-byte header fields. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Command { + /// The receiver must acknowledge (flag bit 7). + pub acknowledge: bool, + /// Channel id (0xFF for connection-level commands). + pub channel_id: u8, + /// Reliable sequence number. + pub reliable_sequence: u16, + /// The command body. + pub body: CommandBody, +} + +/// Command bodies. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum CommandBody { + /// Acknowledges `received_reliable_sequence` sent at `received_sent_time`. + Acknowledge { + /// Acknowledged sequence number. + received_reliable_sequence: u16, + /// The acknowledged datagram's `sent_time`. + received_sent_time: u16, + }, + /// Connect, with its user data word. + Connect { + /// Connection parameters. + params: ConnectParams, + /// User data (UNKNOWN U9: what a GameStream host expects here). + data: u32, + }, + /// Verify connect. + VerifyConnect(ConnectParams), + /// Disconnect with a user data word. + Disconnect { + /// User data. + data: u32, + }, + /// Ping. + Ping, + /// Reliable data. + SendReliable(Vec), + /// Unreliable sequenced data. + SendUnreliable { + /// Unreliable sequence number. + unreliable_sequence: u16, + /// The data. + data: Vec, + }, + /// Reliable fragment. + SendFragment(Fragment), + /// Unsequenced data. + SendUnsequenced { + /// Unsequenced group. + unsequenced_group: u16, + /// The data. + data: Vec, + }, + /// Bandwidth limits, bytes/s. + BandwidthLimit { + /// Incoming. + incoming: u32, + /// Outgoing. + outgoing: u32, + }, + /// Throttle parameters. + ThrottleConfigure { + /// Interval, ms. + interval: u32, + /// Acceleration. + acceleration: u32, + /// Deceleration. + deceleration: u32, + }, + /// Unreliable fragment. + SendUnreliableFragment(Fragment), +} + +/// One datagram: protocol header plus commands. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Datagram { + /// Receiver's peer id (12 bits). + pub peer_id: u16, + /// Session id (2 bits). + pub session_id: u8, + /// `sent_time` (low 16 bits of the sender's ms clock), if present. + pub sent_time: Option, + /// The commands, at most [`MAX_COMMANDS_PER_DATAGRAM`]. + pub commands: Vec, +} + +/// Parses one datagram strictly: every length checked against the bytes present, unknown command numbers and +/// compressed datagrams refused. The unsequenced flag and the two unused command bits are not kept. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`], +/// [`crate::Error::Truncated`] for a cut header, command or data, [`crate::Error::UnexpectedValue`] for an unknown +/// command or the compressed flag. +pub fn parse_datagram(datagram: &[u8]) -> crate::Result { + use crate::util::{byte, cap, slice, u16_be, u32_be}; + 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, 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 { + 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, 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::try_from(data.len()).map_err(|_| crate::Error::TooLarge { + what: "enet command data", + max: usize::from(u16::MAX), + actual: data.len(), + }) +} + +/// Serializes one datagram. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`], +/// [`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> { + use crate::util::cap; + 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) +} diff --git a/crates/domistream/src/entropy.rs b/crates/domistream/src/entropy.rs new file mode 100644 index 0000000..4957e8c --- /dev/null +++ b/crates/domistream/src/entropy.rs @@ -0,0 +1,11 @@ +//! Randomness comes in from the caller, so every test is deterministic. + +/// A source of random bytes supplied by the caller. +/// +/// In production this must be a cryptographically secure generator (the OS generator). Tests pass a fixed, +/// seeded source. DomiStream never reads randomness any other way: salts, challenges, secrets, the client key, +/// `rikey`, ENet connect ids and PINs all come from here. +pub trait RandomSource { + /// Fills `dest` completely with random bytes. + fn fill(&mut self, dest: &mut [u8]); +} diff --git a/crates/domistream/src/error.rs b/crates/domistream/src/error.rs new file mode 100644 index 0000000..8bc8153 --- /dev/null +++ b/crates/domistream/src/error.rs @@ -0,0 +1,94 @@ +//! The one error type of the crate. + +use core::fmt; + +/// Result with the crate's [`Error`]. +pub type Result = core::result::Result; + +/// Everything that can go wrong. Errors never carry key material or decrypted bytes. +#[derive(Debug, Clone, PartialEq, Eq)] +#[non_exhaustive] +pub enum Error { + /// A part of the API that has no implementation (none today; kept so callers and tests can name it). + Unimplemented, + /// Input is larger than the parser's `MAX_*` constant. Checked before anything is allocated. + TooLarge { + /// What was being parsed, e.g. `"rtsp message"`. + what: &'static str, + /// The cap. + max: usize, + /// The size that was offered. + actual: usize, + }, + /// Input ends before a field it announces. + Truncated { + /// What was being parsed. + what: &'static str, + /// Bytes the field needs. + needed: usize, + /// Bytes that were there. + actual: usize, + }, + /// Input does not follow the format (bad syntax, bad length field, wrong constant, bad encoding). + Malformed { + /// What was being parsed and what was wrong, a fixed string. + what: &'static str, + }, + /// A field holds a value this client does not accept (unknown type code, out-of-range number). + UnexpectedValue { + /// The field. + what: &'static str, + /// The value seen. + value: u64, + }, + /// The host answered with a non-200 `status_code` (HTTP XML) or RTSP status. + HostStatus { + /// The status code. + code: u32, + }, + /// Decryption, tag or signature check failed. Deliberately without detail. + Crypto, + /// Pairing refused: wrong PIN, failed host proof (possible man in the middle), or `paired=0`. + PairingRefused, + /// The host does not offer something this client requires (for example control encryption). + Unsupported { + /// What is missing. + what: &'static str, + }, + /// The call is not valid in the current state of the state machine. + State { + /// The state the call needs, a fixed string. + expected: &'static str, + }, + /// The peer stopped answering within its timeout. + TimedOut, + /// The session is closed; no more calls are accepted. + Closed, +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::Unimplemented => f.write_str("not implemented yet"), + Self::TooLarge { what, max, actual } => { + write!(f, "{what}: {actual} bytes is over the {max}-byte limit") + } + Self::Truncated { what, needed, actual } => { + write!(f, "{what}: needs {needed} bytes, got {actual}") + } + Self::Malformed { what } => write!(f, "malformed {what}"), + Self::UnexpectedValue { what, value } => { + write!(f, "{what}: unexpected value {value:#x}") + } + Self::HostStatus { code } => write!(f, "host answered with status {code}"), + Self::Crypto => f.write_str("cryptographic check failed"), + Self::PairingRefused => f.write_str("pairing refused"), + Self::Unsupported { what } => write!(f, "host does not support {what}"), + Self::State { expected } => write!(f, "not allowed now: needs state {expected}"), + Self::TimedOut => f.write_str("timed out"), + Self::Closed => f.write_str("session closed"), + } + } +} + +impl std::error::Error for Error {} diff --git a/crates/domistream/src/fec.rs b/crates/domistream/src/fec.rs new file mode 100644 index 0000000..0e59b74 --- /dev/null +++ b/crates/domistream/src/fec.rs @@ -0,0 +1,381 @@ +//! Reed-Solomon erasure coding over GF(2^8), polynomial `0x11D` (`docs/PROTOCOL.md` 5.3, 6.4). +//! +//! Systematic code: `data` shards pass through unchanged, `parity` shards are linear combinations of them, and any +//! `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. +//! +//! Two matrices are needed: video ([`ReedSolomon::new`]: the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`, from +//! 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). +pub const MAX_SHARDS: usize = 255; +/// Maximum length of one shard, in bytes. +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, n: usize) -> Option> { + 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 = (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 = 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)`. +/// +/// # Errors +/// [`Error::UnexpectedValue`] when `data_shards` is 0 or data + parity would exceed [`MAX_SHARDS`]. +pub fn parity_count(data_shards: usize, fec_percentage: u8) -> Result { + let k = u64::try_from(data_shards).unwrap_or(u64::MAX); + let m = k.saturating_mul(u64::from(fec_percentage)).div_ceil(100); + 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. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ReedSolomon { + data_shards: usize, + parity_shards: usize, + /// `parity_shards × data_shards` coefficients, row-major. + parity_matrix: Vec, +} + +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 { + /// 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 + /// [`Error::UnexpectedValue`] when either count is 0 or the sum exceeds [`MAX_SHARDS`]. + pub fn new(data_shards: usize, parity_shards: usize) -> Result { + check_counts(data_shards, parity_shards)?; + let mut parity_matrix = Vec::with_capacity(data_shards * parity_shards); + 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 + /// 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 + /// 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]) -> Result { + check_counts(data_shards, parity_shards)?; + 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. + #[must_use] + pub const fn data_shards(&self) -> usize { + self.data_shards + } + + /// Number of parity shards. + #[must_use] + pub const fn parity_shards(&self) -> usize { + self.parity_shards + } + + /// The parity matrix, row-major. + #[must_use] + pub fn parity_matrix(&self) -> &[u8] { + &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 { + 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; + /// the parity ones are overwritten. + /// + /// # Errors + /// [`Error::Malformed`] for the wrong shard count or unequal lengths, [`Error::TooLarge`] over + /// [`MAX_SHARD_BYTES`]. + pub fn encode(&self, shards: &mut [Vec]) -> Result<()> { + if shards.len() != self.data_shards + self.parity_shards { + 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 + /// every entry is `Some`, and present entries are never changed. + /// + /// # Errors + /// [`Error::Malformed`] for the wrong count, unequal lengths, or a singular system (a matrix that was not + /// MDS), [`Error::TooLarge`] over [`MAX_SHARD_BYTES`], [`Error::Truncated`] when fewer than `data` shards are + /// present. + pub fn reconstruct(&self, shards: &mut [Option>]) -> Result<()> { + let k = self.data_shards; + 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 = (0..k).filter(|&i| shards.get(i).is_some_and(Option::is_none)).collect(); + if !missing.is_empty() { + let rows: Vec = (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 = 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::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 = + (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)> = + 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(()) + } +} diff --git a/crates/domistream/src/http/applist.rs b/crates/domistream/src/http/applist.rs new file mode 100644 index 0000000..0b6efc7 --- /dev/null +++ b/crates/domistream/src/http/applist.rs @@ -0,0 +1,48 @@ +//! `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. +pub const MAX_APPLIST_BYTES: usize = 1024 * 1024; +/// Maximum number of apps accepted in one list. +pub const MAX_APPS: usize = 4096; +/// Maximum length of an app title, in bytes. +pub const MAX_APP_TITLE_BYTES: usize = 512; + +/// One app the host can launch. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct App { + /// `ID`: the value for `appid` in launch. + pub id: u32, + /// `AppTitle`, unescaped. + pub title: String, + /// `IsHdrSupported == 1`. + pub hdr_supported: bool, +} + +/// Parses an applist body. Apps keep the host's order; duplicate ids are refused; other elements are ignored. +/// +/// # Errors +/// [`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 +/// `AppTitle`, a bad `ID`, or a duplicate `ID`. +pub fn parse_app_list(body: &[u8]) -> Result> { + let doc = super::document(body, MAX_APPLIST_BYTES, "applist")?; + let count = doc.root.children.iter().filter(|c| c.name == "App").count(); + cap("applist apps", MAX_APPS, count)?; + let mut apps: Vec = 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) +} diff --git a/crates/domistream/src/http/launch.rs b/crates/domistream/src/http/launch.rs new file mode 100644 index 0000000..0dc59ee --- /dev/null +++ b/crates/domistream/src/http/launch.rs @@ -0,0 +1,140 @@ +//! `GET /launch` and `GET /resume` (`docs/PROTOCOL.md` 1.4). + +use super::{HttpRequest, Scheme, build, check_unique_id}; +use crate::util::{cap, check_rtsp_url, hex_encode, malformed}; +use crate::{Result, SessionKeys}; + +/// Maximum size of a launch or resume answer, in bytes. +pub const MAX_LAUNCH_RESPONSE_BYTES: usize = 16 * 1024; +/// Maximum length of `sessionUrl0`, in bytes. +pub const MAX_SESSION_URL_BYTES: usize = 256; + +/// Audio channel layouts the client can ask for. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum AudioLayout { + /// 2.0. + Stereo, + /// 5.1. + Surround51, + /// 7.1. + 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. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LaunchParams { + /// App `ID` from [`super::parse_app_list`]. + pub app_id: u32, + /// Stream width in pixels. + pub width: u32, + /// Stream height in pixels. + pub height: u32, + /// Frames per second. + pub fps: u32, + /// Fresh keys for this session (never reuse; see [`SessionKeys`]). + pub keys: SessionKeys, + /// Ask for HDR (`hdrMode=1`). + pub hdr: bool, + /// Audio layout (`surroundAudioInfo`). + pub audio: AudioLayout, +} + +/// What the host answers to launch or resume. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LaunchResponse { + /// `gamesession == 1`. + pub game_session: bool, + /// `sessionUrl0`, e.g. `rtsp://192.0.2.10:48010`; `None` when missing (UNKNOWN U4). + pub session_url: Option, +} + +/// Builds `GET /launch` (HTTPS). +/// +/// # Errors +/// [`crate::Error::Malformed`] for a zero size or frame rate, or a bad `unique_id`. +pub fn launch_request(params: &LaunchParams, unique_id: &str) -> Result { + check_unique_id(unique_id)?; + if params.width == 0 || params.height == 0 || params.fps == 0 { + 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. +/// +/// # Errors +/// As [`launch_request`]. +pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> Result { + check_unique_id(unique_id)?; + 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. +/// +/// # Errors +/// [`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 +/// `rtsp://host:port` URL. +pub fn parse_launch_response(body: &[u8]) -> Result { + let doc = super::document(body, MAX_LAUNCH_RESPONSE_BYTES, "launch answer")?; + 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 }) +} diff --git a/crates/domistream/src/http/mod.rs b/crates/domistream/src/http/mod.rs new file mode 100644 index 0000000..f31415b --- /dev/null +++ b/crates/domistream/src/http/mod.rs @@ -0,0 +1,128 @@ +//! The HTTP/HTTPS side of GameStream (`docs/PROTOCOL.md` section 1): request building and strict parsers of the +//! host's XML answers. Pairing has its own module, [`crate::pairing`]. +//! +//! DomiStream builds the path and query of each `GET`; the caller sends it over plain HTTP or over TLS (with the +//! client certificate and the pinned host certificate, see [`crate::pairing::ServerCert`]) and hands the response +//! body back to the matching `parse_*` function. + +use core::time::Duration; + +use crate::Result; +use crate::util::{malformed, percent_encode}; + +pub mod applist; +pub mod launch; +pub mod serverinfo; +pub mod xml; + +pub use applist::{App, parse_app_list}; +pub use launch::{LaunchParams, LaunchResponse, parse_launch_response}; +pub use serverinfo::{ServerInfo, parse_server_info}; + +/// Default HTTP port of a GameStream host. +pub const DEFAULT_HTTP_PORT: u16 = 47989; +/// Default HTTPS port of a GameStream host. +pub const DEFAULT_HTTPS_PORT: u16 = 47984; + +/// Maximum length of the client's `uniqueid`, in bytes. +pub const MAX_UNIQUE_ID_BYTES: usize = 64; +/// Maximum length of the device name sent while pairing, in bytes. +pub const MAX_DEVICE_NAME_BYTES: usize = 64; + +/// Plain HTTP or HTTPS. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Scheme { + /// Plain HTTP (port [`DEFAULT_HTTP_PORT`] unless the host says otherwise). + Http, + /// HTTPS with the client certificate (port from `serverinfo`'s `HttpsPort`). + Https, +} + +/// One `GET` request for the caller to send. Always a `GET`; the body is always empty. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct HttpRequest { + /// Which port and transport to use. + pub scheme: Scheme, + /// Path and percent-encoded query, e.g. `/serverinfo?uniqueid=0123456789ABCDEF`. + pub path_and_query: String, + /// How long the caller should wait for the answer. `None` = the caller's normal timeout. Pairing step 1 blocks + /// on the host until the PIN is entered, so it asks for a long one. + pub timeout: Option, +} + +/// 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) -> 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 { + 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. +/// +/// # Errors +/// [`crate::Error::Malformed`] for an empty, oversized or non-alphanumeric `unique_id`. +pub fn server_info_request(scheme: Scheme, unique_id: &str) -> Result { + check_unique_id(unique_id)?; + Ok(build(scheme, "/serverinfo", &[("uniqueid", unique_id)], None)) +} + +/// Builds `GET /applist` (HTTPS). +/// +/// # Errors +/// As [`server_info_request`]. +pub fn app_list_request(unique_id: &str) -> Result { + check_unique_id(unique_id)?; + Ok(build(Scheme::Https, "/applist", &[("uniqueid", unique_id)], None)) +} + +/// Builds `GET /cancel` (HTTPS): quits the app running on the host. +/// +/// # Errors +/// As [`server_info_request`]. +pub fn cancel_request(unique_id: &str) -> Result { + check_unique_id(unique_id)?; + Ok(build(Scheme::Https, "/cancel", &[("uniqueid", unique_id)], None)) +} + +/// Builds `GET /unpair` (HTTPS): the host forgets this client. +/// +/// # Errors +/// As [`server_info_request`]. +pub fn unpair_request(unique_id: &str) -> Result { + check_unique_id(unique_id)?; + Ok(build(Scheme::Https, "/unpair", &[("uniqueid", unique_id)], None)) +} + +/// Checks a plain `` answer (cancel, unpair). +/// +/// # Errors +/// [`crate::Error::HostStatus`] for a non-200 status, parser errors as [`xml::parse`]. +pub fn parse_status_response(body: &[u8]) -> Result<()> { + document(body, xml::MAX_XML_BYTES, "status answer").map(|_| ()) +} diff --git a/crates/domistream/src/http/serverinfo.rs b/crates/domistream/src/http/serverinfo.rs new file mode 100644 index 0000000..ce1fef0 --- /dev/null +++ b/crates/domistream/src/http/serverinfo.rs @@ -0,0 +1,129 @@ +//! `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. +pub const MAX_SERVERINFO_BYTES: usize = 64 * 1024; +/// Maximum length of any string field in serverinfo, in bytes. +pub const MAX_SERVERINFO_FIELD_BYTES: usize = 256; + +/// What the host says about itself. Optional fields are `None` when the element is missing or empty. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ServerInfo { + /// `hostname`. + pub hostname: String, + /// `appversion`, e.g. `7.1.431.-1`. + pub app_version: String, + /// `GfeVersion`. + pub gfe_version: Option, + /// `uniqueid`: the host's stable id. + pub unique_id: String, + /// `HttpsPort`. + pub https_port: u16, + /// `ExternalPort` (the HTTP port). + pub http_port: Option, + /// `mac`, for Wake-on-LAN, as `aa:bb:cc:dd:ee:ff`. + pub mac: Option<[u8; 6]>, + /// `LocalIP`, as the host wrote it. + pub local_ip: Option, + /// `MaxLumaPixelsHEVC`; 0 = no HEVC. + pub max_luma_pixels_hevc: Option, + /// `ServerCodecModeSupport` bitmask (bit meanings UNKNOWN U25). + pub codec_mode_support: Option, + /// `PairStatus == 1`. Only meaningful over HTTPS. + pub paired: bool, + /// `currentgame`: id of the running app, 0 = none. + pub current_game: u32, + /// `state`, raw (host-specific `…_SERVER_BUSY` / `…_SERVER_FREE`). + pub state: String, +} + +impl ServerInfo { + /// Whether the host reports a running app (`state` ends in `_BUSY` or `currentgame != 0`). + /// + /// # Errors + /// None today; the `Result` leaves room for stricter state checks. + pub fn is_busy(&self) -> Result { + 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> { + 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> { + 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. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_SERVERINFO_BYTES`] or [`MAX_SERVERINFO_FIELD_BYTES`], +/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a missing required element +/// (`hostname`, `uniqueid`, `HttpsPort`) or a bad number. +pub fn parse_server_info(body: &[u8]) -> Result { + let doc = super::document(body, MAX_SERVERINFO_BYTES, "serverinfo")?; + 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(), + }) +} diff --git a/crates/domistream/src/http/xml.rs b/crates/domistream/src/http/xml.rs new file mode 100644 index 0000000..cf7e138 --- /dev/null +++ b/crates/domistream/src/http/xml.rs @@ -0,0 +1,331 @@ +//! A small, strict XML reader for the host's answers: one `` element with nested +//! 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 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. +pub const MAX_XML_BYTES: usize = 1024 * 1024; +/// Maximum element nesting depth (the root is depth 1). +pub const MAX_XML_DEPTH: usize = 8; +/// Maximum number of elements in one document. +pub const MAX_XML_ELEMENTS: usize = 16 * 1024; +/// Maximum length of one element's text, in bytes after unescaping. +pub const MAX_XML_TEXT_BYTES: usize = 64 * 1024; +/// Maximum number of attributes on one element. +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. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Element { + /// Tag name, case-sensitive. + pub name: String, + /// Attributes in document order, values unescaped. + pub attributes: Vec<(String, String)>, + /// Text content directly inside this element. + pub text: String, + /// Child elements in document order. + pub children: Vec, +} + +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. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Document { + /// The root element's `status_code` attribute (the host's status; 200 = OK). + pub status_code: u32, + /// The root element's `status_message` attribute, if any (UNKNOWN U27). + pub status_message: Option, + /// The root element itself. + pub root: Element, +} + +/// Parses an XML answer. The root element must be `root` and carry a decimal `status_code`. +/// +/// # Errors +/// [`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. +pub fn parse(body: &[u8]) -> Result { + cap("xml document", MAX_XML_BYTES, body.len())?; + 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 { + self.b.get(self.pos).copied() + } + + fn peek_at(&self, ahead: usize) -> Option { + 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 { + 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 ``, only at byte 0. + fn declaration(&mut self) -> Result<()> { + if self.rest().starts_with(b"").ok_or(malformed("xml: unclosed declaration"))?; + self.pos += end + 2; + } + Ok(()) + } + + fn attach(stack: &mut [Element], root: &mut Option, element: Element) { + match stack.last_mut() { + Some(parent) => parent.children.push(element), + None => *root = Some(element), + } + } + + fn document(mut self) -> Result { + self.declaration()?; + self.skip_ws(); + let mut stack: Vec = Vec::new(); + let mut root: Option = 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 { + 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 { + 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 { + 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) + } +} diff --git a/crates/domistream/src/input/gamepad.rs b/crates/domistream/src/input/gamepad.rs new file mode 100644 index 0000000..7a500c2 --- /dev/null +++ b/crates/domistream/src/input/gamepad.rs @@ -0,0 +1,115 @@ +//! Gamepad state, buttons and capabilities (`docs/PROTOCOL.md` section 4, CONTROLLER_MULTI and ARRIVAL). + +/// Data length of `CONTROLLER_MULTI` (26 bytes after the input type). +pub const CONTROLLER_MULTI_DATA_LEN: usize = 26; +/// Highest controller number accepted (16 controllers, matching a 16-bit active mask). +pub const MAX_CONTROLLER_NUMBER: u8 = 15; + +/// Button bits: low 16 bits in the first button field, high 16 bits in the second. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct ButtonFlags(pub u32); + +impl ButtonFlags { + /// D-pad up. + pub const DPAD_UP: u32 = 0x0001; + /// D-pad down. + pub const DPAD_DOWN: u32 = 0x0002; + /// D-pad left. + pub const DPAD_LEFT: u32 = 0x0004; + /// D-pad right. + pub const DPAD_RIGHT: u32 = 0x0008; + /// Start / Menu. + pub const START: u32 = 0x0010; + /// Back / View. + pub const BACK: u32 = 0x0020; + /// Left stick press. + pub const LEFT_STICK: u32 = 0x0040; + /// Right stick press. + pub const RIGHT_STICK: u32 = 0x0080; + /// Left shoulder. + pub const LEFT_BUTTON: u32 = 0x0100; + /// Right shoulder. + pub const RIGHT_BUTTON: u32 = 0x0200; + /// Home / Guide. + pub const HOME: u32 = 0x0400; + /// A. + pub const A: u32 = 0x1000; + /// B. + pub const B: u32 = 0x2000; + /// X. + pub const X: u32 = 0x4000; + /// Y. + pub const Y: u32 = 0x8000; + /// Paddle 1. + pub const PADDLE1: u32 = 0x01_0000; + /// Paddle 2. + pub const PADDLE2: u32 = 0x02_0000; + /// Paddle 3. + pub const PADDLE3: u32 = 0x04_0000; + /// Paddle 4. + pub const PADDLE4: u32 = 0x08_0000; + /// Touchpad click. + pub const TOUCHPAD: u32 = 0x10_0000; + /// Misc (share / capture). + pub const MISC: u32 = 0x20_0000; +} + +/// Controller type in `CONTROLLER_ARRIVAL`. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum ControllerKind { + /// Unknown. + Unknown = 0x00, + /// Xbox-style. + Xbox = 0x01, + /// PlayStation-style. + PlayStation = 0x02, + /// Nintendo-style. + Nintendo = 0x03, +} + +/// Capability bits in `CONTROLLER_ARRIVAL`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct ControllerCapabilities(pub u8); + +impl ControllerCapabilities { + /// Analog triggers. + pub const ANALOG_TRIGGERS: u8 = 0x01; + /// Rumble. + pub const RUMBLE: u8 = 0x02; + /// Trigger rumble. + pub const TRIGGER_RUMBLE: u8 = 0x04; + /// Touchpad. + pub const TOUCHPAD: u8 = 0x08; + /// Accelerometer. + pub const ACCELEROMETER: u8 = 0x10; + /// Gyroscope. + pub const GYRO: u8 = 0x20; + /// Battery state. + pub const BATTERY: u8 = 0x40; + /// RGB LED. + pub const RGB_LED: u8 = 0x80; +} + +/// One `CONTROLLER_MULTI` state. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct GamepadState { + /// Controller number, 0..=15. + pub controller: u8, + /// Bit per connected controller. A cleared bit for `controller` means it was unplugged. + pub active_mask: u16, + /// Pressed buttons. + pub buttons: ButtonFlags, + /// Left trigger, 0..=255. + pub left_trigger: u8, + /// Right trigger, 0..=255. + pub right_trigger: u8, + /// Left stick X. + pub left_stick_x: i16, + /// Left stick Y. + pub left_stick_y: i16, + /// Right stick X. + pub right_stick_x: i16, + /// Right stick Y. + pub right_stick_y: i16, +} diff --git a/crates/domistream/src/input/mod.rs b/crates/domistream/src/input/mod.rs new file mode 100644 index 0000000..153f49b --- /dev/null +++ b/crates/domistream/src/input/mod.rs @@ -0,0 +1,359 @@ +//! Input and gamepad packets (`docs/PROTOCOL.md` section 4). +//! +//! An `INPUT_DATA` message is `0x0206 (LE) ‖ length (LE) ‖ size (BE) ‖ input type (LE) ‖ data`; see the field +//! tables and the test vectors in PROTOCOL.md. [`encode_input`] produces the whole message, ready for the control +//! frame; [`parse_input`] is its inverse (for round-trip tests, fuzzing and the Lumen host). + +pub mod gamepad; + +pub use gamepad::{ButtonFlags, ControllerCapabilities, ControllerKind, GamepadState}; + +/// Maximum size of one `INPUT_DATA` message, in bytes. +pub const MAX_INPUT_MESSAGE_BYTES: usize = 1024; +/// Bytes before the input data (message header 4 + size 4 + input type 4). +pub const INPUT_HEADER_LEN: usize = 12; + +/// Input type codes (little-endian on the wire). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u32)] +pub enum InputType { + /// Key pressed. + KeyDown = 0x0000_0003, + /// Key released. + KeyUp = 0x0000_0004, + /// Absolute mouse position. + MouseMoveAbs = 0x0000_0005, + /// Relative mouse move. + MouseMoveRel = 0x0000_0007, + /// Mouse button pressed. + MouseButtonDown = 0x0000_0008, + /// Mouse button released. + MouseButtonUp = 0x0000_0009, + /// Vertical scroll. + MouseScroll = 0x0000_000A, + /// Gamepad state. + ControllerMulti = 0x0000_000C, + /// Haptics (layout UNKNOWN U21). + Haptics = 0x0000_000D, + /// UTF-8 text (layout UNKNOWN U21). + Utf8Text = 0x0000_0017, + /// Horizontal scroll. + MouseHScroll = 0x5500_0001, + /// Touch (layout UNKNOWN U21). + Touch = 0x5500_0002, + /// Pen (layout UNKNOWN U21). + Pen = 0x5500_0003, + /// A controller was plugged in. + ControllerArrival = 0x5500_0004, + /// Controller touchpad (layout UNKNOWN U21). + ControllerTouch = 0x5500_0005, + /// Controller motion sensors (layout UNKNOWN U21). + ControllerMotion = 0x5500_0006, + /// Controller battery (layout UNKNOWN U21). + 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 for InputType { + type Error = crate::Error; + + /// # Errors + /// [`crate::Error::UnexpectedValue`] for an unknown code. + fn try_from(code: u32) -> crate::Result { + Self::ALL + .into_iter() + .find(|t| *t as u32 == code) + .ok_or(crate::Error::UnexpectedValue { what: "input type", value: code.into() }) + } +} + +/// Mouse buttons. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum MouseButton { + /// Left. + Left = 1, + /// Middle. + Middle = 2, + /// Right. + Right = 3, + /// Side (back). + Side = 4, + /// Extra (forward). + Extra = 5, +} + +/// One input event with a known layout. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum InputEvent { + /// Relative mouse move. + MouseMoveRel { + /// Horizontal delta. + dx: i16, + /// Vertical delta. + dy: i16, + }, + /// Absolute mouse position within the client's viewport (the LG Magic Remote pointer). + MouseMoveAbs { + /// X in the viewport. + x: i16, + /// Y in the viewport. + y: i16, + /// Viewport width as the client reports it. + width: u16, + /// Viewport height as the client reports it. + height: u16, + }, + /// Mouse button. + MouseButton { + /// Pressed (true) or released. + pressed: bool, + /// Which button. + button: MouseButton, + }, + /// Keyboard key. + Key { + /// Pressed (true) or released. + pressed: bool, + /// `flags` byte (bit meanings UNKNOWN U20). + flags: u8, + /// Key code, Windows virtual-key style in the low byte (high byte UNKNOWN U20). + key_code: u16, + /// `modifiers` byte (bit meanings UNKNOWN U20). + modifiers: u8, + }, + /// Vertical scroll (positive = up), in wheel units (120 = one notch). + Scroll { + /// Amount. + amount: i16, + }, + /// Horizontal scroll. + HScroll { + /// Amount. + amount: i16, + }, + /// Full gamepad state. + Gamepad(GamepadState), + /// A controller appeared. + ControllerArrival { + /// Controller number. + controller: u8, + /// What it is. + kind: ControllerKind, + /// What it can do. + capabilities: ControllerCapabilities, + /// Which buttons it has. + supported_buttons: ButtonFlags, + }, +} + +/// `0x0206 LE ‖ length LE ‖ size BE ‖ input type LE ‖ data`. +fn frame(input_type: InputType, data: &[u8]) -> crate::Result> { + 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. +/// +/// # Errors +/// [`crate::Error::UnexpectedValue`] for a controller number above 15. +pub fn encode_input(event: &InputEvent) -> crate::Result> { + match *event { + 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`]). Bytes the layout fixes at zero or at a +/// copy (scroll `amount2`, key padding) are not checked; the `CONTROLLER_MULTI` constants are. +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_INPUT_MESSAGE_BYTES`], [`crate::Error::Truncated`] under +/// [`INPUT_HEADER_LEN`], [`crate::Error::Malformed`] when the type, length or size field does not match, the data +/// length is wrong for the type, or a constant differs; [`crate::Error::UnexpectedValue`] for an unknown type, a +/// 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 { + use crate::util::{byte, i16_from, malformed, u16_le, u32_be, u32_le}; + 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)" }); + } + }) +} diff --git a/crates/domistream/src/keys.rs b/crates/domistream/src/keys.rs new file mode 100644 index 0000000..6b01316 --- /dev/null +++ b/crates/domistream/src/keys.rs @@ -0,0 +1,41 @@ +//! The per-session stream key handed to the host in `launch` / `resume` (`docs/PROTOCOL.md` 1.4, 7). + +use core::fmt; + +use crate::{RandomSource, Result}; + +/// Length of `rikey` in bytes (AES-128). +pub const RIKEY_LEN: usize = 16; + +/// The stream key pair of one session: `rikey` (AES-128 key for control, audio and video) and `rikeyid` +/// (feeds the audio IV). +/// +/// A fresh pair is generated for every launch and resume, because the GCM nonce counters restart per session. +/// `Debug` never prints the key. +#[derive(Clone, PartialEq, Eq)] +pub struct SessionKeys { + /// AES-128 key, sent hex-encoded as the `rikey` launch parameter. + pub rikey: [u8; RIKEY_LEN], + /// Key id, sent as the decimal `rikeyid` launch parameter. + pub rikeyid: u32, +} + +impl SessionKeys { + /// Draws a fresh key and key id from `rng`. + /// + /// # Errors + /// None today; the `Result` leaves room for a fallible source. + pub fn generate(rng: &mut dyn RandomSource) -> Result { + let mut rikey = [0u8; RIKEY_LEN]; + rng.fill(&mut rikey); + let mut id = [0u8; 4]; + rng.fill(&mut id); + Ok(Self { rikey, rikeyid: u32::from_le_bytes(id) }) + } +} + +impl fmt::Debug for SessionKeys { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("SessionKeys").field("rikey", &"").field("rikeyid", &self.rikeyid).finish() + } +} diff --git a/crates/domistream/src/lib.rs b/crates/domistream/src/lib.rs new file mode 100644 index 0000000..d333eaa --- /dev/null +++ b/crates/domistream/src/lib.rs @@ -0,0 +1,56 @@ +//! 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. +//! +//! Interop with real hosts is unverified: the blocking UNKNOWNs of `docs/PROTOCOL.md` are settled live on Day 1. +//! Where the protocol is UNKNOWN, the Wolf-documented behaviour is implemented and kept easy to change. +//! +//! # Shape +//! +//! Nothing here opens a socket, reads a clock, spawns a thread or touches a file. The caller: +//! - feeds received bytes in (`handle_*` / `push` / `parse_*`, always `&[u8]`), +//! - passes the current time in as [`Instant`] and randomness as a [`RandomSource`], +//! - sends the bytes the state machines hand out (`poll_transmit`, [`http::HttpRequest`]), +//! - reacts to events (`poll_event`) and wakes the machine at its deadline (`poll_timeout` / `handle_timeout`). +//! +//! Every parser has a `MAX_*` constant and refuses larger input before it allocates. +//! +//! # Modules, in session order +//! +//! | Module | Protocol (see `docs/PROTOCOL.md`) | +//! | :-- | :-- | +//! | [`http`] | serverinfo, applist, launch/resume/cancel (section 1) | +//! | [`pairing`] | the PIN handshake and the client certificate (section 1.5) | +//! | [`rtsp`] | OPTIONS, DESCRIBE, SETUP, ANNOUNCE, PLAY and SDP (section 2) | +//! | [`enet`] | the ENet-compatible reliable UDP layer under the control stream (section 3.1) | +//! | [`control`] | AES-GCM framing and control messages (sections 3.2, 3.3) | +//! | [`input`] | input and gamepad packets (section 4) | +//! | [`rtp`] | the RTP header shared by video and audio | +//! | [`fec`] | Reed-Solomon erasure coding over GF(2^8) | +//! | [`video`] | video depacketizer with FEC recovery and decryption (section 5) | +//! | [`audio`] | audio depacketizer with FEC recovery and decryption (section 6) | +//! +//! Opus and video decoding are not here: they belong to the platform layer (ArenaTV). + +#![forbid(unsafe_code)] +#![deny(missing_docs)] + +pub mod audio; +pub mod control; +pub mod enet; +pub mod entropy; +pub mod error; +pub mod fec; +pub mod http; +pub mod input; +pub mod keys; +pub mod pairing; +pub mod rtp; +pub mod rtsp; +pub mod time; +mod util; +pub mod video; + +pub use entropy::RandomSource; +pub use error::{Error, Result}; +pub use keys::SessionKeys; +pub use time::Instant; diff --git a/crates/domistream/src/pairing/crypto.rs b/crates/domistream/src/pairing/crypto.rs new file mode 100644 index 0000000..a47d263 --- /dev/null +++ b/crates/domistream/src/pairing/crypto.rs @@ -0,0 +1,109 @@ +//! 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). + +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::util::{cap, malformed}; + +/// AES-128 key used for every encrypted pairing value. +pub type PairingKey = [u8; 16]; + +/// `K = SHA-256(salt ‖ PIN digits)[0..16]`. +/// +/// # Errors +/// None today; the `Result` keeps the signature uniform with the other steps. +pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result { + let mut h = Sha256::new(); + 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> { + 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. +/// +/// # Errors +/// [`crate::Error::Malformed`] when `data` is not a whole, non-zero number of 16-byte blocks. +pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result> { + ecb(key, data, true) +} + +/// AES-128-ECB decryption without padding. +/// +/// # Errors +/// As [`ecb_encrypt`]. +pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result> { + ecb(key, data, false) +} + +/// `SHA-256(challenge ‖ cert_signature ‖ secret)`: the host's proof `H_s` (with the client challenge, the host +/// certificate's signature and the host secret) and the client's proof `H_c` (with the host challenge, the client +/// certificate's signature and the client secret). +/// +/// # Errors +/// [`crate::Error::TooLarge`] for a signature over [`MAX_SIGNATURE_BYTES`]. +pub fn proof_hash( + challenge: &[u8; CHALLENGE_LEN], + cert_signature: &[u8], + secret: &[u8; SECRET_LEN], +) -> Result<[u8; HASH_LEN]> { + cap("certificate signature", MAX_SIGNATURE_BYTES, cert_signature.len())?; + 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`. +/// +/// # Errors +/// [`crate::Error::Malformed`] unless exactly 48 bytes. +pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> { + if decrypted.len() != HASH_LEN + CHALLENGE_LEN { + return Err(malformed("challengeresponse is not 48 bytes")); + } + let hash = crate::util::array::("challengeresponse", decrypted, 0)?; + let challenge = crate::util::array::("challengeresponse", decrypted, HASH_LEN)?; + Ok((hash, challenge)) +} + +/// Splits a `pairingsecret` into the host secret (16 bytes) and its signature (the rest). +/// +/// # Errors +/// [`crate::Error::Malformed`] when shorter than 17 bytes, [`crate::Error::TooLarge`] when the signature is over +/// [`MAX_SIGNATURE_BYTES`]. +pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> { + if pairing_secret.len() <= SECRET_LEN { + 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::("pairingsecret", pairing_secret, 0)?; + Ok((secret, signature)) +} diff --git a/crates/domistream/src/pairing/identity.rs b/crates/domistream/src/pairing/identity.rs new file mode 100644 index 0000000..0faca2a --- /dev/null +++ b/crates/domistream/src/pairing/identity.rs @@ -0,0 +1,326 @@ +//! The client's certificate and key, and the host certificate learnt while pairing. + +use core::fmt; + +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. +pub const MAX_CERT_PEM_BYTES: usize = 16 * 1024; +/// Maximum size of a certificate in DER form, in bytes. +pub const MAX_CERT_DER_BYTES: usize = 12 * 1024; +/// Maximum size of a PKCS#8 private key in DER form, in bytes. +pub const MAX_KEY_DER_BYTES: usize = 8 * 1024; +/// RSA modulus size of keys this client generates. +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 +/// and its private key. Generated once per device and kept by the platform layer (never in logs; the key belongs +/// in the platform's secret store). `Debug` never prints the key. +#[derive(Clone)] +pub struct ClientIdentity { + cert_der: Vec, + key_pkcs8_der: zeroize::Zeroizing>, +} + +/// 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 { + 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 { + 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 { + 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 { + 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 { + 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> { + 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 { + 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 { + /// Generates a new key and self-signed certificate. + /// + /// `common_name` becomes the subject and issuer CN. `not_before_unix` is the validity start in Unix seconds + /// (passed in: no clock reads); validity runs 20 years from it. RSA key generation is slow (hundreds of ms on a + /// TV); call it once per device. + /// + /// # Errors + /// [`Error::Malformed`] for an empty, oversized or control-character `common_name`, or a time before 1970; + /// [`Error::Crypto`] if key generation fails. + pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result { + if common_name.is_empty() + || 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::::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. + /// + /// # Errors + /// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`Error::Malformed`] for bad DER, a + /// certificate without an RSA key, or a key that does not match. + pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result { + cap("client certificate", MAX_CERT_DER_BYTES, cert_der.len())?; + 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. + #[must_use] + pub fn cert_der(&self) -> &[u8] { + &self.cert_der + } + + /// The private key, PKCS#8 DER, for the platform's secret store and its TLS stack. + #[must_use] + pub fn key_pkcs8_der(&self) -> &[u8] { + &self.key_pkcs8_der + } + + /// The certificate as PEM text (what pairing step 1 sends, hex-encoded). + /// + /// # Errors + /// None today. + pub fn cert_pem(&self) -> Result { + 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). + /// + /// # Errors + /// [`Error::Malformed`] if the stored certificate no longer parses (it was checked when loaded). + pub fn cert_signature(&self) -> Result> { + parse_rsa_cert(&self.cert_der).map(|(c, _)| signature_bytes(&c)) + } + + /// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key. + /// + /// # Errors + /// [`Error::Crypto`] if signing fails. + pub fn sign(&self, data: &[u8]) -> Result> { + let key = PrivateKey::from_pkcs8_der(&self.key_pkcs8_der).map_err(|_| Error::Crypto)?; + let sig = SigningKey::::new(key).try_sign(data).map_err(|_| Error::Crypto)?; + Ok(sig.to_vec()) + } +} + +impl fmt::Debug for ClientIdentity { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("ClientIdentity") + .field("cert_der_len", &self.cert_der.len()) + .field("key", &"") + .finish() + } +} + +/// The host certificate received as `plaincert` in pairing step 1, kept to pin HTTPS connections. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ServerCert { + der: Vec, +} + +impl ServerCert { + /// Parses the PEM the host sent (already hex-decoded): exactly one `CERTIFICATE` block and nothing but + /// whitespace around it. + /// + /// # Errors + /// [`Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`Error::Malformed`] for anything that is not one + /// well-formed X.509 certificate with an RSA key. + pub fn from_pem(pem: &[u8]) -> Result { + const BEGIN: &[u8] = b"-----BEGIN CERTIFICATE-----"; + 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. + /// + /// # Errors + /// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise. + pub fn from_der(der: &[u8]) -> Result { + cap("host certificate", MAX_CERT_DER_BYTES, der.len())?; + parse_rsa_cert(der)?; + Ok(Self { der: der.to_vec() }) + } + + /// The certificate, DER. + #[must_use] + pub fn der(&self) -> &[u8] { + &self.der + } + + /// The raw `signatureValue` bytes (input to the pairing proofs). + /// + /// # Errors + /// [`Error::Malformed`] if the stored certificate no longer parses. + pub fn signature(&self) -> Result> { + 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. + /// + /// # Errors + /// [`Error::Crypto`] when it does not verify. + pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> { + let (_, key) = parse_rsa_cert(&self.der)?; + let sig = Signature::try_from(signature).map_err(|_| Error::Crypto)?; + VerifyingKey::::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 + /// constant time. The platform's TLS verifier calls this and nothing else to accept the host. + /// + /// # Errors + /// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`]. + pub fn matches(&self, presented_der: &[u8]) -> Result { + cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?; + Ok(ct_eq(&self.der, presented_der)) + } +} diff --git a/crates/domistream/src/pairing/mod.rs b/crates/domistream/src/pairing/mod.rs new file mode 100644 index 0000000..d5f7bd5 --- /dev/null +++ b/crates/domistream/src/pairing/mod.rs @@ -0,0 +1,369 @@ +//! The PIN pairing handshake (`docs/PROTOCOL.md` 1.5), as a sans-I/O state machine. +//! +//! In Arena Domi the PIN is never shown: Arena Domi TV makes it with [`Pin::generate`], sends it to arena-host over +//! its own signed channel, and arena-host submits it to Sunshine. On the GameStream wire the handshake is unchanged. +//! +//! ```text +//! start ─▶ AwaitServerCert ─▶ AwaitChallengeResponse ─▶ AwaitPairingSecret ─▶ AwaitClientSecretAck +//! │ +//! Paired ◀── AwaitPairChallenge (HTTPS) ◀───────────────────────┘ +//! any step: host says paired=0 / bad proof / bad signature ─▶ Failed +//! ``` +//! +//! Each [`PairingSession::handle_response`] consumes one HTTP answer body and returns the next request to send, +//! 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 crate::http::{HttpRequest, MAX_DEVICE_NAME_BYTES, Scheme, build, check_unique_id}; +use crate::util::{ct_eq, hex_decode, hex_encode, malformed}; +use crate::{Error, RandomSource, Result}; + +pub mod crypto; +pub mod identity; + +pub use identity::{ClientIdentity, ServerCert}; + +/// Length of the salt sent in step 1. +pub const SALT_LEN: usize = 16; +/// Length of the client and host challenges. +pub const CHALLENGE_LEN: usize = 16; +/// Length of the client and host pairing secrets. +pub const SECRET_LEN: usize = 16; +/// Length of the SHA-256 proofs exchanged in steps 2 and 3. +pub const HASH_LEN: usize = 32; +/// Number of PIN digits. +pub const PIN_LEN: usize = 4; +/// Maximum size of one pairing answer body, in bytes. +pub const MAX_PAIR_RESPONSE_BYTES: usize = 64 * 1024; +/// Maximum size of a signature accepted from the host (RSA-8192), in bytes. +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. +#[derive(Clone, Copy, PartialEq, Eq)] +pub struct Pin([u8; PIN_LEN]); + +impl Pin { + /// Draws a uniformly random PIN (rejection sampling, no modulo bias). + /// + /// # Errors + /// None today. + pub fn generate(rng: &mut dyn RandomSource) -> Result { + let mut digits = [0u8; PIN_LEN]; + 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. + /// + /// # Errors + /// [`Error::Malformed`] for anything else. + pub fn from_digits(digits: &str) -> Result { + let b = digits.as_bytes(); + 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. + #[must_use] + pub const fn as_bytes(&self) -> &[u8; PIN_LEN] { + &self.0 + } +} + +impl fmt::Debug for Pin { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("Pin()") + } +} + +/// Where the handshake is. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PairingState { + /// Step 1 sent (`phrase=getservercert`); waiting for `plaincert`. The host holds this answer until the PIN is in. + AwaitServerCert, + /// Step 2 sent (`clientchallenge`); waiting for `challengeresponse`. + AwaitChallengeResponse, + /// Step 3 sent (`serverchallengeresp`); waiting for `pairingsecret`. + AwaitPairingSecret, + /// Step 4 sent (`clientpairingsecret`); waiting for `paired=1`. + AwaitClientSecretAck, + /// Step 5 sent over HTTPS (`phrase=pairchallenge`); waiting for `paired=1`. + AwaitPairChallenge, + /// Done. + Paired, + /// Stopped; see [`PairingFailure`]. No further calls are accepted. + Failed(PairingFailure), +} + +/// Why pairing stopped. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum PairingFailure { + /// The host answered `paired=0`. + HostRefused, + /// The host's proof `H_s` did not match: wrong PIN, or someone in the middle. + ProofMismatch, + /// The host's signature over its secret did not verify against its certificate. + BadHostSignature, + /// An answer could not be parsed or missed its element. + MalformedAnswer, + /// A non-200 HTTP or XML status. + HostStatus, +} + +/// What to do next. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum PairingStep { + /// Send this request and feed its answer to [`PairingSession::handle_response`]. + Send(HttpRequest), + /// Pairing finished; store this. + Paired(PairedHost), +} + +/// The result of a successful pairing, to store with the client identity. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PairedHost { + /// The host certificate from step 1; HTTPS connections must present exactly this certificate. + pub server_cert: ServerCert, +} + +/// The fields a pairing answer can carry (`1…`), hex-decoded. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct PairResponse { + /// `paired == 1`. + pub paired: bool, + /// `plaincert`: the host certificate PEM (step 1). + pub plain_cert: Option>, + /// `challengeresponse`: `E_K(H_s ‖ S_c)`, 48 bytes (step 2). + pub challenge_response: Option>, + /// `pairingsecret`: `secret_s ‖ signature` (step 3). + pub pairing_secret: Option>, +} + +/// Parses one pairing answer. +/// +/// # Errors +/// [`Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`Error::HostStatus`] for a non-200 answer, +/// [`Error::Malformed`] for bad hex or a missing or bad `paired`. +pub fn parse_pair_response(body: &[u8]) -> Result { + let doc = crate::http::document(body, MAX_PAIR_RESPONSE_BYTES, "pairing answer")?; + 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>> { + 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. +pub struct PairingSession { + state: PairingState, + unique_id: String, + device_name: String, + cert_der: Vec, + key: zeroize::Zeroizing<[u8; 16]>, + server_cert: Option, + client_challenge: [u8; CHALLENGE_LEN], + host_proof: [u8; HASH_LEN], + client_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>, +} + +impl PairingSession { + /// Starts pairing: draws the salt, derives the AES key from salt and PIN, and returns step 1. + /// + /// `unique_id` is this client's id (stable per device), `device_name` is shown on the host. + /// + /// # Errors + /// [`Error::Malformed`] for a bad `unique_id` or `device_name` (empty, too long, control characters). + pub fn start( + identity: &ClientIdentity, + unique_id: &str, + device_name: &str, + pin: Pin, + rng: &mut dyn RandomSource, + ) -> Result<(Self, HttpRequest)> { + check_unique_id(unique_id)?; + 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) -> 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 { + 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 + /// [`Self::start`] (it is borrowed per call so the session never holds a copy of the private key). Draws + /// randomness for steps 2 and 3. + /// + /// # Errors + /// [`Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as + /// [`parse_pair_response`], [`Error::State`] after `Paired` or `Failed`, [`Error::Malformed`] for a different + /// identity than at the start. + pub fn handle_response( + &mut self, + identity: &ClientIdentity, + http_status: u16, + body: &[u8], + rng: &mut dyn RandomSource, + ) -> Result { + if matches!(self.state, PairingState::Paired | PairingState::Failed(_)) { + 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 { + 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. + #[must_use] + pub const fn state(&self) -> PairingState { + self.state + } +} + +impl fmt::Debug for PairingSession { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("PairingSession").field("state", &self.state).finish_non_exhaustive() + } +} diff --git a/crates/domistream/src/rtp.rs b/crates/domistream/src/rtp.rs new file mode 100644 index 0000000..25e4827 --- /dev/null +++ b/crates/domistream/src/rtp.rs @@ -0,0 +1,43 @@ +//! The 12-byte RTP header shared by video and audio ([RFC 3550] §5.1, `docs/PROTOCOL.md` 5.2, 6.2). +//! +//! [RFC 3550]: https://www.rfc-editor.org/rfc/rfc3550 + +/// Length of the fixed RTP header. +pub const RTP_HEADER_LEN: usize = 12; + +/// The fixed RTP header. Fields are big-endian on the wire. The first byte is kept raw (version 2 plus flags: +/// `0x90` for video, `0x80` for audio). +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct RtpHeader { + /// Byte 0: version, padding, extension, CSRC count. + pub flags: u8, + /// Byte 1: payload type (video 0, audio 97, audio parity 127). + pub payload_type: u8, + /// Sequence number. + pub sequence: u16, + /// Timestamp. + pub timestamp: u32, + /// SSRC. + pub ssrc: u32, +} + +/// Parses the first [`RTP_HEADER_LEN`] bytes of `packet` (the rest is ignored here). Refuses a version other +/// than 2. +/// +/// # Errors +/// [`crate::Error::Truncated`] for fewer than 12 bytes, [`crate::Error::UnexpectedValue`] for another RTP version. +pub fn parse_rtp_header(packet: &[u8]) -> crate::Result { + const W: &str = "rtp header"; + 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)?, + }) +} diff --git a/crates/domistream/src/rtsp/client.rs b/crates/domistream/src/rtsp/client.rs new file mode 100644 index 0000000..93e7570 --- /dev/null +++ b/crates/domistream/src/rtsp/client.rs @@ -0,0 +1,325 @@ +//! The RTSP client state machine: OPTIONS → DESCRIBE → SETUP audio → SETUP video → SETUP control → ANNOUNCE → +//! PLAY (`docs/PROTOCOL.md` 2.2). +//! +//! The caller opens TCP to the session URL, writes each request from [`RtspClient::poll_request`], cuts the +//! answers with [`super::RtspFramer`], and feeds each whole answer to [`RtspClient::handle_response`] until it +//! returns [`RtspProgress::Ready`]. + +use super::sdp::{self, EncryptionFlags, HostCapabilities, OpusConfig}; +use super::{Method, RtspRequest, RtspResponse, parse_response}; +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. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum VideoCodec { + /// H.264. + H264, + /// HEVC (H.265). + Hevc, + /// AV1. + Av1, +} + +/// What the client asks for in ANNOUNCE. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct StreamConfig { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Frames per second. + pub fps: u32, + /// Video bitrate in kbit/s. + pub bitrate_kbps: u32, + /// Video `packetSize` (default 1024). + pub packet_size: u16, + /// Video codec. + pub codec: VideoCodec, + /// HDR (10-bit) stream. + pub hdr: bool, + /// Audio layout. + pub audio: AudioLayout, + /// Audio packet duration in milliseconds (`x-nv-aqos.packetDuration`). + pub audio_packet_duration_ms: u8, + /// Minimum video parity packets per FEC block. + pub min_fec_packets: u8, + /// The client can recover with reference frame invalidation instead of an IDR. + pub reference_frame_invalidation: bool, + /// Encryption the client wants (Day 1: all three); the ANNOUNCE turns on the intersection with the host. + pub encryption: EncryptionFlags, +} + +/// The three UDP ports from the SETUP answers. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct StreamPorts { + /// Audio RTP port. + pub audio: u16, + /// Video RTP port. + pub video: u16, + /// Control (ENet) port. + pub control: u16, +} + +/// Everything the stream stage needs once RTSP is done. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct NegotiatedStream { + /// UDP ports. + pub ports: StreamPorts, + /// What the host offered in DESCRIBE. + pub host: HostCapabilities, + /// Encryption turned on in ANNOUNCE. + pub encryption: EncryptionFlags, + /// The Opus configuration chosen for `StreamConfig::audio`, for the platform decoder. + pub opus: OpusConfig, + /// The `Session` id from SETUP, if the host sent one. + pub session_id: Option, + /// The datagram to send to the video and audio ports before the stream starts (UNKNOWN U8; `PING` for + /// Moonshine-like hosts). + pub ping_payload: Vec, +} + +/// Where the negotiation is. Each state names the request just sent. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum RtspClientState { + /// OPTIONS sent. + Options, + /// DESCRIBE sent. + Describe, + /// SETUP audio sent. + SetupAudio, + /// SETUP video sent. + SetupVideo, + /// SETUP control sent. + SetupControl, + /// ANNOUNCE sent. + Announce, + /// PLAY sent. + Play, + /// Done; see [`NegotiatedStream`]. + Ready, + /// A non-200 answer or a bad payload stopped it. + Failed, +} + +/// Result of feeding one answer. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum RtspProgress { + /// The next request is ready in [`RtspClient::poll_request`]. + Continue, + /// Negotiation finished. + Ready(NegotiatedStream), +} + +/// The RTSP negotiation for one stream session. +#[derive(Debug)] +pub struct RtspClient { + 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>, + outstanding: bool, + host: Option, + ports: [u16; 3], + session_id: Option, +} + +impl RtspClient { + /// Prepares the negotiation against `session_url` (`sessionUrl0` from launch). The first request (OPTIONS) + /// is ready in [`Self::poll_request`]. + /// + /// # Errors + /// [`Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame + /// rate, bitrate or packet size. + pub fn new(session_url: &str, config: StreamConfig) -> Result { + check_rtsp_url("rtsp session URL", session_url)?; + 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) -> 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. + pub fn poll_request(&mut self) -> Option> { + let req = self.pending.take(); + if req.is_some() { + self.outstanding = true; + } + req + } + + /// Feeds one whole answer (see [`super::RtspFramer`]). + /// + /// # Errors + /// [`Error::HostStatus`] for a non-200 answer, [`Error::Malformed`] for a `CSeq` that does not match or a bad + /// payload, [`Error::Unsupported`] when the host lacks something required, [`Error::State`] when no request is + /// outstanding. Every error but `State` moves the client to [`RtspClientState::Failed`]. + pub fn handle_response(&mut self, message: &[u8]) -> Result { + if !self.outstanding || matches!(self.state, RtspClientState::Ready | RtspClientState::Failed) { + 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 { + 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. + #[must_use] + pub const fn state(&self) -> RtspClientState { + self.state + } +} + +/// `server_port=N` from the `Transport` header (other `;` parts ignored), N in 1..=65535. +fn server_port(r: &RtspResponse) -> Result { + 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) +} diff --git a/crates/domistream/src/rtsp/mod.rs b/crates/domistream/src/rtsp/mod.rs new file mode 100644 index 0000000..241bd29 --- /dev/null +++ b/crates/domistream/src/rtsp/mod.rs @@ -0,0 +1,339 @@ +//! RTSP stream negotiation (`docs/PROTOCOL.md` section 2): message codec, a framer for the TCP byte stream, SDP, +//! and the client state machine. + +pub mod client; +pub mod sdp; + +pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts}; +pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp}; + +use crate::util::{cap, malformed, parse_dec}; +use crate::{Error, Result}; + +/// Default RTSP port. +pub const DEFAULT_RTSP_PORT: u16 = 48010; +/// Maximum size of one RTSP message (start line + headers + payload), in bytes. +pub const MAX_RTSP_MESSAGE_BYTES: usize = 64 * 1024; +/// Maximum length of one start or header line, in bytes (without CRLF). +pub const MAX_RTSP_LINE_BYTES: usize = 4096; +/// Maximum number of header lines in one message. +pub const MAX_RTSP_HEADERS: usize = 64; + +/// The only protocol version spoken. +const VERSION: &str = "RTSP/1.0"; + +/// The methods this client sends. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum Method { + /// `OPTIONS`. + Options, + /// `DESCRIBE`. + Describe, + /// `SETUP`. + Setup, + /// `ANNOUNCE`. + Announce, + /// `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::Options, Self::Describe, Self::Setup, Self::Announce, Self::Play].into_iter().find(|m| m.as_str() == t) + } +} + +/// An RTSP request. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RtspRequest { + /// The method. + pub method: Method, + /// The target, e.g. `rtsp://192.0.2.10:48010` or `streamid=video/0/0`. + pub target: String, + /// Header lines in order, `CSeq` included. + pub headers: Vec<(String, String)>, + /// The payload (SDP for ANNOUNCE), possibly empty. + pub body: Vec, +} + +fn is_token(b: u8) -> bool { + b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b) +} + +impl RtspRequest { + /// Serializes the request (CRLF line ends, empty line, payload) with exactly the given headers. Refuses CR or + /// LF inside a target, header name or value, whitespace in the target, and header names that are not tokens. + /// + /// # Errors + /// [`Error::Malformed`] for a forbidden character, [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`]. + pub fn encode(&self) -> Result> { + if self.target.is_empty() || self.target.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) { + 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) + } +} + +/// An RTSP response. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RtspResponse { + /// Status code, e.g. 200. + pub status: u16, + /// Reason phrase. + pub reason: String, + /// Header lines in order. + pub headers: Vec<(String, String)>, + /// The payload (SDP for DESCRIBE), possibly empty. + pub body: Vec, +} + +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 { + /// The first header with this name, compared case-insensitively. + #[must_use] + pub fn header(&self, name: &str) -> Option<&str> { + header(&self.headers, name) + } +} + +/// A message split into start line, headers and payload. +struct Message { + start: String, + headers: Vec<(String, String)>, + body: Vec, +} + +/// One CRLF-terminated line at `pos`: (line without CRLF, position after CRLF). `None` when no LF follows. +fn line(data: &[u8], pos: usize) -> Result> { + 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> { + let mut found: Option = 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 { + 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`]). +/// +/// # Errors +/// [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`], +/// [`Error::Malformed`] for a bad start line, header line or `Content-Length`, [`Error::Truncated`] when the headers +/// or the payload end early. +pub fn parse_response(message: &[u8]) -> Result { + let m = split_message(message)?; + 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). +/// +/// # Errors +/// As [`parse_response`], plus [`Error::UnexpectedValue`] for an unknown method. +pub fn parse_request(message: &[u8]) -> Result { + let m = split_message(message)?; + 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. +/// +/// A message ends after its headers plus `Content-Length` payload bytes; without `Content-Length` it ends when +/// the host closes the connection ([`RtspFramer::finish`]) (UNKNOWN U5). Never buffers more than +/// [`MAX_RTSP_MESSAGE_BYTES`]. +#[derive(Debug, Default)] +pub struct RtspFramer { + buffer: Vec, +} + +impl RtspFramer { + /// An empty framer. + #[must_use] + pub const fn new() -> Self { + Self { buffer: Vec::new() } + } + + /// Appends received bytes. + /// + /// # Errors + /// [`Error::TooLarge`] when the buffered bytes would exceed [`MAX_RTSP_MESSAGE_BYTES`] (nothing is appended). + pub fn push(&mut self, bytes: &[u8]) -> Result<()> { + cap("rtsp stream", MAX_RTSP_MESSAGE_BYTES, self.buffer.len().saturating_add(bytes.len()))?; + self.buffer.extend_from_slice(bytes); + Ok(()) + } + + /// Where the buffered header section ends and the message's Content-Length, if the headers are complete. + fn head(&self) -> Result)>> { + 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())); + } + } + Ok(Some((head_len, content_length(&headers, head_len)?))) + } + + /// Takes the next complete message, if one is buffered. + /// + /// # Errors + /// [`Error::Malformed`] for a bad `Content-Length`, [`Error::TooLarge`] when it announces a message over the cap. + pub fn next_message(&mut self) -> Result>> { + 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. + /// + /// # Errors + /// [`Error::Truncated`] when the headers never ended or a `Content-Length` promised more. + pub fn finish(&mut self) -> Result>> { + if self.buffer.is_empty() { + 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. + #[must_use] + pub fn buffered(&self) -> usize { + self.buffer.len() + } +} diff --git a/crates/domistream/src/rtsp/sdp.rs b/crates/domistream/src/rtsp/sdp.rs new file mode 100644 index 0000000..49fa92a --- /dev/null +++ b/crates/domistream/src/rtsp/sdp.rs @@ -0,0 +1,263 @@ +//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4). + +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. +pub const MAX_SDP_BYTES: usize = 32 * 1024; +/// Maximum number of lines in an SDP payload. +pub const MAX_SDP_LINES: usize = 1024; +/// Maximum number of Opus configurations a host may advertise. +pub const MAX_OPUS_CONFIGS: usize = 16; +/// Maximum number of audio channels (7.1). +pub const MAX_AUDIO_CHANNELS: usize = 8; + +/// A parsed SDP payload: `a=name:value` attributes plus every other `x=value` line, in order. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Sdp { + /// `a=` attributes: name and value (value empty for flag attributes). + pub attributes: Vec<(String, String)>, + /// Other lines: type character and value (e.g. `('v', "0")`), and bare lines such as `sprop-parameter-sets=…` + /// with type `'\0'`. + pub other: Vec<(char, String)>, +} + +impl Sdp { + /// The first attribute with this exact name. + #[must_use] + pub fn attribute(&self, name: &str) -> Option<&str> { + self.attributes.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str()) + } +} + +/// Parses an SDP payload. Lines end in LF or CRLF; empty lines are skipped. +/// +/// # Errors +/// [`Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`Error::Malformed`] for a payload that is not +/// UTF-8 or a line without `=` or with an empty type. +pub fn parse_sdp(payload: &[u8]) -> Result { + cap("sdp", MAX_SDP_BYTES, payload.len())?; + 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`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct EncryptionFlags(pub u8); + +impl EncryptionFlags { + /// Control stream V2 framing with AES-GCM. + pub const CONTROL_V2: u8 = 0x01; + /// Video AES-GCM. + pub const VIDEO: u8 = 0x02; + /// Audio AES-CBC. + 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`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct FeatureFlags(pub u32); + +impl FeatureFlags { + /// The host accepts pen and touch events. + pub const PEN_TOUCH_EVENTS: u32 = 0x01; + /// The host accepts controller touch events. + pub const CONTROLLER_TOUCH_EVENTS: u32 = 0x02; +} + +/// One Opus multistream configuration (RFC 7845 §5.1.1), for the platform's Opus decoder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct OpusConfig { + /// Output channels (2, 6 or 8). + pub channels: u8, + /// Opus streams per packet. + pub streams: u8, + /// Of which coupled (stereo) streams. + pub coupled_streams: u8, + /// Channel mapping, one entry per channel. + pub mapping: Vec, +} + +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 +/// channel), e.g. `21101`. +/// +/// # Errors +/// [`Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules +/// (`1 ≤ channels ≤ 8`, `streams ≥ 1`, `coupled ≤ streams`, mapping entries `< streams + coupled`). +pub fn parse_surround_params(value: &str) -> Result { + let digits: Vec = value + .bytes() + .map(|b| if b.is_ascii_digit() { Some(b - b'0') } else { None }) + .collect::>>() + .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. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct HostCapabilities { + /// `x-ss-general.encryptionSupported`. + pub encryption_supported: EncryptionFlags, + /// `x-ss-general.featureFlags`. + pub feature_flags: FeatureFlags, + /// `x-nv-video[0].refPicInvalidation:1`. + pub reference_frame_invalidation: bool, + /// `rtpmap:98 AV1/90000` present. + pub av1: bool, + /// Every `fmtp:97 surround-params=…`, in order. + pub opus_configs: Vec, +} + +impl HostCapabilities { + /// Reads the capabilities from a DESCRIBE payload. + /// + /// # Errors + /// [`Error::Malformed`] for a present attribute with a bad value, [`Error::TooLarge`] over + /// [`MAX_OPUS_CONFIGS`]. + pub fn from_sdp(sdp: &Sdp) -> Result { + let mut caps = Self::default(); + 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 (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6). +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 { + 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. +/// +/// # Errors +/// [`Error::Unsupported`] when the host lacks control V2 encryption or the requested codec. +pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> Result> { + let enabled = negotiated_encryption(config, host)?; + if config.codec == VideoCodec::Av1 && !host.av1 { + 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()) +} diff --git a/crates/domistream/src/time.rs b/crates/domistream/src/time.rs new file mode 100644 index 0000000..17b3b4c --- /dev/null +++ b/crates/domistream/src/time.rs @@ -0,0 +1,39 @@ +//! Time comes in from the caller as an [`Instant`]; DomiStream never reads a clock. + +use core::time::Duration; + +/// A point on the caller's monotonic clock, in microseconds since an epoch the caller chooses. +/// +/// Only differences between instants matter. The caller must never let it go backwards within one session. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub struct Instant(u64); + +impl Instant { + /// The caller's epoch. + pub const ZERO: Self = Self(0); + + /// An instant `micros` microseconds after the caller's epoch. + #[must_use] + pub const fn from_micros(micros: u64) -> Self { + Self(micros) + } + + /// Microseconds since the caller's epoch. + #[must_use] + pub const fn as_micros(self) -> u64 { + self.0 + } + + /// `self + d`, saturating at the end of the clock. + #[must_use] + pub fn saturating_add(self, d: Duration) -> Self { + let micros = u64::try_from(d.as_micros()).unwrap_or(u64::MAX); + Self(self.0.saturating_add(micros)) + } + + /// `self - earlier`, or zero when `earlier` is later. + #[must_use] + pub fn saturating_duration_since(self, earlier: Self) -> Duration { + Duration::from_micros(self.0.saturating_sub(earlier.0)) + } +} diff --git a/crates/domistream/src/util.rs b/crates/domistream/src/util.rs new file mode 100644 index 0000000..4c7e747 --- /dev/null +++ b/crates/domistream/src/util.rs @@ -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(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 { + array::<2>(what, data, at).map(u16::from_le_bytes) +} + +pub(crate) fn u16_be(what: &'static str, data: &[u8], at: usize) -> Result { + array::<2>(what, data, at).map(u16::from_be_bytes) +} + +pub(crate) fn u32_le(what: &'static str, data: &[u8], at: usize) -> Result { + array::<4>(what, data, at).map(u32::from_le_bytes) +} + +pub(crate) fn u32_be(what: &'static str, data: &[u8], at: usize) -> Result { + 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 { + 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 { + 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::try_from(parse_dec(what, s)?).map_err(|_| malformed(what)) +} + +pub(crate) fn parse_u16(what: &'static str, s: &str) -> Result { + u16::try_from(parse_dec(what, s)?).map_err(|_| malformed(what)) +} + +pub(crate) fn parse_u8(what: &'static str, s: &str) -> Result { + 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 { + 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> { + 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> { + let mut vals: Vec = 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 = (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()); + } +} diff --git a/crates/domistream/src/video/mod.rs b/crates/domistream/src/video/mod.rs new file mode 100644 index 0000000..b0f6772 --- /dev/null +++ b/crates/domistream/src/video/mod.rs @@ -0,0 +1,456 @@ +//! 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. +//! +//! 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. +//! +//! 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::time::Duration; +use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque}; + +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 use packet::{FecInfo, FrameHeader, FrameType, NvVideoHeader, VideoFlags, VideoPacket, parse_video_packet}; + +/// Length of the prefix of an encrypted packet: IV 12 + frame number 4 + tag 16. +pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16; +/// Maximum size of one reassembled frame (frame header + bitstream), in bytes. +pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024; +/// Maximum frames being assembled at once; older ones are declared lost. +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. +#[derive(Clone)] +pub struct VideoCipher { + key: zeroize::Zeroizing<[u8; 16]>, +} + +impl VideoCipher { + /// A cipher for `rikey`. + #[must_use] + pub fn new(rikey: [u8; 16]) -> Self { + Self { key: zeroize::Zeroizing::new(rikey) } + } + + /// Decrypts one encrypted packet (`IV ‖ frame number ‖ tag ‖ ciphertext`) into the plaintext packet. + /// + /// # Errors + /// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Truncated`] under the prefix, + /// [`Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`Error::Crypto`] for a bad tag. + pub fn decrypt(&self, packet: &[u8]) -> Result> { + const W: &str = "encrypted video packet"; + 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 fmt::Debug for VideoCipher { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str("VideoCipher()") + } +} + +/// Settings of the video receiver. +#[derive(Clone, Debug)] +pub struct VideoConfig { + /// Negotiated `packetSize`. + pub packet_size: u16, + /// Decrypt packets with this cipher when video encryption was negotiated. + pub cipher: Option, + /// How long to wait for missing shards of a frame before declaring it lost. + pub frame_timeout: Duration, +} + +/// One complete frame for the decoder. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct VideoFrame { + /// Frame index. + pub frame_index: u32, + /// The frame header. + pub header: FrameHeader, + /// Annex-B bitstream (start codes included), frame header and padding removed. + pub bitstream: Vec, + /// RTP timestamp of its first packet. + pub rtp_timestamp: u32, + /// When its first packet arrived. + pub first_packet_at: Instant, + /// When it was completed. + pub completed_at: Instant, + /// Data shards rebuilt by FEC. + pub recovered_shards: u16, +} + +/// What the receiver reports. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum VideoEvent { + /// A frame is ready, in frame order. + Frame(VideoFrame), + /// Frames `first..=last` cannot be completed; ask for recovery. + FrameLost { + /// First lost frame index. + first: u32, + /// Last lost frame index. + last: u32, + }, +} + +/// Counters for the stats overlay. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct VideoStats { + /// Packets accepted. + pub packets: u64, + /// Packets refused (bad format, bad tag, duplicate, too old). + pub packets_dropped: u64, + /// Data shards rebuilt by FEC. + pub shards_recovered: u64, + /// Frames delivered. + pub frames: u64, + /// Frames lost. + pub frames_lost: u64, +} + +#[derive(Debug)] +struct Block { + data_shards: u16, + parity_shards: u16, + fec_percentage: u8, + shards: BTreeMap>, +} + +#[derive(Debug)] +struct Pending { + first_packet_at: Instant, + rtp_timestamp: u32, + last_block: u8, + blocks: [Option; packet::MAX_FEC_BLOCKS], + /// Every shard seen, by (block, shard index). + seen: BTreeSet<(u8, u16)>, + complete: Option, +} + +/// The video receiver. +#[derive(Debug)] +pub struct VideoDepacketizer { + config: VideoConfig, + payload_len: usize, + next_frame: Option, + frames: HashMap, + recent: VecDeque<(u32, BTreeSet<(u8, u16)>)>, + events: VecDeque, + stats: VideoStats, +} + +impl VideoDepacketizer { + /// A receiver for one stream. + /// + /// # Errors + /// [`Error::Malformed`] for a `packet_size` not above the NV header size or above what fits in + /// [`packet::MAX_VIDEO_PACKET_BYTES`]. + pub fn new(config: VideoConfig) -> Result { + let size = usize::from(config.packet_size); + 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 + /// an oversized datagram is an error. + /// + /// # Errors + /// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`]. + pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> { + cap("video datagram", packet::MAX_VIDEO_PACKET_BYTES, datagram.len())?; + 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. + pub fn poll_event(&mut self) -> Option { + self.events.pop_front() + } + + /// When an incomplete frame times out. + #[must_use] + pub fn poll_timeout(&self) -> Option { + 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. + /// + /// # Errors + /// None today. + pub fn handle_timeout(&mut self, now: Instant) -> Result<()> { + self.advance(now); + Ok(()) + } + + /// Counters. + #[must_use] + pub const fn stats(&self) -> VideoStats { + 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 = 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>> = + (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, + )) +} diff --git a/crates/domistream/src/video/packet.rs b/crates/domistream/src/video/packet.rs new file mode 100644 index 0000000..43de108 --- /dev/null +++ b/crates/domistream/src/video/packet.rs @@ -0,0 +1,167 @@ +//! The video packet layout (`docs/PROTOCOL.md` 5.2): RTP header, 4 reserved bytes, the 16-byte NV video header, +//! payload. NV header fields are little-endian. + +use crate::rtp::RtpHeader; + +/// RTP header plus the 4 reserved bytes. +pub const VIDEO_RTP_LEN: usize = 16; +/// Length of the NV video header. +pub const NV_HEADER_LEN: usize = 16; +/// Offset of the payload in a packet. +pub const PAYLOAD_OFFSET: usize = VIDEO_RTP_LEN + NV_HEADER_LEN; +/// Length of the frame header at the start of each frame's data. +pub const FRAME_HEADER_LEN: usize = 8; +/// Maximum size of one video packet (plaintext or encrypted), in bytes. +pub const MAX_VIDEO_PACKET_BYTES: usize = 4096; +/// Maximum FEC blocks per frame (two-bit block index). +pub const MAX_FEC_BLOCKS: usize = 4; +/// The `packetSize` used when ANNOUNCE does not set one. +pub const DEFAULT_PACKET_SIZE: u16 = 1024; + +/// NV video flags. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct VideoFlags(pub u8); + +impl VideoFlags { + /// The packet carries picture data (0 on parity packets). + pub const PICTURE_DATA: u8 = 0x01; + /// Last data packet of the frame. + pub const END_OF_FRAME: u8 = 0x02; + /// First data packet of the frame. + pub const START_OF_FRAME: u8 = 0x04; +} + +/// The FEC fields of one packet, decoded from `fecInfo` and `multiFecBlocks`. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct FecInfo { + /// Index in the block: `0..data_shards` data, `data_shards..` parity (`fecInfo` bits 12-21). + pub shard_index: u16, + /// Data shards in this block (`fecInfo` bits 22-31). + pub data_shards: u16, + /// FEC percentage of this block (`fecInfo` bits 4-11). + pub fec_percentage: u8, + /// This block's index in the frame (`multiFecBlocks` bits 4-5). + pub block_index: u8, + /// The frame's last block index (`multiFecBlocks` bits 6-7). + pub last_block_index: u8, +} + +/// The NV video header. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct NvVideoHeader { + /// Stream packet index (RTP sequence << 8). + pub stream_packet_index: u32, + /// Frame index. + pub frame_index: u32, + /// Flags. + pub flags: VideoFlags, + /// `multiFecFlags` byte, raw (UNKNOWN U15). + pub multi_fec_flags: u8, + /// FEC fields. + pub fec: FecInfo, +} + +/// One plaintext video packet. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct VideoPacket<'a> { + /// RTP header. + pub rtp: RtpHeader, + /// NV video header. + pub nv: NvVideoHeader, + /// Payload (frame data for data shards, parity bytes for parity shards). + pub payload: &'a [u8], +} + +/// Parses one plaintext video packet. Checks the FEC fields are consistent (`data_shards > 0`, data + parity +/// `<= 255` with parity `= ceil(data × percentage / 100)`, `shard_index < data + parity`, +/// `block_index <= last_block_index`). +/// +/// # Errors +/// [`crate::Error::TooLarge`] over [`MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under +/// [`PAYLOAD_OFFSET`], [`crate::Error::UnexpectedValue`] for an RTP version other than 2, +/// [`crate::Error::Malformed`] for inconsistent FEC fields. +pub fn parse_video_packet(packet: &[u8]) -> crate::Result> { + use crate::util::{byte, malformed, u32_le}; + 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. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum FrameType { + /// Predicted (1). + Predicted, + /// Key / IDR (2). + Key, + /// First frame after a reference frame invalidation (5). + Recovery, + /// Any other value. + Other(u8), +} + +/// The 8-byte header in front of each frame's bitstream (UNKNOWN U13: Wolf shows a constant, Moonshine these +/// fields). +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub struct FrameHeader { + /// The 8 bytes as received. + pub raw: [u8; FRAME_HEADER_LEN], + /// Byte 0. + pub header_type: u8, + /// Bytes 1-2, LE: host processing latency (unit UNKNOWN). + pub processing_latency: u16, + /// Byte 3. + pub frame_type: FrameType, + /// Bytes 4-7, LE: payload bytes in the last data shard. + pub last_payload_len: u32, +} + +/// Parses the frame header at the start of a frame's data (the rest is ignored here). +/// +/// # Errors +/// [`crate::Error::Truncated`] under [`FRAME_HEADER_LEN`]. +pub fn parse_frame_header(frame_data: &[u8]) -> crate::Result { + const W: &str = "video frame header"; + let raw = crate::util::array::(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]), + }) +} diff --git a/crates/domistream/tests/alloc_caps.rs b/crates/domistream/tests/alloc_caps.rs new file mode 100644 index 0000000..836941f --- /dev/null +++ b/crates/domistream/tests/alloc_caps.rs @@ -0,0 +1,259 @@ +//! "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(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, fn(&[u8]) -> bool); + +fn lying_inputs() -> Vec { + let mut v: Vec = 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 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"�".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 +} + +/// 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 = 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))), + ("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::(), 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}")); + } +} diff --git a/crates/domistream/tests/audio.rs b/crates/domistream/tests/audio.rs new file mode 100644 index 0000000..655676b --- /dev/null +++ b/crates/domistream/tests/audio.rs @@ -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, + stats: AudioStats, +} + +fn run(cfg: AudioConfig, datagrams: &[Vec]) -> 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 = expect.iter().enumerate().map(|(i, e)| (e.sequence, i)).collect(); + let mut seen = vec![false; expect.len()]; + let mut prev: Option = 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, Vec, Vec>) { + 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 = (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> = 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> = 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 = 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 { + 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> = 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::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::(), 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 = (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::(), 0..80), 0..60)) { + let r = run(config(true, AudioFec::ParityMatrix(audio_test_matrix())), &datagrams); + prop_assert!(r.events.len() <= datagrams.len() * 4 + 4); + } +} diff --git a/crates/domistream/tests/common/mod.rs b/crates/domistream/tests/common/mod.rs new file mode 100644 index 0000000..8838ee0 --- /dev/null +++ b/crates/domistream/tests/common/mod.rs @@ -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(r: &domistream::Result) -> 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 { + 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 { + let mut all: Vec = (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(&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, + pos: usize, +} + +impl ScriptedRng { + pub fn new(bytes: Vec) -> 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 { + 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); + +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 { + 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 { + 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