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(not(target_arch = "wasm32"))]
35pub(crate) mod upgrade;
36#[cfg(feature = "http2")]
37pub(crate) mod h2_upstream;
38#[cfg(feature = "http3")]
39pub(crate) mod h3_upstream;
40#[cfg(feature = "http2")]
41pub mod grpc_web;
42#[cfg(feature = "http2")]
43pub use grpc_web::GrpcWebLayer;
44
45#[cfg(test)]
46mod tests;
47
48use std::io::{Read, Write};
49use crate::ext::decimal::Decimal;
50use std::net::{TcpStream, ToSocketAddrs};
51use std::sync::atomic::{AtomicUsize, Ordering};
52use std::sync::Arc;
53use std::time::Duration;
54
55pub use pool::{ConnPool, Pool};
56
57use crate::application::Application;
58use crate::middleware::Middleware;
59use crate::request::Request;
60use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
61use crate::server::ConnectionInfo;
62
63const HOP_BY_HOP: &[&str] = &[
67 "connection",
68 "keep-alive",
69 "proxy-authenticate",
70 "proxy-authorization",
71 "proxy-connection",
72 "te",
73 "trailer",
74 "transfer-encoding",
75 "upgrade",
76];
77
78pub enum LoadBalancing {
80 RoundRobin,
82}
83
84pub struct ReverseProxy {
99 backends: Vec<Backend>,
100 path_prefix: Option<String>,
101 connect_timeout: Duration,
102 read_timeout: Duration,
103 counter: AtomicUsize,
104 pool: Arc<ConnPool>,
105 breaker: Option<Arc<dyn crate::circuit_breaker::Breaker>>,
106 trust: Option<Arc<UpstreamTls>>,
107 tls_ca: Option<String>,
109 tls_client: Option<(String, String)>,
110}
111
112impl ReverseProxy {
113 pub fn new<I, S>(backends: I) -> Self
117 where
118 I: IntoIterator<Item = S>,
119 S: AsRef<str>,
120 {
121 Self {
122 backends: backends
123 .into_iter()
124 .filter_map(|u| Backend::parse(u.as_ref()))
125 .collect(),
126 path_prefix: None,
127 connect_timeout: Duration::from_secs(5),
128 read_timeout: Duration::from_secs(30),
129 counter: AtomicUsize::new(0),
130 pool: Arc::new(ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60))),
131 breaker: None,
132 trust: None,
133 tls_ca: None,
134 tls_client: None,
135 }
136 }
137
138 pub fn with_circuit_breaker(mut self, breaker: Arc<dyn crate::circuit_breaker::Breaker>) -> Self {
156 self.breaker = Some(breaker);
157 self
158 }
159
160 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
165 self.path_prefix = Some(prefix.into());
166 self
167 }
168
169 pub fn strategy(self, _strategy: LoadBalancing) -> Self {
171 self
172 }
173
174 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
176 self.connect_timeout = Duration::from_millis(ms);
177 self
178 }
179
180 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
182 self.read_timeout = Duration::from_millis(ms);
183 self
184 }
185
186 pub fn with_pool(mut self, pool: Arc<ConnPool>) -> Self {
191 self.pool = pool;
192 self
193 }
194
195 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
199 self.tls_ca = Some(path.to_string());
200 self.rebuild_trust()?;
201 Ok(self)
202 }
203
204 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
208 self.tls_client = Some((cert.to_string(), key.to_string()));
209 self.rebuild_trust()?;
210 Ok(self)
211 }
212
213 fn rebuild_trust(&mut self) -> Result<(), String> {
214 let client = self.tls_client.as_ref().map(|(c, k)| (c.as_str(), k.as_str()));
215 self.trust = Some(Arc::new(UpstreamTls::new(self.tls_ca.as_deref(), client)?));
216 Ok(())
217 }
218
219 pub fn max_idle_conns(mut self, n: usize) -> Self {
221 self.pool = Arc::new(ConnPool::new(n, Duration::from_secs(60)));
222 self
223 }
224
225 fn proxy(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
226 if self.backends.is_empty() {
227 return Err("no backends configured".to_string());
228 }
229 let n = self.backends.len();
230 let start = self.counter.fetch_add(1, Ordering::Relaxed);
231 let mut last_err = "all backends failed".to_string();
232 for attempt in 0..n {
233 let idx = (start + attempt) % n;
234 let backend = &self.backends[idx];
235 let key = format!("{}:{}", backend.host, backend.port);
236
237 if let Some(breaker) = &self.breaker {
238 if !breaker.is_available(&key) {
239 last_err = format!("circuit open for {}", key);
240 continue;
241 }
242 }
243
244 match self.try_backend(request, connection, backend) {
245 Ok(resp) => {
246 if let Some(breaker) = &self.breaker {
247 breaker.record_success(&key);
248 }
249 return Ok(resp);
250 }
251 Err(e) => {
252 if let Some(breaker) = &self.breaker {
253 breaker.record_failure(&key);
254 }
255 last_err = e;
256 }
257 }
258 }
259 Err(last_err)
260 }
261
262 fn try_backend(
263 &self,
264 request: &Request,
265 connection: &ConnectionInfo,
266 backend: &Backend,
267 ) -> Result<Response, String> {
268 forward_upstream_trusting(
269 &self.pool,
270 request,
271 crate::proxy::Peer::of(connection),
272 &backend.host,
273 backend.port,
274 backend.tls,
275 self.trust.as_deref(),
276 self.connect_timeout,
277 self.read_timeout,
278 )
279 }
280}
281
282impl Middleware for ReverseProxy {
283 fn handle(
284 &self,
285 request: &Request,
286 connection: &ConnectionInfo,
287 next: &dyn Application,
288 ) -> Result<Response, String> {
289 if let Some(prefix) = &self.path_prefix {
290 if !request.request_uri.starts_with(prefix.as_str()) {
291 return next.execute(request, connection);
292 }
293 }
294 match self.proxy(request, connection) {
295 Ok(mut resp) => {
296 status::received(&mut resp, None);
297 Ok(resp)
298 }
299 Err(e) => {
300 let mut resp = bad_gateway();
301 status::failed_with(&mut resp, &e, None);
302 Ok(resp)
303 }
304 }
305 }
306}
307
308#[derive(Clone, Copy, Debug)]
313pub(crate) struct Peer<'a> {
314 pub ip: &'a str,
315 pub tls: bool,
316}
317
318impl<'a> Peer<'a> {
319 pub(crate) fn of(connection: &'a ConnectionInfo) -> Self {
320 Peer { ip: &connection.client.ip, tls: connection.tls }
321 }
322
323 pub(crate) fn plain(ip: &'a str) -> Self {
325 Peer { ip, tls: false }
326 }
327
328 pub(crate) fn proto(&self) -> &'static str {
329 if self.tls { "https" } else { "http" }
330 }
331}
332
333pub(crate) fn forwarded_value(request: &Request, client: Peer<'_>) -> Option<String> {
338 if !crate::server_config::ServerConfig::current().forwarded_header {
339 return None;
340 }
341 let node = match client.ip.parse::<std::net::IpAddr>() {
342 Ok(std::net::IpAddr::V4(v4)) => v4.to_string(),
343 Ok(std::net::IpAddr::V6(v6)) => match v6.to_ipv4_mapped() {
344 Some(v4) => v4.to_string(),
345 None => format!("\"[{v6}]\""),
346 },
347 Err(_) => "unknown".to_string(),
348 };
349 let mut element = format!("for={node};proto={}", client.proto());
350 if let Some(host) = request.header(crate::header::Header::_HOST).map(|h| h.value.as_ref()).filter(|h: &&str| !h.is_empty() && h.bytes().all(|b| b.is_ascii_graphic() && b != b'"' && b != b'\\')) {
351 let token = host.bytes().all(|b| b.is_ascii_alphanumeric() || b"!#$%&'*+-.^_`|~".contains(&b));
352 if token {
353 element.push_str(&format!(";host={host}"));
354 } else {
355 element.push_str(&format!(";host=\"{host}\""));
356 }
357 }
358 let prior = request.headers.iter().filter(|h| h.name.eq_ignore_ascii_case("forwarded")).map(|h| h.value.trim()).filter(|v| !v.is_empty() && !v.bytes().any(|b| b < 0x20)).collect::<Vec<_>>();
359 Some(if prior.is_empty() { element } else { format!("{}, {element}", prior.join(", ")) })
360}
361
362pub(crate) fn build_request(
363 request: &Request,
364 backend_host: &str,
365 client: Peer<'_>,
366 keep_alive: bool,
367) -> Vec<u8> {
368 let connection = request.header(crate::header::Header::_CONNECTION).map(|h| h.value.as_ref());
374 #[cfg(not(target_arch = "wasm32"))]
377 let trace = crate::otel::propagation_headers();
378 #[cfg(target_arch = "wasm32")]
379 let trace: Option<(String, Option<String>)> = None;
380 let forwarded_header = forwarded_value(request, client);
381 let forwarded = |h: &&crate::header::Header| {
382 !h.name.is_empty()
384 && !is_hop_by_hop_or_host(&h.name)
385 && !h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_LENGTH)
386 && !h.name.eq_ignore_ascii_case("X-Forwarded-For")
387 && !(forwarded_header.is_some() && h.name.eq_ignore_ascii_case("Forwarded"))
388 && !connection.is_some_and(|c| connection_listed(c, &h.name))
389 && !(trace.is_some() && (h.name.eq_ignore_ascii_case("traceparent") || h.name.eq_ignore_ascii_case("baggage")))
390 };
391 let prior_xff = request.header("X-Forwarded-For").map(|h| h.value.as_ref()).filter(|v| !v.trim().is_empty());
392 let forwarded_proto = request.header("X-Forwarded-Proto").is_none().then(|| client.proto());
396 let forwarded_host = match request.header("X-Forwarded-Host") {
397 Some(_) => None,
398 None => request.header(crate::header::Header::_HOST).map(|h| h.value.as_ref()).filter(|v| !v.is_empty()),
399 };
400 let body_len = Decimal::new(request.body.len() as u128);
401 let capacity = request.method.len() + request.request_uri.len() + backend_host.len() + 25
402 + request.headers.iter().filter(forwarded).map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
403 + client.ip.len() + 19 + prior_xff.map_or(0, |v| v.len() + 2)
404 + forwarded_host.map_or(0, |v| v.len() + 20)
405 + forwarded_proto.map_or(0, |v| v.len() + 21)
406 + forwarded_header.as_ref().map_or(0, |v| v.len() + 13)
407 + trace.as_ref().map_or(0, |(t, b)| t.len() + 15 + b.as_ref().map_or(0, |b| b.len() + 11))
408 + 13
409 + 24
410 + if request.body.is_empty() { 0 } else { body_len.as_str().len() + 18 }
411 + 2
412 + request.body.len();
413 let mut out: Vec<u8> = Vec::with_capacity(capacity);
414 for part in [request.method.as_str(), " ", request.request_uri.as_str(), " HTTP/1.1\r\nHost: ", backend_host, "\r\n"] {
415 out.extend_from_slice(part.as_bytes());
416 }
417 for h in request.headers.iter().filter(forwarded) {
418 for part in [h.name.as_ref(), ": ", h.value.as_ref(), "\r\n"] {
419 out.extend_from_slice(part.as_bytes());
420 }
421 }
422 out.extend_from_slice(b"X-Forwarded-For: ");
423 if let Some(prior) = prior_xff {
424 out.extend_from_slice(prior.as_bytes());
425 out.extend_from_slice(b", ");
426 }
427 for part in [client.ip, "\r\n", "Via: 1.1 rws\r\n"] {
428 out.extend_from_slice(part.as_bytes());
429 }
430 if let Some(host) = forwarded_host {
431 for part in ["X-Forwarded-Host: ", host, "\r\n"] {
432 out.extend_from_slice(part.as_bytes());
433 }
434 }
435 if let Some(proto) = forwarded_proto {
436 for part in ["X-Forwarded-Proto: ", proto, "\r\n"] {
437 out.extend_from_slice(part.as_bytes());
438 }
439 }
440 if let Some(value) = &forwarded_header {
441 for part in ["Forwarded: ", value.as_str(), "\r\n"] {
442 out.extend_from_slice(part.as_bytes());
443 }
444 }
445 if let Some((traceparent, baggage)) = &trace {
446 for part in ["traceparent: ", traceparent, "\r\n"] {
447 out.extend_from_slice(part.as_bytes());
448 }
449 if let Some(baggage) = baggage {
450 for part in ["baggage: ", baggage, "\r\n"] {
451 out.extend_from_slice(part.as_bytes());
452 }
453 }
454 }
455 if keep_alive {
456 out.extend_from_slice(b"Connection: keep-alive\r\n");
457 } else {
458 out.extend_from_slice(b"Connection: close\r\n");
459 }
460 if !request.body.is_empty() {
461 out.extend_from_slice(b"Content-Length: ");
462 out.extend_from_slice(body_len.as_str().as_bytes());
463 out.extend_from_slice(b"\r\n");
464 }
465 out.extend_from_slice(b"\r\n");
466 out.extend_from_slice(&request.body);
467 out
468}
469
470fn is_hop_by_hop_or_host(name: &str) -> bool {
475 if name.is_ascii() {
476 name.eq_ignore_ascii_case("host") || HOP_BY_HOP.iter().any(|h| name.eq_ignore_ascii_case(h))
477 } else {
478 let lower = name.to_lowercase();
479 lower == "host" || HOP_BY_HOP.contains(&lower.as_str())
480 }
481}
482
483fn connection_listed(connection: &str, name: &str) -> bool {
486 connection.split(',').any(|token| token.trim().eq_ignore_ascii_case(name))
487}
488
489fn decode_chunked<S: Read>(
494 stream: &mut S,
495 buf: &[u8],
496 header_end: usize,
497 tmp: &mut [u8],
498) -> Result<Vec<u8>, String> {
499 let mut raw: Vec<u8> = buf[header_end..].to_vec();
501 let mut decoded: Vec<u8> = Vec::new();
502
503 loop {
504 let crlf = loop {
506 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
507 break p;
508 }
509 let n = stream.read(tmp).map_err(|e| e.to_string())?;
510 if n == 0 {
511 return Err("chunked: premature EOF reading chunk size".to_string());
512 }
513 raw.extend_from_slice(&tmp[..n]);
514 };
515
516 let size_line = std::str::from_utf8(&raw[..crlf])
518 .map_err(|_| "chunked: non-UTF-8 chunk size line".to_string())?;
519 let size_str = size_line.split(';').next().unwrap_or("").trim();
520 let chunk_size = usize::from_str_radix(size_str, 16)
521 .map_err(|_| format!("chunked: invalid chunk size '{}'", size_str))?;
522 raw.drain(..crlf + 2); if chunk_size == 0 {
525 loop {
529 let line_end = loop {
530 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
531 break p;
532 }
533 let n = stream.read(tmp).map_err(|e| e.to_string())?;
534 if n == 0 {
535 return Err("chunked: premature EOF in trailer".to_string());
536 }
537 raw.extend_from_slice(&tmp[..n]);
538 };
539 raw.drain(..line_end + 2);
540 if line_end == 0 {
541 break;
542 }
543 }
544 break;
545 }
546
547 while raw.len() < chunk_size + 2 {
549 let n = stream.read(tmp).map_err(|e| e.to_string())?;
550 if n == 0 {
551 return Err("chunked: premature EOF reading chunk body".to_string());
552 }
553 raw.extend_from_slice(&tmp[..n]);
554 }
555 decoded.extend_from_slice(&raw[..chunk_size]);
556 raw.drain(..chunk_size + 2); }
558
559 Ok(decoded)
560}
561
562fn rewrite_as_content_length(buf: &mut Vec<u8>, header_end: usize, decoded: &[u8]) {
565 let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_string();
566 buf.clear();
567 for line in header_str.lines() {
568 if line.to_ascii_lowercase().starts_with("transfer-encoding:") || line.is_empty() {
569 continue;
570 }
571 buf.extend_from_slice(line.as_bytes());
572 buf.extend_from_slice(b"\r\n");
573 }
574 let _ = write!(buf, "Content-Length: {}\r\n\r\n", decoded.len());
575 buf.extend_from_slice(decoded);
576}
577
578pub(crate) const REGENERATED_OR_HOP_BY_HOP: &[&str] = &[
581 "content-length", "transfer-encoding", "connection", "keep-alive",
582 "proxy-connection", "te", "trailer", "upgrade",
583];
584
585#[cfg_attr(not(feature = "http2"), allow(dead_code))]
594pub(crate) fn normalize_upstream_response(mut response: Response) -> Response {
595 response.http_version.clear();
596 response.http_version.push_str(crate::http::VERSION.http_1_1);
597 let has_body = !response.content_range_list.is_empty();
598 if let [range] = response.content_range_list.as_mut_slice() {
599 if let Some(h) = response
600 .headers
601 .iter()
602 .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
603 {
604 range.content_type.clear();
605 range.content_type.push_str(&h.value);
606 }
607 }
608 response.headers.retain(|h| {
611 if h.name.eq_ignore_ascii_case("content-type") {
612 return !has_body;
614 }
615 !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
616 });
617 response
618}
619
620pub(crate) fn bad_gateway() -> Response {
621 crate::error::problem(STATUS_CODE_REASON_PHRASE.n502_bad_gateway, "")
622}
623
624const STREAM_THRESHOLD: usize = 1024 * 1024; pub(crate) struct ConcatReader<R: Read + Send> {
632 prefix: Vec<u8>,
633 prefix_pos: usize,
634 inner: R,
635}
636
637impl<R: Read + Send> ConcatReader<R> {
638 fn new(prefix: Vec<u8>, inner: R) -> Self {
639 ConcatReader { prefix, prefix_pos: 0, inner }
640 }
641}
642
643impl<R: Read + Send> Read for ConcatReader<R> {
644 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
645 if self.prefix_pos < self.prefix.len() {
646 let avail = &self.prefix[self.prefix_pos..];
647 let n = buf.len().min(avail.len());
648 buf[..n].copy_from_slice(&avail[..n]);
649 self.prefix_pos += n;
650 return Ok(n);
651 }
652 self.inner.read(buf)
653 }
654}
655
656
657pub(crate) const POOL_MAX_IDLE: usize = 64;
661
662pub(crate) fn shared_pool() -> &'static ConnPool {
665 static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
666 POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
667}
668
669pub(crate) trait UpstreamIo: Read + Write + Send + 'static {
672 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
673}
674
675impl UpstreamIo for TcpStream {
676 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
677 self.set_read_timeout(Some(read))?;
678 self.set_write_timeout(Some(write))
679 }
680}
681
682#[cfg(any(feature = "http-client", feature = "http2"))]
683pub(crate) type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
684
685#[cfg(any(feature = "http-client", feature = "http2"))]
686impl UpstreamIo for TlsStream {
687 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
688 self.sock.set_io_timeouts(read, write)
689 }
690}
691
692pub(crate) fn forward_upstream(
698 plain_pool: &ConnPool,
699 request: &Request,
700 client: Peer<'_>,
701 host: &str,
702 port: u16,
703 tls: bool,
704 connect_timeout: Duration,
705 read_timeout: Duration,
706) -> Result<Response, String> {
707 forward_upstream_trusting(plain_pool, request, client, host, port, tls, None, connect_timeout, read_timeout)
708}
709
710#[allow(clippy::too_many_arguments)]
713pub(crate) fn forward_upstream_trusting(
714 plain_pool: &ConnPool,
715 request: &Request,
716 client: Peer<'_>,
717 host: &str,
718 port: u16,
719 tls: bool,
720 trust: Option<&UpstreamTls>,
721 connect_timeout: Duration,
722 read_timeout: Duration,
723) -> Result<Response, String> {
724 forward_upstream_as(plain_pool, request, client, host, port, host, tls, trust, connect_timeout, read_timeout)
725}
726
727#[allow(clippy::too_many_arguments)]
731pub(crate) fn forward_upstream_as(
732 plain_pool: &ConnPool,
733 request: &Request,
734 client: Peer<'_>,
735 host: &str,
736 port: u16,
737 host_header: &str,
738 tls: bool,
739 trust: Option<&UpstreamTls>,
740 connect_timeout: Duration,
741 read_timeout: Duration,
742) -> Result<Response, String> {
743 #[cfg(not(target_arch = "wasm32"))]
746 let span = crate::otel::outbound_span(&request.method);
747 #[cfg(not(target_arch = "wasm32"))]
748 if let Some(span) = &span {
749 let scheme = if tls { "https" } else { "http" };
750 let path = request.request_uri.as_str();
751 for (key, value) in crate::otel::http_client_attributes(&request.method, &format!("{scheme}://{host}:{port}{path}")) {
752 span.set_attribute(key, value);
753 }
754 }
755 let result = forward_upstream_untraced(plain_pool, request, client, host, port, host_header, tls, trust, connect_timeout, read_timeout);
756 #[cfg(not(target_arch = "wasm32"))]
757 if let Some(span) = &span {
758 span.finish_http_client(result.as_ref().map(|r| r.status_code as u16).map_err(String::as_str));
759 }
760 result
761}
762
763#[allow(clippy::too_many_arguments)]
764fn forward_upstream_untraced(
765 plain_pool: &ConnPool,
766 request: &Request,
767 client: Peer<'_>,
768 host: &str,
769 port: u16,
770 host_header: &str,
771 tls: bool,
772 trust: Option<&UpstreamTls>,
773 connect_timeout: Duration,
774 read_timeout: Duration,
775) -> Result<Response, String> {
776 if tls {
777 #[cfg(any(feature = "http-client", feature = "http2"))]
778 {
779 let (pool, config) = match trust {
780 Some(t) => (t.pool, Arc::clone(&t.config)),
781 None => (shared_tls_pool(), tls_client_config()),
782 };
783 return forward_via(pool, request, client, host, port, host_header, read_timeout, || {
784 connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
785 });
786 }
787 #[cfg(not(any(feature = "http-client", feature = "http2")))]
788 {
789 let _ = trust;
790 return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
791 }
792 }
793 forward_via(plain_pool, request, client, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
794}
795
796pub struct UpstreamTls {
804 #[cfg(any(feature = "http-client", feature = "http2"))]
805 config: Arc<rustls::ClientConfig>,
806 #[cfg(any(feature = "http-client", feature = "http2"))]
807 pool: &'static Pool<TlsStream>,
808 #[cfg(feature = "http2")]
810 async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
811 #[cfg(feature = "http2")]
813 h2_config: Arc<rustls::ClientConfig>,
814}
815
816impl UpstreamTls {
817 pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
819 UpstreamTls::new(Some(path), None)
820 }
821
822 pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
826 #[cfg(any(feature = "http-client", feature = "http2"))]
827 {
828 use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
829 let roots = match ca_file {
830 Some(path) => {
831 let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
832 let certs = CertificateDer::pem_slice_iter(&bytes)
833 .collect::<Result<Vec<_>, _>>()
834 .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
835 if certs.is_empty() {
836 return Err(format!("no certificates in CA file '{path}'"));
837 }
838 let mut roots = rustls::RootCertStore::empty();
839 for cert in certs {
840 roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
841 }
842 roots
843 }
844 None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
845 };
846 let builder = crate::tls_client_builder().with_root_certificates(roots);
847 let config = match client_cert {
848 None => builder.with_no_client_auth(),
849 Some((cert_path, key_path)) => {
850 let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
851 let chain = CertificateDer::pem_slice_iter(&bytes)
852 .collect::<Result<Vec<_>, _>>()
853 .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
854 if chain.is_empty() {
855 return Err(format!("no certificate in '{cert_path}'"));
856 }
857 let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
858 let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
859 builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
860 }
861 };
862 let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
863 Ok(UpstreamTls::with_config(config, &label))
864 }
865 #[cfg(not(any(feature = "http-client", feature = "http2")))]
866 {
867 let _ = client_cert;
868 Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
869 }
870 }
871
872 #[cfg(any(feature = "http-client", feature = "http2"))]
873 fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
874 #[cfg(feature = "http2")]
875 let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
876 UpstreamTls {
877 config: Arc::new(config),
878 pool: tls_pool_for_ca(label),
879 #[cfg(feature = "http2")]
880 async_pool: async_tls_pool_for_ca(label),
881 #[cfg(feature = "http2")]
882 h2_config,
883 }
884 }
885
886 #[cfg(feature = "http2")]
888 pub(crate) fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
889 &self.h2_config
890 }
891
892 pub(crate) fn reject_all(label: &str) -> UpstreamTls {
896 #[cfg(any(feature = "http-client", feature = "http2"))]
897 {
898 let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
899 UpstreamTls::with_config(config, &format!("reject-all:{label}"))
900 }
901 #[cfg(not(any(feature = "http-client", feature = "http2")))]
902 {
903 let _ = label;
904 UpstreamTls {}
905 }
906 }
907
908 #[cfg(feature = "http2")]
910 pub(crate) fn async_tls(&self) -> async_upstream::AsyncTls {
911 async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
912 }
913
914 #[cfg(any(feature = "http-client", feature = "http2"))]
916 pub(crate) fn client_config(&self) -> Arc<rustls::ClientConfig> {
917 Arc::clone(&self.config)
918 }
919}
920
921#[cfg(feature = "http2")]
924fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
925 static POOLS: std::sync::OnceLock<
926 std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
927 > = std::sync::OnceLock::new();
928 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
929 pools
930 .entry(path.to_string())
931 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
932}
933
934#[cfg(any(feature = "http-client", feature = "http2"))]
936fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
937 static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
938 std::sync::OnceLock::new();
939 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
940 pools
941 .entry(path.to_string())
942 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
943}
944
945pub(crate) fn forward_pooled(
949 pool: &ConnPool,
950 request: &Request,
951 client: Peer<'_>,
952 host: &str,
953 port: u16,
954 connect_timeout: Duration,
955 read_timeout: Duration,
956) -> Result<Response, String> {
957 forward_via(pool, request, client, host, port, host, read_timeout, || connect_tcp(host, port, connect_timeout))
958}
959
960#[cfg(feature = "gateway-api")]
963#[allow(clippy::too_many_arguments)]
964pub(crate) fn forward_pooled_with_host(
965 pool: &ConnPool,
966 request: &Request,
967 client: Peer<'_>,
968 host: &str,
969 port: u16,
970 host_header: &str,
971 connect_timeout: Duration,
972 read_timeout: Duration,
973) -> Result<Response, String> {
974 forward_via(pool, request, client, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
975}
976
977#[allow(clippy::too_many_arguments)]
984fn forward_via<S: UpstreamIo>(
985 pool: &Pool<S>,
986 request: &Request,
987 client: Peer<'_>,
988 host: &str,
989 port: u16,
990 host_header: &str,
991 read_timeout: Duration,
992 connect: impl Fn() -> Result<S, String>,
993) -> Result<Response, String> {
994 let key = format!("{}:{}", host, port);
995 if let Some(stream) = pool.acquire(&key) {
996 match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
997 Exchange::Done(response) => return Ok(response),
998 Exchange::NoResponse(_) if is_idempotent(&request.method) => {} Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
1000 }
1001 }
1002 let stream = connect()?;
1003 match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
1004 Exchange::Done(response) => Ok(response),
1005 Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
1006 }
1007}
1008
1009fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
1013 let key = format!("{}:{}", host, port);
1014 let addrs: Vec<_> = key
1015 .to_socket_addrs()
1016 .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
1017 .collect();
1018 let mut last_error = format!("no address resolved for {}", key);
1019 for addr in addrs {
1020 match TcpStream::connect_timeout(&addr, connect_timeout) {
1021 Ok(stream) => {
1022 let _ = stream.set_nodelay(true);
1023 return Ok(stream);
1024 }
1025 Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
1026 }
1027 }
1028 Err(last_error)
1029}
1030
1031#[cfg(any(feature = "http-client", feature = "http2"))]
1033fn shared_tls_pool() -> &'static Pool<TlsStream> {
1034 static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
1035 POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
1036}
1037
1038#[cfg(any(feature = "http-client", feature = "http2"))]
1042pub(crate) fn tls_client_config() -> Arc<rustls::ClientConfig> {
1043 static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
1044 Arc::clone(CONFIG.get_or_init(|| {
1045 let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
1046 Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
1047 }))
1048}
1049
1050#[cfg(any(feature = "http-client", feature = "http2"))]
1051fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
1052 let tcp = connect_tcp(host, port, connect_timeout)?;
1053 let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
1054 .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
1055 let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
1056 Ok(rustls::StreamOwned::new(conn, tcp))
1057}
1058
1059fn is_idempotent(method: &str) -> bool {
1060 matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
1061}
1062
1063enum Exchange {
1064 Done(Response),
1065 NoResponse(String),
1067 Failed(String),
1068}
1069
1070fn exchange<S: UpstreamIo>(
1073 pool: &Pool<S>,
1074 key: &str,
1075 mut stream: S,
1076 request: &Request,
1077 host: &str,
1078 client: Peer<'_>,
1079 read_timeout: Duration,
1080) -> Exchange {
1081 if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
1082 return Exchange::Failed(e.to_string());
1083 }
1084 let req_bytes = build_request(request, host, client, true);
1086 if let Err(e) = stream.write_all(&req_bytes) {
1087 return Exchange::NoResponse(format!("write to backend failed: {}", e));
1088 }
1089
1090 let mut tmp = [0u8; 4096];
1091 let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
1092 Ok(head) => head,
1093 Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
1094 Err(HeadError::Partial(e)) => return Exchange::Failed(e),
1095 };
1096 let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
1097
1098 if response_has_no_body(&request.method, &header_lower) {
1099 if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
1100 pool.release(key, stream);
1101 }
1102 return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
1103 Ok(response) => Exchange::Done(response),
1104 Err(e) => Exchange::Failed(e),
1105 };
1106 }
1107
1108 if should_stream_response(&header_lower) {
1109 return match parse_status_and_headers(&header_bytes) {
1112 Ok(mut response) => {
1113 response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
1114 Exchange::Done(response)
1115 }
1116 Err(e) => Exchange::Failed(e),
1117 };
1118 }
1119 match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
1121 Ok((resp_bytes, reusable)) => {
1122 if reusable {
1123 pool.release(key, stream);
1124 }
1125 match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
1126 Ok(response) => Exchange::Done(response),
1127 Err(e) => Exchange::Failed(e),
1128 }
1129 }
1130 Err(e) => Exchange::Failed(e),
1131 }
1132}
1133
1134#[cfg(test)]
1139fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
1140 read_response_head(stream, tmp).map_err(|e| match e {
1141 HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
1142 })
1143}
1144
1145enum HeadError {
1149 NothingReceived(String),
1150 Partial(String),
1151}
1152
1153fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1154 read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
1155}
1156
1157fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1163 let (mut head, mut rest) = read_response_head(stream, tmp)?;
1164 let mut interim = 0;
1165 while is_interim_response(&head) {
1166 crate::early_hints::forward_upstream(&head);
1167 interim += 1;
1168 if interim > MAX_INTERIM_RESPONSES {
1169 return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
1170 }
1171 (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
1172 }
1173 Ok((head, rest))
1174}
1175
1176fn read_response_head_from<S: Read>(
1180 stream: &mut S,
1181 tmp: &mut [u8],
1182 mut buf: Vec<u8>,
1183 received: bool,
1184) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1185 loop {
1186 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1187 let body_prefix = buf[pos + 4..].to_vec();
1188 buf.truncate(pos + 4);
1189 return Ok((buf, body_prefix));
1190 }
1191 let nothing = buf.is_empty() && !received;
1192 let n = match stream.read(tmp) {
1193 Ok(n) => n,
1194 Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1195 Err(e) => return Err(HeadError::Partial(e.to_string())),
1196 };
1197 if n == 0 {
1198 let msg = "backend closed connection before headers were complete".to_string();
1199 return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1200 }
1201 buf.extend_from_slice(&tmp[..n]);
1202 }
1203}
1204
1205pub(crate) const MAX_INTERIM_RESPONSES: usize = 16;
1207
1208pub(crate) fn is_interim_response(head: &[u8]) -> bool {
1211 let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1212 let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1213 status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1214}
1215
1216pub(crate) fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1220 let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1221 method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1222}
1223
1224pub(crate) fn should_stream_response(header_lower: &str) -> bool {
1231 let is_sse = header_lower.lines().any(|l| {
1232 l.starts_with("content-type:") && l.contains("text/event-stream")
1233 });
1234 let is_chunked = header_lower.lines().any(|l| {
1235 l.starts_with("transfer-encoding:") && l.contains("chunked")
1236 });
1237 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1238 l.strip_prefix("content-length:")?.trim().parse().ok()
1239 });
1240 let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1241 is_sse || is_chunked || is_large
1242}
1243
1244#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1250pub(crate) struct HeadFacts {
1251 pub(crate) status_no_body: bool,
1253 pub(crate) sse: bool,
1254 pub(crate) chunked: bool,
1255 pub(crate) content_length: Option<usize>,
1257 pub(crate) connection_close: bool,
1258}
1259
1260#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1261impl HeadFacts {
1262 pub(crate) fn scan(head: &[u8]) -> HeadFacts {
1263 let text = std::str::from_utf8(head).unwrap_or("");
1264 let status = text.split_whitespace().nth(1).unwrap_or("");
1265 let mut facts = HeadFacts {
1266 status_no_body: status.starts_with('1') || status == "204" || status == "304",
1267 sse: false,
1268 chunked: false,
1269 content_length: None,
1270 connection_close: false,
1271 };
1272 for line in text.lines() {
1273 if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1274 facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1275 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1276 facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1277 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1278 if facts.content_length.is_none() {
1279 facts.content_length = value.trim().parse().ok();
1280 }
1281 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1282 facts.connection_close |= contains_ignore_ascii_case(value, "close");
1283 }
1284 }
1285 facts
1286 }
1287
1288 pub(crate) fn no_body(&self, method: &str) -> bool {
1290 method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1291 }
1292
1293 pub(crate) fn should_stream(&self) -> bool {
1295 self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1296 }
1297}
1298
1299fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1300 let bytes = line.as_bytes();
1301 (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1303 .then(|| &line[prefix.len()..])
1304}
1305
1306fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1307 haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1308}
1309
1310fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1312 let s = std::str::from_utf8(header_bytes)
1313 .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1314 let mut lines = s.lines();
1315 let status_line = lines.next().ok_or("empty backend response")?;
1316 let mut parts = status_line.splitn(3, ' ');
1317 let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1318 let status_code: i16 = parts
1319 .next()
1320 .unwrap_or("502")
1321 .parse()
1322 .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1323 let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1324 let mut headers = Vec::new();
1325 for line in lines {
1326 let line = line.trim_end_matches('\r');
1327 if line.is_empty() { break; }
1328 if let Some(colon) = line.find(':') {
1329 headers.push(crate::header::Header {
1330 name: line[..colon].trim().to_string().into(),
1331 value: (line[colon + 1..].trim().to_string()).into(),
1332 });
1333 }
1334 }
1335 Ok(Response {
1336 http_version,
1337 status_code,
1338 reason_phrase,
1339 headers,
1340 content_range_list: vec![],
1341 stream_file: None,
1342 stream_pipe: None,
1343 trailers: None,
1344 })
1345}
1346
1347fn read_response_from_partial<S: Read>(
1353 stream: &mut S,
1354 header_bytes: Vec<u8>,
1355 body_prefix: Vec<u8>,
1356 tmp: &mut [u8],
1357) -> Result<(Vec<u8>, bool), String> {
1358 let header_end = header_bytes.len();
1359 let mut buf = header_bytes;
1360 buf.extend_from_slice(&body_prefix);
1361
1362 let header_lower =
1363 std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1364 let connection_close =
1365 header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1366 let is_chunked = header_lower
1367 .lines()
1368 .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1369 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1370 l.strip_prefix("content-length:")?.trim().parse().ok()
1371 });
1372
1373 if is_chunked {
1374 let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1375 rewrite_as_content_length(&mut buf, header_end, &decoded);
1376 Ok((buf, !connection_close))
1377 } else if let Some(len) = content_length {
1378 while buf.len() < header_end + len {
1379 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1380 if n == 0 { break; }
1381 buf.extend_from_slice(&tmp[..n]);
1382 }
1383 Ok((buf, !connection_close))
1384 } else {
1385 loop {
1386 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1387 if n == 0 { break; }
1388 buf.extend_from_slice(&tmp[..n]);
1389 }
1390 Ok((buf, false))
1391 }
1392}
1393
1394struct Backend {
1397 host: String,
1398 port: u16,
1399 tls: bool,
1402}
1403
1404impl Backend {
1405 fn parse(url: &str) -> Option<Self> {
1406 let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1407 (r, true, 443u16)
1408 } else if let Some(r) = url.strip_prefix("h2s://") {
1409 (r, true, 443u16)
1410 } else if let Some(r) = url.strip_prefix("grpcs://") {
1411 (r, true, 443u16)
1412 } else if let Some(r) = url.strip_prefix("http://") {
1413 (r, false, 80u16)
1414 } else if let Some(r) = url.strip_prefix("h2://") {
1415 (r, false, 80u16)
1416 } else if let Some(r) = url.strip_prefix("grpc://") {
1417 (r, false, 80u16)
1418 } else {
1419 (url, false, 80u16)
1420 };
1421 let host_port = rest.split('/').next().unwrap_or(rest);
1423 let (host, port) = if let Some(colon) = host_port.rfind(':') {
1424 let port_str = &host_port[colon + 1..];
1425 if let Ok(p) = port_str.parse::<u16>() {
1426 (host_port[..colon].to_string(), p)
1427 } else {
1428 (host_port.to_string(), default_port)
1429 }
1430 } else {
1431 (host_port.to_string(), default_port)
1432 };
1433 if host.is_empty() {
1434 return None;
1435 }
1436 Some(Backend { host, port, tls })
1437 }
1438}
1439
1440#[cfg(feature = "http2")]
1451pub struct H2ReverseProxy {
1452 inner: ReverseProxy,
1453}
1454
1455#[cfg(feature = "http2")]
1456impl H2ReverseProxy {
1457 pub fn new<I, S>(backends: I) -> Self
1468 where
1469 I: IntoIterator<Item = S>,
1470 S: AsRef<str>,
1471 {
1472 H2ReverseProxy {
1473 inner: ReverseProxy::new(backends),
1474 }
1475 }
1476
1477 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1479 self.inner = self.inner.path_prefix(prefix);
1480 self
1481 }
1482
1483 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1485 self.inner = self.inner.connect_timeout_ms(ms);
1486 self
1487 }
1488
1489 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1494 self.inner = self.inner.read_timeout_ms(ms);
1495 self
1496 }
1497
1498 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1501 self.inner = self.inner.tls_ca_file(path)?;
1502 Ok(self)
1503 }
1504
1505 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1508 self.inner = self.inner.tls_client_cert(cert, key)?;
1509 Ok(self)
1510 }
1511
1512 fn matches(&self, request: &Request) -> bool {
1513 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1514 }
1515}
1516
1517#[cfg(feature = "http2")]
1518impl crate::middleware::Middleware for H2ReverseProxy {
1519 fn handle(
1520 &self,
1521 request: &crate::request::Request,
1522 connection: &crate::server::ConnectionInfo,
1523 next: &dyn crate::application::Application,
1524 ) -> Result<crate::response::Response, String> {
1525 if !self.matches(request) {
1526 return next.execute(request, connection);
1527 }
1528 if self.inner.backends.is_empty() {
1529 let mut response = bad_gateway();
1530 status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1531 return Ok(response);
1532 }
1533 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1535 let n = self.inner.backends.len();
1536 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1537 let mut last_error = String::new();
1538 for attempt in 0..attempts {
1539 let backend = &self.inner.backends[(start + attempt) % n];
1540 let tls = backend.tls.then(|| match &self.inner.trust {
1541 Some(trust) => trust.h2_config(),
1542 None => h2_upstream::default_tls(),
1543 });
1544 let target = h2_upstream::Target {
1545 backend,
1546 tls,
1547 connect_timeout: self.inner.connect_timeout,
1548 read_timeout: self.inner.read_timeout,
1549 authority: None,
1550 };
1551 match h2_upstream::forward(request, Peer::of(connection), &target) {
1552 Ok(mut response) => {
1553 status::received(&mut response, None);
1554 return Ok(response);
1555 }
1556 Err(e) => last_error = e,
1557 }
1558 }
1559 let mut response = bad_gateway();
1560 status::failed_with(&mut response, &last_error, None);
1561 Ok(response)
1562 }
1563
1564 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1567 true
1568 }
1569
1570 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1573 self.matches(request)
1574 }
1575}
1576
1577#[cfg(feature = "http3")]
1599pub struct H3ReverseProxy {
1600 inner: ReverseProxy,
1601 name: String,
1602 tcp_until: std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>,
1604}
1605
1606#[cfg(feature = "http3")]
1607impl H3ReverseProxy {
1608 pub fn new<I, S>(backends: I) -> Self
1614 where
1615 I: IntoIterator<Item = S>,
1616 S: AsRef<str>,
1617 {
1618 H3ReverseProxy { inner: ReverseProxy::new(backends), name: "h3-reverse-proxy".to_string(), tcp_until: std::sync::Mutex::default() }
1619 }
1620
1621 pub fn name(mut self, name: impl Into<String>) -> Self {
1623 self.name = name.into();
1624 self
1625 }
1626
1627 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1629 self.inner = self.inner.path_prefix(prefix);
1630 self
1631 }
1632
1633 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1635 self.inner = self.inner.connect_timeout_ms(ms);
1636 self
1637 }
1638
1639 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1642 self.inner = self.inner.read_timeout_ms(ms);
1643 self
1644 }
1645
1646 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1649 self.inner = self.inner.tls_ca_file(path)?;
1650 Ok(self)
1651 }
1652
1653 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1655 self.inner = self.inner.tls_client_cert(cert, key)?;
1656 Ok(self)
1657 }
1658
1659 fn matches(&self, request: &Request) -> bool {
1660 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1661 }
1662
1663 fn on_tcp(&self, key: &str) -> bool {
1664 let mut tcp_until = self.tcp_until.lock().unwrap_or_else(|e| e.into_inner());
1665 match tcp_until.get(key) {
1666 Some(until) if std::time::Instant::now() < *until => true,
1667 Some(_) => {
1668 tcp_until.remove(key);
1669 false
1670 }
1671 None => false,
1672 }
1673 }
1674
1675 fn attempt(&self, backend: &Backend, request: &Request, connection: &crate::server::ConnectionInfo) -> Result<Response, String> {
1678 let key = format!("{}:{}", backend.host, backend.port);
1679 if backend.tls && !self.on_tcp(&key) {
1680 let config = match &self.inner.trust {
1681 Some(trust) => trust.client_config(),
1682 None => tls_client_config(),
1683 };
1684 let target = h3_upstream::Target {
1685 host: &backend.host,
1686 port: backend.port,
1687 authority: None,
1688 tls: &config,
1689 connect_timeout: self.inner.connect_timeout,
1690 read_timeout: self.inner.read_timeout,
1691 };
1692 match h3_upstream::forward(request, Peer::of(connection), &target) {
1693 Err(h3_upstream::H3Error::Connect(e)) => {
1694 self.tcp_until.lock().unwrap_or_else(|e| e.into_inner()).insert(key.clone(), std::time::Instant::now() + crate::proxy_config::H3_FALLBACK);
1695 crate::proxy_config::upstream::observe_h3_fallback(&self.name);
1696 eprintln!("{}: HTTP/3 to {key} failed ({e}); using TCP for {} s", self.name, crate::proxy_config::H3_FALLBACK.as_secs());
1697 }
1698 result => return result.map_err(|e| e.to_string()),
1699 }
1700 }
1701 forward_upstream_trusting(
1702 &self.inner.pool,
1703 request,
1704 Peer::of(connection),
1705 &backend.host,
1706 backend.port,
1707 backend.tls,
1708 self.inner.trust.as_deref(),
1709 self.inner.connect_timeout,
1710 self.inner.read_timeout,
1711 )
1712 }
1713}
1714
1715#[cfg(feature = "http3")]
1716impl crate::middleware::Middleware for H3ReverseProxy {
1717 fn handle(
1718 &self,
1719 request: &crate::request::Request,
1720 connection: &crate::server::ConnectionInfo,
1721 next: &dyn crate::application::Application,
1722 ) -> Result<crate::response::Response, String> {
1723 if !self.matches(request) {
1724 return next.execute(request, connection);
1725 }
1726 if self.inner.backends.is_empty() {
1727 let mut response = bad_gateway();
1728 status::failed(&mut response, status::ProxyError::DestinationUnavailable, None, None);
1729 return Ok(response);
1730 }
1731 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1733 let n = self.inner.backends.len();
1734 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1735 let mut last_error = String::new();
1736 for attempt in 0..attempts {
1737 match self.attempt(&self.inner.backends[(start + attempt) % n], request, connection) {
1738 Ok(mut response) => {
1739 status::received(&mut response, None);
1740 return Ok(response);
1741 }
1742 Err(e) => last_error = e,
1743 }
1744 }
1745 let mut response = bad_gateway();
1746 status::failed_with(&mut response, &last_error, None);
1747 Ok(response)
1748 }
1749
1750 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1751 true
1752 }
1753
1754 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1756 self.matches(request)
1757 }
1758}
1759
1760#[cfg(feature = "http2")]
1764pub(crate) fn forward_h2(
1765 request: &Request,
1766 client: Peer<'_>,
1767 url: &str,
1768 tls: bool,
1769 trust: Option<&UpstreamTls>,
1770 connect_timeout: Duration,
1771 read_timeout: Duration,
1772) -> Result<Response, String> {
1773 let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1774 backend.tls |= tls;
1775 let tls = backend.tls.then(|| match trust {
1776 Some(t) => t.h2_config(),
1777 None => h2_upstream::default_tls(),
1778 });
1779 h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout, authority: None })
1780}
1781
1782#[cfg(feature = "gateway-api")]
1787#[allow(clippy::too_many_arguments)]
1788pub(crate) fn forward_tls_with_host(
1789 config: &Arc<rustls::ClientConfig>,
1790 label: &str,
1791 request: &Request,
1792 client: Peer<'_>,
1793 ip: &str,
1794 port: u16,
1795 server_name: &str,
1796 host_header: &str,
1797 connect_timeout: Duration,
1798 read_timeout: Duration,
1799) -> Result<Response, String> {
1800 let pool = tls_pool_for_ca(label);
1801 forward_via(pool, request, client, ip, port, host_header, read_timeout, || {
1802 let tcp = connect_tcp(ip, port, connect_timeout)?;
1803 let name = rustls::pki_types::ServerName::try_from(server_name.to_string()).map_err(|e| format!("invalid TLS server name '{server_name}': {e}"))?;
1804 let conn = rustls::ClientConnection::new(Arc::clone(config), name).map_err(|e| e.to_string())?;
1805 Ok(rustls::StreamOwned::new(conn, tcp))
1806 })
1807}
1808
1809#[cfg(feature = "gateway-api")]
1813pub(crate) fn forward_h2c_with_host(
1814 request: &Request,
1815 client: Peer<'_>,
1816 host: &str,
1817 port: u16,
1818 authority: &str,
1819 connect_timeout: Duration,
1820 read_timeout: Duration,
1821) -> Result<Response, String> {
1822 let backend = Backend { host: host.to_string(), port, tls: false };
1823 h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls: None, connect_timeout, read_timeout, authority: Some(authority) })
1824}
1825
1826#[cfg(feature = "http2")]
1846pub struct GrpcProxy {
1847 inner: H2ReverseProxy,
1848}
1849
1850#[cfg(feature = "http2")]
1851impl GrpcProxy {
1852 pub fn new<I, S>(backends: I) -> Self
1862 where
1863 I: IntoIterator<Item = S>,
1864 S: AsRef<str>,
1865 {
1866 GrpcProxy { inner: H2ReverseProxy::new(backends) }
1867 }
1868
1869 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1871 self.inner = self.inner.path_prefix(prefix);
1872 self
1873 }
1874
1875 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1877 self.inner = self.inner.connect_timeout_ms(ms);
1878 self
1879 }
1880
1881 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1883 self.inner = self.inner.read_timeout_ms(ms);
1884 self
1885 }
1886
1887 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1889 self.inner = self.inner.tls_ca_file(path)?;
1890 Ok(self)
1891 }
1892
1893 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1896 self.inner = self.inner.tls_client_cert(cert, key)?;
1897 Ok(self)
1898 }
1899}
1900
1901#[cfg(feature = "http2")]
1902impl crate::middleware::Middleware for GrpcProxy {
1903 fn handle(
1904 &self,
1905 request: &crate::request::Request,
1906 connection: &crate::server::ConnectionInfo,
1907 next: &dyn crate::application::Application,
1908 ) -> Result<crate::response::Response, String> {
1909 if is_grpc(request) {
1910 self.inner.handle(request, connection, next)
1911 } else {
1912 next.execute(request, connection)
1913 }
1914 }
1915
1916 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1917 true
1918 }
1919
1920 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1921 is_grpc(request) && self.inner.matches(request)
1922 }
1923}
1924
1925#[cfg(feature = "http2")]
1926fn is_grpc(request: &Request) -> bool {
1927 request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
1928}
1929
1930#[cfg(test)]
1933mod backend_parse_tests {
1934 use super::Backend;
1935
1936 fn parse(url: &str) -> Option<(String, u16, bool)> {
1937 Backend::parse(url).map(|b| (b.host, b.port, b.tls))
1938 }
1939
1940 #[test]
1941 fn bare_host_port() {
1942 assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
1943 }
1944
1945 #[test]
1946 fn http_scheme() {
1947 assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
1948 }
1949
1950 #[test]
1951 fn h2_scheme_plain() {
1952 assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
1953 }
1954
1955 #[test]
1956 fn grpc_scheme_plain() {
1957 assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
1958 }
1959
1960 #[test]
1961 fn https_scheme_sets_tls_and_default_port() {
1962 assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
1963 }
1964
1965 #[test]
1966 fn https_scheme_explicit_port() {
1967 assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
1968 }
1969
1970 #[test]
1971 fn h2s_scheme_sets_tls() {
1972 assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
1973 }
1974
1975 #[test]
1976 fn h2s_scheme_explicit_port() {
1977 assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
1978 }
1979
1980 #[test]
1981 fn grpcs_scheme_sets_tls() {
1982 assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
1983 }
1984
1985 #[test]
1986 fn grpcs_scheme_explicit_port() {
1987 assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
1988 }
1989
1990 #[test]
1991 fn empty_host_returns_none() {
1992 assert_eq!(None, parse("https://"));
1993 }
1994
1995 #[test]
1996 fn bare_host_no_port_defaults_to_80() {
1997 assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
1998 }
1999}