21 Commits

Author SHA1 Message Date
mnovak e4ca1509c8 [domistream] Tests: RTSP parsers, framer, SDP and client
Bad start lines, header floods, line cap, lying Content-Length (over, under,
past the cap, past u64), 64 KiB+1 in the framer, chunking invariance,
surround-params against RFC 7845, ANNOUNCE intersection, and the client state
machine with hostile answers.
2026-11-25 12:51:03 +01:00
mnovak d0fe9a906c [domistream] Tests: pairing state machine against recorded vectors
Walks every state with a recorded transcript (fixtures from tools/vectors).
Wrong PIN, wrong hash, wrong cert, rogue and flipped signatures, wrong sizes,
out-of-order, replayed and cross-session answers all end in Failed(reason);
Paired cannot be reached by skipping a step. Crypto helpers, certificates,
identities and the PIN against the same vectors.
2026-11-25 12:51:01 +01:00
mnovak b261d7ddc9 [domistream] Tests: hostile HTTP and XML input
XML reader, serverinfo, applist, launch and status answers: empty, 1 byte,
max-1, max, max+1, huge; depth bombs, element, attribute and text caps,
entities, DTD and billion laughs, namespaces. Request builders refuse bad ids
and query injection. proptest round trip of generated XML trees.
2026-11-25 12:51:01 +01:00
mnovak 9d94b66975 [domistream] Tests: sans-I/O guard and secret hygiene
Fails if src/ uses std::net, Instant::now, SystemTime::now, std::thread,
std::fs, processes, env reads or OS randomness (comments stripped, grouped
std imports caught). Checks forbid(unsafe_code) and that Debug never prints
rikey, the PIN or the private key.
2026-11-25 12:51:00 +01:00
mnovak 7326767f37 [domistream] Tests: vector generator and shared test helpers
tools/vectors/gen_vectors.py makes the crypto vectors with tools independent of
RustCrypto: Python hashlib (SHA-256), the OpenSSL 3.5 CLI (RSA-2048 test-only
keys, X.509 certs, PKCS#1 v1.5 SHA-256 signatures, AES-128-ECB -nopad,
AES-128-CBC) and .NET 10 AesGcm (gcm_vectors.cs). Output goes to
crates/domistream/tests/fixtures (text only); not generated in this commit.

tests/common: seeded and scripted RandomSource, fixture reader, an independent
GF(2^8)/0x11D reference with Cauchy matrices, and test hosts that packetize
video (PROTOCOL.md 5.2-5.3) and audio (6.2-6.4).

