[probe] gs-probe: desktop GameStream probe client and the live interop run book

tools/gs-probe (own workspace, never published): `probe serverinfo | pair | apps | launch <app-id> | quit | unpair`
against one host address, driving DomiStream's pairing, HTTP, RTSP, ENet, control, video and audio state machines
over real sockets. Structured JSONL log per run (requests, answers, timings, the U each record bears on, parser
errors with their bytes), secrets redacted (rikey, pairing values; PIN never logged; registered key hex scrubbed from
every line). Test-only client key and cert in --out. Video: frames, decode-ready frames, FEC recoveries, losses,
elementary-stream dump, live U14 parity check; audio: packets, losses, decrypting vs plain receivers (U17), packet
dump and offline U16 solver (`solve-audio-fec`). START_A/START_B/PERIODIC_PING/IDR bodies come from the command line
(U10).

docs/LIVE-INTEROP.md: the sitting's run book (preparation, sequence S0-S5 with the U each step settles, variants,
log reading, where each fact lands in PROTOCOL.md and the code, stop-and-report rule, clean-up, Mark's timeline).

Built and unit-tested only (41 tests, clippy -D warnings, fmt); never run against a host.
This commit is contained in:
2026-11-30 10:57:07 +01:00
parent a3c8cea7a6
commit 07ccff4241
17 changed files with 4909 additions and 0 deletions
+692
View File
@@ -0,0 +1,692 @@
# 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 = "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 = "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",
"num-traits",
"rand_core",
"serdect",
"zeroize",
]
[[package]]
name = "crypto-common"
version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
dependencies = [
"hybrid-array",
"rand_core",
]
[[package]]
name = "crypto-primes"
version = "0.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f"
dependencies = [
"crypto-bigint",
"rand_core",
]
[[package]]
name = "ctr"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21"
dependencies = [
"cipher",
]
[[package]]
name = "ctutils"
version = "0.4.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "261af4dc7a06ea8a527a8717d8cbba3417530d6ea14e1edb3de6b67806be474f"
dependencies = [
"cmov",
]
[[package]]
name = "der"
version = "0.8.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6a996a108feb8b427a6e12fcf6af4aa83409b79d72c15337d7741368131ee004"
dependencies = [
"const-oid",
"der_derive",
"flagset",
"pem-rfc7468",
"zeroize",
]
[[package]]
name = "der_derive"
version = "0.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "59600e2c2d636fde9b65e99cc6445ac770c63d3628195ff39932b8d6d7409903"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "digest"
version = "0.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
dependencies = [
"block-buffer",
"const-oid",
"crypto-common",
"ctutils",
"zeroize",
]
[[package]]
name = "domistream"
version = "0.1.0"
dependencies = [
"aes",
"aes-gcm",
"cbc",
"rand_core",
"rsa",
"sha2",
"x509-cert",
"zeroize",
]
[[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.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
"cfg-if",
"libc",
"wasi",
]
[[package]]
name = "ghash"
version = "0.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5"
dependencies = [
"polyval",
]
[[package]]
name = "gs-probe"
version = "0.1.0"
dependencies = [
"domistream",
"ring",
"rustls",
]
[[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 = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[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 = "rand_core"
version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
[[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 = "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 = "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 = "serde"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
dependencies = [
"serde_core",
]
[[package]]
name = "serde_core"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.229"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.10",
]
[[package]]
name = "serdect"
version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e"
dependencies = [
"base16ct",
"serde",
]
[[package]]
name = "sha2"
version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b0e5c7d67bc53f435386b2130fdc900488c5703770f6d8a4633060e34288a27"
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 = "subtle"
version = "2.6.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "syn"
version = "3.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "typenum"
version = "1.20.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
[[package]]
name = "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 = "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 = "x509-cert"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417"
dependencies = [
"const-oid",
"der",
"spki",
]
[[package]]
name = "zeroize"
version = "1.9.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
+28
View File
@@ -0,0 +1,28 @@
# gs-probe: a desktop GameStream probe client for the one live interop sitting (docs/LIVE-INTEROP.md). A tool, never
# published, never part of the domistream crate: it may use sockets, threads, files and the clock, and drives
# DomiStream's sans-I/O state machines against ONE host address given on the command line. Its own workspace so it
# never joins the main build.
[package]
name = "gs-probe"
version = "0.1.0"
edition = "2024"
rust-version = "1.89"
license = "CPAL-1.0"
publish = false
[workspace]
members = ["."]
[[bin]]
name = "probe"
path = "src/main.rs"
[dependencies]
domistream = { path = "../../crates/domistream" }
# HTTPS with the client certificate and the pinned host certificate. ring backend, as in tools/lab-relay.
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
# The OS random generator (salts, keys, PIN) and SHA-256 fingerprints; already under rustls.
ring = "0.17"
[lints.rust]
unsafe_code = "forbid"
+447
View File
@@ -0,0 +1,447 @@
//! The command line. Strict: an unknown option, a missing value or a value out of range is refused, never guessed.
use std::net::IpAddr;
use std::path::PathBuf;
use domistream::http::launch::AudioLayout;
use domistream::rtsp::client::VideoCodec;
pub const USAGE: &str = "\
usage: probe <command> --host <ip> --out <dir> [options]
commands:
serverinfo GET /serverinfo over HTTP (and HTTPS once paired)
pair pair this probe: prints a 4-digit PIN for the operator to submit through Sunshine's API
apps GET /applist (HTTPS)
launch <app-id> launch, RTSP, ENet control, then receive video + audio for --seconds
quit GET /cancel (HTTPS): quits the running app
unpair GET /unpair (HTTPS): the host forgets this probe
solve-audio-fec <file> offline: solve the audio parity matrix (U16) from a launch run's audio-packets.bin
common options:
--host <ip> the ONE host address; every socket goes there (or to --relay)
--out <dir> identity (test-only key and cert), runs/<utc>-<command>/log.jsonl and dumps
--http-port <n> 47989 --https-port <n> 47984
--relay <loopback ip> connect to tools/lab-relay on this loopback address instead (same ports)
--bind <ip> local address for the UDP sockets (default: unspecified)
--name <text> device name sent while pairing and certificate CN (default: DomiStream probe)
pair:
--wrong-pin print one PIN but use another (U28: what the host does after a failed pairing)
launch:
--mode <WxHxFPS> 1920x1080x60 --bitrate <kbps> 20000 --packet-size <n> 1024
--codec h264|hevc|av1 h264 --hdr --audio stereo|5.1|7.1
--audio-ms <n> 5 --min-fec <n> 2 --rfi (ask for reference frame invalidation)
--encryption <0-7> 7 (bits: 1 control V2, 2 video, 4 audio)
--seconds <n> 20 (1-600) --dump-frames <n> 120 --dump-packets <n> 3000
--ping-ms <n> 500 (UDP ping to the video and audio ports)
--enet-channels <n> 1 --enet-mtu <n> 1392 --enet-connect-data <n> 0
--control-channel <n> 0 --first-control-seq <n> 0
--start-a <hex|empty|none> empty --start-b <hex|empty|none> empty
--periodic-ping <hex|empty> off --periodic-ping-ms <n> 100
--idr <hex|empty> off (body of an IDR request sent on frame loss)
--nudge-mouse send one relative mouse move +1/-1 after the first decodable frame
";
/// What to do.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Command {
ServerInfo,
Pair,
Apps,
Launch { app_id: u32 },
Quit,
Unpair,
SolveAudioFec { dump: PathBuf },
}
impl Command {
/// The short name used in run folder names and the log.
pub const fn name(&self) -> &'static str {
match self {
Self::ServerInfo => "serverinfo",
Self::Pair => "pair",
Self::Apps => "apps",
Self::Launch { .. } => "launch",
Self::Quit => "quit",
Self::Unpair => "unpair",
Self::SolveAudioFec { .. } => "solve-audio-fec",
}
}
/// Whether the command talks to the host (and so needs `--host` and `--out`).
pub const fn is_network(&self) -> bool {
!matches!(self, Self::SolveAudioFec { .. })
}
}
/// A control message body from the command line: skip the message, send it empty, or send these bytes.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Body {
None,
Bytes(Vec<u8>),
}
/// Every option, with its default.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Options {
pub host: Option<IpAddr>,
pub out: Option<PathBuf>,
pub http_port: u16,
pub https_port: u16,
pub relay: Option<IpAddr>,
pub bind: Option<IpAddr>,
pub name: String,
pub wrong_pin: bool,
pub width: u32,
pub height: u32,
pub fps: u32,
pub bitrate_kbps: u32,
pub packet_size: u16,
pub codec: VideoCodec,
pub hdr: bool,
pub audio: AudioLayout,
pub audio_ms: u8,
pub min_fec: u8,
pub rfi: bool,
pub encryption: u8,
pub seconds: u32,
pub dump_frames: u32,
pub dump_packets: u32,
pub ping_ms: u32,
pub enet_channels: u8,
pub enet_mtu: u16,
pub enet_connect_data: u32,
pub control_channel: u8,
pub first_control_seq: u32,
pub start_a: Body,
pub start_b: Body,
pub periodic_ping: Body,
pub periodic_ping_ms: u32,
pub idr: Body,
pub nudge_mouse: bool,
}
impl Default for Options {
fn default() -> Self {
Self {
host: None,
out: None,
http_port: domistream::http::DEFAULT_HTTP_PORT,
https_port: domistream::http::DEFAULT_HTTPS_PORT,
relay: None,
bind: None,
name: "DomiStream probe".to_owned(),
wrong_pin: false,
width: 1920,
height: 1080,
fps: 60,
bitrate_kbps: 20_000,
packet_size: 1024,
codec: VideoCodec::H264,
hdr: false,
audio: AudioLayout::Stereo,
audio_ms: 5,
min_fec: 2,
rfi: false,
encryption: 7,
seconds: 20,
dump_frames: 120,
dump_packets: 3000,
ping_ms: 500,
enet_channels: 1,
enet_mtu: 1392,
enet_connect_data: 0,
control_channel: 0,
first_control_seq: 0,
start_a: Body::Bytes(Vec::new()),
start_b: Body::Bytes(Vec::new()),
periodic_ping: Body::None,
periodic_ping_ms: 100,
idr: Body::None,
nudge_mouse: false,
}
}
}
impl Options {
/// The address every socket connects to: the relay when one is given, else the host.
pub fn connect_ip(&self) -> Option<IpAddr> {
self.relay.or(self.host)
}
}
/// A parsed command line.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Invocation {
pub command: Command,
pub options: Options,
}
/// Largest control message body accepted from the command line.
pub const MAX_BODY_BYTES: usize = 1024;
fn number<T: std::str::FromStr>(name: &str, v: &str) -> Result<T, String> {
v.parse().map_err(|_| format!("{name}: '{v}' is not a valid number"))
}
fn ranged<T: std::str::FromStr + PartialOrd + std::fmt::Display>(
name: &str,
v: &str,
min: T,
max: T,
) -> Result<T, String> {
let n: T = number(name, v)?;
if n < min || n > max {
return Err(format!("{name}: {n} is outside {min}..={max}"));
}
Ok(n)
}
/// `hex`, `empty` or `none` (when `allow_none`).
pub fn parse_body(name: &str, v: &str, allow_none: bool) -> Result<Body, String> {
match v {
"none" if allow_none => Ok(Body::None),
"empty" => Ok(Body::Bytes(Vec::new())),
_ => parse_hex(v).map(Body::Bytes).map_err(|e| format!("{name}: {e}")),
}
}
/// Hex digits, upper or lower case, optionally separated by spaces, colons or dashes; at most [`MAX_BODY_BYTES`].
pub fn parse_hex(v: &str) -> Result<Vec<u8>, String> {
let digits: Vec<u8> = v.bytes().filter(|b| !matches!(b, b' ' | b':' | b'-')).collect();
if digits.is_empty() || !digits.len().is_multiple_of(2) {
return Err(format!("'{v}' is not an even number of hex digits"));
}
if digits.len() / 2 > MAX_BODY_BYTES {
return Err(format!("more than {MAX_BODY_BYTES} bytes"));
}
let nibble = |b: u8| match b {
b'0'..=b'9' => Ok(b - b'0'),
b'a'..=b'f' => Ok(b - b'a' + 10),
b'A'..=b'F' => Ok(b - b'A' + 10),
_ => Err(format!("'{v}' holds a non-hex character")),
};
digits.chunks(2).map(|p| Ok((nibble(p[0])? << 4) | nibble(p[1])?)).collect()
}
/// `WxHxFPS`, each part non-zero.
pub fn parse_mode(v: &str) -> Result<(u32, u32, u32), String> {
let parts: Vec<&str> = v.split('x').collect();
let [w, h, f] = parts.as_slice() else { return Err(format!("--mode: '{v}' is not WxHxFPS")) };
Ok((ranged("--mode width", w, 1, 8192)?, ranged("--mode height", h, 1, 8192)?, ranged("--mode fps", f, 1, 480)?))
}
fn ip(name: &str, v: &str) -> Result<IpAddr, String> {
v.parse().map_err(|_| format!("{name}: '{v}' is not an IP address (names are not resolved)"))
}
/// Parses the arguments after the program name.
pub fn parse(args: &[String]) -> Result<Invocation, String> {
let mut it = args.iter();
let command = match it.next().map(String::as_str) {
Some("serverinfo") => Command::ServerInfo,
Some("pair") => Command::Pair,
Some("apps") => Command::Apps,
Some("launch") => {
let id = it.next().ok_or("launch: needs an app id")?;
Command::Launch { app_id: number("launch <app-id>", id)? }
}
Some("quit") => Command::Quit,
Some("unpair") => Command::Unpair,
Some("solve-audio-fec") => {
let file = it.next().ok_or("solve-audio-fec: needs a file")?;
Command::SolveAudioFec { dump: PathBuf::from(file) }
}
Some(other) => return Err(format!("unknown command '{other}'")),
None => return Err("no command".into()),
};
let mut o = Options::default();
while let Some(flag) = it.next() {
let mut value = || it.next().map(String::as_str).ok_or(format!("{flag}: needs a value"));
match flag.as_str() {
"--host" => o.host = Some(ip(flag, value()?)?),
"--out" => o.out = Some(PathBuf::from(value()?)),
"--http-port" => o.http_port = ranged(flag, value()?, 1, 65535)?,
"--https-port" => o.https_port = ranged(flag, value()?, 1, 65535)?,
"--relay" => {
let r = ip(flag, value()?)?;
if !r.is_loopback() {
return Err(format!(
"--relay: {r} is not a loopback address (tools/lab-relay runs on loopback only)"
));
}
o.relay = Some(r);
}
"--bind" => o.bind = Some(ip(flag, value()?)?),
"--name" => {
let n = value()?;
if n.is_empty() || n.len() > 64 || n.chars().any(char::is_control) {
return Err("--name: 1-64 characters, no control characters".into());
}
o.name = n.to_owned();
}
"--wrong-pin" => o.wrong_pin = true,
"--mode" => (o.width, o.height, o.fps) = parse_mode(value()?)?,
"--bitrate" => o.bitrate_kbps = ranged(flag, value()?, 500, 500_000)?,
"--packet-size" => o.packet_size = ranged(flag, value()?, 64, 4000)?,
"--codec" => {
o.codec = match value()? {
"h264" => VideoCodec::H264,
"hevc" => VideoCodec::Hevc,
"av1" => VideoCodec::Av1,
v => return Err(format!("--codec: '{v}' is not h264, hevc or av1")),
}
}
"--hdr" => o.hdr = true,
"--audio" => {
o.audio = match value()? {
"stereo" => AudioLayout::Stereo,
"5.1" => AudioLayout::Surround51,
"7.1" => AudioLayout::Surround71,
v => return Err(format!("--audio: '{v}' is not stereo, 5.1 or 7.1")),
}
}
"--audio-ms" => o.audio_ms = ranged(flag, value()?, 1, 100)?,
"--min-fec" => o.min_fec = ranged(flag, value()?, 0, 64)?,
"--rfi" => o.rfi = true,
"--encryption" => o.encryption = ranged(flag, value()?, 0, 7)?,
"--seconds" => o.seconds = ranged(flag, value()?, 1, 600)?,
"--dump-frames" => o.dump_frames = ranged(flag, value()?, 0, 100_000)?,
"--dump-packets" => o.dump_packets = ranged(flag, value()?, 0, 1_000_000)?,
"--ping-ms" => o.ping_ms = ranged(flag, value()?, 10, 10_000)?,
"--enet-channels" => o.enet_channels = ranged(flag, value()?, 1, 255)?,
"--enet-mtu" => o.enet_mtu = ranged(flag, value()?, 576, 4096)?,
"--enet-connect-data" => o.enet_connect_data = number(flag, value()?)?,
"--control-channel" => o.control_channel = number(flag, value()?)?,
"--first-control-seq" => o.first_control_seq = number(flag, value()?)?,
"--start-a" => o.start_a = parse_body(flag, value()?, true)?,
"--start-b" => o.start_b = parse_body(flag, value()?, true)?,
"--periodic-ping" => o.periodic_ping = parse_body(flag, value()?, true)?,
"--periodic-ping-ms" => o.periodic_ping_ms = ranged(flag, value()?, 10, 10_000)?,
"--idr" => o.idr = parse_body(flag, value()?, true)?,
"--nudge-mouse" => o.nudge_mouse = true,
other => return Err(format!("unknown option '{other}'")),
}
}
if o.control_channel >= o.enet_channels {
return Err(format!(
"--control-channel {} needs --enet-channels above it (now {})",
o.control_channel, o.enet_channels
));
}
if command.is_network() {
if o.host.is_none() {
return Err(format!("{}: --host is required", command.name()));
}
if o.out.is_none() {
return Err(format!("{}: --out is required", command.name()));
}
}
Ok(Invocation { command, options: o })
}
#[cfg(test)]
mod tests {
use super::*;
fn args(s: &str) -> Vec<String> {
s.split_whitespace().map(str::to_owned).collect()
}
fn ok(s: &str) -> Invocation {
parse(&args(s)).unwrap()
}
fn err(s: &str) -> String {
parse(&args(s)).unwrap_err()
}
#[test]
fn network_commands_need_host_and_out() {
assert!(err("serverinfo --out x").contains("--host"));
assert!(err("serverinfo --host 192.168.100.140").contains("--out"));
let i = ok("serverinfo --host 192.168.100.140 --out F:/x");
assert_eq!(i.command, Command::ServerInfo);
assert_eq!(i.options.host, Some("192.168.100.140".parse().unwrap()));
assert_eq!(i.options.connect_ip(), i.options.host);
}
#[test]
fn defaults_are_the_documented_ones() {
let o = ok("pair --host 127.0.0.1 --out o").options;
assert_eq!((o.http_port, o.https_port), (47989, 47984));
assert_eq!((o.width, o.height, o.fps, o.bitrate_kbps, o.packet_size), (1920, 1080, 60, 20_000, 1024));
assert_eq!((o.encryption, o.seconds, o.enet_channels, o.enet_mtu), (7, 20, 1, 1392));
assert_eq!(o.start_a, Body::Bytes(vec![]));
assert_eq!(o.periodic_ping, Body::None);
assert!(!o.wrong_pin && !o.nudge_mouse && !o.rfi);
}
#[test]
fn launch_needs_a_numeric_app_id() {
assert!(err("launch").contains("app id"));
assert!(err("launch --host 1.2.3.4 --out o").contains("not a valid number"));
assert!(err("launch abc --host 1.2.3.4 --out o").contains("not a valid number"));
assert_eq!(ok("launch 881448767 --host 1.2.3.4 --out o").command, Command::Launch { app_id: 881_448_767 });
}
#[test]
fn host_names_and_unknown_options_are_refused() {
assert!(err("apps --host my-pc --out o").contains("not an IP address"));
assert!(err("apps --host 1.2.3.4 --out o --verbose").contains("unknown option"));
assert!(err("apps --host 1.2.3.4 --out").contains("needs a value"));
assert!(err("dance").contains("unknown command"));
assert!(err("").contains("no command"));
}
#[test]
fn relay_must_be_loopback() {
assert!(err("apps --host 192.168.100.140 --out o --relay 192.168.100.2").contains("loopback"));
let o = ok("apps --host 192.168.100.140 --out o --relay 127.0.0.1").options;
assert_eq!(o.connect_ip(), Some("127.0.0.1".parse().unwrap()));
}
#[test]
fn launch_options_parse_and_are_ranged() {
let o = ok("launch 1 --host ::1 --out o --mode 1280x720x30 --codec hevc --audio 5.1 --seconds 600 \
--start-b 0a0B --start-a none --idr empty --enet-channels 48 --control-channel 47 --hdr --rfi")
.options;
assert_eq!((o.width, o.height, o.fps), (1280, 720, 30));
assert_eq!((o.codec, o.audio), (VideoCodec::Hevc, AudioLayout::Surround51));
assert_eq!((o.start_a, o.start_b, o.idr), (Body::None, Body::Bytes(vec![0x0a, 0x0b]), Body::Bytes(vec![])));
assert!(o.hdr && o.rfi);
assert!(err("launch 1 --host ::1 --out o --seconds 601").contains("outside"));
assert!(err("launch 1 --host ::1 --out o --encryption 8").contains("outside"));
assert!(err("launch 1 --host ::1 --out o --mode 1920x1080").contains("WxHxFPS"));
assert!(err("launch 1 --host ::1 --out o --mode 0x1080x60").contains("outside"));
assert!(err("launch 1 --host ::1 --out o --control-channel 1").contains("--enet-channels"));
assert!(err("launch 1 --host ::1 --out o --codec vp9").contains("h264"));
}
#[test]
fn hex_bodies() {
assert_eq!(parse_hex("00 ff:A0-0b").unwrap(), vec![0x00, 0xff, 0xa0, 0x0b]);
assert!(parse_hex("abc").is_err());
assert!(parse_hex("zz").is_err());
assert!(parse_hex("").is_err());
assert!(parse_hex(&"00".repeat(MAX_BODY_BYTES + 1)).is_err());
assert_eq!(parse_body("x", "none", true).unwrap(), Body::None);
assert!(parse_body("x", "none", false).is_err());
}
#[test]
fn solve_audio_fec_is_offline() {
let i = ok("solve-audio-fec F:/runs/a/audio-packets.bin");
assert_eq!(i.command, Command::SolveAudioFec { dump: PathBuf::from("F:/runs/a/audio-packets.bin") });
assert!(!i.command.is_network());
}
#[test]
fn device_name_is_checked() {
assert!(err("pair --host 1.2.3.4 --out o --name").contains("needs a value"));
let long = format!("pair --host 1.2.3.4 --out o --name {}", "n".repeat(65));
assert!(err(&long).contains("1-64"));
}
}
+222
View File
@@ -0,0 +1,222 @@
//! `serverinfo`, `pair`, `apps`, `quit`, `unpair`.
use domistream::http::{
Scheme, app_list_request, cancel_request, parse_app_list, parse_server_info, parse_status_response,
server_info_request, unpair_request,
};
use domistream::pairing::{PairingSession, PairingState, PairingStep, Pin, ServerCert, parse_pair_response};
use crate::log::{J, Kind};
use crate::rng::sha256_hex;
use crate::{Ctx, body_j, state};
/// Non-200 HTTP status: stop and report (U27 is in the body).
fn check_status(ctx: &mut Ctx, step: &str, x: &crate::http::Exchange) -> Result<(), String> {
if x.response.status == 200 {
return Ok(());
}
let m = format!("HTTP status {} {}", x.response.status, x.response.reason);
ctx.log.stop(step, &["U27"], m.clone(), body_j(&x.response.body));
Err(m)
}
fn server_info(ctx: &mut Ctx, scheme: Scheme) -> Result<(), String> {
let step = match scheme {
Scheme::Http => "serverinfo.http",
Scheme::Https => "serverinfo.https",
};
let req = server_info_request(scheme, &ctx.id.unique_id).map_err(|e| e.to_string())?;
let x = ctx.http(step, &["U25", "U27"], &req, None)?;
check_status(ctx, step, &x)?;
let info = match parse_server_info(&x.response.body) {
Ok(i) => i,
Err(e) => {
ctx.log.parse_error(step, &["U25", "U27"], &e, body_j(&x.response.body));
ctx.log.stop(step, &["U25"], format!("serverinfo refused: {e}"), J::Null);
return Err(format!("serverinfo refused: {e}"));
}
};
let codec_bits = info.codec_mode_support.map_or(J::Null, |b| J::s(format!("{b:#010x} = {b:032b}")));
ctx.log.record(
step,
Kind::Note,
&["U25"],
J::O(vec![("parsed", J::dbg(&info)), ("codec_mode_support_bits", codec_bits)]),
);
println!("{step}:");
println!(" hostname {} appversion {} GfeVersion {:?}", info.hostname, info.app_version, info.gfe_version);
println!(
" HttpsPort {} ExternalPort {:?} state {} currentgame {}",
info.https_port, info.http_port, info.state, info.current_game
);
println!(
" ServerCodecModeSupport {:?} MaxLumaPixelsHEVC {:?} PairStatus {}",
info.codec_mode_support, info.max_luma_pixels_hevc, info.paired
);
if info.https_port != ctx.opts.https_port {
let m = format!(
"the host's HttpsPort is {}; pass --https-port {} for HTTPS calls",
info.https_port, info.https_port
);
ctx.log.note(step, &[], m.clone());
println!(" note: {m}");
}
Ok(())
}
pub fn serverinfo(ctx: &mut Ctx) -> Result<(), String> {
server_info(ctx, Scheme::Http)?;
if ctx.host_cert.is_some() {
server_info(ctx, Scheme::Https)?;
} else {
println!("(not paired yet: HTTPS serverinfo skipped)");
}
Ok(())
}
pub fn pair(ctx: &mut Ctx) -> Result<(), String> {
let shown = Pin::generate(&mut ctx.rng).map_err(|e| e.to_string())?;
let used = if ctx.opts.wrong_pin {
loop {
let p = Pin::generate(&mut ctx.rng).map_err(|e| e.to_string())?;
if p != shown {
break p;
}
}
} else {
shown
};
// The PIN goes to the operator's terminal only, never to the log.
let digits = String::from_utf8_lossy(shown.as_bytes()).into_owned();
println!();
println!(" PIN for the operator: {digits}");
println!(" Submit it through Sunshine's API now (docs/LIVE-INTEROP.md, step P). Waiting up to 120 s.");
if ctx.opts.wrong_pin {
println!(" (--wrong-pin: the probe itself uses another PIN; pairing is expected to fail, U28)");
}
println!();
ctx.log.note(
"pair",
&["U1", "U2", "U28"],
format!(
"PIN generated and shown to the operator (not logged); wrong_pin={}; device name '{}'; client cert sha256 {}",
ctx.opts.wrong_pin,
ctx.opts.name,
sha256_hex(ctx.id.client.cert_der())
),
);
let name = ctx.opts.name.clone();
let (mut session, mut req) = PairingSession::start(&ctx.id.client, &ctx.id.unique_id, &name, used, &mut ctx.rng)
.map_err(|e| format!("pairing start: {e}"))?;
let mut host_cert: Option<ServerCert> = None;
let mut n = 1;
loop {
let before = session.state();
let step = format!("pair.{n}");
let us: &[&str] = if n == 1 { &["U1", "U2", "U24"] } else { &["U1", "U2", "U28"] };
let x = match ctx.http(&step, us, &req, host_cert.as_ref()) {
Ok(x) => x,
Err(e) => {
println!("pairing stopped at step {n} ({before:?}): {e}");
return Err(e);
}
};
if before == PairingState::AwaitServerCert
&& let Ok(a) = parse_pair_response(&x.response.body)
&& let Some(pem) = a.plain_cert
{
match ServerCert::from_pem(&pem) {
Ok(c) => {
ctx.log.note(&step, &["U2"], format!("host certificate sha256 {}", sha256_hex(c.der())));
host_cert = Some(c);
}
Err(e) => ctx.log.parse_error(&step, &["U2"], &e, crate::log::text(&pem)),
}
}
let status = x.response.status;
match session.handle_response(&ctx.id.client, status, &x.response.body, &mut ctx.rng) {
Ok(PairingStep::Send(next)) => {
req = next;
n += 1;
}
Ok(PairingStep::Paired(p)) => {
state::save_host_cert(&ctx.out, &p.server_cert, ctx.host)?;
ctx.log.record(
"pair.done",
Kind::Summary,
&["U1", "U2"],
J::O(vec![("steps", J::U(n)), ("host_cert_sha256", J::s(sha256_hex(p.server_cert.der())))]),
);
ctx.host_cert = Some(p.server_cert);
println!(
"paired after {n} steps; host certificate pinned in {}",
state::identity_dir(&ctx.out).display()
);
// Evidence that the host now treats this certificate as paired.
return server_info(ctx, Scheme::Https);
}
Err(e) => {
let failed = session.state();
ctx.log.parse_error(&step, &["U1", "U28"], &e, body_j(&x.response.body));
ctx.log.stop(
&step,
&["U1", "U2", "U28"],
format!("pairing failed at step {n} ({before:?} -> {failed:?}): {e}"),
J::O(vec![("wrong_pin", J::Bool(ctx.opts.wrong_pin))]),
);
println!("pairing failed at step {n}: {failed:?} ({e})");
return Err(format!("pairing failed: {e}"));
}
}
}
}
pub fn apps(ctx: &mut Ctx) -> Result<(), String> {
let req = app_list_request(&ctx.id.unique_id).map_err(|e| e.to_string())?;
let x = ctx.http("apps", &["U24", "U27"], &req, None)?;
check_status(ctx, "apps", &x)?;
match parse_app_list(&x.response.body) {
Ok(apps) => {
ctx.log.record("apps", Kind::Note, &[], J::dbg(&apps));
println!("{} apps:", apps.len());
for a in &apps {
println!(" {:>12} hdr={} {}", a.id, u8::from(a.hdr_supported), a.title);
}
Ok(())
}
Err(e) => {
ctx.log.parse_error("apps", &["U27"], &e, body_j(&x.response.body));
ctx.log.stop("apps", &[], format!("applist refused: {e}"), J::Null);
Err(format!("applist refused: {e}"))
}
}
}
fn status_call(ctx: &mut Ctx, step: &str, req: domistream::http::HttpRequest) -> Result<(), String> {
let x = ctx.http(step, &["U27"], &req, None)?;
check_status(ctx, step, &x)?;
match parse_status_response(&x.response.body) {
Ok(()) => {
println!("{step}: done");
Ok(())
}
Err(e) => {
ctx.log.parse_error(step, &["U27"], &e, body_j(&x.response.body));
ctx.log.stop(step, &["U27"], format!("{step} refused: {e}"), J::Null);
Err(format!("{step} refused: {e}"))
}
}
}
pub fn quit(ctx: &mut Ctx) -> Result<(), String> {
let req = cancel_request(&ctx.id.unique_id).map_err(|e| e.to_string())?;
status_call(ctx, "quit", req)
}
pub fn unpair(ctx: &mut Ctx) -> Result<(), String> {
let req = unpair_request(&ctx.id.unique_id).map_err(|e| e.to_string())?;
status_call(ctx, "unpair", req)?;
state::forget_host_cert(&ctx.out)?;
ctx.host_cert = None;
Ok(())
}
+97
View File
@@ -0,0 +1,97 @@
//! Packet dumps for offline analysis after the sitting (U14 video parity, U16 audio parity matrix): a magic, then
//! one record per datagram: `t_us u64 LE`, `len u16 LE`, the bytes.
use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::path::Path;
pub const MAGIC: &[u8; 8] = b"GSPROBE1";
/// Largest dump file read back.
pub const MAX_DUMP_BYTES: usize = 512 * 1024 * 1024;
pub fn encode_record(t_us: u64, bytes: &[u8]) -> Vec<u8> {
let len = u16::try_from(bytes.len()).unwrap_or(u16::MAX);
let shown = bytes.get(..usize::from(len)).unwrap_or(bytes);
let mut r = Vec::with_capacity(10 + shown.len());
r.extend_from_slice(&t_us.to_le_bytes());
r.extend_from_slice(&len.to_le_bytes());
r.extend_from_slice(shown);
r
}
/// Every record of a dump file's contents.
pub fn decode(data: &[u8]) -> Result<Vec<(u64, Vec<u8>)>, String> {
if data.len() > MAX_DUMP_BYTES {
return Err(format!("dump over {MAX_DUMP_BYTES} bytes"));
}
let mut rest = data.strip_prefix(MAGIC.as_slice()).ok_or("not a gs-probe dump (magic)")?;
let mut out = Vec::new();
while !rest.is_empty() {
let head = rest.get(..10).ok_or("record header cut")?;
let mut t = [0u8; 8];
t.copy_from_slice(&head[..8]);
let len = usize::from(u16::from_le_bytes([head[8], head[9]]));
let body = rest.get(10..10 + len).ok_or("record body cut")?;
out.push((u64::from_le_bytes(t), body.to_vec()));
rest = &rest[10 + len..];
}
Ok(out)
}
/// Writes up to `limit` records.
pub struct PacketDump {
w: Option<BufWriter<File>>,
pub written: u32,
limit: u32,
}
impl PacketDump {
pub fn create(path: &Path, limit: u32) -> io::Result<Self> {
if limit == 0 {
return Ok(Self { w: None, written: 0, limit });
}
let mut w = BufWriter::new(File::options().write(true).create_new(true).open(path)?);
w.write_all(MAGIC)?;
Ok(Self { w: Some(w), written: 0, limit })
}
pub fn push(&mut self, t_us: u64, bytes: &[u8]) -> io::Result<()> {
if self.written >= self.limit {
return Ok(());
}
if let Some(w) = &mut self.w {
w.write_all(&encode_record(t_us, bytes))?;
self.written += 1;
}
Ok(())
}
pub fn finish(&mut self) -> io::Result<()> {
if let Some(w) = &mut self.w {
w.flush()?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn records_round_trip() {
let mut file = MAGIC.to_vec();
file.extend(encode_record(7, b"abc"));
file.extend(encode_record(u64::MAX, b""));
assert_eq!(decode(&file).unwrap(), vec![(7, b"abc".to_vec()), (u64::MAX, vec![])]);
}
#[test]
fn cut_or_foreign_files_are_refused() {
assert!(decode(b"NOTADUMP").is_err());
let mut file = MAGIC.to_vec();
file.extend(encode_record(1, b"abcd"));
assert!(decode(&file[..file.len() - 1]).unwrap_err().contains("body cut"));
assert!(decode(&file[..MAGIC.len() + 5]).unwrap_err().contains("header cut"));
}
}
+390
View File
@@ -0,0 +1,390 @@
//! Two FEC measurements the sitting settles from real traffic, with our own arithmetic:
//!
//! - **U14** (video, live): for each complete block, DomiStream's Cauchy encoder must reproduce the parity packets
//! the host sent (offset 32 on). Two readings are checked: parity over whole data packets (PROTOCOL.md 5.3) and
//! over data packets with their 32 header bytes zeroed.
//! - **U16** (audio, offline from `audio-packets.bin`): each parity byte is a linear combination over GF(2^8)
//! (polynomial `0x11D`) of the four data bytes at the same offset, so a few offsets give the 2 × 4 matrix; every
//! other byte of every block then checks it.
use std::collections::BTreeMap;
use domistream::audio::{AudioPacket, parse_audio_packet};
use domistream::fec::{ReedSolomon, parity_count};
/// GF(2^8) with polynomial `0x11D`, generator 2.
pub struct Gf {
exp: [u8; 512],
log: [u8; 256],
}
impl Gf {
pub fn new() -> Self {
let (mut exp, mut log) = ([0u8; 512], [0u8; 256]);
let mut x: u16 = 1;
for (i, e) in exp.iter_mut().take(255).enumerate() {
*e = x as u8;
log[usize::from(x)] = i as u8;
x <<= 1;
if x & 0x100 != 0 {
x ^= 0x11D;
}
}
// exp[i + 255] = exp[i], so a product's log sum (at most 508) needs no reduction.
exp.copy_within(0..255, 255);
Self { exp, log }
}
pub fn mul(&self, a: u8, b: u8) -> u8 {
if a == 0 || b == 0 {
0
} else {
self.exp[usize::from(self.log[usize::from(a)]) + usize::from(self.log[usize::from(b)])]
}
}
/// `1 / a`; `a` must not be 0.
pub fn inv(&self, a: u8) -> u8 {
self.exp[255 - usize::from(self.log[usize::from(a)])]
}
}
/// What the audio solver found for one parity row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RowResult {
/// The four coefficients, and how many byte equations agreed and disagreed with them.
Solved { coefficients: [u8; 4], equations: u64, mismatches: u64 },
/// Not enough independent equations (rank below 4).
Underdetermined { rank: usize, equations: u64 },
}
/// The audio parity matrix from captured blocks.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AudioFecReport {
pub data_packets: u64,
pub parity_packets: u64,
pub unparsed: u64,
pub blocks: usize,
/// Blocks with all 4 data packets and parity row 0 / row 1, all of one length.
pub complete: [usize; 2],
pub rows: [RowResult; 2],
}
impl AudioFecReport {
/// The 2 × 4 matrix, row-major, when both rows solved without a single mismatch.
pub fn matrix(&self) -> Option<[u8; 8]> {
match (&self.rows[0], &self.rows[1]) {
(
RowResult::Solved { coefficients: a, mismatches: 0, .. },
RowResult::Solved { coefficients: b, mismatches: 0, .. },
) => Some([a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]]),
_ => None,
}
}
/// Whether DomiStream accepts the solved matrix as an MDS code (`AudioFec::ParityMatrix`).
pub fn matrix_is_mds(&self) -> Option<bool> {
self.matrix().map(|m| ReedSolomon::with_parity_matrix(4, 2, &m).is_ok())
}
}
#[derive(Default)]
struct AudioBlock {
data: [Option<Vec<u8>>; 4],
parity: [Option<Vec<u8>>; 2],
}
/// Solves U16 from raw audio datagrams (as received: encrypted payloads are the shards).
pub fn solve_audio(datagrams: &[Vec<u8>]) -> AudioFecReport {
let gf = Gf::new();
let mut blocks: BTreeMap<u16, AudioBlock> = BTreeMap::new();
let (mut data_packets, mut parity_packets, mut unparsed) = (0, 0, 0);
for d in datagrams {
match parse_audio_packet(d) {
Ok(AudioPacket::Data { rtp, payload }) => {
data_packets += 1;
let b = blocks.entry(rtp.sequence & !3).or_default();
b.data[usize::from(rtp.sequence & 3)] = Some(payload.to_vec());
}
Ok(AudioPacket::Parity { fec, parity, .. }) => {
parity_packets += 1;
let b = blocks.entry(fec.base_sequence).or_default();
b.parity[usize::from(fec.shard_index & 1)] = Some(parity.to_vec());
}
Err(_) => unparsed += 1,
}
}
let mut complete = [0usize; 2];
let rows = [0usize, 1].map(|row| {
let mut basis: Vec<(usize, [u8; 5])> = Vec::new();
let mut equations: Vec<[u8; 5]> = Vec::new();
for b in blocks.values() {
let (Some(d0), Some(d1), Some(d2), Some(d3), Some(p)) =
(&b.data[0], &b.data[1], &b.data[2], &b.data[3], &b.parity[row])
else {
continue;
};
let len = p.len();
if [d0, d1, d2, d3].iter().any(|d| d.len() != len) {
continue;
}
complete[row] += 1;
for o in 0..len {
let eq = [d0[o], d1[o], d2[o], d3[o], p[o]];
equations.push(eq);
if basis.len() < 4 {
add_to_basis(&gf, &mut basis, eq);
}
}
}
let count = equations.len() as u64;
if basis.len() < 4 {
return RowResult::Underdetermined { rank: basis.len(), equations: count };
}
let mut c = [0u8; 4];
for (pc, r) in &basis {
c[*pc] = r[4];
}
let mismatches =
equations.iter().filter(|e| (0..4).fold(0u8, |acc, i| acc ^ gf.mul(c[i], e[i])) != e[4]).count() as u64;
RowResult::Solved { coefficients: c, equations: count, mismatches }
});
AudioFecReport { data_packets, parity_packets, unparsed, blocks: blocks.len(), complete, rows }
}
/// Adds one augmented equation to a reduced row-echelon basis (pivot 1, zero in other rows' pivot columns).
fn add_to_basis(gf: &Gf, basis: &mut Vec<(usize, [u8; 5])>, mut row: [u8; 5]) {
for (pc, b) in basis.iter() {
let f = row[*pc];
if f != 0 {
for i in 0..5 {
row[i] ^= gf.mul(f, b[i]);
}
}
}
let Some(pc) = (0..4).find(|&i| row[i] != 0) else { return };
let inv = gf.inv(row[pc]);
for v in &mut row {
*v = gf.mul(*v, inv);
}
for (_, b) in basis.iter_mut() {
let f = b[pc];
if f != 0 {
for i in 0..5 {
b[i] ^= gf.mul(f, row[i]);
}
}
}
basis.push((pc, row));
}
/// How a complete video block compared with our encoder.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum VideoOutcome {
/// Parity over whole data packets (PROTOCOL.md 5.3) matches.
Whole,
/// Only parity over data packets with zeroed 32-byte headers matches.
PayloadOnly,
/// Neither reading matches.
Neither,
/// Not comparable (shards of different lengths, or a code DomiStream refuses).
Skipped,
}
struct VideoBlock {
k: u16,
m: usize,
shards: BTreeMap<u16, Vec<u8>>,
}
/// The live U14 check: collects each block's packets (plaintext) and compares the parity once it is complete.
pub struct VideoFecCheck {
pending: BTreeMap<(u32, u8), VideoBlock>,
limit: u64,
pub checked: u64,
pub whole: u64,
pub payload_only: u64,
pub neither: u64,
pub skipped: u64,
}
/// Blocks kept open at once; the oldest is dropped beyond this (a lost packet means it never completes).
const MAX_PENDING_BLOCKS: usize = 64;
impl VideoFecCheck {
/// Checks at most `limit` blocks.
pub fn new(limit: u64) -> Self {
Self { pending: BTreeMap::new(), limit, checked: 0, whole: 0, payload_only: 0, neither: 0, skipped: 0 }
}
/// One plaintext packet of block `block` of frame `frame`: shard `shard` of `k` data shards at `pct` percent.
pub fn push(&mut self, frame: u32, block: u8, shard: u16, k: u16, pct: u8, packet: &[u8]) -> Option<VideoOutcome> {
if self.checked >= self.limit {
return None;
}
let m = parity_count(usize::from(k), pct).ok()?;
if m == 0 {
return None;
}
let entry = self.pending.entry((frame, block)).or_insert_with(|| VideoBlock { k, m, shards: BTreeMap::new() });
if entry.k != k || entry.m != m {
return None;
}
entry.shards.insert(shard, packet.to_vec());
if entry.shards.len() < usize::from(k) + m {
while self.pending.len() > MAX_PENDING_BLOCKS {
self.pending.pop_first();
}
return None;
}
let b = self.pending.remove(&(frame, block))?;
self.checked += 1;
let outcome = compare(&b);
match outcome {
VideoOutcome::Whole => self.whole += 1,
VideoOutcome::PayloadOnly => self.payload_only += 1,
VideoOutcome::Neither => self.neither += 1,
VideoOutcome::Skipped => self.skipped += 1,
}
Some(outcome)
}
}
fn compare(b: &VideoBlock) -> VideoOutcome {
let k = usize::from(b.k);
let shards: Vec<&Vec<u8>> = b.shards.values().collect();
let len = shards.first().map_or(0, |s| s.len());
if len <= 32 || shards.iter().any(|s| s.len() != len) {
return VideoOutcome::Skipped;
}
let Ok(rs) = ReedSolomon::new(k, b.m) else { return VideoOutcome::Skipped };
let parity_matches = |zero_headers: bool| -> Option<bool> {
let mut work: Vec<Vec<u8>> = Vec::with_capacity(k + b.m);
for s in shards.iter().take(k) {
let mut d = (*s).clone();
if zero_headers {
d.iter_mut().take(32).for_each(|x| *x = 0);
}
work.push(d);
}
work.extend((0..b.m).map(|_| vec![0u8; len]));
rs.encode(&mut work).ok()?;
Some(work.iter().skip(k).zip(shards.iter().skip(k)).all(|(ours, theirs)| ours.get(32..) == theirs.get(32..)))
};
match (parity_matches(false), parity_matches(true)) {
(Some(true), _) => VideoOutcome::Whole,
(_, Some(true)) => VideoOutcome::PayloadOnly,
(Some(false), _) | (_, Some(false)) => VideoOutcome::Neither,
_ => VideoOutcome::Skipped,
}
}
#[cfg(test)]
mod tests {
use super::*;
fn rtp(pt: u8, seq: u16, payload: &[u8]) -> Vec<u8> {
let mut p = vec![0x80, pt];
p.extend_from_slice(&seq.to_be_bytes());
p.extend_from_slice(&[0, 0, 0, 0, 0, 0, 0, 0]);
p.extend_from_slice(payload);
p
}
fn parity_packet(seq: u16, shard: u8, base: u16, parity: &[u8]) -> Vec<u8> {
let mut fec = vec![shard, 97];
fec.extend_from_slice(&base.to_be_bytes());
fec.extend_from_slice(&[0; 8]);
fec.extend_from_slice(parity);
rtp(127, seq, &fec)
}
/// Blocks made with a known matrix; the solver must find it and every byte must agree.
#[test]
fn audio_matrix_is_recovered() {
let gf = Gf::new();
let m = [0x77, 0x40, 0x38, 0x0e, 0xc7, 0xa7, 0x0d, 0x6c];
let mut datagrams = Vec::new();
let mut x: u32 = 12345;
for block in 0..6u16 {
let base = block * 4;
let data: Vec<Vec<u8>> = (0..4)
.map(|_| {
(0..32)
.map(|_| {
x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
(x >> 16) as u8
})
.collect()
})
.collect();
for (i, d) in data.iter().enumerate() {
datagrams.push(rtp(97, base + i as u16, d));
}
for row in 0..2 {
let p: Vec<u8> =
(0..32).map(|o| (0..4).fold(0u8, |acc, i| acc ^ gf.mul(m[row * 4 + i], data[i][o]))).collect();
datagrams.push(parity_packet(1000 + block * 2 + row as u16, row as u8, base, &p));
}
}
datagrams.push(vec![0x00, 0x01]);
let r = solve_audio(&datagrams);
assert_eq!((r.data_packets, r.parity_packets, r.unparsed, r.blocks, r.complete), (24, 12, 1, 6, [6, 6]));
assert_eq!(r.matrix(), Some(m), "{r:?}");
}
#[test]
fn too_little_audio_is_underdetermined() {
let r = solve_audio(&[rtp(97, 0, &[1, 2]), rtp(97, 1, &[3, 4])]);
assert!(matches!(r.rows[0], RowResult::Underdetermined { rank: 0, equations: 0 }));
assert_eq!(r.matrix(), None);
}
#[test]
fn gf_inverse() {
let gf = Gf::new();
for a in 1..=255u8 {
assert_eq!(gf.mul(a, gf.inv(a)), 1);
}
// 2 * 0x80 wraps through the polynomial.
assert_eq!(gf.mul(2, 0x80), 0x1D);
}
fn packet(shard: u16, fill: u8, len: usize) -> Vec<u8> {
let mut p = vec![fill; len];
p[0] = 0x90;
p[2..4].copy_from_slice(&shard.to_be_bytes());
p
}
#[test]
fn video_parity_from_our_encoder_matches_whole_packets() {
let (k, m, len) = (4usize, 2usize, 64usize);
let rs = ReedSolomon::new(k, m).unwrap();
let mut shards: Vec<Vec<u8>> = (0..k).map(|i| packet(i as u16, 0x10 + i as u8, len)).collect();
shards.extend((0..m).map(|_| vec![0u8; len]));
rs.encode(&mut shards).unwrap();
// The host overwrites parity bytes 0-31 with headers after computing the parity.
for s in shards.iter_mut().skip(k) {
s[..32].fill(0xEE);
}
let mut check = VideoFecCheck::new(10);
let mut last = None;
for (i, s) in shards.iter().enumerate() {
last = check.push(9, 0, i as u16, k as u16, 50, s);
}
assert_eq!(last, Some(VideoOutcome::Whole));
assert_eq!((check.checked, check.whole), (1, 1));
}
#[test]
fn foreign_video_parity_is_reported() {
let mut check = VideoFecCheck::new(10);
let mut last = None;
for i in 0..6u16 {
last = check.push(1, 0, i, 4, 50, &packet(i, 0x33 + i as u8, 64));
}
assert_eq!(last, Some(VideoOutcome::Neither));
assert_eq!(check.neither, 1);
}
}
+325
View File
@@ -0,0 +1,325 @@
//! A minimal HTTP/1.1 `GET` client for the host's HTTP and HTTPS ports: one request per connection
//! (`Connection: close`), size caps, a deadline, and a strict response parser (`Content-Length`, chunked, or the
//! connection close).
use std::io::{self, Read, Write};
use std::net::{SocketAddr, TcpStream};
use std::sync::Arc;
use std::time::{Duration, Instant};
use rustls::pki_types::ServerName;
use rustls::{ClientConfig, ClientConnection, StreamOwned};
/// Largest response accepted, headers included.
pub const MAX_RESPONSE_BYTES: usize = 2 * 1024 * 1024;
/// Largest header section.
pub const MAX_HEAD_BYTES: usize = 16 * 1024;
/// Most header lines.
pub const MAX_HEADERS: usize = 64;
/// How long a TCP connect may take.
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
/// Read poll interval (the deadline is checked between reads).
const POLL: Duration = Duration::from_millis(250);
/// How the body's end was found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Framing {
Length,
Chunked,
Close,
}
/// A parsed response.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Response {
pub status: u16,
pub reason: String,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
pub framing: Framing,
}
impl Response {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
}
/// The request bytes. `host` is the `Host` header value (`ip:port`).
pub fn request(path_and_query: &str, host: &str) -> Vec<u8> {
format!(
"GET {path_and_query} HTTP/1.1\r\nHost: {host}\r\nUser-Agent: gs-probe/0.1\r\nAccept: */*\r\nConnection: close\r\n\r\n"
)
.into_bytes()
}
/// Parses what has arrived so far. `Ok(None)`: not complete yet (and the connection is still open).
pub fn parse(raw: &[u8], eof: bool) -> Result<Option<Response>, String> {
if raw.len() > MAX_RESPONSE_BYTES {
return Err(format!("response over {MAX_RESPONSE_BYTES} bytes"));
}
let Some(end) = raw.windows(4).position(|w| w == b"\r\n\r\n") else {
if raw.len() > MAX_HEAD_BYTES {
return Err(format!("headers over {MAX_HEAD_BYTES} bytes"));
}
return if eof { Err("connection closed inside the headers".into()) } else { Ok(None) };
};
if end > MAX_HEAD_BYTES {
return Err(format!("headers over {MAX_HEAD_BYTES} bytes"));
}
let head = std::str::from_utf8(raw.get(..end).unwrap_or(&[])).map_err(|_| "headers are not UTF-8".to_owned())?;
let mut lines = head.split("\r\n");
let status_line = lines.next().unwrap_or("");
let mut parts = status_line.splitn(3, ' ');
let (version, code, reason) = (parts.next().unwrap_or(""), parts.next().unwrap_or(""), parts.next().unwrap_or(""));
if !matches!(version, "HTTP/1.1" | "HTTP/1.0") || code.len() != 3 || !code.bytes().all(|b| b.is_ascii_digit()) {
return Err(format!("bad status line '{status_line}'"));
}
let status: u16 = code.parse().map_err(|_| format!("bad status line '{status_line}'"))?;
let mut headers = Vec::new();
for l in lines {
let (n, v) = l.split_once(':').ok_or_else(|| format!("bad header line '{l}'"))?;
if n.is_empty() || n.bytes().any(|b| !b.is_ascii_graphic()) {
return Err(format!("bad header name '{n}'"));
}
headers.push((n.to_owned(), v.trim().to_owned()));
if headers.len() > MAX_HEADERS {
return Err(format!("more than {MAX_HEADERS} headers"));
}
}
let rest = raw.get(end + 4..).unwrap_or(&[]);
let mut r = Response { status, reason: reason.to_owned(), headers, body: Vec::new(), framing: Framing::Close };
let chunked = r.header("Transfer-Encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked"));
if chunked {
r.framing = Framing::Chunked;
return match dechunk(rest)? {
Some(body) => {
r.body = body;
Ok(Some(r))
}
None if eof => Err("connection closed inside a chunked body".into()),
None => Ok(None),
};
}
if let Some(v) = r.header("Content-Length") {
let len: usize = v.parse().map_err(|_| format!("bad Content-Length '{v}'"))?;
if len > MAX_RESPONSE_BYTES {
return Err(format!("Content-Length {len} over the cap"));
}
r.framing = Framing::Length;
return match rest.get(..len) {
Some(body) => {
r.body = body.to_vec();
Ok(Some(r))
}
None if eof => Err(format!("connection closed after {} of {len} body bytes", rest.len())),
None => Ok(None),
};
}
if eof {
r.body = rest.to_vec();
Ok(Some(r))
} else {
Ok(None)
}
}
/// The body of a chunked message, or `None` while the last chunk has not arrived.
fn dechunk(mut data: &[u8]) -> Result<Option<Vec<u8>>, String> {
let mut body = Vec::new();
loop {
let Some(nl) = data.windows(2).position(|w| w == b"\r\n") else { return Ok(None) };
let line = std::str::from_utf8(data.get(..nl).unwrap_or(&[])).map_err(|_| "bad chunk size".to_owned())?;
let size_hex = line.split(';').next().unwrap_or("").trim();
if size_hex.is_empty() || size_hex.len() > 8 {
return Err(format!("bad chunk size '{line}'"));
}
let size = usize::from_str_radix(size_hex, 16).map_err(|_| format!("bad chunk size '{line}'"))?;
if body.len() + size > MAX_RESPONSE_BYTES {
return Err("chunked body over the cap".into());
}
let after = data.get(nl + 2..).unwrap_or(&[]);
if size == 0 {
return Ok(Some(body));
}
let Some(chunk) = after.get(..size) else { return Ok(None) };
match after.get(size..size + 2) {
None => return Ok(None),
Some(b"\r\n") => {}
Some(_) => return Err("chunk not followed by CRLF".into()),
}
body.extend_from_slice(chunk);
data = after.get(size + 2..).unwrap_or(&[]);
}
}
/// Reads until [`parse`] has a whole response, the peer closes, or `deadline` passes.
pub fn read_response<R: Read>(r: &mut R, deadline: Instant) -> Result<Response, String> {
let mut raw = Vec::new();
let mut buf = [0u8; 16 * 1024];
loop {
match r.read(&mut buf) {
Ok(0) => return parse(&raw, true)?.ok_or_else(|| "connection closed without an answer".into()),
Ok(n) => {
raw.extend_from_slice(buf.get(..n).unwrap_or(&[]));
if let Some(resp) = parse(&raw, false)? {
return Ok(resp);
}
}
// rustls reports a close without close_notify as UnexpectedEof: the body may still be complete.
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
return parse(&raw, true)?.ok_or_else(|| "connection closed without an answer".into());
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(format!("read failed: {e}")),
}
if Instant::now() >= deadline {
return Err(format!("no complete answer before the deadline ({} bytes so far)", raw.len()));
}
}
}
/// TLS facts of an HTTPS exchange (U24).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TlsInfo {
pub version: String,
pub suite: String,
}
/// One finished request.
#[derive(Clone, Debug)]
pub struct Exchange {
pub response: Response,
pub elapsed: Duration,
pub tls: Option<TlsInfo>,
}
fn connect(addr: SocketAddr) -> Result<TcpStream, String> {
let s = TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).map_err(|e| format!("connect to {addr} failed: {e}"))?;
s.set_read_timeout(Some(POLL)).map_err(|e| format!("socket setup failed: {e}"))?;
s.set_write_timeout(Some(CONNECT_TIMEOUT)).map_err(|e| format!("socket setup failed: {e}"))?;
s.set_nodelay(true).map_err(|e| format!("socket setup failed: {e}"))?;
Ok(s)
}
/// `GET path` to `addr`, plain or over TLS with `tls`, answered within `timeout`.
pub fn get(
addr: SocketAddr,
path_and_query: &str,
timeout: Duration,
tls: Option<Arc<ClientConfig>>,
) -> Result<Exchange, String> {
let started = Instant::now();
let deadline = started + timeout;
let mut tcp = connect(addr)?;
let req = request(path_and_query, &addr.to_string());
match tls {
None => {
tcp.write_all(&req).map_err(|e| format!("write failed: {e}"))?;
let response = read_response(&mut tcp, deadline)?;
Ok(Exchange { response, elapsed: started.elapsed(), tls: None })
}
Some(cfg) => {
let name = ServerName::IpAddress(addr.ip().into());
let mut conn = ClientConnection::new(cfg, name).map_err(|e| format!("TLS setup failed: {e}"))?;
while conn.is_handshaking() {
match conn.complete_io(&mut tcp) {
Ok(_) => {}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
if Instant::now() >= deadline {
return Err("TLS handshake timed out".into());
}
}
Err(e) => return Err(format!("TLS handshake failed: {e}")),
}
}
let info = TlsInfo {
version: conn.protocol_version().map_or_else(|| "?".into(), |v| format!("{v:?}")),
suite: conn.negotiated_cipher_suite().map_or_else(|| "?".into(), |s| format!("{:?}", s.suite())),
};
let mut stream = StreamOwned::new(conn, tcp);
stream.write_all(&req).map_err(|e| format!("write failed: {e}"))?;
stream.flush().map_err(|e| format!("write failed: {e}"))?;
let response = read_response(&mut stream, deadline)?;
Ok(Exchange { response, elapsed: started.elapsed(), tls: Some(info) })
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::net::TcpListener;
#[test]
fn content_length_body() {
let raw = b"HTTP/1.1 200 OK\r\nContent-Type: text/xml\r\nContent-Length: 5\r\n\r\nhelloEXTRA";
let r = parse(raw, false).unwrap().unwrap();
assert_eq!((r.status, r.reason.as_str(), r.framing), (200, "OK", Framing::Length));
assert_eq!(r.body, b"hello");
assert_eq!(r.header("content-type"), Some("text/xml"));
// Cut after "hell": 4 of the 5 body bytes.
let cut = &raw[..raw.len() - 6];
assert_eq!(parse(cut, false).unwrap(), None);
assert!(parse(cut, true).unwrap_err().contains("4 of 5"));
}
#[test]
fn chunked_body() {
let raw = b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n4\r\n<roo\r\n3;x=y\r\nt/>\r\n0\r\n\r\n";
let r = parse(raw, false).unwrap().unwrap();
assert_eq!((r.body.as_slice(), r.framing), (&b"<root/>"[..], Framing::Chunked));
assert_eq!(parse(&raw[..raw.len() - 5], false).unwrap(), None);
assert!(parse(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\nzz\r\n", false).is_err());
assert!(parse(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n2\r\nabXX", false).is_err());
}
#[test]
fn close_delimited_body() {
let raw = b"HTTP/1.0 404 Not Found\r\n\r\n<root status_code=\"404\"/>";
assert_eq!(parse(raw, false).unwrap(), None);
let r = parse(raw, true).unwrap().unwrap();
assert_eq!((r.status, r.framing), (404, Framing::Close));
assert_eq!(r.body, b"<root status_code=\"404\"/>");
}
#[test]
fn hostile_answers_are_refused() {
assert!(parse(b"HTTP/2 200 OK\r\n\r\n", true).unwrap_err().contains("status line"));
assert!(parse(b"HTTP/1.1 20x OK\r\n\r\n", true).unwrap_err().contains("status line"));
assert!(parse(b"HTTP/1.1 200 OK\r\nno colon\r\n\r\n", true).unwrap_err().contains("header line"));
assert!(parse(b"HTTP/1.1 200 OK\r\nContent-Length: -1\r\n\r\n", true).unwrap_err().contains("Content-Length"));
assert!(parse(b"HTTP/1.1 200 OK\r\nContent-Length: 99999999\r\n\r\n", true).unwrap_err().contains("cap"));
assert!(parse(&vec![b'a'; MAX_HEAD_BYTES + 1], false).unwrap_err().contains("headers over"));
assert!(parse(b"HTTP/1.1 200", true).unwrap_err().contains("inside the headers"));
let many: String = (0..=MAX_HEADERS).map(|i| format!("X-{i}: 1\r\n")).collect();
assert!(parse(format!("HTTP/1.1 200 OK\r\n{many}\r\n").as_bytes(), true).unwrap_err().contains("headers"));
}
#[test]
fn request_line_and_headers() {
let r = String::from_utf8(request("/serverinfo?uniqueid=AB", "192.0.2.1:47989")).unwrap();
assert!(r.starts_with("GET /serverinfo?uniqueid=AB HTTP/1.1\r\nHost: 192.0.2.1:47989\r\n"));
assert!(r.ends_with("Connection: close\r\n\r\n"));
}
/// The only socket the tests open: a loopback listener on an ephemeral port.
#[test]
fn get_over_loopback() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let server = std::thread::spawn(move || {
let (mut s, _) = listener.accept().unwrap();
let mut buf = [0u8; 1024];
let n = s.read(&mut buf).unwrap();
let req = String::from_utf8_lossy(&buf[..n]).into_owned();
s.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\n<root/>").unwrap();
req
});
let x = get(addr, "/serverinfo?uniqueid=AB", Duration::from_secs(5), None).unwrap();
assert_eq!((x.response.status, x.response.body.as_slice()), (200, &b"<root/>"[..]));
assert!(x.tls.is_none());
assert!(server.join().unwrap().starts_with("GET /serverinfo?uniqueid=AB HTTP/1.1\r\n"));
}
}
+367
View File
@@ -0,0 +1,367 @@
//! The structured log: one JSON object per line (`log.jsonl` in the run folder), flushed after every record so a
//! crash keeps everything before it.
//!
//! ```text
//! {"n":7,"t_ms":812.441,"step":"rtsp.describe","kind":"recv","u":["U5","U26"],"data":{…}}
//! ```
//!
//! `kind` is one of `send`, `recv`, `note`, `parse_error`, `stop`, `summary`. A `stop` record is the
//! stop-and-report rule of docs/LIVE-INTEROP.md: something unexpected happened, the probe ends the step and the
//! operator reports before changing anything.
//!
//! Secrets: HTTP paths and bodies are redacted by the callers (`crate::redact`), and every line is scanned once more
//! for the hex of each registered secret (the session's `rikey`) before it is written. The PIN is never passed to
//! the log at all.
use std::fs::File;
use std::io::{self, BufWriter, Write};
use std::path::{Path, PathBuf};
use std::time::Instant;
use crate::redact::MARK;
/// Bytes shown per byte field; the rest is cut and marked `truncated`.
pub const MAX_LOGGED_BYTES: usize = 4096;
/// Characters shown per text field.
pub const MAX_LOGGED_TEXT: usize = 64 * 1024;
/// A JSON value, built by the probe and written by [`J::write`].
#[derive(Clone, Debug, PartialEq)]
pub enum J {
Null,
Bool(bool),
U(u64),
I(i64),
F(f64),
S(String),
A(Vec<J>),
O(Vec<(&'static str, J)>),
}
impl J {
pub fn s(v: impl Into<String>) -> Self {
Self::S(v.into())
}
/// A string via `Debug` (for DomiStream's own types, which never print key material).
pub fn dbg(v: &impl std::fmt::Debug) -> Self {
let mut s = format!("{v:?}");
cut(&mut s, MAX_LOGGED_TEXT);
Self::S(s)
}
pub fn write(&self, out: &mut String) {
match self {
Self::Null => out.push_str("null"),
Self::Bool(b) => out.push_str(if *b { "true" } else { "false" }),
Self::U(n) => out.push_str(&n.to_string()),
Self::I(n) => out.push_str(&n.to_string()),
Self::F(f) if f.is_finite() => out.push_str(&format!("{f:.3}")),
Self::F(_) => out.push_str("null"),
Self::S(s) => escape(s, out),
Self::A(items) => {
out.push('[');
for (i, v) in items.iter().enumerate() {
if i > 0 {
out.push(',');
}
v.write(out);
}
out.push(']');
}
Self::O(fields) => {
out.push('{');
for (i, (k, v)) in fields.iter().enumerate() {
if i > 0 {
out.push(',');
}
escape(k, out);
out.push(':');
v.write(out);
}
out.push('}');
}
}
}
}
fn cut(s: &mut String, max: usize) {
if s.len() > max {
let mut end = max;
while !s.is_char_boundary(end) {
end -= 1;
}
s.truncate(end);
s.push_str("…<cut>");
}
}
/// A JSON string literal.
pub fn escape(s: &str, out: &mut String) {
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
'\r' => out.push_str("\\r"),
'\t' => out.push_str("\\t"),
c if (c as u32) < 0x20 || c == '\u{7f}' => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
}
/// Lower-case hex.
pub fn hex(bytes: &[u8]) -> String {
const D: &[u8; 16] = b"0123456789abcdef";
let mut s = String::with_capacity(bytes.len() * 2);
for b in bytes {
s.push(char::from(D[usize::from(b >> 4)]));
s.push(char::from(D[usize::from(b & 0xF)]));
}
s
}
/// `{"len":n,"hex":"…"}`, the hex cut at [`MAX_LOGGED_BYTES`] bytes (`"truncated":true`).
pub fn bytes(b: &[u8]) -> J {
let shown = b.get(..MAX_LOGGED_BYTES).unwrap_or(b);
let mut f = vec![("len", J::U(b.len() as u64)), ("hex", J::S(hex(shown)))];
if shown.len() < b.len() {
f.push(("truncated", J::Bool(true)));
}
J::O(f)
}
/// `{"len":n,"text":"…"}` when `b` is UTF-8 text (tabs and line ends allowed), else [`bytes`].
pub fn text(b: &[u8]) -> J {
match std::str::from_utf8(b) {
Ok(s) if !s.chars().any(|c| c.is_control() && !matches!(c, '\r' | '\n' | '\t')) => {
let mut t = s.to_owned();
cut(&mut t, MAX_LOGGED_TEXT);
J::O(vec![("len", J::U(b.len() as u64)), ("text", J::S(t))])
}
_ => bytes(b),
}
}
/// What a record is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Kind {
Send,
Recv,
Note,
ParseError,
Stop,
Summary,
}
impl Kind {
pub const fn as_str(self) -> &'static str {
match self {
Self::Send => "send",
Self::Recv => "recv",
Self::Note => "note",
Self::ParseError => "parse_error",
Self::Stop => "stop",
Self::Summary => "summary",
}
}
}
/// One log line, without the trailing newline, with every registered secret's hex replaced by [`MARK`].
pub fn format_line(n: u64, t_ms: f64, step: &str, kind: Kind, us: &[&str], data: &J, secrets: &[String]) -> String {
let rec = J::O(vec![
("n", J::U(n)),
("t_ms", J::F(t_ms)),
("step", J::s(step)),
("kind", J::s(kind.as_str())),
("u", J::A(us.iter().map(|u| J::s(*u)).collect())),
("data", data.clone()),
]);
let mut line = String::new();
rec.write(&mut line);
for s in secrets {
if line.contains(s.as_str()) {
line = line.replace(s.as_str(), MARK);
}
}
line
}
/// The run's log file.
pub struct Log {
out: Option<BufWriter<File>>,
start: Instant,
n: u64,
secrets: Vec<String>,
pub path: PathBuf,
pub stops: u32,
pub parse_errors: u32,
}
impl Log {
/// Creates `path` (it must not exist yet).
pub fn create(path: &Path, start: Instant) -> io::Result<Self> {
let f = File::options().write(true).create_new(true).open(path)?;
Ok(Self {
out: Some(BufWriter::new(f)),
start,
n: 0,
secrets: Vec::new(),
path: path.to_owned(),
stops: 0,
parse_errors: 0,
})
}
/// A log that writes nothing (tests of code that logs).
#[cfg(test)]
pub fn discard() -> Self {
Self {
out: None,
start: Instant::now(),
n: 0,
secrets: Vec::new(),
path: PathBuf::new(),
stops: 0,
parse_errors: 0,
}
}
/// From now on, the hex of `secret` (both cases) never reaches the file.
pub fn register_secret(&mut self, secret: &[u8]) {
let lower = hex(secret);
self.secrets.push(lower.to_ascii_uppercase());
self.secrets.push(lower);
}
/// Milliseconds since the run started.
pub fn t_ms(&self) -> f64 {
self.start.elapsed().as_secs_f64() * 1000.0
}
pub fn record(&mut self, step: &str, kind: Kind, us: &[&str], data: J) {
self.n += 1;
match kind {
Kind::Stop => self.stops += 1,
Kind::ParseError => self.parse_errors += 1,
_ => {}
}
let line = format_line(self.n, self.t_ms(), step, kind, us, &data, &self.secrets);
if let Some(out) = &mut self.out {
// A log that cannot be written is reported once on stderr; the probe goes on.
if writeln!(out, "{line}").and_then(|()| out.flush()).is_err() {
eprintln!("probe: cannot write the log {}", self.path.display());
self.out = None;
}
}
}
pub fn note(&mut self, step: &str, us: &[&str], text: impl Into<String>) {
self.record(step, Kind::Note, us, J::O(vec![("text", J::S(text.into()))]));
}
/// A parser refused something: the error and the bytes that caused it.
pub fn parse_error(&mut self, step: &str, us: &[&str], error: &dyn std::fmt::Display, input: J) {
self.record(step, Kind::ParseError, us, J::O(vec![("error", J::s(error.to_string())), ("input", input)]));
}
/// The stop-and-report rule: records why, and tells the operator on stderr.
pub fn stop(&mut self, step: &str, us: &[&str], reason: impl Into<String>, data: J) {
let reason = reason.into();
eprintln!("STOP AND REPORT [{step}]: {reason}");
eprintln!(" log: {}", self.path.display());
self.record(step, Kind::Stop, us, J::O(vec![("reason", J::S(reason)), ("data", data)]));
}
}
/// `YYYYMMDDTHHMMSSZ` for Unix seconds (UTC), for run folder names.
pub fn utc_stamp(unix_secs: u64) -> String {
let days = (unix_secs / 86_400) as i64;
let rem = unix_secs % 86_400;
// Civil date from days since 1970-01-01 (H. Hinnant's algorithm).
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let y = yoe + era * 400 + i64::from(m <= 2);
format!("{y:04}{m:02}{d:02}T{:02}{:02}{:02}Z", rem / 3600, rem % 3600 / 60, rem % 60)
}
#[cfg(test)]
mod tests {
use super::*;
fn line(data: J, secrets: &[String]) -> String {
format_line(3, 12.5, "pair.1", Kind::Send, &["U1", "U2"], &data, secrets)
}
#[test]
fn line_has_the_documented_fields_in_order() {
assert_eq!(
line(J::O(vec![("x", J::U(1))]), &[]),
r#"{"n":3,"t_ms":12.500,"step":"pair.1","kind":"send","u":["U1","U2"],"data":{"x":1}}"#
);
}
#[test]
fn strings_are_escaped() {
let mut s = String::new();
escape("a\"b\\c\nd\u{1}é", &mut s);
assert_eq!(s, r#""a\"b\\c\nd\u0001é""#);
let mut n = String::new();
J::A(vec![J::Null, J::Bool(false), J::I(-2), J::F(f64::NAN)]).write(&mut n);
assert_eq!(n, "[null,false,-2,null]");
}
#[test]
fn registered_secrets_never_reach_a_line() {
let key = [0x5Au8, 0x01, 0xFE, 0x33, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB];
let mut log = Log::discard();
log.register_secret(&key);
let lower = hex(&key);
let upper = lower.to_ascii_uppercase();
let data = J::O(vec![
("in_bytes", bytes(&[&[1, 2][..], &key, &[3][..]].concat())),
("in_text", J::s(format!("rikey={upper}&x=1"))),
]);
let l = line(data, &log.secrets);
assert!(!l.contains(&lower) && !l.contains(&upper), "{l}");
assert!(l.contains("0102<redacted>03"), "{l}");
assert!(l.contains("rikey=<redacted>&x=1"), "{l}");
}
#[test]
fn byte_fields_are_capped() {
let big = vec![0xABu8; MAX_LOGGED_BYTES + 10];
let mut s = String::new();
bytes(&big).write(&mut s);
assert!(s.starts_with(&format!(r#"{{"len":{},"hex":"abab"#, big.len())));
assert!(s.ends_with(r#","truncated":true}"#));
assert_eq!(s.matches("ab").count(), MAX_LOGGED_BYTES);
}
#[test]
fn text_or_hex() {
let mut s = String::new();
text(b"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n").write(&mut s);
assert_eq!(s, r#"{"len":28,"text":"RTSP/1.0 200 OK\r\nCSeq: 1\r\n\r\n"}"#);
let mut b = String::new();
text(&[0x80, 0x00]).write(&mut b);
assert_eq!(b, r#"{"len":2,"hex":"8000"}"#);
}
#[test]
fn utc_stamps() {
assert_eq!(utc_stamp(0), "19700101T000000Z");
assert_eq!(utc_stamp(951_782_400), "20000229T000000Z");
assert_eq!(utc_stamp(951_782_400 + 86_399), "20000229T235959Z");
assert_eq!(utc_stamp(946_684_799), "19991231T235959Z");
}
}
+247
View File
@@ -0,0 +1,247 @@
//! gs-probe (`probe`): a desktop GameStream client that drives DomiStream's state machines over real sockets
//! against ONE host address, and writes a structured log of every step for the live interop sitting
//! (`docs/LIVE-INTEROP.md`). A dev tool, never shipped: it prints the pairing PIN for the operator to submit through
//! Sunshine's API.
//!
//! Exit codes: 0 done, 1 error, 2 bad command line, 3 stop and report (something unexpected; see the log).
mod args;
mod commands;
mod dump;
mod fec;
mod http;
mod log;
mod redact;
mod rng;
mod rtsp;
mod state;
mod stream;
mod tls;
use std::fs;
use std::net::{IpAddr, SocketAddr};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use domistream::http::{HttpRequest, Scheme};
use domistream::pairing::ServerCert;
use args::{Command, Options};
use log::{J, Kind, Log};
/// Everything a network command needs.
pub struct Ctx {
pub opts: Options,
/// `--host`: the one host.
pub host: IpAddr,
/// Where sockets connect: `--relay` when given, else `--host`.
pub connect: IpAddr,
pub out: PathBuf,
pub run_dir: PathBuf,
pub log: Log,
pub rng: rng::OsRandom,
pub id: state::Identity,
pub host_cert: Option<ServerCert>,
pub epoch: Instant,
}
/// An HTTP body for the log: text (secret XML elements redacted) or hex.
pub fn body_j(body: &[u8]) -> J {
match std::str::from_utf8(body) {
Ok(s) => log::text(redact::xml(s).as_bytes()),
Err(_) => log::bytes(body),
}
}
impl Ctx {
/// Sends one DomiStream-built request and logs both directions (redacted). HTTPS pins `pinned` (pairing step 5)
/// or the stored host certificate.
pub fn http(
&mut self,
step: &str,
us: &[&str],
req: &HttpRequest,
pinned: Option<&ServerCert>,
) -> Result<http::Exchange, String> {
let (port, tls) = match req.scheme {
Scheme::Http => (self.opts.http_port, None),
Scheme::Https => {
let cert = pinned.or(self.host_cert.as_ref()).ok_or("not paired yet: run `probe pair` first")?;
(self.opts.https_port, Some(tls::client_config(&self.id.client, cert)?))
}
};
let addr = SocketAddr::new(self.connect, port);
let timeout = req.timeout.unwrap_or(Duration::from_secs(10));
self.log.record(
step,
Kind::Send,
us,
J::O(vec![
("scheme", J::dbg(&req.scheme)),
("to", J::s(addr.to_string())),
("path", J::s(redact::query(&req.path_and_query))),
("timeout_ms", J::U(u64::try_from(timeout.as_millis()).unwrap_or(u64::MAX))),
]),
);
match http::get(addr, &req.path_and_query, timeout, tls) {
Ok(x) => {
let r = &x.response;
self.log.record(
step,
Kind::Recv,
us,
J::O(vec![
("status", J::U(u64::from(r.status))),
("reason", J::s(r.reason.clone())),
("elapsed_ms", J::F(x.elapsed.as_secs_f64() * 1000.0)),
("framing", J::dbg(&r.framing)),
(
"headers",
J::A(r.headers.iter().map(|(n, v)| J::A(vec![J::s(n.clone()), J::s(v.clone())])).collect()),
),
(
"tls",
x.tls.as_ref().map_or(J::Null, |t| {
J::O(vec![("version", J::s(t.version.clone())), ("suite", J::s(t.suite.clone()))])
}),
),
("body", body_j(&r.body)),
]),
);
Ok(x)
}
Err(e) => {
let m = format!("{} {addr}: {e}", req.path_and_query.split('?').next().unwrap_or(""));
self.log.stop(step, us, m.clone(), J::Null);
Err(m)
}
}
}
}
/// U16 from a dump file, as a log value.
pub fn solve_audio_file(path: &Path) -> Result<J, String> {
let len = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len();
if len > dump::MAX_DUMP_BYTES as u64 {
return Err(format!("{}: larger than {} bytes", path.display(), dump::MAX_DUMP_BYTES));
}
let data = fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?;
let records = dump::decode(&data)?;
let datagrams: Vec<Vec<u8>> = records.into_iter().map(|(_, b)| b).collect();
let r = fec::solve_audio(&datagrams);
Ok(J::O(vec![
("report", J::dbg(&r)),
("matrix", r.matrix().map_or(J::Null, |m| J::s(log::hex(&m)))),
("matrix_is_mds", r.matrix_is_mds().map_or(J::Null, J::Bool)),
]))
}
fn run(cmd: &Command, opts: Options) -> Result<u8, String> {
if let Command::SolveAudioFec { dump } = cmd {
let j = solve_audio_file(dump)?;
let mut s = String::new();
j.write(&mut s);
println!("{s}");
return Ok(0);
}
let (Some(host), Some(out)) = (opts.host, opts.out.clone()) else {
return Err("--host and --out are required".into());
};
let connect = opts.connect_ip().unwrap_or(host);
let epoch = Instant::now();
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "the clock is before 1970")?.as_secs();
let run_dir = out.join("runs").join(format!("{}-{}", log::utc_stamp(now), cmd.name()));
fs::create_dir_all(&run_dir).map_err(|e| format!("{}: {e}", run_dir.display()))?;
let mut log = Log::create(&run_dir.join("log.jsonl"), epoch).map_err(|e| format!("log: {e}"))?;
println!(
"probe {}: host {host}{}; log {}",
cmd.name(),
opts.relay.map_or(String::new(), |r| format!(" via relay {r}")),
log.path.display()
);
log.record(
"start",
Kind::Note,
&[],
J::O(vec![
("probe", J::s(env!("CARGO_PKG_VERSION"))),
("command", J::dbg(cmd)),
("host", J::s(host.to_string())),
("connect", J::s(connect.to_string())),
("options", J::dbg(&opts)),
]),
);
let mut rng = rng::OsRandom::new();
let id = state::load_or_create(&out, &opts.name, &mut rng)?;
log.note(
"identity",
&["U2"],
format!(
"{} client identity: uniqueid {}, certificate sha256 {} (test-only key in {}, never logged)",
if id.created { "generated a new" } else { "loaded the" },
id.unique_id,
rng::sha256_hex(id.client.cert_der()),
state::identity_dir(&out).display()
),
);
let host_cert = match state::load_host_cert(&out)? {
Some((cert, paired_at)) => {
if paired_at != host.to_string() {
log.note(
"identity",
&[],
format!("the pinned host certificate was paired at '{paired_at}', not {host}"),
);
}
Some(cert)
}
None => None,
};
let mut ctx = Ctx { opts, host, connect, out, run_dir, log, rng, id, host_cert, epoch };
let result = match cmd {
Command::ServerInfo => commands::serverinfo(&mut ctx),
Command::Pair => commands::pair(&mut ctx),
Command::Apps => commands::apps(&mut ctx),
Command::Launch { app_id } => stream::launch(&mut ctx, *app_id),
Command::Quit => commands::quit(&mut ctx),
Command::Unpair => commands::unpair(&mut ctx),
Command::SolveAudioFec { .. } => Ok(()),
};
let stops = ctx.log.stops;
ctx.log.record(
"end",
Kind::Note,
&[],
J::O(vec![
("ok", J::Bool(result.is_ok())),
("error", result.as_ref().err().map_or(J::Null, |e| J::s(e.clone()))),
("stops", J::U(u64::from(stops))),
("parse_errors", J::U(u64::from(ctx.log.parse_errors))),
]),
);
println!("log: {}", ctx.log.path.display());
match result {
_ if stops > 0 => Ok(3),
Ok(()) => Ok(0),
Err(e) => Err(e),
}
}
fn main() -> ExitCode {
let argv: Vec<String> = std::env::args().skip(1).collect();
let inv = match args::parse(&argv) {
Ok(i) => i,
Err(e) => {
eprintln!("probe: {e}\n\n{}", args::USAGE);
return ExitCode::from(2);
}
};
match run(&inv.command, inv.options) {
Ok(code) => ExitCode::from(code),
Err(e) => {
eprintln!("probe: {e}");
ExitCode::from(1)
}
}
}
+111
View File
@@ -0,0 +1,111 @@
//! Hides secrets before anything reaches the log or the terminal: the stream key (`rikey`) and the pairing values
//! that, together with the PIN, would let someone redo the pairing proofs. Names stay, values go, so the log still
//! shows which parameters were sent and in which order (U1, U4).
/// Query parameters whose values never reach the log.
pub const SECRET_PARAMS: [&str; 6] =
["rikey", "salt", "clientchallenge", "serverchallengeresp", "clientpairingsecret", "pin"];
/// XML elements whose text never reaches the log.
pub const SECRET_ELEMENTS: [&str; 2] = ["challengeresponse", "pairingsecret"];
/// What replaces a secret value.
pub const MARK: &str = "<redacted>";
/// `path?k=v&…` with the value of every [`SECRET_PARAMS`] name replaced by [`MARK`] (names compared ignoring case).
pub fn query(path_and_query: &str) -> String {
let Some((path, q)) = path_and_query.split_once('?') else { return path_and_query.to_owned() };
let parts: Vec<String> = q
.split('&')
.map(|kv| match kv.split_once('=') {
Some((k, _)) if SECRET_PARAMS.iter().any(|s| s.eq_ignore_ascii_case(k)) => format!("{k}={MARK}"),
_ => kv.to_owned(),
})
.collect();
format!("{path}?{}", parts.join("&"))
}
/// `text` with the content of every `<name>…</…>` of [`SECRET_ELEMENTS`] replaced by [`MARK`] (names compared
/// ignoring case; an element left open is redacted to the end).
pub fn xml(text: &str) -> String {
let lower = text.to_ascii_lowercase();
let mut out = String::with_capacity(text.len());
let mut i = 0;
'scan: while i < text.len() {
for name in SECRET_ELEMENTS {
let open = format!("<{name}>");
if lower.get(i..).is_some_and(|rest| rest.starts_with(&open)) {
out.push_str(text.get(i..i + open.len()).unwrap_or(""));
out.push_str(MARK);
i += open.len();
i = lower.get(i..).and_then(|rest| rest.find("</")).map_or(text.len(), |p| i + p);
continue 'scan;
}
}
let Some(c) = text.get(i..).and_then(|rest| rest.chars().next()) else { break };
out.push(c);
i += c.len_utf8();
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use domistream::SessionKeys;
use domistream::http::launch::{AudioLayout, LaunchParams, launch_request};
#[test]
fn launch_key_is_hidden_and_the_rest_stays() {
assert_eq!(
query("/launch?uniqueid=0123&appid=1&rikey=00112233445566778899aabbccddeeff&rikeyid=7"),
"/launch?uniqueid=0123&appid=1&rikey=<redacted>&rikeyid=7"
);
}
#[test]
fn a_real_launch_request_never_shows_its_key() {
let keys = SessionKeys { rikey: [0xA5; 16], rikeyid: 42 };
let params = LaunchParams {
app_id: 5,
width: 1920,
height: 1080,
fps: 60,
keys,
hdr: false,
audio: AudioLayout::Stereo,
};
let req = launch_request(&params, "0123456789ABCDEF").unwrap();
let shown = query(&req.path_and_query);
assert!(!shown.to_ascii_lowercase().contains("a5a5a5a5"), "{shown}");
assert!(shown.contains("rikey=<redacted>") && shown.contains("rikeyid=42") && shown.contains("appid=5"));
}
#[test]
fn pairing_values_are_hidden_but_names_and_certs_stay() {
assert_eq!(
query("/pair?uniqueid=1&devicename=x&updateState=1&phrase=getservercert&salt=ABCD&clientcert=2D2D"),
"/pair?uniqueid=1&devicename=x&updateState=1&phrase=getservercert&salt=<redacted>&clientcert=2D2D"
);
assert_eq!(query("/pair?uniqueid=1&ClientChallenge=ff"), "/pair?uniqueid=1&ClientChallenge=<redacted>");
assert_eq!(
xml("<root status_code=\"200\"><paired>1</paired><pairingsecret>ffee</pairingsecret></root>"),
"<root status_code=\"200\"><paired>1</paired><pairingsecret><redacted></pairingsecret></root>"
);
assert_eq!(
xml("<root><challengeresponse>0011</challengeresponse><plaincert>2D2D</plaincert></root>"),
"<root><challengeresponse><redacted></challengeresponse><plaincert>2D2D</plaincert></root>"
);
}
#[test]
fn lookalikes_and_plain_text_are_untouched() {
assert_eq!(query("/x?rikeyid=5&nosalt=1&pinned=2"), "/x?rikeyid=5&nosalt=1&pinned=2");
assert_eq!(query("/serverinfo"), "/serverinfo");
assert_eq!(xml("<root><hostname>PC é</hostname></root>"), "<root><hostname>PC é</hostname></root>");
}
#[test]
fn an_open_element_is_redacted_to_the_end() {
assert_eq!(xml("<challengeresponse>abc"), "<challengeresponse><redacted>");
assert_eq!(query("?rikey=abc"), "?rikey=<redacted>");
}
}
+28
View File
@@ -0,0 +1,28 @@
//! DomiStream's randomness comes from the caller; the probe hands it the OS generator.
use domistream::RandomSource;
use ring::rand::{SecureRandom, SystemRandom};
/// The operating system's cryptographic generator.
pub struct OsRandom(SystemRandom);
impl OsRandom {
pub fn new() -> Self {
Self(SystemRandom::new())
}
}
impl RandomSource for OsRandom {
fn fill(&mut self, dest: &mut [u8]) {
// Keys, salts and the PIN depend on this; without the OS generator nothing may go on.
if self.0.fill(dest).is_err() {
eprintln!("probe: the OS random generator failed; stopping");
std::process::exit(1);
}
}
}
/// SHA-256 of `data`, as lower-case hex (certificate fingerprints in the log).
pub fn sha256_hex(data: &[u8]) -> String {
crate::log::hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())
}
+258
View File
@@ -0,0 +1,258 @@
//! Drives DomiStream's `RtspClient` over real TCP and records what U5 needs: whether answers carry
//! `Content-Length`, whether the host closes the connection after each answer, and every header it sends.
use std::io::{self, Read, Write};
use std::net::{IpAddr, SocketAddr, TcpStream};
use std::time::{Duration, Instant};
use domistream::rtsp::client::{RtspClientState, StreamConfig};
use domistream::rtsp::{DEFAULT_RTSP_PORT, NegotiatedStream, RtspClient, RtspFramer, RtspProgress, parse_response};
use crate::log::{J, Kind, Log, text};
/// A whole exchange may take this long.
const ANSWER_TIMEOUT: Duration = Duration::from_secs(15);
/// With headers in and no `Content-Length`, an open connection that stays quiet this long ends the message.
const IDLE_CUT: Duration = Duration::from_secs(2);
const POLL: Duration = Duration::from_millis(200);
/// Where to connect for RTSP and the URL the requests name.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Target {
pub addr: SocketAddr,
pub url: String,
/// Set when the host named another address than the one the probe talks to (it is never used).
pub foreign_host: Option<String>,
/// `sessionUrl0` was missing and port 48010 was assumed (U4).
pub assumed_port: bool,
}
/// The RTSP target from the launch answer. The probe only ever connects to `connect_ip`; the host part of
/// `sessionUrl0` is compared with `host` and otherwise ignored.
pub fn target(session_url: Option<&str>, host: IpAddr, connect_ip: IpAddr) -> Result<Target, String> {
let Some(url) = session_url else {
let url = format!("rtsp://{}", SocketAddr::new(host, DEFAULT_RTSP_PORT));
return Ok(Target {
addr: SocketAddr::new(connect_ip, DEFAULT_RTSP_PORT),
url,
foreign_host: None,
assumed_port: true,
});
};
let rest = url.strip_prefix("rtsp://").ok_or_else(|| format!("sessionUrl0 '{url}' is not rtsp://"))?;
let authority = rest.split('/').next().unwrap_or("");
let (h, p) = authority.rsplit_once(':').ok_or_else(|| format!("sessionUrl0 '{url}' has no port"))?;
let port: u16 = p.parse().map_err(|_| format!("sessionUrl0 '{url}' has a bad port"))?;
if port == 0 {
return Err(format!("sessionUrl0 '{url}' has port 0"));
}
let named = h.trim_start_matches('[').trim_end_matches(']');
let foreign_host = match named.parse::<IpAddr>() {
Ok(ip) if ip == host => None,
_ => Some(named.to_owned()),
};
Ok(Target { addr: SocketAddr::new(connect_ip, port), url: url.to_owned(), foreign_host, assumed_port: false })
}
fn state_name(s: RtspClientState) -> &'static str {
match s {
RtspClientState::Options => "options",
RtspClientState::Describe => "describe",
RtspClientState::SetupAudio => "setup_audio",
RtspClientState::SetupVideo => "setup_video",
RtspClientState::SetupControl => "setup_control",
RtspClientState::Announce => "announce",
RtspClientState::Play => "play",
RtspClientState::Ready => "ready",
RtspClientState::Failed => "failed",
}
}
fn unknowns(s: RtspClientState) -> &'static [&'static str] {
match s {
RtspClientState::Describe => &["U5", "U26"],
RtspClientState::SetupAudio | RtspClientState::SetupVideo | RtspClientState::SetupControl => &["U5", "U7"],
RtspClientState::Announce => &["U5", "U6"],
_ => &["U5"],
}
}
/// How an answer's end was found.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum End {
/// Headers plus `Content-Length` (the connection stays open).
Length,
/// The host closed the connection.
Closed,
/// No `Content-Length`; the open connection went quiet ([`IDLE_CUT`]).
Idle,
}
fn connect(addr: SocketAddr) -> io::Result<TcpStream> {
let s = TcpStream::connect_timeout(&addr, Duration::from_secs(5))?;
s.set_read_timeout(Some(POLL))?;
s.set_nodelay(true)?;
Ok(s)
}
fn read_answer(s: &mut TcpStream) -> Result<(Vec<u8>, End), String> {
let started = Instant::now();
let mut last_data = Instant::now();
let mut framer = RtspFramer::new();
let mut buf = [0u8; 8192];
loop {
match s.read(&mut buf) {
Ok(0) => {
return match framer.finish() {
Ok(Some(m)) => Ok((m, End::Closed)),
Ok(None) => Err("closed with no answer".into()),
Err(e) => Err(format!("closed inside an answer: {e}")),
};
}
Ok(n) => {
framer.push(buf.get(..n).unwrap_or(&[])).map_err(|e| e.to_string())?;
if let Some(m) = framer.next_message().map_err(|e| e.to_string())? {
return Ok((m, End::Length));
}
last_data = Instant::now();
}
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
if framer.buffered() > 0 && last_data.elapsed() >= IDLE_CUT {
// Complete headers without Content-Length: the message ends here. Otherwise keep waiting.
if let Ok(Some(m)) = framer.finish() {
return Ok((m, End::Idle));
}
}
}
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(format!("read failed: {e}")),
}
if started.elapsed() >= ANSWER_TIMEOUT {
return Err(format!(
"no complete answer within {} s ({} bytes buffered)",
ANSWER_TIMEOUT.as_secs(),
framer.buffered()
));
}
}
}
/// OPTIONS … PLAY. Every request and answer goes to the log in full (RTSP carries no secrets).
pub fn negotiate(log: &mut Log, t: &Target, config: StreamConfig) -> Result<NegotiatedStream, String> {
let mut client = RtspClient::new(&t.url, config).map_err(|e| format!("rtsp setup: {e}"))?;
let mut conn: Option<TcpStream> = None;
let mut connections = 0u32;
while let Some(req) = client.poll_request() {
let state = client.state();
let step = format!("rtsp.{}", state_name(state));
let us = unknowns(state);
log.record(&step, Kind::Send, us, J::O(vec![("to", J::s(t.addr.to_string())), ("message", text(&req))]));
let mut retried = false;
let (answer, end) = loop {
let reused = conn.is_some();
if conn.is_none() {
let s = connect(t.addr).map_err(|e| {
let m = format!("RTSP connect to {} failed: {e}", t.addr);
log.stop(&step, us, m.clone(), J::Null);
m
})?;
connections += 1;
log.note(&step, &["U5"], format!("TCP connection #{connections} to {}", t.addr));
conn = Some(s);
}
let Some(s) = conn.as_mut() else { return Err("no RTSP connection".into()) };
let result = s.write_all(&req).map_err(|e| format!("write failed: {e}")).and_then(|()| read_answer(s));
match result {
Ok(x) => break x,
Err(e) if reused && !retried => {
log.note(
&step,
&["U5"],
format!("the kept connection failed ({e}); the host closes between requests; reconnecting"),
);
conn = None;
retried = true;
}
Err(e) => {
let m = format!("RTSP {}: {e}", state_name(state));
log.stop(&step, us, m.clone(), J::Null);
return Err(m);
}
}
};
if end == End::Closed {
conn = None;
}
let parsed = parse_response(&answer).ok();
let has_length =
parsed.as_ref().is_some_and(|r| r.headers.iter().any(|(n, _)| n.eq_ignore_ascii_case("content-length")));
let headers = parsed
.map(|r| J::A(r.headers.iter().map(|(n, v)| J::A(vec![J::s(n.clone()), J::s(v.clone())])).collect()))
.unwrap_or(J::Null);
log.record(
&step,
Kind::Recv,
us,
J::O(vec![
("end", J::s(format!("{end:?}"))),
("content_length_header", J::Bool(has_length)),
("headers", headers),
("message", text(&answer)),
]),
);
match client.handle_response(&answer) {
Ok(RtspProgress::Continue) => {}
Ok(RtspProgress::Ready(n)) => {
log.note("rtsp.ready", &["U5"], format!("negotiated over {connections} TCP connection(s)"));
return Ok(n);
}
Err(e) => {
log.parse_error(&step, us, &e, text(&answer));
let m = format!("RTSP {} answer refused: {e}", state_name(state));
log.stop(&step, us, m.clone(), J::Null);
return Err(m);
}
}
}
Err("RTSP ended without a request to send".into())
}
#[cfg(test)]
mod tests {
use super::*;
fn ip(s: &str) -> IpAddr {
s.parse().unwrap()
}
#[test]
fn session_url_port_is_used_with_the_given_address_only() {
let t = target(Some("rtsp://192.168.100.140:48010"), ip("192.168.100.140"), ip("192.168.100.140")).unwrap();
assert_eq!((t.addr, t.foreign_host, t.assumed_port), ("192.168.100.140:48010".parse().unwrap(), None, false));
let t = target(Some("rtsp://10.0.0.9:48011"), ip("192.168.100.140"), ip("192.168.100.140")).unwrap();
assert_eq!(t.addr, "192.168.100.140:48011".parse().unwrap());
assert_eq!(t.foreign_host.as_deref(), Some("10.0.0.9"));
assert_eq!(t.url, "rtsp://10.0.0.9:48011");
}
#[test]
fn relay_and_ipv6() {
let t = target(Some("rtsp://[::1]:48010"), ip("::1"), ip("127.0.0.1")).unwrap();
assert_eq!((t.addr, t.foreign_host), ("127.0.0.1:48010".parse().unwrap(), None));
}
#[test]
fn missing_session_url_assumes_48010() {
let t = target(None, ip("192.168.100.140"), ip("192.168.100.140")).unwrap();
assert_eq!((t.url.as_str(), t.assumed_port), ("rtsp://192.168.100.140:48010", true));
}
#[test]
fn bad_session_urls_are_refused() {
let h = ip("192.168.100.140");
assert!(target(Some("http://x:1"), h, h).is_err());
assert!(target(Some("rtsp://x"), h, h).is_err());
assert!(target(Some("rtsp://x:0"), h, h).is_err());
assert!(target(Some("rtsp://x:99999"), h, h).is_err());
}
}
+147
View File
@@ -0,0 +1,147 @@
//! The probe's own state in `--out/identity/`: its client id, its test-only key and certificate (generated on the
//! first run), and the host certificate pinned by `probe pair`. Nothing here is a real device's key; the folder
//! stays out of git and is deleted after the sitting.
use std::fs;
use std::io::Write;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
use domistream::RandomSource;
use domistream::pairing::{ClientIdentity, ServerCert};
/// Largest state file read back.
const MAX_STATE_FILE: u64 = 16 * 1024;
pub const UNIQUE_ID_FILE: &str = "uniqueid.txt";
pub const CERT_FILE: &str = "client-cert.der";
pub const KEY_FILE: &str = "client-key.pk8";
pub const HOST_CERT_FILE: &str = "host-cert.der";
pub const HOST_ADDR_FILE: &str = "host-address.txt";
pub fn identity_dir(out: &Path) -> PathBuf {
out.join("identity")
}
fn read_capped(path: &Path) -> Result<Vec<u8>, String> {
let len = fs::metadata(path).map_err(|e| format!("{}: {e}", path.display()))?.len();
if len > MAX_STATE_FILE {
return Err(format!("{}: larger than {MAX_STATE_FILE} bytes", path.display()));
}
fs::read(path).map_err(|e| format!("{}: {e}", path.display()))
}
fn write_new(path: &Path, data: &[u8]) -> Result<(), String> {
let mut f =
fs::File::options().write(true).create_new(true).open(path).map_err(|e| format!("{}: {e}", path.display()))?;
f.write_all(data).and_then(|()| f.sync_all()).map_err(|e| format!("{}: {e}", path.display()))
}
/// 16 upper-case hex characters, as the crate's own clients use.
pub fn new_unique_id(rng: &mut dyn RandomSource) -> String {
let mut b = [0u8; 8];
rng.fill(&mut b);
crate::log::hex(&b).to_ascii_uppercase()
}
pub fn valid_unique_id(s: &str) -> bool {
s.len() == 16 && s.bytes().all(|b| b.is_ascii_hexdigit())
}
/// The probe's identity.
pub struct Identity {
pub unique_id: String,
pub client: ClientIdentity,
/// Generated by this run (else loaded).
pub created: bool,
}
/// Loads the identity, or makes one on the first run. Never prints or logs the key.
pub fn load_or_create(out: &Path, common_name: &str, rng: &mut dyn RandomSource) -> Result<Identity, String> {
let dir = identity_dir(out);
fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
let (id_path, cert_path, key_path) = (dir.join(UNIQUE_ID_FILE), dir.join(CERT_FILE), dir.join(KEY_FILE));
if cert_path.exists() || key_path.exists() || id_path.exists() {
let unique_id = String::from_utf8(read_capped(&id_path)?).map_err(|_| "uniqueid.txt is not text".to_owned())?;
let unique_id = unique_id.trim().to_owned();
if !valid_unique_id(&unique_id) {
return Err(format!("{}: not 16 hex characters", id_path.display()));
}
let client = ClientIdentity::from_der(&read_capped(&cert_path)?, &read_capped(&key_path)?)
.map_err(|e| format!("stored identity refused: {e}"))?;
return Ok(Identity { unique_id, client, created: false });
}
let now = SystemTime::now().duration_since(UNIX_EPOCH).map_err(|_| "the clock is before 1970".to_owned())?;
// A day of slack for a host whose clock is behind.
let not_before = i64::try_from(now.as_secs()).unwrap_or(i64::MAX) - 86_400;
let client = ClientIdentity::generate(rng, common_name, not_before).map_err(|e| format!("key generation: {e}"))?;
let unique_id = new_unique_id(rng);
write_new(&cert_path, client.cert_der())?;
write_new(&key_path, client.key_pkcs8_der())?;
write_new(&id_path, unique_id.as_bytes())?;
Ok(Identity { unique_id, client, created: true })
}
/// The pinned host certificate and the address it was paired at, if `probe pair` succeeded before.
pub fn load_host_cert(out: &Path) -> Result<Option<(ServerCert, String)>, String> {
let dir = identity_dir(out);
let path = dir.join(HOST_CERT_FILE);
if !path.exists() {
return Ok(None);
}
let cert =
ServerCert::from_der(&read_capped(&path)?).map_err(|e| format!("stored host certificate refused: {e}"))?;
let addr = read_capped(&dir.join(HOST_ADDR_FILE))
.map(|b| String::from_utf8_lossy(&b).trim().to_owned())
.unwrap_or_default();
Ok(Some((cert, addr)))
}
/// Stores the host certificate after pairing (replacing an older one).
pub fn save_host_cert(out: &Path, cert: &ServerCert, host: IpAddr) -> Result<(), String> {
let dir = identity_dir(out);
let (path, addr) = (dir.join(HOST_CERT_FILE), dir.join(HOST_ADDR_FILE));
for p in [&path, &addr] {
if p.exists() {
fs::remove_file(p).map_err(|e| format!("{}: {e}", p.display()))?;
}
}
write_new(&path, cert.der())?;
write_new(&addr, host.to_string().as_bytes())
}
/// Forgets the host certificate (after `probe unpair`).
pub fn forget_host_cert(out: &Path) -> Result<(), String> {
let dir = identity_dir(out);
for p in [dir.join(HOST_CERT_FILE), dir.join(HOST_ADDR_FILE)] {
if p.exists() {
fs::remove_file(&p).map_err(|e| format!("{}: {e}", p.display()))?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
struct Counter(u8);
impl RandomSource for Counter {
fn fill(&mut self, dest: &mut [u8]) {
for b in dest {
self.0 = self.0.wrapping_add(0x3B);
*b = self.0;
}
}
}
#[test]
fn unique_ids_are_16_upper_hex() {
let id = new_unique_id(&mut Counter(0));
assert!(valid_unique_id(&id), "{id}");
assert_eq!(id, id.to_ascii_uppercase());
assert!(!valid_unique_id("0123"));
assert!(!valid_unique_id("0123456789ABCDEG"));
}
}
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
//! HTTPS as a GameStream client does it: the probe presents its own client certificate and accepts exactly the host
//! certificate it pinned while pairing (`plaincert`), byte for byte (`ServerCert::matches`). Handshake signatures
//! are still checked against that certificate's key.
use std::sync::Arc;
use domistream::pairing::{ClientIdentity, ServerCert};
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
use rustls::crypto::{WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime};
use rustls::{ClientConfig, DigitallySignedStruct, SignatureScheme};
/// Accepts exactly the pinned host certificate.
#[derive(Debug)]
struct PinnedHost {
pinned: ServerCert,
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> {
match self.pinned.matches(end_entity.as_ref()) {
Ok(true) => Ok(ServerCertVerified::assertion()),
_ => {
Err(rustls::Error::General("the host presented another certificate than the one it paired with".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()
}
}
/// A client configuration presenting `identity` and pinning `host`. TLS 1.2 and 1.3 are both offered (U24 is
/// whatever the host picks; the log records it).
pub fn client_config(identity: &ClientIdentity, host: &ServerCert) -> Result<Arc<ClientConfig>, String> {
let provider = Arc::new(rustls::crypto::ring::default_provider());
let algs = provider.signature_verification_algorithms;
let cert = CertificateDer::from(identity.cert_der().to_vec());
let key = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(identity.key_pkcs8_der().to_vec()));
let cfg = ClientConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.map_err(|e| format!("TLS setup failed: {e}"))?
.dangerous()
.with_custom_certificate_verifier(Arc::new(PinnedHost { pinned: host.clone(), algs }))
.with_client_auth_cert(vec![cert], key)
// The error text never carries key bytes.
.map_err(|e| format!("TLS client certificate refused: {e}"))?;
Ok(Arc::new(cfg))
}