1pub mod pool;
27#[cfg(feature = "http2")]
28pub(crate) mod async_upstream;
29#[cfg(not(target_arch = "wasm32"))]
30pub mod mirror;
31#[cfg(feature = "http2")]
32pub(crate) mod h2_upstream;
33#[cfg(feature = "http2")]
34pub mod grpc_web;
35#[cfg(feature = "http2")]
36pub use grpc_web::GrpcWebLayer;
37
38#[cfg(test)]
39mod tests;
40
41use std::io::{Read, Write};
42use crate::ext::decimal::Decimal;
43use std::net::{TcpStream, ToSocketAddrs};
44use std::sync::atomic::{AtomicUsize, Ordering};
45use std::sync::Arc;
46use std::time::Duration;
47
48pub use pool::{ConnPool, Pool};
49
50use crate::application::Application;
51use crate::core::New;
52use crate::middleware::Middleware;
53use crate::mime_type::MimeType;
54use crate::range::Range;
55use crate::request::Request;
56use crate::response::{Response, STATUS_CODE_REASON_PHRASE};
57use crate::server::ConnectionInfo;
58
59const HOP_BY_HOP: &[&str] = &[
63 "connection",
64 "keep-alive",
65 "proxy-authenticate",
66 "proxy-authorization",
67 "proxy-connection",
68 "te",
69 "trailer",
70 "transfer-encoding",
71 "upgrade",
72];
73
74pub enum LoadBalancing {
76 RoundRobin,
78}
79
80pub struct ReverseProxy {
95 backends: Vec<Backend>,
96 path_prefix: Option<String>,
97 connect_timeout: Duration,
98 read_timeout: Duration,
99 counter: AtomicUsize,
100 pool: Arc<ConnPool>,
101 breaker: Option<Arc<dyn crate::circuit_breaker::Breaker>>,
102 trust: Option<Arc<UpstreamTls>>,
103 tls_ca: Option<String>,
105 tls_client: Option<(String, String)>,
106}
107
108impl ReverseProxy {
109 pub fn new<I, S>(backends: I) -> Self
113 where
114 I: IntoIterator<Item = S>,
115 S: AsRef<str>,
116 {
117 Self {
118 backends: backends
119 .into_iter()
120 .filter_map(|u| Backend::parse(u.as_ref()))
121 .collect(),
122 path_prefix: None,
123 connect_timeout: Duration::from_secs(5),
124 read_timeout: Duration::from_secs(30),
125 counter: AtomicUsize::new(0),
126 pool: Arc::new(ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60))),
127 breaker: None,
128 trust: None,
129 tls_ca: None,
130 tls_client: None,
131 }
132 }
133
134 pub fn with_circuit_breaker(mut self, breaker: Arc<dyn crate::circuit_breaker::Breaker>) -> Self {
152 self.breaker = Some(breaker);
153 self
154 }
155
156 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
161 self.path_prefix = Some(prefix.into());
162 self
163 }
164
165 pub fn strategy(self, _strategy: LoadBalancing) -> Self {
167 self
168 }
169
170 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
172 self.connect_timeout = Duration::from_millis(ms);
173 self
174 }
175
176 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
178 self.read_timeout = Duration::from_millis(ms);
179 self
180 }
181
182 pub fn with_pool(mut self, pool: Arc<ConnPool>) -> Self {
187 self.pool = pool;
188 self
189 }
190
191 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
195 self.tls_ca = Some(path.to_string());
196 self.rebuild_trust()?;
197 Ok(self)
198 }
199
200 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
204 self.tls_client = Some((cert.to_string(), key.to_string()));
205 self.rebuild_trust()?;
206 Ok(self)
207 }
208
209 fn rebuild_trust(&mut self) -> Result<(), String> {
210 let client = self.tls_client.as_ref().map(|(c, k)| (c.as_str(), k.as_str()));
211 self.trust = Some(Arc::new(UpstreamTls::new(self.tls_ca.as_deref(), client)?));
212 Ok(())
213 }
214
215 pub fn max_idle_conns(mut self, n: usize) -> Self {
217 self.pool = Arc::new(ConnPool::new(n, Duration::from_secs(60)));
218 self
219 }
220
221 fn proxy(&self, request: &Request, connection: &ConnectionInfo) -> Result<Response, String> {
222 if self.backends.is_empty() {
223 return Err("no backends configured".to_string());
224 }
225 let n = self.backends.len();
226 let start = self.counter.fetch_add(1, Ordering::Relaxed);
227 let mut last_err = "all backends failed".to_string();
228 for attempt in 0..n {
229 let idx = (start + attempt) % n;
230 let backend = &self.backends[idx];
231 let key = format!("{}:{}", backend.host, backend.port);
232
233 if let Some(breaker) = &self.breaker {
234 if !breaker.is_available(&key) {
235 last_err = format!("circuit open for {}", key);
236 continue;
237 }
238 }
239
240 match self.try_backend(request, connection, backend) {
241 Ok(resp) => {
242 if let Some(breaker) = &self.breaker {
243 breaker.record_success(&key);
244 }
245 return Ok(resp);
246 }
247 Err(e) => {
248 if let Some(breaker) = &self.breaker {
249 breaker.record_failure(&key);
250 }
251 last_err = e;
252 }
253 }
254 }
255 Err(last_err)
256 }
257
258 fn try_backend(
259 &self,
260 request: &Request,
261 connection: &ConnectionInfo,
262 backend: &Backend,
263 ) -> Result<Response, String> {
264 forward_upstream_trusting(
265 &self.pool,
266 request,
267 crate::proxy::Peer::of(connection),
268 &backend.host,
269 backend.port,
270 backend.tls,
271 self.trust.as_deref(),
272 self.connect_timeout,
273 self.read_timeout,
274 )
275 }
276}
277
278impl Middleware for ReverseProxy {
279 fn handle(
280 &self,
281 request: &Request,
282 connection: &ConnectionInfo,
283 next: &dyn Application,
284 ) -> Result<Response, String> {
285 if let Some(prefix) = &self.path_prefix {
286 if !request.request_uri.starts_with(prefix.as_str()) {
287 return next.execute(request, connection);
288 }
289 }
290 match self.proxy(request, connection) {
291 Ok(resp) => Ok(resp),
292 Err(_) => Ok(bad_gateway()),
293 }
294 }
295}
296
297#[derive(Clone, Copy, Debug)]
302pub(crate) struct Peer<'a> {
303 pub ip: &'a str,
304 pub tls: bool,
305}
306
307impl<'a> Peer<'a> {
308 pub(crate) fn of(connection: &'a ConnectionInfo) -> Self {
309 Peer { ip: &connection.client.ip, tls: connection.tls }
310 }
311
312 pub(crate) fn plain(ip: &'a str) -> Self {
314 Peer { ip, tls: false }
315 }
316
317 pub(crate) fn proto(&self) -> &'static str {
318 if self.tls { "https" } else { "http" }
319 }
320}
321
322pub(crate) fn build_request(
323 request: &Request,
324 backend_host: &str,
325 client: Peer<'_>,
326 keep_alive: bool,
327) -> Vec<u8> {
328 let connection = request.header(crate::header::Header::_CONNECTION).map(|h| h.value.as_ref());
334 #[cfg(not(target_arch = "wasm32"))]
337 let trace = crate::otel::propagation_headers();
338 #[cfg(target_arch = "wasm32")]
339 let trace: Option<(String, Option<String>)> = None;
340 let forwarded = |h: &&crate::header::Header| {
341 !h.name.is_empty()
343 && !is_hop_by_hop_or_host(&h.name)
344 && !h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_LENGTH)
345 && !h.name.eq_ignore_ascii_case("X-Forwarded-For")
346 && !connection.is_some_and(|c| connection_listed(c, &h.name))
347 && !(trace.is_some() && (h.name.eq_ignore_ascii_case("traceparent") || h.name.eq_ignore_ascii_case("baggage")))
348 };
349 let prior_xff = request.header("X-Forwarded-For").map(|h| h.value.as_ref()).filter(|v| !v.trim().is_empty());
350 let forwarded_proto = request.header("X-Forwarded-Proto").is_none().then(|| client.proto());
354 let forwarded_host = match request.header("X-Forwarded-Host") {
355 Some(_) => None,
356 None => request.header(crate::header::Header::_HOST).map(|h| h.value.as_ref()).filter(|v| !v.is_empty()),
357 };
358 let body_len = Decimal::new(request.body.len() as u128);
359 let capacity = request.method.len() + request.request_uri.len() + backend_host.len() + 25
360 + request.headers.iter().filter(forwarded).map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
361 + client.ip.len() + 19 + prior_xff.map_or(0, |v| v.len() + 2)
362 + forwarded_host.map_or(0, |v| v.len() + 20)
363 + forwarded_proto.map_or(0, |v| v.len() + 21)
364 + trace.as_ref().map_or(0, |(t, b)| t.len() + 15 + b.as_ref().map_or(0, |b| b.len() + 11))
365 + 13
366 + 24
367 + if request.body.is_empty() { 0 } else { body_len.as_str().len() + 18 }
368 + 2
369 + request.body.len();
370 let mut out: Vec<u8> = Vec::with_capacity(capacity);
371 for part in [request.method.as_str(), " ", request.request_uri.as_str(), " HTTP/1.1\r\nHost: ", backend_host, "\r\n"] {
372 out.extend_from_slice(part.as_bytes());
373 }
374 for h in request.headers.iter().filter(forwarded) {
375 for part in [h.name.as_ref(), ": ", h.value.as_ref(), "\r\n"] {
376 out.extend_from_slice(part.as_bytes());
377 }
378 }
379 out.extend_from_slice(b"X-Forwarded-For: ");
380 if let Some(prior) = prior_xff {
381 out.extend_from_slice(prior.as_bytes());
382 out.extend_from_slice(b", ");
383 }
384 for part in [client.ip, "\r\n", "Via: 1.1 rws\r\n"] {
385 out.extend_from_slice(part.as_bytes());
386 }
387 if let Some(host) = forwarded_host {
388 for part in ["X-Forwarded-Host: ", host, "\r\n"] {
389 out.extend_from_slice(part.as_bytes());
390 }
391 }
392 if let Some(proto) = forwarded_proto {
393 for part in ["X-Forwarded-Proto: ", proto, "\r\n"] {
394 out.extend_from_slice(part.as_bytes());
395 }
396 }
397 if let Some((traceparent, baggage)) = &trace {
398 for part in ["traceparent: ", traceparent, "\r\n"] {
399 out.extend_from_slice(part.as_bytes());
400 }
401 if let Some(baggage) = baggage {
402 for part in ["baggage: ", baggage, "\r\n"] {
403 out.extend_from_slice(part.as_bytes());
404 }
405 }
406 }
407 if keep_alive {
408 out.extend_from_slice(b"Connection: keep-alive\r\n");
409 } else {
410 out.extend_from_slice(b"Connection: close\r\n");
411 }
412 if !request.body.is_empty() {
413 out.extend_from_slice(b"Content-Length: ");
414 out.extend_from_slice(body_len.as_str().as_bytes());
415 out.extend_from_slice(b"\r\n");
416 }
417 out.extend_from_slice(b"\r\n");
418 out.extend_from_slice(&request.body);
419 out
420}
421
422fn is_hop_by_hop_or_host(name: &str) -> bool {
427 if name.is_ascii() {
428 name.eq_ignore_ascii_case("host") || HOP_BY_HOP.iter().any(|h| name.eq_ignore_ascii_case(h))
429 } else {
430 let lower = name.to_lowercase();
431 lower == "host" || HOP_BY_HOP.contains(&lower.as_str())
432 }
433}
434
435fn connection_listed(connection: &str, name: &str) -> bool {
438 connection.split(',').any(|token| token.trim().eq_ignore_ascii_case(name))
439}
440
441fn decode_chunked<S: Read>(
446 stream: &mut S,
447 buf: &[u8],
448 header_end: usize,
449 tmp: &mut [u8],
450) -> Result<Vec<u8>, String> {
451 let mut raw: Vec<u8> = buf[header_end..].to_vec();
453 let mut decoded: Vec<u8> = Vec::new();
454
455 loop {
456 let crlf = loop {
458 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
459 break p;
460 }
461 let n = stream.read(tmp).map_err(|e| e.to_string())?;
462 if n == 0 {
463 return Err("chunked: premature EOF reading chunk size".to_string());
464 }
465 raw.extend_from_slice(&tmp[..n]);
466 };
467
468 let size_line = std::str::from_utf8(&raw[..crlf])
470 .map_err(|_| "chunked: non-UTF-8 chunk size line".to_string())?;
471 let size_str = size_line.split(';').next().unwrap_or("").trim();
472 let chunk_size = usize::from_str_radix(size_str, 16)
473 .map_err(|_| format!("chunked: invalid chunk size '{}'", size_str))?;
474 raw.drain(..crlf + 2); if chunk_size == 0 {
477 loop {
481 let line_end = loop {
482 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
483 break p;
484 }
485 let n = stream.read(tmp).map_err(|e| e.to_string())?;
486 if n == 0 {
487 return Err("chunked: premature EOF in trailer".to_string());
488 }
489 raw.extend_from_slice(&tmp[..n]);
490 };
491 raw.drain(..line_end + 2);
492 if line_end == 0 {
493 break;
494 }
495 }
496 break;
497 }
498
499 while raw.len() < chunk_size + 2 {
501 let n = stream.read(tmp).map_err(|e| e.to_string())?;
502 if n == 0 {
503 return Err("chunked: premature EOF reading chunk body".to_string());
504 }
505 raw.extend_from_slice(&tmp[..n]);
506 }
507 decoded.extend_from_slice(&raw[..chunk_size]);
508 raw.drain(..chunk_size + 2); }
510
511 Ok(decoded)
512}
513
514fn rewrite_as_content_length(buf: &mut Vec<u8>, header_end: usize, decoded: &[u8]) {
517 let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_string();
518 buf.clear();
519 for line in header_str.lines() {
520 if line.to_ascii_lowercase().starts_with("transfer-encoding:") || line.is_empty() {
521 continue;
522 }
523 buf.extend_from_slice(line.as_bytes());
524 buf.extend_from_slice(b"\r\n");
525 }
526 let _ = write!(buf, "Content-Length: {}\r\n\r\n", decoded.len());
527 buf.extend_from_slice(decoded);
528}
529
530pub(crate) const REGENERATED_OR_HOP_BY_HOP: &[&str] = &[
533 "content-length", "transfer-encoding", "connection", "keep-alive",
534 "proxy-connection", "te", "trailer", "upgrade",
535];
536
537#[cfg_attr(not(feature = "http2"), allow(dead_code))]
546pub(crate) fn normalize_upstream_response(mut response: Response) -> Response {
547 response.http_version.clear();
548 response.http_version.push_str(crate::http::VERSION.http_1_1);
549 let has_body = !response.content_range_list.is_empty();
550 if let [range] = response.content_range_list.as_mut_slice() {
551 if let Some(h) = response
552 .headers
553 .iter()
554 .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
555 {
556 range.content_type.clear();
557 range.content_type.push_str(&h.value);
558 }
559 }
560 response.headers.retain(|h| {
563 if h.name.eq_ignore_ascii_case("content-type") {
564 return !has_body;
566 }
567 !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
568 });
569 response
570}
571
572pub(crate) fn bad_gateway() -> Response {
573 let cr = Range::get_content_range(
574 b"502 Bad Gateway".to_vec(),
575 MimeType::TEXT_PLAIN.to_string(),
576 );
577 let mut r = Response::new();
578 r.status_code = *STATUS_CODE_REASON_PHRASE.n502_bad_gateway.status_code;
579 r.reason_phrase = STATUS_CODE_REASON_PHRASE
580 .n502_bad_gateway
581 .reason_phrase
582 .to_string();
583 r.content_range_list = vec![cr];
584 r
585}
586
587const STREAM_THRESHOLD: usize = 1024 * 1024; pub(crate) struct ConcatReader<R: Read + Send> {
595 prefix: Vec<u8>,
596 prefix_pos: usize,
597 inner: R,
598}
599
600impl<R: Read + Send> ConcatReader<R> {
601 fn new(prefix: Vec<u8>, inner: R) -> Self {
602 ConcatReader { prefix, prefix_pos: 0, inner }
603 }
604}
605
606impl<R: Read + Send> Read for ConcatReader<R> {
607 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
608 if self.prefix_pos < self.prefix.len() {
609 let avail = &self.prefix[self.prefix_pos..];
610 let n = buf.len().min(avail.len());
611 buf[..n].copy_from_slice(&avail[..n]);
612 self.prefix_pos += n;
613 return Ok(n);
614 }
615 self.inner.read(buf)
616 }
617}
618
619
620pub(crate) const POOL_MAX_IDLE: usize = 64;
624
625pub(crate) fn shared_pool() -> &'static ConnPool {
628 static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
629 POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
630}
631
632pub(crate) trait UpstreamIo: Read + Write + Send + 'static {
635 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
636}
637
638impl UpstreamIo for TcpStream {
639 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
640 self.set_read_timeout(Some(read))?;
641 self.set_write_timeout(Some(write))
642 }
643}
644
645#[cfg(any(feature = "http-client", feature = "http2"))]
646pub(crate) type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
647
648#[cfg(any(feature = "http-client", feature = "http2"))]
649impl UpstreamIo for TlsStream {
650 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
651 self.sock.set_io_timeouts(read, write)
652 }
653}
654
655pub(crate) fn forward_upstream(
661 plain_pool: &ConnPool,
662 request: &Request,
663 client: Peer<'_>,
664 host: &str,
665 port: u16,
666 tls: bool,
667 connect_timeout: Duration,
668 read_timeout: Duration,
669) -> Result<Response, String> {
670 forward_upstream_trusting(plain_pool, request, client, host, port, tls, None, connect_timeout, read_timeout)
671}
672
673#[allow(clippy::too_many_arguments)]
676pub(crate) fn forward_upstream_trusting(
677 plain_pool: &ConnPool,
678 request: &Request,
679 client: Peer<'_>,
680 host: &str,
681 port: u16,
682 tls: bool,
683 trust: Option<&UpstreamTls>,
684 connect_timeout: Duration,
685 read_timeout: Duration,
686) -> Result<Response, String> {
687 #[cfg(not(target_arch = "wasm32"))]
690 let span = crate::otel::outbound_span(&request.method);
691 #[cfg(not(target_arch = "wasm32"))]
692 if let Some(span) = &span {
693 let scheme = if tls { "https" } else { "http" };
694 let path = request.request_uri.as_str();
695 for (key, value) in crate::otel::http_client_attributes(&request.method, &format!("{scheme}://{host}:{port}{path}")) {
696 span.set_attribute(key, value);
697 }
698 }
699 let result = forward_upstream_untraced(plain_pool, request, client, host, port, tls, trust, connect_timeout, read_timeout);
700 #[cfg(not(target_arch = "wasm32"))]
701 if let Some(span) = &span {
702 span.finish_http_client(result.as_ref().map(|r| r.status_code as u16).map_err(String::as_str));
703 }
704 result
705}
706
707#[allow(clippy::too_many_arguments)]
708fn forward_upstream_untraced(
709 plain_pool: &ConnPool,
710 request: &Request,
711 client: Peer<'_>,
712 host: &str,
713 port: u16,
714 tls: bool,
715 trust: Option<&UpstreamTls>,
716 connect_timeout: Duration,
717 read_timeout: Duration,
718) -> Result<Response, String> {
719 if tls {
720 #[cfg(any(feature = "http-client", feature = "http2"))]
721 {
722 let (pool, config) = match trust {
723 Some(t) => (t.pool, Arc::clone(&t.config)),
724 None => (shared_tls_pool(), tls_client_config()),
725 };
726 return forward_via(pool, request, client, host, port, host, read_timeout, || {
727 connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
728 });
729 }
730 #[cfg(not(any(feature = "http-client", feature = "http2")))]
731 {
732 let _ = trust;
733 return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
734 }
735 }
736 forward_pooled(plain_pool, request, client, host, port, connect_timeout, read_timeout)
737}
738
739pub struct UpstreamTls {
747 #[cfg(any(feature = "http-client", feature = "http2"))]
748 config: Arc<rustls::ClientConfig>,
749 #[cfg(any(feature = "http-client", feature = "http2"))]
750 pool: &'static Pool<TlsStream>,
751 #[cfg(feature = "http2")]
753 async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
754 #[cfg(feature = "http2")]
756 h2_config: Arc<rustls::ClientConfig>,
757}
758
759impl UpstreamTls {
760 pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
762 UpstreamTls::new(Some(path), None)
763 }
764
765 pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
769 #[cfg(any(feature = "http-client", feature = "http2"))]
770 {
771 use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
772 let roots = match ca_file {
773 Some(path) => {
774 let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
775 let certs = CertificateDer::pem_slice_iter(&bytes)
776 .collect::<Result<Vec<_>, _>>()
777 .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
778 if certs.is_empty() {
779 return Err(format!("no certificates in CA file '{path}'"));
780 }
781 let mut roots = rustls::RootCertStore::empty();
782 for cert in certs {
783 roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
784 }
785 roots
786 }
787 None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
788 };
789 let builder = crate::tls_client_builder().with_root_certificates(roots);
790 let config = match client_cert {
791 None => builder.with_no_client_auth(),
792 Some((cert_path, key_path)) => {
793 let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
794 let chain = CertificateDer::pem_slice_iter(&bytes)
795 .collect::<Result<Vec<_>, _>>()
796 .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
797 if chain.is_empty() {
798 return Err(format!("no certificate in '{cert_path}'"));
799 }
800 let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
801 let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
802 builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
803 }
804 };
805 let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
806 Ok(UpstreamTls::with_config(config, &label))
807 }
808 #[cfg(not(any(feature = "http-client", feature = "http2")))]
809 {
810 let _ = client_cert;
811 Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
812 }
813 }
814
815 #[cfg(any(feature = "http-client", feature = "http2"))]
816 fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
817 #[cfg(feature = "http2")]
818 let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
819 UpstreamTls {
820 config: Arc::new(config),
821 pool: tls_pool_for_ca(label),
822 #[cfg(feature = "http2")]
823 async_pool: async_tls_pool_for_ca(label),
824 #[cfg(feature = "http2")]
825 h2_config,
826 }
827 }
828
829 #[cfg(feature = "http2")]
831 pub(crate) fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
832 &self.h2_config
833 }
834
835 pub(crate) fn reject_all(label: &str) -> UpstreamTls {
839 #[cfg(any(feature = "http-client", feature = "http2"))]
840 {
841 let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
842 UpstreamTls::with_config(config, &format!("reject-all:{label}"))
843 }
844 #[cfg(not(any(feature = "http-client", feature = "http2")))]
845 {
846 let _ = label;
847 UpstreamTls {}
848 }
849 }
850
851 #[cfg(feature = "http2")]
853 pub(crate) fn async_tls(&self) -> async_upstream::AsyncTls {
854 async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
855 }
856
857 #[cfg(any(feature = "http-client", feature = "http2"))]
859 pub(crate) fn client_config(&self) -> Arc<rustls::ClientConfig> {
860 Arc::clone(&self.config)
861 }
862}
863
864#[cfg(feature = "http2")]
867fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
868 static POOLS: std::sync::OnceLock<
869 std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
870 > = std::sync::OnceLock::new();
871 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
872 pools
873 .entry(path.to_string())
874 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
875}
876
877#[cfg(any(feature = "http-client", feature = "http2"))]
879fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
880 static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
881 std::sync::OnceLock::new();
882 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
883 pools
884 .entry(path.to_string())
885 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
886}
887
888pub(crate) fn forward_pooled(
892 pool: &ConnPool,
893 request: &Request,
894 client: Peer<'_>,
895 host: &str,
896 port: u16,
897 connect_timeout: Duration,
898 read_timeout: Duration,
899) -> Result<Response, String> {
900 forward_via(pool, request, client, host, port, host, read_timeout, || connect_tcp(host, port, connect_timeout))
901}
902
903#[cfg(feature = "gateway-api")]
906#[allow(clippy::too_many_arguments)]
907pub(crate) fn forward_pooled_with_host(
908 pool: &ConnPool,
909 request: &Request,
910 client: Peer<'_>,
911 host: &str,
912 port: u16,
913 host_header: &str,
914 connect_timeout: Duration,
915 read_timeout: Duration,
916) -> Result<Response, String> {
917 forward_via(pool, request, client, host, port, host_header, read_timeout, || connect_tcp(host, port, connect_timeout))
918}
919
920#[allow(clippy::too_many_arguments)]
927fn forward_via<S: UpstreamIo>(
928 pool: &Pool<S>,
929 request: &Request,
930 client: Peer<'_>,
931 host: &str,
932 port: u16,
933 host_header: &str,
934 read_timeout: Duration,
935 connect: impl Fn() -> Result<S, String>,
936) -> Result<Response, String> {
937 let key = format!("{}:{}", host, port);
938 if let Some(stream) = pool.acquire(&key) {
939 match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
940 Exchange::Done(response) => return Ok(response),
941 Exchange::NoResponse(_) if is_idempotent(&request.method) => {} Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
943 }
944 }
945 let stream = connect()?;
946 match exchange(pool, &key, stream, request, host_header, client, read_timeout) {
947 Exchange::Done(response) => Ok(response),
948 Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
949 }
950}
951
952fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
956 let key = format!("{}:{}", host, port);
957 let addrs: Vec<_> = key
958 .to_socket_addrs()
959 .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
960 .collect();
961 let mut last_error = format!("no address resolved for {}", key);
962 for addr in addrs {
963 match TcpStream::connect_timeout(&addr, connect_timeout) {
964 Ok(stream) => {
965 let _ = stream.set_nodelay(true);
966 return Ok(stream);
967 }
968 Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
969 }
970 }
971 Err(last_error)
972}
973
974#[cfg(any(feature = "http-client", feature = "http2"))]
976fn shared_tls_pool() -> &'static Pool<TlsStream> {
977 static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
978 POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
979}
980
981#[cfg(any(feature = "http-client", feature = "http2"))]
985pub(crate) fn tls_client_config() -> Arc<rustls::ClientConfig> {
986 static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
987 Arc::clone(CONFIG.get_or_init(|| {
988 let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
989 Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
990 }))
991}
992
993#[cfg(any(feature = "http-client", feature = "http2"))]
994fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
995 let tcp = connect_tcp(host, port, connect_timeout)?;
996 let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
997 .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
998 let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
999 Ok(rustls::StreamOwned::new(conn, tcp))
1000}
1001
1002fn is_idempotent(method: &str) -> bool {
1003 matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
1004}
1005
1006enum Exchange {
1007 Done(Response),
1008 NoResponse(String),
1010 Failed(String),
1011}
1012
1013fn exchange<S: UpstreamIo>(
1016 pool: &Pool<S>,
1017 key: &str,
1018 mut stream: S,
1019 request: &Request,
1020 host: &str,
1021 client: Peer<'_>,
1022 read_timeout: Duration,
1023) -> Exchange {
1024 if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
1025 return Exchange::Failed(e.to_string());
1026 }
1027 let req_bytes = build_request(request, host, client, true);
1029 if let Err(e) = stream.write_all(&req_bytes) {
1030 return Exchange::NoResponse(format!("write to backend failed: {}", e));
1031 }
1032
1033 let mut tmp = [0u8; 4096];
1034 let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
1035 Ok(head) => head,
1036 Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
1037 Err(HeadError::Partial(e)) => return Exchange::Failed(e),
1038 };
1039 let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
1040
1041 if response_has_no_body(&request.method, &header_lower) {
1042 if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
1043 pool.release(key, stream);
1044 }
1045 return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
1046 Ok(response) => Exchange::Done(response),
1047 Err(e) => Exchange::Failed(e),
1048 };
1049 }
1050
1051 if should_stream_response(&header_lower) {
1052 return match parse_status_and_headers(&header_bytes) {
1055 Ok(mut response) => {
1056 response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
1057 Exchange::Done(response)
1058 }
1059 Err(e) => Exchange::Failed(e),
1060 };
1061 }
1062 match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
1064 Ok((resp_bytes, reusable)) => {
1065 if reusable {
1066 pool.release(key, stream);
1067 }
1068 match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
1069 Ok(response) => Exchange::Done(response),
1070 Err(e) => Exchange::Failed(e),
1071 }
1072 }
1073 Err(e) => Exchange::Failed(e),
1074 }
1075}
1076
1077#[cfg(test)]
1082fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
1083 read_response_head(stream, tmp).map_err(|e| match e {
1084 HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
1085 })
1086}
1087
1088enum HeadError {
1092 NothingReceived(String),
1093 Partial(String),
1094}
1095
1096fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1097 read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
1098}
1099
1100fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1105 let (mut head, mut rest) = read_response_head(stream, tmp)?;
1106 let mut interim = 0;
1107 while is_interim_response(&head) {
1108 interim += 1;
1109 if interim > MAX_INTERIM_RESPONSES {
1110 return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
1111 }
1112 (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
1113 }
1114 Ok((head, rest))
1115}
1116
1117fn read_response_head_from<S: Read>(
1121 stream: &mut S,
1122 tmp: &mut [u8],
1123 mut buf: Vec<u8>,
1124 received: bool,
1125) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1126 loop {
1127 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1128 let body_prefix = buf[pos + 4..].to_vec();
1129 buf.truncate(pos + 4);
1130 return Ok((buf, body_prefix));
1131 }
1132 let nothing = buf.is_empty() && !received;
1133 let n = match stream.read(tmp) {
1134 Ok(n) => n,
1135 Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1136 Err(e) => return Err(HeadError::Partial(e.to_string())),
1137 };
1138 if n == 0 {
1139 let msg = "backend closed connection before headers were complete".to_string();
1140 return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1141 }
1142 buf.extend_from_slice(&tmp[..n]);
1143 }
1144}
1145
1146pub(crate) const MAX_INTERIM_RESPONSES: usize = 16;
1148
1149pub(crate) fn is_interim_response(head: &[u8]) -> bool {
1152 let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1153 let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1154 status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1155}
1156
1157pub(crate) fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1161 let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1162 method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1163}
1164
1165pub(crate) fn should_stream_response(header_lower: &str) -> bool {
1172 let is_sse = header_lower.lines().any(|l| {
1173 l.starts_with("content-type:") && l.contains("text/event-stream")
1174 });
1175 let is_chunked = header_lower.lines().any(|l| {
1176 l.starts_with("transfer-encoding:") && l.contains("chunked")
1177 });
1178 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1179 l.strip_prefix("content-length:")?.trim().parse().ok()
1180 });
1181 let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1182 is_sse || is_chunked || is_large
1183}
1184
1185#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1191pub(crate) struct HeadFacts {
1192 pub(crate) status_no_body: bool,
1194 pub(crate) sse: bool,
1195 pub(crate) chunked: bool,
1196 pub(crate) content_length: Option<usize>,
1198 pub(crate) connection_close: bool,
1199}
1200
1201#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1202impl HeadFacts {
1203 pub(crate) fn scan(head: &[u8]) -> HeadFacts {
1204 let text = std::str::from_utf8(head).unwrap_or("");
1205 let status = text.split_whitespace().nth(1).unwrap_or("");
1206 let mut facts = HeadFacts {
1207 status_no_body: status.starts_with('1') || status == "204" || status == "304",
1208 sse: false,
1209 chunked: false,
1210 content_length: None,
1211 connection_close: false,
1212 };
1213 for line in text.lines() {
1214 if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1215 facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1216 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1217 facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1218 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1219 if facts.content_length.is_none() {
1220 facts.content_length = value.trim().parse().ok();
1221 }
1222 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1223 facts.connection_close |= contains_ignore_ascii_case(value, "close");
1224 }
1225 }
1226 facts
1227 }
1228
1229 pub(crate) fn no_body(&self, method: &str) -> bool {
1231 method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1232 }
1233
1234 pub(crate) fn should_stream(&self) -> bool {
1236 self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1237 }
1238}
1239
1240fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1241 let bytes = line.as_bytes();
1242 (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1244 .then(|| &line[prefix.len()..])
1245}
1246
1247fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1248 haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1249}
1250
1251fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1253 let s = std::str::from_utf8(header_bytes)
1254 .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1255 let mut lines = s.lines();
1256 let status_line = lines.next().ok_or("empty backend response")?;
1257 let mut parts = status_line.splitn(3, ' ');
1258 let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1259 let status_code: i16 = parts
1260 .next()
1261 .unwrap_or("502")
1262 .parse()
1263 .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1264 let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1265 let mut headers = Vec::new();
1266 for line in lines {
1267 let line = line.trim_end_matches('\r');
1268 if line.is_empty() { break; }
1269 if let Some(colon) = line.find(':') {
1270 headers.push(crate::header::Header {
1271 name: line[..colon].trim().to_string().into(),
1272 value: (line[colon + 1..].trim().to_string()).into(),
1273 });
1274 }
1275 }
1276 Ok(Response {
1277 http_version,
1278 status_code,
1279 reason_phrase,
1280 headers,
1281 content_range_list: vec![],
1282 stream_file: None,
1283 stream_pipe: None,
1284 trailers: None,
1285 })
1286}
1287
1288fn read_response_from_partial<S: Read>(
1294 stream: &mut S,
1295 header_bytes: Vec<u8>,
1296 body_prefix: Vec<u8>,
1297 tmp: &mut [u8],
1298) -> Result<(Vec<u8>, bool), String> {
1299 let header_end = header_bytes.len();
1300 let mut buf = header_bytes;
1301 buf.extend_from_slice(&body_prefix);
1302
1303 let header_lower =
1304 std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1305 let connection_close =
1306 header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1307 let is_chunked = header_lower
1308 .lines()
1309 .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1310 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1311 l.strip_prefix("content-length:")?.trim().parse().ok()
1312 });
1313
1314 if is_chunked {
1315 let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1316 rewrite_as_content_length(&mut buf, header_end, &decoded);
1317 Ok((buf, !connection_close))
1318 } else if let Some(len) = content_length {
1319 while buf.len() < header_end + len {
1320 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1321 if n == 0 { break; }
1322 buf.extend_from_slice(&tmp[..n]);
1323 }
1324 Ok((buf, !connection_close))
1325 } else {
1326 loop {
1327 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1328 if n == 0 { break; }
1329 buf.extend_from_slice(&tmp[..n]);
1330 }
1331 Ok((buf, false))
1332 }
1333}
1334
1335struct Backend {
1338 host: String,
1339 port: u16,
1340 tls: bool,
1343}
1344
1345impl Backend {
1346 fn parse(url: &str) -> Option<Self> {
1347 let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1348 (r, true, 443u16)
1349 } else if let Some(r) = url.strip_prefix("h2s://") {
1350 (r, true, 443u16)
1351 } else if let Some(r) = url.strip_prefix("grpcs://") {
1352 (r, true, 443u16)
1353 } else if let Some(r) = url.strip_prefix("http://") {
1354 (r, false, 80u16)
1355 } else if let Some(r) = url.strip_prefix("h2://") {
1356 (r, false, 80u16)
1357 } else if let Some(r) = url.strip_prefix("grpc://") {
1358 (r, false, 80u16)
1359 } else {
1360 (url, false, 80u16)
1361 };
1362 let host_port = rest.split('/').next().unwrap_or(rest);
1364 let (host, port) = if let Some(colon) = host_port.rfind(':') {
1365 let port_str = &host_port[colon + 1..];
1366 if let Ok(p) = port_str.parse::<u16>() {
1367 (host_port[..colon].to_string(), p)
1368 } else {
1369 (host_port.to_string(), default_port)
1370 }
1371 } else {
1372 (host_port.to_string(), default_port)
1373 };
1374 if host.is_empty() {
1375 return None;
1376 }
1377 Some(Backend { host, port, tls })
1378 }
1379}
1380
1381#[cfg(feature = "http2")]
1392pub struct H2ReverseProxy {
1393 inner: ReverseProxy,
1394}
1395
1396#[cfg(feature = "http2")]
1397impl H2ReverseProxy {
1398 pub fn new<I, S>(backends: I) -> Self
1409 where
1410 I: IntoIterator<Item = S>,
1411 S: AsRef<str>,
1412 {
1413 H2ReverseProxy {
1414 inner: ReverseProxy::new(backends),
1415 }
1416 }
1417
1418 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1420 self.inner = self.inner.path_prefix(prefix);
1421 self
1422 }
1423
1424 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1426 self.inner = self.inner.connect_timeout_ms(ms);
1427 self
1428 }
1429
1430 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1435 self.inner = self.inner.read_timeout_ms(ms);
1436 self
1437 }
1438
1439 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1442 self.inner = self.inner.tls_ca_file(path)?;
1443 Ok(self)
1444 }
1445
1446 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1449 self.inner = self.inner.tls_client_cert(cert, key)?;
1450 Ok(self)
1451 }
1452
1453 fn matches(&self, request: &Request) -> bool {
1454 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1455 }
1456}
1457
1458#[cfg(feature = "http2")]
1459impl crate::middleware::Middleware for H2ReverseProxy {
1460 fn handle(
1461 &self,
1462 request: &crate::request::Request,
1463 connection: &crate::server::ConnectionInfo,
1464 next: &dyn crate::application::Application,
1465 ) -> Result<crate::response::Response, String> {
1466 if !self.matches(request) {
1467 return next.execute(request, connection);
1468 }
1469 if self.inner.backends.is_empty() {
1470 return Ok(bad_gateway());
1471 }
1472 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1474 let n = self.inner.backends.len();
1475 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1476 for attempt in 0..attempts {
1477 let backend = &self.inner.backends[(start + attempt) % n];
1478 let tls = backend.tls.then(|| match &self.inner.trust {
1479 Some(trust) => trust.h2_config(),
1480 None => h2_upstream::default_tls(),
1481 });
1482 let target = h2_upstream::Target {
1483 backend,
1484 tls,
1485 connect_timeout: self.inner.connect_timeout,
1486 read_timeout: self.inner.read_timeout,
1487 authority: None,
1488 };
1489 if let Ok(response) = h2_upstream::forward(request, Peer::of(connection), &target) {
1490 return Ok(response);
1491 }
1492 }
1493 Ok(bad_gateway())
1494 }
1495
1496 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1499 true
1500 }
1501
1502 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1505 self.matches(request)
1506 }
1507}
1508
1509#[cfg(feature = "http2")]
1513pub(crate) fn forward_h2(
1514 request: &Request,
1515 client: Peer<'_>,
1516 url: &str,
1517 tls: bool,
1518 trust: Option<&UpstreamTls>,
1519 connect_timeout: Duration,
1520 read_timeout: Duration,
1521) -> Result<Response, String> {
1522 let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1523 backend.tls |= tls;
1524 let tls = backend.tls.then(|| match trust {
1525 Some(t) => t.h2_config(),
1526 None => h2_upstream::default_tls(),
1527 });
1528 h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout, authority: None })
1529}
1530
1531#[cfg(feature = "gateway-api")]
1536#[allow(clippy::too_many_arguments)]
1537pub(crate) fn forward_tls_with_host(
1538 config: &Arc<rustls::ClientConfig>,
1539 label: &str,
1540 request: &Request,
1541 client: Peer<'_>,
1542 ip: &str,
1543 port: u16,
1544 server_name: &str,
1545 host_header: &str,
1546 connect_timeout: Duration,
1547 read_timeout: Duration,
1548) -> Result<Response, String> {
1549 let pool = tls_pool_for_ca(label);
1550 forward_via(pool, request, client, ip, port, host_header, read_timeout, || {
1551 let tcp = connect_tcp(ip, port, connect_timeout)?;
1552 let name = rustls::pki_types::ServerName::try_from(server_name.to_string()).map_err(|e| format!("invalid TLS server name '{server_name}': {e}"))?;
1553 let conn = rustls::ClientConnection::new(Arc::clone(config), name).map_err(|e| e.to_string())?;
1554 Ok(rustls::StreamOwned::new(conn, tcp))
1555 })
1556}
1557
1558#[cfg(feature = "gateway-api")]
1562pub(crate) fn forward_h2c_with_host(
1563 request: &Request,
1564 client: Peer<'_>,
1565 host: &str,
1566 port: u16,
1567 authority: &str,
1568 connect_timeout: Duration,
1569 read_timeout: Duration,
1570) -> Result<Response, String> {
1571 let backend = Backend { host: host.to_string(), port, tls: false };
1572 h2_upstream::forward(request, client, &h2_upstream::Target { backend: &backend, tls: None, connect_timeout, read_timeout, authority: Some(authority) })
1573}
1574
1575#[cfg(feature = "http2")]
1595pub struct GrpcProxy {
1596 inner: H2ReverseProxy,
1597}
1598
1599#[cfg(feature = "http2")]
1600impl GrpcProxy {
1601 pub fn new<I, S>(backends: I) -> Self
1611 where
1612 I: IntoIterator<Item = S>,
1613 S: AsRef<str>,
1614 {
1615 GrpcProxy { inner: H2ReverseProxy::new(backends) }
1616 }
1617
1618 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1620 self.inner = self.inner.path_prefix(prefix);
1621 self
1622 }
1623
1624 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1626 self.inner = self.inner.connect_timeout_ms(ms);
1627 self
1628 }
1629
1630 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1632 self.inner = self.inner.read_timeout_ms(ms);
1633 self
1634 }
1635
1636 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1638 self.inner = self.inner.tls_ca_file(path)?;
1639 Ok(self)
1640 }
1641
1642 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1645 self.inner = self.inner.tls_client_cert(cert, key)?;
1646 Ok(self)
1647 }
1648}
1649
1650#[cfg(feature = "http2")]
1651impl crate::middleware::Middleware for GrpcProxy {
1652 fn handle(
1653 &self,
1654 request: &crate::request::Request,
1655 connection: &crate::server::ConnectionInfo,
1656 next: &dyn crate::application::Application,
1657 ) -> Result<crate::response::Response, String> {
1658 if is_grpc(request) {
1659 self.inner.handle(request, connection, next)
1660 } else {
1661 next.execute(request, connection)
1662 }
1663 }
1664
1665 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1666 true
1667 }
1668
1669 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1670 is_grpc(request) && self.inner.matches(request)
1671 }
1672}
1673
1674#[cfg(feature = "http2")]
1675fn is_grpc(request: &Request) -> bool {
1676 request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
1677}
1678
1679#[cfg(test)]
1682mod backend_parse_tests {
1683 use super::Backend;
1684
1685 fn parse(url: &str) -> Option<(String, u16, bool)> {
1686 Backend::parse(url).map(|b| (b.host, b.port, b.tls))
1687 }
1688
1689 #[test]
1690 fn bare_host_port() {
1691 assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
1692 }
1693
1694 #[test]
1695 fn http_scheme() {
1696 assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
1697 }
1698
1699 #[test]
1700 fn h2_scheme_plain() {
1701 assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
1702 }
1703
1704 #[test]
1705 fn grpc_scheme_plain() {
1706 assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
1707 }
1708
1709 #[test]
1710 fn https_scheme_sets_tls_and_default_port() {
1711 assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
1712 }
1713
1714 #[test]
1715 fn https_scheme_explicit_port() {
1716 assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
1717 }
1718
1719 #[test]
1720 fn h2s_scheme_sets_tls() {
1721 assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
1722 }
1723
1724 #[test]
1725 fn h2s_scheme_explicit_port() {
1726 assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
1727 }
1728
1729 #[test]
1730 fn grpcs_scheme_sets_tls() {
1731 assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
1732 }
1733
1734 #[test]
1735 fn grpcs_scheme_explicit_port() {
1736 assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
1737 }
1738
1739 #[test]
1740 fn empty_host_returns_none() {
1741 assert_eq!(None, parse("https://"));
1742 }
1743
1744 #[test]
1745 fn bare_host_no_port_defaults_to_80() {
1746 assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
1747 }
1748}