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 let forwarded = |h: &&crate::header::Header| {
310 !h.name.is_empty()
312 && !is_hop_by_hop_or_host(&h.name)
313 && !h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_LENGTH)
314 && !h.name.eq_ignore_ascii_case("X-Forwarded-For")
315 && !connection.is_some_and(|c| connection_listed(c, &h.name))
316 };
317 let prior_xff = request.header("X-Forwarded-For").map(|h| h.value.as_ref()).filter(|v| !v.trim().is_empty());
318 let body_len = Decimal::new(request.body.len() as u128);
319 let capacity = request.method.len() + request.request_uri.len() + backend_host.len() + 25
320 + request.headers.iter().filter(forwarded).map(|h| h.name.len() + h.value.len() + 4).sum::<usize>()
321 + client_ip.len() + 19 + prior_xff.map_or(0, |v| v.len() + 2)
322 + 13
323 + 24
324 + if request.body.is_empty() { 0 } else { body_len.as_str().len() + 18 }
325 + 2
326 + request.body.len();
327 let mut out: Vec<u8> = Vec::with_capacity(capacity);
328 for part in [request.method.as_str(), " ", request.request_uri.as_str(), " HTTP/1.1\r\nHost: ", backend_host, "\r\n"] {
329 out.extend_from_slice(part.as_bytes());
330 }
331 for h in request.headers.iter().filter(forwarded) {
332 for part in [h.name.as_ref(), ": ", h.value.as_ref(), "\r\n"] {
333 out.extend_from_slice(part.as_bytes());
334 }
335 }
336 out.extend_from_slice(b"X-Forwarded-For: ");
337 if let Some(prior) = prior_xff {
338 out.extend_from_slice(prior.as_bytes());
339 out.extend_from_slice(b", ");
340 }
341 for part in [client_ip, "\r\n", "Via: 1.1 rws\r\n"] {
342 out.extend_from_slice(part.as_bytes());
343 }
344 if keep_alive {
345 out.extend_from_slice(b"Connection: keep-alive\r\n");
346 } else {
347 out.extend_from_slice(b"Connection: close\r\n");
348 }
349 if !request.body.is_empty() {
350 out.extend_from_slice(b"Content-Length: ");
351 out.extend_from_slice(body_len.as_str().as_bytes());
352 out.extend_from_slice(b"\r\n");
353 }
354 out.extend_from_slice(b"\r\n");
355 out.extend_from_slice(&request.body);
356 out
357}
358
359fn is_hop_by_hop_or_host(name: &str) -> bool {
364 if name.is_ascii() {
365 name.eq_ignore_ascii_case("host") || HOP_BY_HOP.iter().any(|h| name.eq_ignore_ascii_case(h))
366 } else {
367 let lower = name.to_lowercase();
368 lower == "host" || HOP_BY_HOP.contains(&lower.as_str())
369 }
370}
371
372fn connection_listed(connection: &str, name: &str) -> bool {
375 connection.split(',').any(|token| token.trim().eq_ignore_ascii_case(name))
376}
377
378fn decode_chunked<S: Read>(
383 stream: &mut S,
384 buf: &[u8],
385 header_end: usize,
386 tmp: &mut [u8],
387) -> Result<Vec<u8>, String> {
388 let mut raw: Vec<u8> = buf[header_end..].to_vec();
390 let mut decoded: Vec<u8> = Vec::new();
391
392 loop {
393 let crlf = loop {
395 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
396 break p;
397 }
398 let n = stream.read(tmp).map_err(|e| e.to_string())?;
399 if n == 0 {
400 return Err("chunked: premature EOF reading chunk size".to_string());
401 }
402 raw.extend_from_slice(&tmp[..n]);
403 };
404
405 let size_line = std::str::from_utf8(&raw[..crlf])
407 .map_err(|_| "chunked: non-UTF-8 chunk size line".to_string())?;
408 let size_str = size_line.split(';').next().unwrap_or("").trim();
409 let chunk_size = usize::from_str_radix(size_str, 16)
410 .map_err(|_| format!("chunked: invalid chunk size '{}'", size_str))?;
411 raw.drain(..crlf + 2); if chunk_size == 0 {
414 loop {
418 let line_end = loop {
419 if let Some(p) = raw.windows(2).position(|w| w == b"\r\n") {
420 break p;
421 }
422 let n = stream.read(tmp).map_err(|e| e.to_string())?;
423 if n == 0 {
424 return Err("chunked: premature EOF in trailer".to_string());
425 }
426 raw.extend_from_slice(&tmp[..n]);
427 };
428 raw.drain(..line_end + 2);
429 if line_end == 0 {
430 break;
431 }
432 }
433 break;
434 }
435
436 while raw.len() < chunk_size + 2 {
438 let n = stream.read(tmp).map_err(|e| e.to_string())?;
439 if n == 0 {
440 return Err("chunked: premature EOF reading chunk body".to_string());
441 }
442 raw.extend_from_slice(&tmp[..n]);
443 }
444 decoded.extend_from_slice(&raw[..chunk_size]);
445 raw.drain(..chunk_size + 2); }
447
448 Ok(decoded)
449}
450
451fn rewrite_as_content_length(buf: &mut Vec<u8>, header_end: usize, decoded: &[u8]) {
454 let header_str = std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_string();
455 buf.clear();
456 for line in header_str.lines() {
457 if line.to_ascii_lowercase().starts_with("transfer-encoding:") || line.is_empty() {
458 continue;
459 }
460 buf.extend_from_slice(line.as_bytes());
461 buf.extend_from_slice(b"\r\n");
462 }
463 let _ = write!(buf, "Content-Length: {}\r\n\r\n", decoded.len());
464 buf.extend_from_slice(decoded);
465}
466
467pub(crate) const REGENERATED_OR_HOP_BY_HOP: &[&str] = &[
470 "content-length", "transfer-encoding", "connection", "keep-alive",
471 "proxy-connection", "te", "trailer", "upgrade",
472];
473
474pub(crate) fn normalize_upstream_response(mut response: Response) -> Response {
483 response.http_version.clear();
484 response.http_version.push_str(crate::http::VERSION.http_1_1);
485 let has_body = !response.content_range_list.is_empty();
486 if let [range] = response.content_range_list.as_mut_slice() {
487 if let Some(h) = response
488 .headers
489 .iter()
490 .find(|h| h.name.eq_ignore_ascii_case(crate::header::Header::_CONTENT_TYPE))
491 {
492 range.content_type.clear();
493 range.content_type.push_str(&h.value);
494 }
495 }
496 response.headers.retain(|h| {
499 if h.name.eq_ignore_ascii_case("content-type") {
500 return !has_body;
502 }
503 !REGENERATED_OR_HOP_BY_HOP.iter().any(|name| h.name.eq_ignore_ascii_case(name))
504 });
505 response
506}
507
508pub(crate) fn bad_gateway() -> Response {
509 let cr = Range::get_content_range(
510 b"502 Bad Gateway".to_vec(),
511 MimeType::TEXT_PLAIN.to_string(),
512 );
513 let mut r = Response::new();
514 r.status_code = *STATUS_CODE_REASON_PHRASE.n502_bad_gateway.status_code;
515 r.reason_phrase = STATUS_CODE_REASON_PHRASE
516 .n502_bad_gateway
517 .reason_phrase
518 .to_string();
519 r.content_range_list = vec![cr];
520 r
521}
522
523const STREAM_THRESHOLD: usize = 1024 * 1024; pub(crate) struct ConcatReader<R: Read + Send> {
531 prefix: Vec<u8>,
532 prefix_pos: usize,
533 inner: R,
534}
535
536impl<R: Read + Send> ConcatReader<R> {
537 fn new(prefix: Vec<u8>, inner: R) -> Self {
538 ConcatReader { prefix, prefix_pos: 0, inner }
539 }
540}
541
542impl<R: Read + Send> Read for ConcatReader<R> {
543 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
544 if self.prefix_pos < self.prefix.len() {
545 let avail = &self.prefix[self.prefix_pos..];
546 let n = buf.len().min(avail.len());
547 buf[..n].copy_from_slice(&avail[..n]);
548 self.prefix_pos += n;
549 return Ok(n);
550 }
551 self.inner.read(buf)
552 }
553}
554
555
556pub(crate) const POOL_MAX_IDLE: usize = 64;
560
561pub(crate) fn shared_pool() -> &'static ConnPool {
564 static POOL: std::sync::OnceLock<ConnPool> = std::sync::OnceLock::new();
565 POOL.get_or_init(|| ConnPool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
566}
567
568pub(crate) trait UpstreamIo: Read + Write + Send + 'static {
571 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()>;
572}
573
574impl UpstreamIo for TcpStream {
575 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
576 self.set_read_timeout(Some(read))?;
577 self.set_write_timeout(Some(write))
578 }
579}
580
581#[cfg(any(feature = "http-client", feature = "http2"))]
582pub(crate) type TlsStream = rustls::StreamOwned<rustls::ClientConnection, TcpStream>;
583
584#[cfg(any(feature = "http-client", feature = "http2"))]
585impl UpstreamIo for TlsStream {
586 fn set_io_timeouts(&self, read: Duration, write: Duration) -> std::io::Result<()> {
587 self.sock.set_io_timeouts(read, write)
588 }
589}
590
591pub(crate) fn forward_upstream(
597 plain_pool: &ConnPool,
598 request: &Request,
599 client_ip: &str,
600 host: &str,
601 port: u16,
602 tls: bool,
603 connect_timeout: Duration,
604 read_timeout: Duration,
605) -> Result<Response, String> {
606 forward_upstream_trusting(plain_pool, request, client_ip, host, port, tls, None, connect_timeout, read_timeout)
607}
608
609#[allow(clippy::too_many_arguments)]
612pub(crate) fn forward_upstream_trusting(
613 plain_pool: &ConnPool,
614 request: &Request,
615 client_ip: &str,
616 host: &str,
617 port: u16,
618 tls: bool,
619 trust: Option<&UpstreamTls>,
620 connect_timeout: Duration,
621 read_timeout: Duration,
622) -> Result<Response, String> {
623 if tls {
624 #[cfg(any(feature = "http-client", feature = "http2"))]
625 {
626 let (pool, config) = match trust {
627 Some(t) => (t.pool, Arc::clone(&t.config)),
628 None => (shared_tls_pool(), tls_client_config()),
629 };
630 return forward_via(pool, request, client_ip, host, port, read_timeout, || {
631 connect_tls_with(Arc::clone(&config), host, port, connect_timeout)
632 });
633 }
634 #[cfg(not(any(feature = "http-client", feature = "http2")))]
635 {
636 let _ = trust;
637 return Err("HTTPS backends need the http2 or http-client feature, which this build doesn't include".to_string());
638 }
639 }
640 forward_pooled(plain_pool, request, client_ip, host, port, connect_timeout, read_timeout)
641}
642
643pub struct UpstreamTls {
651 #[cfg(any(feature = "http-client", feature = "http2"))]
652 config: Arc<rustls::ClientConfig>,
653 #[cfg(any(feature = "http-client", feature = "http2"))]
654 pool: &'static Pool<TlsStream>,
655 #[cfg(feature = "http2")]
657 async_pool: &'static Pool<async_upstream::AsyncTlsStream>,
658 #[cfg(feature = "http2")]
660 h2_config: Arc<rustls::ClientConfig>,
661}
662
663impl UpstreamTls {
664 pub fn from_ca_file(path: &str) -> Result<UpstreamTls, String> {
666 UpstreamTls::new(Some(path), None)
667 }
668
669 pub fn new(ca_file: Option<&str>, client_cert: Option<(&str, &str)>) -> Result<UpstreamTls, String> {
673 #[cfg(any(feature = "http-client", feature = "http2"))]
674 {
675 use rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
676 let roots = match ca_file {
677 Some(path) => {
678 let bytes = std::fs::read(path).map_err(|e| format!("cannot read CA file '{path}': {e}"))?;
679 let certs = CertificateDer::pem_slice_iter(&bytes)
680 .collect::<Result<Vec<_>, _>>()
681 .map_err(|e| format!("cannot parse CA file '{path}': {e}"))?;
682 if certs.is_empty() {
683 return Err(format!("no certificates in CA file '{path}'"));
684 }
685 let mut roots = rustls::RootCertStore::empty();
686 for cert in certs {
687 roots.add(cert).map_err(|e| format!("invalid CA certificate in '{path}': {e}"))?;
688 }
689 roots
690 }
691 None => rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()),
692 };
693 let builder = crate::tls_client_builder().with_root_certificates(roots);
694 let config = match client_cert {
695 None => builder.with_no_client_auth(),
696 Some((cert_path, key_path)) => {
697 let bytes = std::fs::read(cert_path).map_err(|e| format!("cannot read client certificate '{cert_path}': {e}"))?;
698 let chain = CertificateDer::pem_slice_iter(&bytes)
699 .collect::<Result<Vec<_>, _>>()
700 .map_err(|e| format!("cannot parse client certificate '{cert_path}': {e}"))?;
701 if chain.is_empty() {
702 return Err(format!("no certificate in '{cert_path}'"));
703 }
704 let bytes = std::fs::read(key_path).map_err(|e| format!("cannot read client key '{key_path}': {e}"))?;
705 let key = PrivateKeyDer::from_pem_slice(&bytes).map_err(|e| format!("cannot parse client key '{key_path}': {e}"))?;
706 builder.with_client_auth_cert(chain, key).map_err(|e| format!("client certificate '{cert_path}': {e}"))?
707 }
708 };
709 let label = format!("{}|{}", ca_file.unwrap_or("webpki"), client_cert.map_or("", |(cert, _)| cert));
710 Ok(UpstreamTls::with_config(config, &label))
711 }
712 #[cfg(not(any(feature = "http-client", feature = "http2")))]
713 {
714 let _ = client_cert;
715 Err(format!("tls_ca_file '{}': HTTPS backends need the http2 or http-client feature", ca_file.unwrap_or("")))
716 }
717 }
718
719 #[cfg(any(feature = "http-client", feature = "http2"))]
720 fn with_config(config: rustls::ClientConfig, label: &str) -> UpstreamTls {
721 #[cfg(feature = "http2")]
722 let h2_config = Arc::new(h2_upstream::with_h2_alpn(config.clone()));
723 UpstreamTls {
724 config: Arc::new(config),
725 pool: tls_pool_for_ca(label),
726 #[cfg(feature = "http2")]
727 async_pool: async_tls_pool_for_ca(label),
728 #[cfg(feature = "http2")]
729 h2_config,
730 }
731 }
732
733 #[cfg(feature = "http2")]
735 pub(crate) fn h2_config(&self) -> &Arc<rustls::ClientConfig> {
736 &self.h2_config
737 }
738
739 pub(crate) fn reject_all(label: &str) -> UpstreamTls {
743 #[cfg(any(feature = "http-client", feature = "http2"))]
744 {
745 let config = crate::tls_client_builder().with_root_certificates(rustls::RootCertStore::empty()).with_no_client_auth();
746 UpstreamTls::with_config(config, &format!("reject-all:{label}"))
747 }
748 #[cfg(not(any(feature = "http-client", feature = "http2")))]
749 {
750 let _ = label;
751 UpstreamTls {}
752 }
753 }
754
755 #[cfg(feature = "http2")]
757 pub(crate) fn async_tls(&self) -> async_upstream::AsyncTls {
758 async_upstream::AsyncTls { config: Arc::clone(&self.config), pool: self.async_pool }
759 }
760
761 #[cfg(any(feature = "http-client", feature = "http2"))]
763 pub(crate) fn client_config(&self) -> Arc<rustls::ClientConfig> {
764 Arc::clone(&self.config)
765 }
766}
767
768#[cfg(feature = "http2")]
771fn async_tls_pool_for_ca(path: &str) -> &'static Pool<async_upstream::AsyncTlsStream> {
772 static POOLS: std::sync::OnceLock<
773 std::sync::Mutex<std::collections::HashMap<String, &'static Pool<async_upstream::AsyncTlsStream>>>,
774 > = std::sync::OnceLock::new();
775 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
776 pools
777 .entry(path.to_string())
778 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
779}
780
781#[cfg(any(feature = "http-client", feature = "http2"))]
783fn tls_pool_for_ca(path: &str) -> &'static Pool<TlsStream> {
784 static POOLS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, &'static Pool<TlsStream>>>> =
785 std::sync::OnceLock::new();
786 let mut pools = POOLS.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());
787 pools
788 .entry(path.to_string())
789 .or_insert_with(|| Box::leak(Box::new(Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))))
790}
791
792pub(crate) fn forward_pooled(
796 pool: &ConnPool,
797 request: &Request,
798 client_ip: &str,
799 host: &str,
800 port: u16,
801 connect_timeout: Duration,
802 read_timeout: Duration,
803) -> Result<Response, String> {
804 forward_via(pool, request, client_ip, host, port, read_timeout, || connect_tcp(host, port, connect_timeout))
805}
806
807fn forward_via<S: UpstreamIo>(
814 pool: &Pool<S>,
815 request: &Request,
816 client_ip: &str,
817 host: &str,
818 port: u16,
819 read_timeout: Duration,
820 connect: impl Fn() -> Result<S, String>,
821) -> Result<Response, String> {
822 let key = format!("{}:{}", host, port);
823 if let Some(stream) = pool.acquire(&key) {
824 match exchange(pool, &key, stream, request, host, client_ip, read_timeout) {
825 Exchange::Done(response) => return Ok(response),
826 Exchange::NoResponse(_) if is_idempotent(&request.method) => {} Exchange::NoResponse(e) | Exchange::Failed(e) => return Err(e),
828 }
829 }
830 let stream = connect()?;
831 match exchange(pool, &key, stream, request, host, client_ip, read_timeout) {
832 Exchange::Done(response) => Ok(response),
833 Exchange::NoResponse(e) | Exchange::Failed(e) => Err(e),
834 }
835}
836
837fn connect_tcp(host: &str, port: u16, connect_timeout: Duration) -> Result<TcpStream, String> {
841 let key = format!("{}:{}", host, port);
842 let addrs: Vec<_> = key
843 .to_socket_addrs()
844 .map_err(|e| format!("DNS lookup for {} failed: {}", key, e))?
845 .collect();
846 let mut last_error = format!("no address resolved for {}", key);
847 for addr in addrs {
848 match TcpStream::connect_timeout(&addr, connect_timeout) {
849 Ok(stream) => {
850 let _ = stream.set_nodelay(true);
851 return Ok(stream);
852 }
853 Err(e) => last_error = format!("connect to {} ({}) failed: {}", key, addr, e),
854 }
855 }
856 Err(last_error)
857}
858
859#[cfg(any(feature = "http-client", feature = "http2"))]
861fn shared_tls_pool() -> &'static Pool<TlsStream> {
862 static POOL: std::sync::OnceLock<Pool<TlsStream>> = std::sync::OnceLock::new();
863 POOL.get_or_init(|| Pool::new(POOL_MAX_IDLE, Duration::from_secs(60)))
864}
865
866#[cfg(any(feature = "http-client", feature = "http2"))]
870pub(crate) fn tls_client_config() -> Arc<rustls::ClientConfig> {
871 static CONFIG: std::sync::OnceLock<Arc<rustls::ClientConfig>> = std::sync::OnceLock::new();
872 Arc::clone(CONFIG.get_or_init(|| {
873 let roots = rustls::RootCertStore::from_iter(webpki_roots::TLS_SERVER_ROOTS.iter().cloned());
874 Arc::new(crate::tls_client_builder().with_root_certificates(roots).with_no_client_auth())
875 }))
876}
877
878#[cfg(any(feature = "http-client", feature = "http2"))]
879fn connect_tls_with(config: Arc<rustls::ClientConfig>, host: &str, port: u16, connect_timeout: Duration) -> Result<TlsStream, String> {
880 let tcp = connect_tcp(host, port, connect_timeout)?;
881 let server_name = rustls::pki_types::ServerName::try_from(host.to_string())
882 .map_err(|e| format!("invalid upstream hostname '{}': {}", host, e))?;
883 let conn = rustls::ClientConnection::new(config, server_name).map_err(|e| e.to_string())?;
884 Ok(rustls::StreamOwned::new(conn, tcp))
885}
886
887fn is_idempotent(method: &str) -> bool {
888 matches!(method, "GET" | "HEAD" | "OPTIONS" | "TRACE" | "PUT" | "DELETE")
889}
890
891enum Exchange {
892 Done(Response),
893 NoResponse(String),
895 Failed(String),
896}
897
898fn exchange<S: UpstreamIo>(
901 pool: &Pool<S>,
902 key: &str,
903 mut stream: S,
904 request: &Request,
905 host: &str,
906 client_ip: &str,
907 read_timeout: Duration,
908) -> Exchange {
909 if let Err(e) = stream.set_io_timeouts(read_timeout, Duration::from_secs(10)) {
910 return Exchange::Failed(e.to_string());
911 }
912 let req_bytes = build_request(request, host, client_ip, true);
914 if let Err(e) = stream.write_all(&req_bytes) {
915 return Exchange::NoResponse(format!("write to backend failed: {}", e));
916 }
917
918 let mut tmp = [0u8; 4096];
919 let (header_bytes, body_prefix) = match read_final_response_head(&mut stream, &mut tmp) {
920 Ok(head) => head,
921 Err(HeadError::NothingReceived(e)) => return Exchange::NoResponse(e),
922 Err(HeadError::Partial(e)) => return Exchange::Failed(e),
923 };
924 let header_lower = std::str::from_utf8(&header_bytes).unwrap_or("").to_ascii_lowercase();
925
926 if response_has_no_body(&request.method, &header_lower) {
927 if !header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close")) {
928 pool.release(key, stream);
929 }
930 return match Response::parse_upstream(&header_bytes, REGENERATED_OR_HOP_BY_HOP) {
931 Ok(response) => Exchange::Done(response),
932 Err(e) => Exchange::Failed(e),
933 };
934 }
935
936 if should_stream_response(&header_lower) {
937 return match parse_status_and_headers(&header_bytes) {
940 Ok(mut response) => {
941 response.stream_pipe = Some(Box::new(ConcatReader::new(body_prefix, stream)));
942 Exchange::Done(response)
943 }
944 Err(e) => Exchange::Failed(e),
945 };
946 }
947 match read_response_from_partial(&mut stream, header_bytes, body_prefix, &mut tmp) {
949 Ok((resp_bytes, reusable)) => {
950 if reusable {
951 pool.release(key, stream);
952 }
953 match Response::parse_upstream(&resp_bytes, REGENERATED_OR_HOP_BY_HOP) {
954 Ok(response) => Exchange::Done(response),
955 Err(e) => Exchange::Failed(e),
956 }
957 }
958 Err(e) => Exchange::Failed(e),
959 }
960}
961
962#[cfg(test)]
967fn read_headers_only(stream: &mut TcpStream, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), String> {
968 read_response_head(stream, tmp).map_err(|e| match e {
969 HeadError::NothingReceived(msg) | HeadError::Partial(msg) => msg,
970 })
971}
972
973enum HeadError {
977 NothingReceived(String),
978 Partial(String),
979}
980
981fn read_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
982 read_response_head_from(stream, tmp, Vec::with_capacity(4096), false)
983}
984
985fn read_final_response_head<S: Read>(stream: &mut S, tmp: &mut [u8]) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
990 let (mut head, mut rest) = read_response_head(stream, tmp)?;
991 let mut interim = 0;
992 while is_interim_response(&head) {
993 interim += 1;
994 if interim > MAX_INTERIM_RESPONSES {
995 return Err(HeadError::Partial("too many interim (1xx) responses from the backend".to_string()));
996 }
997 (head, rest) = read_response_head_from(stream, tmp, rest, true)?;
998 }
999 Ok((head, rest))
1000}
1001
1002fn read_response_head_from<S: Read>(
1006 stream: &mut S,
1007 tmp: &mut [u8],
1008 mut buf: Vec<u8>,
1009 received: bool,
1010) -> Result<(Vec<u8>, Vec<u8>), HeadError> {
1011 loop {
1012 if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
1013 let body_prefix = buf[pos + 4..].to_vec();
1014 buf.truncate(pos + 4);
1015 return Ok((buf, body_prefix));
1016 }
1017 let nothing = buf.is_empty() && !received;
1018 let n = match stream.read(tmp) {
1019 Ok(n) => n,
1020 Err(e) if nothing => return Err(HeadError::NothingReceived(e.to_string())),
1021 Err(e) => return Err(HeadError::Partial(e.to_string())),
1022 };
1023 if n == 0 {
1024 let msg = "backend closed connection before headers were complete".to_string();
1025 return Err(if nothing { HeadError::NothingReceived(msg) } else { HeadError::Partial(msg) });
1026 }
1027 buf.extend_from_slice(&tmp[..n]);
1028 }
1029}
1030
1031pub(crate) const MAX_INTERIM_RESPONSES: usize = 16;
1033
1034pub(crate) fn is_interim_response(head: &[u8]) -> bool {
1037 let line_end = head.iter().position(|b| *b == b'\r' || *b == b'\n').unwrap_or(head.len());
1038 let status = head[..line_end].split(|b| *b == b' ').nth(1).unwrap_or(&[]);
1039 status.len() == 3 && status.iter().all(u8::is_ascii_digit) && status[0] == b'1' && status != b"101"
1040}
1041
1042pub(crate) fn response_has_no_body(method: &str, header_lower: &str) -> bool {
1046 let status = header_lower.split_whitespace().nth(1).unwrap_or("");
1047 method.eq_ignore_ascii_case("HEAD") || status.starts_with('1') || status == "204" || status == "304"
1048}
1049
1050pub(crate) fn should_stream_response(header_lower: &str) -> bool {
1057 let is_sse = header_lower.lines().any(|l| {
1058 l.starts_with("content-type:") && l.contains("text/event-stream")
1059 });
1060 let is_chunked = header_lower.lines().any(|l| {
1061 l.starts_with("transfer-encoding:") && l.contains("chunked")
1062 });
1063 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1064 l.strip_prefix("content-length:")?.trim().parse().ok()
1065 });
1066 let is_large = content_length.map_or(false, |n| n > STREAM_THRESHOLD);
1067 is_sse || is_chunked || is_large
1068}
1069
1070#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1076pub(crate) struct HeadFacts {
1077 pub(crate) status_no_body: bool,
1079 pub(crate) sse: bool,
1080 pub(crate) chunked: bool,
1081 pub(crate) content_length: Option<usize>,
1083 pub(crate) connection_close: bool,
1084}
1085
1086#[cfg_attr(not(feature = "http2"), allow(dead_code))]
1087impl HeadFacts {
1088 pub(crate) fn scan(head: &[u8]) -> HeadFacts {
1089 let text = std::str::from_utf8(head).unwrap_or("");
1090 let status = text.split_whitespace().nth(1).unwrap_or("");
1091 let mut facts = HeadFacts {
1092 status_no_body: status.starts_with('1') || status == "204" || status == "304",
1093 sse: false,
1094 chunked: false,
1095 content_length: None,
1096 connection_close: false,
1097 };
1098 for line in text.lines() {
1099 if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-type:") {
1100 facts.sse |= contains_ignore_ascii_case(value, "text/event-stream");
1101 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "transfer-encoding:") {
1102 facts.chunked |= contains_ignore_ascii_case(value, "chunked");
1103 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "content-length:") {
1104 if facts.content_length.is_none() {
1105 facts.content_length = value.trim().parse().ok();
1106 }
1107 } else if let Some(value) = strip_prefix_ignore_ascii_case(line, "connection:") {
1108 facts.connection_close |= contains_ignore_ascii_case(value, "close");
1109 }
1110 }
1111 facts
1112 }
1113
1114 pub(crate) fn no_body(&self, method: &str) -> bool {
1116 method.eq_ignore_ascii_case("HEAD") || self.status_no_body
1117 }
1118
1119 pub(crate) fn should_stream(&self) -> bool {
1121 self.sse || self.chunked || self.content_length.is_some_and(|n| n > STREAM_THRESHOLD)
1122 }
1123}
1124
1125fn strip_prefix_ignore_ascii_case<'a>(line: &'a str, prefix: &str) -> Option<&'a str> {
1126 let bytes = line.as_bytes();
1127 (bytes.len() >= prefix.len() && bytes[..prefix.len()].eq_ignore_ascii_case(prefix.as_bytes()))
1129 .then(|| &line[prefix.len()..])
1130}
1131
1132fn contains_ignore_ascii_case(haystack: &str, needle: &str) -> bool {
1133 haystack.as_bytes().windows(needle.len()).any(|w| w.eq_ignore_ascii_case(needle.as_bytes()))
1134}
1135
1136fn parse_status_and_headers(header_bytes: &[u8]) -> Result<Response, String> {
1138 let s = std::str::from_utf8(header_bytes)
1139 .map_err(|e| format!("non-UTF-8 response headers: {}", e))?;
1140 let mut lines = s.lines();
1141 let status_line = lines.next().ok_or("empty backend response")?;
1142 let mut parts = status_line.splitn(3, ' ');
1143 let http_version = parts.next().unwrap_or("HTTP/1.1").to_string();
1144 let status_code: i16 = parts
1145 .next()
1146 .unwrap_or("502")
1147 .parse()
1148 .map_err(|_| format!("invalid status code in '{}'", status_line))?;
1149 let reason_phrase = parts.next().unwrap_or("").trim_end_matches('\r').to_string();
1150 let mut headers = Vec::new();
1151 for line in lines {
1152 let line = line.trim_end_matches('\r');
1153 if line.is_empty() { break; }
1154 if let Some(colon) = line.find(':') {
1155 headers.push(crate::header::Header {
1156 name: line[..colon].trim().to_string().into(),
1157 value: (line[colon + 1..].trim().to_string()).into(),
1158 });
1159 }
1160 }
1161 Ok(Response {
1162 http_version,
1163 status_code,
1164 reason_phrase,
1165 headers,
1166 content_range_list: vec![],
1167 stream_file: None,
1168 stream_pipe: None,
1169 trailers: None,
1170 })
1171}
1172
1173fn read_response_from_partial<S: Read>(
1179 stream: &mut S,
1180 header_bytes: Vec<u8>,
1181 body_prefix: Vec<u8>,
1182 tmp: &mut [u8],
1183) -> Result<(Vec<u8>, bool), String> {
1184 let header_end = header_bytes.len();
1185 let mut buf = header_bytes;
1186 buf.extend_from_slice(&body_prefix);
1187
1188 let header_lower =
1189 std::str::from_utf8(&buf[..header_end]).unwrap_or("").to_ascii_lowercase();
1190 let connection_close =
1191 header_lower.lines().any(|l| l.starts_with("connection:") && l.contains("close"));
1192 let is_chunked = header_lower
1193 .lines()
1194 .any(|l| l.starts_with("transfer-encoding:") && l.contains("chunked"));
1195 let content_length: Option<usize> = header_lower.lines().find_map(|l| {
1196 l.strip_prefix("content-length:")?.trim().parse().ok()
1197 });
1198
1199 if is_chunked {
1200 let decoded = decode_chunked(stream, &buf, header_end, tmp)?;
1201 rewrite_as_content_length(&mut buf, header_end, &decoded);
1202 Ok((buf, !connection_close))
1203 } else if let Some(len) = content_length {
1204 while buf.len() < header_end + len {
1205 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1206 if n == 0 { break; }
1207 buf.extend_from_slice(&tmp[..n]);
1208 }
1209 Ok((buf, !connection_close))
1210 } else {
1211 loop {
1212 let n = stream.read(tmp).map_err(|e| e.to_string())?;
1213 if n == 0 { break; }
1214 buf.extend_from_slice(&tmp[..n]);
1215 }
1216 Ok((buf, false))
1217 }
1218}
1219
1220struct Backend {
1223 host: String,
1224 port: u16,
1225 tls: bool,
1228}
1229
1230impl Backend {
1231 fn parse(url: &str) -> Option<Self> {
1232 let (rest, tls, default_port) = if let Some(r) = url.strip_prefix("https://") {
1233 (r, true, 443u16)
1234 } else if let Some(r) = url.strip_prefix("h2s://") {
1235 (r, true, 443u16)
1236 } else if let Some(r) = url.strip_prefix("grpcs://") {
1237 (r, true, 443u16)
1238 } else if let Some(r) = url.strip_prefix("http://") {
1239 (r, false, 80u16)
1240 } else if let Some(r) = url.strip_prefix("h2://") {
1241 (r, false, 80u16)
1242 } else if let Some(r) = url.strip_prefix("grpc://") {
1243 (r, false, 80u16)
1244 } else {
1245 (url, false, 80u16)
1246 };
1247 let host_port = rest.split('/').next().unwrap_or(rest);
1249 let (host, port) = if let Some(colon) = host_port.rfind(':') {
1250 let port_str = &host_port[colon + 1..];
1251 if let Ok(p) = port_str.parse::<u16>() {
1252 (host_port[..colon].to_string(), p)
1253 } else {
1254 (host_port.to_string(), default_port)
1255 }
1256 } else {
1257 (host_port.to_string(), default_port)
1258 };
1259 if host.is_empty() {
1260 return None;
1261 }
1262 Some(Backend { host, port, tls })
1263 }
1264}
1265
1266#[cfg(feature = "http2")]
1277pub struct H2ReverseProxy {
1278 inner: ReverseProxy,
1279}
1280
1281#[cfg(feature = "http2")]
1282impl H2ReverseProxy {
1283 pub fn new<I, S>(backends: I) -> Self
1294 where
1295 I: IntoIterator<Item = S>,
1296 S: AsRef<str>,
1297 {
1298 H2ReverseProxy {
1299 inner: ReverseProxy::new(backends),
1300 }
1301 }
1302
1303 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1305 self.inner = self.inner.path_prefix(prefix);
1306 self
1307 }
1308
1309 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1311 self.inner = self.inner.connect_timeout_ms(ms);
1312 self
1313 }
1314
1315 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1320 self.inner = self.inner.read_timeout_ms(ms);
1321 self
1322 }
1323
1324 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1327 self.inner = self.inner.tls_ca_file(path)?;
1328 Ok(self)
1329 }
1330
1331 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1334 self.inner = self.inner.tls_client_cert(cert, key)?;
1335 Ok(self)
1336 }
1337
1338 fn matches(&self, request: &Request) -> bool {
1339 self.inner.path_prefix.as_ref().is_none_or(|prefix| request.request_uri.starts_with(prefix.as_str()))
1340 }
1341}
1342
1343#[cfg(feature = "http2")]
1344impl crate::middleware::Middleware for H2ReverseProxy {
1345 fn handle(
1346 &self,
1347 request: &crate::request::Request,
1348 connection: &crate::server::ConnectionInfo,
1349 next: &dyn crate::application::Application,
1350 ) -> Result<crate::response::Response, String> {
1351 if !self.matches(request) {
1352 return next.execute(request, connection);
1353 }
1354 if self.inner.backends.is_empty() {
1355 return Ok(bad_gateway());
1356 }
1357 let attempts = if matches!(request.body, crate::request::Body::Stream(_)) { 1 } else { self.inner.backends.len() };
1359 let n = self.inner.backends.len();
1360 let start = self.inner.counter.fetch_add(1, Ordering::Relaxed);
1361 for attempt in 0..attempts {
1362 let backend = &self.inner.backends[(start + attempt) % n];
1363 let tls = backend.tls.then(|| match &self.inner.trust {
1364 Some(trust) => trust.h2_config(),
1365 None => h2_upstream::default_tls(),
1366 });
1367 let target = h2_upstream::Target {
1368 backend,
1369 tls,
1370 connect_timeout: self.inner.connect_timeout,
1371 read_timeout: self.inner.read_timeout,
1372 };
1373 if let Ok(response) = h2_upstream::forward(request, &connection.client.ip, &target) {
1374 return Ok(response);
1375 }
1376 }
1377 Ok(bad_gateway())
1378 }
1379
1380 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1383 true
1384 }
1385
1386 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1389 self.matches(request)
1390 }
1391}
1392
1393#[cfg(feature = "http2")]
1397pub(crate) fn forward_h2(
1398 request: &Request,
1399 client_ip: &str,
1400 url: &str,
1401 tls: bool,
1402 trust: Option<&UpstreamTls>,
1403 connect_timeout: Duration,
1404 read_timeout: Duration,
1405) -> Result<Response, String> {
1406 let mut backend = Backend::parse(url).ok_or_else(|| format!("invalid upstream address '{url}'"))?;
1407 backend.tls |= tls;
1408 let tls = backend.tls.then(|| match trust {
1409 Some(t) => t.h2_config(),
1410 None => h2_upstream::default_tls(),
1411 });
1412 h2_upstream::forward(request, client_ip, &h2_upstream::Target { backend: &backend, tls, connect_timeout, read_timeout })
1413}
1414
1415#[cfg(feature = "http2")]
1435pub struct GrpcProxy {
1436 inner: H2ReverseProxy,
1437}
1438
1439#[cfg(feature = "http2")]
1440impl GrpcProxy {
1441 pub fn new<I, S>(backends: I) -> Self
1451 where
1452 I: IntoIterator<Item = S>,
1453 S: AsRef<str>,
1454 {
1455 GrpcProxy { inner: H2ReverseProxy::new(backends) }
1456 }
1457
1458 pub fn path_prefix(mut self, prefix: impl Into<String>) -> Self {
1460 self.inner = self.inner.path_prefix(prefix);
1461 self
1462 }
1463
1464 pub fn connect_timeout_ms(mut self, ms: u64) -> Self {
1466 self.inner = self.inner.connect_timeout_ms(ms);
1467 self
1468 }
1469
1470 pub fn read_timeout_ms(mut self, ms: u64) -> Self {
1472 self.inner = self.inner.read_timeout_ms(ms);
1473 self
1474 }
1475
1476 pub fn tls_ca_file(mut self, path: &str) -> Result<Self, String> {
1478 self.inner = self.inner.tls_ca_file(path)?;
1479 Ok(self)
1480 }
1481
1482 pub fn tls_client_cert(mut self, cert: &str, key: &str) -> Result<Self, String> {
1485 self.inner = self.inner.tls_client_cert(cert, key)?;
1486 Ok(self)
1487 }
1488}
1489
1490#[cfg(feature = "http2")]
1491impl crate::middleware::Middleware for GrpcProxy {
1492 fn handle(
1493 &self,
1494 request: &crate::request::Request,
1495 connection: &crate::server::ConnectionInfo,
1496 next: &dyn crate::application::Application,
1497 ) -> Result<crate::response::Response, String> {
1498 if is_grpc(request) {
1499 self.inner.handle(request, connection, next)
1500 } else {
1501 next.execute(request, connection)
1502 }
1503 }
1504
1505 fn accepts_streamed_body(&self, _request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1506 true
1507 }
1508
1509 fn answers_streamed_body(&self, request: &Request, _connection: &crate::server::ConnectionInfo) -> bool {
1510 is_grpc(request) && self.inner.matches(request)
1511 }
1512}
1513
1514#[cfg(feature = "http2")]
1515fn is_grpc(request: &Request) -> bool {
1516 request.header(crate::header::Header::_CONTENT_TYPE).is_some_and(|h| h.value.starts_with("application/grpc"))
1517}
1518
1519#[cfg(test)]
1522mod backend_parse_tests {
1523 use super::Backend;
1524
1525 fn parse(url: &str) -> Option<(String, u16, bool)> {
1526 Backend::parse(url).map(|b| (b.host, b.port, b.tls))
1527 }
1528
1529 #[test]
1530 fn bare_host_port() {
1531 assert_eq!(Some(("api.example.com".into(), 8080, false)), parse("api.example.com:8080"));
1532 }
1533
1534 #[test]
1535 fn http_scheme() {
1536 assert_eq!(Some(("backend".into(), 3000, false)), parse("http://backend:3000"));
1537 }
1538
1539 #[test]
1540 fn h2_scheme_plain() {
1541 assert_eq!(Some(("svc".into(), 50051, false)), parse("h2://svc:50051"));
1542 }
1543
1544 #[test]
1545 fn grpc_scheme_plain() {
1546 assert_eq!(Some(("svc".into(), 50051, false)), parse("grpc://svc:50051"));
1547 }
1548
1549 #[test]
1550 fn https_scheme_sets_tls_and_default_port() {
1551 assert_eq!(Some(("api.example.com".into(), 443, true)), parse("https://api.example.com"));
1552 }
1553
1554 #[test]
1555 fn https_scheme_explicit_port() {
1556 assert_eq!(Some(("api.example.com".into(), 8443, true)), parse("https://api.example.com:8443"));
1557 }
1558
1559 #[test]
1560 fn h2s_scheme_sets_tls() {
1561 assert_eq!(Some(("svc".into(), 443, true)), parse("h2s://svc"));
1562 }
1563
1564 #[test]
1565 fn h2s_scheme_explicit_port() {
1566 assert_eq!(Some(("svc".into(), 8443, true)), parse("h2s://svc:8443"));
1567 }
1568
1569 #[test]
1570 fn grpcs_scheme_sets_tls() {
1571 assert_eq!(Some(("grpc-svc".into(), 443, true)), parse("grpcs://grpc-svc"));
1572 }
1573
1574 #[test]
1575 fn grpcs_scheme_explicit_port() {
1576 assert_eq!(Some(("grpc-svc".into(), 50052, true)), parse("grpcs://grpc-svc:50052"));
1577 }
1578
1579 #[test]
1580 fn empty_host_returns_none() {
1581 assert_eq!(None, parse("https://"));
1582 }
1583
1584 #[test]
1585 fn bare_host_no_port_defaults_to_80() {
1586 assert_eq!(Some(("myhost".into(), 80, false)), parse("myhost"));
1587 }
1588}