27 Commits

Author SHA1 Message Date
mnovak 6c68a25b77 [repo] Lab capture: lab-install.ps1 (pinned MSI, loopback bind, one elevation) and lab-api.ps1 (pinned TLS, DPAPI credentials) 2026-11-25 13:08:46 +01:00
mnovak fd1c141ca8 [repo] Lab relay: compile fixes after the first build (clippy, fmt); 28 unit tests pass 2026-11-25 13:08:46 +01:00
mnovak ab5404b0cf [repo] Lab capture: lab root on E:\build\play-remotely\lab (approved), build rule with TEMP/TMP on E: 2026-11-25 13:03:10 +01:00
mnovak a2b834ed87 [repo] Lab relay: recorder, redacting dump, TCP/TLS-terminating/UDP relays, CLI (never compiled yet) 2026-11-25 12:36:56 +01:00
mnovak fbb8833f3d [repo] Lab capture: lab root back on F:\Akce\DomiStream-lab (move to E: cancelled) 2026-11-25 12:34:46 +01:00
mnovak 8b968be489 [repo] Lab capture: lab root moves to E:\build\play-remotely\lab (F: is full); build rule and TLS fallback noted 2026-11-25 12:32:11 +01:00
mnovak 26ce712e82 [repo] Lab relay: record file format, loopback-only config, streaming rewriter, with unit tests (not yet compiled) 2026-11-25 12:31:06 +01:00
mnovak 11c14b8cb6 [repo] Lab capture: plan for one Sunshine/Moonlight session through our loopback relay 2026-11-25 12:27:30 +01:00
mnovak 424cccfa92 [repo] Protocol: ENet timeout rule counts send attempts, not retries 2026-11-25 12:23:47 +01:00
mnovak 3bd7ebeaed [repo] Protocol: ENet 1.3 wire from stock ENet narrows U9; video FEC Cauchy matrix from fec-rs settles U14 2026-11-25 12:22:59 +01:00
mnovak af1df633a1 [repo] Clean room: stock ENet, tokio-enet and fec-rs approved (Mark, answer 15), binaries black-box only, new reads logged 2026-11-25 12:21:45 +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
73 changed files with 8315 additions and 2 deletions
-2
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 ### Rules that never bend
- Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c) - Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c)
into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements. into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements.
- Also allowed for the wire format, with attribution (Mark, 2026-11-25): stock ENet (MIT), tokio-enet (BSD-2),
fec-rs (BSD-2). GPL code stays off limits.
- Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only. - Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only.
- Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed). - Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed).
- Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever. - Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever.
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 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 ## Licence
DomiStream is licensed under the **Common Public Attribution License 1.0** (SPDX `CPAL-1.0`); see [LICENSE](LICENSE). DomiStream is licensed under the **Common Public Attribution License 1.0** (SPDX `CPAL-1.0`); see [LICENSE](LICENSE).
+23
View File
@@ -0,0 +1,23 @@
[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
+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)
}
+82
View File
@@ -0,0 +1,82 @@
# 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 through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution"
Read for the wire format; anything borrowed beyond a fact is attributed in the file that holds it. GPL stays off
limits, and a value with GPL provenance stays out even when one of these sources carries it.
| Source | Licence | Why |
| :-- | :-- | :-- |
| [Stock ENet](https://github.com/lsalzman/enet) | MIT | The ENet 1.3 wire format is documented nowhere else. Read at v1.3.18 (S-17). |
| [tokio-enet](https://github.com/hgaiser/tokio-enet) | BSD-2-Clause | Pure-Rust ENet 1.3 that Moonshine uses with Moonlight clients (S-10, now approved). |
| [fec-rs](https://github.com/hgaiser/fec-rs) | BSD-2-Clause | Reed-Solomon whose README claims Moonlight compatibility; its matrix construction settles U14 (S-18). |
## 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 |
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
## 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. **Approved** (Mark, 2026-11-25, answer 15). |
| 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. |
| S-17 | 2026-11-25 | [Stock ENet](https://github.com/lsalzman/enet) v1.3.18 (`2662c0d`): `LICENSE`, `include/enet/protocol.h`, `include/enet/enet.h` (constants and peer states), `host.c` (`enet_host_connect`), `peer.c` (default ping and timeout setters), `protocol.c` (header and checksum handling, connect/verify connect session ids, retransmission timeout) | MIT. Wire structs and sizes; header flags; checksum is an optional host setting (4 bytes after the header, no flag on the wire, seeded with the connect id); connect sends session ids 0xFF and channel 0xFF; defaults: MTU 1392, ping interval 500 ms, timeout limit 32 / minimum 5000 ms / maximum 30000 ms, window 4096-65536 derived from bandwidth. |
| S-18 | 2026-11-25 | [fec-rs](https://github.com/hgaiser/fec-rs) at `402f41f970bb8c3ef7c88639821032e3b6460f63`: `LICENSE`, `README.md`, `build.rs` (field tables), `src/galois.rs` (`exp`), `src/matrix.rs` (`vandermonde`), `src/reed_solomon.rs` (`build_matrix`, `new`) | BSD-2. Field GF(2^8) with polynomial 0x11D, generator 2; systematic code whose parity rows are the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`. Its tests also contain the GPL-provenance audio matrix (not taken). |
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
+269
View File
@@ -0,0 +1,269 @@
# Lab capture: one GameStream session on Mark's PC
Status: **plan, not run.** Mark allowed one capture (answer 16, 2026-11-25). Nothing below has been downloaded,
installed or started yet. The build lead relays the timeline (section 7) to Mark first.
Goal: settle the UNKNOWNs U1-U29 in [PROTOCOL.md](PROTOCOL.md) section 8 by watching **one** desktop stream between
the official Moonlight PC client and the pinned Sunshine, both on this PC, through **our own** logging relay.
Moonlight and Sunshine are black-box peers: we run them and watch their traffic, their `--help`, their own logs and
the files they write. We never open their source, never disassemble them ([CLEAN_ROOM.md](CLEAN_ROOM.md)).
Hard limits:
- One stream of the **Desktop** app, no game. Nothing touches the TV or 192.168.100.217.
- Every listening socket is on loopback: Sunshine on `127.0.0.2`, the relay on `127.0.0.1`.
- Lab keys and credentials live only under `E:\build\play-remotely\lab\`, are never printed, never on a command line that
survives, never in git, and are deleted at the end.
- Recordings stay under `E:\build\play-remotely\lab\captures\`, out of git. Only derived facts and test vectors go into
the docs.
- One UAC prompt in total.
## 0. Layout
```
E:\build\play-remotely\lab\
downloads\ Sunshine MSI and the Moonlight portable zip, as downloaded (untrusted until the sha256 matches)
moonlight\ the extracted Moonlight portable folder
keys\ lab-only TLS material (ACL: Mark's account + SYSTEM): Sunshine lab cert/key, Moonlight lab cert/key
secrets\ Sunshine API credentials, DPAPI-protected for Mark's account (ConvertFrom-SecureString)
captures\ relay recordings (*.dslr), Sunshine's log copy, the msiexec log, our notes
```
Our scripts and the relay come from this repo (`tools/lab-relay/`) and run from it, never from `downloads\`.
Built and checked on 2026-11-25 (Windows MSVC, stable 1.99, `-j 2`): `cargo test` 28 passed, `cargo clippy
--all-targets -- -D warnings` and `cargo fmt --check` clean. The relay has **not been run** yet. The two scripts
(`tools/lab-relay/scripts/lab-install.ps1`, `lab-api.ps1`) have been parse-checked only, never run; the build lead
reads them before anything goes to Mark.
The lab root is on E: (approved for Play remotely). The relay is built in `E:uild\play-remotely\DomiStream-wt-lab`
with `TEMP`/`TMP` set to `E:uild\play-remotely mp`, `-j 2`, and only while CPU, RAM, D: and E: are all below
90 % (DomiStream CLAUDE.md).
## 1. Step (a): the old Sunshine is gone (read-only)
Mark has uninstalled it himself. We only check, changing nothing:
| Check | Command (read-only) | Expected |
| :-- | :-- | :-- |
| Service | `Get-Service *sunshine* -ErrorAction SilentlyContinue` | nothing |
| Processes | `Get-Process sunshine*, sunshinesvc -ErrorAction SilentlyContinue` | nothing |
| Folder | `Test-Path 'C:\Program Files\Sunshine'` | `False` (or a folder without `sunshine.exe`; then we stop and ask, we do not delete it) |
| Uninstall entry | `Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*, HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* \| ? DisplayName -like '*Sunshine*'` | nothing |
| TCP ports | `Get-NetTCPConnection -State Listen \| ? LocalPort -in 47984,47989,47990,48010` | nothing |
| UDP ports | `Get-NetUDPEndpoint \| ? LocalPort -in 47998,47999,48000,48002` | nothing |
| Firewall leftovers | `Get-NetFirewallRule -DisplayName '*Sunshine*' -ErrorAction SilentlyContinue` | nothing (only noted if present) |
| Load | the CPU/RAM check from the build rule | both ≤ 90 %, else wait |
Anything unexpected: stop and report; no clean-up on our side.
## 2. Step (b): pinned Sunshine, one UAC prompt
**Pin** (release API, S-19): `v2026.914.233613`, `Sunshine-Windows-AMD64-installer.msi`, 33,710,080 bytes,
sha256 `1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf`,
`https://github.com/SunshineStream/Sunshine/releases/download/v2026.914.233613/Sunshine-Windows-AMD64-installer.msi`.
The same digest is checked twice: against this pin and against the release API's `digest` field fetched at download
time. A mismatch on either = delete the file and stop.
Download (not elevated): `Invoke-WebRequest -Uri <url> -OutFile E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi`,
then `Get-FileHash -Algorithm SHA256`. Nothing is run from `downloads\` before the hash matches.
**Why one elevated script, not a bare `msiexec`:** Sunshine's first start must already be bound to loopback, and
`--creds` needs write access under `C:\Program Files\Sunshine\config`. A plain `msiexec /i` would start the service
on all interfaces with no credentials. So we start **one** elevated PowerShell (`Start-Process powershell -Verb RunAs`
with our script `tools/lab-relay/scripts/lab-install.ps1`). That is the one UAC prompt ("Windows PowerShell",
publisher Microsoft Windows). Inside it, without further prompts:
1. `msiexec /i <msi> /qn /norestart /l*v E:\build\play-remotely\lab\captures\msiexec.log` (quiet; elevated already).
2. `Stop-Service SunshineService` as soon as the MSI returns (the MSI starts it; until our config is in, it has no
credentials, so nobody can pair or call its API).
3. Write `C:\Program Files\Sunshine\config\sunshine.conf` with only these lines:
```
bind_address = 127.0.0.2
address_family = ipv4
origin_web_ui_allowed = pc
upnp = disabled
external_ip = 127.0.0.2
sunshine_name = DomiStream-lab
lan_encryption_mode = 1
wan_encryption_mode = 1
min_log_level = debug
pkey = E:/build/play-remotely/lab/keys/sunshine-lab-key.pem
cert = E:/build/play-remotely/lab/keys/sunshine-lab-cert.pem
```
Forward slashes in paths: how the config parser treats backslashes is not documented. Encryption mode 1 ("if the client supports it") rather than 2: if Moonlight PC lacks one kind of encryption, a
mandatory setting would refuse the only session we get. `pkey`/`cert` point at `keys\` so the lab key never has to
be copied out of Program Files (inferred: Sunshine creates the pair at the configured path when missing; if it does
not, the script removes the two lines, restarts, and copies the default pair from `config\credentials\` into
`keys\` instead, still inside the same elevation).
4. **First-run credentials, never on a surviving command line:** the script draws a throwaway username and password
(32 random bytes each, base64url), runs `sunshine.exe --creds <u> <p>` once (the documented non-interactive way,
sunshine-api.md §4; the arguments live only for that process's lifetime), and saves the throwaway pair to
`secrets\sunshine-throwaway.cred` with `ConvertFrom-SecureString` (DPAPI, Mark's account). It is rotated in step 5.
This needs Mark's account to be the one that elevates (consent prompt, not a password prompt); if UAC asks for a
different admin account, we stop.
5. `Start-Service SunshineService`; wait until `Get-NetTCPConnection` shows 127.0.0.2:47989/47984/47990/48010 and
nothing on 0.0.0.0; `icacls` `keys\` and `secrets\` down to Mark's account + SYSTEM. Exit.
After the elevated script, not elevated (`lab-api.ps1`, PowerShell, Basic auth built in memory, TLS pinned to
`keys\sunshine-lab-cert.pem` by thumbprint): `POST https://127.0.0.2:47990/api/password` from the throwaway pair to a
fresh random lab pair stored in `secrets\sunshine-lab.cred` (DPAPI); delete the throwaway file. Arena's Day 1
takeover rotates once more into Custos.
Firewall: if the MSI added inbound rules, we only note them (`Get-NetFirewallRule`); Sunshine listens on 127.0.0.2,
so they expose nothing. Changing them needs admin and is left to Arena Day 1.
## 3. Step (c): Moonlight PC portable, no install
**Pin** (release API, S-19): `v6.2.0` (2026-10-04), `MoonlightPortable-x64-6.2.0.zip`, 37,242,232 bytes,
sha256 `6f91d268b41ed5ca8066d9d7578dc403b8db190991ff48f00b1700465f8f7ebf`,
`https://github.com/moonlight-stream/moonlight-qt/releases/download/v6.2.0/MoonlightPortable-x64-6.2.0.zip`.
Download to `downloads\`, check the hash (pin and API digest), extract to `E:\build\play-remotely\lab\moonlight\`.
No installer, no admin.
Before its first start we snapshot (names only) the `moonlight\` folder tree and the key names under
`HKCU:\Software` so that afterwards we can see what Moonlight wrote (its settings and its client identity; where it
keeps them is not documented and we do not read its source to find out). We run `Moonlight.exe --help` first
(black-box) to see whether it can pair from the command line with a PIN we choose.
**Moonlight's lab client key:** the relay needs it to talk TLS to Sunshine on Moonlight's behalf (section 4). After
Moonlight's first start (or at the latest right after pairing step 1, which carries its certificate), a small script
finds the new value by name and length only, writes the key as PEM to `keys\moonlight-lab-key.pem` and the certificate
to `keys\moonlight-lab-cert.pem`, and prints neither. If the key is not readable (for example protected with DPAPI by
Moonlight), the relay passes HTTPS through untouched and we fall back to Sunshine's debug log for what HTTPS carries
(section 6 lists what that loses).
## 4. Step (d): the relay
### Addresses
```
Moonlight ──▶ 127.0.0.1:{47984,47989,48010}/tcp, {47998,47999,48000,48002}/udp (lab-relay, logs everything)
└──▶ 127.0.0.2: same ports (Sunshine, bind_address)
```
Moonlight is told the host is `127.0.0.1`. Because Sunshine sits on another loopback address with its **default**
ports, the relay copies the port numbers unchanged: no port rewriting in serverinfo, RTSP or SDP, which matters
because RTSP may be encrypted (U5) and could not be rewritten.
Address rewriting: Sunshine may write its own address (`127.0.0.2`) into answers, for example `sessionUrl0` in the
launch answer, which would send Moonlight around the relay. The relay replaces the 9 bytes `127.0.0.2` with
`127.0.0.1` in **host-to-client plaintext only** (HTTP, decrypted HTTPS, plain RTSP), logs the original and a note
per replacement. Same length, so `Content-Length` stays right.
Fallback if Sunshine refuses `bind_address = 127.0.0.2`: Sunshine on `127.0.0.1` with `port = 48989` (all ports
+1000), the relay on the default ports, and port rewriting of `HttpsPort`/`ExternalPort` (serverinfo), `sessionUrl0`
(launch) and `server_port=` (RTSP SETUP). That only works while RTSP is plaintext, so the fallback also sets the
encryption modes to 0 and gives up U17/U19 for this capture.
UDP: video, audio and control go to the address the client's first datagram (the PING, or the ENet connect) came
from (W5, W6). The relay keeps one upstream socket per client address and port, so Sunshine sees the relay's socket
and answers it; the relay sends the answers back to Moonlight's socket. ENet carries no addresses.
### What is encrypted, and how we see plaintext
| Traffic | Protection | How the relay sees it |
| :-- | :-- | :-- |
| HTTP 47989 (serverinfo, pairing steps 1-4) | none | plaintext |
| HTTPS 47984 (pairing step 5, applist, launch with `rikey`, cancel) | TLS, both sides pin certificates | **terminated in the relay**: towards Moonlight it presents Sunshine's own lab certificate (the one Moonlight pinned in pairing, so the pin holds); towards Sunshine it presents Moonlight's own lab client certificate and pins Sunshine's lab certificate |
| RTSP 48010 | plaintext, or encrypted when negotiated (U5) | as is; if encrypted, decrypted offline with `rikey` from the launch request |
| Control 47999 | AES-128-GCM with `rikey` (client-chosen) | ENet headers plaintext; message bodies decrypted offline with `rikey` |
| Audio 48000 | AES-128-CBC with `rikey`, if negotiated | decrypted offline |
| Video 47998 | AES-128-GCM with `rikey`, only if negotiated | headers plaintext unless encrypted; decrypted offline |
Why TLS termination and not just Sunshine's log: `rikey` and the launch parameters (U4) travel only inside HTTPS.
Without them, control, audio and possibly video stay opaque and U10, U11, U16, U17, U19, U20, U22 stay open. The debug
log's contents are not documented, and asking it to print keys is not something we can count on. Termination uses
only lab material that exists for this capture and is deleted after it; nothing outside this PC's loopback is
touched. Sunshine's debug log (`GET /api/logs`) is still copied into `captures\` as a cross-check.
The relay never changes a byte except the documented address rewrite, and never sends anything on its own.
### Which part of the capture settles which UNKNOWN
| U | Settled by |
| :-- | :-- |
| U1 | HTTP 47989 pairing requests (query names, order), then the first HTTPS request (`pairchallenge`) and its place in the order |
| U2 | partly: the certificate Moonlight sends in pairing step 1 shows one certificate Sunshine accepts (key size, validity, subject); our own certificate is tested on Day 1 |
| U4 | the decrypted HTTPS `/launch` request and answer |
| U5 | the RTSP TCP stream: framing, `Content-Length`, `X-GS-ClientVersion`, SETUP targets, `Transport`, `Session`, PLAY |
| U6 | the ANNOUNCE payload Sunshine accepted |
| U7 | headers of the three SETUP answers |
| U8 | the first client-to-host datagrams on 47998 and 48000, and their timing |
| U9 | control datagrams decoded with our ENet parser: connect/verify connect fields, flags, anything stock 1.3 lacks |
| U10 | decrypted control messages: START_A/B, PERIODIC_PING, LOSS/FRAME_STATS, IDR request, termination at the end, and their timing |
| U11 | control frame sequence numbers in both directions |
| U13 | the first 8 bytes of each reassembled video frame |
| U14 | confirmation: our Cauchy encoder must reproduce every captured video parity packet (offset 32 on) |
| U15 | the multi-FEC flags byte across all video packets |
| U16 | captured audio blocks: solve the 2 × 4 parity matrix over GF(2^8) from data and parity bytes |
| U17 | ANNOUNCE `encryptionEnabled` plus whether audio payloads decrypt |
| U19 | the video packet layout when video encryption was negotiated (if Moonlight PC does not negotiate it, U19 stays open) |
| U20 | keys typed during the stream into a scratch Notepad window |
| U22 | gamepad packets, only if Mark has a controller plugged in (optional) |
| U24 | the TLS handshakes on 47984 (versions, cipher suites), logged by the relay |
| U25 | `ServerCodecModeSupport` in serverinfo from a host whose GPU we know (RTX 3090) |
| U26 | the `surround-params` lines in DESCRIBE (all of them, if Sunshine lists every Opus configuration as Moonshine does) |
| U27 | only if a call is refused during the session; not provoked |
| U29 | video RTP timestamps against the 60 fps frame rate |
| U21, U23, U28 | **not** settled: no touch/pen device, no game to rumble, no wrong PIN in a one-session capture |
## 5. Step (e): what is recorded, analysis, clean-up
**Recorded** (`captures\`):
- `session-<UTC>.dslr`: the relay's record file. Each record: kind (open, data, close, note), protocol (HTTP,
HTTPS plaintext, RTSP, video, control, audio, mic, meta), direction, connection id, microseconds since the start,
and the bytes. Format and tests: `tools/lab-relay/src/record.rs`.
- `sunshine.log` (copied with `GET /api/logs`), `msiexec.log`.
- `notes.md`: what we did and when (times from the relay's clock).
**Privacy:** the video frames are Mark's desktop. Before the stream, Mark closes anything private; during it, only a
scratch Notepad and the desktop are on screen. After analysis the video payload bytes are deleted from the recording
(`lab-relay strip-video`), keeping only packet headers and parity checks.
**Analysis** (offline, no network): `lab-relay dump` lists records with secrets redacted (`rikey=`, `Authorization:`,
pairing values); per-protocol extraction feeds DomiStream's own parsers (Phase B) and small Python checks run with
`python -I` from the repo, never from `captures\`. Every fact that comes out goes into PROTOCOL.md with the tag
`[L1]` (lab capture 1, date, versions) and, where useful, into test vectors that contain **no** lab key (vectors are
re-encrypted with test keys generated in the test).
**Clean-up** (right after the stream, not elevated):
1. Quit Moonlight; stop the relay.
2. `POST /api/clients/unpair-all` (removes the Moonlight lab client from Sunshine).
3. `POST /api/config` without the `pkey`/`cert` lines and `POST /api/restart`, so Sunshine makes a fresh pair at its
default path (inferred; if it does not, the lab pair stays referenced and Arena's Day 1 takeover, which runs
elevated anyway, regenerates it). Then delete `keys\sunshine-lab-*.pem`.
4. Delete `keys\moonlight-lab-*.pem`, the whole `moonlight\` folder and the registry key Moonlight created (found by
the snapshot diff in step (c)).
5. Keep `secrets\sunshine-lab.cred` until Arena's Day 1 takeover rotates the credentials into Custos, then delete it.
6. Delete `downloads\Moonlight*.zip`. Keep the Sunshine MSI (Arena Day 1 pins the same version).
7. Sunshine **stays installed**, bound to 127.0.0.2, ready for Arena's Day 1 takeover.
8. The recordings stay on E: until the facts are in PROTOCOL.md and QA has its vectors; then they are deleted on the
build lead's word.
## 6. If something fails
| Failure | What we do |
| :-- | :-- |
| sha256 mismatch | delete the file, stop, report |
| Sunshine will not bind 127.0.0.2 | fallback of section 4 (port +1000, encryption off for this capture) |
| Moonlight refuses `127.0.0.1` as a host | relay on `127.0.0.3` instead (any loopback address works) |
| The relay's TLS handshake with Moonlight or Sunshine fails (for example a cipher suite rustls does not offer) | restart the relay with `--https-passthrough`: HTTPS is then recorded as raw TLS, with the same losses as the next row |
| Moonlight's key not readable | HTTPS passes through untouched; we lose U4 and `rikey`, so U10, U11, U16, U17, U19, U20, U22 stay open unless Sunshine's debug log shows them |
| Pairing needs a `pairing_id` we cannot find (sunshine-api.md gap) | we watch the network calls of Sunshine's own local PIN page in our browser pane (black-box) and submit the PIN there ourselves |
| CPU or RAM above 90 % | wait (the relay build and the stream are both heavy) |
## 7. Step (f): timeline for Mark
About 20 minutes; Mark's part is **one click**, plus closing private windows before the stream.
| When | What happens | Mark |
| :-- | :-- | :-- |
| 0:00 | We check that the old Sunshine is gone and that the PC is not busy. | nothing |
| 0:02 | We download the pinned Sunshine and Moonlight and check their fingerprints (about 70 MB). | nothing |
| 0:05 | **A UAC prompt appears: "Windows PowerShell – Do you want to allow this app to make changes to your device?" (publisher: Microsoft Windows).** | **click Yes** (the only click) |
| 0:05-0:08 | Sunshine installs quietly and starts, reachable only from this PC. | nothing |
| 0:08 | Moonlight opens in a window (portable, nothing installed). It may show a PIN; we enter it into Sunshine ourselves. If Windows Firewall asks about Moonlight, click **Cancel**: everything runs on this PC. | close private windows; Cancel on a firewall prompt if one appears |
| 0:10 | A one-minute desktop stream: Moonlight shows his own desktop in a window. We move the mouse and type a few letters into a scratch Notepad. If he has a gamepad plugged in, we may ask him to press a few buttons. | hands off the mouse and keyboard for that minute (optional: press gamepad buttons when asked) |
| 0:12 | We close the stream, unpair Moonlight, delete Moonlight and the lab keys. Sunshine stays installed for Arena's Day 1. | nothing |
| later | We analyse the recording offline and delete the desktop video from it. | nothing |
+593
View File
@@ -0,0 +1,593 @@
# 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). U9 narrowed and U14 settled from the approved sources the same
day (sections 3.1, 5.3); the rest waits for the lab capture ([LAB_CAPTURE.md](LAB_CAPTURE.md)).
**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), approved 2026-11-25 |
| [E] | stock ENet v1.3.18 `2662c0d` (S-17), MIT, approved 2026-11-25 |
| [F] | fec-rs README and source `402f41f` (S-13, S-18), BSD-2, approved 2026-11-25 |
| [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]. The wire is stock ENet 1.3 [E][T]
(all multi-byte fields big-endian):
- **Datagram** = protocol header + up to 32 commands [E]. Header: `peer_id u16` whose bits 15 and 14 are flags (`1<<15`
sent time present, `1<<14` compressed) and bits 12-13 the session id; then `sent_time u16` (low 16 bits of the
sender's millisecond clock) if flagged [E]. Peer id `0xFFF` = "no peer yet" (the connect datagram) [E].
- **Checksum** [E]: optional, a setting of the host on *both* ends; when on, 4 bytes follow the header (crc32 over the
datagram with the field first set to the peer's connect id). **Nothing on the wire says whether it is on**, so both
ends must agree.
- **Command header** (4 bytes): `command u8` (low 4 bits type, `0x80` acknowledge wanted, `0x40` unsequenced),
`channel_id u8` (`0xFF` for connection-level commands), `reliable_sequence u16` [E].
- **Commands and total sizes** [E]: 1 acknowledge (8: received reliable sequence, received sent time),
2 connect (48), 3 verify connect (44), 4 disconnect (8: data u32), 5 ping (4), 6 send reliable (6 + data),
7 send unreliable (8 + data), 8 send fragment (24 + data: start sequence, data length, fragment count, fragment
number, total length, fragment offset), 9 send unsequenced (8 + data: unsequenced group), 10 bandwidth limit (12),
11 throttle configure (16), 12 send unreliable fragment (24 + data).
- **Connect** fields [E]: outgoing peer id u16, incoming and outgoing session id u8 (a stock client sends `0xFF` for
both, "pick one"), MTU, window size, channel count, incoming and outgoing bandwidth, throttle interval, acceleration,
deceleration, connect id (random), data u32. Verify connect has the same fields without `data`; the connect id must
match [E].
- **Limits** [E]: MTU 576-4096, window 4096-65536, channels 1-255, peer id ≤ 0xFFF, at most 1024 × 1024 fragments.
- **Stock defaults** [E]: MTU 1392; window 65536 when bandwidth is unlimited; ping every 500 ms when idle;
retransmission timeout = RTT + 4 × RTT variance (initial RTT 500 ms), doubling per retry; a peer is dropped when
the oldest unacknowledged command is 30 s old, or once it has been sent 6 times (`2^(attempts-1) ≥ 32`, the
timeout limit) and is at least 5 s old.
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)).
What follows without a capture (our reasoning on [E][T][M]):
- tokio-enet has no checksum and Moonlight clients work with it, so **Moonlight clients run without the checksum**.
The checksum must match on both ends, and Sunshine works with the same clients, so **Sunshine runs without it too**.
Same reasoning for compression: a client that compressed would fail against tokio-enet without a compressor.
- So everything a Moonlight client *sends* parses as stock 1.3. What stays open is only what the fork might add on the
host's *sending* side, which the fork-aware client accepts and a stock parser might not.
UNKNOWN U9 (narrowed): anything Sunshine's ENet sends that stock 1.3 does not; the channel count, MTU and `connect
data` a client offers; whether the client sets non-default ping or timeout values. Settle: the lab capture's control
port datagrams, decoded with our parser (LAB_CAPTURE.md). Until then our client offers stock defaults.
### 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.
- **Matrix (U14, settled from [F], to be confirmed by the capture):** systematic: the data shards pass through, and
parity shard `j` (0..m) is `Σ_i P[j][i] · data_i` with the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)` over
GF(2^8), polynomial `0x11D`, generator 2 [F]. Nothing in the Wolf docs contradicts this: they only say Reed-Solomon
with parity blocks [W5]. Examples (our own arithmetic): `k = 4, m = 2`:
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
captured parity bytes (offset 32 on) of every block.
- The audio code is **not** this matrix (section 6.4).
### 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 | Narrowed (3.1): only what Sunshine's ENet may add when *sending*; the client's channel count, MTU, connect data | B | capture, decode with our parser |
| U10 | Bodies of START_A, START_B, PERIODIC_PING, LOSS_STATS, FRAME_STATS, IDR request, TERMINATION; ping interval | B | capture, decrypted with the session's `rikey` |
| 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 matrix: **settled** (5.3, Cauchy from fec-rs) | | capture confirms: our parity = captured parity |
| 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"
+208
View File
@@ -0,0 +1,208 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4
[[package]]
name = "cc"
version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
dependencies = [
"find-msvc-tools",
"shlex",
]
[[package]]
name = "cfg-if"
version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
[[package]]
name = "find-msvc-tools"
version = "0.1.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
[[package]]
name = "getrandom"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "lab-relay"
version = "0.1.0"
dependencies = [
"ring",
"rustls",
"rustls-pki-types",
]
[[package]]
name = "libc"
version = "0.2.191"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "ring"
version = "0.17.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
dependencies = [
"cc",
"cfg-if",
"getrandom",
"libc",
"untrusted",
"windows-sys",
]
[[package]]
name = "rustls"
version = "0.23.46"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
dependencies = [
"once_cell",
"ring",
"rustls-pki-types",
"rustls-webpki",
"subtle",
"zeroize",
]
[[package]]
name = "rustls-pki-types"
version = "1.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
dependencies = [
"zeroize",
]
[[package]]
name = "rustls-webpki"
version = "0.103.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
dependencies = [
"ring",
"rustls-pki-types",
"untrusted",
]
[[package]]
name = "shlex"
version = "2.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
[[package]]
name = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "untrusted"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
[[package]]
name = "wasi"
version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
name = "windows-sys"
version = "0.52.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_gnullvm",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
[[package]]
name = "windows_aarch64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
[[package]]
name = "windows_i686_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
[[package]]
name = "windows_i686_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
[[package]]
name = "windows_i686_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
[[package]]
name = "windows_x86_64_gnu"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
[[package]]
name = "windows_x86_64_msvc"
version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
+21
View File
@@ -0,0 +1,21 @@
# lab-relay: our own logging relay for the one lab capture (docs/LAB_CAPTURE.md). A tool, never published, never part
# of the domistream crate. Its own workspace so it never joins the main build.
[package]
name = "lab-relay"
version = "0.1.0"
edition = "2024"
rust-version = "1.89"
license = "CPAL-1.0"
publish = false
[workspace]
members = ["."]
[dependencies]
# TLS termination on the HTTPS port with lab-only keys. ring backend: pure Rust + asm, builds with MSVC.
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
rustls-pki-types = { version = "1", features = ["std"] }
ring = "0.17"
[lints.rust]
unsafe_code = "forbid"
+183
View File
@@ -0,0 +1,183 @@
<#
.SYNOPSIS
Lab capture: talk to the lab Sunshine's local API (docs/LAB_CAPTURE.md sections 2, 3, 5). Not elevated.
.DESCRIPTION
Every call goes to https://127.0.0.2:47990 with Basic auth built in memory, no Origin/Referer header (the
documented non-browser path), TLS pinned to the lab certificate in keys\ byte for byte.
Credentials come only from DPAPI files in secrets\; they are never printed, logged or put on a command line.
-Action Rotate throwaway credentials (from lab-install.ps1) -> fresh lab credentials; deletes the throwaway
-Action Status lists paired clients and apps (names only)
-Action Pin submits the PIN Moonlight shows: -PinFile <file with 4 digits> (the file is deleted after
reading), optional -PairingId, -ClientName (default "DomiStream lab Moonlight")
-Action Logs saves GET /api/logs to captures\sunshine.log (not printed: it may hold secrets)
-Action Cleanup unpair all clients, drop the lab cert/key from the config (bind_address stays 127.0.0.2),
restart Sunshine
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[ValidateSet('Rotate', 'Status', 'Pin', 'Logs', 'Cleanup')]
[string] $Action,
[string] $LabRoot = 'E:\build\play-remotely\lab',
[string] $PinFile,
[string] $PairingId,
[string] $ClientName = 'DomiStream lab Moonlight'
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$BaseUrl = 'https://127.0.0.2:47990'
$keys = Join-Path $LabRoot 'keys'
$secrets = Join-Path $LabRoot 'secrets'
$captures = Join-Path $LabRoot 'captures'
$throwawayFile = Join-Path $secrets 'sunshine-throwaway.cred'
$labFile = Join-Path $secrets 'sunshine-lab.cred'
$certFile = Join-Path $keys 'sunshine-lab-cert.pem'
function Fail([string] $Why) {
Write-Host "lab-api: STOPPED: $Why"
exit 1
}
# --- TLS pinning: accept exactly the lab certificate -------------------------------------------------------------
if (-not (Test-Path -LiteralPath $certFile)) { Fail "lab certificate not found: $certFile" }
$pem = Get-Content -LiteralPath $certFile -Raw
$m = [regex]::Match($pem, '-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')
if (-not $m.Success) { Fail 'lab certificate is not PEM' }
$pinnedDer = [Convert]::FromBase64String(($m.Groups[1].Value -replace '\s', ''))
if (-not ('DomiLabPin' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class DomiLabPin {
public static byte[] Pinned;
public static bool Check(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) {
if (cert == null || Pinned == null) return false;
byte[] raw = cert.GetRawCertData();
if (raw.Length != Pinned.Length) return false;
int diff = 0;
for (int i = 0; i < raw.Length; i++) diff |= raw[i] ^ Pinned[i];
return diff == 0;
}
public static void Install() {
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Check);
}
}
'@
}
[DomiLabPin]::Pinned = $pinnedDer
[DomiLabPin]::Install()
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# --- Credentials -------------------------------------------------------------------------------------------------
function Read-Cred([string] $File) {
if (-not (Test-Path -LiteralPath $File)) { Fail "credentials file not found: $File" }
$j = Get-Content -LiteralPath $File -Raw | ConvertFrom-Json
$u = New-Object Management.Automation.PSCredential('x', ($j.user | ConvertTo-SecureString))
$p = New-Object Management.Automation.PSCredential('x', ($j.password | ConvertTo-SecureString))
return @{ User = $u.GetNetworkCredential().Password; Password = $p.GetNetworkCredential().Password }
}
function Save-Cred([string] $File, [string] $User, [string] $Password) {
@{
user = (ConvertTo-SecureString -String $User -AsPlainText -Force | ConvertFrom-SecureString)
password = (ConvertTo-SecureString -String $Password -AsPlainText -Force | ConvertFrom-SecureString)
} | ConvertTo-Json | Set-Content -LiteralPath $File -Encoding ASCII
}
function New-Secret {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$rng.Dispose()
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
# --- One API call ------------------------------------------------------------------------------------------------
function Invoke-Sunshine([hashtable] $Cred, [string] $Method, [string] $Path, $Body, [string] $OutFile) {
$pair = [Text.Encoding]::UTF8.GetBytes($Cred.User + ':' + $Cred.Password)
$headers = @{ Authorization = 'Basic ' + [Convert]::ToBase64String($pair) }
$req = @{ Uri = $BaseUrl + $Path; Method = $Method; Headers = $headers; UseBasicParsing = $true; TimeoutSec = 30 }
if ($null -ne $Body) {
$req.Body = ($Body | ConvertTo-Json -Depth 5 -Compress)
$req.ContentType = 'application/json'
}
try {
if ($OutFile) {
Invoke-WebRequest @req -OutFile $OutFile | Out-Null
return $null
}
return Invoke-RestMethod @req
} catch {
# The message names the call only; the request, which holds the credentials, is never echoed.
Fail "$Method $Path failed: $($_.Exception.GetType().Name)"
}
}
# --- Actions -----------------------------------------------------------------------------------------------------
switch ($Action) {
'Rotate' {
$old = Read-Cred $throwawayFile
$newUser = 'lab' + (New-Secret).Substring(0, 12)
$newPass = New-Secret
$null = Invoke-Sunshine $old 'POST' '/api/password' @{
currentUsername = $old.User
currentPassword = $old.Password
newUsername = $newUser
newPassword = $newPass
confirmNewPassword = $newPass
}
Save-Cred $labFile $newUser $newPass
# Prove the new pair works before forgetting the old one.
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/clients/list' $null
Remove-Item -LiteralPath $throwawayFile -Force
Write-Host 'lab-api: credentials rotated; throwaway deleted'
}
'Status' {
$c = Read-Cred $labFile
$clients = Invoke-Sunshine $c 'GET' '/api/clients/list' $null
$apps = Invoke-Sunshine $c 'GET' '/api/apps' $null
Write-Host ('lab-api: clients: ' + (($clients | ConvertTo-Json -Depth 4 -Compress)))
Write-Host ('lab-api: apps: ' + ((@($apps.apps) | ForEach-Object { $_.name }) -join ', '))
}
'Pin' {
if (-not $PinFile) { Fail '-PinFile is required' }
$pin = (Get-Content -LiteralPath $PinFile -Raw).Trim()
Remove-Item -LiteralPath $PinFile -Force
if ($pin -notmatch '^[0-9]{4}$') { Fail 'the PIN file must hold exactly 4 digits' }
$body = @{ pin = $pin; name = $ClientName }
if ($PairingId) { $body.pairing_id = $PairingId }
$r = Invoke-Sunshine (Read-Cred $labFile) 'POST' '/api/pin' $body
Write-Host ('lab-api: PIN submitted, answer: ' + ($r | ConvertTo-Json -Compress))
}
'Logs' {
$out = Join-Path $captures 'sunshine.log'
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/logs' $null $out
Write-Host "lab-api: Sunshine log saved to $out (not shown: it may hold secrets)"
}
'Cleanup' {
$c = Read-Cred $labFile
$null = Invoke-Sunshine $c 'POST' '/api/clients/unpair-all' $null
# Same loopback-only config as lab-install.ps1, without the lab cert/key, so Sunshine makes a fresh pair.
$null = Invoke-Sunshine $c 'POST' '/api/config' @{
bind_address = '127.0.0.2'
address_family = 'ipv4'
origin_web_ui_allowed = 'pc'
upnp = 'disabled'
external_ip = '127.0.0.2'
sunshine_name = 'DomiStream-lab'
lan_encryption_mode = '1'
wan_encryption_mode = '1'
}
$null = Invoke-Sunshine $c 'POST' '/api/restart' $null
Write-Host 'lab-api: unpaired all clients, lab cert/key dropped from the config, Sunshine restarting'
Write-Host 'lab-api: next: delete keys\sunshine-lab-*.pem and keys\moonlight-lab-*.pem once Sunshine is back'
}
}
exit 0
+217
View File
@@ -0,0 +1,217 @@
<#
.SYNOPSIS
Lab capture step (b): install the pinned Sunshine bound to 127.0.0.2 only (docs/LAB_CAPTURE.md section 2).
.DESCRIPTION
Runs ELEVATED, once, started by the operator with:
Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
'<repo>\tools\lab-relay\scripts\lab-install.ps1'
That is the one UAC prompt of the lab capture.
What it does, in order, and nothing else:
1. Refuses unless elevated, unless the MSI's sha256 matches the pin, and unless no Sunshine is installed.
2. Creates keys\, secrets\, captures\ under the lab root, readable only by this account and SYSTEM.
3. msiexec /i (quiet, logged to captures\msiexec.log), then stops the service the MSI started.
4. Writes sunshine.conf: bind_address 127.0.0.2, web UI for this PC only, no UPnP, lab cert/key under keys\.
5. Sets throwaway web-UI credentials with `sunshine --creds` (they exist only in that one process's argv and
in a DPAPI-protected file; lab-api.ps1 -Action Rotate replaces them).
6. Starts the service and checks that every Sunshine listener is on 127.0.0.2. Anything else: stop, fail.
It does not touch Windows Defender, firewall rules (it only lists the ones the MSI added), or any other app.
It never prints, logs or writes a credential in plain text.
#>
[CmdletBinding()]
param(
[string] $LabRoot = 'E:\build\play-remotely\lab',
[string] $Msi = 'E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi'
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
# --- Pins (release API, docs/LAB_CAPTURE.md section 2) ------------------------------------------------------------
$PinnedSha256 = '1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf'
$PinnedSize = 33710080
$BindAddress = '127.0.0.2'
$Ports = @(47984, 47989, 47990, 48010)
function Fail([string] $Why) {
Write-Host "lab-install: STOPPED: $Why"
exit 1
}
function Say([string] $What) {
Write-Host "lab-install: $What"
}
# --- 1. Preconditions --------------------------------------------------------------------------------------------
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Fail 'not elevated; start it with Start-Process -Verb RunAs'
}
if (-not (Test-Path -LiteralPath $Msi -PathType Leaf)) { Fail "MSI not found: $Msi" }
$msiItem = Get-Item -LiteralPath $Msi
if ($msiItem.Length -ne $PinnedSize) { Fail "MSI size $($msiItem.Length) is not the pinned $PinnedSize" }
$hash = (Get-FileHash -LiteralPath $Msi -Algorithm SHA256).Hash.ToLowerInvariant()
if ($hash -ne $PinnedSha256) { Fail "MSI sha256 $hash does not match the pin; delete the file" }
Say 'MSI matches the pinned sha256'
if (Get-Service -Name '*sunshine*' -ErrorAction SilentlyContinue) { Fail 'a Sunshine service already exists' }
if (Test-Path -LiteralPath 'C:\Program Files\Sunshine\sunshine.exe') { Fail 'C:\Program Files\Sunshine\sunshine.exe already exists' }
$busy = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
if ($busy) { Fail 'a GameStream port is already in use' }
# --- 2. Lab folders, this account + SYSTEM only ------------------------------------------------------------------
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
$keys = Join-Path $LabRoot 'keys'
$secrets = Join-Path $LabRoot 'secrets'
$captures = Join-Path $LabRoot 'captures'
foreach ($dir in @($keys, $secrets, $captures)) {
New-Item -ItemType Directory -Force -Path $dir | Out-Null
& icacls.exe $dir /inheritance:r /grant:r "${account}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' | Out-Null
if ($LASTEXITCODE -ne 0) { Fail "icacls failed on $dir" }
}
$hostKey = Join-Path $keys 'sunshine-lab-key.pem'
$hostCert = Join-Path $keys 'sunshine-lab-cert.pem'
foreach ($f in @($hostKey, $hostCert)) { if (Test-Path -LiteralPath $f) { Fail "$f already exists; clean up first" } }
Say "lab folders ready under $LabRoot"
# --- 3. Install ----------------------------------------------------------------------------------------------------
$msiLog = Join-Path $captures 'msiexec.log'
$p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', "`"$Msi`"", '/qn', '/norestart', '/l*v', "`"$msiLog`"") -Wait -PassThru
if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { Fail "msiexec exit code $($p.ExitCode); see $msiLog" }
Say "MSI installed (exit code $($p.ExitCode))"
$service = Get-CimInstance Win32_Service | Where-Object { $_.PathName -like '*Sunshine*' } | Select-Object -First 1
if (-not $service) { Fail 'no Sunshine service after the install' }
Stop-Service -Name $service.Name -Force
Say "service $($service.Name) stopped until the config is in"
$exe = 'C:\Program Files\Sunshine\sunshine.exe'
if (-not (Test-Path -LiteralPath $exe)) { Fail "$exe not found after the install" }
$installDir = Split-Path -Parent $exe
$configDir = Join-Path $installDir 'config'
New-Item -ItemType Directory -Force -Path $configDir | Out-Null
$conf = Join-Path $configDir 'sunshine.conf'
if (Test-Path -LiteralPath $conf) { Copy-Item -LiteralPath $conf -Destination (Join-Path $captures 'sunshine.conf.as-installed') -Force }
# --- 4. Config: loopback only ------------------------------------------------------------------------------------
function Write-Conf([bool] $WithLabKeys) {
$lines = @(
"bind_address = $BindAddress",
'address_family = ipv4',
'origin_web_ui_allowed = pc',
'upnp = disabled',
"external_ip = $BindAddress",
'sunshine_name = DomiStream-lab',
'lan_encryption_mode = 1',
'wan_encryption_mode = 1',
'min_log_level = debug'
)
if ($WithLabKeys) {
# Forward slashes: how the config parser treats backslashes is not documented.
$lines += 'pkey = ' + ($hostKey -replace '\\', '/')
$lines += 'cert = ' + ($hostCert -replace '\\', '/')
}
[IO.File]::WriteAllLines($conf, [string[]] $lines, (New-Object Text.UTF8Encoding($false)))
}
Write-Conf $true
Say 'sunshine.conf written (bind_address 127.0.0.2)'
# --- 5. Throwaway credentials ------------------------------------------------------------------------------------
function New-Secret {
$bytes = New-Object byte[] 32
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
$rng.GetBytes($bytes)
$rng.Dispose()
# base64url: only [A-Za-z0-9_-], so it needs no quoting on a command line.
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
}
$user = 'lab' + (New-Secret).Substring(0, 12)
$pass = New-Secret
# One child process; its argv dies with it. Output is read and discarded, never written anywhere.
$psi = New-Object Diagnostics.ProcessStartInfo
$psi.FileName = $exe
$psi.Arguments = "--creds $user $pass"
$psi.WorkingDirectory = $installDir
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$proc = [Diagnostics.Process]::Start($psi)
$null = $proc.StandardOutput.ReadToEnd()
$null = $proc.StandardError.ReadToEnd()
if (-not $proc.WaitForExit(60000)) { $proc.Kill(); Fail 'sunshine --creds did not finish' }
$credsExit = $proc.ExitCode
$psi = $null
$proc.Dispose()
if ($credsExit -ne 0) { Fail "sunshine --creds exit code $credsExit" }
# DPAPI (this account): readable only by this account on this PC; lab-api.ps1 -Action Rotate replaces it.
$throwaway = Join-Path $secrets 'sunshine-throwaway.cred'
@{
user = (ConvertTo-SecureString -String $user -AsPlainText -Force | ConvertFrom-SecureString)
password = (ConvertTo-SecureString -String $pass -AsPlainText -Force | ConvertFrom-SecureString)
} | ConvertTo-Json | Set-Content -LiteralPath $throwaway -Encoding ASCII
Remove-Variable -Name user, pass -ErrorAction SilentlyContinue
Say 'throwaway credentials set and stored (DPAPI)'
# --- 6. Start and check the binding ------------------------------------------------------------------------------
function Wait-Listeners([int] $Seconds) {
$deadline = (Get-Date).AddSeconds($Seconds)
while ((Get-Date) -lt $deadline) {
$l = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
if ($l -and (@($l | Select-Object -ExpandProperty LocalPort -Unique).Count -eq $Ports.Count)) { return $l }
Start-Sleep -Milliseconds 500
}
return $null
}
function Assert-Loopback($Listeners) {
$wrong = @($Listeners | Where-Object { $_.LocalAddress -ne $BindAddress })
if ($wrong.Count -gt 0) {
Stop-Service -Name $service.Name -Force
Fail ('Sunshine listened on ' + (($wrong | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', ') + '; service stopped')
}
}
Start-Service -Name $service.Name
$listeners = Wait-Listeners 60
if (-not $listeners) {
Stop-Service -Name $service.Name -Force
Fail 'Sunshine did not listen on all four TCP ports; service stopped (bind_address 127.0.0.2 refused? see LAB_CAPTURE.md section 4 fallback)'
}
Assert-Loopback $listeners
# Did Sunshine create its pair at the lab path? If not, fall back to its default pair and copy it for the relay.
$deadline = (Get-Date).AddSeconds(30)
while (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert)) -and (Get-Date) -lt $deadline) {
Start-Sleep -Milliseconds 500
}
if (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert))) {
Say 'Sunshine did not create the lab pair at keys\; using its default pair'
Stop-Service -Name $service.Name -Force
Write-Conf $false
Start-Service -Name $service.Name
$listeners = Wait-Listeners 60
if (-not $listeners) { Stop-Service -Name $service.Name -Force; Fail 'Sunshine did not come back after the fallback' }
Assert-Loopback $listeners
$defKey = Join-Path $configDir 'credentials\cakey.pem'
$defCert = Join-Path $configDir 'credentials\cacert.pem'
if (-not ((Test-Path -LiteralPath $defKey) -and (Test-Path -LiteralPath $defCert))) { Fail 'default pair not found either' }
Copy-Item -LiteralPath $defKey -Destination $hostKey
Copy-Item -LiteralPath $defCert -Destination $hostCert
}
Say 'Sunshine listens on 127.0.0.2 only; lab certificate pair in keys\'
# --- Report what the MSI did to the firewall (read only, nothing changed) ----------------------------------------
$rules = @(Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like '*Sunshine*' })
$notes = Join-Path $captures 'install-notes.txt'
@(
"installed: $(Get-Date -Format o)",
"service: $($service.Name)",
"msi sha256: $hash",
"listeners: " + (($listeners | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', '),
"firewall rules named like Sunshine (not changed): " + (($rules | ForEach-Object { "$($_.DisplayName) [$($_.Direction) $($_.Action) $($_.Enabled)]" }) -join '; ')
) | Set-Content -LiteralPath $notes -Encoding ASCII
Say "done; notes in $notes. Next, not elevated: lab-api.ps1 -Action Rotate"
exit 0
+317
View File
@@ -0,0 +1,317 @@
//! Relay settings and the loopback-only rule.
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::time::Duration;
use crate::record::Protocol;
/// Where recordings go unless told otherwise.
pub const DEFAULT_CAPTURE_DIR: &str = r"E:\build\play-remotely\lab\captures";
/// Where lab keys live unless told otherwise.
pub const DEFAULT_KEY_DIR: &str = r"E:\build\play-remotely\lab\keys";
/// Transport of a relayed port.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Transport {
/// TCP, bytes copied (and rewritten host-to-client when the protocol is plaintext).
Tcp,
/// TCP with TLS terminated in the relay.
Tls,
/// UDP datagrams.
Udp,
}
/// One relayed port.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PortSpec {
/// Port the relay listens on.
pub listen_port: u16,
/// Port on the upstream (Sunshine) side.
pub upstream_port: u16,
/// Transport.
pub transport: Transport,
/// Protocol label for the records.
pub protocol: Protocol,
}
/// The GameStream default ports (PROTOCOL.md section 0, ArenaTV sunshine-api.md section 3).
pub const GAMESTREAM_PORTS: [(u16, Transport, Protocol); 7] = [
(47984, Transport::Tls, Protocol::HttpsPlain),
(47989, Transport::Tcp, Protocol::Http),
(48010, Transport::Tcp, Protocol::Rtsp),
(47998, Transport::Udp, Protocol::Video),
(47999, Transport::Udp, Protocol::Control),
(48000, Transport::Udp, Protocol::Audio),
(48002, Transport::Udp, Protocol::Mic),
];
/// TLS material, all lab-only PEM files.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsFiles {
/// Sunshine's lab certificate (presented to Moonlight, pinned towards Sunshine).
pub host_cert: PathBuf,
/// Sunshine's lab private key.
pub host_key: PathBuf,
/// Moonlight's lab client certificate (presented to Sunshine).
pub client_cert: PathBuf,
/// Moonlight's lab client key.
pub client_key: PathBuf,
}
impl TlsFiles {
/// The four default file names in `dir`.
pub fn in_dir(dir: &std::path::Path) -> Self {
Self {
host_cert: dir.join("sunshine-lab-cert.pem"),
host_key: dir.join("sunshine-lab-key.pem"),
client_cert: dir.join("moonlight-lab-cert.pem"),
client_key: dir.join("moonlight-lab-key.pem"),
}
}
}
/// An equal-length byte replacement applied to host-to-client plaintext.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rewrite {
/// Bytes to find.
pub from: Vec<u8>,
/// Bytes to put instead, same length.
pub to: Vec<u8>,
}
/// Everything the relay needs.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Config {
/// Address the relay listens on (Moonlight's "host"). Loopback only.
pub listen: IpAddr,
/// Address Sunshine listens on. Loopback only.
pub upstream: IpAddr,
/// Added to each default port on the upstream side (0, or 1000 in the fallback of LAB_CAPTURE.md section 4).
pub upstream_port_offset: u16,
/// Directory for the record file.
pub capture_dir: PathBuf,
/// TLS files; `None` = HTTPS passes through as raw TLS.
pub tls: Option<TlsFiles>,
/// How long an HTTPS connection waits for the TLS files to appear (Moonlight's key may appear only after
/// pairing step 1).
pub wait_for_keys: Duration,
/// Rewrites, applied in order of position in the stream.
pub rewrites: Vec<Rewrite>,
}
/// Why a configuration is refused.
#[derive(Debug, PartialEq, Eq)]
pub enum ConfigError {
/// An address that is not loopback.
NotLoopback(IpAddr),
/// Listen and upstream are the same address with no port offset: the relay would talk to itself.
SelfLoop,
/// A rewrite whose two sides differ in length, or are empty.
BadRewrite(String),
/// Ports overflow with the offset.
PortOverflow(u16),
/// A command-line argument that is not understood.
BadArgument(String),
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::NotLoopback(ip) => {
write!(f, "{ip} is not a loopback address; the relay binds and connects only on loopback")
}
Self::SelfLoop => f.write_str("listen and upstream are the same address and ports"),
Self::BadRewrite(s) => write!(f, "rewrite {s:?}: both sides must be non-empty and the same length"),
Self::PortOverflow(p) => write!(f, "port {p} plus the offset is over 65535"),
Self::BadArgument(s) => write!(f, "bad argument: {s}"),
}
}
}
impl std::error::Error for ConfigError {}
impl Config {
/// The lab defaults: Moonlight sees 127.0.0.1, Sunshine sits on 127.0.0.2, `127.0.0.2` is rewritten to
/// `127.0.0.1` in host-to-client plaintext, TLS files from [`DEFAULT_KEY_DIR`].
pub fn lab_default() -> Self {
Self {
listen: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
upstream: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)),
upstream_port_offset: 0,
capture_dir: PathBuf::from(DEFAULT_CAPTURE_DIR),
tls: Some(TlsFiles::in_dir(std::path::Path::new(DEFAULT_KEY_DIR))),
wait_for_keys: Duration::from_secs(60),
rewrites: vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }],
}
}
/// Checks the rules: loopback only, no self-loop, sane rewrites, ports in range.
///
/// # Errors
/// The first rule broken.
pub fn validate(&self) -> Result<(), ConfigError> {
for ip in [self.listen, self.upstream] {
if !ip.is_loopback() {
return Err(ConfigError::NotLoopback(ip));
}
}
if self.listen == self.upstream && self.upstream_port_offset == 0 {
return Err(ConfigError::SelfLoop);
}
for r in &self.rewrites {
if r.from.is_empty() || r.from.len() != r.to.len() {
return Err(ConfigError::BadRewrite(String::from_utf8_lossy(&r.from).into_owned()));
}
}
self.ports().map(|_| ())
}
/// The relayed ports with the upstream offset applied.
///
/// # Errors
/// [`ConfigError::PortOverflow`].
pub fn ports(&self) -> Result<Vec<PortSpec>, ConfigError> {
GAMESTREAM_PORTS
.iter()
.map(|&(port, transport, protocol)| {
let upstream_port =
port.checked_add(self.upstream_port_offset).ok_or(ConfigError::PortOverflow(port))?;
let transport =
if transport == Transport::Tls && self.tls.is_none() { Transport::Tcp } else { transport };
let protocol = if transport == Transport::Tcp && protocol == Protocol::HttpsPlain {
Protocol::HttpsTls
} else {
protocol
};
Ok(PortSpec { listen_port: port, upstream_port, transport, protocol })
})
.collect()
}
/// Socket address the relay listens on for `spec`.
pub fn listen_addr(&self, spec: &PortSpec) -> SocketAddr {
SocketAddr::new(self.listen, spec.listen_port)
}
/// Upstream socket address for `spec`.
pub fn upstream_addr(&self, spec: &PortSpec) -> SocketAddr {
SocketAddr::new(self.upstream, spec.upstream_port)
}
/// Applies command-line options to the lab defaults:
/// `--listen <ip>`, `--upstream <ip>`, `--upstream-port-offset <n>`, `--capture-dir <dir>`, `--key-dir <dir>`,
/// `--https-passthrough`, `--wait-for-keys-secs <n>`, `--rewrite <from>=<to>` (repeatable; the first one
/// replaces the default rewrite), `--no-rewrite`.
///
/// # Errors
/// [`ConfigError::BadArgument`] for an unknown option or value, then [`Config::validate`].
pub fn from_args(args: &[String]) -> Result<Self, ConfigError> {
let mut c = Self::lab_default();
let mut custom_rewrites = false;
let mut it = args.iter();
let bad = |s: &str| ConfigError::BadArgument(s.to_owned());
while let Some(a) = it.next() {
let mut value = || it.next().ok_or_else(|| bad(a));
match a.as_str() {
"--listen" => c.listen = value()?.parse().map_err(|_| bad(a))?,
"--upstream" => c.upstream = value()?.parse().map_err(|_| bad(a))?,
"--upstream-port-offset" => c.upstream_port_offset = value()?.parse().map_err(|_| bad(a))?,
"--capture-dir" => c.capture_dir = PathBuf::from(value()?),
"--key-dir" => {
let dir = PathBuf::from(value()?);
if c.tls.is_some() {
c.tls = Some(TlsFiles::in_dir(&dir));
}
}
"--https-passthrough" => c.tls = None,
"--wait-for-keys-secs" => {
c.wait_for_keys = Duration::from_secs(value()?.parse().map_err(|_| bad(a))?);
}
"--rewrite" => {
let v = value()?;
let (from, to) = v.split_once('=').ok_or_else(|| bad(v))?;
if !custom_rewrites {
c.rewrites.clear();
custom_rewrites = true;
}
c.rewrites.push(Rewrite { from: from.as_bytes().to_vec(), to: to.as_bytes().to_vec() });
}
"--no-rewrite" => {
c.rewrites.clear();
custom_rewrites = true;
}
other => return Err(bad(other)),
}
}
c.validate()?;
Ok(c)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_owned).collect()
}
#[test]
fn lab_default_is_valid() {
assert_eq!(Config::lab_default().validate(), Ok(()));
}
#[test]
fn non_loopback_listen_or_upstream_is_refused() {
for a in [
"--listen 0.0.0.0",
"--listen 192.168.100.140",
"--upstream 192.168.100.217",
"--listen ::",
"--upstream 26.1.2.3",
] {
assert!(matches!(Config::from_args(&args(a)), Err(ConfigError::NotLoopback(_))), "{a}");
}
}
#[test]
fn other_loopback_addresses_are_accepted() {
let c = Config::from_args(&args("--listen 127.0.0.3 --upstream ::1")).unwrap();
assert!(c.listen.is_loopback() && c.upstream.is_loopback());
}
#[test]
fn self_loop_is_refused_unless_offset() {
assert_eq!(Config::from_args(&args("--upstream 127.0.0.1")), Err(ConfigError::SelfLoop));
let c = Config::from_args(&args("--upstream 127.0.0.1 --upstream-port-offset 1000")).unwrap();
let ports = c.ports().unwrap();
assert!(ports.iter().all(|p| p.upstream_port == p.listen_port + 1000));
}
#[test]
fn rewrites_must_keep_length() {
assert!(matches!(Config::from_args(&args("--rewrite 48984=7984")), Err(ConfigError::BadRewrite(_))));
assert!(matches!(Config::from_args(&args("--rewrite =")), Err(ConfigError::BadRewrite(_))));
let c = Config::from_args(&args("--rewrite 48984=47984 --rewrite 49010=48010")).unwrap();
assert_eq!(c.rewrites.len(), 2, "custom rewrites replace the default one");
}
#[test]
fn port_overflow_is_refused() {
assert!(matches!(Config::from_args(&args("--upstream-port-offset 20000")), Err(ConfigError::PortOverflow(_))));
}
#[test]
fn passthrough_turns_tls_into_raw_tcp() {
let c = Config::from_args(&args("--https-passthrough")).unwrap();
let https = c.ports().unwrap().into_iter().find(|p| p.listen_port == 47984).unwrap();
assert_eq!((https.transport, https.protocol), (Transport::Tcp, Protocol::HttpsTls));
}
#[test]
fn unknown_arguments_are_refused() {
assert!(matches!(Config::from_args(&args("--bind 0.0.0.0")), Err(ConfigError::BadArgument(_))));
assert!(matches!(Config::from_args(&args("--listen")), Err(ConfigError::BadArgument(_))));
}
}
+154
View File
@@ -0,0 +1,154 @@
//! lab-relay: our own logging relay for the one GameStream lab capture (`docs/LAB_CAPTURE.md`).
//!
//! ```text
//! lab-relay run [--listen 127.0.0.1] [--upstream 127.0.0.2] [--upstream-port-offset N] [--capture-dir DIR]
//! [--key-dir DIR] [--https-passthrough] [--wait-for-keys-secs N] [--rewrite FROM=TO]... [--no-rewrite]
//! lab-relay dump <file.dslr> list records, secrets redacted
//! lab-relay strip-video <in> <out> copy with video payloads cut to their 32 header bytes
//! ```
//!
//! Binds and connects only on loopback (refused otherwise). Never sends anything of its own.
mod config;
mod record;
mod recorder;
mod redact;
mod rewrite;
mod tcp;
mod tls;
mod udp;
use std::fs::File;
use std::io::{self, BufReader, BufWriter, Write};
use std::process::ExitCode;
use std::sync::Arc;
use std::thread;
use config::{Config, Transport};
use record::{Kind, Protocol, Record};
use recorder::Recorder;
/// Bytes of a video packet kept by `strip-video`: RTP header, reserved bytes and the NV header.
const VIDEO_HEADER_KEEP: usize = 32;
/// Text shown per record by `dump`.
const DUMP_TEXT_LIMIT: usize = 4000;
fn main() -> ExitCode {
let args: Vec<String> = std::env::args().skip(1).collect();
let result = match args.split_first() {
Some((cmd, rest)) if cmd == "run" => run(rest),
Some((cmd, [file])) if cmd == "dump" => dump(file),
Some((cmd, [input, output])) if cmd == "strip-video" => strip_video(input, output),
_ => Err("usage: lab-relay run [options] | dump <file> | strip-video <in> <out>".into()),
};
match result {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("lab-relay: {e}");
ExitCode::FAILURE
}
}
}
type AnyResult = Result<(), Box<dyn std::error::Error>>;
fn run(args: &[String]) -> AnyResult {
let config = Arc::new(Config::from_args(args)?);
let (rec, path) = Recorder::create(&config.capture_dir)?;
let rec = Arc::new(rec);
println!("lab-relay: recording to {}", path.display());
let mut threads = Vec::new();
for spec in config.ports()? {
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
println!("lab-relay: {:?} {} -> {}", spec.protocol, config.listen_addr(&spec), config.upstream_addr(&spec));
threads.push(thread::spawn(move || {
let r = match spec.transport {
Transport::Tcp => tcp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
Transport::Tls => tls::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
Transport::Udp => udp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
};
if let Err(e) = r {
eprintln!("lab-relay: port {} stopped: {e}", spec.listen_port);
rec.note(Protocol::Meta, 0, &format!("port {} stopped: {e}", spec.listen_port));
}
}));
}
rec.note(Protocol::Meta, 0, "relay started");
for t in threads {
let _ = t.join();
}
Ok(())
}
fn is_text(r: &Record) -> bool {
r.kind == Kind::Note
|| r.kind == Kind::Open
|| matches!(r.protocol, Protocol::Http | Protocol::HttpsPlain | Protocol::Rtsp)
}
fn dump(file: &str) -> AnyResult {
let mut input = BufReader::new(File::open(file)?);
let header = record::read_header(&mut input)?;
let stdout = io::stdout();
let mut out = stdout.lock();
writeln!(out, "capture started at unix {} us", header.start_unix_micros)?;
let mut index = 0u64;
loop {
let r = match record::read_record(&mut input) {
Ok(Some(r)) => r,
Ok(None) => break,
Err(e) => {
writeln!(out, "stopped at record {index}: {e}")?;
break;
}
};
writeln!(
out,
"#{index} t={}.{:06}s conn={} {:?} {:?} {:?} {} bytes",
r.time_micros / 1_000_000,
r.time_micros % 1_000_000,
r.connection,
r.kind,
r.protocol,
r.direction,
r.payload.len()
)?;
if is_text(&r) {
let text = redact::redact(&r.payload);
let shown = &text[..text.len().min(DUMP_TEXT_LIMIT)];
writeln!(out, " {}", String::from_utf8_lossy(shown).escape_debug())?;
} else {
let hex: String = r.payload.iter().take(32).map(|b| format!("{b:02x} ")).collect();
writeln!(out, " {hex}")?;
}
index += 1;
}
Ok(())
}
fn strip_video(input: &str, output: &str) -> AnyResult {
let mut reader = BufReader::new(File::open(input)?);
let header = record::read_header(&mut reader)?;
let mut writer = BufWriter::new(File::options().write(true).create_new(true).open(output)?);
record::write_header(&mut writer, header)?;
let mut stripped = 0u64;
while let Some(mut r) = record::read_record(&mut reader)? {
if r.kind == Kind::Data && r.protocol == Protocol::Video && r.payload.len() > VIDEO_HEADER_KEEP {
r.payload.truncate(VIDEO_HEADER_KEEP);
stripped += 1;
}
record::write_record(&mut writer, &r)?;
}
let note = Record {
kind: Kind::Note,
protocol: Protocol::Meta,
direction: record::Direction::None,
connection: 0,
time_micros: u64::MAX,
payload: format!("strip-video: {stripped} video payloads cut to {VIDEO_HEADER_KEEP} bytes").into_bytes(),
};
record::write_record(&mut writer, &note)?;
writer.flush()?;
println!("lab-relay: {stripped} video records stripped");
Ok(())
}
+387
View File
@@ -0,0 +1,387 @@
//! The record file: everything the relay sees, framed so it can be read back exactly.
//!
//! ```text
//! file = header record*
//! header = "DSLR" version:u8(=1) reserved:[u8;3](=0) start_unix_micros:u64le
//! record = kind:u8 protocol:u8 direction:u8 reserved:u8(=0) connection:u32le time_micros:u64le len:u32le bytes[len]
//! ```
//!
//! `time_micros` counts from the start of the capture. A record never holds more than [`MAX_PAYLOAD`] bytes.
use std::fmt;
use std::io::{self, Read, Write};
/// File magic.
pub const MAGIC: [u8; 4] = *b"DSLR";
/// Format version.
pub const VERSION: u8 = 1;
/// Header length in bytes.
pub const HEADER_LEN: usize = 16;
/// Record header length in bytes.
pub const RECORD_HEADER_LEN: usize = 20;
/// Largest payload of one record (a UDP datagram is at most 64 KiB; TCP reads are split to fit).
pub const MAX_PAYLOAD: usize = 1 << 20;
/// What a record says.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Kind {
/// A connection or UDP flow opened.
Open,
/// Bytes seen.
Data,
/// A connection or flow closed.
Close,
/// A UTF-8 note from the relay (TLS details, rewrites, errors).
Note,
}
/// Which protocol the bytes belong to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Protocol {
/// Relay-level notes.
Meta,
/// HTTP, port 47989.
Http,
/// Raw TLS bytes on 47984 (when not terminated).
HttpsTls,
/// Decrypted HTTPS plaintext on 47984.
HttpsPlain,
/// RTSP, port 48010.
Rtsp,
/// Video RTP, port 47998.
Video,
/// Control ENet, port 47999.
Control,
/// Audio RTP, port 48000.
Audio,
/// Microphone, port 48002.
Mic,
}
/// Which way the bytes went.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Direction {
/// Not a transfer (notes, opens, closes).
None,
/// Moonlight to Sunshine.
ClientToHost,
/// Sunshine to Moonlight.
HostToClient,
}
macro_rules! codes {
($t:ty { $($v:ident = $c:literal),* $(,)? }) => {
impl $t {
/// Wire code.
pub const fn code(self) -> u8 {
match self { $(Self::$v => $c),* }
}
/// From a wire code.
pub const fn from_code(code: u8) -> Option<Self> {
match code { $($c => Some(Self::$v),)* _ => None }
}
}
};
}
codes!(Kind { Open = 1, Data = 2, Close = 3, Note = 4 });
codes!(Protocol {
Meta = 0, Http = 1, HttpsTls = 2, HttpsPlain = 3, Rtsp = 4, Video = 5, Control = 6, Audio = 7, Mic = 8,
});
codes!(Direction { None = 0, ClientToHost = 1, HostToClient = 2 });
/// The file header.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Header {
/// Wall-clock start of the capture, Unix microseconds.
pub start_unix_micros: u64,
}
/// One record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Record {
/// What it is.
pub kind: Kind,
/// Protocol.
pub protocol: Protocol,
/// Direction.
pub direction: Direction,
/// Connection or flow id, unique per capture.
pub connection: u32,
/// Microseconds since the capture started.
pub time_micros: u64,
/// The bytes (UTF-8 text for notes).
pub payload: Vec<u8>,
}
/// Why a file could not be read.
#[derive(Debug)]
pub enum RecordError {
/// I/O failure.
Io(io::Error),
/// Not a record file, or another version.
BadHeader,
/// The file ends inside a record.
Truncated,
/// A field holds a value this version does not know.
BadField(&'static str, u64),
/// A payload over [`MAX_PAYLOAD`].
TooLarge(usize),
}
impl fmt::Display for RecordError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => write!(f, "i/o: {e}"),
Self::BadHeader => f.write_str("not a DSLR v1 file"),
Self::Truncated => f.write_str("file ends inside a record"),
Self::BadField(name, v) => write!(f, "bad {name}: {v}"),
Self::TooLarge(n) => write!(f, "payload of {n} bytes is over the limit"),
}
}
}
impl std::error::Error for RecordError {}
impl From<io::Error> for RecordError {
fn from(e: io::Error) -> Self {
Self::Io(e)
}
}
/// Writes the file header.
///
/// # Errors
/// I/O errors.
pub fn write_header(out: &mut impl Write, header: Header) -> io::Result<()> {
let mut buf = [0u8; HEADER_LEN];
buf[..4].copy_from_slice(&MAGIC);
buf[4] = VERSION;
buf[8..16].copy_from_slice(&header.start_unix_micros.to_le_bytes());
out.write_all(&buf)
}
/// Writes one record.
///
/// # Errors
/// [`io::ErrorKind::InvalidInput`] for a payload over [`MAX_PAYLOAD`]; I/O errors.
pub fn write_record(out: &mut impl Write, record: &Record) -> io::Result<()> {
let len = record.payload.len();
if len > MAX_PAYLOAD {
return Err(io::Error::new(io::ErrorKind::InvalidInput, "record payload over MAX_PAYLOAD"));
}
let mut head = [0u8; RECORD_HEADER_LEN];
head[0] = record.kind.code();
head[1] = record.protocol.code();
head[2] = record.direction.code();
head[4..8].copy_from_slice(&record.connection.to_le_bytes());
head[8..16].copy_from_slice(&record.time_micros.to_le_bytes());
// `len <= MAX_PAYLOAD < u32::MAX`, checked above.
head[16..20].copy_from_slice(&(len as u32).to_le_bytes());
out.write_all(&head)?;
out.write_all(&record.payload)
}
/// Reads exactly `buf.len()` bytes; `Ok(false)` at a clean end before the first byte.
fn read_full(input: &mut impl Read, buf: &mut [u8]) -> Result<bool, RecordError> {
let mut filled = 0;
while filled < buf.len() {
match input.read(&mut buf[filled..]) {
Ok(0) if filled == 0 => return Ok(false),
Ok(0) => return Err(RecordError::Truncated),
Ok(n) => filled += n,
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e.into()),
}
}
Ok(true)
}
/// Reads and checks the file header.
///
/// # Errors
/// [`RecordError::BadHeader`] for a wrong magic, version or reserved bytes; [`RecordError::Truncated`].
pub fn read_header(input: &mut impl Read) -> Result<Header, RecordError> {
let mut buf = [0u8; HEADER_LEN];
if !read_full(input, &mut buf)? {
return Err(RecordError::Truncated);
}
if buf[..4] != MAGIC || buf[4] != VERSION || buf[5..8] != [0, 0, 0] {
return Err(RecordError::BadHeader);
}
let mut start = [0u8; 8];
start.copy_from_slice(&buf[8..16]);
Ok(Header { start_unix_micros: u64::from_le_bytes(start) })
}
/// Reads the next record; `Ok(None)` at the end of the file.
///
/// # Errors
/// [`RecordError::Truncated`] inside a record, [`RecordError::BadField`] for unknown codes or a non-zero reserved
/// byte, [`RecordError::TooLarge`] before allocating an oversized payload.
pub fn read_record(input: &mut impl Read) -> Result<Option<Record>, RecordError> {
let mut head = [0u8; RECORD_HEADER_LEN];
if !read_full(input, &mut head)? {
return Ok(None);
}
let kind = Kind::from_code(head[0]).ok_or(RecordError::BadField("kind", head[0].into()))?;
let protocol = Protocol::from_code(head[1]).ok_or(RecordError::BadField("protocol", head[1].into()))?;
let direction = Direction::from_code(head[2]).ok_or(RecordError::BadField("direction", head[2].into()))?;
if head[3] != 0 {
return Err(RecordError::BadField("reserved", head[3].into()));
}
let word = |r: std::ops::Range<usize>| {
let mut b = [0u8; 8];
b[..r.len()].copy_from_slice(&head[r]);
u64::from_le_bytes(b)
};
let connection = word(4..8) as u32;
let time_micros = word(8..16);
let len = word(16..20) as usize;
if len > MAX_PAYLOAD {
return Err(RecordError::TooLarge(len));
}
let mut payload = vec![0u8; len];
if len > 0 && !read_full(input, &mut payload)? {
return Err(RecordError::Truncated);
}
Ok(Some(Record { kind, protocol, direction, connection, time_micros, payload }))
}
#[cfg(test)]
mod tests {
use super::*;
fn sample(payload: &[u8]) -> Record {
Record {
kind: Kind::Data,
protocol: Protocol::Control,
direction: Direction::HostToClient,
connection: 0x0102_0304,
time_micros: 0x1122_3344_5566_7788,
payload: payload.to_vec(),
}
}
fn file(records: &[Record]) -> Vec<u8> {
let mut out = Vec::new();
write_header(&mut out, Header { start_unix_micros: 42 }).unwrap();
for r in records {
write_record(&mut out, r).unwrap();
}
out
}
#[test]
fn header_layout_is_fixed() {
let mut out = Vec::new();
write_header(&mut out, Header { start_unix_micros: 0x0807_0605_0403_0201 }).unwrap();
assert_eq!(out, b"DSLR\x01\0\0\0\x01\x02\x03\x04\x05\x06\x07\x08");
}
#[test]
fn record_layout_is_fixed() {
let mut out = Vec::new();
write_record(&mut out, &sample(b"ab")).unwrap();
let mut want = vec![2, 6, 2, 0, 4, 3, 2, 1, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 2, 0, 0, 0];
want.extend_from_slice(b"ab");
assert_eq!(out, want);
}
#[test]
fn round_trip_of_every_code() {
let mut records = Vec::new();
for k in 1..=4 {
for p in 0..=8 {
for d in 0..=2 {
records.push(Record {
kind: Kind::from_code(k).unwrap(),
protocol: Protocol::from_code(p).unwrap(),
direction: Direction::from_code(d).unwrap(),
connection: u32::from(k) * 100 + u32::from(p),
time_micros: u64::from(d),
payload: vec![k, p, d],
});
}
}
}
records.push(sample(&[]));
records.push(sample(&vec![0xAB; MAX_PAYLOAD]));
let bytes = file(&records);
let mut input = bytes.as_slice();
assert_eq!(read_header(&mut input).unwrap(), Header { start_unix_micros: 42 });
for want in &records {
assert_eq!(read_record(&mut input).unwrap().as_ref(), Some(want));
}
assert!(read_record(&mut input).unwrap().is_none());
}
#[test]
fn oversized_payload_is_refused_on_write() {
let err = write_record(&mut Vec::new(), &sample(&vec![0; MAX_PAYLOAD + 1])).unwrap_err();
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
}
#[test]
fn oversized_length_is_refused_before_allocating() {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"")).unwrap();
bytes[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::TooLarge(_))));
}
#[test]
fn every_cut_inside_a_record_is_truncated() {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"payload")).unwrap();
for cut in 1..bytes.len() {
let r = read_record(&mut &bytes[..cut]);
assert!(matches!(r, Err(RecordError::Truncated)), "cut at {cut}");
}
}
#[test]
fn unknown_codes_and_reserved_bytes_are_refused() {
for (offset, value) in [(0, 0u8), (0, 5), (1, 9), (2, 3), (3, 1)] {
let mut bytes = Vec::new();
write_record(&mut bytes, &sample(b"x")).unwrap();
bytes[offset] = value;
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::BadField(..))), "{offset}");
}
}
#[test]
fn bad_headers_are_refused() {
let good = file(&[]);
for (offset, value) in [(0, b'X'), (4, 2), (5, 1)] {
let mut bytes = good.clone();
bytes[offset] = value;
assert!(matches!(read_header(&mut bytes.as_slice()), Err(RecordError::BadHeader)));
}
assert!(matches!(read_header(&mut &good[..10]), Err(RecordError::Truncated)));
}
/// A reader that hands out one byte per call, like a slow pipe.
struct Trickle<'a>(&'a [u8]);
impl Read for Trickle<'_> {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
match (self.0.split_first(), buf.first_mut()) {
(Some((&b, rest)), Some(slot)) => {
*slot = b;
self.0 = rest;
Ok(1)
}
_ => Ok(0),
}
}
}
#[test]
fn short_reads_are_reassembled() {
let bytes = file(&[sample(b"one"), sample(b"two")]);
let mut input = Trickle(&bytes);
read_header(&mut input).unwrap();
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"one");
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"two");
assert!(read_record(&mut input).unwrap().is_none());
}
}
+73
View File
@@ -0,0 +1,73 @@
//! The shared, thread-safe writer of the record file. Every record is flushed at once, so a killed relay leaves a
//! file that reads cleanly up to its last whole record.
use std::fs::{File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::record::{self, Direction, Header, Kind, Protocol, Record};
/// Writes records for one capture.
pub struct Recorder {
out: Mutex<BufWriter<File>>,
start: Instant,
next_connection: AtomicU32,
failed: AtomicBool,
}
impl Recorder {
/// Creates `session-<unix seconds>.dslr` in `dir` (never overwrites) and writes the header.
///
/// # Errors
/// I/O errors, including an existing file of the same name.
pub fn create(dir: &Path) -> io::Result<(Self, PathBuf)> {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
let path = dir.join(format!("session-{}.dslr", now.as_secs()));
let file = OpenOptions::new().write(true).create_new(true).open(&path)?;
let mut out = BufWriter::new(file);
let start_unix_micros = u64::try_from(now.as_micros()).unwrap_or(u64::MAX);
record::write_header(&mut out, Header { start_unix_micros })?;
out.flush()?;
let rec = Self {
out: Mutex::new(out),
start: Instant::now(),
next_connection: AtomicU32::new(1),
failed: AtomicBool::new(false),
};
Ok((rec, path))
}
/// A fresh connection or flow id.
pub fn new_connection(&self) -> u32 {
self.next_connection.fetch_add(1, Ordering::Relaxed)
}
/// Records bytes (split into several records if over [`record::MAX_PAYLOAD`]).
pub fn log(&self, kind: Kind, protocol: Protocol, direction: Direction, connection: u32, payload: &[u8]) {
let time_micros = u64::try_from(self.start.elapsed().as_micros()).unwrap_or(u64::MAX);
let chunks: Vec<&[u8]> =
if payload.is_empty() { vec![payload] } else { payload.chunks(record::MAX_PAYLOAD).collect() };
let Ok(mut out) = self.out.lock() else { return self.fail("lock poisoned") };
for chunk in chunks {
let r = Record { kind, protocol, direction, connection, time_micros, payload: chunk.to_vec() };
if let Err(e) = record::write_record(&mut *out, &r).and_then(|()| out.flush()) {
return self.fail(&e.to_string());
}
}
}
/// Records a note (never pass key material here).
pub fn note(&self, protocol: Protocol, connection: u32, text: &str) {
self.log(Kind::Note, protocol, Direction::None, connection, text.as_bytes());
}
/// Reports the first write failure on stderr; later ones stay silent.
fn fail(&self, why: &str) {
if !self.failed.swap(true, Ordering::Relaxed) {
eprintln!("lab-relay: writing the record file failed: {why}");
}
}
}
+122
View File
@@ -0,0 +1,122 @@
//! Hides secrets when records are printed (`lab-relay dump`). The record file itself keeps everything; it never
//! leaves the lab folder.
/// Query parameters whose values are secret or let someone redo the pairing proofs.
pub const SECRET_PARAMS: [&str; 6] =
["rikey", "salt", "clientchallenge", "serverchallengeresp", "clientpairingsecret", "pin"];
/// XML elements whose text is secret.
pub const SECRET_ELEMENTS: [&str; 2] = ["challengeresponse", "pairingsecret"];
/// HTTP headers whose values are secret.
pub const SECRET_HEADERS: [&str; 2] = ["authorization", "cookie"];
/// What replaces a secret.
pub const MARK: &[u8] = b"<redacted>";
fn ends_param_value(b: u8) -> bool {
matches!(b, b'&' | b' ' | b'"' | b'\r' | b'\n' | b'<' | b'#')
}
/// Returns `text` with every secret value replaced by [`MARK`].
pub fn redact(text: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(text.len());
let mut i = 0;
let lower: Vec<u8> = text.to_ascii_lowercase();
'scan: while i < text.len() {
// `name=` at a parameter boundary.
if i == 0 || matches!(text[i - 1], b'?' | b'&' | b' ' | b'\n') {
for name in SECRET_PARAMS {
let key = [name.as_bytes(), b"="].concat();
if lower[i..].starts_with(&key) {
out.extend_from_slice(&text[i..i + key.len()]);
out.extend_from_slice(MARK);
i += key.len();
while i < text.len() && !ends_param_value(text[i]) {
i += 1;
}
continue 'scan;
}
}
}
// `<element>` … `</`.
if text[i] == b'<' {
for name in SECRET_ELEMENTS {
let open = [b"<", name.as_bytes(), b">"].concat();
if lower[i..].starts_with(&open) {
out.extend_from_slice(&text[i..i + open.len()]);
out.extend_from_slice(MARK);
i += open.len();
while i < text.len() && !text[i..].starts_with(b"</") {
i += 1;
}
continue 'scan;
}
}
}
// `Header:` at a line start, up to the end of the line.
if i == 0 || text[i - 1] == b'\n' {
for name in SECRET_HEADERS {
let key = [name.as_bytes(), b":"].concat();
if lower[i..].starts_with(&key) {
out.extend_from_slice(&text[i..i + key.len()]);
out.extend_from_slice(b" ");
out.extend_from_slice(MARK);
i += key.len();
while i < text.len() && text[i] != b'\r' && text[i] != b'\n' {
i += 1;
}
continue 'scan;
}
}
}
out.push(text[i]);
i += 1;
}
out
}
#[cfg(test)]
mod tests {
use super::*;
fn r(s: &str) -> String {
String::from_utf8(redact(s.as_bytes())).unwrap()
}
#[test]
fn launch_key_is_hidden() {
assert_eq!(
r("GET /launch?uniqueid=0123&appid=1&rikey=00112233445566778899aabbccddeeff&rikeyid=7 HTTP/1.1"),
"GET /launch?uniqueid=0123&appid=1&rikey=<redacted>&rikeyid=7 HTTP/1.1"
);
}
#[test]
fn pairing_values_are_hidden_but_names_and_certs_stay() {
assert_eq!(
r("GET /pair?uniqueid=1&phrase=getservercert&salt=ABCD&clientcert=2D2D HTTP/1.1"),
"GET /pair?uniqueid=1&phrase=getservercert&salt=<redacted>&clientcert=2D2D HTTP/1.1"
);
assert_eq!(
r("<root status_code=\"200\"><paired>1</paired><pairingsecret>ffee</pairingsecret></root>"),
"<root status_code=\"200\"><paired>1</paired><pairingsecret><redacted></pairingsecret></root>"
);
}
#[test]
fn auth_headers_are_hidden() {
assert_eq!(
r("POST /api/pin HTTP/1.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nHost: x\r\n"),
"POST /api/pin HTTP/1.1\r\nAuthorization: <redacted>\r\nHost: x\r\n"
);
}
#[test]
fn lookalike_names_are_not_touched() {
assert_eq!(r("GET /x?rikeyid=5&nosalt=1"), "GET /x?rikeyid=5&nosalt=1");
}
#[test]
fn value_at_end_of_input_is_hidden() {
assert_eq!(r("?rikey=abc"), "?rikey=<redacted>");
assert_eq!(r("<challengeresponse>abc"), "<challengeresponse><redacted>");
}
}
+150
View File
@@ -0,0 +1,150 @@
//! Equal-length byte replacement over a stream, safe across read boundaries.
//!
//! Bytes that could be the start of a pattern at the end of a chunk are held back until the next chunk (or
//! [`Rewriter::flush`]), so a pattern split over two reads is still found. Lengths never change, so HTTP
//! `Content-Length` stays right.
use crate::config::Rewrite;
/// A streaming rewriter.
#[derive(Debug)]
pub struct Rewriter {
rules: Vec<Rewrite>,
held: Vec<u8>,
}
impl Rewriter {
/// A rewriter for `rules` (each non-empty, `from.len() == to.len()`, checked by the config).
pub fn new(rules: Vec<Rewrite>) -> Self {
Self { rules, held: Vec::new() }
}
/// Feeds a chunk; returns the bytes that are safe to send and how many replacements were made.
pub fn push(&mut self, chunk: &[u8]) -> (Vec<u8>, usize) {
if self.rules.is_empty() {
return (chunk.to_vec(), 0);
}
let mut data = std::mem::take(&mut self.held);
data.extend_from_slice(chunk);
let mut out = Vec::with_capacity(data.len());
let mut count = 0;
let mut i = 0;
'scan: while i < data.len() {
for r in &self.rules {
if data[i..].starts_with(&r.from) {
out.extend_from_slice(&r.to);
i += r.from.len();
count += 1;
continue 'scan;
}
}
// Could `data[i..]` be the beginning of a pattern that the next chunk completes?
let rest = &data[i..];
if self.rules.iter().any(|r| rest.len() < r.from.len() && r.from.starts_with(rest)) {
self.held = rest.to_vec();
return (out, count);
}
out.push(data[i]);
i += 1;
}
(out, count)
}
/// Releases held bytes (end of stream, or a pause in it).
pub fn flush(&mut self) -> Vec<u8> {
std::mem::take(&mut self.held)
}
/// Whether there are no rules (the rewriter then passes bytes through and never holds any).
pub fn is_empty(&self) -> bool {
self.rules.is_empty()
}
/// Bytes currently held back.
#[cfg(test)]
pub fn held(&self) -> usize {
self.held.len()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn lab() -> Rewriter {
Rewriter::new(vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }])
}
fn run(r: &mut Rewriter, chunks: &[&[u8]]) -> (Vec<u8>, usize) {
let mut out = Vec::new();
let mut n = 0;
for c in chunks {
let (o, k) = r.push(c);
out.extend(o);
n += k;
}
out.extend(r.flush());
(out, n)
}
const ANSWER: &[u8] = b"<root status_code=\"200\"><sessionUrl0>rtsp://127.0.0.2:48010</sessionUrl0></root>";
#[test]
fn replaces_in_one_chunk() {
let (out, n) = run(&mut lab(), &[ANSWER]);
assert_eq!(n, 1);
assert_eq!(out, ANSWER.to_vec().replace_all_for_test());
}
#[test]
fn replaces_across_every_split_point() {
let want = ANSWER.to_vec().replace_all_for_test();
for cut in 0..=ANSWER.len() {
let (out, n) = run(&mut lab(), &[&ANSWER[..cut], &ANSWER[cut..]]);
assert_eq!(n, 1, "cut {cut}");
assert_eq!(out, want, "cut {cut}");
}
}
#[test]
fn byte_by_byte_works() {
let chunks: Vec<&[u8]> = ANSWER.chunks(1).collect();
let (out, n) = run(&mut lab(), &chunks);
assert_eq!((out, n), (ANSWER.to_vec().replace_all_for_test(), 1));
}
#[test]
fn length_never_changes_and_lookalikes_survive() {
let input = b"127.0.0.20 127.0.0.2127.0.0.2 127.0.0. 127.0.0.3";
let (out, n) = run(&mut lab(), &[input]);
assert_eq!(out.len(), input.len());
assert_eq!(out, b"127.0.0.10 127.0.0.1127.0.0.1 127.0.0. 127.0.0.3");
assert_eq!(n, 3);
}
#[test]
fn holds_only_a_possible_prefix() {
let mut r = lab();
let (out, _) = r.push(b"abc127.0.");
assert_eq!(out, b"abc");
assert_eq!(r.held(), 6);
let (out, n) = r.push(b"x");
assert_eq!((out, n), (b"127.0.x".to_vec(), 0));
assert_eq!(r.held(), 0);
}
#[test]
fn no_rules_is_a_pass_through() {
let mut r = Rewriter::new(Vec::new());
assert_eq!(r.push(b"127.0.0.2"), (b"127.0.0.2".to_vec(), 0));
}
trait ReplaceAll {
fn replace_all_for_test(self) -> Vec<u8>;
}
impl ReplaceAll for Vec<u8> {
fn replace_all_for_test(self) -> Vec<u8> {
String::from_utf8(self).unwrap().replace("127.0.0.2", "127.0.0.1").into_bytes()
}
}
}
+133
View File
@@ -0,0 +1,133 @@
//! Plain TCP relaying (HTTP, RTSP, and HTTPS in pass-through mode).
use std::io::{self, Read, Write};
use std::net::{Shutdown, TcpListener, TcpStream};
use std::sync::Arc;
use std::thread;
use std::time::Duration;
use crate::config::{Config, PortSpec, Rewrite};
use crate::record::{Direction, Kind, Protocol};
use crate::recorder::Recorder;
use crate::rewrite::Rewriter;
/// How long the host-to-client side waits for more bytes before releasing bytes held by the rewriter.
pub const HOLD_TIMEOUT: Duration = Duration::from_millis(50);
/// Timeout for connecting to Sunshine.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Whether a protocol's bytes are plaintext the rewriter may touch.
pub fn rewritable(protocol: Protocol) -> bool {
matches!(protocol, Protocol::Http | Protocol::Rtsp | Protocol::HttpsPlain)
}
/// Accepts connections on `spec`'s port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
let listener = TcpListener::bind(config.listen_addr(&spec))?;
for client in listener.incoming() {
let client = match client {
Ok(c) => c,
Err(e) => {
rec.note(spec.protocol, 0, &format!("accept failed: {e}"));
continue;
}
};
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
thread::spawn(move || {
let conn = rec.new_connection();
if let Err(e) = relay(client, &config, spec, &rec, conn) {
rec.note(spec.protocol, conn, &format!("connection ended with error: {e}"));
}
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
});
}
Ok(())
}
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
let upstream_addr = config.upstream_addr(&spec);
let peer = client.peer_addr()?;
rec.log(Kind::Open, spec.protocol, Direction::None, conn, format!("{peer} -> {upstream_addr}").as_bytes());
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
let _ = client.set_nodelay(true);
let _ = upstream.set_nodelay(true);
let rules = if rewritable(spec.protocol) { config.rewrites.clone() } else { Vec::new() };
pump_pair(client, upstream, spec.protocol, rec, conn, rules)
}
/// Copies both directions until both sides are closed; rewrites host-to-client bytes with `rules`.
///
/// # Errors
/// Socket errors.
pub fn pump_pair(
client: TcpStream,
upstream: TcpStream,
protocol: Protocol,
rec: &Recorder,
conn: u32,
rules: Vec<Rewrite>,
) -> io::Result<()> {
let (mut c_read, mut u_write) = (client.try_clone()?, upstream.try_clone()?);
thread::scope(|s| {
s.spawn(|| {
let mut buf = vec![0u8; 64 * 1024];
loop {
match c_read.read(&mut buf) {
Ok(0) | Err(_) => break,
Ok(n) => {
rec.log(Kind::Data, protocol, Direction::ClientToHost, conn, &buf[..n]);
if u_write.write_all(&buf[..n]).is_err() {
break;
}
}
}
}
let _ = u_write.shutdown(Shutdown::Write);
});
host_to_client(upstream, client, protocol, rec, conn, rules)
})
}
fn host_to_client(
mut upstream: TcpStream,
mut client: TcpStream,
protocol: Protocol,
rec: &Recorder,
conn: u32,
rules: Vec<Rewrite>,
) -> io::Result<()> {
let mut rewriter = Rewriter::new(rules);
if !rewriter.is_empty() {
upstream.set_read_timeout(Some(HOLD_TIMEOUT))?;
}
let mut buf = vec![0u8; 64 * 1024];
let result = loop {
match upstream.read(&mut buf) {
Ok(0) => break Ok(()),
Ok(n) => {
rec.log(Kind::Data, protocol, Direction::HostToClient, conn, &buf[..n]);
let (out, count) = rewriter.push(&buf[..n]);
if count > 0 {
rec.note(protocol, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
}
if let Err(e) = client.write_all(&out) {
break Err(e);
}
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
let held = rewriter.flush();
if let Err(e) = client.write_all(&held) {
break Err(e);
}
}
Err(e) => break Err(e),
}
};
let rest = rewriter.flush();
let _ = client.write_all(&rest);
let _ = client.shutdown(Shutdown::Write);
result
}
+396
View File
@@ -0,0 +1,396 @@
//! TLS termination on the HTTPS port (LAB_CAPTURE.md section 4).
//!
//! Towards Moonlight the relay presents Sunshine's own lab certificate, the one Moonlight pinned while pairing, and
//! asks for (but accepts any) client certificate. Towards Sunshine it presents Moonlight's own lab client
//! certificate and accepts only Sunshine's lab certificate. Both sides see the certificates they expect; the relay
//! records the plaintext in between. All key material is lab-only and is never written to the record file.
use std::io::{self, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::path::Path;
use std::sync::Arc;
use std::thread;
use std::time::{Duration, Instant};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
use rustls::pki_types::pem::PemObject;
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
use rustls::{ClientConfig, ClientConnection, Connection, DigitallySignedStruct, DistinguishedName, ServerConfig};
use rustls::{ServerConnection, SignatureScheme};
use crate::config::{Config, PortSpec, TlsFiles};
use crate::record::{Direction, Kind, Protocol};
use crate::recorder::Recorder;
use crate::rewrite::Rewriter;
use crate::tcp::{self, CONNECT_TIMEOUT};
/// Read timeout while pumping plaintext between the two TLS sessions.
const POLL: Duration = Duration::from_millis(20);
/// Accepts connections on the HTTPS port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
let listener = TcpListener::bind(config.listen_addr(&spec))?;
for client in listener.incoming() {
let client = match client {
Ok(c) => c,
Err(e) => {
rec.note(Protocol::HttpsPlain, 0, &format!("accept failed: {e}"));
continue;
}
};
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
thread::spawn(move || {
let conn = rec.new_connection();
if let Err(e) = relay(client, &config, spec, &rec, conn) {
rec.note(Protocol::HttpsPlain, conn, &format!("connection ended with error: {e}"));
}
rec.log(Kind::Close, Protocol::HttpsPlain, Direction::None, conn, &[]);
});
}
Ok(())
}
/// The lab TLS material, loaded per connection (Moonlight's key may appear only after pairing step 1).
struct Material {
host_certs: Vec<CertificateDer<'static>>,
host_key: PrivateKeyDer<'static>,
client_certs: Vec<CertificateDer<'static>>,
client_key: PrivateKeyDer<'static>,
}
fn load(files: &TlsFiles) -> io::Result<Material> {
fn certs(path: &Path) -> io::Result<Vec<CertificateDer<'static>>> {
let certs = CertificateDer::pem_file_iter(path)
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?
.collect::<Result<Vec<_>, _>>()
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?;
if certs.is_empty() {
return Err(io::Error::other(format!("{}: no certificate", path.display())));
}
Ok(certs)
}
fn key(path: &Path) -> io::Result<PrivateKeyDer<'static>> {
// The error text names the file only; it never echoes key bytes.
PrivateKeyDer::from_pem_file(path).map_err(|_| io::Error::other(format!("{}: no usable key", path.display())))
}
Ok(Material {
host_certs: certs(&files.host_cert)?,
host_key: key(&files.host_key)?,
client_certs: certs(&files.client_cert)?,
client_key: key(&files.client_key)?,
})
}
/// Waits up to `wait` for all four files to load.
fn load_waiting(files: &TlsFiles, wait: Duration) -> io::Result<Material> {
let deadline = Instant::now() + wait;
loop {
match load(files) {
Ok(m) => return Ok(m),
Err(e) if Instant::now() >= deadline => return Err(e),
Err(_) => thread::sleep(Duration::from_millis(200)),
}
}
}
fn sha256_hex(bytes: &[u8]) -> String {
ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|b| format!("{b:02x}")).collect()
}
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
let upstream_addr = config.upstream_addr(&spec);
let peer = client.peer_addr()?;
rec.log(
Kind::Open,
Protocol::HttpsPlain,
Direction::None,
conn,
format!("{peer} -> {upstream_addr} (TLS terminated)").as_bytes(),
);
let Some(files) = &config.tls else {
return Err(io::Error::other("TLS files not configured"));
};
let material = match load_waiting(files, config.wait_for_keys) {
Ok(m) => m,
Err(e) => {
// No keys: carry the raw TLS bytes, so the session still works and is still recorded.
rec.note(Protocol::HttpsTls, conn, &format!("lab keys not available ({e}); passing TLS through"));
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
return tcp::pump_pair(client, upstream, Protocol::HttpsTls, rec, conn, Vec::new());
}
};
let provider = Arc::new(rustls::crypto::ring::default_provider());
let algs = provider.signature_verification_algorithms;
let server_config = ServerConfig::builder_with_provider(Arc::clone(&provider))
.with_safe_default_protocol_versions()
.map_err(io::Error::other)?
.with_client_cert_verifier(Arc::new(AnyClientCert { algs }))
.with_single_cert(material.host_certs.clone(), material.host_key)
.map_err(io::Error::other)?;
let pinned = material.host_certs[0].as_ref().to_vec();
let client_config = client_config(&provider, pinned, material.client_certs.clone(), material.client_key)?;
// Moonlight side first: it has already sent its ClientHello.
let mut moonlight = client;
let mut down = Connection::Server(ServerConnection::new(Arc::new(server_config)).map_err(io::Error::other)?);
while down.is_handshaking() {
down.complete_io(&mut moonlight)?;
}
let presented = down.peer_certificates().and_then(|c| c.first()).map(|c| sha256_hex(c.as_ref()));
let expected = sha256_hex(material.client_certs[0].as_ref());
rec.note(
Protocol::HttpsPlain,
conn,
&format!(
"client side: {:?}, {:?}, client certificate sha256 {} ({})",
down.protocol_version(),
down.negotiated_cipher_suite().map(|s| s.suite()),
presented.as_deref().unwrap_or("none"),
if presented.as_deref() == Some(expected.as_str()) {
"matches the lab client certificate"
} else {
"differs from the lab client certificate"
},
),
);
let mut sunshine = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
let name = ServerName::from(upstream_addr.ip());
let mut up = Connection::Client(ClientConnection::new(Arc::new(client_config), name).map_err(io::Error::other)?);
while up.is_handshaking() {
up.complete_io(&mut sunshine)?;
}
rec.note(
Protocol::HttpsPlain,
conn,
&format!("host side: {:?}, {:?}", up.protocol_version(), up.negotiated_cipher_suite().map(|s| s.suite())),
);
for s in [&moonlight, &sunshine] {
s.set_read_timeout(Some(POLL))?;
let _ = s.set_nodelay(true);
}
pump(&mut down, &mut moonlight, &mut up, &mut sunshine, rec, conn, Rewriter::new(config.rewrites.clone()))
}
fn client_config(
provider: &Arc<CryptoProvider>,
pinned: Vec<u8>,
certs: Vec<CertificateDer<'static>>,
key: PrivateKeyDer<'static>,
) -> io::Result<ClientConfig> {
let algs = provider.signature_verification_algorithms;
ClientConfig::builder_with_provider(Arc::clone(provider))
.with_safe_default_protocol_versions()
.map_err(io::Error::other)?
.dangerous()
.with_custom_certificate_verifier(Arc::new(PinnedHost { pinned, algs }))
.with_client_auth_cert(certs, key)
.map_err(io::Error::other)
}
/// Moves plaintext both ways until both sides are done.
fn pump(
down: &mut Connection,
moonlight: &mut TcpStream,
up: &mut Connection,
sunshine: &mut TcpStream,
rec: &Recorder,
conn: u32,
mut rewriter: Rewriter,
) -> io::Result<()> {
let (mut down_open, mut up_open) = (true, true);
while down_open || up_open {
if down_open {
let (data, eof) = pull(down, moonlight)?;
if !data.is_empty() {
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::ClientToHost, conn, &data);
if up_open {
push(up, sunshine, &data)?;
}
}
if eof {
down_open = false;
if up_open {
up.send_close_notify();
flush(up, sunshine)?;
}
}
}
if up_open {
let (data, eof) = pull(up, sunshine)?;
if data.is_empty() {
let held = rewriter.flush();
if !held.is_empty() && down_open {
push(down, moonlight, &held)?;
}
} else {
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::HostToClient, conn, &data);
let (out, count) = rewriter.push(&data);
if count > 0 {
rec.note(Protocol::HttpsPlain, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
}
if down_open {
push(down, moonlight, &out)?;
}
}
if eof {
up_open = false;
if down_open {
let held = rewriter.flush();
push(down, moonlight, &held)?;
down.send_close_notify();
flush(down, moonlight)?;
}
}
}
}
Ok(())
}
/// Reads what TLS bytes are there (or waits [`POLL`]) and returns the new plaintext and whether the peer is done.
fn pull(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<(Vec<u8>, bool)> {
let mut eof = false;
match conn.read_tls(sock) {
Ok(0) => eof = true,
Ok(_) => {
conn.process_new_packets().map_err(io::Error::other)?;
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
Err(e) => return Err(e),
}
let mut data = Vec::new();
let mut buf = [0u8; 16 * 1024];
loop {
match conn.reader().read(&mut buf) {
Ok(0) => {
eof = true;
break;
}
Ok(n) => data.extend_from_slice(&buf[..n]),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
eof = true;
break;
}
Err(e) => return Err(e),
}
}
flush(conn, sock)?;
Ok((data, eof))
}
fn push(conn: &mut Connection, sock: &mut TcpStream, data: &[u8]) -> io::Result<()> {
conn.writer().write_all(data)?;
flush(conn, sock)
}
fn flush(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<()> {
while conn.wants_write() {
conn.write_tls(sock)?;
}
Ok(())
}
/// Accepts any client certificate (it is recorded by fingerprint, and Sunshine checks the real one).
#[derive(Debug)]
struct AnyClientCert {
algs: WebPkiSupportedAlgorithms,
}
impl ClientCertVerifier for AnyClientCert {
fn offer_client_auth(&self) -> bool {
true
}
fn client_auth_mandatory(&self) -> bool {
false
}
fn root_hint_subjects(&self) -> &[DistinguishedName] {
&[]
}
fn verify_client_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_now: UnixTime,
) -> Result<ClientCertVerified, rustls::Error> {
Ok(ClientCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls12_signature(message, cert, dss, &self.algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls13_signature(message, cert, dss, &self.algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algs.supported_schemes()
}
}
/// Accepts exactly Sunshine's lab certificate, byte for byte.
#[derive(Debug)]
struct PinnedHost {
pinned: Vec<u8>,
algs: WebPkiSupportedAlgorithms,
}
impl ServerCertVerifier for PinnedHost {
fn verify_server_cert(
&self,
end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &ServerName<'_>,
_ocsp_response: &[u8],
_now: UnixTime,
) -> Result<ServerCertVerified, rustls::Error> {
if end_entity.as_ref() == self.pinned.as_slice() {
Ok(ServerCertVerified::assertion())
} else {
Err(rustls::Error::General("host certificate is not the pinned lab certificate".into()))
}
}
fn verify_tls12_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls12_signature(message, cert, dss, &self.algs)
}
fn verify_tls13_signature(
&self,
message: &[u8],
cert: &CertificateDer<'_>,
dss: &DigitallySignedStruct,
) -> Result<HandshakeSignatureValid, rustls::Error> {
verify_tls13_signature(message, cert, dss, &self.algs)
}
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
self.algs.supported_schemes()
}
}
+107
View File
@@ -0,0 +1,107 @@
//! UDP relaying (video, control, audio, mic).
//!
//! Each client address gets its own upstream socket on the listen address, so Sunshine sends the stream to the
//! relay (the address its PING or ENet connect came from) and the relay hands it to Moonlight.
use std::collections::HashMap;
use std::io;
use std::net::{SocketAddr, UdpSocket};
use std::sync::{Arc, Mutex};
use std::thread;
use crate::config::{Config, PortSpec};
use crate::record::{Direction, Kind};
use crate::recorder::Recorder;
/// Most client flows per port (one Moonlight uses one).
pub const MAX_FLOWS: usize = 16;
/// Largest datagram.
pub const MAX_DATAGRAM: usize = 64 * 1024;
/// Windows reports an ICMP "port unreachable" from an earlier send as a reset on the next receive; that is not
/// fatal for UDP.
fn transient(e: &io::Error) -> bool {
matches!(e.kind(), io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionRefused | io::ErrorKind::Interrupted)
}
/// Relays one UDP port forever.
///
/// # Errors
/// Binding fails.
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
let listen = Arc::new(UdpSocket::bind(config.listen_addr(&spec))?);
let upstream_addr = config.upstream_addr(&spec);
let flows: Mutex<HashMap<SocketAddr, (Arc<UdpSocket>, u32)>> = Mutex::new(HashMap::new());
let mut buf = vec![0u8; MAX_DATAGRAM];
loop {
let (n, from) = match listen.recv_from(&mut buf) {
Ok(v) => v,
Err(e) if transient(&e) => continue,
Err(e) => {
rec.note(spec.protocol, 0, &format!("receive failed: {e}"));
continue;
}
};
let flow = {
let Ok(mut map) = flows.lock() else { return Err(io::Error::other("flow table poisoned")) };
if let Some(f) = map.get(&from) {
Some(f.clone())
} else if map.len() >= MAX_FLOWS {
rec.note(spec.protocol, 0, &format!("dropping datagram from {from}: flow table full"));
None
} else {
let up = Arc::new(UdpSocket::bind(SocketAddr::new(config.listen, 0))?);
up.connect(upstream_addr)?;
let conn = rec.new_connection();
rec.log(
Kind::Open,
spec.protocol,
Direction::None,
conn,
format!("{from} -> {upstream_addr}").as_bytes(),
);
spawn_return_path(Arc::clone(&up), Arc::clone(&listen), from, spec, Arc::clone(&rec), conn);
map.insert(from, (Arc::clone(&up), conn));
Some((up, conn))
}
};
let Some((up, conn)) = flow else { continue };
rec.log(Kind::Data, spec.protocol, Direction::ClientToHost, conn, &buf[..n]);
if let Err(e) = up.send(&buf[..n])
&& !transient(&e)
{
rec.note(spec.protocol, conn, &format!("send to host failed: {e}"));
}
}
}
fn spawn_return_path(
up: Arc<UdpSocket>,
listen: Arc<UdpSocket>,
client: SocketAddr,
spec: PortSpec,
rec: Arc<Recorder>,
conn: u32,
) {
thread::spawn(move || {
let mut buf = vec![0u8; MAX_DATAGRAM];
loop {
match up.recv(&mut buf) {
Ok(n) => {
rec.log(Kind::Data, spec.protocol, Direction::HostToClient, conn, &buf[..n]);
if let Err(e) = listen.send_to(&buf[..n], client)
&& !transient(&e)
{
rec.note(spec.protocol, conn, &format!("send to client failed: {e}"));
}
}
Err(e) if transient(&e) => {}
Err(e) => {
rec.note(spec.protocol, conn, &format!("receive from host failed: {e}"));
break;
}
}
}
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
});
}