Skip to main content

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