[edge] Fixes: skip 1xx, enforce auth timeout, resolve upstreams per connect, all Upgrade tokens, strip Remote-*
This commit is contained in:
+81
-13
@@ -3,7 +3,14 @@
|
||||
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
||||
|
||||
//! Small HTTP client on Pingora's connector, for forward-auth subrequests and health checks.
|
||||
//!
|
||||
//! - The whole exchange is bounded by one deadline (Pingora's connector ignores the peer's
|
||||
//! read timeout, so the deadline is enforced here with `tokio::time::timeout`).
|
||||
//! - Informational answers (100, 102, 103) are skipped; `101` is returned as the final head
|
||||
//! without a body, for the caller to reject.
|
||||
//! - Every resolved address is tried in order until one accepts the connection.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::{Bytes, BytesMut};
|
||||
@@ -21,14 +28,17 @@ pub struct Fetched {
|
||||
|
||||
/// Dial timeout, matching Caddy's reverse_proxy default.
|
||||
pub const DIAL_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
/// More 1xx heads than this before a final answer is treated as a broken server.
|
||||
const MAX_INFORMATIONAL: usize = 8;
|
||||
|
||||
pub fn peer(u: &UpstreamRt) -> HttpPeer {
|
||||
let mut p = HttpPeer::new(u.addr, u.tls, u.sni.clone());
|
||||
pub fn peer(addr: SocketAddr, u: &UpstreamRt) -> HttpPeer {
|
||||
let mut p = HttpPeer::new(addr, u.tls, u.sni.clone());
|
||||
p.options.connection_timeout = Some(DIAL_TIMEOUT);
|
||||
p
|
||||
}
|
||||
|
||||
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body.
|
||||
/// Send `req` without a body; read the whole response, at most `max_body` bytes of body,
|
||||
/// all within `timeout`.
|
||||
pub async fn fetch(
|
||||
connector: &Connector,
|
||||
u: &UpstreamRt,
|
||||
@@ -36,18 +46,76 @@ pub async fn fetch(
|
||||
max_body: usize,
|
||||
timeout: Duration,
|
||||
) -> Result<Fetched> {
|
||||
let mut p = peer(u);
|
||||
p.options.read_timeout = Some(timeout);
|
||||
p.options.write_timeout = Some(timeout);
|
||||
p.options.total_connection_timeout = Some(timeout);
|
||||
let (mut http, _reused) = connector.get_http_session(&p).await?;
|
||||
match tokio::time::timeout(timeout, exchange(connector, u, req, max_body, timeout)).await {
|
||||
Ok(r) => r,
|
||||
Err(_) => Error::e_explain(
|
||||
ErrorType::ReadTimedout,
|
||||
format!("no complete answer within {timeout:?}"),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
async fn exchange(
|
||||
connector: &Connector,
|
||||
u: &UpstreamRt,
|
||||
req: RequestHeader,
|
||||
max_body: usize,
|
||||
timeout: Duration,
|
||||
) -> Result<Fetched> {
|
||||
let addrs = u.resolve().await.map_err(|e| {
|
||||
Error::explain(
|
||||
ErrorType::ConnectNoRoute,
|
||||
format!("cannot resolve {}: {e}", u.authority),
|
||||
)
|
||||
})?;
|
||||
let mut last = None;
|
||||
let mut session = None;
|
||||
for addr in addrs {
|
||||
let mut p = peer(addr, u);
|
||||
p.options.total_connection_timeout = Some(timeout);
|
||||
match connector.get_http_session(&p).await {
|
||||
Ok((s, _reused)) => {
|
||||
session = Some(s);
|
||||
break;
|
||||
}
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
}
|
||||
let Some(mut http) = session else {
|
||||
return Err(last.unwrap_or_else(|| {
|
||||
Error::explain(ErrorType::ConnectError, "no address to connect to")
|
||||
}));
|
||||
};
|
||||
http.set_read_timeout(Some(timeout));
|
||||
http.set_write_timeout(Some(timeout));
|
||||
http.write_request_header(Box::new(req)).await?;
|
||||
http.finish_request_body().await?;
|
||||
http.read_response_header().await?;
|
||||
let header = http
|
||||
.response_header()
|
||||
.cloned()
|
||||
.ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?;
|
||||
|
||||
let mut header = None;
|
||||
for _ in 0..=MAX_INFORMATIONAL {
|
||||
http.read_response_header().await?;
|
||||
let h = http
|
||||
.response_header()
|
||||
.cloned()
|
||||
.ok_or_else(|| Error::explain(ErrorType::InvalidHTTPHeader, "no response header"))?;
|
||||
let s = h.status.as_u16();
|
||||
if (100..200).contains(&s) && s != 101 {
|
||||
continue;
|
||||
}
|
||||
header = Some(h);
|
||||
break;
|
||||
}
|
||||
let header = header.ok_or_else(|| {
|
||||
Error::explain(ErrorType::InvalidHTTPHeader, "only informational answers")
|
||||
})?;
|
||||
if header.status.as_u16() == 101 {
|
||||
// Switching protocols: there is no HTTP body to read.
|
||||
return Ok(Fetched {
|
||||
header,
|
||||
body: Bytes::new(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut body = BytesMut::new();
|
||||
while let Some(chunk) = http.read_response_body().await? {
|
||||
if body.len() + chunk.len() > max_body {
|
||||
|
||||
@@ -19,10 +19,10 @@ use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use http::header::{self, HeaderName, HeaderValue};
|
||||
use pingora::Result;
|
||||
use pingora::connectors::http::Connector;
|
||||
use pingora::http::{RequestHeader, ResponseHeader};
|
||||
use pingora::proxy::Session;
|
||||
use pingora::{Error, ErrorType, Result};
|
||||
|
||||
use crate::fetch::fetch;
|
||||
use crate::runtime::ForwardAuthRt;
|
||||
@@ -82,6 +82,13 @@ pub async fn check(
|
||||
|
||||
let got = fetch(connector, &fa.upstream, sub, MAX_AUTH_BODY, AUTH_TIMEOUT).await?;
|
||||
let status = got.header.status.as_u16();
|
||||
if status < 200 {
|
||||
// 101 (or any 1xx left over) is not an answer we can pass on or treat as an allow.
|
||||
return Error::e_explain(
|
||||
ErrorType::InvalidHTTPHeader,
|
||||
format!("auth server answered {status}"),
|
||||
);
|
||||
}
|
||||
if (200..300).contains(&status) {
|
||||
let copy = fa
|
||||
.copy_headers
|
||||
|
||||
+61
-23
@@ -35,25 +35,40 @@ async fn probe(connector: &Connector, u: &UpstreamRt, path: &str) -> bool {
|
||||
{
|
||||
return false;
|
||||
}
|
||||
match tokio::time::timeout(TIMEOUT, fetch(connector, u, req, 64 * 1024, TIMEOUT)).await {
|
||||
Ok(Ok(f)) => f.header.status.is_success(),
|
||||
_ => false,
|
||||
match fetch(connector, u, req, 64 * 1024, TIMEOUT).await {
|
||||
Ok(f) => f.header.status.is_success(),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// One round over a host's upstreams. Each probe runs in its own task, so a panic inside a
|
||||
/// probe (e.g. a library bug on an odd answer) marks that upstream unhealthy instead of
|
||||
/// ending health checks.
|
||||
async fn round(host: &Arc<HostRt>, path: &str, connector: &Arc<Connector>) {
|
||||
for i in 0..host.upstreams.len() {
|
||||
let (h, p, c) = (host.clone(), path.to_owned(), connector.clone());
|
||||
let ok = match tokio::spawn(async move { probe(&c, &h.upstreams[i], &p).await }).await {
|
||||
Ok(ok) => ok,
|
||||
Err(e) => {
|
||||
log::error!(target: "ianitor::health", "{}: health check of {} crashed ({e}); counting it as failed", host.cfg.hostname, host.upstreams[i].authority);
|
||||
false
|
||||
}
|
||||
};
|
||||
let u = &host.upstreams[i];
|
||||
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
|
||||
if ok {
|
||||
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
|
||||
} else {
|
||||
log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
|
||||
let connector = Connector::new(None);
|
||||
let connector = Arc::new(Connector::new(None));
|
||||
loop {
|
||||
for u in &host.upstreams {
|
||||
let ok = probe(&connector, u, &path).await;
|
||||
if u.healthy.swap(ok, Ordering::Relaxed) != ok {
|
||||
if ok {
|
||||
log::info!(target: "ianitor::health", "{}: upstream {} is healthy again", host.cfg.hostname, u.authority);
|
||||
} else {
|
||||
log::warn!(target: "ianitor::health", "{}: upstream {} failed its health check", host.cfg.hostname, u.authority);
|
||||
}
|
||||
}
|
||||
}
|
||||
round(&host, &path, &connector).await;
|
||||
tokio::time::sleep(every).await;
|
||||
}
|
||||
}
|
||||
@@ -61,16 +76,39 @@ async fn watch(host: Arc<HostRt>, path: String, every: Duration) {
|
||||
#[async_trait]
|
||||
impl BackgroundService for HealthChecks {
|
||||
async fn start(&self, mut shutdown: ShutdownWatch) {
|
||||
let mut tasks = Vec::new();
|
||||
for host in self.rt.hosts.values() {
|
||||
if let Some(hc) = &host.cfg.health_check {
|
||||
let every = Duration::from_secs(u64::from(hc.interval_secs.max(1)));
|
||||
tasks.push(tokio::spawn(watch(host.clone(), hc.path.clone(), every)));
|
||||
let checked: Vec<(Arc<HostRt>, String, Duration)> = self
|
||||
.rt
|
||||
.hosts
|
||||
.values()
|
||||
.filter_map(|h| {
|
||||
h.cfg.health_check.as_ref().map(|hc| {
|
||||
(
|
||||
h.clone(),
|
||||
hc.path.clone(),
|
||||
Duration::from_secs(u64::from(hc.interval_secs.max(1))),
|
||||
)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let mut tasks = tokio::task::JoinSet::new();
|
||||
let mut which = std::collections::HashMap::new();
|
||||
for (i, (h, p, every)) in checked.iter().enumerate() {
|
||||
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||
}
|
||||
// A watcher never returns; if one ends anyway, say so and start it again.
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = shutdown.changed() => break,
|
||||
Some(done) = tasks.join_next_with_id() => {
|
||||
let id = match &done { Ok((id, ())) => *id, Err(e) => e.id() };
|
||||
if let Some(i) = which.remove(&id) {
|
||||
let (h, p, every) = &checked[i];
|
||||
log::error!(target: "ianitor::health", "{}: health checker stopped; restarting it", h.cfg.hostname);
|
||||
which.insert(tasks.spawn(watch(h.clone(), p.clone(), *every)).id(), i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = shutdown.changed().await;
|
||||
for t in tasks {
|
||||
t.abort();
|
||||
}
|
||||
tasks.abort_all();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,8 +10,11 @@ use std::time::Instant;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use http::{Response, StatusCode, header};
|
||||
use pingora::apps::http_app::ServeHttp;
|
||||
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};
|
||||
@@ -32,7 +35,44 @@ fn empty(status: StatusCode) -> Response<Vec<u8>> {
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ServeHttp for HttpApp {
|
||||
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 req = session.req_header();
|
||||
|
||||
+88
-23
@@ -30,18 +30,27 @@ pub struct EdgeProxy {
|
||||
|
||||
pub struct Ctx {
|
||||
host: Option<Arc<HostRt>>,
|
||||
/// Chosen upstream and its resolved addresses; connect failures move to the next address.
|
||||
upstream: Option<usize>,
|
||||
addrs: Vec<std::net::SocketAddr>,
|
||||
addr_idx: usize,
|
||||
/// The Host header as the client sent it (with port, if any).
|
||||
host_header: String,
|
||||
start: Instant,
|
||||
}
|
||||
|
||||
/// Host header (HTTP/1) or :authority (HTTP/2).
|
||||
/// The request's host: the authority of an absolute-form target (or HTTP/2 :authority) wins
|
||||
/// over the Host header, as RFC 9112 §3.2.2 requires and Go/Caddy do.
|
||||
pub fn host_header(req: &RequestHeader) -> String {
|
||||
req.headers
|
||||
.get(header::HOST)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned)
|
||||
.or_else(|| req.uri.authority().map(|a| a.as_str().to_owned()))
|
||||
req.uri
|
||||
.authority()
|
||||
.map(|a| a.as_str().to_owned())
|
||||
.or_else(|| {
|
||||
req.headers
|
||||
.get(header::HOST)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
@@ -89,11 +98,13 @@ fn apply(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_websocket_upgrade(req: &RequestHeader) -> bool {
|
||||
req.headers
|
||||
.get(header::UPGRADE)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.is_some_and(|v| v.trim().eq_ignore_ascii_case("websocket"))
|
||||
/// Any `Upgrade` field, any comma-separated token, equal to `websocket` (case-insensitive).
|
||||
pub fn is_websocket_upgrade(req: &RequestHeader) -> bool {
|
||||
req.headers.get_all(header::UPGRADE).iter().any(|v| {
|
||||
String::from_utf8_lossy(v.as_bytes())
|
||||
.split(',')
|
||||
.any(|t| t.trim().eq_ignore_ascii_case("websocket"))
|
||||
})
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
@@ -103,6 +114,9 @@ impl ProxyHttp for EdgeProxy {
|
||||
fn new_ctx(&self) -> Ctx {
|
||||
Ctx {
|
||||
host: None,
|
||||
upstream: None,
|
||||
addrs: Vec::new(),
|
||||
addr_idx: 0,
|
||||
host_header: String::new(),
|
||||
start: Instant::now(),
|
||||
}
|
||||
@@ -120,6 +134,11 @@ impl ProxyHttp for EdgeProxy {
|
||||
let fa = self.rt.forward_auth.as_ref().ok_or_else(|| {
|
||||
Error::explain(ErrorType::HTTPStatus(500), "forward-auth is not configured")
|
||||
})?;
|
||||
// Client-sent identity headers never survive, whatever copy_headers says.
|
||||
let req = session.req_header_mut();
|
||||
for name in &fa.strip_headers {
|
||||
req.remove_header(name);
|
||||
}
|
||||
let ip = client_ip(session).map(|i| i.to_string());
|
||||
let outcome = match forward_auth::check(
|
||||
&self.connector,
|
||||
@@ -171,27 +190,60 @@ impl ProxyHttp for EdgeProxy {
|
||||
async fn upstream_peer(&self, _session: &mut Session, ctx: &mut Ctx) -> Result<Box<HttpPeer>> {
|
||||
let host = ctx
|
||||
.host
|
||||
.as_ref()
|
||||
.clone()
|
||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(500), "no host"))?;
|
||||
let n = host.upstreams.len();
|
||||
let first = host.next.fetch_add(1, Ordering::Relaxed);
|
||||
let chosen = (0..n)
|
||||
.map(|i| &host.upstreams[(first + i) % n])
|
||||
.find(|u| u.healthy.load(Ordering::Relaxed))
|
||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream"))?;
|
||||
log::debug!(target: "ianitor::proxy", "{}: upstream {}", host.cfg.hostname, chosen.authority);
|
||||
Ok(Box::new(fetch::peer(chosen)))
|
||||
let idx = match ctx.upstream {
|
||||
// A retry after a failed connect: same upstream, next address.
|
||||
Some(i) => i,
|
||||
None => {
|
||||
let n = host.upstreams.len();
|
||||
let first = host.next.fetch_add(1, Ordering::Relaxed);
|
||||
let i = (0..n)
|
||||
.map(|k| (first + k) % n)
|
||||
.find(|&k| host.upstreams[k].healthy.load(Ordering::Relaxed))
|
||||
.ok_or_else(|| {
|
||||
Error::explain(ErrorType::HTTPStatus(503), "no healthy upstream")
|
||||
})?;
|
||||
let up = &host.upstreams[i];
|
||||
ctx.addrs = match up.resolve().await {
|
||||
Ok(a) => a,
|
||||
Err(e) => {
|
||||
log::warn!(target: "ianitor::proxy", "{}: cannot resolve upstream {}: {e}", host.cfg.hostname, up.authority);
|
||||
return Err(Error::explain(
|
||||
ErrorType::HTTPStatus(502),
|
||||
"upstream does not resolve",
|
||||
));
|
||||
}
|
||||
};
|
||||
ctx.upstream = Some(i);
|
||||
ctx.addr_idx = 0;
|
||||
i
|
||||
}
|
||||
};
|
||||
let up = &host.upstreams[idx];
|
||||
let addr = *ctx
|
||||
.addrs
|
||||
.get(ctx.addr_idx)
|
||||
.ok_or_else(|| Error::explain(ErrorType::HTTPStatus(502), "no address left"))?;
|
||||
log::debug!(target: "ianitor::proxy", "{}: upstream {} at {addr}", host.cfg.hostname, up.authority);
|
||||
Ok(Box::new(fetch::peer(addr, up)))
|
||||
}
|
||||
|
||||
fn fail_to_connect(
|
||||
&self,
|
||||
_s: &mut Session,
|
||||
_p: &HttpPeer,
|
||||
_c: &mut Ctx,
|
||||
ctx: &mut Ctx,
|
||||
mut e: Box<Error>,
|
||||
) -> Box<Error> {
|
||||
// Like Caddy's default (no lb_try_duration): one attempt, then 502.
|
||||
e.set_retry(false);
|
||||
// Like Caddy's dialer: try every address of the chosen upstream, then 502. Other
|
||||
// upstreams are not tried (Caddy's default has no lb_try_duration).
|
||||
if ctx.addr_idx + 1 < ctx.addrs.len() {
|
||||
ctx.addr_idx += 1;
|
||||
e.set_retry(true);
|
||||
} else {
|
||||
e.set_retry(false);
|
||||
}
|
||||
e
|
||||
}
|
||||
|
||||
@@ -201,6 +253,19 @@ impl ProxyHttp for EdgeProxy {
|
||||
req: &mut RequestHeader,
|
||||
ctx: &mut Ctx,
|
||||
) -> Result<()> {
|
||||
// Origin-form target and the routed host, also for absolute-form requests.
|
||||
if req.uri.authority().is_some() {
|
||||
let pq = req
|
||||
.uri
|
||||
.path_and_query()
|
||||
.map_or("/", |p| p.as_str())
|
||||
.to_owned();
|
||||
let uri = pq
|
||||
.parse::<http::Uri>()
|
||||
.map_err(|_| Error::explain(ErrorType::HTTPStatus(400), "bad request target"))?;
|
||||
req.set_uri(uri);
|
||||
}
|
||||
req.insert_header(header::HOST, ctx.host_header.as_str())?;
|
||||
// Forwarding headers are always edge's own; client-supplied values are replaced.
|
||||
match client_ip(session) {
|
||||
Some(ip) => req.insert_header("X-Forwarded-For", ip.to_string())?,
|
||||
|
||||
+46
-11
@@ -6,7 +6,7 @@
|
||||
//! parsed header names, secrets loaded, certificates loaded. Built once at startup.
|
||||
|
||||
use std::collections::{BTreeSet, HashMap};
|
||||
use std::net::{SocketAddr, ToSocketAddrs};
|
||||
use std::net::SocketAddr;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize};
|
||||
@@ -27,7 +27,9 @@ pub enum Op {
|
||||
}
|
||||
|
||||
pub struct UpstreamRt {
|
||||
pub addr: SocketAddr,
|
||||
/// Host name or IP literal (IPv6 without brackets).
|
||||
pub host: String,
|
||||
pub port: u16,
|
||||
/// `host:port` as configured; the Host header of health checks.
|
||||
pub authority: String,
|
||||
pub tls: bool,
|
||||
@@ -49,6 +51,8 @@ pub struct ForwardAuthRt {
|
||||
pub upstream: UpstreamRt,
|
||||
pub path_and_query: String,
|
||||
pub copy_headers: Vec<HeaderName>,
|
||||
/// Removed from every client request on a forward-auth host before anything else.
|
||||
pub strip_headers: Vec<HeaderName>,
|
||||
}
|
||||
|
||||
pub struct Runtime {
|
||||
@@ -97,19 +101,25 @@ pub fn read_config(path: &Path) -> Result<EdgeConfig, EdgeError> {
|
||||
}
|
||||
|
||||
fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||
let err = |reason: String| EdgeError::Upstream {
|
||||
let err = |reason: &str| EdgeError::Upstream {
|
||||
address: u.address.clone(),
|
||||
reason,
|
||||
reason: reason.to_owned(),
|
||||
};
|
||||
// Resolved once at startup; Pingora peers need a socket address.
|
||||
let addr = u
|
||||
let (host, port) = u
|
||||
.address
|
||||
.to_socket_addrs()
|
||||
.map_err(|e| err(format!("cannot resolve: {e}")))?
|
||||
.next()
|
||||
.ok_or_else(|| err("resolves to no address".into()))?;
|
||||
.rsplit_once(':')
|
||||
.ok_or_else(|| err("expected host:port"))?;
|
||||
let port: u16 = port.parse().map_err(|_| err("bad port"))?;
|
||||
let host = host
|
||||
.strip_prefix('[')
|
||||
.and_then(|h| h.strip_suffix(']'))
|
||||
.unwrap_or(host);
|
||||
if host.is_empty() {
|
||||
return Err(err("empty host"));
|
||||
}
|
||||
Ok(UpstreamRt {
|
||||
addr,
|
||||
host: host.to_owned(),
|
||||
port,
|
||||
authority: u.address.clone(),
|
||||
tls: u.tls,
|
||||
sni: u.sni.clone(),
|
||||
@@ -117,6 +127,26 @@ fn upstream(u: &EdgeUpstream) -> Result<UpstreamRt, EdgeError> {
|
||||
})
|
||||
}
|
||||
|
||||
impl UpstreamRt {
|
||||
/// Addresses to try, in resolver order. Names are resolved at connect time (like Caddy's
|
||||
/// dialer), so DNS changes and unresolvable names only affect requests, not startup.
|
||||
pub async fn resolve(&self) -> std::io::Result<Vec<SocketAddr>> {
|
||||
if let Ok(ip) = self.host.parse::<std::net::IpAddr>() {
|
||||
return Ok(vec![SocketAddr::new(ip, self.port)]);
|
||||
}
|
||||
let addrs: Vec<SocketAddr> = tokio::net::lookup_host((self.host.as_str(), self.port))
|
||||
.await?
|
||||
.collect();
|
||||
if addrs.is_empty() {
|
||||
return Err(std::io::Error::new(
|
||||
std::io::ErrorKind::NotFound,
|
||||
"name resolves to no address",
|
||||
));
|
||||
}
|
||||
Ok(addrs)
|
||||
}
|
||||
}
|
||||
|
||||
fn header_name(name: &str) -> Result<HeaderName, EdgeError> {
|
||||
HeaderName::from_bytes(name.as_bytes()).map_err(|_| EdgeError::Header {
|
||||
name: name.to_owned(),
|
||||
@@ -225,6 +255,11 @@ pub fn build(cfg: EdgeConfig, credentials_dir: Option<&Path>) -> Result<Runtime,
|
||||
.iter()
|
||||
.map(|h| header_name(h))
|
||||
.collect::<Result<_, _>>()?,
|
||||
strip_headers: fa
|
||||
.strip_headers
|
||||
.iter()
|
||||
.map(|h| header_name(h))
|
||||
.collect::<Result<_, _>>()?,
|
||||
}),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user