Files
DomiStream/tools/lab-relay/src/config.rs
T

318 lines
12 KiB
Rust

//! 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(_))));
}
}