Files
ianitor/crates/edge/src/http_app.rs
T

132 lines
4.7 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/.
//! The plain-HTTP listener: answers ACME HTTP-01 challenges, redirects known hosts to HTTPS
//! with 308 (like Caddy), and answers 404 for anything else.
use std::sync::Arc;
use std::time::Instant;
use async_trait::async_trait;
use http::{Response, StatusCode, header};
use pingora::ErrorType;
use pingora::apps::{HttpPersistentSettings, HttpServerApp, ReusedHttpStream};
use pingora::http::ResponseHeader;
use pingora::protocols::http::ServerSession;
use pingora::server::ShutdownWatch;
use crate::acme::Challenges;
use crate::logging::{AccessRecord, now_secs, truncate_ip};
use crate::proxy::{host_header, hostname};
use crate::shared::Shared;
pub struct HttpApp {
pub shared: Arc<Shared>,
pub challenges: Arc<Challenges>,
}
fn empty(status: StatusCode) -> Response<Vec<u8>> {
let mut r = Response::new(Vec::new());
*r.status_mut() = status;
r.headers_mut()
.insert(header::CONTENT_LENGTH, http::HeaderValue::from_static("0"));
r
}
#[async_trait]
impl HttpServerApp for HttpApp {
/// Like Pingora's `ServeHttp` driver, but a request Pingora refuses to parse (for example
/// an absolute-form target whose authority differs from Host) gets a 400 instead of a
/// silently closed connection, as on the HTTPS listener.
async fn process_new_http(
self: &Arc<Self>,
mut http: ServerSession,
shutdown: &ShutdownWatch,
) -> Option<ReusedHttpStream> {
match http.read_request().await {
Ok(true) => {}
Ok(false) => return None,
Err(e) => {
if matches!(e.etype(), ErrorType::InvalidHTTPHeader) {
log::debug!(target: "ianitor::http", "bad request: {e}");
let _ = http.respond_error(400).await;
}
return None;
}
}
http.set_keepalive(if *shutdown.borrow() { None } else { Some(60) });
let (parts, body) = self.response(&mut http).await.into_parts();
let header: ResponseHeader = parts.into();
if http.write_response_header(Box::new(header)).await.is_err() {
return None;
}
if !body.is_empty() && http.write_response_body(body.into(), true).await.is_err() {
return None;
}
let settings = HttpPersistentSettings::for_session(&http);
match http.finish().await {
Ok(c) => c.map(|s| ReusedHttpStream::from_reusable_stream(s, settings)),
Err(_) => None,
}
}
}
impl HttpApp {
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
let start = Instant::now();
let rt = self.shared.current();
let req = session.req_header();
let hh = host_header(req);
let name = hostname(&hh);
let path = req.uri.path().to_owned();
if let Some(token) = path.strip_prefix("/.well-known/acme-challenge/")
&& let Some(key_auth) = self.challenges.get(token)
{
log::info!(target: "ianitor::acme", "answered HTTP-01 challenge for {name}");
let mut r = Response::new(key_auth.into_bytes());
r.headers_mut().insert(
header::CONTENT_TYPE,
http::HeaderValue::from_static("text/plain"),
);
return r;
}
let Some(host) = rt.host(&name) else {
return empty(StatusCode::NOT_FOUND);
};
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
let port = rt.cfg.https_port;
let location = if port == 443 {
format!("https://{name}{uri}")
} else {
format!("https://{name}:{port}{uri}")
};
let mut r = empty(StatusCode::PERMANENT_REDIRECT);
match http::HeaderValue::from_str(&location) {
Ok(v) => {
r.headers_mut().insert(header::LOCATION, v);
}
Err(_) => return empty(StatusCode::BAD_REQUEST),
}
if host.cfg.access_log
&& let Some(log) = &rt.access_log
{
log.write(&AccessRecord {
ts: now_secs(),
host: &host.cfg.hostname,
method: req.method.as_str(),
path: &path,
status: 308,
remote_ip: session
.client_addr()
.and_then(|a| a.as_inet())
.map(|a| truncate_ip(a.ip()).to_string()),
duration_ms: u64::try_from(start.elapsed().as_millis()).unwrap_or(u64::MAX),
});
}
r
}
}