[repo] Merge: feature/probe (gs-probe and the live-interop run book, PR #5)

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