Dev-dependencies: proptest (std only, no fork/timeout) and peak_alloc (MIT,
counting allocator for the allocation-cap test).
2026-11-25 12:51:00 +01:00
mnovak 6370e0a4bc [repo] Fuzz: note that only the SanitizerCoverage build links on Windows 2026-11-25 12:01:19 +01:00
mnovak c83fce11e9 [repo] README: repository layout 2026-11-25 12:01:10 +01:00
mnovak 3ade60d0b4 [repo] Fuzz: one libFuzzer target per parser, own workspace, Windows MSVC setup from Via 2026-11-25 12:01:09 +01:00
mnovak 31d1fc3655 [domistream] Audio API: packet parser, CBC decryption, 4+2 FEC depacketizer 2026-11-25 11:48:04 +01:00
mnovak b4a21dfc10 [domistream] Video API: packet parser, frame header, decryption, depacketizer with FEC 2026-11-25 11:47:55 +01:00
mnovak e7c69ac956 [domistream] RTP and FEC API: RTP header parser, Reed-Solomon over GF(2^8) 2026-11-25 11:47:42 +01:00
mnovak c01f980292 [domistream] Control API: AES-GCM frame, control messages, control stream 2026-11-25 11:47:25 +01:00
mnovak 213f87b871 [domistream] Input API: mouse, keyboard and gamepad events with their INPUT_DATA codec 2026-11-25 11:46:55 +01:00
mnovak fc5b0b116c [domistream] ENet API: sans-I/O 1.3 datagram codec and client peer 2026-11-25 11:46:37 +01:00
mnovak 024fe14ca6 [domistream] RTSP API: message codec, stream framer, SDP, negotiation state machine 2026-11-25 11:46:10 +01:00
mnovak 736a8f42b0 [domistream] Pairing API: PIN handshake state machine, pure crypto steps, client identity, pinned host cert 2026-11-25 11:45:57 +01:00
mnovak 0188ffba97 [domistream] HTTP API: serverinfo, applist, launch/resume/cancel requests and capped XML parsers 2026-11-25 11:45:30 +01:00
mnovak cb8e7ed4c3 [repo] Workspace: one crate, forbid(unsafe), no-panic lints, RustCrypto picked; Error, Instant, RandomSource, SessionKeys 2026-11-25 11:45:23 +01:00
mnovak 184f4024c7 [repo] Protocol: GameStream client side from the Wolf docs, with every UNKNOWN listed 2026-11-25 11:26:31 +01:00
mnovak 5148abfcc3 [repo] Open point 2: Wolf docs licence, Rust ENet crates, own sans-I/O ENet recommended 2026-11-25 11:26:31 +01:00
mnovak b53b9e0be1 [repo] Clean room: allowed and forbidden sources, GPL-provenance rule, source log 2026-11-25 11:26:30 +01:00
66 changed files with 9172 additions and 6 deletions
-6
View File
@@ -10,8 +10,6 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
### Rules that never bend
- Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c)
into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements.
- Also allowed for the wire format, with attribution (Mark, 2026-11-25): stock ENet (MIT), tokio-enet (BSD-2),
fec-rs (BSD-2). GPL code stays off limits.
- Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only.
- Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed).
- Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever.
@@ -30,7 +28,3 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
- Commits: `[<crate>] <Feature>: <description>`, `[repo]` for repo-wide changes. No AI attribution in commits, PRs or tags.
- No binaries, captures or test videos in git.
- Cargo builds: the machine-wide `CARGO_HOME` config sends the build dir to `D:\cargo-build`. Never set `CARGO_TARGET_DIR`.
- Never start a build or a test run (cargo, npm/pnpm, Gradle, dotnet, Playwright, e2e, emulator, Fabrica runs) while this
PC's CPU, RAM, or any drive the work writes to (D:, E:, F:) is more than 90 % used (Mark, 2026-11-25: "CPU, RAM and
disk all 90%"). Check first. If any is above 90 %, don't start; wait and check again later. Don't stop other
sessions' work to make room.
Generated
+574
View File
@@ -0,0 +1,574 @@
# 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 = "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 = "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 = "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",
"getrandom",
"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 = [
"getrandom",
"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",
"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 = "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 = "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_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[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 = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[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 = "tls_codec"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
dependencies = [
"tls_codec_derive",
"zeroize",
]
[[package]]
name = "tls_codec_derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[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",
"sha1",
"signature",
"spki",
"tls_codec",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
+27
View File
@@ -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"
+7
View File
@@ -18,6 +18,13 @@ Rubylight or moonlight-common-c was opened, pasted or ported. See [`docs/CLEAN_R
cargo test --workspace
```
| 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).
+29
View File
@@ -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 = "0.11" # control and video AES-128-GCM
cbc = "0.2" # audio AES-128-CBC
sha2 = "0.11" # pairing SHA-256
rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigint, constant time)
x509-cert = { version = "0.3", features = ["builder", "pem"] } # client certificate, host certificate parsing
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"
+172
View File
@@ -0,0 +1,172 @@
//! 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.
use core::fmt;
use crate::{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;
/// 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: [u8; 16],
rikeyid: u32,
}
impl AudioCipher {
/// A cipher for the session's keys.
#[must_use]
pub const fn new(keys: &SessionKeys) -> Self {
Self { key: keys.rikey, rikeyid: keys.rikeyid }
}
/// The IV for RTP sequence number `sequence`.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn iv(&self, sequence: u16) -> Result<[u8; 16]> {
let _ = (sequence, self.rikeyid);
Err(crate::Error::Unimplemented)
}
/// Decrypts one payload.
///
/// # Errors
/// [`crate::Error::Malformed`] for a length that is not a positive multiple of 16, [`crate::Error::Crypto`] for
/// bad padding. Phase A: always [`crate::Error::Unimplemented`].
pub fn decrypt(&self, sequence: u16, ciphertext: &[u8]) -> Result<Vec<u8>> {
let _ = (sequence, ciphertext, &self.key);
Err(crate::Error::Unimplemented)
}
}
impl fmt::Debug for AudioCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("AudioCipher(<redacted>)")
}
}
/// 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<AudioCipher>,
/// 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<u8>,
/// 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,
}
/// The audio receiver.
#[derive(Debug)]
pub struct AudioDepacketizer {
stats: AudioStats,
}
impl AudioDepacketizer {
/// A receiver for one stream.
///
/// # Errors
/// [`crate::Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn new(config: AudioConfig) -> Result<Self> {
let _ = config;
Err(crate::Error::Unimplemented)
}
/// 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
/// [`crate::Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let _ = (now, datagram);
Err(crate::Error::Unimplemented)
}
/// The next event.
pub fn poll_event(&mut self) -> Option<AudioEvent> {
None
}
/// When a missing packet times out.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// Reports timed-out packets as lost.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
/// Counters.
#[must_use]
pub const fn stats(&self) -> AudioStats {
self.stats
}
}
+60
View File
@@ -0,0 +1,60 @@
//! 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 payload type or a parity shard index above 1.
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_audio_packet(packet: &[u8]) -> crate::Result<AudioPacket<'_>> {
let _ = packet;
Err(crate::Error::Unimplemented)
}
+104
View File
@@ -0,0 +1,104 @@
//! 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 crate::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
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> {
let _ = (sequence, direction);
Err(crate::Error::Unimplemented)
}
/// 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
/// [`crate::Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`crate::Error::Truncated`] under [`MIN_FRAME_BYTES`],
/// [`crate::Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`crate::Error::Malformed`]
/// for a length that does not match. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_encrypted_frame(frame: &[u8]) -> Result<EncryptedFrame<'_>> {
let _ = frame;
Err(crate::Error::Unimplemented)
}
/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key.
#[derive(Clone)]
pub struct ControlCipher {
key: [u8; 16],
}
impl ControlCipher {
/// A cipher for `rikey`.
#[must_use]
pub const fn new(rikey: [u8; 16]) -> Self {
Self { key: rikey }
}
/// Encrypts one message (plaintext = type, length, body) into a whole frame.
///
/// # Errors
/// [`crate::Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result<Vec<u8>> {
let _ = (sequence, direction, plaintext, &self.key);
Err(crate::Error::Unimplemented)
}
/// Checks and decrypts one frame; returns its sequence number and the plaintext message.
///
/// # Errors
/// Parser errors as [`parse_encrypted_frame`]; [`crate::Error::Crypto`] when the tag does not verify. Phase A:
/// always [`crate::Error::Unimplemented`].
pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec<u8>)> {
let _ = (direction, frame);
Err(crate::Error::Unimplemented)
}
}
impl fmt::Debug for ControlCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("ControlCipher(<redacted>)")
}
}
+212
View File
@@ -0,0 +1,212 @@
//! 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;
/// 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 TryFrom<u16> for MessageType {
type Error = crate::Error;
/// # Errors
/// [`crate::Error::UnexpectedValue`] for an unknown code. Phase A: always [`crate::Error::Unimplemented`].
fn try_from(code: u16) -> Result<Self> {
let _ = code;
Err(crate::Error::Unimplemented)
}
}
/// 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. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_message(message: &[u8]) -> Result<RawMessage<'_>> {
let _ = message;
Err(crate::Error::Unimplemented)
}
/// 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<HdrMetadata>,
},
/// The host ended the session.
Termination {
/// Error code (extended form), `None` for the plain form. `0x80030023` = graceful.
error_code: Option<u32>,
},
/// 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,
},
}
/// Interprets a decrypted message from the host.
///
/// # 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. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_host_message(message: &[u8]) -> Result<HostMessage> {
let _ = message;
Err(crate::Error::Unimplemented)
}
/// 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; input errors as
/// [`crate::input::encode_input`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
let _ = message;
Err(crate::Error::Unimplemented)
}
+124
View File
@@ -0,0 +1,124 @@
//! 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 crate::enet::EnetConfig;
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", &"<redacted>")
.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 {
next_sequence: u32,
}
impl ControlStream {
/// Starts connecting.
///
/// # Errors
/// As [`crate::enet::EnetClient::connect`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
let _ = (config, now, rng);
Err(crate::Error::Unimplemented)
}
/// 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`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let _ = (now, datagram);
Err(crate::Error::Unimplemented)
}
/// 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). Phase A: always [`crate::Error::Unimplemented`].
pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> {
let _ = (now, message, self.next_sequence);
Err(crate::Error::Unimplemented)
}
/// The next datagram to send.
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
let _ = now;
None
}
/// The next event.
pub fn poll_event(&mut self) -> Option<ControlEvent> {
None
}
/// When [`Self::handle_timeout`] is due.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// Advances timers (ENet, periodic ping).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
/// Closes the stream gracefully.
///
/// # Errors
/// [`crate::Error::Closed`] when already closed. Phase A: always [`crate::Error::Unimplemented`].
pub fn close(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
}
+175
View File
@@ -0,0 +1,175 @@
//! 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() { … }
//! }
//! ```
use core::time::Duration;
use crate::{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;
/// 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<u8>,
},
/// The host closed the connection.
Disconnected {
/// The host's disconnect data word.
data: u32,
},
/// The host stopped answering.
TimedOut,
}
/// The ENet client peer.
#[derive(Debug)]
pub struct EnetClient {
state: EnetState,
}
impl EnetClient {
/// Starts connecting: queues the connect datagram. The connect id comes from `rng`.
///
/// # Errors
/// [`crate::Error::Malformed`] for a config outside ENet's limits. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
let _ = (config, now, rng);
Err(crate::Error::Unimplemented)
}
/// Feeds one received datagram. Datagrams for another peer id or session are dropped without error.
///
/// # Errors
/// Parser errors as [`protocol::parse_datagram`]; [`crate::Error::TooLarge`] when a reassembly would exceed
/// [`MAX_PACKET_BYTES`]; [`crate::Error::Closed`] after `Disconnected`. A malformed datagram never changes the
/// connection state. Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let _ = (now, datagram);
Err(crate::Error::Unimplemented)
}
/// Queues a packet. Packets larger than the MTU are fragmented.
///
/// # Errors
/// [`crate::Error::State`] unless connected, [`crate::Error::UnexpectedValue`] for a channel outside the
/// negotiated count, [`crate::Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> {
let _ = (now, channel, delivery, data);
Err(crate::Error::Unimplemented)
}
/// Starts a graceful disconnect.
///
/// # Errors
/// [`crate::Error::Closed`] when already disconnected. Phase A: always [`crate::Error::Unimplemented`].
pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> {
let _ = (now, data);
Err(crate::Error::Unimplemented)
}
/// The next datagram to send, at most [`protocol::MAX_DATAGRAM_BYTES`] (acknowledgements, retransmissions,
/// queued packets, pings).
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
let _ = now;
None
}
/// The next event.
pub fn poll_event(&mut self) -> Option<EnetEvent> {
None
}
/// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// Advances timers: retransmits, pings, or gives up with [`EnetEvent::TimedOut`].
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
/// 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<Duration> {
None
}
}
+216
View File
@@ -0,0 +1,216 @@
//! 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<u8>,
}
/// 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<u8>),
/// Unreliable sequenced data.
SendUnreliable {
/// Unreliable sequence number.
unreliable_sequence: u16,
/// The data.
data: Vec<u8>,
},
/// Reliable fragment.
SendFragment(Fragment),
/// Unsequenced data.
SendUnsequenced {
/// Unsequenced group.
unsequenced_group: u16,
/// The data.
data: Vec<u8>,
},
/// 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<u16>,
/// The commands, at most [`MAX_COMMANDS_PER_DATAGRAM`].
pub commands: Vec<Command>,
}
/// Parses one datagram strictly: every length checked against the bytes present, unknown command numbers and
/// compressed datagrams refused.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`],
/// [`crate::Error::Truncated`] for a cut command, [`crate::Error::UnexpectedValue`] for an unknown command or the
/// compressed flag, [`crate::Error::Malformed`] for a data length that does not match. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_datagram(datagram: &[u8]) -> crate::Result<Datagram> {
let _ = datagram;
Err(crate::Error::Unimplemented)
}
/// Serializes one datagram.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn encode_datagram(datagram: &Datagram) -> crate::Result<Vec<u8>> {
let _ = datagram;
Err(crate::Error::Unimplemented)
}
+11
View File
@@ -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]);
}
+94
View File
@@ -0,0 +1,94 @@
//! The one error type of the crate.
use core::fmt;
/// Result with the crate's [`Error`].
pub type Result<T> = core::result::Result<T, Error>;
/// Everything that can go wrong. Errors never carry key material or decrypted bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Error {
/// Phase A: the API exists, the logic does not yet.
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 {}
+95
View File
@@ -0,0 +1,95 @@
//! 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`, construction UNKNOWN U14) and audio (a fixed 2 × 4 parity
//! matrix, UNKNOWN U16, passed in with [`ReedSolomon::with_parity_matrix`] until it is measured).
/// 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;
/// Parity shards for `data_shards` at `fec_percentage`: `ceil(data × percentage / 100)`.
///
/// # Errors
/// [`crate::Error::UnexpectedValue`] when `data_shards` is 0 or the result would exceed [`MAX_SHARDS`]. Phase A:
/// always [`crate::Error::Unimplemented`].
pub fn parity_count(data_shards: usize, fec_percentage: u8) -> crate::Result<usize> {
let _ = (data_shards, fec_percentage);
Err(crate::Error::Unimplemented)
}
/// 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<u8>,
}
impl ReedSolomon {
/// The code GameStream video uses for `data_shards` + `parity_shards` (UNKNOWN U14: construction).
///
/// # Errors
/// [`crate::Error::UnexpectedValue`] when either count is 0 or the sum exceeds [`MAX_SHARDS`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn new(data_shards: usize, parity_shards: usize) -> crate::Result<Self> {
let _ = (data_shards, parity_shards);
Err(crate::Error::Unimplemented)
}
/// 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.
///
/// # Errors
/// As [`Self::new`]; [`crate::Error::Malformed`] for a matrix of the wrong size or one that is not MDS.
pub fn with_parity_matrix(data_shards: usize, parity_shards: usize, parity_matrix: &[u8]) -> crate::Result<Self> {
let _ = (data_shards, parity_shards, parity_matrix);
Err(crate::Error::Unimplemented)
}
/// 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
}
/// Computes the parity shards from the data shards. `shards` holds `data + parity` buffers of equal length;
/// the parity ones are overwritten.
///
/// # Errors
/// [`crate::Error::Malformed`] for the wrong shard count or unequal lengths, [`crate::Error::TooLarge`] over
/// [`MAX_SHARD_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn encode(&self, shards: &mut [Vec<u8>]) -> crate::Result<()> {
let _ = shards;
Err(crate::Error::Unimplemented)
}
/// Rebuilds missing shards in place. `shards` holds `data + parity` entries, `None` for lost ones; on success
/// every entry is `Some`.
///
/// # Errors
/// [`crate::Error::Malformed`] for the wrong count or unequal lengths, [`crate::Error::TooLarge`] over
/// [`MAX_SHARD_BYTES`], [`crate::Error::Truncated`] when fewer than `data` shards are present. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn reconstruct(&self, shards: &mut [Option<Vec<u8>>]) -> crate::Result<()> {
let _ = shards;
Err(crate::Error::Unimplemented)
}
}
+30
View File
@@ -0,0 +1,30 @@
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
/// 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.
///
/// # 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`. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_app_list(body: &[u8]) -> crate::Result<Vec<App>> {
let _ = body;
Err(crate::Error::Unimplemented)
}
+78
View File
@@ -0,0 +1,78 @@
//! `GET /launch` and `GET /resume` (`docs/PROTOCOL.md` 1.4).
use super::HttpRequest;
use crate::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,
}
/// 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<String>,
}
/// Builds `GET /launch` (HTTPS).
///
/// # Errors
/// [`crate::Error::Malformed`] for a zero size or frame rate, or a bad `unique_id`. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn launch_request(params: &LaunchParams, unique_id: &str) -> crate::Result<HttpRequest> {
let _ = (params, unique_id);
Err(crate::Error::Unimplemented)
}
/// Builds `GET /resume` (HTTPS) with fresh keys.
///
/// # Errors
/// As [`launch_request`].
pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> crate::Result<HttpRequest> {
let _ = (keys, unique_id);
Err(crate::Error::Unimplemented)
}
/// 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. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_launch_response(body: &[u8]) -> crate::Result<LaunchResponse> {
let _ = body;
Err(crate::Error::Unimplemented)
}
+95
View File
@@ -0,0 +1,95 @@
//! 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;
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<Duration>,
}
/// Builds `GET /serverinfo` for this client.
///
/// # Errors
/// [`crate::Error::Malformed`] for an empty or oversized `unique_id`. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn server_info_request(scheme: Scheme, unique_id: &str) -> crate::Result<HttpRequest> {
let _ = (scheme, unique_id);
Err(crate::Error::Unimplemented)
}
/// Builds `GET /applist` (HTTPS).
///
/// # Errors
/// As [`server_info_request`].
pub fn app_list_request(unique_id: &str) -> crate::Result<HttpRequest> {
let _ = unique_id;
Err(crate::Error::Unimplemented)
}
/// Builds `GET /cancel` (HTTPS): quits the app running on the host.
///
/// # Errors
/// As [`server_info_request`].
pub fn cancel_request(unique_id: &str) -> crate::Result<HttpRequest> {
let _ = unique_id;
Err(crate::Error::Unimplemented)
}
/// Builds `GET /unpair` (HTTPS): the host forgets this client.
///
/// # Errors
/// As [`server_info_request`].
pub fn unpair_request(unique_id: &str) -> crate::Result<HttpRequest> {
let _ = unique_id;
Err(crate::Error::Unimplemented)
}
/// Checks a plain `<root status_code="200"/>` answer (cancel, unpair).
///
/// # Errors
/// [`crate::Error::HostStatus`] for a non-200 status, parser errors as [`xml::parse`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_status_response(body: &[u8]) -> crate::Result<()> {
let _ = body;
Err(crate::Error::Unimplemented)
}
+58
View File
@@ -0,0 +1,58 @@
//! `GET /serverinfo` (`docs/PROTOCOL.md` 1.2).
/// 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<String>,
/// `uniqueid`: the host's stable id.
pub unique_id: String,
/// `HttpsPort`.
pub https_port: u16,
/// `ExternalPort` (the HTTP port).
pub http_port: Option<u16>,
/// `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<String>,
/// `MaxLumaPixelsHEVC`; 0 = no HEVC.
pub max_luma_pixels_hevc: Option<u64>,
/// `ServerCodecModeSupport` bitmask (bit meanings UNKNOWN U25).
pub codec_mode_support: Option<u32>,
/// `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
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn is_busy(&self) -> crate::Result<bool> {
Err(crate::Error::Unimplemented)
}
}
/// Parses a serverinfo body.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_SERVERINFO_BYTES`], [`crate::Error::HostStatus`] for a non-200 answer,
/// [`crate::Error::Malformed`] for a missing required element (`hostname`, `uniqueid`, `HttpsPort`) or a bad
/// number. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_server_info(body: &[u8]) -> crate::Result<ServerInfo> {
let _ = body;
Err(crate::Error::Unimplemented)
}
+48
View File
@@ -0,0 +1,48 @@
//! A small, strict XML reader for the host's answers: one `<root status_code="…">` element with nested
//! elements and text. No DTD, no entities beyond the five predefined ones and numeric character references,
//! no processing instructions except a leading XML declaration, no namespaces.
/// 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;
/// 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<Element>,
}
/// 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<String>,
/// 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. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse(body: &[u8]) -> crate::Result<Document> {
let _ = body;
Err(crate::Error::Unimplemented)
}
+115
View File
@@ -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,
}
+167
View File
@@ -0,0 +1,167 @@
//! 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 TryFrom<u32> for InputType {
type Error = crate::Error;
/// # Errors
/// [`crate::Error::UnexpectedValue`] for an unknown code. Phase A: always [`crate::Error::Unimplemented`].
fn try_from(code: u32) -> crate::Result<Self> {
let _ = code;
Err(crate::Error::Unimplemented)
}
}
/// 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,
},
}
/// Serializes an event into a whole `INPUT_DATA` message.
///
/// # Errors
/// [`crate::Error::UnexpectedValue`] for a controller number above 15. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn encode_input(event: &InputEvent) -> crate::Result<Vec<u8>> {
let _ = event;
Err(crate::Error::Unimplemented)
}
/// Parses a whole `INPUT_DATA` message (inverse of [`encode_input`]).
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_INPUT_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
/// [`INPUT_HEADER_LEN`], [`crate::Error::Malformed`] when the length or size field does not match, the data length
/// is wrong for the type, or a constant differs; [`crate::Error::Unsupported`] for a type whose layout is UNKNOWN.
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_input(message: &[u8]) -> crate::Result<InputEvent> {
let _ = message;
Err(crate::Error::Unimplemented)
}
+38
View File
@@ -0,0 +1,38 @@
//! 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
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
let _ = rng;
Err(crate::Error::Unimplemented)
}
}
impl fmt::Debug for SessionKeys {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("SessionKeys").field("rikey", &"<redacted>").field("rikeyid", &self.rikeyid).finish()
}
}
+56
View File
@@ -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.
//!
//! **Phase A.** This crate holds the public API only. Every function that does protocol work returns
//! [`Error::Unimplemented`] (or `None` for `poll_*` functions); QA writes the mandatory tests against these
//! signatures before the logic lands. Plain data (constants, enum codes, field structs) is final.
//!
//! # 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;
pub mod video;
pub use entropy::RandomSource;
pub use error::{Error, Result};
pub use keys::SessionKeys;
pub use time::Instant;
+71
View File
@@ -0,0 +1,71 @@
//! 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 super::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN};
use crate::Result;
/// AES-128 key used for every encrypted pairing value.
pub type PairingKey = [u8; 16];
/// `K = SHA-256(salt ‖ PIN digits)[0..16]`.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result<PairingKey> {
let _ = (salt, pin);
Err(crate::Error::Unimplemented)
}
/// AES-128-ECB encryption without padding.
///
/// # Errors
/// [`crate::Error::Malformed`] when `data` is not a whole number of 16-byte blocks. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
let _ = (key, data);
Err(crate::Error::Unimplemented)
}
/// AES-128-ECB decryption without padding.
///
/// # Errors
/// As [`ecb_encrypt`].
pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
let _ = (key, data);
Err(crate::Error::Unimplemented)
}
/// `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 [`super::MAX_SIGNATURE_BYTES`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn proof_hash(
challenge: &[u8; CHALLENGE_LEN],
cert_signature: &[u8],
secret: &[u8; SECRET_LEN],
) -> Result<[u8; HASH_LEN]> {
let _ = (challenge, cert_signature, secret);
Err(crate::Error::Unimplemented)
}
/// 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. Phase A: always [`crate::Error::Unimplemented`].
pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> {
let _ = decrypted;
Err(crate::Error::Unimplemented)
}
/// 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
/// [`super::MAX_SIGNATURE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> {
let _ = pairing_secret;
Err(crate::Error::Unimplemented)
}
+156
View File
@@ -0,0 +1,156 @@
//! The client's certificate and key, and the host certificate learnt while pairing.
use core::fmt;
use crate::{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;
/// 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<u8>,
key_pkcs8_der: Vec<u8>,
}
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
/// [`crate::Error::Malformed`] for an empty or oversized `common_name`. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
let _ = (rng, common_name, not_before_unix);
Err(crate::Error::Unimplemented)
}
/// Loads a stored identity. Checks that the key matches the certificate.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`crate::Error::Malformed`]
/// for bad DER or a key that does not match. Phase A: always [`crate::Error::Unimplemented`].
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
let _ = (cert_der, key_pkcs8_der);
Err(crate::Error::Unimplemented)
}
/// 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
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn cert_pem(&self) -> Result<String> {
Err(crate::Error::Unimplemented)
}
/// The raw `signatureValue` bytes of the certificate (input to the pairing proofs).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn cert_signature(&self) -> Result<Vec<u8>> {
Err(crate::Error::Unimplemented)
}
/// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
let _ = data;
Err(crate::Error::Unimplemented)
}
}
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", &"<redacted>")
.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<u8>,
}
impl ServerCert {
/// Parses the PEM the host sent (already hex-decoded). Exactly one `CERTIFICATE` block.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`crate::Error::Malformed`] for anything that is
/// not one well-formed X.509 certificate with an RSA key. Phase A: always [`crate::Error::Unimplemented`].
pub fn from_pem(pem: &[u8]) -> Result<Self> {
let _ = pem;
Err(crate::Error::Unimplemented)
}
/// Loads a stored certificate.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`crate::Error::Malformed`] otherwise. Phase A:
/// always [`crate::Error::Unimplemented`].
pub fn from_der(der: &[u8]) -> Result<Self> {
let _ = der;
Err(crate::Error::Unimplemented)
}
/// The certificate, DER.
#[must_use]
pub fn der(&self) -> &[u8] {
&self.der
}
/// The raw `signatureValue` bytes (input to the pairing proofs).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn signature(&self) -> Result<Vec<u8>> {
Err(crate::Error::Unimplemented)
}
/// Verifies an RSASSA-PKCS1-v1_5 / SHA-256 `signature` over `data` with the certificate's public key.
///
/// # Errors
/// [`crate::Error::Crypto`] when it does not verify. Phase A: always [`crate::Error::Unimplemented`].
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
let _ = (data, signature);
Err(crate::Error::Unimplemented)
}
/// 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
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
let _ = presented_der;
Err(crate::Error::Unimplemented)
}
}
+205
View File
@@ -0,0 +1,205 @@
//! 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`].
use core::fmt;
use crate::http::HttpRequest;
use crate::{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;
/// A 4-digit GameStream PIN.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Pin([u8; PIN_LEN]);
impl Pin {
/// Draws a uniformly random PIN (no modulo bias).
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
let _ = rng;
Err(crate::Error::Unimplemented)
}
/// Parses exactly four ASCII digits.
///
/// # Errors
/// [`crate::Error::Malformed`] for anything else. Phase A: always [`crate::Error::Unimplemented`].
pub fn from_digits(digits: &str) -> Result<Self> {
let _ = digits;
Err(crate::Error::Unimplemented)
}
/// 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(<redacted>)")
}
}
/// 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 (`<root status_code="200"><paired>1</paired>…</root>`), 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<Vec<u8>>,
/// `challengeresponse`: `E_K(H_s ‖ S_c)`, 48 bytes (step 2).
pub challenge_response: Option<Vec<u8>>,
/// `pairingsecret`: `secret_s ‖ signature` (step 3).
pub pairing_secret: Option<Vec<u8>>,
}
/// Parses one pairing answer.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`crate::Error::HostStatus`] for a non-200
/// answer, [`crate::Error::Malformed`] for bad hex or a missing `paired`. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_pair_response(body: &[u8]) -> Result<PairResponse> {
let _ = body;
Err(crate::Error::Unimplemented)
}
/// One pairing attempt with one host.
pub struct PairingSession {
state: PairingState,
}
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
/// [`crate::Error::Malformed`] for a bad `unique_id` or `device_name`. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn start(
identity: &ClientIdentity,
unique_id: &str,
device_name: &str,
pin: Pin,
rng: &mut dyn RandomSource,
) -> Result<(Self, HttpRequest)> {
let _ = (identity, unique_id, device_name, pin, rng);
Err(crate::Error::Unimplemented)
}
/// 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
/// [`crate::Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as
/// [`parse_pair_response`], [`crate::Error::State`] after `Paired` or `Failed`, [`crate::Error::Malformed`] for
/// a different identity than at the start. Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_response(
&mut self,
identity: &ClientIdentity,
http_status: u16,
body: &[u8],
rng: &mut dyn RandomSource,
) -> Result<PairingStep> {
let _ = (identity, http_status, body, rng);
Err(crate::Error::Unimplemented)
}
/// 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()
}
}
+33
View File
@@ -0,0 +1,33 @@
//! 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.
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_rtp_header(packet: &[u8]) -> crate::Result<RtpHeader> {
let _ = packet;
Err(crate::Error::Unimplemented)
}
+151
View File
@@ -0,0 +1,151 @@
//! 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::{EncryptionFlags, HostCapabilities, OpusConfig};
use crate::http::launch::AudioLayout;
/// 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<String>,
/// 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<u8>,
}
/// 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,
}
impl RtspClient {
/// Prepares the negotiation against `session_url` (`sessionUrl0` from launch). The first request (OPTIONS)
/// is ready in [`Self::poll_request`].
///
/// # Errors
/// [`crate::Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame
/// rate, bitrate or packet size. Phase A: always [`crate::Error::Unimplemented`].
pub fn new(session_url: &str, config: StreamConfig) -> crate::Result<Self> {
let _ = (session_url, config);
Err(crate::Error::Unimplemented)
}
/// The next request to write, if one is due. Each is returned once.
pub fn poll_request(&mut self) -> Option<Vec<u8>> {
None
}
/// Feeds one whole answer (see [`super::RtspFramer`]).
///
/// # Errors
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `CSeq` that does not
/// match or a bad payload, [`crate::Error::Unsupported`] when the host lacks something required,
/// [`crate::Error::State`] when no request is outstanding. Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_response(&mut self, message: &[u8]) -> crate::Result<RtspProgress> {
let _ = message;
Err(crate::Error::Unimplemented)
}
/// Where the negotiation is.
#[must_use]
pub const fn state(&self) -> RtspClientState {
self.state
}
}
+149
View File
@@ -0,0 +1,149 @@
//! 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};
/// 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 methods this client sends.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Method {
/// `OPTIONS`.
Options,
/// `DESCRIBE`.
Describe,
/// `SETUP`.
Setup,
/// `ANNOUNCE`.
Announce,
/// `PLAY`.
Play,
}
/// 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<u8>,
}
impl RtspRequest {
/// Serializes the request (CRLF line ends, empty line, payload). Refuses CR or LF inside a target, header
/// name or value.
///
/// # Errors
/// [`crate::Error::Malformed`] for a forbidden character, [`crate::Error::TooLarge`] over
/// [`MAX_RTSP_MESSAGE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn encode(&self) -> crate::Result<Vec<u8>> {
Err(crate::Error::Unimplemented)
}
}
/// 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<u8>,
}
impl RtspResponse {
/// The first header with this name, compared case-insensitively.
#[must_use]
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
}
/// Parses one complete response (as cut by [`RtspFramer`]).
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`],
/// [`crate::Error::Malformed`] for a bad start line, header line or `Content-Length`. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_response(message: &[u8]) -> crate::Result<RtspResponse> {
let _ = message;
Err(crate::Error::Unimplemented)
}
/// 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 [`crate::Error::UnexpectedValue`] for an unknown method.
pub fn parse_request(message: &[u8]) -> crate::Result<RtspRequest> {
let _ = message;
Err(crate::Error::Unimplemented)
}
/// 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<u8>,
}
impl RtspFramer {
/// An empty framer.
#[must_use]
pub const fn new() -> Self {
Self { buffer: Vec::new() }
}
/// Appends received bytes.
///
/// # Errors
/// [`crate::Error::TooLarge`] when the unfinished message would exceed [`MAX_RTSP_MESSAGE_BYTES`]. Phase A:
/// always [`crate::Error::Unimplemented`].
pub fn push(&mut self, bytes: &[u8]) -> crate::Result<()> {
let _ = bytes;
Err(crate::Error::Unimplemented)
}
/// Takes the next complete message, if one is buffered.
///
/// # Errors
/// [`crate::Error::Malformed`] for a bad `Content-Length`. Phase A: always [`crate::Error::Unimplemented`].
pub fn next_message(&mut self) -> crate::Result<Option<Vec<u8>>> {
Err(crate::Error::Unimplemented)
}
/// The host closed the connection: returns what is buffered as the last message, if anything.
///
/// # Errors
/// [`crate::Error::Truncated`] when a `Content-Length` promised more. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn finish(&mut self) -> crate::Result<Option<Vec<u8>>> {
Err(crate::Error::Unimplemented)
}
/// Bytes buffered but not yet returned.
#[must_use]
pub fn buffered(&self) -> usize {
self.buffer.len()
}
}
+126
View File
@@ -0,0 +1,126 @@
//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4).
use super::client::StreamConfig;
/// 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.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`crate::Error::Malformed`] for a line
/// that is not UTF-8 or has no `=`. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_sdp(payload: &[u8]) -> crate::Result<Sdp> {
let _ = payload;
Err(crate::Error::Unimplemented)
}
/// 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;
}
/// 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<u8>,
}
/// Parses one `surround-params` value (single digits: channels, streams, coupled, then one mapping digit per
/// channel), e.g. `21101`.
///
/// # Errors
/// [`crate::Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules
/// (`coupled ≤ streams`, `streams + coupled ≤ 255`, mapping entries `< streams + coupled`). Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_surround_params(value: &str) -> crate::Result<OpusConfig> {
let _ = value;
Err(crate::Error::Unimplemented)
}
/// 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<OpusConfig>,
}
impl HostCapabilities {
/// Reads the capabilities from a DESCRIBE payload.
///
/// # Errors
/// [`crate::Error::Malformed`] for a present attribute with a bad value, [`crate::Error::TooLarge`] over
/// [`MAX_OPUS_CONFIGS`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn from_sdp(sdp: &Sdp) -> crate::Result<Self> {
let _ = sdp;
Err(crate::Error::Unimplemented)
}
}
/// Builds the ANNOUNCE payload for `config`, turning on the encryption flags both sides support.
///
/// # Errors
/// [`crate::Error::Unsupported`] when the host lacks control V2 encryption or the requested codec. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> crate::Result<Vec<u8>> {
let _ = (config, host);
Err(crate::Error::Unimplemented)
}
+39
View File
@@ -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))
}
}
+165
View File
@@ -0,0 +1,165 @@
//! 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.
//!
//! Lost frames become [`VideoEvent::FrameLost`], which the caller answers on the control stream with
//! `INVALIDATE_REF_FRAMES` (when the host supports it) or an IDR request.
use core::fmt;
use crate::{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;
/// AES-128-GCM for encrypted video packets (`docs/PROTOCOL.md` 7). `Debug` never prints the key.
#[derive(Clone)]
pub struct VideoCipher {
key: [u8; 16],
}
impl VideoCipher {
/// A cipher for `rikey`.
#[must_use]
pub const fn new(rikey: [u8; 16]) -> Self {
Self { key: rikey }
}
/// Decrypts one encrypted packet (`IV ‖ frame number ‖ tag ‖ ciphertext`) into the plaintext packet.
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under the
/// prefix, [`crate::Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`crate::Error::Crypto`] for a bad
/// tag. Phase A: always [`crate::Error::Unimplemented`].
pub fn decrypt(&self, packet: &[u8]) -> Result<Vec<u8>> {
let _ = (packet, &self.key);
Err(crate::Error::Unimplemented)
}
}
impl fmt::Debug for VideoCipher {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("VideoCipher(<redacted>)")
}
}
/// 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<VideoCipher>,
/// How long to wait for missing shards of a frame before declaring it lost.
pub frame_timeout: core::time::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<u8>,
/// 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,
}
/// The video receiver.
#[derive(Debug)]
pub struct VideoDepacketizer {
stats: VideoStats,
}
impl VideoDepacketizer {
/// A receiver for one stream.
///
/// # Errors
/// [`crate::Error::Malformed`] for a `packet_size` below the NV header size or above what fits in
/// [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn new(config: VideoConfig) -> Result<Self> {
let _ = config;
Err(crate::Error::Unimplemented)
}
/// 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
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
let _ = (now, datagram);
Err(crate::Error::Unimplemented)
}
/// The next event.
pub fn poll_event(&mut self) -> Option<VideoEvent> {
None
}
/// When an incomplete frame times out.
#[must_use]
pub fn poll_timeout(&self) -> Option<Instant> {
None
}
/// Declares timed-out frames lost.
///
/// # Errors
/// Phase A: always [`crate::Error::Unimplemented`].
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
let _ = now;
Err(crate::Error::Unimplemented)
}
/// Counters.
#[must_use]
pub const fn stats(&self) -> VideoStats {
self.stats
}
}
+123
View File
@@ -0,0 +1,123 @@
//! 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 (`shard_index < data + parity`,
/// `block_index <= last_block_index`, `data_shards > 0`).
///
/// # Errors
/// [`crate::Error::TooLarge`] over [`MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under
/// [`PAYLOAD_OFFSET`], [`crate::Error::Malformed`] for inconsistent FEC fields. Phase A: always
/// [`crate::Error::Unimplemented`].
pub fn parse_video_packet(packet: &[u8]) -> crate::Result<VideoPacket<'_>> {
let _ = packet;
Err(crate::Error::Unimplemented)
}
/// 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`]. Phase A: always [`crate::Error::Unimplemented`].
pub fn parse_frame_header(frame_data: &[u8]) -> crate::Result<FrameHeader> {
let _ = frame_data;
Err(crate::Error::Unimplemented)
}
+717
View File
@@ -0,0 +1,717 @@
//! 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),
}
};
}
// ------------------------------------------------------------------------------------------------ randomness
/// A seeded, deterministic random source (splitmix64). Never for production.
#[derive(Clone, Debug)]
pub struct SeqRng(u64);
impl SeqRng {
pub fn new(seed: u64) -> Self {
Self(seed)
}
pub fn next_u64(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
/// Uniform in `0..n` (n > 0); bias is irrelevant for test data.
pub fn below(&mut self, n: usize) -> usize {
(self.next_u64() % n as u64) as usize
}
pub fn bytes(&mut self, n: usize) -> Vec<u8> {
let mut v = vec![0; n];
self.fill(&mut v);
v
}
/// `count` distinct indices from `0..n`, sorted.
pub fn subset(&mut self, n: usize, count: usize) -> Vec<usize> {
let mut all: Vec<usize> = (0..n).collect();
for i in 0..count.min(n) {
let j = i + self.below(n - i);
all.swap(i, j);
}
let mut chosen = all[..count.min(n)].to_vec();
chosen.sort_unstable();
chosen
}
pub fn shuffle<T>(&mut self, items: &mut [T]) {
for i in (1..items.len()).rev() {
let j = self.below(i + 1);
items.swap(i, j);
}
}
}
impl RandomSource for SeqRng {
fn fill(&mut self, dest: &mut [u8]) {
for chunk in dest.chunks_mut(8) {
let word = self.next_u64().to_le_bytes();
chunk.copy_from_slice(&word[..chunk.len()]);
}
}
}
/// Hands out a fixed byte stream (a recorded transcript's randomness) and fails the test when the code under
/// test draws more than was recorded.
#[derive(Debug)]
pub struct ScriptedRng {
bytes: Vec<u8>,
pos: usize,
}
impl ScriptedRng {
pub fn new(bytes: Vec<u8>) -> Self {
Self { bytes, pos: 0 }
}
pub fn drawn(&self) -> usize {
self.pos
}
}
impl RandomSource for ScriptedRng {
fn fill(&mut self, dest: &mut [u8]) {
let end = self.pos + dest.len();
assert!(
end <= self.bytes.len(),
"the code drew {} random bytes but the recorded transcript holds only {} \
(fixture assumption: salt, then C, then secret_c, 16 bytes each)",
end,
self.bytes.len()
);
dest.copy_from_slice(&self.bytes[self.pos..end]);
self.pos = end;
}
}
// ------------------------------------------------------------------------------------------------ fixtures
pub fn hex(s: &str) -> Vec<u8> {
let s: String = s.chars().filter(|c| !c.is_whitespace()).collect();
if s == "-" {
return Vec::new();
}
assert!(s.len() % 2 == 0, "odd hex length");
(0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).expect("hex digit")).collect()
}
pub fn to_hex(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02x}")).collect()
}
pub fn to_hex_upper(b: &[u8]) -> String {
b.iter().map(|x| format!("{x:02X}")).collect()
}
/// A `name = value` fixture file written by `tools/vectors/gen_vectors.py`.
pub struct Vectors(HashMap<String, String>);
impl Vectors {
pub fn parse(text: &str) -> Self {
let mut map = HashMap::new();
for line in text.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let (k, v) = line.split_once(" = ").expect("fixture line `name = value`");
map.insert(k.to_string(), v.to_string());
}
Self(map)
}
pub fn str(&self, name: &str) -> &str {
self.0.get(name).unwrap_or_else(|| panic!("fixture value `{name}` missing"))
}
pub fn bytes(&self, name: &str) -> Vec<u8> {
hex(self.str(name))
}
pub fn arr16(&self, name: &str) -> [u8; 16] {
self.bytes(name).try_into().unwrap_or_else(|_| panic!("`{name}` is not 16 bytes"))
}
pub fn u32_hex(&self, name: &str) -> u32 {
u32::from_str_radix(self.str(name), 16).expect("hex u32")
}
}
pub fn pairing_vectors() -> Vectors {
Vectors::parse(include_str!("../fixtures/pairing.txt"))
}
pub fn control_vectors() -> Vectors {
Vectors::parse(include_str!("../fixtures/control_gcm.txt"))
}
pub fn video_vectors() -> Vectors {
Vectors::parse(include_str!("../fixtures/video_gcm.txt"))
}
pub fn audio_vectors() -> Vectors {
Vectors::parse(include_str!("../fixtures/audio_cbc.txt"))
}
pub const HOST_CERT_PEM: &str = include_str!("../fixtures/test-only-host-cert.pem");
pub const CLIENT_CERT_PEM: &str = include_str!("../fixtures/test-only-client-cert.pem");
pub const ROGUE_CERT_PEM: &str = include_str!("../fixtures/test-only-rogue-cert.pem");
pub const EC_CERT_PEM: &str = include_str!("../fixtures/test-only-ec-cert.pem");
pub const CLIENT_KEY_PEM: &str = include_str!("../fixtures/test-only-client-key.pem");
/// Base64 (RFC 4648, standard alphabet, padding allowed) to bytes; panics on anything else.
pub fn base64_decode(s: &str) -> Vec<u8> {
let mut out = Vec::new();
let mut acc = 0u32;
let mut bits = 0;
for c in s.bytes().filter(|c| !c.is_ascii_whitespace()) {
let v = match c {
b'A'..=b'Z' => c - b'A',
b'a'..=b'z' => c - b'a' + 26,
b'0'..=b'9' => c - b'0' + 52,
b'+' => 62,
b'/' => 63,
b'=' => break,
_ => panic!("not base64: {c:#x}"),
};
acc = (acc << 6) | u32::from(v);
bits += 6;
if bits >= 8 {
bits -= 8;
out.push((acc >> bits) as u8);
}
}
out
}
/// The DER inside every `-----BEGIN <label>-----` block of a PEM text.
pub fn pem_blocks(pem: &str, label: &str) -> Vec<Vec<u8>> {
let begin = format!("-----BEGIN {label}-----");
let end = format!("-----END {label}-----");
let mut out = Vec::new();
let mut rest = pem;
while let Some(start) = rest.find(&begin) {
let after = &rest[start + begin.len()..];
let stop = after.find(&end).expect("PEM end line");
out.push(base64_decode(&after[..stop]));
rest = &after[stop + end.len()..];
}
out
}
// ------------------------------------------------------------------------------------------------ HTTP helpers
/// Splits a `path?query` into the path and its decoded parameters, in order.
pub fn parse_query(path_and_query: &str) -> (String, Vec<(String, String)>) {
let (path, query) = path_and_query.split_once('?').unwrap_or((path_and_query, ""));
let params = query
.split('&')
.filter(|p| !p.is_empty())
.map(|p| {
let (k, v) = p.split_once('=').unwrap_or((p, ""));
(percent_decode(k), percent_decode(v))
})
.collect();
(path.to_string(), params)
}
pub fn percent_decode(s: &str) -> String {
let b = s.as_bytes();
let mut out = Vec::new();
let mut i = 0;
while i < b.len() {
if b[i] == b'%' && i + 2 < b.len() {
let h = std::str::from_utf8(&b[i + 1..i + 3]).expect("utf8");
out.push(u8::from_str_radix(h, 16).expect("percent escape"));
i += 3;
} else if b[i] == b'+' {
out.push(b' ');
i += 1;
} else {
out.push(b[i]);
i += 1;
}
}
String::from_utf8(out).expect("decoded query is UTF-8")
}
/// The single value of `name`; fails when it is missing or repeated (parameter injection).
pub fn param<'a>(params: &'a [(String, String)], name: &str) -> &'a str {
let found: Vec<&(String, String)> = params.iter().filter(|(k, _)| k == name).collect();
assert_eq!(found.len(), 1, "query parameter `{name}` must appear exactly once in {params:?}");
&found[0].1
}
/// `<root status_code="200">` + elements + `</root>`.
pub fn xml_root(status: u32, inner: &str) -> Vec<u8> {
format!("<root status_code=\"{status}\">{inner}</root>").into_bytes()
}
/// A child element sequence of exactly `len` bytes (`len >= 7`): `<x>aaa…</x>` pieces of at most 207 bytes, so no
/// single text is long and the element count stays small.
pub fn xml_filler(len: usize) -> String {
assert!(len >= 7, "filler needs at least 7 bytes");
let mut out = String::with_capacity(len);
let mut remaining = len;
while remaining > 0 {
let piece = if remaining <= 207 {
remaining
} else if remaining - 207 >= 7 {
207
} else {
remaining - 7
};
out.push_str("<x>");
out.extend(std::iter::repeat_n('a', piece - 7));
out.push_str("</x>");
remaining -= piece;
}
assert_eq!(out.len(), len);
out
}
/// A document `<root status_code="200">{inner}{filler}</root>` of exactly `total` bytes.
pub fn xml_padded_to(inner: &str, total: usize) -> Vec<u8> {
let bare = xml_root(200, inner).len();
assert!(total >= bare + 7, "target {total} too small for {bare} + filler");
let doc = xml_root(200, &format!("{inner}{}", xml_filler(total - bare)));
assert_eq!(doc.len(), total);
doc
}
/// All subsets of `0..n` with exactly `size` elements, in lexicographic order.
pub fn subsets_of(n: usize, size: usize) -> Vec<Vec<usize>> {
fn go(start: usize, n: usize, size: usize, cur: &mut Vec<usize>, out: &mut Vec<Vec<usize>>) {
if cur.len() == size {
out.push(cur.clone());
return;
}
for i in start..n {
cur.push(i);
go(i + 1, n, size, cur, out);
cur.pop();
}
}
let mut out = Vec::new();
go(0, n, size, &mut Vec::new(), &mut out);
out
}
// ------------------------------------------------------------------------------------------------ GF(2^8)
/// An independent GF(2^8) reference with polynomial 0x11D (`docs/PROTOCOL.md` 5.3), from the field definition.
pub mod gf {
pub fn mul(mut a: u8, mut b: u8) -> u8 {
let mut p = 0u8;
while b != 0 {
if b & 1 != 0 {
p ^= a;
}
let carry = a & 0x80 != 0;
a <<= 1;
if carry {
a ^= 0x1D;
}
b >>= 1;
}
p
}
pub fn inv(a: u8) -> u8 {
assert!(a != 0, "no inverse of 0");
(1..=255u8).find(|&b| mul(a, b) == 1).expect("field inverse")
}
/// A `rows × cols` Cauchy matrix `1 / (x_i + y_j)` with `x_i = i`, `y_j = rows + j`: every square submatrix is
/// invertible, so `[I; C]` is MDS.
pub fn cauchy(rows: usize, cols: usize) -> Vec<u8> {
assert!(rows + cols <= 256);
let mut m = Vec::with_capacity(rows * cols);
for i in 0..rows {
for j in 0..cols {
m.push(inv((i as u8) ^ ((rows + j) as u8)));
}
}
m
}
/// Parity shards for `data` with a row-major `parity × data` matrix.
pub fn encode(matrix: &[u8], data: &[Vec<u8>], parity: usize) -> Vec<Vec<u8>> {
let k = data.len();
let len = data[0].len();
(0..parity)
.map(|r| {
(0..len)
.map(|x| (0..k).fold(0u8, |acc, c| acc ^ mul(matrix[r * k + c], data[c][x])))
.collect()
})
.collect()
}
}
// ------------------------------------------------------------------------------------------------ video
/// One video packet as the test host built it.
#[derive(Clone, Debug)]
pub struct VPkt {
pub bytes: Vec<u8>,
pub frame_index: u32,
pub block: u8,
pub shard_index: u16,
pub data_shards: u16,
pub parity_shards: u16,
pub is_parity: bool,
}
/// What a frame should come out as.
#[derive(Clone, Debug)]
pub struct VExpect {
pub frame_index: u32,
pub header: [u8; 8],
pub bitstream: Vec<u8>,
pub rtp_timestamp: u32,
}
/// A test host that packetizes frames as `docs/PROTOCOL.md` 5.2-5.3 describe (Moonshine-style frame header).
#[derive(Clone, Debug)]
pub struct VideoHost {
pub packet_size: u16,
pub next_sequence: u16,
pub timestamp: u32,
/// When set, parity is computed over data shards whose bytes 0-31 are replaced by this pattern (a host may
/// compute parity before writing headers), so a recovered shard's header is guaranteed garbage.
pub scramble_parity_headers: bool,
}
impl VideoHost {
pub fn new(packet_size: u16) -> Self {
Self { packet_size, next_sequence: 0, timestamp: 90_000, scramble_parity_headers: false }
}
pub fn payload_len(&self) -> usize {
usize::from(self.packet_size) - 16
}
/// An Annex-B bitstream of about `len` bytes that ends in a nonzero byte (so trimming the zero padding by
/// either the frame header's length or the content gives the same answer: UNKNOWN U13).
pub fn bitstream(rng: &mut SeqRng, len: usize) -> Vec<u8> {
let mut b = vec![0, 0, 0, 1, 0x65];
b.extend(rng.bytes(len.saturating_sub(6)));
b.push(0x80 | rng.bytes(1)[0]);
b
}
/// Packetizes one frame into `blocks` FEC blocks at `fec_percentage`.
pub fn frame(
&mut self,
frame_index: u32,
bitstream: &[u8],
fec_percentage: u8,
blocks: usize,
) -> (Vec<VPkt>, VExpect) {
let payload_len = self.payload_len();
let total_len = 8 + bitstream.len();
let shards_total = total_len.div_ceil(payload_len);
let last_payload_len = total_len - (shards_total - 1) * payload_len;
let mut header = [0u8; 8];
header[0] = 0x01;
header[1..3].copy_from_slice(&7u16.to_le_bytes());
header[3] = 2; // key frame
header[4..8].copy_from_slice(&(last_payload_len as u32).to_le_bytes());
let mut data = header.to_vec();
data.extend_from_slice(bitstream);
data.resize(shards_total * payload_len, 0);
let blocks = blocks.clamp(1, 4).min(shards_total);
let base = shards_total / blocks;
let extra = shards_total % blocks;
let last_block = (blocks - 1) as u8;
let mut packets = Vec::new();
let mut shard_offset = 0;
for b in 0..blocks {
let k = base + usize::from(b < extra);
let m = (k * usize::from(fec_percentage)).div_ceil(100);
assert!(k + m <= 255, "test frame needs k + m <= 255");
let mut shards: Vec<Vec<u8>> = Vec::with_capacity(k + m);
for i in 0..k {
let global = shard_offset + i;
let mut flags = 0x01;
if global == 0 {
flags |= 0x04;
}
if global == shards_total - 1 {
flags |= 0x02;
}
let mut p = self.header(frame_index, flags, b as u8, last_block, i, k, fec_percentage);
p.extend_from_slice(&data[global * payload_len..(global + 1) * payload_len]);
shards.push(p);
}
if m > 0 {
let code = domistream::fec::ReedSolomon::new(k, m)
.expect("ReedSolomon::new for the test host (Phase A: Unimplemented)");
let shard_len = shards[0].len();
let mut work: Vec<Vec<u8>> = shards.clone();
if self.scramble_parity_headers {
for (i, s) in work.iter_mut().enumerate() {
for (x, byte) in s[..32].iter_mut().enumerate() {
*byte = (0xA5 ^ (i as u8).wrapping_mul(31) ^ (x as u8).wrapping_mul(7)) | 1;
}
}
}
work.extend((0..m).map(|_| vec![0u8; shard_len]));
code.encode(&mut work).expect("ReedSolomon::encode for the test host");
for j in 0..m {
let mut p = self.header(frame_index, 0, b as u8, last_block, k + j, k, fec_percentage);
p.extend_from_slice(&work[k + j][32..]);
shards.push(p);
}
}
for (i, bytes) in shards.into_iter().enumerate() {
packets.push(VPkt {
bytes,
frame_index,
block: b as u8,
shard_index: i as u16,
data_shards: k as u16,
parity_shards: m as u16,
is_parity: i >= k,
});
}
shard_offset += k;
}
let expect = VExpect { frame_index, header, bitstream: bitstream.to_vec(), rtp_timestamp: self.timestamp };
self.timestamp = self.timestamp.wrapping_add(1500);
(packets, expect)
}
/// RTP header + 4 reserved + NV header for the next sequence number (all packets of a frame share the
/// timestamp).
#[allow(clippy::too_many_arguments)]
fn header(
&mut self,
frame_index: u32,
flags: u8,
block: u8,
last_block: u8,
shard_index: usize,
data_shards: usize,
fec_percentage: u8,
) -> Vec<u8> {
let seq = self.next_sequence;
self.next_sequence = self.next_sequence.wrapping_add(1);
let mut p = Vec::with_capacity(usize::from(self.packet_size) + 16);
p.extend_from_slice(&[0x90, 0x00]);
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&self.timestamp.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(&[0; 4]);
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
p.extend_from_slice(&frame_index.to_le_bytes());
p.push(flags);
p.push(0);
p.push(0x10);
p.push((block << 4) | (last_block << 6));
let fec_info =
(u32::from(fec_percentage) << 4) | ((shard_index as u32) << 12) | ((data_shards as u32) << 22);
p.extend_from_slice(&fec_info.to_le_bytes());
p
}
}
/// Builds one NV video packet by hand from the field table (`docs/PROTOCOL.md` 5.2).
#[allow(clippy::too_many_arguments)]
pub fn video_packet_bytes(
seq: u16,
timestamp: u32,
frame_index: u32,
flags: u8,
multi_fec_blocks: u8,
fec_info: u32,
payload: &[u8],
) -> Vec<u8> {
let mut p = vec![0x90, 0x00];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&timestamp.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(&[0; 4]);
p.extend_from_slice(&(u32::from(seq) << 8).to_le_bytes());
p.extend_from_slice(&frame_index.to_le_bytes());
p.extend_from_slice(&[flags, 0, 0x10, multi_fec_blocks]);
p.extend_from_slice(&fec_info.to_le_bytes());
p.extend_from_slice(payload);
p
}
pub fn fec_info(fec_percentage: u8, shard_index: u16, data_shards: u16) -> u32 {
(u32::from(fec_percentage) << 4) | (u32::from(shard_index) << 12) | (u32::from(data_shards) << 22)
}
/// AES-128-GCM sealing of a plaintext video packet with the layout of `docs/PROTOCOL.md` 7, using RustCrypto as
/// the test oracle (checked against the .NET vectors in `media.rs`).
pub fn video_encrypt(key: &[u8; 16], counter: u64, frame_number: u32, plaintext: &[u8]) -> Vec<u8> {
use aes_gcm::aead::{AeadInOut, KeyInit};
let cipher = aes_gcm::Aes128Gcm::new_from_slice(key).expect("key");
let mut iv = [0u8; 12];
iv[..8].copy_from_slice(&counter.to_le_bytes());
iv[11] = b'V';
let mut buf = plaintext.to_vec();
let tag = cipher
.encrypt_inout_detached(&iv.into(), b"", buf.as_mut_slice().into())
.expect("gcm encrypt");
let mut out = iv.to_vec();
out.extend_from_slice(&frame_number.to_le_bytes());
out.extend_from_slice(tag.as_slice());
out.extend_from_slice(&buf);
out
}
// ------------------------------------------------------------------------------------------------ audio
/// AES-128-CBC + PKCS#7 with the audio IV of `docs/PROTOCOL.md` 6.3 (`rikeyid + seq`, wrapping), RustCrypto as
/// the test oracle (checked against the openssl vectors in `media.rs`).
pub fn audio_encrypt(key: &[u8; 16], rikeyid: u32, seq: u16, plaintext: &[u8]) -> Vec<u8> {
use cbc::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
let mut iv = [0u8; 16];
iv[..4].copy_from_slice(&rikeyid.wrapping_add(u32::from(seq)).to_be_bytes());
let mut buf = vec![0u8; (plaintext.len() / 16 + 1) * 16];
buf[..plaintext.len()].copy_from_slice(plaintext);
let len = cbc::Encryptor::<aes::Aes128>::new(key.into(), &iv.into())
.encrypt_padded::<Pkcs7>(&mut buf, plaintext.len())
.expect("cbc encrypt")
.len();
buf.truncate(len);
buf
}
/// One audio packet as the test host built it.
#[derive(Clone, Debug)]
pub struct APkt {
pub bytes: Vec<u8>,
pub sequence: u16,
pub block: usize,
/// 0..4 data, 4..6 parity.
pub index: usize,
}
/// What a data packet should come out as.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AExpect {
pub sequence: u16,
pub timestamp_ms: u32,
pub opus: Vec<u8>,
}
/// Parity packets' RTP sequence number: "continues after the 4 data packets" (PROTOCOL.md 6.2), read as
/// base + 4 + shard index. The depacketizer must key parity by the FEC header's base sequence, not by this.
pub fn audio_parity_rtp_sequence(base: u16, shard: u8) -> u16 {
base.wrapping_add(4).wrapping_add(u16::from(shard))
}
/// A test host for audio: blocks of 4 data + 2 parity packets (`docs/PROTOCOL.md` 6.2-6.4).
pub struct AudioHost {
pub key: [u8; 16],
pub rikeyid: u32,
pub encrypt: bool,
pub matrix: [u8; 8],
pub duration_ms: u32,
pub opus_len: usize,
}
impl AudioHost {
/// `blocks` consecutive blocks starting at `first_seq` (a multiple of 4) and `first_ts`.
pub fn blocks(&self, rng: &mut SeqRng, first_seq: u16, first_ts: u32, blocks: usize) -> (Vec<APkt>, Vec<AExpect>) {
assert_eq!(first_seq % 4, 0);
let mut packets = Vec::new();
let mut expect = Vec::new();
for b in 0..blocks {
let base_seq = first_seq.wrapping_add((4 * b) as u16);
let base_ts = first_ts.wrapping_add(4 * b as u32 * self.duration_ms);
let mut shards = Vec::new();
for i in 0..4u16 {
let seq = base_seq.wrapping_add(i);
let ts = base_ts.wrapping_add(u32::from(i) * self.duration_ms);
let opus = rng.bytes(self.opus_len);
let payload =
if self.encrypt { audio_encrypt(&self.key, self.rikeyid, seq, &opus) } else { opus.clone() };
let mut p = vec![0x80, 97];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&ts.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(&payload);
packets.push(APkt { bytes: p, sequence: seq, block: b, index: usize::from(i) });
expect.push(AExpect { sequence: seq, timestamp_ms: ts, opus });
shards.push(payload);
}
let parity = gf::encode(&self.matrix, &shards, 2);
for (j, par) in parity.iter().enumerate() {
let seq = audio_parity_rtp_sequence(base_seq, j as u8);
let mut p = vec![0x80, 127];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&base_ts.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.push(j as u8);
p.push(97);
p.extend_from_slice(&base_seq.to_be_bytes());
p.extend_from_slice(&base_ts.to_be_bytes());
p.extend_from_slice(&0u32.to_be_bytes());
p.extend_from_slice(par);
packets.push(APkt { bytes: p, sequence: seq, block: b, index: 4 + j });
}
}
(packets, expect)
}
}
/// The 2 × 4 Cauchy parity matrix the audio tests pass through `AudioFec::ParityMatrix` (U16 is unmeasured; any
/// MDS matrix must work).
pub fn audio_test_matrix() -> [u8; 8] {
gf::cauchy(2, 4).try_into().expect("2x4")
}
+663
View File
@@ -0,0 +1,663 @@
//! Hostile input for the HTTP side (`docs/PROTOCOL.md` 1.1-1.4): the XML reader, serverinfo, applist, launch and
//! status answers, and the request builders. Every case asserts a specific result.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{param, parse_query, xml_padded_to, xml_root};
use domistream::Error;
use domistream::http::xml::{self, MAX_XML_ATTRIBUTES, MAX_XML_BYTES, MAX_XML_DEPTH, MAX_XML_ELEMENTS, MAX_XML_TEXT_BYTES};
use domistream::http::{self, Scheme};
use proptest::prelude::*;
/// Asserts `Err(TooLarge { max, .. })` for caps where `actual` is a count the parser chooses how to report.
macro_rules! assert_cap {
($e:expr, $max:expr) => {
match $e {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
}
};
}
// ================================================================================================ XML
#[test]
fn xml_minimal_documents() {
let d = xml::parse(br#"<root status_code="200"/>"#).unwrap();
assert_eq!(d.status_code, 200);
assert_eq!(d.status_message, None);
assert_eq!(d.root.name, "root");
assert!(d.root.children.is_empty());
let d = xml::parse(br#"<?xml version="1.0" encoding="utf-8"?><root status_code="200"></root>"#).unwrap();
assert_eq!(d.status_code, 200);
let d = xml::parse(br#"<root status_code="401" status_message="The client is not authorized"/>"#).unwrap();
assert_eq!(d.status_code, 401, "xml::parse reports the status; refusing it is the callers' job");
assert_eq!(d.status_message.as_deref(), Some("The client is not authorized"));
}
#[test]
fn xml_tree_text_and_attributes() {
let d = xml::parse(br#"<root status_code="200" a="1"><x k="v&amp;w">t1<y/>t2</x><z>&lt;&gt;&amp;&quot;&apos;&#65;&#x42;</z></root>"#)
.unwrap();
assert_eq!(d.root.attributes, vec![("status_code".into(), "200".into()), ("a".into(), "1".into())]);
let x = &d.root.children[0];
assert_eq!(x.name, "x");
assert_eq!(x.attributes, vec![("k".into(), "v&w".into())]);
assert_eq!(x.text, "t1t2", "text is concatenated around child elements");
assert_eq!(x.children[0].name, "y");
assert_eq!(d.root.children[1].text, "<>&\"'AB");
}
#[test]
fn xml_text_is_not_trimmed() {
let d = xml::parse(b"<root status_code=\"200\"><a> x \n</a></root>").unwrap();
assert_eq!(d.root.children[0].text, " x \n");
}
#[test]
fn xml_empty_and_tiny_inputs() {
assert_err!(xml::parse(b""), Error::Malformed { .. });
assert_err!(xml::parse(b"<"), Error::Malformed { .. });
assert_err!(xml::parse(b"x"), Error::Malformed { .. });
assert_err!(xml::parse(b"<root"), Error::Malformed { .. });
assert_err!(xml::parse(b"<root status_code=\"200\">"), Error::Malformed { .. }, "unclosed root");
}
#[test]
fn xml_refuses_non_documents() {
for (bad, why) in [
(&br#"<other status_code="200"/>"#[..], "root must be `root`"),
(br#"<root/>"#, "no status_code"),
(br#"<root status_code="abc"/>"#, "status_code not decimal"),
(br#"<root status_code=""/>"#, "empty status_code"),
(br#"<root status_code="99999999999"/>"#, "status_code over u32"),
(br#"<root status_code="-200"/>"#, "negative status_code"),
(br#"<root status_code=200/>"#, "unquoted attribute"),
(br#"<root status_code="200" status_code="200"/>"#, "duplicate attribute"),
(br#"<root status_code="200"><a></b></root>"#, "mismatched end tag"),
(br#"<root status_code="200"><a></root>"#, "unclosed child"),
(br#"<root status_code="200"/><root status_code="200"/>"#, "two roots"),
(br#"<root status_code="200"/>garbage"#, "text after the root"),
(br#"<root status_code="200">&unknown;</root>"#, "unknown entity"),
(br#"<root status_code="200">&amp</root>"#, "entity without ;"),
(br#"<root status_code="200">a & b</root>"#, "bare &"),
(br#"<root status_code="200">&#0;</root>"#, "NUL character reference"),
(br#"<root status_code="200">&#xD800;</root>"#, "surrogate character reference"),
(br#"<root status_code="200">&#x110000;</root>"#, "character reference past Unicode"),
(br#"<root status_code="200">&#99999999999999999999;</root>"#, "overflowing character reference"),
(br#"<root status_code="200">&#xZZ;</root>"#, "bad hex reference"),
(br#"<root status_code="200"><a b="<"/></root>"#, "< in attribute value"),
(br#"<!DOCTYPE root><root status_code="200"/>"#, "DTD"),
(br#"<?xml version="1.0"?><!DOCTYPE r [<!ENTITY a "aaaa">]><root status_code="200">&a;</root>"#, "entity declaration"),
(br#"<root status_code="200"><?pi data?></root>"#, "processing instruction in the body"),
(br#" <?xml version="1.0"?><root status_code="200"/>"#, "XML declaration not at the start"),
(br#"<root xmlns:a="urn:x" status_code="200"><a:b/></root>"#, "namespaces"),
(b"<root status_code=\"200\">\xff\xfe</root>", "not UTF-8"),
(b"<root status_code=\"200\">\xc3</root>", "truncated UTF-8"),
(br#"<1root status_code="200"/>"#, "bad name"),
] {
assert_err!(xml::parse(bad), Error::Malformed { .. }, "{why}");
}
}
#[test]
fn xml_billion_laughs_is_refused_without_expansion() {
let mut doc = String::from("<?xml version=\"1.0\"?><!DOCTYPE lolz [<!ENTITY lol \"lol\">");
for i in 1..10 {
doc.push_str(&format!("<!ENTITY lol{i} \"{}\">", format!("&lol{};", i - 1).repeat(10)));
}
doc.push_str("]><root status_code=\"200\">&lol9;</root>");
assert_err!(xml::parse(doc.as_bytes()), Error::Malformed { .. });
}
#[test]
fn xml_size_boundaries() {
// max-1 and max are fine (a valid document of exactly that size), max+1 is refused before parsing.
for len in [MAX_XML_BYTES - 1, MAX_XML_BYTES] {
let d = xml::parse(&xml_padded_to("", len)).unwrap_or_else(|e| panic!("{len} bytes: {e:?}"));
assert_eq!(d.status_code, 200);
}
let over = xml_padded_to("", MAX_XML_BYTES + 1);
assert_too_large!(xml::parse(&over), MAX_XML_BYTES, MAX_XML_BYTES + 1);
// Huge: refused on size alone, whatever the content.
let huge = vec![b'<'; 4 * MAX_XML_BYTES];
assert_too_large!(xml::parse(&huge), MAX_XML_BYTES, 4 * MAX_XML_BYTES);
}
fn nested(depth: usize) -> Vec<u8> {
// root is depth 1
let mut s = String::from("<root status_code=\"200\">");
for _ in 1..depth {
s.push_str("<a>");
}
for _ in 1..depth {
s.push_str("</a>");
}
s.push_str("</root>");
s.into_bytes()
}
#[test]
fn xml_depth_cap() {
let d = xml::parse(&nested(MAX_XML_DEPTH)).unwrap();
let mut e = &d.root;
let mut depth = 1;
while let Some(c) = e.children.first() {
e = c;
depth += 1;
}
assert_eq!(depth, MAX_XML_DEPTH);
assert_cap!(xml::parse(&nested(MAX_XML_DEPTH + 1)), MAX_XML_DEPTH);
}
#[test]
fn xml_depth_bomb_does_not_recurse() {
// 300 000 open tags in under 1 MiB: a recursive parser overflows the stack; a strict one stops at depth 9.
let mut s = String::from("<root status_code=\"200\">");
s.push_str(&"<a>".repeat(300_000));
assert!(s.len() < MAX_XML_BYTES);
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
// Same with the closing tags present.
s.push_str(&"</a>".repeat(300_000));
s.push_str("</root>");
assert!(s.len() < MAX_XML_BYTES * 2);
if s.len() <= MAX_XML_BYTES {
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
}
}
#[test]
fn xml_element_cap() {
let ok = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS - 1));
assert_eq!(xml::parse(&ok).unwrap().root.children.len(), MAX_XML_ELEMENTS - 1);
let over = xml_root(200, &"<a/>".repeat(MAX_XML_ELEMENTS));
assert_cap!(xml::parse(&over), MAX_XML_ELEMENTS);
}
#[test]
fn xml_attribute_cap() {
let attrs = |n: usize| (1..n).map(|i| format!(" a{i}=\"{i}\"")).collect::<String>();
let ok = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES));
assert_eq!(xml::parse(ok.as_bytes()).unwrap().root.attributes.len(), MAX_XML_ATTRIBUTES);
let over = format!("<root status_code=\"200\"{}/>", attrs(MAX_XML_ATTRIBUTES + 1));
assert_cap!(xml::parse(over.as_bytes()), MAX_XML_ATTRIBUTES);
}
#[test]
fn xml_text_cap_counts_unescaped_bytes() {
let ok = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES)));
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
let over = xml_root(200, &format!("<t>{}</t>", "a".repeat(MAX_XML_TEXT_BYTES + 1)));
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
// 5 raw bytes per unescaped byte: the cap is on the result, not the input.
let ok = xml_root(200, &format!("<t>{}</t>", "&amp;".repeat(MAX_XML_TEXT_BYTES)));
assert_eq!(xml::parse(&ok).unwrap().root.children[0].text.len(), MAX_XML_TEXT_BYTES);
let over = xml_root(200, &format!("<t>{}</t>", "&amp;".repeat(MAX_XML_TEXT_BYTES + 1)));
assert_cap!(xml::parse(&over), MAX_XML_TEXT_BYTES);
}
// ------------------------------------------------------------------------------------------------ XML properties
#[derive(Clone, Debug)]
struct Tree {
name: String,
attrs: Vec<(String, String)>,
text: String,
children: Vec<Tree>,
}
fn escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
}
fn serialize(t: &Tree, out: &mut String) {
out.push('<');
out.push_str(&t.name);
for (k, v) in &t.attrs {
out.push_str(&format!(" {k}=\"{}\"", escape(v)));
}
out.push('>');
out.push_str(&escape(&t.text));
for c in &t.children {
serialize(c, out);
}
out.push_str(&format!("</{}>", t.name));
}
fn same(e: &xml::Element, t: &Tree) -> bool {
e.name == t.name
&& e.attributes == t.attrs
&& e.text == t.text
&& e.children.len() == t.children.len()
&& e.children.iter().zip(&t.children).all(|(a, b)| same(a, b))
}
fn tree(depth: u32) -> impl Strategy<Value = Tree> {
// No leading x/X: names starting with "xml" are reserved, and `xmlns` would be a namespace declaration.
let name = "[a-wA-W][a-zA-Z0-9_]{0,6}";
let text = "[ -~&<>\"'é]{0,12}";
let attrs = proptest::collection::btree_map("[a-w][a-z0-9]{0,4}", text, 0..3)
.prop_map(|m| m.into_iter().filter(|(k, _)| k != "status_code").collect::<Vec<_>>());
let leaf = (name, attrs.clone(), text).prop_map(|(name, attrs, text)| Tree {
name: name.to_string(),
attrs,
text,
children: vec![],
});
leaf.prop_recursive(depth, 24, 4, move |inner| {
("[a-wA-W][a-zA-Z0-9_]{0,6}", attrs.clone(), "[ -~]{0,8}", proptest::collection::vec(inner, 0..4)).prop_map(
|(name, attrs, text, children)| Tree { name, attrs, text, children },
)
})
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
/// Serialize a random tree (depth <= MAX_XML_DEPTH - 1 under root), parse it back, get the same tree.
#[test]
fn xml_round_trips_generated_trees(children in proptest::collection::vec(tree(5), 0..4), code in 100u32..600) {
let root = Tree {
name: "root".into(),
attrs: vec![("status_code".into(), code.to_string())],
text: String::new(),
children,
};
let mut s = String::new();
serialize(&root, &mut s);
let d = xml::parse(s.as_bytes()).map_err(|e| TestCaseError::fail(format!("{e:?} for {s}")))?;
prop_assert_eq!(d.status_code, code);
prop_assert!(same(&d.root, &root), "tree differs for {}", s);
}
/// Arbitrary bytes: never panics; any success respects every cap.
#[test]
fn xml_never_panics_and_respects_caps(data in proptest::collection::vec(any::<u8>(), 0..2048)) {
if let Ok(d) = xml::parse(&data) {
fn walk(e: &xml::Element, depth: usize, count: &mut usize) -> bool {
*count += 1;
depth <= MAX_XML_DEPTH
&& e.attributes.len() <= MAX_XML_ATTRIBUTES
&& e.text.len() <= MAX_XML_TEXT_BYTES
&& e.children.iter().all(|c| walk(c, depth + 1, count))
}
let mut count = 0;
prop_assert!(walk(&d.root, 1, &mut count));
prop_assert!(count <= MAX_XML_ELEMENTS);
prop_assert_eq!(d.root.name.as_str(), "root");
}
}
/// Mutating a valid document (one byte flipped, truncated) never panics, and truncation is always an error.
#[test]
fn xml_truncation_is_an_error(cut in 0usize..60) {
let doc = br#"<root status_code="200"><a k="v">text&amp;</a><b/></root>"#;
let cut = cut.min(doc.len() - 1);
prop_assert!(xml::parse(&doc[..cut]).is_err());
}
}
// ================================================================================================ serverinfo
const SERVERINFO: &str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">\n\
<hostname>LAB-PC</hostname>\n<appversion>7.1.431.-1</appversion>\n<GfeVersion>3.23.0.74</GfeVersion>\n\
<uniqueid>0123456789ABCDEF0123456789ABCDEF</uniqueid>\n<HttpsPort>47984</HttpsPort>\n\
<ExternalPort>47989</ExternalPort>\n<mac>00:11:22:aa:BB:ff</mac>\n<LocalIP>192.0.2.10</LocalIP>\n\
<MaxLumaPixelsHEVC>1869449984</MaxLumaPixelsHEVC>\n<ServerCodecModeSupport>259</ServerCodecModeSupport>\n\
<SupportedDisplayMode></SupportedDisplayMode>\n<PairStatus>0</PairStatus>\n<currentgame>0</currentgame>\n\
<state>SUNSHINE_SERVER_FREE</state>\n</root>\n";
fn serverinfo_with(field: &str, value: Option<&str>) -> Vec<u8> {
let open = format!("<{field}>");
let close = format!("</{field}>");
let start = SERVERINFO.find(&open).unwrap_or_else(|| panic!("{field} in sample"));
let end = SERVERINFO[start..].find(&close).unwrap() + start + close.len();
let replacement = value.map(|v| format!("{open}{v}{close}")).unwrap_or_default();
format!("{}{}{}", &SERVERINFO[..start], replacement, &SERVERINFO[end..]).into_bytes()
}
#[test]
fn serverinfo_sample() {
let s = http::parse_server_info(SERVERINFO.as_bytes()).unwrap();
assert_eq!(s.hostname, "LAB-PC");
assert_eq!(s.app_version, "7.1.431.-1");
assert_eq!(s.gfe_version.as_deref(), Some("3.23.0.74"));
assert_eq!(s.unique_id, "0123456789ABCDEF0123456789ABCDEF");
assert_eq!(s.https_port, 47984);
assert_eq!(s.http_port, Some(47989));
assert_eq!(s.mac, Some([0x00, 0x11, 0x22, 0xAA, 0xBB, 0xFF]));
assert_eq!(s.local_ip.as_deref(), Some("192.0.2.10"));
assert_eq!(s.max_luma_pixels_hevc, Some(1_869_449_984));
assert_eq!(s.codec_mode_support, Some(259));
assert!(!s.paired);
assert_eq!(s.current_game, 0);
assert_eq!(s.state, "SUNSHINE_SERVER_FREE");
assert!(!s.is_busy().unwrap());
}
#[test]
fn serverinfo_optional_fields() {
let s = http::parse_server_info(&serverinfo_with("mac", Some(""))).unwrap();
assert_eq!(s.mac, None, "empty mac is None");
let s = http::parse_server_info(&serverinfo_with("GfeVersion", None)).unwrap();
assert_eq!(s.gfe_version, None);
let s = http::parse_server_info(&serverinfo_with("ExternalPort", None)).unwrap();
assert_eq!(s.http_port, None);
let s = http::parse_server_info(&serverinfo_with("PairStatus", Some("1"))).unwrap();
assert!(s.paired);
}
#[test]
fn serverinfo_busy() {
let s = http::parse_server_info(&serverinfo_with("state", Some("SUNSHINE_SERVER_BUSY"))).unwrap();
assert!(s.is_busy().unwrap());
let s = http::parse_server_info(&serverinfo_with("currentgame", Some("881448767"))).unwrap();
assert_eq!(s.current_game, 881_448_767);
assert!(s.is_busy().unwrap());
}
#[test]
fn serverinfo_refuses_bad_fields() {
for field in ["hostname", "uniqueid", "HttpsPort"] {
assert_err!(http::parse_server_info(&serverinfo_with(field, None)), Error::Malformed { .. }, "missing {field}");
}
for (field, value) in [
("HttpsPort", "70000"),
("HttpsPort", "-1"),
("HttpsPort", ""),
("HttpsPort", "0x1F"),
("HttpsPort", " 47984"),
("ExternalPort", "65536"),
("currentgame", "abc"),
("currentgame", "4294967296"),
("MaxLumaPixelsHEVC", "1e9"),
("ServerCodecModeSupport", "-3"),
("mac", "00:11:22:33:44"),
("mac", "00:11:22:33:44:55:66"),
("mac", "zz:11:22:33:44:55"),
] {
assert_err!(
http::parse_server_info(&serverinfo_with(field, Some(value))),
Error::Malformed { .. },
"{field}={value:?}"
);
}
}
#[test]
fn serverinfo_field_cap() {
use domistream::http::serverinfo::MAX_SERVERINFO_FIELD_BYTES as MAX;
let ok = "h".repeat(MAX);
assert_eq!(http::parse_server_info(&serverinfo_with("hostname", Some(&ok))).unwrap().hostname, ok);
assert_cap!(http::parse_server_info(&serverinfo_with("hostname", Some(&"h".repeat(MAX + 1)))), MAX);
assert_cap!(http::parse_server_info(&serverinfo_with("state", Some(&"s".repeat(MAX + 1)))), MAX);
}
#[test]
fn serverinfo_status_and_sizes() {
use domistream::http::serverinfo::MAX_SERVERINFO_BYTES as MAX;
assert_err!(http::parse_server_info(&xml_root(503, "")), Error::HostStatus { code: 503 });
assert_err!(http::parse_server_info(b""), Error::Malformed { .. });
assert_err!(http::parse_server_info(b"<"), Error::Malformed { .. });
let inner = SERVERINFO
.trim_start_matches("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root status_code=\"200\">")
.trim_end_matches("</root>\n");
for len in [MAX - 1, MAX] {
let s = http::parse_server_info(&xml_padded_to(inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(s.hostname, "LAB-PC");
}
assert_too_large!(http::parse_server_info(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
assert_too_large!(http::parse_server_info(&vec![b' '; 64 * MAX]), MAX, 64 * MAX);
}
// ================================================================================================ applist
#[test]
fn applist_sample() {
let body = xml_root(
200,
"<App><IsHdrSupported>1</IsHdrSupported><AppTitle>Desktop</AppTitle><ID>881448767</ID></App>\
<App><AppTitle>Steam &amp; Friends</AppTitle><ID>2</ID><IsHdrSupported>0</IsHdrSupported></App>\
<App><AppTitle>No HDR field</AppTitle><ID>3</ID></App>",
);
let apps = http::parse_app_list(&body).unwrap();
assert_eq!(
apps,
vec![
http::App { id: 881_448_767, title: "Desktop".into(), hdr_supported: true },
http::App { id: 2, title: "Steam & Friends".into(), hdr_supported: false },
http::App { id: 3, title: "No HDR field".into(), hdr_supported: false },
]
);
assert_eq!(http::parse_app_list(&xml_root(200, "")).unwrap(), vec![]);
}
#[test]
fn applist_refuses_bad_apps() {
for (inner, why) in [
("<App><AppTitle>A</AppTitle></App>", "no ID"),
("<App><ID>1</ID></App>", "no AppTitle"),
("<App><AppTitle>A</AppTitle><ID>-1</ID></App>", "negative ID"),
("<App><AppTitle>A</AppTitle><ID>abc</ID></App>", "ID not decimal"),
("<App><AppTitle>A</AppTitle><ID>4294967296</ID></App>", "ID over u32"),
("<App><AppTitle>A</AppTitle><ID>1</ID></App><App><AppTitle>B</AppTitle><ID>1</ID></App>", "duplicate ID"),
] {
assert_err!(http::parse_app_list(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
}
assert_err!(http::parse_app_list(&xml_root(401, "")), Error::HostStatus { code: 401 });
}
#[test]
fn applist_caps() {
use domistream::http::applist::{MAX_APP_TITLE_BYTES, MAX_APPLIST_BYTES, MAX_APPS};
let app = |i: usize, title: &str| format!("<App><AppTitle>{title}</AppTitle><ID>{i}</ID></App>");
let t = "t".repeat(MAX_APP_TITLE_BYTES);
assert_eq!(http::parse_app_list(&xml_root(200, &app(1, &t))).unwrap()[0].title, t);
assert_cap!(http::parse_app_list(&xml_root(200, &app(1, &"t".repeat(MAX_APP_TITLE_BYTES + 1)))), MAX_APP_TITLE_BYTES);
// Multi-byte titles: the cap is in bytes.
assert_cap!(http::parse_app_list(&xml_root(200, &app(1, &"é".repeat(MAX_APP_TITLE_BYTES / 2 + 1)))), MAX_APP_TITLE_BYTES);
let list = |n: usize| (0..n).map(|i| app(i, "g")).collect::<String>();
assert_eq!(http::parse_app_list(&xml_root(200, &list(MAX_APPS))).unwrap().len(), MAX_APPS);
assert_cap!(http::parse_app_list(&xml_root(200, &list(MAX_APPS + 1))), MAX_APPS);
let inner = app(1, "Desktop");
for len in [MAX_APPLIST_BYTES - 1, MAX_APPLIST_BYTES] {
let apps = http::parse_app_list(&xml_padded_to(&inner, len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(apps.len(), 1, "unknown elements are ignored");
}
assert_too_large!(http::parse_app_list(&xml_padded_to(&inner, MAX_APPLIST_BYTES + 1)), MAX_APPLIST_BYTES, MAX_APPLIST_BYTES + 1);
assert_too_large!(http::parse_app_list(&vec![b'<'; 3 * MAX_APPLIST_BYTES]), MAX_APPLIST_BYTES, 3 * MAX_APPLIST_BYTES);
}
// ================================================================================================ launch
#[test]
fn launch_response_sample() {
let r = http::parse_launch_response(&xml_root(
200,
"<sessionUrl0>rtsp://192.0.2.10:48010</sessionUrl0><gamesession>1</gamesession>",
))
.unwrap();
assert!(r.game_session);
assert_eq!(r.session_url.as_deref(), Some("rtsp://192.0.2.10:48010"));
let r = http::parse_launch_response(&xml_root(200, "<gamesession>1</gamesession>")).unwrap();
assert_eq!(r.session_url, None, "missing sessionUrl0 is None (UNKNOWN U4)");
let r = http::parse_launch_response(&xml_root(200, "<gamesession>0</gamesession>")).unwrap();
assert!(!r.game_session);
}
#[test]
fn launch_response_refuses_bad_urls() {
for url in [
"http://192.0.2.10:48010",
"rtsp://192.0.2.10",
"rtsp://192.0.2.10:",
"rtsp://192.0.2.10:99999",
"rtsp://192.0.2.10:-1",
"rtsp://:48010",
"rtsp://192.0.2.10:48010\r\nCSeq: 9",
"rtsp://192.0.2.10:48a",
"",
] {
let body = xml_root(200, &format!("<sessionUrl0>{url}</sessionUrl0><gamesession>1</gamesession>"));
assert_err!(http::parse_launch_response(&body), Error::Malformed { .. }, "{url:?}");
}
}
#[test]
fn launch_response_caps() {
use domistream::http::launch::{MAX_LAUNCH_RESPONSE_BYTES as MAX, MAX_SESSION_URL_BYTES as URL};
let prefix = "rtsp://";
let suffix = ":48010";
// A host name of DNS labels of 9 letters, so only the length is unusual.
let host = |n: usize| {
let len = n - prefix.len() - suffix.len();
(0..len).map(|i| if i % 10 == 9 && i + 1 < len { '.' } else { 'h' }).collect::<String>()
};
let ok = format!("{prefix}{}{suffix}", host(URL));
let r = http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{ok}</sessionUrl0>"))).unwrap();
assert_eq!(r.session_url.as_deref(), Some(ok.as_str()));
let over = format!("{prefix}{}{suffix}", host(URL + 1));
assert_cap!(http::parse_launch_response(&xml_root(200, &format!("<sessionUrl0>{over}</sessionUrl0>"))), URL);
let inner = "<gamesession>1</gamesession>";
for len in [MAX - 1, MAX] {
assert!(http::parse_launch_response(&xml_padded_to(inner, len)).unwrap().game_session);
}
assert_too_large!(http::parse_launch_response(&xml_padded_to(inner, MAX + 1)), MAX, MAX + 1);
assert_too_large!(http::parse_launch_response(&vec![0u8; 1 << 20]), MAX, 1 << 20);
assert_err!(http::parse_launch_response(&xml_root(503, "")), Error::HostStatus { code: 503 });
assert_err!(http::parse_launch_response(b""), Error::Malformed { .. });
}
#[test]
fn status_response() {
assert_eq!(http::parse_status_response(&xml_root(200, "")), Ok(()));
assert_err!(http::parse_status_response(&xml_root(404, "")), Error::HostStatus { code: 404 });
assert_err!(http::parse_status_response(b"OK"), Error::Malformed { .. });
assert_err!(http::parse_status_response(b""), Error::Malformed { .. });
assert_too_large!(http::parse_status_response(&vec![b' '; MAX_XML_BYTES + 1]), MAX_XML_BYTES, MAX_XML_BYTES + 1);
}
// ================================================================================================ requests
const UID: &str = "0123456789ABCDEF";
#[test]
fn simple_requests() {
let r = http::server_info_request(Scheme::Http, UID).unwrap();
assert_eq!(r.scheme, Scheme::Http);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/serverinfo");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(http::server_info_request(Scheme::Https, UID).unwrap().scheme, Scheme::Https);
for (r, want) in [
(http::app_list_request(UID).unwrap(), "/applist"),
(http::cancel_request(UID).unwrap(), "/cancel"),
(http::unpair_request(UID).unwrap(), "/unpair"),
] {
assert_eq!(r.scheme, Scheme::Https, "{want} goes over HTTPS");
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, want);
assert_eq!(param(&q, "uniqueid"), UID);
}
}
#[test]
fn requests_refuse_bad_unique_ids() {
use domistream::http::MAX_UNIQUE_ID_BYTES as MAX;
for bad in [String::new(), "a".repeat(MAX + 1)] {
assert_err!(http::server_info_request(Scheme::Http, &bad), Error::Malformed { .. });
assert_err!(http::app_list_request(&bad), Error::Malformed { .. });
assert_err!(http::cancel_request(&bad), Error::Malformed { .. });
assert_err!(http::unpair_request(&bad), Error::Malformed { .. });
}
assert!(http::server_info_request(Scheme::Http, &"a".repeat(MAX)).is_ok());
}
#[test]
fn requests_cannot_be_injected() {
// A unique id with query syntax is refused or encoded; it never adds a parameter.
for evil in ["a&uniqueid=b", "a#frag", "a b", "a\r\nX: y", "a=b", "%26"] {
match http::server_info_request(Scheme::Http, evil) {
Err(Error::Malformed { .. }) => {}
Ok(r) => {
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/serverinfo");
assert_eq!(param(&q, "uniqueid"), evil);
assert!(!r.path_and_query.contains(['\r', '\n', ' ', '#']), "{:?}", r.path_and_query);
}
other => panic!("{evil:?}: {other:?}"),
}
}
}
fn launch_params() -> http::LaunchParams {
http::LaunchParams {
app_id: 881_448_767,
width: 1920,
height: 1080,
fps: 60,
keys: domistream::SessionKeys { rikey: *b"\x00\x11\x22\x33\x44\x55\x66\x77\x88\x99\xaa\xbb\xcc\xdd\xee\xff", rikeyid: 1_234_567 },
hdr: false,
audio: http::launch::AudioLayout::Stereo,
}
}
#[test]
fn launch_request_parameters() {
let r = http::launch::launch_request(&launch_params(), UID).unwrap();
assert_eq!(r.scheme, Scheme::Https);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/launch");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(param(&q, "appid"), "881448767");
assert_eq!(param(&q, "mode"), "1920x1080x60");
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
assert_eq!(param(&q, "rikeyid"), "1234567");
assert_eq!(param(&q, "hdrMode"), "0");
assert_eq!(param(&q, "surroundAudioInfo"), "196610", "stereo = 0x30002");
let mut p = launch_params();
p.hdr = true;
let (_, q) = parse_query(&http::launch::launch_request(&p, UID).unwrap().path_and_query);
assert_eq!(param(&q, "hdrMode"), "1");
for broken in [
http::LaunchParams { width: 0, ..launch_params() },
http::LaunchParams { height: 0, ..launch_params() },
http::LaunchParams { fps: 0, ..launch_params() },
] {
assert_err!(http::launch::launch_request(&broken, UID), Error::Malformed { .. });
}
assert_err!(http::launch::launch_request(&launch_params(), ""), Error::Malformed { .. });
}
#[test]
fn resume_request_parameters() {
let keys = launch_params().keys;
let r = http::launch::resume_request(&keys, UID).unwrap();
assert_eq!(r.scheme, Scheme::Https);
let (path, q) = parse_query(&r.path_and_query);
assert_eq!(path, "/resume");
assert_eq!(param(&q, "rikey").to_lowercase(), "00112233445566778899aabbccddeeff");
assert_eq!(param(&q, "rikeyid"), "1234567");
assert_err!(http::launch::resume_request(&keys, ""), Error::Malformed { .. });
}
#[test]
fn session_keys_are_fresh() {
let a = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
let b = domistream::SessionKeys::generate(&mut common::SeqRng::new(2)).unwrap();
let a2 = domistream::SessionKeys::generate(&mut common::SeqRng::new(1)).unwrap();
assert_eq!(a, a2, "keys come only from the caller's randomness");
assert_ne!(a.rikey, b.rikey);
assert_ne!(a.rikey, [0; 16]);
}
+258
View File
@@ -0,0 +1,258 @@
//! Repository rules that are checked by reading the crate itself: the sans-I/O guard (no sockets, clocks,
//! threads, files or OS randomness in `src/`), `forbid(unsafe_code)`, and that `Debug` never prints a secret.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use std::path::{Path, PathBuf};
/// Things `src/` must never contain outside comments (CLAUDE.md "Sans-I/O"). The left side is matched with all
/// whitespace removed, so `std :: net` and `use std::{fs, net}` are caught too.
const FORBIDDEN: &[(&str, &str)] = &[
("std::net", "sockets"),
("Instant::now", "clock reads"),
("SystemTime::now", "clock reads"),
("std::time::Instant", "the std clock type (use crate::Instant)"),
("std::time::SystemTime", "the std clock type"),
("UNIX_EPOCH", "clock reads"),
("std::thread", "threads"),
("thread::spawn", "threads"),
("std::fs", "files"),
("File::open", "files"),
("File::create", "files"),
("std::process", "processes"),
("std::env::var", "environment reads"),
("OsRng", "OS randomness (randomness comes in through RandomSource)"),
("thread_rng", "OS randomness"),
("getrandom", "OS randomness"),
("rand::random", "OS randomness"),
("tokio", "async runtimes"),
("mio::", "async runtimes"),
];
/// Grouped imports `use std::{…}` naming a forbidden module.
const FORBIDDEN_IN_STD_GROUP: &[&str] = &["net", "fs", "thread", "process"];
fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
for entry in std::fs::read_dir(dir).expect("read src dir") {
let path = entry.expect("dir entry").path();
if path.is_dir() {
rust_files(&path, out);
} else if path.extension().is_some_and(|e| e == "rs") {
out.push(path);
}
}
}
/// The code of a file with `//` comments (line and doc comments) and `/* */` comments removed. String literals are
/// kept: a forbidden name inside a string still fails, on purpose.
fn strip_comments(src: &str) -> String {
let mut out = String::with_capacity(src.len());
let mut chars = src.chars().peekable();
let mut in_str = false;
while let Some(c) = chars.next() {
if in_str {
out.push(c);
if c == '\\' {
if let Some(n) = chars.next() {
out.push(n);
}
} else if c == '"' {
in_str = false;
}
continue;
}
match (c, chars.peek()) {
('"', _) => {
in_str = true;
out.push(c);
}
('/', Some('/')) => {
for n in chars.by_ref() {
if n == '\n' {
out.push('\n');
break;
}
}
}
('/', Some('*')) => {
chars.next();
let mut prev = ' ';
for n in chars.by_ref() {
if prev == '*' && n == '/' {
break;
}
prev = n;
}
}
_ => out.push(c),
}
}
out
}
fn violations_in(code: &str) -> Vec<String> {
let squashed: String = code.chars().filter(|c| !c.is_whitespace()).collect();
let mut found = Vec::new();
for (needle, why) in FORBIDDEN {
if squashed.contains(needle) {
found.push(format!("`{needle}` ({why})"));
}
}
let mut rest = squashed.as_str();
while let Some(i) = rest.find("std::{") {
let group = &rest[i + 6..];
let end = group.find('}').unwrap_or(group.len());
for item in group[..end].split(',') {
let head = item.split("::").next().unwrap_or("");
if FORBIDDEN_IN_STD_GROUP.contains(&head) {
found.push(format!("`std::{{{head}}}` (grouped import)"));
}
}
rest = &group[end.min(group.len())..];
}
found
}
#[test]
fn src_is_sans_io() {
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = Vec::new();
rust_files(&src, &mut files);
assert!(files.len() >= 20, "expected the whole crate under {}", src.display());
let mut report = Vec::new();
for file in &files {
let code = strip_comments(&std::fs::read_to_string(file).expect("read source"));
for v in violations_in(&code) {
report.push(format!("{}: {v}", file.strip_prefix(&src).unwrap_or(file).display()));
}
}
assert!(report.is_empty(), "sans-I/O rule broken:\n{}", report.join("\n"));
}
#[test]
fn guard_catches_what_it_should() {
// The guard itself must work, or `src_is_sans_io` proves nothing.
for bad in [
"use std::net::UdpSocket;",
"let t = std::time::Instant::now();",
"let t = Instant :: now();",
"let t = SystemTime::now();",
"std::thread::spawn(|| {});",
"let f = std::fs::read(\"x\");",
"use std::{fs, io};",
"use std::{io, net::TcpStream};",
"let mut r = rand::rngs::OsRng;",
"getrandom::fill(&mut b);",
] {
assert!(!violations_in(&strip_comments(bad)).is_empty(), "guard missed: {bad}");
}
for fine in [
"// no std::net here, only a comment",
"/// Docs may say Instant::now is forbidden.",
"/* std::fs in a block comment */ let x = 1;",
"use crate::Instant; let t = Instant::from_micros(5);",
"use std::{fmt, error};",
"use core::time::Duration;",
] {
assert!(violations_in(&strip_comments(fine)).is_empty(), "guard flagged: {fine}");
}
}
#[test]
fn every_module_forbids_unsafe() {
let lib = std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/lib.rs")).expect("lib.rs");
assert!(lib.contains("#![forbid(unsafe_code)]"), "lib.rs must carry #![forbid(unsafe_code)]");
let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
let mut files = Vec::new();
rust_files(&src, &mut files);
for file in files {
let code = strip_comments(&std::fs::read_to_string(&file).expect("read"));
assert_eq!(
code.matches("unsafe").count(),
code.matches("unsafe_code").count(),
"{}: `unsafe` in src",
file.display()
);
assert!(!code.contains("allow(unsafe_code)"), "{}: unsafe allowed", file.display());
}
}
// ------------------------------------------------------------------------------------------------ secrets
const KEY: [u8; 16] = [0xA1, 0xB2, 0xC3, 0xD4, 0xE5, 0xF6, 0x17, 0x28, 0x39, 0x4A, 0x5B, 0x6C, 0x7D, 0x8E, 0x9F, 0x10];
/// Every way the key could show up in a `Debug` string.
fn leaks_key(s: &str) -> bool {
let lower = s.to_lowercase();
lower.contains(&common::to_hex(&KEY))
|| lower.contains("161, 178")
|| lower.contains("0xa1, 0xb2")
|| lower.contains("a1b2c3")
|| s.contains("[161")
}
#[test]
fn debug_never_prints_keys() {
let keys = domistream::SessionKeys { rikey: KEY, rikeyid: 7 };
let control = domistream::control::ControlCipher::new(KEY);
let video = domistream::video::VideoCipher::new(KEY);
let audio = domistream::audio::AudioCipher::new(&keys);
let config = domistream::control::ControlConfig {
enet: domistream::enet::EnetConfig {
channel_count: 1,
mtu: 1400,
connect_data: 0,
ping_interval: core::time::Duration::from_millis(500),
timeout: core::time::Duration::from_secs(10),
},
rikey: KEY,
ping_interval: core::time::Duration::from_millis(100),
};
for (what, s) in [
("SessionKeys", format!("{keys:?}")),
("ControlCipher", format!("{control:?}")),
("VideoCipher", format!("{video:?}")),
("AudioCipher", format!("{audio:?}")),
("ControlConfig", format!("{config:?}")),
("VideoConfig", format!("{:?}", domistream::video::VideoConfig {
packet_size: 1024,
cipher: Some(video.clone()),
frame_timeout: core::time::Duration::from_millis(100),
})),
] {
assert!(!leaks_key(&s), "{what} Debug leaks the key: {s}");
assert!(s.contains("redacted"), "{what} Debug should say the key is redacted: {s}");
}
// rikeyid is not secret: it may show.
assert!(format!("{keys:?}").contains('7'));
}
#[test]
fn debug_never_prints_the_pin_or_the_private_key() {
// Pin and ClientIdentity can only be made through the API (Phase A: Unimplemented, so these fail now).
let pin = domistream::pairing::Pin::from_digits("4071").expect("Pin::from_digits");
let s = format!("{pin:?}");
assert!(!s.contains("4071") && !s.contains("52, 48, 55, 49"), "Pin Debug leaks the PIN: {s}");
let v = common::pairing_vectors();
let key = v.bytes("client_key_pkcs8_der");
let identity = domistream::pairing::ClientIdentity::from_der(&v.bytes("client_cert_der"), &key)
.expect("ClientIdentity::from_der");
let s = format!("{identity:?}");
assert!(s.contains("redacted"), "{s}");
let key_hex = common::to_hex(&key[key.len() - 32..]);
assert!(!s.to_lowercase().contains(&key_hex), "ClientIdentity Debug leaks key bytes");
assert!(!s.contains(&format!("{:?}", &key[key.len() - 8..])), "ClientIdentity Debug leaks key bytes");
}
#[test]
fn error_display_has_no_secret_material() {
// Errors are fixed strings and numbers; make sure the variants that come out of crypto paths say nothing.
for e in [domistream::Error::Crypto, domistream::Error::PairingRefused] {
let s = format!("{e} {e:?}");
assert!(!leaks_key(&s), "{s}");
assert!(s.len() < 80, "crypto errors are deliberately short: {s}");
}
}
+791
View File
@@ -0,0 +1,791 @@
//! Pairing (`docs/PROTOCOL.md` 1.5) against recorded vectors made by independent tools
//! (`tools/vectors/gen_vectors.py`: Python hashlib, the OpenSSL CLI). The keys are test-only.
//!
//! Recorded transcript assumption: the state machine draws its randomness as salt (step 1), then C (step 2), then
//! secret_c (step 3), 16 bytes each, and nothing else. [`common::ScriptedRng`] fails loudly if that changes.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use common::{
CLIENT_CERT_PEM, CLIENT_KEY_PEM, EC_CERT_PEM, HOST_CERT_PEM, ROGUE_CERT_PEM, ScriptedRng, SeqRng, Vectors, hex,
param, parse_query, pem_blocks, to_hex, to_hex_upper, xml_padded_to, xml_root,
};
use domistream::Error;
use domistream::http::{HttpRequest, Scheme};
use domistream::pairing::crypto;
use domistream::pairing::identity::{MAX_CERT_DER_BYTES, MAX_CERT_PEM_BYTES};
use domistream::pairing::{
ClientIdentity, MAX_PAIR_RESPONSE_BYTES, MAX_SIGNATURE_BYTES, PairingFailure, PairingSession, PairingState,
PairingStep, Pin, ServerCert, parse_pair_response,
};
const UID: &str = "0123456789ABCDEF";
const DEVICE: &str = "DomiStreamTestTV";
fn v() -> Vectors {
common::pairing_vectors()
}
fn client() -> ClientIdentity {
let v = v();
ClientIdentity::from_der(&v.bytes("client_cert_der"), &v.bytes("client_key_pkcs8_der"))
.expect("ClientIdentity::from_der(test-only client)")
}
fn rogue() -> ClientIdentity {
let v = v();
ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &v.bytes("rogue_key_pkcs8_der")).expect("rogue identity")
}
fn pin() -> Pin {
Pin::from_digits(v().str("pin")).expect("Pin::from_digits")
}
fn rng_a() -> ScriptedRng {
let v = v();
ScriptedRng::new([v.bytes("salt"), v.bytes("client_challenge"), v.bytes("client_secret")].concat())
}
fn rng_b() -> ScriptedRng {
let v = v();
ScriptedRng::new([v.bytes("salt_b"), v.bytes("client_challenge_b"), v.bytes("client_secret_b")].concat())
}
// ------------------------------------------------------------------------------------------------ host answers
fn answer(paired: bool, element: Option<(&str, &[u8])>) -> Vec<u8> {
let mut inner = format!("<paired>{}</paired>", u8::from(paired));
if let Some((name, value)) = element {
// Upper-case hex: the parser must accept both cases (PROTOCOL.md 1.1).
inner.push_str(&format!("<{name}>{}</{name}>", to_hex_upper(value)));
}
xml_root(200, &inner)
}
fn resp1() -> Vec<u8> {
answer(true, Some(("plaincert", HOST_CERT_PEM.as_bytes())))
}
fn resp2() -> Vec<u8> {
answer(true, Some(("challengeresponse", &v().bytes("step2_challengeresponse"))))
}
fn resp3() -> Vec<u8> {
answer(true, Some(("pairingsecret", &v().bytes("step3_pairingsecret"))))
}
fn resp_ok() -> Vec<u8> {
answer(true, None)
}
/// The recorded host answers, in order.
fn transcript() -> Vec<Vec<u8>> {
vec![resp1(), resp2(), resp3(), resp_ok(), resp_ok()]
}
/// A session that has been fed the first `steps` recorded answers.
fn session_after(steps: usize) -> (PairingSession, ScriptedRng, ClientIdentity) {
let id = client();
let mut rng = rng_a();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).expect("PairingSession::start");
for body in transcript().into_iter().take(steps) {
s.handle_response(&id, 200, &body, &mut rng).expect("recorded answer");
}
(s, rng, id)
}
const STATES: [PairingState; 5] = [
PairingState::AwaitServerCert,
PairingState::AwaitChallengeResponse,
PairingState::AwaitPairingSecret,
PairingState::AwaitClientSecretAck,
PairingState::AwaitPairChallenge,
];
fn sent(step: PairingStep) -> HttpRequest {
match step {
PairingStep::Send(r) => r,
PairingStep::Paired(p) => panic!("expected a request, pairing already finished: {p:?}"),
}
}
fn hex_param(req: &HttpRequest, name: &str) -> Vec<u8> {
let (path, q) = parse_query(&req.path_and_query);
assert_eq!(path, "/pair");
hex(param(&q, name))
}
/// Feeds `body` and checks the session fails into `Failed(reason)`.
fn expect_failure(s: &mut PairingSession, id: &ClientIdentity, rng: &mut ScriptedRng, status: u16, body: &[u8], reason: PairingFailure) {
let r = s.handle_response(id, status, body, rng);
assert!(r.is_err(), "expected a failure ({reason:?}), got {r:?}");
assert_eq!(s.state(), PairingState::Failed(reason), "result was {r:?}");
// Failed is terminal.
assert_err!(s.handle_response(id, 200, &resp_ok(), rng), Error::State { .. });
assert_eq!(s.state(), PairingState::Failed(reason));
}
// ================================================================================================ happy path
#[test]
fn recorded_transcript_walks_every_state() {
let v = v();
let id = client();
let mut rng = rng_a();
let (mut s, req1) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
assert_eq!(s.state(), PairingState::AwaitServerCert);
// Step 1 (HTTP): getservercert, salt, client certificate; blocks on the host, so a long timeout.
assert_eq!(req1.scheme, Scheme::Http);
assert!(req1.timeout.is_some_and(|t| t >= core::time::Duration::from_secs(30)), "step 1 timeout {:?}", req1.timeout);
let (path, q) = parse_query(&req1.path_and_query);
assert_eq!(path, "/pair");
assert_eq!(param(&q, "uniqueid"), UID);
assert_eq!(param(&q, "phrase"), "getservercert");
assert_eq!(hex(param(&q, "salt")), v.bytes("salt"));
let pem = String::from_utf8(hex(param(&q, "clientcert"))).expect("clientcert is PEM text");
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "clientcert is the identity's cert");
// Step 2: clientchallenge = E_K(C).
let req2 = sent(s.handle_response(&id, 200, &resp1(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitChallengeResponse);
assert_eq!(req2.scheme, Scheme::Http);
assert_eq!(hex_param(&req2, "clientchallenge"), v.bytes("step2_clientchallenge"));
assert_eq!(param(&parse_query(&req2.path_and_query).1, "uniqueid"), UID);
// Step 3: serverchallengeresp = E_K(H_c).
let req3 = sent(s.handle_response(&id, 200, &resp2(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
assert_eq!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
// Step 4: clientpairingsecret = secret_c || Sign_client(secret_c), after checking the host's proof.
let req4 = sent(s.handle_response(&id, 200, &resp3(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitClientSecretAck);
assert_eq!(hex_param(&req4, "clientpairingsecret"), v.bytes("step4_clientpairingsecret"));
// Step 5 (HTTPS): pairchallenge.
let req5 = sent(s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap());
assert_eq!(s.state(), PairingState::AwaitPairChallenge);
assert_eq!(req5.scheme, Scheme::Https, "step 5 runs over HTTPS with the client certificate");
assert_eq!(param(&parse_query(&req5.path_and_query).1, "phrase"), "pairchallenge");
match s.handle_response(&id, 200, &resp_ok(), &mut rng).unwrap() {
PairingStep::Paired(host) => assert_eq!(host.server_cert.der(), v.bytes("host_cert_der").as_slice()),
PairingStep::Send(r) => panic!("expected Paired, got another request {r:?}"),
}
assert_eq!(s.state(), PairingState::Paired);
assert_eq!(rng.drawn(), 48, "salt + C + secret_c");
assert_err!(s.handle_response(&id, 200, &resp_ok(), &mut rng), Error::State { .. });
assert_eq!(s.state(), PairingState::Paired);
}
#[test]
fn lower_case_hex_answers_work_too() {
let id = client();
let mut rng = rng_a();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
for body in transcript() {
let lower = String::from_utf8(body).unwrap();
// Lower-case only the hex payloads (element names keep their case).
let mut out = String::new();
let mut in_text = false;
for c in lower.chars() {
match c {
'>' => {
in_text = true;
out.push(c);
}
'<' => {
in_text = false;
out.push(c);
}
_ if in_text => out.push(c.to_ascii_lowercase()),
_ => out.push(c),
}
}
s.handle_response(&id, 200, out.as_bytes(), &mut rng).unwrap();
}
assert_eq!(s.state(), PairingState::Paired);
}
// ================================================================================================ no shortcuts
#[test]
fn paired_needs_exactly_five_answers() {
// An answer carrying every element at once still moves one step at a time.
let v = v();
let all = xml_root(
200,
&format!(
"<paired>1</paired><plaincert>{}</plaincert><challengeresponse>{}</challengeresponse><pairingsecret>{}</pairingsecret>",
to_hex(HOST_CERT_PEM.as_bytes()),
to_hex(&v.bytes("step2_challengeresponse")),
to_hex(&v.bytes("step3_pairingsecret")),
),
);
let id = client();
let mut rng = rng_a();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
for (i, want) in STATES.iter().enumerate().skip(1) {
let step = s.handle_response(&id, 200, &all, &mut rng).unwrap();
assert!(matches!(step, PairingStep::Send(_)), "answer {} must not finish pairing", i);
assert_eq!(s.state(), *want, "after {i} answers");
}
assert!(matches!(s.handle_response(&id, 200, &all, &mut rng).unwrap(), PairingStep::Paired(_)));
assert_eq!(s.state(), PairingState::Paired);
}
#[test]
fn a_bare_paired_answer_cannot_skip_any_step() {
// `<paired>1</paired>` is all steps 4 and 5 need. Fed early, it must fail, never jump ahead.
for steps in 0..3 {
let (mut s, mut rng, id) = session_after(steps);
assert_eq!(s.state(), STATES[steps]);
expect_failure(&mut s, &id, &mut rng, 200, &resp_ok(), PairingFailure::MalformedAnswer);
}
}
#[test]
fn out_of_order_answers_fail() {
// Each state fed an answer meant for another state (replayed or reordered by an attacker).
let cases: Vec<(usize, Vec<u8>)> = vec![
(0, resp2()),
(0, resp3()),
(1, resp1()),
(1, resp3()),
(2, resp1()),
(2, resp2()),
];
for (steps, body) in cases {
let (mut s, mut rng, id) = session_after(steps);
expect_failure(&mut s, &id, &mut rng, 200, &body, PairingFailure::MalformedAnswer);
}
}
#[test]
fn replayed_answers_from_another_session_fail() {
// Session B (fresh randomness) fed session A's recorded answers: the host proof cannot match.
let id = client();
let mut rng = rng_b();
let (mut s, _) = PairingSession::start(&id, UID, DEVICE, pin(), &mut rng).unwrap();
s.handle_response(&id, 200, &resp1(), &mut rng).unwrap();
s.handle_response(&id, 200, &resp2(), &mut rng).unwrap();
assert_eq!(s.state(), PairingState::AwaitPairingSecret);
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
}
#[test]
fn replaying_the_same_answer_twice_fails() {
// Step 2's answer accepted, then replayed in place of step 3's.
let (mut s, mut rng, id) = session_after(2);
expect_failure(&mut s, &id, &mut rng, 200, &resp2(), PairingFailure::MalformedAnswer);
}
// ================================================================================================ hostile host
#[test]
fn host_refusal_at_every_step() {
for steps in 0..5 {
let (mut s, mut rng, id) = session_after(steps);
let body = answer(false, None);
let r = s.handle_response(&id, 200, &body, &mut rng);
assert_err!(r, Error::PairingRefused, "step {}", steps + 1);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostRefused), "step {}", steps + 1);
}
}
#[test]
fn host_status_errors_at_every_step() {
for steps in 0..5 {
let (mut s, mut rng, id) = session_after(steps);
let r = s.handle_response(&id, 200, &xml_root(500, "<paired>1</paired>"), &mut rng);
assert_err!(r, Error::HostStatus { code: 500 }, "step {}", steps + 1);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
let (mut s, mut rng, id) = session_after(steps);
let good = transcript().swap_remove(steps);
let r = s.handle_response(&id, 404, &good, &mut rng);
assert_err!(r, Error::HostStatus { code: 404 }, "HTTP 404 at step {}", steps + 1);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::HostStatus));
}
}
#[test]
fn malformed_answers_at_every_step() {
let bodies: Vec<Vec<u8>> = vec![
b"".to_vec(),
b"garbage".to_vec(),
b"<root status_code=\"200\"><paired>1</paired>".to_vec(),
xml_root(200, ""),
xml_root(200, "<paired>yes</paired>"),
xml_root(200, "<paired>1</paired><plaincert>zz</plaincert><challengeresponse>zz</challengeresponse><pairingsecret>zz</pairingsecret>"),
xml_root(200, "<paired>1</paired><plaincert>abc</plaincert><challengeresponse>abc</challengeresponse><pairingsecret>abc</pairingsecret>"),
];
for steps in 0..3 {
for body in &bodies {
let (mut s, mut rng, id) = session_after(steps);
expect_failure(&mut s, &id, &mut rng, 200, body, PairingFailure::MalformedAnswer);
}
}
}
#[test]
fn wrong_pin_is_a_proof_mismatch() {
let v = v();
let (mut s, mut rng, id) = session_after(1);
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &v.bytes("step2_challengeresponse_wrong_pin")))), &mut rng)
.unwrap();
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch));
}
#[test]
fn wrong_host_hash_is_a_proof_mismatch() {
let v = v();
for name in ["step2_challengeresponse_wrong_hash", "step2_challengeresponse_wrong_cert"] {
let (mut s, mut rng, id) = session_after(1);
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &v.bytes(name)))), &mut rng).unwrap();
let r = s.handle_response(&id, 200, &resp3(), &mut rng);
assert_err!(r, Error::PairingRefused, "{name}");
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "{name}");
}
}
#[test]
fn tampered_challenge_response() {
let v = v();
// Block 0 or 1 holds H_s: flipping it must end in ProofMismatch once the secret arrives.
for byte in [0usize, 17, 31] {
let mut cr = v.bytes("step2_challengeresponse");
cr[byte] ^= 0x01;
let (mut s, mut rng, id) = session_after(1);
s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap();
assert_err!(s.handle_response(&id, 200, &resp3(), &mut rng), Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::ProofMismatch), "byte {byte}");
}
// Block 2 holds S_c: the client cannot see it, but it must feed S_c into H_c (so step 3 changes).
let mut cr = v.bytes("step2_challengeresponse");
cr[40] ^= 0x01;
let (mut s, mut rng, id) = session_after(1);
let req3 = sent(s.handle_response(&id, 200, &answer(true, Some(("challengeresponse", &cr))), &mut rng).unwrap());
assert_ne!(hex_param(&req3, "serverchallengeresp"), v.bytes("step3_serverchallengeresp"));
}
#[test]
fn wrong_challenge_response_sizes() {
let v = v();
let good = v.bytes("step2_challengeresponse");
let cases: Vec<Vec<u8>> = vec![
good[..32].to_vec(),
good[..47].to_vec(),
[good.clone(), vec![0; 1]].concat(),
[good.clone(), vec![0; 16]].concat(),
vec![],
];
for cr in cases {
let (mut s, mut rng, id) = session_after(1);
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("challengeresponse", &cr))), PairingFailure::MalformedAnswer);
}
}
#[test]
fn bad_host_signatures() {
let v = v();
// Signed by another key.
let (mut s, mut rng, id) = session_after(2);
let r = s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &v.bytes("step3_pairingsecret_rogue_signature")))), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
// One bit of the signature flipped, the signature cut short, or zeroed.
let good = v.bytes("step3_pairingsecret");
let mut flipped = good.clone();
*flipped.last_mut().unwrap() ^= 0x80;
let mut zeroed = good.clone();
zeroed[16..].fill(0);
for ps in [flipped, good[..good.len() - 1].to_vec(), zeroed, [good[..16].to_vec(), vec![0x01]].concat()] {
let (mut s, mut rng, id) = session_after(2);
let r = s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &ps))), &mut rng);
assert_err!(r, Error::PairingRefused);
assert_eq!(s.state(), PairingState::Failed(PairingFailure::BadHostSignature));
}
// The secret itself changed: both checks fail; either reason is a refusal.
let mut secret = good.clone();
secret[0] ^= 1;
let (mut s, mut rng, id) = session_after(2);
assert_err!(s.handle_response(&id, 200, &answer(true, Some(("pairingsecret", &secret))), &mut rng), Error::PairingRefused);
assert!(matches!(
s.state(),
PairingState::Failed(PairingFailure::ProofMismatch | PairingFailure::BadHostSignature)
));
}
#[test]
fn wrong_pairing_secret_sizes() {
let v = v();
let secret = v.bytes("server_secret");
for ps in [secret[..15].to_vec(), secret.clone(), [secret.clone(), vec![0x55; MAX_SIGNATURE_BYTES + 1]].concat(), vec![]] {
let (mut s, mut rng, id) = session_after(2);
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("pairingsecret", &ps))), PairingFailure::MalformedAnswer);
}
}
#[test]
fn bad_host_certificates() {
let two = format!("{HOST_CERT_PEM}{ROGUE_CERT_PEM}");
let mut long = HOST_CERT_PEM.to_string();
long.push_str(&"\n".repeat(MAX_CERT_PEM_BYTES));
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() / 2];
for pem in [
"".to_string(),
"hello".to_string(),
EC_CERT_PEM.to_string(),
two,
CLIENT_KEY_PEM.to_string(),
cut.to_string(),
long,
] {
let (mut s, mut rng, id) = session_after(0);
expect_failure(&mut s, &id, &mut rng, 200, &answer(true, Some(("plaincert", pem.as_bytes()))), PairingFailure::MalformedAnswer);
}
}
#[test]
fn identity_must_stay_the_same() {
let (mut s, mut rng, _) = session_after(1);
assert_err!(s.handle_response(&rogue(), 200, &resp2(), &mut rng), Error::Malformed { .. });
}
#[test]
fn start_refuses_bad_names_and_injection() {
use domistream::http::{MAX_DEVICE_NAME_BYTES, MAX_UNIQUE_ID_BYTES};
let id = client();
for (uid, dev) in [
("", DEVICE),
(&*"a".repeat(MAX_UNIQUE_ID_BYTES + 1), DEVICE),
(UID, ""),
(UID, &*"d".repeat(MAX_DEVICE_NAME_BYTES + 1)),
] {
assert_err!(PairingSession::start(&id, uid, dev, pin(), &mut rng_a()), Error::Malformed { .. });
}
// A device name with query syntax is refused or encoded: never a second `phrase`.
for evil in ["tv&phrase=pairchallenge", "tv\r\nHost: x", "tv#x", "tv salt=00"] {
match PairingSession::start(&id, UID, evil, pin(), &mut rng_a()) {
Err(Error::Malformed { .. }) => {}
Ok((_, req)) => {
let (_, q) = parse_query(&req.path_and_query);
assert_eq!(param(&q, "phrase"), "getservercert");
assert_eq!(param(&q, "devicename"), evil);
assert!(!req.path_and_query.contains(['\r', '\n', ' ', '#']));
}
Err(e) => panic!("{evil:?}: {e:?}"),
}
}
}
// ================================================================================================ crypto vectors
#[test]
fn derive_key_vectors() {
let v = v();
for i in 0..4 {
let salt: [u8; 16] = v.arr16(&format!("derive_{i}_salt"));
let p = Pin::from_digits(v.str(&format!("derive_{i}_pin"))).unwrap();
assert_eq!(crypto::derive_key(&salt, &p).unwrap().to_vec(), v.bytes(&format!("derive_{i}_key")), "vector {i}");
}
assert_eq!(crypto::derive_key(&v.arr16("salt"), &pin()).unwrap().to_vec(), v.bytes("key"));
}
#[test]
fn ecb_vectors() {
let v = v();
for blocks in 1..=4 {
let key = v.arr16(&format!("ecb_{blocks}_key"));
let plain = v.bytes(&format!("ecb_{blocks}_plain"));
let cipher = v.bytes(&format!("ecb_{blocks}_cipher"));
assert_eq!(crypto::ecb_encrypt(&key, &plain).unwrap(), cipher, "{blocks} blocks");
assert_eq!(crypto::ecb_decrypt(&key, &cipher).unwrap(), plain, "{blocks} blocks");
}
let key = v.arr16("key");
assert_eq!(crypto::ecb_encrypt(&key, &v.bytes("client_challenge")).unwrap(), v.bytes("step2_clientchallenge"));
for len in [1usize, 15, 17, 47] {
assert_err!(crypto::ecb_encrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
assert_err!(crypto::ecb_decrypt(&key, &vec![0; len]), Error::Malformed { .. }, "{len} bytes");
}
}
#[test]
fn proof_hash_vectors() {
let v = v();
for i in 0..6 {
let h = crypto::proof_hash(
&v.arr16(&format!("proof_{i}_challenge")),
&v.bytes(&format!("proof_{i}_signature")),
&v.arr16(&format!("proof_{i}_secret")),
)
.unwrap();
assert_eq!(h.to_vec(), v.bytes(&format!("proof_{i}_hash")), "vector {i}");
}
let h = crypto::proof_hash(&v.arr16("client_challenge"), &v.bytes("host_cert_signature"), &v.arr16("server_secret"));
assert_eq!(h.unwrap().to_vec(), v.bytes("host_proof"));
let h = crypto::proof_hash(&v.arr16("server_challenge"), &v.bytes("client_cert_signature"), &v.arr16("client_secret"));
assert_eq!(h.unwrap().to_vec(), v.bytes("client_proof"));
assert_too_large!(
crypto::proof_hash(&[0; 16], &vec![0; MAX_SIGNATURE_BYTES + 1], &[0; 16]),
MAX_SIGNATURE_BYTES,
MAX_SIGNATURE_BYTES + 1
);
}
#[test]
fn split_helpers() {
let v = v();
let key = v.arr16("key");
let decrypted = crypto::ecb_decrypt(&key, &v.bytes("step2_challengeresponse")).unwrap();
let (h, sc) = crypto::split_challenge_response(&decrypted).unwrap();
assert_eq!(h.to_vec(), v.bytes("host_proof"));
assert_eq!(sc.to_vec(), v.bytes("server_challenge"));
for len in [0usize, 1, 32, 47, 49, 64] {
assert_err!(crypto::split_challenge_response(&vec![0; len]), Error::Malformed { .. }, "{len}");
}
let ps = v.bytes("step3_pairingsecret");
let (secret, sig) = crypto::split_pairing_secret(&ps).unwrap();
assert_eq!(secret.to_vec(), v.bytes("server_secret"));
assert_eq!(sig, v.bytes("server_secret_signature").as_slice());
assert_eq!(crypto::split_pairing_secret(&[7; 17]).unwrap().1, &[7]);
assert_eq!(crypto::split_pairing_secret(&vec![7; 16 + MAX_SIGNATURE_BYTES]).unwrap().1.len(), MAX_SIGNATURE_BYTES);
for len in [0usize, 1, 15, 16] {
assert_err!(crypto::split_pairing_secret(&vec![0; len]), Error::Malformed { .. }, "{len}");
}
assert_too_large!(
crypto::split_pairing_secret(&vec![0; 16 + MAX_SIGNATURE_BYTES + 1]),
MAX_SIGNATURE_BYTES,
MAX_SIGNATURE_BYTES + 1
);
}
// ================================================================================================ certificates
#[test]
fn server_cert_from_recorded_pem() {
let v = v();
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
assert_eq!(c.der(), v.bytes("host_cert_der").as_slice());
assert_eq!(c.signature().unwrap(), v.bytes("host_cert_signature"));
assert_eq!(ServerCert::from_der(&v.bytes("host_cert_der")).unwrap(), c);
c.verify(&v.bytes("server_secret"), &v.bytes("server_secret_signature")).unwrap();
}
#[test]
fn server_cert_verify_refuses() {
let v = v();
let c = ServerCert::from_pem(HOST_CERT_PEM.as_bytes()).unwrap();
let secret = v.bytes("server_secret");
let sig = v.bytes("server_secret_signature");
let mut flipped = sig.clone();
flipped[100] ^= 0x04;
let rogue_sig = &v.bytes("step3_pairingsecret_rogue_signature")[16..];
let mut other = secret.clone();
other[15] ^= 1;
assert_err!(c.verify(&secret, &flipped), Error::Crypto);
assert_err!(c.verify(&secret, rogue_sig), Error::Crypto);
assert_err!(c.verify(&other, &sig), Error::Crypto);
assert_err!(c.verify(&secret, &sig[..255]), Error::Crypto);
assert_err!(c.verify(&secret, &[]), Error::Crypto);
assert_err!(c.verify(&secret, &[sig.clone(), vec![0]].concat()), Error::Crypto);
}
#[test]
fn server_cert_pinning() {
let v = v();
let der = v.bytes("host_cert_der");
let c = ServerCert::from_der(&der).unwrap();
assert_eq!(c.matches(&der), Ok(true));
let mut flipped = der.clone();
flipped[der.len() / 2] ^= 1;
assert_eq!(c.matches(&flipped), Ok(false));
assert_eq!(c.matches(&der[..der.len() - 1]), Ok(false));
assert_eq!(c.matches(&[der.clone(), vec![0]].concat()), Ok(false));
assert_eq!(c.matches(&v.bytes("rogue_cert_der")), Ok(false));
assert_eq!(c.matches(&[]), Ok(false));
assert_too_large!(c.matches(&vec![0; MAX_CERT_DER_BYTES + 1]), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
}
#[test]
fn server_cert_hostile_pem() {
let cut = &HOST_CERT_PEM[..HOST_CERT_PEM.len() - 40];
let bad_b64 = HOST_CERT_PEM.replacen('M', "!", 3);
let two = format!("{HOST_CERT_PEM}{CLIENT_CERT_PEM}");
for (pem, why) in [
("", "empty"),
("x", "one byte"),
("-----BEGIN CERTIFICATE-----\n-----END CERTIFICATE-----\n", "empty block"),
(cut, "cut"),
(&*bad_b64, "bad base64"),
(&*two, "two certificates"),
(CLIENT_KEY_PEM, "a private key"),
(EC_CERT_PEM, "not an RSA key"),
] {
assert_err!(ServerCert::from_pem(pem.as_bytes()), Error::Malformed { .. }, "{why}");
}
let mut big = HOST_CERT_PEM.as_bytes().to_vec();
big.resize(MAX_CERT_PEM_BYTES + 1, b'\n');
assert_too_large!(ServerCert::from_pem(&big), MAX_CERT_PEM_BYTES, MAX_CERT_PEM_BYTES + 1);
assert_too_large!(ServerCert::from_pem(&vec![b'A'; 1 << 24]), MAX_CERT_PEM_BYTES, 1 << 24);
}
#[test]
fn server_cert_hostile_der() {
let der = v().bytes("host_cert_der");
for (bad, why) in [
(vec![], "empty"),
(vec![0x30], "one byte"),
(der[..der.len() - 1].to_vec(), "cut"),
([der.clone(), vec![0]].concat(), "trailing byte"),
({
let mut d = der.clone();
d[1] = 0x84; // outer length claims 4 length bytes: lies about the size
d
}, "lying length"),
] {
assert_err!(ServerCert::from_der(&bad), Error::Malformed { .. }, "{why}");
}
let mut big = der.clone();
big.resize(MAX_CERT_DER_BYTES + 1, 0);
assert_too_large!(ServerCert::from_der(&big), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
}
#[test]
fn client_identity_from_recorded_keys() {
let v = v();
let id = client();
assert_eq!(id.cert_der(), v.bytes("client_cert_der").as_slice());
assert_eq!(id.key_pkcs8_der(), v.bytes("client_key_pkcs8_der").as_slice());
assert_eq!(id.cert_signature().unwrap(), v.bytes("client_cert_signature"));
assert_eq!(id.sign(&v.bytes("sign_data")).unwrap(), v.bytes("sign_data_client_signature"), "PKCS#1 v1.5 is deterministic");
assert_eq!(id.sign(&v.bytes("client_secret")).unwrap(), v.bytes("client_secret_signature"));
let pem = id.cert_pem().unwrap();
assert_eq!(pem_blocks(&pem, "CERTIFICATE"), vec![v.bytes("client_cert_der")]);
assert_eq!(pem_blocks(CLIENT_CERT_PEM, "CERTIFICATE"), vec![v.bytes("client_cert_der")], "fixture sanity");
}
#[test]
fn client_identity_refuses() {
use domistream::pairing::identity::MAX_KEY_DER_BYTES;
let v = v();
let cert = v.bytes("client_cert_der");
let key = v.bytes("client_key_pkcs8_der");
assert_err!(ClientIdentity::from_der(&cert, &v.bytes("rogue_key_pkcs8_der")), Error::Malformed { .. }, "key of another cert");
assert_err!(ClientIdentity::from_der(&v.bytes("rogue_cert_der"), &key), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&[], &key), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&cert, &[]), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&cert, &key[..key.len() - 1]), Error::Malformed { .. });
assert_err!(ClientIdentity::from_der(&cert, &cert), Error::Malformed { .. });
let mut big_cert = cert.clone();
big_cert.resize(MAX_CERT_DER_BYTES + 1, 0);
assert_too_large!(ClientIdentity::from_der(&big_cert, &key), MAX_CERT_DER_BYTES, MAX_CERT_DER_BYTES + 1);
let mut big_key = key.clone();
big_key.resize(MAX_KEY_DER_BYTES + 1, 0);
assert_too_large!(ClientIdentity::from_der(&cert, &big_key), MAX_KEY_DER_BYTES, MAX_KEY_DER_BYTES + 1);
}
#[test]
fn client_identity_generate() {
let id = ClientIdentity::generate(&mut SeqRng::new(0xD0D0), "Living Room TV", 1_764_000_000).unwrap();
let cert = ServerCert::from_der(id.cert_der()).expect("a generated cert is a valid RSA X.509 certificate");
let sig = id.sign(b"hello").unwrap();
assert_eq!(sig.len(), domistream::pairing::identity::CLIENT_KEY_BITS / 8);
cert.verify(b"hello", &sig).expect("the cert carries the identity's public key");
let again = ClientIdentity::from_der(id.cert_der(), id.key_pkcs8_der()).unwrap();
assert_eq!(again.cert_der(), id.cert_der());
assert!(id.cert_der().windows(14).any(|w| w == b"Living Room TV"), "CN in the certificate");
assert_eq!(id.cert_signature().unwrap(), cert.signature().unwrap());
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), "", 0), Error::Malformed { .. });
assert_err!(ClientIdentity::generate(&mut SeqRng::new(1), &"n".repeat(10_000), 0), Error::Malformed { .. });
}
// ================================================================================================ PIN
#[test]
fn pin_from_digits() {
assert_eq!(Pin::from_digits("0000").unwrap().as_bytes(), b"0000");
assert_eq!(Pin::from_digits("4071").unwrap().as_bytes(), b"4071");
for bad in ["", "1", "123", "12345", "12a4", " 123", "123 ", "-123", "+123", "\u{0661}\u{0662}\u{0663}\u{0664}", "1234", "12\u{0}4"] {
assert_err!(Pin::from_digits(bad), Error::Malformed { .. }, "{bad:?}");
}
}
#[test]
fn pin_generate_is_uniform_digits() {
let mut rng = SeqRng::new(42);
let mut counts = [[0u32; 10]; 4];
let draws = 4000;
for _ in 0..draws {
let p = Pin::generate(&mut rng).unwrap();
for (pos, d) in p.as_bytes().iter().enumerate() {
assert!(d.is_ascii_digit(), "{d:#x}");
counts[pos][usize::from(d - b'0')] += 1;
}
}
// 400 expected per digit and position; a 4-sigma band (sd ~ 19) catches modulo bias of a u8 draw (+20 %).
for (pos, row) in counts.iter().enumerate() {
for (digit, &n) in row.iter().enumerate() {
assert!((324..=476).contains(&n), "digit {digit} at position {pos}: {n} of {draws}");
}
}
let a = Pin::generate(&mut SeqRng::new(9)).unwrap();
let b = Pin::generate(&mut SeqRng::new(9)).unwrap();
assert_eq!(a, b, "the PIN comes only from the caller's randomness");
}
// ================================================================================================ answer parser
#[test]
fn pair_response_parser() {
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><plaincert>4142</plaincert>")).unwrap();
assert!(r.paired);
assert_eq!(r.plain_cert.as_deref(), Some(&b"AB"[..]));
assert_eq!(r.challenge_response, None);
let r = parse_pair_response(&xml_root(200, "<paired>0</paired><challengeresponse>aBcD</challengeresponse>")).unwrap();
assert!(!r.paired);
assert_eq!(r.challenge_response.as_deref(), Some(&[0xAB, 0xCD][..]));
let r = parse_pair_response(&xml_root(200, "<paired>1</paired><pairingsecret>00ff</pairingsecret>")).unwrap();
assert_eq!(r.pairing_secret.as_deref(), Some(&[0x00, 0xFF][..]));
for (inner, why) in [
("", "no paired"),
("<plaincert>4142</plaincert>", "no paired"),
("<paired>1</paired><plaincert>414</plaincert>", "odd hex"),
("<paired>1</paired><plaincert>41 42</plaincert>", "space in hex"),
("<paired>1</paired><plaincert>4G</plaincert>", "not hex"),
("<paired>1</paired><challengeresponse>0x41</challengeresponse>", "0x prefix"),
] {
assert_err!(parse_pair_response(&xml_root(200, inner)), Error::Malformed { .. }, "{why}");
}
assert_err!(parse_pair_response(&xml_root(400, "<paired>0</paired>")), Error::HostStatus { code: 400 });
assert_err!(parse_pair_response(b""), Error::Malformed { .. });
assert_err!(parse_pair_response(b"<"), Error::Malformed { .. });
}
#[test]
fn pair_response_sizes() {
let inner = "<paired>1</paired>";
for len in [MAX_PAIR_RESPONSE_BYTES - 1, MAX_PAIR_RESPONSE_BYTES] {
assert!(parse_pair_response(&xml_padded_to(inner, len)).unwrap().paired, "{len}");
}
assert_too_large!(
parse_pair_response(&xml_padded_to(inner, MAX_PAIR_RESPONSE_BYTES + 1)),
MAX_PAIR_RESPONSE_BYTES,
MAX_PAIR_RESPONSE_BYTES + 1
);
assert_too_large!(parse_pair_response(&vec![b'0'; 1 << 22]), MAX_PAIR_RESPONSE_BYTES, 1 << 22);
// A plaincert near the cap: the hex text is within MAX_XML_TEXT_BYTES and decodes to half its size.
let cert = vec![0x41u8; 30_000];
let r = parse_pair_response(&answer(true, Some(("plaincert", &cert)))).unwrap();
assert_eq!(r.plain_cert.unwrap().len(), 30_000);
}
+727
View File
@@ -0,0 +1,727 @@
//! RTSP (`docs/PROTOCOL.md` 2): message parsers, the TCP framer (64 KiB cap), SDP and `surround-params`, the
//! ANNOUNCE builder and the client state machine, all with hostile input.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::indexing_slicing, missing_docs)]
mod common;
use domistream::Error;
use domistream::http::launch::AudioLayout;
use domistream::rtsp::client::VideoCodec;
use domistream::rtsp::sdp::{self, MAX_OPUS_CONFIGS, MAX_SDP_BYTES, MAX_SDP_LINES};
use domistream::rtsp::{
EncryptionFlags, HostCapabilities, MAX_RTSP_HEADERS, MAX_RTSP_LINE_BYTES, MAX_RTSP_MESSAGE_BYTES, Method,
RtspClient, RtspClientState, RtspFramer, RtspProgress, RtspRequest, StreamConfig, parse_request, parse_response,
};
use proptest::prelude::*;
macro_rules! assert_cap {
($e:expr, $max:expr) => {
match $e {
Err(Error::TooLarge { max, .. }) => assert_eq!(max, $max, "TooLarge.max"),
other => panic!("expected Err(TooLarge {{ max: {} }}), got {:?}", $max, other),
}
};
}
fn response(status: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
let mut m = format!("RTSP/1.0 {status}\r\n");
for (k, v) in headers {
m.push_str(&format!("{k}: {v}\r\n"));
}
m.push_str("\r\n");
let mut m = m.into_bytes();
m.extend_from_slice(body);
m
}
/// A 200 answer padded with a body to exactly `total` bytes.
fn response_of_size(total: usize) -> Vec<u8> {
let probe = response("200 OK", &[("CSeq", "1"), ("Content-Length", "00000")], b"");
let body_len = total - probe.len();
let cl = format!("{body_len:05}");
let m = response("200 OK", &[("CSeq", "1"), ("Content-Length", &cl)], &vec![b'b'; body_len]);
assert_eq!(m.len(), total);
m
}
// ================================================================================================ responses
#[test]
fn response_sample() {
let r = parse_response(&response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello")).unwrap();
assert_eq!(r.status, 200);
assert_eq!(r.reason, "OK");
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("Content-Length".into(), "5".into())]);
assert_eq!(r.body, b"hello");
assert_eq!(r.header("cseq"), Some("1"));
assert_eq!(r.header("CONTENT-LENGTH"), Some("5"));
// Without Content-Length the payload is everything after the headers (UNKNOWN U5).
let r = parse_response(&response("404 Not Found", &[("CSeq", "2")], b"rest")).unwrap();
assert_eq!(r.status, 404);
assert_eq!(r.reason, "Not Found");
assert_eq!(r.body, b"rest");
let r = parse_response(&response("200 OK", &[("content-length", "0")], b"")).unwrap();
assert!(r.body.is_empty());
}
#[test]
fn response_bad_start_lines() {
for bad in [
&b""[..],
b"R",
b"HTTP/1.1 200 OK\r\n\r\n",
b"RTSP/1.0 abc OK\r\n\r\n",
b"RTSP/1.0 2000 OK\r\n\r\n",
b"RTSP/1.0 -20 OK\r\n\r\n",
b"RTSP/1.0\r\n\r\n",
b"RTSP/2.0 200 OK\r\n\r\n",
b" RTSP/1.0 200 OK\r\n\r\n",
b"\r\n\r\n",
] {
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
}
}
#[test]
fn response_bad_headers() {
for bad in [
&b"RTSP/1.0 200 OK\r\nno colon here\r\n\r\n"[..],
b"RTSP/1.0 200 OK\r\n: empty name\r\n\r\n",
b"RTSP/1.0 200 OK\r\nCSeq: \xff\xfe\r\n\r\n",
b"RTSP/1.0 200 OK\r\nCSeq: 1\rX: y\r\n\r\n",
] {
assert_err!(parse_response(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
}
// Headers that never end.
assert_err!(parse_response(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n"), Error::Truncated { .. });
}
#[test]
fn response_lying_content_length() {
// Over: claims more than is there.
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "10")], b"12345")), Error::Truncated { .. });
// Under: more bytes than it claims.
assert_err!(parse_response(&response("200 OK", &[("Content-Length", "2")], b"12345")), Error::Malformed { .. });
for cl in ["abc", "-1", "+5", "5 5", "0x5", "", "5;"] {
assert_err!(parse_response(&response("200 OK", &[("Content-Length", cl)], b"12345")), Error::Malformed { .. }, "{cl:?}");
}
// Two different lengths.
assert_err!(
parse_response(&response("200 OK", &[("Content-Length", "5"), ("Content-Length", "4")], b"12345")),
Error::Malformed { .. }
);
// Past the cap: refused as too large, not waited for.
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "65537")], b"")), MAX_RTSP_MESSAGE_BYTES);
assert_cap!(parse_response(&response("200 OK", &[("Content-Length", "4294967295")], b"")), MAX_RTSP_MESSAGE_BYTES);
// Past u64: a number that big is over the cap or not a number; either way refused, never wrapped.
let r = parse_response(&response("200 OK", &[("Content-Length", "99999999999999999999999")], b""));
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{r:?}");
}
#[test]
fn response_header_flood() {
let names: Vec<String> = (0..=MAX_RTSP_HEADERS).map(|i| format!("X-H{i}")).collect();
let headers = |n: usize| names[..n].iter().map(|n| (n.as_str(), "v")).collect::<Vec<_>>();
assert_eq!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS), b"")).unwrap().headers.len(), MAX_RTSP_HEADERS);
assert_cap!(parse_response(&response("200 OK", &headers(MAX_RTSP_HEADERS + 1), b"")), MAX_RTSP_HEADERS);
// A flood of empty-valued headers in under 64 KiB.
let flood: Vec<(String, &str)> = (0..5000).map(|i| (format!("F{i}"), "")).collect();
let flood: Vec<(&str, &str)> = flood.iter().map(|(k, v)| (k.as_str(), *v)).collect();
assert_cap!(parse_response(&response("200 OK", &flood, b"")), MAX_RTSP_HEADERS);
}
#[test]
fn response_line_cap() {
// "X: " + value, without CRLF.
let value = |line: usize| "v".repeat(line - 3);
let ok = value(MAX_RTSP_LINE_BYTES);
assert_eq!(parse_response(&response("200 OK", &[("X", &ok)], b"")).unwrap().header("x"), Some(ok.as_str()));
assert_cap!(parse_response(&response("200 OK", &[("X", &value(MAX_RTSP_LINE_BYTES + 1))], b"")), MAX_RTSP_LINE_BYTES);
let reason = "r".repeat(MAX_RTSP_LINE_BYTES);
assert_cap!(parse_response(&response(&format!("200 {reason}"), &[], b"")), MAX_RTSP_LINE_BYTES);
}
#[test]
fn response_size_boundaries() {
for len in [MAX_RTSP_MESSAGE_BYTES - 1, MAX_RTSP_MESSAGE_BYTES] {
let r = parse_response(&response_of_size(len)).unwrap_or_else(|e| panic!("{len}: {e:?}"));
assert_eq!(r.status, 200);
}
assert_too_large!(parse_response(&response_of_size(MAX_RTSP_MESSAGE_BYTES + 1)), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
assert_too_large!(parse_response(&vec![b'R'; 1 << 24]), MAX_RTSP_MESSAGE_BYTES, 1 << 24);
}
// ================================================================================================ requests
#[test]
fn request_parse_and_encode() {
let raw = b"OPTIONS rtsp://192.0.2.10:48010 RTSP/1.0\r\nCSeq: 1\r\nX-GS-ClientVersion: 14\r\n\r\n";
let r = parse_request(raw).unwrap();
assert_eq!(r.method, Method::Options);
assert_eq!(r.target, "rtsp://192.0.2.10:48010");
assert_eq!(r.headers, vec![("CSeq".into(), "1".into()), ("X-GS-ClientVersion".into(), "14".into())]);
assert!(r.body.is_empty());
assert_eq!(r.encode().unwrap(), raw.to_vec(), "encode emits exactly the given headers, CRLF, empty line");
let announce = RtspRequest {
method: Method::Announce,
target: "streamid=control/13/0".into(),
headers: vec![("CSeq".into(), "6".into()), ("Content-Length".into(), "6".into())],
body: b"v=0\r\n\r".to_vec(),
};
let bytes = announce.encode().unwrap();
assert!(bytes.starts_with(b"ANNOUNCE streamid=control/13/0 RTSP/1.0\r\n"));
assert_eq!(parse_request(&bytes).unwrap(), announce);
for (m, name) in [
(Method::Options, "OPTIONS"),
(Method::Describe, "DESCRIBE"),
(Method::Setup, "SETUP"),
(Method::Announce, "ANNOUNCE"),
(Method::Play, "PLAY"),
] {
let req = RtspRequest { method: m, target: "x".into(), headers: vec![("CSeq".into(), "1".into())], body: vec![] };
assert!(req.encode().unwrap().starts_with(format!("{name} x RTSP/1.0\r\n").as_bytes()));
}
}
#[test]
fn request_refuses_unknown_methods_and_bad_lines() {
for m in ["GET_PARAMETER", "TEARDOWN", "options", "GET", "PAUSE"] {
let raw = format!("{m} rtsp://h:1 RTSP/1.0\r\nCSeq: 1\r\n\r\n");
assert_err!(parse_request(raw.as_bytes()), Error::UnexpectedValue { .. }, "{m}");
}
for bad in [&b""[..], b"O", b"OPTIONS\r\n\r\n", b"OPTIONS rtsp://h:1\r\n\r\n", b"OPTIONS rtsp://h:1 RTSP/9.9\r\n\r\n"] {
assert_err!(parse_request(bad), Error::Malformed { .. }, "{:?}", String::from_utf8_lossy(bad));
}
assert_too_large!(parse_request(&vec![b'O'; MAX_RTSP_MESSAGE_BYTES + 1]), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
}
#[test]
fn encode_refuses_header_injection() {
let base = || RtspRequest { method: Method::Setup, target: "streamid=video/0/0".into(), headers: vec![("CSeq".into(), "4".into())], body: vec![] };
let mut cases = Vec::new();
for evil in ["a\r\nX: y", "a\ny", "a\rb"] {
cases.push(RtspRequest { target: evil.into(), ..base() });
cases.push(RtspRequest { headers: vec![(evil.into(), "v".into())], ..base() });
cases.push(RtspRequest { headers: vec![("Transport".into(), evil.into())], ..base() });
}
cases.push(RtspRequest { headers: vec![("Bad:Name".into(), "v".into())], ..base() });
cases.push(RtspRequest { headers: vec![(String::new(), "v".into())], ..base() });
cases.push(RtspRequest { target: String::new(), ..base() });
for req in cases {
assert_err!(req.encode(), Error::Malformed { .. }, "{req:?}");
}
let big = RtspRequest { body: vec![0; MAX_RTSP_MESSAGE_BYTES], ..base() };
assert_cap!(big.encode(), MAX_RTSP_MESSAGE_BYTES);
}
fn method() -> impl Strategy<Value = Method> {
prop_oneof![Just(Method::Options), Just(Method::Describe), Just(Method::Setup), Just(Method::Announce), Just(Method::Play)]
}
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
/// encode then parse gives the request back.
#[test]
fn request_round_trip(
m in method(),
target in "[!-~]{1,40}",
headers in proptest::collection::vec(("[A-Za-z][A-Za-z0-9-]{0,15}", "[!-~]([ -~]{0,30}[!-~])?"), 0..10),
body in proptest::collection::vec(any::<u8>(), 0..200),
) {
let mut headers: Vec<(String, String)> =
headers.into_iter().filter(|(k, _)| !k.eq_ignore_ascii_case("content-length")).collect();
headers.insert(0, ("CSeq".into(), "1".into()));
if !body.is_empty() {
headers.push(("Content-Length".into(), body.len().to_string()));
}
let req = RtspRequest { method: m, target, headers, body };
let bytes = req.encode().map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
prop_assert_eq!(parse_request(&bytes), Ok(req));
}
/// Arbitrary bytes never panic, and a parsed response respects the caps.
#[test]
fn response_never_panics(data in proptest::collection::vec(any::<u8>(), 0..1024)) {
if let Ok(r) = parse_response(&data) {
prop_assert!(r.headers.len() <= MAX_RTSP_HEADERS);
prop_assert!(r.body.len() <= data.len());
prop_assert!(r.reason.len() <= MAX_RTSP_LINE_BYTES);
}
let _ = parse_request(&data);
}
}
// ================================================================================================ framer
fn drain(f: &mut RtspFramer) -> Vec<Vec<u8>> {
let mut out = Vec::new();
while let Some(m) = f.next_message().unwrap() {
out.push(m);
}
out
}
#[test]
fn framer_cuts_messages() {
let a = response("200 OK", &[("CSeq", "1"), ("Content-Length", "5")], b"hello");
let b = response("200 OK", &[("CSeq", "2"), ("Content-Length", "0")], b"");
let mut f = RtspFramer::new();
f.push(&[a.clone(), b.clone()].concat()).unwrap();
assert_eq!(drain(&mut f), vec![a.clone(), b.clone()]);
assert_eq!(f.buffered(), 0);
assert_eq!(f.finish(), Ok(None));
// One byte at a time: same messages, nothing early.
let mut f = RtspFramer::new();
let stream = [a.clone(), b.clone()].concat();
let mut got = Vec::new();
for (i, byte) in stream.iter().enumerate() {
f.push(std::slice::from_ref(byte)).unwrap();
got.extend(drain(&mut f));
if i + 1 < a.len() {
assert!(got.is_empty(), "message returned before its last byte");
}
}
assert_eq!(got, vec![a, b]);
}
#[test]
fn framer_partial_second_message_stays_buffered() {
let a = response("200 OK", &[("Content-Length", "2")], b"ok");
let partial = b"RTSP/1.0 200 OK\r\nCont";
let mut f = RtspFramer::new();
f.push(&[a.clone(), partial.to_vec()].concat()).unwrap();
assert_eq!(f.next_message().unwrap(), Some(a));
assert_eq!(f.next_message().unwrap(), None);
assert_eq!(f.buffered(), partial.len());
}
#[test]
fn framer_without_content_length_waits_for_close() {
let m = response("200 OK", &[("CSeq", "1")], b"payload until close");
let mut f = RtspFramer::new();
f.push(&m).unwrap();
assert_eq!(f.next_message().unwrap(), None, "no Content-Length: the message ends at close (U5)");
assert_eq!(f.finish().unwrap(), Some(m));
assert_eq!(f.buffered(), 0);
}
#[test]
fn framer_close_mid_body_is_truncated() {
let mut f = RtspFramer::new();
f.push(&response("200 OK", &[("Content-Length", "10")], b"12345")).unwrap();
assert_eq!(f.next_message().unwrap(), None);
assert_err!(f.finish(), Error::Truncated { .. });
}
#[test]
fn framer_cap_64k_plus_one() {
// Bytes that never form a complete header section.
let mut f = RtspFramer::new();
f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES]).unwrap();
assert_eq!(f.next_message().unwrap(), None);
assert_eq!(f.buffered(), MAX_RTSP_MESSAGE_BYTES);
assert_too_large!(f.push(b"a"), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
// One push over the cap.
let mut f = RtspFramer::new();
assert_too_large!(f.push(&vec![b'a'; MAX_RTSP_MESSAGE_BYTES + 1]), MAX_RTSP_MESSAGE_BYTES, MAX_RTSP_MESSAGE_BYTES + 1);
// A whole message of exactly the cap is fine.
let mut f = RtspFramer::new();
let m = response_of_size(MAX_RTSP_MESSAGE_BYTES);
f.push(&m).unwrap();
assert_eq!(f.next_message().unwrap(), Some(m));
}
/// Pushes `bytes` and asks for a message; the first error from either call.
fn push_then_next(f: &mut RtspFramer, bytes: &[u8]) -> domistream::Result<Option<Vec<u8>>> {
f.push(bytes)?;
f.next_message()
}
#[test]
fn framer_refuses_lying_content_length_early() {
// The header says the message will be over the cap: refused now, without waiting for (or buffering) it.
for cl in ["65537", "4294967295", "18446744073709551615"] {
let mut f = RtspFramer::new();
let r = push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"x"));
assert!(matches!(r, Err(Error::TooLarge { .. } | Error::Malformed { .. })), "{cl}: {r:?}");
}
let mut f = RtspFramer::new();
assert_cap!(push_then_next(&mut f, &response("200 OK", &[("Content-Length", "65537")], b"")), MAX_RTSP_MESSAGE_BYTES);
for cl in ["abc", "-1", "1 2"] {
let mut f = RtspFramer::new();
assert_err!(push_then_next(&mut f, &response("200 OK", &[("Content-Length", cl)], b"")), Error::Malformed { .. }, "{cl}");
}
}
#[test]
fn framer_empty_pushes() {
let mut f = RtspFramer::new();
f.push(b"").unwrap();
assert_eq!(f.next_message().unwrap(), None);
assert_eq!(f.finish().unwrap(), None);
}
proptest! {
#![proptest_config(ProptestConfig { cases: 128, ..ProptestConfig::default() })]
/// Any chunking of a stream of messages yields the same messages.
#[test]
fn framer_is_chunking_invariant(bodies in proptest::collection::vec(proptest::collection::vec(any::<u8>(), 0..300), 1..6), cuts in proptest::collection::vec(1usize..200, 1..50)) {
let msgs: Vec<Vec<u8>> = bodies.iter().enumerate()
.map(|(i, b)| response("200 OK", &[("CSeq", &i.to_string()), ("Content-Length", &b.len().to_string())], b))
.collect();
let stream = msgs.concat();
let mut f = RtspFramer::new();
let mut got = Vec::new();
let mut pos = 0;
let mut cut = cuts.iter().cycle();
while pos < stream.len() {
let end = (pos + cut.next().copied().unwrap_or(1)).min(stream.len());
f.push(&stream[pos..end]).map_err(|e| TestCaseError::fail(format!("{e:?}")))?;
while let Some(m) = f.next_message().map_err(|e| TestCaseError::fail(format!("{e:?}")))? {
got.push(m);
}
prop_assert!(f.buffered() <= MAX_RTSP_MESSAGE_BYTES);
pos = end;
}
prop_assert_eq!(got, msgs);
prop_assert_eq!(f.finish(), Ok(None));
}
}
// ================================================================================================ SDP
const DESCRIBE_SDP: &str = "v=0\r\no=- 0 14 IN IPv4 0.0.0.0\r\ns=Lab host\r\n\
a=x-ss-general.featureFlags:3\r\n\
a=x-ss-general.encryptionSupported:7\r\n\
a=x-nv-video[0].refPicInvalidation:1\r\n\
a=rtpmap:98 AV1/90000\r\n\
a=fmtp:96 packetization-mode=1\r\n\
sprop-parameter-sets=AAAAAU\r\n\
a=fmtp:97 surround-params=21101\r\n\
a=fmtp:97 surround-params=642012345\r\n\
a=fmtp:97 surround-params=85301234567\r\n\
a=recvonly\r\n";
#[test]
fn sdp_sample() {
let s = sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap();
assert_eq!(s.attribute("x-ss-general.featureFlags"), Some("3"));
assert_eq!(s.attribute("rtpmap"), Some("98 AV1/90000"));
assert_eq!(s.attribute("fmtp"), Some("96 packetization-mode=1"), "first one wins");
assert_eq!(s.attribute("recvonly"), Some(""), "flag attribute");
assert_eq!(s.attributes.iter().filter(|(n, _)| n == "fmtp").count(), 4);
assert_eq!(s.other[0], ('v', "0".to_string()));
assert!(s.other.iter().any(|(t, v)| *t == '\0' && v.contains("sprop-parameter-sets")), "{:?}", s.other);
// LF-only line ends give the same result.
assert_eq!(sdp::parse_sdp(DESCRIBE_SDP.replace("\r\n", "\n").as_bytes()).unwrap(), s);
assert_eq!(sdp::parse_sdp(b"").unwrap(), sdp::Sdp::default());
}
#[test]
fn sdp_hostile() {
for (bad, why) in [
(&b"v=0\r\nno equals sign\r\n"[..], "line without ="),
(b"a=x:\xff\r\n", "not UTF-8"),
(b"=x\r\n", "empty type"),
] {
assert_err!(sdp::parse_sdp(bad), Error::Malformed { .. }, "{why}");
}
let lines = |n: usize| "a=x:1\n".repeat(n);
assert_eq!(sdp::parse_sdp(lines(MAX_SDP_LINES).as_bytes()).unwrap().attributes.len(), MAX_SDP_LINES);
assert_cap!(sdp::parse_sdp(lines(MAX_SDP_LINES + 1).as_bytes()), MAX_SDP_LINES);
let sized = |n: usize| {
let mut s = "a=pad:".to_string();
s.push_str(&"p".repeat(n - s.len() - 1));
s.push('\n');
s
};
for n in [MAX_SDP_BYTES - 1, MAX_SDP_BYTES] {
assert!(sdp::parse_sdp(sized(n).as_bytes()).is_ok(), "{n}");
}
assert_too_large!(sdp::parse_sdp(sized(MAX_SDP_BYTES + 1).as_bytes()), MAX_SDP_BYTES, MAX_SDP_BYTES + 1);
assert_too_large!(sdp::parse_sdp(&vec![b'a'; 1 << 20]), MAX_SDP_BYTES, 1 << 20);
}
#[test]
fn surround_params() {
let c = sdp::parse_surround_params("21101").unwrap();
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.clone()), (2, 1, 1, vec![0, 1]));
let c = sdp::parse_surround_params("642012345").unwrap();
assert_eq!((c.channels, c.streams, c.coupled_streams), (6, 4, 2));
assert_eq!(c.mapping, vec![0, 1, 2, 3, 4, 5]);
let c = sdp::parse_surround_params("85301234567").unwrap();
assert_eq!((c.channels, c.streams, c.coupled_streams, c.mapping.len()), (8, 5, 3, 8));
let c = sdp::parse_surround_params("11000").unwrap_err();
assert!(matches!(c, Error::Malformed { .. }), "one channel needs one mapping digit, not two");
assert_eq!(sdp::parse_surround_params("1100").unwrap().mapping, vec![0]);
for (bad, why) in [
("", "empty"),
("2", "cut"),
("2110", "one mapping digit short"),
("211012", "one mapping digit too many"),
("21102", "mapping 2 >= streams + coupled"),
("21201", "coupled > streams"),
("01100", "zero channels"),
("20001", "zero streams"),
("2a101", "not a digit"),
("2 1101", "space"),
("9530123456789", "9 channels > MAX_AUDIO_CHANNELS"),
("-2110", "sign"),
] {
assert_err!(sdp::parse_surround_params(bad), Error::Malformed { .. }, "{why}: {bad:?}");
}
}
#[test]
fn host_capabilities() {
let caps = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
assert_eq!(caps.encryption_supported, EncryptionFlags(7));
assert_eq!(caps.feature_flags.0, 3);
assert!(caps.reference_frame_invalidation);
assert!(caps.av1);
assert_eq!(caps.opus_configs.len(), 3);
assert_eq!(caps.opus_configs[0].mapping, vec![0, 1]);
let none = HostCapabilities::from_sdp(&sdp::parse_sdp(b"v=0\n").unwrap()).unwrap();
assert_eq!(none, HostCapabilities::default());
for bad in [
"a=x-ss-general.encryptionSupported:x\n",
"a=x-ss-general.encryptionSupported:256\n",
"a=x-ss-general.featureFlags:-1\n",
"a=fmtp:97 surround-params=2110\n",
"a=fmtp:97 surround-params=\n",
] {
let s = sdp::parse_sdp(bad.as_bytes()).unwrap();
assert_err!(HostCapabilities::from_sdp(&s), Error::Malformed { .. }, "{bad:?}");
}
let many = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS + 1);
assert_cap!(HostCapabilities::from_sdp(&sdp::parse_sdp(many.as_bytes()).unwrap()), MAX_OPUS_CONFIGS);
let max = "a=fmtp:97 surround-params=21101\n".repeat(MAX_OPUS_CONFIGS);
assert_eq!(HostCapabilities::from_sdp(&sdp::parse_sdp(max.as_bytes()).unwrap()).unwrap().opus_configs.len(), MAX_OPUS_CONFIGS);
}
fn config() -> StreamConfig {
StreamConfig {
width: 1920,
height: 1080,
fps: 60,
bitrate_kbps: 20_000,
packet_size: 1024,
codec: VideoCodec::Hevc,
hdr: false,
audio: AudioLayout::Stereo,
audio_packet_duration_ms: 5,
min_fec_packets: 2,
reference_frame_invalidation: true,
encryption: EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::VIDEO | EncryptionFlags::AUDIO),
}
}
#[test]
fn announce_payload() {
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &host).unwrap()).expect("ANNOUNCE is valid SDP");
assert_eq!(s.attribute("x-nv-video[0].clientViewportWd"), Some("1920"));
assert_eq!(s.attribute("x-nv-video[0].clientViewportHt"), Some("1080"));
assert_eq!(s.attribute("x-nv-video[0].maxFPS"), Some("60"));
assert_eq!(s.attribute("x-nv-video[0].packetSize"), Some("1024"));
assert_eq!(s.attribute("x-ml-video.configuredBitrateKbps"), Some("20000"));
assert_eq!(s.attribute("x-nv-aqos.packetDuration"), Some("5"));
assert_eq!(s.attribute("x-nv-vqos[0].fec.minRequiredFecPackets"), Some("2"));
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
// Only what both sides support is turned on.
let mut partial = host.clone();
partial.encryption_supported = EncryptionFlags(EncryptionFlags::CONTROL_V2 | EncryptionFlags::AUDIO);
let s = sdp::parse_sdp(&sdp::build_announce(&config(), &partial).unwrap()).unwrap();
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("5"));
}
#[test]
fn announce_refuses_what_the_host_lacks() {
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(DESCRIBE_SDP.as_bytes()).unwrap()).unwrap();
let mut no_v2 = host.clone();
no_v2.encryption_supported = EncryptionFlags(EncryptionFlags::VIDEO | EncryptionFlags::AUDIO);
assert_err!(sdp::build_announce(&config(), &no_v2), Error::Unsupported { .. });
let mut no_av1 = host.clone();
no_av1.av1 = false;
assert_err!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &no_av1), Error::Unsupported { .. });
assert!(sdp::build_announce(&StreamConfig { codec: VideoCodec::Av1, ..config() }, &host).is_ok());
}
// ================================================================================================ client
const URL: &str = "rtsp://192.0.2.10:48010";
fn describe_answer(cseq: u32, sdp: &str) -> Vec<u8> {
response("200 OK", &[("CSeq", &cseq.to_string()), ("Content-Length", &sdp.len().to_string())], sdp.as_bytes())
}
fn setup_answer(cseq: u32, port: &str) -> Vec<u8> {
response(
"200 OK",
&[("CSeq", &cseq.to_string()), ("Session", "DEADBEEFCAFE;timeout = 90"), ("Transport", &format!("server_port={port}"))],
b"",
)
}
fn ok_answer(cseq: u32) -> Vec<u8> {
response("200 OK", &[("CSeq", &cseq.to_string())], b"")
}
fn next_request(c: &mut RtspClient) -> RtspRequest {
let bytes = c.poll_request().expect("a request is due");
assert_eq!(c.poll_request(), None, "each request is returned once");
parse_request(&bytes).expect("the client's request parses")
}
fn cseq(r: &RtspRequest) -> u32 {
r.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case("cseq")).expect("CSeq").1.parse().expect("CSeq number")
}
#[test]
fn client_full_negotiation() {
let mut c = RtspClient::new(URL, config()).unwrap();
assert_eq!(c.state(), RtspClientState::Options);
let expect = [
(Method::Options, RtspClientState::Describe),
(Method::Describe, RtspClientState::SetupAudio),
(Method::Setup, RtspClientState::SetupVideo),
(Method::Setup, RtspClientState::SetupControl),
(Method::Setup, RtspClientState::Announce),
(Method::Announce, RtspClientState::Play),
];
let mut last_cseq = 0;
let streams = ["streamid=audio", "streamid=video", "streamid=control"];
for (i, (method, next_state)) in expect.iter().enumerate() {
let req = next_request(&mut c);
assert_eq!(req.method, *method, "request {i}");
let n = cseq(&req);
assert!(n > last_cseq, "CSeq counts up");
last_cseq = n;
if *method == Method::Setup {
assert!(req.target.contains(streams[i - 2]), "SETUP {} target {:?}", i - 2, req.target);
assert!(req.headers.iter().any(|(k, _)| k.eq_ignore_ascii_case("transport")), "SETUP has Transport");
}
if *method == Method::Announce {
let s = sdp::parse_sdp(&req.body).unwrap();
assert_eq!(s.attribute("x-ss-general.encryptionEnabled"), Some("7"));
}
let answer = match i {
1 => describe_answer(n, DESCRIBE_SDP),
2 => setup_answer(n, "48000"),
3 => setup_answer(n, "47998"),
4 => setup_answer(n, "47999"),
_ => ok_answer(n),
};
assert_eq!(c.handle_response(&answer).unwrap(), RtspProgress::Continue);
assert_eq!(c.state(), *next_state);
}
let play = next_request(&mut c);
assert_eq!(play.method, Method::Play);
match c.handle_response(&ok_answer(cseq(&play))).unwrap() {
RtspProgress::Ready(n) => {
assert_eq!((n.ports.audio, n.ports.video, n.ports.control), (48000, 47998, 47999));
assert_eq!(n.encryption, EncryptionFlags(7));
assert_eq!(n.opus.mapping, vec![0, 1]);
assert_eq!(n.opus.channels, 2);
assert_eq!(n.session_id.as_deref(), Some("DEADBEEFCAFE"));
assert!(n.host.av1);
assert!(!n.ping_payload.is_empty());
}
RtspProgress::Continue => panic!("PLAY answered: expected Ready"),
}
assert_eq!(c.state(), RtspClientState::Ready);
assert_eq!(c.poll_request(), None);
assert_err!(c.handle_response(&ok_answer(last_cseq + 2)), Error::State { .. });
}
/// Runs the negotiation, answering with `answers(i, cseq)`; returns the first error and the state then.
fn run_until_error(answers: impl Fn(usize, u32) -> Vec<u8>) -> (Error, RtspClientState) {
let mut c = RtspClient::new(URL, config()).unwrap();
for i in 0..7 {
let req = next_request(&mut c);
if let Err(e) = c.handle_response(&answers(i, cseq(&req))) {
return (e, c.state());
}
}
panic!("negotiation finished without an error");
}
fn good(i: usize, n: u32) -> Vec<u8> {
match i {
1 => describe_answer(n, DESCRIBE_SDP),
2 => setup_answer(n, "48000"),
3 => setup_answer(n, "47998"),
4 => setup_answer(n, "47999"),
_ => ok_answer(n),
}
}
#[test]
fn client_refuses_hostile_answers() {
let (e, s) = run_until_error(|i, n| if i == 1 { ok_answer(n + 1) } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "CSeq mismatch: {e:?}");
assert_eq!(s, RtspClientState::Failed);
let (e, s) = run_until_error(|i, n| if i == 1 { response("404 Not Found", &[("CSeq", &n.to_string())], b"") } else { good(i, n) });
assert_eq!(e, Error::HostStatus { code: 404 });
assert_eq!(s, RtspClientState::Failed);
let no_v2 = DESCRIBE_SDP.replace("encryptionSupported:7", "encryptionSupported:6");
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, &no_v2) } else { good(i, n) });
assert!(matches!(e, Error::Unsupported { .. }), "host without control V2: {e:?}");
for port in ["0", "70000", "abc", ""] {
let (e, s) = run_until_error(|i, n| if i == 3 { setup_answer(n, port) } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "server_port={port:?}: {e:?}");
assert_eq!(s, RtspClientState::Failed);
}
let (e, _) = run_until_error(|i, n| if i == 2 { ok_answer(n) } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "SETUP answer without Transport: {e:?}");
let (e, _) = run_until_error(|i, n| if i == 1 { describe_answer(n, "v=0\nbroken line\n") } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "bad SDP: {e:?}");
let (e, _) = run_until_error(|i, n| if i == 0 { b"garbage".to_vec() } else { good(i, n) });
assert!(matches!(e, Error::Malformed { .. }), "garbage: {e:?}");
}
#[test]
fn client_answer_without_request() {
let mut c = RtspClient::new(URL, config()).unwrap();
let req = next_request(&mut c);
c.handle_response(&ok_answer(cseq(&req))).unwrap();
// DESCRIBE is due but its answer arrives twice.
let d = next_request(&mut c);
c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)).unwrap();
assert_err!(c.handle_response(&describe_answer(cseq(&d), DESCRIBE_SDP)), Error::State { .. });
}
#[test]
fn client_refuses_bad_setup() {
for url in ["http://192.0.2.10:48010", "rtsp://192.0.2.10", "rtsp://:48010", "", "rtsp://h:99999", "rtsp://h:1\r\nX: y"] {
assert_err!(RtspClient::new(url, config()), Error::Malformed { .. }, "{url:?}");
}
for broken in [
StreamConfig { width: 0, ..config() },
StreamConfig { height: 0, ..config() },
StreamConfig { fps: 0, ..config() },
StreamConfig { bitrate_kbps: 0, ..config() },
StreamConfig { packet_size: 0, ..config() },
] {
assert_err!(RtspClient::new(URL, broken), Error::Malformed { .. });
}
}
+73
View File
@@ -0,0 +1,73 @@
# Clean room
DomiStream is a clean-room implementation of the GameStream protocol (the one Moonlight clients and Sunshine hosts
speak). The protocol is written from public protocol notes and our own measurements, never from the code of a
GPL-licensed implementation. This file says what may be read, what may not, and logs every source used.
## Allowed sources
| Source | Licence | How we may use it |
| :-- | :-- | :-- |
| [Wolf protocol docs](https://games-on-whales.github.io/wolf/stable/protocols/index.html) and their sub-pages (pairing/HTTP, RTSP, control, RTP video, RTP Opus, input) | Docs site: CC BY-SA 4.0 "except where otherwise noted"; repo: MIT (see [research/open-point-2.md](research/open-point-2.md)) | Read for facts. Restate facts in our own words with a link. Never paste prose or diagrams. The diagram sources (PlantUML, bytefield, wavedrom) are part of the docs pages and may be read the same way. |
| [Moonshine](https://github.com/hgaiser/moonshine) | BSD-2-Clause | May be read. Facts taken are logged below. Code is not copied; if a snippet is ever borrowed, it keeps Moonshine's copyright line and licence text in the file that holds it. |
| RFCs and standards (RTP RFC 3550, RTSP RFC 2326, SDP RFC 4566, Opus RFC 6716 / RFC 7845, AES FIPS 197, GCM/CBC NIST SP 800-38D/38A, PKCS #1 RFC 8017, X.509 RFC 5280) | open standards | Read freely. |
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
| Our own measurements | ours | Captures between our client and a host on a **lab machine** (never Mark's PC, never Mark's TV, never 192.168.100.217). Captures stay out of git; only the facts and test vectors derived from them go in, with the date and setup. |
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
### Proposed additions (need the build lead's yes before use)
| Source | Licence | Why |
| :-- | :-- | :-- |
| [Stock ENet](https://github.com/lsalzman/enet) (`protocol.h`, `protocol.c`) | MIT | The ENet 1.3 wire format is not documented anywhere else in prose. The Wolf docs do not describe it. |
| [tokio-enet](https://github.com/hgaiser/tokio-enet) source | BSD-2-Clause | A pure-Rust ENet 1.3 used by Moonshine to talk to Moonlight clients. Its `src/protocol/` files were read for the command list (logged below, S-10). |
| [fec-rs](https://github.com/hgaiser/fec-rs) source | BSD-2-Clause | Its README says its field setup is compatible with Moonlight. Reading its matrix construction would settle UNKNOWN U14 (video FEC). |
## Forbidden
Never open, read, paste or port code from: **Sunshine, Moonlight (any client: Qt, Android, iOS, embedded, moonlight-tv),
moonlight-common-c, Moonlight's ENet fork, Apollo, Vibeshine, Rubylight, chiaki** (and forks of them). That also
means their source files on GitHub. Their READMEs and wikis are fine for facts.
### Second-hand GPL facts
Moonshine credits Sunshine for "groundwork" on the host side, and a few Moonshine comments cite Sunshine or
moonlight-common-c as the origin of a value. We treat such a value as **GPL-provenance**: it is logged, never
copied into DomiStream, and settled by our own measurement instead. Known cases:
| Where in Moonshine | What | What we do |
| :-- | :-- | :-- |
| `src/session/stream/audio/encoder.rs` | the fixed 2x4 Reed-Solomon parity matrix for audio FEC; the comment cites a moonlight-common-c file | Not taken. I saw the constant while reading the file; it is not in this repo. U16 in [PROTOCOL.md](PROTOCOL.md) says how to measure it ourselves. |
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
## How code gets written
1. Every fact in [PROTOCOL.md](PROTOCOL.md) carries a source tag that points to the log below.
2. A fact without a tag is UNKNOWN until a log entry or a measurement backs it.
3. Code comments cite the PROTOCOL.md section, not the outside source directly.
4. Anything borrowed (more than a fact) is attributed in the file that holds it and listed here.
5. A PR that adds a source adds a row to the log in the same PR.
## Source log
All entries by the DomiStream protocol engineer. Pinned commits are the ones read.
| # | Date | Source | What was taken |
| :-- | :-- | :-- | :-- |
| S-1 | 2026-11-25 | [Wolf: protocols index](https://games-on-whales.github.io/wolf/stable/protocols/index.html) | The six protocols, their default ports, which are encrypted (control AES-GCM 128, audio AES-CBC 128, video plain), that ports other than HTTP/S are dynamic. Licence footer (CC BY-SA 4.0). |
| S-2 | 2026-11-25 | [Wolf: HTTP/S pairing](https://games-on-whales.github.io/wolf/stable/protocols/http-pairing.html) incl. its PlantUML diagram sources | Phases 1-5; AES key from SHA-256(salt + PIN); the hash inputs of phase 2 and phase 4; field names `plaincert`, `challengeresponse`, `serverchallengeresp`, `pairingsecret`, `pairchallenge`, `paired`; phase 5 runs over HTTPS with the client certificate. |
| S-3 | 2026-11-25 | [Wolf: RTSP](https://games-on-whales.github.io/wolf/stable/protocols/rtsp.html) incl. diagram | Method order OPTIONS, DESCRIBE, SETUP (audio, video, control), ANNOUNCE, PLAY; message layout (start line, `CSeq`, options, empty line, payload); example `X-GS-ClientVersion: 14`, `a=fmtp:97 surround-params=21101`. |
| S-4 | 2026-11-25 | [Wolf: control](https://games-on-whales.github.io/wolf/stable/protocols/control-specs.html) incl. bytefield sources | ENet fork with IPv4 + IPv6; encrypted frame `type 0x0001 / len / seq / 16-byte tag / payload`, little-endian, seq used for the IV; message type codes; payloads of rumble, rumble triggers, motion event, RGB LED. |
| S-5 | 2026-11-25 | [Wolf: RTP video](https://games-on-whales.github.io/wolf/stable/protocols/rtp-video.html) incl. diagrams | PING to the negotiated port; packetSize default 1024 + 16-byte RTP header; 16-byte NV video header layout; flags (picture data 1, EOF 2, SOF 4); 8-byte frame prefix `01 37 63 68 61 72 73 73`; FEC example (4 KB, 1024, 50 % = 4 + 2); parity packets have flags 0; IDR requests over control. |
| S-6 | 2026-11-25 | [Wolf: RTP Opus](https://games-on-whales.github.io/wolf/stable/protocols/rtp-opus.html) incl. diagrams | 12-byte RTP header; 12-byte FEC header (shard index, payload type, base seq, base timestamp, SSRC); 4 data + 2 parity; AES-CBC with key and IV from the launch call, same key as control; PING. |
| S-7 | 2026-11-25 | [Wolf: input](https://games-on-whales.github.io/wolf/stable/protocols/input-data.html) incl. bytefield sources | INPUT_DATA layout (size BE, type LE); input type codes; layouts and example bytes for mouse move rel/abs, buttons, keys, scroll, hscroll, controller arrival, controller multi; key code table; button flags; controller types and capability bits. |
| S-8 | 2026-11-25 | GitHub API for [games-on-whales/wolf](https://github.com/games-on-whales/wolf) (`/repos`, `/git/trees/beta`, `LICENSE`, `docs/README.adoc`) | Repo licence MIT; the docs live in `docs/modules/protocols/pages/*.adoc` of the same repo; latest tag `v2026.11`. No source files of Wolf were read. |
| S-9 | 2026-11-25 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc`: `LICENSE`, `README.md`, `Cargo.toml`, `src/clients.rs`, `src/crypto.rs`, `src/webserver/pairing.rs`, `src/webserver/mod.rs`, `src/rtsp.rs`, `src/session/stream/control/mod.rs`, `src/session/stream/audio/{mod,encoder}.rs`, `src/session/stream/video/{mod,packetizer,shard_batch}.rs` | Facts tagged `[M]` in PROTOCOL.md: pairing query names, AES-128-ECB, key = first 16 bytes of SHA-256(salt + PIN), 16-byte salt/challenge/secret, RSA PKCS#1 v1.5 SHA-256, "certificate signature" = X.509 signatureValue bytes; serverinfo, applist and launch XML and query fields; SDP attribute names, SETUP reply headers, encryption flag bits; control IV layout and direction bytes, START_B starts the streams, INVALIDATE_REF_FRAMES and termination layouts, ENet host settings; audio IV, payload types 97/127, millisecond timestamps; video RTP/NV header byte layout, FEC bit fields and block split, video encryption prefix and IV; `PING` payload. Moonshine depends on `tokio-enet` for the control channel. |
| S-10 | 2026-11-25 | [tokio-enet](https://github.com/hgaiser/tokio-enet) at `364628ed754760c99e0df7bcc88e479ad91475c4`: `README.md`, `CHANGELOG.md`, `src/protocol/{mod,header,commands}.rs` | Claims wire compatibility with C ENet 1.3.x, BSD-2; ENet command numbers 1-12, command sizes, header flags (compressed 1<<14, sent time 1<<15, session bits 12-13), 4-byte command header, big-endian fields. Pending approval as an allowed source (see above). |
| S-11 | 2026-11-25 | crates.io API for `enet`, `enet-rs`, `nsys-enet`, `rusty_enet`, `tokio-enet`, `enet-sys`, `henet`, `enet-cs-sys`, `fec-rs`, `reed-solomon-erasure` and the RustCrypto crates | Licences, versions, repositories (see research/open-point-2.md and the Cargo manifest). |
| S-12 | 2026-11-25 | [docs.rs: rusty_enet](https://docs.rs/rusty_enet/latest/rusty_enet/) | Transpiled from C ENet; caller-supplied `Socket` trait and `HostSettings::time`; optional crc32 checksum; MIT. |
| S-13 | 2026-11-25 | [fec-rs README](https://github.com/hgaiser/fec-rs) | GF(2^8) with polynomial 0x1D (0x11D), "compatible with the Moonlight streaming protocol", reconstruction supported, BSD-2. |
| S-14 | 2026-11-25 | [moonlight-common-c README](https://github.com/moonlight-stream/moonlight-common-c) (README only) | Needs its bundled ENet; other ENet versions are incompatible; GPL-3.0. |
| S-15 | 2026-11-25 | [cgutman/enet](https://github.com/cgutman/enet) repository page (description only) | Forked from lsalzman/enet, has a `moonlight` branch. No files opened. |
| S-16 | 2026-11-25 | Roadmap brief §3.2 ([moonlight-android releases](https://github.com/moonlight-stream/moonlight-android/releases)) | Moonlight Android 12.1 added end-to-end stream encryption with Sunshine. |
+565
View File
@@ -0,0 +1,565 @@
# GameStream protocol, as DomiStream speaks it (client side)
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, Phase A (docs + API, no logic yet).
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
| Tag | Source |
| :-- | :-- |
| [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) |
| [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. |
| [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. |
| [T] | tokio-enet `364628e` (S-10), pending approval as a source |
| [F] | fec-rs README (S-13) |
| [RFC n] | the RFC |
**Not in DomiStream:** sockets, TLS, the clock, video decoding and **Opus decoding**. DomiStream hands the platform
layer (ArenaTV: webOS NDL, Android MediaCodec, Windows D3D11VA) a complete Annex-B access unit per video frame and one
Opus packet (or a "lost" marker) per audio packet, plus the Opus multistream configuration. Decoding, packet-loss
concealment and output are the platform's job.
---
## 0. Overview
Six protocols [W1]:
| Protocol | Default port | Transport | Protection | Purpose |
| :-- | :-- | :-- | :-- | :-- |
| HTTP | TCP 47989 | plain | none | server info, pairing |
| HTTPS | TCP 47984 | TLS, client certificate | TLS | app list, launch/resume/cancel, the last pairing step |
| RTSP | TCP 48010 | plain | none | negotiate the three streams |
| Control | UDP 47999 | ENet | AES-128-GCM per message | input, feedback, host events |
| Video | UDP 47998 | RTP | none by default; optional AES-128-GCM [M] | H.264 / HEVC / AV1 |
| Audio | UDP 48000 | RTP | AES-128-CBC | Opus |
All ports except HTTP/HTTPS can be changed by the host and reach the client through RTSP [W1].
Session order (client view): `serverinfo` (HTTP) → pair once (HTTP + one HTTPS step) → `applist` (HTTPS) →
`launch` (HTTPS, hands over the stream keys) → RTSP OPTIONS, DESCRIBE, SETUP ×3, ANNOUNCE, PLAY → UDP PING to the
video and audio ports + ENet connect to the control port → `START_B` on control → video and audio flow [W1][W3][M].
---
## 1. HTTP and HTTPS
Source: [Wolf: HTTP/S pairing](https://games-on-whales.github.io/wolf/stable/protocols/http-pairing.html) [W2], Moonshine `src/webserver/` and `src/clients.rs` [M].
### 1.1 Common shape
- Every call is a `GET` with a query string. Every response body is XML with one root:
`<root status_code="200">…</root>`; a non-200 `status_code` is an error, possibly with a `status_message`
attribute (UNKNOWN U27: attribute names on errors). [M]
- Every call carries `uniqueid=<client id>` [M]. Our client id: 16 random hex characters, stored with the pairing
(UNKNOWN U1: whether the host requires a particular form).
- Binary values travel as hex in both directions [M]. Our parser accepts upper and lower case.
- HTTPS: the host presents its certificate (the same one it sends as `plaincert` while pairing [M]); the client
presents its own certificate. Only a client certificate that completed pairing may call HTTPS APIs [W2].
The client **pins** the host certificate: the TLS certificate must equal the paired `plaincert` byte for byte.
TLS itself (version, ciphers) belongs to the platform layer (UNKNOWN U24: TLS versions Sunshine offers).
### 1.2 serverinfo
`GET /serverinfo?uniqueid=…` over HTTP (unpaired) or HTTPS (paired). `PairStatus` is 1 only over HTTPS with a
paired certificate [M]. Elements under `root` [M]:
| Element | Meaning |
| :-- | :-- |
| `hostname` | host name to show |
| `appversion` | protocol version string, e.g. `7.1.431.-1`; a negative fourth part marks the Sunshine-era protocol [M] |
| `GfeVersion` | compatibility version string |
| `uniqueid` | host id (stable across restarts) |
| `HttpsPort`, `ExternalPort` | HTTPS and HTTP ports |
| `mac` | MAC address for Wake-on-LAN (may be empty) |
| `LocalIP` | host's address as it sees it |
| `MaxLumaPixelsHEVC` | HEVC capability (0 = none) |
| `ServerCodecModeSupport` | codec bitmask (UNKNOWN U25: bit meanings) |
| `SupportedDisplayMode` | display modes (may be empty) |
| `PairStatus` | 1 = this client is paired |
| `currentgame` | running app id, 0 = none |
| `state` | busy/free string, host-specific suffix (e.g. `…_SERVER_BUSY`, `…_SERVER_FREE`) |
### 1.3 applist
`GET /applist?uniqueid=…` over HTTPS. One `<App>` per app with `<AppTitle>`, `<ID>` (decimal) and
`<IsHdrSupported>` (0/1) [M]. Box art: `GET /appasset?appid=<ID>…` returns an image [M] (not used: Arena Domi TV
shows Arena's own covers).
### 1.4 launch, resume, cancel
`GET /launch?…` over HTTPS. Parameters [M]:
| Parameter | Value |
| :-- | :-- |
| `appid` | app `ID` from applist |
| `mode` | `<width>x<height>x<fps>`, e.g. `1920x1080x60` |
| `rikey` | 16-byte AES key, hex. Used for control, audio and video encryption [W6][M] |
| `rikeyid` | integer key id, decimal. Feeds the audio IV (section 6.3) [M] |
| `hdrMode` | 0/1 |
| `surroundAudioInfo` | `(channel_mask << 16) | channel_count`; stereo default 196610 = `0x30002` [M] |
| others | UNKNOWN U4 (e.g. local audio playback, SOPS, gamepad mask, any version field) |
Response [M]: `<gamesession>1</gamesession>` and `<sessionUrl0>rtsp://<host>:<port></sessionUrl0>`
(UNKNOWN U4: what to assume when `sessionUrl0` is missing; we use port 48010 of the same host).
`GET /resume?rikey=…&rikeyid=…` reattaches to the running app with fresh keys [M]. `GET /cancel` quits the running
app [M]. `GET /unpair` forgets this client [M].
**Key rule (ours):** a fresh random `rikey` and `rikeyid` for every launch and resume. Counters behind the GCM
nonces restart with each session (section 7), so a reused key would reuse nonces.
### 1.5 Pairing
The host shows nothing to the user in Arena Domi: arena-host submits the PIN to Sunshine locally. On the wire the PIN
handshake is unchanged.
Inputs: `PIN` (4 ASCII digits [M]), the client's RSA certificate and key, randomness. Notation: `‖` concatenation,
`E_K` / `D_K` AES-128-ECB with key `K` and no padding (inputs are whole blocks) [M], `sig(cert)` the raw
`signatureValue` bytes of an X.509 certificate [M], `Sign`/`Verify` RSASSA-PKCS1-v1_5 with SHA-256 [M][RFC 8017].
| Step | Client sends | Host answers | Client then |
| :-- | :-- | :-- | :-- |
| 1 (HTTP) | `/pair?uniqueid&devicename&updateState=1&phrase=getservercert&salt=hex(salt)&clientcert=hex(client cert PEM)`; `salt` 16 random bytes | blocks until the PIN is entered on the host [M], then `paired=1`, `plaincert=hex(host cert PEM)` | derives `K = SHA-256(salt ‖ PIN)[0..16]` [W2][M]; stores the host cert |
| 2 (HTTP) | `clientchallenge=hex(E_K(C))`; `C` 16 random bytes | `challengeresponse=hex(E_K(H_s ‖ S_c))`, 48 bytes: `H_s = SHA-256(C ‖ sig(host cert) ‖ secret_s)`, `S_c` the 16-byte host challenge [W2][M] | decrypts, keeps `H_s` and `S_c`; cannot check `H_s` yet |
| 3 (HTTP) | `serverchallengeresp=hex(E_K(H_c))`, `H_c = SHA-256(S_c ‖ sig(client cert) ‖ secret_c)`, `secret_c` 16 random bytes | `pairingsecret=hex(secret_s ‖ Sign_host(secret_s))` [W2][M] | checks `Verify_host(secret_s, signature)` **and** `SHA-256(C ‖ sig(host cert) ‖ secret_s) == H_s`. Failure = wrong PIN or man in the middle: stop. |
| 4 (HTTP) | `clientpairingsecret=hex(secret_c ‖ Sign_client(secret_c))` | host checks `H_c` and the signature, answers `paired=1` (or `paired=0`) [W2][M] | |
| 5 (HTTPS) | `phrase=pairchallenge`, with the client certificate | `paired=1` [W2] | pairing done; store host cert + host `uniqueid` |
All step responses are `<root status_code="200"><paired>1</paired>…</root>` with the named element inside [M].
`paired` is `0` when the host refuses.
- UNKNOWN U1: whether Sunshine requires `devicename` / `updateState`, and the order of steps 4 and 5 (Wolf's diagram:
secret then HTTPS `pairchallenge`; Moonshine's comment lists `pairchallenge` first). We follow Wolf. Settle: lab
capture of a pairing against Sunshine.
- UNKNOWN U2: what Sunshine checks in the client certificate (key size, validity, subject). Our certificate: RSA-2048,
SHA-256, self-signed, long validity, `CN` from the device name. Settle: lab pairing.
- UNKNOWN U28: what a client should do after a failed step (call `/unpair`? just stop?). Settle: lab capture.
---
## 2. RTSP
Source: [Wolf: RTSP](https://games-on-whales.github.io/wolf/stable/protocols/rtsp.html) [W3], Moonshine `src/rtsp.rs` [M], [RFC 2326].
### 2.1 Messages
Plain text over TCP [W3]. A request is a start line `<METHOD> <target> RTSP/1.0`, header lines `Name: value`, an
empty line, then an optional payload; lines end in CRLF [W3]. A response starts `RTSP/1.0 <status> <reason>` [W3].
`CSeq` is always present and counts requests [W3]. Wolf's example carries `X-GS-ClientVersion: 14` [W3]
(UNKNOWN U5: which value Sunshine expects).
- UNKNOWN U5: framing. Wolf calls the payload "anything after the headers". Our framer uses `Content-Length` when
present and otherwise ends the message when the host closes the connection. Settle: lab capture (does Sunshine
close the TCP connection after each reply, and does it send `Content-Length`?).
- Target: `rtsp://<host>:<port>` from `sessionUrl0` [W3][M].
### 2.2 Sequence [W3]
| # | Request | Answer that matters |
| :-- | :-- | :-- |
| 1 | `OPTIONS` | 200 |
| 2 | `DESCRIBE` | SDP payload with the host's capabilities (2.3) |
| 3 | `SETUP` audio | `Transport: server_port=<audio port>` |
| 4 | `SETUP` video | `Transport: server_port=<video port>` |
| 5 | `SETUP` control | `Transport: server_port=<control port>` |
| 6 | `ANNOUNCE` | SDP payload from the client with the stream settings (2.4); 200 |
| 7 | `PLAY` | 200 |
SETUP details [M]: the target's query is `streamid=<audio|video|control>/…` (Moonshine's example:
`streamid=control/13/0`); a `Transport` header must be present (its value is not interpreted by Moonshine); the reply
has `Session: <id>;timeout = 90` and `Transport: server_port=<port>`.
- UNKNOWN U5: the exact SETUP targets and `Transport` value Sunshine expects, whether later requests must echo
`Session`, and the PLAY target.
- UNKNOWN U7: whether Sunshine's SETUP replies carry extra headers the client must use (for example a payload for the
UDP ping or a value for the ENet connect). Settle: lab capture.
### 2.3 DESCRIBE reply (host → client)
SDP-like lines, one attribute per line [M][RFC 4566]:
| Line | Meaning |
| :-- | :-- |
| `a=x-ss-general.featureFlags:<n>` | bit 0x01 pen/touch events, 0x02 controller touch events [M] |
| `a=x-ss-general.encryptionSupported:<n>` | bit 0x01 control V2, 0x02 video, 0x04 audio [M] |
| `a=x-nv-video[0].refPicInvalidation:1` | host can invalidate reference frames instead of sending an IDR [M] |
| `a=rtpmap:98 AV1/90000` | host can send AV1 [M] |
| `a=fmtp:96 packetization-mode=1` | H.264 packetization [M] |
| `sprop-parameter-sets=…` | present, value not used [M] |
| `a=fmtp:97 surround-params=<digits>` | one line per Opus configuration [W3][M] |
`surround-params` is a run of single decimal digits: channel count, stream count, coupled-stream count, then one
mapping digit per channel. Wolf's example `21101` = 2 channels, 1 stream, 1 coupled stream, mapping `0 1` [W3].
These are the Opus multistream parameters of [RFC 7845] §5.1.1 and go straight to the platform's Opus decoder.
UNKNOWN U26: the host advertises 5.1/7.1 normal-quality mappings with a channel rotated [M*]; settle by capture.
### 2.4 ANNOUNCE payload (client → host)
SDP attribute lines `a=<name>:<value>`. Names the host reads [M]; values and the full required set are UNKNOWN U6:
| Attribute | What |
| :-- | :-- |
| `x-nv-video[0].clientViewportWd`, `…clientViewportHt` | resolution |
| `x-nv-video[0].maxFPS` | frame rate |
| `x-nv-video[0].packetSize` | video packet size (default 1024 [W5]) |
| `x-nv-video[0].maxNumReferenceFrames` | 0 = host's choice when the decoder supports invalidation [M*] |
| `x-nv-video[0].refPicInvalidation` | client supports invalidation |
| `x-nv-video[0].dynamicRangeMode`, `…encoderCscMode` | HDR, colour space |
| `x-nv-vqos[0].bitStreamFormat` | codec |
| `x-nv-vqos[0].fec.minRequiredFecPackets` | minimum parity packets per block |
| `x-nv-vqos[0].qosTrafficType`, `x-nv-aqos.qosTrafficType` | DSCP class |
| `x-ml-video.configuredBitrateKbps` | bitrate |
| `x-nv-aqos.packetDuration` | audio packet duration in ms |
| `x-nv-audio.surround.enable`, `…numChannels`, `…channelMask`, `…AudioQuality` | audio layout |
| `x-ss-video[0].chromaSamplingType` | 4:2:0 / 4:4:4 |
| `x-ss-general.encryptionEnabled` | encryption flags the client turns on (bits as in 2.3) [M] |
Settle U6: lab capture of an ANNOUNCE accepted by Sunshine, then vary one attribute at a time.
---
## 3. Control channel (ENet + AES-GCM)
Source: [Wolf: control](https://games-on-whales.github.io/wolf/stable/protocols/control-specs.html) [W4], Moonshine `src/session/stream/control/mod.rs` [M], tokio-enet [T].
### 3.1 ENet
The control stream runs over a custom fork of ENet supporting IPv4 and IPv6 [W4]. What is known about the wire,
from stock ENet 1.3 as tokio-enet implements it [T] (all multi-byte fields big-endian):
- Datagram = protocol header + up to 32 commands. Header: `peer_id u16` whose top bits are flags (`1<<15` sent time
present, `1<<14` compressed) and bits 12-13 the session id; then `sent_time u16` if flagged.
- Command header (4 bytes): `command u8` (low 4 bits type, `0x80` acknowledge wanted, `0x40` unsequenced),
`channel_id u8`, `reliable_sequence u16`.
- Commands and total sizes: 1 acknowledge (8), 2 connect (48), 3 verify connect (44), 4 disconnect (8), 5 ping (4),
6 send reliable (6 + data), 7 send unreliable (8 + data), 8 send fragment (24 + data), 9 send unsequenced (8 + data),
10 bandwidth limit (12), 11 throttle configure (16), 12 send unreliable fragment (24 + data).
- MTU 576-4096, window 4096-65536, channels 1-255, peer id ≤ 0xFFF.
How the host uses it [M]: one peer per session; host created with a channel limit of 0x30; every host message is sent
**reliable on channel 0**. Moonshine does this with stock-wire ENet and real Moonlight clients (see
[research/open-point-2.md](research/open-point-2.md)).
UNKNOWN U9: anything Sunshine's ENet sends that stock 1.3 does not (checksum, compression, header or connect field
differences); the channel count, MTU and `connect data` the client should offer; ping interval and timeouts.
Settle: lab capture of one session, decoded with our parser.
### 3.2 Encrypted frame
Every control message is wrapped [W4] (little-endian):
| Offset | Size | Field |
| :-- | :-- | :-- |
| 0 | 2 | type, always `0x0001` |
| 2 | 2 | length of the rest (`4 + 16 + ciphertext`) |
| 4 | 4 | sequence number, increasing |
| 8 | 16 | GCM tag |
| 24 | n | ciphertext |
- Cipher: AES-128-GCM with the launch `rikey` [W4][W6].
- Nonce (12 bytes) [M]: bytes 0-3 the sequence number (LE), bytes 4-9 zero, byte 10 the direction (`'C'` client to
host, `'H'` host to client), byte 11 `'C'`. No associated data [M].
- Minimum frame: 24 bytes + at least the 4-byte message header [M].
- UNKNOWN U11: the first sequence number and whether the host rejects gaps or repeats. Settle: lab capture.
We start at 0, never reuse a number, and drop host frames whose number is not greater than the last accepted one
(replay protection, ours).
- UNKNOWN U10: whether anything is ever sent outside the wrapper once control encryption (V2) is negotiated. Our
client refuses to stream with a host that does not offer control V2.
### 3.3 Messages (decrypted payload)
`type u16 LE`, `length u16 LE` (bytes that follow, must equal the rest of the payload [M]), then the body [W4].
| Type | Name | Direction | Body |
| :-- | :-- | :-- | :-- |
| 0x0305 | START_A | client → host | UNKNOWN U10 |
| 0x0307 | START_B | client → host | UNKNOWN U10. The host starts video and audio when it arrives [M] |
| 0x0200 | PERIODIC_PING | client → host | UNKNOWN U10. Keeps the session alive; the host stops after a timeout without one [M] |
| 0x0201 | LOSS_STATS | client → host | UNKNOWN U10 |
| 0x0204 | FRAME_STATS | client → host | UNKNOWN U10 |
| 0x0206 | INPUT_DATA | client → host | section 4 |
| 0x0302 | IDR_FRAME (request) | client → host | UNKNOWN U10 (Moonshine ignores the body) |
| 0x0301 | INVALIDATE_REF_FRAMES | client → host | `first u32`, `reserved u32`, `last u32`, `reserved 12 bytes`, LE [M] |
| 0x0100 | TERMINATION | host → client | UNKNOWN U10 |
| 0x0109 | TERMINATION (extended) | host → client | `error_code u32 BE`; `0x80030023` = graceful [M] |
| 0x010b | RUMBLE_DATA | host → client | `unused 4`, `controller u16`, `low u16`, `high u16` [W4] |
| 0x5500 | RUMBLE_TRIGGERS | host → client | `controller u16`, `left u16`, `right u16` [W4] |
| 0x5501 | MOTION_EVENT | host → client | `controller u16`, `rate u16`, `type u8` (1 accelerometer, 2 gyroscope) [W4] |
| 0x5502 | RGB_LED | host → client | `controller u16`, `r u8`, `g u8`, `b u8` [W4] |
| 0x5503 | trigger effect | host → client | UNKNOWN [M] |
| 0x010e | HDR_MODE | host → client | `enabled u8` + 30 bytes HDR metadata (15 × u16 LE) [M*] |
UNKNOWN U23: Wolf states "all data is little-endian" for the frame; we assume LE for the host event bodies too.
---
## 4. Input and gamepad packets
Source: [Wolf: input](https://games-on-whales.github.io/wolf/stable/protocols/input-data.html) [W7].
An INPUT_DATA message (inside the encrypted frame) [W7]:
| Offset | Size | Field |
| :-- | :-- | :-- |
| 0 | 2 | `0x0206` LE |
| 2 | 2 | length LE = 4 + size |
| 4 | 4 | **size, big-endian** = 4 + data length |
| 8 | 4 | input type, LE |
| 12 | n | data |
Input types [W7]: MOUSE_MOVE_REL `0x07`, MOUSE_MOVE_ABS `0x05`, MOUSE_BUTTON_DOWN `0x08`, MOUSE_BUTTON_UP `0x09`,
KEY_DOWN `0x03`, KEY_UP `0x04`, MOUSE_SCROLL `0x0A`, MOUSE_HSCROLL `0x55000001`, TOUCH `0x55000002`,
PEN `0x55000003`, CONTROLLER_MULTI `0x0C`, CONTROLLER_ARRIVAL `0x55000004`, CONTROLLER_TOUCH `0x55000005`,
CONTROLLER_MOTION `0x55000006`, CONTROLLER_BATTERY `0x55000007`, HAPTICS `0x0D`, UTF8_TEXT `0x17`.
Data layouts [W7]:
| Type | Data |
| :-- | :-- |
| MOUSE_MOVE_REL | `dx i16 BE`, `dy i16 BE` |
| MOUSE_MOVE_ABS | `x i16 BE`, `y i16 BE`, `unused 2`, `width u16 BE`, `height u16 BE` (client viewport) |
| MOUSE_BUTTON_DOWN/UP | `button u8`: 1 left, 2 middle, 3 right, 4 side, 5 extra |
| KEY_DOWN/UP | `flags u8`, `key code u16 LE`, `modifiers u8`, `zero 2` |
| MOUSE_SCROLL | `amount1 i16 BE`, `amount2 i16 BE`, `zero 2`; hosts use amount1 |
| MOUSE_HSCROLL | `amount i16 BE` |
| CONTROLLER_ARRIVAL | `controller u8`, `type u8` (0 unknown, 1 Xbox, 2 PlayStation, 3 Nintendo), `capabilities u8`, `supported buttons u32` |
| CONTROLLER_MULTI | below |
Key codes are Windows virtual-key style (`0x41` A … `0x5A` Z, `0x70` F1 …, `0xA0`/`0xA1` shifts, …) [W7].
UNKNOWN U20: the example key packet carries `A4 80` (LE `0x80A4`) for LEFTALT `0xA4`, so the high byte has a flag
meaning; also the bit meanings of `flags` and `modifiers` (the example has `modifiers = 0x04` with Alt).
Controller capability bits [W7]: analog triggers 0x01, rumble 0x02, trigger rumble 0x04, touchpad 0x08,
accelerometer 0x10, gyro 0x20, battery 0x40, RGB LED 0x80.
**CONTROLLER_MULTI** data (26 bytes, LE) [W7]:
| Offset | Size | Field |
| :-- | :-- | :-- |
| 0 | 2 | `0x001A` |
| 2 | 2 | controller number |
| 4 | 2 | active mask (bit per connected controller; mask 0 with number 1 = controller 1 unplugged) |
| 6 | 2 | `0x0014` |
| 8 | 2 | button flags (low 16 bits) |
| 10 | 1 | left trigger |
| 11 | 1 | right trigger |
| 12 | 2 | left stick X, i16 |
| 14 | 2 | left stick Y, i16 |
| 16 | 2 | right stick X, i16 |
| 18 | 2 | right stick Y, i16 |
| 20 | 2 | `0x009C` |
| 22 | 2 | button flags (high 16 bits; 0 in the legacy format) |
| 24 | 2 | `0x0055` |
Buttons = `low | (high << 16)` [W7]: DPAD_UP 0x0001, DPAD_DOWN 0x0002, DPAD_LEFT 0x0004, DPAD_RIGHT 0x0008,
START 0x0010, BACK 0x0020, LEFT_STICK 0x0040, RIGHT_STICK 0x0080, LEFT_BUTTON 0x0100, RIGHT_BUTTON 0x0200,
HOME 0x0400, A 0x1000, B 0x2000, X 0x4000, Y 0x8000, PADDLE1-4 0x010000-0x080000, TOUCHPAD 0x100000,
MISC 0x200000.
UNKNOWN U21: layouts of TOUCH, PEN, CONTROLLER_TOUCH, CONTROLLER_MOTION, CONTROLLER_BATTERY, HAPTICS and
UTF8_TEXT (Wolf lists them without a layout). Not needed for Day 1 (gamepad + Magic Remote pointer + keys).
UNKNOWN U22: meaning of the constants `0x1A`, `0x14`, `0x9C`, `0x55`, and whether the arrival packet has more
bytes. Settle: lab capture with a gamepad.
### Test vectors QA can build from [W7]
Full INPUT_DATA messages (plaintext, before the encrypted frame), hex:
| Event | Bytes |
| :-- | :-- |
| relative move dx = -1, dy = 0 | `06 02 0C 00 00 00 00 08 07 00 00 00 FF FF 00 00` |
| absolute move x 1464, y 528, viewport 1919 × 1079 | `06 02 12 00 00 00 00 0E 05 00 00 00 05 B8 02 10 00 00 07 7F 04 37` |
| left button down | `06 02 09 00 00 00 00 05 08 00 00 00 01` |
| key down, code `0x80A4`, modifiers 0x04 | `06 02 0E 00 00 00 00 0A 03 00 00 00 00 A4 80 04 00 00` |
| scroll -120 | `06 02 0E 00 00 00 00 0A 0A 00 00 00 FF 88 FF 88 00 00` |
| horizontal scroll 30 | `06 02 0A 00 00 00 00 06 01 00 00 55 00 1E` |
| controller 0, active mask 1, right stick Y -104 | `06 02 22 00 00 00 00 1E 0C 00 00 00 1A 00 00 00 01 00 14 00 00 00 00 00 00 00 00 00 00 00 98 FF 9C 00 00 00 55 00` |
---
## 5. RTP video
Source: [Wolf: RTP video](https://games-on-whales.github.io/wolf/stable/protocols/rtp-video.html) [W5], Moonshine `src/session/stream/video/packetizer.rs` [M], [RFC 3550].
### 5.1 Ping
The SETUP port is not where video arrives from: the client sends a PING from its own UDP socket to that port, and
the host sends the stream back to the source address of the PING (NAT) [W5]. Moonshine accepts the 4 bytes `PING`
[M]. UNKNOWN U8: Sunshine's ping payload and how often to repeat it. Settle: lab capture.
### 5.2 Packet
Each packet is `packetSize + 16` bytes, `packetSize` from ANNOUNCE (default 1024) [W5]:
| Offset | Size | Field |
| :-- | :-- | :-- |
| 0 | 1 | RTP byte 0, `0x90` [M] (version 2, extension bit set) |
| 1 | 1 | payload type, 0 [M] |
| 2 | 2 | sequence number, BE [W5][RFC 3550] |
| 4 | 4 | timestamp, BE (UNKNOWN U29: clock rate, probably 90 kHz) |
| 8 | 4 | SSRC, 0 [M] |
| 12 | 4 | reserved [W5] |
| 16 | 4 | stream packet index, LE (= RTP sequence << 8 [M]) |
| 20 | 4 | frame index, LE [W5][M] |
| 24 | 1 | flags: 0x01 picture data, 0x02 end of frame, 0x04 start of frame [W5] |
| 25 | 1 | reserved [W5] |
| 26 | 1 | multi-FEC flags, `0x10` [M] (UNKNOWN U15: meaning) |
| 27 | 1 | multi-FEC blocks: bits 4-5 this block's index, bits 6-7 the last block's index [M] |
| 28 | 4 | FEC info, LE: bits 4-11 FEC percentage, bits 12-21 shard index in block, bits 22-31 data shards in block [M] |
| 32 | n | payload: `packetSize - 16` bytes of frame data |
A frame's data = an 8-byte frame header + the Annex-B bitstream (start codes `00 00 01` / `00 00 00 01`) [W5].
Wolf shows the 8 bytes as the constant `01 37 63 68 61 72 73 73` [W5]; Moonshine fills them as
`header type u8 = 0x01`, `processing latency u16 LE`, `frame type u8` (1 predicted, 2 key, 5 first frame after a
reference invalidation), `last shard payload length u32 LE` [M]. UNKNOWN U13: which one Sunshine sends. Our parser
returns the 8 bytes raw plus the structured reading. The last data shard is zero-padded to full size [M]; the
last-payload length (or the Annex-B content) tells where the frame really ends.
### 5.3 FEC
Reed-Solomon erasure code over GF(2^8), polynomial `0x11D` [F] [W5]:
- A frame splits into **blocks** (up to 4 [M]); each block has `k` data shards and
`m = ceil(k × percentage / 100)` parity shards, `k + m ≤ 255` [M]. Wolf's example: 4 KB at packetSize 1024 and
50 % → 4 data + 2 parity packets [W5].
- **Where the receiver gets the parameters:** from every packet of the block: `k` = FEC info bits 22-31, shard index =
bits 12-21 (0..k-1 data, k..k+m-1 parity), percentage = bits 4-11, block index and last block index from the
multi-FEC byte. `m` follows from `k` and the percentage. The requested percentage and the minimum parity count are
set by the client (`x-nv-vqos[0].fec.minRequiredFecPackets`, ANNOUNCE) [M].
- Shards are the **whole packets** (all `packetSize + 16` bytes, headers included) [M]. Parity packets have flags 0
[W5] and their RTP and NV header fields are written **after** the parity is computed [M], so parity bytes 0-31 are
not parity. Consequence for the receiver: a recovered data shard's bytes 0-31 are garbage; use only its payload
(offset 32 on) and take its place from the shard index.
- UNKNOWN U14: the generator matrix (systematic construction). fec-rs (BSD-2) claims Moonlight compatibility [F].
Settle: approve fec-rs as a source and read its construction, or measure: capture blocks with known losses and
check our decoder against them.
### 5.4 Feedback
On an unrecoverable frame the client asks for an IDR frame or, when the host advertised `refPicInvalidation`, sends
INVALIDATE_REF_FRAMES with the lost range (section 3.3) [W5][M].
---
## 6. RTP audio (Opus)
Source: [Wolf: RTP Opus](https://games-on-whales.github.io/wolf/stable/protocols/rtp-opus.html) [W6], Moonshine `src/session/stream/audio/encoder.rs` [M], [RFC 6716].
### 6.1 Ping
As for video: the client pings the SETUP audio port and audio comes back to the ping's source address [W6].
### 6.2 Packets
RTP header, 12 bytes [W6]: byte 0 `0x80` [M], payload type **97** for audio and **127** for FEC parity [M],
sequence BE, timestamp BE, SSRC 0 [M]. The timestamp counts **milliseconds** and advances by the packet duration
(`x-nv-aqos.packetDuration`) per packet [M].
Data packet: RTP header + one Opus packet [RFC 6716], encrypted (6.3).
Parity packet [W6]: RTP header (sequence continues after the 4 data packets [M]) + a 12-byte FEC header + parity:
| Offset | Size | Field |
| :-- | :-- | :-- |
| 12 | 1 | shard index (0 or 1) [W6][M] |
| 13 | 1 | payload type of the protected packets, 97 [M] |
| 14 | 2 | base sequence number, BE [W6][M] |
| 16 | 4 | base timestamp, BE [W6][M] |
| 20 | 4 | SSRC [W6] |
| 24 | n | parity bytes |
### 6.3 Encryption
AES-128-CBC with `rikey` [W6]. IV (16 bytes) [M]: `u32 BE (rikeyid + sequence number)` then 12 zero bytes; PKCS#7
padding [M]. UNKNOWN U17: Wolf says audio is always encrypted; Moonshine only when the audio flag is negotiated.
Settle: lab capture.
### 6.4 FEC
Every 4 data packets are followed by 2 parity packets [W6]. A block is the 4 data packets whose sequence numbers
start at a multiple of 4 [M]; the base sequence and timestamp in the FEC header are the first data packet's [M].
Shards are the encrypted payloads (all 4 the same length, constant-bitrate Opus) [M]. A lost data packet is rebuilt
from any 4 of the 6 packets; its RTP header comes from the base values (sequence = base + index, timestamp = base +
index × duration) [M].
UNKNOWN U16 (blocks audio FEC): the parity matrix. It is a fixed 2 × 4 matrix over GF(2^8), **not** the default
construction of the RS library Moonshine uses [M]. The only value we have seen carries GPL provenance and is not
used (see CLEAN_ROOM.md). Settle by measurement: capture a few audio blocks from a lab host and solve for the 8
coefficients (each parity byte is a linear combination of the 4 data bytes at the same offset: 4 unknowns per
parity row, so a handful of byte positions gives a unique solution). Until then, audio loss falls back to the
platform's packet-loss concealment.
### 6.5 Decoding
**Not DomiStream.** DomiStream outputs each Opus packet (or a "lost" marker) in sequence order plus the multistream
configuration from `surround-params` (section 2.3). ArenaTV decodes (NDL or libopus on webOS, MediaCodec on
Android) and does concealment.
---
## 7. Stream encryption
| Stream | When | Cipher | Key | Nonce / IV |
| :-- | :-- | :-- | :-- | :-- |
| Pairing | always | AES-128-ECB + RSA PKCS#1 v1.5 SHA-256 | SHA-256(salt ‖ PIN)[0..16] | none (ECB) |
| HTTPS | after pairing | TLS (platform), pinned host cert, client cert | | |
| Control | control V2 flag (0x01) | AES-128-GCM, 16-byte tag, no AAD | `rikey` | seq LE ‖ 6 zero ‖ dir (`C`/`H`) ‖ `C` [M] |
| Audio | audio flag (0x04) [M] (always, per [W6]) | AES-128-CBC, PKCS#7 | `rikey` | BE(rikeyid + seq) ‖ 12 zero [M] |
| Video | video flag (0x02) [M] | AES-128-GCM, 16-byte tag, no AAD | `rikey` | 8-byte LE counter ‖ 3 zero ‖ `V` [M] |
Negotiation: the host lists what it supports in DESCRIBE (`x-ss-general.encryptionSupported`), the client turns on
what it wants in ANNOUNCE (`x-ss-general.encryptionEnabled`) [M].
Encrypted video packet [M]: `IV 12 bytes ‖ frame number u32 LE ‖ tag 16 bytes ‖ ciphertext`, where the ciphertext is
the whole plaintext packet of section 5.2; FEC is applied before encryption, so the client decrypts first.
UNKNOWN U19: whether Sunshine uses this exact layout (Moonlight Android 12.1 added end-to-end encryption with
Sunshine, S-16). Settle: lab capture with video encryption on.
Our policy (Day 1: "stream encryption on"): request every flag the host supports; refuse to stream without control
V2; show in the stats overlay whether video is encrypted. A new `rikey`/`rikeyid` per launch and resume, because the
three nonce spaces (control `C`/`H`, video `V`) share one key and their counters restart per session. On top of this,
traffic goes through the Via Domi tunnel whenever Via is installed (roadmap J6).
---
## 8. UNKNOWNs
**B** = blocks a Day 1 stream against Sunshine. Almost everything is settled by **one lab capture** (a GameStream
client and Sunshine on a lab machine, not Mark's PC, his Sunshine or his TV); the column says what to look at.
| # | What | B | Settle by |
| :-- | :-- | :-- | :-- |
| U1 | Pairing query params beyond `uniqueid/phrase/salt/clientcert`; order of steps 4 and 5 | B | capture a pairing |
| U2 | Client certificate requirements | B | lab pairing with our certificate |
| U4 | Full launch parameter set; default when `sessionUrl0` is missing | B | capture a launch |
| U5 | RTSP framing, `X-GS-ClientVersion`, SETUP targets and `Transport`, `Session` echo, PLAY target | B | capture the RTSP exchange |
| U6 | ANNOUNCE attributes and values Sunshine requires | B | capture, then vary one at a time |
| U7 | Extra headers in SETUP replies | B | capture |
| U8 | UDP ping payload and repeat interval | B | capture |
| U9 | ENet differences from stock 1.3; client's channel count, MTU, connect data; ping/timeouts | B | capture, decode with our parser |
| U10 | Bodies of START_A, START_B, PERIODIC_PING, LOSS_STATS, FRAME_STATS, IDR request, TERMINATION; ping interval | B | capture, decrypted with the session's `rikey` |
| U11 | First control sequence number; host's replay rules | | capture |
| U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture |
| U14 | Video RS generator matrix | B (for FEC; video plays without it at zero loss) | read fec-rs (approval) or capture with loss |
| U15 | Multi-FEC flags `0x10` | | capture |
| U16 | Audio RS parity matrix | (audio plays without it) | capture, solve over GF(2^8) |
| U17 | Audio encryption always or only when negotiated | B | capture |
| U19 | Video encryption layout against Sunshine | | capture with video encryption on |
| U20 | Key code high byte, `flags`, `modifiers` bits | | capture with a keyboard |
| U21 | TOUCH, PEN, controller touch/motion/battery, HAPTICS, UTF8_TEXT layouts | | capture (Day 5 scope) |
| U22 | CONTROLLER_MULTI constants, arrival packet length | | capture with a gamepad |
| U23 | Endianness of host event bodies | | capture rumble |
| U24 | TLS versions and ciphers | | capture (platform concern) |
| U25 | `ServerCodecModeSupport` bits | | serverinfo from hosts with known codecs |
| U26 | Surround mapping rotation | | capture 5.1 |
| U27 | Error attributes on non-200 XML | | capture a refused call |
| U28 | Client behaviour after a failed pairing step | | capture a wrong PIN |
| U29 | Video RTP clock rate | | capture |
## 9. Notes on the Wolf docs
- The video FEC example sums the overhead as "32 * 6 + 2048 = 2248 bytes"; the arithmetic gives 2240.
- The button table lists both HOME and SPECIAL_FLAG as `0x0400`.
- The key table prints NUMPAD PLUS as `x6B` (meaning `0x6B`).
+96
View File
@@ -0,0 +1,96 @@
# Open point 2: Wolf docs licence, Rust ENet crates, and a clean ENet
Roadmap open point 2 asks three things before Day 1 code: the licence of the Wolf protocol docs, the licences of the
Rust ENet crates, and whether Moonlight's ENet changes can be met by a clean Rust implementation.
Checked 2026-11-25. Source numbers (S-n) refer to the log in [../CLEAN_ROOM.md](../CLEAN_ROOM.md).
## 1. Wolf: docs and repo
| What | Licence | Evidence |
| :-- | :-- | :-- |
| Docs site `games-on-whales.github.io/wolf` | **CC BY-SA 4.0**, "except where otherwise noted" | Footer of every page: "Copyright © ABeltramo and GOW contributors. Except where otherwise noted, docs are licensed under the Creative Commons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0)." ([index](https://games-on-whales.github.io/wolf/stable/protocols/index.html), S-1) |
| Repo `games-on-whales/wolf` | **MIT** | [`LICENSE`](https://github.com/games-on-whales/wolf/blob/beta/LICENSE), GitHub API reports `MIT` (S-8). The docs sources live in the same repo (`docs/modules/protocols/pages/*.adoc`). |
The two statements overlap: the `.adoc` files sit in an MIT repo, and the rendered site says CC BY-SA 4.0. We take the
stricter one (CC BY-SA 4.0) for the docs.
What that means for DomiStream (judgment, not legal advice):
- **Facts are free.** Port numbers, field layouts, message codes and algorithms are facts and methods. We can
implement them under CPAL-1.0.
- **Prose and diagrams are not ours to copy.** CC BY-SA content pasted into our docs would make that part
share-alike, and CC BY-SA 4.0 is not compatible with CPAL-1.0. So PROTOCOL.md restates the facts in our own words
and links each section to its Wolf page (attribution is good practice anyway).
- **Example bytes** (the input packet examples) are short functional data needed to interoperate. QA may rebuild
them from the documented field layout instead of copying the example lines; both give the same bytes.
## 2. Rust ENet crates
| Crate | Version (date) | Licence | What it is | Fits DomiStream? |
| :-- | :-- | :-- | :-- | :-- |
| [`rusty_enet`](https://github.com/jabuwu/rusty_enet) | 0.4.1 (2026-11-01) | MIT | Stock C ENet transpiled to Rust; caller supplies the `Socket` and a time function (`HostSettings::time`); optional crc32 checksum ([docs.rs](https://docs.rs/rusty_enet/latest/rusty_enet/), S-12) | Licence fits. Socket and time are pluggable, so it can run in memory. But it is transpiled C (pointer-heavy, `unsafe` inside), stock ENet only, and its API is the C host/peer model rather than bytes in/events out. Good as a **test oracle**, weak as the parser of hostile input. |
| [`tokio-enet`](https://github.com/hgaiser/tokio-enet) | 0.1.1 (2026-06-14) | BSD-2-Clause | Pure-Rust ENet, "wire-compatible with the C ENet v1.3.x protocol" ([README](https://github.com/hgaiser/tokio-enet), S-10). **Moonshine uses it for its control stream with Moonlight clients** (S-9). | Licence fits. Bound to tokio sockets and the clock, so not sans-I/O; cannot run on webOS without tokio. Its existence is the strongest evidence for the compatibility question below. |
| [`enet`](https://github.com/futile/enet-rs) | 0.3.0 (2022-03-30) | MIT OR Apache-2.0 | Bindings to the C library through `enet-sys` | Not pure Rust, not sans-I/O, stock ENet. No. |
| [`enet-sys`](https://github.com/ruabmbua/enet-sys) | 1.0.5 (2026-03-16) | MIT | Raw FFI to C ENet | No (C, FFI, stock). |
| [`enet-rs`](https://github.com/ZTzTopia/enet-rs) | 1.3.171 (2021-08-29) | ISC | Bindings for C ENet 1.3.17 | No (C, unmaintained). |
| [`nsys-enet`](https://github.com/spearman/enet-rs) | 0.2.2 (2026-07-07) | Apache-2.0 | Rust interface to C ENet | No (C). |
| [`enet-cs-sys`](https://github.com/Kalkatral/enet-cs-sys) | 0.1.1 (2023-02-25) | MIT | Bindings to ENet-CSharp, a different, incompatible ENet fork | No. |
| [`henet`](https://github.com/dehorsed/henet) | 0.1.0 (published 2026-11-25) | MIT OR Apache-2.0 | "Idiomatic Rust implementation of ENet" | Too new to judge; first release today. |
All licences above (MIT, Apache-2.0, BSD-2-Clause, ISC) are permissive and fit a CPAL-1.0 project as dependencies.
None of these crates is GPL. None is a port of Moonlight's ENet fork.
## 3. Can Moonlight's ENet semantics be met by a clean Rust implementation?
What is documented:
- Wolf: the control stream "runs over UDP via a custom fork of ENET that supports IPV4 and IPV6" and every message
inside is AES-GCM framed ([control](https://games-on-whales.github.io/wolf/stable/protocols/control-specs.html), S-4).
Wolf documents nothing else about the fork: no wire change, no extra command.
- moonlight-common-c README: the client "requires the specific version of ENet that is bundled" and other versions
are "incompatible", with a crash warning against recent GeForce Experience (S-14). It does not say which bytes differ.
- IPv6 support is a socket-address change in the C library. It does not appear on the ENet wire: ENet datagrams
carry no addresses.
What is measured by others:
- Moonshine (BSD-2) serves real Moonlight clients with `tokio-enet`, a stock ENet 1.3 wire implementation
(S-9, S-10): one peer, `channel_limit 0x30`, every host message sent reliable on channel 0. So **whatever the fork
changes, a stock-1.3 wire host interoperates with Moonlight clients**.
What is not known (UNKNOWN U9 in PROTOCOL.md):
- whether Sunshine (which ships the fork on the host side) *sends* anything a stock 1.3 peer would reject: a
checksum, a different `connect`/`verify connect` field, a different MTU, window or timeout default;
- which `connect data` value, channel count and MTU a client must offer.
Settled by our own measurement: a capture of the control channel between a GameStream client and Sunshine on a
lab machine (not Mark's PC), decoded with our own ENet parser. One session is enough to see the handshake fields.
**Answer: yes.** Nothing documented points at a wire change, and a stock-wire Rust ENet already talks to
Moonlight clients. The fork's differences that matter to us can be found by measurement; we do not need its code.
### What we write ourselves
A sans-I/O ENet 1.3 **client** subset in `domistream::enet`, `#![forbid(unsafe_code)]`:
| Part | Scope |
| :-- | :-- |
| Datagram codec | protocol header (peer id, session bits, compressed flag rejected, optional sent time), command header, all 12 commands; strict lengths, caps (`MAX_DATAGRAM_BYTES` 4096, 32 commands per datagram) |
| Connection | connect, verify connect, disconnect (incl. disconnect-later), ping, timeout |
| Reliability | reliable sequence numbers per channel, acknowledgements, retransmission with RTT-based timeout, reliable window |
| Delivery | reliable, unreliable sequenced, unsequenced, fragments (send + reassembly, capped) |
| Throttle | parse `throttle configure` and `bandwidth limit`; honour the window; no bandwidth shaping beyond that (the control channel is tiny) |
| Not written | host side, many peers, compression (refused), the crc32 checksum (UNKNOWN whether used; refused until measured) |
About 1,500-2,500 lines with tests. Tests: our client against `rusty_enet` (MIT) as a **dev-dependency** host over an
in-memory socket (no network, deterministic time), plus fuzzing of the datagram codec, plus the lab capture as a
recorded vector once it exists.
## Recommendation
1. **Write the ENet client ourselves** (`domistream::enet`, sans-I/O, no unsafe). Do not depend on an ENet crate at
runtime: the only pure-Rust ones are either tokio-bound (`tokio-enet`) or transpiled C (`rusty_enet`), and this
code parses hostile datagrams.
2. **Use `rusty_enet` (MIT) as a dev-dependency** for in-memory interop tests only.
3. **Approve stock ENet (MIT) and tokio-enet (BSD-2) as reference sources** in CLEAN_ROOM.md, because the ENet wire
format is documented nowhere else. Moonlight's fork stays forbidden.
4. **Book one lab capture** (client to Sunshine on a lab machine) to settle U9 and the other measurement-only
unknowns in PROTOCOL.md in one go. It must not be Mark's PC, his Sunshine install or his TV.
5. **Docs licence:** treat the Wolf docs as CC BY-SA 4.0: facts only, our own words, link every section.
+633
View File
@@ -0,0 +1,633 @@
# 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 = "arbitrary"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed"
[[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 = "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 = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"jobserver",
"libc",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[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 = "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",
"getrandom",
"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 = [
"getrandom",
"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",
"rand_core",
"rsa",
"sha2",
"x509-cert",
"zeroize",
]
[[package]]
name = "domistream-fuzz"
version = "0.0.0"
dependencies = [
"cc",
"domistream",
"libfuzzer-sys",
]
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[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 = "jobserver"
version = "0.1.35"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"
dependencies = [
"getrandom",
"libc",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "libfuzzer-sys"
version = "0.4.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2"
dependencies = [
"arbitrary",
"cc",
]
[[package]]
name = "num-traits"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[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 = "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_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[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 = "sha1"
version = "0.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
dependencies = [
"cfg-if",
"cpufeatures",
"digest",
]
[[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 = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[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 = "tls_codec"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
dependencies = [
"tls_codec_derive",
"zeroize",
]
[[package]]
name = "tls_codec_derive"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[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",
"sha1",
"signature",
"spki",
"tls_codec",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
dependencies = [
"zeroize_derive",
]
[[package]]
name = "zeroize_derive"
version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
+157
View File
@@ -0,0 +1,157 @@
# Fuzz targets: one per DomiStream parser. Its own workspace, built only for fuzzing, never released.
#
# Linux, nightly, cargo-fuzz:
# cargo fuzz run <target> -- -max_total_time=600
#
# Windows, stable MSVC, no cargo-fuzz, no sanitizer (same setup as Via's via-core/fuzz): build.rs + win_sections.c
# give SanitizerCoverage's counters their section bounds, so the targets link without a sanitizer runtime.
# cd fuzz
# RUSTFLAGS="-Cpasses=sancov-module -Cllvm-args=-sanitizer-coverage-level=4
# -Cllvm-args=-sanitizer-coverage-inline-8bit-counters -Cllvm-args=-sanitizer-coverage-trace-compares
# -Cllvm-args=-simplifycfg-branch-fold-threshold=0 -Ccodegen-units=1 --cfg fuzzing -Cdebug-assertions
# -Clink-arg=/include:main" \
# cargo build --release --target x86_64-pc-windows-msvc --bin <target>
# target/x86_64-pc-windows-msvc/release/<target>.exe -max_total_time=600 corpus/<target>
# A plain `cargo build` here does not link on Windows (LNK1561: libFuzzer's `main` needs `/include:main`); use the
# RUSTFLAGS above. Checked 2026-11-25: enet_datagram built this way ran 12,183,242 inputs in 11 s.
# corpus/ and artifacts/ stay out of git. Never set CARGO_TARGET_DIR.
[package]
name = "domistream-fuzz"
version = "0.0.0"
edition = "2024"
publish = false
license = "CPAL-1.0"
[package.metadata]
cargo-fuzz = true
[build-dependencies]
cc = "1"
[dependencies]
libfuzzer-sys = "0.4"
domistream = { path = "../crates/domistream" }
# Its own workspace, so the fuzz build never joins the main one (cargo fuzz's layout).
[workspace]
members = ["."]
[[bin]]
name = "xml"
path = "fuzz_targets/xml.rs"
test = false
doc = false
bench = false
[[bin]]
name = "server_info"
path = "fuzz_targets/server_info.rs"
test = false
doc = false
bench = false
[[bin]]
name = "app_list"
path = "fuzz_targets/app_list.rs"
test = false
doc = false
bench = false
[[bin]]
name = "launch_response"
path = "fuzz_targets/launch_response.rs"
test = false
doc = false
bench = false
[[bin]]
name = "pair_response"
path = "fuzz_targets/pair_response.rs"
test = false
doc = false
bench = false
[[bin]]
name = "server_cert_pem"
path = "fuzz_targets/server_cert_pem.rs"
test = false
doc = false
bench = false
[[bin]]
name = "rtsp_response"
path = "fuzz_targets/rtsp_response.rs"
test = false
doc = false
bench = false
[[bin]]
name = "rtsp_request"
path = "fuzz_targets/rtsp_request.rs"
test = false
doc = false
bench = false
[[bin]]
name = "sdp"
path = "fuzz_targets/sdp.rs"
test = false
doc = false
bench = false
[[bin]]
name = "rtsp_framer"
path = "fuzz_targets/rtsp_framer.rs"
test = false
doc = false
bench = false
[[bin]]
name = "enet_datagram"
path = "fuzz_targets/enet_datagram.rs"
test = false
doc = false
bench = false
[[bin]]
name = "control_frame"
path = "fuzz_targets/control_frame.rs"
test = false
doc = false
bench = false
[[bin]]
name = "control_message"
path = "fuzz_targets/control_message.rs"
test = false
doc = false
bench = false
[[bin]]
name = "input"
path = "fuzz_targets/input.rs"
test = false
doc = false
bench = false
[[bin]]
name = "rtp_header"
path = "fuzz_targets/rtp_header.rs"
test = false
doc = false
bench = false
[[bin]]
name = "video_packet"
path = "fuzz_targets/video_packet.rs"
test = false
doc = false
bench = false
[[bin]]
name = "audio_packet"
path = "fuzz_targets/audio_packet.rs"
test = false
doc = false
bench = false
+7
View File
@@ -0,0 +1,7 @@
// Windows only: give the coverage counters their section bounds (see win_sections.c).
fn main() {
println!("cargo:rerun-if-changed=win_sections.c");
if std::env::var("CARGO_CFG_TARGET_ENV").as_deref() == Ok("msvc") {
cc::Build::new().file("win_sections.c").compile("win_sections");
}
}
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes `/applist` answers: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::http::parse_app_list(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes audio packets: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::audio::parse_audio_packet(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes encrypted control frames (outer fields): never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::control::parse_encrypted_frame(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes decrypted control messages from the host: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::control::parse_host_message(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes ENet datagrams: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::enet::protocol::parse_datagram(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes INPUT_DATA messages: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::input::parse_input(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes `/launch` and `/resume` answers: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::http::parse_launch_response(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes pairing answers: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::pairing::parse_pair_response(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes the RTP header: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::rtp::parse_rtp_header(data);
});
+23
View File
@@ -0,0 +1,23 @@
//! Fuzzes the RTSP framer over a chunked byte stream: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
// First byte picks the chunk size, so libFuzzer explores message boundaries across pushes.
let Some((&chunk, rest)) = data.split_first() else { return };
let chunk = usize::from(chunk).max(1);
let mut framer = domistream::rtsp::RtspFramer::new();
for piece in rest.chunks(chunk) {
if framer.push(piece).is_err() {
return;
}
while let Ok(Some(message)) = framer.next_message() {
let _ = domistream::rtsp::parse_response(&message);
}
}
let _ = framer.finish();
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes RTSP requests: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::rtsp::parse_request(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes RTSP responses: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::rtsp::parse_response(data);
});
+13
View File
@@ -0,0 +1,13 @@
//! Fuzzes SDP payloads and the host capabilities read from them: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
if let Ok(sdp) = domistream::rtsp::sdp::parse_sdp(data) {
let _ = domistream::rtsp::HostCapabilities::from_sdp(&sdp);
}
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes the host certificate PEM (`plaincert`): never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::pairing::ServerCert::from_pem(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes `/serverinfo` answers: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::http::parse_server_info(data);
});
+12
View File
@@ -0,0 +1,12 @@
//! Fuzzes video packets and the frame header: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::video::parse_video_packet(data);
let _ = domistream::video::packet::parse_frame_header(data);
});
+11
View File
@@ -0,0 +1,11 @@
//! Fuzzes the XML reader behind every HTTP answer: never panics, whatever the bytes.
//! Phase A: the parser returns `Unimplemented`; QA adds the properties (round trips, caps) with the logic.
//! How to run: see the comment at the top of `fuzz/Cargo.toml`.
#![no_main]
use libfuzzer_sys::fuzz_target;
fuzz_target!(|data: &[u8]| {
let _ = domistream::http::xml::parse(data);
});
+9
View File
@@ -0,0 +1,9 @@
/* Section bounds for SanitizerCoverage's inline 8-bit counters on Windows (COFF), so the fuzz targets link
* without a sanitizer runtime. LLVM puts the counters in ".SCOV$CM"; the linker sorts ".SCOV$CA" before it and
* ".SCOV$CZ" after it, and libFuzzer reads everything in between. compiler-rt does the same in
* sanitizer_coverage_win_sections.cpp, which only ships inside a sanitizer runtime. Built only for MSVC targets
* and only for the fuzz crate, which is never part of a release. */
#pragma section(".SCOV$CA", read, write)
__declspec(allocate(".SCOV$CA")) unsigned char __start___sancov_cntrs[1] = {0};
#pragma section(".SCOV$CZ", read, write)
__declspec(allocate(".SCOV$CZ")) unsigned char __stop___sancov_cntrs[1] = {0};
+2
View File
@@ -0,0 +1,2 @@
max_width = 120
use_small_heuristics = "Max"
+32
View File
@@ -0,0 +1,32 @@
// AES-128-GCM test vectors for DomiStream (control frames and video packets), computed with .NET's AesGcm, a
// crypto implementation independent of the RustCrypto crates DomiStream uses.
//
// Run by gen_vectors.py (`dotnet run gcm_vectors.cs -- <input> <output>`), never by hand. Input lines:
// <name> <key hex> <nonce hex> <plaintext hex>
// Output lines:
// <name> <ciphertext hex> <tag hex>
// No associated data, 16-byte tags (docs/PROTOCOL.md 3.2 and 7). Keys are fixed test-only values.
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
var input = File.ReadAllLines(args[0]);
var output = new StringBuilder();
foreach (var line in input)
{
if (line.Trim().Length == 0) continue;
var parts = line.Split(' ');
var key = Convert.FromHexString(parts[1]);
var nonce = Convert.FromHexString(parts[2]);
var plaintext = parts[3] == "-" ? Array.Empty<byte>() : Convert.FromHexString(parts[3]);
var ciphertext = new byte[plaintext.Length];
var tag = new byte[16];
using var gcm = new AesGcm(key, 16);
gcm.Encrypt(nonce, plaintext, ciphertext, tag);
output.Append(parts[0]).Append(' ')
.Append(ciphertext.Length == 0 ? "-" : Convert.ToHexString(ciphertext)).Append(' ')
.Append(Convert.ToHexString(tag)).Append('\n');
}
File.WriteAllText(args[1], output.ToString());
+437
View File
@@ -0,0 +1,437 @@
#!/usr/bin/env python3
"""Generates DomiStream's crypto test vectors with tools that are independent of the RustCrypto crates DomiStream
uses: Python's hashlib (SHA-256), the OpenSSL 3.x command line (RSA keys, X.509 certificates, PKCS#1 v1.5 SHA-256
signatures, AES-128-ECB without padding, AES-128-CBC with PKCS#7) and .NET's AesGcm (AES-128-GCM, gcm_vectors.cs).
Everything written here is TEST-ONLY: the keys are made fresh on this machine for the tests, never a real host's
or client's, and must never be used for anything else. Values follow docs/PROTOCOL.md (sections in the comments).
python tools/vectors/gen_vectors.py # recompute vectors, keep the existing test keys
python tools/vectors/gen_vectors.py --fresh-keys # also make new test keys and certificates
Environment: DOMISTREAM_OPENSSL (path to openssl, default: Git for Windows' OpenSSL 3.5, then PATH) and
DOMISTREAM_DOTNET (default: dotnet on PATH). Standard library only; nothing is installed or downloaded.
Output: crates/domistream/tests/fixtures/ (text only: hex and PEM).
"""
import argparse
import hashlib
import os
import shutil
import subprocess
import sys
import tempfile
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
HERE = os.path.dirname(os.path.abspath(__file__))
FIXTURES = os.path.join(ROOT, "crates", "domistream", "tests", "fixtures")
HEADER = (
"# Generated by tools/vectors/gen_vectors.py. TEST-ONLY values and keys, made for DomiStream's tests.\n"
"# Never a real host's or client's key. Do not edit by hand: change the script and run it again.\n"
)
def find_openssl():
env = os.environ.get("DOMISTREAM_OPENSSL")
if env:
return env
git = r"C:\Program Files\Git\mingw64\bin\openssl.exe"
if os.path.exists(git):
return git
found = shutil.which("openssl")
if not found:
sys.exit("openssl not found; set DOMISTREAM_OPENSSL")
return found
OPENSSL = find_openssl()
DOTNET = os.environ.get("DOMISTREAM_DOTNET") or shutil.which("dotnet") or "dotnet"
WORK = tempfile.mkdtemp(prefix="domistream-vectors-")
OPENSSL_CNF = os.path.join(WORK, "openssl.cnf")
with open(OPENSSL_CNF, "w", encoding="ascii") as f:
f.write("[req]\ndistinguished_name = dn\nprompt = no\n[dn]\n")
def run(args, stdin=None):
env = dict(os.environ, OPENSSL_CONF=OPENSSL_CNF)
proc = subprocess.run(args, input=stdin, capture_output=True, env=env, check=False)
if proc.returncode != 0:
sys.exit(f"command failed: {args}\n{proc.stderr.decode(errors='replace')}")
return proc.stdout
def openssl(*args, stdin=None):
return run([OPENSSL, *args], stdin=stdin)
def fixed(label, n):
"""A fixed, reproducible test value: the first n bytes of SHA-256 of a label (chained when n > 32)."""
out = b""
counter = 0
while len(out) < n:
out += hashlib.sha256(f"domistream-test:{label}:{counter}".encode()).digest()
counter += 1
return out[:n]
def sha256(*parts):
h = hashlib.sha256()
for p in parts:
h.update(p)
return h.digest()
def tmp(name, data=None):
path = os.path.join(WORK, name)
if data is not None:
with open(path, "wb") as f:
f.write(data)
return path
# ---------------------------------------------------------------- AES via the OpenSSL CLI
def ecb_encrypt(key, data):
assert len(data) % 16 == 0
return openssl("enc", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data)
def ecb_decrypt(key, data):
return openssl("enc", "-d", "-aes-128-ecb", "-nopad", "-K", key.hex(), stdin=data)
def cbc_encrypt(key, iv, data):
return openssl("enc", "-aes-128-cbc", "-K", key.hex(), "-iv", iv.hex(), stdin=data)
# ---------------------------------------------------------------- RSA and X.509 via the OpenSSL CLI
def make_rsa_identity(stem, common_name):
key = os.path.join(FIXTURES, f"{stem}-key.pem")
cert = os.path.join(FIXTURES, f"{stem}-cert.pem")
openssl("genpkey", "-algorithm", "RSA", "-pkeyopt", "rsa_keygen_bits:2048", "-out", key)
openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", f"/CN={common_name}",
"-config", OPENSSL_CNF, "-out", cert)
def make_ec_cert(stem):
key = tmp(f"{stem}-key.pem")
cert = os.path.join(FIXTURES, f"{stem}-cert.pem")
openssl("genpkey", "-algorithm", "EC", "-pkeyopt", "ec_paramgen_curve:P-256", "-out", key)
openssl("req", "-x509", "-new", "-key", key, "-sha256", "-days", "7300", "-subj", "/CN=DomiStream test-only EC",
"-config", OPENSSL_CNF, "-out", cert)
def cert_der(stem):
return openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-outform", "DER")
def key_pkcs8_der(stem):
return openssl("pkcs8", "-topk8", "-nocrypt", "-in", os.path.join(FIXTURES, f"{stem}-key.pem"), "-outform", "DER")
def sign(stem, data):
"""RSASSA-PKCS1-v1_5 with SHA-256 (OpenSSL's default padding for RSA keys)."""
sig = openssl("dgst", "-sha256", "-sign", os.path.join(FIXTURES, f"{stem}-key.pem"), tmp("data.bin", data))
# Check it with the certificate's public key, so a vector never carries a signature OpenSSL itself rejects.
pub = tmp("pub.pem", openssl("x509", "-in", os.path.join(FIXTURES, f"{stem}-cert.pem"), "-pubkey", "-noout"))
openssl("dgst", "-sha256", "-verify", pub, "-signature", tmp("sig.bin", sig), tmp("data.bin", data))
return sig
def der_read(buf, pos):
"""One DER TLV at pos: (tag, content_start, content_end)."""
tag = buf[pos]
length = buf[pos + 1]
pos += 2
if length & 0x80:
n = length & 0x7F
length = int.from_bytes(buf[pos:pos + n], "big")
pos += n
return tag, pos, pos + length
def cert_signature_value(der):
"""The raw signatureValue bytes of an X.509 certificate (RFC 5280 4.1): the BIT STRING's content after its
unused-bits octet."""
tag, start, end = der_read(der, 0)
assert tag == 0x30 and end == len(der)
_, _, tbs_end = der_read(der, start) # tbsCertificate
_, _, alg_end = der_read(der, tbs_end) # signatureAlgorithm
tag, sig_start, sig_end = der_read(der, alg_end)
assert tag == 0x03 and sig_end == end
assert der[sig_start] == 0, "unused bits in signatureValue"
return der[sig_start + 1:sig_end]
# ---------------------------------------------------------------- AES-GCM via .NET
def gcm_batch(rows):
"""rows: (name, key, nonce, plaintext) -> {name: (ciphertext, tag)}"""
lines = [f"{n} {k.hex()} {iv.hex()} {pt.hex() if pt else '-'}" for n, k, iv, pt in rows]
src = tmp("gcm_in.txt", ("\n".join(lines) + "\n").encode())
dst = tmp("gcm_out.txt")
run([DOTNET, "run", os.path.join(HERE, "gcm_vectors.cs"), "--", src, dst])
out = {}
with open(dst, encoding="ascii") as f:
for line in f:
name, ct, tag = line.split()
out[name] = (b"" if ct == "-" else bytes.fromhex(ct), bytes.fromhex(tag))
return out
# ---------------------------------------------------------------- writers
def write_vectors(filename, title, entries):
path = os.path.join(FIXTURES, filename)
with open(path, "w", encoding="ascii", newline="\n") as f:
f.write(HEADER)
f.write(f"# {title}\n")
for name, value in entries:
if name.startswith("#"):
f.write(f"\n{name}\n")
continue
if isinstance(value, bytes):
value = value.hex()
f.write(f"{name} = {value}\n")
print("wrote", os.path.relpath(path, ROOT))
# ---------------------------------------------------------------- pairing (PROTOCOL.md 1.5)
def pairing_vectors():
host_der = cert_der("test-only-host")
client_der = cert_der("test-only-client")
rogue_der = cert_der("test-only-rogue")
host_sig = cert_signature_value(host_der)
client_sig = cert_signature_value(client_der)
pin = b"4071"
wrong_pin = b"4072"
# The client's randomness, in the order the state machine draws it: salt (step 1), C (step 2), secret_c (step 3).
salt = fixed("salt-a", 16)
c = fixed("client-challenge-a", 16)
secret_c = fixed("client-secret-a", 16)
# A second session (different randomness) for the replay test.
salt_b = fixed("salt-b", 16)
c_b = fixed("client-challenge-b", 16)
secret_c_b = fixed("client-secret-b", 16)
# The host's values.
s_c = fixed("server-challenge", 16)
secret_s = fixed("server-secret", 16)
key = sha256(salt, pin)[:16]
req2 = ecb_encrypt(key, c)
assert ecb_decrypt(key, req2) == c
h_s = sha256(c, host_sig, secret_s)
resp2 = ecb_encrypt(key, h_s + s_c)
h_c = sha256(s_c, client_sig, secret_c)
req3 = ecb_encrypt(key, h_c)
secret_s_sig = sign("test-only-host", secret_s)
resp3 = secret_s + secret_s_sig
secret_c_sig = sign("test-only-client", secret_c)
req4 = secret_c + secret_c_sig
# Wrong PIN on the host: the host decrypts the client challenge with its own key and answers with it.
key_wrong = sha256(salt, wrong_pin)[:16]
c_seen_by_host = ecb_decrypt(key_wrong, req2)
resp2_wrong_pin = ecb_encrypt(key_wrong, sha256(c_seen_by_host, host_sig, secret_s) + s_c)
# Right key, but H_s over a different host secret than the one the host reveals in step 3.
resp2_wrong_hash = ecb_encrypt(key, sha256(c, host_sig, fixed("other-server-secret", 16)) + s_c)
# Right key, but H_s over the rogue certificate's signature instead of the host's.
resp2_wrong_cert = ecb_encrypt(key, sha256(c, cert_signature_value(rogue_der), secret_s) + s_c)
# Step 3 signed by a key other than the host certificate's.
resp3_rogue = secret_s + sign("test-only-rogue", secret_s)
sign_data = b"DomiStream test-only signing input"
entries = [
("# Identities (DER, hex). PEM forms: test-only-*.pem next to this file.", None),
("host_cert_der", host_der),
("host_cert_signature", host_sig),
("client_cert_der", client_der),
("client_key_pkcs8_der", key_pkcs8_der("test-only-client")),
("client_cert_signature", client_sig),
("rogue_cert_der", rogue_der),
("rogue_key_pkcs8_der", key_pkcs8_der("test-only-rogue")),
("# Session A: the client's randomness (rng stream = salt || client_challenge || client_secret)", None),
("pin", pin.decode()),
("wrong_pin", wrong_pin.decode()),
("salt", salt),
("client_challenge", c),
("client_secret", secret_c),
("# Host values", None),
("server_challenge", s_c),
("server_secret", secret_s),
("# Derived, step by step", None),
("key", key),
("step2_clientchallenge", req2),
("host_proof", h_s),
("step2_challengeresponse", resp2),
("client_proof", h_c),
("step3_serverchallengeresp", req3),
("server_secret_signature", secret_s_sig),
("step3_pairingsecret", resp3),
("client_secret_signature", secret_c_sig),
("step4_clientpairingsecret", req4),
("# Hostile host answers", None),
("step2_challengeresponse_wrong_pin", resp2_wrong_pin),
("step2_challengeresponse_wrong_hash", resp2_wrong_hash),
("step2_challengeresponse_wrong_cert", resp2_wrong_cert),
("step3_pairingsecret_rogue_signature", resp3_rogue),
("# Session B: different randomness, for replaying session A's answers", None),
("salt_b", salt_b),
("client_challenge_b", c_b),
("client_secret_b", secret_c_b),
("# ClientIdentity::sign over a fixed input (PKCS#1 v1.5 is deterministic)", None),
("sign_data", sign_data),
("sign_data_client_signature", sign("test-only-client", sign_data)),
]
# derive_key over several salts and PINs.
entries.append(("# derive_key: SHA-256(salt || pin)[0..16]", None))
for i, p in enumerate([b"0000", b"9999", b"1234", b"4071"]):
s = fixed(f"derive-salt-{i}", 16)
entries += [(f"derive_{i}_salt", s), (f"derive_{i}_pin", p.decode()), (f"derive_{i}_key", sha256(s, p)[:16])]
# AES-128-ECB, no padding, 1 to 4 blocks.
entries.append(("# ecb: AES-128-ECB without padding", None))
for blocks in [1, 2, 3, 4]:
k = fixed(f"ecb-key-{blocks}", 16)
pt = fixed(f"ecb-plain-{blocks}", 16 * blocks)
entries += [(f"ecb_{blocks}_key", k), (f"ecb_{blocks}_plain", pt), (f"ecb_{blocks}_cipher", ecb_encrypt(k, pt))]
# proof_hash with signatures of several lengths (RSA-1024 .. RSA-8192, plus 0 and 1 byte).
entries.append(("# proof_hash: SHA-256(challenge || signature || secret)", None))
for i, n in enumerate([0, 1, 128, 256, 512, 1024]):
ch = fixed(f"proof-challenge-{i}", 16)
sg = fixed(f"proof-signature-{i}", n)
se = fixed(f"proof-secret-{i}", 16)
entries += [(f"proof_{i}_challenge", ch), (f"proof_{i}_signature", sg if n else "-"),
(f"proof_{i}_secret", se), (f"proof_{i}_hash", sha256(ch, sg, se))]
write_vectors("pairing.txt", "Pairing (PROTOCOL.md 1.5): SHA-256 hashlib, AES-ECB + RSA openssl", entries)
# ---------------------------------------------------------------- control frames (PROTOCOL.md 3.2)
def control_nonce(seq, direction):
return seq.to_bytes(4, "little") + bytes(6) + direction + b"C"
def control_vectors():
key = fixed("control-rikey", 16)
cases = [
# (name, seq, direction byte, plaintext)
("c_ping_0", 0, b"C", bytes.fromhex("00020000")),
("c_input_1", 1, b"C", bytes.fromhex("06020c000000000807000000ffff0000")),
("c_ping_ffff", 0xFFFF, b"C", bytes.fromhex("00020000")),
("c_ping_10000", 0x10000, b"C", bytes.fromhex("00020000")),
("c_ping_fffffffe", 0xFFFFFFFE, b"C", bytes.fromhex("00020000")),
("c_ping_ffffffff", 0xFFFFFFFF, b"C", bytes.fromhex("00020000")),
("h_rumble_0", 0, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")),
("h_rumble_7", 7, b"H", bytes.fromhex("0b010a00000000000100ff7f0080")),
("h_termination_ffffffff", 0xFFFFFFFF, b"H", bytes.fromhex("0901040080030023")),
("h_rgb_2a", 0x2A, b"H", bytes.fromhex("0255050003001020ff")),
]
out = gcm_batch([(n, key, control_nonce(s, d), pt) for n, s, d, pt in cases])
entries = [("key", key)]
for name, seq, direction, pt in cases:
ct, tag = out[name]
frame = (1).to_bytes(2, "little") + (4 + 16 + len(ct)).to_bytes(2, "little") + seq.to_bytes(4, "little")
frame += tag + ct
entries += [
(f"# {name}", None),
(f"{name}_sequence", f"{seq:08x}"),
(f"{name}_direction", direction.decode()),
(f"{name}_nonce", control_nonce(seq, direction)),
(f"{name}_plain", pt),
(f"{name}_frame", frame),
]
write_vectors("control_gcm.txt", "Control frames (PROTOCOL.md 3.2): AES-128-GCM by .NET AesGcm", entries)
# ---------------------------------------------------------------- video encryption (PROTOCOL.md 7)
def video_vectors():
key = fixed("video-rikey", 16)
cases = []
for name, counter, frame_number, n in [
("v_0", 0, 0, 48),
("v_1", 1, 0, 48),
("v_big_counter", 0x0102030405060708, 0x11223344, 64),
("v_1040", 7, 3, 1040),
]:
pt = fixed(f"video-plain-{name}", n)
iv = counter.to_bytes(8, "little") + bytes(3) + b"V"
cases.append((name, counter, frame_number, iv, pt))
out = gcm_batch([(n, key, iv, pt) for n, _, _, iv, pt in cases])
entries = [("key", key)]
for name, counter, frame_number, iv, pt in cases:
ct, tag = out[name]
packet = iv + frame_number.to_bytes(4, "little") + tag + ct
entries += [(f"# {name}", None), (f"{name}_plain", pt), (f"{name}_packet", packet)]
write_vectors("video_gcm.txt", "Video packets (PROTOCOL.md 7): AES-128-GCM by .NET AesGcm", entries)
# ---------------------------------------------------------------- audio encryption (PROTOCOL.md 6.3)
def audio_vectors():
key = fixed("audio-rikey", 16)
entries = [("key", key)]
for name, rikeyid, seq, n in [
("a_0", 0, 0, 20),
("a_1", 0x01020304, 1, 20),
("a_ffff", 0x00000010, 0xFFFF, 33),
("a_wrap", 0xFFFFFFFE, 5, 16),
("a_exact_block", 7, 100, 32),
("a_one_byte", 7, 101, 1),
]:
iv = ((rikeyid + seq) & 0xFFFFFFFF).to_bytes(4, "big") + bytes(12)
pt = fixed(f"audio-plain-{name}", n)
entries += [
(f"# {name}", None),
(f"{name}_rikeyid", f"{rikeyid:08x}"),
(f"{name}_sequence", f"{seq:04x}"),
(f"{name}_iv", iv),
(f"{name}_plain", pt),
(f"{name}_cipher", cbc_encrypt(key, iv, pt)),
]
write_vectors("audio_cbc.txt", "Audio payloads (PROTOCOL.md 6.3): AES-128-CBC + PKCS#7 by openssl", entries)
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--fresh-keys", action="store_true", help="make new test-only keys and certificates")
args = parser.parse_args()
print("openssl:", openssl("version").decode().strip())
os.makedirs(FIXTURES, exist_ok=True)
stems = ["test-only-host", "test-only-client", "test-only-rogue"]
missing = any(not os.path.exists(os.path.join(FIXTURES, f"{s}-cert.pem")) for s in stems)
if args.fresh_keys or missing:
make_rsa_identity("test-only-host", "DomiStream test-only host")
make_rsa_identity("test-only-client", "DomiStream test-only client")
make_rsa_identity("test-only-rogue", "DomiStream test-only rogue")
make_ec_cert("test-only-ec")
print("made fresh test-only keys")
pairing_vectors()
control_vectors()
video_vectors()
audio_vectors()
shutil.rmtree(WORK, ignore_errors=True)
if __name__ == "__main__":
main()