91 lines
3.1 KiB
Rust
91 lines
3.1 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::apps::http_app::ServeHttp;
|
|
use pingora::protocols::http::ServerSession;
|
|
|
|
use crate::acme::Challenges;
|
|
use crate::logging::{AccessRecord, now_secs, truncate_ip};
|
|
use crate::proxy::{host_header, hostname};
|
|
use crate::runtime::Runtime;
|
|
|
|
pub struct HttpApp {
|
|
pub rt: Arc<Runtime>,
|
|
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 ServeHttp for HttpApp {
|
|
async fn response(&self, session: &mut ServerSession) -> Response<Vec<u8>> {
|
|
let start = Instant::now();
|
|
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) = self.rt.host(&name) else {
|
|
return empty(StatusCode::NOT_FOUND);
|
|
};
|
|
let uri = req.uri.path_and_query().map_or("/", |p| p.as_str());
|
|
let port = self.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) = &self.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
|
|
}
|
|
}
|