134 lines
4.7 KiB
Rust
134 lines
4.7 KiB
Rust
//! 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
|
|
}
|