266 lines
9.3 KiB
Rust
266 lines
9.3 KiB
Rust
pub(super) async fn php_response(
|
|
service: &CompiledService,
|
|
php: &CompiledPhp,
|
|
method: Method,
|
|
headers: HeaderMap,
|
|
original_uri: Uri,
|
|
script_path: String,
|
|
path_info: Option<String>,
|
|
query: Option<String>,
|
|
body: Body,
|
|
context: RequestContext,
|
|
) -> Response {
|
|
let start = Instant::now();
|
|
let mut response = php_response_inner(
|
|
service,
|
|
php,
|
|
method,
|
|
headers,
|
|
original_uri,
|
|
script_path,
|
|
path_info,
|
|
query,
|
|
body,
|
|
context,
|
|
)
|
|
.await;
|
|
php.metrics.record(
|
|
response.status(),
|
|
start.elapsed().as_micros().min(u64::MAX as u128) as u64,
|
|
);
|
|
response
|
|
.extensions_mut()
|
|
.insert(crate::web_server::metrics::ResponseKind::Php);
|
|
response
|
|
}
|
|
|
|
async fn php_response_inner(
|
|
service: &CompiledService,
|
|
php: &CompiledPhp,
|
|
method: Method,
|
|
headers: HeaderMap,
|
|
original_uri: Uri,
|
|
script_path: String,
|
|
path_info: Option<String>,
|
|
query: Option<String>,
|
|
body: Body,
|
|
context: RequestContext,
|
|
) -> Response {
|
|
if php.max_request_body_bytes > 0 {
|
|
if let Some(length) = headers
|
|
.get(CONTENT_LENGTH)
|
|
.and_then(|value| value.to_str().ok())
|
|
.and_then(|value| value.parse::<u64>().ok())
|
|
{
|
|
if length > php.max_request_body_bytes {
|
|
return builtin_error_response(StatusCode::PAYLOAD_TOO_LARGE, &method);
|
|
}
|
|
}
|
|
}
|
|
let permit = match php.permits.clone().try_acquire_owned() {
|
|
Ok(permit) => permit,
|
|
Err(_) => {
|
|
php.metrics.failure(0);
|
|
let mut response = builtin_error_response(StatusCode::SERVICE_UNAVAILABLE, &method);
|
|
response
|
|
.headers_mut()
|
|
.insert(::http::header::RETRY_AFTER, HeaderValue::from_static("1"));
|
|
return response;
|
|
}
|
|
};
|
|
let mut io =
|
|
match tokio::time::timeout(php.connect_timeout, connect_fastcgi(&php.endpoint)).await {
|
|
Ok(Ok(io)) => io,
|
|
Ok(Err(error)) => {
|
|
php.metrics.failure(2);
|
|
tracing::warn!(%error, service = %service.id, "FastCGI connection failed");
|
|
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
|
}
|
|
Err(_) => {
|
|
php.metrics.failure(1);
|
|
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
|
|
}
|
|
};
|
|
let params = match fastcgi_params(
|
|
service,
|
|
php,
|
|
&method,
|
|
&headers,
|
|
&original_uri,
|
|
&script_path,
|
|
path_info.as_deref(),
|
|
query.as_deref(),
|
|
&context,
|
|
) {
|
|
Ok(params) => params,
|
|
Err(error) => {
|
|
tracing::warn!(%error, service = %service.id, "FastCGI parameter preparation failed");
|
|
php.metrics.failure(4);
|
|
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
|
}
|
|
};
|
|
let deadline = Instant::now() + php.request_timeout;
|
|
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?;
|
|
for chunk in params.chunks(u16::MAX as usize) {
|
|
write_fcgi_record(io.as_mut(), FCGI_PARAMS, chunk).await?;
|
|
}
|
|
write_fcgi_record(io.as_mut(), FCGI_PARAMS, &[]).await?;
|
|
|
|
let mut body = body;
|
|
let mut body_bytes = 0u64;
|
|
while let Some(frame) = body.frame().await {
|
|
let frame = frame.map_err(|error| {
|
|
FastCgiRequestWriteError::Io(io::Error::other(error.to_string()))
|
|
})?;
|
|
if let Ok(data) = frame.into_data() {
|
|
body_bytes = body_bytes.saturating_add(data.len() as u64);
|
|
if php.max_request_body_bytes > 0 && body_bytes > php.max_request_body_bytes {
|
|
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(io.as_mut(), FCGI_STDIN, &[]).await?;
|
|
io.flush().await?;
|
|
Ok::<(), FastCgiRequestWriteError>(())
|
|
};
|
|
match tokio::time::timeout_at(deadline, exchange).await {
|
|
Ok(Ok(())) => {}
|
|
Ok(Err(FastCgiRequestWriteError::BodyTooLarge)) => {
|
|
return builtin_error_response(StatusCode::PAYLOAD_TOO_LARGE, &method);
|
|
}
|
|
Ok(Err(FastCgiRequestWriteError::Io(error))) => {
|
|
php.metrics.failure(4);
|
|
tracing::warn!(%error, service = %service.id, "FastCGI request write failed");
|
|
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
|
}
|
|
Err(_) => {
|
|
php.metrics.failure(3);
|
|
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
|
|
}
|
|
}
|
|
|
|
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_type, content) = match record {
|
|
Ok(value) => value,
|
|
Err(error) if error.kind() == io::ErrorKind::TimedOut => {
|
|
php.metrics.failure(5);
|
|
return builtin_error_response(StatusCode::GATEWAY_TIMEOUT, &method);
|
|
}
|
|
Err(error) => {
|
|
tracing::warn!(%error, service = %service.id, "FastCGI response read failed");
|
|
php.metrics.failure(6);
|
|
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
|
}
|
|
};
|
|
match record_type {
|
|
FCGI_STDOUT => {
|
|
stdout.extend_from_slice(&content);
|
|
if stdout.len() > php.max_response_header_bytes {
|
|
php.metrics.failure(7);
|
|
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
|
}
|
|
if let Some((position, separator_len)) = find_cgi_header_end(&stdout) {
|
|
let body = stdout[position + separator_len..].to_vec();
|
|
let parsed = parse_cgi_headers(&stdout[..position]);
|
|
match parsed {
|
|
Ok((status, headers)) => break (status, headers, body),
|
|
Err(error) => {
|
|
tracing::warn!(%error, service = %service.id, "FastCGI CGI headers rejected");
|
|
php.metrics.failure(7);
|
|
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
FCGI_STDERR => {
|
|
let room = php.stderr_log_bytes.saturating_sub(stderr.len());
|
|
stderr.extend_from_slice(&content[..content.len().min(room)]);
|
|
}
|
|
FCGI_END_REQUEST => {
|
|
php.metrics.failure(7);
|
|
if !stderr.is_empty() {
|
|
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "FastCGI stderr");
|
|
}
|
|
return builtin_error_response(StatusCode::BAD_GATEWAY, &method);
|
|
}
|
|
_ => {}
|
|
}
|
|
};
|
|
if !stderr.is_empty() {
|
|
tracing::warn!(stderr = %String::from_utf8_lossy(&stderr), service = %service.id, "FastCGI stderr");
|
|
}
|
|
let send_body = method != Method::HEAD
|
|
&& status != StatusCode::NO_CONTENT
|
|
&& status != StatusCode::NOT_MODIFIED
|
|
&& !status.is_informational();
|
|
let (tx, rx) = mpsc::channel::<io::Result<Bytes>>(8);
|
|
tokio::spawn(drain_fastcgi_body(
|
|
io,
|
|
deadline,
|
|
tx,
|
|
initial_body,
|
|
send_body,
|
|
php.stderr_log_bytes,
|
|
php.metrics.clone(),
|
|
permit,
|
|
));
|
|
let mut response = Response::new(if send_body {
|
|
Body::from_stream(fastcgi_body_stream(rx))
|
|
} else {
|
|
Body::empty()
|
|
});
|
|
*response.status_mut() = status;
|
|
*response.headers_mut() = response_headers;
|
|
response
|
|
}
|
|
|
|
pub(super) fn fastcgi_body_stream(
|
|
rx: mpsc::Receiver<io::Result<Bytes>>,
|
|
) -> impl futures_util::Stream<Item = io::Result<Bytes>> {
|
|
stream::unfold(rx, |mut rx| async move {
|
|
rx.recv().await.map(|item| (item, rx))
|
|
})
|
|
.fuse()
|
|
}
|
|
|
|
pub(super) fn method_not_allowed_response() -> Response {
|
|
let mut response = status_response(
|
|
StatusCode::METHOD_NOT_ALLOWED,
|
|
"RustProxy: Web Server method is not allowed for a static resource\n",
|
|
);
|
|
response
|
|
.headers_mut()
|
|
.insert(ALLOW, HeaderValue::from_static("GET, HEAD"));
|
|
response
|
|
}
|
|
|
|
pub(super) fn php_for_path<'a>(
|
|
service: &'a CompiledService,
|
|
path: &Path,
|
|
) -> Option<&'a CompiledPhp> {
|
|
let php = service.php.as_ref()?;
|
|
let extension = path
|
|
.extension()
|
|
.and_then(|value| value.to_str())?
|
|
.to_ascii_lowercase();
|
|
(php.extensions.contains(&extension)
|
|
|| htaccess::php_extension(service.htaccess.as_ref(), path))
|
|
.then_some(php)
|
|
}
|
|
|
|
pub(super) fn protected_script_without_handler(service: &CompiledService, path: &Path) -> bool {
|
|
path.extension()
|
|
.and_then(|value| value.to_str())
|
|
.map(|value| value.to_ascii_lowercase())
|
|
.is_some_and(|extension| service.script_extensions.contains(&extension))
|
|
}
|