[repo] Merge feature/lab: lab capture plan, relay tool, approved sources, U9/U14 from ENet and fec-rs
This commit is contained in:
Generated
+208
@@ -0,0 +1,208 @@
|
||||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.11.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69"
|
||||
dependencies = [
|
||||
"find-msvc-tools",
|
||||
"shlex",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "cfg-if"
|
||||
version = "1.0.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||
|
||||
[[package]]
|
||||
name = "find-msvc-tools"
|
||||
version = "0.1.15"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48"
|
||||
|
||||
[[package]]
|
||||
name = "getrandom"
|
||||
version = "0.2.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"wasi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lab-relay"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls",
|
||||
"rustls-pki-types",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.191"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
||||
|
||||
[[package]]
|
||||
name = "ring"
|
||||
version = "0.17.14"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"getrandom",
|
||||
"libc",
|
||||
"untrusted",
|
||||
"windows-sys",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls"
|
||||
version = "0.23.46"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"rustls-webpki",
|
||||
"subtle",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-pki-types"
|
||||
version = "1.16.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.17"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
|
||||
dependencies = [
|
||||
"ring",
|
||||
"rustls-pki-types",
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "2.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
||||
|
||||
[[package]]
|
||||
name = "subtle"
|
||||
version = "2.6.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
||||
|
||||
[[package]]
|
||||
name = "untrusted"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
||||
|
||||
[[package]]
|
||||
name = "wasi"
|
||||
version = "0.11.1+wasi-snapshot-preview1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
||||
|
||||
[[package]]
|
||||
name = "windows-sys"
|
||||
version = "0.52.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
||||
dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows-targets"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||
dependencies = [
|
||||
"windows_aarch64_gnullvm",
|
||||
"windows_aarch64_msvc",
|
||||
"windows_i686_gnu",
|
||||
"windows_i686_gnullvm",
|
||||
"windows_i686_msvc",
|
||||
"windows_x86_64_gnu",
|
||||
"windows_x86_64_gnullvm",
|
||||
"windows_x86_64_msvc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||
|
||||
[[package]]
|
||||
name = "windows_aarch64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_i686_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnu"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_gnullvm"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||
|
||||
[[package]]
|
||||
name = "windows_x86_64_msvc"
|
||||
version = "0.52.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||
|
||||
[[package]]
|
||||
name = "zeroize"
|
||||
version = "1.9.2"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa"
|
||||
@@ -0,0 +1,21 @@
|
||||
# lab-relay: our own logging relay for the one lab capture (docs/LAB_CAPTURE.md). A tool, never published, never part
|
||||
# of the domistream crate. Its own workspace so it never joins the main build.
|
||||
[package]
|
||||
name = "lab-relay"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.89"
|
||||
license = "CPAL-1.0"
|
||||
publish = false
|
||||
|
||||
[workspace]
|
||||
members = ["."]
|
||||
|
||||
[dependencies]
|
||||
# TLS termination on the HTTPS port with lab-only keys. ring backend: pure Rust + asm, builds with MSVC.
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] }
|
||||
rustls-pki-types = { version = "1", features = ["std"] }
|
||||
ring = "0.17"
|
||||
|
||||
[lints.rust]
|
||||
unsafe_code = "forbid"
|
||||
@@ -0,0 +1,183 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Lab capture: talk to the lab Sunshine's local API (docs/LAB_CAPTURE.md sections 2, 3, 5). Not elevated.
|
||||
|
||||
.DESCRIPTION
|
||||
Every call goes to https://127.0.0.2:47990 with Basic auth built in memory, no Origin/Referer header (the
|
||||
documented non-browser path), TLS pinned to the lab certificate in keys\ byte for byte.
|
||||
Credentials come only from DPAPI files in secrets\; they are never printed, logged or put on a command line.
|
||||
|
||||
-Action Rotate throwaway credentials (from lab-install.ps1) -> fresh lab credentials; deletes the throwaway
|
||||
-Action Status lists paired clients and apps (names only)
|
||||
-Action Pin submits the PIN Moonlight shows: -PinFile <file with 4 digits> (the file is deleted after
|
||||
reading), optional -PairingId, -ClientName (default "DomiStream lab Moonlight")
|
||||
-Action Logs saves GET /api/logs to captures\sunshine.log (not printed: it may hold secrets)
|
||||
-Action Cleanup unpair all clients, drop the lab cert/key from the config (bind_address stays 127.0.0.2),
|
||||
restart Sunshine
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory = $true)]
|
||||
[ValidateSet('Rotate', 'Status', 'Pin', 'Logs', 'Cleanup')]
|
||||
[string] $Action,
|
||||
[string] $LabRoot = 'E:\build\play-remotely\lab',
|
||||
[string] $PinFile,
|
||||
[string] $PairingId,
|
||||
[string] $ClientName = 'DomiStream lab Moonlight'
|
||||
)
|
||||
|
||||
Set-StrictMode -Version 2.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
$BaseUrl = 'https://127.0.0.2:47990'
|
||||
$keys = Join-Path $LabRoot 'keys'
|
||||
$secrets = Join-Path $LabRoot 'secrets'
|
||||
$captures = Join-Path $LabRoot 'captures'
|
||||
$throwawayFile = Join-Path $secrets 'sunshine-throwaway.cred'
|
||||
$labFile = Join-Path $secrets 'sunshine-lab.cred'
|
||||
$certFile = Join-Path $keys 'sunshine-lab-cert.pem'
|
||||
|
||||
function Fail([string] $Why) {
|
||||
Write-Host "lab-api: STOPPED: $Why"
|
||||
exit 1
|
||||
}
|
||||
|
||||
# --- TLS pinning: accept exactly the lab certificate -------------------------------------------------------------
|
||||
if (-not (Test-Path -LiteralPath $certFile)) { Fail "lab certificate not found: $certFile" }
|
||||
$pem = Get-Content -LiteralPath $certFile -Raw
|
||||
$m = [regex]::Match($pem, '-----BEGIN CERTIFICATE-----([A-Za-z0-9+/=\s]+)-----END CERTIFICATE-----')
|
||||
if (-not $m.Success) { Fail 'lab certificate is not PEM' }
|
||||
$pinnedDer = [Convert]::FromBase64String(($m.Groups[1].Value -replace '\s', ''))
|
||||
|
||||
if (-not ('DomiLabPin' -as [type])) {
|
||||
Add-Type -TypeDefinition @'
|
||||
using System;
|
||||
using System.Net;
|
||||
using System.Net.Security;
|
||||
using System.Security.Cryptography.X509Certificates;
|
||||
public static class DomiLabPin {
|
||||
public static byte[] Pinned;
|
||||
public static bool Check(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors) {
|
||||
if (cert == null || Pinned == null) return false;
|
||||
byte[] raw = cert.GetRawCertData();
|
||||
if (raw.Length != Pinned.Length) return false;
|
||||
int diff = 0;
|
||||
for (int i = 0; i < raw.Length; i++) diff |= raw[i] ^ Pinned[i];
|
||||
return diff == 0;
|
||||
}
|
||||
public static void Install() {
|
||||
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(Check);
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
[DomiLabPin]::Pinned = $pinnedDer
|
||||
[DomiLabPin]::Install()
|
||||
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
|
||||
|
||||
# --- Credentials -------------------------------------------------------------------------------------------------
|
||||
function Read-Cred([string] $File) {
|
||||
if (-not (Test-Path -LiteralPath $File)) { Fail "credentials file not found: $File" }
|
||||
$j = Get-Content -LiteralPath $File -Raw | ConvertFrom-Json
|
||||
$u = New-Object Management.Automation.PSCredential('x', ($j.user | ConvertTo-SecureString))
|
||||
$p = New-Object Management.Automation.PSCredential('x', ($j.password | ConvertTo-SecureString))
|
||||
return @{ User = $u.GetNetworkCredential().Password; Password = $p.GetNetworkCredential().Password }
|
||||
}
|
||||
|
||||
function Save-Cred([string] $File, [string] $User, [string] $Password) {
|
||||
@{
|
||||
user = (ConvertTo-SecureString -String $User -AsPlainText -Force | ConvertFrom-SecureString)
|
||||
password = (ConvertTo-SecureString -String $Password -AsPlainText -Force | ConvertFrom-SecureString)
|
||||
} | ConvertTo-Json | Set-Content -LiteralPath $File -Encoding ASCII
|
||||
}
|
||||
|
||||
function New-Secret {
|
||||
$bytes = New-Object byte[] 32
|
||||
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
$rng.GetBytes($bytes)
|
||||
$rng.Dispose()
|
||||
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
|
||||
}
|
||||
|
||||
# --- One API call ------------------------------------------------------------------------------------------------
|
||||
function Invoke-Sunshine([hashtable] $Cred, [string] $Method, [string] $Path, $Body, [string] $OutFile) {
|
||||
$pair = [Text.Encoding]::UTF8.GetBytes($Cred.User + ':' + $Cred.Password)
|
||||
$headers = @{ Authorization = 'Basic ' + [Convert]::ToBase64String($pair) }
|
||||
$req = @{ Uri = $BaseUrl + $Path; Method = $Method; Headers = $headers; UseBasicParsing = $true; TimeoutSec = 30 }
|
||||
if ($null -ne $Body) {
|
||||
$req.Body = ($Body | ConvertTo-Json -Depth 5 -Compress)
|
||||
$req.ContentType = 'application/json'
|
||||
}
|
||||
try {
|
||||
if ($OutFile) {
|
||||
Invoke-WebRequest @req -OutFile $OutFile | Out-Null
|
||||
return $null
|
||||
}
|
||||
return Invoke-RestMethod @req
|
||||
} catch {
|
||||
# The message names the call only; the request, which holds the credentials, is never echoed.
|
||||
Fail "$Method $Path failed: $($_.Exception.GetType().Name)"
|
||||
}
|
||||
}
|
||||
|
||||
# --- Actions -----------------------------------------------------------------------------------------------------
|
||||
switch ($Action) {
|
||||
'Rotate' {
|
||||
$old = Read-Cred $throwawayFile
|
||||
$newUser = 'lab' + (New-Secret).Substring(0, 12)
|
||||
$newPass = New-Secret
|
||||
$null = Invoke-Sunshine $old 'POST' '/api/password' @{
|
||||
currentUsername = $old.User
|
||||
currentPassword = $old.Password
|
||||
newUsername = $newUser
|
||||
newPassword = $newPass
|
||||
confirmNewPassword = $newPass
|
||||
}
|
||||
Save-Cred $labFile $newUser $newPass
|
||||
# Prove the new pair works before forgetting the old one.
|
||||
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/clients/list' $null
|
||||
Remove-Item -LiteralPath $throwawayFile -Force
|
||||
Write-Host 'lab-api: credentials rotated; throwaway deleted'
|
||||
}
|
||||
'Status' {
|
||||
$c = Read-Cred $labFile
|
||||
$clients = Invoke-Sunshine $c 'GET' '/api/clients/list' $null
|
||||
$apps = Invoke-Sunshine $c 'GET' '/api/apps' $null
|
||||
Write-Host ('lab-api: clients: ' + (($clients | ConvertTo-Json -Depth 4 -Compress)))
|
||||
Write-Host ('lab-api: apps: ' + ((@($apps.apps) | ForEach-Object { $_.name }) -join ', '))
|
||||
}
|
||||
'Pin' {
|
||||
if (-not $PinFile) { Fail '-PinFile is required' }
|
||||
$pin = (Get-Content -LiteralPath $PinFile -Raw).Trim()
|
||||
Remove-Item -LiteralPath $PinFile -Force
|
||||
if ($pin -notmatch '^[0-9]{4}$') { Fail 'the PIN file must hold exactly 4 digits' }
|
||||
$body = @{ pin = $pin; name = $ClientName }
|
||||
if ($PairingId) { $body.pairing_id = $PairingId }
|
||||
$r = Invoke-Sunshine (Read-Cred $labFile) 'POST' '/api/pin' $body
|
||||
Write-Host ('lab-api: PIN submitted, answer: ' + ($r | ConvertTo-Json -Compress))
|
||||
}
|
||||
'Logs' {
|
||||
$out = Join-Path $captures 'sunshine.log'
|
||||
$null = Invoke-Sunshine (Read-Cred $labFile) 'GET' '/api/logs' $null $out
|
||||
Write-Host "lab-api: Sunshine log saved to $out (not shown: it may hold secrets)"
|
||||
}
|
||||
'Cleanup' {
|
||||
$c = Read-Cred $labFile
|
||||
$null = Invoke-Sunshine $c 'POST' '/api/clients/unpair-all' $null
|
||||
# Same loopback-only config as lab-install.ps1, without the lab cert/key, so Sunshine makes a fresh pair.
|
||||
$null = Invoke-Sunshine $c 'POST' '/api/config' @{
|
||||
bind_address = '127.0.0.2'
|
||||
address_family = 'ipv4'
|
||||
origin_web_ui_allowed = 'pc'
|
||||
upnp = 'disabled'
|
||||
external_ip = '127.0.0.2'
|
||||
sunshine_name = 'DomiStream-lab'
|
||||
lan_encryption_mode = '1'
|
||||
wan_encryption_mode = '1'
|
||||
}
|
||||
$null = Invoke-Sunshine $c 'POST' '/api/restart' $null
|
||||
Write-Host 'lab-api: unpaired all clients, lab cert/key dropped from the config, Sunshine restarting'
|
||||
Write-Host 'lab-api: next: delete keys\sunshine-lab-*.pem and keys\moonlight-lab-*.pem once Sunshine is back'
|
||||
}
|
||||
}
|
||||
exit 0
|
||||
@@ -0,0 +1,217 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Lab capture step (b): install the pinned Sunshine bound to 127.0.0.2 only (docs/LAB_CAPTURE.md section 2).
|
||||
|
||||
.DESCRIPTION
|
||||
Runs ELEVATED, once, started by the operator with:
|
||||
Start-Process powershell -Verb RunAs -ArgumentList '-NoProfile','-ExecutionPolicy','Bypass','-File',
|
||||
'<repo>\tools\lab-relay\scripts\lab-install.ps1'
|
||||
That is the one UAC prompt of the lab capture.
|
||||
|
||||
What it does, in order, and nothing else:
|
||||
1. Refuses unless elevated, unless the MSI's sha256 matches the pin, and unless no Sunshine is installed.
|
||||
2. Creates keys\, secrets\, captures\ under the lab root, readable only by this account and SYSTEM.
|
||||
3. msiexec /i (quiet, logged to captures\msiexec.log), then stops the service the MSI started.
|
||||
4. Writes sunshine.conf: bind_address 127.0.0.2, web UI for this PC only, no UPnP, lab cert/key under keys\.
|
||||
5. Sets throwaway web-UI credentials with `sunshine --creds` (they exist only in that one process's argv and
|
||||
in a DPAPI-protected file; lab-api.ps1 -Action Rotate replaces them).
|
||||
6. Starts the service and checks that every Sunshine listener is on 127.0.0.2. Anything else: stop, fail.
|
||||
It does not touch Windows Defender, firewall rules (it only lists the ones the MSI added), or any other app.
|
||||
It never prints, logs or writes a credential in plain text.
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string] $LabRoot = 'E:\build\play-remotely\lab',
|
||||
[string] $Msi = 'E:\build\play-remotely\lab\downloads\Sunshine-Windows-AMD64-installer.msi'
|
||||
)
|
||||
|
||||
Set-StrictMode -Version 2.0
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# --- Pins (release API, docs/LAB_CAPTURE.md section 2) ------------------------------------------------------------
|
||||
$PinnedSha256 = '1d7fed8beecd5889dc7ff14cf9f42d6d38f37c3066c13c6c2a5f4e91847e0ccf'
|
||||
$PinnedSize = 33710080
|
||||
$BindAddress = '127.0.0.2'
|
||||
$Ports = @(47984, 47989, 47990, 48010)
|
||||
|
||||
function Fail([string] $Why) {
|
||||
Write-Host "lab-install: STOPPED: $Why"
|
||||
exit 1
|
||||
}
|
||||
|
||||
function Say([string] $What) {
|
||||
Write-Host "lab-install: $What"
|
||||
}
|
||||
|
||||
# --- 1. Preconditions --------------------------------------------------------------------------------------------
|
||||
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
|
||||
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
|
||||
Fail 'not elevated; start it with Start-Process -Verb RunAs'
|
||||
}
|
||||
if (-not (Test-Path -LiteralPath $Msi -PathType Leaf)) { Fail "MSI not found: $Msi" }
|
||||
$msiItem = Get-Item -LiteralPath $Msi
|
||||
if ($msiItem.Length -ne $PinnedSize) { Fail "MSI size $($msiItem.Length) is not the pinned $PinnedSize" }
|
||||
$hash = (Get-FileHash -LiteralPath $Msi -Algorithm SHA256).Hash.ToLowerInvariant()
|
||||
if ($hash -ne $PinnedSha256) { Fail "MSI sha256 $hash does not match the pin; delete the file" }
|
||||
Say 'MSI matches the pinned sha256'
|
||||
|
||||
if (Get-Service -Name '*sunshine*' -ErrorAction SilentlyContinue) { Fail 'a Sunshine service already exists' }
|
||||
if (Test-Path -LiteralPath 'C:\Program Files\Sunshine\sunshine.exe') { Fail 'C:\Program Files\Sunshine\sunshine.exe already exists' }
|
||||
$busy = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
|
||||
if ($busy) { Fail 'a GameStream port is already in use' }
|
||||
|
||||
# --- 2. Lab folders, this account + SYSTEM only ------------------------------------------------------------------
|
||||
$account = [Security.Principal.WindowsIdentity]::GetCurrent().Name
|
||||
$keys = Join-Path $LabRoot 'keys'
|
||||
$secrets = Join-Path $LabRoot 'secrets'
|
||||
$captures = Join-Path $LabRoot 'captures'
|
||||
foreach ($dir in @($keys, $secrets, $captures)) {
|
||||
New-Item -ItemType Directory -Force -Path $dir | Out-Null
|
||||
& icacls.exe $dir /inheritance:r /grant:r "${account}:(OI)(CI)F" '*S-1-5-18:(OI)(CI)F' | Out-Null
|
||||
if ($LASTEXITCODE -ne 0) { Fail "icacls failed on $dir" }
|
||||
}
|
||||
$hostKey = Join-Path $keys 'sunshine-lab-key.pem'
|
||||
$hostCert = Join-Path $keys 'sunshine-lab-cert.pem'
|
||||
foreach ($f in @($hostKey, $hostCert)) { if (Test-Path -LiteralPath $f) { Fail "$f already exists; clean up first" } }
|
||||
Say "lab folders ready under $LabRoot"
|
||||
|
||||
# --- 3. Install ----------------------------------------------------------------------------------------------------
|
||||
$msiLog = Join-Path $captures 'msiexec.log'
|
||||
$p = Start-Process -FilePath 'msiexec.exe' -ArgumentList @('/i', "`"$Msi`"", '/qn', '/norestart', '/l*v', "`"$msiLog`"") -Wait -PassThru
|
||||
if ($p.ExitCode -ne 0 -and $p.ExitCode -ne 3010) { Fail "msiexec exit code $($p.ExitCode); see $msiLog" }
|
||||
Say "MSI installed (exit code $($p.ExitCode))"
|
||||
|
||||
$service = Get-CimInstance Win32_Service | Where-Object { $_.PathName -like '*Sunshine*' } | Select-Object -First 1
|
||||
if (-not $service) { Fail 'no Sunshine service after the install' }
|
||||
Stop-Service -Name $service.Name -Force
|
||||
Say "service $($service.Name) stopped until the config is in"
|
||||
|
||||
$exe = 'C:\Program Files\Sunshine\sunshine.exe'
|
||||
if (-not (Test-Path -LiteralPath $exe)) { Fail "$exe not found after the install" }
|
||||
$installDir = Split-Path -Parent $exe
|
||||
$configDir = Join-Path $installDir 'config'
|
||||
New-Item -ItemType Directory -Force -Path $configDir | Out-Null
|
||||
$conf = Join-Path $configDir 'sunshine.conf'
|
||||
if (Test-Path -LiteralPath $conf) { Copy-Item -LiteralPath $conf -Destination (Join-Path $captures 'sunshine.conf.as-installed') -Force }
|
||||
|
||||
# --- 4. Config: loopback only ------------------------------------------------------------------------------------
|
||||
function Write-Conf([bool] $WithLabKeys) {
|
||||
$lines = @(
|
||||
"bind_address = $BindAddress",
|
||||
'address_family = ipv4',
|
||||
'origin_web_ui_allowed = pc',
|
||||
'upnp = disabled',
|
||||
"external_ip = $BindAddress",
|
||||
'sunshine_name = DomiStream-lab',
|
||||
'lan_encryption_mode = 1',
|
||||
'wan_encryption_mode = 1',
|
||||
'min_log_level = debug'
|
||||
)
|
||||
if ($WithLabKeys) {
|
||||
# Forward slashes: how the config parser treats backslashes is not documented.
|
||||
$lines += 'pkey = ' + ($hostKey -replace '\\', '/')
|
||||
$lines += 'cert = ' + ($hostCert -replace '\\', '/')
|
||||
}
|
||||
[IO.File]::WriteAllLines($conf, [string[]] $lines, (New-Object Text.UTF8Encoding($false)))
|
||||
}
|
||||
Write-Conf $true
|
||||
Say 'sunshine.conf written (bind_address 127.0.0.2)'
|
||||
|
||||
# --- 5. Throwaway credentials ------------------------------------------------------------------------------------
|
||||
function New-Secret {
|
||||
$bytes = New-Object byte[] 32
|
||||
$rng = [Security.Cryptography.RandomNumberGenerator]::Create()
|
||||
$rng.GetBytes($bytes)
|
||||
$rng.Dispose()
|
||||
# base64url: only [A-Za-z0-9_-], so it needs no quoting on a command line.
|
||||
return ([Convert]::ToBase64String($bytes)).TrimEnd('=').Replace('+', '-').Replace('/', '_')
|
||||
}
|
||||
$user = 'lab' + (New-Secret).Substring(0, 12)
|
||||
$pass = New-Secret
|
||||
|
||||
# One child process; its argv dies with it. Output is read and discarded, never written anywhere.
|
||||
$psi = New-Object Diagnostics.ProcessStartInfo
|
||||
$psi.FileName = $exe
|
||||
$psi.Arguments = "--creds $user $pass"
|
||||
$psi.WorkingDirectory = $installDir
|
||||
$psi.UseShellExecute = $false
|
||||
$psi.CreateNoWindow = $true
|
||||
$psi.RedirectStandardOutput = $true
|
||||
$psi.RedirectStandardError = $true
|
||||
$proc = [Diagnostics.Process]::Start($psi)
|
||||
$null = $proc.StandardOutput.ReadToEnd()
|
||||
$null = $proc.StandardError.ReadToEnd()
|
||||
if (-not $proc.WaitForExit(60000)) { $proc.Kill(); Fail 'sunshine --creds did not finish' }
|
||||
$credsExit = $proc.ExitCode
|
||||
$psi = $null
|
||||
$proc.Dispose()
|
||||
if ($credsExit -ne 0) { Fail "sunshine --creds exit code $credsExit" }
|
||||
|
||||
# DPAPI (this account): readable only by this account on this PC; lab-api.ps1 -Action Rotate replaces it.
|
||||
$throwaway = Join-Path $secrets 'sunshine-throwaway.cred'
|
||||
@{
|
||||
user = (ConvertTo-SecureString -String $user -AsPlainText -Force | ConvertFrom-SecureString)
|
||||
password = (ConvertTo-SecureString -String $pass -AsPlainText -Force | ConvertFrom-SecureString)
|
||||
} | ConvertTo-Json | Set-Content -LiteralPath $throwaway -Encoding ASCII
|
||||
Remove-Variable -Name user, pass -ErrorAction SilentlyContinue
|
||||
Say 'throwaway credentials set and stored (DPAPI)'
|
||||
|
||||
# --- 6. Start and check the binding ------------------------------------------------------------------------------
|
||||
function Wait-Listeners([int] $Seconds) {
|
||||
$deadline = (Get-Date).AddSeconds($Seconds)
|
||||
while ((Get-Date) -lt $deadline) {
|
||||
$l = Get-NetTCPConnection -State Listen -ErrorAction SilentlyContinue | Where-Object { $Ports -contains $_.LocalPort }
|
||||
if ($l -and (@($l | Select-Object -ExpandProperty LocalPort -Unique).Count -eq $Ports.Count)) { return $l }
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
return $null
|
||||
}
|
||||
function Assert-Loopback($Listeners) {
|
||||
$wrong = @($Listeners | Where-Object { $_.LocalAddress -ne $BindAddress })
|
||||
if ($wrong.Count -gt 0) {
|
||||
Stop-Service -Name $service.Name -Force
|
||||
Fail ('Sunshine listened on ' + (($wrong | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', ') + '; service stopped')
|
||||
}
|
||||
}
|
||||
|
||||
Start-Service -Name $service.Name
|
||||
$listeners = Wait-Listeners 60
|
||||
if (-not $listeners) {
|
||||
Stop-Service -Name $service.Name -Force
|
||||
Fail 'Sunshine did not listen on all four TCP ports; service stopped (bind_address 127.0.0.2 refused? see LAB_CAPTURE.md section 4 fallback)'
|
||||
}
|
||||
Assert-Loopback $listeners
|
||||
|
||||
# Did Sunshine create its pair at the lab path? If not, fall back to its default pair and copy it for the relay.
|
||||
$deadline = (Get-Date).AddSeconds(30)
|
||||
while (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert)) -and (Get-Date) -lt $deadline) {
|
||||
Start-Sleep -Milliseconds 500
|
||||
}
|
||||
if (-not ((Test-Path -LiteralPath $hostKey) -and (Test-Path -LiteralPath $hostCert))) {
|
||||
Say 'Sunshine did not create the lab pair at keys\; using its default pair'
|
||||
Stop-Service -Name $service.Name -Force
|
||||
Write-Conf $false
|
||||
Start-Service -Name $service.Name
|
||||
$listeners = Wait-Listeners 60
|
||||
if (-not $listeners) { Stop-Service -Name $service.Name -Force; Fail 'Sunshine did not come back after the fallback' }
|
||||
Assert-Loopback $listeners
|
||||
$defKey = Join-Path $configDir 'credentials\cakey.pem'
|
||||
$defCert = Join-Path $configDir 'credentials\cacert.pem'
|
||||
if (-not ((Test-Path -LiteralPath $defKey) -and (Test-Path -LiteralPath $defCert))) { Fail 'default pair not found either' }
|
||||
Copy-Item -LiteralPath $defKey -Destination $hostKey
|
||||
Copy-Item -LiteralPath $defCert -Destination $hostCert
|
||||
}
|
||||
Say 'Sunshine listens on 127.0.0.2 only; lab certificate pair in keys\'
|
||||
|
||||
# --- Report what the MSI did to the firewall (read only, nothing changed) ----------------------------------------
|
||||
$rules = @(Get-NetFirewallRule -ErrorAction SilentlyContinue | Where-Object { $_.DisplayName -like '*Sunshine*' })
|
||||
$notes = Join-Path $captures 'install-notes.txt'
|
||||
@(
|
||||
"installed: $(Get-Date -Format o)",
|
||||
"service: $($service.Name)",
|
||||
"msi sha256: $hash",
|
||||
"listeners: " + (($listeners | ForEach-Object { "$($_.LocalAddress):$($_.LocalPort)" }) -join ', '),
|
||||
"firewall rules named like Sunshine (not changed): " + (($rules | ForEach-Object { "$($_.DisplayName) [$($_.Direction) $($_.Action) $($_.Enabled)]" }) -join '; ')
|
||||
) | Set-Content -LiteralPath $notes -Encoding ASCII
|
||||
Say "done; notes in $notes. Next, not elevated: lab-api.ps1 -Action Rotate"
|
||||
exit 0
|
||||
@@ -0,0 +1,317 @@
|
||||
//! Relay settings and the loopback-only rule.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::path::PathBuf;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::record::Protocol;
|
||||
|
||||
/// Where recordings go unless told otherwise.
|
||||
pub const DEFAULT_CAPTURE_DIR: &str = r"E:\build\play-remotely\lab\captures";
|
||||
/// Where lab keys live unless told otherwise.
|
||||
pub const DEFAULT_KEY_DIR: &str = r"E:\build\play-remotely\lab\keys";
|
||||
|
||||
/// Transport of a relayed port.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Transport {
|
||||
/// TCP, bytes copied (and rewritten host-to-client when the protocol is plaintext).
|
||||
Tcp,
|
||||
/// TCP with TLS terminated in the relay.
|
||||
Tls,
|
||||
/// UDP datagrams.
|
||||
Udp,
|
||||
}
|
||||
|
||||
/// One relayed port.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PortSpec {
|
||||
/// Port the relay listens on.
|
||||
pub listen_port: u16,
|
||||
/// Port on the upstream (Sunshine) side.
|
||||
pub upstream_port: u16,
|
||||
/// Transport.
|
||||
pub transport: Transport,
|
||||
/// Protocol label for the records.
|
||||
pub protocol: Protocol,
|
||||
}
|
||||
|
||||
/// The GameStream default ports (PROTOCOL.md section 0, ArenaTV sunshine-api.md section 3).
|
||||
pub const GAMESTREAM_PORTS: [(u16, Transport, Protocol); 7] = [
|
||||
(47984, Transport::Tls, Protocol::HttpsPlain),
|
||||
(47989, Transport::Tcp, Protocol::Http),
|
||||
(48010, Transport::Tcp, Protocol::Rtsp),
|
||||
(47998, Transport::Udp, Protocol::Video),
|
||||
(47999, Transport::Udp, Protocol::Control),
|
||||
(48000, Transport::Udp, Protocol::Audio),
|
||||
(48002, Transport::Udp, Protocol::Mic),
|
||||
];
|
||||
|
||||
/// TLS material, all lab-only PEM files.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct TlsFiles {
|
||||
/// Sunshine's lab certificate (presented to Moonlight, pinned towards Sunshine).
|
||||
pub host_cert: PathBuf,
|
||||
/// Sunshine's lab private key.
|
||||
pub host_key: PathBuf,
|
||||
/// Moonlight's lab client certificate (presented to Sunshine).
|
||||
pub client_cert: PathBuf,
|
||||
/// Moonlight's lab client key.
|
||||
pub client_key: PathBuf,
|
||||
}
|
||||
|
||||
impl TlsFiles {
|
||||
/// The four default file names in `dir`.
|
||||
pub fn in_dir(dir: &std::path::Path) -> Self {
|
||||
Self {
|
||||
host_cert: dir.join("sunshine-lab-cert.pem"),
|
||||
host_key: dir.join("sunshine-lab-key.pem"),
|
||||
client_cert: dir.join("moonlight-lab-cert.pem"),
|
||||
client_key: dir.join("moonlight-lab-key.pem"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An equal-length byte replacement applied to host-to-client plaintext.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Rewrite {
|
||||
/// Bytes to find.
|
||||
pub from: Vec<u8>,
|
||||
/// Bytes to put instead, same length.
|
||||
pub to: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Everything the relay needs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Config {
|
||||
/// Address the relay listens on (Moonlight's "host"). Loopback only.
|
||||
pub listen: IpAddr,
|
||||
/// Address Sunshine listens on. Loopback only.
|
||||
pub upstream: IpAddr,
|
||||
/// Added to each default port on the upstream side (0, or 1000 in the fallback of LAB_CAPTURE.md section 4).
|
||||
pub upstream_port_offset: u16,
|
||||
/// Directory for the record file.
|
||||
pub capture_dir: PathBuf,
|
||||
/// TLS files; `None` = HTTPS passes through as raw TLS.
|
||||
pub tls: Option<TlsFiles>,
|
||||
/// How long an HTTPS connection waits for the TLS files to appear (Moonlight's key may appear only after
|
||||
/// pairing step 1).
|
||||
pub wait_for_keys: Duration,
|
||||
/// Rewrites, applied in order of position in the stream.
|
||||
pub rewrites: Vec<Rewrite>,
|
||||
}
|
||||
|
||||
/// Why a configuration is refused.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ConfigError {
|
||||
/// An address that is not loopback.
|
||||
NotLoopback(IpAddr),
|
||||
/// Listen and upstream are the same address with no port offset: the relay would talk to itself.
|
||||
SelfLoop,
|
||||
/// A rewrite whose two sides differ in length, or are empty.
|
||||
BadRewrite(String),
|
||||
/// Ports overflow with the offset.
|
||||
PortOverflow(u16),
|
||||
/// A command-line argument that is not understood.
|
||||
BadArgument(String),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ConfigError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
Self::NotLoopback(ip) => {
|
||||
write!(f, "{ip} is not a loopback address; the relay binds and connects only on loopback")
|
||||
}
|
||||
Self::SelfLoop => f.write_str("listen and upstream are the same address and ports"),
|
||||
Self::BadRewrite(s) => write!(f, "rewrite {s:?}: both sides must be non-empty and the same length"),
|
||||
Self::PortOverflow(p) => write!(f, "port {p} plus the offset is over 65535"),
|
||||
Self::BadArgument(s) => write!(f, "bad argument: {s}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for ConfigError {}
|
||||
|
||||
impl Config {
|
||||
/// The lab defaults: Moonlight sees 127.0.0.1, Sunshine sits on 127.0.0.2, `127.0.0.2` is rewritten to
|
||||
/// `127.0.0.1` in host-to-client plaintext, TLS files from [`DEFAULT_KEY_DIR`].
|
||||
pub fn lab_default() -> Self {
|
||||
Self {
|
||||
listen: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)),
|
||||
upstream: IpAddr::V4(Ipv4Addr::new(127, 0, 0, 2)),
|
||||
upstream_port_offset: 0,
|
||||
capture_dir: PathBuf::from(DEFAULT_CAPTURE_DIR),
|
||||
tls: Some(TlsFiles::in_dir(std::path::Path::new(DEFAULT_KEY_DIR))),
|
||||
wait_for_keys: Duration::from_secs(60),
|
||||
rewrites: vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }],
|
||||
}
|
||||
}
|
||||
|
||||
/// Checks the rules: loopback only, no self-loop, sane rewrites, ports in range.
|
||||
///
|
||||
/// # Errors
|
||||
/// The first rule broken.
|
||||
pub fn validate(&self) -> Result<(), ConfigError> {
|
||||
for ip in [self.listen, self.upstream] {
|
||||
if !ip.is_loopback() {
|
||||
return Err(ConfigError::NotLoopback(ip));
|
||||
}
|
||||
}
|
||||
if self.listen == self.upstream && self.upstream_port_offset == 0 {
|
||||
return Err(ConfigError::SelfLoop);
|
||||
}
|
||||
for r in &self.rewrites {
|
||||
if r.from.is_empty() || r.from.len() != r.to.len() {
|
||||
return Err(ConfigError::BadRewrite(String::from_utf8_lossy(&r.from).into_owned()));
|
||||
}
|
||||
}
|
||||
self.ports().map(|_| ())
|
||||
}
|
||||
|
||||
/// The relayed ports with the upstream offset applied.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`ConfigError::PortOverflow`].
|
||||
pub fn ports(&self) -> Result<Vec<PortSpec>, ConfigError> {
|
||||
GAMESTREAM_PORTS
|
||||
.iter()
|
||||
.map(|&(port, transport, protocol)| {
|
||||
let upstream_port =
|
||||
port.checked_add(self.upstream_port_offset).ok_or(ConfigError::PortOverflow(port))?;
|
||||
let transport =
|
||||
if transport == Transport::Tls && self.tls.is_none() { Transport::Tcp } else { transport };
|
||||
let protocol = if transport == Transport::Tcp && protocol == Protocol::HttpsPlain {
|
||||
Protocol::HttpsTls
|
||||
} else {
|
||||
protocol
|
||||
};
|
||||
Ok(PortSpec { listen_port: port, upstream_port, transport, protocol })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Socket address the relay listens on for `spec`.
|
||||
pub fn listen_addr(&self, spec: &PortSpec) -> SocketAddr {
|
||||
SocketAddr::new(self.listen, spec.listen_port)
|
||||
}
|
||||
|
||||
/// Upstream socket address for `spec`.
|
||||
pub fn upstream_addr(&self, spec: &PortSpec) -> SocketAddr {
|
||||
SocketAddr::new(self.upstream, spec.upstream_port)
|
||||
}
|
||||
|
||||
/// Applies command-line options to the lab defaults:
|
||||
/// `--listen <ip>`, `--upstream <ip>`, `--upstream-port-offset <n>`, `--capture-dir <dir>`, `--key-dir <dir>`,
|
||||
/// `--https-passthrough`, `--wait-for-keys-secs <n>`, `--rewrite <from>=<to>` (repeatable; the first one
|
||||
/// replaces the default rewrite), `--no-rewrite`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`ConfigError::BadArgument`] for an unknown option or value, then [`Config::validate`].
|
||||
pub fn from_args(args: &[String]) -> Result<Self, ConfigError> {
|
||||
let mut c = Self::lab_default();
|
||||
let mut custom_rewrites = false;
|
||||
let mut it = args.iter();
|
||||
let bad = |s: &str| ConfigError::BadArgument(s.to_owned());
|
||||
while let Some(a) = it.next() {
|
||||
let mut value = || it.next().ok_or_else(|| bad(a));
|
||||
match a.as_str() {
|
||||
"--listen" => c.listen = value()?.parse().map_err(|_| bad(a))?,
|
||||
"--upstream" => c.upstream = value()?.parse().map_err(|_| bad(a))?,
|
||||
"--upstream-port-offset" => c.upstream_port_offset = value()?.parse().map_err(|_| bad(a))?,
|
||||
"--capture-dir" => c.capture_dir = PathBuf::from(value()?),
|
||||
"--key-dir" => {
|
||||
let dir = PathBuf::from(value()?);
|
||||
if c.tls.is_some() {
|
||||
c.tls = Some(TlsFiles::in_dir(&dir));
|
||||
}
|
||||
}
|
||||
"--https-passthrough" => c.tls = None,
|
||||
"--wait-for-keys-secs" => {
|
||||
c.wait_for_keys = Duration::from_secs(value()?.parse().map_err(|_| bad(a))?);
|
||||
}
|
||||
"--rewrite" => {
|
||||
let v = value()?;
|
||||
let (from, to) = v.split_once('=').ok_or_else(|| bad(v))?;
|
||||
if !custom_rewrites {
|
||||
c.rewrites.clear();
|
||||
custom_rewrites = true;
|
||||
}
|
||||
c.rewrites.push(Rewrite { from: from.as_bytes().to_vec(), to: to.as_bytes().to_vec() });
|
||||
}
|
||||
"--no-rewrite" => {
|
||||
c.rewrites.clear();
|
||||
custom_rewrites = true;
|
||||
}
|
||||
other => return Err(bad(other)),
|
||||
}
|
||||
}
|
||||
c.validate()?;
|
||||
Ok(c)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn args(s: &str) -> Vec<String> {
|
||||
s.split_whitespace().map(str::to_owned).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lab_default_is_valid() {
|
||||
assert_eq!(Config::lab_default().validate(), Ok(()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_loopback_listen_or_upstream_is_refused() {
|
||||
for a in [
|
||||
"--listen 0.0.0.0",
|
||||
"--listen 192.168.100.140",
|
||||
"--upstream 192.168.100.217",
|
||||
"--listen ::",
|
||||
"--upstream 26.1.2.3",
|
||||
] {
|
||||
assert!(matches!(Config::from_args(&args(a)), Err(ConfigError::NotLoopback(_))), "{a}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn other_loopback_addresses_are_accepted() {
|
||||
let c = Config::from_args(&args("--listen 127.0.0.3 --upstream ::1")).unwrap();
|
||||
assert!(c.listen.is_loopback() && c.upstream.is_loopback());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn self_loop_is_refused_unless_offset() {
|
||||
assert_eq!(Config::from_args(&args("--upstream 127.0.0.1")), Err(ConfigError::SelfLoop));
|
||||
let c = Config::from_args(&args("--upstream 127.0.0.1 --upstream-port-offset 1000")).unwrap();
|
||||
let ports = c.ports().unwrap();
|
||||
assert!(ports.iter().all(|p| p.upstream_port == p.listen_port + 1000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rewrites_must_keep_length() {
|
||||
assert!(matches!(Config::from_args(&args("--rewrite 48984=7984")), Err(ConfigError::BadRewrite(_))));
|
||||
assert!(matches!(Config::from_args(&args("--rewrite =")), Err(ConfigError::BadRewrite(_))));
|
||||
let c = Config::from_args(&args("--rewrite 48984=47984 --rewrite 49010=48010")).unwrap();
|
||||
assert_eq!(c.rewrites.len(), 2, "custom rewrites replace the default one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn port_overflow_is_refused() {
|
||||
assert!(matches!(Config::from_args(&args("--upstream-port-offset 20000")), Err(ConfigError::PortOverflow(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passthrough_turns_tls_into_raw_tcp() {
|
||||
let c = Config::from_args(&args("--https-passthrough")).unwrap();
|
||||
let https = c.ports().unwrap().into_iter().find(|p| p.listen_port == 47984).unwrap();
|
||||
assert_eq!((https.transport, https.protocol), (Transport::Tcp, Protocol::HttpsTls));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_arguments_are_refused() {
|
||||
assert!(matches!(Config::from_args(&args("--bind 0.0.0.0")), Err(ConfigError::BadArgument(_))));
|
||||
assert!(matches!(Config::from_args(&args("--listen")), Err(ConfigError::BadArgument(_))));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
//! lab-relay: our own logging relay for the one GameStream lab capture (`docs/LAB_CAPTURE.md`).
|
||||
//!
|
||||
//! ```text
|
||||
//! lab-relay run [--listen 127.0.0.1] [--upstream 127.0.0.2] [--upstream-port-offset N] [--capture-dir DIR]
|
||||
//! [--key-dir DIR] [--https-passthrough] [--wait-for-keys-secs N] [--rewrite FROM=TO]... [--no-rewrite]
|
||||
//! lab-relay dump <file.dslr> list records, secrets redacted
|
||||
//! lab-relay strip-video <in> <out> copy with video payloads cut to their 32 header bytes
|
||||
//! ```
|
||||
//!
|
||||
//! Binds and connects only on loopback (refused otherwise). Never sends anything of its own.
|
||||
|
||||
mod config;
|
||||
mod record;
|
||||
mod recorder;
|
||||
mod redact;
|
||||
mod rewrite;
|
||||
mod tcp;
|
||||
mod tls;
|
||||
mod udp;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, BufReader, BufWriter, Write};
|
||||
use std::process::ExitCode;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
|
||||
use config::{Config, Transport};
|
||||
use record::{Kind, Protocol, Record};
|
||||
use recorder::Recorder;
|
||||
|
||||
/// Bytes of a video packet kept by `strip-video`: RTP header, reserved bytes and the NV header.
|
||||
const VIDEO_HEADER_KEEP: usize = 32;
|
||||
/// Text shown per record by `dump`.
|
||||
const DUMP_TEXT_LIMIT: usize = 4000;
|
||||
|
||||
fn main() -> ExitCode {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
let result = match args.split_first() {
|
||||
Some((cmd, rest)) if cmd == "run" => run(rest),
|
||||
Some((cmd, [file])) if cmd == "dump" => dump(file),
|
||||
Some((cmd, [input, output])) if cmd == "strip-video" => strip_video(input, output),
|
||||
_ => Err("usage: lab-relay run [options] | dump <file> | strip-video <in> <out>".into()),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => ExitCode::SUCCESS,
|
||||
Err(e) => {
|
||||
eprintln!("lab-relay: {e}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type AnyResult = Result<(), Box<dyn std::error::Error>>;
|
||||
|
||||
fn run(args: &[String]) -> AnyResult {
|
||||
let config = Arc::new(Config::from_args(args)?);
|
||||
let (rec, path) = Recorder::create(&config.capture_dir)?;
|
||||
let rec = Arc::new(rec);
|
||||
println!("lab-relay: recording to {}", path.display());
|
||||
let mut threads = Vec::new();
|
||||
for spec in config.ports()? {
|
||||
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
|
||||
println!("lab-relay: {:?} {} -> {}", spec.protocol, config.listen_addr(&spec), config.upstream_addr(&spec));
|
||||
threads.push(thread::spawn(move || {
|
||||
let r = match spec.transport {
|
||||
Transport::Tcp => tcp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
|
||||
Transport::Tls => tls::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
|
||||
Transport::Udp => udp::serve(Arc::clone(&config), spec, Arc::clone(&rec)),
|
||||
};
|
||||
if let Err(e) = r {
|
||||
eprintln!("lab-relay: port {} stopped: {e}", spec.listen_port);
|
||||
rec.note(Protocol::Meta, 0, &format!("port {} stopped: {e}", spec.listen_port));
|
||||
}
|
||||
}));
|
||||
}
|
||||
rec.note(Protocol::Meta, 0, "relay started");
|
||||
for t in threads {
|
||||
let _ = t.join();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_text(r: &Record) -> bool {
|
||||
r.kind == Kind::Note
|
||||
|| r.kind == Kind::Open
|
||||
|| matches!(r.protocol, Protocol::Http | Protocol::HttpsPlain | Protocol::Rtsp)
|
||||
}
|
||||
|
||||
fn dump(file: &str) -> AnyResult {
|
||||
let mut input = BufReader::new(File::open(file)?);
|
||||
let header = record::read_header(&mut input)?;
|
||||
let stdout = io::stdout();
|
||||
let mut out = stdout.lock();
|
||||
writeln!(out, "capture started at unix {} us", header.start_unix_micros)?;
|
||||
let mut index = 0u64;
|
||||
loop {
|
||||
let r = match record::read_record(&mut input) {
|
||||
Ok(Some(r)) => r,
|
||||
Ok(None) => break,
|
||||
Err(e) => {
|
||||
writeln!(out, "stopped at record {index}: {e}")?;
|
||||
break;
|
||||
}
|
||||
};
|
||||
writeln!(
|
||||
out,
|
||||
"#{index} t={}.{:06}s conn={} {:?} {:?} {:?} {} bytes",
|
||||
r.time_micros / 1_000_000,
|
||||
r.time_micros % 1_000_000,
|
||||
r.connection,
|
||||
r.kind,
|
||||
r.protocol,
|
||||
r.direction,
|
||||
r.payload.len()
|
||||
)?;
|
||||
if is_text(&r) {
|
||||
let text = redact::redact(&r.payload);
|
||||
let shown = &text[..text.len().min(DUMP_TEXT_LIMIT)];
|
||||
writeln!(out, " {}", String::from_utf8_lossy(shown).escape_debug())?;
|
||||
} else {
|
||||
let hex: String = r.payload.iter().take(32).map(|b| format!("{b:02x} ")).collect();
|
||||
writeln!(out, " {hex}")?;
|
||||
}
|
||||
index += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn strip_video(input: &str, output: &str) -> AnyResult {
|
||||
let mut reader = BufReader::new(File::open(input)?);
|
||||
let header = record::read_header(&mut reader)?;
|
||||
let mut writer = BufWriter::new(File::options().write(true).create_new(true).open(output)?);
|
||||
record::write_header(&mut writer, header)?;
|
||||
let mut stripped = 0u64;
|
||||
while let Some(mut r) = record::read_record(&mut reader)? {
|
||||
if r.kind == Kind::Data && r.protocol == Protocol::Video && r.payload.len() > VIDEO_HEADER_KEEP {
|
||||
r.payload.truncate(VIDEO_HEADER_KEEP);
|
||||
stripped += 1;
|
||||
}
|
||||
record::write_record(&mut writer, &r)?;
|
||||
}
|
||||
let note = Record {
|
||||
kind: Kind::Note,
|
||||
protocol: Protocol::Meta,
|
||||
direction: record::Direction::None,
|
||||
connection: 0,
|
||||
time_micros: u64::MAX,
|
||||
payload: format!("strip-video: {stripped} video payloads cut to {VIDEO_HEADER_KEEP} bytes").into_bytes(),
|
||||
};
|
||||
record::write_record(&mut writer, ¬e)?;
|
||||
writer.flush()?;
|
||||
println!("lab-relay: {stripped} video records stripped");
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
//! The record file: everything the relay sees, framed so it can be read back exactly.
|
||||
//!
|
||||
//! ```text
|
||||
//! file = header record*
|
||||
//! header = "DSLR" version:u8(=1) reserved:[u8;3](=0) start_unix_micros:u64le
|
||||
//! record = kind:u8 protocol:u8 direction:u8 reserved:u8(=0) connection:u32le time_micros:u64le len:u32le bytes[len]
|
||||
//! ```
|
||||
//!
|
||||
//! `time_micros` counts from the start of the capture. A record never holds more than [`MAX_PAYLOAD`] bytes.
|
||||
|
||||
use std::fmt;
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
/// File magic.
|
||||
pub const MAGIC: [u8; 4] = *b"DSLR";
|
||||
/// Format version.
|
||||
pub const VERSION: u8 = 1;
|
||||
/// Header length in bytes.
|
||||
pub const HEADER_LEN: usize = 16;
|
||||
/// Record header length in bytes.
|
||||
pub const RECORD_HEADER_LEN: usize = 20;
|
||||
/// Largest payload of one record (a UDP datagram is at most 64 KiB; TCP reads are split to fit).
|
||||
pub const MAX_PAYLOAD: usize = 1 << 20;
|
||||
|
||||
/// What a record says.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Kind {
|
||||
/// A connection or UDP flow opened.
|
||||
Open,
|
||||
/// Bytes seen.
|
||||
Data,
|
||||
/// A connection or flow closed.
|
||||
Close,
|
||||
/// A UTF-8 note from the relay (TLS details, rewrites, errors).
|
||||
Note,
|
||||
}
|
||||
|
||||
/// Which protocol the bytes belong to.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Protocol {
|
||||
/// Relay-level notes.
|
||||
Meta,
|
||||
/// HTTP, port 47989.
|
||||
Http,
|
||||
/// Raw TLS bytes on 47984 (when not terminated).
|
||||
HttpsTls,
|
||||
/// Decrypted HTTPS plaintext on 47984.
|
||||
HttpsPlain,
|
||||
/// RTSP, port 48010.
|
||||
Rtsp,
|
||||
/// Video RTP, port 47998.
|
||||
Video,
|
||||
/// Control ENet, port 47999.
|
||||
Control,
|
||||
/// Audio RTP, port 48000.
|
||||
Audio,
|
||||
/// Microphone, port 48002.
|
||||
Mic,
|
||||
}
|
||||
|
||||
/// Which way the bytes went.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum Direction {
|
||||
/// Not a transfer (notes, opens, closes).
|
||||
None,
|
||||
/// Moonlight to Sunshine.
|
||||
ClientToHost,
|
||||
/// Sunshine to Moonlight.
|
||||
HostToClient,
|
||||
}
|
||||
|
||||
macro_rules! codes {
|
||||
($t:ty { $($v:ident = $c:literal),* $(,)? }) => {
|
||||
impl $t {
|
||||
/// Wire code.
|
||||
pub const fn code(self) -> u8 {
|
||||
match self { $(Self::$v => $c),* }
|
||||
}
|
||||
/// From a wire code.
|
||||
pub const fn from_code(code: u8) -> Option<Self> {
|
||||
match code { $($c => Some(Self::$v),)* _ => None }
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
codes!(Kind { Open = 1, Data = 2, Close = 3, Note = 4 });
|
||||
codes!(Protocol {
|
||||
Meta = 0, Http = 1, HttpsTls = 2, HttpsPlain = 3, Rtsp = 4, Video = 5, Control = 6, Audio = 7, Mic = 8,
|
||||
});
|
||||
codes!(Direction { None = 0, ClientToHost = 1, HostToClient = 2 });
|
||||
|
||||
/// The file header.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
/// Wall-clock start of the capture, Unix microseconds.
|
||||
pub start_unix_micros: u64,
|
||||
}
|
||||
|
||||
/// One record.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct Record {
|
||||
/// What it is.
|
||||
pub kind: Kind,
|
||||
/// Protocol.
|
||||
pub protocol: Protocol,
|
||||
/// Direction.
|
||||
pub direction: Direction,
|
||||
/// Connection or flow id, unique per capture.
|
||||
pub connection: u32,
|
||||
/// Microseconds since the capture started.
|
||||
pub time_micros: u64,
|
||||
/// The bytes (UTF-8 text for notes).
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
/// Why a file could not be read.
|
||||
#[derive(Debug)]
|
||||
pub enum RecordError {
|
||||
/// I/O failure.
|
||||
Io(io::Error),
|
||||
/// Not a record file, or another version.
|
||||
BadHeader,
|
||||
/// The file ends inside a record.
|
||||
Truncated,
|
||||
/// A field holds a value this version does not know.
|
||||
BadField(&'static str, u64),
|
||||
/// A payload over [`MAX_PAYLOAD`].
|
||||
TooLarge(usize),
|
||||
}
|
||||
|
||||
impl fmt::Display for RecordError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Io(e) => write!(f, "i/o: {e}"),
|
||||
Self::BadHeader => f.write_str("not a DSLR v1 file"),
|
||||
Self::Truncated => f.write_str("file ends inside a record"),
|
||||
Self::BadField(name, v) => write!(f, "bad {name}: {v}"),
|
||||
Self::TooLarge(n) => write!(f, "payload of {n} bytes is over the limit"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for RecordError {}
|
||||
|
||||
impl From<io::Error> for RecordError {
|
||||
fn from(e: io::Error) -> Self {
|
||||
Self::Io(e)
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes the file header.
|
||||
///
|
||||
/// # Errors
|
||||
/// I/O errors.
|
||||
pub fn write_header(out: &mut impl Write, header: Header) -> io::Result<()> {
|
||||
let mut buf = [0u8; HEADER_LEN];
|
||||
buf[..4].copy_from_slice(&MAGIC);
|
||||
buf[4] = VERSION;
|
||||
buf[8..16].copy_from_slice(&header.start_unix_micros.to_le_bytes());
|
||||
out.write_all(&buf)
|
||||
}
|
||||
|
||||
/// Writes one record.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`io::ErrorKind::InvalidInput`] for a payload over [`MAX_PAYLOAD`]; I/O errors.
|
||||
pub fn write_record(out: &mut impl Write, record: &Record) -> io::Result<()> {
|
||||
let len = record.payload.len();
|
||||
if len > MAX_PAYLOAD {
|
||||
return Err(io::Error::new(io::ErrorKind::InvalidInput, "record payload over MAX_PAYLOAD"));
|
||||
}
|
||||
let mut head = [0u8; RECORD_HEADER_LEN];
|
||||
head[0] = record.kind.code();
|
||||
head[1] = record.protocol.code();
|
||||
head[2] = record.direction.code();
|
||||
head[4..8].copy_from_slice(&record.connection.to_le_bytes());
|
||||
head[8..16].copy_from_slice(&record.time_micros.to_le_bytes());
|
||||
// `len <= MAX_PAYLOAD < u32::MAX`, checked above.
|
||||
head[16..20].copy_from_slice(&(len as u32).to_le_bytes());
|
||||
out.write_all(&head)?;
|
||||
out.write_all(&record.payload)
|
||||
}
|
||||
|
||||
/// Reads exactly `buf.len()` bytes; `Ok(false)` at a clean end before the first byte.
|
||||
fn read_full(input: &mut impl Read, buf: &mut [u8]) -> Result<bool, RecordError> {
|
||||
let mut filled = 0;
|
||||
while filled < buf.len() {
|
||||
match input.read(&mut buf[filled..]) {
|
||||
Ok(0) if filled == 0 => return Ok(false),
|
||||
Ok(0) => return Err(RecordError::Truncated),
|
||||
Ok(n) => filled += n,
|
||||
Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(e) => return Err(e.into()),
|
||||
}
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// Reads and checks the file header.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`RecordError::BadHeader`] for a wrong magic, version or reserved bytes; [`RecordError::Truncated`].
|
||||
pub fn read_header(input: &mut impl Read) -> Result<Header, RecordError> {
|
||||
let mut buf = [0u8; HEADER_LEN];
|
||||
if !read_full(input, &mut buf)? {
|
||||
return Err(RecordError::Truncated);
|
||||
}
|
||||
if buf[..4] != MAGIC || buf[4] != VERSION || buf[5..8] != [0, 0, 0] {
|
||||
return Err(RecordError::BadHeader);
|
||||
}
|
||||
let mut start = [0u8; 8];
|
||||
start.copy_from_slice(&buf[8..16]);
|
||||
Ok(Header { start_unix_micros: u64::from_le_bytes(start) })
|
||||
}
|
||||
|
||||
/// Reads the next record; `Ok(None)` at the end of the file.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`RecordError::Truncated`] inside a record, [`RecordError::BadField`] for unknown codes or a non-zero reserved
|
||||
/// byte, [`RecordError::TooLarge`] before allocating an oversized payload.
|
||||
pub fn read_record(input: &mut impl Read) -> Result<Option<Record>, RecordError> {
|
||||
let mut head = [0u8; RECORD_HEADER_LEN];
|
||||
if !read_full(input, &mut head)? {
|
||||
return Ok(None);
|
||||
}
|
||||
let kind = Kind::from_code(head[0]).ok_or(RecordError::BadField("kind", head[0].into()))?;
|
||||
let protocol = Protocol::from_code(head[1]).ok_or(RecordError::BadField("protocol", head[1].into()))?;
|
||||
let direction = Direction::from_code(head[2]).ok_or(RecordError::BadField("direction", head[2].into()))?;
|
||||
if head[3] != 0 {
|
||||
return Err(RecordError::BadField("reserved", head[3].into()));
|
||||
}
|
||||
let word = |r: std::ops::Range<usize>| {
|
||||
let mut b = [0u8; 8];
|
||||
b[..r.len()].copy_from_slice(&head[r]);
|
||||
u64::from_le_bytes(b)
|
||||
};
|
||||
let connection = word(4..8) as u32;
|
||||
let time_micros = word(8..16);
|
||||
let len = word(16..20) as usize;
|
||||
if len > MAX_PAYLOAD {
|
||||
return Err(RecordError::TooLarge(len));
|
||||
}
|
||||
let mut payload = vec![0u8; len];
|
||||
if len > 0 && !read_full(input, &mut payload)? {
|
||||
return Err(RecordError::Truncated);
|
||||
}
|
||||
Ok(Some(Record { kind, protocol, direction, connection, time_micros, payload }))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn sample(payload: &[u8]) -> Record {
|
||||
Record {
|
||||
kind: Kind::Data,
|
||||
protocol: Protocol::Control,
|
||||
direction: Direction::HostToClient,
|
||||
connection: 0x0102_0304,
|
||||
time_micros: 0x1122_3344_5566_7788,
|
||||
payload: payload.to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
fn file(records: &[Record]) -> Vec<u8> {
|
||||
let mut out = Vec::new();
|
||||
write_header(&mut out, Header { start_unix_micros: 42 }).unwrap();
|
||||
for r in records {
|
||||
write_record(&mut out, r).unwrap();
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_layout_is_fixed() {
|
||||
let mut out = Vec::new();
|
||||
write_header(&mut out, Header { start_unix_micros: 0x0807_0605_0403_0201 }).unwrap();
|
||||
assert_eq!(out, b"DSLR\x01\0\0\0\x01\x02\x03\x04\x05\x06\x07\x08");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn record_layout_is_fixed() {
|
||||
let mut out = Vec::new();
|
||||
write_record(&mut out, &sample(b"ab")).unwrap();
|
||||
let mut want = vec![2, 6, 2, 0, 4, 3, 2, 1, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 2, 0, 0, 0];
|
||||
want.extend_from_slice(b"ab");
|
||||
assert_eq!(out, want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn round_trip_of_every_code() {
|
||||
let mut records = Vec::new();
|
||||
for k in 1..=4 {
|
||||
for p in 0..=8 {
|
||||
for d in 0..=2 {
|
||||
records.push(Record {
|
||||
kind: Kind::from_code(k).unwrap(),
|
||||
protocol: Protocol::from_code(p).unwrap(),
|
||||
direction: Direction::from_code(d).unwrap(),
|
||||
connection: u32::from(k) * 100 + u32::from(p),
|
||||
time_micros: u64::from(d),
|
||||
payload: vec![k, p, d],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
records.push(sample(&[]));
|
||||
records.push(sample(&vec![0xAB; MAX_PAYLOAD]));
|
||||
let bytes = file(&records);
|
||||
let mut input = bytes.as_slice();
|
||||
assert_eq!(read_header(&mut input).unwrap(), Header { start_unix_micros: 42 });
|
||||
for want in &records {
|
||||
assert_eq!(read_record(&mut input).unwrap().as_ref(), Some(want));
|
||||
}
|
||||
assert!(read_record(&mut input).unwrap().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_payload_is_refused_on_write() {
|
||||
let err = write_record(&mut Vec::new(), &sample(&vec![0; MAX_PAYLOAD + 1])).unwrap_err();
|
||||
assert_eq!(err.kind(), io::ErrorKind::InvalidInput);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_length_is_refused_before_allocating() {
|
||||
let mut bytes = Vec::new();
|
||||
write_record(&mut bytes, &sample(b"")).unwrap();
|
||||
bytes[16..20].copy_from_slice(&u32::MAX.to_le_bytes());
|
||||
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::TooLarge(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_cut_inside_a_record_is_truncated() {
|
||||
let mut bytes = Vec::new();
|
||||
write_record(&mut bytes, &sample(b"payload")).unwrap();
|
||||
for cut in 1..bytes.len() {
|
||||
let r = read_record(&mut &bytes[..cut]);
|
||||
assert!(matches!(r, Err(RecordError::Truncated)), "cut at {cut}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_codes_and_reserved_bytes_are_refused() {
|
||||
for (offset, value) in [(0, 0u8), (0, 5), (1, 9), (2, 3), (3, 1)] {
|
||||
let mut bytes = Vec::new();
|
||||
write_record(&mut bytes, &sample(b"x")).unwrap();
|
||||
bytes[offset] = value;
|
||||
assert!(matches!(read_record(&mut bytes.as_slice()), Err(RecordError::BadField(..))), "{offset}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_headers_are_refused() {
|
||||
let good = file(&[]);
|
||||
for (offset, value) in [(0, b'X'), (4, 2), (5, 1)] {
|
||||
let mut bytes = good.clone();
|
||||
bytes[offset] = value;
|
||||
assert!(matches!(read_header(&mut bytes.as_slice()), Err(RecordError::BadHeader)));
|
||||
}
|
||||
assert!(matches!(read_header(&mut &good[..10]), Err(RecordError::Truncated)));
|
||||
}
|
||||
|
||||
/// A reader that hands out one byte per call, like a slow pipe.
|
||||
struct Trickle<'a>(&'a [u8]);
|
||||
impl Read for Trickle<'_> {
|
||||
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
|
||||
match (self.0.split_first(), buf.first_mut()) {
|
||||
(Some((&b, rest)), Some(slot)) => {
|
||||
*slot = b;
|
||||
self.0 = rest;
|
||||
Ok(1)
|
||||
}
|
||||
_ => Ok(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn short_reads_are_reassembled() {
|
||||
let bytes = file(&[sample(b"one"), sample(b"two")]);
|
||||
let mut input = Trickle(&bytes);
|
||||
read_header(&mut input).unwrap();
|
||||
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"one");
|
||||
assert_eq!(read_record(&mut input).unwrap().unwrap().payload, b"two");
|
||||
assert!(read_record(&mut input).unwrap().is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
//! The shared, thread-safe writer of the record file. Every record is flushed at once, so a killed relay leaves a
|
||||
//! file that reads cleanly up to its last whole record.
|
||||
|
||||
use std::fs::{File, OpenOptions};
|
||||
use std::io::{self, BufWriter, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use crate::record::{self, Direction, Header, Kind, Protocol, Record};
|
||||
|
||||
/// Writes records for one capture.
|
||||
pub struct Recorder {
|
||||
out: Mutex<BufWriter<File>>,
|
||||
start: Instant,
|
||||
next_connection: AtomicU32,
|
||||
failed: AtomicBool,
|
||||
}
|
||||
|
||||
impl Recorder {
|
||||
/// Creates `session-<unix seconds>.dslr` in `dir` (never overwrites) and writes the header.
|
||||
///
|
||||
/// # Errors
|
||||
/// I/O errors, including an existing file of the same name.
|
||||
pub fn create(dir: &Path) -> io::Result<(Self, PathBuf)> {
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
|
||||
let path = dir.join(format!("session-{}.dslr", now.as_secs()));
|
||||
let file = OpenOptions::new().write(true).create_new(true).open(&path)?;
|
||||
let mut out = BufWriter::new(file);
|
||||
let start_unix_micros = u64::try_from(now.as_micros()).unwrap_or(u64::MAX);
|
||||
record::write_header(&mut out, Header { start_unix_micros })?;
|
||||
out.flush()?;
|
||||
let rec = Self {
|
||||
out: Mutex::new(out),
|
||||
start: Instant::now(),
|
||||
next_connection: AtomicU32::new(1),
|
||||
failed: AtomicBool::new(false),
|
||||
};
|
||||
Ok((rec, path))
|
||||
}
|
||||
|
||||
/// A fresh connection or flow id.
|
||||
pub fn new_connection(&self) -> u32 {
|
||||
self.next_connection.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Records bytes (split into several records if over [`record::MAX_PAYLOAD`]).
|
||||
pub fn log(&self, kind: Kind, protocol: Protocol, direction: Direction, connection: u32, payload: &[u8]) {
|
||||
let time_micros = u64::try_from(self.start.elapsed().as_micros()).unwrap_or(u64::MAX);
|
||||
let chunks: Vec<&[u8]> =
|
||||
if payload.is_empty() { vec![payload] } else { payload.chunks(record::MAX_PAYLOAD).collect() };
|
||||
let Ok(mut out) = self.out.lock() else { return self.fail("lock poisoned") };
|
||||
for chunk in chunks {
|
||||
let r = Record { kind, protocol, direction, connection, time_micros, payload: chunk.to_vec() };
|
||||
if let Err(e) = record::write_record(&mut *out, &r).and_then(|()| out.flush()) {
|
||||
return self.fail(&e.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Records a note (never pass key material here).
|
||||
pub fn note(&self, protocol: Protocol, connection: u32, text: &str) {
|
||||
self.log(Kind::Note, protocol, Direction::None, connection, text.as_bytes());
|
||||
}
|
||||
|
||||
/// Reports the first write failure on stderr; later ones stay silent.
|
||||
fn fail(&self, why: &str) {
|
||||
if !self.failed.swap(true, Ordering::Relaxed) {
|
||||
eprintln!("lab-relay: writing the record file failed: {why}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
//! Hides secrets when records are printed (`lab-relay dump`). The record file itself keeps everything; it never
|
||||
//! leaves the lab folder.
|
||||
|
||||
/// Query parameters whose values are secret or let someone redo the pairing proofs.
|
||||
pub const SECRET_PARAMS: [&str; 6] =
|
||||
["rikey", "salt", "clientchallenge", "serverchallengeresp", "clientpairingsecret", "pin"];
|
||||
/// XML elements whose text is secret.
|
||||
pub const SECRET_ELEMENTS: [&str; 2] = ["challengeresponse", "pairingsecret"];
|
||||
/// HTTP headers whose values are secret.
|
||||
pub const SECRET_HEADERS: [&str; 2] = ["authorization", "cookie"];
|
||||
/// What replaces a secret.
|
||||
pub const MARK: &[u8] = b"<redacted>";
|
||||
|
||||
fn ends_param_value(b: u8) -> bool {
|
||||
matches!(b, b'&' | b' ' | b'"' | b'\r' | b'\n' | b'<' | b'#')
|
||||
}
|
||||
|
||||
/// Returns `text` with every secret value replaced by [`MARK`].
|
||||
pub fn redact(text: &[u8]) -> Vec<u8> {
|
||||
let mut out = Vec::with_capacity(text.len());
|
||||
let mut i = 0;
|
||||
let lower: Vec<u8> = text.to_ascii_lowercase();
|
||||
'scan: while i < text.len() {
|
||||
// `name=` at a parameter boundary.
|
||||
if i == 0 || matches!(text[i - 1], b'?' | b'&' | b' ' | b'\n') {
|
||||
for name in SECRET_PARAMS {
|
||||
let key = [name.as_bytes(), b"="].concat();
|
||||
if lower[i..].starts_with(&key) {
|
||||
out.extend_from_slice(&text[i..i + key.len()]);
|
||||
out.extend_from_slice(MARK);
|
||||
i += key.len();
|
||||
while i < text.len() && !ends_param_value(text[i]) {
|
||||
i += 1;
|
||||
}
|
||||
continue 'scan;
|
||||
}
|
||||
}
|
||||
}
|
||||
// `<element>` … `</`.
|
||||
if text[i] == b'<' {
|
||||
for name in SECRET_ELEMENTS {
|
||||
let open = [b"<", name.as_bytes(), b">"].concat();
|
||||
if lower[i..].starts_with(&open) {
|
||||
out.extend_from_slice(&text[i..i + open.len()]);
|
||||
out.extend_from_slice(MARK);
|
||||
i += open.len();
|
||||
while i < text.len() && !text[i..].starts_with(b"</") {
|
||||
i += 1;
|
||||
}
|
||||
continue 'scan;
|
||||
}
|
||||
}
|
||||
}
|
||||
// `Header:` at a line start, up to the end of the line.
|
||||
if i == 0 || text[i - 1] == b'\n' {
|
||||
for name in SECRET_HEADERS {
|
||||
let key = [name.as_bytes(), b":"].concat();
|
||||
if lower[i..].starts_with(&key) {
|
||||
out.extend_from_slice(&text[i..i + key.len()]);
|
||||
out.extend_from_slice(b" ");
|
||||
out.extend_from_slice(MARK);
|
||||
i += key.len();
|
||||
while i < text.len() && text[i] != b'\r' && text[i] != b'\n' {
|
||||
i += 1;
|
||||
}
|
||||
continue 'scan;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push(text[i]);
|
||||
i += 1;
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn r(s: &str) -> String {
|
||||
String::from_utf8(redact(s.as_bytes())).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_key_is_hidden() {
|
||||
assert_eq!(
|
||||
r("GET /launch?uniqueid=0123&appid=1&rikey=00112233445566778899aabbccddeeff&rikeyid=7 HTTP/1.1"),
|
||||
"GET /launch?uniqueid=0123&appid=1&rikey=<redacted>&rikeyid=7 HTTP/1.1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pairing_values_are_hidden_but_names_and_certs_stay() {
|
||||
assert_eq!(
|
||||
r("GET /pair?uniqueid=1&phrase=getservercert&salt=ABCD&clientcert=2D2D HTTP/1.1"),
|
||||
"GET /pair?uniqueid=1&phrase=getservercert&salt=<redacted>&clientcert=2D2D HTTP/1.1"
|
||||
);
|
||||
assert_eq!(
|
||||
r("<root status_code=\"200\"><paired>1</paired><pairingsecret>ffee</pairingsecret></root>"),
|
||||
"<root status_code=\"200\"><paired>1</paired><pairingsecret><redacted></pairingsecret></root>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn auth_headers_are_hidden() {
|
||||
assert_eq!(
|
||||
r("POST /api/pin HTTP/1.1\r\nAuthorization: Basic dXNlcjpwYXNz\r\nHost: x\r\n"),
|
||||
"POST /api/pin HTTP/1.1\r\nAuthorization: <redacted>\r\nHost: x\r\n"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookalike_names_are_not_touched() {
|
||||
assert_eq!(r("GET /x?rikeyid=5&nosalt=1"), "GET /x?rikeyid=5&nosalt=1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn value_at_end_of_input_is_hidden() {
|
||||
assert_eq!(r("?rikey=abc"), "?rikey=<redacted>");
|
||||
assert_eq!(r("<challengeresponse>abc"), "<challengeresponse><redacted>");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! Equal-length byte replacement over a stream, safe across read boundaries.
|
||||
//!
|
||||
//! Bytes that could be the start of a pattern at the end of a chunk are held back until the next chunk (or
|
||||
//! [`Rewriter::flush`]), so a pattern split over two reads is still found. Lengths never change, so HTTP
|
||||
//! `Content-Length` stays right.
|
||||
|
||||
use crate::config::Rewrite;
|
||||
|
||||
/// A streaming rewriter.
|
||||
#[derive(Debug)]
|
||||
pub struct Rewriter {
|
||||
rules: Vec<Rewrite>,
|
||||
held: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Rewriter {
|
||||
/// A rewriter for `rules` (each non-empty, `from.len() == to.len()`, checked by the config).
|
||||
pub fn new(rules: Vec<Rewrite>) -> Self {
|
||||
Self { rules, held: Vec::new() }
|
||||
}
|
||||
|
||||
/// Feeds a chunk; returns the bytes that are safe to send and how many replacements were made.
|
||||
pub fn push(&mut self, chunk: &[u8]) -> (Vec<u8>, usize) {
|
||||
if self.rules.is_empty() {
|
||||
return (chunk.to_vec(), 0);
|
||||
}
|
||||
let mut data = std::mem::take(&mut self.held);
|
||||
data.extend_from_slice(chunk);
|
||||
let mut out = Vec::with_capacity(data.len());
|
||||
let mut count = 0;
|
||||
let mut i = 0;
|
||||
'scan: while i < data.len() {
|
||||
for r in &self.rules {
|
||||
if data[i..].starts_with(&r.from) {
|
||||
out.extend_from_slice(&r.to);
|
||||
i += r.from.len();
|
||||
count += 1;
|
||||
continue 'scan;
|
||||
}
|
||||
}
|
||||
// Could `data[i..]` be the beginning of a pattern that the next chunk completes?
|
||||
let rest = &data[i..];
|
||||
if self.rules.iter().any(|r| rest.len() < r.from.len() && r.from.starts_with(rest)) {
|
||||
self.held = rest.to_vec();
|
||||
return (out, count);
|
||||
}
|
||||
out.push(data[i]);
|
||||
i += 1;
|
||||
}
|
||||
(out, count)
|
||||
}
|
||||
|
||||
/// Releases held bytes (end of stream, or a pause in it).
|
||||
pub fn flush(&mut self) -> Vec<u8> {
|
||||
std::mem::take(&mut self.held)
|
||||
}
|
||||
|
||||
/// Whether there are no rules (the rewriter then passes bytes through and never holds any).
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.rules.is_empty()
|
||||
}
|
||||
|
||||
/// Bytes currently held back.
|
||||
#[cfg(test)]
|
||||
pub fn held(&self) -> usize {
|
||||
self.held.len()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn lab() -> Rewriter {
|
||||
Rewriter::new(vec![Rewrite { from: b"127.0.0.2".to_vec(), to: b"127.0.0.1".to_vec() }])
|
||||
}
|
||||
|
||||
fn run(r: &mut Rewriter, chunks: &[&[u8]]) -> (Vec<u8>, usize) {
|
||||
let mut out = Vec::new();
|
||||
let mut n = 0;
|
||||
for c in chunks {
|
||||
let (o, k) = r.push(c);
|
||||
out.extend(o);
|
||||
n += k;
|
||||
}
|
||||
out.extend(r.flush());
|
||||
(out, n)
|
||||
}
|
||||
|
||||
const ANSWER: &[u8] = b"<root status_code=\"200\"><sessionUrl0>rtsp://127.0.0.2:48010</sessionUrl0></root>";
|
||||
|
||||
#[test]
|
||||
fn replaces_in_one_chunk() {
|
||||
let (out, n) = run(&mut lab(), &[ANSWER]);
|
||||
assert_eq!(n, 1);
|
||||
assert_eq!(out, ANSWER.to_vec().replace_all_for_test());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_across_every_split_point() {
|
||||
let want = ANSWER.to_vec().replace_all_for_test();
|
||||
for cut in 0..=ANSWER.len() {
|
||||
let (out, n) = run(&mut lab(), &[&ANSWER[..cut], &ANSWER[cut..]]);
|
||||
assert_eq!(n, 1, "cut {cut}");
|
||||
assert_eq!(out, want, "cut {cut}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_by_byte_works() {
|
||||
let chunks: Vec<&[u8]> = ANSWER.chunks(1).collect();
|
||||
let (out, n) = run(&mut lab(), &chunks);
|
||||
assert_eq!((out, n), (ANSWER.to_vec().replace_all_for_test(), 1));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn length_never_changes_and_lookalikes_survive() {
|
||||
let input = b"127.0.0.20 127.0.0.2127.0.0.2 127.0.0. 127.0.0.3";
|
||||
let (out, n) = run(&mut lab(), &[input]);
|
||||
assert_eq!(out.len(), input.len());
|
||||
assert_eq!(out, b"127.0.0.10 127.0.0.1127.0.0.1 127.0.0. 127.0.0.3");
|
||||
assert_eq!(n, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn holds_only_a_possible_prefix() {
|
||||
let mut r = lab();
|
||||
let (out, _) = r.push(b"abc127.0.");
|
||||
assert_eq!(out, b"abc");
|
||||
assert_eq!(r.held(), 6);
|
||||
let (out, n) = r.push(b"x");
|
||||
assert_eq!((out, n), (b"127.0.x".to_vec(), 0));
|
||||
assert_eq!(r.held(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_rules_is_a_pass_through() {
|
||||
let mut r = Rewriter::new(Vec::new());
|
||||
assert_eq!(r.push(b"127.0.0.2"), (b"127.0.0.2".to_vec(), 0));
|
||||
}
|
||||
|
||||
trait ReplaceAll {
|
||||
fn replace_all_for_test(self) -> Vec<u8>;
|
||||
}
|
||||
impl ReplaceAll for Vec<u8> {
|
||||
fn replace_all_for_test(self) -> Vec<u8> {
|
||||
String::from_utf8(self).unwrap().replace("127.0.0.2", "127.0.0.1").into_bytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
//! Plain TCP relaying (HTTP, RTSP, and HTTPS in pass-through mode).
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::{Shutdown, TcpListener, TcpStream};
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::config::{Config, PortSpec, Rewrite};
|
||||
use crate::record::{Direction, Kind, Protocol};
|
||||
use crate::recorder::Recorder;
|
||||
use crate::rewrite::Rewriter;
|
||||
|
||||
/// How long the host-to-client side waits for more bytes before releasing bytes held by the rewriter.
|
||||
pub const HOLD_TIMEOUT: Duration = Duration::from_millis(50);
|
||||
/// Timeout for connecting to Sunshine.
|
||||
pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// Whether a protocol's bytes are plaintext the rewriter may touch.
|
||||
pub fn rewritable(protocol: Protocol) -> bool {
|
||||
matches!(protocol, Protocol::Http | Protocol::Rtsp | Protocol::HttpsPlain)
|
||||
}
|
||||
|
||||
/// Accepts connections on `spec`'s port forever.
|
||||
///
|
||||
/// # Errors
|
||||
/// Binding fails.
|
||||
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
|
||||
let listener = TcpListener::bind(config.listen_addr(&spec))?;
|
||||
for client in listener.incoming() {
|
||||
let client = match client {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
rec.note(spec.protocol, 0, &format!("accept failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
|
||||
thread::spawn(move || {
|
||||
let conn = rec.new_connection();
|
||||
if let Err(e) = relay(client, &config, spec, &rec, conn) {
|
||||
rec.note(spec.protocol, conn, &format!("connection ended with error: {e}"));
|
||||
}
|
||||
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
|
||||
let upstream_addr = config.upstream_addr(&spec);
|
||||
let peer = client.peer_addr()?;
|
||||
rec.log(Kind::Open, spec.protocol, Direction::None, conn, format!("{peer} -> {upstream_addr}").as_bytes());
|
||||
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
|
||||
let _ = client.set_nodelay(true);
|
||||
let _ = upstream.set_nodelay(true);
|
||||
let rules = if rewritable(spec.protocol) { config.rewrites.clone() } else { Vec::new() };
|
||||
pump_pair(client, upstream, spec.protocol, rec, conn, rules)
|
||||
}
|
||||
|
||||
/// Copies both directions until both sides are closed; rewrites host-to-client bytes with `rules`.
|
||||
///
|
||||
/// # Errors
|
||||
/// Socket errors.
|
||||
pub fn pump_pair(
|
||||
client: TcpStream,
|
||||
upstream: TcpStream,
|
||||
protocol: Protocol,
|
||||
rec: &Recorder,
|
||||
conn: u32,
|
||||
rules: Vec<Rewrite>,
|
||||
) -> io::Result<()> {
|
||||
let (mut c_read, mut u_write) = (client.try_clone()?, upstream.try_clone()?);
|
||||
thread::scope(|s| {
|
||||
s.spawn(|| {
|
||||
let mut buf = vec![0u8; 64 * 1024];
|
||||
loop {
|
||||
match c_read.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
rec.log(Kind::Data, protocol, Direction::ClientToHost, conn, &buf[..n]);
|
||||
if u_write.write_all(&buf[..n]).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = u_write.shutdown(Shutdown::Write);
|
||||
});
|
||||
host_to_client(upstream, client, protocol, rec, conn, rules)
|
||||
})
|
||||
}
|
||||
|
||||
fn host_to_client(
|
||||
mut upstream: TcpStream,
|
||||
mut client: TcpStream,
|
||||
protocol: Protocol,
|
||||
rec: &Recorder,
|
||||
conn: u32,
|
||||
rules: Vec<Rewrite>,
|
||||
) -> io::Result<()> {
|
||||
let mut rewriter = Rewriter::new(rules);
|
||||
if !rewriter.is_empty() {
|
||||
upstream.set_read_timeout(Some(HOLD_TIMEOUT))?;
|
||||
}
|
||||
let mut buf = vec![0u8; 64 * 1024];
|
||||
let result = loop {
|
||||
match upstream.read(&mut buf) {
|
||||
Ok(0) => break Ok(()),
|
||||
Ok(n) => {
|
||||
rec.log(Kind::Data, protocol, Direction::HostToClient, conn, &buf[..n]);
|
||||
let (out, count) = rewriter.push(&buf[..n]);
|
||||
if count > 0 {
|
||||
rec.note(protocol, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
|
||||
}
|
||||
if let Err(e) = client.write_all(&out) {
|
||||
break Err(e);
|
||||
}
|
||||
}
|
||||
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {
|
||||
let held = rewriter.flush();
|
||||
if let Err(e) = client.write_all(&held) {
|
||||
break Err(e);
|
||||
}
|
||||
}
|
||||
Err(e) => break Err(e),
|
||||
}
|
||||
};
|
||||
let rest = rewriter.flush();
|
||||
let _ = client.write_all(&rest);
|
||||
let _ = client.shutdown(Shutdown::Write);
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,396 @@
|
||||
//! TLS termination on the HTTPS port (LAB_CAPTURE.md section 4).
|
||||
//!
|
||||
//! Towards Moonlight the relay presents Sunshine's own lab certificate, the one Moonlight pinned while pairing, and
|
||||
//! asks for (but accepts any) client certificate. Towards Sunshine it presents Moonlight's own lab client
|
||||
//! certificate and accepts only Sunshine's lab certificate. Both sides see the certificates they expect; the relay
|
||||
//! records the plaintext in between. All key material is lab-only and is never written to the record file.
|
||||
|
||||
use std::io::{self, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier};
|
||||
use rustls::crypto::{CryptoProvider, WebPkiSupportedAlgorithms, verify_tls12_signature, verify_tls13_signature};
|
||||
use rustls::pki_types::pem::PemObject;
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, ServerName, UnixTime};
|
||||
use rustls::server::danger::{ClientCertVerified, ClientCertVerifier};
|
||||
use rustls::{ClientConfig, ClientConnection, Connection, DigitallySignedStruct, DistinguishedName, ServerConfig};
|
||||
use rustls::{ServerConnection, SignatureScheme};
|
||||
|
||||
use crate::config::{Config, PortSpec, TlsFiles};
|
||||
use crate::record::{Direction, Kind, Protocol};
|
||||
use crate::recorder::Recorder;
|
||||
use crate::rewrite::Rewriter;
|
||||
use crate::tcp::{self, CONNECT_TIMEOUT};
|
||||
|
||||
/// Read timeout while pumping plaintext between the two TLS sessions.
|
||||
const POLL: Duration = Duration::from_millis(20);
|
||||
|
||||
/// Accepts connections on the HTTPS port forever.
|
||||
///
|
||||
/// # Errors
|
||||
/// Binding fails.
|
||||
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
|
||||
let listener = TcpListener::bind(config.listen_addr(&spec))?;
|
||||
for client in listener.incoming() {
|
||||
let client = match client {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
rec.note(Protocol::HttpsPlain, 0, &format!("accept failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let (config, rec) = (Arc::clone(&config), Arc::clone(&rec));
|
||||
thread::spawn(move || {
|
||||
let conn = rec.new_connection();
|
||||
if let Err(e) = relay(client, &config, spec, &rec, conn) {
|
||||
rec.note(Protocol::HttpsPlain, conn, &format!("connection ended with error: {e}"));
|
||||
}
|
||||
rec.log(Kind::Close, Protocol::HttpsPlain, Direction::None, conn, &[]);
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The lab TLS material, loaded per connection (Moonlight's key may appear only after pairing step 1).
|
||||
struct Material {
|
||||
host_certs: Vec<CertificateDer<'static>>,
|
||||
host_key: PrivateKeyDer<'static>,
|
||||
client_certs: Vec<CertificateDer<'static>>,
|
||||
client_key: PrivateKeyDer<'static>,
|
||||
}
|
||||
|
||||
fn load(files: &TlsFiles) -> io::Result<Material> {
|
||||
fn certs(path: &Path) -> io::Result<Vec<CertificateDer<'static>>> {
|
||||
let certs = CertificateDer::pem_file_iter(path)
|
||||
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| io::Error::other(format!("{}: {e:?}", path.display())))?;
|
||||
if certs.is_empty() {
|
||||
return Err(io::Error::other(format!("{}: no certificate", path.display())));
|
||||
}
|
||||
Ok(certs)
|
||||
}
|
||||
fn key(path: &Path) -> io::Result<PrivateKeyDer<'static>> {
|
||||
// The error text names the file only; it never echoes key bytes.
|
||||
PrivateKeyDer::from_pem_file(path).map_err(|_| io::Error::other(format!("{}: no usable key", path.display())))
|
||||
}
|
||||
Ok(Material {
|
||||
host_certs: certs(&files.host_cert)?,
|
||||
host_key: key(&files.host_key)?,
|
||||
client_certs: certs(&files.client_cert)?,
|
||||
client_key: key(&files.client_key)?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Waits up to `wait` for all four files to load.
|
||||
fn load_waiting(files: &TlsFiles, wait: Duration) -> io::Result<Material> {
|
||||
let deadline = Instant::now() + wait;
|
||||
loop {
|
||||
match load(files) {
|
||||
Ok(m) => return Ok(m),
|
||||
Err(e) if Instant::now() >= deadline => return Err(e),
|
||||
Err(_) => thread::sleep(Duration::from_millis(200)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn sha256_hex(bytes: &[u8]) -> String {
|
||||
ring::digest::digest(&ring::digest::SHA256, bytes).as_ref().iter().map(|b| format!("{b:02x}")).collect()
|
||||
}
|
||||
|
||||
fn relay(client: TcpStream, config: &Config, spec: PortSpec, rec: &Recorder, conn: u32) -> io::Result<()> {
|
||||
let upstream_addr = config.upstream_addr(&spec);
|
||||
let peer = client.peer_addr()?;
|
||||
rec.log(
|
||||
Kind::Open,
|
||||
Protocol::HttpsPlain,
|
||||
Direction::None,
|
||||
conn,
|
||||
format!("{peer} -> {upstream_addr} (TLS terminated)").as_bytes(),
|
||||
);
|
||||
let Some(files) = &config.tls else {
|
||||
return Err(io::Error::other("TLS files not configured"));
|
||||
};
|
||||
let material = match load_waiting(files, config.wait_for_keys) {
|
||||
Ok(m) => m,
|
||||
Err(e) => {
|
||||
// No keys: carry the raw TLS bytes, so the session still works and is still recorded.
|
||||
rec.note(Protocol::HttpsTls, conn, &format!("lab keys not available ({e}); passing TLS through"));
|
||||
let upstream = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
|
||||
return tcp::pump_pair(client, upstream, Protocol::HttpsTls, rec, conn, Vec::new());
|
||||
}
|
||||
};
|
||||
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let algs = provider.signature_verification_algorithms;
|
||||
let server_config = ServerConfig::builder_with_provider(Arc::clone(&provider))
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(io::Error::other)?
|
||||
.with_client_cert_verifier(Arc::new(AnyClientCert { algs }))
|
||||
.with_single_cert(material.host_certs.clone(), material.host_key)
|
||||
.map_err(io::Error::other)?;
|
||||
let pinned = material.host_certs[0].as_ref().to_vec();
|
||||
let client_config = client_config(&provider, pinned, material.client_certs.clone(), material.client_key)?;
|
||||
|
||||
// Moonlight side first: it has already sent its ClientHello.
|
||||
let mut moonlight = client;
|
||||
let mut down = Connection::Server(ServerConnection::new(Arc::new(server_config)).map_err(io::Error::other)?);
|
||||
while down.is_handshaking() {
|
||||
down.complete_io(&mut moonlight)?;
|
||||
}
|
||||
let presented = down.peer_certificates().and_then(|c| c.first()).map(|c| sha256_hex(c.as_ref()));
|
||||
let expected = sha256_hex(material.client_certs[0].as_ref());
|
||||
rec.note(
|
||||
Protocol::HttpsPlain,
|
||||
conn,
|
||||
&format!(
|
||||
"client side: {:?}, {:?}, client certificate sha256 {} ({})",
|
||||
down.protocol_version(),
|
||||
down.negotiated_cipher_suite().map(|s| s.suite()),
|
||||
presented.as_deref().unwrap_or("none"),
|
||||
if presented.as_deref() == Some(expected.as_str()) {
|
||||
"matches the lab client certificate"
|
||||
} else {
|
||||
"differs from the lab client certificate"
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
let mut sunshine = TcpStream::connect_timeout(&upstream_addr, CONNECT_TIMEOUT)?;
|
||||
let name = ServerName::from(upstream_addr.ip());
|
||||
let mut up = Connection::Client(ClientConnection::new(Arc::new(client_config), name).map_err(io::Error::other)?);
|
||||
while up.is_handshaking() {
|
||||
up.complete_io(&mut sunshine)?;
|
||||
}
|
||||
rec.note(
|
||||
Protocol::HttpsPlain,
|
||||
conn,
|
||||
&format!("host side: {:?}, {:?}", up.protocol_version(), up.negotiated_cipher_suite().map(|s| s.suite())),
|
||||
);
|
||||
|
||||
for s in [&moonlight, &sunshine] {
|
||||
s.set_read_timeout(Some(POLL))?;
|
||||
let _ = s.set_nodelay(true);
|
||||
}
|
||||
pump(&mut down, &mut moonlight, &mut up, &mut sunshine, rec, conn, Rewriter::new(config.rewrites.clone()))
|
||||
}
|
||||
|
||||
fn client_config(
|
||||
provider: &Arc<CryptoProvider>,
|
||||
pinned: Vec<u8>,
|
||||
certs: Vec<CertificateDer<'static>>,
|
||||
key: PrivateKeyDer<'static>,
|
||||
) -> io::Result<ClientConfig> {
|
||||
let algs = provider.signature_verification_algorithms;
|
||||
ClientConfig::builder_with_provider(Arc::clone(provider))
|
||||
.with_safe_default_protocol_versions()
|
||||
.map_err(io::Error::other)?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(PinnedHost { pinned, algs }))
|
||||
.with_client_auth_cert(certs, key)
|
||||
.map_err(io::Error::other)
|
||||
}
|
||||
|
||||
/// Moves plaintext both ways until both sides are done.
|
||||
fn pump(
|
||||
down: &mut Connection,
|
||||
moonlight: &mut TcpStream,
|
||||
up: &mut Connection,
|
||||
sunshine: &mut TcpStream,
|
||||
rec: &Recorder,
|
||||
conn: u32,
|
||||
mut rewriter: Rewriter,
|
||||
) -> io::Result<()> {
|
||||
let (mut down_open, mut up_open) = (true, true);
|
||||
while down_open || up_open {
|
||||
if down_open {
|
||||
let (data, eof) = pull(down, moonlight)?;
|
||||
if !data.is_empty() {
|
||||
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::ClientToHost, conn, &data);
|
||||
if up_open {
|
||||
push(up, sunshine, &data)?;
|
||||
}
|
||||
}
|
||||
if eof {
|
||||
down_open = false;
|
||||
if up_open {
|
||||
up.send_close_notify();
|
||||
flush(up, sunshine)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
if up_open {
|
||||
let (data, eof) = pull(up, sunshine)?;
|
||||
if data.is_empty() {
|
||||
let held = rewriter.flush();
|
||||
if !held.is_empty() && down_open {
|
||||
push(down, moonlight, &held)?;
|
||||
}
|
||||
} else {
|
||||
rec.log(Kind::Data, Protocol::HttpsPlain, Direction::HostToClient, conn, &data);
|
||||
let (out, count) = rewriter.push(&data);
|
||||
if count > 0 {
|
||||
rec.note(Protocol::HttpsPlain, conn, &format!("rewrote {count} occurrence(s) in the bytes above"));
|
||||
}
|
||||
if down_open {
|
||||
push(down, moonlight, &out)?;
|
||||
}
|
||||
}
|
||||
if eof {
|
||||
up_open = false;
|
||||
if down_open {
|
||||
let held = rewriter.flush();
|
||||
push(down, moonlight, &held)?;
|
||||
down.send_close_notify();
|
||||
flush(down, moonlight)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reads what TLS bytes are there (or waits [`POLL`]) and returns the new plaintext and whether the peer is done.
|
||||
fn pull(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<(Vec<u8>, bool)> {
|
||||
let mut eof = false;
|
||||
match conn.read_tls(sock) {
|
||||
Ok(0) => eof = true,
|
||||
Ok(_) => {
|
||||
conn.process_new_packets().map_err(io::Error::other)?;
|
||||
}
|
||||
Err(e) if matches!(e.kind(), io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut) => {}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
let mut data = Vec::new();
|
||||
let mut buf = [0u8; 16 * 1024];
|
||||
loop {
|
||||
match conn.reader().read(&mut buf) {
|
||||
Ok(0) => {
|
||||
eof = true;
|
||||
break;
|
||||
}
|
||||
Ok(n) => data.extend_from_slice(&buf[..n]),
|
||||
Err(e) if e.kind() == io::ErrorKind::WouldBlock => break,
|
||||
Err(e) if e.kind() == io::ErrorKind::UnexpectedEof => {
|
||||
eof = true;
|
||||
break;
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
}
|
||||
}
|
||||
flush(conn, sock)?;
|
||||
Ok((data, eof))
|
||||
}
|
||||
|
||||
fn push(conn: &mut Connection, sock: &mut TcpStream, data: &[u8]) -> io::Result<()> {
|
||||
conn.writer().write_all(data)?;
|
||||
flush(conn, sock)
|
||||
}
|
||||
|
||||
fn flush(conn: &mut Connection, sock: &mut TcpStream) -> io::Result<()> {
|
||||
while conn.wants_write() {
|
||||
conn.write_tls(sock)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Accepts any client certificate (it is recorded by fingerprint, and Sunshine checks the real one).
|
||||
#[derive(Debug)]
|
||||
struct AnyClientCert {
|
||||
algs: WebPkiSupportedAlgorithms,
|
||||
}
|
||||
|
||||
impl ClientCertVerifier for AnyClientCert {
|
||||
fn offer_client_auth(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn client_auth_mandatory(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn root_hint_subjects(&self) -> &[DistinguishedName] {
|
||||
&[]
|
||||
}
|
||||
|
||||
fn verify_client_cert(
|
||||
&self,
|
||||
_end_entity: &CertificateDer<'_>,
|
||||
_intermediates: &[CertificateDer<'_>],
|
||||
_now: UnixTime,
|
||||
) -> Result<ClientCertVerified, rustls::Error> {
|
||||
Ok(ClientCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
verify_tls12_signature(message, cert, dss, &self.algs)
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
verify_tls13_signature(message, cert, dss, &self.algs)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
self.algs.supported_schemes()
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts exactly Sunshine's lab certificate, byte for byte.
|
||||
#[derive(Debug)]
|
||||
struct PinnedHost {
|
||||
pinned: Vec<u8>,
|
||||
algs: WebPkiSupportedAlgorithms,
|
||||
}
|
||||
|
||||
impl ServerCertVerifier for PinnedHost {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
end_entity: &CertificateDer<'_>,
|
||||
_intermediates: &[CertificateDer<'_>],
|
||||
_server_name: &ServerName<'_>,
|
||||
_ocsp_response: &[u8],
|
||||
_now: UnixTime,
|
||||
) -> Result<ServerCertVerified, rustls::Error> {
|
||||
if end_entity.as_ref() == self.pinned.as_slice() {
|
||||
Ok(ServerCertVerified::assertion())
|
||||
} else {
|
||||
Err(rustls::Error::General("host certificate is not the pinned lab certificate".into()))
|
||||
}
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
verify_tls12_signature(message, cert, dss, &self.algs)
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
message: &[u8],
|
||||
cert: &CertificateDer<'_>,
|
||||
dss: &DigitallySignedStruct,
|
||||
) -> Result<HandshakeSignatureValid, rustls::Error> {
|
||||
verify_tls13_signature(message, cert, dss, &self.algs)
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<SignatureScheme> {
|
||||
self.algs.supported_schemes()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
//! UDP relaying (video, control, audio, mic).
|
||||
//!
|
||||
//! Each client address gets its own upstream socket on the listen address, so Sunshine sends the stream to the
|
||||
//! relay (the address its PING or ENet connect came from) and the relay hands it to Moonlight.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::net::{SocketAddr, UdpSocket};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
|
||||
use crate::config::{Config, PortSpec};
|
||||
use crate::record::{Direction, Kind};
|
||||
use crate::recorder::Recorder;
|
||||
|
||||
/// Most client flows per port (one Moonlight uses one).
|
||||
pub const MAX_FLOWS: usize = 16;
|
||||
/// Largest datagram.
|
||||
pub const MAX_DATAGRAM: usize = 64 * 1024;
|
||||
|
||||
/// Windows reports an ICMP "port unreachable" from an earlier send as a reset on the next receive; that is not
|
||||
/// fatal for UDP.
|
||||
fn transient(e: &io::Error) -> bool {
|
||||
matches!(e.kind(), io::ErrorKind::ConnectionReset | io::ErrorKind::ConnectionRefused | io::ErrorKind::Interrupted)
|
||||
}
|
||||
|
||||
/// Relays one UDP port forever.
|
||||
///
|
||||
/// # Errors
|
||||
/// Binding fails.
|
||||
pub fn serve(config: Arc<Config>, spec: PortSpec, rec: Arc<Recorder>) -> io::Result<()> {
|
||||
let listen = Arc::new(UdpSocket::bind(config.listen_addr(&spec))?);
|
||||
let upstream_addr = config.upstream_addr(&spec);
|
||||
let flows: Mutex<HashMap<SocketAddr, (Arc<UdpSocket>, u32)>> = Mutex::new(HashMap::new());
|
||||
let mut buf = vec![0u8; MAX_DATAGRAM];
|
||||
loop {
|
||||
let (n, from) = match listen.recv_from(&mut buf) {
|
||||
Ok(v) => v,
|
||||
Err(e) if transient(&e) => continue,
|
||||
Err(e) => {
|
||||
rec.note(spec.protocol, 0, &format!("receive failed: {e}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let flow = {
|
||||
let Ok(mut map) = flows.lock() else { return Err(io::Error::other("flow table poisoned")) };
|
||||
if let Some(f) = map.get(&from) {
|
||||
Some(f.clone())
|
||||
} else if map.len() >= MAX_FLOWS {
|
||||
rec.note(spec.protocol, 0, &format!("dropping datagram from {from}: flow table full"));
|
||||
None
|
||||
} else {
|
||||
let up = Arc::new(UdpSocket::bind(SocketAddr::new(config.listen, 0))?);
|
||||
up.connect(upstream_addr)?;
|
||||
let conn = rec.new_connection();
|
||||
rec.log(
|
||||
Kind::Open,
|
||||
spec.protocol,
|
||||
Direction::None,
|
||||
conn,
|
||||
format!("{from} -> {upstream_addr}").as_bytes(),
|
||||
);
|
||||
spawn_return_path(Arc::clone(&up), Arc::clone(&listen), from, spec, Arc::clone(&rec), conn);
|
||||
map.insert(from, (Arc::clone(&up), conn));
|
||||
Some((up, conn))
|
||||
}
|
||||
};
|
||||
let Some((up, conn)) = flow else { continue };
|
||||
rec.log(Kind::Data, spec.protocol, Direction::ClientToHost, conn, &buf[..n]);
|
||||
if let Err(e) = up.send(&buf[..n])
|
||||
&& !transient(&e)
|
||||
{
|
||||
rec.note(spec.protocol, conn, &format!("send to host failed: {e}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_return_path(
|
||||
up: Arc<UdpSocket>,
|
||||
listen: Arc<UdpSocket>,
|
||||
client: SocketAddr,
|
||||
spec: PortSpec,
|
||||
rec: Arc<Recorder>,
|
||||
conn: u32,
|
||||
) {
|
||||
thread::spawn(move || {
|
||||
let mut buf = vec![0u8; MAX_DATAGRAM];
|
||||
loop {
|
||||
match up.recv(&mut buf) {
|
||||
Ok(n) => {
|
||||
rec.log(Kind::Data, spec.protocol, Direction::HostToClient, conn, &buf[..n]);
|
||||
if let Err(e) = listen.send_to(&buf[..n], client)
|
||||
&& !transient(&e)
|
||||
{
|
||||
rec.note(spec.protocol, conn, &format!("send to client failed: {e}"));
|
||||
}
|
||||
}
|
||||
Err(e) if transient(&e) => {}
|
||||
Err(e) => {
|
||||
rec.note(spec.protocol, conn, &format!("receive from host failed: {e}"));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
rec.log(Kind::Close, spec.protocol, Direction::None, conn, &[]);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user