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