241 lines
8.2 KiB
Rust
241 lines
8.2 KiB
Rust
// This Source Code Form is subject to the terms of the Mozilla Public
|
|
// License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
|
|
//! A raw TCP HTTP/1.1 server that answers with scripted bytes: 1xx heads, truncated bodies,
|
|
//! hangs. One request per connection, then the connection is closed. The request body is
|
|
//! read and recorded (Content-Length or chunked), so tests can check what was sent.
|
|
|
|
use std::net::SocketAddr;
|
|
use std::sync::{Arc, Mutex};
|
|
use std::time::Duration;
|
|
|
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
|
use tokio::net::TcpListener;
|
|
|
|
use crate::upstream::Recorded;
|
|
|
|
pub enum Reply {
|
|
/// Write these bytes, then close.
|
|
Bytes(Vec<u8>),
|
|
/// Accept, read the request, never answer (until the peer gives up).
|
|
Hang,
|
|
}
|
|
|
|
/// A complete response with Content-Length and `Connection: close`.
|
|
pub fn response(status: u16, reason: &str, headers: &[(&str, &str)], body: &[u8]) -> Vec<u8> {
|
|
let mut out = format!("HTTP/1.1 {status} {reason}\r\n");
|
|
for (n, v) in headers {
|
|
out.push_str(&format!("{n}: {v}\r\n"));
|
|
}
|
|
out.push_str(&format!(
|
|
"Content-Length: {}\r\nConnection: close\r\n\r\n",
|
|
body.len()
|
|
));
|
|
let mut bytes = out.into_bytes();
|
|
bytes.extend_from_slice(body);
|
|
bytes
|
|
}
|
|
|
|
type Handler = dyn Fn(&Recorded) -> Reply + Send + Sync;
|
|
|
|
#[derive(Clone)]
|
|
pub struct RawServer {
|
|
pub addr: SocketAddr,
|
|
requests: Arc<Mutex<Vec<Recorded>>>,
|
|
}
|
|
|
|
impl RawServer {
|
|
pub async fn start(handler: impl Fn(&Recorded) -> Reply + Send + Sync + 'static) -> RawServer {
|
|
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let server = RawServer {
|
|
addr: listener.local_addr().unwrap(),
|
|
requests: Arc::default(),
|
|
};
|
|
let handler: Arc<Handler> = Arc::new(handler);
|
|
let requests = server.requests.clone();
|
|
tokio::spawn(async move {
|
|
loop {
|
|
let Ok((mut stream, _)) = listener.accept().await else {
|
|
continue;
|
|
};
|
|
let handler = handler.clone();
|
|
let requests = requests.clone();
|
|
tokio::spawn(async move {
|
|
let mut buf = Vec::new();
|
|
let mut chunk = [0u8; 4096];
|
|
while !buf.windows(4).any(|w| w == b"\r\n\r\n") && buf.len() < 65536 {
|
|
match stream.read(&mut chunk).await {
|
|
Ok(0) | Err(_) => return,
|
|
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
|
}
|
|
}
|
|
let Some(mut req) = parse(&buf) else { return };
|
|
let end = buf.windows(4).position(|w| w == b"\r\n\r\n").unwrap_or(0) + 4;
|
|
let rest = buf.split_off(end);
|
|
match read_body(&mut stream, &req, rest).await {
|
|
Some(body) => req.body = body,
|
|
None => return,
|
|
}
|
|
requests.lock().unwrap().push(req.clone());
|
|
match handler(&req) {
|
|
Reply::Bytes(b) => {
|
|
let _ = stream.write_all(&b).await;
|
|
let _ = stream.shutdown().await;
|
|
}
|
|
Reply::Hang => tokio::time::sleep(Duration::from_secs(600)).await,
|
|
}
|
|
});
|
|
}
|
|
});
|
|
server
|
|
}
|
|
|
|
pub fn requests(&self) -> Vec<Recorded> {
|
|
self.requests.lock().unwrap().clone()
|
|
}
|
|
|
|
pub fn url(&self) -> String {
|
|
format!("http://{}", self.addr)
|
|
}
|
|
}
|
|
|
|
const MAX_BODY: usize = 16 << 20;
|
|
|
|
/// Read the request body that follows the head; `have` is what was read past the head.
|
|
/// `None` when the peer breaks off or sends malformed framing.
|
|
async fn read_body<S: AsyncReadExt + Unpin>(
|
|
stream: &mut S,
|
|
req: &Recorded,
|
|
mut have: Vec<u8>,
|
|
) -> Option<Vec<u8>> {
|
|
let mut chunk = [0u8; 4096];
|
|
let te = req
|
|
.header("transfer-encoding")
|
|
.map(|v| String::from_utf8_lossy(v).to_ascii_lowercase());
|
|
if te.as_deref().is_some_and(|t| t.contains("chunked")) {
|
|
let mut body = Vec::new();
|
|
let mut pos = 0;
|
|
loop {
|
|
// Need a full size line.
|
|
let line_end = loop {
|
|
if let Some(i) = have[pos..].windows(2).position(|w| w == b"\r\n") {
|
|
break pos + i;
|
|
}
|
|
let n = stream.read(&mut chunk).await.ok()?;
|
|
if n == 0 || have.len() > MAX_BODY {
|
|
return None;
|
|
}
|
|
have.extend_from_slice(&chunk[..n]);
|
|
};
|
|
let line = std::str::from_utf8(&have[pos..line_end]).ok()?;
|
|
let size = usize::from_str_radix(line.split(';').next()?.trim(), 16).ok()?;
|
|
pos = line_end + 2;
|
|
if size == 0 {
|
|
// Trailers (if any) end with an empty line.
|
|
while !have[pos..].windows(2).any(|w| w == b"\r\n") {
|
|
let n = stream.read(&mut chunk).await.ok()?;
|
|
if n == 0 {
|
|
return None;
|
|
}
|
|
have.extend_from_slice(&chunk[..n]);
|
|
}
|
|
return Some(body);
|
|
}
|
|
while have.len() < pos + size + 2 {
|
|
let n = stream.read(&mut chunk).await.ok()?;
|
|
if n == 0 || have.len() > MAX_BODY {
|
|
return None;
|
|
}
|
|
have.extend_from_slice(&chunk[..n]);
|
|
}
|
|
body.extend_from_slice(&have[pos..pos + size]);
|
|
pos += size + 2;
|
|
}
|
|
}
|
|
let len: usize = match req.header("content-length") {
|
|
Some(v) => std::str::from_utf8(v).ok()?.trim().parse().ok()?,
|
|
None => 0,
|
|
};
|
|
if len > MAX_BODY {
|
|
return None;
|
|
}
|
|
while have.len() < len {
|
|
let n = stream.read(&mut chunk).await.ok()?;
|
|
if n == 0 {
|
|
return None;
|
|
}
|
|
have.extend_from_slice(&chunk[..n]);
|
|
}
|
|
have.truncate(len);
|
|
Some(have)
|
|
}
|
|
|
|
fn parse(buf: &[u8]) -> Option<Recorded> {
|
|
let end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
|
|
let head = std::str::from_utf8(&buf[..end]).ok()?;
|
|
let mut lines = head.split("\r\n");
|
|
let mut first = lines.next()?.split(' ');
|
|
let method = first.next()?.to_owned();
|
|
let target = first.next()?.to_owned();
|
|
let path = target.split('?').next().unwrap_or("").to_owned();
|
|
let headers = lines
|
|
.filter_map(|l| l.split_once(':'))
|
|
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().as_bytes().to_vec()))
|
|
.collect();
|
|
Some(Recorded {
|
|
method,
|
|
path,
|
|
headers,
|
|
body: Vec::new(),
|
|
})
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
#![allow(clippy::unwrap_used)]
|
|
use super::*;
|
|
use tokio::net::TcpStream;
|
|
|
|
async fn send(server: &RawServer, bytes: &[u8]) {
|
|
let mut s = TcpStream::connect(server.addr).await.unwrap();
|
|
s.write_all(bytes).await.unwrap();
|
|
let mut out = Vec::new();
|
|
let _ = s.read_to_end(&mut out).await;
|
|
assert!(
|
|
out.starts_with(b"HTTP/1.1 200"),
|
|
"{}",
|
|
String::from_utf8_lossy(&out)
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn records_request_bodies() {
|
|
let server = RawServer::start(|_| Reply::Bytes(response(200, "OK", &[], b""))).await;
|
|
send(&server, b"GET /none HTTP/1.1\r\nHost: x\r\n\r\n").await;
|
|
send(
|
|
&server,
|
|
b"POST /cl HTTP/1.1\r\nHost: x\r\nContent-Length: 11\r\n\r\nLEAKED-BODY",
|
|
)
|
|
.await;
|
|
send(
|
|
&server,
|
|
b"POST /chunked HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n6\r\nLEAKED\r\n5;ext=1\r\n-BODY\r\n0\r\n\r\n",
|
|
)
|
|
.await;
|
|
let got: Vec<(String, Vec<u8>)> = server
|
|
.requests()
|
|
.into_iter()
|
|
.map(|r| (r.path, r.body))
|
|
.collect();
|
|
assert_eq!(
|
|
got,
|
|
[
|
|
("/none".to_owned(), b"".to_vec()),
|
|
("/cl".to_owned(), b"LEAKED-BODY".to_vec()),
|
|
("/chunked".to_owned(), b"LEAKED-BODY".to_vec()),
|
|
]
|
|
);
|
|
}
|
|
}
|