1pub mod pool;
27pub mod status;
28#[cfg(feature = "http2")]
29pub(crate) mod async_upstream;
30#[cfg(not(target_arch = "wasm32"))]
31pub mod mirror;
32#[cfg(feature = "http2")]
33pub(crate) mod h2_upstream;
34#[cfg(feature = "http3")]
35pub(crate) mod h3_upstream;
36#[cfg(feature = "http2")]
37pub mod grpc_web;
38#[cfg(feature = "http2")]
39pub use grpc_web::GrpcWebLayer;
40
41#[cfg(test)]
42mod tests;
43
44use std::io::{Read, Write};
45use crate::ext::decimal::Decimal;
46use std::net::{TcpStream, ToSocketAddrs};
47use std::sync::atomic::{AtomicUsize, Ordering};
48use std::sync::Arc;
49use std::time::Duration;
50
51pub use pool::{ConnPool, Pool};
52
53use crate::application::Application;
54use crate::middleware::Middleware;
55use crate::request::Request;
56use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
57use crate::server::ConnectionInfo;
58
59const HOP_BY_HOP: &[&str] = &[
63 "connection",
64 "keep-alive",
65 "proxy-authenticate",
66 "proxy-authorization",
67 "proxy-connection",
68 "te",
69 "trailer",
70 "transfer-encoding",
71 "upgrade",
72];
73
74pub enum LoadBalancing {
76 RoundRobin,
78}
79
80pub struct ReverseProxy {
95 backends: Vec<Backend>,
96 path_prefix: Option<String>,
97 connect_timeout: Duration,
98 read_timeout: Duration,
99 counter: AtomicUsize,
100 pool: Arc<ConnPool>,
101 breaker: Option<Arc<dyn crate::circuit_breaker::Breaker>>,
102 trust: Option<Arc<UpstreamTls>>,
103 tls_ca: Option<String>,
105 tls_client: Option<(String, String)>,
106}
107
108impl ReverseProxy {
109 pub fn new<I, S>(backends: I) -> Self
113 where
114 I: IntoIterator<Item = S>,
115 S: AsRef<str>,
116 {
117 Self {
118 backends: backends
119 .into_iter()
120 .filter_map(|u| Backend::parse(u.as_ref()))
121 .collect(),
122 path_prefix: None,
123 connect_timeout: Duration::from_secs(5),
124 read_timeout: Duration::from_secs(30),
125 counter: AtomicUsize::new(0),
126 pool: Arc::new(ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60))),
127 breaker: None,
128 trust: None,
129 tls_ca: None,
130 tls_client: None,
131 }
132 }
133
134 pub fn with_circuit_breaker(mut self, breaker: Arc<dyn crate::circuit_breaker::Breaker>) -> Self {
152 self.breaker = Some(breaker);
153 self
154 }
155
156 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
161 self.path_prefix = Some(prefix.into());
162 self
163 }
164
165 pub fn strategy(self, _strategy: LoadBalancing) -> Self {
167 self
168 }
169
170 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
172 self.connect_timeout = Duration::from_millis(ms);
173 self
174 }
175
176 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
178 self.read_timeout = Duration::from_millis(ms);
179 self
180 }
181
182 pub fn with_pool(mut self, pool: Arc<ConnPool>) -> Self {
187 self.pool = pool;
188 self
189 }
190
191 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
195 self.tls_ca = Some(path.to_string());
196 self.rebuild_trust()?;
197 Ok(self)
198 }
199
200 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
204 self.tls_client = Some((cert.to_string(), key.to_string()));
205 self.rebuild_trust()?;
206 Ok(self)
207 }
208
209 fn rebuild_trust(&mut self) -> Result<(), String> {
210 let client = self.tls_client.as_ref().map(|(c, k)| (c.as_str(), k.as_str()));
211 self.trust = Some(Arc::new(UpstreamTls::new(self.tls_ca.as_deref(), client)?));
212 Ok(())
213 }
214
215 pub fn max_idle_conns(mut self, n: usize) -> Self {
217 self.pool = Arc::new(ConnPool::new(n, Duration::from_secs(60)));
218 self
219 }
220
221 fn proxy(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
222 if self.backends.is_empty() {
223 return Err("no backends configured".to_string());
224 }
225 let n = self.backends.len();
226 let start = self.counter.fetch_add(1, Ordering::Relaxed);
227 let mut last_err = "all backends failed".to_string();
228 for attempt in 0..n {
229 let idx = (start + attempt) % n;
230 let backend = &self.backends[idx];
231 let key = format!("{}:{}", backend.host, backend.port);
232
233 if let Some(breaker) = &self.breaker {
234 if !breaker.is_available(&key) {
235 last_err = format!("circuit open for {}", key);
236 continue;
237 }
238 }
239
240 match self.try_backend(request, connection, backend) {
241 Ok(resp) => {
242 if let Some(breaker) = &self.breaker {
243 breaker.record_success(&key);
244 }
245 return Ok(resp);
246 }
247 Err(e) => {
248 if let Some(breaker) = &self.breaker {
249 breaker.record_failure(&key);
250 }
251 last_err = e;
252 }
253 }
254 }
255 Err(last_err)
256 }
257
258 fn try_backend(
259 &self,
260 request: &Request,
261 connection: &ConnectionInfo,
262 backend: &Backend,
263 ) -> Result<Response, String> {
264 forward_upstream_trusting(
265 &self.pool,
266 request,
267 crate::proxy::Peer::of(connection),
268 &backend.host,
269 backend.port,
270 backend.tls,
271 self.trust.as_deref(),
272 self.connect_timeout,
273 self.read_timeout,
274 )
275 }
276}
277
278impl Middleware for ReverseProxy {
279 fn handle(
280 &self,
281 request: &Request,
282 connection: &ConnectionInfo,
283 next: &dyn Application,
284 ) -> Result<Response, String> {
285 if let Some(prefix) = &self.path_prefix {
286 if !request.request_uri.starts_with(prefix.as_str()) {
287 return next.execute(request, connection);
288 }
289 }
290 match self.proxy(request, connection) {
291 Ok(mut resp) => {
292 status::received(&mut resp, None);
293 Ok(resp)
294 }
295 Err(e) => {
296 let mut resp = bad_gateway();
297 status::failed_with(&mut resp, &e, None);
298 Ok(resp)
299 }
300 }
301 }
302}
303
304#[derive(Clone, Copy, Debug)]
309pub(crate) struct Peer<'a> {
310 pub ip: &'a str,
311 pub tls: bool,
312}
313
314impl<'a> Peer<'a> {
315 pub(crate) fn of(connection: &'a ConnectionInfo) -> Self {
316 Peer { ip: &connection.client.ip, tls: connection.tls }
317 }
318
319 pub(crate) fn plain(ip: &'a str) -> Self {
321 Peer { ip, tls: false }
322 }
323
324 pub(crate) fn proto(&self) -> &'static str {
325 if self.tls { "https" } else { "http" }
326 }
327}
328
329pub(crate) fn build_request(
330 request: &Request,
331 backend_host: &str,
332 client: Peer<'_>,
333 keep_alive: bool,
334) -> Vec<u8> {
335 let connection = request.header(crate::header::Header::_CONNECTION).map(|h| h.value.as_ref());
341 #[cfg(not(target_arch = "wasm32"))]
344 let trace = crate::otel::propagation_headers();
345 #[cfg(target_arch = "wasm32")]
346 let trace: Option<(String, Option<String>)> = None;
347 let forwarded = |h: &&crate::header::Header| {
348 !h.name.is_empty()
350 && !is_hop_by_hop_or_host(&h.name)
351 && !h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_LENGTH)
352 && !h.name.eq_ignore_ascii_case("X-Forwarded-For")
353 && !connection.is_some_and(|c| connection_listed(c, &h.name))
354 && !(trace.is_some() && (h.name.eq_ignore_ascii_case("traceparent") || h.name.eq_ignore_ascii_case("baggage")))
355 };
356 let prior_xff = request.header("X-Forwarded-For").map(|h| h.value.as_ref()).filter(|v| !v.trim().is_empty());
357 let forwarded_proto = request.header("X-Forwarded-Proto").is_none().then(|| client.proto());
361 let forwarded_host = match request.header("X-Forwarded-Host") {
362 Some(_) => None,
363 None => request.header(crate::header::Header::_HOST).map(|h| h.value.as_ref()).filter(|v| !v.is_empty()),
364 };
365 let body_len = Decimal::new(request.body.len() as u128);
366 let capacity = request.method.len() + request.request_uri.len() + backend_host.len() + 25
367 + request.headers.iter().filter(forwarded).map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
368 + client.ip.len() + 19 + prior_xff.map_or(0, |v| v.len() + 2)
369 + forwarded_host.map_or(0, |v| v.len() + 20)
370 + forwarded_proto.map_or(0, |v| v.len() + 21)
371 + trace.as_ref().map_or(0, |(t, b)| t.len() + 15 + b.as_ref().map_or(0, |b| b.len() + 11))
372 + 13
373 + 24
374 + if request.body.is_empty() { 0 } else { body_len.as_str().len() + 18 }
375 + 2
376 + request.body.len();
377 let mut out: Vec<u8> = Vec::with_capacity(capacity);
378 for part in [request.method.as_str(), " ", request.request_uri.as_str(), " HTTP/1.1\r\nHost: ", backend_host, "\r\n"] {
379 out.extend_from_slice(part.as_bytes());
380 }
381 for h in request.headers.iter().filter(forwarded) {
382 for part in [h.name.as_ref(), ": ", h.value.as_ref(), "\r\n"] {
383 out.extend_from_slice(part.as_bytes());
384 }
385 }
386 out.extend_from_slice(b"X-Forwarded-For: ");
387 if let Some(prior) = prior_xff {
388 out.extend_from_slice(prior.as_bytes());
389 out.extend_from_slice(b", ");
390 }
391 for part in [client.ip, "\r\n", "Via: 1.1 rws\r\n"] {
392 out.extend_from_slice(part.as_bytes());
393 }
394 if let Some(host) = forwarded_host {
395 for part in ["X-Forwarded-Host: ", host, "\r\n"] {
396 out.extend_from_slice(part.as_bytes());
397 }
398 }
399 if let Some(proto) = forwarded_proto {
400 for part in ["X-Forwarded-Proto: ", proto, "\r\n"] {
401 out.extend_from_slice(part.as_bytes());
402 }
403 }
404 if let Some((traceparent, baggage)) = &trace {
405 for part in ["traceparent: ", traceparent, "\r\n"] {
406 out.extend_from_slice(part.as_bytes());
407 }
408 if let Some(baggage) = baggage {
409 for part in ["baggage: ", baggage, "\r\n"] {
410 out.extend_from_slice(part.as_bytes());
411 }
412 }
413 }
414 if keep_alive {
415 out.extend_from_slice(b"Connection: keep-alive\r\n");
416 } else {
417 out.extend_from_slice(b"Connection: close\r\n");
418 }
419 if !request.body.is_empty() {
420 out.extend_from_slice(b"Content-Length: ");
421 out.extend_from_slice(body_len.as_str().as_bytes());
422 out.extend_from_slice(b"\r\n");
423 }
424 out.extend_from_slice(b"\r\n");
425 out.extend_from_slice(&request.body);
426 out
427}
428
429fn is_hop_by_hop_or_host(name: &str) -> bool {
434 if name.is_ascii() {
435 name.eq_ignore_ascii_case("host") || HOP_BY_HOP.iter().any(|h| name.eq_ignore_ascii_case(h))
436 } else {
437 let lower = name.to_lowercase();
438 lower == "host" || HOP_BY_HOP.contains(&lower.as_str())
439 }
440}
441
442fn connection_listed(connection: &str, name: &str) -> bool {
445 connection.split(',').any(|token| token.trim().eq_ignore_ascii_case(name))
446}
447
448fn decode_chunked<S: Read>(
453 stream: &mut S,
454 buf: &[u8],
455 header_end: usize,
456 tmp: &mut [u8],
457) -> Result<Vec<u8>, String> {
458 let mut raw: Vec<u8> = buf[header_end..].to_vec();
460 let mut decoded: Vec<u8> = Vec::new();
461
462 loop {
463 let crlf = loop {
465 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
466 break p;
467 }
468 let n = stream.read(tmp).map_err(|e| e.to_string())?;
469 if n == 0 {
470 return Err("chunked: premature EOF reading chunk size".to_string());
471 }
472 raw.extend_from_slice(&tmp[..n]);
473 };
474
475 let size_line = std::str::from_utf8(&raw[..crlf])
477 .map_err(|_| "chunked: non-UTF-8 chunk size line".to_string())?;
478 let size_str = size_line.split(';').next().unwrap_or("").trim();
479 let chunk_size = usize::from_str_radix(size_str, 16)
480 .map_err(|_| format!("chunked: invalid chunk size '{}'", size_str))?;
481 raw.drain(..crlf + 2); if chunk_size == 0 {
484 loop {
488 let line_end = loop {
489 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
490 break p;
491 }
492 let n = stream.read(tmp).map_err(|e| e.to_string())?;
493 if n == 0 {
494 return Err("chunked: premature EOF in trailer".to_string());
495 }
496 raw.extend_from_slice(&tmp[..n]);
497 };
498 raw.drain(..line_end + 2);
499 if line_end == 0 {
500 break;
501 }
502 }
503 break;
504 }
505
506 while raw.len() < chunk_size + 2 {
508 let n = stream.read(tmp).map_err(|e| e.to_string())?;
509 if n == 0 {
510 return Err("chunked: premature EOF reading chunk body".to_string());
511 }
512 raw.extend_from_slice(&tmp[..n]);
513 }
514 decoded.extend_from_slice(&raw[..chunk_size]);
515 raw.drain(..chunk_size + 2); }
517
518 Ok(decoded)
519}
520
521fn rewrite_as_content_length(buf: &mut Vec<u8>, header_end: usize, decoded: &[u8]) {
524 let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_string();
525 buf.clear();
526 for line in header_str.lines() {
527 if line.to_ascii_lowercase().starts_with("transfer-encoding:") || line.is_empty() {
528 continue;
529 }
530 buf.extend_from_slice(line.as_bytes());
531 buf.extend_from_slice(b"\r\n");
532 }
533 let _ = write!(buf, "Content-Length: {}\r\n\r\n", decoded.len());
534 buf.extend_from_slice(decoded);
535}
536
537pub(crate) const REGENERATED_OR_HOP_BY_HOP: &[&str] = &[
540 "content-length", "transfer-encoding", "connection", "keep-alive",
541 "proxy-connection", "te", "trailer", "upgrade",
542];
543
544#[cfg_attr(not(feature = "http2"), allow(dead_code))]
553pub(crate) fn normalize_upstream_response(mut response: Response) -> Response {
554 response.http_version.clear();
555 response.http_version.push_str(crate::http::VERSION.http_1_1);
556 let has_body = !response.content_range_list.is_empty();
557 if let [range] = response.content_range_list.as_mut_slice() {
558 if let Some(h) = response
559 .headers
560 .iter()
561 .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
562 {
563 range.content_type.clear();
564 range.content_type.push_str(&h.value);
565 }
566 }
567 response.headers.retain(|h| {
570 if h.name.eq_ignore_ascii_case("content-type") {
571 return !has_body;
573 }
574 !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
575 });
576 response
577}
578
579pub(crate) fn bad_gateway() -> Response {
580 crate::error::problem(STATUS_CODE_REASON_PHRASE.n502_bad_gateway, "")
581}
582
583const STREAM_THRESHOLD: usize = 1024 * 1024; pub(crate) struct ConcatReader<R: Read + Send> {
591 prefix: Vec<u8>,
592 prefix_pos: usize,
593 inner: R,
594}
595
596impl<R: Read + Send> ConcatReader<R> {
597 fn new(prefix: Vec<u8>, inner: R) -> Self {
598 ConcatReader { prefix, prefix_pos: 0, inner }
599 }
600}
601
602impl<R: Read + Send> Read for ConcatReader<R> {
603 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
604 if self.prefix_pos < self.prefix.len() {
605 let avail = &self.prefix[self.prefix_pos..];
606 let n = buf.len().min(avail.len());
607 buf[..n].copy_from_slice(&avail[..n]);
608 self.prefix_pos += n;
609 return Ok(n);
610 }
611 self.inner.read(buf)
612 }
613}
614
615
616pub(crate) const POOL_MAX_IDLE: usize = 64;
620
621pub(crate) fn shared_pool() -> &'static ConnPool {
624 static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
625 POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
626}
627
628pub(crate) trait UpstreamIo: Read + Write + Send + 'static {
631 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
632}
633
634impl UpstreamIo for TcpStream {
635 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
636 self.set_read_timeout(Some(read))?;
637 self.set_write_timeout(Some(write))
638 }
639}
640
641#[cfg(any(feature = "http-client", feature = "http2"))]
642pub(crate) type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
643
644#[cfg(any(feature = "http-client", feature = "http2"))]
645impl UpstreamIo for TlsStream {
646 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
647 self.sock.set_io_timeouts(read, write)
648 }
649}
650
651pub(crate) fn forward_upstream(
657 plain_pool: &ConnPool,
658 request: &Request,
659 client: Peer<'_>,
660 host: &str,
661 port: u16,
662 tls: bool,
663 connect_timeout: Duration,
664 read_timeout: Duration,
665) -> Result<Response, String> {
666 forward_upstream_trusting(plain_pool, request, client, host, port, tls, None, connect_timeout, read_timeout)
667}
668
669#[allow(clippy::too_many_arguments)]
672pub(crate) fn forward_upstream_trusting(
673 plain_pool: &ConnPool,
674 request: &Request,
675 client: Peer<'_>,
676 host: &str,
677 port: u16,
678 tls: bool,
679 trust: Option<&UpstreamTls>,
680 connect_timeout: Duration,
681 read_timeout: Duration,
682) -> Result<Response, String> {
683 #[cfg(not(target_arch = "wasm32"))]
686 let span = crate::otel::outbound_span(&request.method);
687 #[cfg(not(target_arch = "wasm32"))]
688 if let Some(span) = &span {
689 let scheme = if tls { "https" } else { "http" };
690 let path = request.request_uri.as_str();
691 for (key, value) in crate::otel::http_client_attributes(&request.method, &format!("{scheme}://{host}:{port}{path}")) {
692 span.set_attribute(key, value);
693 }
694 }
695 let result = forward_upstream_untraced(plain_pool, request, client, host, port, tls, trust, connect_timeout, read_timeout);
696 #[cfg(not(target_arch = "wasm32"))]
697 if let Some(span) = &span {
698 span.finish_http_client(result.as_ref().map(|r| r.status_code as u16).map_err(String::as_str));
699 }
700 result
701}
702
703#[allow(clippy::too_many_arguments)]
704fn forward_upstream_untraced(
705 plain_pool: &ConnPool,
706 request: &Request,
707 client: Peer<'_>,
708 host: &str,
709 port: u16,
710 tls: bool,
711 trust: Option<&UpstreamTls>,
712 connect_timeout: Duration,
713 read_timeout: Duration,
714) -> Result<Response, String> {
715 if tls {
716 #[cfg(any(feature = "http-client", feature = "http2"))]
717 {
718 let (pool, config) = match trust {
719 Some(t) => (t.pool, Arc::clone(&t.config)),
720 None => (shared_tls_pool(), tls_client_config()),
721 };
722 return forward_via(pool, request, client, host, port, host, read_timeout, || {
723 connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
724 });
725 }
726 #[cfg(not(any(feature = "http-client", feature = "http2")))]
727 {
728 let _ = trust;
729 return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
730 }
731 }
732 forward_pooled(plain_pool, request, client, host, port, connect_timeout, read_timeout)
733}
734
735pub struct UpstreamTls {
743 #[cfg(any(feature = "http-client", feature = "http2"))]
744 config: Arc<rustls::ClientConfig>,
745 #[cfg(any(feature = "http-client", feature = "http2"))]
746 pool: &'static Pool<TlsStream>,
747 #[cfg(feature = "http2")]
749 async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
750 #[cfg(feature = "http2")]
752 h2_config: Arc<rustls::ClientConfig>,
753}
754
755impl UpstreamTls {
756 pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
758 UpstreamTls::new(Some(path), None)
759 }
760
761 pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
765 #[cfg(any(feature = "http-client", feature = "http2"))]
766 {
767 use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
768 let roots = match ca_file {
769 Some(path) => {
770 let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
771 let certs = CertificateDer::pem_slice_iter(&bytes)
772 .collect::<Result<Vec<_>, _>>()
773 .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
774 if certs.is_empty() {
775 return Err(format!("no certificates in CA file '{path}'"));
776 }
777 let mut roots = rustls::RootCertStore::empty();
778 for cert in certs {
779 roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
780 }
781 roots
782 }
783 None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
784 };
785 let builder = crate::tls_client_builder().with_root_certificates(roots);
786 let config = match client_cert {
787 None => builder.with_no_client_auth(),
788 Some((cert_path, key_path)) => {
789 let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
790 let chain = CertificateDer::pem_slice_iter(&bytes)
791 .collect::<Result<Vec<_>, _>>()
792 .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
793 if chain.is_empty() {
794 return Err(format!("no certificate in '{cert_path}'"));
795 }
796 let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
797 let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
798 builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
799 }
800 };
801 let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
802 Ok(UpstreamTls::with_config(config, &label))
803 }
804 #[cfg(not(any(feature = "http-client", feature = "http2")))]
805 {
806 let _ = client_cert;
807 Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
808 }
809 }
810
811 #[cfg(any(feature = "http-client", feature = "http2"))]
812 fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
813 #[cfg(feature = "http2")]
814 let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
815 UpstreamTls {
816 config: Arc::new(config),
817 pool: tls_pool_for_ca(label),
818 #[cfg(feature = "http2")]
819 async_pool: async_tls_pool_for_ca(label),
820 #[cfg(feature = "http2")]
821 h2_config,
822 }
823 }
824
825 #[cfg(feature = "http2")]
827 pub(crate) fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
828 &self.h2_config
829 }
830
831 pub(crate) fn reject_all(label: &str) -> UpstreamTls {
835 #[cfg(any(feature = "http-client", feature = "http2"))]
836 {
837 let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
838 UpstreamTls::with_config(config, &format!("reject-all:{label}"))
839 }
840 #[cfg(not(any(feature = "http-client", feature = "http2")))]
841 {
842 let _ = label;
843 UpstreamTls {}
844 }
845 }
846
847 #[cfg(feature = "http2")]
849 pub(crate) fn async_tls(&self) -> async_upstream::AsyncTls {
850 async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
851 }
852
853 #[cfg(any(feature = "http-client", feature = "http2"))]
855 pub(crate) fn client_config(&self) -> Arc<rustls::ClientConfig> {
856 Arc::clone(&self.config)
857 }
858}
859
860#[cfg(feature = "http2")]
863fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
864 static POOLS: std::sync::OnceLock<
865 std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
866 > = std::sync::OnceLock::new();
867 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
868 pools
869 .entry(path.to_string())
870 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
871}
872
873#[cfg(any(feature = "http-client", feature = "http2"))]
875fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
876 static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
877 std::sync::OnceLock::new();
878 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
879 pools
880 .entry(path.to_string())
881 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
882}
883
884pub(crate) fn forward_pooled(
888 pool: &ConnPool,
889 request: &Request,
890 client: Peer<'_>,
891 host: &str,
892 port: u16,
893 connect_timeout: Duration,
894 read_timeout: Duration,
895) -> Result<Response, String> {
896 forward_via(pool, request, client, host, port, host, read_timeout, || connect_tcp(host, port, connect_timeout))
897}
898
899#[cfg(feature = "gateway-api")]
902#[allow(clippy::too_many_arguments)]
903pub(crate) fn forward_pooled_with_host(
904 pool: &ConnPool,
905 request: &Request,
906 client: Peer<'_>,
907 host: &str,
908 port: u16,
909 host_header: &str,
910 connect_timeout: Duration,
911 read_timeout: Duration,
912) -> Result<Response, String> {
913 forward_via(pool, request, client, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
914}
915
916#[allow(clippy::too_many_arguments)]
923fn forward_via<S: UpstreamIo>(
924 pool: &Pool<S>,
925 request: &Request,
926 client: Peer<'_>,
927 host: &str,
928 port: u16,
929 host_header: &str,
930 read_timeout: Duration,
931 connect: impl Fn() -> Result<S, String>,
932) -> Result<Response, String> {
933 let key = format!("{}:{}", host, port);
934 if let Some(stream) = pool.acquire(&key) {
935 match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
936 Exchange::Done(response) => return Ok(response),
937 Exchange::NoResponse(_) if is_idempotent(&request.method) => {} Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
939 }
940 }
941 let stream = connect()?;
942 match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
943 Exchange::Done(response) => Ok(response),
944 Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
945 }
946}
947
948fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
952 let key = format!("{}:{}", host, port);
953 let addrs: Vec<_> = key
954 .to_socket_addrs()
955 .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
956 .collect();
957 let mut last_error = format!("no address resolved for {}", key);
958 for addr in addrs {
959 match TcpStream::connect_timeout(&addr, connect_timeout) {
960 Ok(stream) => {
961 let _ = stream.set_nodelay(true);
962 return Ok(stream);
963 }
964 Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
965 }
966 }
967 Err(last_error)
968}
969
970#[cfg(any(feature = "http-client", feature = "http2"))]
972fn shared_tls_pool() -> &'static Pool<TlsStream> {
973 static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
974 POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
975}
976
977#[cfg(any(feature = "http-client", feature = "http2"))]
981pub(crate) fn tls_client_config() -> Arc<rustls::ClientConfig> {
982 static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
983 Arc::clone(CONFIG.get_or_init(|| {
984 let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
985 Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
986 }))
987}
988
989#[cfg(any(feature = "http-client", feature = "http2"))]
990fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
991 let tcp = connect_tcp(host, port, connect_timeout)?;
992 let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
993 .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
994 let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
995 Ok(rustls::StreamOwned::new(conn, tcp))
996}
997
998fn is_idempotent(method: &str) -> bool {
999 matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
1000}
1001
1002enum Exchange {
1003 Done(Response),
1004 NoResponse(String),
1006 Failed(String),
1007}
1008
1009fn exchange<S: UpstreamIo>(
1012 pool: &Pool<S>,
1013 key: &str,
1014 mut stream: S,
1015 request: &Request,
1016 host: &str,
1017 client: Peer<'_>,
1018 read_timeout: Duration,
1019) -> Exchange {
1020 if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
1021 return Exchange::Failed(e.to_string());
1022 }
1023 let req_bytes = build_request(request, host, client, true);
1025 if let Err(e) = stream.write_all(&req_bytes) {
1026 return Exchange::NoResponse(format!("write to backend failed: {}", e));
1027 }
1028
1029 let mut tmp = [0u8; 4096];
1030 let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
1031 Ok(head) => head,
1032 Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
1033 Err(HeadError::Partial(e)) => return Exchange::Failed(e),
1034 };
1035 let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
1036
1037 if response_has_no_body(&request.method, &header_lower) {
1038 if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
1039 pool.release(key, stream);
1040 }
1041 return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
1042 Ok(response) => Exchange::Done(response),
1043 Err(e) => Exchange::Failed(e),
1044 };
1045 }
1046
1047 if should_stream_response(&header_lower) {
1048 return match parse_status_and_headers(&header_bytes) {
1051 Ok(mut response) => {
1052 response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
1053 Exchange::Done(response)
1054 }
1055 Err(e) => Exchange::Failed(e),
1056 };
1057 }
1058 match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
1060 Ok((resp_bytes, reusable)) => {
1061 if reusable {
1062 pool.release(key, stream);
1063 }
1064 match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
1065 Ok(response) => Exchange::Done(response),
1066 Err(e) => Exchange::Failed(e),
1067 }
1068 }
1069 Err(e) => Exchange::Failed(e),
1070 }
1071}
1072
1073#[cfg(test)]
1078fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
1079 read_response_head(stream, tmp).map_err(|e| match e {
1080 HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
1081 })
1082}
1083
1084enum HeadError {
1088 NothingReceived(String),
1089 Partial(String),
1090}
1091
1092fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1093 read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
1094}
1095
1096fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1102 let (mut head, mut rest) = read_response_head(stream, tmp)?;
1103 let mut interim = 0;
1104 while is_interim_response(&head) {
1105 crate::early_hints::forward_upstream(&head);
1106 interim += 1;
1107 if interim > MAX_INTERIM_RESPONSES {
1108 return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
1109 }
1110 (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
1111 }
1112 Ok((head, rest))
1113}
1114
1115fn read_response_head_from<S: Read>(
1119 stream: &mut S,
1120 tmp: &mut [u8],
1121 mut buf: Vec<u8>,
1122 received: bool,
1123) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1124 loop {
1125 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1126 let body_prefix = buf[pos + 4..].to_vec();
1127 buf.truncate(pos + 4);
1128 return Ok((buf, body_prefix));
1129 }
1130 let nothing = buf.is_empty() && !received;
1131 let n = match stream.read(tmp) {
1132 Ok(n) => n,
1133 Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1134 Err(e) => return Err(HeadError::Partial(e.to_string())),
1135 };
1136 if n == 0 {
1137 let msg = "backend closed connection before headers were complete".to_string();
1138 return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1139 }
1140 buf.extend_from_slice(&tmp[..n]);
1141 }
1142}
1143
1144pub(crate) const MAX_INTERIM_RESPONSES: usize = 16;
1146
1147pub(crate) fn is_interim_response(head: &[u8]) -> bool {
1150 let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1151 let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1152 status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1153}
1154
1155pub(crate) fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1159 let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1160 method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1161}
1162
1163pub(crate) fn should_stream_response(header_lower: &str) -> bool {
1170 let is_sse = header_lower.lines().any(|l| {
1171 l.starts_with("content-type:") && l.contains("text/event-stream")
1172 });
1173 let is_chunked = header_lower.lines().any(|l| {
1174 l.starts_with("transfer-encoding:") && l.contains("chunked")
1175 });
1176 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1177 l.strip_prefix("content-length:")?.trim().parse().ok()
1178 });
1179 let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1180 is_sse || is_chunked || is_large
1181}
1182
1183#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1189pub(crate) struct HeadFacts {
1190 pub(crate) status_no_body: bool,
1192 pub(crate) sse: bool,
1193 pub(crate) chunked: bool,
1194 pub(crate) content_length: Option<usize>,
1196 pub(crate) connection_close: bool,
1197}
1198
1199#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1200impl HeadFacts {
1201 pub(crate) fn scan(head: &[u8]) -> HeadFacts {
1202 let text = std::str::from_utf8(head).unwrap_or("");
1203 let status = text.split_whitespace().nth(1).unwrap_or("");
1204 let mut facts = HeadFacts {
1205 status_no_body: status.starts_with('1') || status == "204" || status == "304",
1206 sse: false,
1207 chunked: false,
1208 content_length: None,
1209 connection_close: false,
1210 };
1211 for line in text.lines() {
1212 if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1213 facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1214 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1215 facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1216 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1217 if facts.content_length.is_none() {
1218 facts.content_length = value.trim().parse().ok();
1219 }
1220 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1221 facts.connection_close |= contains_ignore_ascii_case(value, "close");
1222 }
1223 }
1224 facts
1225 }
1226
1227 pub(crate) fn no_body(&self, method: &str) -> bool {
1229 method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1230 }
1231
1232 pub(crate) fn should_stream(&self) -> bool {
1234 self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1235 }
1236}
1237
1238fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1239 let bytes = line.as_bytes();
1240 (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1242 .then(|| &line[prefix.len()..])
1243}
1244
1245fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1246 haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1247}
1248
1249fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1251 let s = std::str::from_utf8(header_bytes)
1252 .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1253 let mut lines = s.lines();
1254 let status_line = lines.next().ok_or("empty backend response")?;
1255 let mut parts = status_line.splitn(3, ' ');
1256 let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1257 let status_code: i16 = parts
1258 .next()
1259 .unwrap_or("502")
1260 .parse()
1261 .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1262 let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1263 let mut headers = Vec::new();
1264 for line in lines {
1265 let line = line.trim_end_matches('\r');
1266 if line.is_empty() { break; }
1267 if let Some(colon) = line.find(':') {
1268 headers.push(crate::header::Header {
1269 name: line[..colon].trim().to_string().into(),
1270 value: (line[colon + 1..].trim().to_string()).into(),
1271 });
1272 }
1273 }
1274 Ok(Response {
1275 http_version,
1276 status_code,
1277 reason_phrase,
1278 headers,
1279 content_range_list: vec![],
1280 stream_file: None,
1281 stream_pipe: None,
1282 trailers: None,
1283 })
1284}
1285
1286fn read_response_from_partial<S: Read>(
1292 stream: &mut S,
1293 header_bytes: Vec<u8>,
1294 body_prefix: Vec<u8>,
1295 tmp: &mut [u8],
1296) -> Result<(Vec<u8>, bool), String> {
1297 let header_end = header_bytes.len();
1298 let mut buf = header_bytes;
1299 buf.extend_from_slice(&body_prefix);
1300
1301 let header_lower =
1302 std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1303 let connection_close =
1304 header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1305 let is_chunked = header_lower
1306 .lines()
1307 .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1308 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1309 l.strip_prefix("content-length:")?.trim().parse().ok()
1310 });
1311
1312 if is_chunked {
1313 let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1314 rewrite_as_content_length(&mut buf, header_end, &decoded);
1315 Ok((buf, !connection_close))
1316 } else if let Some(len) = content_length {
1317 while buf.len() < header_end + len {
1318 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1319 if n == 0 { break; }
1320 buf.extend_from_slice(&tmp[..n]);
1321 }
1322 Ok((buf, !connection_close))
1323 } else {
1324 loop {
1325 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1326 if n == 0 { break; }
1327 buf.extend_from_slice(&tmp[..n]);
1328 }
1329 Ok((buf, false))
1330 }
1331}
1332
1333struct Backend {
1336 host: String,
1337 port: u16,
1338 tls: bool,
1341}
1342
1343impl Backend {
1344 fn parse(url: &str) -> Option<Self> {
1345 let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1346 (r, true, 443u16)
1347 } else if let Some(r) = url.strip_prefix("h2s://") {
1348 (r, true, 443u16)
1349 } else if let Some(r) = url.strip_prefix("grpcs://") {
1350 (r, true, 443u16)
1351 } else if let Some(r) = url.strip_prefix("http://") {
1352 (r, false, 80u16)
1353 } else if let Some(r) = url.strip_prefix("h2://") {
1354 (r, false, 80u16)
1355 } else if let Some(r) = url.strip_prefix("grpc://") {
1356 (r, false, 80u16)
1357 } else {
1358 (url, false, 80u16)
1359 };
1360 let host_port = rest.split('/').next().unwrap_or(rest);
1362 let (host, port) = if let Some(colon) = host_port.rfind(':') {
1363 let port_str = &host_port[colon + 1..];
1364 if let Ok(p) = port_str.parse::<u16>() {
1365 (host_port[..colon].to_string(), p)
1366 } else {
1367 (host_port.to_string(), default_port)
1368 }
1369 } else {
1370 (host_port.to_string(), default_port)
1371 };
1372 if host.is_empty() {
1373 return None;
1374 }
1375 Some(Backend { host, port, tls })
1376 }
1377}
1378
1379#[cfg(feature = "http2")]
1390pub struct H2ReverseProxy {
1391 inner: ReverseProxy,
1392}
1393
1394#[cfg(feature = "http2")]
1395impl H2ReverseProxy {
1396 pub fn new<I, S>(backends: I) -> Self
1407 where
1408 I: IntoIterator<Item = S>,
1409 S: AsRef<str>,
1410 {
1411 H2ReverseProxy {
1412 inner: ReverseProxy::new(backends),
1413 }
1414 }
1415
1416 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1418 self.inner = self.inner.path_prefix(prefix);
1419 self
1420 }
1421
1422 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1424 self.inner = self.inner.connect_timeout_ms(ms);
1425 self
1426 }
1427
1428 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1433 self.inner = self.inner.read_timeout_ms(ms);
1434 self
1435 }
1436
1437 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1440 self.inner = self.inner.tls_ca_file(path)?;
1441 Ok(self)
1442 }
1443
1444 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1447 self.inner = self.inner.tls_client_cert(cert, key)?;
1448 Ok(self)
1449 }
1450
1451 fn matches(&self, request: &Request) -> bool {
1452 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1453 }
1454}
1455
1456#[cfg(feature = "http2")]
1457impl crate::middleware::Middleware for H2ReverseProxy {
1458 fn handle(
1459 &self,
1460 request: &crate::request::Request,
1461 connection: &crate::server::ConnectionInfo,
1462 next: &dyn crate::application::Application,
1463 ) -> Result<crate::response::Response, String> {
1464 if !self.matches(request) {
1465 return next.execute(request, connection);
1466 }
1467 if self.inner.backends.is_empty() {
1468 let mut response = bad_gateway();
1469 status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1470 return Ok(response);
1471 }
1472 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1474 let n = self.inner.backends.len();
1475 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1476 let mut last_error = String::new();
1477 for attempt in 0..attempts {
1478 let backend = &self.inner.backends[(start + attempt) % n];
1479 let tls = backend.tls.then(|| match &self.inner.trust {
1480 Some(trust) => trust.h2_config(),
1481 None => h2_upstream::default_tls(),
1482 });
1483 let target = h2_upstream::Target {
1484 backend,
1485 tls,
1486 connect_timeout: self.inner.connect_timeout,
1487 read_timeout: self.inner.read_timeout,
1488 authority: None,
1489 };
1490 match h2_upstream::forward(request, Peer::of(connection), &target) {
1491 Ok(mut response) => {
1492 status::received(&mut response, None);
1493 return Ok(response);
1494 }
1495 Err(e) => last_error = e,
1496 }
1497 }
1498 let mut response = bad_gateway();
1499 status::failed_with(&mut response, &last_error, None);
1500 Ok(response)
1501 }
1502
1503 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1506 true
1507 }
1508
1509 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1512 self.matches(request)
1513 }
1514}
1515
1516#[cfg(feature = "http3")]
1538pub struct H3ReverseProxy {
1539 inner: ReverseProxy,
1540 name: String,
1541 tcp_until: std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>,
1543}
1544
1545#[cfg(feature = "http3")]
1546impl H3ReverseProxy {
1547 pub fn new<I, S>(backends: I) -> Self
1553 where
1554 I: IntoIterator<Item = S>,
1555 S: AsRef<str>,
1556 {
1557 H3ReverseProxy { inner: ReverseProxy::new(backends), name: "h3-reverse-proxy".to_string(), tcp_until: std::sync::Mutex::default() }
1558 }
1559
1560 pub fn name(mut self, name: impl Into<String>) -> Self {
1562 self.name = name.into();
1563 self
1564 }
1565
1566 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1568 self.inner = self.inner.path_prefix(prefix);
1569 self
1570 }
1571
1572 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1574 self.inner = self.inner.connect_timeout_ms(ms);
1575 self
1576 }
1577
1578 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1581 self.inner = self.inner.read_timeout_ms(ms);
1582 self
1583 }
1584
1585 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1588 self.inner = self.inner.tls_ca_file(path)?;
1589 Ok(self)
1590 }
1591
1592 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1594 self.inner = self.inner.tls_client_cert(cert, key)?;
1595 Ok(self)
1596 }
1597
1598 fn matches(&self, request: &Request) -> bool {
1599 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1600 }
1601
1602 fn on_tcp(&self, key: &str) -> bool {
1603 let mut tcp_until = self.tcp_until.lock().unwrap_or_else(|e| e.into_inner());
1604 match tcp_until.get(key) {
1605 Some(until) if std::time::Instant::now() < *until => true,
1606 Some(_) => {
1607 tcp_until.remove(key);
1608 false
1609 }
1610 None => false,
1611 }
1612 }
1613
1614 fn attempt(&self, backend: &Backend, request: &Request, connection: &crate::server::ConnectionInfo) -> Result<Response, String> {
1617 let key = format!("{}:{}", backend.host, backend.port);
1618 if backend.tls && !self.on_tcp(&key) {
1619 let config = match &self.inner.trust {
1620 Some(trust) => trust.client_config(),
1621 None => tls_client_config(),
1622 };
1623 let target = h3_upstream::Target {
1624 host: &backend.host,
1625 port: backend.port,
1626 tls: &config,
1627 connect_timeout: self.inner.connect_timeout,
1628 read_timeout: self.inner.read_timeout,
1629 };
1630 match h3_upstream::forward(request, Peer::of(connection), &target) {
1631 Err(h3_upstream::H3Error::Connect(e)) => {
1632 self.tcp_until.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone(), std::time::Instant::now() + crate::proxy_config::H3_FALLBACK);
1633 crate::proxy_config::upstream::observe_h3_fallback(&self.name);
1634 eprintln!("{}: HTTP/3 to {key} failed ({e}); using TCP for {} s", self.name, crate::proxy_config::H3_FALLBACK.as_secs());
1635 }
1636 result => return result.map_err(|e| e.to_string()),
1637 }
1638 }
1639 forward_upstream_trusting(
1640 &self.inner.pool,
1641 request,
1642 Peer::of(connection),
1643 &backend.host,
1644 backend.port,
1645 backend.tls,
1646 self.inner.trust.as_deref(),
1647 self.inner.connect_timeout,
1648 self.inner.read_timeout,
1649 )
1650 }
1651}
1652
1653#[cfg(feature = "http3")]
1654impl crate::middleware::Middleware for H3ReverseProxy {
1655 fn handle(
1656 &self,
1657 request: &crate::request::Request,
1658 connection: &crate::server::ConnectionInfo,
1659 next: &dyn crate::application::Application,
1660 ) -> Result<crate::response::Response, String> {
1661 if !self.matches(request) {
1662 return next.execute(request, connection);
1663 }
1664 if self.inner.backends.is_empty() {
1665 let mut response = bad_gateway();
1666 status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1667 return Ok(response);
1668 }
1669 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1671 let n = self.inner.backends.len();
1672 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1673 let mut last_error = String::new();
1674 for attempt in 0..attempts {
1675 match self.attempt(&self.inner.backends[(start + attempt) % n], request, connection) {
1676 Ok(mut response) => {
1677 status::received(&mut response, None);
1678 return Ok(response);
1679 }
1680 Err(e) => last_error = e,
1681 }
1682 }
1683 let mut response = bad_gateway();
1684 status::failed_with(&mut response, &last_error, None);
1685 Ok(response)
1686 }
1687
1688 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1689 true
1690 }
1691
1692 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1694 self.matches(request)
1695 }
1696}
1697
1698#[cfg(feature = "http2")]
1702pub(crate) fn forward_h2(
1703 request: &Request,
1704 client: Peer<'_>,
1705 url: &str,
1706 tls: bool,
1707 trust: Option<&UpstreamTls>,
1708 connect_timeout: Duration,
1709 read_timeout: Duration,
1710) -> Result<Response, String> {
1711 let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1712 backend.tls |= tls;
1713 let tls = backend.tls.then(|| match trust {
1714 Some(t) => t.h2_config(),
1715 None => h2_upstream::default_tls(),
1716 });
1717 h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout, authority: None })
1718}
1719
1720#[cfg(feature = "gateway-api")]
1725#[allow(clippy::too_many_arguments)]
1726pub(crate) fn forward_tls_with_host(
1727 config: &Arc<rustls::ClientConfig>,
1728 label: &str,
1729 request: &Request,
1730 client: Peer<'_>,
1731 ip: &str,
1732 port: u16,
1733 server_name: &str,
1734 host_header: &str,
1735 connect_timeout: Duration,
1736 read_timeout: Duration,
1737) -> Result<Response, String> {
1738 let pool = tls_pool_for_ca(label);
1739 forward_via(pool, request, client, ip, port, host_header, read_timeout, || {
1740 let tcp = connect_tcp(ip, port, connect_timeout)?;
1741 let name = rustls::pki_types::ServerName::try_from(server_name.to_string()).map_err(|e| format!("invalid TLS server name '{server_name}': {e}"))?;
1742 let conn = rustls::ClientConnection::new(Arc::clone(config), name).map_err(|e| e.to_string())?;
1743 Ok(rustls::StreamOwned::new(conn, tcp))
1744 })
1745}
1746
1747#[cfg(feature = "gateway-api")]
1751pub(crate) fn forward_h2c_with_host(
1752 request: &Request,
1753 client: Peer<'_>,
1754 host: &str,
1755 port: u16,
1756 authority: &str,
1757 connect_timeout: Duration,
1758 read_timeout: Duration,
1759) -> Result<Response, String> {
1760 let backend = Backend { host: host.to_string(), port, tls: false };
1761 h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls: None, connect_timeout, read_timeout, authority: Some(authority) })
1762}
1763
1764#[cfg(feature = "http2")]
1784pub struct GrpcProxy {
1785 inner: H2ReverseProxy,
1786}
1787
1788#[cfg(feature = "http2")]
1789impl GrpcProxy {
1790 pub fn new<I, S>(backends: I) -> Self
1800 where
1801 I: IntoIterator<Item = S>,
1802 S: AsRef<str>,
1803 {
1804 GrpcProxy { inner: H2ReverseProxy::new(backends) }
1805 }
1806
1807 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1809 self.inner = self.inner.path_prefix(prefix);
1810 self
1811 }
1812
1813 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1815 self.inner = self.inner.connect_timeout_ms(ms);
1816 self
1817 }
1818
1819 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1821 self.inner = self.inner.read_timeout_ms(ms);
1822 self
1823 }
1824
1825 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1827 self.inner = self.inner.tls_ca_file(path)?;
1828 Ok(self)
1829 }
1830
1831 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1834 self.inner = self.inner.tls_client_cert(cert, key)?;
1835 Ok(self)
1836 }
1837}
1838
1839#[cfg(feature = "http2")]
1840impl crate::middleware::Middleware for GrpcProxy {
1841 fn handle(
1842 &self,
1843 request: &crate::request::Request,
1844 connection: &crate::server::ConnectionInfo,
1845 next: &dyn crate::application::Application,
1846 ) -> Result<crate::response::Response, String> {
1847 if is_grpc(request) {
1848 self.inner.handle(request, connection, next)
1849 } else {
1850 next.execute(request, connection)
1851 }
1852 }
1853
1854 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1855 true
1856 }
1857
1858 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1859 is_grpc(request) && self.inner.matches(request)
1860 }
1861}
1862
1863#[cfg(feature = "http2")]
1864fn is_grpc(request: &Request) -> bool {
1865 request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
1866}
1867
1868#[cfg(test)]
1871mod backend_parse_tests {
1872 use super::Backend;
1873
1874 fn parse(url: &str) -> Option<(String, u16, bool)> {
1875 Backend::parse(url).map(|b| (b.host, b.port, b.tls))
1876 }
1877
1878 #[test]
1879 fn bare_host_port() {
1880 assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
1881 }
1882
1883 #[test]
1884 fn http_scheme() {
1885 assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
1886 }
1887
1888 #[test]
1889 fn h2_scheme_plain() {
1890 assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
1891 }
1892
1893 #[test]
1894 fn grpc_scheme_plain() {
1895 assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
1896 }
1897
1898 #[test]
1899 fn https_scheme_sets_tls_and_default_port() {
1900 assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
1901 }
1902
1903 #[test]
1904 fn https_scheme_explicit_port() {
1905 assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
1906 }
1907
1908 #[test]
1909 fn h2s_scheme_sets_tls() {
1910 assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
1911 }
1912
1913 #[test]
1914 fn h2s_scheme_explicit_port() {
1915 assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
1916 }
1917
1918 #[test]
1919 fn grpcs_scheme_sets_tls() {
1920 assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
1921 }
1922
1923 #[test]
1924 fn grpcs_scheme_explicit_port() {
1925 assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
1926 }
1927
1928 #[test]
1929 fn empty_host_returns_none() {
1930 assert_eq!(None, parse("https://"));
1931 }
1932
1933 #[test]
1934 fn bare_host_no_port_defaults_to_80() {
1935 assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
1936 }
1937}