Skip to main content

rws_proxy/proxy/
mod.rs

1//! Reverse proxy middleware with round-robin load balancing.
2//!
3//! `ReverseProxy` implements [`Middleware`] — wrap any application with it and
4//! all matching requests are forwarded to one of the configured backends over
5//! plain HTTP/1.1.  Failed backends are skipped and the next one is tried
6//! before returning `502 Bad Gateway`.
7//!
8//! # Example
9//!
10//! ```rust,no_run
11//! # extern crate rws_proxy as rust_web_server;
12//! use rust_web_server::app::App;
13//! use rust_web_server::core::New;
14//! use rust_web_server::proxy::{LoadBalancing, ReverseProxy};
15//!
16//! // Proxy every request across two backends in round-robin order.
17//! let app = App::new()
18//!     .wrap(ReverseProxy::new(["http://backend-1:8080", "http://backend-2:8080"])
19//!         .strategy(LoadBalancing::RoundRobin));
20//!
21//! // Only proxy /api/* requests; everything else is handled locally.
22//! let app2 = App::new()
23//!     .wrap(ReverseProxy::new(["http://api-service:3000"])
24//!         .path_prefix("/api"));
25//! ```
26
27pub mod pool;
28pub mod status;
29#[cfg(feature = "http2")]
30#[doc(hidden)]
31pub mod async_upstream;
32#[cfg(not(target_arch = "wasm32"))]
33pub mod mirror;
34/// Upgraded connections (WebSocket) relayed to a backend (moved from the
35/// Gateway API controller in 18.21.0; config proxy routes use it too).
36#[cfg(not(target_arch = "wasm32"))]
37#[doc(hidden)]
38pub mod upgrade;
39#[cfg(feature = "http2")]
40#[doc(hidden)]
41pub mod h2_upstream;
42#[cfg(feature = "http3")]
43#[doc(hidden)]
44pub mod h3_upstream;
45#[cfg(feature = "http2")]
46pub mod grpc_web;
47#[cfg(feature = "http2")]
48pub use grpc_web::GrpcWebLayer;
49
50#[cfg(test)]
51mod tests;
52
53use std::io::{Read, Write};
54use crate::ext::decimal::Decimal;
55use std::net::{TcpStream, ToSocketAddrs};
56use std::sync::atomic::{AtomicUsize, Ordering};
57use std::sync::Arc;
58use std::time::Duration;
59
60pub use pool::{ConnPool, Pool};
61
62use crate::application::Application;
63use crate::middleware::Middleware;
64use crate::request::Request;
65use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
66use crate::server::ConnectionInfo;
67
68// Hop-by-hop headers that must not be forwarded (RFC 9110 §7.6.1), plus
69// `proxy-connection` (legacy clients). Headers named in `Connection` are
70// dropped too (`connection_listed`).
71const HOP_BY_HOP: &[&str] = &[
72    "connection",
73    "keep-alive",
74    "proxy-authenticate",
75    "proxy-authorization",
76    "proxy-connection",
77    "te",
78    "trailer",
79    "transfer-encoding",
80    "upgrade",
81];
82
83/// Load balancing strategy used by [`ReverseProxy`].
84pub enum LoadBalancing {
85    /// Distribute requests across backends in a cyclic order.
86    RoundRobin,
87}
88
89/// Reverse proxy middleware.
90///
91/// Forwards incoming requests to one of the configured backends over HTTP/1.1.
92/// On connection failure the next backend in the list is tried; when all
93/// backends have failed the middleware returns `502 Bad Gateway`.
94///
95/// Hop-by-hop headers are stripped before forwarding.  `X-Forwarded-For` and
96/// `Via` are added to every forwarded request.
97///
98/// Idle connections are pooled and reused across requests (up to
99/// 64 idle per backend, 60-second timeout).
100/// This eliminates per-request TCP handshake overhead and ephemeral-port
101/// exhaustion.  Use [`ReverseProxy::with_pool`] to share a pool across
102/// multiple proxy instances or to tune pool parameters.
103pub struct ReverseProxy {
104    backends: Vec<Backend>,
105    path_prefix: Option<String>,
106    connect_timeout: Duration,
107    read_timeout: Duration,
108    counter: AtomicUsize,
109    pool: Arc<ConnPool>,
110    breaker: Option<Arc<dyn crate::circuit_breaker::Breaker>>,
111    trust: Option<Arc<UpstreamTls>>,
112    /// What `trust` was built from, so each TLS option adds to the others.
113    tls_ca: Option<String>,
114    tls_client: Option<(String, String)>,
115}
116
117impl ReverseProxy {
118    /// Create a proxy that distributes requests across `backends` in
119    /// round-robin order.  Each entry must be `"http://host:port"` or
120    /// `"host:port"` (port defaults to 80).
121    pub fn new<I, S>(backends: I) -> Self
122    where
123        I: IntoIterator<Item = S>,
124        S: AsRef<str>,
125    {
126        Self {
127            backends: backends
128                .into_iter()
129                .filter_map(|u| Backend::parse(u.as_ref()))
130                .collect(),
131            path_prefix: None,
132            connect_timeout: Duration::from_secs(5),
133            read_timeout: Duration::from_secs(30),
134            counter: AtomicUsize::new(0),
135            pool: Arc::new(ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60))),
136            breaker: None,
137            trust: None,
138            tls_ca: None,
139            tls_client: None,
140        }
141    }
142
143    /// Wire a [`crate::circuit_breaker::CircuitBreaker`] or
144    /// [`crate::circuit_breaker::RedisCircuitBreaker`] into this proxy:
145    /// before dialing a backend, its breaker state is checked (an `Open`
146    /// backend is skipped with no TCP attempt, exactly like a caller
147    /// manually checking `is_available` around each proxied call); after a
148    /// dial, `record_success`/`record_failure` is called automatically.
149    /// No breaker is wired by default — existing `ReverseProxy` callers see
150    /// no behavior change unless they opt in here.
151    ///
152    /// ```rust,no_run
153    /// # extern crate rws_proxy as rust_web_server;
154    /// use std::sync::Arc;
155    /// use rust_web_server::circuit_breaker::global as global_breaker;
156    /// use rust_web_server::proxy::ReverseProxy;
157    ///
158    /// let proxy = ReverseProxy::new(["http://backend-1:8080", "http://backend-2:8080"])
159    ///     .with_circuit_breaker(Arc::new(global_breaker()));
160    /// ```
161    pub fn with_circuit_breaker(mut self, breaker: Arc<dyn crate::circuit_breaker::Breaker>) -> Self {
162        self.breaker = Some(breaker);
163        self
164    }
165
166    /// Only proxy requests whose URI starts with `prefix`.
167    ///
168    /// Other requests are passed through to the next layer in the middleware
169    /// chain (or the inner application).
170    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
171        self.path_prefix = Some(prefix.into());
172        self
173    }
174
175    /// Override the load balancing strategy (currently only `RoundRobin`).
176    pub fn strategy(self, _strategy: LoadBalancing) -> Self {
177        self
178    }
179
180    /// Override the TCP connect timeout (default: 5 000 ms).
181    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
182        self.connect_timeout = Duration::from_millis(ms);
183        self
184    }
185
186    /// Override the response read timeout (default: 30 000 ms).
187    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
188        self.read_timeout = Duration::from_millis(ms);
189        self
190    }
191
192    /// Attach a shared connection pool.
193    ///
194    /// Useful for sharing one pool across multiple `ReverseProxy` instances
195    /// or for tuning pool parameters (capacity, idle timeout).
196    pub fn with_pool(mut self, pool: Arc<ConnPool>) -> Self {
197        self.pool = pool;
198        self
199    }
200
201    /// Trust the CA certificates in the PEM file `path` for `https://`
202    /// backends, **instead of** the public WebPKI roots — for internal
203    /// services behind a private CA or a self-signed certificate.
204    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
205        self.tls_ca = Some(path.to_string());
206        self.rebuild_trust()?;
207        Ok(self)
208    }
209
210    /// Present the client certificate in the PEM file `cert` (with its
211    /// private key in `key`) to `https://` backends that require one —
212    /// mutual TLS to the upstream. Since 18.3.0.
213    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
214        self.tls_client = Some((cert.to_string(), key.to_string()));
215        self.rebuild_trust()?;
216        Ok(self)
217    }
218
219    fn rebuild_trust(&mut self) -> Result<(), String> {
220        let client = self.tls_client.as_ref().map(|(c, k)| (c.as_str(), k.as_str()));
221        self.trust = Some(Arc::new(UpstreamTls::new(self.tls_ca.as_deref(), client)?));
222        Ok(())
223    }
224
225    /// Set the maximum number of idle connections per backend (default: 64).
226    pub fn max_idle_conns(mut self, n: usize) -> Self {
227        self.pool = Arc::new(ConnPool::new(n, Duration::from_secs(60)));
228        self
229    }
230
231    fn proxy(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
232        if self.backends.is_empty() {
233            return Err("no backends configured".to_string());
234        }
235        let n = self.backends.len();
236        let start = self.counter.fetch_add(1, Ordering::Relaxed);
237        let mut last_err = "all backends failed".to_string();
238        for attempt in 0..n {
239            let idx = (start + attempt) % n;
240            let backend = &self.backends[idx];
241            let key = format!("{}:{}", backend.host, backend.port);
242
243            if let Some(breaker) = &self.breaker {
244                if !breaker.is_available(&key) {
245                    last_err = format!("circuit open for {}", key);
246                    continue;
247                }
248            }
249
250            match self.try_backend(request, connection, backend) {
251                Ok(resp) => {
252                    if let Some(breaker) = &self.breaker {
253                        breaker.record_success(&key);
254                    }
255                    return Ok(resp);
256                }
257                Err(e) => {
258                    if let Some(breaker) = &self.breaker {
259                        breaker.record_failure(&key);
260                    }
261                    last_err = e;
262                }
263            }
264        }
265        Err(last_err)
266    }
267
268    fn try_backend(
269        &self,
270        request: &Request,
271        connection: &ConnectionInfo,
272        backend: &Backend,
273    ) -> Result<Response, String> {
274        forward_upstream_trusting(
275            &self.pool,
276            request,
277            crate::proxy::Peer::of(connection),
278            &backend.host,
279            backend.port,
280            backend.tls,
281            self.trust.as_deref(),
282            self.connect_timeout,
283            self.read_timeout,
284        )
285    }
286}
287
288impl Middleware for ReverseProxy {
289    fn handle(
290        &self,
291        request: &Request,
292        connection: &ConnectionInfo,
293        next: &dyn Application,
294    ) -> Result<Response, String> {
295        if let Some(prefix) = &self.path_prefix {
296            if !request.request_uri.starts_with(prefix.as_str()) {
297                return next.execute(request, connection);
298            }
299        }
300        match self.proxy(request, connection) {
301            Ok(mut resp) => {
302                status::received(&mut resp, None);
303                Ok(resp)
304            }
305            Err(e) => {
306                let mut resp = bad_gateway();
307                status::failed_with(&mut resp, &e, None);
308                Ok(resp)
309            }
310        }
311    }
312}
313
314// ── helpers ───────────────────────────────────────────────────────────────────
315
316/// The client as the forwarders need it: its address for `X-Forwarded-For`
317/// and whether it connected over TLS, for `X-Forwarded-Proto`.
318#[derive(Clone, Copy, Debug)]
319#[doc(hidden)]
320pub struct Peer<'a> {
321    pub ip: &'a str,
322    pub tls: bool,
323}
324
325impl<'a> Peer<'a> {
326    #[doc(hidden)]
327    pub fn of(connection: &'a ConnectionInfo) -> Self {
328        Peer { ip: &connection.client.ip, tls: connection.tls }
329    }
330
331    /// A plain-HTTP client at `ip` (tests and callers without a connection).
332    #[doc(hidden)]
333    pub fn plain(ip: &'a str) -> Self {
334        Peer { ip, tls: false }
335    }
336
337    #[doc(hidden)]
338    pub fn proto(&self) -> &'static str {
339        if self.tls { "https" } else { "http" }
340    }
341}
342
343/// The headers a client sets to describe earlier hops.
344const FORWARDING_HEADERS: [&str; 4] = ["x-forwarded-for", "x-forwarded-proto", "x-forwarded-host", "forwarded"];
345
346/// `request` as the proxy may pass it on: from a peer outside
347/// `trusted_proxies` its `X-Forwarded-For/Proto/Host` and `Forwarded` are
348/// dropped (rws sets its own), so a client can't claim `https` or another
349/// host (18.24.0). Borrowed when nothing needs dropping.
350#[doc(hidden)]
351pub fn from_peer<'a>(request: &'a Request, client: Peer<'_>) -> std::borrow::Cow<'a, Request> {
352    let has = request.headers.iter().any(|h| FORWARDING_HEADERS.iter().any(|n| h.name.eq_ignore_ascii_case(n)));
353    if !has || crate::server_config::ServerConfig::current().trusted_proxies.trusts(client.ip) {
354        return std::borrow::Cow::Borrowed(request);
355    }
356    let mut owned = request.clone();
357    owned.headers.retain(|h| !FORWARDING_HEADERS.iter().any(|n| h.name.eq_ignore_ascii_case(n)));
358    std::borrow::Cow::Owned(owned)
359}
360
361/// The `Forwarded` value for this hop (RFC 7239, 18.20.0): the request's
362/// own `Forwarded` (from proxies before this one) extended with
363/// `for=<client>;proto=<http|https>;host=<Host>`; `None` when
364/// `forwarded_header = "off"`.
365#[doc(hidden)]
366pub fn forwarded_value(request: &Request, client: Peer<'_>) -> Option<String> {
367    if !crate::server_config::ServerConfig::current().forwarded_header {
368        return None;
369    }
370    let mut element = format!("for={};proto={}", forwarded_node(client.ip), client.proto());
371    if let Some(host) = request.header(crate::header::Header::_HOST).map(|h| h.value.as_ref()) {
372        push_forwarded_host(&mut element, host);
373    }
374    let prior = request.headers.iter().filter(|h| h.name.eq_ignore_ascii_case("forwarded")).map(|h| h.value.trim()).filter(|v| !v.is_empty() && !v.bytes().any(|b| b < 0x20)).collect::<Vec<_>>();
375    if prior.is_empty() {
376        // A trusted proxy that sent only X-Forwarded-* (most do): its hops
377        // become Forwarded elements first, the client's with the proto and
378        // host it reported (RFC 7239 §7.4, since 18.27.0), so the chain says
379        // proto=https like X-Forwarded-Proto instead of just this hop's http.
380        if let Some(earlier) = forwarded_from_x_forwarded(request, client) {
381            return Some(format!("{earlier}, {element}"));
382        }
383    }
384    Some(if prior.is_empty() { element } else { format!("{}, {element}", prior.join(", ")) })
385}
386
387/// An RFC 7239 node for an address: IPv4 bare, IPv6 quoted in brackets,
388/// `unknown` for anything else.
389fn forwarded_node(ip: &str) -> String {
390    let ip = ip.trim();
391    let parsed = ip.parse::<std::net::IpAddr>().ok().or_else(|| ip.parse::<std::net::SocketAddr>().ok().map(|a| a.ip()));
392    match parsed {
393        Some(std::net::IpAddr::V4(v4)) => v4.to_string(),
394        Some(std::net::IpAddr::V6(v6)) => match v6.to_ipv4_mapped() {
395            Some(v4) => v4.to_string(),
396            None => format!("\"[{v6}]\""),
397        },
398        None => "unknown".to_string(),
399    }
400}
401
402fn push_forwarded_host(element: &mut String, host: &str) {
403    if host.is_empty() || !host.bytes().all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\') {
404        return;
405    }
406    if host.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b)) {
407        element.push_str(&format!(";host={host}"));
408    } else {
409        element.push_str(&format!(";host=\"{host}\""));
410    }
411}
412
413/// `X-Forwarded-For` hops from a trusted peer as `Forwarded` elements, the
414/// first with `X-Forwarded-Proto` and `-Host`; `None` without one.
415fn forwarded_from_x_forwarded(request: &Request, client: Peer<'_>) -> Option<String> {
416    if !crate::server_config::ServerConfig::current().trusted_proxies.trusts(client.ip) {
417        return None;
418    }
419    let hops: Vec<&str> = request.headers.iter()
420        .filter(|h| h.name.eq_ignore_ascii_case("x-forwarded-for"))
421        .flat_map(|h| h.value.split(','))
422        .map(str::trim)
423        .filter(|h| !h.is_empty())
424        .collect();
425    if hops.is_empty() {
426        return None;
427    }
428    let mut elements = Vec::with_capacity(hops.len());
429    for (i, hop) in hops.iter().enumerate() {
430        let mut element = format!("for={}", forwarded_node(hop));
431        if i == 0 {
432            if let Some(proto) = request.header("X-Forwarded-Proto").map(|h| h.value.trim().to_ascii_lowercase()).filter(|p| p == "http" || p == "https") {
433                element.push_str(&format!(";proto={proto}"));
434            }
435            if let Some(host) = request.header("X-Forwarded-Host").map(|h| h.value.trim().to_string()) {
436                push_forwarded_host(&mut element, &host);
437            }
438        }
439        elements.push(element);
440    }
441    Some(elements.join(", "))
442}
443
444#[doc(hidden)]
445pub fn build_request(
446    request: &Request,
447    backend_host: &str,
448    client: Peer<'_>,
449    keep_alive: bool,
450) -> Vec<u8> {
451    let request = &*from_peer(request, client);
452    // One buffer, sized up front and filled with extend_from_slice — no
453    // write!/format machinery, no lower-cased copy of each header name.
454    // `Content-Length` is regenerated from the (possibly de-chunked) body and
455    // `X-Forwarded-For` is extended below, so the client's copies are dropped:
456    // two `Content-Length` lines are a protocol error and a desync risk.
457    let connection = request.header(crate::header::Header::_CONNECTION).map(|h| h.value.as_ref());
458    // Inside a traced request the current span's `traceparent` (and the
459    // request's `baggage`) replace the client's.
460    #[cfg(not(target_arch = "wasm32"))]
461    let trace = crate::otel::propagation_headers();
462    #[cfg(target_arch = "wasm32")]
463    let trace: Option<(String, Option<String>)> = None;
464    let forwarded_header = forwarded_value(request, client);
465    let forwarded = |h: &&crate::header::Header| {
466        // An empty name would be sent as a malformed ": value" line.
467        !h.name.is_empty()
468            && !is_hop_by_hop_or_host(&h.name)
469            && !h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_LENGTH)
470            && !h.name.eq_ignore_ascii_case("X-Forwarded-For")
471            && !(forwarded_header.is_some() && h.name.eq_ignore_ascii_case("Forwarded"))
472            && !connection.is_some_and(|c| connection_listed(c, &h.name))
473            && !(trace.is_some() && (h.name.eq_ignore_ascii_case("traceparent") || h.name.eq_ignore_ascii_case("baggage")))
474    };
475    let prior_xff = request.header("X-Forwarded-For").map(|h| h.value.as_ref()).filter(|v| !v.trim().is_empty());
476    // The Host the client asked for, unless an outer proxy already said
477    // (its X-Forwarded-Host passes through like any header).
478    // http or https, as the client connected, unless an outer proxy said.
479    let forwarded_proto = request.header("X-Forwarded-Proto").is_none().then(|| client.proto());
480    let forwarded_host = match request.header("X-Forwarded-Host") {
481        Some(_) => None,
482        None => request.header(crate::header::Header::_HOST).map(|h| h.value.as_ref()).filter(|v| !v.is_empty()),
483    };
484    let body_len = Decimal::new(request.body.len() as u128);
485    let capacity = request.method.len() + request.request_uri.len() + backend_host.len() + 25
486        + request.headers.iter().filter(forwarded).map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
487        + client.ip.len() + 19 + prior_xff.map_or(0, |v| v.len() + 2)
488        + forwarded_host.map_or(0, |v| v.len() + 20)
489        + forwarded_proto.map_or(0, |v| v.len() + 21)
490        + forwarded_header.as_ref().map_or(0, |v| v.len() + 13)
491        + trace.as_ref().map_or(0, |(t, b)| t.len() + 15 + b.as_ref().map_or(0, |b| b.len() + 11))
492        + 13
493        + 24
494        + if request.body.is_empty() { 0 } else { body_len.as_str().len() + 18 }
495        + 2
496        + request.body.len();
497    let mut out: Vec<u8> = Vec::with_capacity(capacity);
498    for part in [request.method.as_str(), " ", request.request_uri.as_str(), " HTTP/1.1\r\nHost: ", backend_host, "\r\n"] {
499        out.extend_from_slice(part.as_bytes());
500    }
501    for h in request.headers.iter().filter(forwarded) {
502        for part in [h.name.as_ref(), ": ", h.value.as_ref(), "\r\n"] {
503            out.extend_from_slice(part.as_bytes());
504        }
505    }
506    out.extend_from_slice(b"X-Forwarded-For: ");
507    if let Some(prior) = prior_xff {
508        out.extend_from_slice(prior.as_bytes());
509        out.extend_from_slice(b", ");
510    }
511    for part in [client.ip, "\r\n", "Via: 1.1 rws\r\n"] {
512        out.extend_from_slice(part.as_bytes());
513    }
514    if let Some(host) = forwarded_host {
515        for part in ["X-Forwarded-Host: ", host, "\r\n"] {
516            out.extend_from_slice(part.as_bytes());
517        }
518    }
519    if let Some(proto) = forwarded_proto {
520        for part in ["X-Forwarded-Proto: ", proto, "\r\n"] {
521            out.extend_from_slice(part.as_bytes());
522        }
523    }
524    if let Some(value) = &forwarded_header {
525        for part in ["Forwarded: ", value.as_str(), "\r\n"] {
526            out.extend_from_slice(part.as_bytes());
527        }
528    }
529    if let Some((traceparent, baggage)) = &trace {
530        for part in ["traceparent: ", traceparent, "\r\n"] {
531            out.extend_from_slice(part.as_bytes());
532        }
533        if let Some(baggage) = baggage {
534            for part in ["baggage: ", baggage, "\r\n"] {
535                out.extend_from_slice(part.as_bytes());
536            }
537        }
538    }
539    if keep_alive {
540        out.extend_from_slice(b"Connection: keep-alive\r\n");
541    } else {
542        out.extend_from_slice(b"Connection: close\r\n");
543    }
544    if !request.body.is_empty() {
545        out.extend_from_slice(b"Content-Length: ");
546        out.extend_from_slice(body_len.as_str().as_bytes());
547        out.extend_from_slice(b"\r\n");
548    }
549    out.extend_from_slice(b"\r\n");
550    out.extend_from_slice(&request.body);
551    out
552}
553
554/// Whether a request header is dropped on the way upstream: hop-by-hop
555/// headers and `Host` (rws sends its own). Matches `to_lowercase()` against
556/// the lower-case list — Unicode lower-casing, so a non-ASCII name (where
557/// e.g. the Kelvin sign lower-cases to `k`) still takes that path.
558fn is_hop_by_hop_or_host(name: &str) -> bool {
559    if name.is_ascii() {
560        name.eq_ignore_ascii_case("host") || HOP_BY_HOP.iter().any(|h| name.eq_ignore_ascii_case(h))
561    } else {
562        let lower = name.to_lowercase();
563        lower == "host" || HOP_BY_HOP.contains(&lower.as_str())
564    }
565}
566
567/// Whether `name` is one of the comma-separated tokens of a `Connection`
568/// header value — those headers are hop-by-hop for this connection only.
569fn connection_listed(connection: &str, name: &str) -> bool {
570    connection.split(',').any(|token| token.trim().eq_ignore_ascii_case(name))
571}
572
573/// Decode HTTP/1.1 chunked transfer-encoding from `stream`.
574///
575/// `buf[header_end..]` may already contain some body bytes that arrived in
576/// the same read as the headers.  Returns the fully decoded body.
577fn decode_chunked<S: Read>(
578    stream: &mut S,
579    buf: &[u8],
580    header_end: usize,
581    tmp: &mut [u8],
582) -> Result<Vec<u8>, String> {
583    // Seed `raw` with any body bytes already buffered alongside the headers.
584    let mut raw: Vec<u8> = buf[header_end..].to_vec();
585    let mut decoded: Vec<u8> = Vec::new();
586
587    loop {
588        // Wait until we have at least one complete chunk-size line (ends with \r\n).
589        let crlf = loop {
590            if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
591                break p;
592            }
593            let n = stream.read(tmp).map_err(|e| e.to_string())?;
594            if n == 0 {
595                return Err("chunked: premature EOF reading chunk size".to_string());
596            }
597            raw.extend_from_slice(&tmp[..n]);
598        };
599
600        // Chunk size is hex, optionally followed by chunk-extensions (";…").
601        let size_line = std::str::from_utf8(&raw[..crlf])
602            .map_err(|_| "chunked: non-UTF-8 chunk size line".to_string())?;
603        let size_str = size_line.split(';').next().unwrap_or("").trim();
604        let chunk_size = usize::from_str_radix(size_str, 16)
605            .map_err(|_| format!("chunked: invalid chunk size '{}'", size_str))?;
606        raw.drain(..crlf + 2); // consume "<size>\r\n"
607
608        if chunk_size == 0 {
609            // Last chunk: skip trailer fields up to the empty line that ends
610            // the message. Leaving any of it unread would corrupt the next
611            // response on a pooled connection.
612            loop {
613                let line_end = loop {
614                    if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
615                        break p;
616                    }
617                    let n = stream.read(tmp).map_err(|e| e.to_string())?;
618                    if n == 0 {
619                        return Err("chunked: premature EOF in trailer".to_string());
620                    }
621                    raw.extend_from_slice(&tmp[..n]);
622                };
623                raw.drain(..line_end + 2);
624                if line_end == 0 {
625                    break;
626                }
627            }
628            break;
629        }
630
631        // Read chunk data + trailing CRLF.
632        while raw.len() < chunk_size + 2 {
633            let n = stream.read(tmp).map_err(|e| e.to_string())?;
634            if n == 0 {
635                return Err("chunked: premature EOF reading chunk body".to_string());
636            }
637            raw.extend_from_slice(&tmp[..n]);
638        }
639        decoded.extend_from_slice(&raw[..chunk_size]);
640        raw.drain(..chunk_size + 2); // consume "<data>\r\n"
641    }
642
643    Ok(decoded)
644}
645
646/// Rewrite `buf` in-place: strip `Transfer-Encoding`, add `Content-Length`,
647/// replace the old (undecoded) body with `decoded`.
648fn rewrite_as_content_length(buf: &mut Vec<u8>, header_end: usize, decoded: &[u8]) {
649    let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_string();
650    buf.clear();
651    for line in header_str.lines() {
652        if line.to_ascii_lowercase().starts_with("transfer-encoding:") || line.is_empty() {
653            continue;
654        }
655        buf.extend_from_slice(line.as_bytes());
656        buf.extend_from_slice(b"\r\n");
657    }
658    let _ = write!(buf, "Content-Length: {}\r\n\r\n", decoded.len());
659    buf.extend_from_slice(decoded);
660}
661
662// Lives in rws-http (`response`): the disk cache parses stored responses with it too.
663pub(crate) use crate::response::REGENERATED_OR_HOP_BY_HOP;
664
665/// Make a buffered upstream response safe to re-serialize. The body is
666/// already held in `content_range_list`, from which `Response::generate`
667/// (and the HTTP/2 / HTTP/3 writers) emit `Content-Type` and
668/// `Content-Length` themselves, so the upstream's own copies would be
669/// duplicated — and a duplicate `content-length` is a protocol error that
670/// HTTP/2 clients reject outright. The upstream's `Content-Type` is moved
671/// onto the body instead; the status line is re-emitted as HTTP/1.1
672/// regardless of the backend's version.
673#[cfg_attr(not(feature = "http2"), allow(dead_code))]
674#[doc(hidden)]
675pub fn normalize_upstream_response(mut response: Response) -> Response {
676    response.http_version.clear();
677    response.http_version.push_str(crate::http::VERSION.http_1_1);
678    let has_body = !response.content_range_list.is_empty();
679    if let [range] = response.content_range_list.as_mut_slice() {
680        if let Some(h) = response
681            .headers
682            .iter()
683            .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
684        {
685            range.content_type.clear();
686            range.content_type.push_str(&h.value);
687        }
688    }
689    // Compared in place (the list is lower-case ASCII), not lower-cased
690    // into a new String per header.
691    response.headers.retain(|h| {
692        if h.name.eq_ignore_ascii_case("content-type") {
693            // Keep it only when there's no body to carry it (e.g. HEAD, 304).
694            return !has_body;
695        }
696        !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
697    });
698    response
699}
700
701#[doc(hidden)]
702pub fn bad_gateway() -> Response {
703    crate::error::problem(STATUS_CODE_REASON_PHRASE.n502_bad_gateway, "")
704}
705
706// ── Streaming proxy helpers ───────────────────────────────────────────────────
707
708/// Responses larger than this threshold are streamed instead of buffered.
709const STREAM_THRESHOLD: usize = 1024 * 1024; // 1 MB
710
711/// A `Read` implementation that drains a prefix buffer before reading from the
712/// inner stream. Used to replay body bytes that arrived with the HTTP headers.
713#[doc(hidden)]
714pub struct ConcatReader<R: Read + Send> {
715    prefix: Vec<u8>,
716    prefix_pos: usize,
717    inner: R,
718}
719
720impl<R: Read + Send> ConcatReader<R> {
721    fn new(prefix: Vec<u8>, inner: R) -> Self {
722        ConcatReader { prefix, prefix_pos: 0, inner }
723    }
724}
725
726impl<R: Read + Send> Read for ConcatReader<R> {
727    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
728        if self.prefix_pos < self.prefix.len() {
729            let avail = &self.prefix[self.prefix_pos..];
730            let n = buf.len().min(avail.len());
731            buf[..n].copy_from_slice(&avail[..n]);
732            self.prefix_pos += n;
733            return Ok(n);
734        }
735        self.inner.read(buf)
736    }
737}
738
739
740/// Idle backend connections kept per `host:port`. 64 matches common nginx
741/// `keepalive` settings and the benchmark's concurrency; fewer meant most
742/// requests at 64-way concurrency still paid a TCP connect.
743#[doc(hidden)]
744pub const POOL_MAX_IDLE: usize = 64;
745
746/// The process-wide backend connection pool used by config-driven proxy
747/// routes (`proxy_config::DynamicProxy`), keyed by `host:port`.
748#[doc(hidden)]
749pub fn shared_pool() -> &'static ConnPool {
750    static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
751    POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
752}
753
754/// A backend connection the pooled forwarder drives: plain TCP, or TLS
755/// over TCP for `https://` backends.
756#[doc(hidden)]
757pub trait UpstreamIo: Read + Write + Send + 'static {
758    fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
759}
760
761impl UpstreamIo for TcpStream {
762    fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
763        self.set_read_timeout(Some(read))?;
764        self.set_write_timeout(Some(write))
765    }
766}
767
768#[cfg(any(feature = "http-client", feature = "http2"))]
769#[doc(hidden)]
770pub type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
771
772#[cfg(any(feature = "http-client", feature = "http2"))]
773impl UpstreamIo for TlsStream {
774    fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
775        self.sock.set_io_timeouts(read, write)
776    }
777}
778
779/// Forward `request` to an HTTP or HTTPS backend at `host:port`, over a
780/// pooled keep-alive connection either way: plain backends use `plain_pool`,
781/// TLS backends the process-wide TLS pool (one handshake per connection, not
782/// per request). The single entry point for `ReverseProxy`, config-driven
783/// routes, `canary` and `ingress`.
784#[doc(hidden)]
785pub fn forward_upstream(
786    plain_pool: &ConnPool,
787    request: &Request,
788    client: Peer<'_>,
789    host: &str,
790    port: u16,
791    tls: bool,
792    connect_timeout: Duration,
793    read_timeout: Duration,
794) -> Result<Response, String> {
795    forward_upstream_trusting(plain_pool, request, client, host, port, tls, None, connect_timeout, read_timeout)
796}
797
798/// [`forward_upstream`] with the trust settings of one upstream: `trust`
799/// replaces the WebPKI roots for TLS backends (a private CA).
800#[allow(clippy::too_many_arguments)]
801#[doc(hidden)]
802pub fn forward_upstream_trusting(
803    plain_pool: &ConnPool,
804    request: &Request,
805    client: Peer<'_>,
806    host: &str,
807    port: u16,
808    tls: bool,
809    trust: Option<&UpstreamTls>,
810    connect_timeout: Duration,
811    read_timeout: Duration,
812) -> Result<Response, String> {
813    forward_upstream_as(plain_pool, request, client, host, port, host, tls, trust, connect_timeout, read_timeout)
814}
815
816/// [`forward_upstream_trusting`], sending `host_header` as the `Host` instead
817/// of the backend's address (a config route's `preserve_host` /
818/// `upstream_host`).
819#[allow(clippy::too_many_arguments)]
820#[doc(hidden)]
821pub fn forward_upstream_as(
822    plain_pool: &ConnPool,
823    request: &Request,
824    client: Peer<'_>,
825    host: &str,
826    port: u16,
827    host_header: &str,
828    tls: bool,
829    trust: Option<&UpstreamTls>,
830    connect_timeout: Duration,
831    read_timeout: Duration,
832) -> Result<Response, String> {
833    // Inside a traced request: a client span per forward, current while the
834    // request is built, so the upstream's `traceparent` names it.
835    #[cfg(not(target_arch = "wasm32"))]
836    let span = crate::otel::outbound_span(&request.method);
837    #[cfg(not(target_arch = "wasm32"))]
838    if let Some(span) = &span {
839        let scheme = if tls { "https" } else { "http" };
840        let path = request.request_uri.as_str();
841        for (key, value) in crate::otel::http_client_attributes(&request.method, &format!("{scheme}://{host}:{port}{path}")) {
842            span.set_attribute(key, value);
843        }
844    }
845    let result = forward_upstream_untraced(plain_pool, request, client, host, port, host_header, tls, trust, connect_timeout, read_timeout);
846    #[cfg(not(target_arch = "wasm32"))]
847    if let Some(span) = &span {
848        span.finish_http_client(result.as_ref().map(|r| r.status_code as u16).map_err(String::as_str));
849    }
850    result
851}
852
853#[allow(clippy::too_many_arguments)]
854fn forward_upstream_untraced(
855    plain_pool: &ConnPool,
856    request: &Request,
857    client: Peer<'_>,
858    host: &str,
859    port: u16,
860    host_header: &str,
861    tls: bool,
862    trust: Option<&UpstreamTls>,
863    connect_timeout: Duration,
864    read_timeout: Duration,
865) -> Result<Response, String> {
866    if tls {
867        #[cfg(any(feature = "http-client", feature = "http2"))]
868        {
869            let (pool, config) = match trust {
870                Some(t) => (t.pool, Arc::clone(&t.config)),
871                None => (shared_tls_pool(), tls_client_config()),
872            };
873            return forward_via(pool, request, client, host, port, host_header, read_timeout, || {
874                connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
875            });
876        }
877        #[cfg(not(any(feature = "http-client", feature = "http2")))]
878        {
879            let _ = trust;
880            return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
881        }
882    }
883    forward_via(plain_pool, request, client, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
884}
885
886/// Trust settings for one upstream's TLS backends: the certificates in a CA
887/// file **instead of** the WebPKI roots — for internal services behind a
888/// private CA or a self-signed certificate (nginx's
889/// `proxy_ssl_trusted_certificate`) — and/or a client certificate rws
890/// presents to backends that require one (`proxy_ssl_certificate`, since
891/// 18.3.0). Connections are pooled per setting, so two upstreams at the same
892/// address with different trust never share one.
893pub struct UpstreamTls {
894    #[cfg(any(feature = "http-client", feature = "http2"))]
895    config: Arc<rustls::ClientConfig>,
896    #[cfg(any(feature = "http-client", feature = "http2"))]
897    pool: &'static Pool<TlsStream>,
898    /// Connections for the non-blocking forwarder, made with `config`.
899    #[cfg(feature = "http2")]
900    async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
901    /// `config` offering HTTP/2 by ALPN, for HTTP/2 and gRPC upstreams.
902    #[cfg(feature = "http2")]
903    h2_config: Arc<rustls::ClientConfig>,
904}
905
906impl UpstreamTls {
907    /// Load the PEM certificates in `path` as the only trusted roots.
908    pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
909        UpstreamTls::new(Some(path), None)
910    }
911
912    /// Trust the PEM certificates in `ca_file` (the WebPKI roots when `None`)
913    /// and, with `client_cert` = `(certificate chain PEM, private key PEM)`,
914    /// present that certificate to backends that ask for one.
915    pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
916        #[cfg(any(feature = "http-client", feature = "http2"))]
917        {
918            use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
919            let roots = match ca_file {
920                Some(path) => {
921                    let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
922                    let certs = CertificateDer::pem_slice_iter(&bytes)
923                        .collect::<Result<Vec<_>, _>>()
924                        .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
925                    if certs.is_empty() {
926                        return Err(format!("no certificates in CA file '{path}'"));
927                    }
928                    let mut roots = rustls::RootCertStore::empty();
929                    for cert in certs {
930                        roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
931                    }
932                    roots
933                }
934                None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
935            };
936            let builder = crate::tls_client_builder().with_root_certificates(roots);
937            let config = match client_cert {
938                None => builder.with_no_client_auth(),
939                Some((cert_path, key_path)) => {
940                    let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
941                    let chain = CertificateDer::pem_slice_iter(&bytes)
942                        .collect::<Result<Vec<_>, _>>()
943                        .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
944                    if chain.is_empty() {
945                        return Err(format!("no certificate in '{cert_path}'"));
946                    }
947                    let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
948                    let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
949                    builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
950                }
951            };
952            let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
953            Ok(UpstreamTls::with_config(config, &label))
954        }
955        #[cfg(not(any(feature = "http-client", feature = "http2")))]
956        {
957            let _ = client_cert;
958            Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
959        }
960    }
961
962    #[cfg(any(feature = "http-client", feature = "http2"))]
963    fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
964        #[cfg(feature = "http2")]
965        let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
966        UpstreamTls {
967            config: Arc::new(config),
968            pool: tls_pool_for_ca(label),
969            #[cfg(feature = "http2")]
970            async_pool: async_tls_pool_for_ca(label),
971            #[cfg(feature = "http2")]
972            h2_config,
973        }
974    }
975
976    /// The client configuration for HTTP/2 upstreams (ALPN `h2`).
977    #[cfg(feature = "http2")]
978    #[doc(hidden)]
979    pub fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
980        &self.h2_config
981    }
982
983    /// Trust nothing: every TLS handshake fails, so the upstream answers 502.
984    /// Used when a configured CA file can't be loaded — failing closed rather
985    /// than falling back to the public roots.
986    #[doc(hidden)]
987    pub fn reject_all(label: &str) -> UpstreamTls {
988        #[cfg(any(feature = "http-client", feature = "http2"))]
989        {
990            let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
991            UpstreamTls::with_config(config, &format!("reject-all:{label}"))
992        }
993        #[cfg(not(any(feature = "http-client", feature = "http2")))]
994        {
995            let _ = label;
996            UpstreamTls {}
997        }
998    }
999
1000    /// How the non-blocking forwarder reaches these backends.
1001    #[cfg(feature = "http2")]
1002    #[doc(hidden)]
1003    pub fn async_tls(&self) -> async_upstream::AsyncTls {
1004        async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
1005    }
1006
1007    /// The client configuration (for health checks).
1008    #[cfg(any(feature = "http-client", feature = "http2"))]
1009    #[doc(hidden)]
1010    pub fn client_config(&self) -> Arc<rustls::ClientConfig> {
1011        Arc::clone(&self.config)
1012    }
1013}
1014
1015/// One non-blocking connection pool per CA file, for the life of the process
1016/// (a reload that keeps the same file keeps its warm connections).
1017#[cfg(feature = "http2")]
1018fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
1019    static POOLS: std::sync::OnceLock<
1020        std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
1021    > = std::sync::OnceLock::new();
1022    let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
1023    pools
1024        .entry(path.to_string())
1025        .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
1026}
1027
1028/// One pool per CA file, for the life of the process.
1029#[cfg(any(feature = "http-client", feature = "http2"))]
1030fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
1031    static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
1032        std::sync::OnceLock::new();
1033    let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
1034    pools
1035        .entry(path.to_string())
1036        .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
1037}
1038
1039/// Forward `request` to `host:port` over plain HTTP/1.1, reusing an idle
1040/// connection from `pool` when there is one and returning the connection to
1041/// `pool` after a complete, reusable response.
1042#[doc(hidden)]
1043pub fn forward_pooled(
1044    pool: &ConnPool,
1045    request: &Request,
1046    client: Peer<'_>,
1047    host: &str,
1048    port: u16,
1049    connect_timeout: Duration,
1050    read_timeout: Duration,
1051) -> Result<Response, String> {
1052    forward_via(pool, request, client, host, port, host, read_timeout, || connect_tcp(host, port, connect_timeout))
1053}
1054
1055/// [`forward_pooled`], sending `host_header` as the `Host` (the client's, for
1056/// a gateway that must preserve it) instead of the backend's address.
1057#[cfg(feature = "gateway-api")]
1058#[allow(clippy::too_many_arguments)]
1059#[doc(hidden)]
1060pub fn forward_pooled_with_host(
1061    pool: &ConnPool,
1062    request: &Request,
1063    client: Peer<'_>,
1064    host: &str,
1065    port: u16,
1066    host_header: &str,
1067    connect_timeout: Duration,
1068    read_timeout: Duration,
1069) -> Result<Response, String> {
1070    forward_via(pool, request, client, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
1071}
1072
1073/// The pooled request/response cycle, for any connection type.
1074///
1075/// A backend may close an idle keep-alive connection at any moment, so a
1076/// pooled connection that fails before *any* response byte arrives is
1077/// retried once on a fresh connection — but only for idempotent methods
1078/// (RFC 9110 §9.2.2): the request may already have reached the backend.
1079#[allow(clippy::too_many_arguments)]
1080fn forward_via<S: UpstreamIo>(
1081    pool: &Pool<S>,
1082    request: &Request,
1083    client: Peer<'_>,
1084    host: &str,
1085    port: u16,
1086    host_header: &str,
1087    read_timeout: Duration,
1088    connect: impl Fn() -> Result<S, String>,
1089) -> Result<Response, String> {
1090    let key = format!("{}:{}", host, port);
1091    if let Some(stream) = pool.acquire(&key) {
1092        match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
1093            Exchange::Done(response) => return Ok(response),
1094            Exchange::NoResponse(_) if is_idempotent(&request.method) => {} // stale: retry fresh
1095            Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
1096        }
1097    }
1098    let stream = connect()?;
1099    match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
1100        Exchange::Done(response) => Ok(response),
1101        Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
1102    }
1103}
1104
1105/// Connect to the first address of `host:port` that accepts. `localhost`
1106/// resolves to `::1` before `127.0.0.1` on many systems; a backend listening
1107/// on IPv4 only must still be reachable by name.
1108fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
1109    let key = format!("{}:{}", host, port);
1110    let addrs: Vec<_> = key
1111        .to_socket_addrs()
1112        .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
1113        .collect();
1114    let mut last_error = format!("no address resolved for {}", key);
1115    for addr in addrs {
1116        match TcpStream::connect_timeout(&addr, connect_timeout) {
1117            Ok(stream) => {
1118                let _ = stream.set_nodelay(true);
1119                return Ok(stream);
1120            }
1121            Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
1122        }
1123    }
1124    Err(last_error)
1125}
1126
1127/// The process-wide pool of TLS connections to `https://` backends.
1128#[cfg(any(feature = "http-client", feature = "http2"))]
1129fn shared_tls_pool() -> &'static Pool<TlsStream> {
1130    static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
1131    POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
1132}
1133
1134/// TLS client settings for backends: the Mozilla root store, no client
1135/// certificate. Built once — parsing the root store per request was a large
1136/// part of the per-request cost of HTTPS upstreams.
1137#[cfg(any(feature = "http-client", feature = "http2"))]
1138#[doc(hidden)]
1139pub fn tls_client_config() -> Arc<rustls::ClientConfig> {
1140    static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
1141    Arc::clone(CONFIG.get_or_init(|| {
1142        let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
1143        Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
1144    }))
1145}
1146
1147#[cfg(any(feature = "http-client", feature = "http2"))]
1148fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
1149    let tcp = connect_tcp(host, port, connect_timeout)?;
1150    let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
1151        .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
1152    let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
1153    Ok(rustls::StreamOwned::new(conn, tcp))
1154}
1155
1156fn is_idempotent(method: &str) -> bool {
1157    matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
1158}
1159
1160enum Exchange {
1161    Done(Response),
1162    /// Failed before any response byte (write error, or closed/errored on the first read).
1163    NoResponse(String),
1164    Failed(String),
1165}
1166
1167/// One request/response on `stream`. A fully read, keep-alive response puts
1168/// the connection back in `pool`; a streamed response keeps it until done.
1169fn exchange<S: UpstreamIo>(
1170    pool: &Pool<S>,
1171    key: &str,
1172    mut stream: S,
1173    request: &Request,
1174    host: &str,
1175    client: Peer<'_>,
1176    read_timeout: Duration,
1177) -> Exchange {
1178    if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
1179        return Exchange::Failed(e.to_string());
1180    }
1181    // keep_alive = true: ask the backend to hold the connection open.
1182    let req_bytes = build_request(request, host, client, true);
1183    if let Err(e) = stream.write_all(&req_bytes) {
1184        return Exchange::NoResponse(format!("write to backend failed: {}", e));
1185    }
1186
1187    let mut tmp = [0u8; 4096];
1188    let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
1189        Ok(head) => head,
1190        Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
1191        Err(HeadError::Partial(e)) => return Exchange::Failed(e),
1192    };
1193    let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
1194
1195    if response_has_no_body(&request.method, &header_lower) {
1196        if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
1197            pool.release(key, stream);
1198        }
1199        return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
1200            Ok(response) => Exchange::Done(response),
1201            Err(e) => Exchange::Failed(e),
1202        };
1203    }
1204
1205    if should_stream_response(&header_lower) {
1206        // Streaming path — pipe bytes straight to the client; the connection
1207        // can't be reused while the body is in flight.
1208        return match parse_status_and_headers(&header_bytes) {
1209            Ok(mut response) => {
1210                response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
1211                Exchange::Done(response)
1212            }
1213            Err(e) => Exchange::Failed(e),
1214        };
1215    }
1216    // Buffered path — read the full body, then return the connection to the pool.
1217    match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
1218        Ok((resp_bytes, reusable)) => {
1219            if reusable {
1220                pool.release(key, stream);
1221            }
1222            match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
1223                Ok(response) => Exchange::Done(response),
1224                Err(e) => Exchange::Failed(e),
1225            }
1226        }
1227        Err(e) => Exchange::Failed(e),
1228    }
1229}
1230
1231/// Read exactly the HTTP response headers (up to and including `\r\n\r\n`).
1232///
1233/// Returns `(header_bytes, body_prefix)` where `body_prefix` contains any
1234/// body bytes that arrived in the same TCP segment as the headers.
1235#[cfg(test)]
1236fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
1237    read_response_head(stream, tmp).map_err(|e| match e {
1238        HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
1239    })
1240}
1241
1242/// Why reading a response head failed: before any byte arrived (the request
1243/// may never have been processed — e.g. a pooled connection the backend had
1244/// already closed) or part-way through.
1245enum HeadError {
1246    NothingReceived(String),
1247    Partial(String),
1248}
1249
1250fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1251    read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
1252}
1253
1254/// The final response head: interim `1xx` heads (`100 Continue`,
1255/// `103 Early Hints`, …) are read past (RFC 9110 §15.2); a `103`'s `Link`
1256/// values are passed on to the client (`early_hints::forward_upstream`). Returning one as
1257/// the response left the real response in the connection, and once pooled
1258/// the next request — possibly another client's — received it.
1259fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1260    let (mut head, mut rest) = read_response_head(stream, tmp)?;
1261    let mut interim = 0;
1262    while is_interim_response(&head) {
1263        crate::early_hints::forward_upstream(&head);
1264        interim += 1;
1265        if interim > MAX_INTERIM_RESPONSES {
1266            return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
1267        }
1268        (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
1269    }
1270    Ok((head, rest))
1271}
1272
1273/// Read until a complete head is in `buf` (which may already hold bytes
1274/// that followed a previous head). `received` — bytes already came from this
1275/// response, so a failure is never "nothing received".
1276fn read_response_head_from<S: Read>(
1277    stream: &mut S,
1278    tmp: &mut [u8],
1279    mut buf: Vec<u8>,
1280    received: bool,
1281) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1282    loop {
1283        if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1284            let body_prefix = buf[pos + 4..].to_vec();
1285            buf.truncate(pos + 4);
1286            return Ok((buf, body_prefix));
1287        }
1288        let nothing = buf.is_empty() && !received;
1289        let n = match stream.read(tmp) {
1290            Ok(n) => n,
1291            Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1292            Err(e) => return Err(HeadError::Partial(e.to_string())),
1293        };
1294        if n == 0 {
1295            let msg = "backend closed connection before headers were complete".to_string();
1296            return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1297        }
1298        buf.extend_from_slice(&tmp[..n]);
1299    }
1300}
1301
1302/// Interim responses tolerated before the final one.
1303#[doc(hidden)]
1304pub const MAX_INTERIM_RESPONSES: usize = 16;
1305
1306/// An interim (1xx) response head other than `101 Switching Protocols`
1307/// (which ends the HTTP exchange): the final response follows it.
1308#[doc(hidden)]
1309pub fn is_interim_response(head: &[u8]) -> bool {
1310    let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1311    let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1312    status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1313}
1314
1315/// RFC 9112 §6.3: a response to HEAD, and any 1xx, 204 or 304 response, ends
1316/// with its head — whatever `Content-Length` says (for HEAD it describes the
1317/// GET body). Waiting for that body hung until the read timeout (a 502).
1318#[doc(hidden)]
1319pub fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1320    let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1321    method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1322}
1323
1324/// Returns `true` when the response should be streamed rather than buffered.
1325///
1326/// Streams when any of the following hold:
1327/// - `Content-Type: text/event-stream` — SSE
1328/// - `Transfer-Encoding: chunked` — AI token streams, etc.
1329/// - `Content-Length` exceeds 1 MB — large file downloads
1330#[doc(hidden)]
1331pub fn should_stream_response(header_lower: &str) -> bool {
1332    let is_sse = header_lower.lines().any(|l| {
1333        l.starts_with("content-type:") && l.contains("text/event-stream")
1334    });
1335    let is_chunked = header_lower.lines().any(|l| {
1336        l.starts_with("transfer-encoding:") && l.contains("chunked")
1337    });
1338    let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1339        l.strip_prefix("content-length:")?.trim().parse().ok()
1340    });
1341    let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1342    is_sse || is_chunked || is_large
1343}
1344
1345/// What the forwarders need from an upstream response head, found in one
1346/// case-insensitive pass over the raw bytes — the same answers as
1347/// [`response_has_no_body`], [`should_stream_response`] and the
1348/// `connection:` / `content-length:` scans over a lower-cased copy, without
1349/// making that copy.
1350#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1351#[doc(hidden)]
1352pub struct HeadFacts {
1353    /// The second whitespace-separated token of the head (the status code).
1354    #[doc(hidden)]
1355    pub status_no_body: bool,
1356    #[doc(hidden)]
1357    pub sse: bool,
1358    #[doc(hidden)]
1359    pub chunked: bool,
1360    /// The first `content-length:` value that parses.
1361    #[doc(hidden)]
1362    pub content_length: Option<usize>,
1363    #[doc(hidden)]
1364    pub connection_close: bool,
1365}
1366
1367#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1368impl HeadFacts {
1369    #[doc(hidden)]
1370    pub fn scan(head: &[u8]) -> HeadFacts {
1371        let text = std::str::from_utf8(head).unwrap_or("");
1372        let status = text.split_whitespace().nth(1).unwrap_or("");
1373        let mut facts = HeadFacts {
1374            status_no_body: status.starts_with('1') || status == "204" || status == "304",
1375            sse: false,
1376            chunked: false,
1377            content_length: None,
1378            connection_close: false,
1379        };
1380        for line in text.lines() {
1381            if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1382                facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1383            } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1384                facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1385            } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1386                if facts.content_length.is_none() {
1387                    facts.content_length = value.trim().parse().ok();
1388                }
1389            } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1390                facts.connection_close |= contains_ignore_ascii_case(value, "close");
1391            }
1392        }
1393        facts
1394    }
1395
1396    /// [`response_has_no_body`].
1397    #[doc(hidden)]
1398    pub fn no_body(&self, method: &str) -> bool {
1399        method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1400    }
1401
1402    /// [`should_stream_response`].
1403    #[doc(hidden)]
1404    pub fn should_stream(&self) -> bool {
1405        self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1406    }
1407}
1408
1409fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1410    let bytes = line.as_bytes();
1411    // `prefix` is ASCII, so a byte match ends on a char boundary.
1412    (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1413        .then(|| &line[prefix.len()..])
1414}
1415
1416fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1417    haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1418}
1419
1420/// Parse the status line and headers from raw header bytes (ending at `\r\n\r\n`).
1421fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1422    let s = std::str::from_utf8(header_bytes)
1423        .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1424    let mut lines = s.lines();
1425    let status_line = lines.next().ok_or("empty backend response")?;
1426    let mut parts = status_line.splitn(3, ' ');
1427    let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1428    let status_code: i16 = parts
1429        .next()
1430        .unwrap_or("502")
1431        .parse()
1432        .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1433    let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1434    let mut headers = Vec::new();
1435    for line in lines {
1436        let line = line.trim_end_matches('\r');
1437        if line.is_empty() { break; }
1438        if let Some(colon) = line.find(':') {
1439            headers.push(crate::header::Header {
1440                name: line[..colon].trim().to_string().into(),
1441                value: (line[colon + 1..].trim().to_string()).into(),
1442            });
1443        }
1444    }
1445    Ok(Response {
1446        http_version,
1447        status_code,
1448        reason_phrase,
1449        headers,
1450        content_range_list: vec![],
1451        stream_file: None,
1452        stream_pipe: None,
1453        trailers: None,
1454    })
1455}
1456
1457/// Read the remaining body after headers have already been read.
1458///
1459/// `header_bytes` ends with `\r\n\r\n`; `body_prefix` holds any body bytes
1460/// that arrived in the same TCP read.  Handles all three body mechanisms
1461/// (chunked, content-length, read-to-EOF).  Returns `(full_response_bytes, can_reuse)`.
1462fn read_response_from_partial<S: Read>(
1463    stream: &mut S,
1464    header_bytes: Vec<u8>,
1465    body_prefix: Vec<u8>,
1466    tmp: &mut [u8],
1467) -> Result<(Vec<u8>, bool), String> {
1468    let header_end = header_bytes.len();
1469    let mut buf = header_bytes;
1470    buf.extend_from_slice(&body_prefix);
1471
1472    let header_lower =
1473        std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1474    let connection_close =
1475        header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1476    let is_chunked = header_lower
1477        .lines()
1478        .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1479    let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1480        l.strip_prefix("content-length:")?.trim().parse().ok()
1481    });
1482
1483    if is_chunked {
1484        let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1485        rewrite_as_content_length(&mut buf, header_end, &decoded);
1486        Ok((buf, !connection_close))
1487    } else if let Some(len) = content_length {
1488        while buf.len() < header_end + len {
1489            let n = stream.read(tmp).map_err(|e| e.to_string())?;
1490            if n == 0 { break; }
1491            buf.extend_from_slice(&tmp[..n]);
1492        }
1493        Ok((buf, !connection_close))
1494    } else {
1495        loop {
1496            let n = stream.read(tmp).map_err(|e| e.to_string())?;
1497            if n == 0 { break; }
1498            buf.extend_from_slice(&tmp[..n]);
1499        }
1500        Ok((buf, false))
1501    }
1502}
1503
1504// ── Backend URL parsing ───────────────────────────────────────────────────────
1505
1506struct Backend {
1507    host: String,
1508    port: u16,
1509    /// Whether the upstream connection should use TLS.
1510    /// Set when the URL scheme is `https://`, `h2s://`, or `grpcs://`.
1511    tls: bool,
1512}
1513
1514impl Backend {
1515    fn parse(url: &str) -> Option<Self> {
1516        let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1517            (r, true, 443u16)
1518        } else if let Some(r) = url.strip_prefix("h2s://") {
1519            (r, true, 443u16)
1520        } else if let Some(r) = url.strip_prefix("grpcs://") {
1521            (r, true, 443u16)
1522        } else if let Some(r) = url.strip_prefix("http://") {
1523            (r, false, 80u16)
1524        } else if let Some(r) = url.strip_prefix("h2://") {
1525            (r, false, 80u16)
1526        } else if let Some(r) = url.strip_prefix("grpc://") {
1527            (r, false, 80u16)
1528        } else {
1529            (url, false, 80u16)
1530        };
1531        // Drop any path component.
1532        let host_port = rest.split('/').next().unwrap_or(rest);
1533        let (host, port) = if let Some(colon) = host_port.rfind(':') {
1534            let port_str = &host_port[colon + 1..];
1535            if let Ok(p) = port_str.parse::<u16>() {
1536                (host_port[..colon].to_string(), p)
1537            } else {
1538                (host_port.to_string(), default_port)
1539            }
1540        } else {
1541            (host_port.to_string(), default_port)
1542        };
1543        if host.is_empty() {
1544            return None;
1545        }
1546        Some(Backend { host, port, tls })
1547    }
1548}
1549
1550// ── HTTP/2 reverse proxy ──────────────────────────────────────────────────────
1551
1552/// Reverse proxy that forwards requests to HTTP/2 backends.
1553///
1554/// Wraps [`ReverseProxy`] and forces HTTP/2 (`h2`) for all upstream connections.
1555/// Requires the `http2` Cargo feature.
1556///
1557/// This proxy also transparently handles gRPC traffic
1558/// (`Content-Type: application/grpc*`) — gRPC DATA frames are forwarded
1559/// as-is because gRPC is layered directly on HTTP/2.
1560#[cfg(feature = "http2")]
1561pub struct H2ReverseProxy {
1562    inner: ReverseProxy,
1563}
1564
1565#[cfg(feature = "http2")]
1566impl H2ReverseProxy {
1567    /// Create a proxy distributing requests across `backends` in round-robin order.
1568    ///
1569    /// Each backend entry can be:
1570    /// - `"host:port"` — plain TCP (HTTP/2 cleartext)
1571    /// - `"h2://host:port"` — plain TCP (explicit scheme)
1572    /// - `"h2s://host:port"` — TLS (HTTP/2 over HTTPS; port defaults to 443)
1573    /// - `"https://host:port"` — TLS (same as `h2s://`)
1574    ///
1575    /// TLS backends require the `http2` Cargo feature (includes `rustls` +
1576    /// `webpki-roots`).  Certificate verification uses the WebPKI trust store.
1577    pub fn new<I, S>(backends: I) -> Self
1578    where
1579        I: IntoIterator<Item = S>,
1580        S: AsRef<str>,
1581    {
1582        H2ReverseProxy {
1583            inner: ReverseProxy::new(backends),
1584        }
1585    }
1586
1587    /// Only proxy requests whose URI starts with `prefix`; pass others through.
1588    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1589        self.inner = self.inner.path_prefix(prefix);
1590        self
1591    }
1592
1593    /// Override the TCP connect timeout (default: 5 s).
1594    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1595        self.inner = self.inner.connect_timeout_ms(ms);
1596        self
1597    }
1598
1599    /// Override the read timeout (default: 30 s). It bounds each wait for
1600    /// the upstream — the handshake, the response head, every body frame — so
1601    /// a streaming response (a gRPC server stream) ends only when it goes
1602    /// quiet for that long.
1603    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1604        self.inner = self.inner.read_timeout_ms(ms);
1605        self
1606    }
1607
1608    /// Trust the CA certificates in the PEM file `path` for `h2s://` /
1609    /// `https://` backends instead of the WebPKI roots. Since 18.3.0.
1610    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1611        self.inner = self.inner.tls_ca_file(path)?;
1612        Ok(self)
1613    }
1614
1615    /// Present a client certificate to TLS backends that require one (mutual
1616    /// TLS). Since 18.3.0.
1617    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1618        self.inner = self.inner.tls_client_cert(cert, key)?;
1619        Ok(self)
1620    }
1621
1622    fn matches(&self, request: &Request) -> bool {
1623        self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1624    }
1625}
1626
1627#[cfg(feature = "http2")]
1628impl crate::middleware::Middleware for H2ReverseProxy {
1629    fn handle(
1630        &self,
1631        request: &crate::request::Request,
1632        connection: &crate::server::ConnectionInfo,
1633        next: &dyn crate::application::Application,
1634    ) -> Result<crate::response::Response, String> {
1635        if !self.matches(request) {
1636            return next.execute(request, connection);
1637        }
1638        if self.inner.backends.is_empty() {
1639            let mut response = bad_gateway();
1640            status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1641            return Ok(response);
1642        }
1643        // A streamed request body can be sent once: no second backend then.
1644        let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1645        let n = self.inner.backends.len();
1646        let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1647        let mut last_error = String::new();
1648        for attempt in 0..attempts {
1649            let backend = &self.inner.backends[(start + attempt) % n];
1650            let tls = backend.tls.then(|| match &self.inner.trust {
1651                Some(trust) => trust.h2_config(),
1652                None => h2_upstream::default_tls(),
1653            });
1654            let target = h2_upstream::Target {
1655                backend,
1656                tls,
1657                connect_timeout: self.inner.connect_timeout,
1658                read_timeout: self.inner.read_timeout,
1659                authority: None,
1660            };
1661            match h2_upstream::forward(request, Peer::of(connection), &target) {
1662                Ok(mut response) => {
1663                    status::received(&mut response, None);
1664                    return Ok(response);
1665                }
1666                Err(e) => last_error = e,
1667            }
1668        }
1669        let mut response = bad_gateway();
1670        status::failed_with(&mut response, &last_error, None);
1671        Ok(response)
1672    }
1673
1674    /// Headers only: a request this proxy doesn't forward passes through
1675    /// untouched.
1676    fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1677        true
1678    }
1679
1680    /// Requests this proxy forwards are sent as their body arrives (gRPC
1681    /// client streaming and bidirectional calls).
1682    fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1683        self.matches(request)
1684    }
1685}
1686
1687// ── HTTP/3 reverse proxy ──────────────────────────────────────────────────────
1688
1689/// Reverse proxy that forwards requests to `https://` backends over HTTP/3
1690/// (QUIC). Since 18.13.0; requires the `http3` feature (default).
1691///
1692/// A backend QUIC can't reach (UDP blocked, no handshake within the connect
1693/// timeout, a TLS failure) is sent the request over HTTPS on TCP instead,
1694/// and stays on TCP for five minutes; `rws_upstream_h3_fallbacks_total`
1695/// counts it under the proxy's [`name`](Self::name).
1696///
1697/// ```rust,no_run
1698/// # extern crate rws_proxy as rust_web_server;
1699/// use rust_web_server::app::App;
1700/// use rust_web_server::core::New;
1701/// use rust_web_server::proxy::H3ReverseProxy;
1702///
1703/// let proxy = H3ReverseProxy::new(["https://edge1.internal:443", "https://edge2.internal:443"])
1704///     .path_prefix("/api")
1705///     .tls_ca_file("/etc/rws/internal-ca.pem")
1706///     .unwrap();
1707/// let app = App::new().wrap(proxy);
1708/// ```
1709#[cfg(feature = "http3")]
1710pub struct H3ReverseProxy {
1711    inner: ReverseProxy,
1712    name: String,
1713    /// Backends on TCP until the time kept here.
1714    tcp_until: std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>,
1715}
1716
1717#[cfg(feature = "http3")]
1718impl H3ReverseProxy {
1719    /// A proxy distributing requests across `backends` (`https://host:port`,
1720    /// port 443 by default) in round-robin order. Certificates are checked
1721    /// against the WebPKI roots unless [`tls_ca_file`](Self::tls_ca_file)
1722    /// says otherwise. A backend that isn't `https://` is reached over
1723    /// HTTP/1.1 on TCP.
1724    pub fn new<I, S>(backends: I) -> Self
1725    where
1726        I: IntoIterator<Item = S>,
1727        S: AsRef<str>,
1728    {
1729        H3ReverseProxy { inner: ReverseProxy::new(backends), name: "h3-reverse-proxy".to_string(), tcp_until: std::sync::Mutex::default() }
1730    }
1731
1732    /// The `upstream` label of this proxy's fallback metric.
1733    pub fn name(mut self, name: impl Into<String>) -> Self {
1734        self.name = name.into();
1735        self
1736    }
1737
1738    /// Only proxy requests whose URI starts with `prefix`; pass others through.
1739    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1740        self.inner = self.inner.path_prefix(prefix);
1741        self
1742    }
1743
1744    /// QUIC handshake (and TCP connect) timeout (default: 5 s).
1745    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1746        self.inner = self.inner.connect_timeout_ms(ms);
1747        self
1748    }
1749
1750    /// Longest wait for the backend — the response head and each body
1751    /// chunk (default: 30 s).
1752    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1753        self.inner = self.inner.read_timeout_ms(ms);
1754        self
1755    }
1756
1757    /// Trust the CA certificates in the PEM file `path` instead of the
1758    /// WebPKI roots.
1759    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1760        self.inner = self.inner.tls_ca_file(path)?;
1761        Ok(self)
1762    }
1763
1764    /// Present a client certificate to backends that require one.
1765    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1766        self.inner = self.inner.tls_client_cert(cert, key)?;
1767        Ok(self)
1768    }
1769
1770    fn matches(&self, request: &Request) -> bool {
1771        self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1772    }
1773
1774    fn on_tcp(&self, key: &str) -> bool {
1775        let mut tcp_until = self.tcp_until.lock().unwrap_or_else(|e| e.into_inner());
1776        match tcp_until.get(key) {
1777            Some(until) if std::time::Instant::now() < *until => true,
1778            Some(_) => {
1779                tcp_until.remove(key);
1780                false
1781            }
1782            None => false,
1783        }
1784    }
1785
1786    /// One attempt at `backend`: HTTP/3 unless it's on TCP, TCP when QUIC
1787    /// can't connect.
1788    fn attempt(&self, backend: &Backend, request: &Request, connection: &crate::server::ConnectionInfo) -> Result<Response, String> {
1789        let key = format!("{}:{}", backend.host, backend.port);
1790        if backend.tls && !self.on_tcp(&key) {
1791            let config = match &self.inner.trust {
1792                Some(trust) => trust.client_config(),
1793                None => tls_client_config(),
1794            };
1795            let target = h3_upstream::Target {
1796                host: &backend.host,
1797                port: backend.port,
1798                authority: None,
1799                tls: &config,
1800                connect_timeout: self.inner.connect_timeout,
1801                read_timeout: self.inner.read_timeout,
1802            };
1803            match h3_upstream::forward(request, Peer::of(connection), &target) {
1804                Err(h3_upstream::H3Error::Connect(e)) => {
1805                    self.tcp_until.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone(), std::time::Instant::now() + crate::proxy_config::H3_FALLBACK);
1806                    crate::proxy_config::upstream::observe_h3_fallback(&self.name);
1807                    eprintln!("{}: HTTP/3 to {key} failed ({e}); using TCP for {} s", self.name, crate::proxy_config::H3_FALLBACK.as_secs());
1808                }
1809                result => return result.map_err(|e| e.to_string()),
1810            }
1811        }
1812        forward_upstream_trusting(
1813            &self.inner.pool,
1814            request,
1815            Peer::of(connection),
1816            &backend.host,
1817            backend.port,
1818            backend.tls,
1819            self.inner.trust.as_deref(),
1820            self.inner.connect_timeout,
1821            self.inner.read_timeout,
1822        )
1823    }
1824}
1825
1826#[cfg(feature = "http3")]
1827impl crate::middleware::Middleware for H3ReverseProxy {
1828    fn handle(
1829        &self,
1830        request: &crate::request::Request,
1831        connection: &crate::server::ConnectionInfo,
1832        next: &dyn crate::application::Application,
1833    ) -> Result<crate::response::Response, String> {
1834        if !self.matches(request) {
1835            return next.execute(request, connection);
1836        }
1837        if self.inner.backends.is_empty() {
1838            let mut response = bad_gateway();
1839            status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1840            return Ok(response);
1841        }
1842        // A streamed request body can be sent once: no second backend then.
1843        let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1844        let n = self.inner.backends.len();
1845        let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1846        let mut last_error = String::new();
1847        for attempt in 0..attempts {
1848            match self.attempt(&self.inner.backends[(start + attempt) % n], request, connection) {
1849                Ok(mut response) => {
1850                    status::received(&mut response, None);
1851                    return Ok(response);
1852                }
1853                Err(e) => last_error = e,
1854            }
1855        }
1856        let mut response = bad_gateway();
1857        status::failed_with(&mut response, &last_error, None);
1858        Ok(response)
1859    }
1860
1861    fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1862        true
1863    }
1864
1865    /// Requests this proxy forwards are sent as their body arrives.
1866    fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1867        self.matches(request)
1868    }
1869}
1870
1871/// Forward `request` over HTTP/2 to `url` (`h2://`, `grpc://`, `h2s://`,
1872/// `grpcs://`, `https://` or `host:port`) — the config file's `grpc` action.
1873/// `tls` forces TLS for a bare `host:port` (`[[upstream]] tls = true`).
1874#[cfg(feature = "http2")]
1875#[doc(hidden)]
1876pub fn forward_h2(
1877    request: &Request,
1878    client: Peer<'_>,
1879    url: &str,
1880    tls: bool,
1881    trust: Option<&UpstreamTls>,
1882    connect_timeout: Duration,
1883    read_timeout: Duration,
1884) -> Result<Response, String> {
1885    let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1886    backend.tls |= tls;
1887    let tls = backend.tls.then(|| match trust {
1888        Some(t) => t.h2_config(),
1889        None => h2_upstream::default_tls(),
1890    });
1891    h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout, authority: None })
1892}
1893
1894/// Forward over TLS to `ip:port` with `config`, `server_name` as SNI (and
1895/// the name `config`'s verifier checks), `host_header` as the `Host` — the
1896/// Gateway API router's BackendTLSPolicy backends. Connections are pooled
1897/// per `label` (one per distinct policy content).
1898#[cfg(feature = "gateway-api")]
1899#[allow(clippy::too_many_arguments)]
1900#[doc(hidden)]
1901pub fn forward_tls_with_host(
1902    config: &Arc<rustls::ClientConfig>,
1903    label: &str,
1904    request: &Request,
1905    client: Peer<'_>,
1906    ip: &str,
1907    port: u16,
1908    server_name: &str,
1909    host_header: &str,
1910    connect_timeout: Duration,
1911    read_timeout: Duration,
1912) -> Result<Response, String> {
1913    let pool = tls_pool_for_ca(label);
1914    forward_via(pool, request, client, ip, port, host_header, read_timeout, || {
1915        let tcp = connect_tcp(ip, port, connect_timeout)?;
1916        let name = rustls::pki_types::ServerName::try_from(server_name.to_string()).map_err(|e| format!("invalid TLS server name '{server_name}': {e}"))?;
1917        let conn = rustls::ClientConnection::new(Arc::clone(config), name).map_err(|e| e.to_string())?;
1918        Ok(rustls::StreamOwned::new(conn, tcp))
1919    })
1920}
1921
1922/// Forward over cleartext HTTP/2 with prior knowledge (h2c) to `host:port`,
1923/// sending `authority` as `:authority` — the Gateway API router's
1924/// `kubernetes.io/h2c` backends.
1925#[cfg(feature = "gateway-api")]
1926#[doc(hidden)]
1927pub fn forward_h2c_with_host(
1928    request: &Request,
1929    client: Peer<'_>,
1930    host: &str,
1931    port: u16,
1932    authority: &str,
1933    connect_timeout: Duration,
1934    read_timeout: Duration,
1935) -> Result<Response, String> {
1936    let backend = Backend { host: host.to_string(), port, tls: false };
1937    h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls: None, connect_timeout, read_timeout, authority: Some(authority) })
1938}
1939
1940// ── gRPC proxy ────────────────────────────────────────────────────────────────
1941
1942/// gRPC reverse proxy middleware.
1943///
1944/// Recognises requests with `Content-Type: application/grpc*` and forwards them
1945/// to a backend over HTTP/2, leaving all other requests to the next layer.
1946///
1947/// Requires the `http2` Cargo feature.
1948///
1949/// # Example
1950///
1951/// ```rust,no_run
1952/// # extern crate rws_proxy as rust_web_server;
1953/// use rust_web_server::app::App;
1954/// use rust_web_server::core::New;
1955/// use rust_web_server::proxy::GrpcProxy;
1956///
1957/// let app = App::new()
1958///     .wrap(GrpcProxy::new(["grpc-service:50051"]));
1959/// ```
1960#[cfg(feature = "http2")]
1961pub struct GrpcProxy {
1962    inner: H2ReverseProxy,
1963}
1964
1965#[cfg(feature = "http2")]
1966impl GrpcProxy {
1967    /// Create a proxy distributing gRPC connections across `backends` in round-robin order.
1968    ///
1969    /// Each backend entry can be:
1970    /// - `"host:port"` — plain TCP (gRPC cleartext)
1971    /// - `"grpc://host:port"` — plain TCP (explicit scheme)
1972    /// - `"grpcs://host:port"` — TLS (gRPC over TLS; port defaults to 443)
1973    /// - `"https://host:port"` — TLS (same as `grpcs://`)
1974    ///
1975    /// TLS backends require the `http2` Cargo feature.
1976    pub fn new<I, S>(backends: I) -> Self
1977    where
1978        I: IntoIterator<Item = S>,
1979        S: AsRef<str>,
1980    {
1981        GrpcProxy { inner: H2ReverseProxy::new(backends) }
1982    }
1983
1984    /// Only proxy requests whose URI starts with `prefix`; pass others through.
1985    pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1986        self.inner = self.inner.path_prefix(prefix);
1987        self
1988    }
1989
1990    /// See [`H2ReverseProxy::connect_timeout_ms`].
1991    pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1992        self.inner = self.inner.connect_timeout_ms(ms);
1993        self
1994    }
1995
1996    /// See [`H2ReverseProxy::read_timeout_ms`]: a stream quiet for longer ends.
1997    pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1998        self.inner = self.inner.read_timeout_ms(ms);
1999        self
2000    }
2001
2002    /// Trust this CA for `grpcs://` backends. Since 18.3.0.
2003    pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
2004        self.inner = self.inner.tls_ca_file(path)?;
2005        Ok(self)
2006    }
2007
2008    /// Present a client certificate to `grpcs://` backends (mutual TLS).
2009    /// Since 18.3.0.
2010    pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
2011        self.inner = self.inner.tls_client_cert(cert, key)?;
2012        Ok(self)
2013    }
2014}
2015
2016#[cfg(feature = "http2")]
2017impl crate::middleware::Middleware for GrpcProxy {
2018    fn handle(
2019        &self,
2020        request: &crate::request::Request,
2021        connection: &crate::server::ConnectionInfo,
2022        next: &dyn crate::application::Application,
2023    ) -> Result<crate::response::Response, String> {
2024        if is_grpc(request) {
2025            self.inner.handle(request, connection, next)
2026        } else {
2027            next.execute(request, connection)
2028        }
2029    }
2030
2031    fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
2032        true
2033    }
2034
2035    fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
2036        is_grpc(request) && self.inner.matches(request)
2037    }
2038}
2039
2040#[cfg(feature = "http2")]
2041fn is_grpc(request: &Request) -> bool {
2042    request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
2043}
2044
2045// ── Backend::parse unit tests ─────────────────────────────────────────────────
2046
2047#[cfg(test)]
2048mod backend_parse_tests {
2049    use super::Backend;
2050
2051    fn parse(url: &str) -> Option<(String, u16, bool)> {
2052        Backend::parse(url).map(|b| (b.host, b.port, b.tls))
2053    }
2054
2055    #[test]
2056    fn bare_host_port() {
2057        assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
2058    }
2059
2060    #[test]
2061    fn http_scheme() {
2062        assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
2063    }
2064
2065    #[test]
2066    fn h2_scheme_plain() {
2067        assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
2068    }
2069
2070    #[test]
2071    fn grpc_scheme_plain() {
2072        assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
2073    }
2074
2075    #[test]
2076    fn https_scheme_sets_tls_and_default_port() {
2077        assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
2078    }
2079
2080    #[test]
2081    fn https_scheme_explicit_port() {
2082        assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
2083    }
2084
2085    #[test]
2086    fn h2s_scheme_sets_tls() {
2087        assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
2088    }
2089
2090    #[test]
2091    fn h2s_scheme_explicit_port() {
2092        assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
2093    }
2094
2095    #[test]
2096    fn grpcs_scheme_sets_tls() {
2097        assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
2098    }
2099
2100    #[test]
2101    fn grpcs_scheme_explicit_port() {
2102        assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
2103    }
2104
2105    #[test]
2106    fn empty_host_returns_none() {
2107        assert_eq!(None, parse("https://"));
2108    }
2109
2110    #[test]
2111    fn bare_host_no_port_defaults_to_80() {
2112        assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
2113    }
2114}