Medlar/crates/testserver/src/lib.rs

343 lines
12 KiB
Rust

//! Local server with faults (ranges, throttle, cuts, expiry, logins) for the engine tests.
//!
//! `TestServer::start().await` binds 127.0.0.1 on a free port. Routes (all GET/HEAD):
//! - `/data/<seed>/<len>[/<name>]` deterministic file (`len` accepts k, m, g, t; 100g is fine).
//! Query: `disp=attachment|bare|star|both|inline|evil|dotfile`, `chunked=1`, `nolen=1`, `etag=0`,
//! `lm=0`, `weak=1`, plus any fault by name (see [`Faults`]). `farm=N` serves it from N nodes in turn that differ in
//! Last-Modified and nginx-style ETag only; `liar=1` with it gives the odd nodes other bytes of the same size.
//! - `/redirect/<n>?to=<path>&code=<30x>`, `/redirect/loop`, `/status/<code>`
//! - `/basic/<user>/<pass>/…`, `/digest/<user>/<pass>/…`, `/cookie/<token>/login` then `/cookie/<token>/…`,
//! `/referrer/<needle>/…`: the rest of the path is served after the check.
//! - `/dir/` (open listing, with `sub/`, `pack.zip`, `pack.tar`), `/site/` (small linked site),
//! `/archive.zip`, `/archive.tar`, `/sum/<md5|sha1|sha256|sha512>/<seed>/<len>`,
//! `/meta/v4.meta4`, `/meta/v3.metalink`, `/meta/header.bin` (Link and Digest headers),
//! `/media/<file>` (HLS and DASH, after [`TestServer::build_media`]).
mod content;
mod faults;
mod http;
pub mod proxy;
use std::collections::HashMap;
use std::io;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::net::{TcpListener, TcpStream};
use tokio::task::{JoinHandle, JoinSet};
use tokio::time::Instant;
pub use content::{ARCHIVE_FILES, META_LEN, META_SEED, expected, make_tar, make_zip, md5_hex};
pub use faults::Faults;
/// One request as the server saw it.
#[derive(Clone, Debug)]
pub struct Request {
pub id: usize,
pub conn: u64,
pub method: String,
/// Path and query as sent.
pub target: String,
pub headers: Vec<(String, String)>,
/// 0 until the answer is written.
pub status: u16,
/// Body bytes written.
pub sent: u64,
}
impl Request {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
pub fn path(&self) -> &str {
self.target.split('?').next().unwrap_or("")
}
}
#[derive(Default)]
struct PathStat {
requests: u32,
first: Option<Instant>,
}
pub(crate) struct State {
faults: Mutex<HashMap<String, Faults>>,
stats: Mutex<HashMap<String, PathStat>>,
log: Mutex<Vec<Request>>,
conns: Mutex<HashMap<IpAddr, usize>>,
pub(crate) pacer: tokio::sync::Mutex<Instant>,
pub(crate) media: Mutex<Option<PathBuf>>,
}
impl State {
/// Faults of a path: `*` for all, `prefix*` for a prefix (longest wins), else exact. Exact wins.
pub(crate) fn faults_for(&self, path: &str) -> Faults {
let map = self.faults.lock().unwrap();
if let Some(f) = map.get(path) {
return f.clone();
}
map.iter()
.filter_map(|(k, f)| k.strip_suffix('*').filter(|p| path.starts_with(p)).map(|p| (p.len(), f)))
.max_by_key(|(n, _)| *n)
.map(|(_, f)| f.clone())
.unwrap_or_default()
}
/// Count a request on a path: its number (from 1) and the age of the first one.
pub(crate) fn touch(&self, path: &str) -> (u32, Duration) {
let mut stats = self.stats.lock().unwrap();
let s = stats.entry(path.to_string()).or_default();
s.requests += 1;
let first = *s.first.get_or_insert_with(Instant::now);
(s.requests, first.elapsed())
}
pub(crate) fn conns_of(&self, ip: IpAddr) -> usize {
self.conns.lock().unwrap().get(&ip).copied().unwrap_or(0)
}
pub(crate) fn log_push(&self, req: &mut Request) -> usize {
let mut log = self.log.lock().unwrap();
req.id = log.len();
log.push(req.clone());
req.id
}
pub(crate) fn log_done(&self, idx: usize, status: u16, sent: u64) {
if let Some(r) = self.log.lock().unwrap().get_mut(idx) {
r.status = status;
r.sent = sent;
}
}
}
struct ConnGuard {
st: Arc<State>,
ip: IpAddr,
}
impl ConnGuard {
fn new(st: &Arc<State>, ip: IpAddr) -> ConnGuard {
*st.conns.lock().unwrap().entry(ip).or_default() += 1;
ConnGuard { st: st.clone(), ip }
}
}
impl Drop for ConnGuard {
fn drop(&mut self) {
if let Some(n) = self.st.conns.lock().unwrap().get_mut(&self.ip) {
*n = n.saturating_sub(1);
}
}
}
struct Tls {
cert_der: Vec<u8>,
cert_pem: String,
}
pub struct TestServer {
addr: SocketAddr,
st: Arc<State>,
tls: Option<Tls>,
task: JoinHandle<()>,
}
impl TestServer {
/// Plain HTTP on a free port of 127.0.0.1.
pub async fn start() -> TestServer {
Self::launch(0, false).await.expect("bind test server")
}
/// HTTPS with a fresh self-signed certificate for `localhost` and `127.0.0.1`.
pub async fn start_tls() -> TestServer {
Self::launch(0, true).await.expect("bind test server")
}
/// A fixed port (for the binary).
pub async fn start_on(port: u16, tls: bool) -> io::Result<TestServer> {
Self::launch(port, tls).await
}
async fn launch(port: u16, tls: bool) -> io::Result<TestServer> {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, port)).await?;
let addr = listener.local_addr()?;
let st = Arc::new(State {
faults: Mutex::default(),
stats: Mutex::default(),
log: Mutex::default(),
conns: Mutex::default(),
pacer: tokio::sync::Mutex::new(Instant::now()),
media: Mutex::default(),
});
let (acceptor, tls_info) = if tls {
let (cfg, info) = make_tls();
(Some(tokio_rustls::TlsAcceptor::from(Arc::new(cfg))), Some(info))
} else {
(None, None)
};
let st2 = st.clone();
let task = tokio::spawn(async move {
let mut conns = JoinSet::new();
let counter = AtomicU64::new(0);
loop {
tokio::select! {
Ok((tcp, peer)) = listener.accept() => {
let conn = counter.fetch_add(1, Ordering::Relaxed);
conns.spawn(handle_conn(tcp, peer.ip(), st2.clone(), acceptor.clone(), conn));
}
Some(_) = conns.join_next(), if !conns.is_empty() => {}
}
}
});
Ok(TestServer { addr, st, tls: tls_info, task })
}
pub fn addr(&self) -> SocketAddr {
self.addr
}
pub fn port(&self) -> u16 {
self.addr.port()
}
/// `http://127.0.0.1:PORT` (or https).
pub fn base(&self) -> String {
format!("{}://127.0.0.1:{}", if self.tls.is_some() { "https" } else { "http" }, self.addr.port())
}
/// Full URL of a path (with query).
pub fn url(&self, path: &str) -> String {
format!("{}{path}", self.base())
}
/// Path of the deterministic file `seed`/`len`.
pub fn data_path(seed: u64, len: u64) -> String {
format!("/data/{seed}/{len}")
}
/// DER of the server certificate (HTTPS only), to trust in a client.
pub fn cert_der(&self) -> Option<Vec<u8>> {
self.tls.as_ref().map(|t| t.cert_der.clone())
}
pub fn cert_pem(&self) -> Option<String> {
self.tls.as_ref().map(|t| t.cert_pem.clone())
}
/// Faults for a path: exact (`/data/1/1000`), prefix (`/data/*`) or all (`*`). Counters of an exact path restart.
pub fn set_faults(&self, path: &str, faults: Faults) {
self.st.stats.lock().unwrap().remove(path);
self.st.faults.lock().unwrap().insert(path.to_string(), faults);
}
pub fn clear_faults(&self, path: &str) {
self.st.faults.lock().unwrap().remove(path);
}
pub fn clear_all_faults(&self) {
self.st.faults.lock().unwrap().clear();
self.st.stats.lock().unwrap().clear();
}
/// Every request so far, oldest first.
pub fn log(&self) -> Vec<Request> {
self.st.log.lock().unwrap().clone()
}
/// Requests whose path (without query) is `path`.
pub fn requests_for(&self, path: &str) -> Vec<Request> {
self.log().into_iter().filter(|r| r.path() == path).collect()
}
pub fn clear_log(&self) {
self.st.log.lock().unwrap().clear();
}
/// Open connections from 127.0.0.1 now.
pub fn open_connections(&self) -> usize {
self.st.conns_of(IpAddr::V4(Ipv4Addr::LOCALHOST))
}
/// Make the HLS and DASH fixtures with ffmpeg (3 s of test video, 1 s segments) and serve them under
/// `/media/`: `master.m3u8`, `index.m3u8`, `seg*.ts`, `manifest.mpd`, `*.m4s`.
pub async fn build_media(&self) -> io::Result<()> {
let dir = std::env::temp_dir().join(format!("medlar-testserver-{}-{}", std::process::id(), self.addr.port()));
let d2 = dir.clone();
tokio::task::spawn_blocking(move || media::build(&d2)).await.map_err(io::Error::other)??;
*self.st.media.lock().unwrap() = Some(dir);
Ok(())
}
}
impl Drop for TestServer {
fn drop(&mut self) {
self.task.abort();
if let Some(dir) = self.st.media.lock().unwrap().take() {
let _ = std::fs::remove_dir_all(dir);
}
}
}
async fn handle_conn(tcp: TcpStream, ip: IpAddr, st: Arc<State>, acceptor: Option<tokio_rustls::TlsAcceptor>, conn: u64) {
let _ = tcp.set_nodelay(true);
let _guard = ConnGuard::new(&st, ip);
let Ok(reset) = socket2::SockRef::from(&tcp).try_clone() else { return };
let _ = match acceptor {
Some(a) => match a.accept(tcp).await {
Ok(s) => http::serve_conn(s, st, ip, conn, reset, "https").await,
Err(_) => return,
},
None => http::serve_conn(tcp, st, ip, conn, reset, "http").await,
};
}
fn make_tls() -> (tokio_rustls::rustls::ServerConfig, Tls) {
use tokio_rustls::rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
let certified = rcgen::generate_simple_self_signed(vec!["localhost".to_string(), "127.0.0.1".to_string()]).expect("make certificate");
let der = certified.cert.der().to_vec();
let key = PrivatePkcs8KeyDer::from(certified.signing_key.serialize_der());
let provider = Arc::new(tokio_rustls::rustls::crypto::ring::default_provider());
let cfg = tokio_rustls::rustls::ServerConfig::builder_with_provider(provider)
.with_safe_default_protocol_versions()
.expect("tls versions")
.with_no_client_auth()
.with_single_cert(vec![CertificateDer::from(der.clone())], PrivateKeyDer::Pkcs8(key))
.expect("tls config");
(cfg, Tls { cert_der: der, cert_pem: certified.cert.pem() })
}
mod media {
use std::io;
use std::path::Path;
use std::process::{Command, Stdio};
fn ffmpeg(dir: &Path, args: &[&str]) -> io::Result<()> {
let out = Command::new("/usr/bin/ffmpeg")
.current_dir(dir)
.args(["-y", "-loglevel", "error", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=10", "-t", "3", "-c:v", "mpeg4", "-g", "10"])
.args(args)
.stdin(Stdio::null())
.output()?;
if out.status.success() {
Ok(())
} else {
Err(io::Error::other(String::from_utf8_lossy(&out.stderr).into_owned()))
}
}
pub fn build(dir: &Path) -> io::Result<()> {
std::fs::create_dir_all(dir)?;
ffmpeg(dir, &["-f", "hls", "-hls_time", "1", "-hls_playlist_type", "vod", "-hls_segment_filename", "seg%d.ts", "index.m3u8"])?;
std::fs::write(
dir.join("master.m3u8"),
"#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=200000,RESOLUTION=160x120\nindex.m3u8\n",
)?;
ffmpeg(dir, &["-f", "dash", "-seg_duration", "1", "manifest.mpd"])?;
Ok(())
}
}