Compare commits
30 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 3e09dbc09a | |||
| 07ccff4241 | |||
| a3c8cea7a6 | |||
| beeb72cec8 | |||
| c21e68565b | |||
| 66a6e98cf2 | |||
| 8125949db2 | |||
| d62aa8f581 | |||
| 6f13976ba5 | |||
| 61296102d1 | |||
| bd91a1007e | |||
| 30a7b90034 | |||
| 27b26a992b | |||
| a939821124 | |||
| 0f2edc66c9 | |||
| 6c68a25b77 | |||
| fd1c141ca8 | |||
| ab5404b0cf | |||
| a2b834ed87 | |||
| fbb8833f3d | |||
| 8b968be489 | |||
| 26ce712e82 | |||
| 8bc8b4f7ab | |||
| ff62498c9e | |||
| 11c14b8cb6 | |||
| 424cccfa92 | |||
| 3bd7ebeaed | |||
| af1df633a1 | |||
| f72babc5b5 | |||
| ccfcdcc36c |
@@ -11,3 +11,4 @@ fuzz/corpus/
|
|||||||
*.h265
|
*.h265
|
||||||
*.pcap
|
*.pcap
|
||||||
*.pcapng
|
*.pcapng
|
||||||
|
*.proptest-regressions
|
||||||
|
|||||||
@@ -10,6 +10,8 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
|
|||||||
### Rules that never bend
|
### Rules that never bend
|
||||||
- Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c)
|
- Clean room: never open, paste or port GPL code (Sunshine, Moonlight, Apollo, Vibeshine, Rubylight, moonlight-common-c)
|
||||||
into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements.
|
into Domi repos. Allowed sources: Wolf protocol docs, Moonshine (BSD-2, attribute), our own measurements.
|
||||||
|
- Also allowed for the wire format, with attribution (Mark, 2026-11-25): stock ENet (MIT), tokio-enet (BSD-2),
|
||||||
|
fec-rs (BSD-2). GPL code stays off limits.
|
||||||
- Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only.
|
- Sunshine is never patched, linked or bundled: official release, sha256-pinned, separate program, local API only.
|
||||||
- Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed).
|
- Sunshine and Lumen listen only on the Via Domi interface and loopback (home LAN only when Via isn't installed).
|
||||||
- Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever.
|
- Every device must hold a Tessera identity with a grant from the PC's owner. No PIN shown to the user, ever.
|
||||||
@@ -28,3 +30,9 @@ Days 1-2 wrap Sunshine; from Day 3 the engine is Lumen (own Rust code). Roadmap:
|
|||||||
- Commits: `[<crate>] <Feature>: <description>`, `[repo]` for repo-wide changes. No AI attribution in commits, PRs or tags.
|
- Commits: `[<crate>] <Feature>: <description>`, `[repo]` for repo-wide changes. No AI attribution in commits, PRs or tags.
|
||||||
- No binaries, captures or test videos in git.
|
- No binaries, captures or test videos in git.
|
||||||
- Cargo builds: the machine-wide `CARGO_HOME` config sends the build dir to `D:\cargo-build`. Never set `CARGO_TARGET_DIR`.
|
- Cargo builds: the machine-wide `CARGO_HOME` config sends the build dir to `D:\cargo-build`. Never set `CARGO_TARGET_DIR`.
|
||||||
|
- Never start a build or a test run (cargo, npm/pnpm, Gradle, dotnet, Playwright, e2e, emulator, Fabrica runs) while this
|
||||||
|
PC's CPU or RAM is more than 90 % used, or any drive the work writes to (D:, E:, F:) is more than 95 % used
|
||||||
|
(Mark, 2026-11-25: "CPU, RAM and disk all 90%"; drives raised to 95 % on 2026-11-29). Check first. If any is over,
|
||||||
|
don't start; wait and check again later. Don't stop other sessions' work to make room.
|
||||||
|
- The limits gate builds and tests only. Merging, writing docs or CLAUDE.md and finishing a job never wait for the load
|
||||||
|
(Mark, 2026-11-29: "No merge you can do even on 100 percent CPU same as writing to claude.md and finishing job").
|
||||||
|
|||||||
Generated
-51
@@ -158,7 +158,6 @@ checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cpubits",
|
"cpubits",
|
||||||
"ctutils",
|
"ctutils",
|
||||||
"getrandom",
|
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
"serdect",
|
"serdect",
|
||||||
@@ -171,7 +170,6 @@ version = "0.2.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom",
|
|
||||||
"hybrid-array",
|
"hybrid-array",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
]
|
]
|
||||||
@@ -504,17 +502,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "sha1"
|
|
||||||
version = "0.11.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"cpufeatures",
|
|
||||||
"digest",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha2"
|
name = "sha2"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -568,27 +555,6 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
|
|
||||||
dependencies = [
|
|
||||||
"tls_codec_derive",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec_derive"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
@@ -625,10 +591,7 @@ checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"const-oid",
|
"const-oid",
|
||||||
"der",
|
"der",
|
||||||
"sha1",
|
|
||||||
"signature",
|
|
||||||
"spki",
|
"spki",
|
||||||
"tls_codec",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -636,17 +599,3 @@ name = "zeroize"
|
|||||||
version = "1.9.2"
|
version = "1.9.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
||||||
dependencies = [
|
|
||||||
"zeroize_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "zeroize_derive"
|
|
||||||
version = "1.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|||||||
@@ -18,6 +18,14 @@ Rubylight or moonlight-common-c was opened, pasted or ported. See [`docs/CLEAN_R
|
|||||||
cargo test --workspace
|
cargo test --workspace
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## Status: `stream-v0.1.0`
|
||||||
|
|
||||||
|
Written from the Wolf protocol docs and the approved permissive sources (stock ENet, tokio-enet, fec-rs). **Interop is
|
||||||
|
unverified**: this release has not yet talked to a real Sunshine host. Ten details that block interop (U1, U2, U4–U10,
|
||||||
|
U17 in [`docs/PROTOCOL.md`](docs/PROTOCOL.md)) are settled live on Arena Domi's Play remotely Day 1, and a
|
||||||
|
`stream-v0.1.x` patch is expected. Evidence for this release: 242 tests, a mutation pass (24 of 24 caught,
|
||||||
|
[`docs/MUTATION.md`](docs/MUTATION.md)), and 25 fuzz targets with 0 crashes ([`docs/HANDOVER.md`](docs/HANDOVER.md)).
|
||||||
|
|
||||||
| Path | What |
|
| Path | What |
|
||||||
| :-- | :-- |
|
| :-- | :-- |
|
||||||
| `crates/domistream` | the crate: one module per protocol part (see its rustdoc) |
|
| `crates/domistream` | the crate: one module per protocol part (see its rustdoc) |
|
||||||
|
|||||||
@@ -17,8 +17,8 @@ aes = "0.9" # AES-128 block cipher (pairing ECB)
|
|||||||
aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"] } # control and video AES-128-GCM; no getrandom, randomness only through RandomSource
|
aes-gcm = { version = "0.11", default-features = false, features = ["aes", "alloc"] } # control and video AES-128-GCM; no getrandom, randomness only through RandomSource
|
||||||
cbc = "0.2" # audio AES-128-CBC
|
cbc = "0.2" # audio AES-128-CBC
|
||||||
sha2 = "0.11" # pairing SHA-256
|
sha2 = "0.11" # pairing SHA-256
|
||||||
rsa = "0.10" # client key, PKCS#1 v1.5 SHA-256 sign/verify (crypto-bigint, constant time)
|
rsa = { version = "0.10", default-features = false, features = ["std", "encoding", "pkcs1v15"] } # client key, PKCS#1 v1.5 SHA-256; no getrandom: randomness only through RandomSource
|
||||||
x509-cert = { version = "0.3", features = ["builder", "pem"] } # client certificate, host certificate parsing
|
x509-cert = { version = "0.3", default-features = false } # host and client certificate parsing (our own DER writer builds the client certificate)
|
||||||
rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits
|
rand_core = "0.10" # adapter from our RandomSource to the RustCrypto RNG traits
|
||||||
zeroize = "1.8" # wipe keys on drop
|
zeroize = "1.8" # wipe keys on drop
|
||||||
|
|
||||||
|
|||||||
@@ -3,10 +3,19 @@
|
|||||||
//!
|
//!
|
||||||
//! **Opus decoding is not here.** A packet that cannot be rebuilt becomes [`AudioEvent::Lost`]; the platform
|
//! **Opus decoding is not here.** A packet that cannot be rebuilt becomes [`AudioEvent::Lost`]; the platform
|
||||||
//! conceals it.
|
//! conceals it.
|
||||||
|
//!
|
||||||
|
//! Parity packets are keyed by their FEC header's base sequence number, never by their own RTP sequence number,
|
||||||
|
//! which overlaps the next block's data. The parity covers the (encrypted) payloads of the four data packets.
|
||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
use std::collections::{HashMap, VecDeque};
|
||||||
|
|
||||||
use crate::{Instant, Result, SessionKeys};
|
use cbc::cipher::block_padding::Pkcs7;
|
||||||
|
use cbc::cipher::{BlockModeDecrypt, KeyIvInit};
|
||||||
|
|
||||||
|
use crate::fec::ReedSolomon;
|
||||||
|
use crate::util::malformed;
|
||||||
|
use crate::{Error, Instant, Result, SessionKeys};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
|
||||||
@@ -18,39 +27,54 @@ pub const DATA_SHARDS: usize = 4;
|
|||||||
pub const PARITY_SHARDS: usize = 2;
|
pub const PARITY_SHARDS: usize = 2;
|
||||||
/// Maximum blocks kept while waiting for missing packets.
|
/// Maximum blocks kept while waiting for missing packets.
|
||||||
pub const MAX_BLOCKS_IN_FLIGHT: usize = 8;
|
pub const MAX_BLOCKS_IN_FLIGHT: usize = 8;
|
||||||
|
/// Packets further than this ahead of the next expected one are dropped (a stray, not a gap to wait for).
|
||||||
|
pub const MAX_PACKETS_AHEAD: u16 = 1024;
|
||||||
|
|
||||||
/// AES-128-CBC for audio payloads: IV = `u32 BE (rikeyid + sequence) ‖ 12 zero bytes`, PKCS#7 padding.
|
/// AES-128-CBC for audio payloads: IV = `u32 BE (rikeyid + sequence) ‖ 12 zero bytes`, PKCS#7 padding.
|
||||||
/// `Debug` never prints the key.
|
/// `Debug` never prints the key.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AudioCipher {
|
pub struct AudioCipher {
|
||||||
key: [u8; 16],
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
rikeyid: u32,
|
rikeyid: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl AudioCipher {
|
impl AudioCipher {
|
||||||
/// A cipher for the session's keys.
|
/// A cipher for the session's keys.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new(keys: &SessionKeys) -> Self {
|
pub fn new(keys: &SessionKeys) -> Self {
|
||||||
Self { key: keys.rikey, rikeyid: keys.rikeyid }
|
Self { key: zeroize::Zeroizing::new(keys.rikey), rikeyid: keys.rikeyid }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The IV for RTP sequence number `sequence`.
|
/// The IV for RTP sequence number `sequence` (the sum wraps).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn iv(&self, sequence: u16) -> Result<[u8; 16]> {
|
pub fn iv(&self, sequence: u16) -> Result<[u8; 16]> {
|
||||||
let _ = (sequence, self.rikeyid);
|
let mut iv = [0u8; 16];
|
||||||
Err(crate::Error::Unimplemented)
|
let [a, b, c, d] = self.rikeyid.wrapping_add(u32::from(sequence)).to_be_bytes();
|
||||||
|
iv[0] = a;
|
||||||
|
iv[1] = b;
|
||||||
|
iv[2] = c;
|
||||||
|
iv[3] = d;
|
||||||
|
Ok(iv)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decrypts one payload.
|
/// Decrypts one payload.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a length that is not a positive multiple of 16, [`crate::Error::Crypto`] for
|
/// [`Error::Malformed`] for a length that is not a positive multiple of 16, [`Error::Crypto`] for bad padding.
|
||||||
/// bad padding. Phase A: always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn decrypt(&self, sequence: u16, ciphertext: &[u8]) -> Result<Vec<u8>> {
|
pub fn decrypt(&self, sequence: u16, ciphertext: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (sequence, ciphertext, &self.key);
|
if ciphertext.is_empty() || !ciphertext.len().is_multiple_of(16) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("audio ciphertext length"));
|
||||||
|
}
|
||||||
|
let iv = self.iv(sequence)?;
|
||||||
|
let mut buf = ciphertext.to_vec();
|
||||||
|
let len = cbc::Decryptor::<aes::Aes128>::new((&*self.key).into(), &iv.into())
|
||||||
|
.decrypt_padded::<Pkcs7>(&mut buf)
|
||||||
|
.map_err(|_| Error::Crypto)?
|
||||||
|
.len();
|
||||||
|
buf.truncate(len);
|
||||||
|
Ok(buf)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -116,52 +140,352 @@ pub struct AudioStats {
|
|||||||
pub lost: u64,
|
pub lost: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// One received or rebuilt data packet.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct Data {
|
||||||
|
/// The payload as sent (ciphertext when encrypted): the FEC shard.
|
||||||
|
shard: Vec<u8>,
|
||||||
|
opus: Vec<u8>,
|
||||||
|
timestamp_ms: u32,
|
||||||
|
arrived: Instant,
|
||||||
|
recovered: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct Parity {
|
||||||
|
shard: Vec<u8>,
|
||||||
|
base_timestamp: u32,
|
||||||
|
arrived: Instant,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Block {
|
||||||
|
data: [Option<Data>; DATA_SHARDS],
|
||||||
|
parity: [Option<Parity>; PARITY_SHARDS],
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Block {
|
||||||
|
fn earliest_after(&self, index: usize) -> Option<Instant> {
|
||||||
|
let data = self.data.iter().skip(index + 1).flatten().map(|d| d.arrived);
|
||||||
|
let parity = self.parity.iter().flatten().map(|p| p.arrived);
|
||||||
|
data.chain(parity).min()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The audio receiver.
|
/// The audio receiver.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct AudioDepacketizer {
|
pub struct AudioDepacketizer {
|
||||||
|
config: AudioConfig,
|
||||||
|
code: Option<ReedSolomon>,
|
||||||
|
next: Option<u16>,
|
||||||
|
blocks: HashMap<u16, Block>,
|
||||||
|
events: VecDeque<AudioEvent>,
|
||||||
stats: AudioStats,
|
stats: AudioStats,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const fn block_base(seq: u16) -> u16 {
|
||||||
|
seq & !3
|
||||||
|
}
|
||||||
|
|
||||||
impl AudioDepacketizer {
|
impl AudioDepacketizer {
|
||||||
/// A receiver for one stream.
|
/// A receiver for one stream.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS. Phase A: always
|
/// [`Error::Malformed`] for a zero packet duration or a parity matrix that is not MDS.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn new(config: AudioConfig) -> Result<Self> {
|
pub fn new(config: AudioConfig) -> Result<Self> {
|
||||||
let _ = config;
|
if config.packet_duration_ms == 0 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("audio packet duration"));
|
||||||
|
}
|
||||||
|
let code = match config.fec {
|
||||||
|
AudioFec::Disabled => None,
|
||||||
|
AudioFec::ParityMatrix(m) => Some(ReedSolomon::with_parity_matrix(DATA_SHARDS, PARITY_SHARDS, &m)?),
|
||||||
|
};
|
||||||
|
Ok(Self {
|
||||||
|
config,
|
||||||
|
code,
|
||||||
|
next: None,
|
||||||
|
blocks: HashMap::new(),
|
||||||
|
events: VecDeque::new(),
|
||||||
|
stats: AudioStats::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drop_packet(&mut self) -> Result<()> {
|
||||||
|
self.stats.packets_dropped += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one datagram from the audio port. Bad, duplicate and too-old packets are counted and dropped; only an
|
/// Feeds one datagram from the audio port. Bad, duplicate and too-old packets are counted and dropped; only an
|
||||||
/// oversized datagram is an error.
|
/// oversized datagram is an error.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`]. Phase A: always
|
/// [`Error::TooLarge`] over [`packet::MAX_AUDIO_PACKET_BYTES`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
crate::util::cap("audio datagram", packet::MAX_AUDIO_PACKET_BYTES, datagram.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let Ok(p) = parse_audio_packet(datagram) else { return self.drop_packet() };
|
||||||
|
match p {
|
||||||
|
AudioPacket::Data { rtp, payload } => {
|
||||||
|
let seq = rtp.sequence;
|
||||||
|
if !self.admit(seq, seq) {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
let opus = match &self.config.cipher {
|
||||||
|
Some(c) => match c.decrypt(seq, payload) {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(_) => return self.drop_packet(),
|
||||||
|
},
|
||||||
|
None => payload.to_vec(),
|
||||||
|
};
|
||||||
|
let slot = self.blocks.entry(block_base(seq)).or_default().data.get_mut(usize::from(seq & 3));
|
||||||
|
match slot {
|
||||||
|
Some(s) if s.is_none() => {
|
||||||
|
*s = Some(Data {
|
||||||
|
shard: payload.to_vec(),
|
||||||
|
opus,
|
||||||
|
timestamp_ms: rtp.timestamp,
|
||||||
|
arrived: now,
|
||||||
|
recovered: false,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => return self.drop_packet(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
AudioPacket::Parity { fec, parity, .. } => {
|
||||||
|
let base = fec.base_sequence;
|
||||||
|
if base & 3 != 0 || fec.payload_type != packet::AUDIO_PAYLOAD_TYPE {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
if self.code.is_none() {
|
||||||
|
self.stats.packets += 1;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if !self.admit(base, base.wrapping_add(3)) {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
let slot = self.blocks.entry(base).or_default().parity.get_mut(usize::from(fec.shard_index));
|
||||||
|
match slot {
|
||||||
|
Some(s) if s.is_none() => {
|
||||||
|
*s = Some(Parity { shard: parity.to_vec(), base_timestamp: fec.base_timestamp, arrived: now });
|
||||||
|
}
|
||||||
|
_ => return self.drop_packet(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.stats.packets += 1;
|
||||||
|
self.advance(now);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a packet covering `first..=last` may be stored: not entirely in the past, not too far ahead. A packet
|
||||||
|
/// ahead of the block window first moves the window up (the blocks it passes are emitted or reported lost).
|
||||||
|
fn admit(&mut self, first: u16, last: u16) -> bool {
|
||||||
|
let next = *self.next.get_or_insert(block_base(first));
|
||||||
|
if last.wrapping_sub(next) >= 0x8000 {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let ahead = first.wrapping_sub(next);
|
||||||
|
if (MAX_PACKETS_AHEAD..0x8000).contains(&ahead) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let window = (MAX_BLOCKS_IN_FLIGHT * DATA_SHARDS) as u16;
|
||||||
|
if block_base(first).wrapping_sub(block_base(next)) < 0x8000
|
||||||
|
&& block_base(first).wrapping_sub(block_base(next)) >= window
|
||||||
|
{
|
||||||
|
self.flush_until(block_base(first).wrapping_sub(window - DATA_SHARDS as u16));
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits or reports lost every sequence number before `target`, at once.
|
||||||
|
fn flush_until(&mut self, target: u16) {
|
||||||
|
while let Some(n) = self.next {
|
||||||
|
if target.wrapping_sub(n) == 0 || target.wrapping_sub(n) >= 0x8000 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if !self.emit_if_available(n) {
|
||||||
|
self.events.push_back(AudioEvent::Lost { sequence: n });
|
||||||
|
self.stats.lost += 1;
|
||||||
|
self.step(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits `n` if it was received or can be rebuilt now.
|
||||||
|
fn emit_if_available(&mut self, n: u16) -> bool {
|
||||||
|
let base = block_base(n);
|
||||||
|
let index = usize::from(n & 3);
|
||||||
|
let present = |s: &Self| s.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some);
|
||||||
|
if present(self) || (self.recover(base) && present(self)) {
|
||||||
|
self.emit_present(n, base, index);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Emits in sequence order: received packets at once; a missing packet waits for the jitter budget
|
||||||
|
/// (`loss_timeout`), since a late packet beats a rebuilt one, and is then rebuilt or reported lost.
|
||||||
|
fn advance(&mut self, now: Instant) {
|
||||||
|
let timeout = self.config.loss_timeout;
|
||||||
|
while let Some(n) = self.next {
|
||||||
|
let base = block_base(n);
|
||||||
|
let index = usize::from(n & 3);
|
||||||
|
if self.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some) {
|
||||||
|
self.emit_present(n, base, index);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(start) = self.earliest_after(n, base, index) else { return };
|
||||||
|
if start.saturating_add(timeout) > now {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self.emit_if_available(n) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
self.events.push_back(AudioEvent::Lost { sequence: n });
|
||||||
|
self.stats.lost += 1;
|
||||||
|
self.step(n);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_present(&mut self, n: u16, base: u16, index: usize) {
|
||||||
|
// The shard stays in the block: a later packet of the same block may still need it to be rebuilt.
|
||||||
|
if let Some(d) = self.blocks.get_mut(&base).and_then(|b| b.data.get_mut(index)).and_then(Option::as_mut) {
|
||||||
|
if d.recovered {
|
||||||
|
self.stats.recovered += 1;
|
||||||
|
}
|
||||||
|
let opus = core::mem::take(&mut d.opus);
|
||||||
|
self.events.push_back(AudioEvent::Packet {
|
||||||
|
sequence: n,
|
||||||
|
timestamp_ms: d.timestamp_ms,
|
||||||
|
opus,
|
||||||
|
recovered: d.recovered,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.step(n);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves past `n`, dropping its block once its last data packet is done.
|
||||||
|
fn step(&mut self, n: u16) {
|
||||||
|
if n & 3 == 3 {
|
||||||
|
self.blocks.remove(&block_base(n));
|
||||||
|
}
|
||||||
|
self.next = Some(n.wrapping_add(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The earliest arrival of anything stored after sequence `n`: when the wait for `n` began.
|
||||||
|
fn earliest_after(&self, n: u16, base: u16, index: usize) -> Option<Instant> {
|
||||||
|
let own = self.blocks.get(&base).and_then(|b| b.earliest_after(index));
|
||||||
|
let later = self
|
||||||
|
.blocks
|
||||||
|
.iter()
|
||||||
|
.filter(|(b, _)| b.wrapping_sub(base) != 0 && b.wrapping_sub(n) < 0x8000)
|
||||||
|
.filter_map(|(_, blk)| {
|
||||||
|
blk.data.iter().flatten().map(|d| d.arrived).chain(blk.parity.iter().flatten().map(|p| p.arrived)).min()
|
||||||
|
})
|
||||||
|
.min();
|
||||||
|
match (own, later) {
|
||||||
|
(Some(a), Some(b)) => Some(a.min(b)),
|
||||||
|
(a, b) => a.or(b),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Rebuilds the missing data packets of block `base` when FEC is on and 4 equal-length shards are there.
|
||||||
|
fn recover(&mut self, base: u16) -> bool {
|
||||||
|
let Some(code) = &self.code else { return false };
|
||||||
|
let Some(block) = self.blocks.get(&base) else { return false };
|
||||||
|
let len = block
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|d| d.shard.len())
|
||||||
|
.next()
|
||||||
|
.or_else(|| block.parity.iter().flatten().map(|p| p.shard.len()).next());
|
||||||
|
let Some(len) = len else { return false };
|
||||||
|
let mut shards: Vec<Option<Vec<u8>>> = block
|
||||||
|
.data
|
||||||
|
.iter()
|
||||||
|
.map(|d| d.as_ref().filter(|d| d.shard.len() == len).map(|d| d.shard.clone()))
|
||||||
|
.chain(block.parity.iter().map(|p| p.as_ref().filter(|p| p.shard.len() == len).map(|p| p.shard.clone())))
|
||||||
|
.collect();
|
||||||
|
if shards.iter().flatten().count() < DATA_SHARDS || block.data.iter().all(Option::is_some) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if code.reconstruct(&mut shards).is_err() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let base_ts = block
|
||||||
|
.parity
|
||||||
|
.iter()
|
||||||
|
.flatten()
|
||||||
|
.map(|p| p.base_timestamp)
|
||||||
|
.next()
|
||||||
|
.or_else(|| {
|
||||||
|
block.data.iter().enumerate().find_map(|(i, d)| {
|
||||||
|
d.as_ref()
|
||||||
|
.map(|d| d.timestamp_ms.wrapping_sub(i as u32 * u32::from(self.config.packet_duration_ms)))
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.unwrap_or(0);
|
||||||
|
let duration = u32::from(self.config.packet_duration_ms);
|
||||||
|
let mut rebuilt = Vec::new();
|
||||||
|
for (i, shard) in shards.into_iter().take(DATA_SHARDS).enumerate() {
|
||||||
|
if block.data.get(i).is_some_and(Option::is_some) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let Some(shard) = shard else { continue };
|
||||||
|
let seq = base.wrapping_add(i as u16);
|
||||||
|
let opus = match &self.config.cipher {
|
||||||
|
Some(c) => match c.decrypt(seq, &shard) {
|
||||||
|
Ok(o) => o,
|
||||||
|
Err(_) => continue,
|
||||||
|
},
|
||||||
|
None => shard.clone(),
|
||||||
|
};
|
||||||
|
rebuilt.push((
|
||||||
|
i,
|
||||||
|
Data {
|
||||||
|
shard,
|
||||||
|
opus,
|
||||||
|
timestamp_ms: base_ts.wrapping_add(i as u32 * duration),
|
||||||
|
arrived: Instant::ZERO,
|
||||||
|
recovered: true,
|
||||||
|
},
|
||||||
|
));
|
||||||
|
}
|
||||||
|
let any = !rebuilt.is_empty();
|
||||||
|
if let Some(block) = self.blocks.get_mut(&base) {
|
||||||
|
for (i, d) in rebuilt {
|
||||||
|
if let Some(slot) = block.data.get_mut(i) {
|
||||||
|
*slot = Some(d);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
any
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<AudioEvent> {
|
pub fn poll_event(&mut self) -> Option<AudioEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When a missing packet times out.
|
/// When a missing packet times out.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
let n = self.next?;
|
||||||
|
let base = block_base(n);
|
||||||
|
let index = usize::from(n & 3);
|
||||||
|
if self.blocks.get(&base).and_then(|b| b.data.get(index)).is_some_and(Option::is_some) {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.earliest_after(n, base, index).map(|t| t.saturating_add(self.config.loss_timeout))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Reports timed-out packets as lost.
|
/// Reports timed-out packets as lost.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
self.advance(now);
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Counters.
|
/// Counters.
|
||||||
|
|||||||
@@ -52,9 +52,34 @@ pub enum AudioPacket<'a> {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_AUDIO_PACKET_BYTES`], [`crate::Error::Truncated`] for a cut header or an
|
/// [`crate::Error::TooLarge`] over [`MAX_AUDIO_PACKET_BYTES`], [`crate::Error::Truncated`] for a cut header or an
|
||||||
/// empty payload, [`crate::Error::UnexpectedValue`] for another payload type or a parity shard index above 1.
|
/// empty payload, [`crate::Error::UnexpectedValue`] for another RTP version or payload type, or a parity shard
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// index above 1.
|
||||||
pub fn parse_audio_packet(packet: &[u8]) -> crate::Result<AudioPacket<'_>> {
|
pub fn parse_audio_packet(packet: &[u8]) -> crate::Result<AudioPacket<'_>> {
|
||||||
let _ = packet;
|
use crate::util::{byte, need, u16_be, u32_be};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "audio packet";
|
||||||
|
crate::util::cap(W, MAX_AUDIO_PACKET_BYTES, packet.len())?;
|
||||||
|
let rtp = crate::rtp::parse_rtp_header(packet)?;
|
||||||
|
let at = crate::rtp::RTP_HEADER_LEN;
|
||||||
|
match rtp.payload_type {
|
||||||
|
AUDIO_PAYLOAD_TYPE => {
|
||||||
|
need(W, at + 1, packet.len())?;
|
||||||
|
Ok(AudioPacket::Data { rtp, payload: packet.get(at..).unwrap_or(&[]) })
|
||||||
|
}
|
||||||
|
AUDIO_FEC_PAYLOAD_TYPE => {
|
||||||
|
need(W, at + AUDIO_FEC_HEADER_LEN + 1, packet.len())?;
|
||||||
|
let shard_index = byte(W, packet, at)?;
|
||||||
|
if shard_index > 1 {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "audio parity shard", value: shard_index.into() });
|
||||||
|
}
|
||||||
|
let fec = AudioFecHeader {
|
||||||
|
shard_index,
|
||||||
|
payload_type: byte(W, packet, at + 1)?,
|
||||||
|
base_sequence: u16_be(W, packet, at + 2)?,
|
||||||
|
base_timestamp: u32_be(W, packet, at + 4)?,
|
||||||
|
ssrc: u32_be(W, packet, at + 8)?,
|
||||||
|
};
|
||||||
|
Ok(AudioPacket::Parity { rtp, fec, parity: packet.get(at + AUDIO_FEC_HEADER_LEN..).unwrap_or(&[]) })
|
||||||
|
}
|
||||||
|
other => Err(crate::Error::UnexpectedValue { what: "audio payload type", value: other.into() }),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,7 +8,11 @@
|
|||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
|
||||||
use crate::Result;
|
use aes_gcm::Aes128Gcm;
|
||||||
|
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||||||
|
|
||||||
|
use crate::util::{array, cap, malformed, u16_le, u32_le};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Type field of an encrypted frame.
|
/// Type field of an encrypted frame.
|
||||||
pub const ENCRYPTED_FRAME_TYPE: u16 = 0x0001;
|
pub const ENCRYPTED_FRAME_TYPE: u16 = 0x0001;
|
||||||
@@ -35,10 +39,20 @@ pub enum Direction {
|
|||||||
/// The nonce for sequence number `sequence` in `direction`.
|
/// The nonce for sequence number `sequence` in `direction`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> {
|
pub fn nonce(sequence: u32, direction: Direction) -> Result<[u8; NONCE_LEN]> {
|
||||||
let _ = (sequence, direction);
|
let mut n = [0u8; NONCE_LEN];
|
||||||
Err(crate::Error::Unimplemented)
|
let [a, b, c, d] = sequence.to_le_bytes();
|
||||||
|
n[0] = a;
|
||||||
|
n[1] = b;
|
||||||
|
n[2] = c;
|
||||||
|
n[3] = d;
|
||||||
|
n[10] = match direction {
|
||||||
|
Direction::ClientToHost => b'C',
|
||||||
|
Direction::HostToClient => b'H',
|
||||||
|
};
|
||||||
|
n[11] = b'C';
|
||||||
|
Ok(n)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A frame split into its fields, not yet decrypted.
|
/// A frame split into its fields, not yet decrypted.
|
||||||
@@ -55,45 +69,78 @@ pub struct EncryptedFrame<'a> {
|
|||||||
/// Splits a frame (one ENet packet) into its fields. The length field must match the bytes present exactly.
|
/// Splits a frame (one ENet packet) into its fields. The length field must match the bytes present exactly.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`crate::Error::Truncated`] under [`MIN_FRAME_BYTES`],
|
/// [`Error::TooLarge`] over [`MAX_FRAME_BYTES`], [`Error::Truncated`] under [`MIN_FRAME_BYTES`],
|
||||||
/// [`crate::Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`crate::Error::Malformed`]
|
/// [`Error::UnexpectedValue`] for a type other than [`ENCRYPTED_FRAME_TYPE`], [`Error::Malformed`] for a length
|
||||||
/// for a length that does not match. Phase A: always [`crate::Error::Unimplemented`].
|
/// that does not match.
|
||||||
pub fn parse_encrypted_frame(frame: &[u8]) -> Result<EncryptedFrame<'_>> {
|
pub fn parse_encrypted_frame(frame: &[u8]) -> Result<EncryptedFrame<'_>> {
|
||||||
let _ = frame;
|
const W: &str = "control frame";
|
||||||
Err(crate::Error::Unimplemented)
|
cap(W, MAX_FRAME_BYTES, frame.len())?;
|
||||||
|
crate::util::need(W, MIN_FRAME_BYTES, frame.len())?;
|
||||||
|
let kind = u16_le(W, frame, 0)?;
|
||||||
|
if kind != ENCRYPTED_FRAME_TYPE {
|
||||||
|
return Err(Error::UnexpectedValue { what: "control frame type", value: kind.into() });
|
||||||
|
}
|
||||||
|
if usize::from(u16_le(W, frame, 2)?) != frame.len() - 4 {
|
||||||
|
return Err(malformed("control frame length"));
|
||||||
|
}
|
||||||
|
Ok(EncryptedFrame {
|
||||||
|
sequence: u32_le(W, frame, 4)?,
|
||||||
|
tag: array::<GCM_TAG_LEN>(W, frame, 8)?,
|
||||||
|
ciphertext: frame.get(FRAME_HEADER_LEN..).unwrap_or(&[]),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key.
|
/// AES-128-GCM with the session's `rikey`. `Debug` never prints the key.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ControlCipher {
|
pub struct ControlCipher {
|
||||||
key: [u8; 16],
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ControlCipher {
|
impl ControlCipher {
|
||||||
/// A cipher for `rikey`.
|
/// A cipher for `rikey`.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new(rikey: [u8; 16]) -> Self {
|
pub fn new(rikey: [u8; 16]) -> Self {
|
||||||
Self { key: rikey }
|
Self { key: zeroize::Zeroizing::new(rikey) }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn aead(&self) -> Aes128Gcm {
|
||||||
|
Aes128Gcm::new((&*self.key).into())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encrypts one message (plaintext = type, length, body) into a whole frame.
|
/// Encrypts one message (plaintext = type, length, body) into a whole frame.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]. Phase A: always
|
/// [`Error::TooLarge`] when the frame would exceed [`MAX_FRAME_BYTES`]; [`Error::Crypto`] if sealing fails.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result<Vec<u8>> {
|
pub fn seal(&self, sequence: u32, direction: Direction, plaintext: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (sequence, direction, plaintext, &self.key);
|
cap("control frame", MAX_FRAME_BYTES, FRAME_HEADER_LEN.saturating_add(plaintext.len()))?;
|
||||||
Err(crate::Error::Unimplemented)
|
let n = nonce(sequence, direction)?;
|
||||||
|
let mut body = plaintext.to_vec();
|
||||||
|
let tag = self
|
||||||
|
.aead()
|
||||||
|
.encrypt_inout_detached(&n.into(), b"", body.as_mut_slice().into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
let len = u16::try_from(4 + GCM_TAG_LEN + body.len()).map_err(|_| malformed("control frame length"))?;
|
||||||
|
let mut out = Vec::with_capacity(FRAME_HEADER_LEN + body.len());
|
||||||
|
out.extend_from_slice(&ENCRYPTED_FRAME_TYPE.to_le_bytes());
|
||||||
|
out.extend_from_slice(&len.to_le_bytes());
|
||||||
|
out.extend_from_slice(&sequence.to_le_bytes());
|
||||||
|
out.extend_from_slice(tag.as_slice());
|
||||||
|
out.extend_from_slice(&body);
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks and decrypts one frame; returns its sequence number and the plaintext message.
|
/// Checks and decrypts one frame; returns its sequence number and the plaintext message.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Parser errors as [`parse_encrypted_frame`]; [`crate::Error::Crypto`] when the tag does not verify. Phase A:
|
/// Parser errors as [`parse_encrypted_frame`]; [`Error::Crypto`] when the tag does not verify.
|
||||||
/// always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec<u8>)> {
|
pub fn open(&self, direction: Direction, frame: &[u8]) -> Result<(u32, Vec<u8>)> {
|
||||||
let _ = (direction, frame);
|
let f = parse_encrypted_frame(frame)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let n = nonce(f.sequence, direction)?;
|
||||||
|
let mut body = f.ciphertext.to_vec();
|
||||||
|
self.aead()
|
||||||
|
.decrypt_inout_detached(&n.into(), b"", body.as_mut_slice().into(), &f.tag.into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
Ok((f.sequence, body))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
use crate::Result;
|
use crate::Result;
|
||||||
use crate::input::InputEvent;
|
use crate::input::InputEvent;
|
||||||
|
use crate::util::{byte, cap, malformed, need, u16_le, u32_be};
|
||||||
|
|
||||||
/// Length of the message header (type + length).
|
/// Length of the message header (type + length).
|
||||||
pub const MESSAGE_HEADER_LEN: usize = 4;
|
pub const MESSAGE_HEADER_LEN: usize = 4;
|
||||||
@@ -48,14 +49,37 @@ pub enum MessageType {
|
|||||||
TriggerEffect = 0x5503,
|
TriggerEffect = 0x5503,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl MessageType {
|
||||||
|
const ALL: [Self; 16] = [
|
||||||
|
Self::StartA,
|
||||||
|
Self::StartB,
|
||||||
|
Self::InvalidateRefFrames,
|
||||||
|
Self::IdrFrame,
|
||||||
|
Self::LossStats,
|
||||||
|
Self::FrameStats,
|
||||||
|
Self::InputData,
|
||||||
|
Self::PeriodicPing,
|
||||||
|
Self::Termination,
|
||||||
|
Self::TerminationExtended,
|
||||||
|
Self::HdrMode,
|
||||||
|
Self::RumbleData,
|
||||||
|
Self::RumbleTriggers,
|
||||||
|
Self::MotionEvent,
|
||||||
|
Self::RgbLed,
|
||||||
|
Self::TriggerEffect,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
impl TryFrom<u16> for MessageType {
|
impl TryFrom<u16> for MessageType {
|
||||||
type Error = crate::Error;
|
type Error = crate::Error;
|
||||||
|
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] for an unknown code. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::UnexpectedValue`] for an unknown code.
|
||||||
fn try_from(code: u16) -> Result<Self> {
|
fn try_from(code: u16) -> Result<Self> {
|
||||||
let _ = code;
|
Self::ALL
|
||||||
Err(crate::Error::Unimplemented)
|
.into_iter()
|
||||||
|
.find(|t| *t as u16 == code)
|
||||||
|
.ok_or(crate::Error::UnexpectedValue { what: "control message type", value: code.into() })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,11 +96,16 @@ pub struct RawMessage<'a> {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
/// [`crate::Error::TooLarge`] over [`MAX_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
||||||
/// [`MESSAGE_HEADER_LEN`], [`crate::Error::Malformed`] for a length that does not match. Phase A: always
|
/// [`MESSAGE_HEADER_LEN`], [`crate::Error::Malformed`] for a length that does not match.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_message(message: &[u8]) -> Result<RawMessage<'_>> {
|
pub fn parse_message(message: &[u8]) -> Result<RawMessage<'_>> {
|
||||||
let _ = message;
|
const W: &str = "control message";
|
||||||
Err(crate::Error::Unimplemented)
|
cap(W, MAX_MESSAGE_BYTES, message.len())?;
|
||||||
|
need(W, MESSAGE_HEADER_LEN, message.len())?;
|
||||||
|
let message_type = u16_le(W, message, 0)?;
|
||||||
|
if usize::from(u16_le(W, message, 2)?) != message.len() - MESSAGE_HEADER_LEN {
|
||||||
|
return Err(malformed("control message length"));
|
||||||
|
}
|
||||||
|
Ok(RawMessage { message_type, body: message.get(MESSAGE_HEADER_LEN..).unwrap_or(&[]) })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Motion sensor kinds of `MOTION_EVENT`.
|
/// Motion sensor kinds of `MOTION_EVENT`.
|
||||||
@@ -169,14 +198,70 @@ pub enum HostMessage {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Interprets a decrypted message from the host.
|
fn exact(body: &[u8], len: usize, what: &'static str) -> Result<()> {
|
||||||
|
if body.len() == len { Ok(()) } else { Err(malformed(what)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Interprets a decrypted message from the host. Bodies are little-endian (UNKNOWN U23), except the extended
|
||||||
|
/// termination code (big-endian).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`parse_message`]; [`crate::Error::Malformed`] when a known type's body has the wrong length;
|
/// As [`parse_message`]; [`crate::Error::Malformed`] when a known type's body has the wrong length;
|
||||||
/// [`crate::Error::UnexpectedValue`] for an unknown motion kind. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::UnexpectedValue`] for an unknown motion kind.
|
||||||
pub fn parse_host_message(message: &[u8]) -> Result<HostMessage> {
|
pub fn parse_host_message(message: &[u8]) -> Result<HostMessage> {
|
||||||
let _ = message;
|
const W: &str = "host message";
|
||||||
Err(crate::Error::Unimplemented)
|
let raw = parse_message(message)?;
|
||||||
|
let b = raw.body;
|
||||||
|
let u16_at = |at: usize| u16_le(W, b, at);
|
||||||
|
Ok(match raw.message_type {
|
||||||
|
0x010b => {
|
||||||
|
exact(b, 10, "rumble body")?;
|
||||||
|
HostMessage::Rumble { controller: u16_at(4)?, low_frequency: u16_at(6)?, high_frequency: u16_at(8)? }
|
||||||
|
}
|
||||||
|
0x5500 => {
|
||||||
|
exact(b, 6, "trigger rumble body")?;
|
||||||
|
HostMessage::RumbleTriggers { controller: u16_at(0)?, left: u16_at(2)?, right: u16_at(4)? }
|
||||||
|
}
|
||||||
|
0x5501 => {
|
||||||
|
exact(b, 5, "motion event body")?;
|
||||||
|
let kind = match byte(W, b, 4)? {
|
||||||
|
1 => MotionKind::Accelerometer,
|
||||||
|
2 => MotionKind::Gyroscope,
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "motion kind", value: other.into() }),
|
||||||
|
};
|
||||||
|
HostMessage::MotionEvent { controller: u16_at(0)?, rate_hz: u16_at(2)?, kind }
|
||||||
|
}
|
||||||
|
0x5502 => {
|
||||||
|
exact(b, 5, "rgb led body")?;
|
||||||
|
HostMessage::RgbLed { controller: u16_at(0)?, r: byte(W, b, 2)?, g: byte(W, b, 3)?, b: byte(W, b, 4)? }
|
||||||
|
}
|
||||||
|
0x0109 => {
|
||||||
|
exact(b, 4, "termination body")?;
|
||||||
|
HostMessage::Termination { error_code: Some(u32_be(W, b, 0)?) }
|
||||||
|
}
|
||||||
|
0x0100 => HostMessage::Termination { error_code: None },
|
||||||
|
0x010e => {
|
||||||
|
let enabled = byte(W, b, 0).map_err(|_| malformed("hdr mode body"))? != 0;
|
||||||
|
let metadata = match b.len() {
|
||||||
|
1 => None,
|
||||||
|
31 => {
|
||||||
|
let v = |i: usize| u16_le(W, b, 1 + 2 * i);
|
||||||
|
Some(HdrMetadata {
|
||||||
|
display_primaries: [(v(0)?, v(1)?), (v(2)?, v(3)?), (v(4)?, v(5)?)],
|
||||||
|
white_point: (v(6)?, v(7)?),
|
||||||
|
max_display_luminance: v(8)?,
|
||||||
|
min_display_luminance: v(9)?,
|
||||||
|
max_content_light_level: v(10)?,
|
||||||
|
max_frame_average_light_level: v(11)?,
|
||||||
|
max_full_frame_luminance: v(12)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("hdr mode body")),
|
||||||
|
};
|
||||||
|
HostMessage::HdrMode { enabled, metadata }
|
||||||
|
}
|
||||||
|
other => HostMessage::Other { message_type: other, body_len: b.len() },
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A message to the host.
|
/// A message to the host.
|
||||||
@@ -204,9 +289,26 @@ pub enum ClientMessage {
|
|||||||
/// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`].
|
/// Serializes a message to the host (type, length, body), ready for [`super::ControlCipher::seal`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN; input errors as
|
/// [`crate::Error::Unsupported`] for a message whose body is still UNKNOWN (U10: START_A, START_B,
|
||||||
/// [`crate::input::encode_input`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// PERIODIC_PING, IDR request; refused rather than guessed); input errors as [`crate::input::encode_input`].
|
||||||
pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
|
pub fn encode_client_message(message: &ClientMessage) -> Result<Vec<u8>> {
|
||||||
let _ = message;
|
match message {
|
||||||
Err(crate::Error::Unimplemented)
|
ClientMessage::InvalidateRefFrames { first, last } => {
|
||||||
|
let mut m = Vec::with_capacity(28);
|
||||||
|
m.extend_from_slice(&(MessageType::InvalidateRefFrames as u16).to_le_bytes());
|
||||||
|
m.extend_from_slice(&24u16.to_le_bytes());
|
||||||
|
m.extend_from_slice(&first.to_le_bytes());
|
||||||
|
m.extend_from_slice(&[0; 4]);
|
||||||
|
m.extend_from_slice(&last.to_le_bytes());
|
||||||
|
m.extend_from_slice(&[0; 12]);
|
||||||
|
Ok(m)
|
||||||
|
}
|
||||||
|
ClientMessage::Input(e) => crate::input::encode_input(e),
|
||||||
|
ClientMessage::StartA
|
||||||
|
| ClientMessage::StartB
|
||||||
|
| ClientMessage::PeriodicPing
|
||||||
|
| ClientMessage::RequestIdrFrame => {
|
||||||
|
Err(crate::Error::Unsupported { what: "a control message whose body is still UNKNOWN (U10)" })
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,9 @@
|
|||||||
//! [`HostMessage`]s.
|
//! [`HostMessage`]s.
|
||||||
|
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
|
use std::collections::VecDeque;
|
||||||
|
|
||||||
use crate::enet::EnetConfig;
|
use crate::enet::{Delivery, EnetClient, EnetConfig, EnetEvent};
|
||||||
use crate::{Instant, RandomSource, Result};
|
use crate::{Instant, RandomSource, Result};
|
||||||
|
|
||||||
pub mod frame;
|
pub mod frame;
|
||||||
@@ -54,71 +55,113 @@ pub enum ControlEvent {
|
|||||||
/// One control stream.
|
/// One control stream.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct ControlStream {
|
pub struct ControlStream {
|
||||||
next_sequence: u32,
|
enet: EnetClient,
|
||||||
|
cipher: ControlCipher,
|
||||||
|
/// Next sequence number to seal with; `u32::MAX + 1` once the space is used up.
|
||||||
|
next_sequence: u64,
|
||||||
|
/// Highest host sequence number accepted so far.
|
||||||
|
last_host_sequence: Option<u32>,
|
||||||
|
events: VecDeque<ControlEvent>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl ControlStream {
|
impl ControlStream {
|
||||||
/// Starts connecting.
|
/// Starts connecting.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`crate::enet::EnetClient::connect`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// As [`crate::enet::EnetClient::connect`].
|
||||||
pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn connect(config: ControlConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = (config, now, rng);
|
Ok(Self {
|
||||||
Err(crate::Error::Unimplemented)
|
enet: EnetClient::connect(config.enet, now, rng)?,
|
||||||
|
cipher: ControlCipher::new(config.rikey),
|
||||||
|
next_sequence: 0,
|
||||||
|
last_host_sequence: None,
|
||||||
|
events: VecDeque::new(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves ENet events into control events, opening every host frame.
|
||||||
|
fn drain(&mut self) {
|
||||||
|
while let Some(e) = self.enet.poll_event() {
|
||||||
|
let event = match e {
|
||||||
|
EnetEvent::Connected => ControlEvent::Connected,
|
||||||
|
EnetEvent::Disconnected { .. } => ControlEvent::Disconnected,
|
||||||
|
EnetEvent::TimedOut => ControlEvent::TimedOut,
|
||||||
|
EnetEvent::Received { data, .. } => self.open(&data),
|
||||||
|
};
|
||||||
|
self.events.push_back(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Opens one host frame. A frame that fails, or whose number is not above the last accepted one, is dropped
|
||||||
|
/// without touching the replay state; a frame that opens moves it forward even if its message is unknown.
|
||||||
|
fn open(&mut self, frame: &[u8]) -> ControlEvent {
|
||||||
|
let Ok((sequence, plain)) = self.cipher.open(Direction::HostToClient, frame) else {
|
||||||
|
return ControlEvent::Dropped;
|
||||||
|
};
|
||||||
|
if self.last_host_sequence.is_some_and(|last| sequence <= last) {
|
||||||
|
return ControlEvent::Dropped;
|
||||||
|
}
|
||||||
|
self.last_host_sequence = Some(sequence);
|
||||||
|
parse_host_message(&plain).map_or(ControlEvent::Dropped, ControlEvent::Message)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one datagram from the control port.
|
/// Feeds one datagram from the control port.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`crate::enet::EnetClient::handle_datagram`]. Bad frames inside a good datagram are not errors; they
|
/// As [`crate::enet::EnetClient::handle_datagram`]. Bad frames inside a good datagram are not errors; they
|
||||||
/// become [`ControlEvent::Dropped`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// become [`ControlEvent::Dropped`].
|
||||||
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
let r = self.enet.handle_datagram(now, datagram);
|
||||||
Err(crate::Error::Unimplemented)
|
self.drain();
|
||||||
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Seals and queues a message (reliable, channel 0 unless measurement says otherwise).
|
/// Seals and queues a message (reliable, channel 0 unless measurement says otherwise).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`message::encode_client_message`] and [`crate::enet::EnetClient::send`]; [`crate::Error::Closed`] once
|
/// As [`message::encode_client_message`] and [`crate::enet::EnetClient::send`]; [`crate::Error::Closed`] once
|
||||||
/// the sequence space is used up (2^32 messages). Phase A: always [`crate::Error::Unimplemented`].
|
/// the sequence space is used up (2^32 messages).
|
||||||
pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> {
|
pub fn send(&mut self, now: Instant, message: &ClientMessage) -> Result<()> {
|
||||||
let _ = (now, message, self.next_sequence);
|
let plain = message::encode_client_message(message)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let sequence = u32::try_from(self.next_sequence).map_err(|_| crate::Error::Closed)?;
|
||||||
|
let frame = self.cipher.seal(sequence, Direction::ClientToHost, &plain)?;
|
||||||
|
self.enet.send(now, 0, Delivery::Reliable, &frame)?;
|
||||||
|
self.next_sequence += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next datagram to send.
|
/// The next datagram to send.
|
||||||
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
||||||
let _ = now;
|
self.enet.poll_transmit(now)
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<ControlEvent> {
|
pub fn poll_event(&mut self) -> Option<ControlEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When [`Self::handle_timeout`] is due.
|
/// When [`Self::handle_timeout`] is due.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
self.enet.poll_timeout()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Advances timers (ENet, periodic ping).
|
/// Advances timers (ENet). `PERIODIC_PING` is not sent while its body is UNKNOWN (U10); ENet's own pings keep
|
||||||
|
/// the connection alive.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// As [`crate::enet::EnetClient::handle_timeout`].
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
let r = self.enet.handle_timeout(now);
|
||||||
Err(crate::Error::Unimplemented)
|
self.drain();
|
||||||
|
r
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Closes the stream gracefully.
|
/// Closes the stream gracefully.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Closed`] when already closed. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Closed`] when already closed.
|
||||||
pub fn close(&mut self, now: Instant) -> Result<()> {
|
pub fn close(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
self.enet.disconnect(now, 0)
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,18 @@
|
|||||||
//! while let Some(e) = peer.poll_event() { … }
|
//! while let Some(e) = peer.poll_event() { … }
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Reliable packets are delivered in order per channel; duplicates and stale sequence numbers are acknowledged but
|
||||||
|
//! never delivered twice; sequence numbers too far ahead are dropped. Fragments are reassembled with every length
|
||||||
|
//! checked against [`MAX_PACKET_BYTES`] before memory is reserved.
|
||||||
|
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
|
use std::collections::{BTreeMap, VecDeque};
|
||||||
|
|
||||||
use crate::{Instant, RandomSource, Result};
|
use protocol::{Command, CommandBody, ConnectParams, Datagram, Fragment, MAX_DATAGRAM_BYTES, MIN_MTU, NO_PEER_ID};
|
||||||
|
|
||||||
|
use crate::util::malformed;
|
||||||
|
use crate::{Error, Instant, RandomSource, Result};
|
||||||
|
|
||||||
pub mod protocol;
|
pub mod protocol;
|
||||||
|
|
||||||
@@ -24,6 +32,25 @@ pub const MAX_PACKET_BYTES: usize = 64 * 1024;
|
|||||||
pub const MAX_SEND_QUEUE: usize = 1024;
|
pub const MAX_SEND_QUEUE: usize = 1024;
|
||||||
/// Maximum number of reliable commands waiting for an acknowledgement.
|
/// Maximum number of reliable commands waiting for an acknowledgement.
|
||||||
pub const MAX_IN_FLIGHT: usize = 256;
|
pub const MAX_IN_FLIGHT: usize = 256;
|
||||||
|
/// Reliable sequence numbers accepted ahead of the next expected one (7 of ENet's 4096-wide windows).
|
||||||
|
pub const RELIABLE_WINDOW: u16 = 0x7000;
|
||||||
|
/// Out-of-order reliable commands kept per channel while waiting for a gap to fill.
|
||||||
|
pub const MAX_PENDING_PER_CHANNEL: usize = 1024;
|
||||||
|
/// Packets being reassembled at once; the oldest is dropped when another starts.
|
||||||
|
pub const MAX_REASSEMBLIES: usize = 4;
|
||||||
|
/// Acknowledgements kept for sending; beyond this the oldest are dropped (the host retransmits).
|
||||||
|
pub const MAX_PENDING_ACKS: usize = 4096;
|
||||||
|
|
||||||
|
/// Channel id of connection-level commands.
|
||||||
|
const CONNECTION_CHANNEL: u8 = 0xFF;
|
||||||
|
/// Our peer id towards the host (we are the only peer of this client).
|
||||||
|
const LOCAL_PEER_ID: u16 = 0;
|
||||||
|
/// Window size we offer (ENet's maximum, as for unlimited bandwidth).
|
||||||
|
const WINDOW_SIZE: u32 = 65_536;
|
||||||
|
/// Retransmission timeout before any round trip is measured (stock ENet's initial round-trip time).
|
||||||
|
const INITIAL_RTO: Duration = Duration::from_millis(500);
|
||||||
|
const MIN_RTO: Duration = Duration::from_millis(100);
|
||||||
|
const MAX_RTO: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
/// How a packet is delivered.
|
/// How a packet is delivered.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -86,79 +113,614 @@ pub enum EnetEvent {
|
|||||||
TimedOut,
|
TimedOut,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A reliable command in the sequence stream of a channel, as it will be processed in order.
|
||||||
|
#[derive(Debug)]
|
||||||
|
enum Pending {
|
||||||
|
Data(Vec<u8>),
|
||||||
|
Fragment(Fragment),
|
||||||
|
/// A command that occupies its sequence number but carries nothing usable (a lying fragment).
|
||||||
|
Skip,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Default)]
|
||||||
|
struct Channel {
|
||||||
|
/// Last reliable sequence number we sent.
|
||||||
|
out_reliable: u16,
|
||||||
|
/// Last unreliable sequence number we sent.
|
||||||
|
out_unreliable: u16,
|
||||||
|
/// Last reliable sequence number delivered from the host.
|
||||||
|
in_reliable: u16,
|
||||||
|
/// Last unreliable sequence number delivered from the host.
|
||||||
|
in_unreliable: Option<u16>,
|
||||||
|
pending: BTreeMap<u16, Pending>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Reassembly {
|
||||||
|
channel: u8,
|
||||||
|
start: u16,
|
||||||
|
count: u32,
|
||||||
|
total: u32,
|
||||||
|
got: Vec<bool>,
|
||||||
|
received: u32,
|
||||||
|
data: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct InFlight {
|
||||||
|
command: Command,
|
||||||
|
first_sent: Instant,
|
||||||
|
sent_at: Instant,
|
||||||
|
rto: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A command waiting to be sent; `ends_packet` marks the last command of a user packet (for the queue cap).
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Outgoing {
|
||||||
|
command: Command,
|
||||||
|
ends_packet: bool,
|
||||||
|
}
|
||||||
|
|
||||||
/// The ENet client peer.
|
/// The ENet client peer.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct EnetClient {
|
pub struct EnetClient {
|
||||||
|
config: EnetConfig,
|
||||||
state: EnetState,
|
state: EnetState,
|
||||||
|
connect_id: u32,
|
||||||
|
host_peer_id: u16,
|
||||||
|
out_session: u8,
|
||||||
|
in_session: u8,
|
||||||
|
channel_count: u8,
|
||||||
|
mtu: usize,
|
||||||
|
connection_out_reliable: u16,
|
||||||
|
unsequenced_group: u16,
|
||||||
|
channels: Vec<Channel>,
|
||||||
|
outgoing: VecDeque<Outgoing>,
|
||||||
|
queued_packets: usize,
|
||||||
|
resend: VecDeque<Command>,
|
||||||
|
acks: VecDeque<Command>,
|
||||||
|
in_flight: Vec<InFlight>,
|
||||||
|
reassemblies: Vec<Reassembly>,
|
||||||
|
events: VecDeque<EnetEvent>,
|
||||||
|
last_send: Instant,
|
||||||
|
srtt: Option<Duration>,
|
||||||
|
rttvar: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ms16(t: Instant) -> u16 {
|
||||||
|
((t.as_micros() / 1000) & 0xFFFF) as u16
|
||||||
}
|
}
|
||||||
|
|
||||||
impl EnetClient {
|
impl EnetClient {
|
||||||
/// Starts connecting: queues the connect datagram. The connect id comes from `rng`.
|
/// Starts connecting: queues the connect datagram. The connect id comes from `rng`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a config outside ENet's limits. Phase A: always
|
/// [`Error::Malformed`] for a config outside ENet's limits (MTU 576..=4096, at least one channel).
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn connect(config: EnetConfig, now: Instant, rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = (config, now, rng);
|
if config.mtu < MIN_MTU || usize::from(config.mtu) > MAX_DATAGRAM_BYTES || config.channel_count == 0 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("enet config"));
|
||||||
|
}
|
||||||
|
let mut id = [0u8; 4];
|
||||||
|
rng.fill(&mut id);
|
||||||
|
let connect_id = u32::from_le_bytes(id);
|
||||||
|
let mut c = Self {
|
||||||
|
config,
|
||||||
|
state: EnetState::Connecting,
|
||||||
|
connect_id,
|
||||||
|
host_peer_id: NO_PEER_ID,
|
||||||
|
out_session: 0,
|
||||||
|
in_session: 0,
|
||||||
|
channel_count: config.channel_count,
|
||||||
|
mtu: usize::from(config.mtu),
|
||||||
|
connection_out_reliable: 0,
|
||||||
|
unsequenced_group: 0,
|
||||||
|
channels: (0..config.channel_count).map(|_| Channel::default()).collect(),
|
||||||
|
outgoing: VecDeque::new(),
|
||||||
|
queued_packets: 0,
|
||||||
|
resend: VecDeque::new(),
|
||||||
|
acks: VecDeque::new(),
|
||||||
|
in_flight: Vec::new(),
|
||||||
|
reassemblies: Vec::new(),
|
||||||
|
events: VecDeque::new(),
|
||||||
|
last_send: now,
|
||||||
|
srtt: None,
|
||||||
|
rttvar: Duration::ZERO,
|
||||||
|
};
|
||||||
|
let params = ConnectParams {
|
||||||
|
outgoing_peer_id: LOCAL_PEER_ID,
|
||||||
|
incoming_session_id: 0xFF,
|
||||||
|
outgoing_session_id: 0xFF,
|
||||||
|
mtu: u32::from(config.mtu),
|
||||||
|
window_size: WINDOW_SIZE,
|
||||||
|
channel_count: u32::from(config.channel_count),
|
||||||
|
incoming_bandwidth: 0,
|
||||||
|
outgoing_bandwidth: 0,
|
||||||
|
packet_throttle_interval: 5000,
|
||||||
|
packet_throttle_acceleration: 2,
|
||||||
|
packet_throttle_deceleration: 2,
|
||||||
|
connect_id,
|
||||||
|
};
|
||||||
|
c.queue_connection_command(CommandBody::Connect { params, data: config.connect_data });
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn queue_connection_command(&mut self, body: CommandBody) {
|
||||||
|
self.connection_out_reliable = self.connection_out_reliable.wrapping_add(1);
|
||||||
|
let command = Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: CONNECTION_CHANNEL,
|
||||||
|
reliable_sequence: self.connection_out_reliable,
|
||||||
|
body,
|
||||||
|
};
|
||||||
|
self.outgoing.push_back(Outgoing { command, ends_packet: false });
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rto(&self) -> Duration {
|
||||||
|
match self.srtt {
|
||||||
|
None => INITIAL_RTO,
|
||||||
|
Some(s) => (s + 4 * self.rttvar).clamp(MIN_RTO, MAX_RTO),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn close(&mut self, event: EnetEvent) {
|
||||||
|
self.state = EnetState::Disconnected;
|
||||||
|
self.events.push_back(event);
|
||||||
|
self.outgoing.clear();
|
||||||
|
self.queued_packets = 0;
|
||||||
|
self.resend.clear();
|
||||||
|
self.in_flight.clear();
|
||||||
|
self.reassemblies.clear();
|
||||||
|
for ch in &mut self.channels {
|
||||||
|
ch.pending.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one received datagram. Datagrams for another peer id or session are dropped without error.
|
/// Feeds one received datagram. Datagrams for another peer id or session are dropped without error.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Parser errors as [`protocol::parse_datagram`]; [`crate::Error::TooLarge`] when a reassembly would exceed
|
/// Parser errors as [`protocol::parse_datagram`]; [`Error::TooLarge`] when a fragment announces more than
|
||||||
/// [`MAX_PACKET_BYTES`]; [`crate::Error::Closed`] after `Disconnected`. A malformed datagram never changes the
|
/// [`MAX_PACKET_BYTES`]; [`Error::Closed`] after `Disconnected`. A malformed datagram never changes the
|
||||||
/// connection state. Phase A: always [`crate::Error::Unimplemented`].
|
/// connection state.
|
||||||
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn handle_datagram(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
if self.state == EnetState::Disconnected {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::Closed);
|
||||||
|
}
|
||||||
|
let d = protocol::parse_datagram(datagram)?;
|
||||||
|
if d.peer_id != LOCAL_PEER_ID {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if self.state != EnetState::Connecting && d.session_id != self.in_session {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let sent_time = d.sent_time.unwrap_or(0);
|
||||||
|
let mut first_error = None;
|
||||||
|
for c in d.commands {
|
||||||
|
if self.state == EnetState::Disconnected {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Err(e) = self.command(now, sent_time, c) {
|
||||||
|
first_error.get_or_insert(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
first_error.map_or(Ok(()), Err)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Queues a packet. Packets larger than the MTU are fragmented.
|
fn ack(&mut self, channel: u8, seq: u16, sent_time: u16) {
|
||||||
|
if self.acks.len() >= MAX_PENDING_ACKS {
|
||||||
|
self.acks.pop_front();
|
||||||
|
}
|
||||||
|
self.acks.push_back(Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: seq,
|
||||||
|
body: CommandBody::Acknowledge { received_reliable_sequence: seq, received_sent_time: sent_time },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
fn command(&mut self, now: Instant, sent_time: u16, c: Command) -> Result<()> {
|
||||||
|
let (channel, seq) = (c.channel_id, c.reliable_sequence);
|
||||||
|
match c.body {
|
||||||
|
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
|
||||||
|
self.acknowledged(now, channel, received_reliable_sequence, received_sent_time);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::VerifyConnect(p) => {
|
||||||
|
if c.acknowledge {
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
}
|
||||||
|
if self.state == EnetState::Connecting && p.connect_id == self.connect_id {
|
||||||
|
self.host_peer_id = p.outgoing_peer_id & protocol::MAX_PEER_ID;
|
||||||
|
self.out_session = p.incoming_session_id & 0x3;
|
||||||
|
self.in_session = p.outgoing_session_id & 0x3;
|
||||||
|
let count = u8::try_from(p.channel_count.clamp(1, 255)).unwrap_or(1);
|
||||||
|
self.channel_count = self.channel_count.min(count);
|
||||||
|
let mtu = usize::try_from(p.mtu).unwrap_or(MAX_DATAGRAM_BYTES);
|
||||||
|
self.mtu = self.mtu.min(mtu).max(usize::from(MIN_MTU));
|
||||||
|
self.in_flight.retain(|f| !matches!(f.command.body, CommandBody::Connect { .. }));
|
||||||
|
self.state = EnetState::Connected;
|
||||||
|
self.events.push_back(EnetEvent::Connected);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::Disconnect { data } => {
|
||||||
|
if c.acknowledge {
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
}
|
||||||
|
self.close(EnetEvent::Disconnected { data });
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::Ping | CommandBody::BandwidthLimit { .. } | CommandBody::ThrottleConfigure { .. } => {
|
||||||
|
if c.acknowledge {
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::Connect { .. } => Ok(()),
|
||||||
|
CommandBody::SendReliable(data) => self.reliable(channel, seq, sent_time, Pending::Data(data)),
|
||||||
|
CommandBody::SendFragment(f) => {
|
||||||
|
let check = check_fragment(seq, &f);
|
||||||
|
let pending = match &check {
|
||||||
|
Ok(()) => Pending::Fragment(f),
|
||||||
|
Err(_) => Pending::Skip,
|
||||||
|
};
|
||||||
|
self.reliable(channel, seq, sent_time, pending)?;
|
||||||
|
check
|
||||||
|
}
|
||||||
|
CommandBody::SendUnreliable { unreliable_sequence, data } => {
|
||||||
|
if self.state == EnetState::Connected
|
||||||
|
&& channel < self.channel_count
|
||||||
|
&& let Some(ch) = self.channels.get_mut(usize::from(channel))
|
||||||
|
{
|
||||||
|
let newer = ch
|
||||||
|
.in_unreliable
|
||||||
|
.is_none_or(|last| (1..0x8000).contains(&unreliable_sequence.wrapping_sub(last)));
|
||||||
|
if newer {
|
||||||
|
ch.in_unreliable = Some(unreliable_sequence);
|
||||||
|
self.events.push_back(EnetEvent::Received { channel, data });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::SendUnsequenced { data, .. } => {
|
||||||
|
if self.state == EnetState::Connected && channel < self.channel_count {
|
||||||
|
self.events.push_back(EnetEvent::Received { channel, data });
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
CommandBody::SendUnreliableFragment(_) => Ok(()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reliable command on a data channel: acknowledged, ordered, then processed in sequence.
|
||||||
|
fn reliable(&mut self, channel: u8, seq: u16, sent_time: u16, pending: Pending) -> Result<()> {
|
||||||
|
if self.state != EnetState::Connected || channel >= self.channel_count {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return Ok(()) };
|
||||||
|
let next = ch.in_reliable.wrapping_add(1);
|
||||||
|
let distance = seq.wrapping_sub(next);
|
||||||
|
if distance >= 0x8000 {
|
||||||
|
// Already delivered: a retransmission. Acknowledge again, deliver nothing.
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if distance >= RELIABLE_WINDOW || ch.pending.len() >= MAX_PENDING_PER_CHANNEL {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
ch.pending.entry(seq).or_insert(pending);
|
||||||
|
self.ack(channel, seq, sent_time);
|
||||||
|
self.deliver_in_order(channel)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver_in_order(&mut self, channel: u8) -> Result<()> {
|
||||||
|
loop {
|
||||||
|
let Some(ch) = self.channels.get_mut(usize::from(channel)) else { return Ok(()) };
|
||||||
|
let next = ch.in_reliable.wrapping_add(1);
|
||||||
|
let Some(p) = ch.pending.remove(&next) else { return Ok(()) };
|
||||||
|
ch.in_reliable = next;
|
||||||
|
match p {
|
||||||
|
Pending::Data(data) => self.events.push_back(EnetEvent::Received { channel, data }),
|
||||||
|
Pending::Fragment(f) => self.fragment(channel, f),
|
||||||
|
Pending::Skip => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fragment(&mut self, channel: u8, f: Fragment) {
|
||||||
|
let idx = match self.reassemblies.iter().position(|r| r.channel == channel && r.start == f.start_sequence) {
|
||||||
|
Some(i) => i,
|
||||||
|
None => {
|
||||||
|
if self.reassemblies.len() >= MAX_REASSEMBLIES {
|
||||||
|
self.reassemblies.remove(0);
|
||||||
|
}
|
||||||
|
let (Ok(count), Ok(total)) = (usize::try_from(f.fragment_count), usize::try_from(f.total_length))
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
self.reassemblies.push(Reassembly {
|
||||||
|
channel,
|
||||||
|
start: f.start_sequence,
|
||||||
|
count: f.fragment_count,
|
||||||
|
total: f.total_length,
|
||||||
|
got: vec![false; count],
|
||||||
|
received: 0,
|
||||||
|
data: vec![0; total],
|
||||||
|
});
|
||||||
|
self.reassemblies.len() - 1
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let Some(r) = self.reassemblies.get_mut(idx) else { return };
|
||||||
|
if r.count != f.fragment_count || r.total != f.total_length {
|
||||||
|
self.reassemblies.remove(idx);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let (Ok(number), Ok(offset)) = (usize::try_from(f.fragment_number), usize::try_from(f.fragment_offset)) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let Some(seen) = r.got.get_mut(number) else { return };
|
||||||
|
if *seen {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(dest) = r.data.get_mut(offset..offset + f.data.len()) else { return };
|
||||||
|
dest.copy_from_slice(&f.data);
|
||||||
|
*seen = true;
|
||||||
|
r.received += 1;
|
||||||
|
if r.received == r.count {
|
||||||
|
let done = self.reassemblies.remove(idx);
|
||||||
|
self.events.push_back(EnetEvent::Received { channel, data: done.data });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn acknowledged(&mut self, now: Instant, channel: u8, seq: u16, sent_time: u16) {
|
||||||
|
let before = self.in_flight.len();
|
||||||
|
let mut acked_disconnect = false;
|
||||||
|
self.in_flight.retain(|f| {
|
||||||
|
let hit = f.command.channel_id == channel && f.command.reliable_sequence == seq;
|
||||||
|
if hit && matches!(f.command.body, CommandBody::Disconnect { .. }) {
|
||||||
|
acked_disconnect = true;
|
||||||
|
}
|
||||||
|
!hit
|
||||||
|
});
|
||||||
|
self.resend.retain(|c| !(c.channel_id == channel && c.reliable_sequence == seq));
|
||||||
|
if self.in_flight.len() < before {
|
||||||
|
let sample = ms16(now).wrapping_sub(sent_time);
|
||||||
|
if sample < 10_000 {
|
||||||
|
let sample = Duration::from_millis(u64::from(sample));
|
||||||
|
match self.srtt {
|
||||||
|
None => {
|
||||||
|
self.srtt = Some(sample);
|
||||||
|
self.rttvar = sample / 2;
|
||||||
|
}
|
||||||
|
Some(s) => {
|
||||||
|
let diff = s.abs_diff(sample);
|
||||||
|
self.rttvar = (self.rttvar * 3 + diff) / 4;
|
||||||
|
self.srtt = Some((s * 7 + sample) / 8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if acked_disconnect && self.state == EnetState::Disconnecting {
|
||||||
|
self.state = EnetState::Disconnected;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Queues a packet. Packets larger than one command within the MTU are fragmented.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::State`] unless connected, [`crate::Error::UnexpectedValue`] for a channel outside the
|
/// [`Error::State`] unless connected, [`Error::UnexpectedValue`] for a channel outside the negotiated count,
|
||||||
/// negotiated count, [`crate::Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue. Phase A: always
|
/// [`Error::TooLarge`] over [`MAX_PACKET_BYTES`] or a full queue ([`MAX_SEND_QUEUE`] packets).
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> {
|
pub fn send(&mut self, now: Instant, channel: u8, delivery: Delivery, data: &[u8]) -> Result<()> {
|
||||||
let _ = (now, channel, delivery, data);
|
let _ = now;
|
||||||
Err(crate::Error::Unimplemented)
|
if self.state != EnetState::Connected {
|
||||||
|
return Err(Error::State { expected: "enet connected" });
|
||||||
|
}
|
||||||
|
if channel >= self.channel_count {
|
||||||
|
return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() });
|
||||||
|
}
|
||||||
|
crate::util::cap("enet packet", MAX_PACKET_BYTES, data.len())?;
|
||||||
|
crate::util::cap("enet send queue", MAX_SEND_QUEUE, self.queued_packets + 1)?;
|
||||||
|
// Header with sent time (4) plus the command header and its fields.
|
||||||
|
let single = self.mtu.saturating_sub(4 + 6);
|
||||||
|
let piece = self.mtu.saturating_sub(4 + 24).max(1);
|
||||||
|
let Some(ch) = self.channels.get_mut(usize::from(channel)) else {
|
||||||
|
return Err(Error::UnexpectedValue { what: "enet channel", value: channel.into() });
|
||||||
|
};
|
||||||
|
let mut commands = Vec::new();
|
||||||
|
match delivery {
|
||||||
|
Delivery::Reliable | Delivery::Unreliable if data.len() > single => {
|
||||||
|
let count = data.len().div_ceil(piece);
|
||||||
|
let start = ch.out_reliable.wrapping_add(1);
|
||||||
|
let total = u32::try_from(data.len()).unwrap_or(u32::MAX);
|
||||||
|
for (n, chunk) in data.chunks(piece).enumerate() {
|
||||||
|
ch.out_reliable = ch.out_reliable.wrapping_add(1);
|
||||||
|
let f = Fragment {
|
||||||
|
start_sequence: start,
|
||||||
|
fragment_count: u32::try_from(count).unwrap_or(u32::MAX),
|
||||||
|
fragment_number: u32::try_from(n).unwrap_or(u32::MAX),
|
||||||
|
total_length: total,
|
||||||
|
fragment_offset: u32::try_from(n * piece).unwrap_or(u32::MAX),
|
||||||
|
data: chunk.to_vec(),
|
||||||
|
};
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: ch.out_reliable,
|
||||||
|
body: CommandBody::SendFragment(f),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Delivery::Reliable => {
|
||||||
|
ch.out_reliable = ch.out_reliable.wrapping_add(1);
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: true,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: ch.out_reliable,
|
||||||
|
body: CommandBody::SendReliable(data.to_vec()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Delivery::Unreliable => {
|
||||||
|
ch.out_unreliable = ch.out_unreliable.wrapping_add(1);
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: ch.out_reliable,
|
||||||
|
body: CommandBody::SendUnreliable { unreliable_sequence: ch.out_unreliable, data: data.to_vec() },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Delivery::Unsequenced => {
|
||||||
|
if data.len() > single {
|
||||||
|
return Err(Error::TooLarge { what: "enet unsequenced packet", max: single, actual: data.len() });
|
||||||
|
}
|
||||||
|
self.unsequenced_group = self.unsequenced_group.wrapping_add(1);
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: false,
|
||||||
|
channel_id: channel,
|
||||||
|
reliable_sequence: 0,
|
||||||
|
body: CommandBody::SendUnsequenced {
|
||||||
|
unsequenced_group: self.unsequenced_group,
|
||||||
|
data: data.to_vec(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let last = commands.len().saturating_sub(1);
|
||||||
|
for (i, command) in commands.into_iter().enumerate() {
|
||||||
|
self.outgoing.push_back(Outgoing { command, ends_packet: i == last });
|
||||||
|
}
|
||||||
|
self.queued_packets += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Starts a graceful disconnect.
|
/// Starts a graceful disconnect.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Closed`] when already disconnected. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Closed`] when already disconnected or disconnecting.
|
||||||
pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> {
|
pub fn disconnect(&mut self, now: Instant, data: u32) -> Result<()> {
|
||||||
let _ = (now, data);
|
let _ = now;
|
||||||
Err(crate::Error::Unimplemented)
|
if matches!(self.state, EnetState::Disconnected | EnetState::Disconnecting) {
|
||||||
|
return Err(Error::Closed);
|
||||||
|
}
|
||||||
|
self.queue_connection_command(CommandBody::Disconnect { data });
|
||||||
|
self.state = EnetState::Disconnecting;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next datagram to send, at most [`protocol::MAX_DATAGRAM_BYTES`] (acknowledgements, retransmissions,
|
/// The next datagram to send, at most the MTU (acknowledgements, retransmissions, queued packets, pings).
|
||||||
/// queued packets, pings).
|
|
||||||
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
pub fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
|
||||||
let _ = now;
|
let budget = self.mtu;
|
||||||
None
|
let mut size = 4;
|
||||||
|
let mut commands: Vec<Command> = Vec::new();
|
||||||
|
let fits = |size: usize, c: &Command, n: usize| {
|
||||||
|
n < protocol::MAX_COMMANDS_PER_DATAGRAM && size + protocol::command_size(c) <= budget
|
||||||
|
};
|
||||||
|
while let Some(a) = self.acks.front() {
|
||||||
|
if !fits(size, a, commands.len()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size += protocol::command_size(a);
|
||||||
|
if let Some(a) = self.acks.pop_front() {
|
||||||
|
commands.push(a);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.state != EnetState::Disconnected {
|
||||||
|
let rto = self.rto();
|
||||||
|
while let Some(c) = self.resend.front() {
|
||||||
|
if !fits(size, c, commands.len()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size += protocol::command_size(c);
|
||||||
|
if let Some(c) = self.resend.pop_front() {
|
||||||
|
if let Some(f) = self.in_flight.iter_mut().find(|f| {
|
||||||
|
f.command.channel_id == c.channel_id && f.command.reliable_sequence == c.reliable_sequence
|
||||||
|
}) {
|
||||||
|
f.sent_at = now;
|
||||||
|
}
|
||||||
|
commands.push(c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
while let Some(o) = self.outgoing.front() {
|
||||||
|
if !fits(size, &o.command, commands.len()) || self.in_flight.len() >= MAX_IN_FLIGHT {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size += protocol::command_size(&o.command);
|
||||||
|
let Some(o) = self.outgoing.pop_front() else { break };
|
||||||
|
if o.ends_packet {
|
||||||
|
self.queued_packets = self.queued_packets.saturating_sub(1);
|
||||||
|
}
|
||||||
|
if o.command.acknowledge {
|
||||||
|
self.in_flight.push(InFlight { command: o.command.clone(), first_sent: now, sent_at: now, rto });
|
||||||
|
}
|
||||||
|
commands.push(o.command);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if commands.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
self.last_send = now;
|
||||||
|
let peer_id = if self.state == EnetState::Connecting { NO_PEER_ID } else { self.host_peer_id };
|
||||||
|
let d = Datagram { peer_id, session_id: self.out_session, sent_time: Some(ms16(now)), commands };
|
||||||
|
protocol::encode_datagram(&d).ok()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<EnetEvent> {
|
pub fn poll_event(&mut self) -> Option<EnetEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever.
|
/// When [`Self::handle_timeout`] must be called next (retransmission, ping or timeout), if ever.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
if self.state == EnetState::Disconnected {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let flight = self
|
||||||
|
.in_flight
|
||||||
|
.iter()
|
||||||
|
.flat_map(|f| [f.sent_at.saturating_add(f.rto), f.first_sent.saturating_add(self.config.timeout)])
|
||||||
|
.min();
|
||||||
|
// Also while packets are only queued: the caller then still gets a deadline, and the data goes out with the
|
||||||
|
// next poll_transmit at the latest.
|
||||||
|
let ping = (self.state == EnetState::Connected && self.in_flight.is_empty())
|
||||||
|
.then(|| self.last_send.saturating_add(self.config.ping_interval));
|
||||||
|
match (flight, ping) {
|
||||||
|
(Some(a), Some(b)) => Some(a.min(b)),
|
||||||
|
(a, b) => a.or(b),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Advances timers: retransmits, pings, or gives up with [`EnetEvent::TimedOut`].
|
/// Advances timers: retransmits, pings, or gives up with [`EnetEvent::TimedOut`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
if self.state == EnetState::Disconnected {
|
||||||
Err(crate::Error::Unimplemented)
|
return Ok(());
|
||||||
|
}
|
||||||
|
let timeout = self.config.timeout;
|
||||||
|
if self.in_flight.iter().any(|f| f.first_sent.saturating_add(timeout) <= now) {
|
||||||
|
self.close(EnetEvent::TimedOut);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
for f in &mut self.in_flight {
|
||||||
|
if f.sent_at.saturating_add(f.rto) <= now
|
||||||
|
&& !self
|
||||||
|
.resend
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.channel_id == f.command.channel_id && c.reliable_sequence == f.command.reliable_sequence)
|
||||||
|
{
|
||||||
|
f.rto = (f.rto * 2).min(MAX_RTO);
|
||||||
|
f.sent_at = now;
|
||||||
|
self.resend.push_back(f.command.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.state == EnetState::Connected
|
||||||
|
&& self.in_flight.is_empty()
|
||||||
|
&& self.outgoing.is_empty()
|
||||||
|
&& self.last_send.saturating_add(self.config.ping_interval) <= now
|
||||||
|
{
|
||||||
|
self.queue_connection_command(CommandBody::Ping);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Connection state.
|
/// Connection state.
|
||||||
@@ -170,6 +732,20 @@ impl EnetClient {
|
|||||||
/// Smoothed round-trip time, once measured.
|
/// Smoothed round-trip time, once measured.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn round_trip_time(&self) -> Option<Duration> {
|
pub fn round_trip_time(&self) -> Option<Duration> {
|
||||||
None
|
self.srtt
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The checks a fragment must pass before any memory is reserved for it.
|
||||||
|
fn check_fragment(seq: u16, f: &Fragment) -> Result<()> {
|
||||||
|
let total = usize::try_from(f.total_length).unwrap_or(usize::MAX);
|
||||||
|
crate::util::cap("enet fragmented packet", MAX_PACKET_BYTES, total)?;
|
||||||
|
let offset = usize::try_from(f.fragment_offset).unwrap_or(usize::MAX);
|
||||||
|
let sound = f.fragment_count >= 1
|
||||||
|
&& f.fragment_number < f.fragment_count
|
||||||
|
&& usize::try_from(f.fragment_count).is_ok_and(|c| c <= total.max(1))
|
||||||
|
&& !f.data.is_empty()
|
||||||
|
&& offset.checked_add(f.data.len()).is_some_and(|end| end <= total)
|
||||||
|
&& u32::from(seq.wrapping_sub(f.start_sequence)) == f.fragment_number;
|
||||||
|
if sound { Ok(()) } else { Err(malformed("enet fragment")) }
|
||||||
|
}
|
||||||
|
|||||||
@@ -193,24 +193,260 @@ pub struct Datagram {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Parses one datagram strictly: every length checked against the bytes present, unknown command numbers and
|
/// Parses one datagram strictly: every length checked against the bytes present, unknown command numbers and
|
||||||
/// compressed datagrams refused.
|
/// compressed datagrams refused. The unsequenced flag and the two unused command bits are not kept.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`],
|
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`],
|
||||||
/// [`crate::Error::Truncated`] for a cut command, [`crate::Error::UnexpectedValue`] for an unknown command or the
|
/// [`crate::Error::Truncated`] for a cut header, command or data, [`crate::Error::UnexpectedValue`] for an unknown
|
||||||
/// compressed flag, [`crate::Error::Malformed`] for a data length that does not match. Phase A: always
|
/// command or the compressed flag.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_datagram(datagram: &[u8]) -> crate::Result<Datagram> {
|
pub fn parse_datagram(datagram: &[u8]) -> crate::Result<Datagram> {
|
||||||
let _ = datagram;
|
use crate::util::{byte, cap, slice, u16_be, u32_be};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "enet datagram";
|
||||||
|
cap(W, MAX_DATAGRAM_BYTES, datagram.len())?;
|
||||||
|
let raw = u16_be(W, datagram, 0)?;
|
||||||
|
if raw & HEADER_FLAG_COMPRESSED != 0 {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "enet compressed datagram", value: raw.into() });
|
||||||
|
}
|
||||||
|
let mut pos = 2;
|
||||||
|
let sent_time = if raw & HEADER_FLAG_SENT_TIME != 0 {
|
||||||
|
pos = 4;
|
||||||
|
Some(u16_be(W, datagram, 2)?)
|
||||||
|
} else {
|
||||||
|
None
|
||||||
|
};
|
||||||
|
let mut commands = Vec::new();
|
||||||
|
while pos < datagram.len() {
|
||||||
|
cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, commands.len() + 1)?;
|
||||||
|
let command = byte(W, datagram, pos)?;
|
||||||
|
let channel_id = byte(W, datagram, pos + 1)?;
|
||||||
|
let reliable_sequence = u16_be(W, datagram, pos + 2)?;
|
||||||
|
let kind = command & 0x0F;
|
||||||
|
let at = pos + 4;
|
||||||
|
let u32_at = |off: usize| u32_be(W, datagram, at + off);
|
||||||
|
let data_of = |len_at: usize, data_at: usize| -> crate::Result<(Vec<u8>, usize)> {
|
||||||
|
let len = usize::from(u16_be(W, datagram, at + len_at)?);
|
||||||
|
Ok((slice(W, datagram, at + data_at, len)?.to_vec(), at + data_at + len))
|
||||||
|
};
|
||||||
|
let params = || -> crate::Result<ConnectParams> {
|
||||||
|
Ok(ConnectParams {
|
||||||
|
outgoing_peer_id: u16_be(W, datagram, at)?,
|
||||||
|
incoming_session_id: byte(W, datagram, at + 2)?,
|
||||||
|
outgoing_session_id: byte(W, datagram, at + 3)?,
|
||||||
|
mtu: u32_at(4)?,
|
||||||
|
window_size: u32_at(8)?,
|
||||||
|
channel_count: u32_at(12)?,
|
||||||
|
incoming_bandwidth: u32_at(16)?,
|
||||||
|
outgoing_bandwidth: u32_at(20)?,
|
||||||
|
packet_throttle_interval: u32_at(24)?,
|
||||||
|
packet_throttle_acceleration: u32_at(28)?,
|
||||||
|
packet_throttle_deceleration: u32_at(32)?,
|
||||||
|
connect_id: u32_at(36)?,
|
||||||
|
})
|
||||||
|
};
|
||||||
|
let fragment = || -> crate::Result<(Fragment, usize)> {
|
||||||
|
let start_sequence = u16_be(W, datagram, at)?;
|
||||||
|
let fragment_count = u32_at(4)?;
|
||||||
|
let fragment_number = u32_at(8)?;
|
||||||
|
let total_length = u32_at(12)?;
|
||||||
|
let fragment_offset = u32_at(16)?;
|
||||||
|
let (data, end) = data_of(2, 20)?;
|
||||||
|
Ok((Fragment { start_sequence, fragment_count, fragment_number, total_length, fragment_offset, data }, end))
|
||||||
|
};
|
||||||
|
let (body, end) = match kind {
|
||||||
|
1 => (
|
||||||
|
CommandBody::Acknowledge {
|
||||||
|
received_reliable_sequence: u16_be(W, datagram, at)?,
|
||||||
|
received_sent_time: u16_be(W, datagram, at + 2)?,
|
||||||
|
},
|
||||||
|
at + 4,
|
||||||
|
),
|
||||||
|
2 => {
|
||||||
|
let p = params()?;
|
||||||
|
(CommandBody::Connect { params: p, data: u32_at(40)? }, at + 44)
|
||||||
|
}
|
||||||
|
3 => (CommandBody::VerifyConnect(params()?), at + 40),
|
||||||
|
4 => (CommandBody::Disconnect { data: u32_at(0)? }, at + 4),
|
||||||
|
5 => (CommandBody::Ping, at),
|
||||||
|
6 => {
|
||||||
|
let (data, end) = data_of(0, 2)?;
|
||||||
|
(CommandBody::SendReliable(data), end)
|
||||||
|
}
|
||||||
|
7 => {
|
||||||
|
let unreliable_sequence = u16_be(W, datagram, at)?;
|
||||||
|
let (data, end) = data_of(2, 4)?;
|
||||||
|
(CommandBody::SendUnreliable { unreliable_sequence, data }, end)
|
||||||
|
}
|
||||||
|
8 => {
|
||||||
|
let (f, end) = fragment()?;
|
||||||
|
(CommandBody::SendFragment(f), end)
|
||||||
|
}
|
||||||
|
9 => {
|
||||||
|
let unsequenced_group = u16_be(W, datagram, at)?;
|
||||||
|
let (data, end) = data_of(2, 4)?;
|
||||||
|
(CommandBody::SendUnsequenced { unsequenced_group, data }, end)
|
||||||
|
}
|
||||||
|
10 => (CommandBody::BandwidthLimit { incoming: u32_at(0)?, outgoing: u32_at(4)? }, at + 8),
|
||||||
|
11 => (
|
||||||
|
CommandBody::ThrottleConfigure {
|
||||||
|
interval: u32_at(0)?,
|
||||||
|
acceleration: u32_at(4)?,
|
||||||
|
deceleration: u32_at(8)?,
|
||||||
|
},
|
||||||
|
at + 12,
|
||||||
|
),
|
||||||
|
12 => {
|
||||||
|
let (f, end) = fragment()?;
|
||||||
|
(CommandBody::SendUnreliableFragment(f), end)
|
||||||
|
}
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "enet command", value: other.into() }),
|
||||||
|
};
|
||||||
|
commands.push(Command {
|
||||||
|
acknowledge: command & COMMAND_FLAG_ACKNOWLEDGE != 0,
|
||||||
|
channel_id,
|
||||||
|
reliable_sequence,
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
pos = end;
|
||||||
|
}
|
||||||
|
Ok(Datagram { peer_id: raw & MAX_PEER_ID, session_id: ((raw >> 12) & 0x3) as u8, sent_time, commands })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The command number of a body.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn kind_of(body: &CommandBody) -> CommandKind {
|
||||||
|
match body {
|
||||||
|
CommandBody::Acknowledge { .. } => CommandKind::Acknowledge,
|
||||||
|
CommandBody::Connect { .. } => CommandKind::Connect,
|
||||||
|
CommandBody::VerifyConnect(_) => CommandKind::VerifyConnect,
|
||||||
|
CommandBody::Disconnect { .. } => CommandKind::Disconnect,
|
||||||
|
CommandBody::Ping => CommandKind::Ping,
|
||||||
|
CommandBody::SendReliable(_) => CommandKind::SendReliable,
|
||||||
|
CommandBody::SendUnreliable { .. } => CommandKind::SendUnreliable,
|
||||||
|
CommandBody::SendFragment(_) => CommandKind::SendFragment,
|
||||||
|
CommandBody::SendUnsequenced { .. } => CommandKind::SendUnsequenced,
|
||||||
|
CommandBody::BandwidthLimit { .. } => CommandKind::BandwidthLimit,
|
||||||
|
CommandBody::ThrottleConfigure { .. } => CommandKind::ThrottleConfigure,
|
||||||
|
CommandBody::SendUnreliableFragment(_) => CommandKind::SendUnreliableFragment,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes one command takes on the wire.
|
||||||
|
#[must_use]
|
||||||
|
pub fn command_size(c: &Command) -> usize {
|
||||||
|
4 + match &c.body {
|
||||||
|
CommandBody::Acknowledge { .. } | CommandBody::Disconnect { .. } => 4,
|
||||||
|
CommandBody::Connect { .. } => 44,
|
||||||
|
CommandBody::VerifyConnect(_) => 40,
|
||||||
|
CommandBody::Ping => 0,
|
||||||
|
CommandBody::SendReliable(d) => 2 + d.len(),
|
||||||
|
CommandBody::SendUnreliable { data, .. } | CommandBody::SendUnsequenced { data, .. } => 4 + data.len(),
|
||||||
|
CommandBody::SendFragment(f) | CommandBody::SendUnreliableFragment(f) => 20 + f.data.len(),
|
||||||
|
CommandBody::BandwidthLimit { .. } => 8,
|
||||||
|
CommandBody::ThrottleConfigure { .. } => 12,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn put_params(out: &mut Vec<u8>, p: &ConnectParams) {
|
||||||
|
out.extend_from_slice(&p.outgoing_peer_id.to_be_bytes());
|
||||||
|
out.push(p.incoming_session_id);
|
||||||
|
out.push(p.outgoing_session_id);
|
||||||
|
for v in [
|
||||||
|
p.mtu,
|
||||||
|
p.window_size,
|
||||||
|
p.channel_count,
|
||||||
|
p.incoming_bandwidth,
|
||||||
|
p.outgoing_bandwidth,
|
||||||
|
p.packet_throttle_interval,
|
||||||
|
p.packet_throttle_acceleration,
|
||||||
|
p.packet_throttle_deceleration,
|
||||||
|
p.connect_id,
|
||||||
|
] {
|
||||||
|
out.extend_from_slice(&v.to_be_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn data_len(data: &[u8]) -> crate::Result<u16> {
|
||||||
|
u16::try_from(data.len()).map_err(|_| crate::Error::TooLarge {
|
||||||
|
what: "enet command data",
|
||||||
|
max: usize::from(u16::MAX),
|
||||||
|
actual: data.len(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Serializes one datagram.
|
/// Serializes one datagram.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`]. Phase A: always
|
/// [`crate::Error::TooLarge`] over [`MAX_DATAGRAM_BYTES`] or [`MAX_COMMANDS_PER_DATAGRAM`],
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Malformed`] for a peer id over [`MAX_PEER_ID`] or a session id over 3.
|
||||||
pub fn encode_datagram(datagram: &Datagram) -> crate::Result<Vec<u8>> {
|
pub fn encode_datagram(datagram: &Datagram) -> crate::Result<Vec<u8>> {
|
||||||
let _ = datagram;
|
use crate::util::cap;
|
||||||
Err(crate::Error::Unimplemented)
|
cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, datagram.commands.len())?;
|
||||||
|
if datagram.peer_id > MAX_PEER_ID || datagram.session_id > 3 {
|
||||||
|
return Err(crate::util::malformed("enet peer or session id"));
|
||||||
|
}
|
||||||
|
let header_len = if datagram.sent_time.is_some() { 4 } else { 2 };
|
||||||
|
let size = datagram.commands.iter().map(command_size).fold(header_len, usize::saturating_add);
|
||||||
|
cap("enet datagram", MAX_DATAGRAM_BYTES, size)?;
|
||||||
|
let mut out = Vec::with_capacity(size);
|
||||||
|
let mut header = datagram.peer_id | (u16::from(datagram.session_id) << 12);
|
||||||
|
if datagram.sent_time.is_some() {
|
||||||
|
header |= HEADER_FLAG_SENT_TIME;
|
||||||
|
}
|
||||||
|
out.extend_from_slice(&header.to_be_bytes());
|
||||||
|
if let Some(t) = datagram.sent_time {
|
||||||
|
out.extend_from_slice(&t.to_be_bytes());
|
||||||
|
}
|
||||||
|
for c in &datagram.commands {
|
||||||
|
let mut command = kind_of(&c.body) as u8;
|
||||||
|
if c.acknowledge {
|
||||||
|
command |= COMMAND_FLAG_ACKNOWLEDGE;
|
||||||
|
}
|
||||||
|
if matches!(c.body, CommandBody::SendUnsequenced { .. }) {
|
||||||
|
command |= COMMAND_FLAG_UNSEQUENCED;
|
||||||
|
}
|
||||||
|
out.push(command);
|
||||||
|
out.push(c.channel_id);
|
||||||
|
out.extend_from_slice(&c.reliable_sequence.to_be_bytes());
|
||||||
|
match &c.body {
|
||||||
|
CommandBody::Acknowledge { received_reliable_sequence, received_sent_time } => {
|
||||||
|
out.extend_from_slice(&received_reliable_sequence.to_be_bytes());
|
||||||
|
out.extend_from_slice(&received_sent_time.to_be_bytes());
|
||||||
|
}
|
||||||
|
CommandBody::Connect { params, data } => {
|
||||||
|
put_params(&mut out, params);
|
||||||
|
out.extend_from_slice(&data.to_be_bytes());
|
||||||
|
}
|
||||||
|
CommandBody::VerifyConnect(params) => put_params(&mut out, params),
|
||||||
|
CommandBody::Disconnect { data } => out.extend_from_slice(&data.to_be_bytes()),
|
||||||
|
CommandBody::Ping => {}
|
||||||
|
CommandBody::SendReliable(data) => {
|
||||||
|
out.extend_from_slice(&data_len(data)?.to_be_bytes());
|
||||||
|
out.extend_from_slice(data);
|
||||||
|
}
|
||||||
|
CommandBody::SendUnreliable { unreliable_sequence: s, data }
|
||||||
|
| CommandBody::SendUnsequenced { unsequenced_group: s, data } => {
|
||||||
|
out.extend_from_slice(&s.to_be_bytes());
|
||||||
|
out.extend_from_slice(&data_len(data)?.to_be_bytes());
|
||||||
|
out.extend_from_slice(data);
|
||||||
|
}
|
||||||
|
CommandBody::SendFragment(f) | CommandBody::SendUnreliableFragment(f) => {
|
||||||
|
out.extend_from_slice(&f.start_sequence.to_be_bytes());
|
||||||
|
out.extend_from_slice(&data_len(&f.data)?.to_be_bytes());
|
||||||
|
for v in [f.fragment_count, f.fragment_number, f.total_length, f.fragment_offset] {
|
||||||
|
out.extend_from_slice(&v.to_be_bytes());
|
||||||
|
}
|
||||||
|
out.extend_from_slice(&f.data);
|
||||||
|
}
|
||||||
|
CommandBody::BandwidthLimit { incoming, outgoing } => {
|
||||||
|
out.extend_from_slice(&incoming.to_be_bytes());
|
||||||
|
out.extend_from_slice(&outgoing.to_be_bytes());
|
||||||
|
}
|
||||||
|
CommandBody::ThrottleConfigure { interval, acceleration, deceleration } => {
|
||||||
|
for v in [interval, acceleration, deceleration] {
|
||||||
|
out.extend_from_slice(&v.to_be_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ pub type Result<T> = core::result::Result<T, Error>;
|
|||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// Phase A: the API exists, the logic does not yet.
|
/// A part of the API that has no implementation (none today; kept so callers and tests can name it).
|
||||||
Unimplemented,
|
Unimplemented,
|
||||||
/// Input is larger than the parser's `MAX_*` constant. Checked before anything is allocated.
|
/// Input is larger than the parser's `MAX_*` constant. Checked before anything is allocated.
|
||||||
TooLarge {
|
TooLarge {
|
||||||
|
|||||||
+316
-30
@@ -4,22 +4,200 @@
|
|||||||
//! `data` of the `data + parity` shards rebuild the rest. Every byte position is coded on its own, so all shards of
|
//! `data` of the `data + parity` shards rebuild the rest. Every byte position is coded on its own, so all shards of
|
||||||
//! a block have the same length.
|
//! a block have the same length.
|
||||||
//!
|
//!
|
||||||
//! Two matrices are needed: video (`ReedSolomon::new`, construction UNKNOWN U14) and audio (a fixed 2 × 4 parity
|
//! Two matrices are needed: video ([`ReedSolomon::new`]: the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`, from
|
||||||
//! matrix, UNKNOWN U16, passed in with [`ReedSolomon::with_parity_matrix`] until it is measured).
|
//! fec-rs, U14 settled pending the Day 1 check) and audio (a fixed 2 × 4 parity matrix, UNKNOWN U16, passed in
|
||||||
|
//! with [`ReedSolomon::with_parity_matrix`] until it is measured).
|
||||||
|
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Maximum shards in one block (data + parity).
|
/// Maximum shards in one block (data + parity).
|
||||||
pub const MAX_SHARDS: usize = 255;
|
pub const MAX_SHARDS: usize = 255;
|
||||||
/// Maximum length of one shard, in bytes.
|
/// Maximum length of one shard, in bytes.
|
||||||
pub const MAX_SHARD_BYTES: usize = 4096;
|
pub const MAX_SHARD_BYTES: usize = 4096;
|
||||||
|
|
||||||
|
/// Square submatrices checked exhaustively for the MDS property; bigger matrices get the 1 × 1 and, if cheap
|
||||||
|
/// enough, the 2 × 2 checks only.
|
||||||
|
const MDS_EXHAUSTIVE_BUDGET: u64 = 200_000;
|
||||||
|
const MDS_PAIRS_BUDGET: u64 = 1_000_000;
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ GF(2^8)
|
||||||
|
|
||||||
|
/// `EXP[i] = 2^i` (doubled so a sum of two logarithms needs no reduction) and `LOG[x] = log2(x)`.
|
||||||
|
#[allow(clippy::indexing_slicing, reason = "compile-time table: any out-of-bounds index fails the build")]
|
||||||
|
const fn tables() -> ([u8; 512], [u8; 256]) {
|
||||||
|
let mut exp = [0u8; 512];
|
||||||
|
let mut log = [0u8; 256];
|
||||||
|
let mut x: u16 = 1;
|
||||||
|
let mut i = 0;
|
||||||
|
while i < 255 {
|
||||||
|
exp[i] = x as u8;
|
||||||
|
log[x as usize] = i as u8;
|
||||||
|
x <<= 1;
|
||||||
|
if x & 0x100 != 0 {
|
||||||
|
x ^= 0x11D;
|
||||||
|
}
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
while i < 512 {
|
||||||
|
exp[i] = exp[i - 255];
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
(exp, log)
|
||||||
|
}
|
||||||
|
|
||||||
|
const TABLES: ([u8; 512], [u8; 256]) = tables();
|
||||||
|
|
||||||
|
fn log(x: u8) -> usize {
|
||||||
|
usize::from(TABLES.1.get(usize::from(x)).copied().unwrap_or(0))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn exp(i: usize) -> u8 {
|
||||||
|
TABLES.0.get(i).copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn mul(a: u8, b: u8) -> u8 {
|
||||||
|
if a == 0 || b == 0 { 0 } else { exp(log(a) + log(b)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multiplicative inverse; `inv(0)` is 0 (never used as a divisor).
|
||||||
|
fn inv(a: u8) -> u8 {
|
||||||
|
if a == 0 { 0 } else { exp(255 - log(a)) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `dst ^= c · src`, byte by byte.
|
||||||
|
fn mul_add(dst: &mut [u8], src: &[u8], c: u8) {
|
||||||
|
if c == 0 {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let lc = log(c);
|
||||||
|
for (d, &s) in dst.iter_mut().zip(src) {
|
||||||
|
if s != 0 {
|
||||||
|
*d ^= exp(lc + log(s));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Inverse of a row-major `n × n` matrix by Gauss-Jordan elimination; `None` when singular.
|
||||||
|
fn invert(mut a: Vec<u8>, n: usize) -> Option<Vec<u8>> {
|
||||||
|
let mut out = vec![0u8; n * n];
|
||||||
|
for i in 0..n {
|
||||||
|
*out.get_mut(i * n + i)? = 1;
|
||||||
|
}
|
||||||
|
for col in 0..n {
|
||||||
|
let pivot = (col..n).find(|&r| a.get(r * n + col).is_some_and(|v| *v != 0))?;
|
||||||
|
if pivot != col {
|
||||||
|
for c in 0..n {
|
||||||
|
a.swap(pivot * n + c, col * n + c);
|
||||||
|
out.swap(pivot * n + c, col * n + c);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let scale = inv(*a.get(col * n + col)?);
|
||||||
|
for c in 0..n {
|
||||||
|
let v = a.get_mut(col * n + c)?;
|
||||||
|
*v = mul(*v, scale);
|
||||||
|
let w = out.get_mut(col * n + c)?;
|
||||||
|
*w = mul(*w, scale);
|
||||||
|
}
|
||||||
|
for r in 0..n {
|
||||||
|
if r == col {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let factor = *a.get(r * n + col)?;
|
||||||
|
if factor == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for c in 0..n {
|
||||||
|
let ac = mul(factor, *a.get(col * n + c)?);
|
||||||
|
*a.get_mut(r * n + c)? ^= ac;
|
||||||
|
let oc = mul(factor, *out.get(col * n + c)?);
|
||||||
|
*out.get_mut(r * n + c)? ^= oc;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `n choose k`, saturating.
|
||||||
|
fn choose(n: usize, k: usize) -> u64 {
|
||||||
|
let mut r: u64 = 1;
|
||||||
|
for i in 0..k.min(n) {
|
||||||
|
// Exact while it fits (r * (n - i) is divisible by i + 1); once it saturates it stays saturated.
|
||||||
|
r = match r.checked_mul(n.saturating_sub(i) as u64) {
|
||||||
|
Some(v) => v / (i as u64 + 1),
|
||||||
|
None => return u64::MAX,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if k > n { 0 } else { r }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// All `size`-element subsets of `0..n`, in lexicographic order, passed to `f` until it returns false.
|
||||||
|
fn each_subset(n: usize, size: usize, mut f: impl FnMut(&[usize]) -> bool) -> bool {
|
||||||
|
if size > n {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let mut idx: Vec<usize> = (0..size).collect();
|
||||||
|
loop {
|
||||||
|
if !f(&idx) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
// The rightmost position that can still move right.
|
||||||
|
let Some(i) = (0..size).rev().find(|&i| idx.get(i).is_some_and(|&v| v < n - size + i)) else {
|
||||||
|
return true;
|
||||||
|
};
|
||||||
|
let start = idx.get(i).copied().unwrap_or(0) + 1;
|
||||||
|
for (off, slot) in idx.iter_mut().enumerate().skip(i) {
|
||||||
|
*slot = start + (off - i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether `[I; P]` is MDS, i.e. every square submatrix of `P` is invertible (see the budgets above).
|
||||||
|
fn is_mds(p: &[u8], data: usize, parity: usize) -> bool {
|
||||||
|
if p.contains(&0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let total: u64 = (2..=data.min(parity))
|
||||||
|
.map(|s| choose(data, s).saturating_mul(choose(parity, s)))
|
||||||
|
.fold(0u64, u64::saturating_add);
|
||||||
|
let max_size = if total <= MDS_EXHAUSTIVE_BUDGET {
|
||||||
|
data.min(parity)
|
||||||
|
} else if choose(data, 2).saturating_mul(choose(parity, 2)) <= MDS_PAIRS_BUDGET {
|
||||||
|
2
|
||||||
|
} else {
|
||||||
|
1
|
||||||
|
};
|
||||||
|
for s in 2..=max_size {
|
||||||
|
let ok = each_subset(parity, s, |rows| {
|
||||||
|
each_subset(data, s, |cols| {
|
||||||
|
let sub: Vec<u8> = rows
|
||||||
|
.iter()
|
||||||
|
.flat_map(|&r| cols.iter().map(move |&c| p.get(r * data + c).copied().unwrap_or(0)))
|
||||||
|
.collect();
|
||||||
|
invert(sub, s).is_some()
|
||||||
|
})
|
||||||
|
});
|
||||||
|
if !ok {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ the code
|
||||||
|
|
||||||
/// Parity shards for `data_shards` at `fec_percentage`: `ceil(data × percentage / 100)`.
|
/// Parity shards for `data_shards` at `fec_percentage`: `ceil(data × percentage / 100)`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] when `data_shards` is 0 or the result would exceed [`MAX_SHARDS`]. Phase A:
|
/// [`Error::UnexpectedValue`] when `data_shards` is 0 or data + parity would exceed [`MAX_SHARDS`].
|
||||||
/// always [`crate::Error::Unimplemented`].
|
pub fn parity_count(data_shards: usize, fec_percentage: u8) -> Result<usize> {
|
||||||
pub fn parity_count(data_shards: usize, fec_percentage: u8) -> crate::Result<usize> {
|
let k = u64::try_from(data_shards).unwrap_or(u64::MAX);
|
||||||
let _ = (data_shards, fec_percentage);
|
let m = k.saturating_mul(u64::from(fec_percentage)).div_ceil(100);
|
||||||
Err(crate::Error::Unimplemented)
|
let m = usize::try_from(m).unwrap_or(usize::MAX);
|
||||||
|
if data_shards == 0 || data_shards.saturating_add(m) > MAX_SHARDS {
|
||||||
|
return Err(Error::UnexpectedValue { what: "fec shard count", value: k });
|
||||||
|
}
|
||||||
|
Ok(m)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One code: shard counts and its parity matrix.
|
/// One code: shard counts and its parity matrix.
|
||||||
@@ -31,25 +209,50 @@ pub struct ReedSolomon {
|
|||||||
parity_matrix: Vec<u8>,
|
parity_matrix: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn check_counts(data_shards: usize, parity_shards: usize) -> Result<()> {
|
||||||
|
let sum = data_shards.checked_add(parity_shards);
|
||||||
|
if data_shards == 0 || parity_shards == 0 || sum.is_none_or(|s| s > MAX_SHARDS) {
|
||||||
|
return Err(Error::UnexpectedValue {
|
||||||
|
what: "fec shard counts",
|
||||||
|
value: u64::try_from(data_shards).unwrap_or(u64::MAX),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
impl ReedSolomon {
|
impl ReedSolomon {
|
||||||
/// The code GameStream video uses for `data_shards` + `parity_shards` (UNKNOWN U14: construction).
|
/// The code GameStream video uses for `data_shards` + `parity_shards`: parity row `j` is the Cauchy row
|
||||||
|
/// `1 / ((parity_shards + i) XOR j)` (`docs/PROTOCOL.md` 5.3).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] when either count is 0 or the sum exceeds [`MAX_SHARDS`]. Phase A: always
|
/// [`Error::UnexpectedValue`] when either count is 0 or the sum exceeds [`MAX_SHARDS`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn new(data_shards: usize, parity_shards: usize) -> Result<Self> {
|
||||||
pub fn new(data_shards: usize, parity_shards: usize) -> crate::Result<Self> {
|
check_counts(data_shards, parity_shards)?;
|
||||||
let _ = (data_shards, parity_shards);
|
let mut parity_matrix = Vec::with_capacity(data_shards * parity_shards);
|
||||||
Err(crate::Error::Unimplemented)
|
for j in 0..parity_shards {
|
||||||
|
for i in 0..data_shards {
|
||||||
|
// parity + i <= 254 and j < parity, so the XOR is never zero.
|
||||||
|
parity_matrix.push(inv(((parity_shards + i) ^ j) as u8));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self { data_shards, parity_shards, parity_matrix })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A code with an explicit parity matrix (`parity_shards × data_shards`, row-major). The matrix must make every
|
/// A code with an explicit parity matrix (`parity_shards × data_shards`, row-major). The matrix must make every
|
||||||
/// square submatrix of `[I; P]` invertible, or some loss patterns cannot be rebuilt; this is checked.
|
/// square submatrix of `[I; P]` invertible, or some loss patterns cannot be rebuilt; this is checked
|
||||||
|
/// exhaustively for small matrices and by its 1 × 1 and 2 × 2 minors for large ones.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`Self::new`]; [`crate::Error::Malformed`] for a matrix of the wrong size or one that is not MDS.
|
/// As [`Self::new`]; [`Error::Malformed`] for a matrix of the wrong size or one that is not MDS.
|
||||||
pub fn with_parity_matrix(data_shards: usize, parity_shards: usize, parity_matrix: &[u8]) -> crate::Result<Self> {
|
pub fn with_parity_matrix(data_shards: usize, parity_shards: usize, parity_matrix: &[u8]) -> Result<Self> {
|
||||||
let _ = (data_shards, parity_shards, parity_matrix);
|
check_counts(data_shards, parity_shards)?;
|
||||||
Err(crate::Error::Unimplemented)
|
if parity_matrix.len() != data_shards * parity_shards {
|
||||||
|
return Err(malformed("fec parity matrix size"));
|
||||||
|
}
|
||||||
|
if !is_mds(parity_matrix, data_shards, parity_shards) {
|
||||||
|
return Err(malformed("fec parity matrix is not MDS"));
|
||||||
|
}
|
||||||
|
Ok(Self { data_shards, parity_shards, parity_matrix: parity_matrix.to_vec() })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Number of data shards.
|
/// Number of data shards.
|
||||||
@@ -70,26 +273,109 @@ impl ReedSolomon {
|
|||||||
&self.parity_matrix
|
&self.parity_matrix
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn coefficient(&self, row: usize, col: usize) -> u8 {
|
||||||
|
self.parity_matrix.get(row * self.data_shards + col).copied().unwrap_or(0)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One parity row over the given data shards.
|
||||||
|
fn parity_row(&self, row: usize, data: &[&[u8]], len: usize) -> Vec<u8> {
|
||||||
|
let mut out = vec![0u8; len];
|
||||||
|
for (i, d) in data.iter().enumerate() {
|
||||||
|
mul_add(&mut out, d, self.coefficient(row, i));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
/// Computes the parity shards from the data shards. `shards` holds `data + parity` buffers of equal length;
|
/// Computes the parity shards from the data shards. `shards` holds `data + parity` buffers of equal length;
|
||||||
/// the parity ones are overwritten.
|
/// the parity ones are overwritten.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for the wrong shard count or unequal lengths, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for the wrong shard count or unequal lengths, [`Error::TooLarge`] over
|
||||||
/// [`MAX_SHARD_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`MAX_SHARD_BYTES`].
|
||||||
pub fn encode(&self, shards: &mut [Vec<u8>]) -> crate::Result<()> {
|
pub fn encode(&self, shards: &mut [Vec<u8>]) -> Result<()> {
|
||||||
let _ = shards;
|
if shards.len() != self.data_shards + self.parity_shards {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("fec shard count"));
|
||||||
|
}
|
||||||
|
let len = shards.first().map_or(0, Vec::len);
|
||||||
|
if shards.iter().any(|s| s.len() != len) {
|
||||||
|
return Err(malformed("fec shards of unequal length"));
|
||||||
|
}
|
||||||
|
cap("fec shard", MAX_SHARD_BYTES, len)?;
|
||||||
|
let (data, parity) = shards.split_at_mut(self.data_shards);
|
||||||
|
let data: Vec<&[u8]> = data.iter().map(Vec::as_slice).collect();
|
||||||
|
for (j, p) in parity.iter_mut().enumerate() {
|
||||||
|
*p = self.parity_row(j, &data, len);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Rebuilds missing shards in place. `shards` holds `data + parity` entries, `None` for lost ones; on success
|
/// Rebuilds missing shards in place. `shards` holds `data + parity` entries, `None` for lost ones; on success
|
||||||
/// every entry is `Some`.
|
/// every entry is `Some`, and present entries are never changed.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for the wrong count or unequal lengths, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for the wrong count, unequal lengths, or a singular system (a matrix that was not
|
||||||
/// [`MAX_SHARD_BYTES`], [`crate::Error::Truncated`] when fewer than `data` shards are present. Phase A: always
|
/// MDS), [`Error::TooLarge`] over [`MAX_SHARD_BYTES`], [`Error::Truncated`] when fewer than `data` shards are
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// present.
|
||||||
pub fn reconstruct(&self, shards: &mut [Option<Vec<u8>>]) -> crate::Result<()> {
|
pub fn reconstruct(&self, shards: &mut [Option<Vec<u8>>]) -> Result<()> {
|
||||||
let _ = shards;
|
let k = self.data_shards;
|
||||||
Err(crate::Error::Unimplemented)
|
if shards.len() != k + self.parity_shards {
|
||||||
|
return Err(malformed("fec shard count"));
|
||||||
|
}
|
||||||
|
let len = shards.iter().flatten().next().map_or(0, Vec::len);
|
||||||
|
if shards.iter().flatten().any(|s| s.len() != len) {
|
||||||
|
return Err(malformed("fec shards of unequal length"));
|
||||||
|
}
|
||||||
|
cap("fec shard", MAX_SHARD_BYTES, len)?;
|
||||||
|
let present = shards.iter().flatten().count();
|
||||||
|
if present < k {
|
||||||
|
return Err(Error::Truncated { what: "fec shards", needed: k, actual: present });
|
||||||
|
}
|
||||||
|
let missing: Vec<usize> = (0..k).filter(|&i| shards.get(i).is_some_and(Option::is_none)).collect();
|
||||||
|
if !missing.is_empty() {
|
||||||
|
let rows: Vec<usize> = (0..self.parity_shards)
|
||||||
|
.filter(|&j| shards.get(k + j).is_some_and(Option::is_some))
|
||||||
|
.take(missing.len())
|
||||||
|
.collect();
|
||||||
|
let e = missing.len();
|
||||||
|
let a: Vec<u8> = rows
|
||||||
|
.iter()
|
||||||
|
.flat_map(|&r| missing.iter().map(move |&c| (r, c)))
|
||||||
|
.map(|(r, c)| self.coefficient(r, c))
|
||||||
|
.collect();
|
||||||
|
let a_inv = invert(a, e).ok_or(malformed("fec system is singular (matrix not MDS)"))?;
|
||||||
|
// rhs_r = parity_r - sum over present data of P[r][i] * d_i
|
||||||
|
let mut rhs: Vec<Vec<u8>> = Vec::with_capacity(e);
|
||||||
|
for &r in &rows {
|
||||||
|
let mut v = shards.get(k + r).and_then(Option::as_ref).cloned().unwrap_or_default();
|
||||||
|
for i in (0..k).filter(|i| !missing.contains(i)) {
|
||||||
|
if let Some(Some(d)) = shards.get(i) {
|
||||||
|
mul_add(&mut v, d, self.coefficient(r, i));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rhs.push(v);
|
||||||
|
}
|
||||||
|
for (c, &slot) in missing.iter().enumerate() {
|
||||||
|
let mut out = vec![0u8; len];
|
||||||
|
for (r, v) in rhs.iter().enumerate() {
|
||||||
|
mul_add(&mut out, v, a_inv.get(c * e + r).copied().unwrap_or(0));
|
||||||
|
}
|
||||||
|
if let Some(s) = shards.get_mut(slot) {
|
||||||
|
*s = Some(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let parity_missing: Vec<usize> =
|
||||||
|
(0..self.parity_shards).filter(|&j| shards.get(k + j).is_some_and(Option::is_none)).collect();
|
||||||
|
if !parity_missing.is_empty() {
|
||||||
|
let data: Vec<&[u8]> = shards.iter().take(k).flatten().map(Vec::as_slice).collect();
|
||||||
|
let rebuilt: Vec<(usize, Vec<u8>)> =
|
||||||
|
parity_missing.iter().map(|&j| (j, self.parity_row(j, &data, len))).collect();
|
||||||
|
for (j, p) in rebuilt {
|
||||||
|
if let Some(s) = shards.get_mut(k + j) {
|
||||||
|
*s = Some(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,8 @@
|
|||||||
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
|
//! `GET /applist` (`docs/PROTOCOL.md` 1.3).
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{cap, malformed, parse_u32};
|
||||||
|
|
||||||
/// Maximum size of an applist body, in bytes.
|
/// Maximum size of an applist body, in bytes.
|
||||||
pub const MAX_APPLIST_BYTES: usize = 1024 * 1024;
|
pub const MAX_APPLIST_BYTES: usize = 1024 * 1024;
|
||||||
/// Maximum number of apps accepted in one list.
|
/// Maximum number of apps accepted in one list.
|
||||||
@@ -18,13 +21,28 @@ pub struct App {
|
|||||||
pub hdr_supported: bool,
|
pub hdr_supported: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses an applist body. Apps keep the host's order; duplicate ids are refused.
|
/// Parses an applist body. Apps keep the host's order; duplicate ids are refused; other elements are ignored.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_APPLIST_BYTES`], [`MAX_APPS`] or [`MAX_APP_TITLE_BYTES`],
|
/// [`crate::Error::TooLarge`] over [`MAX_APPLIST_BYTES`], [`MAX_APPS`] or [`MAX_APP_TITLE_BYTES`],
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for an `App` without `ID` or
|
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for an `App` without `ID` or
|
||||||
/// `AppTitle`. Phase A: always [`crate::Error::Unimplemented`].
|
/// `AppTitle`, a bad `ID`, or a duplicate `ID`.
|
||||||
pub fn parse_app_list(body: &[u8]) -> crate::Result<Vec<App>> {
|
pub fn parse_app_list(body: &[u8]) -> Result<Vec<App>> {
|
||||||
let _ = body;
|
let doc = super::document(body, MAX_APPLIST_BYTES, "applist")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let count = doc.root.children.iter().filter(|c| c.name == "App").count();
|
||||||
|
cap("applist apps", MAX_APPS, count)?;
|
||||||
|
let mut apps: Vec<App> = Vec::with_capacity(count);
|
||||||
|
let mut ids = std::collections::BTreeSet::new();
|
||||||
|
for e in doc.root.children.iter().filter(|c| c.name == "App") {
|
||||||
|
let title = e.child("AppTitle").ok_or(malformed("applist: App without AppTitle"))?;
|
||||||
|
cap("applist AppTitle", MAX_APP_TITLE_BYTES, title.text.len())?;
|
||||||
|
let id = e.child("ID").ok_or(malformed("applist: App without ID"))?;
|
||||||
|
let id = parse_u32("applist ID", &id.text)?;
|
||||||
|
if !ids.insert(id) {
|
||||||
|
return Err(malformed("applist: duplicate ID"));
|
||||||
|
}
|
||||||
|
let hdr_supported = e.child("IsHdrSupported").is_some_and(|h| h.text == "1");
|
||||||
|
apps.push(App { id, title: title.text.clone(), hdr_supported });
|
||||||
|
}
|
||||||
|
Ok(apps)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
//! `GET /launch` and `GET /resume` (`docs/PROTOCOL.md` 1.4).
|
//! `GET /launch` and `GET /resume` (`docs/PROTOCOL.md` 1.4).
|
||||||
|
|
||||||
use super::HttpRequest;
|
use super::{HttpRequest, Scheme, build, check_unique_id};
|
||||||
use crate::SessionKeys;
|
use crate::util::{cap, check_rtsp_url, hex_encode, malformed};
|
||||||
|
use crate::{Result, SessionKeys};
|
||||||
|
|
||||||
/// Maximum size of a launch or resume answer, in bytes.
|
/// Maximum size of a launch or resume answer, in bytes.
|
||||||
pub const MAX_LAUNCH_RESPONSE_BYTES: usize = 16 * 1024;
|
pub const MAX_LAUNCH_RESPONSE_BYTES: usize = 16 * 1024;
|
||||||
@@ -19,6 +20,35 @@ pub enum AudioLayout {
|
|||||||
Surround71,
|
Surround71,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl AudioLayout {
|
||||||
|
/// Channel count.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn channels(self) -> u8 {
|
||||||
|
match self {
|
||||||
|
Self::Stereo => 2,
|
||||||
|
Self::Surround51 => 6,
|
||||||
|
Self::Surround71 => 8,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The speaker mask (WAVE channel-mask bits: FL FR, + FC LFE BL BR, + SL SR). Stereo's `0x3` matches the
|
||||||
|
/// documented default `surroundAudioInfo` 0x30002 (source M); the surround masks are the standard layouts (U4).
|
||||||
|
#[must_use]
|
||||||
|
pub const fn channel_mask(self) -> u32 {
|
||||||
|
match self {
|
||||||
|
Self::Stereo => 0x0003,
|
||||||
|
Self::Surround51 => 0x003F,
|
||||||
|
Self::Surround71 => 0x063F,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `surroundAudioInfo`: `(channel_mask << 16) | channel_count`.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn surround_audio_info(self) -> u32 {
|
||||||
|
(self.channel_mask() << 16) | self.channels() as u32
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// What to launch and how.
|
/// What to launch and how.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct LaunchParams {
|
pub struct LaunchParams {
|
||||||
@@ -50,20 +80,43 @@ pub struct LaunchResponse {
|
|||||||
/// Builds `GET /launch` (HTTPS).
|
/// Builds `GET /launch` (HTTPS).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a zero size or frame rate, or a bad `unique_id`. Phase A: always
|
/// [`crate::Error::Malformed`] for a zero size or frame rate, or a bad `unique_id`.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn launch_request(params: &LaunchParams, unique_id: &str) -> Result<HttpRequest> {
|
||||||
pub fn launch_request(params: &LaunchParams, unique_id: &str) -> crate::Result<HttpRequest> {
|
check_unique_id(unique_id)?;
|
||||||
let _ = (params, unique_id);
|
if params.width == 0 || params.height == 0 || params.fps == 0 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("launch mode"));
|
||||||
|
}
|
||||||
|
let app = params.app_id.to_string();
|
||||||
|
let mode = format!("{}x{}x{}", params.width, params.height, params.fps);
|
||||||
|
let rikey = hex_encode(¶ms.keys.rikey);
|
||||||
|
let rikeyid = params.keys.rikeyid.to_string();
|
||||||
|
let hdr = if params.hdr { "1" } else { "0" };
|
||||||
|
let audio = params.audio.surround_audio_info().to_string();
|
||||||
|
Ok(build(
|
||||||
|
Scheme::Https,
|
||||||
|
"/launch",
|
||||||
|
&[
|
||||||
|
("uniqueid", unique_id),
|
||||||
|
("appid", &app),
|
||||||
|
("mode", &mode),
|
||||||
|
("rikey", &rikey),
|
||||||
|
("rikeyid", &rikeyid),
|
||||||
|
("hdrMode", hdr),
|
||||||
|
("surroundAudioInfo", &audio),
|
||||||
|
],
|
||||||
|
None,
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /resume` (HTTPS) with fresh keys.
|
/// Builds `GET /resume` (HTTPS) with fresh keys.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`launch_request`].
|
/// As [`launch_request`].
|
||||||
pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = (keys, unique_id);
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let rikey = hex_encode(&keys.rikey);
|
||||||
|
let rikeyid = keys.rikeyid.to_string();
|
||||||
|
Ok(build(Scheme::Https, "/resume", &[("uniqueid", unique_id), ("rikey", &rikey), ("rikeyid", &rikeyid)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a launch or resume answer.
|
/// Parses a launch or resume answer.
|
||||||
@@ -71,8 +124,17 @@ pub fn resume_request(keys: &SessionKeys, unique_id: &str) -> crate::Result<Http
|
|||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_LAUNCH_RESPONSE_BYTES`] or [`MAX_SESSION_URL_BYTES`],
|
/// [`crate::Error::TooLarge`] over [`MAX_LAUNCH_RESPONSE_BYTES`] or [`MAX_SESSION_URL_BYTES`],
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `sessionUrl0` that is not an
|
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `sessionUrl0` that is not an
|
||||||
/// `rtsp://host:port` URL. Phase A: always [`crate::Error::Unimplemented`].
|
/// `rtsp://host:port` URL.
|
||||||
pub fn parse_launch_response(body: &[u8]) -> crate::Result<LaunchResponse> {
|
pub fn parse_launch_response(body: &[u8]) -> Result<LaunchResponse> {
|
||||||
let _ = body;
|
let doc = super::document(body, MAX_LAUNCH_RESPONSE_BYTES, "launch answer")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let game_session = doc.root.child("gamesession").is_some_and(|g| g.text == "1");
|
||||||
|
let session_url = match doc.root.child("sessionUrl0") {
|
||||||
|
None => None,
|
||||||
|
Some(e) => {
|
||||||
|
cap("sessionUrl0", MAX_SESSION_URL_BYTES, e.text.len())?;
|
||||||
|
check_rtsp_url("sessionUrl0", &e.text)?;
|
||||||
|
Some(e.text.clone())
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(LaunchResponse { game_session, session_url })
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,6 +7,9 @@
|
|||||||
|
|
||||||
use core::time::Duration;
|
use core::time::Duration;
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{malformed, percent_encode};
|
||||||
|
|
||||||
pub mod applist;
|
pub mod applist;
|
||||||
pub mod launch;
|
pub mod launch;
|
||||||
pub mod serverinfo;
|
pub mod serverinfo;
|
||||||
@@ -47,49 +50,79 @@ pub struct HttpRequest {
|
|||||||
pub timeout: Option<Duration>,
|
pub timeout: Option<Duration>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Checks a client `uniqueid`: 1..=[`MAX_UNIQUE_ID_BYTES`] of letters, digits, `-` and `_` (our own ids are hex).
|
||||||
|
pub(crate) fn check_unique_id(unique_id: &str) -> Result<()> {
|
||||||
|
if unique_id.is_empty()
|
||||||
|
|| unique_id.len() > MAX_UNIQUE_ID_BYTES
|
||||||
|
|| !unique_id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
|
||||||
|
{
|
||||||
|
return Err(malformed("uniqueid"));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `path?k=v&…` with every value percent-encoded.
|
||||||
|
pub(crate) fn build(scheme: Scheme, path: &str, params: &[(&str, &str)], timeout: Option<Duration>) -> HttpRequest {
|
||||||
|
let mut s = String::from(path);
|
||||||
|
for (i, (k, v)) in params.iter().enumerate() {
|
||||||
|
s.push(if i == 0 { '?' } else { '&' });
|
||||||
|
s.push_str(k);
|
||||||
|
s.push('=');
|
||||||
|
s.push_str(&percent_encode(v));
|
||||||
|
}
|
||||||
|
HttpRequest { scheme, path_and_query: s, timeout }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses `body` as XML after checking it against `max` bytes, and refuses a non-200 status.
|
||||||
|
pub(crate) fn document(body: &[u8], max: usize, what: &'static str) -> Result<xml::Document> {
|
||||||
|
crate::util::cap(what, max, body.len())?;
|
||||||
|
let d = xml::parse(body)?;
|
||||||
|
if d.status_code != 200 {
|
||||||
|
return Err(crate::Error::HostStatus { code: d.status_code });
|
||||||
|
}
|
||||||
|
Ok(d)
|
||||||
|
}
|
||||||
|
|
||||||
/// Builds `GET /serverinfo` for this client.
|
/// Builds `GET /serverinfo` for this client.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for an empty or oversized `unique_id`. Phase A: always
|
/// [`crate::Error::Malformed`] for an empty, oversized or non-alphanumeric `unique_id`.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn server_info_request(scheme: Scheme, unique_id: &str) -> Result<HttpRequest> {
|
||||||
pub fn server_info_request(scheme: Scheme, unique_id: &str) -> crate::Result<HttpRequest> {
|
check_unique_id(unique_id)?;
|
||||||
let _ = (scheme, unique_id);
|
Ok(build(scheme, "/serverinfo", &[("uniqueid", unique_id)], None))
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /applist` (HTTPS).
|
/// Builds `GET /applist` (HTTPS).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`server_info_request`].
|
/// As [`server_info_request`].
|
||||||
pub fn app_list_request(unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn app_list_request(unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = unique_id;
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(build(Scheme::Https, "/applist", &[("uniqueid", unique_id)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /cancel` (HTTPS): quits the app running on the host.
|
/// Builds `GET /cancel` (HTTPS): quits the app running on the host.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`server_info_request`].
|
/// As [`server_info_request`].
|
||||||
pub fn cancel_request(unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn cancel_request(unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = unique_id;
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(build(Scheme::Https, "/cancel", &[("uniqueid", unique_id)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds `GET /unpair` (HTTPS): the host forgets this client.
|
/// Builds `GET /unpair` (HTTPS): the host forgets this client.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`server_info_request`].
|
/// As [`server_info_request`].
|
||||||
pub fn unpair_request(unique_id: &str) -> crate::Result<HttpRequest> {
|
pub fn unpair_request(unique_id: &str) -> Result<HttpRequest> {
|
||||||
let _ = unique_id;
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(build(Scheme::Https, "/unpair", &[("uniqueid", unique_id)], None))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Checks a plain `<root status_code="200"/>` answer (cancel, unpair).
|
/// Checks a plain `<root status_code="200"/>` answer (cancel, unpair).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 status, parser errors as [`xml::parse`]. Phase A: always
|
/// [`crate::Error::HostStatus`] for a non-200 status, parser errors as [`xml::parse`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn parse_status_response(body: &[u8]) -> Result<()> {
|
||||||
pub fn parse_status_response(body: &[u8]) -> crate::Result<()> {
|
document(body, xml::MAX_XML_BYTES, "status answer").map(|_| ())
|
||||||
let _ = body;
|
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
//! `GET /serverinfo` (`docs/PROTOCOL.md` 1.2).
|
//! `GET /serverinfo` (`docs/PROTOCOL.md` 1.2).
|
||||||
|
|
||||||
|
use super::xml::Element;
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{cap, hex_decode, malformed, parse_dec, parse_u16, parse_u32};
|
||||||
|
|
||||||
/// Maximum size of a serverinfo body, in bytes.
|
/// Maximum size of a serverinfo body, in bytes.
|
||||||
pub const MAX_SERVERINFO_BYTES: usize = 64 * 1024;
|
pub const MAX_SERVERINFO_BYTES: usize = 64 * 1024;
|
||||||
/// Maximum length of any string field in serverinfo, in bytes.
|
/// Maximum length of any string field in serverinfo, in bytes.
|
||||||
@@ -40,19 +44,86 @@ impl ServerInfo {
|
|||||||
/// Whether the host reports a running app (`state` ends in `_BUSY` or `currentgame != 0`).
|
/// Whether the host reports a running app (`state` ends in `_BUSY` or `currentgame != 0`).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today; the `Result` leaves room for stricter state checks.
|
||||||
pub fn is_busy(&self) -> crate::Result<bool> {
|
pub fn is_busy(&self) -> Result<bool> {
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(self.state.ends_with("_BUSY") || self.current_game != 0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The text of field `name` if present, after the field cap; `None` when missing.
|
||||||
|
fn field<'a>(root: &'a Element, name: &str) -> Result<Option<&'a str>> {
|
||||||
|
match root.child(name) {
|
||||||
|
Some(e) => {
|
||||||
|
cap("serverinfo field", MAX_SERVERINFO_FIELD_BYTES, e.text.len())?;
|
||||||
|
Ok(Some(e.text.as_str()))
|
||||||
|
}
|
||||||
|
None => Ok(None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Present and non-empty.
|
||||||
|
fn non_empty<'a>(root: &'a Element, name: &str) -> Result<Option<&'a str>> {
|
||||||
|
Ok(field(root, name)?.filter(|t| !t.is_empty()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_mac(s: &str) -> Result<[u8; 6]> {
|
||||||
|
let mut out = [0u8; 6];
|
||||||
|
let mut parts = s.split(':');
|
||||||
|
for slot in &mut out {
|
||||||
|
let part = parts.next().filter(|p| p.len() == 2).ok_or(malformed("serverinfo mac"))?;
|
||||||
|
let b = hex_decode("serverinfo mac", part)?;
|
||||||
|
*slot = b.first().copied().ok_or(malformed("serverinfo mac"))?;
|
||||||
|
}
|
||||||
|
if parts.next().is_some() {
|
||||||
|
return Err(malformed("serverinfo mac"));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
/// Parses a serverinfo body.
|
/// Parses a serverinfo body.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_SERVERINFO_BYTES`], [`crate::Error::HostStatus`] for a non-200 answer,
|
/// [`crate::Error::TooLarge`] over [`MAX_SERVERINFO_BYTES`] or [`MAX_SERVERINFO_FIELD_BYTES`],
|
||||||
/// [`crate::Error::Malformed`] for a missing required element (`hostname`, `uniqueid`, `HttpsPort`) or a bad
|
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a missing required element
|
||||||
/// number. Phase A: always [`crate::Error::Unimplemented`].
|
/// (`hostname`, `uniqueid`, `HttpsPort`) or a bad number.
|
||||||
pub fn parse_server_info(body: &[u8]) -> crate::Result<ServerInfo> {
|
pub fn parse_server_info(body: &[u8]) -> Result<ServerInfo> {
|
||||||
let _ = body;
|
let doc = super::document(body, MAX_SERVERINFO_BYTES, "serverinfo")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let r = &doc.root;
|
||||||
|
// Cap every field first, so an oversized field is TooLarge whatever else is wrong.
|
||||||
|
for c in &r.children {
|
||||||
|
cap("serverinfo field", MAX_SERVERINFO_FIELD_BYTES, c.text.len())?;
|
||||||
|
}
|
||||||
|
let hostname = non_empty(r, "hostname")?.ok_or(malformed("serverinfo: no hostname"))?.to_owned();
|
||||||
|
let unique_id = non_empty(r, "uniqueid")?.ok_or(malformed("serverinfo: no uniqueid"))?.to_owned();
|
||||||
|
let https_port =
|
||||||
|
parse_u16("serverinfo HttpsPort", field(r, "HttpsPort")?.ok_or(malformed("serverinfo: no HttpsPort"))?)?;
|
||||||
|
let http_port = non_empty(r, "ExternalPort")?.map(|p| parse_u16("serverinfo ExternalPort", p)).transpose()?;
|
||||||
|
let mac = non_empty(r, "mac")?.map(parse_mac).transpose()?;
|
||||||
|
let max_luma_pixels_hevc =
|
||||||
|
non_empty(r, "MaxLumaPixelsHEVC")?.map(|v| parse_dec("serverinfo MaxLumaPixelsHEVC", v)).transpose()?;
|
||||||
|
let codec_mode_support = non_empty(r, "ServerCodecModeSupport")?
|
||||||
|
.map(|v| parse_u32("serverinfo ServerCodecModeSupport", v))
|
||||||
|
.transpose()?;
|
||||||
|
let paired = match non_empty(r, "PairStatus")? {
|
||||||
|
None | Some("0") => false,
|
||||||
|
Some("1") => true,
|
||||||
|
Some(_) => return Err(malformed("serverinfo PairStatus")),
|
||||||
|
};
|
||||||
|
let current_game =
|
||||||
|
non_empty(r, "currentgame")?.map(|v| parse_u32("serverinfo currentgame", v)).transpose()?.unwrap_or(0);
|
||||||
|
Ok(ServerInfo {
|
||||||
|
hostname,
|
||||||
|
app_version: field(r, "appversion")?.unwrap_or_default().to_owned(),
|
||||||
|
gfe_version: non_empty(r, "GfeVersion")?.map(str::to_owned),
|
||||||
|
unique_id,
|
||||||
|
https_port,
|
||||||
|
http_port,
|
||||||
|
mac,
|
||||||
|
local_ip: non_empty(r, "LocalIP")?.map(str::to_owned),
|
||||||
|
max_luma_pixels_hevc,
|
||||||
|
codec_mode_support,
|
||||||
|
paired,
|
||||||
|
current_game,
|
||||||
|
state: field(r, "state")?.unwrap_or_default().to_owned(),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,12 @@
|
|||||||
//! A small, strict XML reader for the host's answers: one `<root status_code="…">` element with nested
|
//! A small, strict XML reader for the host's answers: one `<root status_code="…">` element with nested
|
||||||
//! elements and text. No DTD, no entities beyond the five predefined ones and numeric character references,
|
//! elements and text. No DTD, no entities beyond the five predefined ones and numeric character references,
|
||||||
//! no processing instructions except a leading XML declaration, no namespaces.
|
//! no processing instructions except a leading XML declaration, no comments, no CDATA, no namespaces.
|
||||||
|
//!
|
||||||
|
//! The reader is iterative (an explicit stack), so nesting cannot exhaust the call stack, and every cap is checked
|
||||||
|
//! before the memory it guards is used.
|
||||||
|
|
||||||
|
use crate::Result;
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
|
||||||
/// Maximum size of any XML body accepted, in bytes.
|
/// Maximum size of any XML body accepted, in bytes.
|
||||||
pub const MAX_XML_BYTES: usize = 1024 * 1024;
|
pub const MAX_XML_BYTES: usize = 1024 * 1024;
|
||||||
@@ -13,6 +19,9 @@ pub const MAX_XML_TEXT_BYTES: usize = 64 * 1024;
|
|||||||
/// Maximum number of attributes on one element.
|
/// Maximum number of attributes on one element.
|
||||||
pub const MAX_XML_ATTRIBUTES: usize = 8;
|
pub const MAX_XML_ATTRIBUTES: usize = 8;
|
||||||
|
|
||||||
|
/// Longest entity or character reference body accepted (`#x10FFFF` is 8).
|
||||||
|
const MAX_ENTITY_LEN: usize = 10;
|
||||||
|
|
||||||
/// One element: its name, attributes, text (concatenated, unescaped, not trimmed) and child elements.
|
/// One element: its name, attributes, text (concatenated, unescaped, not trimmed) and child elements.
|
||||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||||
pub struct Element {
|
pub struct Element {
|
||||||
@@ -26,6 +35,20 @@ pub struct Element {
|
|||||||
pub children: Vec<Element>,
|
pub children: Vec<Element>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Element {
|
||||||
|
/// The first child with this name.
|
||||||
|
#[must_use]
|
||||||
|
pub fn child(&self, name: &str) -> Option<&Element> {
|
||||||
|
self.children.iter().find(|c| c.name == name)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The value of the first attribute with this name.
|
||||||
|
#[must_use]
|
||||||
|
pub fn attribute(&self, name: &str) -> Option<&str> {
|
||||||
|
self.attributes.iter().find(|(n, _)| n == name).map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A parsed host answer.
|
/// A parsed host answer.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct Document {
|
pub struct Document {
|
||||||
@@ -41,8 +64,268 @@ pub struct Document {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_XML_BYTES`] or any other cap, [`crate::Error::Malformed`] for anything that
|
/// [`crate::Error::TooLarge`] over [`MAX_XML_BYTES`] or any other cap, [`crate::Error::Malformed`] for anything that
|
||||||
/// is not well-formed or uses a refused feature. Phase A: always [`crate::Error::Unimplemented`].
|
/// is not well-formed or uses a refused feature.
|
||||||
pub fn parse(body: &[u8]) -> crate::Result<Document> {
|
pub fn parse(body: &[u8]) -> Result<Document> {
|
||||||
let _ = body;
|
cap("xml document", MAX_XML_BYTES, body.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let text = core::str::from_utf8(body).map_err(|_| malformed("xml: not UTF-8"))?;
|
||||||
|
let root = Reader { s: text, b: text.as_bytes(), pos: 0, elements: 0 }.document()?;
|
||||||
|
if root.name != "root" {
|
||||||
|
return Err(malformed("xml: root element is not `root`"));
|
||||||
|
}
|
||||||
|
let code = root.attribute("status_code").ok_or(malformed("xml: no status_code"))?;
|
||||||
|
let status_code = crate::util::parse_u32("xml status_code", code)?;
|
||||||
|
let status_message = root.attribute("status_message").map(str::to_owned);
|
||||||
|
Ok(Document { status_code, status_message, root })
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Reader<'a> {
|
||||||
|
s: &'a str,
|
||||||
|
b: &'a [u8],
|
||||||
|
pos: usize,
|
||||||
|
elements: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_name_start(c: u8) -> bool {
|
||||||
|
c.is_ascii_alphabetic() || c == b'_'
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_name_char(c: u8) -> bool {
|
||||||
|
c.is_ascii_alphanumeric() || matches!(c, b'_' | b'-' | b'.')
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_space(c: u8) -> bool {
|
||||||
|
matches!(c, b' ' | b'\t' | b'\r' | b'\n')
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Reader<'_> {
|
||||||
|
fn peek(&self) -> Option<u8> {
|
||||||
|
self.b.get(self.pos).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn peek_at(&self, ahead: usize) -> Option<u8> {
|
||||||
|
self.b.get(self.pos.saturating_add(ahead)).copied()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rest(&self) -> &[u8] {
|
||||||
|
self.b.get(self.pos..).unwrap_or(&[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn skip_ws(&mut self) -> bool {
|
||||||
|
let start = self.pos;
|
||||||
|
while self.peek().is_some_and(is_space) {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
self.pos > start
|
||||||
|
}
|
||||||
|
|
||||||
|
fn expect(&mut self, c: u8, what: &'static str) -> Result<()> {
|
||||||
|
if self.peek() == Some(c) {
|
||||||
|
self.pos += 1;
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(malformed(what))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn name(&mut self) -> Result<String> {
|
||||||
|
let start = self.pos;
|
||||||
|
if !self.peek().is_some_and(is_name_start) {
|
||||||
|
return Err(malformed("xml: bad name"));
|
||||||
|
}
|
||||||
|
while self.peek().is_some_and(is_name_char) {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
if self.peek() == Some(b':') {
|
||||||
|
return Err(malformed("xml: namespaces are refused"));
|
||||||
|
}
|
||||||
|
self.s.get(start..self.pos).map(str::to_owned).ok_or(malformed("xml: bad name"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The optional leading `<?xml …?>`, only at byte 0.
|
||||||
|
fn declaration(&mut self) -> Result<()> {
|
||||||
|
if self.rest().starts_with(b"<?xml") && self.peek_at(5).is_some_and(|c| is_space(c) || c == b'?') {
|
||||||
|
let end = self.rest().windows(2).position(|w| w == b"?>").ok_or(malformed("xml: unclosed declaration"))?;
|
||||||
|
self.pos += end + 2;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attach(stack: &mut [Element], root: &mut Option<Element>, element: Element) {
|
||||||
|
match stack.last_mut() {
|
||||||
|
Some(parent) => parent.children.push(element),
|
||||||
|
None => *root = Some(element),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn document(mut self) -> Result<Element> {
|
||||||
|
self.declaration()?;
|
||||||
|
self.skip_ws();
|
||||||
|
let mut stack: Vec<Element> = Vec::new();
|
||||||
|
let mut root: Option<Element> = None;
|
||||||
|
while let Some(c) = self.peek() {
|
||||||
|
if c == b'<' {
|
||||||
|
if root.is_some() {
|
||||||
|
return Err(malformed("xml: content after the root element"));
|
||||||
|
}
|
||||||
|
match self.peek_at(1) {
|
||||||
|
Some(b'/') => {
|
||||||
|
self.pos += 2;
|
||||||
|
let name = self.name()?;
|
||||||
|
self.skip_ws();
|
||||||
|
self.expect(b'>', "xml: bad end tag")?;
|
||||||
|
let done = stack.pop().ok_or(malformed("xml: end tag without start"))?;
|
||||||
|
if done.name != name {
|
||||||
|
return Err(malformed("xml: mismatched end tag"));
|
||||||
|
}
|
||||||
|
Self::attach(&mut stack, &mut root, done);
|
||||||
|
}
|
||||||
|
Some(b'!' | b'?') => return Err(malformed("xml: DTD, comment, CDATA or PI refused")),
|
||||||
|
_ => {
|
||||||
|
self.pos += 1;
|
||||||
|
let (element, closed) = self.start_tag()?;
|
||||||
|
self.elements += 1;
|
||||||
|
cap("xml elements", MAX_XML_ELEMENTS, self.elements)?;
|
||||||
|
cap("xml depth", MAX_XML_DEPTH, stack.len() + 1)?;
|
||||||
|
if closed {
|
||||||
|
Self::attach(&mut stack, &mut root, element);
|
||||||
|
} else {
|
||||||
|
stack.push(element);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let already = stack.last().map_or(0, |t| t.text.len());
|
||||||
|
let text = self.text(already)?;
|
||||||
|
match stack.last_mut() {
|
||||||
|
Some(top) => top.text.push_str(&text),
|
||||||
|
None => {
|
||||||
|
if !text.bytes().all(is_space) {
|
||||||
|
return Err(malformed("xml: text outside the root element"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !stack.is_empty() {
|
||||||
|
return Err(malformed("xml: unclosed element"));
|
||||||
|
}
|
||||||
|
root.ok_or(malformed("xml: no root element"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// After `<`: name, attributes, `>` or `/>`. Returns the element and whether it was self-closing.
|
||||||
|
fn start_tag(&mut self) -> Result<(Element, bool)> {
|
||||||
|
let name = self.name()?;
|
||||||
|
let mut attributes: Vec<(String, String)> = Vec::new();
|
||||||
|
loop {
|
||||||
|
let had_ws = self.skip_ws();
|
||||||
|
match self.peek() {
|
||||||
|
Some(b'>') => {
|
||||||
|
self.pos += 1;
|
||||||
|
return Ok((Element { name, attributes, ..Element::default() }, false));
|
||||||
|
}
|
||||||
|
Some(b'/') => {
|
||||||
|
self.pos += 1;
|
||||||
|
self.expect(b'>', "xml: bad self-closing tag")?;
|
||||||
|
return Ok((Element { name, attributes, ..Element::default() }, true));
|
||||||
|
}
|
||||||
|
Some(_) if had_ws => {
|
||||||
|
let key = self.name()?;
|
||||||
|
if key == "xmlns" {
|
||||||
|
return Err(malformed("xml: namespaces are refused"));
|
||||||
|
}
|
||||||
|
self.skip_ws();
|
||||||
|
self.expect(b'=', "xml: attribute without =")?;
|
||||||
|
self.skip_ws();
|
||||||
|
let value = self.attribute_value()?;
|
||||||
|
if attributes.iter().any(|(k, _)| *k == key) {
|
||||||
|
return Err(malformed("xml: duplicate attribute"));
|
||||||
|
}
|
||||||
|
attributes.push((key, value));
|
||||||
|
cap("xml attributes", MAX_XML_ATTRIBUTES, attributes.len())?;
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("xml: bad start tag")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn attribute_value(&mut self) -> Result<String> {
|
||||||
|
let quote = self.peek().filter(|q| *q == b'"' || *q == b'\'').ok_or(malformed("xml: unquoted attribute"))?;
|
||||||
|
self.pos += 1;
|
||||||
|
let mut out = String::new();
|
||||||
|
loop {
|
||||||
|
let start = self.pos;
|
||||||
|
while self.peek().is_some_and(|c| c != quote && c != b'&' && c != b'<') {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, out.len().saturating_add(self.pos - start))?;
|
||||||
|
out.push_str(self.s.get(start..self.pos).ok_or(malformed("xml: bad attribute"))?);
|
||||||
|
match self.peek() {
|
||||||
|
Some(c) if c == quote => {
|
||||||
|
self.pos += 1;
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
Some(b'&') => {
|
||||||
|
out.push(self.entity()?);
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, out.len())?;
|
||||||
|
}
|
||||||
|
_ => return Err(malformed("xml: bad attribute value")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Text up to the next `<` (or the end), unescaped, capped together with the `already` bytes of the element.
|
||||||
|
fn text(&mut self, already: usize) -> Result<String> {
|
||||||
|
let mut out = String::new();
|
||||||
|
loop {
|
||||||
|
let start = self.pos;
|
||||||
|
while self.peek().is_some_and(|c| c != b'<' && c != b'&') {
|
||||||
|
self.pos += 1;
|
||||||
|
}
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, already.saturating_add(out.len()).saturating_add(self.pos - start))?;
|
||||||
|
out.push_str(self.s.get(start..self.pos).ok_or(malformed("xml: bad text"))?);
|
||||||
|
if self.peek() == Some(b'&') {
|
||||||
|
out.push(self.entity()?);
|
||||||
|
cap("xml text", MAX_XML_TEXT_BYTES, already.saturating_add(out.len()))?;
|
||||||
|
} else {
|
||||||
|
return Ok(out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// At `&`: one of the five entities or a character reference, ending in `;`.
|
||||||
|
fn entity(&mut self) -> Result<char> {
|
||||||
|
self.pos += 1;
|
||||||
|
let len = self
|
||||||
|
.rest()
|
||||||
|
.iter()
|
||||||
|
.take(MAX_ENTITY_LEN + 1)
|
||||||
|
.position(|&c| c == b';')
|
||||||
|
.ok_or(malformed("xml: entity without ;"))?;
|
||||||
|
let body = self.s.get(self.pos..self.pos + len).ok_or(malformed("xml: bad entity"))?;
|
||||||
|
self.pos += len + 1;
|
||||||
|
let c = match body {
|
||||||
|
"lt" => '<',
|
||||||
|
"gt" => '>',
|
||||||
|
"amp" => '&',
|
||||||
|
"quot" => '"',
|
||||||
|
"apos" => '\'',
|
||||||
|
_ => {
|
||||||
|
let code = if let Some(hex) = body.strip_prefix("#x") {
|
||||||
|
if hex.is_empty() || hex.len() > 8 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
|
||||||
|
return Err(malformed("xml: bad character reference"));
|
||||||
|
}
|
||||||
|
u32::from_str_radix(hex, 16).map_err(|_| malformed("xml: bad character reference"))?
|
||||||
|
} else if let Some(dec) = body.strip_prefix('#') {
|
||||||
|
crate::util::parse_u32("xml character reference", dec)?
|
||||||
|
} else {
|
||||||
|
return Err(malformed("xml: unknown entity"));
|
||||||
|
};
|
||||||
|
if code == 0 {
|
||||||
|
return Err(malformed("xml: NUL character reference"));
|
||||||
|
}
|
||||||
|
char::from_u32(code).ok_or(malformed("xml: invalid character reference"))?
|
||||||
|
}
|
||||||
|
};
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,14 +53,38 @@ pub enum InputType {
|
|||||||
ControllerBattery = 0x5500_0007,
|
ControllerBattery = 0x5500_0007,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl InputType {
|
||||||
|
const ALL: [Self; 17] = [
|
||||||
|
Self::KeyDown,
|
||||||
|
Self::KeyUp,
|
||||||
|
Self::MouseMoveAbs,
|
||||||
|
Self::MouseMoveRel,
|
||||||
|
Self::MouseButtonDown,
|
||||||
|
Self::MouseButtonUp,
|
||||||
|
Self::MouseScroll,
|
||||||
|
Self::ControllerMulti,
|
||||||
|
Self::Haptics,
|
||||||
|
Self::Utf8Text,
|
||||||
|
Self::MouseHScroll,
|
||||||
|
Self::Touch,
|
||||||
|
Self::Pen,
|
||||||
|
Self::ControllerArrival,
|
||||||
|
Self::ControllerTouch,
|
||||||
|
Self::ControllerMotion,
|
||||||
|
Self::ControllerBattery,
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
impl TryFrom<u32> for InputType {
|
impl TryFrom<u32> for InputType {
|
||||||
type Error = crate::Error;
|
type Error = crate::Error;
|
||||||
|
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] for an unknown code. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::UnexpectedValue`] for an unknown code.
|
||||||
fn try_from(code: u32) -> crate::Result<Self> {
|
fn try_from(code: u32) -> crate::Result<Self> {
|
||||||
let _ = code;
|
Self::ALL
|
||||||
Err(crate::Error::Unimplemented)
|
.into_iter()
|
||||||
|
.find(|t| *t as u32 == code)
|
||||||
|
.ok_or(crate::Error::UnexpectedValue { what: "input type", value: code.into() })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -144,24 +168,192 @@ pub enum InputEvent {
|
|||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `0x0206 LE ‖ length LE ‖ size BE ‖ input type LE ‖ data`.
|
||||||
|
fn frame(input_type: InputType, data: &[u8]) -> crate::Result<Vec<u8>> {
|
||||||
|
let size = 4 + data.len();
|
||||||
|
crate::util::cap("input message", MAX_INPUT_MESSAGE_BYTES, 8 + size)?;
|
||||||
|
let mut m = Vec::with_capacity(8 + size);
|
||||||
|
m.extend_from_slice(&0x0206u16.to_le_bytes());
|
||||||
|
m.extend_from_slice(&u16::try_from(4 + size).unwrap_or(u16::MAX).to_le_bytes());
|
||||||
|
m.extend_from_slice(&u32::try_from(size).unwrap_or(u32::MAX).to_be_bytes());
|
||||||
|
m.extend_from_slice(&(input_type as u32).to_le_bytes());
|
||||||
|
m.extend_from_slice(data);
|
||||||
|
Ok(m)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn check_controller(controller: u8) -> crate::Result<()> {
|
||||||
|
if controller > gamepad::MAX_CONTROLLER_NUMBER {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "controller number", value: controller.into() });
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
/// Serializes an event into a whole `INPUT_DATA` message.
|
/// Serializes an event into a whole `INPUT_DATA` message.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::UnexpectedValue`] for a controller number above 15. Phase A: always
|
/// [`crate::Error::UnexpectedValue`] for a controller number above 15.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn encode_input(event: &InputEvent) -> crate::Result<Vec<u8>> {
|
pub fn encode_input(event: &InputEvent) -> crate::Result<Vec<u8>> {
|
||||||
let _ = event;
|
match *event {
|
||||||
Err(crate::Error::Unimplemented)
|
InputEvent::MouseMoveRel { dx, dy } => {
|
||||||
|
frame(InputType::MouseMoveRel, &[dx.to_be_bytes(), dy.to_be_bytes()].concat())
|
||||||
|
}
|
||||||
|
InputEvent::MouseMoveAbs { x, y, width, height } => frame(
|
||||||
|
InputType::MouseMoveAbs,
|
||||||
|
&[x.to_be_bytes(), y.to_be_bytes(), [0, 0], width.to_be_bytes(), height.to_be_bytes()].concat(),
|
||||||
|
),
|
||||||
|
InputEvent::MouseButton { pressed, button } => {
|
||||||
|
frame(if pressed { InputType::MouseButtonDown } else { InputType::MouseButtonUp }, &[button as u8])
|
||||||
|
}
|
||||||
|
InputEvent::Key { pressed, flags, key_code, modifiers } => {
|
||||||
|
let [lo, hi] = key_code.to_le_bytes();
|
||||||
|
frame(if pressed { InputType::KeyDown } else { InputType::KeyUp }, &[flags, lo, hi, modifiers, 0, 0])
|
||||||
|
}
|
||||||
|
InputEvent::Scroll { amount } => {
|
||||||
|
let [a, b] = amount.to_be_bytes();
|
||||||
|
frame(InputType::MouseScroll, &[a, b, a, b, 0, 0])
|
||||||
|
}
|
||||||
|
InputEvent::HScroll { amount } => frame(InputType::MouseHScroll, &amount.to_be_bytes()),
|
||||||
|
InputEvent::Gamepad(g) => {
|
||||||
|
check_controller(g.controller)?;
|
||||||
|
let mut d = Vec::with_capacity(gamepad::CONTROLLER_MULTI_DATA_LEN);
|
||||||
|
d.extend_from_slice(&0x001Au16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&u16::from(g.controller).to_le_bytes());
|
||||||
|
d.extend_from_slice(&g.active_mask.to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0014u16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 & 0xFFFF) as u16).to_le_bytes());
|
||||||
|
d.push(g.left_trigger);
|
||||||
|
d.push(g.right_trigger);
|
||||||
|
for v in [g.left_stick_x, g.left_stick_y, g.right_stick_x, g.right_stick_y] {
|
||||||
|
d.extend_from_slice(&v.to_le_bytes());
|
||||||
|
}
|
||||||
|
d.extend_from_slice(&0x009Cu16.to_le_bytes());
|
||||||
|
d.extend_from_slice(&((g.buttons.0 >> 16) as u16).to_le_bytes());
|
||||||
|
d.extend_from_slice(&0x0055u16.to_le_bytes());
|
||||||
|
frame(InputType::ControllerMulti, &d)
|
||||||
|
}
|
||||||
|
InputEvent::ControllerArrival { controller, kind, capabilities, supported_buttons } => {
|
||||||
|
check_controller(controller)?;
|
||||||
|
let mut d = vec![controller, kind as u8, capabilities.0];
|
||||||
|
d.extend_from_slice(&supported_buttons.0.to_le_bytes());
|
||||||
|
frame(InputType::ControllerArrival, &d)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses a whole `INPUT_DATA` message (inverse of [`encode_input`]).
|
/// Parses a whole `INPUT_DATA` message (inverse of [`encode_input`]). Bytes the layout fixes at zero or at a
|
||||||
|
/// copy (scroll `amount2`, key padding) are not checked; the `CONTROLLER_MULTI` constants are.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_INPUT_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
/// [`crate::Error::TooLarge`] over [`MAX_INPUT_MESSAGE_BYTES`], [`crate::Error::Truncated`] under
|
||||||
/// [`INPUT_HEADER_LEN`], [`crate::Error::Malformed`] when the length or size field does not match, the data length
|
/// [`INPUT_HEADER_LEN`], [`crate::Error::Malformed`] when the type, length or size field does not match, the data
|
||||||
/// is wrong for the type, or a constant differs; [`crate::Error::Unsupported`] for a type whose layout is UNKNOWN.
|
/// length is wrong for the type, or a constant differs; [`crate::Error::UnexpectedValue`] for an unknown type, a
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// button, controller number or controller kind out of range; [`crate::Error::Unsupported`] for a type whose
|
||||||
|
/// layout is UNKNOWN.
|
||||||
pub fn parse_input(message: &[u8]) -> crate::Result<InputEvent> {
|
pub fn parse_input(message: &[u8]) -> crate::Result<InputEvent> {
|
||||||
let _ = message;
|
use crate::util::{byte, i16_from, malformed, u16_le, u32_be, u32_le};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "input message";
|
||||||
|
crate::util::cap(W, MAX_INPUT_MESSAGE_BYTES, message.len())?;
|
||||||
|
crate::util::need(W, INPUT_HEADER_LEN, message.len())?;
|
||||||
|
if u16_le(W, message, 0)? != 0x0206 {
|
||||||
|
return Err(malformed("input message type"));
|
||||||
|
}
|
||||||
|
if usize::from(u16_le(W, message, 2)?) != message.len() - 4 {
|
||||||
|
return Err(malformed("input message length"));
|
||||||
|
}
|
||||||
|
if usize::try_from(u32_be(W, message, 4)?).ok() != Some(message.len() - 8) {
|
||||||
|
return Err(malformed("input message size"));
|
||||||
|
}
|
||||||
|
let input_type = InputType::try_from(u32_le(W, message, 8)?)?;
|
||||||
|
let d = message.get(INPUT_HEADER_LEN..).unwrap_or(&[]);
|
||||||
|
let want = |len: usize| if d.len() == len { Ok(()) } else { Err(malformed("input data length")) };
|
||||||
|
let be = |at: usize| crate::util::u16_be(W, d, at);
|
||||||
|
let le = |at: usize| u16_le(W, d, at);
|
||||||
|
Ok(match input_type {
|
||||||
|
InputType::MouseMoveRel => {
|
||||||
|
want(4)?;
|
||||||
|
InputEvent::MouseMoveRel { dx: i16_from(be(0)?), dy: i16_from(be(2)?) }
|
||||||
|
}
|
||||||
|
InputType::MouseMoveAbs => {
|
||||||
|
want(10)?;
|
||||||
|
InputEvent::MouseMoveAbs { x: i16_from(be(0)?), y: i16_from(be(2)?), width: be(6)?, height: be(8)? }
|
||||||
|
}
|
||||||
|
InputType::MouseButtonDown | InputType::MouseButtonUp => {
|
||||||
|
want(1)?;
|
||||||
|
let button = match byte(W, d, 0)? {
|
||||||
|
1 => MouseButton::Left,
|
||||||
|
2 => MouseButton::Middle,
|
||||||
|
3 => MouseButton::Right,
|
||||||
|
4 => MouseButton::Side,
|
||||||
|
5 => MouseButton::Extra,
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "mouse button", value: other.into() }),
|
||||||
|
};
|
||||||
|
InputEvent::MouseButton { pressed: input_type == InputType::MouseButtonDown, button }
|
||||||
|
}
|
||||||
|
InputType::KeyDown | InputType::KeyUp => {
|
||||||
|
want(6)?;
|
||||||
|
InputEvent::Key {
|
||||||
|
pressed: input_type == InputType::KeyDown,
|
||||||
|
flags: byte(W, d, 0)?,
|
||||||
|
key_code: le(1)?,
|
||||||
|
modifiers: byte(W, d, 3)?,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputType::MouseScroll => {
|
||||||
|
want(6)?;
|
||||||
|
InputEvent::Scroll { amount: i16_from(be(0)?) }
|
||||||
|
}
|
||||||
|
InputType::MouseHScroll => {
|
||||||
|
want(2)?;
|
||||||
|
InputEvent::HScroll { amount: i16_from(be(0)?) }
|
||||||
|
}
|
||||||
|
InputType::ControllerMulti => {
|
||||||
|
want(gamepad::CONTROLLER_MULTI_DATA_LEN)?;
|
||||||
|
if le(0)? != 0x001A || le(6)? != 0x0014 || le(20)? != 0x009C || le(24)? != 0x0055 {
|
||||||
|
return Err(malformed("controller state constant"));
|
||||||
|
}
|
||||||
|
let controller = le(2)?;
|
||||||
|
let controller = u8::try_from(controller)
|
||||||
|
.ok()
|
||||||
|
.filter(|c| *c <= gamepad::MAX_CONTROLLER_NUMBER)
|
||||||
|
.ok_or(crate::Error::UnexpectedValue { what: "controller number", value: controller.into() })?;
|
||||||
|
InputEvent::Gamepad(GamepadState {
|
||||||
|
controller,
|
||||||
|
active_mask: le(4)?,
|
||||||
|
buttons: ButtonFlags(u32::from(le(8)?) | (u32::from(le(22)?) << 16)),
|
||||||
|
left_trigger: byte(W, d, 10)?,
|
||||||
|
right_trigger: byte(W, d, 11)?,
|
||||||
|
left_stick_x: i16_from(le(12)?),
|
||||||
|
left_stick_y: i16_from(le(14)?),
|
||||||
|
right_stick_x: i16_from(le(16)?),
|
||||||
|
right_stick_y: i16_from(le(18)?),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
InputType::ControllerArrival => {
|
||||||
|
want(7)?;
|
||||||
|
let controller = byte(W, d, 0)?;
|
||||||
|
check_controller(controller)?;
|
||||||
|
let kind = match byte(W, d, 1)? {
|
||||||
|
0 => ControllerKind::Unknown,
|
||||||
|
1 => ControllerKind::Xbox,
|
||||||
|
2 => ControllerKind::PlayStation,
|
||||||
|
3 => ControllerKind::Nintendo,
|
||||||
|
other => return Err(crate::Error::UnexpectedValue { what: "controller kind", value: other.into() }),
|
||||||
|
};
|
||||||
|
InputEvent::ControllerArrival {
|
||||||
|
controller,
|
||||||
|
kind,
|
||||||
|
capabilities: ControllerCapabilities(byte(W, d, 2)?),
|
||||||
|
supported_buttons: ButtonFlags(u32_le(W, d, 3)?),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
InputType::Haptics
|
||||||
|
| InputType::Utf8Text
|
||||||
|
| InputType::Touch
|
||||||
|
| InputType::Pen
|
||||||
|
| InputType::ControllerTouch
|
||||||
|
| InputType::ControllerMotion
|
||||||
|
| InputType::ControllerBattery => {
|
||||||
|
return Err(crate::Error::Unsupported { what: "an input type whose layout is UNKNOWN (U21)" });
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -24,10 +24,13 @@ impl SessionKeys {
|
|||||||
/// Draws a fresh key and key id from `rng`.
|
/// Draws a fresh key and key id from `rng`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today; the `Result` leaves room for a fallible source.
|
||||||
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = rng;
|
let mut rikey = [0u8; RIKEY_LEN];
|
||||||
Err(crate::Error::Unimplemented)
|
rng.fill(&mut rikey);
|
||||||
|
let mut id = [0u8; 4];
|
||||||
|
rng.fill(&mut id);
|
||||||
|
Ok(Self { rikey, rikeyid: u32::from_le_bytes(id) })
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
//! DomiStream: a sans-I/O GameStream client (the protocol Sunshine hosts and Moonlight clients speak), for
|
//! DomiStream: a sans-I/O GameStream client (the protocol Sunshine hosts and Moonlight clients speak), for
|
||||||
//! Arena Domi TV and the other Play remotely clients.
|
//! Arena Domi TV and the other Play remotely clients.
|
||||||
//!
|
//!
|
||||||
//! **Phase A.** This crate holds the public API only. Every function that does protocol work returns
|
//! Interop with real hosts is unverified: the blocking UNKNOWNs of `docs/PROTOCOL.md` are settled live on Day 1.
|
||||||
//! [`Error::Unimplemented`] (or `None` for `poll_*` functions); QA writes the mandatory tests against these
|
//! Where the protocol is UNKNOWN, the Wolf-documented behaviour is implemented and kept easy to change.
|
||||||
//! signatures before the logic lands. Plain data (constants, enum codes, field structs) is final.
|
|
||||||
//!
|
//!
|
||||||
//! # Shape
|
//! # Shape
|
||||||
//!
|
//!
|
||||||
@@ -48,6 +47,7 @@ pub mod pairing;
|
|||||||
pub mod rtp;
|
pub mod rtp;
|
||||||
pub mod rtsp;
|
pub mod rtsp;
|
||||||
pub mod time;
|
pub mod time;
|
||||||
|
mod util;
|
||||||
pub mod video;
|
pub mod video;
|
||||||
|
|
||||||
pub use entropy::RandomSource;
|
pub use entropy::RandomSource;
|
||||||
|
|||||||
@@ -1,8 +1,13 @@
|
|||||||
//! The pure cryptographic steps of pairing (`docs/PROTOCOL.md` 1.5), public so QA can test them against
|
//! The pure cryptographic steps of pairing (`docs/PROTOCOL.md` 1.5), public so QA can test them against
|
||||||
//! independent vectors (for example Python `hashlib` + `cryptography` with fixed test keys).
|
//! independent vectors (for example Python `hashlib` + `cryptography` with fixed test keys).
|
||||||
|
|
||||||
use super::{CHALLENGE_LEN, HASH_LEN, Pin, SALT_LEN, SECRET_LEN};
|
use aes::Aes128;
|
||||||
|
use aes::cipher::{BlockCipherDecrypt, BlockCipherEncrypt, KeyInit};
|
||||||
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
|
use super::{CHALLENGE_LEN, HASH_LEN, MAX_SIGNATURE_BYTES, Pin, SALT_LEN, SECRET_LEN};
|
||||||
use crate::Result;
|
use crate::Result;
|
||||||
|
use crate::util::{cap, malformed};
|
||||||
|
|
||||||
/// AES-128 key used for every encrypted pairing value.
|
/// AES-128 key used for every encrypted pairing value.
|
||||||
pub type PairingKey = [u8; 16];
|
pub type PairingKey = [u8; 16];
|
||||||
@@ -10,20 +15,40 @@ pub type PairingKey = [u8; 16];
|
|||||||
/// `K = SHA-256(salt ‖ PIN digits)[0..16]`.
|
/// `K = SHA-256(salt ‖ PIN digits)[0..16]`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today; the `Result` keeps the signature uniform with the other steps.
|
||||||
pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result<PairingKey> {
|
pub fn derive_key(salt: &[u8; SALT_LEN], pin: &Pin) -> Result<PairingKey> {
|
||||||
let _ = (salt, pin);
|
let mut h = Sha256::new();
|
||||||
Err(crate::Error::Unimplemented)
|
h.update(salt);
|
||||||
|
h.update(pin.as_bytes());
|
||||||
|
let digest = h.finalize();
|
||||||
|
let mut key = [0u8; 16];
|
||||||
|
key.copy_from_slice(digest.get(..16).ok_or(malformed("sha-256 output"))?);
|
||||||
|
Ok(key)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ecb(key: &PairingKey, data: &[u8], encrypt: bool) -> Result<Vec<u8>> {
|
||||||
|
if data.is_empty() || !data.len().is_multiple_of(16) {
|
||||||
|
return Err(malformed("aes-ecb input is not whole blocks"));
|
||||||
|
}
|
||||||
|
let cipher = Aes128::new(key.into());
|
||||||
|
let mut out = data.to_vec();
|
||||||
|
for chunk in out.as_chunks_mut::<16>().0 {
|
||||||
|
let block: &mut aes::Block = chunk.into();
|
||||||
|
if encrypt {
|
||||||
|
cipher.encrypt_block(block);
|
||||||
|
} else {
|
||||||
|
cipher.decrypt_block(block);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AES-128-ECB encryption without padding.
|
/// AES-128-ECB encryption without padding.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] when `data` is not a whole number of 16-byte blocks. Phase A: always
|
/// [`crate::Error::Malformed`] when `data` is not a whole, non-zero number of 16-byte blocks.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (key, data);
|
ecb(key, data, true)
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AES-128-ECB decryption without padding.
|
/// AES-128-ECB decryption without padding.
|
||||||
@@ -31,8 +56,7 @@ pub fn ecb_encrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
|||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`ecb_encrypt`].
|
/// As [`ecb_encrypt`].
|
||||||
pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (key, data);
|
ecb(key, data, false)
|
||||||
Err(crate::Error::Unimplemented)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `SHA-256(challenge ‖ cert_signature ‖ secret)`: the host's proof `H_s` (with the client challenge, the host
|
/// `SHA-256(challenge ‖ cert_signature ‖ secret)`: the host's proof `H_s` (with the client challenge, the host
|
||||||
@@ -40,32 +64,46 @@ pub fn ecb_decrypt(key: &PairingKey, data: &[u8]) -> Result<Vec<u8>> {
|
|||||||
/// certificate's signature and the client secret).
|
/// certificate's signature and the client secret).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] for a signature over [`super::MAX_SIGNATURE_BYTES`]. Phase A: always
|
/// [`crate::Error::TooLarge`] for a signature over [`MAX_SIGNATURE_BYTES`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn proof_hash(
|
pub fn proof_hash(
|
||||||
challenge: &[u8; CHALLENGE_LEN],
|
challenge: &[u8; CHALLENGE_LEN],
|
||||||
cert_signature: &[u8],
|
cert_signature: &[u8],
|
||||||
secret: &[u8; SECRET_LEN],
|
secret: &[u8; SECRET_LEN],
|
||||||
) -> Result<[u8; HASH_LEN]> {
|
) -> Result<[u8; HASH_LEN]> {
|
||||||
let _ = (challenge, cert_signature, secret);
|
cap("certificate signature", MAX_SIGNATURE_BYTES, cert_signature.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let mut h = Sha256::new();
|
||||||
|
h.update(challenge);
|
||||||
|
h.update(cert_signature);
|
||||||
|
h.update(secret);
|
||||||
|
let mut out = [0u8; HASH_LEN];
|
||||||
|
out.copy_from_slice(&h.finalize());
|
||||||
|
Ok(out)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Splits a decrypted `challengeresponse` (48 bytes) into the host proof `H_s` and the host challenge `S_c`.
|
/// Splits a decrypted `challengeresponse` (48 bytes) into the host proof `H_s` and the host challenge `S_c`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] unless exactly 48 bytes. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Malformed`] unless exactly 48 bytes.
|
||||||
pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> {
|
pub fn split_challenge_response(decrypted: &[u8]) -> Result<([u8; HASH_LEN], [u8; CHALLENGE_LEN])> {
|
||||||
let _ = decrypted;
|
if decrypted.len() != HASH_LEN + CHALLENGE_LEN {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("challengeresponse is not 48 bytes"));
|
||||||
|
}
|
||||||
|
let hash = crate::util::array::<HASH_LEN>("challengeresponse", decrypted, 0)?;
|
||||||
|
let challenge = crate::util::array::<CHALLENGE_LEN>("challengeresponse", decrypted, HASH_LEN)?;
|
||||||
|
Ok((hash, challenge))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Splits a `pairingsecret` into the host secret (16 bytes) and its signature (the rest).
|
/// Splits a `pairingsecret` into the host secret (16 bytes) and its signature (the rest).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] when shorter than 17 bytes, [`crate::Error::TooLarge`] when the signature is over
|
/// [`crate::Error::Malformed`] when shorter than 17 bytes, [`crate::Error::TooLarge`] when the signature is over
|
||||||
/// [`super::MAX_SIGNATURE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`MAX_SIGNATURE_BYTES`].
|
||||||
pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> {
|
pub fn split_pairing_secret(pairing_secret: &[u8]) -> Result<([u8; SECRET_LEN], &[u8])> {
|
||||||
let _ = pairing_secret;
|
if pairing_secret.len() <= SECRET_LEN {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("pairingsecret too short"));
|
||||||
|
}
|
||||||
|
let signature = pairing_secret.get(SECRET_LEN..).unwrap_or(&[]);
|
||||||
|
cap("pairingsecret signature", MAX_SIGNATURE_BYTES, signature.len())?;
|
||||||
|
let secret = crate::util::array::<SECRET_LEN>("pairingsecret", pairing_secret, 0)?;
|
||||||
|
Ok((secret, signature))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,7 +2,16 @@
|
|||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
|
||||||
use crate::{RandomSource, Result};
|
use rsa::pkcs1v15::{Signature, SigningKey, VerifyingKey};
|
||||||
|
use rsa::pkcs8::{DecodePrivateKey, DecodePublicKey, EncodePrivateKey, EncodePublicKey};
|
||||||
|
use rsa::signature::{SignatureEncoding, Signer, Verifier};
|
||||||
|
use rsa::{PrivateKey, PublicKey};
|
||||||
|
use sha2::Sha256;
|
||||||
|
use x509_cert::Certificate;
|
||||||
|
use x509_cert::der::{Decode, Encode};
|
||||||
|
|
||||||
|
use crate::util::{base64_decode, base64_pem_lines, cap, ct_eq, malformed};
|
||||||
|
use crate::{Error, RandomSource, Result};
|
||||||
|
|
||||||
/// Maximum size of a certificate in PEM form, in bytes.
|
/// Maximum size of a certificate in PEM form, in bytes.
|
||||||
pub const MAX_CERT_PEM_BYTES: usize = 16 * 1024;
|
pub const MAX_CERT_PEM_BYTES: usize = 16 * 1024;
|
||||||
@@ -12,6 +21,13 @@ pub const MAX_CERT_DER_BYTES: usize = 12 * 1024;
|
|||||||
pub const MAX_KEY_DER_BYTES: usize = 8 * 1024;
|
pub const MAX_KEY_DER_BYTES: usize = 8 * 1024;
|
||||||
/// RSA modulus size of keys this client generates.
|
/// RSA modulus size of keys this client generates.
|
||||||
pub const CLIENT_KEY_BITS: usize = 2048;
|
pub const CLIENT_KEY_BITS: usize = 2048;
|
||||||
|
/// Maximum length of a generated certificate's common name, in bytes.
|
||||||
|
pub const MAX_COMMON_NAME_BYTES: usize = 64;
|
||||||
|
/// Validity of a generated certificate: 20 years of 365.25 days.
|
||||||
|
pub const CLIENT_CERT_VALIDITY_SECS: i64 = 20 * 31_557_600;
|
||||||
|
|
||||||
|
/// OID 1.2.840.113549.1.1.1, rsaEncryption.
|
||||||
|
const RSA_ENCRYPTION: &str = "1.2.840.113549.1.1.1";
|
||||||
|
|
||||||
/// The client's long-lived identity towards GameStream hosts: a self-signed RSA-2048 / SHA-256 X.509 certificate
|
/// The client's long-lived identity towards GameStream hosts: a self-signed RSA-2048 / SHA-256 X.509 certificate
|
||||||
/// and its private key. Generated once per device and kept by the platform layer (never in logs; the key belongs
|
/// and its private key. Generated once per device and kept by the platform layer (never in logs; the key belongs
|
||||||
@@ -19,9 +35,116 @@ pub const CLIENT_KEY_BITS: usize = 2048;
|
|||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ClientIdentity {
|
pub struct ClientIdentity {
|
||||||
cert_der: Vec<u8>,
|
cert_der: Vec<u8>,
|
||||||
key_pkcs8_der: Vec<u8>,
|
key_pkcs8_der: zeroize::Zeroizing<Vec<u8>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A parsed certificate with an RSA key.
|
||||||
|
fn parse_rsa_cert(der: &[u8]) -> Result<(Certificate, PublicKey)> {
|
||||||
|
let cert = Certificate::from_der(der).map_err(|_| malformed("x509 certificate"))?;
|
||||||
|
let spki = cert.tbs_certificate().subject_public_key_info();
|
||||||
|
if spki.algorithm.oid.to_string() != RSA_ENCRYPTION {
|
||||||
|
return Err(malformed("certificate key is not RSA"));
|
||||||
|
}
|
||||||
|
let spki_der = spki.to_der().map_err(|_| malformed("certificate key"))?;
|
||||||
|
let key = PublicKey::from_public_key_der(&spki_der).map_err(|_| malformed("certificate RSA key"))?;
|
||||||
|
Ok((cert, key))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn signature_bytes(cert: &Certificate) -> Vec<u8> {
|
||||||
|
cert.signature().raw_bytes().to_vec()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Adapts our [`RandomSource`] to the RustCrypto RNG traits (infallible, cryptographic by contract).
|
||||||
|
struct Rng<'a>(&'a mut dyn RandomSource);
|
||||||
|
|
||||||
|
impl rand_core::TryRng for Rng<'_> {
|
||||||
|
type Error = core::convert::Infallible;
|
||||||
|
|
||||||
|
fn try_next_u32(&mut self) -> core::result::Result<u32, Self::Error> {
|
||||||
|
let mut b = [0u8; 4];
|
||||||
|
self.0.fill(&mut b);
|
||||||
|
Ok(u32::from_le_bytes(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_next_u64(&mut self) -> core::result::Result<u64, Self::Error> {
|
||||||
|
let mut b = [0u8; 8];
|
||||||
|
self.0.fill(&mut b);
|
||||||
|
Ok(u64::from_le_bytes(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_fill_bytes(&mut self, dst: &mut [u8]) -> core::result::Result<(), Self::Error> {
|
||||||
|
self.0.fill(dst);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rand_core::TryCryptoRng for Rng<'_> {}
|
||||||
|
|
||||||
|
// ------------------------------------------------------------------------------------------------ DER writer
|
||||||
|
|
||||||
|
/// One DER TLV.
|
||||||
|
fn tlv(tag: u8, content: &[u8]) -> Vec<u8> {
|
||||||
|
let mut out = vec![tag];
|
||||||
|
let len = content.len();
|
||||||
|
if len < 0x80 {
|
||||||
|
out.push(len as u8);
|
||||||
|
} else {
|
||||||
|
let bytes = len.to_be_bytes();
|
||||||
|
let skip = bytes.iter().take_while(|b| **b == 0).count();
|
||||||
|
let used = bytes.get(skip..).unwrap_or(&[]);
|
||||||
|
out.push(0x80 | used.len() as u8);
|
||||||
|
out.extend_from_slice(used);
|
||||||
|
}
|
||||||
|
out.extend_from_slice(content);
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
fn seq(parts: &[&[u8]]) -> Vec<u8> {
|
||||||
|
tlv(0x30, &parts.concat())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Civil date from days since 1970-01-01 (proleptic Gregorian).
|
||||||
|
fn civil(days: i64) -> (i64, u32, u32) {
|
||||||
|
let z = days + 719_468;
|
||||||
|
let era = z.div_euclid(146_097);
|
||||||
|
let doe = z.rem_euclid(146_097);
|
||||||
|
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
|
||||||
|
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
|
||||||
|
let mp = (5 * doy + 2) / 153;
|
||||||
|
let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
|
||||||
|
let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
|
||||||
|
let year = yoe + era * 400 + i64::from(month <= 2);
|
||||||
|
(year, month, day)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RFC 5280 time: UTCTime for 1950..=2049, GeneralizedTime otherwise.
|
||||||
|
fn x509_time(unix: i64) -> Result<Vec<u8>> {
|
||||||
|
if unix < 0 {
|
||||||
|
return Err(malformed("certificate time before 1970"));
|
||||||
|
}
|
||||||
|
let (year, month, day) = civil(unix.div_euclid(86_400));
|
||||||
|
if year > 9999 {
|
||||||
|
return Err(malformed("certificate time after 9999"));
|
||||||
|
}
|
||||||
|
let secs = unix.rem_euclid(86_400);
|
||||||
|
let (h, m, s) = (secs / 3600, secs / 60 % 60, secs % 60);
|
||||||
|
if year < 2050 {
|
||||||
|
Ok(tlv(0x17, format!("{:02}{month:02}{day:02}{h:02}{m:02}{s:02}Z", year % 100).as_bytes()))
|
||||||
|
} else {
|
||||||
|
Ok(tlv(0x18, format!("{year:04}{month:02}{day:02}{h:02}{m:02}{s:02}Z").as_bytes()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `SEQ { SET { SEQ { id-at-commonName, UTF8String } } }`.
|
||||||
|
fn name(common_name: &str) -> Vec<u8> {
|
||||||
|
let atv = seq(&[&[0x06, 0x03, 0x55, 0x04, 0x03], &tlv(0x0C, common_name.as_bytes())]);
|
||||||
|
seq(&[&tlv(0x31, &atv)])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// sha256WithRSAEncryption, NULL parameters.
|
||||||
|
const SHA256_WITH_RSA: [u8; 15] =
|
||||||
|
[0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x0B, 0x05, 0x00];
|
||||||
|
|
||||||
impl ClientIdentity {
|
impl ClientIdentity {
|
||||||
/// Generates a new key and self-signed certificate.
|
/// Generates a new key and self-signed certificate.
|
||||||
///
|
///
|
||||||
@@ -30,21 +153,56 @@ impl ClientIdentity {
|
|||||||
/// TV); call it once per device.
|
/// TV); call it once per device.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for an empty or oversized `common_name`. Phase A: always
|
/// [`Error::Malformed`] for an empty, oversized or control-character `common_name`, or a time before 1970;
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// [`Error::Crypto`] if key generation fails.
|
||||||
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
|
pub fn generate(rng: &mut dyn RandomSource, common_name: &str, not_before_unix: i64) -> Result<Self> {
|
||||||
let _ = (rng, common_name, not_before_unix);
|
if common_name.is_empty()
|
||||||
Err(crate::Error::Unimplemented)
|
|| common_name.len() > MAX_COMMON_NAME_BYTES
|
||||||
|
|| common_name.chars().any(char::is_control)
|
||||||
|
{
|
||||||
|
return Err(malformed("certificate common name"));
|
||||||
|
}
|
||||||
|
let not_before = x509_time(not_before_unix)?;
|
||||||
|
let not_after = x509_time(not_before_unix.saturating_add(CLIENT_CERT_VALIDITY_SECS))?;
|
||||||
|
let mut serial = [0u8; 16];
|
||||||
|
rng.fill(&mut serial);
|
||||||
|
if let Some(first) = serial.first_mut() {
|
||||||
|
// Positive and with a non-zero top byte, so the INTEGER is 16 bytes, minimal.
|
||||||
|
*first = (*first & 0x7F) | 0x40;
|
||||||
|
}
|
||||||
|
let key = PrivateKey::new(&mut Rng(rng), CLIENT_KEY_BITS).map_err(|_| Error::Crypto)?;
|
||||||
|
let spki = key.to_public_key().to_public_key_der().map_err(|_| Error::Crypto)?;
|
||||||
|
let subject = name(common_name);
|
||||||
|
let tbs = seq(&[
|
||||||
|
&[0xA0, 0x03, 0x02, 0x01, 0x02],
|
||||||
|
&tlv(0x02, &serial),
|
||||||
|
&SHA256_WITH_RSA,
|
||||||
|
&subject,
|
||||||
|
&seq(&[¬_before, ¬_after]),
|
||||||
|
&subject,
|
||||||
|
spki.as_bytes(),
|
||||||
|
]);
|
||||||
|
let signature = SigningKey::<Sha256>::new(key.clone()).try_sign(&tbs).map_err(|_| Error::Crypto)?.to_vec();
|
||||||
|
let bits = [&[0u8][..], &signature].concat();
|
||||||
|
let cert = seq(&[&tbs, &SHA256_WITH_RSA, &tlv(0x03, &bits)]);
|
||||||
|
let pkcs8 = key.to_pkcs8_der().map_err(|_| Error::Crypto)?;
|
||||||
|
Self::from_der(&cert, pkcs8.as_bytes())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads a stored identity. Checks that the key matches the certificate.
|
/// Loads a stored identity. Checks that the key matches the certificate.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`crate::Error::Malformed`]
|
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`] / [`MAX_KEY_DER_BYTES`], [`Error::Malformed`] for bad DER, a
|
||||||
/// for bad DER or a key that does not match. Phase A: always [`crate::Error::Unimplemented`].
|
/// certificate without an RSA key, or a key that does not match.
|
||||||
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
|
pub fn from_der(cert_der: &[u8], key_pkcs8_der: &[u8]) -> Result<Self> {
|
||||||
let _ = (cert_der, key_pkcs8_der);
|
cap("client certificate", MAX_CERT_DER_BYTES, cert_der.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
cap("client key", MAX_KEY_DER_BYTES, key_pkcs8_der.len())?;
|
||||||
|
let (_, public) = parse_rsa_cert(cert_der)?;
|
||||||
|
let key = PrivateKey::from_pkcs8_der(key_pkcs8_der).map_err(|_| malformed("client key"))?;
|
||||||
|
if key.to_public_key() != public {
|
||||||
|
return Err(malformed("client key does not match its certificate"));
|
||||||
|
}
|
||||||
|
Ok(Self { cert_der: cert_der.to_vec(), key_pkcs8_der: zeroize::Zeroizing::new(key_pkcs8_der.to_vec()) })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The certificate, DER.
|
/// The certificate, DER.
|
||||||
@@ -62,26 +220,27 @@ impl ClientIdentity {
|
|||||||
/// The certificate as PEM text (what pairing step 1 sends, hex-encoded).
|
/// The certificate as PEM text (what pairing step 1 sends, hex-encoded).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn cert_pem(&self) -> Result<String> {
|
pub fn cert_pem(&self) -> Result<String> {
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(format!("-----BEGIN CERTIFICATE-----\n{}-----END CERTIFICATE-----\n", base64_pem_lines(&self.cert_der)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The raw `signatureValue` bytes of the certificate (input to the pairing proofs).
|
/// The raw `signatureValue` bytes of the certificate (input to the pairing proofs).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] if the stored certificate no longer parses (it was checked when loaded).
|
||||||
pub fn cert_signature(&self) -> Result<Vec<u8>> {
|
pub fn cert_signature(&self) -> Result<Vec<u8>> {
|
||||||
Err(crate::Error::Unimplemented)
|
parse_rsa_cert(&self.cert_der).map(|(c, _)| signature_bytes(&c))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key.
|
/// RSASSA-PKCS1-v1_5 / SHA-256 signature over `data` with the client key.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Crypto`] if signing fails.
|
||||||
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
|
pub fn sign(&self, data: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = data;
|
let key = PrivateKey::from_pkcs8_der(&self.key_pkcs8_der).map_err(|_| Error::Crypto)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let sig = SigningKey::<Sha256>::new(key).try_sign(data).map_err(|_| Error::Crypto)?;
|
||||||
|
Ok(sig.to_vec())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,24 +260,34 @@ pub struct ServerCert {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl ServerCert {
|
impl ServerCert {
|
||||||
/// Parses the PEM the host sent (already hex-decoded). Exactly one `CERTIFICATE` block.
|
/// Parses the PEM the host sent (already hex-decoded): exactly one `CERTIFICATE` block and nothing but
|
||||||
|
/// whitespace around it.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`crate::Error::Malformed`] for anything that is
|
/// [`Error::TooLarge`] over [`MAX_CERT_PEM_BYTES`], [`Error::Malformed`] for anything that is not one
|
||||||
/// not one well-formed X.509 certificate with an RSA key. Phase A: always [`crate::Error::Unimplemented`].
|
/// well-formed X.509 certificate with an RSA key.
|
||||||
pub fn from_pem(pem: &[u8]) -> Result<Self> {
|
pub fn from_pem(pem: &[u8]) -> Result<Self> {
|
||||||
let _ = pem;
|
const BEGIN: &[u8] = b"-----BEGIN CERTIFICATE-----";
|
||||||
Err(crate::Error::Unimplemented)
|
const END: &[u8] = b"-----END CERTIFICATE-----";
|
||||||
|
cap("host certificate PEM", MAX_CERT_PEM_BYTES, pem.len())?;
|
||||||
|
let trimmed = pem.trim_ascii();
|
||||||
|
let body =
|
||||||
|
trimmed.strip_prefix(BEGIN).and_then(|b| b.strip_suffix(END)).ok_or(malformed("host certificate PEM"))?;
|
||||||
|
if body.windows(5).any(|w| w == b"-----") {
|
||||||
|
return Err(malformed("host certificate PEM holds more than one block"));
|
||||||
|
}
|
||||||
|
let der = base64_decode("host certificate PEM", body)?;
|
||||||
|
Self::from_der(&der)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Loads a stored certificate.
|
/// Loads a stored certificate.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`crate::Error::Malformed`] otherwise. Phase A:
|
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`], [`Error::Malformed`] otherwise.
|
||||||
/// always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn from_der(der: &[u8]) -> Result<Self> {
|
pub fn from_der(der: &[u8]) -> Result<Self> {
|
||||||
let _ = der;
|
cap("host certificate", MAX_CERT_DER_BYTES, der.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
parse_rsa_cert(der)?;
|
||||||
|
Ok(Self { der: der.to_vec() })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The certificate, DER.
|
/// The certificate, DER.
|
||||||
@@ -130,27 +299,28 @@ impl ServerCert {
|
|||||||
/// The raw `signatureValue` bytes (input to the pairing proofs).
|
/// The raw `signatureValue` bytes (input to the pairing proofs).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] if the stored certificate no longer parses.
|
||||||
pub fn signature(&self) -> Result<Vec<u8>> {
|
pub fn signature(&self) -> Result<Vec<u8>> {
|
||||||
Err(crate::Error::Unimplemented)
|
parse_rsa_cert(&self.der).map(|(c, _)| signature_bytes(&c))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Verifies an RSASSA-PKCS1-v1_5 / SHA-256 `signature` over `data` with the certificate's public key.
|
/// Verifies an RSASSA-PKCS1-v1_5 / SHA-256 `signature` over `data` with the certificate's public key.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Crypto`] when it does not verify. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Crypto`] when it does not verify.
|
||||||
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
|
pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {
|
||||||
let _ = (data, signature);
|
let (_, key) = parse_rsa_cert(&self.der)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let sig = Signature::try_from(signature).map_err(|_| Error::Crypto)?;
|
||||||
|
VerifyingKey::<Sha256>::new(key).verify(data, &sig).map_err(|_| Error::Crypto)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// TLS pinning: whether the certificate a host presents over HTTPS (DER) is exactly this one, compared in
|
/// TLS pinning: whether the certificate a host presents over HTTPS (DER) is exactly this one, compared in
|
||||||
/// constant time. The platform's TLS verifier calls this and nothing else to accept the host.
|
/// constant time. The platform's TLS verifier calls this and nothing else to accept the host.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_CERT_DER_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::TooLarge`] over [`MAX_CERT_DER_BYTES`].
|
||||||
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
|
pub fn matches(&self, presented_der: &[u8]) -> Result<bool> {
|
||||||
let _ = presented_der;
|
cap("presented certificate", MAX_CERT_DER_BYTES, presented_der.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(ct_eq(&self.der, presented_der))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,12 +11,14 @@
|
|||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Each [`PairingSession::handle_response`] consumes one HTTP answer body and returns the next request to send,
|
//! Each [`PairingSession::handle_response`] consumes one HTTP answer body and returns the next request to send,
|
||||||
//! or the finished [`PairedHost`].
|
//! or the finished [`PairedHost`]. Every answer must carry the element of its own step; an answer meant for another
|
||||||
|
//! step fails the session, so replayed or reordered answers can never skip a check.
|
||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
|
||||||
use crate::http::HttpRequest;
|
use crate::http::{HttpRequest, MAX_DEVICE_NAME_BYTES, Scheme, build, check_unique_id};
|
||||||
use crate::{RandomSource, Result};
|
use crate::util::{ct_eq, hex_decode, hex_encode, malformed};
|
||||||
|
use crate::{Error, RandomSource, Result};
|
||||||
|
|
||||||
pub mod crypto;
|
pub mod crypto;
|
||||||
pub mod identity;
|
pub mod identity;
|
||||||
@@ -37,28 +39,47 @@ pub const PIN_LEN: usize = 4;
|
|||||||
pub const MAX_PAIR_RESPONSE_BYTES: usize = 64 * 1024;
|
pub const MAX_PAIR_RESPONSE_BYTES: usize = 64 * 1024;
|
||||||
/// Maximum size of a signature accepted from the host (RSA-8192), in bytes.
|
/// Maximum size of a signature accepted from the host (RSA-8192), in bytes.
|
||||||
pub const MAX_SIGNATURE_BYTES: usize = 1024;
|
pub const MAX_SIGNATURE_BYTES: usize = 1024;
|
||||||
|
/// How long the caller should wait for the step 1 answer: the host holds it until the PIN is entered.
|
||||||
|
pub const STEP1_TIMEOUT: core::time::Duration = core::time::Duration::from_secs(120);
|
||||||
|
|
||||||
/// A 4-digit GameStream PIN.
|
/// A 4-digit GameStream PIN.
|
||||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||||
pub struct Pin([u8; PIN_LEN]);
|
pub struct Pin([u8; PIN_LEN]);
|
||||||
|
|
||||||
impl Pin {
|
impl Pin {
|
||||||
/// Draws a uniformly random PIN (no modulo bias).
|
/// Draws a uniformly random PIN (rejection sampling, no modulo bias).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
pub fn generate(rng: &mut dyn RandomSource) -> Result<Self> {
|
||||||
let _ = rng;
|
let mut digits = [0u8; PIN_LEN];
|
||||||
Err(crate::Error::Unimplemented)
|
for d in &mut digits {
|
||||||
|
loop {
|
||||||
|
let mut b = [0u8; 1];
|
||||||
|
rng.fill(&mut b);
|
||||||
|
let [v] = b;
|
||||||
|
// 250 = 25 × 10: values 250..=255 would favour digits 0-5.
|
||||||
|
if v < 250 {
|
||||||
|
*d = b'0' + v % 10;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Self(digits))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses exactly four ASCII digits.
|
/// Parses exactly four ASCII digits.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for anything else. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] for anything else.
|
||||||
pub fn from_digits(digits: &str) -> Result<Self> {
|
pub fn from_digits(digits: &str) -> Result<Self> {
|
||||||
let _ = digits;
|
let b = digits.as_bytes();
|
||||||
Err(crate::Error::Unimplemented)
|
if b.len() != PIN_LEN || !b.iter().all(u8::is_ascii_digit) {
|
||||||
|
return Err(malformed("PIN"));
|
||||||
|
}
|
||||||
|
let mut out = [0u8; PIN_LEN];
|
||||||
|
out.copy_from_slice(b);
|
||||||
|
Ok(Self(out))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The four ASCII digits.
|
/// The four ASCII digits.
|
||||||
@@ -140,17 +161,41 @@ pub struct PairResponse {
|
|||||||
/// Parses one pairing answer.
|
/// Parses one pairing answer.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`crate::Error::HostStatus`] for a non-200
|
/// [`Error::TooLarge`] over [`MAX_PAIR_RESPONSE_BYTES`], [`Error::HostStatus`] for a non-200 answer,
|
||||||
/// answer, [`crate::Error::Malformed`] for bad hex or a missing `paired`. Phase A: always
|
/// [`Error::Malformed`] for bad hex or a missing or bad `paired`.
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_pair_response(body: &[u8]) -> Result<PairResponse> {
|
pub fn parse_pair_response(body: &[u8]) -> Result<PairResponse> {
|
||||||
let _ = body;
|
let doc = crate::http::document(body, MAX_PAIR_RESPONSE_BYTES, "pairing answer")?;
|
||||||
Err(crate::Error::Unimplemented)
|
let r = &doc.root;
|
||||||
|
let paired = match r.child("paired").map(|p| p.text.as_str()) {
|
||||||
|
Some("1") => true,
|
||||||
|
Some("0") => false,
|
||||||
|
_ => return Err(malformed("pairing answer: paired")),
|
||||||
|
};
|
||||||
|
let hex_field = |name: &str| -> Result<Option<Vec<u8>>> {
|
||||||
|
r.child(name).map(|e| hex_decode("pairing answer hex", &e.text)).transpose()
|
||||||
|
};
|
||||||
|
Ok(PairResponse {
|
||||||
|
paired,
|
||||||
|
plain_cert: hex_field("plaincert")?,
|
||||||
|
challenge_response: hex_field("challengeresponse")?,
|
||||||
|
pairing_secret: hex_field("pairingsecret")?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A failed step: why, and the error to return.
|
||||||
|
type StepError = (PairingFailure, Error);
|
||||||
|
|
||||||
/// One pairing attempt with one host.
|
/// One pairing attempt with one host.
|
||||||
pub struct PairingSession {
|
pub struct PairingSession {
|
||||||
state: PairingState,
|
state: PairingState,
|
||||||
|
unique_id: String,
|
||||||
|
device_name: String,
|
||||||
|
cert_der: Vec<u8>,
|
||||||
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
|
server_cert: Option<ServerCert>,
|
||||||
|
client_challenge: [u8; CHALLENGE_LEN],
|
||||||
|
host_proof: [u8; HASH_LEN],
|
||||||
|
client_secret: zeroize::Zeroizing<[u8; SECRET_LEN]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl PairingSession {
|
impl PairingSession {
|
||||||
@@ -159,8 +204,7 @@ impl PairingSession {
|
|||||||
/// `unique_id` is this client's id (stable per device), `device_name` is shown on the host.
|
/// `unique_id` is this client's id (stable per device), `device_name` is shown on the host.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a bad `unique_id` or `device_name`. Phase A: always
|
/// [`Error::Malformed`] for a bad `unique_id` or `device_name` (empty, too long, control characters).
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn start(
|
pub fn start(
|
||||||
identity: &ClientIdentity,
|
identity: &ClientIdentity,
|
||||||
unique_id: &str,
|
unique_id: &str,
|
||||||
@@ -168,8 +212,47 @@ impl PairingSession {
|
|||||||
pin: Pin,
|
pin: Pin,
|
||||||
rng: &mut dyn RandomSource,
|
rng: &mut dyn RandomSource,
|
||||||
) -> Result<(Self, HttpRequest)> {
|
) -> Result<(Self, HttpRequest)> {
|
||||||
let _ = (identity, unique_id, device_name, pin, rng);
|
check_unique_id(unique_id)?;
|
||||||
Err(crate::Error::Unimplemented)
|
if device_name.is_empty()
|
||||||
|
|| device_name.len() > MAX_DEVICE_NAME_BYTES
|
||||||
|
|| device_name.chars().any(char::is_control)
|
||||||
|
{
|
||||||
|
return Err(malformed("device name"));
|
||||||
|
}
|
||||||
|
let mut salt = [0u8; SALT_LEN];
|
||||||
|
rng.fill(&mut salt);
|
||||||
|
let key = crypto::derive_key(&salt, &pin)?;
|
||||||
|
let session = Self {
|
||||||
|
state: PairingState::AwaitServerCert,
|
||||||
|
unique_id: unique_id.to_owned(),
|
||||||
|
device_name: device_name.to_owned(),
|
||||||
|
cert_der: identity.cert_der().to_vec(),
|
||||||
|
key: zeroize::Zeroizing::new(key),
|
||||||
|
server_cert: None,
|
||||||
|
client_challenge: [0; CHALLENGE_LEN],
|
||||||
|
host_proof: [0; HASH_LEN],
|
||||||
|
client_secret: zeroize::Zeroizing::new([0; SECRET_LEN]),
|
||||||
|
};
|
||||||
|
let cert = hex_encode(identity.cert_pem()?.as_bytes());
|
||||||
|
let salt = hex_encode(&salt);
|
||||||
|
let req = session.request(
|
||||||
|
Scheme::Http,
|
||||||
|
&[("phrase", "getservercert"), ("salt", &salt), ("clientcert", &cert)],
|
||||||
|
Some(STEP1_TIMEOUT),
|
||||||
|
);
|
||||||
|
Ok((session, req))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn request(&self, scheme: Scheme, extra: &[(&str, &str)], timeout: Option<core::time::Duration>) -> HttpRequest {
|
||||||
|
let mut params: Vec<(&str, &str)> =
|
||||||
|
vec![("uniqueid", &self.unique_id), ("devicename", &self.device_name), ("updateState", "1")];
|
||||||
|
params.extend_from_slice(extra);
|
||||||
|
build(scheme, "/pair", ¶ms, timeout)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fail(&mut self, why: PairingFailure, error: Error) -> Result<PairingStep> {
|
||||||
|
self.state = PairingState::Failed(why);
|
||||||
|
Err(error)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds the answer to the last request: its HTTP status and body. `identity` must be the one passed to
|
/// Feeds the answer to the last request: its HTTP status and body. `identity` must be the one passed to
|
||||||
@@ -177,9 +260,9 @@ impl PairingSession {
|
|||||||
/// randomness for steps 2 and 3.
|
/// randomness for steps 2 and 3.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as
|
/// [`Error::PairingRefused`] (the state becomes [`PairingState::Failed`]), parser errors as
|
||||||
/// [`parse_pair_response`], [`crate::Error::State`] after `Paired` or `Failed`, [`crate::Error::Malformed`] for
|
/// [`parse_pair_response`], [`Error::State`] after `Paired` or `Failed`, [`Error::Malformed`] for a different
|
||||||
/// a different identity than at the start. Phase A: always [`crate::Error::Unimplemented`].
|
/// identity than at the start.
|
||||||
pub fn handle_response(
|
pub fn handle_response(
|
||||||
&mut self,
|
&mut self,
|
||||||
identity: &ClientIdentity,
|
identity: &ClientIdentity,
|
||||||
@@ -187,8 +270,89 @@ impl PairingSession {
|
|||||||
body: &[u8],
|
body: &[u8],
|
||||||
rng: &mut dyn RandomSource,
|
rng: &mut dyn RandomSource,
|
||||||
) -> Result<PairingStep> {
|
) -> Result<PairingStep> {
|
||||||
let _ = (identity, http_status, body, rng);
|
if matches!(self.state, PairingState::Paired | PairingState::Failed(_)) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::State { expected: "a pairing step in progress" });
|
||||||
|
}
|
||||||
|
if identity.cert_der() != self.cert_der.as_slice() {
|
||||||
|
return Err(malformed("pairing: a different identity than at the start"));
|
||||||
|
}
|
||||||
|
if http_status != 200 {
|
||||||
|
return self.fail(PairingFailure::HostStatus, Error::HostStatus { code: u32::from(http_status) });
|
||||||
|
}
|
||||||
|
let answer = match parse_pair_response(body) {
|
||||||
|
Ok(a) => a,
|
||||||
|
Err(e @ Error::HostStatus { .. }) => return self.fail(PairingFailure::HostStatus, e),
|
||||||
|
Err(e) => return self.fail(PairingFailure::MalformedAnswer, e),
|
||||||
|
};
|
||||||
|
if !answer.paired {
|
||||||
|
return self.fail(PairingFailure::HostRefused, Error::PairingRefused);
|
||||||
|
}
|
||||||
|
match self.step(identity, answer, rng) {
|
||||||
|
Ok(step) => Ok(step),
|
||||||
|
Err((why, e)) => self.fail(why, e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn step(
|
||||||
|
&mut self,
|
||||||
|
identity: &ClientIdentity,
|
||||||
|
answer: PairResponse,
|
||||||
|
rng: &mut dyn RandomSource,
|
||||||
|
) -> core::result::Result<PairingStep, StepError> {
|
||||||
|
let bad = |e: Error| (PairingFailure::MalformedAnswer, e);
|
||||||
|
match self.state {
|
||||||
|
PairingState::AwaitServerCert => {
|
||||||
|
let pem = answer.plain_cert.ok_or_else(|| bad(malformed("pairing: no plaincert")))?;
|
||||||
|
let cert = ServerCert::from_pem(&pem).map_err(bad)?;
|
||||||
|
self.server_cert = Some(cert);
|
||||||
|
rng.fill(&mut self.client_challenge);
|
||||||
|
let enc = crypto::ecb_encrypt(&self.key, &self.client_challenge).map_err(bad)?;
|
||||||
|
self.state = PairingState::AwaitChallengeResponse;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Http, &[("clientchallenge", &hex_encode(&enc))], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitChallengeResponse => {
|
||||||
|
let cr = answer.challenge_response.ok_or_else(|| bad(malformed("pairing: no challengeresponse")))?;
|
||||||
|
let plain = crypto::ecb_decrypt(&self.key, &cr).map_err(bad)?;
|
||||||
|
let (host_proof, server_challenge) = crypto::split_challenge_response(&plain).map_err(bad)?;
|
||||||
|
self.host_proof = host_proof;
|
||||||
|
rng.fill(&mut *self.client_secret);
|
||||||
|
let client_sig = identity.cert_signature().map_err(bad)?;
|
||||||
|
let client_proof =
|
||||||
|
crypto::proof_hash(&server_challenge, &client_sig, &self.client_secret).map_err(bad)?;
|
||||||
|
let enc = crypto::ecb_encrypt(&self.key, &client_proof).map_err(bad)?;
|
||||||
|
self.state = PairingState::AwaitPairingSecret;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Http, &[("serverchallengeresp", &hex_encode(&enc))], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitPairingSecret => {
|
||||||
|
let ps = answer.pairing_secret.ok_or_else(|| bad(malformed("pairing: no pairingsecret")))?;
|
||||||
|
let (secret, signature) = crypto::split_pairing_secret(&ps).map_err(bad)?;
|
||||||
|
let cert = self.server_cert.as_ref().ok_or_else(|| bad(malformed("pairing: no host certificate")))?;
|
||||||
|
cert.verify(&secret, signature)
|
||||||
|
.map_err(|_| (PairingFailure::BadHostSignature, Error::PairingRefused))?;
|
||||||
|
let host_sig = cert.signature().map_err(bad)?;
|
||||||
|
let expected = crypto::proof_hash(&self.client_challenge, &host_sig, &secret).map_err(bad)?;
|
||||||
|
if !ct_eq(&expected, &self.host_proof) {
|
||||||
|
return Err((PairingFailure::ProofMismatch, Error::PairingRefused));
|
||||||
|
}
|
||||||
|
let sig = identity.sign(&*self.client_secret).map_err(bad)?;
|
||||||
|
let value = [&self.client_secret[..], &sig].concat();
|
||||||
|
self.state = PairingState::AwaitClientSecretAck;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Http, &[("clientpairingsecret", &hex_encode(&value))], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitClientSecretAck => {
|
||||||
|
self.state = PairingState::AwaitPairChallenge;
|
||||||
|
Ok(PairingStep::Send(self.request(Scheme::Https, &[("phrase", "pairchallenge")], None)))
|
||||||
|
}
|
||||||
|
PairingState::AwaitPairChallenge => {
|
||||||
|
let server_cert =
|
||||||
|
self.server_cert.clone().ok_or_else(|| bad(malformed("pairing: no host certificate")))?;
|
||||||
|
self.state = PairingState::Paired;
|
||||||
|
Ok(PairingStep::Paired(PairedHost { server_cert }))
|
||||||
|
}
|
||||||
|
PairingState::Paired | PairingState::Failed(_) => {
|
||||||
|
Err((PairingFailure::MalformedAnswer, Error::State { expected: "a pairing step in progress" }))
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where the handshake is.
|
/// Where the handshake is.
|
||||||
|
|||||||
@@ -26,8 +26,18 @@ pub struct RtpHeader {
|
|||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Truncated`] for fewer than 12 bytes, [`crate::Error::UnexpectedValue`] for another RTP version.
|
/// [`crate::Error::Truncated`] for fewer than 12 bytes, [`crate::Error::UnexpectedValue`] for another RTP version.
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn parse_rtp_header(packet: &[u8]) -> crate::Result<RtpHeader> {
|
pub fn parse_rtp_header(packet: &[u8]) -> crate::Result<RtpHeader> {
|
||||||
let _ = packet;
|
const W: &str = "rtp header";
|
||||||
Err(crate::Error::Unimplemented)
|
crate::util::need(W, RTP_HEADER_LEN, packet.len())?;
|
||||||
|
let flags = crate::util::byte(W, packet, 0)?;
|
||||||
|
if flags >> 6 != 2 {
|
||||||
|
return Err(crate::Error::UnexpectedValue { what: "rtp version", value: (flags >> 6).into() });
|
||||||
|
}
|
||||||
|
Ok(RtpHeader {
|
||||||
|
flags,
|
||||||
|
payload_type: crate::util::byte(W, packet, 1)?,
|
||||||
|
sequence: crate::util::u16_be(W, packet, 2)?,
|
||||||
|
timestamp: crate::util::u32_be(W, packet, 4)?,
|
||||||
|
ssrc: crate::util::u32_be(W, packet, 8)?,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,8 +5,20 @@
|
|||||||
//! answers with [`super::RtspFramer`], and feeds each whole answer to [`RtspClient::handle_response`] until it
|
//! answers with [`super::RtspFramer`], and feeds each whole answer to [`RtspClient::handle_response`] until it
|
||||||
//! returns [`RtspProgress::Ready`].
|
//! returns [`RtspProgress::Ready`].
|
||||||
|
|
||||||
use super::sdp::{EncryptionFlags, HostCapabilities, OpusConfig};
|
use super::sdp::{self, EncryptionFlags, HostCapabilities, OpusConfig};
|
||||||
|
use super::{Method, RtspRequest, RtspResponse, parse_response};
|
||||||
use crate::http::launch::AudioLayout;
|
use crate::http::launch::AudioLayout;
|
||||||
|
use crate::util::{check_rtsp_url, malformed, parse_u16};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// `X-GS-ClientVersion` sent with every request (the value in Wolf's example, UNKNOWN U5).
|
||||||
|
pub const CLIENT_VERSION: &str = "14";
|
||||||
|
/// What the client sends to the video and audio ports to open the NAT path (Moonshine accepts it; U8).
|
||||||
|
pub const PING_PAYLOAD: &[u8] = b"PING";
|
||||||
|
/// SETUP targets (Moonshine's example form `streamid=control/13/0`; UNKNOWN U5).
|
||||||
|
const SETUP_TARGETS: [&str; 3] = ["streamid=audio/0/0", "streamid=video/0/0", "streamid=control/13/0"];
|
||||||
|
/// `Transport` value of the SETUP requests (not interpreted by the hosts we know of; U5).
|
||||||
|
const TRANSPORT: &str = "unicast;X-GS-ClientPort=50000-50001";
|
||||||
|
|
||||||
/// Video codecs.
|
/// Video codecs.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
@@ -113,6 +125,15 @@ pub enum RtspProgress {
|
|||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct RtspClient {
|
pub struct RtspClient {
|
||||||
state: RtspClientState,
|
state: RtspClientState,
|
||||||
|
url: String,
|
||||||
|
config: StreamConfig,
|
||||||
|
cseq: u32,
|
||||||
|
/// The request to hand out, and whether one was handed out and is not answered yet.
|
||||||
|
pending: Option<Vec<u8>>,
|
||||||
|
outstanding: bool,
|
||||||
|
host: Option<HostCapabilities>,
|
||||||
|
ports: [u16; 3],
|
||||||
|
session_id: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RtspClient {
|
impl RtspClient {
|
||||||
@@ -120,27 +141,164 @@ impl RtspClient {
|
|||||||
/// is ready in [`Self::poll_request`].
|
/// is ready in [`Self::poll_request`].
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame
|
/// [`Error::Malformed`] for a URL that is not `rtsp://host:port`, or a config with zero size, frame
|
||||||
/// rate, bitrate or packet size. Phase A: always [`crate::Error::Unimplemented`].
|
/// rate, bitrate or packet size.
|
||||||
pub fn new(session_url: &str, config: StreamConfig) -> crate::Result<Self> {
|
pub fn new(session_url: &str, config: StreamConfig) -> Result<Self> {
|
||||||
let _ = (session_url, config);
|
check_rtsp_url("rtsp session URL", session_url)?;
|
||||||
Err(crate::Error::Unimplemented)
|
if config.width == 0
|
||||||
|
|| config.height == 0
|
||||||
|
|| config.fps == 0
|
||||||
|
|| config.bitrate_kbps == 0
|
||||||
|
|| config.packet_size == 0
|
||||||
|
|| config.audio_packet_duration_ms == 0
|
||||||
|
{
|
||||||
|
return Err(malformed("rtsp stream config"));
|
||||||
|
}
|
||||||
|
let mut c = Self {
|
||||||
|
state: RtspClientState::Options,
|
||||||
|
url: session_url.to_owned(),
|
||||||
|
config,
|
||||||
|
cseq: 0,
|
||||||
|
pending: None,
|
||||||
|
outstanding: false,
|
||||||
|
host: None,
|
||||||
|
ports: [0; 3],
|
||||||
|
session_id: None,
|
||||||
|
};
|
||||||
|
let url = c.url.clone();
|
||||||
|
c.queue(Method::Options, &url, Vec::new(), Vec::new())?;
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn queue(&mut self, method: Method, target: &str, mut extra: Vec<(String, String)>, body: Vec<u8>) -> Result<()> {
|
||||||
|
self.cseq = self.cseq.wrapping_add(1);
|
||||||
|
let mut headers = vec![("CSeq".to_owned(), self.cseq.to_string())];
|
||||||
|
headers.push(("X-GS-ClientVersion".to_owned(), CLIENT_VERSION.to_owned()));
|
||||||
|
if let Some(s) = &self.session_id {
|
||||||
|
headers.push(("Session".to_owned(), s.clone()));
|
||||||
|
}
|
||||||
|
headers.append(&mut extra);
|
||||||
|
if !body.is_empty() {
|
||||||
|
headers.push(("Content-Length".to_owned(), body.len().to_string()));
|
||||||
|
}
|
||||||
|
let req = RtspRequest { method, target: target.to_owned(), headers, body };
|
||||||
|
self.pending = Some(req.encode()?);
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next request to write, if one is due. Each is returned once.
|
/// The next request to write, if one is due. Each is returned once.
|
||||||
pub fn poll_request(&mut self) -> Option<Vec<u8>> {
|
pub fn poll_request(&mut self) -> Option<Vec<u8>> {
|
||||||
None
|
let req = self.pending.take();
|
||||||
|
if req.is_some() {
|
||||||
|
self.outstanding = true;
|
||||||
|
}
|
||||||
|
req
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one whole answer (see [`super::RtspFramer`]).
|
/// Feeds one whole answer (see [`super::RtspFramer`]).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::HostStatus`] for a non-200 answer, [`crate::Error::Malformed`] for a `CSeq` that does not
|
/// [`Error::HostStatus`] for a non-200 answer, [`Error::Malformed`] for a `CSeq` that does not match or a bad
|
||||||
/// match or a bad payload, [`crate::Error::Unsupported`] when the host lacks something required,
|
/// payload, [`Error::Unsupported`] when the host lacks something required, [`Error::State`] when no request is
|
||||||
/// [`crate::Error::State`] when no request is outstanding. Phase A: always [`crate::Error::Unimplemented`].
|
/// outstanding. Every error but `State` moves the client to [`RtspClientState::Failed`].
|
||||||
pub fn handle_response(&mut self, message: &[u8]) -> crate::Result<RtspProgress> {
|
pub fn handle_response(&mut self, message: &[u8]) -> Result<RtspProgress> {
|
||||||
let _ = message;
|
if !self.outstanding || matches!(self.state, RtspClientState::Ready | RtspClientState::Failed) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::State { expected: "an RTSP request outstanding" });
|
||||||
|
}
|
||||||
|
self.outstanding = false;
|
||||||
|
match self.advance(message) {
|
||||||
|
Ok(p) => Ok(p),
|
||||||
|
Err(e) => {
|
||||||
|
self.state = RtspClientState::Failed;
|
||||||
|
self.pending = None;
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn advance(&mut self, message: &[u8]) -> Result<RtspProgress> {
|
||||||
|
let r = parse_response(message)?;
|
||||||
|
let cseq = r.header("CSeq").ok_or(malformed("rtsp answer without CSeq"))?;
|
||||||
|
if crate::util::parse_u32("rtsp CSeq", cseq)? != self.cseq {
|
||||||
|
return Err(malformed("rtsp answer to another request (CSeq)"));
|
||||||
|
}
|
||||||
|
if r.status != 200 {
|
||||||
|
return Err(Error::HostStatus { code: u32::from(r.status) });
|
||||||
|
}
|
||||||
|
let url = self.url.clone();
|
||||||
|
match self.state {
|
||||||
|
RtspClientState::Options => {
|
||||||
|
self.queue(Method::Describe, &url, vec![("Accept".into(), "application/sdp".into())], Vec::new())?;
|
||||||
|
self.state = RtspClientState::Describe;
|
||||||
|
}
|
||||||
|
RtspClientState::Describe => {
|
||||||
|
let host = HostCapabilities::from_sdp(&sdp::parse_sdp(&r.body)?)?;
|
||||||
|
sdp::negotiated_encryption(&self.config, &host)?;
|
||||||
|
self.host = Some(host);
|
||||||
|
self.setup(0)?;
|
||||||
|
self.state = RtspClientState::SetupAudio;
|
||||||
|
}
|
||||||
|
RtspClientState::SetupAudio | RtspClientState::SetupVideo | RtspClientState::SetupControl => {
|
||||||
|
let index = match self.state {
|
||||||
|
RtspClientState::SetupAudio => 0,
|
||||||
|
RtspClientState::SetupVideo => 1,
|
||||||
|
_ => 2,
|
||||||
|
};
|
||||||
|
let port = server_port(&r)?;
|
||||||
|
if let Some(slot) = self.ports.get_mut(index) {
|
||||||
|
*slot = port;
|
||||||
|
}
|
||||||
|
if let Some(s) = r.header("Session") {
|
||||||
|
let id = s.split(';').next().unwrap_or("").trim();
|
||||||
|
if !id.is_empty() {
|
||||||
|
self.session_id = Some(id.to_owned());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if index < 2 {
|
||||||
|
self.setup(index + 1)?;
|
||||||
|
self.state = if index == 0 { RtspClientState::SetupVideo } else { RtspClientState::SetupControl };
|
||||||
|
} else {
|
||||||
|
let host = self.host.as_ref().ok_or(Error::State { expected: "DESCRIBE answered" })?;
|
||||||
|
let body = sdp::build_announce(&self.config, host)?;
|
||||||
|
let target = SETUP_TARGETS.get(2).copied().unwrap_or("streamid=control/13/0");
|
||||||
|
self.queue(
|
||||||
|
Method::Announce,
|
||||||
|
target,
|
||||||
|
vec![("Content-type".into(), "application/sdp".into())],
|
||||||
|
body,
|
||||||
|
)?;
|
||||||
|
self.state = RtspClientState::Announce;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RtspClientState::Announce => {
|
||||||
|
self.queue(Method::Play, &url, Vec::new(), Vec::new())?;
|
||||||
|
self.state = RtspClientState::Play;
|
||||||
|
}
|
||||||
|
RtspClientState::Play => {
|
||||||
|
let host = self.host.clone().ok_or(Error::State { expected: "DESCRIBE answered" })?;
|
||||||
|
let encryption = sdp::negotiated_encryption(&self.config, &host)?;
|
||||||
|
let [audio, video, control] = self.ports;
|
||||||
|
let stream = NegotiatedStream {
|
||||||
|
ports: StreamPorts { audio, video, control },
|
||||||
|
encryption,
|
||||||
|
opus: host.opus_for(self.config.audio.channels()),
|
||||||
|
host,
|
||||||
|
session_id: self.session_id.clone(),
|
||||||
|
ping_payload: PING_PAYLOAD.to_vec(),
|
||||||
|
};
|
||||||
|
self.state = RtspClientState::Ready;
|
||||||
|
return Ok(RtspProgress::Ready(stream));
|
||||||
|
}
|
||||||
|
RtspClientState::Ready | RtspClientState::Failed => {
|
||||||
|
return Err(Error::State { expected: "an RTSP request outstanding" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(RtspProgress::Continue)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn setup(&mut self, index: usize) -> Result<()> {
|
||||||
|
let target = SETUP_TARGETS.get(index).copied().ok_or(Error::State { expected: "a SETUP stream" })?;
|
||||||
|
self.queue(Method::Setup, target, vec![("Transport".into(), TRANSPORT.into())], Vec::new())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Where the negotiation is.
|
/// Where the negotiation is.
|
||||||
@@ -149,3 +307,19 @@ impl RtspClient {
|
|||||||
self.state
|
self.state
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `server_port=N` from the `Transport` header (other `;` parts ignored), N in 1..=65535.
|
||||||
|
fn server_port(r: &RtspResponse) -> Result<u16> {
|
||||||
|
let t = r.header("Transport").ok_or(malformed("rtsp SETUP answer without Transport"))?;
|
||||||
|
let v = t
|
||||||
|
.split(';')
|
||||||
|
.find_map(|p| p.trim().strip_prefix("server_port="))
|
||||||
|
.ok_or(malformed("rtsp Transport without server_port"))?;
|
||||||
|
// `server_port=a-b` names a range; the first port is the one used.
|
||||||
|
let first = v.split('-').next().unwrap_or("");
|
||||||
|
let port = parse_u16("rtsp server_port", first)?;
|
||||||
|
if port == 0 {
|
||||||
|
return Err(malformed("rtsp server_port 0"));
|
||||||
|
}
|
||||||
|
Ok(port)
|
||||||
|
}
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ pub mod sdp;
|
|||||||
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
pub use client::{NegotiatedStream, RtspClient, RtspClientState, RtspProgress, StreamConfig, StreamPorts};
|
||||||
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
pub use sdp::{EncryptionFlags, HostCapabilities, OpusConfig, Sdp};
|
||||||
|
|
||||||
|
use crate::util::{cap, malformed, parse_dec};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Default RTSP port.
|
/// Default RTSP port.
|
||||||
pub const DEFAULT_RTSP_PORT: u16 = 48010;
|
pub const DEFAULT_RTSP_PORT: u16 = 48010;
|
||||||
/// Maximum size of one RTSP message (start line + headers + payload), in bytes.
|
/// Maximum size of one RTSP message (start line + headers + payload), in bytes.
|
||||||
@@ -16,6 +19,9 @@ pub const MAX_RTSP_LINE_BYTES: usize = 4096;
|
|||||||
/// Maximum number of header lines in one message.
|
/// Maximum number of header lines in one message.
|
||||||
pub const MAX_RTSP_HEADERS: usize = 64;
|
pub const MAX_RTSP_HEADERS: usize = 64;
|
||||||
|
|
||||||
|
/// The only protocol version spoken.
|
||||||
|
const VERSION: &str = "RTSP/1.0";
|
||||||
|
|
||||||
/// The methods this client sends.
|
/// The methods this client sends.
|
||||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
pub enum Method {
|
pub enum Method {
|
||||||
@@ -31,6 +37,24 @@ pub enum Method {
|
|||||||
Play,
|
Play,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Method {
|
||||||
|
/// The method token.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Options => "OPTIONS",
|
||||||
|
Self::Describe => "DESCRIBE",
|
||||||
|
Self::Setup => "SETUP",
|
||||||
|
Self::Announce => "ANNOUNCE",
|
||||||
|
Self::Play => "PLAY",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn from_token(t: &str) -> Option<Self> {
|
||||||
|
[Self::Options, Self::Describe, Self::Setup, Self::Announce, Self::Play].into_iter().find(|m| m.as_str() == t)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// An RTSP request.
|
/// An RTSP request.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
pub struct RtspRequest {
|
pub struct RtspRequest {
|
||||||
@@ -44,15 +68,44 @@ pub struct RtspRequest {
|
|||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_token(b: u8) -> bool {
|
||||||
|
b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)
|
||||||
|
}
|
||||||
|
|
||||||
impl RtspRequest {
|
impl RtspRequest {
|
||||||
/// Serializes the request (CRLF line ends, empty line, payload). Refuses CR or LF inside a target, header
|
/// Serializes the request (CRLF line ends, empty line, payload) with exactly the given headers. Refuses CR or
|
||||||
/// name or value.
|
/// LF inside a target, header name or value, whitespace in the target, and header names that are not tokens.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a forbidden character, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for a forbidden character, [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`].
|
||||||
/// [`MAX_RTSP_MESSAGE_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||||
pub fn encode(&self) -> crate::Result<Vec<u8>> {
|
if self.target.is_empty() || self.target.bytes().any(|b| b.is_ascii_whitespace() || b.is_ascii_control()) {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(malformed("rtsp target"));
|
||||||
|
}
|
||||||
|
let mut out = format!("{} {} {VERSION}\r\n", self.method.as_str(), self.target);
|
||||||
|
for (name, value) in &self.headers {
|
||||||
|
if name.is_empty() || !name.bytes().all(is_token) {
|
||||||
|
return Err(malformed("rtsp header name"));
|
||||||
|
}
|
||||||
|
if value.bytes().any(|b| b == b'\r' || b == b'\n') {
|
||||||
|
return Err(malformed("rtsp header value"));
|
||||||
|
}
|
||||||
|
out.push_str(name);
|
||||||
|
out.push_str(": ");
|
||||||
|
out.push_str(value);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
out.push_str("\r\n");
|
||||||
|
let mut bytes = out.into_bytes();
|
||||||
|
cap("rtsp request", MAX_RTSP_MESSAGE_BYTES, bytes.len().saturating_add(self.body.len()))?;
|
||||||
|
bytes.extend_from_slice(&self.body);
|
||||||
|
Ok(bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first header with this name, compared case-insensitively.
|
||||||
|
#[must_use]
|
||||||
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
|
header(&self.headers, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -69,32 +122,134 @@ pub struct RtspResponse {
|
|||||||
pub body: Vec<u8>,
|
pub body: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn header<'a>(headers: &'a [(String, String)], name: &str) -> Option<&'a str> {
|
||||||
|
headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||||
|
}
|
||||||
|
|
||||||
impl RtspResponse {
|
impl RtspResponse {
|
||||||
/// The first header with this name, compared case-insensitively.
|
/// The first header with this name, compared case-insensitively.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn header(&self, name: &str) -> Option<&str> {
|
pub fn header(&self, name: &str) -> Option<&str> {
|
||||||
self.headers.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
header(&self.headers, name)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A message split into start line, headers and payload.
|
||||||
|
struct Message {
|
||||||
|
start: String,
|
||||||
|
headers: Vec<(String, String)>,
|
||||||
|
body: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One CRLF-terminated line at `pos`: (line without CRLF, position after CRLF). `None` when no LF follows.
|
||||||
|
fn line(data: &[u8], pos: usize) -> Result<Option<(&str, usize)>> {
|
||||||
|
let rest = data.get(pos..).unwrap_or(&[]);
|
||||||
|
let Some(lf) = rest.iter().take(MAX_RTSP_LINE_BYTES + 2).position(|&b| b == b'\n') else {
|
||||||
|
if rest.len() > MAX_RTSP_LINE_BYTES + 1 {
|
||||||
|
return Err(Error::TooLarge { what: "rtsp line", max: MAX_RTSP_LINE_BYTES, actual: rest.len() });
|
||||||
|
}
|
||||||
|
return Ok(None);
|
||||||
|
};
|
||||||
|
let raw = rest.get(..lf).unwrap_or(&[]);
|
||||||
|
let text = raw.strip_suffix(b"\r").ok_or(malformed("rtsp line without CRLF"))?;
|
||||||
|
cap("rtsp line", MAX_RTSP_LINE_BYTES, text.len())?;
|
||||||
|
if text.contains(&b'\r') {
|
||||||
|
return Err(malformed("rtsp: CR inside a line"));
|
||||||
|
}
|
||||||
|
let text = core::str::from_utf8(text).map_err(|_| malformed("rtsp: not UTF-8"))?;
|
||||||
|
Ok(Some((text, pos + lf + 1)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parses headers from `pos` up to the empty line: (headers, position of the payload).
|
||||||
|
fn headers_from(data: &[u8], mut pos: usize) -> Result<(Vec<(String, String)>, usize)> {
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
loop {
|
||||||
|
let (text, next) = line(data, pos)?.ok_or(Error::Truncated {
|
||||||
|
what: "rtsp headers",
|
||||||
|
needed: data.len().saturating_add(2),
|
||||||
|
actual: data.len(),
|
||||||
|
})?;
|
||||||
|
pos = next;
|
||||||
|
if text.is_empty() {
|
||||||
|
return Ok((headers, pos));
|
||||||
|
}
|
||||||
|
let (name, value) = text.split_once(':').ok_or(malformed("rtsp header without :"))?;
|
||||||
|
if name.is_empty() || !name.bytes().all(is_token) {
|
||||||
|
return Err(malformed("rtsp header name"));
|
||||||
|
}
|
||||||
|
headers.push((name.to_owned(), value.trim_matches([' ', '\t']).to_owned()));
|
||||||
|
cap("rtsp headers", MAX_RTSP_HEADERS, headers.len())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The message's Content-Length, if any: strict digits, all copies equal, within the cap.
|
||||||
|
fn content_length(headers: &[(String, String)], head_len: usize) -> Result<Option<usize>> {
|
||||||
|
let mut found: Option<u64> = None;
|
||||||
|
for (_, v) in headers.iter().filter(|(n, _)| n.eq_ignore_ascii_case("content-length")) {
|
||||||
|
let n = parse_dec("rtsp Content-Length", v)?;
|
||||||
|
if found.is_some_and(|f| f != n) {
|
||||||
|
return Err(malformed("rtsp: two different Content-Length values"));
|
||||||
|
}
|
||||||
|
found = Some(n);
|
||||||
|
}
|
||||||
|
let Some(n) = found else { return Ok(None) };
|
||||||
|
let total = usize::try_from(n).unwrap_or(usize::MAX).saturating_add(head_len);
|
||||||
|
cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, total)?;
|
||||||
|
Ok(Some(total - head_len))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn split_message(msg: &[u8]) -> Result<Message> {
|
||||||
|
cap("rtsp message", MAX_RTSP_MESSAGE_BYTES, msg.len())?;
|
||||||
|
let (start, pos) = line(msg, 0)?.ok_or(malformed("rtsp: no start line"))?;
|
||||||
|
if start.is_empty() {
|
||||||
|
return Err(malformed("rtsp: empty start line"));
|
||||||
|
}
|
||||||
|
let start = start.to_owned();
|
||||||
|
let (headers, body_at) = headers_from(msg, pos)?;
|
||||||
|
let rest = msg.get(body_at..).unwrap_or(&[]);
|
||||||
|
let body = match content_length(&headers, body_at)? {
|
||||||
|
None => rest.to_vec(),
|
||||||
|
Some(n) if rest.len() < n => {
|
||||||
|
return Err(Error::Truncated { what: "rtsp payload", needed: body_at + n, actual: msg.len() });
|
||||||
|
}
|
||||||
|
Some(n) if rest.len() > n => return Err(malformed("rtsp: bytes after the payload")),
|
||||||
|
Some(_) => rest.to_vec(),
|
||||||
|
};
|
||||||
|
Ok(Message { start, headers, body })
|
||||||
|
}
|
||||||
|
|
||||||
/// Parses one complete response (as cut by [`RtspFramer`]).
|
/// Parses one complete response (as cut by [`RtspFramer`]).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`],
|
/// [`Error::TooLarge`] over [`MAX_RTSP_MESSAGE_BYTES`], [`MAX_RTSP_LINE_BYTES`] or [`MAX_RTSP_HEADERS`],
|
||||||
/// [`crate::Error::Malformed`] for a bad start line, header line or `Content-Length`. Phase A: always
|
/// [`Error::Malformed`] for a bad start line, header line or `Content-Length`, [`Error::Truncated`] when the headers
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// or the payload end early.
|
||||||
pub fn parse_response(message: &[u8]) -> crate::Result<RtspResponse> {
|
pub fn parse_response(message: &[u8]) -> Result<RtspResponse> {
|
||||||
let _ = message;
|
let m = split_message(message)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let rest = m.start.strip_prefix("RTSP/1.0 ").ok_or(malformed("rtsp: not an RTSP/1.0 response"))?;
|
||||||
|
let (code, reason) = rest.split_once(' ').unwrap_or((rest, ""));
|
||||||
|
if code.len() != 3 || !code.bytes().all(|b| b.is_ascii_digit()) {
|
||||||
|
return Err(malformed("rtsp status code"));
|
||||||
|
}
|
||||||
|
let status = crate::util::parse_u16("rtsp status code", code)?;
|
||||||
|
Ok(RtspResponse { status, reason: reason.to_owned(), headers: m.headers, body: m.body })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses one complete request. Not used by the client; here for the fuzz harness and the Lumen host (Day 3).
|
/// Parses one complete request. Not used by the client; here for the fuzz harness and the Lumen host (Day 3).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// As [`parse_response`], plus [`crate::Error::UnexpectedValue`] for an unknown method.
|
/// As [`parse_response`], plus [`Error::UnexpectedValue`] for an unknown method.
|
||||||
pub fn parse_request(message: &[u8]) -> crate::Result<RtspRequest> {
|
pub fn parse_request(message: &[u8]) -> Result<RtspRequest> {
|
||||||
let _ = message;
|
let m = split_message(message)?;
|
||||||
Err(crate::Error::Unimplemented)
|
let mut parts = m.start.splitn(3, ' ');
|
||||||
|
let (Some(method), Some(target), Some(version)) = (parts.next(), parts.next(), parts.next()) else {
|
||||||
|
return Err(malformed("rtsp request line"));
|
||||||
|
};
|
||||||
|
if method.is_empty() || target.is_empty() || version != VERSION {
|
||||||
|
return Err(malformed("rtsp request line"));
|
||||||
|
}
|
||||||
|
let method = Method::from_token(method).ok_or(Error::UnexpectedValue { what: "rtsp method", value: 0 })?;
|
||||||
|
Ok(RtspRequest { method, target: target.to_owned(), headers: m.headers, body: m.body })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Cuts the TCP byte stream from the host into whole messages.
|
/// Cuts the TCP byte stream from the host into whole messages.
|
||||||
@@ -117,28 +272,63 @@ impl RtspFramer {
|
|||||||
/// Appends received bytes.
|
/// Appends received bytes.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] when the unfinished message would exceed [`MAX_RTSP_MESSAGE_BYTES`]. Phase A:
|
/// [`Error::TooLarge`] when the buffered bytes would exceed [`MAX_RTSP_MESSAGE_BYTES`] (nothing is appended).
|
||||||
/// always [`crate::Error::Unimplemented`].
|
pub fn push(&mut self, bytes: &[u8]) -> Result<()> {
|
||||||
pub fn push(&mut self, bytes: &[u8]) -> crate::Result<()> {
|
cap("rtsp stream", MAX_RTSP_MESSAGE_BYTES, self.buffer.len().saturating_add(bytes.len()))?;
|
||||||
let _ = bytes;
|
self.buffer.extend_from_slice(bytes);
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Where the buffered header section ends and the message's Content-Length, if the headers are complete.
|
||||||
|
fn head(&self) -> Result<Option<(usize, Option<usize>)>> {
|
||||||
|
let Some(end) = self.buffer.windows(4).position(|w| w == b"\r\n\r\n") else { return Ok(None) };
|
||||||
|
let head_len = end + 4;
|
||||||
|
let head = self.buffer.get(..head_len).unwrap_or(&[]);
|
||||||
|
let mut headers = Vec::new();
|
||||||
|
for raw in head.split(|&b| b == b'\n').skip(1) {
|
||||||
|
let text = core::str::from_utf8(raw.strip_suffix(b"\r").unwrap_or(raw)).unwrap_or("");
|
||||||
|
if let Some((n, v)) = text.split_once(':')
|
||||||
|
&& n.eq_ignore_ascii_case("content-length")
|
||||||
|
{
|
||||||
|
headers.push((n.to_owned(), v.trim_matches([' ', '\t']).to_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(Some((head_len, content_length(&headers, head_len)?)))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Takes the next complete message, if one is buffered.
|
/// Takes the next complete message, if one is buffered.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a bad `Content-Length`. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`Error::Malformed`] for a bad `Content-Length`, [`Error::TooLarge`] when it announces a message over the cap.
|
||||||
pub fn next_message(&mut self) -> crate::Result<Option<Vec<u8>>> {
|
pub fn next_message(&mut self) -> Result<Option<Vec<u8>>> {
|
||||||
Err(crate::Error::Unimplemented)
|
match self.head()? {
|
||||||
|
Some((head, Some(len))) if self.buffer.len() >= head + len => {
|
||||||
|
let rest = self.buffer.split_off(head + len);
|
||||||
|
Ok(Some(core::mem::replace(&mut self.buffer, rest)))
|
||||||
|
}
|
||||||
|
_ => Ok(None),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The host closed the connection: returns what is buffered as the last message, if anything.
|
/// The host closed the connection: returns what is buffered as the last message, if anything.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Truncated`] when a `Content-Length` promised more. Phase A: always
|
/// [`Error::Truncated`] when the headers never ended or a `Content-Length` promised more.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn finish(&mut self) -> Result<Option<Vec<u8>>> {
|
||||||
pub fn finish(&mut self) -> crate::Result<Option<Vec<u8>>> {
|
if self.buffer.is_empty() {
|
||||||
Err(crate::Error::Unimplemented)
|
return Ok(None);
|
||||||
|
}
|
||||||
|
match self.head()? {
|
||||||
|
None => Err(Error::Truncated {
|
||||||
|
what: "rtsp headers at close",
|
||||||
|
needed: self.buffer.len().saturating_add(4),
|
||||||
|
actual: self.buffer.len(),
|
||||||
|
}),
|
||||||
|
Some((head, Some(len))) if self.buffer.len() < head + len => {
|
||||||
|
Err(Error::Truncated { what: "rtsp payload at close", needed: head + len, actual: self.buffer.len() })
|
||||||
|
}
|
||||||
|
Some(_) => Ok(Some(core::mem::take(&mut self.buffer))),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Bytes buffered but not yet returned.
|
/// Bytes buffered but not yet returned.
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4).
|
//! The SDP-like payloads of DESCRIBE (host → client) and ANNOUNCE (client → host) (`docs/PROTOCOL.md` 2.3, 2.4).
|
||||||
|
|
||||||
use super::client::StreamConfig;
|
use super::client::{StreamConfig, VideoCodec};
|
||||||
|
use crate::util::{cap, malformed, parse_u8, parse_u32};
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
/// Maximum size of an SDP payload, in bytes.
|
/// Maximum size of an SDP payload, in bytes.
|
||||||
pub const MAX_SDP_BYTES: usize = 32 * 1024;
|
pub const MAX_SDP_BYTES: usize = 32 * 1024;
|
||||||
@@ -29,14 +31,39 @@ impl Sdp {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses an SDP payload. Lines end in LF or CRLF.
|
/// Parses an SDP payload. Lines end in LF or CRLF; empty lines are skipped.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`crate::Error::Malformed`] for a line
|
/// [`Error::TooLarge`] over [`MAX_SDP_BYTES`] or [`MAX_SDP_LINES`], [`Error::Malformed`] for a payload that is not
|
||||||
/// that is not UTF-8 or has no `=`. Phase A: always [`crate::Error::Unimplemented`].
|
/// UTF-8 or a line without `=` or with an empty type.
|
||||||
pub fn parse_sdp(payload: &[u8]) -> crate::Result<Sdp> {
|
pub fn parse_sdp(payload: &[u8]) -> Result<Sdp> {
|
||||||
let _ = payload;
|
cap("sdp", MAX_SDP_BYTES, payload.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let text = core::str::from_utf8(payload).map_err(|_| malformed("sdp: not UTF-8"))?;
|
||||||
|
let mut sdp = Sdp::default();
|
||||||
|
let mut lines = 0usize;
|
||||||
|
for raw in text.split('\n') {
|
||||||
|
let line = raw.strip_suffix('\r').unwrap_or(raw);
|
||||||
|
if line.is_empty() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lines += 1;
|
||||||
|
cap("sdp lines", MAX_SDP_LINES, lines)?;
|
||||||
|
let (kind, value) = line.split_once('=').ok_or(malformed("sdp line without ="))?;
|
||||||
|
if kind.is_empty() {
|
||||||
|
return Err(malformed("sdp line with an empty type"));
|
||||||
|
}
|
||||||
|
if kind == "a" {
|
||||||
|
let (name, value) = value.split_once(':').unwrap_or((value, ""));
|
||||||
|
sdp.attributes.push((name.to_owned(), value.to_owned()));
|
||||||
|
} else {
|
||||||
|
let mut chars = kind.chars();
|
||||||
|
match (chars.next(), chars.next()) {
|
||||||
|
(Some(c), None) => sdp.other.push((c, value.to_owned())),
|
||||||
|
_ => sdp.other.push(('\0', line.to_owned())),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(sdp)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Encryption flag bits of `x-ss-general.encryptionSupported` / `encryptionEnabled`.
|
/// Encryption flag bits of `x-ss-general.encryptionSupported` / `encryptionEnabled`.
|
||||||
@@ -50,6 +77,12 @@ impl EncryptionFlags {
|
|||||||
pub const VIDEO: u8 = 0x02;
|
pub const VIDEO: u8 = 0x02;
|
||||||
/// Audio AES-CBC.
|
/// Audio AES-CBC.
|
||||||
pub const AUDIO: u8 = 0x04;
|
pub const AUDIO: u8 = 0x04;
|
||||||
|
|
||||||
|
/// Whether every bit of `flags` is set.
|
||||||
|
#[must_use]
|
||||||
|
pub const fn contains(self, flags: u8) -> bool {
|
||||||
|
self.0 & flags == flags
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feature flag bits of `x-ss-general.featureFlags`.
|
/// Feature flag bits of `x-ss-general.featureFlags`.
|
||||||
@@ -76,16 +109,41 @@ pub struct OpusConfig {
|
|||||||
pub mapping: Vec<u8>,
|
pub mapping: Vec<u8>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl OpusConfig {
|
||||||
|
/// Plain stereo: 2 channels, 1 coupled stream, mapping 0 1 (Wolf's `21101`).
|
||||||
|
#[must_use]
|
||||||
|
pub fn stereo() -> Self {
|
||||||
|
Self { channels: 2, streams: 1, coupled_streams: 1, mapping: vec![0, 1] }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Parses one `surround-params` value (single digits: channels, streams, coupled, then one mapping digit per
|
/// Parses one `surround-params` value (single digits: channels, streams, coupled, then one mapping digit per
|
||||||
/// channel), e.g. `21101`.
|
/// channel), e.g. `21101`.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules
|
/// [`Error::Malformed`] for a non-digit, a wrong length, or values that break RFC 7845's rules
|
||||||
/// (`coupled ≤ streams`, `streams + coupled ≤ 255`, mapping entries `< streams + coupled`). Phase A: always
|
/// (`1 ≤ channels ≤ 8`, `streams ≥ 1`, `coupled ≤ streams`, mapping entries `< streams + coupled`).
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn parse_surround_params(value: &str) -> Result<OpusConfig> {
|
||||||
pub fn parse_surround_params(value: &str) -> crate::Result<OpusConfig> {
|
let digits: Vec<u8> = value
|
||||||
let _ = value;
|
.bytes()
|
||||||
Err(crate::Error::Unimplemented)
|
.map(|b| if b.is_ascii_digit() { Some(b - b'0') } else { None })
|
||||||
|
.collect::<Option<Vec<u8>>>()
|
||||||
|
.ok_or(malformed("surround-params"))?;
|
||||||
|
let (&channels, &streams, &coupled) = match digits.as_slice() {
|
||||||
|
[c, s, k, ..] => (c, s, k),
|
||||||
|
_ => return Err(malformed("surround-params")),
|
||||||
|
};
|
||||||
|
let mapping = digits.get(3..).unwrap_or(&[]);
|
||||||
|
if channels == 0
|
||||||
|
|| usize::from(channels) > MAX_AUDIO_CHANNELS
|
||||||
|
|| streams == 0
|
||||||
|
|| coupled > streams
|
||||||
|
|| mapping.len() != usize::from(channels)
|
||||||
|
|| mapping.iter().any(|&m| m >= streams + coupled)
|
||||||
|
{
|
||||||
|
return Err(malformed("surround-params"));
|
||||||
|
}
|
||||||
|
Ok(OpusConfig { channels, streams, coupled_streams: coupled, mapping: mapping.to_vec() })
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What the host offers, read from the DESCRIBE payload.
|
/// What the host offers, read from the DESCRIBE payload.
|
||||||
@@ -107,20 +165,99 @@ impl HostCapabilities {
|
|||||||
/// Reads the capabilities from a DESCRIBE payload.
|
/// Reads the capabilities from a DESCRIBE payload.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a present attribute with a bad value, [`crate::Error::TooLarge`] over
|
/// [`Error::Malformed`] for a present attribute with a bad value, [`Error::TooLarge`] over
|
||||||
/// [`MAX_OPUS_CONFIGS`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`MAX_OPUS_CONFIGS`].
|
||||||
pub fn from_sdp(sdp: &Sdp) -> crate::Result<Self> {
|
pub fn from_sdp(sdp: &Sdp) -> Result<Self> {
|
||||||
let _ = sdp;
|
let mut caps = Self::default();
|
||||||
Err(crate::Error::Unimplemented)
|
if let Some(v) = sdp.attribute("x-ss-general.encryptionSupported") {
|
||||||
|
caps.encryption_supported = EncryptionFlags(parse_u8("sdp encryptionSupported", v)?);
|
||||||
|
}
|
||||||
|
if let Some(v) = sdp.attribute("x-ss-general.featureFlags") {
|
||||||
|
caps.feature_flags = FeatureFlags(parse_u32("sdp featureFlags", v)?);
|
||||||
|
}
|
||||||
|
caps.reference_frame_invalidation = sdp.attribute("x-nv-video[0].refPicInvalidation") == Some("1");
|
||||||
|
caps.av1 = sdp
|
||||||
|
.attributes
|
||||||
|
.iter()
|
||||||
|
.any(|(n, v)| n == "rtpmap" && v.split_whitespace().nth(1).is_some_and(|c| c.starts_with("AV1/")));
|
||||||
|
for (_, v) in sdp.attributes.iter().filter(|(n, _)| n == "fmtp") {
|
||||||
|
let Some(params) = v.strip_prefix("97 ") else { continue };
|
||||||
|
for p in params.split(';').map(str::trim) {
|
||||||
|
if let Some(digits) = p.strip_prefix("surround-params=") {
|
||||||
|
caps.opus_configs.push(parse_surround_params(digits)?);
|
||||||
|
cap("sdp opus configurations", MAX_OPUS_CONFIGS, caps.opus_configs.len())?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(caps)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The first configuration with `channels` channels, or plain stereo when the host lists none for it.
|
||||||
|
#[must_use]
|
||||||
|
pub fn opus_for(&self, channels: u8) -> OpusConfig {
|
||||||
|
self.opus_configs.iter().find(|c| c.channels == channels).cloned().unwrap_or_else(OpusConfig::stereo)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `x-nv-vqos[0].bitStreamFormat` values (judgment from the codec order H.264, HEVC, AV1; UNKNOWN U6).
|
||||||
|
const fn bitstream_format(codec: VideoCodec) -> u8 {
|
||||||
|
match codec {
|
||||||
|
VideoCodec::H264 => 0,
|
||||||
|
VideoCodec::Hevc => 1,
|
||||||
|
VideoCodec::Av1 => 2,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The encryption flags an ANNOUNCE turns on: what both sides support. Control V2 is required.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`Error::Unsupported`] when the host or the client config lacks control V2 encryption.
|
||||||
|
pub fn negotiated_encryption(config: &StreamConfig, host: &HostCapabilities) -> Result<EncryptionFlags> {
|
||||||
|
let flags = EncryptionFlags(config.encryption.0 & host.encryption_supported.0);
|
||||||
|
if !flags.contains(EncryptionFlags::CONTROL_V2) {
|
||||||
|
return Err(Error::Unsupported { what: "control stream encryption (V2)" });
|
||||||
|
}
|
||||||
|
Ok(flags)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Builds the ANNOUNCE payload for `config`, turning on the encryption flags both sides support.
|
/// Builds the ANNOUNCE payload for `config`, turning on the encryption flags both sides support.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Unsupported`] when the host lacks control V2 encryption or the requested codec. Phase A: always
|
/// [`Error::Unsupported`] when the host lacks control V2 encryption or the requested codec.
|
||||||
/// [`crate::Error::Unimplemented`].
|
pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> Result<Vec<u8>> {
|
||||||
pub fn build_announce(config: &StreamConfig, host: &HostCapabilities) -> crate::Result<Vec<u8>> {
|
let enabled = negotiated_encryption(config, host)?;
|
||||||
let _ = (config, host);
|
if config.codec == VideoCodec::Av1 && !host.av1 {
|
||||||
Err(crate::Error::Unimplemented)
|
return Err(Error::Unsupported { what: "AV1 video" });
|
||||||
|
}
|
||||||
|
let channels = config.audio.channels();
|
||||||
|
let attrs: [(&str, String); 19] = [
|
||||||
|
("x-nv-video[0].clientViewportWd", config.width.to_string()),
|
||||||
|
("x-nv-video[0].clientViewportHt", config.height.to_string()),
|
||||||
|
("x-nv-video[0].maxFPS", config.fps.to_string()),
|
||||||
|
("x-nv-video[0].packetSize", config.packet_size.to_string()),
|
||||||
|
("x-nv-video[0].maxNumReferenceFrames", if config.reference_frame_invalidation { "0" } else { "1" }.into()),
|
||||||
|
("x-nv-video[0].refPicInvalidation", u8::from(config.reference_frame_invalidation).to_string()),
|
||||||
|
("x-nv-video[0].dynamicRangeMode", u8::from(config.hdr).to_string()),
|
||||||
|
("x-nv-video[0].encoderCscMode", if config.hdr { "5" } else { "0" }.into()),
|
||||||
|
("x-nv-vqos[0].bitStreamFormat", bitstream_format(config.codec).to_string()),
|
||||||
|
("x-nv-vqos[0].fec.minRequiredFecPackets", config.min_fec_packets.to_string()),
|
||||||
|
("x-nv-vqos[0].qosTrafficType", "5".into()),
|
||||||
|
("x-ml-video.configuredBitrateKbps", config.bitrate_kbps.to_string()),
|
||||||
|
("x-nv-aqos.packetDuration", config.audio_packet_duration_ms.to_string()),
|
||||||
|
("x-nv-aqos.qosTrafficType", "4".into()),
|
||||||
|
("x-nv-audio.surround.enable", u8::from(channels > 2).to_string()),
|
||||||
|
("x-nv-audio.surround.numChannels", channels.to_string()),
|
||||||
|
("x-nv-audio.surround.channelMask", config.audio.channel_mask().to_string()),
|
||||||
|
("x-ss-video[0].chromaSamplingType", "0".into()),
|
||||||
|
("x-ss-general.encryptionEnabled", enabled.0.to_string()),
|
||||||
|
];
|
||||||
|
let mut out = String::from("v=0\r\n");
|
||||||
|
for (name, value) in &attrs {
|
||||||
|
out.push_str("a=");
|
||||||
|
out.push_str(name);
|
||||||
|
out.push(':');
|
||||||
|
out.push_str(value);
|
||||||
|
out.push_str("\r\n");
|
||||||
|
}
|
||||||
|
Ok(out.into_bytes())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,259 @@
|
|||||||
|
//! Small strict helpers shared by the parsers. Nothing here indexes without a bound check.
|
||||||
|
|
||||||
|
use crate::{Error, Result};
|
||||||
|
|
||||||
|
/// `Error::Malformed`.
|
||||||
|
pub(crate) const fn malformed(what: &'static str) -> Error {
|
||||||
|
Error::Malformed { what }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Error::TooLarge` when `actual > max`.
|
||||||
|
pub(crate) const fn cap(what: &'static str, max: usize, actual: usize) -> Result<()> {
|
||||||
|
if actual > max { Err(Error::TooLarge { what, max, actual }) } else { Ok(()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `Error::Truncated` when `actual < needed`.
|
||||||
|
pub(crate) const fn need(what: &'static str, needed: usize, actual: usize) -> Result<()> {
|
||||||
|
if actual < needed { Err(Error::Truncated { what, needed, actual }) } else { Ok(()) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes `start..start + len` of `data`, or `Truncated`.
|
||||||
|
pub(crate) fn slice<'a>(what: &'static str, data: &'a [u8], start: usize, len: usize) -> Result<&'a [u8]> {
|
||||||
|
let end = start.checked_add(len).ok_or(malformed(what))?;
|
||||||
|
data.get(start..end).ok_or(Error::Truncated { what, needed: end, actual: data.len() })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fixed-size array at `start`.
|
||||||
|
pub(crate) fn array<const N: usize>(what: &'static str, data: &[u8], start: usize) -> Result<[u8; N]> {
|
||||||
|
let s = slice(what, data, start, N)?;
|
||||||
|
let mut out = [0u8; N];
|
||||||
|
out.copy_from_slice(s);
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u16_le(what: &'static str, data: &[u8], at: usize) -> Result<u16> {
|
||||||
|
array::<2>(what, data, at).map(u16::from_le_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u16_be(what: &'static str, data: &[u8], at: usize) -> Result<u16> {
|
||||||
|
array::<2>(what, data, at).map(u16::from_be_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u32_le(what: &'static str, data: &[u8], at: usize) -> Result<u32> {
|
||||||
|
array::<4>(what, data, at).map(u32::from_le_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn u32_be(what: &'static str, data: &[u8], at: usize) -> Result<u32> {
|
||||||
|
array::<4>(what, data, at).map(u32::from_be_bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reinterprets 16 bits as a signed value (two's complement).
|
||||||
|
pub(crate) const fn i16_from(v: u16) -> i16 {
|
||||||
|
i16::from_ne_bytes(v.to_ne_bytes())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn byte(what: &'static str, data: &[u8], at: usize) -> Result<u8> {
|
||||||
|
data.get(at).copied().ok_or(Error::Truncated { what, needed: at.saturating_add(1), actual: data.len() })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A strict decimal number: ASCII digits only, at least one, no sign, no spaces, no overflow.
|
||||||
|
pub(crate) fn parse_dec(what: &'static str, s: &str) -> Result<u64> {
|
||||||
|
if s.is_empty() || s.len() > 20 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let mut v: u64 = 0;
|
||||||
|
for b in s.bytes() {
|
||||||
|
if !b.is_ascii_digit() {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
v = v.checked_mul(10).and_then(|v| v.checked_add(u64::from(b - b'0'))).ok_or(malformed(what))?;
|
||||||
|
}
|
||||||
|
Ok(v)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_u32(what: &'static str, s: &str) -> Result<u32> {
|
||||||
|
u32::try_from(parse_dec(what, s)?).map_err(|_| malformed(what))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_u16(what: &'static str, s: &str) -> Result<u16> {
|
||||||
|
u16::try_from(parse_dec(what, s)?).map_err(|_| malformed(what))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn parse_u8(what: &'static str, s: &str) -> Result<u8> {
|
||||||
|
u8::try_from(parse_dec(what, s)?).map_err(|_| malformed(what))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lower-case hex.
|
||||||
|
pub(crate) fn hex_encode(bytes: &[u8]) -> String {
|
||||||
|
const DIGITS: &[u8; 16] = b"0123456789abcdef";
|
||||||
|
let mut s = String::with_capacity(bytes.len() * 2);
|
||||||
|
for b in bytes {
|
||||||
|
for nibble in [b >> 4, b & 0x0F] {
|
||||||
|
s.push(char::from(DIGITS.get(usize::from(nibble)).copied().unwrap_or(b'0')));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hex_digit(c: u8) -> Option<u8> {
|
||||||
|
match c {
|
||||||
|
b'0'..=b'9' => Some(c - b'0'),
|
||||||
|
b'a'..=b'f' => Some(c - b'a' + 10),
|
||||||
|
b'A'..=b'F' => Some(c - b'A' + 10),
|
||||||
|
_ => None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict hex of either case: even length, digits only.
|
||||||
|
pub(crate) fn hex_decode(what: &'static str, s: &str) -> Result<Vec<u8>> {
|
||||||
|
let b = s.as_bytes();
|
||||||
|
if !b.len().is_multiple_of(2) {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let mut out = Vec::with_capacity(b.len() / 2);
|
||||||
|
for [h, l] in b.as_chunks::<2>().0 {
|
||||||
|
match (hex_digit(*h), hex_digit(*l)) {
|
||||||
|
(Some(h), Some(l)) => out.push((h << 4) | l),
|
||||||
|
_ => return Err(malformed(what)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Percent-encodes everything but RFC 3986 unreserved characters.
|
||||||
|
pub(crate) fn percent_encode(s: &str) -> String {
|
||||||
|
const DIGITS: &[u8; 16] = b"0123456789ABCDEF";
|
||||||
|
let mut out = String::with_capacity(s.len());
|
||||||
|
for b in s.bytes() {
|
||||||
|
if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
|
||||||
|
out.push(char::from(b));
|
||||||
|
} else {
|
||||||
|
out.push('%');
|
||||||
|
out.push(char::from(DIGITS.get(usize::from(b >> 4)).copied().unwrap_or(b'0')));
|
||||||
|
out.push(char::from(DIGITS.get(usize::from(b & 0x0F)).copied().unwrap_or(b'0')));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
const B64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
|
||||||
|
/// Standard base64 with padding, wrapped at 64 characters per line (PEM).
|
||||||
|
pub(crate) fn base64_pem_lines(bytes: &[u8]) -> String {
|
||||||
|
let mut out = String::with_capacity(bytes.len() * 4 / 3 + bytes.len() / 48 + 4);
|
||||||
|
let mut line = 0;
|
||||||
|
for chunk in bytes.chunks(3) {
|
||||||
|
let b0 = chunk.first().copied().unwrap_or(0);
|
||||||
|
let b1 = chunk.get(1).copied().unwrap_or(0);
|
||||||
|
let b2 = chunk.get(2).copied().unwrap_or(0);
|
||||||
|
let n = (u32::from(b0) << 16) | (u32::from(b1) << 8) | u32::from(b2);
|
||||||
|
let sym = |shift: u32| char::from(B64.get(((n >> shift) & 0x3F) as usize).copied().unwrap_or(b'A'));
|
||||||
|
out.push(sym(18));
|
||||||
|
out.push(sym(12));
|
||||||
|
out.push(if chunk.len() > 1 { sym(6) } else { '=' });
|
||||||
|
out.push(if chunk.len() > 2 { sym(0) } else { '=' });
|
||||||
|
line += 4;
|
||||||
|
if line == 64 {
|
||||||
|
out.push('\n');
|
||||||
|
line = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if line != 0 {
|
||||||
|
out.push('\n');
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Strict standard base64: the 64 symbols, `=` padding only at the end, ASCII whitespace ignored, length a multiple
|
||||||
|
/// of 4 symbols, zero bits in the unused tail.
|
||||||
|
pub(crate) fn base64_decode(what: &'static str, s: &[u8]) -> Result<Vec<u8>> {
|
||||||
|
let mut vals: Vec<u8> = Vec::with_capacity(s.len());
|
||||||
|
let mut pad = 0usize;
|
||||||
|
for &c in s {
|
||||||
|
if c.is_ascii_whitespace() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if c == b'=' {
|
||||||
|
pad += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if pad > 0 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let v = B64.iter().position(|&x| x == c).ok_or(malformed(what))?;
|
||||||
|
vals.push(u8::try_from(v).map_err(|_| malformed(what))?);
|
||||||
|
}
|
||||||
|
if pad > 2 || !(vals.len() + pad).is_multiple_of(4) {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let mut out = Vec::with_capacity(vals.len() * 3 / 4);
|
||||||
|
let mut acc = 0u32;
|
||||||
|
let mut bits = 0u32;
|
||||||
|
for v in &vals {
|
||||||
|
// At most 13 pending bits: keep 14 so the shift never overflows.
|
||||||
|
acc = ((acc << 6) | u32::from(*v)) & 0x3FFF;
|
||||||
|
bits += 6;
|
||||||
|
if bits >= 8 {
|
||||||
|
bits -= 8;
|
||||||
|
out.push(((acc >> bits) & 0xFF) as u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if acc & ((1 << bits) - 1) != 0 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
Ok(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Constant-time equality (time depends on the lengths only).
|
||||||
|
pub(crate) fn ct_eq(a: &[u8], b: &[u8]) -> bool {
|
||||||
|
if a.len() != b.len() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `rtsp://host:port` with a non-empty host of letters, digits, `.`, `-` (or a bracketed IPv6 literal) and a port
|
||||||
|
/// 1..=65535.
|
||||||
|
pub(crate) fn check_rtsp_url(what: &'static str, url: &str) -> Result<(String, u16)> {
|
||||||
|
let rest = url.strip_prefix("rtsp://").ok_or(malformed(what))?;
|
||||||
|
let (host, port) = rest.rsplit_once(':').ok_or(malformed(what))?;
|
||||||
|
let host_ok = if let Some(inner) = host.strip_prefix('[').and_then(|h| h.strip_suffix(']')) {
|
||||||
|
!inner.is_empty() && inner.bytes().all(|b| b.is_ascii_hexdigit() || b == b':' || b == b'.')
|
||||||
|
} else {
|
||||||
|
!host.is_empty() && host.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'.' || b == b'-')
|
||||||
|
};
|
||||||
|
if !host_ok {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
let port = parse_u16(what, port)?;
|
||||||
|
if port == 0 {
|
||||||
|
return Err(malformed(what));
|
||||||
|
}
|
||||||
|
Ok((host.to_owned(), port))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn base64_round_trip() {
|
||||||
|
for n in 0..70usize {
|
||||||
|
let data: Vec<u8> = (0..n).map(|i| (i * 37) as u8).collect();
|
||||||
|
let text = base64_pem_lines(&data);
|
||||||
|
assert_eq!(base64_decode("t", text.as_bytes()).unwrap(), data);
|
||||||
|
}
|
||||||
|
assert!(base64_decode("t", b"QQ=A").is_err());
|
||||||
|
assert!(base64_decode("t", b"QR==").is_err(), "non-zero tail bits");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn hex_and_numbers() {
|
||||||
|
assert_eq!(hex_decode("t", "0aFf").unwrap(), vec![0x0A, 0xFF]);
|
||||||
|
assert!(hex_decode("t", "0").is_err() && hex_decode("t", "0x").is_err());
|
||||||
|
assert_eq!(parse_dec("t", "18446744073709551615").unwrap(), u64::MAX);
|
||||||
|
assert!(parse_dec("t", "18446744073709551616").is_err());
|
||||||
|
assert!(parse_dec("t", "+1").is_err() && parse_dec("t", "").is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,12 +1,23 @@
|
|||||||
//! The video receive path (`docs/PROTOCOL.md` section 5): decrypt (if negotiated) → parse → group by frame and
|
//! The video receive path (`docs/PROTOCOL.md` section 5): decrypt (if negotiated) → parse → group by frame and
|
||||||
//! FEC block → rebuild lost data shards → reassemble the frame → hand the Annex-B bitstream to the platform decoder.
|
//! FEC block → rebuild lost data shards → reassemble the frame → hand the Annex-B bitstream to the platform decoder.
|
||||||
//!
|
//!
|
||||||
//! Lost frames become [`VideoEvent::FrameLost`], which the caller answers on the control stream with
|
//! Frames come out strictly in frame order, each at most once and byte-exact; a frame that cannot be completed is
|
||||||
|
//! reported in a [`VideoEvent::FrameLost`] range, which the caller answers on the control stream with
|
||||||
//! `INVALIDATE_REF_FRAMES` (when the host supports it) or an IDR request.
|
//! `INVALIDATE_REF_FRAMES` (when the host supports it) or an IDR request.
|
||||||
|
//!
|
||||||
|
//! Only a shard's payload is used: the RTP and NV header bytes of a shard rebuilt by FEC are garbage (the host
|
||||||
|
//! writes parity headers after computing parity), so a shard's place comes from its FEC fields alone.
|
||||||
|
|
||||||
use core::fmt;
|
use core::fmt;
|
||||||
|
use core::time::Duration;
|
||||||
|
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
|
||||||
|
|
||||||
use crate::{Instant, Result};
|
use aes_gcm::Aes128Gcm;
|
||||||
|
use aes_gcm::aead::{AeadInOut, KeyInit};
|
||||||
|
|
||||||
|
use crate::fec::ReedSolomon;
|
||||||
|
use crate::util::{array, cap, malformed, need};
|
||||||
|
use crate::{Error, Instant, Result};
|
||||||
|
|
||||||
pub mod packet;
|
pub mod packet;
|
||||||
|
|
||||||
@@ -18,29 +29,43 @@ pub const ENCRYPTION_PREFIX_LEN: usize = 12 + 4 + 16;
|
|||||||
pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
|
pub const MAX_FRAME_BYTES: usize = 4 * 1024 * 1024;
|
||||||
/// Maximum frames being assembled at once; older ones are declared lost.
|
/// Maximum frames being assembled at once; older ones are declared lost.
|
||||||
pub const MAX_FRAMES_IN_FLIGHT: usize = 8;
|
pub const MAX_FRAMES_IN_FLIGHT: usize = 8;
|
||||||
|
/// Packets for frames further than this ahead of the next expected frame are dropped.
|
||||||
|
pub const MAX_FRAMES_AHEAD: u32 = 1024;
|
||||||
|
/// Finished frames remembered, so their late parity packets are not counted as drops but replays are.
|
||||||
|
const RECENT_FRAMES: usize = 32;
|
||||||
|
|
||||||
/// AES-128-GCM for encrypted video packets (`docs/PROTOCOL.md` 7). `Debug` never prints the key.
|
/// AES-128-GCM for encrypted video packets (`docs/PROTOCOL.md` 7). `Debug` never prints the key.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct VideoCipher {
|
pub struct VideoCipher {
|
||||||
key: [u8; 16],
|
key: zeroize::Zeroizing<[u8; 16]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl VideoCipher {
|
impl VideoCipher {
|
||||||
/// A cipher for `rikey`.
|
/// A cipher for `rikey`.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub const fn new(rikey: [u8; 16]) -> Self {
|
pub fn new(rikey: [u8; 16]) -> Self {
|
||||||
Self { key: rikey }
|
Self { key: zeroize::Zeroizing::new(rikey) }
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decrypts one encrypted packet (`IV ‖ frame number ‖ tag ‖ ciphertext`) into the plaintext packet.
|
/// Decrypts one encrypted packet (`IV ‖ frame number ‖ tag ‖ ciphertext`) into the plaintext packet.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under the
|
/// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`], [`Error::Truncated`] under the prefix,
|
||||||
/// prefix, [`crate::Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`crate::Error::Crypto`] for a bad
|
/// [`Error::Malformed`] for an IV whose byte 11 is not `'V'`, [`Error::Crypto`] for a bad tag.
|
||||||
/// tag. Phase A: always [`crate::Error::Unimplemented`].
|
|
||||||
pub fn decrypt(&self, packet: &[u8]) -> Result<Vec<u8>> {
|
pub fn decrypt(&self, packet: &[u8]) -> Result<Vec<u8>> {
|
||||||
let _ = (packet, &self.key);
|
const W: &str = "encrypted video packet";
|
||||||
Err(crate::Error::Unimplemented)
|
cap(W, packet::MAX_VIDEO_PACKET_BYTES, packet.len())?;
|
||||||
|
need(W, ENCRYPTION_PREFIX_LEN, packet.len())?;
|
||||||
|
let iv = array::<12>(W, packet, 0)?;
|
||||||
|
if iv.get(11) != Some(&b'V') {
|
||||||
|
return Err(malformed("video IV byte 11 is not 'V'"));
|
||||||
|
}
|
||||||
|
let tag = array::<16>(W, packet, 16)?;
|
||||||
|
let mut body = packet.get(ENCRYPTION_PREFIX_LEN..).unwrap_or(&[]).to_vec();
|
||||||
|
Aes128Gcm::new((&*self.key).into())
|
||||||
|
.decrypt_inout_detached(&iv.into(), b"", body.as_mut_slice().into(), &tag.into())
|
||||||
|
.map_err(|_| Error::Crypto)?;
|
||||||
|
Ok(body)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,7 +83,7 @@ pub struct VideoConfig {
|
|||||||
/// Decrypt packets with this cipher when video encryption was negotiated.
|
/// Decrypt packets with this cipher when video encryption was negotiated.
|
||||||
pub cipher: Option<VideoCipher>,
|
pub cipher: Option<VideoCipher>,
|
||||||
/// How long to wait for missing shards of a frame before declaring it lost.
|
/// How long to wait for missing shards of a frame before declaring it lost.
|
||||||
pub frame_timeout: core::time::Duration,
|
pub frame_timeout: Duration,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// One complete frame for the decoder.
|
/// One complete frame for the decoder.
|
||||||
@@ -109,9 +134,34 @@ pub struct VideoStats {
|
|||||||
pub frames_lost: u64,
|
pub frames_lost: u64,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Block {
|
||||||
|
data_shards: u16,
|
||||||
|
parity_shards: u16,
|
||||||
|
fec_percentage: u8,
|
||||||
|
shards: BTreeMap<u16, Vec<u8>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct Pending {
|
||||||
|
first_packet_at: Instant,
|
||||||
|
rtp_timestamp: u32,
|
||||||
|
last_block: u8,
|
||||||
|
blocks: [Option<Block>; packet::MAX_FEC_BLOCKS],
|
||||||
|
/// Every shard seen, by (block, shard index).
|
||||||
|
seen: BTreeSet<(u8, u16)>,
|
||||||
|
complete: Option<VideoFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
/// The video receiver.
|
/// The video receiver.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct VideoDepacketizer {
|
pub struct VideoDepacketizer {
|
||||||
|
config: VideoConfig,
|
||||||
|
payload_len: usize,
|
||||||
|
next_frame: Option<u32>,
|
||||||
|
frames: HashMap<u32, Pending>,
|
||||||
|
recent: VecDeque<(u32, BTreeSet<(u8, u16)>)>,
|
||||||
|
events: VecDeque<VideoEvent>,
|
||||||
stats: VideoStats,
|
stats: VideoStats,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -119,42 +169,227 @@ impl VideoDepacketizer {
|
|||||||
/// A receiver for one stream.
|
/// A receiver for one stream.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Malformed`] for a `packet_size` below the NV header size or above what fits in
|
/// [`Error::Malformed`] for a `packet_size` not above the NV header size or above what fits in
|
||||||
/// [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`packet::MAX_VIDEO_PACKET_BYTES`].
|
||||||
pub fn new(config: VideoConfig) -> Result<Self> {
|
pub fn new(config: VideoConfig) -> Result<Self> {
|
||||||
let _ = config;
|
let size = usize::from(config.packet_size);
|
||||||
Err(crate::Error::Unimplemented)
|
if size <= packet::NV_HEADER_LEN || size + packet::VIDEO_RTP_LEN > packet::MAX_VIDEO_PACKET_BYTES {
|
||||||
|
return Err(malformed("video packet_size"));
|
||||||
|
}
|
||||||
|
Ok(Self {
|
||||||
|
payload_len: size - packet::NV_HEADER_LEN,
|
||||||
|
config,
|
||||||
|
next_frame: None,
|
||||||
|
frames: HashMap::new(),
|
||||||
|
recent: VecDeque::new(),
|
||||||
|
events: VecDeque::new(),
|
||||||
|
stats: VideoStats::default(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn drop_packet(&mut self) -> Result<()> {
|
||||||
|
self.stats.packets_dropped += 1;
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Feeds one datagram from the video port. Bad, duplicate and too-old packets are counted and dropped; only
|
/// Feeds one datagram from the video port. Bad, duplicate and too-old packets are counted and dropped; only
|
||||||
/// an oversized datagram is an error.
|
/// an oversized datagram is an error.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`]. Phase A: always
|
/// [`Error::TooLarge`] over [`packet::MAX_VIDEO_PACKET_BYTES`].
|
||||||
/// [`crate::Error::Unimplemented`].
|
|
||||||
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
pub fn push(&mut self, now: Instant, datagram: &[u8]) -> Result<()> {
|
||||||
let _ = (now, datagram);
|
cap("video datagram", packet::MAX_VIDEO_PACKET_BYTES, datagram.len())?;
|
||||||
Err(crate::Error::Unimplemented)
|
let plain;
|
||||||
|
let bytes = match &self.config.cipher {
|
||||||
|
Some(c) => match c.decrypt(datagram) {
|
||||||
|
Ok(p) => {
|
||||||
|
plain = p;
|
||||||
|
plain.as_slice()
|
||||||
|
}
|
||||||
|
Err(_) => return self.drop_packet(),
|
||||||
|
},
|
||||||
|
None => datagram,
|
||||||
|
};
|
||||||
|
let Ok(p) = parse_video_packet(bytes) else { return self.drop_packet() };
|
||||||
|
if p.payload.len() != self.payload_len {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
let frame = p.nv.frame_index;
|
||||||
|
let next = *self.next_frame.get_or_insert(frame);
|
||||||
|
let ahead = frame.wrapping_sub(next);
|
||||||
|
let shard = (p.nv.fec.block_index, p.nv.fec.shard_index);
|
||||||
|
if ahead >= 1 << 31 {
|
||||||
|
// Before the next frame: late parity of a finished frame is fine, anything seen before is a replay.
|
||||||
|
let late = self.recent.iter_mut().find(|(f, _)| *f == frame).is_some_and(|(_, seen)| seen.insert(shard));
|
||||||
|
if late {
|
||||||
|
self.stats.packets += 1;
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
if ahead >= MAX_FRAMES_AHEAD {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
if !self.frames.contains_key(&frame) {
|
||||||
|
while self.frames.len() >= MAX_FRAMES_IN_FLIGHT {
|
||||||
|
self.give_up_head(now);
|
||||||
|
}
|
||||||
|
if self.next_frame.is_some_and(|n| frame.wrapping_sub(n) >= 1 << 31) {
|
||||||
|
// The forced advance passed this frame.
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
self.frames.insert(
|
||||||
|
frame,
|
||||||
|
Pending {
|
||||||
|
first_packet_at: now,
|
||||||
|
rtp_timestamp: p.rtp.timestamp,
|
||||||
|
last_block: p.nv.fec.last_block_index,
|
||||||
|
blocks: [None, None, None, None],
|
||||||
|
seen: BTreeSet::new(),
|
||||||
|
complete: None,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let accepted = self.store(frame, &p, now);
|
||||||
|
if !accepted {
|
||||||
|
return self.drop_packet();
|
||||||
|
}
|
||||||
|
self.stats.packets += 1;
|
||||||
|
self.advance(now);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Stores one packet in its frame; false for a duplicate or a packet that contradicts the frame's FEC layout.
|
||||||
|
fn store(&mut self, frame: u32, p: &VideoPacket<'_>, now: Instant) -> bool {
|
||||||
|
let payload_len = self.payload_len;
|
||||||
|
let Some(f) = self.frames.get_mut(&frame) else { return false };
|
||||||
|
let fec = p.nv.fec;
|
||||||
|
if fec.last_block_index != f.last_block || !f.seen.insert((fec.block_index, fec.shard_index)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
if f.complete.is_some() {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let Some(slot) = f.blocks.get_mut(usize::from(fec.block_index)) else { return false };
|
||||||
|
let block = slot.get_or_insert_with(|| Block {
|
||||||
|
data_shards: fec.data_shards,
|
||||||
|
parity_shards: crate::fec::parity_count(usize::from(fec.data_shards), fec.fec_percentage)
|
||||||
|
.ok()
|
||||||
|
.and_then(|m| u16::try_from(m).ok())
|
||||||
|
.unwrap_or(0),
|
||||||
|
fec_percentage: fec.fec_percentage,
|
||||||
|
shards: BTreeMap::new(),
|
||||||
|
});
|
||||||
|
if block.data_shards != fec.data_shards || block.fec_percentage != fec.fec_percentage {
|
||||||
|
f.seen.remove(&(fec.block_index, fec.shard_index));
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
block.shards.insert(fec.shard_index, p.payload.to_vec());
|
||||||
|
let complete = (0..=usize::from(f.last_block)).all(|b| {
|
||||||
|
f.blocks.get(b).and_then(Option::as_ref).is_some_and(|blk| blk.shards.len() >= usize::from(blk.data_shards))
|
||||||
|
});
|
||||||
|
if complete {
|
||||||
|
match assemble(f, frame, payload_len, now) {
|
||||||
|
Some((v, recovered)) => {
|
||||||
|
self.stats.shards_recovered += u64::from(recovered);
|
||||||
|
f.complete = Some(v);
|
||||||
|
for b in &mut f.blocks {
|
||||||
|
*b = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None => {
|
||||||
|
// Rebuilt but unusable: it can never complete; the timeout reports it lost.
|
||||||
|
for b in &mut f.blocks {
|
||||||
|
*b = None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lose(&mut self, first: u32, last: u32) {
|
||||||
|
self.events.push_back(VideoEvent::FrameLost { first, last });
|
||||||
|
let span = last.wrapping_sub(first);
|
||||||
|
self.stats.frames_lost += u64::from(span) + 1;
|
||||||
|
self.frames.retain(|&f, _| f.wrapping_sub(first) > span);
|
||||||
|
self.next_frame = Some(last.wrapping_add(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn deliver(&mut self, frame: u32) {
|
||||||
|
if let Some(mut f) = self.frames.remove(&frame) {
|
||||||
|
if let Some(v) = f.complete.take() {
|
||||||
|
self.events.push_back(VideoEvent::Frame(v));
|
||||||
|
self.stats.frames += 1;
|
||||||
|
}
|
||||||
|
if self.recent.len() >= RECENT_FRAMES {
|
||||||
|
self.recent.pop_front();
|
||||||
|
}
|
||||||
|
self.recent.push_back((frame, core::mem::take(&mut f.seen)));
|
||||||
|
}
|
||||||
|
self.next_frame = Some(frame.wrapping_add(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pending frame closest after `next`, as (frame index, distance).
|
||||||
|
fn lowest_pending(&self, next: u32) -> Option<(u32, u32)> {
|
||||||
|
self.frames.keys().map(|&f| (f, f.wrapping_sub(next))).min_by_key(|&(_, d)| d)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Delivers or gives up frames at the head while it is complete or has timed out.
|
||||||
|
fn advance(&mut self, now: Instant) {
|
||||||
|
let timeout = self.config.frame_timeout;
|
||||||
|
while let Some(next) = self.next_frame {
|
||||||
|
match self.frames.get(&next) {
|
||||||
|
Some(f) if f.complete.is_some() => self.deliver(next),
|
||||||
|
Some(f) if f.first_packet_at.saturating_add(timeout) <= now => self.lose(next, next),
|
||||||
|
Some(_) => return,
|
||||||
|
None => {
|
||||||
|
let Some((lowest, _)) = self.lowest_pending(next) else { return };
|
||||||
|
let expired =
|
||||||
|
self.frames.get(&lowest).is_some_and(|f| f.first_packet_at.saturating_add(timeout) <= now);
|
||||||
|
if !expired {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.lose(next, lowest.wrapping_sub(1));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Frees one slot: delivers the head if complete, else declares it (or the gap before the oldest frame) lost.
|
||||||
|
fn give_up_head(&mut self, now: Instant) {
|
||||||
|
let Some(next) = self.next_frame else { return };
|
||||||
|
match self.frames.get(&next) {
|
||||||
|
Some(f) if f.complete.is_some() => self.deliver(next),
|
||||||
|
Some(_) => self.lose(next, next),
|
||||||
|
None => match self.lowest_pending(next) {
|
||||||
|
Some((lowest, _)) => self.lose(next, lowest.wrapping_sub(1)),
|
||||||
|
None => return,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
self.advance(now);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The next event.
|
/// The next event.
|
||||||
pub fn poll_event(&mut self) -> Option<VideoEvent> {
|
pub fn poll_event(&mut self) -> Option<VideoEvent> {
|
||||||
None
|
self.events.pop_front()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// When an incomplete frame times out.
|
/// When an incomplete frame times out.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn poll_timeout(&self) -> Option<Instant> {
|
pub fn poll_timeout(&self) -> Option<Instant> {
|
||||||
None
|
let next = self.next_frame?;
|
||||||
|
let head = self.frames.get(&next).map(|_| next).or_else(|| self.lowest_pending(next).map(|(f, _)| f))?;
|
||||||
|
self.frames.get(&head).map(|f| f.first_packet_at.saturating_add(self.config.frame_timeout))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Declares timed-out frames lost.
|
/// Declares timed-out frames lost.
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// Phase A: always [`crate::Error::Unimplemented`].
|
/// None today.
|
||||||
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
pub fn handle_timeout(&mut self, now: Instant) -> Result<()> {
|
||||||
let _ = now;
|
self.advance(now);
|
||||||
Err(crate::Error::Unimplemented)
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Counters.
|
/// Counters.
|
||||||
@@ -163,3 +398,59 @@ impl VideoDepacketizer {
|
|||||||
self.stats
|
self.stats
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Builds the frame of a pending entry whose every block has enough shards: rebuilds missing data shards, joins the
|
||||||
|
/// data in block order and trims the frame header and padding. `None` when the result is unusable.
|
||||||
|
fn assemble(f: &Pending, frame_index: u32, payload_len: usize, now: Instant) -> Option<(VideoFrame, u16)> {
|
||||||
|
let mut data: Vec<u8> = Vec::new();
|
||||||
|
let mut recovered: u16 = 0;
|
||||||
|
let mut shards_total = 0usize;
|
||||||
|
for b in 0..=usize::from(f.last_block) {
|
||||||
|
let block = f.blocks.get(b)?.as_ref()?;
|
||||||
|
let k = usize::from(block.data_shards);
|
||||||
|
let m = usize::from(block.parity_shards);
|
||||||
|
shards_total += k;
|
||||||
|
if data.len().saturating_add(k * payload_len) > MAX_FRAME_BYTES + payload_len {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let missing = (0..block.data_shards).filter(|i| !block.shards.contains_key(i)).count();
|
||||||
|
if missing == 0 {
|
||||||
|
for i in 0..block.data_shards {
|
||||||
|
data.extend_from_slice(block.shards.get(&i)?);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let code = ReedSolomon::new(k, m).ok()?;
|
||||||
|
let mut shards: Vec<Option<Vec<u8>>> =
|
||||||
|
(0..k + m).map(|i| u16::try_from(i).ok().and_then(|i| block.shards.get(&i).cloned())).collect();
|
||||||
|
code.reconstruct(&mut shards).ok()?;
|
||||||
|
for s in shards.iter().take(k) {
|
||||||
|
data.extend_from_slice(s.as_ref()?);
|
||||||
|
}
|
||||||
|
recovered = recovered.saturating_add(u16::try_from(missing).unwrap_or(u16::MAX));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let header = packet::parse_frame_header(&data).ok()?;
|
||||||
|
let last = usize::try_from(header.last_payload_len).unwrap_or(0);
|
||||||
|
let end = if (1..=payload_len).contains(&last) && shards_total >= 1 {
|
||||||
|
(shards_total - 1) * payload_len + last
|
||||||
|
} else {
|
||||||
|
// The header does not say where the frame ends (Wolf's constant, U13): trim the zero padding.
|
||||||
|
data.iter().rposition(|&b| b != 0).map_or(0, |p| p + 1)
|
||||||
|
};
|
||||||
|
let bitstream = data.get(packet::FRAME_HEADER_LEN..end)?.to_vec();
|
||||||
|
if bitstream.len() > MAX_FRAME_BYTES {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
Some((
|
||||||
|
VideoFrame {
|
||||||
|
frame_index,
|
||||||
|
header,
|
||||||
|
bitstream,
|
||||||
|
rtp_timestamp: f.rtp_timestamp,
|
||||||
|
first_packet_at: f.first_packet_at,
|
||||||
|
completed_at: now,
|
||||||
|
recovered_shards: recovered,
|
||||||
|
},
|
||||||
|
recovered,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|||||||
@@ -72,16 +72,46 @@ pub struct VideoPacket<'a> {
|
|||||||
pub payload: &'a [u8],
|
pub payload: &'a [u8],
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Parses one plaintext video packet. Checks the FEC fields are consistent (`shard_index < data + parity`,
|
/// Parses one plaintext video packet. Checks the FEC fields are consistent (`data_shards > 0`, data + parity
|
||||||
/// `block_index <= last_block_index`, `data_shards > 0`).
|
/// `<= 255` with parity `= ceil(data × percentage / 100)`, `shard_index < data + parity`,
|
||||||
|
/// `block_index <= last_block_index`).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::TooLarge`] over [`MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under
|
/// [`crate::Error::TooLarge`] over [`MAX_VIDEO_PACKET_BYTES`], [`crate::Error::Truncated`] under
|
||||||
/// [`PAYLOAD_OFFSET`], [`crate::Error::Malformed`] for inconsistent FEC fields. Phase A: always
|
/// [`PAYLOAD_OFFSET`], [`crate::Error::UnexpectedValue`] for an RTP version other than 2,
|
||||||
/// [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Malformed`] for inconsistent FEC fields.
|
||||||
pub fn parse_video_packet(packet: &[u8]) -> crate::Result<VideoPacket<'_>> {
|
pub fn parse_video_packet(packet: &[u8]) -> crate::Result<VideoPacket<'_>> {
|
||||||
let _ = packet;
|
use crate::util::{byte, malformed, u32_le};
|
||||||
Err(crate::Error::Unimplemented)
|
const W: &str = "video packet";
|
||||||
|
crate::util::cap(W, MAX_VIDEO_PACKET_BYTES, packet.len())?;
|
||||||
|
crate::util::need(W, PAYLOAD_OFFSET, packet.len())?;
|
||||||
|
let rtp = crate::rtp::parse_rtp_header(packet)?;
|
||||||
|
let nv = VIDEO_RTP_LEN;
|
||||||
|
let fec_info = u32_le(W, packet, nv + 12)?;
|
||||||
|
let blocks = byte(W, packet, nv + 11)?;
|
||||||
|
let fec = FecInfo {
|
||||||
|
shard_index: ((fec_info >> 12) & 0x3FF) as u16,
|
||||||
|
data_shards: ((fec_info >> 22) & 0x3FF) as u16,
|
||||||
|
fec_percentage: ((fec_info >> 4) & 0xFF) as u8,
|
||||||
|
block_index: (blocks >> 4) & 0x3,
|
||||||
|
last_block_index: (blocks >> 6) & 0x3,
|
||||||
|
};
|
||||||
|
let parity = crate::fec::parity_count(usize::from(fec.data_shards), fec.fec_percentage)
|
||||||
|
.map_err(|_| malformed("video fec shard counts"))?;
|
||||||
|
if usize::from(fec.shard_index) >= usize::from(fec.data_shards) + parity || fec.block_index > fec.last_block_index {
|
||||||
|
return Err(malformed("video fec fields"));
|
||||||
|
}
|
||||||
|
Ok(VideoPacket {
|
||||||
|
rtp,
|
||||||
|
nv: NvVideoHeader {
|
||||||
|
stream_packet_index: u32_le(W, packet, nv)?,
|
||||||
|
frame_index: u32_le(W, packet, nv + 4)?,
|
||||||
|
flags: VideoFlags(byte(W, packet, nv + 8)?),
|
||||||
|
multi_fec_flags: byte(W, packet, nv + 10)?,
|
||||||
|
fec,
|
||||||
|
},
|
||||||
|
payload: packet.get(PAYLOAD_OFFSET..).unwrap_or(&[]),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Frame types in the frame header.
|
/// Frame types in the frame header.
|
||||||
@@ -116,8 +146,22 @@ pub struct FrameHeader {
|
|||||||
/// Parses the frame header at the start of a frame's data (the rest is ignored here).
|
/// Parses the frame header at the start of a frame's data (the rest is ignored here).
|
||||||
///
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
/// [`crate::Error::Truncated`] under [`FRAME_HEADER_LEN`]. Phase A: always [`crate::Error::Unimplemented`].
|
/// [`crate::Error::Truncated`] under [`FRAME_HEADER_LEN`].
|
||||||
pub fn parse_frame_header(frame_data: &[u8]) -> crate::Result<FrameHeader> {
|
pub fn parse_frame_header(frame_data: &[u8]) -> crate::Result<FrameHeader> {
|
||||||
let _ = frame_data;
|
const W: &str = "video frame header";
|
||||||
Err(crate::Error::Unimplemented)
|
let raw = crate::util::array::<FRAME_HEADER_LEN>(W, frame_data, 0)?;
|
||||||
|
let [header_type, l0, l1, kind, a, b, c, d] = raw;
|
||||||
|
let frame_type = match kind {
|
||||||
|
1 => FrameType::Predicted,
|
||||||
|
2 => FrameType::Key,
|
||||||
|
5 => FrameType::Recovery,
|
||||||
|
other => FrameType::Other(other),
|
||||||
|
};
|
||||||
|
Ok(FrameHeader {
|
||||||
|
raw,
|
||||||
|
header_type,
|
||||||
|
processing_latency: u16::from_le_bytes([l0, l1]),
|
||||||
|
frame_type,
|
||||||
|
last_payload_len: u32::from_le_bytes([a, b, c, d]),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -166,13 +166,15 @@ fn xml_depth_bomb_does_not_recurse() {
|
|||||||
s.push_str(&"<a>".repeat(300_000));
|
s.push_str(&"<a>".repeat(300_000));
|
||||||
assert!(s.len() < MAX_XML_BYTES);
|
assert!(s.len() < MAX_XML_BYTES);
|
||||||
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
|
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
|
||||||
// Same with the closing tags present.
|
// A closed, well-formed bomb that fits under the size cap (100 000 opens + 100 000 closes, about 0.7 MB): still
|
||||||
s.push_str(&"</a>".repeat(300_000));
|
// refused at depth 9, never parsed by recursion. (The earlier 300 000-pair version was 2.1 MB, over the size
|
||||||
s.push_str("</root>");
|
// cap, so its depth check never ran: ruled wrong 2026-11-26.)
|
||||||
assert!(s.len() < MAX_XML_BYTES * 2);
|
let mut closed = String::from("<root status_code=\"200\">");
|
||||||
if s.len() <= MAX_XML_BYTES {
|
closed.push_str(&"<a>".repeat(100_000));
|
||||||
assert_cap!(xml::parse(s.as_bytes()), MAX_XML_DEPTH);
|
closed.push_str(&"</a>".repeat(100_000));
|
||||||
}
|
closed.push_str("</root>");
|
||||||
|
assert!(closed.len() <= MAX_XML_BYTES, "{} bytes must fit the size cap", closed.len());
|
||||||
|
assert_cap!(xml::parse(closed.as_bytes()), MAX_XML_DEPTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
+16
-6
@@ -12,16 +12,20 @@ GPL-licensed implementation. This file says what may be read, what may not, and
|
|||||||
| [Moonshine](https://github.com/hgaiser/moonshine) | BSD-2-Clause | May be read. Facts taken are logged below. Code is not copied; if a snippet is ever borrowed, it keeps Moonshine's copyright line and licence text in the file that holds it. |
|
| [Moonshine](https://github.com/hgaiser/moonshine) | BSD-2-Clause | May be read. Facts taken are logged below. Code is not copied; if a snippet is ever borrowed, it keeps Moonshine's copyright line and licence text in the file that holds it. |
|
||||||
| RFCs and standards (RTP RFC 3550, RTSP RFC 2326, SDP RFC 4566, Opus RFC 6716 / RFC 7845, AES FIPS 197, GCM/CBC NIST SP 800-38D/38A, PKCS #1 RFC 8017, X.509 RFC 5280) | open standards | Read freely. |
|
| RFCs and standards (RTP RFC 3550, RTSP RFC 2326, SDP RFC 4566, Opus RFC 6716 / RFC 7845, AES FIPS 197, GCM/CBC NIST SP 800-38D/38A, PKCS #1 RFC 8017, X.509 RFC 5280) | open standards | Read freely. |
|
||||||
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
|
| Crate docs (docs.rs, crates.io, crate READMEs) | per crate | Read freely. |
|
||||||
| Our own measurements | ours | Captures between our client and a host on a **lab machine** (never Mark's PC, never Mark's TV, never 192.168.100.217). Captures stay out of git; only the facts and test vectors derived from them go in, with the date and setup. |
|
| Our own measurements | ours | Captures through our own relay ([tools/lab-relay](../tools/lab-relay)). Mark allowed **one** capture on his PC (answer 16, 2026-11-25), done exactly as [LAB_CAPTURE.md](LAB_CAPTURE.md) says; never his TV, never 192.168.100.217. Recordings stay local (on E:, approved for Play remotely) under `E:\build\play-remotely\lab\`, out of git; only facts and test vectors derived from them go in, with the date and setup. |
|
||||||
|
| Official Sunshine and Moonlight PC **binaries** in that capture | GPL-3.0 (we only run them) | Black-box peers: run, observe their traffic, their `--help` output, their own logs and the files/registry keys they write. Never open their source, never disassemble or decompile them. |
|
||||||
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
|
| READMEs and wikis of forbidden projects | n/a | For facts only (licence, release notes, compatibility statements). Never their source files. |
|
||||||
|
|
||||||
### Proposed additions (need the build lead's yes before use)
|
### Approved by Mark (answer 15, 2026-11-25): "Yes, with attribution"
|
||||||
|
|
||||||
|
Read for the wire format; anything borrowed beyond a fact is attributed in the file that holds it. GPL stays off
|
||||||
|
limits, and a value with GPL provenance stays out even when one of these sources carries it.
|
||||||
|
|
||||||
| Source | Licence | Why |
|
| Source | Licence | Why |
|
||||||
| :-- | :-- | :-- |
|
| :-- | :-- | :-- |
|
||||||
| [Stock ENet](https://github.com/lsalzman/enet) (`protocol.h`, `protocol.c`) | MIT | The ENet 1.3 wire format is not documented anywhere else in prose. The Wolf docs do not describe it. |
|
| [Stock ENet](https://github.com/lsalzman/enet) | MIT | The ENet 1.3 wire format is documented nowhere else. Read at v1.3.18 (S-17). |
|
||||||
| [tokio-enet](https://github.com/hgaiser/tokio-enet) source | BSD-2-Clause | A pure-Rust ENet 1.3 used by Moonshine to talk to Moonlight clients. Its `src/protocol/` files were read for the command list (logged below, S-10). |
|
| [tokio-enet](https://github.com/hgaiser/tokio-enet) | BSD-2-Clause | Pure-Rust ENet 1.3 that Moonshine uses with Moonlight clients (S-10, now approved). |
|
||||||
| [fec-rs](https://github.com/hgaiser/fec-rs) source | BSD-2-Clause | Its README says its field setup is compatible with Moonlight. Reading its matrix construction would settle UNKNOWN U14 (video FEC). |
|
| [fec-rs](https://github.com/hgaiser/fec-rs) | BSD-2-Clause | Reed-Solomon whose README claims Moonlight compatibility; its matrix construction settles U14 (S-18). |
|
||||||
|
|
||||||
## Forbidden
|
## Forbidden
|
||||||
|
|
||||||
@@ -39,6 +43,7 @@ copied into DomiStream, and settled by our own measurement instead. Known cases:
|
|||||||
| :-- | :-- | :-- |
|
| :-- | :-- | :-- |
|
||||||
| `src/session/stream/audio/encoder.rs` | the fixed 2x4 Reed-Solomon parity matrix for audio FEC; the comment cites a moonlight-common-c file | Not taken. I saw the constant while reading the file; it is not in this repo. U16 in [PROTOCOL.md](PROTOCOL.md) says how to measure it ourselves. |
|
| `src/session/stream/audio/encoder.rs` | the fixed 2x4 Reed-Solomon parity matrix for audio FEC; the comment cites a moonlight-common-c file | Not taken. I saw the constant while reading the file; it is not in this repo. U16 in [PROTOCOL.md](PROTOCOL.md) says how to measure it ourselves. |
|
||||||
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
|
| `src/session/stream/control/mod.rs` | HDR mode payload "matches Sunshine's" struct | Field layout logged as `[M*]`, confirm by measurement before relying on it |
|
||||||
|
| fec-rs `src/reed_solomon.rs` tests (`test_partial_eq_reflects_parity_matrix_changes`) | the same audio parity matrix as Moonshine's encoder | Not taken, same rule. Seen while reading fec-rs on 2026-11-25. |
|
||||||
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
|
| `src/rtsp.rs` | `surround-params` digit packing "matching moonlight-common-c" | The Wolf example `surround-params=21101` gives the same packing independently, so we use the Wolf source |
|
||||||
|
|
||||||
## How code gets written
|
## How code gets written
|
||||||
@@ -64,10 +69,15 @@ All entries by the DomiStream protocol engineer. Pinned commits are the ones rea
|
|||||||
| S-7 | 2026-11-25 | [Wolf: input](https://games-on-whales.github.io/wolf/stable/protocols/input-data.html) incl. bytefield sources | INPUT_DATA layout (size BE, type LE); input type codes; layouts and example bytes for mouse move rel/abs, buttons, keys, scroll, hscroll, controller arrival, controller multi; key code table; button flags; controller types and capability bits. |
|
| S-7 | 2026-11-25 | [Wolf: input](https://games-on-whales.github.io/wolf/stable/protocols/input-data.html) incl. bytefield sources | INPUT_DATA layout (size BE, type LE); input type codes; layouts and example bytes for mouse move rel/abs, buttons, keys, scroll, hscroll, controller arrival, controller multi; key code table; button flags; controller types and capability bits. |
|
||||||
| S-8 | 2026-11-25 | GitHub API for [games-on-whales/wolf](https://github.com/games-on-whales/wolf) (`/repos`, `/git/trees/beta`, `LICENSE`, `docs/README.adoc`) | Repo licence MIT; the docs live in `docs/modules/protocols/pages/*.adoc` of the same repo; latest tag `v2026.11`. No source files of Wolf were read. |
|
| S-8 | 2026-11-25 | GitHub API for [games-on-whales/wolf](https://github.com/games-on-whales/wolf) (`/repos`, `/git/trees/beta`, `LICENSE`, `docs/README.adoc`) | Repo licence MIT; the docs live in `docs/modules/protocols/pages/*.adoc` of the same repo; latest tag `v2026.11`. No source files of Wolf were read. |
|
||||||
| S-9 | 2026-11-25 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc`: `LICENSE`, `README.md`, `Cargo.toml`, `src/clients.rs`, `src/crypto.rs`, `src/webserver/pairing.rs`, `src/webserver/mod.rs`, `src/rtsp.rs`, `src/session/stream/control/mod.rs`, `src/session/stream/audio/{mod,encoder}.rs`, `src/session/stream/video/{mod,packetizer,shard_batch}.rs` | Facts tagged `[M]` in PROTOCOL.md: pairing query names, AES-128-ECB, key = first 16 bytes of SHA-256(salt + PIN), 16-byte salt/challenge/secret, RSA PKCS#1 v1.5 SHA-256, "certificate signature" = X.509 signatureValue bytes; serverinfo, applist and launch XML and query fields; SDP attribute names, SETUP reply headers, encryption flag bits; control IV layout and direction bytes, START_B starts the streams, INVALIDATE_REF_FRAMES and termination layouts, ENet host settings; audio IV, payload types 97/127, millisecond timestamps; video RTP/NV header byte layout, FEC bit fields and block split, video encryption prefix and IV; `PING` payload. Moonshine depends on `tokio-enet` for the control channel. |
|
| S-9 | 2026-11-25 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e3693e09c3a6ab1025bde6cdb67f36a6bc`: `LICENSE`, `README.md`, `Cargo.toml`, `src/clients.rs`, `src/crypto.rs`, `src/webserver/pairing.rs`, `src/webserver/mod.rs`, `src/rtsp.rs`, `src/session/stream/control/mod.rs`, `src/session/stream/audio/{mod,encoder}.rs`, `src/session/stream/video/{mod,packetizer,shard_batch}.rs` | Facts tagged `[M]` in PROTOCOL.md: pairing query names, AES-128-ECB, key = first 16 bytes of SHA-256(salt + PIN), 16-byte salt/challenge/secret, RSA PKCS#1 v1.5 SHA-256, "certificate signature" = X.509 signatureValue bytes; serverinfo, applist and launch XML and query fields; SDP attribute names, SETUP reply headers, encryption flag bits; control IV layout and direction bytes, START_B starts the streams, INVALIDATE_REF_FRAMES and termination layouts, ENet host settings; audio IV, payload types 97/127, millisecond timestamps; video RTP/NV header byte layout, FEC bit fields and block split, video encryption prefix and IV; `PING` payload. Moonshine depends on `tokio-enet` for the control channel. |
|
||||||
| S-10 | 2026-11-25 | [tokio-enet](https://github.com/hgaiser/tokio-enet) at `364628ed754760c99e0df7bcc88e479ad91475c4`: `README.md`, `CHANGELOG.md`, `src/protocol/{mod,header,commands}.rs` | Claims wire compatibility with C ENet 1.3.x, BSD-2; ENet command numbers 1-12, command sizes, header flags (compressed 1<<14, sent time 1<<15, session bits 12-13), 4-byte command header, big-endian fields. Pending approval as an allowed source (see above). |
|
| S-10 | 2026-11-25 | [tokio-enet](https://github.com/hgaiser/tokio-enet) at `364628ed754760c99e0df7bcc88e479ad91475c4`: `README.md`, `CHANGELOG.md`, `src/protocol/{mod,header,commands}.rs` | Claims wire compatibility with C ENet 1.3.x, BSD-2; ENet command numbers 1-12, command sizes, header flags (compressed 1<<14, sent time 1<<15, session bits 12-13), 4-byte command header, big-endian fields. **Approved** (Mark, 2026-11-25, answer 15). |
|
||||||
| S-11 | 2026-11-25 | crates.io API for `enet`, `enet-rs`, `nsys-enet`, `rusty_enet`, `tokio-enet`, `enet-sys`, `henet`, `enet-cs-sys`, `fec-rs`, `reed-solomon-erasure` and the RustCrypto crates | Licences, versions, repositories (see research/open-point-2.md and the Cargo manifest). |
|
| S-11 | 2026-11-25 | crates.io API for `enet`, `enet-rs`, `nsys-enet`, `rusty_enet`, `tokio-enet`, `enet-sys`, `henet`, `enet-cs-sys`, `fec-rs`, `reed-solomon-erasure` and the RustCrypto crates | Licences, versions, repositories (see research/open-point-2.md and the Cargo manifest). |
|
||||||
| S-12 | 2026-11-25 | [docs.rs: rusty_enet](https://docs.rs/rusty_enet/latest/rusty_enet/) | Transpiled from C ENet; caller-supplied `Socket` trait and `HostSettings::time`; optional crc32 checksum; MIT. |
|
| S-12 | 2026-11-25 | [docs.rs: rusty_enet](https://docs.rs/rusty_enet/latest/rusty_enet/) | Transpiled from C ENet; caller-supplied `Socket` trait and `HostSettings::time`; optional crc32 checksum; MIT. |
|
||||||
| S-13 | 2026-11-25 | [fec-rs README](https://github.com/hgaiser/fec-rs) | GF(2^8) with polynomial 0x1D (0x11D), "compatible with the Moonlight streaming protocol", reconstruction supported, BSD-2. |
|
| S-13 | 2026-11-25 | [fec-rs README](https://github.com/hgaiser/fec-rs) | GF(2^8) with polynomial 0x1D (0x11D), "compatible with the Moonlight streaming protocol", reconstruction supported, BSD-2. |
|
||||||
| S-14 | 2026-11-25 | [moonlight-common-c README](https://github.com/moonlight-stream/moonlight-common-c) (README only) | Needs its bundled ENet; other ENet versions are incompatible; GPL-3.0. |
|
| S-14 | 2026-11-25 | [moonlight-common-c README](https://github.com/moonlight-stream/moonlight-common-c) (README only) | Needs its bundled ENet; other ENet versions are incompatible; GPL-3.0. |
|
||||||
| S-15 | 2026-11-25 | [cgutman/enet](https://github.com/cgutman/enet) repository page (description only) | Forked from lsalzman/enet, has a `moonlight` branch. No files opened. |
|
| S-15 | 2026-11-25 | [cgutman/enet](https://github.com/cgutman/enet) repository page (description only) | Forked from lsalzman/enet, has a `moonlight` branch. No files opened. |
|
||||||
| S-16 | 2026-11-25 | Roadmap brief §3.2 ([moonlight-android releases](https://github.com/moonlight-stream/moonlight-android/releases)) | Moonlight Android 12.1 added end-to-end stream encryption with Sunshine. |
|
| S-16 | 2026-11-25 | Roadmap brief §3.2 ([moonlight-android releases](https://github.com/moonlight-stream/moonlight-android/releases)) | Moonlight Android 12.1 added end-to-end stream encryption with Sunshine. |
|
||||||
|
| S-17 | 2026-11-25 | [Stock ENet](https://github.com/lsalzman/enet) v1.3.18 (`2662c0d`): `LICENSE`, `include/enet/protocol.h`, `include/enet/enet.h` (constants and peer states), `host.c` (`enet_host_connect`), `peer.c` (default ping and timeout setters), `protocol.c` (header and checksum handling, connect/verify connect session ids, retransmission timeout) | MIT. Wire structs and sizes; header flags; checksum is an optional host setting (4 bytes after the header, no flag on the wire, seeded with the connect id); connect sends session ids 0xFF and channel 0xFF; defaults: MTU 1392, ping interval 500 ms, timeout limit 32 / minimum 5000 ms / maximum 30000 ms, window 4096-65536 derived from bandwidth. |
|
||||||
|
| S-18 | 2026-11-25 | [fec-rs](https://github.com/hgaiser/fec-rs) at `402f41f970bb8c3ef7c88639821032e3b6460f63`: `LICENSE`, `README.md`, `build.rs` (field tables), `src/galois.rs` (`exp`), `src/matrix.rs` (`vandermonde`), `src/reed_solomon.rs` (`build_matrix`, `new`) | BSD-2. Field GF(2^8) with polynomial 0x11D, generator 2; systematic code whose parity rows are the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)`. Its tests also contain the GPL-provenance audio matrix (not taken). |
|
||||||
|
| S-19 | 2026-11-25 | GitHub release API: [Moonlight PC v6.2.0](https://api.github.com/repos/moonlight-stream/moonlight-qt/releases/latest), [Sunshine v2026.914.233613](https://api.github.com/repos/SunshineStream/Sunshine/releases/tags/v2026.914.233613) | Asset names, sizes and sha256 digests for the lab capture pins. Release metadata only. |
|
||||||
|
| S-20 | 2026-11-25 | ArenaTV `docs/research/sunshine-api.md` and `docs/research/this-pc.md` (Domi's own research from LizardByte's docs) | Sunshine's API calls, `--creds`, `bind_address`, port offsets, first-run behaviour, this PC's adapters and old install. |
|
||||||
|
| S-21 | 2026-11-30 | [Moonshine](https://github.com/hgaiser/moonshine) at `f184d5e` (same pin as S-9): `src/session/stream/control/mod.rs` again (client message parsing and the control loop), `src/session/stream/mod.rs` (`StreamConfig`), `src/session/stream/video/mod.rs` (PING handling), `src/config.rs` (nothing relevant); the repository tree listing | BSD-2. U10, as facts only: the host reads **no body** from START_B (0x0307), Ping (0x0200), LOSS_STATS, FRAME_STATS or the IDR request; START_A (0x0305) is not a type it knows; inside the encrypted frame an unknown type or a failed decryption is skipped, outside it an unknown type or a bad length ends the session; INVALIDATE_REF_FRAMES `first`/`last` at message bytes 4..8 and 12..16 (LE), short bodies mean "from 0"; each Ping resets a stop deadline, `StreamConfig.timeout` default 60 s; the client-to-host IV is `seq LE ‖ 6 zero ‖ 'C' 'C'`; host messages go reliable on channel 0; the video receiver waits for START_B and takes exactly the 4 bytes `PING`, each PING updating the client address. No value in these parts cites Sunshine or moonlight-common-c (the HDR payload's Sunshine note is the known S-9 case). Used for the probe's default bodies (all empty) and the PROTOCOL.md 3.3 facts. |
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
# DomiStream — handover
|
||||||
|
|
||||||
|
## stream-v0.1.0 (2026-11-26)
|
||||||
|
|
||||||
|
The GameStream client, sans-I/O, for Arena Domi TV (Play remotely Day 1).
|
||||||
|
|
||||||
|
| Part | Module |
|
||||||
|
| :-- | :-- |
|
||||||
|
| pairing handshake (4-phase PIN exchange, client cert), serverinfo, app list, launch | `pairing`, `http` |
|
||||||
|
| RTSP client and framer, SDP | `rtsp` |
|
||||||
|
| ENet 1.3-compatible client peer | `enet` |
|
||||||
|
| control channel (AES-GCM, replay refusal), input and gamepad messages | `control`, `input` |
|
||||||
|
| RTP, Reed-Solomon FEC, video depacketizer (FEC recovery), Opus audio depacketizer (4 + 2 FEC) | `rtp`, `fec`, `video`, `audio` |
|
||||||
|
|
||||||
|
Evidence (worktree checks, 2026-11-26, every run gated on CPU, RAM and drives below 90 %):
|
||||||
|
- `cargo test --workspace`: **242 passed, 0 failed**. QA wrote the tests before the code; vectors come from OpenSSL
|
||||||
|
3.5, Python hashlib and .NET 10, with test-only keys.
|
||||||
|
- Mutation pass: **24 of 24 caught** (`docs/MUTATION.md`, rerunnable with `tools/mutation/mutate.py`).
|
||||||
|
- Fuzz: 25 targets × 60 s, **0 crashes**, from 59,665 (pairing_session) to 101 M (rtp_header) executions; then
|
||||||
|
pairing_session for 600 s: 574,761 runs, 0 crashes. Windows MSVC, SanitizerCoverage, libFuzzer (`fuzz/`).
|
||||||
|
- clippy `-D warnings`, fmt and rustdoc `-D warnings` are clean. `getrandom` is not in the dependency tree.
|
||||||
|
|
||||||
|
Open (see `docs/PROTOCOL.md` §UNKNOWN):
|
||||||
|
- **Interop unverified.** U1, U2, U4–U10 and U17 block a real stream; they are settled live on Play remotely Day 1
|
||||||
|
against the pinned Sunshine (Mark, 2026-11-25: "COntinue roadmap without the check"). Expect `stream-v0.1.x`.
|
||||||
|
- U16 (audio parity matrix: audio plays without it at zero loss) and U19 (video encryption layout).
|
||||||
|
- `tools/lab-relay` and its scripts were never run (`docs/LAB_CAPTURE.md`); they're kept for byte logs on Day 1.
|
||||||
|
- The live sitting is prepared: `tools/gs-probe` (a desktop probe client driving these state machines over real
|
||||||
|
sockets, built and unit-tested, never run against a host) and its run book `docs/LIVE-INTEROP.md`.
|
||||||
@@ -0,0 +1,271 @@
|
|||||||
|
# Lab capture: one GameStream session on Mark's PC
|
||||||
|
|
||||||
|
Status: **Not run.** Mark, 2026-11-25: "COntinue roadmap without the check". The relay and scripts are kept for byte
|
||||||
|
logs during Day 1's live interop work; the scripts install nothing unless Mark approves a new step. The blocking
|
||||||
|
UNKNOWNs are settled live on Day 1 against the Sunshine that arena-host installs (Arena ROADMAP-REMOTE.md open
|
||||||
|
point 14).
|
||||||
|
|
||||||
|
Goal: settle the UNKNOWNs U1-U29 in [PROTOCOL.md](PROTOCOL.md) section 8 by watching **one** desktop stream between
|
||||||
|
the official Moonlight PC client and the pinned Sunshine, both on this PC, through **our own** logging relay.
|
||||||
|
Moonlight and Sunshine are black-box peers: we run them and watch their traffic, their `--help`, their own logs and
|
||||||
|
the files they write. We never open their source, never disassemble them ([CLEAN_ROOM.md](CLEAN_ROOM.md)).
|
||||||
|
|
||||||
|
Hard limits:
|
||||||
|
- One stream of the **Desktop** app, no game. Nothing touches the TV or 192.168.100.217.
|
||||||
|
- Every listening socket is on loopback: Sunshine on `127.0.0.2`, the relay on `127.0.0.1`.
|
||||||
|
- Lab keys and credentials live only under `E:\build\play-remotely\lab\`, are never printed, never on a command line that
|
||||||
|
survives, never in git, and are deleted at the end.
|
||||||
|
- Recordings stay under `E:\build\play-remotely\lab\captures\`, out of git. Only derived facts and test vectors go into
|
||||||
|
the docs.
|
||||||
|
- One UAC prompt in total.
|
||||||
|
|
||||||
|
## 0. Layout
|
||||||
|
|
||||||
|
```
|
||||||
|
E:\build\play-remotely\lab\
|
||||||
|
downloads\ Sunshine MSI and the Moonlight portable zip, as downloaded (untrusted until the sha256 matches)
|
||||||
|
moonlight\ the extracted Moonlight portable folder
|
||||||
|
keys\ lab-only TLS material (ACL: Mark's account + SYSTEM): Sunshine lab cert/key, Moonlight lab cert/key
|
||||||
|
secrets\ Sunshine API credentials, DPAPI-protected for Mark's account (ConvertFrom-SecureString)
|
||||||
|
captures\ relay recordings (*.dslr), Sunshine's log copy, the msiexec log, our notes
|
||||||
|
```
|
||||||
|
|
||||||
|
Our scripts and the relay come from this repo (`tools/lab-relay/`) and run from it, never from `downloads\`.
|
||||||
|
Built and checked on 2026-11-25 (Windows MSVC, stable 1.99, `-j 2`): `cargo test` 28 passed, `cargo clippy
|
||||||
|
--all-targets -- -D warnings` and `cargo fmt --check` clean. The relay has **not been run** yet. The two scripts
|
||||||
|
(`tools/lab-relay/scripts/lab-install.ps1`, `lab-api.ps1`) have been parse-checked only, never run; the build lead
|
||||||
|
reads them before anything goes to Mark.
|
||||||
|
|
||||||
|
The lab root is on E: (approved for Play remotely). The relay is built in `E:uild\play-remotely\DomiStream-wt-lab`
|
||||||
|
with `TEMP`/`TMP` set to `E:uild\play-remotely mp`, `-j 2`, and only while CPU, RAM, D: and E: are all below
|
||||||
|
90 % (DomiStream CLAUDE.md).
|
||||||
|
|
||||||
|
## 1. Step (a): the old Sunshine is gone (read-only)
|
||||||
|
|
||||||
|
Mark has uninstalled it himself. We only check, changing nothing:
|
||||||
|
|
||||||
|
| Check | Command (read-only) | Expected |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| Service | `Get-Service *sunshine* -ErrorAction SilentlyContinue` | nothing |
|
||||||
|
| Processes | `Get-Process sunshine*, sunshinesvc -ErrorAction SilentlyContinue` | nothing |
|
||||||
|
| Folder | `Test-Path 'C:\Program Files\Sunshine'` | `False` (or a folder without `sunshine.exe`; then we stop and ask, we do not delete it) |
|
||||||
|
| Uninstall entry | `Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*, HKLM:\Software\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* \| ? DisplayName -like '*Sunshine*'` | nothing |
|
||||||
|
| TCP ports | `Get-NetTCPConnection -State Listen \| ? LocalPort -in 47984,47989,47990,48010` | nothing |
|
||||||
|
| UDP ports | `Get-NetUDPEndpoint \| ? LocalPort -in 47998,47999,48000,48002` | nothing |
|
||||||
|
| Firewall leftovers | `Get-NetFirewallRule -DisplayName '*Sunshine*' -ErrorAction SilentlyContinue` | nothing (only noted if present) |
|
||||||
|
| Load | the CPU/RAM check from the build rule | both ≤ 90 %, else wait |
|
||||||
|
|
||||||
|
Anything unexpected: stop and report; no clean-up on our side.
|
||||||
|
|
||||||
|
## 2. Step (b): pinned Sunshine, one UAC prompt
|
||||||
|
|
||||||
|
**Pin** (release API, S-19): `v2026.914.233613`, `Sunshine-Windows-AMD64-installer.msi`, 33,710,080 bytes,
|
||||||
|
sha256 `1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf`,
|
||||||
|
`https://github.com/SunshineStream/Sunshine/releases/download/v2026.914.233613/Sunshine-Windows-AMD64-installer.msi`.
|
||||||
|
The same digest is checked twice: against this pin and against the release API's `digest` field fetched at download
|
||||||
|
time. A mismatch on either = delete the file and stop.
|
||||||
|
|
||||||
|
Download (not elevated): `Invoke-WebRequest -Uri <url> -OutFile E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi`,
|
||||||
|
then `Get-FileHash -Algorithm SHA256`. Nothing is run from `downloads\` before the hash matches.
|
||||||
|
|
||||||
|
**Why one elevated script, not a bare `msiexec`:** Sunshine's first start must already be bound to loopback, and
|
||||||
|
`--creds` needs write access under `C:\Program Files\Sunshine\config`. A plain `msiexec /i` would start the service
|
||||||
|
on all interfaces with no credentials. So we start **one** elevated PowerShell (`Start-Process powershell -Verb RunAs`
|
||||||
|
with our script `tools/lab-relay/scripts/lab-install.ps1`). That is the one UAC prompt ("Windows PowerShell",
|
||||||
|
publisher Microsoft Windows). Inside it, without further prompts:
|
||||||
|
|
||||||
|
1. `msiexec /i <msi> /qn /norestart /l*v E:\build\play-remotely\lab\captures\msiexec.log` (quiet; elevated already).
|
||||||
|
2. `Stop-Service SunshineService` as soon as the MSI returns (the MSI starts it; until our config is in, it has no
|
||||||
|
credentials, so nobody can pair or call its API).
|
||||||
|
3. Write `C:\Program Files\Sunshine\config\sunshine.conf` with only these lines:
|
||||||
|
|
||||||
|
```
|
||||||
|
bind_address = 127.0.0.2
|
||||||
|
address_family = ipv4
|
||||||
|
origin_web_ui_allowed = pc
|
||||||
|
upnp = disabled
|
||||||
|
external_ip = 127.0.0.2
|
||||||
|
sunshine_name = DomiStream-lab
|
||||||
|
lan_encryption_mode = 1
|
||||||
|
wan_encryption_mode = 1
|
||||||
|
min_log_level = debug
|
||||||
|
pkey = E:/build/play-remotely/lab/keys/sunshine-lab-key.pem
|
||||||
|
cert = E:/build/play-remotely/lab/keys/sunshine-lab-cert.pem
|
||||||
|
```
|
||||||
|
|
||||||
|
Forward slashes in paths: how the config parser treats backslashes is not documented. Encryption mode 1 ("if the client supports it") rather than 2: if Moonlight PC lacks one kind of encryption, a
|
||||||
|
mandatory setting would refuse the only session we get. `pkey`/`cert` point at `keys\` so the lab key never has to
|
||||||
|
be copied out of Program Files (inferred: Sunshine creates the pair at the configured path when missing; if it does
|
||||||
|
not, the script removes the two lines, restarts, and copies the default pair from `config\credentials\` into
|
||||||
|
`keys\` instead, still inside the same elevation).
|
||||||
|
4. **First-run credentials, never on a surviving command line:** the script draws a throwaway username and password
|
||||||
|
(32 random bytes each, base64url), runs `sunshine.exe --creds <u> <p>` once (the documented non-interactive way,
|
||||||
|
sunshine-api.md §4; the arguments live only for that process's lifetime), and saves the throwaway pair to
|
||||||
|
`secrets\sunshine-throwaway.cred` with `ConvertFrom-SecureString` (DPAPI, Mark's account). It is rotated in step 5.
|
||||||
|
This needs Mark's account to be the one that elevates (consent prompt, not a password prompt); if UAC asks for a
|
||||||
|
different admin account, we stop.
|
||||||
|
5. `Start-Service SunshineService`; wait until `Get-NetTCPConnection` shows 127.0.0.2:47989/47984/47990/48010 and
|
||||||
|
nothing on 0.0.0.0; `icacls` `keys\` and `secrets\` down to Mark's account + SYSTEM. Exit.
|
||||||
|
|
||||||
|
After the elevated script, not elevated (`lab-api.ps1`, PowerShell, Basic auth built in memory, TLS pinned to
|
||||||
|
`keys\sunshine-lab-cert.pem` by thumbprint): `POST https://127.0.0.2:47990/api/password` from the throwaway pair to a
|
||||||
|
fresh random lab pair stored in `secrets\sunshine-lab.cred` (DPAPI); delete the throwaway file. Arena's Day 1
|
||||||
|
takeover rotates once more into Custos.
|
||||||
|
|
||||||
|
Firewall: if the MSI added inbound rules, we only note them (`Get-NetFirewallRule`); Sunshine listens on 127.0.0.2,
|
||||||
|
so they expose nothing. Changing them needs admin and is left to Arena Day 1.
|
||||||
|
|
||||||
|
## 3. Step (c): Moonlight PC portable, no install
|
||||||
|
|
||||||
|
**Pin** (release API, S-19): `v6.2.0` (2026-10-04), `MoonlightPortable-x64-6.2.0.zip`, 37,242,232 bytes,
|
||||||
|
sha256 `6f91d268b41ed5ca8066d9d7578dc403b8db190991ff48f00b1700465f8f7ebf`,
|
||||||
|
`https://github.com/moonlight-stream/moonlight-qt/releases/download/v6.2.0/MoonlightPortable-x64-6.2.0.zip`.
|
||||||
|
Download to `downloads\`, check the hash (pin and API digest), extract to `E:\build\play-remotely\lab\moonlight\`.
|
||||||
|
No installer, no admin.
|
||||||
|
|
||||||
|
Before its first start we snapshot (names only) the `moonlight\` folder tree and the key names under
|
||||||
|
`HKCU:\Software` so that afterwards we can see what Moonlight wrote (its settings and its client identity; where it
|
||||||
|
keeps them is not documented and we do not read its source to find out). We run `Moonlight.exe --help` first
|
||||||
|
(black-box) to see whether it can pair from the command line with a PIN we choose.
|
||||||
|
|
||||||
|
**Moonlight's lab client key:** the relay needs it to talk TLS to Sunshine on Moonlight's behalf (section 4). After
|
||||||
|
Moonlight's first start (or at the latest right after pairing step 1, which carries its certificate), a small script
|
||||||
|
finds the new value by name and length only, writes the key as PEM to `keys\moonlight-lab-key.pem` and the certificate
|
||||||
|
to `keys\moonlight-lab-cert.pem`, and prints neither. If the key is not readable (for example protected with DPAPI by
|
||||||
|
Moonlight), the relay passes HTTPS through untouched and we fall back to Sunshine's debug log for what HTTPS carries
|
||||||
|
(section 6 lists what that loses).
|
||||||
|
|
||||||
|
## 4. Step (d): the relay
|
||||||
|
|
||||||
|
### Addresses
|
||||||
|
|
||||||
|
```
|
||||||
|
Moonlight ──▶ 127.0.0.1:{47984,47989,48010}/tcp, {47998,47999,48000,48002}/udp (lab-relay, logs everything)
|
||||||
|
└──▶ 127.0.0.2: same ports (Sunshine, bind_address)
|
||||||
|
```
|
||||||
|
|
||||||
|
Moonlight is told the host is `127.0.0.1`. Because Sunshine sits on another loopback address with its **default**
|
||||||
|
ports, the relay copies the port numbers unchanged: no port rewriting in serverinfo, RTSP or SDP, which matters
|
||||||
|
because RTSP may be encrypted (U5) and could not be rewritten.
|
||||||
|
|
||||||
|
Address rewriting: Sunshine may write its own address (`127.0.0.2`) into answers, for example `sessionUrl0` in the
|
||||||
|
launch answer, which would send Moonlight around the relay. The relay replaces the 9 bytes `127.0.0.2` with
|
||||||
|
`127.0.0.1` in **host-to-client plaintext only** (HTTP, decrypted HTTPS, plain RTSP), logs the original and a note
|
||||||
|
per replacement. Same length, so `Content-Length` stays right.
|
||||||
|
|
||||||
|
Fallback if Sunshine refuses `bind_address = 127.0.0.2`: Sunshine on `127.0.0.1` with `port = 48989` (all ports
|
||||||
|
+1000), the relay on the default ports, and port rewriting of `HttpsPort`/`ExternalPort` (serverinfo), `sessionUrl0`
|
||||||
|
(launch) and `server_port=` (RTSP SETUP). That only works while RTSP is plaintext, so the fallback also sets the
|
||||||
|
encryption modes to 0 and gives up U17/U19 for this capture.
|
||||||
|
|
||||||
|
UDP: video, audio and control go to the address the client's first datagram (the PING, or the ENet connect) came
|
||||||
|
from (W5, W6). The relay keeps one upstream socket per client address and port, so Sunshine sees the relay's socket
|
||||||
|
and answers it; the relay sends the answers back to Moonlight's socket. ENet carries no addresses.
|
||||||
|
|
||||||
|
### What is encrypted, and how we see plaintext
|
||||||
|
|
||||||
|
| Traffic | Protection | How the relay sees it |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| HTTP 47989 (serverinfo, pairing steps 1-4) | none | plaintext |
|
||||||
|
| HTTPS 47984 (pairing step 5, applist, launch with `rikey`, cancel) | TLS, both sides pin certificates | **terminated in the relay**: towards Moonlight it presents Sunshine's own lab certificate (the one Moonlight pinned in pairing, so the pin holds); towards Sunshine it presents Moonlight's own lab client certificate and pins Sunshine's lab certificate |
|
||||||
|
| RTSP 48010 | plaintext, or encrypted when negotiated (U5) | as is; if encrypted, decrypted offline with `rikey` from the launch request |
|
||||||
|
| Control 47999 | AES-128-GCM with `rikey` (client-chosen) | ENet headers plaintext; message bodies decrypted offline with `rikey` |
|
||||||
|
| Audio 48000 | AES-128-CBC with `rikey`, if negotiated | decrypted offline |
|
||||||
|
| Video 47998 | AES-128-GCM with `rikey`, only if negotiated | headers plaintext unless encrypted; decrypted offline |
|
||||||
|
|
||||||
|
Why TLS termination and not just Sunshine's log: `rikey` and the launch parameters (U4) travel only inside HTTPS.
|
||||||
|
Without them, control, audio and possibly video stay opaque and U10, U11, U16, U17, U19, U20, U22 stay open. The debug
|
||||||
|
log's contents are not documented, and asking it to print keys is not something we can count on. Termination uses
|
||||||
|
only lab material that exists for this capture and is deleted after it; nothing outside this PC's loopback is
|
||||||
|
touched. Sunshine's debug log (`GET /api/logs`) is still copied into `captures\` as a cross-check.
|
||||||
|
|
||||||
|
The relay never changes a byte except the documented address rewrite, and never sends anything on its own.
|
||||||
|
|
||||||
|
### Which part of the capture settles which UNKNOWN
|
||||||
|
|
||||||
|
| U | Settled by |
|
||||||
|
| :-- | :-- |
|
||||||
|
| U1 | HTTP 47989 pairing requests (query names, order), then the first HTTPS request (`pairchallenge`) and its place in the order |
|
||||||
|
| U2 | partly: the certificate Moonlight sends in pairing step 1 shows one certificate Sunshine accepts (key size, validity, subject); our own certificate is tested on Day 1 |
|
||||||
|
| U4 | the decrypted HTTPS `/launch` request and answer |
|
||||||
|
| U5 | the RTSP TCP stream: framing, `Content-Length`, `X-GS-ClientVersion`, SETUP targets, `Transport`, `Session`, PLAY |
|
||||||
|
| U6 | the ANNOUNCE payload Sunshine accepted |
|
||||||
|
| U7 | headers of the three SETUP answers |
|
||||||
|
| U8 | the first client-to-host datagrams on 47998 and 48000, and their timing |
|
||||||
|
| U9 | control datagrams decoded with our ENet parser: connect/verify connect fields, flags, anything stock 1.3 lacks |
|
||||||
|
| U10 | decrypted control messages: START_A/B, PERIODIC_PING, LOSS/FRAME_STATS, IDR request, termination at the end, and their timing |
|
||||||
|
| U11 | control frame sequence numbers in both directions |
|
||||||
|
| U13 | the first 8 bytes of each reassembled video frame |
|
||||||
|
| U14 | confirmation: our Cauchy encoder must reproduce every captured video parity packet (offset 32 on) |
|
||||||
|
| U15 | the multi-FEC flags byte across all video packets |
|
||||||
|
| U16 | captured audio blocks: solve the 2 × 4 parity matrix over GF(2^8) from data and parity bytes |
|
||||||
|
| U17 | ANNOUNCE `encryptionEnabled` plus whether audio payloads decrypt |
|
||||||
|
| U19 | the video packet layout when video encryption was negotiated (if Moonlight PC does not negotiate it, U19 stays open) |
|
||||||
|
| U20 | keys typed during the stream into a scratch Notepad window |
|
||||||
|
| U22 | gamepad packets, only if Mark has a controller plugged in (optional) |
|
||||||
|
| U24 | the TLS handshakes on 47984 (versions, cipher suites), logged by the relay |
|
||||||
|
| U25 | `ServerCodecModeSupport` in serverinfo from a host whose GPU we know (RTX 3090) |
|
||||||
|
| U26 | the `surround-params` lines in DESCRIBE (all of them, if Sunshine lists every Opus configuration as Moonshine does) |
|
||||||
|
| U27 | only if a call is refused during the session; not provoked |
|
||||||
|
| U29 | video RTP timestamps against the 60 fps frame rate |
|
||||||
|
| U21, U23, U28 | **not** settled: no touch/pen device, no game to rumble, no wrong PIN in a one-session capture |
|
||||||
|
|
||||||
|
## 5. Step (e): what is recorded, analysis, clean-up
|
||||||
|
|
||||||
|
**Recorded** (`captures\`):
|
||||||
|
- `session-<UTC>.dslr`: the relay's record file. Each record: kind (open, data, close, note), protocol (HTTP,
|
||||||
|
HTTPS plaintext, RTSP, video, control, audio, mic, meta), direction, connection id, microseconds since the start,
|
||||||
|
and the bytes. Format and tests: `tools/lab-relay/src/record.rs`.
|
||||||
|
- `sunshine.log` (copied with `GET /api/logs`), `msiexec.log`.
|
||||||
|
- `notes.md`: what we did and when (times from the relay's clock).
|
||||||
|
|
||||||
|
**Privacy:** the video frames are Mark's desktop. Before the stream, Mark closes anything private; during it, only a
|
||||||
|
scratch Notepad and the desktop are on screen. After analysis the video payload bytes are deleted from the recording
|
||||||
|
(`lab-relay strip-video`), keeping only packet headers and parity checks.
|
||||||
|
|
||||||
|
**Analysis** (offline, no network): `lab-relay dump` lists records with secrets redacted (`rikey=`, `Authorization:`,
|
||||||
|
pairing values); per-protocol extraction feeds DomiStream's own parsers (Phase B) and small Python checks run with
|
||||||
|
`python -I` from the repo, never from `captures\`. Every fact that comes out goes into PROTOCOL.md with the tag
|
||||||
|
`[L1]` (lab capture 1, date, versions) and, where useful, into test vectors that contain **no** lab key (vectors are
|
||||||
|
re-encrypted with test keys generated in the test).
|
||||||
|
|
||||||
|
**Clean-up** (right after the stream, not elevated):
|
||||||
|
1. Quit Moonlight; stop the relay.
|
||||||
|
2. `POST /api/clients/unpair-all` (removes the Moonlight lab client from Sunshine).
|
||||||
|
3. `POST /api/config` without the `pkey`/`cert` lines and `POST /api/restart`, so Sunshine makes a fresh pair at its
|
||||||
|
default path (inferred; if it does not, the lab pair stays referenced and Arena's Day 1 takeover, which runs
|
||||||
|
elevated anyway, regenerates it). Then delete `keys\sunshine-lab-*.pem`.
|
||||||
|
4. Delete `keys\moonlight-lab-*.pem`, the whole `moonlight\` folder and the registry key Moonlight created (found by
|
||||||
|
the snapshot diff in step (c)).
|
||||||
|
5. Keep `secrets\sunshine-lab.cred` until Arena's Day 1 takeover rotates the credentials into Custos, then delete it.
|
||||||
|
6. Delete `downloads\Moonlight*.zip`. Keep the Sunshine MSI (Arena Day 1 pins the same version).
|
||||||
|
7. Sunshine **stays installed**, bound to 127.0.0.2, ready for Arena's Day 1 takeover.
|
||||||
|
8. The recordings stay on E: until the facts are in PROTOCOL.md and QA has its vectors; then they are deleted on the
|
||||||
|
build lead's word.
|
||||||
|
|
||||||
|
## 6. If something fails
|
||||||
|
|
||||||
|
| Failure | What we do |
|
||||||
|
| :-- | :-- |
|
||||||
|
| sha256 mismatch | delete the file, stop, report |
|
||||||
|
| Sunshine will not bind 127.0.0.2 | fallback of section 4 (port +1000, encryption off for this capture) |
|
||||||
|
| Moonlight refuses `127.0.0.1` as a host | relay on `127.0.0.3` instead (any loopback address works) |
|
||||||
|
| The relay's TLS handshake with Moonlight or Sunshine fails (for example a cipher suite rustls does not offer) | restart the relay with `--https-passthrough`: HTTPS is then recorded as raw TLS, with the same losses as the next row |
|
||||||
|
| Moonlight's key not readable | HTTPS passes through untouched; we lose U4 and `rikey`, so U10, U11, U16, U17, U19, U20, U22 stay open unless Sunshine's debug log shows them |
|
||||||
|
| Pairing needs a `pairing_id` we cannot find (sunshine-api.md gap) | we watch the network calls of Sunshine's own local PIN page in our browser pane (black-box) and submit the PIN there ourselves |
|
||||||
|
| CPU or RAM above 90 % | wait (the relay build and the stream are both heavy) |
|
||||||
|
|
||||||
|
## 7. Step (f): timeline for Mark
|
||||||
|
|
||||||
|
About 20 minutes; Mark's part is **one click**, plus closing private windows before the stream.
|
||||||
|
|
||||||
|
| When | What happens | Mark |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| 0:00 | We check that the old Sunshine is gone and that the PC is not busy. | nothing |
|
||||||
|
| 0:02 | We download the pinned Sunshine and Moonlight and check their fingerprints (about 70 MB). | nothing |
|
||||||
|
| 0:05 | **A UAC prompt appears: "Windows PowerShell – Do you want to allow this app to make changes to your device?" (publisher: Microsoft Windows).** | **click Yes** (the only click) |
|
||||||
|
| 0:05-0:08 | Sunshine installs quietly and starts, reachable only from this PC. | nothing |
|
||||||
|
| 0:08 | Moonlight opens in a window (portable, nothing installed). It may show a PIN; we enter it into Sunshine ourselves. If Windows Firewall asks about Moonlight, click **Cancel**: everything runs on this PC. | close private windows; Cancel on a firewall prompt if one appears |
|
||||||
|
| 0:10 | A one-minute desktop stream: Moonlight shows his own desktop in a window. We move the mouse and type a few letters into a scratch Notepad. If he has a gamepad plugged in, we may ask him to press a few buttons. | hands off the mouse and keyboard for that minute (optional: press gamepad buttons when asked) |
|
||||||
|
| 0:12 | We close the stream, unpair Moonlight, delete Moonlight and the lab keys. Sunshine stays installed for Arena's Day 1. | nothing |
|
||||||
|
| later | We analyse the recording offline and delete the desktop video from it. | nothing |
|
||||||
@@ -0,0 +1,324 @@
|
|||||||
|
# Live interop: the one sitting with Mark
|
||||||
|
|
||||||
|
Status: **prepared 2026-11-30, not run.** The probe (`tools/gs-probe`) is built and unit-tested and has never talked
|
||||||
|
to a host: no Sunshine existed when it was written.
|
||||||
|
|
||||||
|
This sitting settles the open UNKNOWNs of [PROTOCOL.md](PROTOCOL.md) §8 live, in one go, and answers the black-box
|
||||||
|
checks a GameStream client can answer from Arena `docs/PLAY-REMOTELY.md`. That list lives in its handover ("Next on
|
||||||
|
RESUME", item 3), §8 (the `pairing_id` call, the clients list) and §15 (the test-PC checks); §17 is the installer
|
||||||
|
spec and is not part of this sitting. The host is the pinned Sunshine
|
||||||
|
`v2026.914.233613`, installed by arena-host at Turn on to `E:\Apps\Sunshine` and bound to `192.168.100.140`. The
|
||||||
|
client is our probe, which runs DomiStream `stream-v0.1.0`'s state machines over real sockets from this PC. No
|
||||||
|
Moonlight, no TV and no other machine take part.
|
||||||
|
|
||||||
|
## 0. Hard limits
|
||||||
|
|
||||||
|
- **One address.** Every probe socket goes to `192.168.100.140`. If `sessionUrl0` names another host, the probe
|
||||||
|
records it and still connects only to .140.
|
||||||
|
- **No listening port on this PC.** During `launch` the probe has only three ephemeral UDP client sockets. Nothing
|
||||||
|
binds a fixed port.
|
||||||
|
- **Out folder:** `F:\build\play-remotely\live\<date>\` (E: is full). It is outside git and holds:
|
||||||
|
- `identity\`: the probe's test-only key and certificate, made on the first run;
|
||||||
|
- `runs\<utc>-<command>\`: one folder per command, with `log.jsonl` and the dumps.
|
||||||
|
|
||||||
|
It is deleted at the end (section 7).
|
||||||
|
- **Secrets:**
|
||||||
|
- The probe never prints its key and never logs the stream key (`rikey`), pairing salts, challenges or secrets.
|
||||||
|
- The PIN goes to the operator's terminal only, never to the log. Every log line is also scanned for the session
|
||||||
|
key's hex before it is written.
|
||||||
|
- Sunshine's API credentials stay in Custos: never typed, never on a command line, never in a log.
|
||||||
|
- **Nothing changes on Mark's PC** during the sitting: no Sunshine config, firewall, arena-host setting or install.
|
||||||
|
The only exceptions are the steps below that the run book names (pairing the probe, launching one game) and their
|
||||||
|
undo in section 7.
|
||||||
|
- **The stop-and-report rule** (section 6) wins over everything in this file.
|
||||||
|
|
||||||
|
## 1. What Mark sees
|
||||||
|
|
||||||
|
- **Nothing on his screen except:**
|
||||||
|
- Sunshine's own notifications, if any (for example when a client asks to pair, or a stream starts or ends);
|
||||||
|
- at `launch`, the game starting on his PC;
|
||||||
|
- at `quit`, the game closing.
|
||||||
|
- The probe runs in our terminal. No UAC prompt, no Custos card (Arena Domi was approved at Turn on), and no PIN is
|
||||||
|
shown to Mark.
|
||||||
|
- **Two things we cannot rule out before the sitting.** If either appears, Mark answers as below and we stop and
|
||||||
|
report:
|
||||||
|
- A **Windows Security Alert** for `probe.exe` when its UDP sockets first receive. Mark clicks **Cancel**.
|
||||||
|
- **Arena Domi's own first-stream toast** (PLAY-REMOTELY §7.4). It can appear if the Arena window is running when
|
||||||
|
Sunshine's prep-cmd hook reports the probe's stream. Mark dismisses it.
|
||||||
|
- **Mark's part:** be present, agree on the game for `launch` beforehand (a light one from the `apps` list), and keep
|
||||||
|
hands off mouse and keyboard while the stream runs (90 s for the first launch, about 30 s for any variant).
|
||||||
|
|
||||||
|
## 2. Before the sitting (without Mark)
|
||||||
|
|
||||||
|
| # | What | How |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| P1 | Probe built | `cd tools\gs-probe`, `CARGO_BUILD_BUILD_DIR=F:\build\play-remotely\cargo-build-probe`, `TEMP`/`TMP=F:\build\play-remotely\tmp\protocol`, load gate (CPU and RAM < 90 %, D: and F: < 95 %), then `cargo test --offline -j 2` and `cargo build --offline --release -j 2`. Binary: `tools\gs-probe\target\release\probe.exe`. |
|
||||||
|
| P2 | Sunshine as arena-host left it (read-only) | `Get-NetTCPConnection -State Listen \| ? LocalPort -in 47984,47989,47990,48010` shows each on `192.168.100.140` only: nothing on `0.0.0.0` or loopback on Day 1 (PLAY-REMOTELY §4). `Get-NetUDPEndpoint \| ? LocalPort -in 47998,47999,48000` is empty while idle (PLAY-REMOTELY §9). |
|
||||||
|
| P3 | Sunshine's API without seeing the credentials (**decided: a**, build lead 2026-11-30) | Needed for the PIN (step S2) and checks B1–B3. The host engineer writes a dev-only `sunshine-api <GET\|POST> <path> [json]` command in arena-host (Play remotely's own crate), behind a cargo feature that never ships. It takes the credentials from Custos (never typed, printed or logged), calls `https://192.168.100.140:47990` with arena-host's pinned client (§3, §4) and prints the answer with secrets redacted. Its first call also answers §15's "does `pc` cover a self-connection to .140". It must be built and checked before the sitting; this file writes the calls as `sunshine-api …`. |
|
||||||
|
| P4 | U10 bodies (**done** 2026-11-30, CLEAN_ROOM S-21) | Moonshine (BSD-2) reads **no body** from START_B, PERIODIC_PING or the IDR request, ignores LOSS_STATS and FRAME_STATS, and does not know START_A. Inside the encrypted frame, an unknown type is skipped, not fatal. Each PERIODIC_PING pushes its stop deadline out (60 s by default). Nothing taken has GPL provenance. The probe's defaults follow: START_A and START_B empty, PERIODIC_PING empty every 500 ms, an empty IDR request on frame loss. Table V holds what to try if Sunshine differs. |
|
||||||
|
| P5 | Game | Agree the `launch` game with Mark (a light one) and note its app id after S4. |
|
||||||
|
|
||||||
|
Shell variables used below (PowerShell):
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
$P = "F:\Akce\DomiStream-wt-probe\tools\gs-probe\target\release\probe.exe"
|
||||||
|
$O = "F:\build\play-remotely\live\2026-12-XX" # the sitting's date
|
||||||
|
$H = "192.168.100.140"
|
||||||
|
```
|
||||||
|
|
||||||
|
Exit codes: 0 done, 1 error, 2 bad command line, 3 **stop and report** (a `stop` record is in the log).
|
||||||
|
|
||||||
|
## 3. The sequence
|
||||||
|
|
||||||
|
Each step names the command, the UNKNOWNs it settles and what to look for. "Log" means that run's
|
||||||
|
`$O\runs\<utc>-<command>\log.jsonl` (format in section 4).
|
||||||
|
|
||||||
|
### S0. Preflight (read-only, 1 min)
|
||||||
|
|
||||||
|
- Run the P2 checks again.
|
||||||
|
- Sunshine's own traffic baseline (B4): `Get-NetTCPConnection -OwningProcess (Get-Process sunshine).Id` and
|
||||||
|
`Get-NetUDPEndpoint -OwningProcess …`. Note every remote address.
|
||||||
|
|
||||||
|
### S1. `& $P serverinfo --host $H --out $O`
|
||||||
|
|
||||||
|
- **Settles:** U25 (codec bits, from a host whose GPU we know: RTX 3090).
|
||||||
|
- **Look for:**
|
||||||
|
- `serverinfo.http` recv: status 200, the XML in full;
|
||||||
|
- the note with `parsed` and `codec_mode_support_bits`;
|
||||||
|
- `HttpsPort` (if it is not 47984, add `--https-port` to every later command);
|
||||||
|
- `appversion`, `state` (…`_FREE`), `PairStatus 0`.
|
||||||
|
- On the first run the probe generates its identity: log record `identity` (`generated a new …`).
|
||||||
|
|
||||||
|
### S2. `& $P pair --host $H --out $O`
|
||||||
|
|
||||||
|
- **Settles:**
|
||||||
|
- U1: the parameter names we send are accepted, and the order of steps 4 and 5;
|
||||||
|
- U2: our RSA-2048 self-signed certificate is accepted;
|
||||||
|
- U24: the TLS version and suite at step 5;
|
||||||
|
- with B1 and B2, PLAY-REMOTELY §8.
|
||||||
|
- **Procedure.** The probe prints `PIN for the operator: NNNN` and waits up to 120 s at step 1. Within that time:
|
||||||
|
1. **B1, the pending pairing.**
|
||||||
|
- Call each documented read-only GET of the pinned API docs (at least `sunshine-api GET /api/clients/list`).
|
||||||
|
- Look for an entry naming the probe's `uniqueid` (log record `identity`) or the device name
|
||||||
|
`DomiStream probe`.
|
||||||
|
- Read `E:\Apps\Sunshine\config\sunshine.log` (black-box: Sunshine's own log, read-only) for a line about the
|
||||||
|
incoming pairing and any id it names.
|
||||||
|
- Record which call or line shows the pending pairing and its `pairing_id`.
|
||||||
|
2. **Submit:** `sunshine-api POST /api/pin '{"pairing_id":"<id>","pin":"NNNN","name":"DomiStream probe"}'`. If no
|
||||||
|
`pairing_id` was found, try `{"pin":"NNNN","name":"DomiStream probe"}` once and record the answer. If that is
|
||||||
|
refused too: stop and report (B1 open, and pairing cannot go on).
|
||||||
|
3. The probe goes on by itself through steps 2–5 and ends with an HTTPS `serverinfo` (`PairStatus 1`).
|
||||||
|
- **Look for:**
|
||||||
|
- `pair.1` … `pair.5`: send and recv of each step (values redacted, names and order kept);
|
||||||
|
- `pair.1`'s `elapsed_ms` (the time until the PIN went in);
|
||||||
|
- the `host certificate sha256` note;
|
||||||
|
- `pair.5`'s `tls` (version, suite);
|
||||||
|
- `pair.done`;
|
||||||
|
- on failure, the `stop` record, with the step and the state it failed in.
|
||||||
|
- **B2:** `sunshine-api GET /api/clients/list` must show exactly one new client, named `DomiStream probe`. Record the
|
||||||
|
entry's fields: this is also B3's input.
|
||||||
|
|
||||||
|
### S3. `& $P apps --host $H --out $O`
|
||||||
|
|
||||||
|
- **Settles:** nothing new. It confirms HTTPS with the pinned certificate (U24 again).
|
||||||
|
- **Look for:** the agreed game's id (P5); `Desktop`, if listed, is the fallback.
|
||||||
|
|
||||||
|
### S4. `& $P launch <id> --host $H --out $O --seconds 90 --nudge-mouse`
|
||||||
|
|
||||||
|
90 s outlasts Moonshine's 60 s no-ping deadline. A stream that lives to the end shows Sunshine accepts the default
|
||||||
|
empty PERIODIC_PING, or does not need one within 90 s; `sunshine.log` tells which (U10). Variants use `--seconds 30`.
|
||||||
|
|
||||||
|
- **Mark sees** the game start.
|
||||||
|
- **Settles:**
|
||||||
|
|
||||||
|
| Area | UNKNOWNs |
|
||||||
|
| :-- | :-- |
|
||||||
|
| Launch | U4 |
|
||||||
|
| RTSP | U5, U6, U7, U26 |
|
||||||
|
| UDP setup | U8 |
|
||||||
|
| Control stream | U9, U10, U11 |
|
||||||
|
| Video | U13, U14, U15, U29; U19 only if the host offers video encryption |
|
||||||
|
| Audio | U17; data for U16 |
|
||||||
|
| Host events | U23, only if any arrive |
|
||||||
|
|
||||||
|
- **Look for**, in order:
|
||||||
|
|
||||||
|
| Record | Settles | What it shows |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| `launch` send/recv | U4 | Our parameter set accepted (`uniqueid, appid, mode, rikey=<redacted>, rikeyid, hdrMode, surroundAudioInfo`); `gamesession`, `sessionUrl0` |
|
||||||
|
| `rtsp.*` send/recv | U5 | Every request and answer in full; `end` (`Length` / `Closed` / `Idle`), `content_length_header`, and notes about new TCP connections |
|
||||||
|
| `rtsp.describe` recv | U26 | The SDP: every `surround-params` line, `encryptionSupported`, `featureFlags` |
|
||||||
|
| `rtsp.setup_*` recv | U5, U7 | Every header of the three answers (`Session`, `Transport`, anything extra) |
|
||||||
|
| `rtsp.announce` | U6 | 200 means our 19 attributes are accepted as they are |
|
||||||
|
| `ping` + `video.first` / `audio.first` | U8 | Payload `PING`; `pings_before` and the source port of the first packet |
|
||||||
|
| `control.datagram` (first 64 each way) | U9 | Decoded ENet: our connect, the host's verify connect (channel count, MTU, window, flags), anything stock 1.3 lacks (`unparsed: …` or `parse_error`) |
|
||||||
|
| `control.start_a`, `control.start_b` | U10 | What we sent (empty bodies by default). Video then flowing means the host accepted it |
|
||||||
|
| `control.periodic_ping` (first 3), `launch.summary` `control.ended` | U10 | The empty ping every 500 ms; `ended` null after 90 s means the pings kept the session alive |
|
||||||
|
| `control.host` | U10, U11, U23 | Every decrypted host message: type, sequence, body |
|
||||||
|
| `video.frame` (first 16) | U13 | `header_raw`: Wolf's constant `0137636861727373` or Moonshine's fields |
|
||||||
|
| `launch.summary` | U14 | `u14_*`: whole-packet parity matches (5.3 confirmed), or payload-only, or neither |
|
||||||
|
| `launch.summary` | U15 | `multi_fec_flags_u15` histogram |
|
||||||
|
| `launch.summary` | U29 | `u29_rtp_ticks_per_frame`, `u29_clock_hz_estimate` (90000 expected) |
|
||||||
|
| `launch.summary` | U17 | `u17_decrypting` vs `u17_plain`: the receiver that accepts the packets says whether audio is encrypted. Compare with bit 0x04 of `negotiated.encryption` |
|
||||||
|
| `launch.summary` | U19 | `decrypt_failures` is 0 when video encryption was negotiated |
|
||||||
|
| `audio.u16` | U16 | Matrix solved from `audio-packets.bin` (or later: `& $P solve-audio-fec <run>\audio-packets.bin`); `matrix_is_mds` |
|
||||||
|
| `launch.summary` counters | — | Video: `frames`, `decode_ready_frames`, `frames_lost`, `fec_recovered_shards`. Audio: data and parity packets, losses |
|
||||||
|
|
||||||
|
- **B3, per-device input:**
|
||||||
|
- The `--nudge-mouse` input is one relative move of +1 then −1 pixel after the first decodable frame:
|
||||||
|
harmless, and invisible to Mark.
|
||||||
|
- If the B2 entry has a per-client input field, an extra launch with that input turned off for the probe shows
|
||||||
|
whether Sunshine drops it (watch `sunshine.log`). That launch needs the build lead's OK: it changes a Sunshine
|
||||||
|
setting.
|
||||||
|
- If the entry has no such field, record "per-client: enable/disable only".
|
||||||
|
- **B4:** during the stream, list Sunshine's sockets again (S0). The three UDP ports appear, and no remote address
|
||||||
|
besides .140 shows up.
|
||||||
|
- **B5:** with arena-host running, the prep-cmd hook should report `start <game>` with
|
||||||
|
`SUNSHINE_CLIENT_NAME = DomiStream probe`, and arena-host should write its audit record "Play remotely started".
|
||||||
|
Record what happened.
|
||||||
|
- Then `& $P quit --host $H --out $O`: the game closes. B5 again: `end`.
|
||||||
|
|
||||||
|
**Variants (table V), only when S4 stops.** Each variant is one `launch` (with `quit` before the next). There are at
|
||||||
|
most 6 launches in the sitting, and the same variant is never tried twice.
|
||||||
|
|
||||||
|
| Symptom (log) | Variant |
|
||||||
|
| :-- | :-- |
|
||||||
|
| ANNOUNCE not 200 (U6) | `--encryption 1`, then `--codec hevc`, then `--packet-size 1392`. Attribute values beyond the CLI need a code change: stop and report |
|
||||||
|
| No verify connect, ENet `timed_out` (U9) | `--enet-channels 48`. Nothing else is known about the connect fields: stop and report |
|
||||||
|
| Connected, but the host ends the session right after START_A, or `sunshine.log` names an unknown control message (U10) | `--start-a none` (Moonshine has no START_A) |
|
||||||
|
| Connected but no video within 5 s of START_B (U10) | Read `sunshine.log` for what it says about START_B. If it names a body or a length, give that body with `--start-b <hex>` (one try). Otherwise stop and report: P4 found no body, and none is guessed |
|
||||||
|
| Video stops after N s, host disconnects (U10) | `--periodic-ping-ms 100`; if it still stops, `--periodic-ping none` (to see whether the empty ping is what the host refuses), then stop and report |
|
||||||
|
| Frames lost and never recovered (U10) | `--rfi`, if DESCRIBE has `refPicInvalidation`; else `--idr none`, to compare with the default empty request |
|
||||||
|
| Surround (U26), only if time allows | `--audio 5.1` |
|
||||||
|
|
||||||
|
### S5. U28, a refused pairing (optional, 2 min)
|
||||||
|
|
||||||
|
1. `& $P unpair --host $H --out $O`.
|
||||||
|
2. `& $P pair --host $H --out $O --wrong-pin`. The probe prints one PIN, uses another, and must stop at step 3 with
|
||||||
|
`ProofMismatch`.
|
||||||
|
3. Submit the printed PIN as in S2.
|
||||||
|
4. Look for:
|
||||||
|
- what `/api/pin` answers;
|
||||||
|
- whether B1's call still lists a pending pairing afterwards;
|
||||||
|
- whether the client list stays without the probe;
|
||||||
|
- whether a fresh `probe pair` works without any clean-up. That last point is U28's answer.
|
||||||
|
5. Leave it unpaired.
|
||||||
|
|
||||||
|
## 4. Reading the log
|
||||||
|
|
||||||
|
One JSON object per line, flushed as written:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"n":12,"t_ms":845.210,"step":"rtsp.setup_video","kind":"recv","u":["U5","U7"],"data":{…}}
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`kind`:**
|
||||||
|
- `send`: what the probe sent;
|
||||||
|
- `recv`: what the host sent;
|
||||||
|
- `note`: an observation;
|
||||||
|
- `parse_error`: the parser's error plus the bytes that caused it (hex or text, capped at 4 KiB);
|
||||||
|
- `stop`: the stop-and-report rule fired;
|
||||||
|
- `summary`: the end-of-step counters.
|
||||||
|
- **`u`:** the UNKNOWNs the record bears on.
|
||||||
|
- **Filtering** (PowerShell):
|
||||||
|
`Get-Content log.jsonl | ConvertFrom-Json | ? { $_.u -contains 'U5' } | ConvertTo-Json -Depth 8`.
|
||||||
|
- **Run folder contents:**
|
||||||
|
- `video.h264` (or `.h265`): the first `--dump-frames` frames' Annex-B elementary stream, for `ffprobe` later.
|
||||||
|
The probe decodes nothing.
|
||||||
|
- `video-packets.bin`: plaintext video packets, `--dump-packets` of them.
|
||||||
|
- `audio-packets.bin`: audio datagrams as received.
|
||||||
|
|
||||||
|
The `.bin` files use the format in `tools/gs-probe/src/dump.rs`. **The video files hold frames of Mark's game:**
|
||||||
|
they never go into git and are deleted after analysis.
|
||||||
|
|
||||||
|
## 5. From the log to PROTOCOL.md and the code
|
||||||
|
|
||||||
|
1. **Facts first.** Each settled UNKNOWN gets its fact in PROTOCOL.md with the tag `[L2]` (live sitting, date,
|
||||||
|
Sunshine `v2026.914.233613`, probe commit). Add the tag to the tag table and the row to §8. An UNKNOWN that stays
|
||||||
|
open says why.
|
||||||
|
2. **Tests before code** (repo rule). Every fact becomes a unit test or vector in `crates/domistream`:
|
||||||
|
- structure and constants only;
|
||||||
|
- re-encrypted with keys generated in the test;
|
||||||
|
- never bytes of Mark's video.
|
||||||
|
3. **Where each U lands:**
|
||||||
|
|
||||||
|
| U | PROTOCOL.md | Code |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| U1, U28 | 1.5 | `pairing/mod.rs` (`request`, step order) |
|
||||||
|
| U2 | 1.5 | `pairing/identity.rs` (`generate`) |
|
||||||
|
| U4 | 1.4 | `http/launch.rs` (`launch_request`, the `sessionUrl0` default) |
|
||||||
|
| U5 | 2.1, 2.2 | `rtsp/mod.rs` (`RtspFramer`), `rtsp/client.rs` (`CLIENT_VERSION`, `SETUP_TARGETS`, `TRANSPORT`, `Session` echo, PLAY target) |
|
||||||
|
| U6 | 2.4 | `rtsp/sdp.rs` (`build_announce`) |
|
||||||
|
| U7 | 2.2 | `rtsp/client.rs` (`advance`, `NegotiatedStream`) |
|
||||||
|
| U8 | 5.1, 6.1 | `rtsp/client.rs` (`PING_PAYLOAD`); the ping interval in the platform layer's docs |
|
||||||
|
| U9 | 3.1 | the `EnetConfig` defaults the callers use (docs in `enet/mod.rs`); `enet/protocol.rs` only if the host sends something stock 1.3 lacks |
|
||||||
|
| U10 | 3.3 | `control/message.rs` (`encode_client_message`: START_A, START_B, PERIODIC_PING, IDR bodies instead of `Unsupported`), `control/mod.rs` (send PERIODIC_PING on `ping_interval`) |
|
||||||
|
| U11 | 3.2 | `control/mod.rs` (`next_sequence` start, replay rule) |
|
||||||
|
| U13, U15 | 5.2 | `video/packet.rs` (docs, `FrameHeader`) |
|
||||||
|
| U14 | 5.3 | `fec.rs`: confirmed, nothing to change (or stop and report if `u14_no_match`) |
|
||||||
|
| U16 | 6.4 | a `pub const` parity matrix in `audio/mod.rs`, used as `AudioFec::ParityMatrix` by the callers |
|
||||||
|
| U17 | 6.3 | `AudioConfig.cipher` policy (docs in `audio/mod.rs`) |
|
||||||
|
| U19 | 7 | `video/mod.rs` (`VideoCipher::decrypt`) |
|
||||||
|
| U23 | 3.3 | `control/message.rs` (host event bodies) |
|
||||||
|
| U25, U27 | 1.2, 1.1 | `http/serverinfo.rs`, `http/xml.rs` docs |
|
||||||
|
| U26 | 2.3 | `rtsp/sdp.rs` |
|
||||||
|
| U29 | 5.2 | `rtp.rs` / `video/mod.rs` docs |
|
||||||
|
|
||||||
|
4. **Re-run** clippy, fmt, rustdoc, the tests, the mutation script and the fuzz targets of the touched parsers (load
|
||||||
|
gate first).
|
||||||
|
5. **Re-run the probe** against Sunshine with the patched crate: `launch` with **no** variant flags must give
|
||||||
|
`decode_ready_frames > 0`, audio packets, and no `stop`. Then release `stream-v0.1.1` (HANDOVER).
|
||||||
|
6. **Arena:** B1–B5 answers go to Arena `docs/PLAY-REMOTELY.md` (handover, §8, §15). That file and arena-host are Play
|
||||||
|
remotely's own, so we write them; the seam files stay the Arena build lead's.
|
||||||
|
|
||||||
|
**Not settled by the probe:**
|
||||||
|
- U20, U21, U22: no keyboard, touch or gamepad input beyond the one mouse nudge.
|
||||||
|
- U24 beyond what rustls negotiates.
|
||||||
|
- U26 beyond stereo, unless the 5.1 variant runs.
|
||||||
|
- U19, if the host does not offer video encryption.
|
||||||
|
- U23, if no host event arrives.
|
||||||
|
|
||||||
|
`tools/lab-relay` cannot be used as it stands: its upstream must be loopback, and Sunshine listens on .140 only.
|
||||||
|
`--relay` is ready on the probe side if the build lead ever widens that rule. The probe's own log already holds the
|
||||||
|
plaintext of HTTP, HTTPS and RTSP, and the decrypted control messages.
|
||||||
|
|
||||||
|
## 6. Stop and report
|
||||||
|
|
||||||
|
**Stop** means: no further probe command, no Sunshine call beyond read-only GETs, no retry outside table V. Report to
|
||||||
|
the coordinator:
|
||||||
|
- the step;
|
||||||
|
- the log path and the record number `n`;
|
||||||
|
- what was expected;
|
||||||
|
- what was seen.
|
||||||
|
|
||||||
|
Then wait.
|
||||||
|
|
||||||
|
**Stop when:**
|
||||||
|
- a probe command exits with code 3 (a `stop` record), or with 1;
|
||||||
|
- anything appears on Mark's screen beyond section 1's list, or Mark asks to stop;
|
||||||
|
- any socket of the probe or of Sunshine talks to an address other than `192.168.100.140` or loopback;
|
||||||
|
- Sunshine crashes, restarts, or its notifications show an error;
|
||||||
|
- the game misbehaves, or the PC slows down noticeably;
|
||||||
|
- an answer fits none of the expectations above, even if the probe accepted it;
|
||||||
|
- table V is used up (6 launches), or a variant would need a code change, a Sunshine setting or an install;
|
||||||
|
- a secret shows up anywhere it should not (terminal, log, file name). Stop at once and delete the record.
|
||||||
|
|
||||||
|
## 7. Clean-up (same sitting)
|
||||||
|
|
||||||
|
1. `& $P quit --host $H --out $O`, if a game is still running.
|
||||||
|
2. `& $P unpair --host $H --out $O`, then B2 again: the client list no longer shows the probe.
|
||||||
|
3. Delete `$O\identity\` (the probe's test key).
|
||||||
|
4. **The run folders stay** until the facts are in PROTOCOL.md and the tests are in. Then they are deleted on the
|
||||||
|
build lead's word. `video.*` and `video-packets.bin` go first, right after the U13/U14/U15/U29 analysis.
|
||||||
|
5. Nothing to undo on Sunshine, arena-host or the firewall: nothing was changed.
|
||||||
|
|
||||||
|
## 8. Timeline for Mark (about 20 minutes)
|
||||||
|
|
||||||
|
| When | What happens | Mark |
|
||||||
|
| :-- | :-- | :-- |
|
||||||
|
| 0:00 | S0, S1: read-only checks, `serverinfo` | nothing |
|
||||||
|
| 0:02 | S2: the probe pairs (we submit the PIN through Sunshine's API). Sunshine may show a notification | nothing |
|
||||||
|
| 0:05 | S3, S4: the agreed game starts on his PC and streams to the probe for 90 s; then we close it | hands off mouse and keyboard while it runs |
|
||||||
|
| 0:07-0:15 | Variants, only if needed (up to 6 launches, each about 1 min) | same |
|
||||||
|
| 0:15 | S5 (optional), clean-up | nothing |
|
||||||
|
| later | Analysis offline; the game frames are deleted | nothing |
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Mutation pass
|
||||||
|
|
||||||
|
Each row puts back one bug a test is meant to guard against (an exact edit to `crates/domistream/src`), runs the
|
||||||
|
test binary that should catch it, and reverts the edit. "Caught by" lists the tests that failed. All 24 rows were
|
||||||
|
caught; none failed to compile, so every row is a real behaviour change the tests saw.
|
||||||
|
|
||||||
|
- **When:** 2026-11-26, QA, on `feature/client` at `d62aa8f`. The baseline was 242/242 tests passing.
|
||||||
|
- **Driver:** [`tools/mutation/mutate.py`](../tools/mutation/mutate.py) holds the exact edits, so the pass can be
|
||||||
|
rerun: `python tools/mutation/mutate.py [M1 ...]`. Every cargo run goes through the resource gate (CPU, RAM and
|
||||||
|
drives below 90 %, `-j 2`).
|
||||||
|
|
||||||
|
| # | Area | Mutation | Test binary | Caught by | Result |
|
||||||
|
| :-- | :-- | :-- | :-- | :-- | :-- |
|
||||||
|
| M1 | XML cap | size cap off by one (refuses exactly `MAX_XML_BYTES`) | http | `xml_size_boundaries`, `applist_caps` | caught |
|
||||||
|
| M2 | XML cap | depth cap off by one (allows depth 9) | http | `xml_depth_cap`, `xml_depth_bomb_does_not_recurse` | caught |
|
||||||
|
| M3 | RTSP cap | header cap off by one (allows 65 headers) | rtsp | `response_header_flood` | caught |
|
||||||
|
| M4 | ENet cap | command cap off by one (allows 33 commands) | enet | `hostile_sizes` | caught |
|
||||||
|
| M5 | Input cap | message size cap removed | input | `hostile_sizes` | caught |
|
||||||
|
| M6 | Video cap | packet size cap off by one (accepts 4097 bytes) | media | `video_packet_hostile_sizes` | caught |
|
||||||
|
| M7 | Audio cap | packet size cap removed | media | `audio_packet_hostile` | caught |
|
||||||
|
| M8 | Lying length | control frame: a length field that claims less is accepted | control | `frame_parser_lying_lengths` | caught |
|
||||||
|
| M9 | Lying length | RTSP: bytes after `Content-Length` kept instead of refused | rtsp | `response_lying_content_length` | caught |
|
||||||
|
| M10 | Lying length | INPUT_DATA: the big-endian size field not checked | input | `lying_length_and_size_fields` | caught |
|
||||||
|
| M11 | ENet wrap | reliable delivery does not wrap at 0xFFFF (saturating "next") | enet | `reliable_sequence_wraps_at_0xffff` | caught |
|
||||||
|
| M12 | Control replay | a repeated sequence number accepted (`<` instead of `<=`) | control | `replayed_and_old_host_frames_are_dropped` | caught |
|
||||||
|
| M13 | Control replay | the replay check removed | control | `replayed_and_old_host_frames_are_dropped`, `host_sequence_at_u32_wrap` | caught |
|
||||||
|
| M14 | Nonce | direction bytes swapped (`'H'` client to host) | control | `nonce_layout`, `nonce_matches_the_definition`, `seal_matches_dotnet_vectors`, `wrong_direction_and_wrong_key_are_refused` | caught |
|
||||||
|
| M15 | GCM tag | control `open` ignores a failed tag check | control | `tampering_is_refused`, `tampered_and_reflected_frames_are_dropped`, `open_never_accepts_random_frames`, `wrong_direction_and_wrong_key_are_refused` | caught |
|
||||||
|
| M24 | GCM tag | video `decrypt` ignores a failed tag check | media | `video_decrypt_refuses` | caught |
|
||||||
|
| M16 | FEC index | a video parity shard stored one index too high | video | 12 tests, e.g. `random_loss`, `all_data_lost_but_recoverable`, `recovered_shard_headers_are_not_trusted`, `generated_patterns` | caught |
|
||||||
|
| M17 | Video header | bytes 0-31 of a rebuilt shard trusted (whole-packet shards, start-of-frame flag read from a rebuilt shard) | video | 9 tests, e.g. `recovered_shard_headers_are_not_trusted`, `all_data_lost_but_recoverable`, `random_loss` | caught |
|
||||||
|
| M18 | Audio parity | parity keyed by its own RTP sequence instead of the FEC header's base | audio | 9 tests, e.g. `every_loss_pattern_of_a_block`, `sequence_wraps`, `hostile_parity_never_corrupts` | caught |
|
||||||
|
| M19 | Pairing skip | no `pairingsecret`: proof and signature skipped, straight to step 4 | pairing | `a_bare_paired_answer_cannot_skip_any_step`, `out_of_order_answers_fail`, `replaying_the_same_answer_twice_fails` | caught |
|
||||||
|
| M20 | Signature | the host's signature over its secret not checked | pairing | `bad_host_signatures` | caught |
|
||||||
|
| M21 | Signature | `ServerCert::verify` accepts any signature | pairing | `bad_host_signatures`, `server_cert_verify_refuses` | caught |
|
||||||
|
| M22 | Sans-I/O | `std::time::Instant::now()` added in `src/time.rs` | hygiene | `src_is_sans_io` | caught |
|
||||||
|
| M23 | OS randomness | `getrandom` added as a dependency and used in `src/entropy.rs` | hygiene | `src_is_sans_io` | caught |
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- **M17.** The video receiver keeps only the payloads (bytes 32 on) of each shard and rebuilds from those, so as
|
||||||
|
written it cannot read a rebuilt shard's header. The mutation therefore first switches it to whole-packet shards,
|
||||||
|
then makes it trust one header field of a rebuilt shard. `recovered_shard_headers_are_not_trusted` and the other
|
||||||
|
loss tests catch it.
|
||||||
|
- **M23.** The mutation compiled, against the cached getrandom 0.4.3, and the guard caught the source use. Since
|
||||||
|
27b26a9 the dependency tree has no getrandom at all.
|
||||||
|
- **Missing tests.** No mutation got through, so none were added.
|
||||||
+64
-29
@@ -2,7 +2,9 @@
|
|||||||
|
|
||||||
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
|
The protocol between a GameStream host (Sunshine, later Lumen) and a client (Arena Domi TV). Written from the Wolf
|
||||||
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
|
protocol docs in our own words, completed with facts read in Moonshine (BSD-2). Every fact has a tag; every gap is
|
||||||
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, Phase A (docs + API, no logic yet).
|
marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, implemented as stream-v0.1.0 per these docs and the approved sources; interop with a real host
|
||||||
|
is unverified (the lab capture was not run, [LAB_CAPTURE.md](LAB_CAPTURE.md)). U9 narrowed and U14 settled from the
|
||||||
|
approved sources (sections 3.1, 5.3); where an UNKNOWN remains, the code follows the Wolf-documented behaviour.
|
||||||
|
|
||||||
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
**Tags** (details in the source log, [CLEAN_ROOM.md](CLEAN_ROOM.md)):
|
||||||
|
|
||||||
@@ -11,8 +13,9 @@ marked **UNKNOWN Un** with what would settle it. Status: 2026-11-25, Phase A (do
|
|||||||
| [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) |
|
| [W1]-[W7] | Wolf docs: index, pairing, RTSP, control, RTP video, RTP Opus, input (S-1 to S-7) |
|
||||||
| [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. |
|
| [M] | Moonshine `f184d5e` (S-9). A host implementation: we mirror its behaviour for the client. |
|
||||||
| [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. |
|
| [M*] | Moonshine, but the value has GPL provenance (Moonshine cites Sunshine or moonlight-common-c). Confirm by measurement before use. |
|
||||||
| [T] | tokio-enet `364628e` (S-10), pending approval as a source |
|
| [T] | tokio-enet `364628e` (S-10), approved 2026-11-25 |
|
||||||
| [F] | fec-rs README (S-13) |
|
| [E] | stock ENet v1.3.18 `2662c0d` (S-17), MIT, approved 2026-11-25 |
|
||||||
|
| [F] | fec-rs README and source `402f41f` (S-13, S-18), BSD-2, approved 2026-11-25 |
|
||||||
| [RFC n] | the RFC |
|
| [RFC n] | the RFC |
|
||||||
|
|
||||||
**Not in DomiStream:** sockets, TLS, the clock, video decoding and **Opus decoding**. DomiStream hands the platform
|
**Not in DomiStream:** sockets, TLS, the clock, video decoding and **Opus decoding**. DomiStream hands the platform
|
||||||
@@ -226,25 +229,46 @@ Source: [Wolf: control](https://games-on-whales.github.io/wolf/stable/protocols/
|
|||||||
|
|
||||||
### 3.1 ENet
|
### 3.1 ENet
|
||||||
|
|
||||||
The control stream runs over a custom fork of ENet supporting IPv4 and IPv6 [W4]. What is known about the wire,
|
The control stream runs over a custom fork of ENet supporting IPv4 and IPv6 [W4]. The wire is stock ENet 1.3 [E][T]
|
||||||
from stock ENet 1.3 as tokio-enet implements it [T] (all multi-byte fields big-endian):
|
(all multi-byte fields big-endian):
|
||||||
|
|
||||||
- Datagram = protocol header + up to 32 commands. Header: `peer_id u16` whose top bits are flags (`1<<15` sent time
|
- **Datagram** = protocol header + up to 32 commands [E]. Header: `peer_id u16` whose bits 15 and 14 are flags (`1<<15`
|
||||||
present, `1<<14` compressed) and bits 12-13 the session id; then `sent_time u16` if flagged.
|
sent time present, `1<<14` compressed) and bits 12-13 the session id; then `sent_time u16` (low 16 bits of the
|
||||||
- Command header (4 bytes): `command u8` (low 4 bits type, `0x80` acknowledge wanted, `0x40` unsequenced),
|
sender's millisecond clock) if flagged [E]. Peer id `0xFFF` = "no peer yet" (the connect datagram) [E].
|
||||||
`channel_id u8`, `reliable_sequence u16`.
|
- **Checksum** [E]: optional, a setting of the host on *both* ends; when on, 4 bytes follow the header (crc32 over the
|
||||||
- Commands and total sizes: 1 acknowledge (8), 2 connect (48), 3 verify connect (44), 4 disconnect (8), 5 ping (4),
|
datagram with the field first set to the peer's connect id). **Nothing on the wire says whether it is on**, so both
|
||||||
6 send reliable (6 + data), 7 send unreliable (8 + data), 8 send fragment (24 + data), 9 send unsequenced (8 + data),
|
ends must agree.
|
||||||
10 bandwidth limit (12), 11 throttle configure (16), 12 send unreliable fragment (24 + data).
|
- **Command header** (4 bytes): `command u8` (low 4 bits type, `0x80` acknowledge wanted, `0x40` unsequenced),
|
||||||
- MTU 576-4096, window 4096-65536, channels 1-255, peer id ≤ 0xFFF.
|
`channel_id u8` (`0xFF` for connection-level commands), `reliable_sequence u16` [E].
|
||||||
|
- **Commands and total sizes** [E]: 1 acknowledge (8: received reliable sequence, received sent time),
|
||||||
|
2 connect (48), 3 verify connect (44), 4 disconnect (8: data u32), 5 ping (4), 6 send reliable (6 + data),
|
||||||
|
7 send unreliable (8 + data), 8 send fragment (24 + data: start sequence, data length, fragment count, fragment
|
||||||
|
number, total length, fragment offset), 9 send unsequenced (8 + data: unsequenced group), 10 bandwidth limit (12),
|
||||||
|
11 throttle configure (16), 12 send unreliable fragment (24 + data).
|
||||||
|
- **Connect** fields [E]: outgoing peer id u16, incoming and outgoing session id u8 (a stock client sends `0xFF` for
|
||||||
|
both, "pick one"), MTU, window size, channel count, incoming and outgoing bandwidth, throttle interval, acceleration,
|
||||||
|
deceleration, connect id (random), data u32. Verify connect has the same fields without `data`; the connect id must
|
||||||
|
match [E].
|
||||||
|
- **Limits** [E]: MTU 576-4096, window 4096-65536, channels 1-255, peer id ≤ 0xFFF, at most 1024 × 1024 fragments.
|
||||||
|
- **Stock defaults** [E]: MTU 1392; window 65536 when bandwidth is unlimited; ping every 500 ms when idle;
|
||||||
|
retransmission timeout = RTT + 4 × RTT variance (initial RTT 500 ms), doubling per retry; a peer is dropped when
|
||||||
|
the oldest unacknowledged command is 30 s old, or once it has been sent 6 times (`2^(attempts-1) ≥ 32`, the
|
||||||
|
timeout limit) and is at least 5 s old.
|
||||||
|
|
||||||
How the host uses it [M]: one peer per session; host created with a channel limit of 0x30; every host message is sent
|
How the host uses it [M]: one peer per session; host created with a channel limit of 0x30; every host message is sent
|
||||||
**reliable on channel 0**. Moonshine does this with stock-wire ENet and real Moonlight clients (see
|
**reliable on channel 0**. Moonshine does this with stock-wire ENet and real Moonlight clients (see
|
||||||
[research/open-point-2.md](research/open-point-2.md)).
|
[research/open-point-2.md](research/open-point-2.md)).
|
||||||
|
|
||||||
UNKNOWN U9: anything Sunshine's ENet sends that stock 1.3 does not (checksum, compression, header or connect field
|
What follows without a capture (our reasoning on [E][T][M]):
|
||||||
differences); the channel count, MTU and `connect data` the client should offer; ping interval and timeouts.
|
- tokio-enet has no checksum and Moonlight clients work with it, so **Moonlight clients run without the checksum**.
|
||||||
Settle: lab capture of one session, decoded with our parser.
|
The checksum must match on both ends, and Sunshine works with the same clients, so **Sunshine runs without it too**.
|
||||||
|
Same reasoning for compression: a client that compressed would fail against tokio-enet without a compressor.
|
||||||
|
- So everything a Moonlight client *sends* parses as stock 1.3. What stays open is only what the fork might add on the
|
||||||
|
host's *sending* side, which the fork-aware client accepts and a stock parser might not.
|
||||||
|
|
||||||
|
UNKNOWN U9 (narrowed): anything Sunshine's ENet sends that stock 1.3 does not; the channel count, MTU and `connect
|
||||||
|
data` a client offers; whether the client sets non-default ping or timeout values. Settle: the lab capture's control
|
||||||
|
port datagrams, decoded with our parser (LAB_CAPTURE.md). Until then our client offers stock defaults.
|
||||||
|
|
||||||
### 3.2 Encrypted frame
|
### 3.2 Encrypted frame
|
||||||
|
|
||||||
@@ -274,13 +298,13 @@ Every control message is wrapped [W4] (little-endian):
|
|||||||
|
|
||||||
| Type | Name | Direction | Body |
|
| Type | Name | Direction | Body |
|
||||||
| :-- | :-- | :-- | :-- |
|
| :-- | :-- | :-- | :-- |
|
||||||
| 0x0305 | START_A | client → host | UNKNOWN U10 |
|
| 0x0305 | START_A | client → host | UNKNOWN U10. Moonshine has no such type; inside the encrypted frame it skips an unknown type [M] |
|
||||||
| 0x0307 | START_B | client → host | UNKNOWN U10. The host starts video and audio when it arrives [M] |
|
| 0x0307 | START_B | client → host | Moonshine reads no body [M]. The host starts video and audio when it arrives [M]; Moonshine's video receiver (and so its PING handling) only runs from then on [M] |
|
||||||
| 0x0200 | PERIODIC_PING | client → host | UNKNOWN U10. Keeps the session alive; the host stops after a timeout without one [M] |
|
| 0x0200 | PERIODIC_PING | client → host | Moonshine reads no body [M]. Each one pushes the host's stop deadline out; Moonshine stops a stream after 60 s without one (its default) [M] |
|
||||||
| 0x0201 | LOSS_STATS | client → host | UNKNOWN U10 |
|
| 0x0201 | LOSS_STATS | client → host | Moonshine ignores it [M]; body UNKNOWN U10 |
|
||||||
| 0x0204 | FRAME_STATS | client → host | UNKNOWN U10 |
|
| 0x0204 | FRAME_STATS | client → host | Moonshine ignores it [M]; body UNKNOWN U10 |
|
||||||
| 0x0206 | INPUT_DATA | client → host | section 4 |
|
| 0x0206 | INPUT_DATA | client → host | section 4 |
|
||||||
| 0x0302 | IDR_FRAME (request) | client → host | UNKNOWN U10 (Moonshine ignores the body) |
|
| 0x0302 | IDR_FRAME (request) | client → host | Moonshine reads no body [M] |
|
||||||
| 0x0301 | INVALIDATE_REF_FRAMES | client → host | `first u32`, `reserved u32`, `last u32`, `reserved 12 bytes`, LE [M] |
|
| 0x0301 | INVALIDATE_REF_FRAMES | client → host | `first u32`, `reserved u32`, `last u32`, `reserved 12 bytes`, LE [M] |
|
||||||
| 0x0100 | TERMINATION | host → client | UNKNOWN U10 |
|
| 0x0100 | TERMINATION | host → client | UNKNOWN U10 |
|
||||||
| 0x0109 | TERMINATION (extended) | host → client | `error_code u32 BE`; `0x80030023` = graceful [M] |
|
| 0x0109 | TERMINATION (extended) | host → client | `error_code u32 BE`; `0x80030023` = graceful [M] |
|
||||||
@@ -293,6 +317,11 @@ Every control message is wrapped [W4] (little-endian):
|
|||||||
|
|
||||||
UNKNOWN U23: Wolf states "all data is little-endian" for the frame; we assume LE for the host event bodies too.
|
UNKNOWN U23: Wolf states "all data is little-endian" for the frame; we assume LE for the host event bodies too.
|
||||||
|
|
||||||
|
How Moonshine treats what a client sends on control [M]: a message whose type it does not know, or whose length field
|
||||||
|
does not match, **ends the session** when it arrives outside the encrypted frame; inside the encrypted frame the same
|
||||||
|
message is skipped, and so is a frame that fails decryption. Whether Sunshine reads bodies (and which) is what U10
|
||||||
|
still settles live: the probe sends empty bodies first ([LIVE-INTEROP.md](LIVE-INTEROP.md), table V).
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 4. Input and gamepad packets
|
## 4. Input and gamepad packets
|
||||||
@@ -432,9 +461,14 @@ Reed-Solomon erasure code over GF(2^8), polynomial `0x11D` [F] [W5]:
|
|||||||
[W5] and their RTP and NV header fields are written **after** the parity is computed [M], so parity bytes 0-31 are
|
[W5] and their RTP and NV header fields are written **after** the parity is computed [M], so parity bytes 0-31 are
|
||||||
not parity. Consequence for the receiver: a recovered data shard's bytes 0-31 are garbage; use only its payload
|
not parity. Consequence for the receiver: a recovered data shard's bytes 0-31 are garbage; use only its payload
|
||||||
(offset 32 on) and take its place from the shard index.
|
(offset 32 on) and take its place from the shard index.
|
||||||
- UNKNOWN U14: the generator matrix (systematic construction). fec-rs (BSD-2) claims Moonlight compatibility [F].
|
- **Matrix (U14, settled from [F], to be confirmed by the capture):** systematic: the data shards pass through, and
|
||||||
Settle: approve fec-rs as a source and read its construction, or measure: capture blocks with known losses and
|
parity shard `j` (0..m) is `Σ_i P[j][i] · data_i` with the Cauchy matrix `P[j][i] = 1 / ((m + i) XOR j)` over
|
||||||
check our decoder against them.
|
GF(2^8), polynomial `0x11D`, generator 2 [F]. Nothing in the Wolf docs contradicts this: they only say Reed-Solomon
|
||||||
|
with parity blocks [W5]. Examples (our own arithmetic): `k = 4, m = 2`:
|
||||||
|
`P = [[8e f4 47 a7], [f4 8e a7 47]]`; `k = 3, m = 1`: `P = [[01 8e f4]]`.
|
||||||
|
The capture settles it without any loss: parity packets are always sent, so our encoder must reproduce the
|
||||||
|
captured parity bytes (offset 32 on) of every block.
|
||||||
|
- The audio code is **not** this matrix (section 6.4).
|
||||||
|
|
||||||
### 5.4 Feedback
|
### 5.4 Feedback
|
||||||
|
|
||||||
@@ -482,7 +516,8 @@ Every 4 data packets are followed by 2 parity packets [W6]. A block is the 4 dat
|
|||||||
start at a multiple of 4 [M]; the base sequence and timestamp in the FEC header are the first data packet's [M].
|
start at a multiple of 4 [M]; the base sequence and timestamp in the FEC header are the first data packet's [M].
|
||||||
Shards are the encrypted payloads (all 4 the same length, constant-bitrate Opus) [M]. A lost data packet is rebuilt
|
Shards are the encrypted payloads (all 4 the same length, constant-bitrate Opus) [M]. A lost data packet is rebuilt
|
||||||
from any 4 of the 6 packets; its RTP header comes from the base values (sequence = base + index, timestamp = base +
|
from any 4 of the 6 packets; its RTP header comes from the base values (sequence = base + index, timestamp = base +
|
||||||
index × duration) [M].
|
index × duration) [M]. DomiStream waits for the jitter budget (`loss_timeout`) before rebuilding a missing packet,
|
||||||
|
so a packet that arrives late is played as sent rather than as a rebuilt copy.
|
||||||
|
|
||||||
UNKNOWN U16 (blocks audio FEC): the parity matrix. It is a fixed 2 × 4 matrix over GF(2^8), **not** the default
|
UNKNOWN U16 (blocks audio FEC): the parity matrix. It is a fixed 2 × 4 matrix over GF(2^8), **not** the default
|
||||||
construction of the RS library Moonshine uses [M]. The only value we have seen carries GPL provenance and is not
|
construction of the RS library Moonshine uses [M]. The only value we have seen carries GPL provenance and is not
|
||||||
@@ -538,11 +573,11 @@ client and Sunshine on a lab machine, not Mark's PC, his Sunshine or his TV); th
|
|||||||
| U6 | ANNOUNCE attributes and values Sunshine requires | B | capture, then vary one at a time |
|
| U6 | ANNOUNCE attributes and values Sunshine requires | B | capture, then vary one at a time |
|
||||||
| U7 | Extra headers in SETUP replies | B | capture |
|
| U7 | Extra headers in SETUP replies | B | capture |
|
||||||
| U8 | UDP ping payload and repeat interval | B | capture |
|
| U8 | UDP ping payload and repeat interval | B | capture |
|
||||||
| U9 | ENet differences from stock 1.3; client's channel count, MTU, connect data; ping/timeouts | B | capture, decode with our parser |
|
| U9 | Narrowed (3.1): only what Sunshine's ENet may add when *sending*; the client's channel count, MTU, connect data | B | capture, decode with our parser |
|
||||||
| U10 | Bodies of START_A, START_B, PERIODIC_PING, LOSS_STATS, FRAME_STATS, IDR request, TERMINATION; ping interval | B | capture, decrypted with the session's `rikey` |
|
| U10 | Narrowed (3.3): Moonshine reads no body from START_B, PERIODIC_PING or the IDR request and ignores START_A, LOSS_STATS and FRAME_STATS; what Sunshine reads, the ping interval it needs, TERMINATION's body | B | live sitting: empty bodies first, then the hex variants |
|
||||||
| U11 | First control sequence number; host's replay rules | | capture |
|
| U11 | First control sequence number; host's replay rules | | capture |
|
||||||
| U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture |
|
| U13 | Video frame header: Wolf's constant or Moonshine's fields | | capture |
|
||||||
| U14 | Video RS generator matrix | B (for FEC; video plays without it at zero loss) | read fec-rs (approval) or capture with loss |
|
| U14 | Video RS matrix: **settled** (5.3, Cauchy from fec-rs) | | capture confirms: our parity = captured parity |
|
||||||
| U15 | Multi-FEC flags `0x10` | | capture |
|
| U15 | Multi-FEC flags `0x10` | | capture |
|
||||||
| U16 | Audio RS parity matrix | (audio plays without it) | capture, solve over GF(2^8) |
|
| U16 | Audio RS parity matrix | (audio plays without it) | capture, solve over GF(2^8) |
|
||||||
| U17 | Audio encryption always or only when negotiated | B | capture |
|
| U17 | Audio encryption always or only when negotiated | B | capture |
|
||||||
|
|||||||
Generated
-52
@@ -153,7 +153,6 @@ checksum = "914c195c4d7fbc5ed7f88d14cbf85914d5c664967658d43404b263913a477e82"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"cpubits",
|
"cpubits",
|
||||||
"ctutils",
|
"ctutils",
|
||||||
"getrandom",
|
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
"serdect",
|
"serdect",
|
||||||
@@ -166,7 +165,6 @@ version = "0.2.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"getrandom",
|
|
||||||
"hybrid-array",
|
"hybrid-array",
|
||||||
"rand_core",
|
"rand_core",
|
||||||
]
|
]
|
||||||
@@ -280,7 +278,6 @@ dependencies = [
|
|||||||
"cfg-if",
|
"cfg-if",
|
||||||
"libc",
|
"libc",
|
||||||
"r-efi",
|
"r-efi",
|
||||||
"rand_core",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -485,17 +482,6 @@ dependencies = [
|
|||||||
"serde",
|
"serde",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "sha1"
|
|
||||||
version = "0.11.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214"
|
|
||||||
dependencies = [
|
|
||||||
"cfg-if",
|
|
||||||
"cpufeatures",
|
|
||||||
"digest",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "sha2"
|
name = "sha2"
|
||||||
version = "0.11.1"
|
version = "0.11.1"
|
||||||
@@ -555,27 +541,6 @@ dependencies = [
|
|||||||
"unicode-ident",
|
"unicode-ident",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "0de2e01245e2bb89d6f05801c564fa27624dbd7b1846859876c7dad82e90bf6b"
|
|
||||||
dependencies = [
|
|
||||||
"tls_codec_derive",
|
|
||||||
"zeroize",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "tls_codec_derive"
|
|
||||||
version = "0.4.2"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "typenum"
|
name = "typenum"
|
||||||
version = "1.20.1"
|
version = "1.20.1"
|
||||||
@@ -606,10 +571,7 @@ checksum = "e9f58ad685a2945c7c063f5d69b5c27105d75bb85c740380d8fc64e79a098417"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"const-oid",
|
"const-oid",
|
||||||
"der",
|
"der",
|
||||||
"sha1",
|
|
||||||
"signature",
|
|
||||||
"spki",
|
"spki",
|
||||||
"tls_codec",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -617,17 +579,3 @@ name = "zeroize"
|
|||||||
version = "1.9.2"
|
version = "1.9.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
||||||
dependencies = [
|
|
||||||
"zeroize_derive",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "zeroize_derive"
|
|
||||||
version = "1.5.0"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"
|
|
||||||
dependencies = [
|
|
||||||
"proc-macro2",
|
|
||||||
"quote",
|
|
||||||
"syn 2.0.119",
|
|
||||||
]
|
|
||||||
|
|||||||
Generated
+692
@@ -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"
|
||||||
@@ -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"
|
||||||
@@ -0,0 +1,453 @@
|
|||||||
|
//! 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
|
||||||
|
Control message bodies (U10; defaults from Moonshine, which reads no body from any of them, PROTOCOL.md 3.3):
|
||||||
|
--start-a <hex|empty|none> empty --start-b <hex|empty|none> empty
|
||||||
|
--periodic-ping <hex|empty|none> empty --periodic-ping-ms <n> 500
|
||||||
|
--idr <hex|empty|none> empty (IDR request on frame loss, unless --rfi and the host offers invalidation)
|
||||||
|
--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::Bytes(Vec::new()),
|
||||||
|
periodic_ping_ms: 500,
|
||||||
|
idr: Body::Bytes(Vec::new()),
|
||||||
|
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![]));
|
||||||
|
// U10 candidates (PROTOCOL.md 3.3): every body empty, a ping every 500 ms.
|
||||||
|
assert_eq!(
|
||||||
|
(o.start_b, o.periodic_ping, o.idr),
|
||||||
|
(Body::Bytes(vec![]), Body::Bytes(vec![]), Body::Bytes(vec![]))
|
||||||
|
);
|
||||||
|
assert_eq!(o.periodic_ping_ms, 500);
|
||||||
|
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 none --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::None));
|
||||||
|
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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(())
|
||||||
|
}
|
||||||
@@ -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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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"));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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(¶ms, "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>");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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())
|
||||||
|
}
|
||||||
@@ -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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
@@ -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))
|
||||||
|
}
|
||||||
Generated
+208
@@ -0,0 +1,208 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cc"
|
||||||
|
version = "1.11.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
|
||||||
|
dependencies = [
|
||||||
|
"find-msvc-tools",
|
||||||
|
"shlex",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg-if"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "find-msvc-tools"
|
||||||
|
version = "0.1.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "getrandom"
|
||||||
|
version = "0.2.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"wasi",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lab-relay"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"ring",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pki-types",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libc"
|
||||||
|
version = "0.2.191"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "once_cell"
|
||||||
|
version = "1.21.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ring"
|
||||||
|
version = "0.17.14"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||||
|
dependencies = [
|
||||||
|
"cc",
|
||||||
|
"cfg-if",
|
||||||
|
"getrandom",
|
||||||
|
"libc",
|
||||||
|
"untrusted",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls"
|
||||||
|
version = "0.23.46"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||||
|
dependencies = [
|
||||||
|
"once_cell",
|
||||||
|
"ring",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"rustls-webpki",
|
||||||
|
"subtle",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls-pki-types"
|
||||||
|
version = "1.16.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||||
|
dependencies = [
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustls-webpki"
|
||||||
|
version = "0.103.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
|
||||||
|
dependencies = [
|
||||||
|
"ring",
|
||||||
|
"rustls-pki-types",
|
||||||
|
"untrusted",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "shlex"
|
||||||
|
version = "2.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "subtle"
|
||||||
|
version = "2.6.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "untrusted"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasi"
|
||||||
|
version = "0.11.1+wasi-snapshot-preview1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.52.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||||
|
dependencies = [
|
||||||
|
"windows-targets",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-targets"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||||
|
dependencies = [
|
||||||
|
"windows_aarch64_gnullvm",
|
||||||
|
"windows_aarch64_msvc",
|
||||||
|
"windows_i686_gnu",
|
||||||
|
"windows_i686_gnullvm",
|
||||||
|
"windows_i686_msvc",
|
||||||
|
"windows_x86_64_gnu",
|
||||||
|
"windows_x86_64_gnullvm",
|
||||||
|
"windows_x86_64_msvc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnu"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnu"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zeroize"
|
||||||
|
version = "1.9.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# lab-relay: our own logging relay for the one lab capture (docs/LAB_CAPTURE.md). A tool, never published, never part
|
||||||
|
# of the domistream crate. Its own workspace so it never joins the main build.
|
||||||
|
[package]
|
||||||
|
name = "lab-relay"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2024"
|
||||||
|
rust-version = "1.89"
|
||||||
|
license = "CPAL-1.0"
|
||||||
|
publish = false
|
||||||
|
|
||||||
|
[workspace]
|
||||||
|
members = ["."]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
# TLS termination on the HTTPS port with lab-only keys. ring backend: pure Rust + asm, builds with MSVC.
|
||||||
|
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||||
|
rustls-pki-types = { version = "1", features = ["std"] }
|
||||||
|
ring = "0.17"
|
||||||
|
|
||||||
|
[lints.rust]
|
||||||
|
unsafe_code = "forbid"
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Lab capture: talk to the lab Sunshine's local API (docs/LAB_CAPTURE.md sections 2, 3, 5). Not elevated.
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Every call goes to https://127.0.0.2:47990 with Basic auth built in memory, no Origin/Referer header (the
|
||||||
|
documented non-browser path), TLS pinned to the lab certificate in keys\ byte for byte.
|
||||||
|
Credentials come only from DPAPI files in secrets\; they are never printed, logged or put on a command line.
|
||||||
|
|
||||||
|
-Action Rotate throwaway credentials (from lab-install.ps1) -> fresh lab credentials; deletes the throwaway
|
||||||
|
-Action Status lists paired clients and apps (names only)
|
||||||
|
-Action Pin submits the PIN Moonlight shows: -PinFile <file with 4 digits> (the file is deleted after
|
||||||
|
reading), optional -PairingId, -ClientName (default "DomiStream lab Moonlight")
|
||||||
|
-Action Logs saves GET /api/logs to captures\sunshine.log (not printed: it may hold secrets)
|
||||||
|
-Action Cleanup unpair all clients, drop the lab cert/key from the config (bind_address stays 127.0.0.2),
|
||||||
|
restart Sunshine
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[Parameter(Mandatory = $true)]
|
||||||
|
[ValidateSet('Rotate', 'Status', 'Pin', 'Logs', 'Cleanup')]
|
||||||
|
[string] $Action,
|
||||||
|
[string] $LabRoot = 'E:\build\play-remotely\lab',
|
||||||
|
[string] $PinFile,
|
||||||
|
[string] $PairingId,
|
||||||
|
[string] $ClientName = 'DomiStream lab Moonlight'
|
||||||
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version 2.0
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$BaseUrl = 'https://127.0.0.2:47990'
|
||||||
|
$keys = Join-Path $LabRoot 'keys'
|
||||||
|
$secrets = Join-Path $LabRoot 'secrets'
|
||||||
|
$captures = Join-Path $LabRoot 'captures'
|
||||||
|
$throwawayFile = Join-Path $secrets 'sunshine-throwaway.cred'
|
||||||
|
$labFile = Join-Path $secrets 'sunshine-lab.cred'
|
||||||
|
$certFile = Join-Path $keys 'sunshine-lab-cert.pem'
|
||||||
|
|
||||||
|
function Fail([string] $Why) {
|
||||||
|
Write-Host "lab-api: STOPPED: $Why"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- TLS pinning: accept exactly the lab certificate -------------------------------------------------------------
|
||||||
|
if (-not (Test-Path -LiteralPath $certFile)) { Fail "lab certificate not found: $certFile" }
|
||||||
|
$pem = Get-Content -LiteralPath $certFile -Raw
|
||||||
|
$m = [regex]::Match($pem, '-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')
|
||||||
|
if (-not $m.Success) { Fail 'lab certificate is not PEM' }
|
||||||
|
$pinnedDer = [Convert]::FromBase64String(($m.Groups[1].Value -replace '\s', ''))
|
||||||
|
|
||||||
|
if (-not ('DomiLabPin' -as [type])) {
|
||||||
|
Add-Type -TypeDefinition @'
|
||||||
|
using System;
|
||||||
|
using System.Net;
|
||||||
|
using System.Net.Security;
|
||||||
|
using System.Security.Cryptography.X509Certificates;
|
||||||
|
public static class DomiLabPin {
|
||||||
|
public static byte[] Pinned;
|
||||||
|
public static bool Check(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) {
|
||||||
|
if (cert == null || Pinned == null) return false;
|
||||||
|
byte[] raw = cert.GetRawCertData();
|
||||||
|
if (raw.Length != Pinned.Length) return false;
|
||||||
|
int diff = 0;
|
||||||
|
for (int i = 0; i < raw.Length; i++) diff |= raw[i] ^ Pinned[i];
|
||||||
|
return diff == 0;
|
||||||
|
}
|
||||||
|
public static void Install() {
|
||||||
|
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Check);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
'@
|
||||||
|
}
|
||||||
|
[DomiLabPin]::Pinned = $pinnedDer
|
||||||
|
[DomiLabPin]::Install()
|
||||||
|
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||||
|
|
||||||
|
# --- Credentials -------------------------------------------------------------------------------------------------
|
||||||
|
function Read-Cred([string] $File) {
|
||||||
|
if (-not (Test-Path -LiteralPath $File)) { Fail "credentials file not found: $File" }
|
||||||
|
$j = Get-Content -LiteralPath $File -Raw | ConvertFrom-Json
|
||||||
|
$u = New-Object Management.Automation.PSCredential('x', ($j.user | ConvertTo-SecureString))
|
||||||
|
$p = New-Object Management.Automation.PSCredential('x', ($j.password | ConvertTo-SecureString))
|
||||||
|
return @{ User = $u.GetNetworkCredential().Password; Password = $p.GetNetworkCredential().Password }
|
||||||
|
}
|
||||||
|
|
||||||
|
function Save-Cred([string] $File, [string] $User, [string] $Password) {
|
||||||
|
@{
|
||||||
|
user = (ConvertTo-SecureString -String $User -AsPlainText -Force | ConvertFrom-SecureString)
|
||||||
|
password = (ConvertTo-SecureString -String $Password -AsPlainText -Force | ConvertFrom-SecureString)
|
||||||
|
} | ConvertTo-Json | Set-Content -LiteralPath $File -Encoding ASCII
|
||||||
|
}
|
||||||
|
|
||||||
|
function New-Secret {
|
||||||
|
$bytes = New-Object byte[] 32
|
||||||
|
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
|
||||||
|
$rng.GetBytes($bytes)
|
||||||
|
$rng.Dispose()
|
||||||
|
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- One API call ------------------------------------------------------------------------------------------------
|
||||||
|
function Invoke-Sunshine([hashtable] $Cred, [string] $Method, [string] $Path, $Body, [string] $OutFile) {
|
||||||
|
$pair = [Text.Encoding]::UTF8.GetBytes($Cred.User + ':' + $Cred.Password)
|
||||||
|
$headers = @{ Authorization = 'Basic ' + [Convert]::ToBase64String($pair) }
|
||||||
|
$req = @{ Uri = $BaseUrl + $Path; Method = $Method; Headers = $headers; UseBasicParsing = $true; TimeoutSec = 30 }
|
||||||
|
if ($null -ne $Body) {
|
||||||
|
$req.Body = ($Body | ConvertTo-Json -Depth 5 -Compress)
|
||||||
|
$req.ContentType = 'application/json'
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if ($OutFile) {
|
||||||
|
Invoke-WebRequest @req -OutFile $OutFile | Out-Null
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
return Invoke-RestMethod @req
|
||||||
|
} catch {
|
||||||
|
# The message names the call only; the request, which holds the credentials, is never echoed.
|
||||||
|
Fail "$Method $Path failed: $($_.Exception.GetType().Name)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- Actions -----------------------------------------------------------------------------------------------------
|
||||||
|
switch ($Action) {
|
||||||
|
'Rotate' {
|
||||||
|
$old = Read-Cred $throwawayFile
|
||||||
|
$newUser = 'lab' + (New-Secret).Substring(0, 12)
|
||||||
|
$newPass = New-Secret
|
||||||
|
$null = Invoke-Sunshine $old 'POST' '/api/password' @{
|
||||||
|
currentUsername = $old.User
|
||||||
|
currentPassword = $old.Password
|
||||||
|
newUsername = $newUser
|
||||||
|
newPassword = $newPass
|
||||||
|
confirmNewPassword = $newPass
|
||||||
|
}
|
||||||
|
Save-Cred $labFile $newUser $newPass
|
||||||
|
# Prove the new pair works before forgetting the old one.
|
||||||
|
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/clients/list' $null
|
||||||
|
Remove-Item -LiteralPath $throwawayFile -Force
|
||||||
|
Write-Host 'lab-api: credentials rotated; throwaway deleted'
|
||||||
|
}
|
||||||
|
'Status' {
|
||||||
|
$c = Read-Cred $labFile
|
||||||
|
$clients = Invoke-Sunshine $c 'GET' '/api/clients/list' $null
|
||||||
|
$apps = Invoke-Sunshine $c 'GET' '/api/apps' $null
|
||||||
|
Write-Host ('lab-api: clients: ' + (($clients | ConvertTo-Json -Depth 4 -Compress)))
|
||||||
|
Write-Host ('lab-api: apps: ' + ((@($apps.apps) | ForEach-Object { $_.name }) -join ', '))
|
||||||
|
}
|
||||||
|
'Pin' {
|
||||||
|
if (-not $PinFile) { Fail '-PinFile is required' }
|
||||||
|
$pin = (Get-Content -LiteralPath $PinFile -Raw).Trim()
|
||||||
|
Remove-Item -LiteralPath $PinFile -Force
|
||||||
|
if ($pin -notmatch '^[0-9]{4}$') { Fail 'the PIN file must hold exactly 4 digits' }
|
||||||
|
$body = @{ pin = $pin; name = $ClientName }
|
||||||
|
if ($PairingId) { $body.pairing_id = $PairingId }
|
||||||
|
$r = Invoke-Sunshine (Read-Cred $labFile) 'POST' '/api/pin' $body
|
||||||
|
Write-Host ('lab-api: PIN submitted, answer: ' + ($r | ConvertTo-Json -Compress))
|
||||||
|
}
|
||||||
|
'Logs' {
|
||||||
|
$out = Join-Path $captures 'sunshine.log'
|
||||||
|
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/logs' $null $out
|
||||||
|
Write-Host "lab-api: Sunshine log saved to $out (not shown: it may hold secrets)"
|
||||||
|
}
|
||||||
|
'Cleanup' {
|
||||||
|
$c = Read-Cred $labFile
|
||||||
|
$null = Invoke-Sunshine $c 'POST' '/api/clients/unpair-all' $null
|
||||||
|
# Same loopback-only config as lab-install.ps1, without the lab cert/key, so Sunshine makes a fresh pair.
|
||||||
|
$null = Invoke-Sunshine $c 'POST' '/api/config' @{
|
||||||
|
bind_address = '127.0.0.2'
|
||||||
|
address_family = 'ipv4'
|
||||||
|
origin_web_ui_allowed = 'pc'
|
||||||
|
upnp = 'disabled'
|
||||||
|
external_ip = '127.0.0.2'
|
||||||
|
sunshine_name = 'DomiStream-lab'
|
||||||
|
lan_encryption_mode = '1'
|
||||||
|
wan_encryption_mode = '1'
|
||||||
|
}
|
||||||
|
$null = Invoke-Sunshine $c 'POST' '/api/restart' $null
|
||||||
|
Write-Host 'lab-api: unpaired all clients, lab cert/key dropped from the config, Sunshine restarting'
|
||||||
|
Write-Host 'lab-api: next: delete keys\sunshine-lab-*.pem and keys\moonlight-lab-*.pem once Sunshine is back'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
exit 0
|
||||||
@@ -0,0 +1,217 @@
|
|||||||
|
<#
|
||||||
|
.SYNOPSIS
|
||||||
|
Lab capture step (b): install the pinned Sunshine bound to 127.0.0.2 only (docs/LAB_CAPTURE.md section 2).
|
||||||
|
|
||||||
|
.DESCRIPTION
|
||||||
|
Runs ELEVATED, once, started by the operator with:
|
||||||
|
Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
|
||||||
|
'<repo>\tools\lab-relay\scripts\lab-install.ps1'
|
||||||
|
That is the one UAC prompt of the lab capture.
|
||||||
|
|
||||||
|
What it does, in order, and nothing else:
|
||||||
|
1. Refuses unless elevated, unless the MSI's sha256 matches the pin, and unless no Sunshine is installed.
|
||||||
|
2. Creates keys\, secrets\, captures\ under the lab root, readable only by this account and SYSTEM.
|
||||||
|
3. msiexec /i (quiet, logged to captures\msiexec.log), then stops the service the MSI started.
|
||||||
|
4. Writes sunshine.conf: bind_address 127.0.0.2, web UI for this PC only, no UPnP, lab cert/key under keys\.
|
||||||
|
5. Sets throwaway web-UI credentials with `sunshine --creds` (they exist only in that one process's argv and
|
||||||
|
in a DPAPI-protected file; lab-api.ps1 -Action Rotate replaces them).
|
||||||
|
6. Starts the service and checks that every Sunshine listener is on 127.0.0.2. Anything else: stop, fail.
|
||||||
|
It does not touch Windows Defender, firewall rules (it only lists the ones the MSI added), or any other app.
|
||||||
|
It never prints, logs or writes a credential in plain text.
|
||||||
|
#>
|
||||||
|
[CmdletBinding()]
|
||||||
|
param(
|
||||||
|
[string] $LabRoot = 'E:\build\play-remotely\lab',
|
||||||
|
[string] $Msi = 'E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi'
|
||||||
|
)
|
||||||
|
|
||||||
|
Set-StrictMode -Version 2.0
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
# --- Pins (release API, docs/LAB_CAPTURE.md section 2) ------------------------------------------------------------
|
||||||
|
$PinnedSha256 = '1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf'
|
||||||
|
$PinnedSize = 33710080
|
||||||
|
$BindAddress = '127.0.0.2'
|
||||||
|
$Ports = @(47984, 47989, 47990, 48010)
|
||||||
|
|
||||||
|
function Fail([string] $Why) {
|
||||||
|
Write-Host "lab-install: STOPPED: $Why"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function Say([string] $What) {
|
||||||
|
Write-Host "lab-install: $What"
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 1. Preconditions --------------------------------------------------------------------------------------------
|
||||||
|
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||||
|
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||||
|
Fail 'not elevated; start it with Start-Process -Verb RunAs'
|
||||||
|
}
|
||||||
|
if (-not (Test-Path -LiteralPath $Msi -PathType Leaf)) { Fail "MSI not found: $Msi" }
|
||||||
|
$msiItem = Get-Item -LiteralPath $Msi
|
||||||
|
if ($msiItem.Length -ne $PinnedSize) { Fail "MSI size $($msiItem.Length) is not the pinned $PinnedSize" }
|
||||||
|
$hash = (Get-FileHash -LiteralPath $Msi -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||||
|
if ($hash -ne $PinnedSha256) { Fail "MSI sha256 $hash does not match the pin; delete the file" }
|
||||||
|
Say 'MSI matches the pinned sha256'
|
||||||
|
|
||||||
|
if (Get-Service -Name '*sunshine*' -ErrorAction SilentlyContinue) { Fail 'a Sunshine service already exists' }
|
||||||
|
if (Test-Path -LiteralPath 'C:\Program Files\Sunshine\sunshine.exe') { Fail 'C:\Program Files\Sunshine\sunshine.exe already exists' }
|
||||||
|
$busy = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
|
||||||
|
if ($busy) { Fail 'a GameStream port is already in use' }
|
||||||
|
|
||||||
|
# --- 2. Lab folders, this account + SYSTEM only ------------------------------------------------------------------
|
||||||
|
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||||
|
$keys = Join-Path $LabRoot 'keys'
|
||||||
|
$secrets = Join-Path $LabRoot 'secrets'
|
||||||
|
$captures = Join-Path $LabRoot 'captures'
|
||||||
|
foreach ($dir in @($keys, $secrets, $captures)) {
|
||||||
|
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||||
|
& icacls.exe $dir /inheritance:r /grant:r "${account}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' | Out-Null
|
||||||
|
if ($LASTEXITCODE -ne 0) { Fail "icacls failed on $dir" }
|
||||||
|
}
|
||||||
|
$hostKey = Join-Path $keys 'sunshine-lab-key.pem'
|
||||||
|
$hostCert = Join-Path $keys 'sunshine-lab-cert.pem'
|
||||||
|
foreach ($f in @($hostKey, $hostCert)) { if (Test-Path -LiteralPath $f) { Fail "$f already exists; clean up first" } }
|
||||||
|
Say "lab folders ready under $LabRoot"
|
||||||
|
|
||||||
|
# --- 3. Install ----------------------------------------------------------------------------------------------------
|
||||||
|
$msiLog = Join-Path $captures 'msiexec.log'
|
||||||
|
$p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', "`"$Msi`"", '/qn', '/norestart', '/l*v', "`"$msiLog`"") -Wait -PassThru
|
||||||
|
if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { Fail "msiexec exit code $($p.ExitCode); see $msiLog" }
|
||||||
|
Say "MSI installed (exit code $($p.ExitCode))"
|
||||||
|
|
||||||
|
$service = Get-CimInstance Win32_Service | Where-Object { $_.PathName -like '*Sunshine*' } | Select-Object -First 1
|
||||||
|
if (-not $service) { Fail 'no Sunshine service after the install' }
|
||||||
|
Stop-Service -Name $service.Name -Force
|
||||||
|
Say "service $($service.Name) stopped until the config is in"
|
||||||
|
|
||||||
|
$exe = 'C:\Program Files\Sunshine\sunshine.exe'
|
||||||
|
if (-not (Test-Path -LiteralPath $exe)) { Fail "$exe not found after the install" }
|
||||||
|
$installDir = Split-Path -Parent $exe
|
||||||
|
$configDir = Join-Path $installDir 'config'
|
||||||
|
New-Item -ItemType Directory -Force -Path $configDir | Out-Null
|
||||||
|
$conf = Join-Path $configDir 'sunshine.conf'
|
||||||
|
if (Test-Path -LiteralPath $conf) { Copy-Item -LiteralPath $conf -Destination (Join-Path $captures 'sunshine.conf.as-installed') -Force }
|
||||||
|
|
||||||
|
# --- 4. Config: loopback only ------------------------------------------------------------------------------------
|
||||||
|
function Write-Conf([bool] $WithLabKeys) {
|
||||||
|
$lines = @(
|
||||||
|
"bind_address = $BindAddress",
|
||||||
|
'address_family = ipv4',
|
||||||
|
'origin_web_ui_allowed = pc',
|
||||||
|
'upnp = disabled',
|
||||||
|
"external_ip = $BindAddress",
|
||||||
|
'sunshine_name = DomiStream-lab',
|
||||||
|
'lan_encryption_mode = 1',
|
||||||
|
'wan_encryption_mode = 1',
|
||||||
|
'min_log_level = debug'
|
||||||
|
)
|
||||||
|
if ($WithLabKeys) {
|
||||||
|
# Forward slashes: how the config parser treats backslashes is not documented.
|
||||||
|
$lines += 'pkey = ' + ($hostKey -replace '\\', '/')
|
||||||
|
$lines += 'cert = ' + ($hostCert -replace '\\', '/')
|
||||||
|
}
|
||||||
|
[IO.File]::WriteAllLines($conf, [string[]] $lines, (New-Object Text.UTF8Encoding($false)))
|
||||||
|
}
|
||||||
|
Write-Conf $true
|
||||||
|
Say 'sunshine.conf written (bind_address 127.0.0.2)'
|
||||||
|
|
||||||
|
# --- 5. Throwaway credentials ------------------------------------------------------------------------------------
|
||||||
|
function New-Secret {
|
||||||
|
$bytes = New-Object byte[] 32
|
||||||
|
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
|
||||||
|
$rng.GetBytes($bytes)
|
||||||
|
$rng.Dispose()
|
||||||
|
# base64url: only [A-Za-z0-9_-], so it needs no quoting on a command line.
|
||||||
|
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
|
||||||
|
}
|
||||||
|
$user = 'lab' + (New-Secret).Substring(0, 12)
|
||||||
|
$pass = New-Secret
|
||||||
|
|
||||||
|
# One child process; its argv dies with it. Output is read and discarded, never written anywhere.
|
||||||
|
$psi = New-Object Diagnostics.ProcessStartInfo
|
||||||
|
$psi.FileName = $exe
|
||||||
|
$psi.Arguments = "--creds $user $pass"
|
||||||
|
$psi.WorkingDirectory = $installDir
|
||||||
|
$psi.UseShellExecute = $false
|
||||||
|
$psi.CreateNoWindow = $true
|
||||||
|
$psi.RedirectStandardOutput = $true
|
||||||
|
$psi.RedirectStandardError = $true
|
||||||
|
$proc = [Diagnostics.Process]::Start($psi)
|
||||||
|
$null = $proc.StandardOutput.ReadToEnd()
|
||||||
|
$null = $proc.StandardError.ReadToEnd()
|
||||||
|
if (-not $proc.WaitForExit(60000)) { $proc.Kill(); Fail 'sunshine --creds did not finish' }
|
||||||
|
$credsExit = $proc.ExitCode
|
||||||
|
$psi = $null
|
||||||
|
$proc.Dispose()
|
||||||
|
if ($credsExit -ne 0) { Fail "sunshine --creds exit code $credsExit" }
|
||||||
|
|
||||||
|
# DPAPI (this account): readable only by this account on this PC; lab-api.ps1 -Action Rotate replaces it.
|
||||||
|
$throwaway = Join-Path $secrets 'sunshine-throwaway.cred'
|
||||||
|
@{
|
||||||
|
user = (ConvertTo-SecureString -String $user -AsPlainText -Force | ConvertFrom-SecureString)
|
||||||
|
password = (ConvertTo-SecureString -String $pass -AsPlainText -Force | ConvertFrom-SecureString)
|
||||||
|
} | ConvertTo-Json | Set-Content -LiteralPath $throwaway -Encoding ASCII
|
||||||
|
Remove-Variable -Name user, pass -ErrorAction SilentlyContinue
|
||||||
|
Say 'throwaway credentials set and stored (DPAPI)'
|
||||||
|
|
||||||
|
# --- 6. Start and check the binding ------------------------------------------------------------------------------
|
||||||
|
function Wait-Listeners([int] $Seconds) {
|
||||||
|
$deadline = (Get-Date).AddSeconds($Seconds)
|
||||||
|
while ((Get-Date) -lt $deadline) {
|
||||||
|
$l = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
|
||||||
|
if ($l -and (@($l | Select-Object -ExpandProperty LocalPort -Unique).Count -eq $Ports.Count)) { return $l }
|
||||||
|
Start-Sleep -Milliseconds 500
|
||||||
|
}
|
||||||
|
return $null
|
||||||
|
}
|
||||||
|
function Assert-Loopback($Listeners) {
|
||||||
|
$wrong = @($Listeners | Where-Object { $_.LocalAddress -ne $BindAddress })
|
||||||
|
if ($wrong.Count -gt 0) {
|
||||||
|
Stop-Service -Name $service.Name -Force
|
||||||
|
Fail ('Sunshine listened on ' + (($wrong | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', ') + '; service stopped')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Start-Service -Name $service.Name
|
||||||
|
$listeners = Wait-Listeners 60
|
||||||
|
if (-not $listeners) {
|
||||||
|
Stop-Service -Name $service.Name -Force
|
||||||
|
Fail 'Sunshine did not listen on all four TCP ports; service stopped (bind_address 127.0.0.2 refused? see LAB_CAPTURE.md section 4 fallback)'
|
||||||
|
}
|
||||||
|
Assert-Loopback $listeners
|
||||||
|
|
||||||
|
# Did Sunshine create its pair at the lab path? If not, fall back to its default pair and copy it for the relay.
|
||||||
|
$deadline = (Get-Date).AddSeconds(30)
|
||||||
|
while (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert)) -and (Get-Date) -lt $deadline) {
|
||||||
|
Start-Sleep -Milliseconds 500
|
||||||
|
}
|
||||||
|
if (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert))) {
|
||||||
|
Say 'Sunshine did not create the lab pair at keys\; using its default pair'
|
||||||
|
Stop-Service -Name $service.Name -Force
|
||||||
|
Write-Conf $false
|
||||||
|
Start-Service -Name $service.Name
|
||||||
|
$listeners = Wait-Listeners 60
|
||||||
|
if (-not $listeners) { Stop-Service -Name $service.Name -Force; Fail 'Sunshine did not come back after the fallback' }
|
||||||
|
Assert-Loopback $listeners
|
||||||
|
$defKey = Join-Path $configDir 'credentials\cakey.pem'
|
||||||
|
$defCert = Join-Path $configDir 'credentials\cacert.pem'
|
||||||
|
if (-not ((Test-Path -LiteralPath $defKey) -and (Test-Path -LiteralPath $defCert))) { Fail 'default pair not found either' }
|
||||||
|
Copy-Item -LiteralPath $defKey -Destination $hostKey
|
||||||
|
Copy-Item -LiteralPath $defCert -Destination $hostCert
|
||||||
|
}
|
||||||
|
Say 'Sunshine listens on 127.0.0.2 only; lab certificate pair in keys\'
|
||||||
|
|
||||||
|
# --- Report what the MSI did to the firewall (read only, nothing changed) ----------------------------------------
|
||||||
|
$rules = @(Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like '*Sunshine*' })
|
||||||
|
$notes = Join-Path $captures 'install-notes.txt'
|
||||||
|
@(
|
||||||
|
"installed: $(Get-Date -Format o)",
|
||||||
|
"service: $($service.Name)",
|
||||||
|
"msi sha256: $hash",
|
||||||
|
"listeners: " + (($listeners | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', '),
|
||||||
|
"firewall rules named like Sunshine (not changed): " + (($rules | ForEach-Object { "$($_.DisplayName) [$($_.Direction) $($_.Action) $($_.Enabled)]" }) -join '; ')
|
||||||
|
) | Set-Content -LiteralPath $notes -Encoding ASCII
|
||||||
|
Say "done; notes in $notes. Next, not elevated: lab-api.ps1 -Action Rotate"
|
||||||
|
exit 0
|
||||||
@@ -0,0 +1,317 @@
|
|||||||
|
//! Relay settings and the loopback-only rule.
|
||||||
|
|
||||||
|
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||||
|
use std::path::PathBuf;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::record::Protocol;
|
||||||
|
|
||||||
|
/// Where recordings go unless told otherwise.
|
||||||
|
pub const DEFAULT_CAPTURE_DIR: &str = r"E:\build\play-remotely\lab\captures";
|
||||||
|
/// Where lab keys live unless told otherwise.
|
||||||
|
pub const DEFAULT_KEY_DIR: &str = r"E:\build\play-remotely\lab\keys";
|
||||||
|
|
||||||
|
/// Transport of a relayed port.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub enum Transport {
|
||||||
|
/// TCP, bytes copied (and rewritten host-to-client when the protocol is plaintext).
|
||||||
|
Tcp,
|
||||||
|
/// TCP with TLS terminated in the relay.
|
||||||
|
Tls,
|
||||||
|
/// UDP datagrams.
|
||||||
|
Udp,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One relayed port.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct PortSpec {
|
||||||
|
/// Port the relay listens on.
|
||||||
|
pub listen_port: u16,
|
||||||
|
/// Port on the upstream (Sunshine) side.
|
||||||
|
pub upstream_port: u16,
|
||||||
|
/// Transport.
|
||||||
|
pub transport: Transport,
|
||||||
|
/// Protocol label for the records.
|
||||||
|
pub protocol: Protocol,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The GameStream default ports (PROTOCOL.md section 0, ArenaTV sunshine-api.md section 3).
|
||||||
|
pub const GAMESTREAM_PORTS: [(u16, Transport, Protocol); 7] = [
|
||||||
|
(47984, Transport::Tls, Protocol::HttpsPlain),
|
||||||
|
(47989, Transport::Tcp, Protocol::Http),
|
||||||
|
(48010, Transport::Tcp, Protocol::Rtsp),
|
||||||
|
(47998, Transport::Udp, Protocol::Video),
|
||||||
|
(47999, Transport::Udp, Protocol::Control),
|
||||||
|
(48000, Transport::Udp, Protocol::Audio),
|
||||||
|
(48002, Transport::Udp, Protocol::Mic),
|
||||||
|
];
|
||||||
|
|
||||||
|
/// TLS material, all lab-only PEM files.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct TlsFiles {
|
||||||
|
/// Sunshine's lab certificate (presented to Moonlight, pinned towards Sunshine).
|
||||||
|
pub host_cert: PathBuf,
|
||||||
|
/// Sunshine's lab private key.
|
||||||
|
pub host_key: PathBuf,
|
||||||
|
/// Moonlight's lab client certificate (presented to Sunshine).
|
||||||
|
pub client_cert: PathBuf,
|
||||||
|
/// Moonlight's lab client key.
|
||||||
|
pub client_key: PathBuf,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TlsFiles {
|
||||||
|
/// The four default file names in `dir`.
|
||||||
|
pub fn in_dir(dir: &std::path::Path) -> Self {
|
||||||
|
Self {
|
||||||
|
host_cert: dir.join("sunshine-lab-cert.pem"),
|
||||||
|
host_key: dir.join("sunshine-lab-key.pem"),
|
||||||
|
client_cert: dir.join("moonlight-lab-cert.pem"),
|
||||||
|
client_key: dir.join("moonlight-lab-key.pem"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An equal-length byte replacement applied to host-to-client plaintext.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Rewrite {
|
||||||
|
/// Bytes to find.
|
||||||
|
pub from: Vec<u8>,
|
||||||
|
/// Bytes to put instead, same length.
|
||||||
|
pub to: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Everything the relay needs.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Config {
|
||||||
|
/// Address the relay listens on (Moonlight's "host"). Loopback only.
|
||||||
|
pub listen: IpAddr,
|
||||||
|
/// Address Sunshine listens on. Loopback only.
|
||||||
|
pub upstream: IpAddr,
|
||||||
|
/// Added to each default port on the upstream side (0, or 1000 in the fallback of LAB_CAPTURE.md section 4).
|
||||||
|
pub upstream_port_offset: u16,
|
||||||
|
/// Directory for the record file.
|
||||||
|
pub capture_dir: PathBuf,
|
||||||
|
/// TLS files; `None` = HTTPS passes through as raw TLS.
|
||||||
|
pub tls: Option<TlsFiles>,
|
||||||
|
/// How long an HTTPS connection waits for the TLS files to appear (Moonlight's key may appear only after
|
||||||
|
/// pairing step 1).
|
||||||
|
pub wait_for_keys: Duration,
|
||||||
|
/// Rewrites, applied in order of position in the stream.
|
||||||
|
pub rewrites: Vec<Rewrite>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a configuration is refused.
|
||||||
|
#[derive(Debug, PartialEq, Eq)]
|
||||||
|
pub enum ConfigError {
|
||||||
|
/// An address that is not loopback.
|
||||||
|
NotLoopback(IpAddr),
|
||||||
|
/// Listen and upstream are the same address with no port offset: the relay would talk to itself.
|
||||||
|
SelfLoop,
|
||||||
|
/// A rewrite whose two sides differ in length, or are empty.
|
||||||
|
BadRewrite(String),
|
||||||
|
/// Ports overflow with the offset.
|
||||||
|
PortOverflow(u16),
|
||||||
|
/// A command-line argument that is not understood.
|
||||||
|
BadArgument(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::fmt::Display for ConfigError {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::NotLoopback(ip) => {
|
||||||
|
write!(f, "{ip} is not a loopback address; the relay binds and connects only on loopback")
|
||||||
|
}
|
||||||
|
Self::SelfLoop => f.write_str("listen and upstream are the same address and ports"),
|
||||||
|
Self::BadRewrite(s) => write!(f, "rewrite {s:?}: both sides must be non-empty and the same length"),
|
||||||
|
Self::PortOverflow(p) => write!(f, "port {p} plus the offset is over 65535"),
|
||||||
|
Self::BadArgument(s) => write!(f, "bad argument: {s}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for ConfigError {}
|
||||||
|
|
||||||
|
impl Config {
|
||||||
|
/// The lab defaults: Moonlight sees 127.0.0.1, Sunshine sits on 127.0.0.2, `127.0.0.2` is rewritten to
|
||||||
|
/// `127.0.0.1` in host-to-client plaintext, TLS files from [`DEFAULT_KEY_DIR`].
|
||||||
|
pub fn lab_default() -> Self {
|
||||||
|
Self {
|
||||||
|
listen: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
|
||||||
|
upstream: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)),
|
||||||
|
upstream_port_offset: 0,
|
||||||
|
capture_dir: PathBuf::from(DEFAULT_CAPTURE_DIR),
|
||||||
|
tls: Some(TlsFiles::in_dir(std::path::Path::new(DEFAULT_KEY_DIR))),
|
||||||
|
wait_for_keys: Duration::from_secs(60),
|
||||||
|
rewrites: vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Checks the rules: loopback only, no self-loop, sane rewrites, ports in range.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// The first rule broken.
|
||||||
|
pub fn validate(&self) -> Result<(), ConfigError> {
|
||||||
|
for ip in [self.listen, self.upstream] {
|
||||||
|
if !ip.is_loopback() {
|
||||||
|
return Err(ConfigError::NotLoopback(ip));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if self.listen == self.upstream && self.upstream_port_offset == 0 {
|
||||||
|
return Err(ConfigError::SelfLoop);
|
||||||
|
}
|
||||||
|
for r in &self.rewrites {
|
||||||
|
if r.from.is_empty() || r.from.len() != r.to.len() {
|
||||||
|
return Err(ConfigError::BadRewrite(String::from_utf8_lossy(&r.from).into_owned()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.ports().map(|_| ())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The relayed ports with the upstream offset applied.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`ConfigError::PortOverflow`].
|
||||||
|
pub fn ports(&self) -> Result<Vec<PortSpec>, ConfigError> {
|
||||||
|
GAMESTREAM_PORTS
|
||||||
|
.iter()
|
||||||
|
.map(|&(port, transport, protocol)| {
|
||||||
|
let upstream_port =
|
||||||
|
port.checked_add(self.upstream_port_offset).ok_or(ConfigError::PortOverflow(port))?;
|
||||||
|
let transport =
|
||||||
|
if transport == Transport::Tls && self.tls.is_none() { Transport::Tcp } else { transport };
|
||||||
|
let protocol = if transport == Transport::Tcp && protocol == Protocol::HttpsPlain {
|
||||||
|
Protocol::HttpsTls
|
||||||
|
} else {
|
||||||
|
protocol
|
||||||
|
};
|
||||||
|
Ok(PortSpec { listen_port: port, upstream_port, transport, protocol })
|
||||||
|
})
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Socket address the relay listens on for `spec`.
|
||||||
|
pub fn listen_addr(&self, spec: &PortSpec) -> SocketAddr {
|
||||||
|
SocketAddr::new(self.listen, spec.listen_port)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Upstream socket address for `spec`.
|
||||||
|
pub fn upstream_addr(&self, spec: &PortSpec) -> SocketAddr {
|
||||||
|
SocketAddr::new(self.upstream, spec.upstream_port)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies command-line options to the lab defaults:
|
||||||
|
/// `--listen <ip>`, `--upstream <ip>`, `--upstream-port-offset <n>`, `--capture-dir <dir>`, `--key-dir <dir>`,
|
||||||
|
/// `--https-passthrough`, `--wait-for-keys-secs <n>`, `--rewrite <from>=<to>` (repeatable; the first one
|
||||||
|
/// replaces the default rewrite), `--no-rewrite`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`ConfigError::BadArgument`] for an unknown option or value, then [`Config::validate`].
|
||||||
|
pub fn from_args(args: &[String]) -> Result<Self, ConfigError> {
|
||||||
|
let mut c = Self::lab_default();
|
||||||
|
let mut custom_rewrites = false;
|
||||||
|
let mut it = args.iter();
|
||||||
|
let bad = |s: &str| ConfigError::BadArgument(s.to_owned());
|
||||||
|
while let Some(a) = it.next() {
|
||||||
|
let mut value = || it.next().ok_or_else(|| bad(a));
|
||||||
|
match a.as_str() {
|
||||||
|
"--listen" => c.listen = value()?.parse().map_err(|_| bad(a))?,
|
||||||
|
"--upstream" => c.upstream = value()?.parse().map_err(|_| bad(a))?,
|
||||||
|
"--upstream-port-offset" => c.upstream_port_offset = value()?.parse().map_err(|_| bad(a))?,
|
||||||
|
"--capture-dir" => c.capture_dir = PathBuf::from(value()?),
|
||||||
|
"--key-dir" => {
|
||||||
|
let dir = PathBuf::from(value()?);
|
||||||
|
if c.tls.is_some() {
|
||||||
|
c.tls = Some(TlsFiles::in_dir(&dir));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
"--https-passthrough" => c.tls = None,
|
||||||
|
"--wait-for-keys-secs" => {
|
||||||
|
c.wait_for_keys = Duration::from_secs(value()?.parse().map_err(|_| bad(a))?);
|
||||||
|
}
|
||||||
|
"--rewrite" => {
|
||||||
|
let v = value()?;
|
||||||
|
let (from, to) = v.split_once('=').ok_or_else(|| bad(v))?;
|
||||||
|
if !custom_rewrites {
|
||||||
|
c.rewrites.clear();
|
||||||
|
custom_rewrites = true;
|
||||||
|
}
|
||||||
|
c.rewrites.push(Rewrite { from: from.as_bytes().to_vec(), to: to.as_bytes().to_vec() });
|
||||||
|
}
|
||||||
|
"--no-rewrite" => {
|
||||||
|
c.rewrites.clear();
|
||||||
|
custom_rewrites = true;
|
||||||
|
}
|
||||||
|
other => return Err(bad(other)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
c.validate()?;
|
||||||
|
Ok(c)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn args(s: &str) -> Vec<String> {
|
||||||
|
s.split_whitespace().map(str::to_owned).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lab_default_is_valid() {
|
||||||
|
assert_eq!(Config::lab_default().validate(), Ok(()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_loopback_listen_or_upstream_is_refused() {
|
||||||
|
for a in [
|
||||||
|
"--listen 0.0.0.0",
|
||||||
|
"--listen 192.168.100.140",
|
||||||
|
"--upstream 192.168.100.217",
|
||||||
|
"--listen ::",
|
||||||
|
"--upstream 26.1.2.3",
|
||||||
|
] {
|
||||||
|
assert!(matches!(Config::from_args(&args(a)), Err(ConfigError::NotLoopback(_))), "{a}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn other_loopback_addresses_are_accepted() {
|
||||||
|
let c = Config::from_args(&args("--listen 127.0.0.3 --upstream ::1")).unwrap();
|
||||||
|
assert!(c.listen.is_loopback() && c.upstream.is_loopback());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn self_loop_is_refused_unless_offset() {
|
||||||
|
assert_eq!(Config::from_args(&args("--upstream 127.0.0.1")), Err(ConfigError::SelfLoop));
|
||||||
|
let c = Config::from_args(&args("--upstream 127.0.0.1 --upstream-port-offset 1000")).unwrap();
|
||||||
|
let ports = c.ports().unwrap();
|
||||||
|
assert!(ports.iter().all(|p| p.upstream_port == p.listen_port + 1000));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn rewrites_must_keep_length() {
|
||||||
|
assert!(matches!(Config::from_args(&args("--rewrite 48984=7984")), Err(ConfigError::BadRewrite(_))));
|
||||||
|
assert!(matches!(Config::from_args(&args("--rewrite =")), Err(ConfigError::BadRewrite(_))));
|
||||||
|
let c = Config::from_args(&args("--rewrite 48984=47984 --rewrite 49010=48010")).unwrap();
|
||||||
|
assert_eq!(c.rewrites.len(), 2, "custom rewrites replace the default one");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn port_overflow_is_refused() {
|
||||||
|
assert!(matches!(Config::from_args(&args("--upstream-port-offset 20000")), Err(ConfigError::PortOverflow(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn passthrough_turns_tls_into_raw_tcp() {
|
||||||
|
let c = Config::from_args(&args("--https-passthrough")).unwrap();
|
||||||
|
let https = c.ports().unwrap().into_iter().find(|p| p.listen_port == 47984).unwrap();
|
||||||
|
assert_eq!((https.transport, https.protocol), (Transport::Tcp, Protocol::HttpsTls));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_arguments_are_refused() {
|
||||||
|
assert!(matches!(Config::from_args(&args("--bind 0.0.0.0")), Err(ConfigError::BadArgument(_))));
|
||||||
|
assert!(matches!(Config::from_args(&args("--listen")), Err(ConfigError::BadArgument(_))));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
//! lab-relay: our own logging relay for the one GameStream lab capture (`docs/LAB_CAPTURE.md`).
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! lab-relay run [--listen 127.0.0.1] [--upstream 127.0.0.2] [--upstream-port-offset N] [--capture-dir DIR]
|
||||||
|
//! [--key-dir DIR] [--https-passthrough] [--wait-for-keys-secs N] [--rewrite FROM=TO]... [--no-rewrite]
|
||||||
|
//! lab-relay dump <file.dslr> list records, secrets redacted
|
||||||
|
//! lab-relay strip-video <in> <out> copy with video payloads cut to their 32 header bytes
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! Binds and connects only on loopback (refused otherwise). Never sends anything of its own.
|
||||||
|
|
||||||
|
mod config;
|
||||||
|
mod record;
|
||||||
|
mod recorder;
|
||||||
|
mod redact;
|
||||||
|
mod rewrite;
|
||||||
|
mod tcp;
|
||||||
|
mod tls;
|
||||||
|
mod udp;
|
||||||
|
|
||||||
|
use std::fs::File;
|
||||||
|
use std::io::{self, BufReader, BufWriter, Write};
|
||||||
|
use std::process::ExitCode;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
use config::{Config, Transport};
|
||||||
|
use record::{Kind, Protocol, Record};
|
||||||
|
use recorder::Recorder;
|
||||||
|
|
||||||
|
/// Bytes of a video packet kept by `strip-video`: RTP header, reserved bytes and the NV header.
|
||||||
|
const VIDEO_HEADER_KEEP: usize = 32;
|
||||||
|
/// Text shown per record by `dump`.
|
||||||
|
const DUMP_TEXT_LIMIT: usize = 4000;
|
||||||
|
|
||||||
|
fn main() -> ExitCode {
|
||||||
|
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||||
|
let result = match args.split_first() {
|
||||||
|
Some((cmd, rest)) if cmd == "run" => run(rest),
|
||||||
|
Some((cmd, [file])) if cmd == "dump" => dump(file),
|
||||||
|
Some((cmd, [input, output])) if cmd == "strip-video" => strip_video(input, output),
|
||||||
|
_ => Err("usage: lab-relay run [options] | dump <file> | strip-video <in> <out>".into()),
|
||||||
|
};
|
||||||
|
match result {
|
||||||
|
Ok(()) => ExitCode::SUCCESS,
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("lab-relay: {e}");
|
||||||
|
ExitCode::FAILURE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type AnyResult = Result<(), Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
|
fn run(args: &[String]) -> AnyResult {
|
||||||
|
let config = Arc::new(Config::from_args(args)?);
|
||||||
|
let (rec, path) = Recorder::create(&config.capture_dir)?;
|
||||||
|
let rec = Arc::new(rec);
|
||||||
|
println!("lab-relay: recording to {}", path.display());
|
||||||
|
let mut threads = Vec::new();
|
||||||
|
for spec in config.ports()? {
|
||||||
|
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
|
||||||
|
println!("lab-relay: {:?} {} -> {}", spec.protocol, config.listen_addr(&spec), config.upstream_addr(&spec));
|
||||||
|
threads.push(thread::spawn(move || {
|
||||||
|
let r = match spec.transport {
|
||||||
|
Transport::Tcp => tcp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
|
||||||
|
Transport::Tls => tls::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
|
||||||
|
Transport::Udp => udp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
|
||||||
|
};
|
||||||
|
if let Err(e) = r {
|
||||||
|
eprintln!("lab-relay: port {} stopped: {e}", spec.listen_port);
|
||||||
|
rec.note(Protocol::Meta, 0, &format!("port {} stopped: {e}", spec.listen_port));
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
rec.note(Protocol::Meta, 0, "relay started");
|
||||||
|
for t in threads {
|
||||||
|
let _ = t.join();
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_text(r: &Record) -> bool {
|
||||||
|
r.kind == Kind::Note
|
||||||
|
|| r.kind == Kind::Open
|
||||||
|
|| matches!(r.protocol, Protocol::Http | Protocol::HttpsPlain | Protocol::Rtsp)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dump(file: &str) -> AnyResult {
|
||||||
|
let mut input = BufReader::new(File::open(file)?);
|
||||||
|
let header = record::read_header(&mut input)?;
|
||||||
|
let stdout = io::stdout();
|
||||||
|
let mut out = stdout.lock();
|
||||||
|
writeln!(out, "capture started at unix {} us", header.start_unix_micros)?;
|
||||||
|
let mut index = 0u64;
|
||||||
|
loop {
|
||||||
|
let r = match record::read_record(&mut input) {
|
||||||
|
Ok(Some(r)) => r,
|
||||||
|
Ok(None) => break,
|
||||||
|
Err(e) => {
|
||||||
|
writeln!(out, "stopped at record {index}: {e}")?;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
writeln!(
|
||||||
|
out,
|
||||||
|
"#{index} t={}.{:06}s conn={} {:?} {:?} {:?} {} bytes",
|
||||||
|
r.time_micros / 1_000_000,
|
||||||
|
r.time_micros % 1_000_000,
|
||||||
|
r.connection,
|
||||||
|
r.kind,
|
||||||
|
r.protocol,
|
||||||
|
r.direction,
|
||||||
|
r.payload.len()
|
||||||
|
)?;
|
||||||
|
if is_text(&r) {
|
||||||
|
let text = redact::redact(&r.payload);
|
||||||
|
let shown = &text[..text.len().min(DUMP_TEXT_LIMIT)];
|
||||||
|
writeln!(out, " {}", String::from_utf8_lossy(shown).escape_debug())?;
|
||||||
|
} else {
|
||||||
|
let hex: String = r.payload.iter().take(32).map(|b| format!("{b:02x} ")).collect();
|
||||||
|
writeln!(out, " {hex}")?;
|
||||||
|
}
|
||||||
|
index += 1;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn strip_video(input: &str, output: &str) -> AnyResult {
|
||||||
|
let mut reader = BufReader::new(File::open(input)?);
|
||||||
|
let header = record::read_header(&mut reader)?;
|
||||||
|
let mut writer = BufWriter::new(File::options().write(true).create_new(true).open(output)?);
|
||||||
|
record::write_header(&mut writer, header)?;
|
||||||
|
let mut stripped = 0u64;
|
||||||
|
while let Some(mut r) = record::read_record(&mut reader)? {
|
||||||
|
if r.kind == Kind::Data && r.protocol == Protocol::Video && r.payload.len() > VIDEO_HEADER_KEEP {
|
||||||
|
r.payload.truncate(VIDEO_HEADER_KEEP);
|
||||||
|
stripped += 1;
|
||||||
|
}
|
||||||
|
record::write_record(&mut writer, &r)?;
|
||||||
|
}
|
||||||
|
let note = Record {
|
||||||
|
kind: Kind::Note,
|
||||||
|
protocol: Protocol::Meta,
|
||||||
|
direction: record::Direction::None,
|
||||||
|
connection: 0,
|
||||||
|
time_micros: u64::MAX,
|
||||||
|
payload: format!("strip-video: {stripped} video payloads cut to {VIDEO_HEADER_KEEP} bytes").into_bytes(),
|
||||||
|
};
|
||||||
|
record::write_record(&mut writer, ¬e)?;
|
||||||
|
writer.flush()?;
|
||||||
|
println!("lab-relay: {stripped} video records stripped");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
//! The record file: everything the relay sees, framed so it can be read back exactly.
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! file = header record*
|
||||||
|
//! header = "DSLR" version:u8(=1) reserved:[u8;3](=0) start_unix_micros:u64le
|
||||||
|
//! record = kind:u8 protocol:u8 direction:u8 reserved:u8(=0) connection:u32le time_micros:u64le len:u32le bytes[len]
|
||||||
|
//! ```
|
||||||
|
//!
|
||||||
|
//! `time_micros` counts from the start of the capture. A record never holds more than [`MAX_PAYLOAD`] bytes.
|
||||||
|
|
||||||
|
use std::fmt;
|
||||||
|
use std::io::{self, Read, Write};
|
||||||
|
|
||||||
|
/// File magic.
|
||||||
|
pub const MAGIC: [u8; 4] = *b"DSLR";
|
||||||
|
/// Format version.
|
||||||
|
pub const VERSION: u8 = 1;
|
||||||
|
/// Header length in bytes.
|
||||||
|
pub const HEADER_LEN: usize = 16;
|
||||||
|
/// Record header length in bytes.
|
||||||
|
pub const RECORD_HEADER_LEN: usize = 20;
|
||||||
|
/// Largest payload of one record (a UDP datagram is at most 64 KiB; TCP reads are split to fit).
|
||||||
|
pub const MAX_PAYLOAD: usize = 1 << 20;
|
||||||
|
|
||||||
|
/// What a record says.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Kind {
|
||||||
|
/// A connection or UDP flow opened.
|
||||||
|
Open,
|
||||||
|
/// Bytes seen.
|
||||||
|
Data,
|
||||||
|
/// A connection or flow closed.
|
||||||
|
Close,
|
||||||
|
/// A UTF-8 note from the relay (TLS details, rewrites, errors).
|
||||||
|
Note,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which protocol the bytes belong to.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Protocol {
|
||||||
|
/// Relay-level notes.
|
||||||
|
Meta,
|
||||||
|
/// HTTP, port 47989.
|
||||||
|
Http,
|
||||||
|
/// Raw TLS bytes on 47984 (when not terminated).
|
||||||
|
HttpsTls,
|
||||||
|
/// Decrypted HTTPS plaintext on 47984.
|
||||||
|
HttpsPlain,
|
||||||
|
/// RTSP, port 48010.
|
||||||
|
Rtsp,
|
||||||
|
/// Video RTP, port 47998.
|
||||||
|
Video,
|
||||||
|
/// Control ENet, port 47999.
|
||||||
|
Control,
|
||||||
|
/// Audio RTP, port 48000.
|
||||||
|
Audio,
|
||||||
|
/// Microphone, port 48002.
|
||||||
|
Mic,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Which way the bytes went.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||||
|
pub enum Direction {
|
||||||
|
/// Not a transfer (notes, opens, closes).
|
||||||
|
None,
|
||||||
|
/// Moonlight to Sunshine.
|
||||||
|
ClientToHost,
|
||||||
|
/// Sunshine to Moonlight.
|
||||||
|
HostToClient,
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! codes {
|
||||||
|
($t:ty { $($v:ident = $c:literal),* $(,)? }) => {
|
||||||
|
impl $t {
|
||||||
|
/// Wire code.
|
||||||
|
pub const fn code(self) -> u8 {
|
||||||
|
match self { $(Self::$v => $c),* }
|
||||||
|
}
|
||||||
|
/// From a wire code.
|
||||||
|
pub const fn from_code(code: u8) -> Option<Self> {
|
||||||
|
match code { $($c => Some(Self::$v),)* _ => None }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
codes!(Kind { Open = 1, Data = 2, Close = 3, Note = 4 });
|
||||||
|
codes!(Protocol {
|
||||||
|
Meta = 0, Http = 1, HttpsTls = 2, HttpsPlain = 3, Rtsp = 4, Video = 5, Control = 6, Audio = 7, Mic = 8,
|
||||||
|
});
|
||||||
|
codes!(Direction { None = 0, ClientToHost = 1, HostToClient = 2 });
|
||||||
|
|
||||||
|
/// The file header.
|
||||||
|
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Header {
|
||||||
|
/// Wall-clock start of the capture, Unix microseconds.
|
||||||
|
pub start_unix_micros: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One record.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub struct Record {
|
||||||
|
/// What it is.
|
||||||
|
pub kind: Kind,
|
||||||
|
/// Protocol.
|
||||||
|
pub protocol: Protocol,
|
||||||
|
/// Direction.
|
||||||
|
pub direction: Direction,
|
||||||
|
/// Connection or flow id, unique per capture.
|
||||||
|
pub connection: u32,
|
||||||
|
/// Microseconds since the capture started.
|
||||||
|
pub time_micros: u64,
|
||||||
|
/// The bytes (UTF-8 text for notes).
|
||||||
|
pub payload: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Why a file could not be read.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub enum RecordError {
|
||||||
|
/// I/O failure.
|
||||||
|
Io(io::Error),
|
||||||
|
/// Not a record file, or another version.
|
||||||
|
BadHeader,
|
||||||
|
/// The file ends inside a record.
|
||||||
|
Truncated,
|
||||||
|
/// A field holds a value this version does not know.
|
||||||
|
BadField(&'static str, u64),
|
||||||
|
/// A payload over [`MAX_PAYLOAD`].
|
||||||
|
TooLarge(usize),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for RecordError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::Io(e) => write!(f, "i/o: {e}"),
|
||||||
|
Self::BadHeader => f.write_str("not a DSLR v1 file"),
|
||||||
|
Self::Truncated => f.write_str("file ends inside a record"),
|
||||||
|
Self::BadField(name, v) => write!(f, "bad {name}: {v}"),
|
||||||
|
Self::TooLarge(n) => write!(f, "payload of {n} bytes is over the limit"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::error::Error for RecordError {}
|
||||||
|
|
||||||
|
impl From<io::Error> for RecordError {
|
||||||
|
fn from(e: io::Error) -> Self {
|
||||||
|
Self::Io(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the file header.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// I/O errors.
|
||||||
|
pub fn write_header(out: &mut impl Write, header: Header) -> io::Result<()> {
|
||||||
|
let mut buf = [0u8; HEADER_LEN];
|
||||||
|
buf[..4].copy_from_slice(&MAGIC);
|
||||||
|
buf[4] = VERSION;
|
||||||
|
buf[8..16].copy_from_slice(&header.start_unix_micros.to_le_bytes());
|
||||||
|
out.write_all(&buf)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes one record.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`io::ErrorKind::InvalidInput`] for a payload over [`MAX_PAYLOAD`]; I/O errors.
|
||||||
|
pub fn write_record(out: &mut impl Write, record: &Record) -> io::Result<()> {
|
||||||
|
let len = record.payload.len();
|
||||||
|
if len > MAX_PAYLOAD {
|
||||||
|
return Err(io::Error::new(io::ErrorKind::InvalidInput, "record payload over MAX_PAYLOAD"));
|
||||||
|
}
|
||||||
|
let mut head = [0u8; RECORD_HEADER_LEN];
|
||||||
|
head[0] = record.kind.code();
|
||||||
|
head[1] = record.protocol.code();
|
||||||
|
head[2] = record.direction.code();
|
||||||
|
head[4..8].copy_from_slice(&record.connection.to_le_bytes());
|
||||||
|
head[8..16].copy_from_slice(&record.time_micros.to_le_bytes());
|
||||||
|
// `len <= MAX_PAYLOAD < u32::MAX`, checked above.
|
||||||
|
head[16..20].copy_from_slice(&(len as u32).to_le_bytes());
|
||||||
|
out.write_all(&head)?;
|
||||||
|
out.write_all(&record.payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads exactly `buf.len()` bytes; `Ok(false)` at a clean end before the first byte.
|
||||||
|
fn read_full(input: &mut impl Read, buf: &mut [u8]) -> Result<bool, RecordError> {
|
||||||
|
let mut filled = 0;
|
||||||
|
while filled < buf.len() {
|
||||||
|
match input.read(&mut buf[filled..]) {
|
||||||
|
Ok(0) if filled == 0 => return Ok(false),
|
||||||
|
Ok(0) => return Err(RecordError::Truncated),
|
||||||
|
Ok(n) => filled += n,
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
|
||||||
|
Err(e) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads and checks the file header.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`RecordError::BadHeader`] for a wrong magic, version or reserved bytes; [`RecordError::Truncated`].
|
||||||
|
pub fn read_header(input: &mut impl Read) -> Result<Header, RecordError> {
|
||||||
|
let mut buf = [0u8; HEADER_LEN];
|
||||||
|
if !read_full(input, &mut buf)? {
|
||||||
|
return Err(RecordError::Truncated);
|
||||||
|
}
|
||||||
|
if buf[..4] != MAGIC || buf[4] != VERSION || buf[5..8] != [0, 0, 0] {
|
||||||
|
return Err(RecordError::BadHeader);
|
||||||
|
}
|
||||||
|
let mut start = [0u8; 8];
|
||||||
|
start.copy_from_slice(&buf[8..16]);
|
||||||
|
Ok(Header { start_unix_micros: u64::from_le_bytes(start) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads the next record; `Ok(None)` at the end of the file.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// [`RecordError::Truncated`] inside a record, [`RecordError::BadField`] for unknown codes or a non-zero reserved
|
||||||
|
/// byte, [`RecordError::TooLarge`] before allocating an oversized payload.
|
||||||
|
pub fn read_record(input: &mut impl Read) -> Result<Option<Record>, RecordError> {
|
||||||
|
let mut head = [0u8; RECORD_HEADER_LEN];
|
||||||
|
if !read_full(input, &mut head)? {
|
||||||
|
return Ok(None);
|
||||||
|
}
|
||||||
|
let kind = Kind::from_code(head[0]).ok_or(RecordError::BadField("kind", head[0].into()))?;
|
||||||
|
let protocol = Protocol::from_code(head[1]).ok_or(RecordError::BadField("protocol", head[1].into()))?;
|
||||||
|
let direction = Direction::from_code(head[2]).ok_or(RecordError::BadField("direction", head[2].into()))?;
|
||||||
|
if head[3] != 0 {
|
||||||
|
return Err(RecordError::BadField("reserved", head[3].into()));
|
||||||
|
}
|
||||||
|
let word = |r: std::ops::Range<usize>| {
|
||||||
|
let mut b = [0u8; 8];
|
||||||
|
b[..r.len()].copy_from_slice(&head[r]);
|
||||||
|
u64::from_le_bytes(b)
|
||||||
|
};
|
||||||
|
let connection = word(4..8) as u32;
|
||||||
|
let time_micros = word(8..16);
|
||||||
|
let len = word(16..20) as usize;
|
||||||
|
if len > MAX_PAYLOAD {
|
||||||
|
return Err(RecordError::TooLarge(len));
|
||||||
|
}
|
||||||
|
let mut payload = vec![0u8; len];
|
||||||
|
if len > 0 && !read_full(input, &mut payload)? {
|
||||||
|
return Err(RecordError::Truncated);
|
||||||
|
}
|
||||||
|
Ok(Some(Record { kind, protocol, direction, connection, time_micros, payload }))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn sample(payload: &[u8]) -> Record {
|
||||||
|
Record {
|
||||||
|
kind: Kind::Data,
|
||||||
|
protocol: Protocol::Control,
|
||||||
|
direction: Direction::HostToClient,
|
||||||
|
connection: 0x0102_0304,
|
||||||
|
time_micros: 0x1122_3344_5566_7788,
|
||||||
|
payload: payload.to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn file(records: &[Record]) -> Vec<u8> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
write_header(&mut out, Header { start_unix_micros: 42 }).unwrap();
|
||||||
|
for r in records {
|
||||||
|
write_record(&mut out, r).unwrap();
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn header_layout_is_fixed() {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
write_header(&mut out, Header { start_unix_micros: 0x0807_0605_0403_0201 }).unwrap();
|
||||||
|
assert_eq!(out, b"DSLR\x01\0\0\0\x01\x02\x03\x04\x05\x06\x07\x08");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn record_layout_is_fixed() {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
write_record(&mut out, &sample(b"ab")).unwrap();
|
||||||
|
let mut want = vec![2, 6, 2, 0, 4, 3, 2, 1, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 2, 0, 0, 0];
|
||||||
|
want.extend_from_slice(b"ab");
|
||||||
|
assert_eq!(out, want);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn round_trip_of_every_code() {
|
||||||
|
let mut records = Vec::new();
|
||||||
|
for k in 1..=4 {
|
||||||
|
for p in 0..=8 {
|
||||||
|
for d in 0..=2 {
|
||||||
|
records.push(Record {
|
||||||
|
kind: Kind::from_code(k).unwrap(),
|
||||||
|
protocol: Protocol::from_code(p).unwrap(),
|
||||||
|
direction: Direction::from_code(d).unwrap(),
|
||||||
|
connection: u32::from(k) * 100 + u32::from(p),
|
||||||
|
time_micros: u64::from(d),
|
||||||
|
payload: vec![k, p, d],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
records.push(sample(&[]));
|
||||||
|
records.push(sample(&vec![0xAB; MAX_PAYLOAD]));
|
||||||
|
let bytes = file(&records);
|
||||||
|
let mut input = bytes.as_slice();
|
||||||
|
assert_eq!(read_header(&mut input).unwrap(), Header { start_unix_micros: 42 });
|
||||||
|
for want in &records {
|
||||||
|
assert_eq!(read_record(&mut input).unwrap().as_ref(), Some(want));
|
||||||
|
}
|
||||||
|
assert!(read_record(&mut input).unwrap().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn oversized_payload_is_refused_on_write() {
|
||||||
|
let err = write_record(&mut Vec::new(), &sample(&vec![0; MAX_PAYLOAD + 1])).unwrap_err();
|
||||||
|
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn oversized_length_is_refused_before_allocating() {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
write_record(&mut bytes, &sample(b"")).unwrap();
|
||||||
|
bytes[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||||
|
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::TooLarge(_))));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn every_cut_inside_a_record_is_truncated() {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
write_record(&mut bytes, &sample(b"payload")).unwrap();
|
||||||
|
for cut in 1..bytes.len() {
|
||||||
|
let r = read_record(&mut &bytes[..cut]);
|
||||||
|
assert!(matches!(r, Err(RecordError::Truncated)), "cut at {cut}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unknown_codes_and_reserved_bytes_are_refused() {
|
||||||
|
for (offset, value) in [(0, 0u8), (0, 5), (1, 9), (2, 3), (3, 1)] {
|
||||||
|
let mut bytes = Vec::new();
|
||||||
|
write_record(&mut bytes, &sample(b"x")).unwrap();
|
||||||
|
bytes[offset] = value;
|
||||||
|
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::BadField(..))), "{offset}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn bad_headers_are_refused() {
|
||||||
|
let good = file(&[]);
|
||||||
|
for (offset, value) in [(0, b'X'), (4, 2), (5, 1)] {
|
||||||
|
let mut bytes = good.clone();
|
||||||
|
bytes[offset] = value;
|
||||||
|
assert!(matches!(read_header(&mut bytes.as_slice()), Err(RecordError::BadHeader)));
|
||||||
|
}
|
||||||
|
assert!(matches!(read_header(&mut &good[..10]), Err(RecordError::Truncated)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A reader that hands out one byte per call, like a slow pipe.
|
||||||
|
struct Trickle<'a>(&'a [u8]);
|
||||||
|
impl Read for Trickle<'_> {
|
||||||
|
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||||
|
match (self.0.split_first(), buf.first_mut()) {
|
||||||
|
(Some((&b, rest)), Some(slot)) => {
|
||||||
|
*slot = b;
|
||||||
|
self.0 = rest;
|
||||||
|
Ok(1)
|
||||||
|
}
|
||||||
|
_ => Ok(0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn short_reads_are_reassembled() {
|
||||||
|
let bytes = file(&[sample(b"one"), sample(b"two")]);
|
||||||
|
let mut input = Trickle(&bytes);
|
||||||
|
read_header(&mut input).unwrap();
|
||||||
|
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"one");
|
||||||
|
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"two");
|
||||||
|
assert!(read_record(&mut input).unwrap().is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
//! The shared, thread-safe writer of the record file. Every record is flushed at once, so a killed relay leaves a
|
||||||
|
//! file that reads cleanly up to its last whole record.
|
||||||
|
|
||||||
|
use std::fs::{File, OpenOptions};
|
||||||
|
use std::io::{self, BufWriter, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::Mutex;
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||||
|
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
|
use crate::record::{self, Direction, Header, Kind, Protocol, Record};
|
||||||
|
|
||||||
|
/// Writes records for one capture.
|
||||||
|
pub struct Recorder {
|
||||||
|
out: Mutex<BufWriter<File>>,
|
||||||
|
start: Instant,
|
||||||
|
next_connection: AtomicU32,
|
||||||
|
failed: AtomicBool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Recorder {
|
||||||
|
/// Creates `session-<unix seconds>.dslr` in `dir` (never overwrites) and writes the header.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// I/O errors, including an existing file of the same name.
|
||||||
|
pub fn create(dir: &Path) -> io::Result<(Self, PathBuf)> {
|
||||||
|
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
|
||||||
|
let path = dir.join(format!("session-{}.dslr", now.as_secs()));
|
||||||
|
let file = OpenOptions::new().write(true).create_new(true).open(&path)?;
|
||||||
|
let mut out = BufWriter::new(file);
|
||||||
|
let start_unix_micros = u64::try_from(now.as_micros()).unwrap_or(u64::MAX);
|
||||||
|
record::write_header(&mut out, Header { start_unix_micros })?;
|
||||||
|
out.flush()?;
|
||||||
|
let rec = Self {
|
||||||
|
out: Mutex::new(out),
|
||||||
|
start: Instant::now(),
|
||||||
|
next_connection: AtomicU32::new(1),
|
||||||
|
failed: AtomicBool::new(false),
|
||||||
|
};
|
||||||
|
Ok((rec, path))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fresh connection or flow id.
|
||||||
|
pub fn new_connection(&self) -> u32 {
|
||||||
|
self.next_connection.fetch_add(1, Ordering::Relaxed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records bytes (split into several records if over [`record::MAX_PAYLOAD`]).
|
||||||
|
pub fn log(&self, kind: Kind, protocol: Protocol, direction: Direction, connection: u32, payload: &[u8]) {
|
||||||
|
let time_micros = u64::try_from(self.start.elapsed().as_micros()).unwrap_or(u64::MAX);
|
||||||
|
let chunks: Vec<&[u8]> =
|
||||||
|
if payload.is_empty() { vec![payload] } else { payload.chunks(record::MAX_PAYLOAD).collect() };
|
||||||
|
let Ok(mut out) = self.out.lock() else { return self.fail("lock poisoned") };
|
||||||
|
for chunk in chunks {
|
||||||
|
let r = Record { kind, protocol, direction, connection, time_micros, payload: chunk.to_vec() };
|
||||||
|
if let Err(e) = record::write_record(&mut *out, &r).and_then(|()| out.flush()) {
|
||||||
|
return self.fail(&e.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Records a note (never pass key material here).
|
||||||
|
pub fn note(&self, protocol: Protocol, connection: u32, text: &str) {
|
||||||
|
self.log(Kind::Note, protocol, Direction::None, connection, text.as_bytes());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reports the first write failure on stderr; later ones stay silent.
|
||||||
|
fn fail(&self, why: &str) {
|
||||||
|
if !self.failed.swap(true, Ordering::Relaxed) {
|
||||||
|
eprintln!("lab-relay: writing the record file failed: {why}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,122 @@
|
|||||||
|
//! Hides secrets when records are printed (`lab-relay dump`). The record file itself keeps everything; it never
|
||||||
|
//! leaves the lab folder.
|
||||||
|
|
||||||
|
/// Query parameters whose values are secret or let someone redo the pairing proofs.
|
||||||
|
pub const SECRET_PARAMS: [&str; 6] =
|
||||||
|
["rikey", "salt", "clientchallenge", "serverchallengeresp", "clientpairingsecret", "pin"];
|
||||||
|
/// XML elements whose text is secret.
|
||||||
|
pub const SECRET_ELEMENTS: [&str; 2] = ["challengeresponse", "pairingsecret"];
|
||||||
|
/// HTTP headers whose values are secret.
|
||||||
|
pub const SECRET_HEADERS: [&str; 2] = ["authorization", "cookie"];
|
||||||
|
/// What replaces a secret.
|
||||||
|
pub const MARK: &[u8] = b"<redacted>";
|
||||||
|
|
||||||
|
fn ends_param_value(b: u8) -> bool {
|
||||||
|
matches!(b, b'&' | b' ' | b'"' | b'\r' | b'\n' | b'<' | b'#')
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns `text` with every secret value replaced by [`MARK`].
|
||||||
|
pub fn redact(text: &[u8]) -> Vec<u8> {
|
||||||
|
let mut out = Vec::with_capacity(text.len());
|
||||||
|
let mut i = 0;
|
||||||
|
let lower: Vec<u8> = text.to_ascii_lowercase();
|
||||||
|
'scan: while i < text.len() {
|
||||||
|
// `name=` at a parameter boundary.
|
||||||
|
if i == 0 || matches!(text[i - 1], b'?' | b'&' | b' ' | b'\n') {
|
||||||
|
for name in SECRET_PARAMS {
|
||||||
|
let key = [name.as_bytes(), b"="].concat();
|
||||||
|
if lower[i..].starts_with(&key) {
|
||||||
|
out.extend_from_slice(&text[i..i + key.len()]);
|
||||||
|
out.extend_from_slice(MARK);
|
||||||
|
i += key.len();
|
||||||
|
while i < text.len() && !ends_param_value(text[i]) {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
continue 'scan;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// `<element>` … `</`.
|
||||||
|
if text[i] == b'<' {
|
||||||
|
for name in SECRET_ELEMENTS {
|
||||||
|
let open = [b"<", name.as_bytes(), b">"].concat();
|
||||||
|
if lower[i..].starts_with(&open) {
|
||||||
|
out.extend_from_slice(&text[i..i + open.len()]);
|
||||||
|
out.extend_from_slice(MARK);
|
||||||
|
i += open.len();
|
||||||
|
while i < text.len() && !text[i..].starts_with(b"</") {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
continue 'scan;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// `Header:` at a line start, up to the end of the line.
|
||||||
|
if i == 0 || text[i - 1] == b'\n' {
|
||||||
|
for name in SECRET_HEADERS {
|
||||||
|
let key = [name.as_bytes(), b":"].concat();
|
||||||
|
if lower[i..].starts_with(&key) {
|
||||||
|
out.extend_from_slice(&text[i..i + key.len()]);
|
||||||
|
out.extend_from_slice(b" ");
|
||||||
|
out.extend_from_slice(MARK);
|
||||||
|
i += key.len();
|
||||||
|
while i < text.len() && text[i] != b'\r' && text[i] != b'\n' {
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
continue 'scan;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.push(text[i]);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn r(s: &str) -> String {
|
||||||
|
String::from_utf8(redact(s.as_bytes())).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn launch_key_is_hidden() {
|
||||||
|
assert_eq!(
|
||||||
|
r("GET /launch?uniqueid=0123&appid=1&rikey=00112233445566778899aabbccddeeff&rikeyid=7 HTTP/1.1"),
|
||||||
|
"GET /launch?uniqueid=0123&appid=1&rikey=<redacted>&rikeyid=7 HTTP/1.1"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pairing_values_are_hidden_but_names_and_certs_stay() {
|
||||||
|
assert_eq!(
|
||||||
|
r("GET /pair?uniqueid=1&phrase=getservercert&salt=ABCD&clientcert=2D2D HTTP/1.1"),
|
||||||
|
"GET /pair?uniqueid=1&phrase=getservercert&salt=<redacted>&clientcert=2D2D HTTP/1.1"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
r("<root status_code=\"200\"><paired>1</paired><pairingsecret>ffee</pairingsecret></root>"),
|
||||||
|
"<root status_code=\"200\"><paired>1</paired><pairingsecret><redacted></pairingsecret></root>"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn auth_headers_are_hidden() {
|
||||||
|
assert_eq!(
|
||||||
|
r("POST /api/pin HTTP/1.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nHost: x\r\n"),
|
||||||
|
"POST /api/pin HTTP/1.1\r\nAuthorization: <redacted>\r\nHost: x\r\n"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lookalike_names_are_not_touched() {
|
||||||
|
assert_eq!(r("GET /x?rikeyid=5&nosalt=1"), "GET /x?rikeyid=5&nosalt=1");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn value_at_end_of_input_is_hidden() {
|
||||||
|
assert_eq!(r("?rikey=abc"), "?rikey=<redacted>");
|
||||||
|
assert_eq!(r("<challengeresponse>abc"), "<challengeresponse><redacted>");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,150 @@
|
|||||||
|
//! Equal-length byte replacement over a stream, safe across read boundaries.
|
||||||
|
//!
|
||||||
|
//! Bytes that could be the start of a pattern at the end of a chunk are held back until the next chunk (or
|
||||||
|
//! [`Rewriter::flush`]), so a pattern split over two reads is still found. Lengths never change, so HTTP
|
||||||
|
//! `Content-Length` stays right.
|
||||||
|
|
||||||
|
use crate::config::Rewrite;
|
||||||
|
|
||||||
|
/// A streaming rewriter.
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Rewriter {
|
||||||
|
rules: Vec<Rewrite>,
|
||||||
|
held: Vec<u8>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Rewriter {
|
||||||
|
/// A rewriter for `rules` (each non-empty, `from.len() == to.len()`, checked by the config).
|
||||||
|
pub fn new(rules: Vec<Rewrite>) -> Self {
|
||||||
|
Self { rules, held: Vec::new() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Feeds a chunk; returns the bytes that are safe to send and how many replacements were made.
|
||||||
|
pub fn push(&mut self, chunk: &[u8]) -> (Vec<u8>, usize) {
|
||||||
|
if self.rules.is_empty() {
|
||||||
|
return (chunk.to_vec(), 0);
|
||||||
|
}
|
||||||
|
let mut data = std::mem::take(&mut self.held);
|
||||||
|
data.extend_from_slice(chunk);
|
||||||
|
let mut out = Vec::with_capacity(data.len());
|
||||||
|
let mut count = 0;
|
||||||
|
let mut i = 0;
|
||||||
|
'scan: while i < data.len() {
|
||||||
|
for r in &self.rules {
|
||||||
|
if data[i..].starts_with(&r.from) {
|
||||||
|
out.extend_from_slice(&r.to);
|
||||||
|
i += r.from.len();
|
||||||
|
count += 1;
|
||||||
|
continue 'scan;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Could `data[i..]` be the beginning of a pattern that the next chunk completes?
|
||||||
|
let rest = &data[i..];
|
||||||
|
if self.rules.iter().any(|r| rest.len() < r.from.len() && r.from.starts_with(rest)) {
|
||||||
|
self.held = rest.to_vec();
|
||||||
|
return (out, count);
|
||||||
|
}
|
||||||
|
out.push(data[i]);
|
||||||
|
i += 1;
|
||||||
|
}
|
||||||
|
(out, count)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Releases held bytes (end of stream, or a pause in it).
|
||||||
|
pub fn flush(&mut self) -> Vec<u8> {
|
||||||
|
std::mem::take(&mut self.held)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether there are no rules (the rewriter then passes bytes through and never holds any).
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.rules.is_empty()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bytes currently held back.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn held(&self) -> usize {
|
||||||
|
self.held.len()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn lab() -> Rewriter {
|
||||||
|
Rewriter::new(vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn run(r: &mut Rewriter, chunks: &[&[u8]]) -> (Vec<u8>, usize) {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut n = 0;
|
||||||
|
for c in chunks {
|
||||||
|
let (o, k) = r.push(c);
|
||||||
|
out.extend(o);
|
||||||
|
n += k;
|
||||||
|
}
|
||||||
|
out.extend(r.flush());
|
||||||
|
(out, n)
|
||||||
|
}
|
||||||
|
|
||||||
|
const ANSWER: &[u8] = b"<root status_code=\"200\"><sessionUrl0>rtsp://127.0.0.2:48010</sessionUrl0></root>";
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replaces_in_one_chunk() {
|
||||||
|
let (out, n) = run(&mut lab(), &[ANSWER]);
|
||||||
|
assert_eq!(n, 1);
|
||||||
|
assert_eq!(out, ANSWER.to_vec().replace_all_for_test());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn replaces_across_every_split_point() {
|
||||||
|
let want = ANSWER.to_vec().replace_all_for_test();
|
||||||
|
for cut in 0..=ANSWER.len() {
|
||||||
|
let (out, n) = run(&mut lab(), &[&ANSWER[..cut], &ANSWER[cut..]]);
|
||||||
|
assert_eq!(n, 1, "cut {cut}");
|
||||||
|
assert_eq!(out, want, "cut {cut}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn byte_by_byte_works() {
|
||||||
|
let chunks: Vec<&[u8]> = ANSWER.chunks(1).collect();
|
||||||
|
let (out, n) = run(&mut lab(), &chunks);
|
||||||
|
assert_eq!((out, n), (ANSWER.to_vec().replace_all_for_test(), 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn length_never_changes_and_lookalikes_survive() {
|
||||||
|
let input = b"127.0.0.20 127.0.0.2127.0.0.2 127.0.0. 127.0.0.3";
|
||||||
|
let (out, n) = run(&mut lab(), &[input]);
|
||||||
|
assert_eq!(out.len(), input.len());
|
||||||
|
assert_eq!(out, b"127.0.0.10 127.0.0.1127.0.0.1 127.0.0. 127.0.0.3");
|
||||||
|
assert_eq!(n, 3);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn holds_only_a_possible_prefix() {
|
||||||
|
let mut r = lab();
|
||||||
|
let (out, _) = r.push(b"abc127.0.");
|
||||||
|
assert_eq!(out, b"abc");
|
||||||
|
assert_eq!(r.held(), 6);
|
||||||
|
let (out, n) = r.push(b"x");
|
||||||
|
assert_eq!((out, n), (b"127.0.x".to_vec(), 0));
|
||||||
|
assert_eq!(r.held(), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn no_rules_is_a_pass_through() {
|
||||||
|
let mut r = Rewriter::new(Vec::new());
|
||||||
|
assert_eq!(r.push(b"127.0.0.2"), (b"127.0.0.2".to_vec(), 0));
|
||||||
|
}
|
||||||
|
|
||||||
|
trait ReplaceAll {
|
||||||
|
fn replace_all_for_test(self) -> Vec<u8>;
|
||||||
|
}
|
||||||
|
impl ReplaceAll for Vec<u8> {
|
||||||
|
fn replace_all_for_test(self) -> Vec<u8> {
|
||||||
|
String::from_utf8(self).unwrap().replace("127.0.0.2", "127.0.0.1").into_bytes()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,133 @@
|
|||||||
|
//! Plain TCP relaying (HTTP, RTSP, and HTTPS in pass-through mode).
|
||||||
|
|
||||||
|
use std::io::{self, Read, Write};
|
||||||
|
use std::net::{Shutdown, TcpListener, TcpStream};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::thread;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::config::{Config, PortSpec, Rewrite};
|
||||||
|
use crate::record::{Direction, Kind, Protocol};
|
||||||
|
use crate::recorder::Recorder;
|
||||||
|
use crate::rewrite::Rewriter;
|
||||||
|
|
||||||
|
/// How long the host-to-client side waits for more bytes before releasing bytes held by the rewriter.
|
||||||
|
pub const HOLD_TIMEOUT: Duration = Duration::from_millis(50);
|
||||||
|
/// Timeout for connecting to Sunshine.
|
||||||
|
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
|
/// Whether a protocol's bytes are plaintext the rewriter may touch.
|
||||||
|
pub fn rewritable(protocol: Protocol) -> bool {
|
||||||
|
matches!(protocol, Protocol::Http | Protocol::Rtsp | Protocol::HttpsPlain)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accepts connections on `spec`'s port forever.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Binding fails.
|
||||||
|
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
|
||||||
|
let listener = TcpListener::bind(config.listen_addr(&spec))?;
|
||||||
|
for client in listener.incoming() {
|
||||||
|
let client = match client {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
rec.note(spec.protocol, 0, &format!("accept failed: {e}"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
|
||||||
|
thread::spawn(move || {
|
||||||
|
let conn = rec.new_connection();
|
||||||
|
if let Err(e) = relay(client, &config, spec, &rec, conn) {
|
||||||
|
rec.note(spec.protocol, conn, &format!("connection ended with error: {e}"));
|
||||||
|
}
|
||||||
|
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
|
||||||
|
let upstream_addr = config.upstream_addr(&spec);
|
||||||
|
let peer = client.peer_addr()?;
|
||||||
|
rec.log(Kind::Open, spec.protocol, Direction::None, conn, format!("{peer} -> {upstream_addr}").as_bytes());
|
||||||
|
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
|
||||||
|
let _ = client.set_nodelay(true);
|
||||||
|
let _ = upstream.set_nodelay(true);
|
||||||
|
let rules = if rewritable(spec.protocol) { config.rewrites.clone() } else { Vec::new() };
|
||||||
|
pump_pair(client, upstream, spec.protocol, rec, conn, rules)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Copies both directions until both sides are closed; rewrites host-to-client bytes with `rules`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Socket errors.
|
||||||
|
pub fn pump_pair(
|
||||||
|
client: TcpStream,
|
||||||
|
upstream: TcpStream,
|
||||||
|
protocol: Protocol,
|
||||||
|
rec: &Recorder,
|
||||||
|
conn: u32,
|
||||||
|
rules: Vec<Rewrite>,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
let (mut c_read, mut u_write) = (client.try_clone()?, upstream.try_clone()?);
|
||||||
|
thread::scope(|s| {
|
||||||
|
s.spawn(|| {
|
||||||
|
let mut buf = vec![0u8; 64 * 1024];
|
||||||
|
loop {
|
||||||
|
match c_read.read(&mut buf) {
|
||||||
|
Ok(0) | Err(_) => break,
|
||||||
|
Ok(n) => {
|
||||||
|
rec.log(Kind::Data, protocol, Direction::ClientToHost, conn, &buf[..n]);
|
||||||
|
if u_write.write_all(&buf[..n]).is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let _ = u_write.shutdown(Shutdown::Write);
|
||||||
|
});
|
||||||
|
host_to_client(upstream, client, protocol, rec, conn, rules)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn host_to_client(
|
||||||
|
mut upstream: TcpStream,
|
||||||
|
mut client: TcpStream,
|
||||||
|
protocol: Protocol,
|
||||||
|
rec: &Recorder,
|
||||||
|
conn: u32,
|
||||||
|
rules: Vec<Rewrite>,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
let mut rewriter = Rewriter::new(rules);
|
||||||
|
if !rewriter.is_empty() {
|
||||||
|
upstream.set_read_timeout(Some(HOLD_TIMEOUT))?;
|
||||||
|
}
|
||||||
|
let mut buf = vec![0u8; 64 * 1024];
|
||||||
|
let result = loop {
|
||||||
|
match upstream.read(&mut buf) {
|
||||||
|
Ok(0) => break Ok(()),
|
||||||
|
Ok(n) => {
|
||||||
|
rec.log(Kind::Data, protocol, Direction::HostToClient, conn, &buf[..n]);
|
||||||
|
let (out, count) = rewriter.push(&buf[..n]);
|
||||||
|
if count > 0 {
|
||||||
|
rec.note(protocol, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
|
||||||
|
}
|
||||||
|
if let Err(e) = client.write_all(&out) {
|
||||||
|
break Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
|
||||||
|
let held = rewriter.flush();
|
||||||
|
if let Err(e) = client.write_all(&held) {
|
||||||
|
break Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => break Err(e),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let rest = rewriter.flush();
|
||||||
|
let _ = client.write_all(&rest);
|
||||||
|
let _ = client.shutdown(Shutdown::Write);
|
||||||
|
result
|
||||||
|
}
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
//! TLS termination on the HTTPS port (LAB_CAPTURE.md section 4).
|
||||||
|
//!
|
||||||
|
//! Towards Moonlight the relay presents Sunshine's own lab certificate, the one Moonlight pinned while pairing, and
|
||||||
|
//! asks for (but accepts any) client certificate. Towards Sunshine it presents Moonlight's own lab client
|
||||||
|
//! certificate and accepts only Sunshine's lab certificate. Both sides see the certificates they expect; the relay
|
||||||
|
//! records the plaintext in between. All key material is lab-only and is never written to the record file.
|
||||||
|
|
||||||
|
use std::io::{self, Read, Write};
|
||||||
|
use std::net::{TcpListener, TcpStream};
|
||||||
|
use std::path::Path;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::thread;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
|
||||||
|
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
|
||||||
|
use rustls::pki_types::pem::PemObject;
|
||||||
|
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
|
||||||
|
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
|
||||||
|
use rustls::{ClientConfig, ClientConnection, Connection, DigitallySignedStruct, DistinguishedName, ServerConfig};
|
||||||
|
use rustls::{ServerConnection, SignatureScheme};
|
||||||
|
|
||||||
|
use crate::config::{Config, PortSpec, TlsFiles};
|
||||||
|
use crate::record::{Direction, Kind, Protocol};
|
||||||
|
use crate::recorder::Recorder;
|
||||||
|
use crate::rewrite::Rewriter;
|
||||||
|
use crate::tcp::{self, CONNECT_TIMEOUT};
|
||||||
|
|
||||||
|
/// Read timeout while pumping plaintext between the two TLS sessions.
|
||||||
|
const POLL: Duration = Duration::from_millis(20);
|
||||||
|
|
||||||
|
/// Accepts connections on the HTTPS port forever.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Binding fails.
|
||||||
|
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
|
||||||
|
let listener = TcpListener::bind(config.listen_addr(&spec))?;
|
||||||
|
for client in listener.incoming() {
|
||||||
|
let client = match client {
|
||||||
|
Ok(c) => c,
|
||||||
|
Err(e) => {
|
||||||
|
rec.note(Protocol::HttpsPlain, 0, &format!("accept failed: {e}"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
|
||||||
|
thread::spawn(move || {
|
||||||
|
let conn = rec.new_connection();
|
||||||
|
if let Err(e) = relay(client, &config, spec, &rec, conn) {
|
||||||
|
rec.note(Protocol::HttpsPlain, conn, &format!("connection ended with error: {e}"));
|
||||||
|
}
|
||||||
|
rec.log(Kind::Close, Protocol::HttpsPlain, Direction::None, conn, &[]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lab TLS material, loaded per connection (Moonlight's key may appear only after pairing step 1).
|
||||||
|
struct Material {
|
||||||
|
host_certs: Vec<CertificateDer<'static>>,
|
||||||
|
host_key: PrivateKeyDer<'static>,
|
||||||
|
client_certs: Vec<CertificateDer<'static>>,
|
||||||
|
client_key: PrivateKeyDer<'static>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn load(files: &TlsFiles) -> io::Result<Material> {
|
||||||
|
fn certs(path: &Path) -> io::Result<Vec<CertificateDer<'static>>> {
|
||||||
|
let certs = CertificateDer::pem_file_iter(path)
|
||||||
|
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?
|
||||||
|
.collect::<Result<Vec<_>, _>>()
|
||||||
|
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?;
|
||||||
|
if certs.is_empty() {
|
||||||
|
return Err(io::Error::other(format!("{}: no certificate", path.display())));
|
||||||
|
}
|
||||||
|
Ok(certs)
|
||||||
|
}
|
||||||
|
fn key(path: &Path) -> io::Result<PrivateKeyDer<'static>> {
|
||||||
|
// The error text names the file only; it never echoes key bytes.
|
||||||
|
PrivateKeyDer::from_pem_file(path).map_err(|_| io::Error::other(format!("{}: no usable key", path.display())))
|
||||||
|
}
|
||||||
|
Ok(Material {
|
||||||
|
host_certs: certs(&files.host_cert)?,
|
||||||
|
host_key: key(&files.host_key)?,
|
||||||
|
client_certs: certs(&files.client_cert)?,
|
||||||
|
client_key: key(&files.client_key)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Waits up to `wait` for all four files to load.
|
||||||
|
fn load_waiting(files: &TlsFiles, wait: Duration) -> io::Result<Material> {
|
||||||
|
let deadline = Instant::now() + wait;
|
||||||
|
loop {
|
||||||
|
match load(files) {
|
||||||
|
Ok(m) => return Ok(m),
|
||||||
|
Err(e) if Instant::now() >= deadline => return Err(e),
|
||||||
|
Err(_) => thread::sleep(Duration::from_millis(200)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn sha256_hex(bytes: &[u8]) -> String {
|
||||||
|
ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|b| format!("{b:02x}")).collect()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
|
||||||
|
let upstream_addr = config.upstream_addr(&spec);
|
||||||
|
let peer = client.peer_addr()?;
|
||||||
|
rec.log(
|
||||||
|
Kind::Open,
|
||||||
|
Protocol::HttpsPlain,
|
||||||
|
Direction::None,
|
||||||
|
conn,
|
||||||
|
format!("{peer} -> {upstream_addr} (TLS terminated)").as_bytes(),
|
||||||
|
);
|
||||||
|
let Some(files) = &config.tls else {
|
||||||
|
return Err(io::Error::other("TLS files not configured"));
|
||||||
|
};
|
||||||
|
let material = match load_waiting(files, config.wait_for_keys) {
|
||||||
|
Ok(m) => m,
|
||||||
|
Err(e) => {
|
||||||
|
// No keys: carry the raw TLS bytes, so the session still works and is still recorded.
|
||||||
|
rec.note(Protocol::HttpsTls, conn, &format!("lab keys not available ({e}); passing TLS through"));
|
||||||
|
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
|
||||||
|
return tcp::pump_pair(client, upstream, Protocol::HttpsTls, rec, conn, Vec::new());
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||||
|
let algs = provider.signature_verification_algorithms;
|
||||||
|
let server_config = ServerConfig::builder_with_provider(Arc::clone(&provider))
|
||||||
|
.with_safe_default_protocol_versions()
|
||||||
|
.map_err(io::Error::other)?
|
||||||
|
.with_client_cert_verifier(Arc::new(AnyClientCert { algs }))
|
||||||
|
.with_single_cert(material.host_certs.clone(), material.host_key)
|
||||||
|
.map_err(io::Error::other)?;
|
||||||
|
let pinned = material.host_certs[0].as_ref().to_vec();
|
||||||
|
let client_config = client_config(&provider, pinned, material.client_certs.clone(), material.client_key)?;
|
||||||
|
|
||||||
|
// Moonlight side first: it has already sent its ClientHello.
|
||||||
|
let mut moonlight = client;
|
||||||
|
let mut down = Connection::Server(ServerConnection::new(Arc::new(server_config)).map_err(io::Error::other)?);
|
||||||
|
while down.is_handshaking() {
|
||||||
|
down.complete_io(&mut moonlight)?;
|
||||||
|
}
|
||||||
|
let presented = down.peer_certificates().and_then(|c| c.first()).map(|c| sha256_hex(c.as_ref()));
|
||||||
|
let expected = sha256_hex(material.client_certs[0].as_ref());
|
||||||
|
rec.note(
|
||||||
|
Protocol::HttpsPlain,
|
||||||
|
conn,
|
||||||
|
&format!(
|
||||||
|
"client side: {:?}, {:?}, client certificate sha256 {} ({})",
|
||||||
|
down.protocol_version(),
|
||||||
|
down.negotiated_cipher_suite().map(|s| s.suite()),
|
||||||
|
presented.as_deref().unwrap_or("none"),
|
||||||
|
if presented.as_deref() == Some(expected.as_str()) {
|
||||||
|
"matches the lab client certificate"
|
||||||
|
} else {
|
||||||
|
"differs from the lab client certificate"
|
||||||
|
},
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
let mut sunshine = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
|
||||||
|
let name = ServerName::from(upstream_addr.ip());
|
||||||
|
let mut up = Connection::Client(ClientConnection::new(Arc::new(client_config), name).map_err(io::Error::other)?);
|
||||||
|
while up.is_handshaking() {
|
||||||
|
up.complete_io(&mut sunshine)?;
|
||||||
|
}
|
||||||
|
rec.note(
|
||||||
|
Protocol::HttpsPlain,
|
||||||
|
conn,
|
||||||
|
&format!("host side: {:?}, {:?}", up.protocol_version(), up.negotiated_cipher_suite().map(|s| s.suite())),
|
||||||
|
);
|
||||||
|
|
||||||
|
for s in [&moonlight, &sunshine] {
|
||||||
|
s.set_read_timeout(Some(POLL))?;
|
||||||
|
let _ = s.set_nodelay(true);
|
||||||
|
}
|
||||||
|
pump(&mut down, &mut moonlight, &mut up, &mut sunshine, rec, conn, Rewriter::new(config.rewrites.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_config(
|
||||||
|
provider: &Arc<CryptoProvider>,
|
||||||
|
pinned: Vec<u8>,
|
||||||
|
certs: Vec<CertificateDer<'static>>,
|
||||||
|
key: PrivateKeyDer<'static>,
|
||||||
|
) -> io::Result<ClientConfig> {
|
||||||
|
let algs = provider.signature_verification_algorithms;
|
||||||
|
ClientConfig::builder_with_provider(Arc::clone(provider))
|
||||||
|
.with_safe_default_protocol_versions()
|
||||||
|
.map_err(io::Error::other)?
|
||||||
|
.dangerous()
|
||||||
|
.with_custom_certificate_verifier(Arc::new(PinnedHost { pinned, algs }))
|
||||||
|
.with_client_auth_cert(certs, key)
|
||||||
|
.map_err(io::Error::other)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Moves plaintext both ways until both sides are done.
|
||||||
|
fn pump(
|
||||||
|
down: &mut Connection,
|
||||||
|
moonlight: &mut TcpStream,
|
||||||
|
up: &mut Connection,
|
||||||
|
sunshine: &mut TcpStream,
|
||||||
|
rec: &Recorder,
|
||||||
|
conn: u32,
|
||||||
|
mut rewriter: Rewriter,
|
||||||
|
) -> io::Result<()> {
|
||||||
|
let (mut down_open, mut up_open) = (true, true);
|
||||||
|
while down_open || up_open {
|
||||||
|
if down_open {
|
||||||
|
let (data, eof) = pull(down, moonlight)?;
|
||||||
|
if !data.is_empty() {
|
||||||
|
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::ClientToHost, conn, &data);
|
||||||
|
if up_open {
|
||||||
|
push(up, sunshine, &data)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if eof {
|
||||||
|
down_open = false;
|
||||||
|
if up_open {
|
||||||
|
up.send_close_notify();
|
||||||
|
flush(up, sunshine)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if up_open {
|
||||||
|
let (data, eof) = pull(up, sunshine)?;
|
||||||
|
if data.is_empty() {
|
||||||
|
let held = rewriter.flush();
|
||||||
|
if !held.is_empty() && down_open {
|
||||||
|
push(down, moonlight, &held)?;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::HostToClient, conn, &data);
|
||||||
|
let (out, count) = rewriter.push(&data);
|
||||||
|
if count > 0 {
|
||||||
|
rec.note(Protocol::HttpsPlain, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
|
||||||
|
}
|
||||||
|
if down_open {
|
||||||
|
push(down, moonlight, &out)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if eof {
|
||||||
|
up_open = false;
|
||||||
|
if down_open {
|
||||||
|
let held = rewriter.flush();
|
||||||
|
push(down, moonlight, &held)?;
|
||||||
|
down.send_close_notify();
|
||||||
|
flush(down, moonlight)?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reads what TLS bytes are there (or waits [`POLL`]) and returns the new plaintext and whether the peer is done.
|
||||||
|
fn pull(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<(Vec<u8>, bool)> {
|
||||||
|
let mut eof = false;
|
||||||
|
match conn.read_tls(sock) {
|
||||||
|
Ok(0) => eof = true,
|
||||||
|
Ok(_) => {
|
||||||
|
conn.process_new_packets().map_err(io::Error::other)?;
|
||||||
|
}
|
||||||
|
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
let mut data = Vec::new();
|
||||||
|
let mut buf = [0u8; 16 * 1024];
|
||||||
|
loop {
|
||||||
|
match conn.reader().read(&mut buf) {
|
||||||
|
Ok(0) => {
|
||||||
|
eof = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Ok(n) => data.extend_from_slice(&buf[..n]),
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
|
||||||
|
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
|
||||||
|
eof = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush(conn, sock)?;
|
||||||
|
Ok((data, eof))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn push(conn: &mut Connection, sock: &mut TcpStream, data: &[u8]) -> io::Result<()> {
|
||||||
|
conn.writer().write_all(data)?;
|
||||||
|
flush(conn, sock)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn flush(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<()> {
|
||||||
|
while conn.wants_write() {
|
||||||
|
conn.write_tls(sock)?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accepts any client certificate (it is recorded by fingerprint, and Sunshine checks the real one).
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct AnyClientCert {
|
||||||
|
algs: WebPkiSupportedAlgorithms,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ClientCertVerifier for AnyClientCert {
|
||||||
|
fn offer_client_auth(&self) -> bool {
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_auth_mandatory(&self) -> bool {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn root_hint_subjects(&self) -> &[DistinguishedName] {
|
||||||
|
&[]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_client_cert(
|
||||||
|
&self,
|
||||||
|
_end_entity: &CertificateDer<'_>,
|
||||||
|
_intermediates: &[CertificateDer<'_>],
|
||||||
|
_now: UnixTime,
|
||||||
|
) -> Result<ClientCertVerified, rustls::Error> {
|
||||||
|
Ok(ClientCertVerified::assertion())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls12_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &DigitallySignedStruct,
|
||||||
|
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||||
|
verify_tls12_signature(message, cert, dss, &self.algs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls13_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &DigitallySignedStruct,
|
||||||
|
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||||
|
verify_tls13_signature(message, cert, dss, &self.algs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||||
|
self.algs.supported_schemes()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Accepts exactly Sunshine's lab certificate, byte for byte.
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct PinnedHost {
|
||||||
|
pinned: Vec<u8>,
|
||||||
|
algs: WebPkiSupportedAlgorithms,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServerCertVerifier for PinnedHost {
|
||||||
|
fn verify_server_cert(
|
||||||
|
&self,
|
||||||
|
end_entity: &CertificateDer<'_>,
|
||||||
|
_intermediates: &[CertificateDer<'_>],
|
||||||
|
_server_name: &ServerName<'_>,
|
||||||
|
_ocsp_response: &[u8],
|
||||||
|
_now: UnixTime,
|
||||||
|
) -> Result<ServerCertVerified, rustls::Error> {
|
||||||
|
if end_entity.as_ref() == self.pinned.as_slice() {
|
||||||
|
Ok(ServerCertVerified::assertion())
|
||||||
|
} else {
|
||||||
|
Err(rustls::Error::General("host certificate is not the pinned lab certificate".into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls12_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &DigitallySignedStruct,
|
||||||
|
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||||
|
verify_tls12_signature(message, cert, dss, &self.algs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls13_signature(
|
||||||
|
&self,
|
||||||
|
message: &[u8],
|
||||||
|
cert: &CertificateDer<'_>,
|
||||||
|
dss: &DigitallySignedStruct,
|
||||||
|
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||||
|
verify_tls13_signature(message, cert, dss, &self.algs)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||||
|
self.algs.supported_schemes()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
//! UDP relaying (video, control, audio, mic).
|
||||||
|
//!
|
||||||
|
//! Each client address gets its own upstream socket on the listen address, so Sunshine sends the stream to the
|
||||||
|
//! relay (the address its PING or ENet connect came from) and the relay hands it to Moonlight.
|
||||||
|
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::io;
|
||||||
|
use std::net::{SocketAddr, UdpSocket};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
use std::thread;
|
||||||
|
|
||||||
|
use crate::config::{Config, PortSpec};
|
||||||
|
use crate::record::{Direction, Kind};
|
||||||
|
use crate::recorder::Recorder;
|
||||||
|
|
||||||
|
/// Most client flows per port (one Moonlight uses one).
|
||||||
|
pub const MAX_FLOWS: usize = 16;
|
||||||
|
/// Largest datagram.
|
||||||
|
pub const MAX_DATAGRAM: usize = 64 * 1024;
|
||||||
|
|
||||||
|
/// Windows reports an ICMP "port unreachable" from an earlier send as a reset on the next receive; that is not
|
||||||
|
/// fatal for UDP.
|
||||||
|
fn transient(e: &io::Error) -> bool {
|
||||||
|
matches!(e.kind(), io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionRefused | io::ErrorKind::Interrupted)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Relays one UDP port forever.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
/// Binding fails.
|
||||||
|
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
|
||||||
|
let listen = Arc::new(UdpSocket::bind(config.listen_addr(&spec))?);
|
||||||
|
let upstream_addr = config.upstream_addr(&spec);
|
||||||
|
let flows: Mutex<HashMap<SocketAddr, (Arc<UdpSocket>, u32)>> = Mutex::new(HashMap::new());
|
||||||
|
let mut buf = vec![0u8; MAX_DATAGRAM];
|
||||||
|
loop {
|
||||||
|
let (n, from) = match listen.recv_from(&mut buf) {
|
||||||
|
Ok(v) => v,
|
||||||
|
Err(e) if transient(&e) => continue,
|
||||||
|
Err(e) => {
|
||||||
|
rec.note(spec.protocol, 0, &format!("receive failed: {e}"));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let flow = {
|
||||||
|
let Ok(mut map) = flows.lock() else { return Err(io::Error::other("flow table poisoned")) };
|
||||||
|
if let Some(f) = map.get(&from) {
|
||||||
|
Some(f.clone())
|
||||||
|
} else if map.len() >= MAX_FLOWS {
|
||||||
|
rec.note(spec.protocol, 0, &format!("dropping datagram from {from}: flow table full"));
|
||||||
|
None
|
||||||
|
} else {
|
||||||
|
let up = Arc::new(UdpSocket::bind(SocketAddr::new(config.listen, 0))?);
|
||||||
|
up.connect(upstream_addr)?;
|
||||||
|
let conn = rec.new_connection();
|
||||||
|
rec.log(
|
||||||
|
Kind::Open,
|
||||||
|
spec.protocol,
|
||||||
|
Direction::None,
|
||||||
|
conn,
|
||||||
|
format!("{from} -> {upstream_addr}").as_bytes(),
|
||||||
|
);
|
||||||
|
spawn_return_path(Arc::clone(&up), Arc::clone(&listen), from, spec, Arc::clone(&rec), conn);
|
||||||
|
map.insert(from, (Arc::clone(&up), conn));
|
||||||
|
Some((up, conn))
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let Some((up, conn)) = flow else { continue };
|
||||||
|
rec.log(Kind::Data, spec.protocol, Direction::ClientToHost, conn, &buf[..n]);
|
||||||
|
if let Err(e) = up.send(&buf[..n])
|
||||||
|
&& !transient(&e)
|
||||||
|
{
|
||||||
|
rec.note(spec.protocol, conn, &format!("send to host failed: {e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn_return_path(
|
||||||
|
up: Arc<UdpSocket>,
|
||||||
|
listen: Arc<UdpSocket>,
|
||||||
|
client: SocketAddr,
|
||||||
|
spec: PortSpec,
|
||||||
|
rec: Arc<Recorder>,
|
||||||
|
conn: u32,
|
||||||
|
) {
|
||||||
|
thread::spawn(move || {
|
||||||
|
let mut buf = vec![0u8; MAX_DATAGRAM];
|
||||||
|
loop {
|
||||||
|
match up.recv(&mut buf) {
|
||||||
|
Ok(n) => {
|
||||||
|
rec.log(Kind::Data, spec.protocol, Direction::HostToClient, conn, &buf[..n]);
|
||||||
|
if let Err(e) = listen.send_to(&buf[..n], client)
|
||||||
|
&& !transient(&e)
|
||||||
|
{
|
||||||
|
rec.note(spec.protocol, conn, &format!("send to client failed: {e}"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) if transient(&e) => {}
|
||||||
|
Err(e) => {
|
||||||
|
rec.note(spec.protocol, conn, &format!("receive from host failed: {e}"));
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
"""Mutation pass for DomiStream (QA, 2026-11-26); results in docs/MUTATION.md.
|
||||||
|
|
||||||
|
For each mutation: apply exact edits to src (and Cargo files), run the guarding test binary through the resource gate,
|
||||||
|
record which tests failed (caught) or whether it did not compile, then revert with `git checkout`. Writes
|
||||||
|
results.json and one log per mutation to DOMISTREAM_QA_DIR (default target/mutation). Run it only on a clean tree:
|
||||||
|
the revert checks out the touched src files and Cargo.lock.
|
||||||
|
|
||||||
|
python tools/mutation/mutate.py [ID ...]
|
||||||
|
"""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
|
||||||
|
REPO = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||||
|
# Logs and results.json; the gate is a PowerShell script taking the command, exiting 75 while the PC is busy.
|
||||||
|
QA = os.environ.get("DOMISTREAM_QA_DIR", os.path.join(REPO, "target", "mutation"))
|
||||||
|
GATE = os.environ.get("DOMISTREAM_GATE", os.path.join(QA, "gate.ps1"))
|
||||||
|
os.makedirs(QA, exist_ok=True)
|
||||||
|
SRC = "crates/domistream/src/"
|
||||||
|
|
||||||
|
M = []
|
||||||
|
|
||||||
|
|
||||||
|
def mut(id_, area, what, test, edits):
|
||||||
|
M.append({"id": id_, "area": area, "what": what, "test": test, "edits": edits})
|
||||||
|
|
||||||
|
|
||||||
|
# ---- parser caps
|
||||||
|
mut("M1", "xml cap", "size cap off by one (refuses exactly MAX_XML_BYTES)", "http",
|
||||||
|
[(SRC + "http/xml.rs", 'cap("xml document", MAX_XML_BYTES, body.len())?;',
|
||||||
|
'cap("xml document", MAX_XML_BYTES - 1, body.len())?;')])
|
||||||
|
mut("M2", "xml cap", "depth cap off by one (allows depth 9)", "http",
|
||||||
|
[(SRC + "http/xml.rs", 'cap("xml depth", MAX_XML_DEPTH, stack.len() + 1)?;',
|
||||||
|
'cap("xml depth", MAX_XML_DEPTH + 1, stack.len() + 1)?;')])
|
||||||
|
mut("M3", "rtsp cap", "header cap off by one (allows 65 headers)", "rtsp",
|
||||||
|
[(SRC + "rtsp/mod.rs", 'cap("rtsp headers", MAX_RTSP_HEADERS, headers.len())?;',
|
||||||
|
'cap("rtsp headers", MAX_RTSP_HEADERS + 1, headers.len())?;')])
|
||||||
|
mut("M4", "enet cap", "command cap off by one (allows 33 commands)", "enet",
|
||||||
|
[(SRC + "enet/protocol.rs", 'cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, commands.len() + 1)?;',
|
||||||
|
'cap("enet commands", MAX_COMMANDS_PER_DATAGRAM, commands.len())?;')])
|
||||||
|
mut("M5", "input cap", "message size cap removed", "input",
|
||||||
|
[(SRC + "input/mod.rs", " crate::util::cap(W, MAX_INPUT_MESSAGE_BYTES, message.len())?;\n",
|
||||||
|
" let _ = MAX_INPUT_MESSAGE_BYTES;\n")])
|
||||||
|
mut("M6", "video cap", "packet size cap off by one (accepts 4097 bytes)", "media",
|
||||||
|
[(SRC + "video/packet.rs", "crate::util::cap(W, MAX_VIDEO_PACKET_BYTES, packet.len())?;",
|
||||||
|
"crate::util::cap(W, MAX_VIDEO_PACKET_BYTES + 1, packet.len())?;")])
|
||||||
|
mut("M7", "audio cap", "packet size cap removed", "media",
|
||||||
|
[(SRC + "audio/packet.rs", " crate::util::cap(W, MAX_AUDIO_PACKET_BYTES, packet.len())?;\n",
|
||||||
|
" let _ = MAX_AUDIO_PACKET_BYTES;\n")])
|
||||||
|
# ---- lying lengths
|
||||||
|
mut("M8", "lying length", "control frame: a length field that claims less is accepted", "control",
|
||||||
|
[(SRC + "control/frame.rs", "if usize::from(u16_le(W, frame, 2)?) != frame.len() - 4 {",
|
||||||
|
"if usize::from(u16_le(W, frame, 2)?) > frame.len() - 4 {")])
|
||||||
|
mut("M9", "lying length", "RTSP: bytes after Content-Length are kept instead of refused", "rtsp",
|
||||||
|
[(SRC + "rtsp/mod.rs", 'Some(n) if rest.len() > n => return Err(malformed("rtsp: bytes after the payload")),',
|
||||||
|
"Some(n) if rest.len() > n => rest.get(..n).unwrap_or(rest).to_vec(),")])
|
||||||
|
mut("M10", "lying length", "INPUT_DATA: the big-endian size field is not checked", "input",
|
||||||
|
[(SRC + "input/mod.rs", "if usize::try_from(u32_be(W, message, 4)?).ok() != Some(message.len() - 8) {",
|
||||||
|
"if usize::try_from(u32_be(W, message, 4)?).is_err() {")])
|
||||||
|
# ---- sequence numbers and crypto
|
||||||
|
mut("M11", "enet wrap", "reliable delivery does not wrap at 0xFFFF (saturating next)", "enet",
|
||||||
|
[(SRC + "enet/mod.rs",
|
||||||
|
" let next = ch.in_reliable.wrapping_add(1);\n let Some(p) = ch.pending.remove(&next)",
|
||||||
|
" let next = ch.in_reliable.saturating_add(1);\n let Some(p) = ch.pending.remove(&next)")])
|
||||||
|
mut("M12", "control replay", "replay check accepts a repeated sequence number (seq < last instead of <=)", "control",
|
||||||
|
[(SRC + "control/mod.rs", "if self.last_host_sequence.is_some_and(|last| sequence <= last) {",
|
||||||
|
"if self.last_host_sequence.is_some_and(|last| sequence < last) {")])
|
||||||
|
mut("M13", "control replay", "replay check removed", "control",
|
||||||
|
[(SRC + "control/mod.rs", "if self.last_host_sequence.is_some_and(|last| sequence <= last) {",
|
||||||
|
"if self.last_host_sequence.is_some_and(|last| sequence <= last && false) {")])
|
||||||
|
mut("M14", "nonce", "direction bytes swapped ('H' client to host)", "control",
|
||||||
|
[(SRC + "control/frame.rs", " Direction::ClientToHost => b'C',\n Direction::HostToClient => b'H',",
|
||||||
|
" Direction::ClientToHost => b'H',\n Direction::HostToClient => b'C',")])
|
||||||
|
mut("M15", "GCM tag", "control open ignores a failed tag check", "control",
|
||||||
|
[(SRC + "control/frame.rs", " .map_err(|_| Error::Crypto)?;\n Ok((f.sequence, body))",
|
||||||
|
" .ok();\n Ok((f.sequence, body))")])
|
||||||
|
mut("M24", "GCM tag", "video decrypt ignores a failed tag check", "media",
|
||||||
|
[(SRC + "video/mod.rs", " .map_err(|_| Error::Crypto)?;\n Ok(body)",
|
||||||
|
" .ok();\n Ok(body)")])
|
||||||
|
# ---- FEC
|
||||||
|
mut("M16", "FEC index", "video parity shard stored one index too high", "video",
|
||||||
|
[(SRC + "video/mod.rs", "block.shards.insert(fec.shard_index, p.payload.to_vec());",
|
||||||
|
"block.shards.insert(if fec.shard_index >= fec.data_shards { fec.shard_index + 1 } else { fec.shard_index }, p.payload.to_vec());")])
|
||||||
|
mut("M17", "video header", "recovered shard's bytes 0-31 trusted (full-packet shards, SOF flag read from a rebuilt shard)", "video",
|
||||||
|
[(SRC + "video/mod.rs", "fn store(&mut self, frame: u32, p: &VideoPacket<'_>, now: Instant) -> bool {",
|
||||||
|
"fn store(&mut self, frame: u32, p: &VideoPacket<'_>, raw: &[u8], now: Instant) -> bool {"),
|
||||||
|
(SRC + "video/mod.rs", "let accepted = self.store(frame, &p, now);", "let accepted = self.store(frame, &p, bytes, now);"),
|
||||||
|
(SRC + "video/mod.rs", "block.shards.insert(fec.shard_index, p.payload.to_vec());",
|
||||||
|
"block.shards.insert(fec.shard_index, raw.to_vec());"),
|
||||||
|
(SRC + "video/mod.rs", " data.extend_from_slice(block.shards.get(&i)?);",
|
||||||
|
" data.extend_from_slice(block.shards.get(&i)?.get(packet::PAYLOAD_OFFSET..)?);"),
|
||||||
|
(SRC + "video/mod.rs",
|
||||||
|
" for s in shards.iter().take(k) {\n data.extend_from_slice(s.as_ref()?);\n }",
|
||||||
|
" if b == 0 && !block.shards.contains_key(&0) && shards.first()?.as_ref()?.get(24)? & 0x04 == 0 {\n"
|
||||||
|
" return None;\n }\n"
|
||||||
|
" for s in shards.iter().take(k) {\n data.extend_from_slice(s.as_ref()?.get(packet::PAYLOAD_OFFSET..)?);\n }")])
|
||||||
|
mut("M18", "audio parity", "parity keyed by its own RTP sequence, not the FEC header's base", "audio",
|
||||||
|
[(SRC + "audio/mod.rs", "AudioPacket::Parity { fec, parity, .. } => {\n let base = fec.base_sequence;",
|
||||||
|
"AudioPacket::Parity { rtp, fec, parity } => {\n let base = rtp.sequence & !3;")])
|
||||||
|
# ---- pairing
|
||||||
|
mut("M19", "pairing skip", "no pairingsecret: skip the proof and the signature, go to step 4", "pairing",
|
||||||
|
[(SRC + "pairing/mod.rs",
|
||||||
|
' let ps = answer.pairing_secret.ok_or_else(|| bad(malformed("pairing: no pairingsecret")))?;',
|
||||||
|
" let Some(ps) = answer.pairing_secret else {\n"
|
||||||
|
" self.state = PairingState::AwaitClientSecretAck;\n"
|
||||||
|
" return Ok(PairingStep::Send(self.request(Scheme::Http, &[], None)));\n"
|
||||||
|
" };")])
|
||||||
|
mut("M20", "signature", "the host's signature over its secret is not checked", "pairing",
|
||||||
|
[(SRC + "pairing/mod.rs",
|
||||||
|
" cert.verify(&secret, signature)\n .map_err(|_| (PairingFailure::BadHostSignature, Error::PairingRefused))?;",
|
||||||
|
" let _ = cert.verify(&secret, signature);")])
|
||||||
|
mut("M21", "signature", "ServerCert::verify accepts any signature", "pairing",
|
||||||
|
[(SRC + "pairing/identity.rs", "pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {",
|
||||||
|
"pub fn verify(&self, data: &[u8], signature: &[u8]) -> Result<()> {\n if !data.is_empty() || signature.is_empty() { return Ok(()); }")])
|
||||||
|
# ---- sans-I/O
|
||||||
|
mut("M22", "sans-I/O", "a wall-clock read (std::time::Instant::now) in src/time.rs", "hygiene",
|
||||||
|
[(SRC + "time.rs", "APPEND",
|
||||||
|
"\n#[allow(dead_code)]\nfn wall_clock_probe() -> std::time::Instant {\n std::time::Instant::now()\n}\n")])
|
||||||
|
mut("M23", "OS randomness", "getrandom added as a dependency and used in src/entropy.rs", "hygiene",
|
||||||
|
[("crates/domistream/Cargo.toml", 'zeroize = "1.8" # wipe keys on drop',
|
||||||
|
'zeroize = "1.8" # wipe keys on drop\ngetrandom = "0.4"'),
|
||||||
|
(SRC + "entropy.rs", "APPEND",
|
||||||
|
"\n#[allow(dead_code)]\nfn os_fill(dest: &mut [u8]) {\n let _ = getrandom::fill(dest);\n}\n")])
|
||||||
|
|
||||||
|
|
||||||
|
def sh(args, **kw):
|
||||||
|
return subprocess.run(args, cwd=REPO, capture_output=True, text=True, encoding="utf-8", errors="replace", **kw)
|
||||||
|
|
||||||
|
|
||||||
|
def gated(cmd):
|
||||||
|
while True:
|
||||||
|
p = sh(["powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", GATE, cmd])
|
||||||
|
if p.returncode != 75:
|
||||||
|
return p
|
||||||
|
time.sleep(15)
|
||||||
|
|
||||||
|
|
||||||
|
def apply(edits):
|
||||||
|
for path, old, new in edits:
|
||||||
|
full = os.path.join(REPO, path)
|
||||||
|
with open(full, encoding="utf-8", newline="") as f:
|
||||||
|
s = f.read()
|
||||||
|
if old == "APPEND":
|
||||||
|
s = s + new
|
||||||
|
else:
|
||||||
|
if s.count(old) != 1:
|
||||||
|
raise SystemExit(f"{path}: anchor found {s.count(old)} times: {old[:60]!r}")
|
||||||
|
s = s.replace(old, new)
|
||||||
|
with open(full, "w", encoding="utf-8", newline="") as f:
|
||||||
|
f.write(s)
|
||||||
|
|
||||||
|
|
||||||
|
def revert(edits):
|
||||||
|
files = sorted({p for p, _, _ in edits} | {"Cargo.lock"})
|
||||||
|
sh(["git", "checkout", "--", *files])
|
||||||
|
if sh(["git", "diff", "--quiet", "--", "crates/domistream/src", "crates/domistream/Cargo.toml", "Cargo.lock"]).returncode != 0:
|
||||||
|
raise SystemExit("revert failed: src is not clean")
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
only = set(sys.argv[1:])
|
||||||
|
results_path = os.path.join(QA, "results.json")
|
||||||
|
results = json.load(open(results_path)) if os.path.exists(results_path) else {}
|
||||||
|
for m in M:
|
||||||
|
if only and m["id"] not in only:
|
||||||
|
continue
|
||||||
|
apply(m["edits"])
|
||||||
|
try:
|
||||||
|
cmd = f"cargo test -j 2 --offline --test {m['test']} -- --test-threads=2 2>&1 | Out-File -Encoding utf8 {QA}\\mut-{m['id']}.log"
|
||||||
|
gated(cmd)
|
||||||
|
log = open(os.path.join(QA, f"mut-{m['id']}.log"), encoding="utf-8-sig", errors="replace").read()
|
||||||
|
finally:
|
||||||
|
revert(m["edits"])
|
||||||
|
failed = re.findall(r"^test (\S+) \.\.\. FAILED", log, re.M)
|
||||||
|
compile_error = bool(re.search(r"^error(\[E\d+\])?:", log, re.M)) and not failed
|
||||||
|
summary = re.findall(r"^test result: .*$", log, re.M)
|
||||||
|
r = {**{k: m[k] for k in ("area", "what", "test")}, "failed": failed, "compile_error": compile_error,
|
||||||
|
"summary": summary[-1] if summary else "", "caught": bool(failed) or compile_error}
|
||||||
|
results[m["id"]] = r
|
||||||
|
print(m["id"], "CAUGHT" if failed else ("COMPILE ERROR" if compile_error else "NOT CAUGHT"), failed[:4], flush=True)
|
||||||
|
json.dump(results, open(results_path, "w"), indent=1)
|
||||||
|
|
||||||
|
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user