[edge] Listeners, tests first: an overall header deadline (slowloris), pipelined requests answered in order on both listeners, a proxy socket whose X-Forwarded-For is believed (red: the deadline is a pass-through)

This commit is contained in:
2026-11-10 20:43:50 +01:00
parent 0e9c2a7bc9
commit 7a2aee20eb
7 changed files with 722 additions and 14 deletions
+184
View File
@@ -311,3 +311,187 @@ pub async fn https_with_cert(
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}
// ------------------------------------------------------------------ pipelining
/// The request as bytes: request line, the headers as given, `content-length` for a body.
pub fn encode(req: &Req) -> Vec<u8> {
let mut out = format!("{} {} HTTP/1.1\r\n", req.method, req.path).into_bytes();
for (n, v) in &req.headers {
out.extend_from_slice(format!("{n}: {v}\r\n").as_bytes());
}
if !req.body.is_empty() {
out.extend_from_slice(format!("content-length: {}\r\n", req.body.len()).as_bytes());
}
out.extend_from_slice(b"\r\n");
out.extend_from_slice(&req.body);
out
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
/// Parse one response from the front of `buf` (`head`: the request was a HEAD). `Ok(None)`:
/// not complete yet; with `eof`, a body without a length ends at the end of the data.
fn parse_one(buf: &[u8], head: bool, eof: bool) -> io::Result<Option<(Resp, usize)>> {
let Some(end) = find(buf, b"\r\n\r\n") else {
return Ok(None);
};
let text = String::from_utf8_lossy(&buf[..end]).into_owned();
let mut lines = text.split("\r\n");
let status_line = lines.next().unwrap_or_default();
let status: u16 = status_line
.split(' ')
.nth(1)
.and_then(|s| s.parse().ok())
.ok_or_else(|| other(format!("bad status line: {status_line}")))?;
let headers: Vec<(String, String)> = lines
.filter_map(|l| l.split_once(':'))
.map(|(n, v)| (n.trim().to_ascii_lowercase(), v.trim().to_owned()))
.collect();
let get = |n: &str| headers.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());
let start = end + 4;
let no_body = head || status < 200 || status == 204 || status == 304;
let (body, used) = if no_body {
(Vec::new(), start)
} else if get("transfer-encoding").is_some_and(|t| t.eq_ignore_ascii_case("chunked")) {
let mut at = start;
let mut body = Vec::new();
loop {
let Some(nl) = find(&buf[at..], b"\r\n") else {
return Ok(None);
};
let size_text = String::from_utf8_lossy(&buf[at..at + nl]).into_owned();
let size = usize::from_str_radix(size_text.split(';').next().unwrap_or("").trim(), 16)
.map_err(|_| other(format!("bad chunk size: {size_text}")))?;
at += nl + 2;
if size == 0 {
// No trailers expected: the empty line ends the message.
if buf.len() < at + 2 {
return Ok(None);
}
at += 2;
break;
}
if buf.len() < at + size + 2 {
return Ok(None);
}
body.extend_from_slice(&buf[at..at + size]);
at += size + 2;
}
(body, at)
} else if let Some(len) = get("content-length") {
let len: usize = len
.parse()
.map_err(|_| other(format!("bad content-length: {len}")))?;
if buf.len() < start + len {
return Ok(None);
}
(buf[start..start + len].to_vec(), start + len)
} else if eof {
(buf[start..].to_vec(), buf.len())
} else {
return Ok(None);
};
Ok(Some((
Resp {
status,
headers,
body,
},
used,
)))
}
/// Send every request back to back in one write on one connection (HTTP/1.1 pipelining), then
/// read the answers in order until the server closes or `idle` passes without data. Interim
/// (1xx) answers are skipped.
pub async fn pipelined_on<S: AsyncRead + AsyncWrite + Unpin>(
mut io: S,
reqs: &[Req],
idle: Duration,
) -> io::Result<Vec<Resp>> {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut all = Vec::new();
for r in reqs {
all.extend(encode(r));
}
io.write_all(&all).await?;
io.flush().await?;
let mut buf = Vec::new();
let mut out = Vec::new();
let mut chunk = [0u8; 16 * 1024];
let mut eof = false;
while out.len() < reqs.len() {
let head = reqs[out.len()].method.eq_ignore_ascii_case("HEAD");
if let Some((resp, used)) = parse_one(&buf, head, eof)? {
buf.drain(..used);
if resp.status >= 200 {
out.push(resp);
}
continue;
}
if eof {
break;
}
match tokio::time::timeout(idle, io.read(&mut chunk)).await {
Ok(Ok(0)) | Ok(Err(_)) => eof = true,
Ok(Ok(n)) => buf.extend_from_slice(&chunk[..n]),
Err(_) => break,
}
}
Ok(out)
}
/// [`pipelined_on`] over a fresh plain TCP connection.
pub async fn http_pipelined(addr: SocketAddr, reqs: &[Req]) -> io::Result<Vec<Resp>> {
let s = TcpStream::connect(addr).await?;
pipelined_on(s, reqs, Duration::from_secs(3)).await
}
/// [`pipelined_on`] over a fresh TLS connection with the given SNI.
pub async fn https_pipelined(
addr: SocketAddr,
sni: &str,
roots: Arc<RootCertStore>,
reqs: &[Req],
) -> io::Result<Vec<Resp>> {
let s = tls_stream(addr, sni, roots).await?;
pipelined_on(s, reqs, Duration::from_secs(3)).await
}
#[cfg(test)]
mod pipeline_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn responses_are_split_by_length_and_chunks() {
let raw = b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\n\r\nhiHTTP/1.1 404 Not Found\r\n\
transfer-encoding: chunked\r\n\r\n3\r\nabc\r\n0\r\n\r\nHTTP/1.1 308 x\r\n\
location: /\r\ncontent-length: 0\r\n\r\n";
let (a, used) = parse_one(raw, false, false).unwrap().unwrap();
assert_eq!((a.status, a.text().as_str()), (200, "hi"));
let rest = &raw[used..];
let (b, used2) = parse_one(rest, false, false).unwrap().unwrap();
assert_eq!((b.status, b.text().as_str()), (404, "abc"));
let (c, _) = parse_one(&rest[used2..], false, false).unwrap().unwrap();
assert_eq!(c.status, 308);
assert!(parse_one(b"HTTP/1.1 200 OK\r\ncontent-length: 5\r\n\r\nab", false, false)
.unwrap()
.is_none());
}
}
/// One request over a fresh connection to a Unix socket (edge's proxy socket, control's UI
/// socket).
#[cfg(unix)]
pub async fn unix(path: &std::path::Path, req: &Req) -> io::Result<Resp> {
tokio::time::timeout(TIMEOUT, async {
let s = tokio::net::UnixStream::connect(path).await?;
send(s, req).await
})
.await
.map_err(|_| io::Error::new(io::ErrorKind::TimedOut, "request timed out"))?
}