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
492pub(crate) fn normalize_upstream_response(mut response: Response) -> Response {
501 response.http_version.clear();
502 response.http_version.push_str(crate::http::VERSION.http_1_1);
503 let has_body = !response.content_range_list.is_empty();
504 if let [range] = response.content_range_list.as_mut_slice() {
505 if let Some(h) = response
506 .headers
507 .iter()
508 .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
509 {
510 range.content_type.clear();
511 range.content_type.push_str(&h.value);
512 }
513 }
514 response.headers.retain(|h| {
517 if h.name.eq_ignore_ascii_case("content-type") {
518 return !has_body;
520 }
521 !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
522 });
523 response
524}
525
526pub(crate) fn bad_gateway() -> Response {
527 let cr = Range::get_content_range(
528 b"502 Bad Gateway".to_vec(),
529 MimeType::TEXT_PLAIN.to_string(),
530 );
531 let mut r = Response::new();
532 r.status_code = *STATUS_CODE_REASON_PHRASE.n502_bad_gateway.status_code;
533 r.reason_phrase = STATUS_CODE_REASON_PHRASE
534 .n502_bad_gateway
535 .reason_phrase
536 .to_string();
537 r.content_range_list = vec![cr];
538 r
539}
540
541const STREAM_THRESHOLD: usize = 1024 * 1024; pub(crate) struct ConcatReader<R: Read + Send> {
549 prefix: Vec<u8>,
550 prefix_pos: usize,
551 inner: R,
552}
553
554impl<R: Read + Send> ConcatReader<R> {
555 fn new(prefix: Vec<u8>, inner: R) -> Self {
556 ConcatReader { prefix, prefix_pos: 0, inner }
557 }
558}
559
560impl<R: Read + Send> Read for ConcatReader<R> {
561 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
562 if self.prefix_pos < self.prefix.len() {
563 let avail = &self.prefix[self.prefix_pos..];
564 let n = buf.len().min(avail.len());
565 buf[..n].copy_from_slice(&avail[..n]);
566 self.prefix_pos += n;
567 return Ok(n);
568 }
569 self.inner.read(buf)
570 }
571}
572
573
574pub(crate) const POOL_MAX_IDLE: usize = 64;
578
579pub(crate) fn shared_pool() -> &'static ConnPool {
582 static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
583 POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
584}
585
586pub(crate) trait UpstreamIo: Read + Write + Send + 'static {
589 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
590}
591
592impl UpstreamIo for TcpStream {
593 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
594 self.set_read_timeout(Some(read))?;
595 self.set_write_timeout(Some(write))
596 }
597}
598
599#[cfg(any(feature = "http-client", feature = "http2"))]
600pub(crate) type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
601
602#[cfg(any(feature = "http-client", feature = "http2"))]
603impl UpstreamIo for TlsStream {
604 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
605 self.sock.set_io_timeouts(read, write)
606 }
607}
608
609pub(crate) fn forward_upstream(
615 plain_pool: &ConnPool,
616 request: &Request,
617 client_ip: &str,
618 host: &str,
619 port: u16,
620 tls: bool,
621 connect_timeout: Duration,
622 read_timeout: Duration,
623) -> Result<Response, String> {
624 forward_upstream_trusting(plain_pool, request, client_ip, host, port, tls, None, connect_timeout, read_timeout)
625}
626
627#[allow(clippy::too_many_arguments)]
630pub(crate) fn forward_upstream_trusting(
631 plain_pool: &ConnPool,
632 request: &Request,
633 client_ip: &str,
634 host: &str,
635 port: u16,
636 tls: bool,
637 trust: Option<&UpstreamTls>,
638 connect_timeout: Duration,
639 read_timeout: Duration,
640) -> Result<Response, String> {
641 #[cfg(not(target_arch = "wasm32"))]
644 let span = crate::otel::outbound_span(&request.method);
645 #[cfg(not(target_arch = "wasm32"))]
646 if let Some(span) = &span {
647 let scheme = if tls { "https" } else { "http" };
648 let path = request.request_uri.as_str();
649 for (key, value) in crate::otel::http_client_attributes(&request.method, &format!("{scheme}://{host}:{port}{path}")) {
650 span.set_attribute(key, value);
651 }
652 }
653 let result = forward_upstream_untraced(plain_pool, request, client_ip, host, port, tls, trust, connect_timeout, read_timeout);
654 #[cfg(not(target_arch = "wasm32"))]
655 if let Some(span) = &span {
656 span.finish_http_client(result.as_ref().map(|r| r.status_code as u16).map_err(String::as_str));
657 }
658 result
659}
660
661#[allow(clippy::too_many_arguments)]
662fn forward_upstream_untraced(
663 plain_pool: &ConnPool,
664 request: &Request,
665 client_ip: &str,
666 host: &str,
667 port: u16,
668 tls: bool,
669 trust: Option<&UpstreamTls>,
670 connect_timeout: Duration,
671 read_timeout: Duration,
672) -> Result<Response, String> {
673 if tls {
674 #[cfg(any(feature = "http-client", feature = "http2"))]
675 {
676 let (pool, config) = match trust {
677 Some(t) => (t.pool, Arc::clone(&t.config)),
678 None => (shared_tls_pool(), tls_client_config()),
679 };
680 return forward_via(pool, request, client_ip, host, port, read_timeout, || {
681 connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
682 });
683 }
684 #[cfg(not(any(feature = "http-client", feature = "http2")))]
685 {
686 let _ = trust;
687 return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
688 }
689 }
690 forward_pooled(plain_pool, request, client_ip, host, port, connect_timeout, read_timeout)
691}
692
693pub struct UpstreamTls {
701 #[cfg(any(feature = "http-client", feature = "http2"))]
702 config: Arc<rustls::ClientConfig>,
703 #[cfg(any(feature = "http-client", feature = "http2"))]
704 pool: &'static Pool<TlsStream>,
705 #[cfg(feature = "http2")]
707 async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
708 #[cfg(feature = "http2")]
710 h2_config: Arc<rustls::ClientConfig>,
711}
712
713impl UpstreamTls {
714 pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
716 UpstreamTls::new(Some(path), None)
717 }
718
719 pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
723 #[cfg(any(feature = "http-client", feature = "http2"))]
724 {
725 use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
726 let roots = match ca_file {
727 Some(path) => {
728 let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
729 let certs = CertificateDer::pem_slice_iter(&bytes)
730 .collect::<Result<Vec<_>, _>>()
731 .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
732 if certs.is_empty() {
733 return Err(format!("no certificates in CA file '{path}'"));
734 }
735 let mut roots = rustls::RootCertStore::empty();
736 for cert in certs {
737 roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
738 }
739 roots
740 }
741 None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
742 };
743 let builder = crate::tls_client_builder().with_root_certificates(roots);
744 let config = match client_cert {
745 None => builder.with_no_client_auth(),
746 Some((cert_path, key_path)) => {
747 let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
748 let chain = CertificateDer::pem_slice_iter(&bytes)
749 .collect::<Result<Vec<_>, _>>()
750 .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
751 if chain.is_empty() {
752 return Err(format!("no certificate in '{cert_path}'"));
753 }
754 let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
755 let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
756 builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
757 }
758 };
759 let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
760 Ok(UpstreamTls::with_config(config, &label))
761 }
762 #[cfg(not(any(feature = "http-client", feature = "http2")))]
763 {
764 let _ = client_cert;
765 Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
766 }
767 }
768
769 #[cfg(any(feature = "http-client", feature = "http2"))]
770 fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
771 #[cfg(feature = "http2")]
772 let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
773 UpstreamTls {
774 config: Arc::new(config),
775 pool: tls_pool_for_ca(label),
776 #[cfg(feature = "http2")]
777 async_pool: async_tls_pool_for_ca(label),
778 #[cfg(feature = "http2")]
779 h2_config,
780 }
781 }
782
783 #[cfg(feature = "http2")]
785 pub(crate) fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
786 &self.h2_config
787 }
788
789 pub(crate) fn reject_all(label: &str) -> UpstreamTls {
793 #[cfg(any(feature = "http-client", feature = "http2"))]
794 {
795 let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
796 UpstreamTls::with_config(config, &format!("reject-all:{label}"))
797 }
798 #[cfg(not(any(feature = "http-client", feature = "http2")))]
799 {
800 let _ = label;
801 UpstreamTls {}
802 }
803 }
804
805 #[cfg(feature = "http2")]
807 pub(crate) fn async_tls(&self) -> async_upstream::AsyncTls {
808 async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
809 }
810
811 #[cfg(any(feature = "http-client", feature = "http2"))]
813 pub(crate) fn client_config(&self) -> Arc<rustls::ClientConfig> {
814 Arc::clone(&self.config)
815 }
816}
817
818#[cfg(feature = "http2")]
821fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
822 static POOLS: std::sync::OnceLock<
823 std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
824 > = std::sync::OnceLock::new();
825 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
826 pools
827 .entry(path.to_string())
828 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
829}
830
831#[cfg(any(feature = "http-client", feature = "http2"))]
833fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
834 static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
835 std::sync::OnceLock::new();
836 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
837 pools
838 .entry(path.to_string())
839 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
840}
841
842pub(crate) fn forward_pooled(
846 pool: &ConnPool,
847 request: &Request,
848 client_ip: &str,
849 host: &str,
850 port: u16,
851 connect_timeout: Duration,
852 read_timeout: Duration,
853) -> Result<Response, String> {
854 forward_via(pool, request, client_ip, host, port, read_timeout, || connect_tcp(host, port, connect_timeout))
855}
856
857fn forward_via<S: UpstreamIo>(
864 pool: &Pool<S>,
865 request: &Request,
866 client_ip: &str,
867 host: &str,
868 port: u16,
869 read_timeout: Duration,
870 connect: impl Fn() -> Result<S, String>,
871) -> Result<Response, String> {
872 let key = format!("{}:{}", host, port);
873 if let Some(stream) = pool.acquire(&key) {
874 match exchange(pool, &key, stream, request, host, client_ip, read_timeout) {
875 Exchange::Done(response) => return Ok(response),
876 Exchange::NoResponse(_) if is_idempotent(&request.method) => {} Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
878 }
879 }
880 let stream = connect()?;
881 match exchange(pool, &key, stream, request, host, client_ip, read_timeout) {
882 Exchange::Done(response) => Ok(response),
883 Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
884 }
885}
886
887fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
891 let key = format!("{}:{}", host, port);
892 let addrs: Vec<_> = key
893 .to_socket_addrs()
894 .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
895 .collect();
896 let mut last_error = format!("no address resolved for {}", key);
897 for addr in addrs {
898 match TcpStream::connect_timeout(&addr, connect_timeout) {
899 Ok(stream) => {
900 let _ = stream.set_nodelay(true);
901 return Ok(stream);
902 }
903 Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
904 }
905 }
906 Err(last_error)
907}
908
909#[cfg(any(feature = "http-client", feature = "http2"))]
911fn shared_tls_pool() -> &'static Pool<TlsStream> {
912 static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
913 POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
914}
915
916#[cfg(any(feature = "http-client", feature = "http2"))]
920pub(crate) fn tls_client_config() -> Arc<rustls::ClientConfig> {
921 static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
922 Arc::clone(CONFIG.get_or_init(|| {
923 let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
924 Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
925 }))
926}
927
928#[cfg(any(feature = "http-client", feature = "http2"))]
929fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
930 let tcp = connect_tcp(host, port, connect_timeout)?;
931 let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
932 .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
933 let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
934 Ok(rustls::StreamOwned::new(conn, tcp))
935}
936
937fn is_idempotent(method: &str) -> bool {
938 matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
939}
940
941enum Exchange {
942 Done(Response),
943 NoResponse(String),
945 Failed(String),
946}
947
948fn exchange<S: UpstreamIo>(
951 pool: &Pool<S>,
952 key: &str,
953 mut stream: S,
954 request: &Request,
955 host: &str,
956 client_ip: &str,
957 read_timeout: Duration,
958) -> Exchange {
959 if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
960 return Exchange::Failed(e.to_string());
961 }
962 let req_bytes = build_request(request, host, client_ip, true);
964 if let Err(e) = stream.write_all(&req_bytes) {
965 return Exchange::NoResponse(format!("write to backend failed: {}", e));
966 }
967
968 let mut tmp = [0u8; 4096];
969 let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
970 Ok(head) => head,
971 Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
972 Err(HeadError::Partial(e)) => return Exchange::Failed(e),
973 };
974 let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
975
976 if response_has_no_body(&request.method, &header_lower) {
977 if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
978 pool.release(key, stream);
979 }
980 return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
981 Ok(response) => Exchange::Done(response),
982 Err(e) => Exchange::Failed(e),
983 };
984 }
985
986 if should_stream_response(&header_lower) {
987 return match parse_status_and_headers(&header_bytes) {
990 Ok(mut response) => {
991 response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
992 Exchange::Done(response)
993 }
994 Err(e) => Exchange::Failed(e),
995 };
996 }
997 match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
999 Ok((resp_bytes, reusable)) => {
1000 if reusable {
1001 pool.release(key, stream);
1002 }
1003 match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
1004 Ok(response) => Exchange::Done(response),
1005 Err(e) => Exchange::Failed(e),
1006 }
1007 }
1008 Err(e) => Exchange::Failed(e),
1009 }
1010}
1011
1012#[cfg(test)]
1017fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
1018 read_response_head(stream, tmp).map_err(|e| match e {
1019 HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
1020 })
1021}
1022
1023enum HeadError {
1027 NothingReceived(String),
1028 Partial(String),
1029}
1030
1031fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1032 read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
1033}
1034
1035fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1040 let (mut head, mut rest) = read_response_head(stream, tmp)?;
1041 let mut interim = 0;
1042 while is_interim_response(&head) {
1043 interim += 1;
1044 if interim > MAX_INTERIM_RESPONSES {
1045 return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
1046 }
1047 (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
1048 }
1049 Ok((head, rest))
1050}
1051
1052fn read_response_head_from<S: Read>(
1056 stream: &mut S,
1057 tmp: &mut [u8],
1058 mut buf: Vec<u8>,
1059 received: bool,
1060) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1061 loop {
1062 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1063 let body_prefix = buf[pos + 4..].to_vec();
1064 buf.truncate(pos + 4);
1065 return Ok((buf, body_prefix));
1066 }
1067 let nothing = buf.is_empty() && !received;
1068 let n = match stream.read(tmp) {
1069 Ok(n) => n,
1070 Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1071 Err(e) => return Err(HeadError::Partial(e.to_string())),
1072 };
1073 if n == 0 {
1074 let msg = "backend closed connection before headers were complete".to_string();
1075 return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1076 }
1077 buf.extend_from_slice(&tmp[..n]);
1078 }
1079}
1080
1081pub(crate) const MAX_INTERIM_RESPONSES: usize = 16;
1083
1084pub(crate) fn is_interim_response(head: &[u8]) -> bool {
1087 let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1088 let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1089 status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1090}
1091
1092pub(crate) fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1096 let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1097 method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1098}
1099
1100pub(crate) fn should_stream_response(header_lower: &str) -> bool {
1107 let is_sse = header_lower.lines().any(|l| {
1108 l.starts_with("content-type:") && l.contains("text/event-stream")
1109 });
1110 let is_chunked = header_lower.lines().any(|l| {
1111 l.starts_with("transfer-encoding:") && l.contains("chunked")
1112 });
1113 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1114 l.strip_prefix("content-length:")?.trim().parse().ok()
1115 });
1116 let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1117 is_sse || is_chunked || is_large
1118}
1119
1120#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1126pub(crate) struct HeadFacts {
1127 pub(crate) status_no_body: bool,
1129 pub(crate) sse: bool,
1130 pub(crate) chunked: bool,
1131 pub(crate) content_length: Option<usize>,
1133 pub(crate) connection_close: bool,
1134}
1135
1136#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1137impl HeadFacts {
1138 pub(crate) fn scan(head: &[u8]) -> HeadFacts {
1139 let text = std::str::from_utf8(head).unwrap_or("");
1140 let status = text.split_whitespace().nth(1).unwrap_or("");
1141 let mut facts = HeadFacts {
1142 status_no_body: status.starts_with('1') || status == "204" || status == "304",
1143 sse: false,
1144 chunked: false,
1145 content_length: None,
1146 connection_close: false,
1147 };
1148 for line in text.lines() {
1149 if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1150 facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1151 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1152 facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1153 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1154 if facts.content_length.is_none() {
1155 facts.content_length = value.trim().parse().ok();
1156 }
1157 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1158 facts.connection_close |= contains_ignore_ascii_case(value, "close");
1159 }
1160 }
1161 facts
1162 }
1163
1164 pub(crate) fn no_body(&self, method: &str) -> bool {
1166 method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1167 }
1168
1169 pub(crate) fn should_stream(&self) -> bool {
1171 self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1172 }
1173}
1174
1175fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1176 let bytes = line.as_bytes();
1177 (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1179 .then(|| &line[prefix.len()..])
1180}
1181
1182fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1183 haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1184}
1185
1186fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1188 let s = std::str::from_utf8(header_bytes)
1189 .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1190 let mut lines = s.lines();
1191 let status_line = lines.next().ok_or("empty backend response")?;
1192 let mut parts = status_line.splitn(3, ' ');
1193 let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1194 let status_code: i16 = parts
1195 .next()
1196 .unwrap_or("502")
1197 .parse()
1198 .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1199 let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1200 let mut headers = Vec::new();
1201 for line in lines {
1202 let line = line.trim_end_matches('\r');
1203 if line.is_empty() { break; }
1204 if let Some(colon) = line.find(':') {
1205 headers.push(crate::header::Header {
1206 name: line[..colon].trim().to_string().into(),
1207 value: (line[colon + 1..].trim().to_string()).into(),
1208 });
1209 }
1210 }
1211 Ok(Response {
1212 http_version,
1213 status_code,
1214 reason_phrase,
1215 headers,
1216 content_range_list: vec![],
1217 stream_file: None,
1218 stream_pipe: None,
1219 trailers: None,
1220 })
1221}
1222
1223fn read_response_from_partial<S: Read>(
1229 stream: &mut S,
1230 header_bytes: Vec<u8>,
1231 body_prefix: Vec<u8>,
1232 tmp: &mut [u8],
1233) -> Result<(Vec<u8>, bool), String> {
1234 let header_end = header_bytes.len();
1235 let mut buf = header_bytes;
1236 buf.extend_from_slice(&body_prefix);
1237
1238 let header_lower =
1239 std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1240 let connection_close =
1241 header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1242 let is_chunked = header_lower
1243 .lines()
1244 .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1245 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1246 l.strip_prefix("content-length:")?.trim().parse().ok()
1247 });
1248
1249 if is_chunked {
1250 let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1251 rewrite_as_content_length(&mut buf, header_end, &decoded);
1252 Ok((buf, !connection_close))
1253 } else if let Some(len) = content_length {
1254 while buf.len() < header_end + len {
1255 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1256 if n == 0 { break; }
1257 buf.extend_from_slice(&tmp[..n]);
1258 }
1259 Ok((buf, !connection_close))
1260 } else {
1261 loop {
1262 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1263 if n == 0 { break; }
1264 buf.extend_from_slice(&tmp[..n]);
1265 }
1266 Ok((buf, false))
1267 }
1268}
1269
1270struct Backend {
1273 host: String,
1274 port: u16,
1275 tls: bool,
1278}
1279
1280impl Backend {
1281 fn parse(url: &str) -> Option<Self> {
1282 let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1283 (r, true, 443u16)
1284 } else if let Some(r) = url.strip_prefix("h2s://") {
1285 (r, true, 443u16)
1286 } else if let Some(r) = url.strip_prefix("grpcs://") {
1287 (r, true, 443u16)
1288 } else if let Some(r) = url.strip_prefix("http://") {
1289 (r, false, 80u16)
1290 } else if let Some(r) = url.strip_prefix("h2://") {
1291 (r, false, 80u16)
1292 } else if let Some(r) = url.strip_prefix("grpc://") {
1293 (r, false, 80u16)
1294 } else {
1295 (url, false, 80u16)
1296 };
1297 let host_port = rest.split('/').next().unwrap_or(rest);
1299 let (host, port) = if let Some(colon) = host_port.rfind(':') {
1300 let port_str = &host_port[colon + 1..];
1301 if let Ok(p) = port_str.parse::<u16>() {
1302 (host_port[..colon].to_string(), p)
1303 } else {
1304 (host_port.to_string(), default_port)
1305 }
1306 } else {
1307 (host_port.to_string(), default_port)
1308 };
1309 if host.is_empty() {
1310 return None;
1311 }
1312 Some(Backend { host, port, tls })
1313 }
1314}
1315
1316#[cfg(feature = "http2")]
1327pub struct H2ReverseProxy {
1328 inner: ReverseProxy,
1329}
1330
1331#[cfg(feature = "http2")]
1332impl H2ReverseProxy {
1333 pub fn new<I, S>(backends: I) -> Self
1344 where
1345 I: IntoIterator<Item = S>,
1346 S: AsRef<str>,
1347 {
1348 H2ReverseProxy {
1349 inner: ReverseProxy::new(backends),
1350 }
1351 }
1352
1353 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1355 self.inner = self.inner.path_prefix(prefix);
1356 self
1357 }
1358
1359 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1361 self.inner = self.inner.connect_timeout_ms(ms);
1362 self
1363 }
1364
1365 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1370 self.inner = self.inner.read_timeout_ms(ms);
1371 self
1372 }
1373
1374 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1377 self.inner = self.inner.tls_ca_file(path)?;
1378 Ok(self)
1379 }
1380
1381 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1384 self.inner = self.inner.tls_client_cert(cert, key)?;
1385 Ok(self)
1386 }
1387
1388 fn matches(&self, request: &Request) -> bool {
1389 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1390 }
1391}
1392
1393#[cfg(feature = "http2")]
1394impl crate::middleware::Middleware for H2ReverseProxy {
1395 fn handle(
1396 &self,
1397 request: &crate::request::Request,
1398 connection: &crate::server::ConnectionInfo,
1399 next: &dyn crate::application::Application,
1400 ) -> Result<crate::response::Response, String> {
1401 if !self.matches(request) {
1402 return next.execute(request, connection);
1403 }
1404 if self.inner.backends.is_empty() {
1405 return Ok(bad_gateway());
1406 }
1407 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1409 let n = self.inner.backends.len();
1410 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1411 for attempt in 0..attempts {
1412 let backend = &self.inner.backends[(start + attempt) % n];
1413 let tls = backend.tls.then(|| match &self.inner.trust {
1414 Some(trust) => trust.h2_config(),
1415 None => h2_upstream::default_tls(),
1416 });
1417 let target = h2_upstream::Target {
1418 backend,
1419 tls,
1420 connect_timeout: self.inner.connect_timeout,
1421 read_timeout: self.inner.read_timeout,
1422 };
1423 if let Ok(response) = h2_upstream::forward(request, &connection.client.ip, &target) {
1424 return Ok(response);
1425 }
1426 }
1427 Ok(bad_gateway())
1428 }
1429
1430 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1433 true
1434 }
1435
1436 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1439 self.matches(request)
1440 }
1441}
1442
1443#[cfg(feature = "http2")]
1447pub(crate) fn forward_h2(
1448 request: &Request,
1449 client_ip: &str,
1450 url: &str,
1451 tls: bool,
1452 trust: Option<&UpstreamTls>,
1453 connect_timeout: Duration,
1454 read_timeout: Duration,
1455) -> Result<Response, String> {
1456 let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1457 backend.tls |= tls;
1458 let tls = backend.tls.then(|| match trust {
1459 Some(t) => t.h2_config(),
1460 None => h2_upstream::default_tls(),
1461 });
1462 h2_upstream::forward(request, client_ip, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout })
1463}
1464
1465#[cfg(feature = "http2")]
1485pub struct GrpcProxy {
1486 inner: H2ReverseProxy,
1487}
1488
1489#[cfg(feature = "http2")]
1490impl GrpcProxy {
1491 pub fn new<I, S>(backends: I) -> Self
1501 where
1502 I: IntoIterator<Item = S>,
1503 S: AsRef<str>,
1504 {
1505 GrpcProxy { inner: H2ReverseProxy::new(backends) }
1506 }
1507
1508 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1510 self.inner = self.inner.path_prefix(prefix);
1511 self
1512 }
1513
1514 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1516 self.inner = self.inner.connect_timeout_ms(ms);
1517 self
1518 }
1519
1520 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1522 self.inner = self.inner.read_timeout_ms(ms);
1523 self
1524 }
1525
1526 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1528 self.inner = self.inner.tls_ca_file(path)?;
1529 Ok(self)
1530 }
1531
1532 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1535 self.inner = self.inner.tls_client_cert(cert, key)?;
1536 Ok(self)
1537 }
1538}
1539
1540#[cfg(feature = "http2")]
1541impl crate::middleware::Middleware for GrpcProxy {
1542 fn handle(
1543 &self,
1544 request: &crate::request::Request,
1545 connection: &crate::server::ConnectionInfo,
1546 next: &dyn crate::application::Application,
1547 ) -> Result<crate::response::Response, String> {
1548 if is_grpc(request) {
1549 self.inner.handle(request, connection, next)
1550 } else {
1551 next.execute(request, connection)
1552 }
1553 }
1554
1555 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1556 true
1557 }
1558
1559 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1560 is_grpc(request) && self.inner.matches(request)
1561 }
1562}
1563
1564#[cfg(feature = "http2")]
1565fn is_grpc(request: &Request) -> bool {
1566 request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
1567}
1568
1569#[cfg(test)]
1572mod backend_parse_tests {
1573 use super::Backend;
1574
1575 fn parse(url: &str) -> Option<(String, u16, bool)> {
1576 Backend::parse(url).map(|b| (b.host, b.port, b.tls))
1577 }
1578
1579 #[test]
1580 fn bare_host_port() {
1581 assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
1582 }
1583
1584 #[test]
1585 fn http_scheme() {
1586 assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
1587 }
1588
1589 #[test]
1590 fn h2_scheme_plain() {
1591 assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
1592 }
1593
1594 #[test]
1595 fn grpc_scheme_plain() {
1596 assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
1597 }
1598
1599 #[test]
1600 fn https_scheme_sets_tls_and_default_port() {
1601 assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
1602 }
1603
1604 #[test]
1605 fn https_scheme_explicit_port() {
1606 assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
1607 }
1608
1609 #[test]
1610 fn h2s_scheme_sets_tls() {
1611 assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
1612 }
1613
1614 #[test]
1615 fn h2s_scheme_explicit_port() {
1616 assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
1617 }
1618
1619 #[test]
1620 fn grpcs_scheme_sets_tls() {
1621 assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
1622 }
1623
1624 #[test]
1625 fn grpcs_scheme_explicit_port() {
1626 assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
1627 }
1628
1629 #[test]
1630 fn empty_host_returns_none() {
1631 assert_eq!(None, parse("https://"));
1632 }
1633
1634 #[test]
1635 fn bare_host_no_port_defaults_to_80() {
1636 assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
1637 }
1638}