v0.43.0
This commit is contained in:
1 parent
51631810e1
commit
e6176cfce3
28 files changed
+959
-506
No files matched your search
@@ -17,7 +17,7 @@ use http::{
|
||||
use http_body_util::BodyExt;
|
||||
use std::{collections::BTreeMap, io, path::Path, str::FromStr};
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt},
|
||||
io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, BufWriter},
|
||||
sync::{mpsc, OwnedSemaphorePermit},
|
||||
time::Instant,
|
||||
};
|
||||
@@ -31,6 +31,13 @@ pub(super) const FCGI_STDOUT: u8 = 6;
|
||||
const FCGI_STDERR: u8 = 7;
|
||||
const FCGI_RESPONDER: u16 = 1;
|
||||
const FCGI_REQUEST_ID: u16 = 1;
|
||||
const FCGI_HEADER_LEN: usize = 8;
|
||||
/// Request records (BEGIN, PARAMS, STDIN) are coalesced into a few socket writes.
|
||||
const FASTCGI_WRITE_BUFFER_BYTES: usize = 16 * 1024;
|
||||
/// Response records are read through one buffer instead of 2-3 reads per record.
|
||||
const FASTCGI_READ_BUFFER_BYTES: usize = 32 * 1024;
|
||||
/// Already-received STDOUT records are merged into one body chunk up to this size.
|
||||
const FASTCGI_BODY_CHUNK_BYTES: usize = 64 * 1024;
|
||||
|
||||
pub(super) trait FastCgiIo: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
impl<T> FastCgiIo for T where T: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
@@ -40,11 +47,27 @@ async fn connect_fastcgi(endpoint: &FastCgiEndpoint) -> io::Result<Box<dyn FastC
|
||||
#[cfg(unix)]
|
||||
FastCgiEndpoint::Unix(path) => Ok(Box::new(tokio::net::UnixStream::connect(path).await?)),
|
||||
FastCgiEndpoint::Tcp(address) => {
|
||||
Ok(Box::new(tokio::net::TcpStream::connect(address).await?))
|
||||
let stream = tokio::net::TcpStream::connect(address).await?;
|
||||
// FastCGI is a request/response exchange of small records; Nagle's
|
||||
// algorithm would only delay the final record of a request.
|
||||
stream.set_nodelay(true)?;
|
||||
Ok(Box::new(stream))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Type of the next FastCGI record when it is already complete in the read
|
||||
/// buffer, so it can be consumed without waiting for the socket.
|
||||
fn buffered_fcgi_record(io: &BufReader<Box<dyn FastCgiIo>>) -> Option<u8> {
|
||||
let buffer = io.buffer();
|
||||
if buffer.len() < FCGI_HEADER_LEN {
|
||||
return None;
|
||||
}
|
||||
let length = u16::from_be_bytes([buffer[4], buffer[5]]) as usize;
|
||||
let padding = buffer[6] as usize;
|
||||
(buffer.len() >= FCGI_HEADER_LEN + length + padding).then_some(buffer[1])
|
||||
}
|
||||
|
||||
pub(super) async fn write_fcgi_record(
|
||||
io: &mut dyn FastCgiIo,
|
||||
record_type: u8,
|
||||
@@ -338,7 +361,7 @@ pub(super) fn parse_cgi_headers(value: &[u8]) -> Result<(StatusCode, HeaderMap)>
|
||||
}
|
||||
|
||||
async fn drain_fastcgi_body(
|
||||
mut io: Box<dyn FastCgiIo>,
|
||||
mut io: BufReader<Box<dyn FastCgiIo>>,
|
||||
deadline: Instant,
|
||||
tx: mpsc::Sender<io::Result<Bytes>>,
|
||||
initial: Vec<u8>,
|
||||
@@ -347,18 +370,29 @@ async fn drain_fastcgi_body(
|
||||
metrics: std::sync::Arc<crate::web_server::metrics::PhpMetrics>,
|
||||
_permit: OwnedSemaphorePermit,
|
||||
) {
|
||||
if send_body && !initial.is_empty() && tx.send(Ok(Bytes::from(initial))).await.is_err() {
|
||||
return;
|
||||
}
|
||||
// Body bytes waiting to be sent. Records that have already arrived are
|
||||
// merged into one chunk; nothing is held back while waiting for the socket,
|
||||
// so flush() from the application still reaches the client immediately.
|
||||
let mut pending = if send_body { initial } else { Vec::new() };
|
||||
let mut stderr = Vec::new();
|
||||
loop {
|
||||
match read_fcgi_record(io.as_mut(), deadline).await {
|
||||
if !pending.is_empty()
|
||||
&& (pending.len() >= FASTCGI_BODY_CHUNK_BYTES || buffered_fcgi_record(&io).is_none())
|
||||
&& tx
|
||||
.send(Ok(Bytes::from(std::mem::take(&mut pending))))
|
||||
.await
|
||||
.is_err()
|
||||
{
|
||||
return;
|
||||
}
|
||||
match read_fcgi_record(&mut io, deadline).await {
|
||||
Ok((FCGI_STDOUT, content)) => {
|
||||
if send_body
|
||||
&& !content.is_empty()
|
||||
&& tx.send(Ok(Bytes::from(content))).await.is_err()
|
||||
{
|
||||
return;
|
||||
if send_body && !content.is_empty() {
|
||||
if pending.is_empty() {
|
||||
pending = content;
|
||||
} else {
|
||||
pending.extend_from_slice(&content);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((FCGI_STDERR, content)) => {
|
||||
@@ -370,12 +404,18 @@ async fn drain_fastcgi_body(
|
||||
Err(error) => {
|
||||
metrics.failure(8);
|
||||
if send_body {
|
||||
if !pending.is_empty() && tx.send(Ok(Bytes::from(pending))).await.is_err() {
|
||||
return;
|
||||
}
|
||||
let _ = tx.send(Err(error)).await;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if !pending.is_empty() && tx.send(Ok(Bytes::from(pending))).await.is_err() {
|
||||
return;
|
||||
}
|
||||
if !stderr.is_empty() {
|
||||
tracing::warn!(
|
||||
stderr = %String::from_utf8_lossy(&stderr),
|
||||
|
||||
@@ -68,7 +68,7 @@ async fn php_response_inner(
|
||||
return response;
|
||||
}
|
||||
};
|
||||
let mut io =
|
||||
let io =
|
||||
match tokio::time::timeout(php.connect_timeout, connect_fastcgi(&php.endpoint)).await {
|
||||
Ok(Ok(io)) => io,
|
||||
Ok(Err(error)) => {
|
||||
@@ -100,16 +100,22 @@ async fn php_response_inner(
|
||||
}
|
||||
};
|
||||
let deadline = Instant::now() + php.request_timeout;
|
||||
let mut writer = BufWriter::with_capacity(FASTCGI_WRITE_BUFFER_BYTES, io);
|
||||
let exchange = async {
|
||||
let mut begin = [0u8; 8];
|
||||
begin[..2].copy_from_slice(&FCGI_RESPONDER.to_be_bytes());
|
||||
write_fcgi_record(io.as_mut(), FCGI_BEGIN_REQUEST, &begin).await?;
|
||||
write_fcgi_record(&mut writer, FCGI_BEGIN_REQUEST, &begin).await?;
|
||||
for chunk in params.chunks(u16::MAX as usize) {
|
||||
write_fcgi_record(io.as_mut(), FCGI_PARAMS, chunk).await?;
|
||||
write_fcgi_record(&mut writer, FCGI_PARAMS, chunk).await?;
|
||||
}
|
||||
write_fcgi_record(io.as_mut(), FCGI_PARAMS, &[]).await?;
|
||||
write_fcgi_record(&mut writer, FCGI_PARAMS, &[]).await?;
|
||||
|
||||
let mut body = body;
|
||||
// Requests without a body go out in one write. With a body, deliver the
|
||||
// parameters first so the responder can start while the client uploads.
|
||||
if !http_body::Body::is_end_stream(&body) {
|
||||
writer.flush().await?;
|
||||
}
|
||||
let mut body_bytes = 0u64;
|
||||
while let Some(frame) = body.frame().await {
|
||||
let frame = frame.map_err(|error| {
|
||||
@@ -121,12 +127,12 @@ async fn php_response_inner(
|
||||
return Err(FastCgiRequestWriteError::BodyTooLarge);
|
||||
}
|
||||
for chunk in data.chunks(u16::MAX as usize) {
|
||||
write_fcgi_record(io.as_mut(), FCGI_STDIN, chunk).await?;
|
||||
write_fcgi_record(&mut writer, FCGI_STDIN, chunk).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
write_fcgi_record(io.as_mut(), FCGI_STDIN, &[]).await?;
|
||||
io.flush().await?;
|
||||
write_fcgi_record(&mut writer, FCGI_STDIN, &[]).await?;
|
||||
writer.flush().await?;
|
||||
Ok::<(), FastCgiRequestWriteError>(())
|
||||
};
|
||||
match tokio::time::timeout_at(deadline, exchange).await {
|
||||
@@ -145,10 +151,12 @@ async fn php_response_inner(
|
||||
}
|
||||
}
|
||||
|
||||
// The request is fully flushed; from here on the connection is only read.
|
||||
let mut io = BufReader::with_capacity(FASTCGI_READ_BUFFER_BYTES, writer.into_inner());
|
||||
let mut stdout = Vec::new();
|
||||
let mut stderr = Vec::new();
|
||||
let (status, response_headers, initial_body) = loop {
|
||||
let record = read_fcgi_record(io.as_mut(), deadline).await;
|
||||
let record = read_fcgi_record(&mut io, deadline).await;
|
||||
let (record_type, content) = match record {
|
||||
Ok(value) => value,
|
||||
Err(error) if error.kind() == io::ErrorKind::TimedOut => {
|
||||
|
||||
@@ -3250,3 +3250,188 @@ async fn htaccess_php_error_document_preserves_status_and_passes_its_own_query()
|
||||
assert_eq!(params["QUERY_STRING"], "404");
|
||||
assert_eq!(params["REQUEST_URI"], "/error.php?404");
|
||||
}
|
||||
|
||||
/// One encoded FastCGI record (request id 1), as a responder writes it.
|
||||
fn fcgi_record_bytes(kind: u8, content: &[u8]) -> Vec<u8> {
|
||||
let padding = (8 - content.len() % 8) % 8;
|
||||
let mut record = vec![1, kind, 0, 1];
|
||||
record.extend_from_slice(&(content.len() as u16).to_be_bytes());
|
||||
record.extend_from_slice(&[padding as u8, 0]);
|
||||
record.extend_from_slice(content);
|
||||
record.resize(record.len() + padding, 0);
|
||||
record
|
||||
}
|
||||
|
||||
fn php_fixture_service(root: &Path, address: std::net::SocketAddr) -> CompiledService {
|
||||
std::fs::write(root.join("index.php"), b"<?php echo 'SOURCE';").unwrap();
|
||||
let mut configured = Service {
|
||||
id: "php-buffered".into(),
|
||||
name: "PHP buffered".into(),
|
||||
document_root: root.to_path_buf(),
|
||||
index: vec!["index.php".into()],
|
||||
php: Php {
|
||||
enabled: true,
|
||||
endpoint: format!("tcp:{address}"),
|
||||
connect_timeout_ms: 500,
|
||||
request_timeout_ms: 5_000,
|
||||
max_concurrent_requests: 2,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
configured.validate().unwrap();
|
||||
configured.compile().unwrap()
|
||||
}
|
||||
|
||||
/// Reads one complete FastCGI request and returns (params, stdin).
|
||||
async fn read_fastcgi_request(stream: &mut tokio::net::TcpStream) -> (Vec<u8>, Vec<u8>) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
let (mut params, mut stdin) = (Vec::new(), Vec::new());
|
||||
loop {
|
||||
let (kind, content) = read_fcgi_record(stream, deadline).await.unwrap();
|
||||
match kind {
|
||||
FCGI_PARAMS => params.extend_from_slice(&content),
|
||||
FCGI_STDIN if content.is_empty() => return (params, stdin),
|
||||
FCGI_STDIN => stdin.extend_from_slice(&content),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fastcgi_buffered_exchange_keeps_many_records_stderr_and_body_intact() {
|
||||
const FCGI_STDERR: u8 = 7;
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let upload: Vec<u8> = (0..200_000u32).map(|value| (value % 251) as u8).collect();
|
||||
let expected_upload = upload.clone();
|
||||
let (seen_tx, seen_rx) = tokio::sync::oneshot::channel();
|
||||
tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
let (params, stdin) = read_fastcgi_request(&mut stream).await;
|
||||
let _ = seen_tx.send((decode_fastcgi_params(¶ms), stdin));
|
||||
// Headers split across records, interleaved STDERR, then many small
|
||||
// body records written in one burst (as PHP output buffers do).
|
||||
let mut burst = Vec::new();
|
||||
for record in [
|
||||
&b"Status: 200 OK\r\nContent-"[..],
|
||||
&b"Type: text/plain\r\n\r\nA"[..],
|
||||
] {
|
||||
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, record));
|
||||
}
|
||||
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDERR, b"notice"));
|
||||
for index in 0..3000u32 {
|
||||
burst.extend_from_slice(&fcgi_record_bytes(
|
||||
FCGI_STDOUT,
|
||||
format!("{index:05}|").as_bytes(),
|
||||
));
|
||||
}
|
||||
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, &[]));
|
||||
burst.extend_from_slice(&fcgi_record_bytes(FCGI_END_REQUEST, &[0u8; 8]));
|
||||
stream.write_all(&burst).await.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
});
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let service = php_fixture_service(tmp.path(), address);
|
||||
let mut post = request(Method::POST, "/index.php?x=1");
|
||||
post.headers_mut()
|
||||
.insert(CONTENT_LENGTH, upload.len().to_string().parse().unwrap());
|
||||
let response = serve_body_request(&service, &post, "/index.php", Body::from(upload)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()[CONTENT_TYPE], "text/plain");
|
||||
let body = response.into_body().collect().await.unwrap().to_bytes();
|
||||
let mut expected = b"A".to_vec();
|
||||
for index in 0..3000u32 {
|
||||
expected.extend_from_slice(format!("{index:05}|").as_bytes());
|
||||
}
|
||||
assert_eq!(body.as_ref(), expected.as_slice());
|
||||
let (params, stdin) = seen_rx.await.unwrap();
|
||||
assert_eq!(params["REQUEST_METHOD"], "POST");
|
||||
assert_eq!(params["QUERY_STRING"], "x=1");
|
||||
assert_eq!(stdin, expected_upload);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fastcgi_streamed_output_is_not_held_back_for_coalescing() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let (release_tx, release_rx) = tokio::sync::oneshot::channel::<()>();
|
||||
tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
read_fastcgi_request(&mut stream).await;
|
||||
write_fcgi_record(
|
||||
&mut stream,
|
||||
FCGI_STDOUT,
|
||||
b"Content-Type: text/plain\r\n\r\nfirst",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
// The rest is produced only after the client has seen the first chunk,
|
||||
// like an application calling flush() between slow steps.
|
||||
release_rx.await.unwrap();
|
||||
write_fcgi_record(&mut stream, FCGI_STDOUT, b"-second")
|
||||
.await
|
||||
.unwrap();
|
||||
write_fcgi_record(&mut stream, FCGI_STDOUT, &[])
|
||||
.await
|
||||
.unwrap();
|
||||
write_fcgi_record(&mut stream, FCGI_END_REQUEST, &[0u8; 8])
|
||||
.await
|
||||
.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
});
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let service = php_fixture_service(tmp.path(), address);
|
||||
let response = serve_request(&service, &request(Method::GET, "/index.php"), "/index.php").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let mut body = response.into_body();
|
||||
let first = tokio::time::timeout(Duration::from_secs(2), body.frame())
|
||||
.await
|
||||
.expect("first chunk must be delivered before more output exists")
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.into_data()
|
||||
.unwrap();
|
||||
assert_eq!(first.as_ref(), b"first");
|
||||
release_tx.send(()).unwrap();
|
||||
let rest = body.collect().await.unwrap().to_bytes();
|
||||
assert_eq!(rest.as_ref(), b"-second");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fastcgi_truncated_stream_delivers_received_bytes_then_errors() {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
let (mut stream, _) = listener.accept().await.unwrap();
|
||||
read_fastcgi_request(&mut stream).await;
|
||||
let mut burst = fcgi_record_bytes(FCGI_STDOUT, b"Content-Type: text/plain\r\n\r\nkept");
|
||||
burst.extend_from_slice(&fcgi_record_bytes(FCGI_STDOUT, b"-also"));
|
||||
stream.write_all(&burst).await.unwrap();
|
||||
// Half a record header, then the responder disappears.
|
||||
stream.write_all(&[1, FCGI_STDOUT, 0]).await.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
});
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let service = php_fixture_service(tmp.path(), address);
|
||||
let response = serve_request(&service, &request(Method::GET, "/index.php"), "/index.php").await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let mut body = response.into_body();
|
||||
let mut received = Vec::new();
|
||||
let mut failed = false;
|
||||
while let Some(frame) = body.frame().await {
|
||||
match frame {
|
||||
Ok(frame) => received.extend_from_slice(&frame.into_data().unwrap()),
|
||||
Err(_) => {
|
||||
failed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
assert_eq!(received, b"kept-also");
|
||||
assert!(
|
||||
failed,
|
||||
"a truncated FastCGI stream must not look like a complete body"
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user