1pub mod pool;
27#[cfg(feature = "http2")]
28pub(crate) mod async_upstream;
29#[cfg(feature = "http2")]
30pub(crate) mod h2_upstream;
31#[cfg(feature = "http2")]
32pub mod grpc_web;
33#[cfg(feature = "http2")]
34pub use grpc_web::GrpcWebLayer;
35
36#[cfg(test)]
37mod tests;
38
39use std::io::{Read, Write};
40use crate::ext::decimal::Decimal;
41use std::net::{TcpStream, ToSocketAddrs};
42use std::sync::atomic::{AtomicUsize, Ordering};
43use std::sync::Arc;
44use std::time::Duration;
45
46pub use pool::{ConnPool, Pool};
47
48use crate::application::Application;
49use crate::core::New;
50use crate::middleware::Middleware;
51use crate::mime_type::MimeType;
52use crate::range::Range;
53use crate::request::Request;
54use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
55use crate::server::ConnectionInfo;
56
57const HOP_BY_HOP: &[&str] = &[
61 "connection",
62 "keep-alive",
63 "proxy-authenticate",
64 "proxy-authorization",
65 "proxy-connection",
66 "te",
67 "trailer",
68 "transfer-encoding",
69 "upgrade",
70];
71
72pub enum LoadBalancing {
74 RoundRobin,
76}
77
78pub struct ReverseProxy {
93 backends: Vec<Backend>,
94 path_prefix: Option<String>,
95 connect_timeout: Duration,
96 read_timeout: Duration,
97 counter: AtomicUsize,
98 pool: Arc<ConnPool>,
99 breaker: Option<Arc<dyn crate::circuit_breaker::Breaker>>,
100 trust: Option<Arc<UpstreamTls>>,
101 tls_ca: Option<String>,
103 tls_client: Option<(String, String)>,
104}
105
106impl ReverseProxy {
107 pub fn new<I, S>(backends: I) -> Self
111 where
112 I: IntoIterator<Item = S>,
113 S: AsRef<str>,
114 {
115 Self {
116 backends: backends
117 .into_iter()
118 .filter_map(|u| Backend::parse(u.as_ref()))
119 .collect(),
120 path_prefix: None,
121 connect_timeout: Duration::from_secs(5),
122 read_timeout: Duration::from_secs(30),
123 counter: AtomicUsize::new(0),
124 pool: Arc::new(ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60))),
125 breaker: None,
126 trust: None,
127 tls_ca: None,
128 tls_client: None,
129 }
130 }
131
132 pub fn with_circuit_breaker(mut self, breaker: Arc<dyn crate::circuit_breaker::Breaker>) -> Self {
150 self.breaker = Some(breaker);
151 self
152 }
153
154 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
159 self.path_prefix = Some(prefix.into());
160 self
161 }
162
163 pub fn strategy(self, _strategy: LoadBalancing) -> Self {
165 self
166 }
167
168 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
170 self.connect_timeout = Duration::from_millis(ms);
171 self
172 }
173
174 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
176 self.read_timeout = Duration::from_millis(ms);
177 self
178 }
179
180 pub fn with_pool(mut self, pool: Arc<ConnPool>) -> Self {
185 self.pool = pool;
186 self
187 }
188
189 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
193 self.tls_ca = Some(path.to_string());
194 self.rebuild_trust()?;
195 Ok(self)
196 }
197
198 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
202 self.tls_client = Some((cert.to_string(), key.to_string()));
203 self.rebuild_trust()?;
204 Ok(self)
205 }
206
207 fn rebuild_trust(&mut self) -> Result<(), String> {
208 let client = self.tls_client.as_ref().map(|(c, k)| (c.as_str(), k.as_str()));
209 self.trust = Some(Arc::new(UpstreamTls::new(self.tls_ca.as_deref(), client)?));
210 Ok(())
211 }
212
213 pub fn max_idle_conns(mut self, n: usize) -> Self {
215 self.pool = Arc::new(ConnPool::new(n, Duration::from_secs(60)));
216 self
217 }
218
219 fn proxy(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
220 if self.backends.is_empty() {
221 return Err("no backends configured".to_string());
222 }
223 let n = self.backends.len();
224 let start = self.counter.fetch_add(1, Ordering::Relaxed);
225 let mut last_err = "all backends failed".to_string();
226 for attempt in 0..n {
227 let idx = (start + attempt) % n;
228 let backend = &self.backends[idx];
229 let key = format!("{}:{}", backend.host, backend.port);
230
231 if let Some(breaker) = &self.breaker {
232 if !breaker.is_available(&key) {
233 last_err = format!("circuit open for {}", key);
234 continue;
235 }
236 }
237
238 match self.try_backend(request, connection, backend) {
239 Ok(resp) => {
240 if let Some(breaker) = &self.breaker {
241 breaker.record_success(&key);
242 }
243 return Ok(resp);
244 }
245 Err(e) => {
246 if let Some(breaker) = &self.breaker {
247 breaker.record_failure(&key);
248 }
249 last_err = e;
250 }
251 }
252 }
253 Err(last_err)
254 }
255
256 fn try_backend(
257 &self,
258 request: &Request,
259 connection: &ConnectionInfo,
260 backend: &Backend,
261 ) -> Result<Response, String> {
262 forward_upstream_trusting(
263 &self.pool,
264 request,
265 &connection.client.ip,
266 &backend.host,
267 backend.port,
268 backend.tls,
269 self.trust.as_deref(),
270 self.connect_timeout,
271 self.read_timeout,
272 )
273 }
274}
275
276impl Middleware for ReverseProxy {
277 fn handle(
278 &self,
279 request: &Request,
280 connection: &ConnectionInfo,
281 next: &dyn Application,
282 ) -> Result<Response, String> {
283 if let Some(prefix) = &self.path_prefix {
284 if !request.request_uri.starts_with(prefix.as_str()) {
285 return next.execute(request, connection);
286 }
287 }
288 match self.proxy(request, connection) {
289 Ok(resp) => Ok(resp),
290 Err(_) => Ok(bad_gateway()),
291 }
292 }
293}
294
295pub(crate) fn build_request(
298 request: &Request,
299 backend_host: &str,
300 client_ip: &str,
301 keep_alive: bool,
302) -> Vec<u8> {
303 let connection = request.header(crate::header::Header::_CONNECTION).map(|h| h.value.as_ref());
309 #[cfg(not(target_arch = "wasm32"))]
312 let trace = crate::otel::propagation_headers();
313 #[cfg(target_arch = "wasm32")]
314 let trace: Option<(String, Option<String>)> = None;
315 let forwarded = |h: &&crate::header::Header| {
316 !h.name.is_empty()
318 && !is_hop_by_hop_or_host(&h.name)
319 && !h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_LENGTH)
320 && !h.name.eq_ignore_ascii_case("X-Forwarded-For")
321 && !connection.is_some_and(|c| connection_listed(c, &h.name))
322 && !(trace.is_some() && (h.name.eq_ignore_ascii_case("traceparent") || h.name.eq_ignore_ascii_case("baggage")))
323 };
324 let prior_xff = request.header("X-Forwarded-For").map(|h| h.value.as_ref()).filter(|v| !v.trim().is_empty());
325 let body_len = Decimal::new(request.body.len() as u128);
326 let capacity = request.method.len() + request.request_uri.len() + backend_host.len() + 25
327 + request.headers.iter().filter(forwarded).map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
328 + client_ip.len() + 19 + prior_xff.map_or(0, |v| v.len() + 2)
329 + trace.as_ref().map_or(0, |(t, b)| t.len() + 15 + b.as_ref().map_or(0, |b| b.len() + 11))
330 + 13
331 + 24
332 + if request.body.is_empty() { 0 } else { body_len.as_str().len() + 18 }
333 + 2
334 + request.body.len();
335 let mut out: Vec<u8> = Vec::with_capacity(capacity);
336 for part in [request.method.as_str(), " ", request.request_uri.as_str(), " HTTP/1.1\r\nHost: ", backend_host, "\r\n"] {
337 out.extend_from_slice(part.as_bytes());
338 }
339 for h in request.headers.iter().filter(forwarded) {
340 for part in [h.name.as_ref(), ": ", h.value.as_ref(), "\r\n"] {
341 out.extend_from_slice(part.as_bytes());
342 }
343 }
344 out.extend_from_slice(b"X-Forwarded-For: ");
345 if let Some(prior) = prior_xff {
346 out.extend_from_slice(prior.as_bytes());
347 out.extend_from_slice(b", ");
348 }
349 for part in [client_ip, "\r\n", "Via: 1.1 rws\r\n"] {
350 out.extend_from_slice(part.as_bytes());
351 }
352 if let Some((traceparent, baggage)) = &trace {
353 for part in ["traceparent: ", traceparent, "\r\n"] {
354 out.extend_from_slice(part.as_bytes());
355 }
356 if let Some(baggage) = baggage {
357 for part in ["baggage: ", baggage, "\r\n"] {
358 out.extend_from_slice(part.as_bytes());
359 }
360 }
361 }
362 if keep_alive {
363 out.extend_from_slice(b"Connection: keep-alive\r\n");
364 } else {
365 out.extend_from_slice(b"Connection: close\r\n");
366 }
367 if !request.body.is_empty() {
368 out.extend_from_slice(b"Content-Length: ");
369 out.extend_from_slice(body_len.as_str().as_bytes());
370 out.extend_from_slice(b"\r\n");
371 }
372 out.extend_from_slice(b"\r\n");
373 out.extend_from_slice(&request.body);
374 out
375}
376
377fn is_hop_by_hop_or_host(name: &str) -> bool {
382 if name.is_ascii() {
383 name.eq_ignore_ascii_case("host") || HOP_BY_HOP.iter().any(|h| name.eq_ignore_ascii_case(h))
384 } else {
385 let lower = name.to_lowercase();
386 lower == "host" || HOP_BY_HOP.contains(&lower.as_str())
387 }
388}
389
390fn connection_listed(connection: &str, name: &str) -> bool {
393 connection.split(',').any(|token| token.trim().eq_ignore_ascii_case(name))
394}
395
396fn decode_chunked<S: Read>(
401 stream: &mut S,
402 buf: &[u8],
403 header_end: usize,
404 tmp: &mut [u8],
405) -> Result<Vec<u8>, String> {
406 let mut raw: Vec<u8> = buf[header_end..].to_vec();
408 let mut decoded: Vec<u8> = Vec::new();
409
410 loop {
411 let crlf = loop {
413 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
414 break p;
415 }
416 let n = stream.read(tmp).map_err(|e| e.to_string())?;
417 if n == 0 {
418 return Err("chunked: premature EOF reading chunk size".to_string());
419 }
420 raw.extend_from_slice(&tmp[..n]);
421 };
422
423 let size_line = std::str::from_utf8(&raw[..crlf])
425 .map_err(|_| "chunked: non-UTF-8 chunk size line".to_string())?;
426 let size_str = size_line.split(';').next().unwrap_or("").trim();
427 let chunk_size = usize::from_str_radix(size_str, 16)
428 .map_err(|_| format!("chunked: invalid chunk size '{}'", size_str))?;
429 raw.drain(..crlf + 2); if chunk_size == 0 {
432 loop {
436 let line_end = loop {
437 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
438 break p;
439 }
440 let n = stream.read(tmp).map_err(|e| e.to_string())?;
441 if n == 0 {
442 return Err("chunked: premature EOF in trailer".to_string());
443 }
444 raw.extend_from_slice(&tmp[..n]);
445 };
446 raw.drain(..line_end + 2);
447 if line_end == 0 {
448 break;
449 }
450 }
451 break;
452 }
453
454 while raw.len() < chunk_size + 2 {
456 let n = stream.read(tmp).map_err(|e| e.to_string())?;
457 if n == 0 {
458 return Err("chunked: premature EOF reading chunk body".to_string());
459 }
460 raw.extend_from_slice(&tmp[..n]);
461 }
462 decoded.extend_from_slice(&raw[..chunk_size]);
463 raw.drain(..chunk_size + 2); }
465
466 Ok(decoded)
467}
468
469fn rewrite_as_content_length(buf: &mut Vec<u8>, header_end: usize, decoded: &[u8]) {
472 let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_string();
473 buf.clear();
474 for line in header_str.lines() {
475 if line.to_ascii_lowercase().starts_with("transfer-encoding:") || line.is_empty() {
476 continue;
477 }
478 buf.extend_from_slice(line.as_bytes());
479 buf.extend_from_slice(b"\r\n");
480 }
481 let _ = write!(buf, "Content-Length: {}\r\n\r\n", decoded.len());
482 buf.extend_from_slice(decoded);
483}
484
485pub(crate) const REGENERATED_OR_HOP_BY_HOP: &[&str] = &[
488 "content-length", "transfer-encoding", "connection", "keep-alive",
489 "proxy-connection", "te", "trailer", "upgrade",
490];
491
492#[cfg_attr(not(feature = "http2"), allow(dead_code))]
501pub(crate) fn normalize_upstream_response(mut response: Response) -> Response {
502 response.http_version.clear();
503 response.http_version.push_str(crate::http::VERSION.http_1_1);
504 let has_body = !response.content_range_list.is_empty();
505 if let [range] = response.content_range_list.as_mut_slice() {
506 if let Some(h) = response
507 .headers
508 .iter()
509 .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
510 {
511 range.content_type.clear();
512 range.content_type.push_str(&h.value);
513 }
514 }
515 response.headers.retain(|h| {
518 if h.name.eq_ignore_ascii_case("content-type") {
519 return !has_body;
521 }
522 !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
523 });
524 response
525}
526
527pub(crate) fn bad_gateway() -> Response {
528 let cr = Range::get_content_range(
529 b"502 Bad Gateway".to_vec(),
530 MimeType::TEXT_PLAIN.to_string(),
531 );
532 let mut r = Response::new();
533 r.status_code = *STATUS_CODE_REASON_PHRASE.n502_bad_gateway.status_code;
534 r.reason_phrase = STATUS_CODE_REASON_PHRASE
535 .n502_bad_gateway
536 .reason_phrase
537 .to_string();
538 r.content_range_list = vec![cr];
539 r
540}
541
542const STREAM_THRESHOLD: usize = 1024 * 1024; pub(crate) struct ConcatReader<R: Read + Send> {
550 prefix: Vec<u8>,
551 prefix_pos: usize,
552 inner: R,
553}
554
555impl<R: Read + Send> ConcatReader<R> {
556 fn new(prefix: Vec<u8>, inner: R) -> Self {
557 ConcatReader { prefix, prefix_pos: 0, inner }
558 }
559}
560
561impl<R: Read + Send> Read for ConcatReader<R> {
562 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
563 if self.prefix_pos < self.prefix.len() {
564 let avail = &self.prefix[self.prefix_pos..];
565 let n = buf.len().min(avail.len());
566 buf[..n].copy_from_slice(&avail[..n]);
567 self.prefix_pos += n;
568 return Ok(n);
569 }
570 self.inner.read(buf)
571 }
572}
573
574
575pub(crate) const POOL_MAX_IDLE: usize = 64;
579
580pub(crate) fn shared_pool() -> &'static ConnPool {
583 static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
584 POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
585}
586
587pub(crate) trait UpstreamIo: Read + Write + Send + 'static {
590 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
591}
592
593impl UpstreamIo for TcpStream {
594 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
595 self.set_read_timeout(Some(read))?;
596 self.set_write_timeout(Some(write))
597 }
598}
599
600#[cfg(any(feature = "http-client", feature = "http2"))]
601pub(crate) type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
602
603#[cfg(any(feature = "http-client", feature = "http2"))]
604impl UpstreamIo for TlsStream {
605 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
606 self.sock.set_io_timeouts(read, write)
607 }
608}
609
610pub(crate) fn forward_upstream(
616 plain_pool: &ConnPool,
617 request: &Request,
618 client_ip: &str,
619 host: &str,
620 port: u16,
621 tls: bool,
622 connect_timeout: Duration,
623 read_timeout: Duration,
624) -> Result<Response, String> {
625 forward_upstream_trusting(plain_pool, request, client_ip, host, port, tls, None, connect_timeout, read_timeout)
626}
627
628#[allow(clippy::too_many_arguments)]
631pub(crate) fn forward_upstream_trusting(
632 plain_pool: &ConnPool,
633 request: &Request,
634 client_ip: &str,
635 host: &str,
636 port: u16,
637 tls: bool,
638 trust: Option<&UpstreamTls>,
639 connect_timeout: Duration,
640 read_timeout: Duration,
641) -> Result<Response, String> {
642 #[cfg(not(target_arch = "wasm32"))]
645 let span = crate::otel::outbound_span(&request.method);
646 #[cfg(not(target_arch = "wasm32"))]
647 if let Some(span) = &span {
648 let scheme = if tls { "https" } else { "http" };
649 let path = request.request_uri.as_str();
650 for (key, value) in crate::otel::http_client_attributes(&request.method, &format!("{scheme}://{host}:{port}{path}")) {
651 span.set_attribute(key, value);
652 }
653 }
654 let result = forward_upstream_untraced(plain_pool, request, client_ip, host, port, tls, trust, connect_timeout, read_timeout);
655 #[cfg(not(target_arch = "wasm32"))]
656 if let Some(span) = &span {
657 span.finish_http_client(result.as_ref().map(|r| r.status_code as u16).map_err(String::as_str));
658 }
659 result
660}
661
662#[allow(clippy::too_many_arguments)]
663fn forward_upstream_untraced(
664 plain_pool: &ConnPool,
665 request: &Request,
666 client_ip: &str,
667 host: &str,
668 port: u16,
669 tls: bool,
670 trust: Option<&UpstreamTls>,
671 connect_timeout: Duration,
672 read_timeout: Duration,
673) -> Result<Response, String> {
674 if tls {
675 #[cfg(any(feature = "http-client", feature = "http2"))]
676 {
677 let (pool, config) = match trust {
678 Some(t) => (t.pool, Arc::clone(&t.config)),
679 None => (shared_tls_pool(), tls_client_config()),
680 };
681 return forward_via(pool, request, client_ip, host, port, host, read_timeout, || {
682 connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
683 });
684 }
685 #[cfg(not(any(feature = "http-client", feature = "http2")))]
686 {
687 let _ = trust;
688 return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
689 }
690 }
691 forward_pooled(plain_pool, request, client_ip, host, port, connect_timeout, read_timeout)
692}
693
694pub struct UpstreamTls {
702 #[cfg(any(feature = "http-client", feature = "http2"))]
703 config: Arc<rustls::ClientConfig>,
704 #[cfg(any(feature = "http-client", feature = "http2"))]
705 pool: &'static Pool<TlsStream>,
706 #[cfg(feature = "http2")]
708 async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
709 #[cfg(feature = "http2")]
711 h2_config: Arc<rustls::ClientConfig>,
712}
713
714impl UpstreamTls {
715 pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
717 UpstreamTls::new(Some(path), None)
718 }
719
720 pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
724 #[cfg(any(feature = "http-client", feature = "http2"))]
725 {
726 use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
727 let roots = match ca_file {
728 Some(path) => {
729 let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
730 let certs = CertificateDer::pem_slice_iter(&bytes)
731 .collect::<Result<Vec<_>, _>>()
732 .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
733 if certs.is_empty() {
734 return Err(format!("no certificates in CA file '{path}'"));
735 }
736 let mut roots = rustls::RootCertStore::empty();
737 for cert in certs {
738 roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
739 }
740 roots
741 }
742 None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
743 };
744 let builder = crate::tls_client_builder().with_root_certificates(roots);
745 let config = match client_cert {
746 None => builder.with_no_client_auth(),
747 Some((cert_path, key_path)) => {
748 let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
749 let chain = CertificateDer::pem_slice_iter(&bytes)
750 .collect::<Result<Vec<_>, _>>()
751 .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
752 if chain.is_empty() {
753 return Err(format!("no certificate in '{cert_path}'"));
754 }
755 let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
756 let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
757 builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
758 }
759 };
760 let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
761 Ok(UpstreamTls::with_config(config, &label))
762 }
763 #[cfg(not(any(feature = "http-client", feature = "http2")))]
764 {
765 let _ = client_cert;
766 Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
767 }
768 }
769
770 #[cfg(any(feature = "http-client", feature = "http2"))]
771 fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
772 #[cfg(feature = "http2")]
773 let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
774 UpstreamTls {
775 config: Arc::new(config),
776 pool: tls_pool_for_ca(label),
777 #[cfg(feature = "http2")]
778 async_pool: async_tls_pool_for_ca(label),
779 #[cfg(feature = "http2")]
780 h2_config,
781 }
782 }
783
784 #[cfg(feature = "http2")]
786 pub(crate) fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
787 &self.h2_config
788 }
789
790 pub(crate) fn reject_all(label: &str) -> UpstreamTls {
794 #[cfg(any(feature = "http-client", feature = "http2"))]
795 {
796 let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
797 UpstreamTls::with_config(config, &format!("reject-all:{label}"))
798 }
799 #[cfg(not(any(feature = "http-client", feature = "http2")))]
800 {
801 let _ = label;
802 UpstreamTls {}
803 }
804 }
805
806 #[cfg(feature = "http2")]
808 pub(crate) fn async_tls(&self) -> async_upstream::AsyncTls {
809 async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
810 }
811
812 #[cfg(any(feature = "http-client", feature = "http2"))]
814 pub(crate) fn client_config(&self) -> Arc<rustls::ClientConfig> {
815 Arc::clone(&self.config)
816 }
817}
818
819#[cfg(feature = "http2")]
822fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
823 static POOLS: std::sync::OnceLock<
824 std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
825 > = std::sync::OnceLock::new();
826 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
827 pools
828 .entry(path.to_string())
829 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
830}
831
832#[cfg(any(feature = "http-client", feature = "http2"))]
834fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
835 static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
836 std::sync::OnceLock::new();
837 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
838 pools
839 .entry(path.to_string())
840 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
841}
842
843pub(crate) fn forward_pooled(
847 pool: &ConnPool,
848 request: &Request,
849 client_ip: &str,
850 host: &str,
851 port: u16,
852 connect_timeout: Duration,
853 read_timeout: Duration,
854) -> Result<Response, String> {
855 forward_via(pool, request, client_ip, host, port, host, read_timeout, || connect_tcp(host, port, connect_timeout))
856}
857
858#[cfg(feature = "gateway-api")]
861#[allow(clippy::too_many_arguments)]
862pub(crate) fn forward_pooled_with_host(
863 pool: &ConnPool,
864 request: &Request,
865 client_ip: &str,
866 host: &str,
867 port: u16,
868 host_header: &str,
869 connect_timeout: Duration,
870 read_timeout: Duration,
871) -> Result<Response, String> {
872 forward_via(pool, request, client_ip, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
873}
874
875#[allow(clippy::too_many_arguments)]
882fn forward_via<S: UpstreamIo>(
883 pool: &Pool<S>,
884 request: &Request,
885 client_ip: &str,
886 host: &str,
887 port: u16,
888 host_header: &str,
889 read_timeout: Duration,
890 connect: impl Fn() -> Result<S, String>,
891) -> Result<Response, String> {
892 let key = format!("{}:{}", host, port);
893 if let Some(stream) = pool.acquire(&key) {
894 match exchange(pool, &key, stream, request, host_header, client_ip, read_timeout) {
895 Exchange::Done(response) => return Ok(response),
896 Exchange::NoResponse(_) if is_idempotent(&request.method) => {} Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
898 }
899 }
900 let stream = connect()?;
901 match exchange(pool, &key, stream, request, host_header, client_ip, read_timeout) {
902 Exchange::Done(response) => Ok(response),
903 Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
904 }
905}
906
907fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
911 let key = format!("{}:{}", host, port);
912 let addrs: Vec<_> = key
913 .to_socket_addrs()
914 .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
915 .collect();
916 let mut last_error = format!("no address resolved for {}", key);
917 for addr in addrs {
918 match TcpStream::connect_timeout(&addr, connect_timeout) {
919 Ok(stream) => {
920 let _ = stream.set_nodelay(true);
921 return Ok(stream);
922 }
923 Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
924 }
925 }
926 Err(last_error)
927}
928
929#[cfg(any(feature = "http-client", feature = "http2"))]
931fn shared_tls_pool() -> &'static Pool<TlsStream> {
932 static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
933 POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
934}
935
936#[cfg(any(feature = "http-client", feature = "http2"))]
940pub(crate) fn tls_client_config() -> Arc<rustls::ClientConfig> {
941 static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
942 Arc::clone(CONFIG.get_or_init(|| {
943 let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
944 Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
945 }))
946}
947
948#[cfg(any(feature = "http-client", feature = "http2"))]
949fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
950 let tcp = connect_tcp(host, port, connect_timeout)?;
951 let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
952 .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
953 let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
954 Ok(rustls::StreamOwned::new(conn, tcp))
955}
956
957fn is_idempotent(method: &str) -> bool {
958 matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
959}
960
961enum Exchange {
962 Done(Response),
963 NoResponse(String),
965 Failed(String),
966}
967
968fn exchange<S: UpstreamIo>(
971 pool: &Pool<S>,
972 key: &str,
973 mut stream: S,
974 request: &Request,
975 host: &str,
976 client_ip: &str,
977 read_timeout: Duration,
978) -> Exchange {
979 if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
980 return Exchange::Failed(e.to_string());
981 }
982 let req_bytes = build_request(request, host, client_ip, true);
984 if let Err(e) = stream.write_all(&req_bytes) {
985 return Exchange::NoResponse(format!("write to backend failed: {}", e));
986 }
987
988 let mut tmp = [0u8; 4096];
989 let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
990 Ok(head) => head,
991 Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
992 Err(HeadError::Partial(e)) => return Exchange::Failed(e),
993 };
994 let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
995
996 if response_has_no_body(&request.method, &header_lower) {
997 if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
998 pool.release(key, stream);
999 }
1000 return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
1001 Ok(response) => Exchange::Done(response),
1002 Err(e) => Exchange::Failed(e),
1003 };
1004 }
1005
1006 if should_stream_response(&header_lower) {
1007 return match parse_status_and_headers(&header_bytes) {
1010 Ok(mut response) => {
1011 response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
1012 Exchange::Done(response)
1013 }
1014 Err(e) => Exchange::Failed(e),
1015 };
1016 }
1017 match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
1019 Ok((resp_bytes, reusable)) => {
1020 if reusable {
1021 pool.release(key, stream);
1022 }
1023 match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
1024 Ok(response) => Exchange::Done(response),
1025 Err(e) => Exchange::Failed(e),
1026 }
1027 }
1028 Err(e) => Exchange::Failed(e),
1029 }
1030}
1031
1032#[cfg(test)]
1037fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
1038 read_response_head(stream, tmp).map_err(|e| match e {
1039 HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
1040 })
1041}
1042
1043enum HeadError {
1047 NothingReceived(String),
1048 Partial(String),
1049}
1050
1051fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1052 read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
1053}
1054
1055fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1060 let (mut head, mut rest) = read_response_head(stream, tmp)?;
1061 let mut interim = 0;
1062 while is_interim_response(&head) {
1063 interim += 1;
1064 if interim > MAX_INTERIM_RESPONSES {
1065 return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
1066 }
1067 (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
1068 }
1069 Ok((head, rest))
1070}
1071
1072fn read_response_head_from<S: Read>(
1076 stream: &mut S,
1077 tmp: &mut [u8],
1078 mut buf: Vec<u8>,
1079 received: bool,
1080) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1081 loop {
1082 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1083 let body_prefix = buf[pos + 4..].to_vec();
1084 buf.truncate(pos + 4);
1085 return Ok((buf, body_prefix));
1086 }
1087 let nothing = buf.is_empty() && !received;
1088 let n = match stream.read(tmp) {
1089 Ok(n) => n,
1090 Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1091 Err(e) => return Err(HeadError::Partial(e.to_string())),
1092 };
1093 if n == 0 {
1094 let msg = "backend closed connection before headers were complete".to_string();
1095 return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1096 }
1097 buf.extend_from_slice(&tmp[..n]);
1098 }
1099}
1100
1101pub(crate) const MAX_INTERIM_RESPONSES: usize = 16;
1103
1104pub(crate) fn is_interim_response(head: &[u8]) -> bool {
1107 let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1108 let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1109 status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1110}
1111
1112pub(crate) fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1116 let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1117 method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1118}
1119
1120pub(crate) fn should_stream_response(header_lower: &str) -> bool {
1127 let is_sse = header_lower.lines().any(|l| {
1128 l.starts_with("content-type:") && l.contains("text/event-stream")
1129 });
1130 let is_chunked = header_lower.lines().any(|l| {
1131 l.starts_with("transfer-encoding:") && l.contains("chunked")
1132 });
1133 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1134 l.strip_prefix("content-length:")?.trim().parse().ok()
1135 });
1136 let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1137 is_sse || is_chunked || is_large
1138}
1139
1140#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1146pub(crate) struct HeadFacts {
1147 pub(crate) status_no_body: bool,
1149 pub(crate) sse: bool,
1150 pub(crate) chunked: bool,
1151 pub(crate) content_length: Option<usize>,
1153 pub(crate) connection_close: bool,
1154}
1155
1156#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1157impl HeadFacts {
1158 pub(crate) fn scan(head: &[u8]) -> HeadFacts {
1159 let text = std::str::from_utf8(head).unwrap_or("");
1160 let status = text.split_whitespace().nth(1).unwrap_or("");
1161 let mut facts = HeadFacts {
1162 status_no_body: status.starts_with('1') || status == "204" || status == "304",
1163 sse: false,
1164 chunked: false,
1165 content_length: None,
1166 connection_close: false,
1167 };
1168 for line in text.lines() {
1169 if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1170 facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1171 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1172 facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1173 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1174 if facts.content_length.is_none() {
1175 facts.content_length = value.trim().parse().ok();
1176 }
1177 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1178 facts.connection_close |= contains_ignore_ascii_case(value, "close");
1179 }
1180 }
1181 facts
1182 }
1183
1184 pub(crate) fn no_body(&self, method: &str) -> bool {
1186 method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1187 }
1188
1189 pub(crate) fn should_stream(&self) -> bool {
1191 self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1192 }
1193}
1194
1195fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1196 let bytes = line.as_bytes();
1197 (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1199 .then(|| &line[prefix.len()..])
1200}
1201
1202fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1203 haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1204}
1205
1206fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1208 let s = std::str::from_utf8(header_bytes)
1209 .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1210 let mut lines = s.lines();
1211 let status_line = lines.next().ok_or("empty backend response")?;
1212 let mut parts = status_line.splitn(3, ' ');
1213 let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1214 let status_code: i16 = parts
1215 .next()
1216 .unwrap_or("502")
1217 .parse()
1218 .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1219 let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1220 let mut headers = Vec::new();
1221 for line in lines {
1222 let line = line.trim_end_matches('\r');
1223 if line.is_empty() { break; }
1224 if let Some(colon) = line.find(':') {
1225 headers.push(crate::header::Header {
1226 name: line[..colon].trim().to_string().into(),
1227 value: (line[colon + 1..].trim().to_string()).into(),
1228 });
1229 }
1230 }
1231 Ok(Response {
1232 http_version,
1233 status_code,
1234 reason_phrase,
1235 headers,
1236 content_range_list: vec![],
1237 stream_file: None,
1238 stream_pipe: None,
1239 trailers: None,
1240 })
1241}
1242
1243fn read_response_from_partial<S: Read>(
1249 stream: &mut S,
1250 header_bytes: Vec<u8>,
1251 body_prefix: Vec<u8>,
1252 tmp: &mut [u8],
1253) -> Result<(Vec<u8>, bool), String> {
1254 let header_end = header_bytes.len();
1255 let mut buf = header_bytes;
1256 buf.extend_from_slice(&body_prefix);
1257
1258 let header_lower =
1259 std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1260 let connection_close =
1261 header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1262 let is_chunked = header_lower
1263 .lines()
1264 .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1265 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1266 l.strip_prefix("content-length:")?.trim().parse().ok()
1267 });
1268
1269 if is_chunked {
1270 let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1271 rewrite_as_content_length(&mut buf, header_end, &decoded);
1272 Ok((buf, !connection_close))
1273 } else if let Some(len) = content_length {
1274 while buf.len() < header_end + len {
1275 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1276 if n == 0 { break; }
1277 buf.extend_from_slice(&tmp[..n]);
1278 }
1279 Ok((buf, !connection_close))
1280 } else {
1281 loop {
1282 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1283 if n == 0 { break; }
1284 buf.extend_from_slice(&tmp[..n]);
1285 }
1286 Ok((buf, false))
1287 }
1288}
1289
1290struct Backend {
1293 host: String,
1294 port: u16,
1295 tls: bool,
1298}
1299
1300impl Backend {
1301 fn parse(url: &str) -> Option<Self> {
1302 let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1303 (r, true, 443u16)
1304 } else if let Some(r) = url.strip_prefix("h2s://") {
1305 (r, true, 443u16)
1306 } else if let Some(r) = url.strip_prefix("grpcs://") {
1307 (r, true, 443u16)
1308 } else if let Some(r) = url.strip_prefix("http://") {
1309 (r, false, 80u16)
1310 } else if let Some(r) = url.strip_prefix("h2://") {
1311 (r, false, 80u16)
1312 } else if let Some(r) = url.strip_prefix("grpc://") {
1313 (r, false, 80u16)
1314 } else {
1315 (url, false, 80u16)
1316 };
1317 let host_port = rest.split('/').next().unwrap_or(rest);
1319 let (host, port) = if let Some(colon) = host_port.rfind(':') {
1320 let port_str = &host_port[colon + 1..];
1321 if let Ok(p) = port_str.parse::<u16>() {
1322 (host_port[..colon].to_string(), p)
1323 } else {
1324 (host_port.to_string(), default_port)
1325 }
1326 } else {
1327 (host_port.to_string(), default_port)
1328 };
1329 if host.is_empty() {
1330 return None;
1331 }
1332 Some(Backend { host, port, tls })
1333 }
1334}
1335
1336#[cfg(feature = "http2")]
1347pub struct H2ReverseProxy {
1348 inner: ReverseProxy,
1349}
1350
1351#[cfg(feature = "http2")]
1352impl H2ReverseProxy {
1353 pub fn new<I, S>(backends: I) -> Self
1364 where
1365 I: IntoIterator<Item = S>,
1366 S: AsRef<str>,
1367 {
1368 H2ReverseProxy {
1369 inner: ReverseProxy::new(backends),
1370 }
1371 }
1372
1373 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1375 self.inner = self.inner.path_prefix(prefix);
1376 self
1377 }
1378
1379 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1381 self.inner = self.inner.connect_timeout_ms(ms);
1382 self
1383 }
1384
1385 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1390 self.inner = self.inner.read_timeout_ms(ms);
1391 self
1392 }
1393
1394 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1397 self.inner = self.inner.tls_ca_file(path)?;
1398 Ok(self)
1399 }
1400
1401 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1404 self.inner = self.inner.tls_client_cert(cert, key)?;
1405 Ok(self)
1406 }
1407
1408 fn matches(&self, request: &Request) -> bool {
1409 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1410 }
1411}
1412
1413#[cfg(feature = "http2")]
1414impl crate::middleware::Middleware for H2ReverseProxy {
1415 fn handle(
1416 &self,
1417 request: &crate::request::Request,
1418 connection: &crate::server::ConnectionInfo,
1419 next: &dyn crate::application::Application,
1420 ) -> Result<crate::response::Response, String> {
1421 if !self.matches(request) {
1422 return next.execute(request, connection);
1423 }
1424 if self.inner.backends.is_empty() {
1425 return Ok(bad_gateway());
1426 }
1427 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1429 let n = self.inner.backends.len();
1430 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1431 for attempt in 0..attempts {
1432 let backend = &self.inner.backends[(start + attempt) % n];
1433 let tls = backend.tls.then(|| match &self.inner.trust {
1434 Some(trust) => trust.h2_config(),
1435 None => h2_upstream::default_tls(),
1436 });
1437 let target = h2_upstream::Target {
1438 backend,
1439 tls,
1440 connect_timeout: self.inner.connect_timeout,
1441 read_timeout: self.inner.read_timeout,
1442 authority: None,
1443 };
1444 if let Ok(response) = h2_upstream::forward(request, &connection.client.ip, &target) {
1445 return Ok(response);
1446 }
1447 }
1448 Ok(bad_gateway())
1449 }
1450
1451 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1454 true
1455 }
1456
1457 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1460 self.matches(request)
1461 }
1462}
1463
1464#[cfg(feature = "http2")]
1468pub(crate) fn forward_h2(
1469 request: &Request,
1470 client_ip: &str,
1471 url: &str,
1472 tls: bool,
1473 trust: Option<&UpstreamTls>,
1474 connect_timeout: Duration,
1475 read_timeout: Duration,
1476) -> Result<Response, String> {
1477 let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1478 backend.tls |= tls;
1479 let tls = backend.tls.then(|| match trust {
1480 Some(t) => t.h2_config(),
1481 None => h2_upstream::default_tls(),
1482 });
1483 h2_upstream::forward(request, client_ip, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout, authority: None })
1484}
1485
1486#[cfg(feature = "gateway-api")]
1491#[allow(clippy::too_many_arguments)]
1492pub(crate) fn forward_tls_with_host(
1493 config: &Arc<rustls::ClientConfig>,
1494 label: &str,
1495 request: &Request,
1496 client_ip: &str,
1497 ip: &str,
1498 port: u16,
1499 server_name: &str,
1500 host_header: &str,
1501 connect_timeout: Duration,
1502 read_timeout: Duration,
1503) -> Result<Response, String> {
1504 let pool = tls_pool_for_ca(label);
1505 forward_via(pool, request, client_ip, ip, port, host_header, read_timeout, || {
1506 let tcp = connect_tcp(ip, port, connect_timeout)?;
1507 let name = rustls::pki_types::ServerName::try_from(server_name.to_string()).map_err(|e| format!("invalid TLS server name '{server_name}': {e}"))?;
1508 let conn = rustls::ClientConnection::new(Arc::clone(config), name).map_err(|e| e.to_string())?;
1509 Ok(rustls::StreamOwned::new(conn, tcp))
1510 })
1511}
1512
1513#[cfg(feature = "gateway-api")]
1517pub(crate) fn forward_h2c_with_host(
1518 request: &Request,
1519 client_ip: &str,
1520 host: &str,
1521 port: u16,
1522 authority: &str,
1523 connect_timeout: Duration,
1524 read_timeout: Duration,
1525) -> Result<Response, String> {
1526 let backend = Backend { host: host.to_string(), port, tls: false };
1527 h2_upstream::forward(request, client_ip, &h2_upstream::Target { backend: &backend, tls: None, connect_timeout, read_timeout, authority: Some(authority) })
1528}
1529
1530#[cfg(feature = "http2")]
1550pub struct GrpcProxy {
1551 inner: H2ReverseProxy,
1552}
1553
1554#[cfg(feature = "http2")]
1555impl GrpcProxy {
1556 pub fn new<I, S>(backends: I) -> Self
1566 where
1567 I: IntoIterator<Item = S>,
1568 S: AsRef<str>,
1569 {
1570 GrpcProxy { inner: H2ReverseProxy::new(backends) }
1571 }
1572
1573 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1575 self.inner = self.inner.path_prefix(prefix);
1576 self
1577 }
1578
1579 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1581 self.inner = self.inner.connect_timeout_ms(ms);
1582 self
1583 }
1584
1585 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1587 self.inner = self.inner.read_timeout_ms(ms);
1588 self
1589 }
1590
1591 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1593 self.inner = self.inner.tls_ca_file(path)?;
1594 Ok(self)
1595 }
1596
1597 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1600 self.inner = self.inner.tls_client_cert(cert, key)?;
1601 Ok(self)
1602 }
1603}
1604
1605#[cfg(feature = "http2")]
1606impl crate::middleware::Middleware for GrpcProxy {
1607 fn handle(
1608 &self,
1609 request: &crate::request::Request,
1610 connection: &crate::server::ConnectionInfo,
1611 next: &dyn crate::application::Application,
1612 ) -> Result<crate::response::Response, String> {
1613 if is_grpc(request) {
1614 self.inner.handle(request, connection, next)
1615 } else {
1616 next.execute(request, connection)
1617 }
1618 }
1619
1620 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1621 true
1622 }
1623
1624 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1625 is_grpc(request) && self.inner.matches(request)
1626 }
1627}
1628
1629#[cfg(feature = "http2")]
1630fn is_grpc(request: &Request) -> bool {
1631 request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
1632}
1633
1634#[cfg(test)]
1637mod backend_parse_tests {
1638 use super::Backend;
1639
1640 fn parse(url: &str) -> Option<(String, u16, bool)> {
1641 Backend::parse(url).map(|b| (b.host, b.port, b.tls))
1642 }
1643
1644 #[test]
1645 fn bare_host_port() {
1646 assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
1647 }
1648
1649 #[test]
1650 fn http_scheme() {
1651 assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
1652 }
1653
1654 #[test]
1655 fn h2_scheme_plain() {
1656 assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
1657 }
1658
1659 #[test]
1660 fn grpc_scheme_plain() {
1661 assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
1662 }
1663
1664 #[test]
1665 fn https_scheme_sets_tls_and_default_port() {
1666 assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
1667 }
1668
1669 #[test]
1670 fn https_scheme_explicit_port() {
1671 assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
1672 }
1673
1674 #[test]
1675 fn h2s_scheme_sets_tls() {
1676 assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
1677 }
1678
1679 #[test]
1680 fn h2s_scheme_explicit_port() {
1681 assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
1682 }
1683
1684 #[test]
1685 fn grpcs_scheme_sets_tls() {
1686 assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
1687 }
1688
1689 #[test]
1690 fn grpcs_scheme_explicit_port() {
1691 assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
1692 }
1693
1694 #[test]
1695 fn empty_host_returns_none() {
1696 assert_eq!(None, parse("https://"));
1697 }
1698
1699 #[test]
1700 fn bare_host_no_port_defaults_to_80() {
1701 assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
1702 }
1703}