1use std::{
2 fmt,
3 future::Future,
4 marker::PhantomData,
5 net,
6 pin::Pin,
7 rc::Rc,
8 task::{Context, Poll},
9};
10
11use actix_codec::{AsyncRead, AsyncWrite, Framed};
12use actix_service::{
13 fn_service, IntoServiceFactory, Service, ServiceFactory, ServiceFactoryExt as _,
14};
15use futures_core::{future::LocalBoxFuture, ready};
16use pin_project_lite::pin_project;
17use tokio::net::TcpStream;
18#[cfg(feature = "http2")]
19use tokio_util::future::FutureExt as _;
20use tracing::error;
21
22use crate::{
23 body::{BoxBody, MessageBody},
24 builder::HttpServiceBuilder,
25 error::DispatchError,
26 h1, ConnectCallback, OnConnectData, Protocol, Request, Response, ServiceConfig,
27};
28
29#[inline]
30fn desired_nodelay(tcp_nodelay: Option<bool>) -> Option<bool> {
31 tcp_nodelay
32}
33
34#[inline]
35fn set_nodelay(stream: &TcpStream, nodelay: bool) {
36 let _ = stream.set_nodelay(nodelay);
37}
38
39pub struct HttpService<T, S, B, X = h1::ExpectHandler, U = h1::UpgradeHandler> {
73 srv: S,
74 cfg: ServiceConfig,
75 expect: X,
76 upgrade: Option<U>,
77 on_connect_ext: Option<Rc<ConnectCallback<T>>>,
78 _phantom: PhantomData<B>,
79}
80
81impl<T, S, B> HttpService<T, S, B>
82where
83 S: ServiceFactory<Request, Config = ()>,
84 S::Error: Into<Response<BoxBody>> + 'static,
85 S::InitError: fmt::Debug,
86 S::Response: Into<Response<B>> + 'static,
87 <S::Service as Service<Request>>::Future: 'static,
88 B: MessageBody + 'static,
89{
90 pub fn build() -> HttpServiceBuilder<T, S> {
92 HttpServiceBuilder::default()
93 }
94}
95
96impl<T, S, B> HttpService<T, S, B>
97where
98 S: ServiceFactory<Request, Config = ()>,
99 S::Error: Into<Response<BoxBody>> + 'static,
100 S::InitError: fmt::Debug,
101 S::Response: Into<Response<B>> + 'static,
102 <S::Service as Service<Request>>::Future: 'static,
103 B: MessageBody + 'static,
104{
105 pub fn new<F: IntoServiceFactory<S, Request>>(service: F) -> Self {
107 HttpService {
108 cfg: ServiceConfig::default(),
109 srv: service.into_factory(),
110 expect: h1::ExpectHandler,
111 upgrade: None,
112 on_connect_ext: None,
113 _phantom: PhantomData,
114 }
115 }
116
117 pub(crate) fn with_config<F: IntoServiceFactory<S, Request>>(
119 cfg: ServiceConfig,
120 service: F,
121 ) -> Self {
122 HttpService {
123 cfg,
124 srv: service.into_factory(),
125 expect: h1::ExpectHandler,
126 upgrade: None,
127 on_connect_ext: None,
128 _phantom: PhantomData,
129 }
130 }
131}
132
133impl<T, S, B, X, U> HttpService<T, S, B, X, U>
134where
135 S: ServiceFactory<Request, Config = ()>,
136 S::Error: Into<Response<BoxBody>> + 'static,
137 S::InitError: fmt::Debug,
138 S::Response: Into<Response<B>> + 'static,
139 <S::Service as Service<Request>>::Future: 'static,
140 B: MessageBody,
141{
142 pub fn expect<X1>(self, expect: X1) -> HttpService<T, S, B, X1, U>
147 where
148 X1: ServiceFactory<Request, Config = (), Response = Request>,
149 X1::Error: Into<Response<BoxBody>>,
150 X1::InitError: fmt::Debug,
151 {
152 HttpService {
153 expect,
154 cfg: self.cfg,
155 srv: self.srv,
156 upgrade: self.upgrade,
157 on_connect_ext: self.on_connect_ext,
158 _phantom: PhantomData,
159 }
160 }
161
162 pub fn upgrade<U1>(self, upgrade: Option<U1>) -> HttpService<T, S, B, X, U1>
167 where
168 U1: ServiceFactory<(Request, Framed<T, h1::Codec>), Config = (), Response = ()>,
169 U1::Error: fmt::Display,
170 U1::InitError: fmt::Debug,
171 {
172 HttpService {
173 upgrade,
174 cfg: self.cfg,
175 srv: self.srv,
176 expect: self.expect,
177 on_connect_ext: self.on_connect_ext,
178 _phantom: PhantomData,
179 }
180 }
181
182 pub(crate) fn on_connect_ext(mut self, f: Option<Rc<ConnectCallback<T>>>) -> Self {
184 self.on_connect_ext = f;
185 self
186 }
187}
188
189impl<S, B, X, U> HttpService<TcpStream, S, B, X, U>
190where
191 S: ServiceFactory<Request, Config = ()>,
192 S::Future: 'static,
193 S::Error: Into<Response<BoxBody>> + 'static,
194 S::InitError: fmt::Debug,
195 S::Response: Into<Response<B>> + 'static,
196 <S::Service as Service<Request>>::Future: 'static,
197
198 B: MessageBody + 'static,
199
200 X: ServiceFactory<Request, Config = (), Response = Request>,
201 X::Future: 'static,
202 X::Error: Into<Response<BoxBody>>,
203 X::InitError: fmt::Debug,
204
205 U: ServiceFactory<(Request, Framed<TcpStream, h1::Codec>), Config = (), Response = ()>,
206 U::Future: 'static,
207 U::Error: fmt::Display + Into<Response<BoxBody>>,
208 U::InitError: fmt::Debug,
209{
210 pub fn tcp(
214 self,
215 ) -> impl ServiceFactory<TcpStream, Config = (), Response = (), Error = DispatchError, InitError = ()>
216 {
217 let tcp_nodelay = self.cfg.tcp_nodelay();
218
219 fn_service(move |io: TcpStream| async move {
220 if let Some(nodelay) = desired_nodelay(tcp_nodelay) {
221 set_nodelay(&io, nodelay);
222 }
223
224 let peer_addr = io.peer_addr().ok();
225 Ok((io, Protocol::Http1, peer_addr))
226 })
227 .and_then(self)
228 }
229
230 #[cfg(feature = "http2")]
233 pub fn tcp_auto_h2c(
234 self,
235 ) -> impl ServiceFactory<TcpStream, Config = (), Response = (), Error = DispatchError, InitError = ()>
236 {
237 let tcp_nodelay = self.cfg.tcp_nodelay();
238 let head_timeout = self.cfg.request_head_timeout();
239
240 fn_service(move |io: TcpStream| async move {
241 const H2_PREFACE: &[u8] = b"PRI * HTTP/2";
246
247 let mut buf = [0; 12];
248
249 let peek = io.peek(&mut buf);
250
251 if head_timeout.is_zero() {
252 peek.await?;
253 } else {
254 peek.timeout(head_timeout)
255 .await
256 .map_err(|_| DispatchError::SlowRequestTimeout)??;
257 }
258
259 let proto = if buf == H2_PREFACE {
260 Protocol::Http2
261 } else {
262 Protocol::Http1
263 };
264
265 if let Some(nodelay) = desired_nodelay(tcp_nodelay) {
266 set_nodelay(&io, nodelay);
267 }
268
269 let peer_addr = io.peer_addr().ok();
270
271 Ok((io, proto, peer_addr))
272 })
273 .and_then(self)
274 }
275}
276
277#[cfg(feature = "__tls")]
279#[derive(Debug, Default)]
280pub struct TlsAcceptorConfig {
281 pub(crate) handshake_timeout: Option<std::time::Duration>,
282}
283
284#[cfg(feature = "__tls")]
285impl TlsAcceptorConfig {
286 pub fn handshake_timeout(self, dur: std::time::Duration) -> Self {
288 Self {
289 handshake_timeout: Some(dur),
290 }
292 }
293}
294
295#[cfg(feature = "openssl")]
296mod openssl {
297 use actix_tls::accept::{
298 openssl::{
299 reexports::{Error as SslError, SslAcceptor},
300 Acceptor, TlsStream,
301 },
302 TlsError,
303 };
304
305 use super::*;
306
307 impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U>
308 where
309 S: ServiceFactory<Request, Config = ()>,
310 S::Future: 'static,
311 S::Error: Into<Response<BoxBody>> + 'static,
312 S::InitError: fmt::Debug,
313 S::Response: Into<Response<B>> + 'static,
314 <S::Service as Service<Request>>::Future: 'static,
315
316 B: MessageBody + 'static,
317
318 X: ServiceFactory<Request, Config = (), Response = Request>,
319 X::Future: 'static,
320 X::Error: Into<Response<BoxBody>>,
321 X::InitError: fmt::Debug,
322
323 U: ServiceFactory<
324 (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
325 Config = (),
326 Response = (),
327 >,
328 U::Future: 'static,
329 U::Error: fmt::Display + Into<Response<BoxBody>>,
330 U::InitError: fmt::Debug,
331 {
332 pub fn openssl(
334 self,
335 acceptor: SslAcceptor,
336 ) -> impl ServiceFactory<
337 TcpStream,
338 Config = (),
339 Response = (),
340 Error = TlsError<SslError, DispatchError>,
341 InitError = (),
342 > {
343 self.openssl_with_config(acceptor, TlsAcceptorConfig::default())
344 }
345
346 pub fn openssl_with_config(
348 self,
349 acceptor: SslAcceptor,
350 tls_acceptor_config: TlsAcceptorConfig,
351 ) -> impl ServiceFactory<
352 TcpStream,
353 Config = (),
354 Response = (),
355 Error = TlsError<SslError, DispatchError>,
356 InitError = (),
357 > {
358 let tcp_nodelay = self.cfg.tcp_nodelay();
359 let mut acceptor = Acceptor::new(acceptor);
360
361 if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout {
362 acceptor.set_handshake_timeout(handshake_timeout);
363 }
364
365 acceptor
366 .map_init_err(|_| {
367 unreachable!("TLS acceptor service factory does not error on init")
368 })
369 .map_err(TlsError::into_service_error)
370 .map(move |io: TlsStream<TcpStream>| {
371 let proto = if let Some(protos) = io.ssl().selected_alpn_protocol() {
372 if protos.windows(2).any(|window| window == b"h2") {
373 Protocol::Http2
374 } else {
375 Protocol::Http1
376 }
377 } else {
378 Protocol::Http1
379 };
380
381 if let Some(nodelay) = desired_nodelay(tcp_nodelay) {
382 set_nodelay(io.get_ref(), nodelay);
383 }
384
385 let peer_addr = io.get_ref().peer_addr().ok();
386 (io, proto, peer_addr)
387 })
388 .and_then(self.map_err(TlsError::Service))
389 }
390 }
391}
392
393#[cfg(feature = "rustls-0_20")]
394mod rustls_0_20 {
395 use std::io;
396
397 use actix_tls::accept::{
398 rustls_0_20::{reexports::ServerConfig, Acceptor, TlsStream},
399 TlsError,
400 };
401
402 use super::*;
403
404 impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U>
405 where
406 S: ServiceFactory<Request, Config = ()>,
407 S::Future: 'static,
408 S::Error: Into<Response<BoxBody>> + 'static,
409 S::InitError: fmt::Debug,
410 S::Response: Into<Response<B>> + 'static,
411 <S::Service as Service<Request>>::Future: 'static,
412
413 B: MessageBody + 'static,
414
415 X: ServiceFactory<Request, Config = (), Response = Request>,
416 X::Future: 'static,
417 X::Error: Into<Response<BoxBody>>,
418 X::InitError: fmt::Debug,
419
420 U: ServiceFactory<
421 (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
422 Config = (),
423 Response = (),
424 >,
425 U::Future: 'static,
426 U::Error: fmt::Display + Into<Response<BoxBody>>,
427 U::InitError: fmt::Debug,
428 {
429 pub fn rustls(
431 self,
432 config: ServerConfig,
433 ) -> impl ServiceFactory<
434 TcpStream,
435 Config = (),
436 Response = (),
437 Error = TlsError<io::Error, DispatchError>,
438 InitError = (),
439 > {
440 self.rustls_with_config(config, TlsAcceptorConfig::default())
441 }
442
443 pub fn rustls_with_config(
445 self,
446 mut config: ServerConfig,
447 tls_acceptor_config: TlsAcceptorConfig,
448 ) -> impl ServiceFactory<
449 TcpStream,
450 Config = (),
451 Response = (),
452 Error = TlsError<io::Error, DispatchError>,
453 InitError = (),
454 > {
455 let tcp_nodelay = self.cfg.tcp_nodelay();
456 let mut protos = vec![b"http/1.1".to_vec()];
457 #[cfg(feature = "http2")]
458 protos.insert(0, b"h2".to_vec());
459 protos.extend_from_slice(&config.alpn_protocols);
460 config.alpn_protocols = protos;
461
462 let mut acceptor = Acceptor::new(config);
463
464 if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout {
465 acceptor.set_handshake_timeout(handshake_timeout);
466 }
467
468 acceptor
469 .map_init_err(|_| {
470 unreachable!("TLS acceptor service factory does not error on init")
471 })
472 .map_err(TlsError::into_service_error)
473 .and_then(move |io: TlsStream<TcpStream>| async move {
474 let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() {
475 if protos.windows(2).any(|window| window == b"h2") {
476 Protocol::Http2
477 } else {
478 Protocol::Http1
479 }
480 } else {
481 Protocol::Http1
482 };
483
484 if let Some(nodelay) = desired_nodelay(tcp_nodelay) {
485 set_nodelay(io.get_ref().0, nodelay);
486 }
487
488 let peer_addr = io.get_ref().0.peer_addr().ok();
489 Ok((io, proto, peer_addr))
490 })
491 .and_then(self.map_err(TlsError::Service))
492 }
493 }
494}
495
496#[cfg(feature = "rustls-0_21")]
497mod rustls_0_21 {
498 use std::io;
499
500 use actix_tls::accept::{
501 rustls_0_21::{reexports::ServerConfig, Acceptor, TlsStream},
502 TlsError,
503 };
504
505 use super::*;
506
507 impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U>
508 where
509 S: ServiceFactory<Request, Config = ()>,
510 S::Future: 'static,
511 S::Error: Into<Response<BoxBody>> + 'static,
512 S::InitError: fmt::Debug,
513 S::Response: Into<Response<B>> + 'static,
514 <S::Service as Service<Request>>::Future: 'static,
515
516 B: MessageBody + 'static,
517
518 X: ServiceFactory<Request, Config = (), Response = Request>,
519 X::Future: 'static,
520 X::Error: Into<Response<BoxBody>>,
521 X::InitError: fmt::Debug,
522
523 U: ServiceFactory<
524 (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
525 Config = (),
526 Response = (),
527 >,
528 U::Future: 'static,
529 U::Error: fmt::Display + Into<Response<BoxBody>>,
530 U::InitError: fmt::Debug,
531 {
532 pub fn rustls_021(
534 self,
535 config: ServerConfig,
536 ) -> impl ServiceFactory<
537 TcpStream,
538 Config = (),
539 Response = (),
540 Error = TlsError<io::Error, DispatchError>,
541 InitError = (),
542 > {
543 self.rustls_021_with_config(config, TlsAcceptorConfig::default())
544 }
545
546 pub fn rustls_021_with_config(
548 self,
549 mut config: ServerConfig,
550 tls_acceptor_config: TlsAcceptorConfig,
551 ) -> impl ServiceFactory<
552 TcpStream,
553 Config = (),
554 Response = (),
555 Error = TlsError<io::Error, DispatchError>,
556 InitError = (),
557 > {
558 let tcp_nodelay = self.cfg.tcp_nodelay();
559 let mut protos = vec![b"http/1.1".to_vec()];
560 #[cfg(feature = "http2")]
561 protos.insert(0, b"h2".to_vec());
562 protos.extend_from_slice(&config.alpn_protocols);
563 config.alpn_protocols = protos;
564
565 let mut acceptor = Acceptor::new(config);
566
567 if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout {
568 acceptor.set_handshake_timeout(handshake_timeout);
569 }
570
571 acceptor
572 .map_init_err(|_| {
573 unreachable!("TLS acceptor service factory does not error on init")
574 })
575 .map_err(TlsError::into_service_error)
576 .and_then(move |io: TlsStream<TcpStream>| async move {
577 let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() {
578 if protos.windows(2).any(|window| window == b"h2") {
579 Protocol::Http2
580 } else {
581 Protocol::Http1
582 }
583 } else {
584 Protocol::Http1
585 };
586
587 if let Some(nodelay) = desired_nodelay(tcp_nodelay) {
588 set_nodelay(io.get_ref().0, nodelay);
589 }
590
591 let peer_addr = io.get_ref().0.peer_addr().ok();
592 Ok((io, proto, peer_addr))
593 })
594 .and_then(self.map_err(TlsError::Service))
595 }
596 }
597}
598
599#[cfg(feature = "rustls-0_22")]
600mod rustls_0_22 {
601 use std::io;
602
603 use actix_tls::accept::{
604 rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
605 TlsError,
606 };
607
608 use super::*;
609
610 impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U>
611 where
612 S: ServiceFactory<Request, Config = ()>,
613 S::Future: 'static,
614 S::Error: Into<Response<BoxBody>> + 'static,
615 S::InitError: fmt::Debug,
616 S::Response: Into<Response<B>> + 'static,
617 <S::Service as Service<Request>>::Future: 'static,
618
619 B: MessageBody + 'static,
620
621 X: ServiceFactory<Request, Config = (), Response = Request>,
622 X::Future: 'static,
623 X::Error: Into<Response<BoxBody>>,
624 X::InitError: fmt::Debug,
625
626 U: ServiceFactory<
627 (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
628 Config = (),
629 Response = (),
630 >,
631 U::Future: 'static,
632 U::Error: fmt::Display + Into<Response<BoxBody>>,
633 U::InitError: fmt::Debug,
634 {
635 pub fn rustls_0_22(
637 self,
638 config: ServerConfig,
639 ) -> impl ServiceFactory<
640 TcpStream,
641 Config = (),
642 Response = (),
643 Error = TlsError<io::Error, DispatchError>,
644 InitError = (),
645 > {
646 self.rustls_0_22_with_config(config, TlsAcceptorConfig::default())
647 }
648
649 pub fn rustls_0_22_with_config(
651 self,
652 mut config: ServerConfig,
653 tls_acceptor_config: TlsAcceptorConfig,
654 ) -> impl ServiceFactory<
655 TcpStream,
656 Config = (),
657 Response = (),
658 Error = TlsError<io::Error, DispatchError>,
659 InitError = (),
660 > {
661 let tcp_nodelay = self.cfg.tcp_nodelay();
662 let mut protos = vec![b"http/1.1".to_vec()];
663 #[cfg(feature = "http2")]
664 protos.insert(0, b"h2".to_vec());
665 protos.extend_from_slice(&config.alpn_protocols);
666 config.alpn_protocols = protos;
667
668 let mut acceptor = Acceptor::new(config);
669
670 if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout {
671 acceptor.set_handshake_timeout(handshake_timeout);
672 }
673
674 acceptor
675 .map_init_err(|_| {
676 unreachable!("TLS acceptor service factory does not error on init")
677 })
678 .map_err(TlsError::into_service_error)
679 .and_then(move |io: TlsStream<TcpStream>| async move {
680 let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() {
681 if protos.windows(2).any(|window| window == b"h2") {
682 Protocol::Http2
683 } else {
684 Protocol::Http1
685 }
686 } else {
687 Protocol::Http1
688 };
689
690 if let Some(nodelay) = desired_nodelay(tcp_nodelay) {
691 set_nodelay(io.get_ref().0, nodelay);
692 }
693
694 let peer_addr = io.get_ref().0.peer_addr().ok();
695 Ok((io, proto, peer_addr))
696 })
697 .and_then(self.map_err(TlsError::Service))
698 }
699 }
700}
701
702#[cfg(feature = "rustls-0_23")]
703mod rustls_0_23 {
704 use std::io;
705
706 use actix_tls::accept::{
707 rustls_0_23::{reexports::ServerConfig, Acceptor, TlsStream},
708 TlsError,
709 };
710
711 use super::*;
712
713 impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U>
714 where
715 S: ServiceFactory<Request, Config = ()>,
716 S::Future: 'static,
717 S::Error: Into<Response<BoxBody>> + 'static,
718 S::InitError: fmt::Debug,
719 S::Response: Into<Response<B>> + 'static,
720 <S::Service as Service<Request>>::Future: 'static,
721
722 B: MessageBody + 'static,
723
724 X: ServiceFactory<Request, Config = (), Response = Request>,
725 X::Future: 'static,
726 X::Error: Into<Response<BoxBody>>,
727 X::InitError: fmt::Debug,
728
729 U: ServiceFactory<
730 (Request, Framed<TlsStream<TcpStream>, h1::Codec>),
731 Config = (),
732 Response = (),
733 >,
734 U::Future: 'static,
735 U::Error: fmt::Display + Into<Response<BoxBody>>,
736 U::InitError: fmt::Debug,
737 {
738 pub fn rustls_0_23(
740 self,
741 config: ServerConfig,
742 ) -> impl ServiceFactory<
743 TcpStream,
744 Config = (),
745 Response = (),
746 Error = TlsError<io::Error, DispatchError>,
747 InitError = (),
748 > {
749 self.rustls_0_23_with_config(config, TlsAcceptorConfig::default())
750 }
751
752 pub fn rustls_0_23_with_config(
754 self,
755 mut config: ServerConfig,
756 tls_acceptor_config: TlsAcceptorConfig,
757 ) -> impl ServiceFactory<
758 TcpStream,
759 Config = (),
760 Response = (),
761 Error = TlsError<io::Error, DispatchError>,
762 InitError = (),
763 > {
764 let tcp_nodelay = self.cfg.tcp_nodelay();
765 let mut protos = vec![b"http/1.1".to_vec()];
766 #[cfg(feature = "http2")]
767 protos.insert(0, b"h2".to_vec());
768 protos.extend_from_slice(&config.alpn_protocols);
769 config.alpn_protocols = protos;
770
771 let mut acceptor = Acceptor::new(config);
772
773 if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout {
774 acceptor.set_handshake_timeout(handshake_timeout);
775 }
776
777 acceptor
778 .map_init_err(|_| {
779 unreachable!("TLS acceptor service factory does not error on init")
780 })
781 .map_err(TlsError::into_service_error)
782 .and_then(move |io: TlsStream<TcpStream>| async move {
783 let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() {
784 if protos.windows(2).any(|window| window == b"h2") {
785 Protocol::Http2
786 } else {
787 Protocol::Http1
788 }
789 } else {
790 Protocol::Http1
791 };
792
793 if let Some(nodelay) = desired_nodelay(tcp_nodelay) {
794 set_nodelay(io.get_ref().0, nodelay);
795 }
796
797 let peer_addr = io.get_ref().0.peer_addr().ok();
798 Ok((io, proto, peer_addr))
799 })
800 .and_then(self.map_err(TlsError::Service))
801 }
802 }
803}
804
805impl<T, S, B, X, U> ServiceFactory<(T, Protocol, Option<net::SocketAddr>)>
806 for HttpService<T, S, B, X, U>
807where
808 T: AsyncRead + AsyncWrite + Unpin + 'static,
809
810 S: ServiceFactory<Request, Config = ()>,
811 S::Future: 'static,
812 S::Error: Into<Response<BoxBody>> + 'static,
813 S::InitError: fmt::Debug,
814 S::Response: Into<Response<B>> + 'static,
815 <S::Service as Service<Request>>::Future: 'static,
816
817 B: MessageBody + 'static,
818
819 X: ServiceFactory<Request, Config = (), Response = Request>,
820 X::Future: 'static,
821 X::Error: Into<Response<BoxBody>>,
822 X::InitError: fmt::Debug,
823
824 U: ServiceFactory<(Request, Framed<T, h1::Codec>), Config = (), Response = ()>,
825 U::Future: 'static,
826 U::Error: fmt::Display + Into<Response<BoxBody>>,
827 U::InitError: fmt::Debug,
828{
829 type Response = ();
830 type Error = DispatchError;
831 type Config = ();
832 type Service = HttpServiceHandler<T, S::Service, B, X::Service, U::Service>;
833 type InitError = ();
834 type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
835
836 fn new_service(&self, _: ()) -> Self::Future {
837 let service = self.srv.new_service(());
838 let expect = self.expect.new_service(());
839 let upgrade = self.upgrade.as_ref().map(|s| s.new_service(()));
840 let on_connect_ext = self.on_connect_ext.clone();
841 let cfg = self.cfg.clone();
842
843 Box::pin(async move {
844 let expect = expect.await.map_err(|err| {
845 tracing::error!("Initialization of HTTP expect service error: {err:?}");
846 })?;
847
848 let upgrade = match upgrade {
849 Some(upgrade) => {
850 let upgrade = upgrade.await.map_err(|err| {
851 tracing::error!("Initialization of HTTP upgrade service error: {err:?}");
852 })?;
853 Some(upgrade)
854 }
855 None => None,
856 };
857
858 let service = service.await.map_err(|err| {
859 tracing::error!("Initialization of HTTP service error: {err:?}");
860 })?;
861
862 Ok(HttpServiceHandler::new(
863 cfg,
864 service,
865 expect,
866 upgrade,
867 on_connect_ext,
868 ))
869 })
870 }
871}
872
873pub struct HttpServiceHandler<T, S, B, X, U>
875where
876 S: Service<Request>,
877 X: Service<Request>,
878 U: Service<(Request, Framed<T, h1::Codec>)>,
879{
880 pub(super) flow: Rc<HttpFlow<S, X, U>>,
881 pub(super) cfg: ServiceConfig,
882 pub(super) on_connect_ext: Option<Rc<ConnectCallback<T>>>,
883 _phantom: PhantomData<B>,
884}
885
886impl<T, S, B, X, U> HttpServiceHandler<T, S, B, X, U>
887where
888 S: Service<Request>,
889 S::Error: Into<Response<BoxBody>>,
890 X: Service<Request>,
891 X::Error: Into<Response<BoxBody>>,
892 U: Service<(Request, Framed<T, h1::Codec>)>,
893 U::Error: Into<Response<BoxBody>>,
894{
895 pub(super) fn new(
896 cfg: ServiceConfig,
897 service: S,
898 expect: X,
899 upgrade: Option<U>,
900 on_connect_ext: Option<Rc<ConnectCallback<T>>>,
901 ) -> HttpServiceHandler<T, S, B, X, U> {
902 HttpServiceHandler {
903 cfg,
904 on_connect_ext,
905 flow: HttpFlow::new(service, expect, upgrade),
906 _phantom: PhantomData,
907 }
908 }
909
910 pub(super) fn _poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Response<BoxBody>>> {
911 ready!(self.flow.expect.poll_ready(cx).map_err(Into::into))?;
912
913 ready!(self.flow.service.poll_ready(cx).map_err(Into::into))?;
914
915 if let Some(ref upg) = self.flow.upgrade {
916 ready!(upg.poll_ready(cx).map_err(Into::into))?;
917 };
918
919 Poll::Ready(Ok(()))
920 }
921}
922
923pub(super) struct HttpFlow<S, X, U> {
925 pub(super) service: S,
926 pub(super) expect: X,
927 pub(super) upgrade: Option<U>,
928}
929
930impl<S, X, U> HttpFlow<S, X, U> {
931 pub(super) fn new(service: S, expect: X, upgrade: Option<U>) -> Rc<Self> {
932 Rc::new(Self {
933 service,
934 expect,
935 upgrade,
936 })
937 }
938}
939
940impl<T, S, B, X, U> Service<(T, Protocol, Option<net::SocketAddr>)>
941 for HttpServiceHandler<T, S, B, X, U>
942where
943 T: AsyncRead + AsyncWrite + Unpin,
944
945 S: Service<Request>,
946 S::Error: Into<Response<BoxBody>> + 'static,
947 S::Future: 'static,
948 S::Response: Into<Response<B>> + 'static,
949
950 B: MessageBody + 'static,
951
952 X: Service<Request, Response = Request>,
953 X::Error: Into<Response<BoxBody>>,
954
955 U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
956 U::Error: fmt::Display + Into<Response<BoxBody>>,
957{
958 type Response = ();
959 type Error = DispatchError;
960 type Future = HttpServiceHandlerResponse<T, S, B, X, U>;
961
962 fn poll_ready(&self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
963 self._poll_ready(cx).map_err(|err| {
964 error!("HTTP service readiness error: {:?}", err);
965 DispatchError::Service(err)
966 })
967 }
968
969 fn call(&self, (io, proto, peer_addr): (T, Protocol, Option<net::SocketAddr>)) -> Self::Future {
970 let conn_data = OnConnectData::from_io(&io, self.on_connect_ext.as_deref());
971
972 match proto {
973 #[cfg(feature = "http2")]
974 Protocol::Http2 => HttpServiceHandlerResponse {
975 state: State::H2Handshake {
976 handshake: Some((
977 crate::h2::handshake_with_timeout(io, &self.cfg),
978 self.cfg.clone(),
979 Rc::clone(&self.flow),
980 conn_data,
981 peer_addr,
982 )),
983 },
984 },
985
986 #[cfg(not(feature = "http2"))]
987 Protocol::Http2 => {
988 panic!("HTTP/2 support is disabled (enable with the `http2` feature flag)")
989 }
990
991 Protocol::Http1 => HttpServiceHandlerResponse {
992 state: State::H1 {
993 dispatcher: h1::Dispatcher::new(
994 io,
995 Rc::clone(&self.flow),
996 self.cfg.clone(),
997 peer_addr,
998 conn_data,
999 ),
1000 },
1001 },
1002
1003 proto => unimplemented!("Unsupported HTTP version: {:?}.", proto),
1004 }
1005 }
1006}
1007
1008#[cfg(not(feature = "http2"))]
1009pin_project! {
1010 #[project = StateProj]
1011 enum State<T, S, B, X, U>
1012 where
1013 T: AsyncRead,
1014 T: AsyncWrite,
1015 T: Unpin,
1016
1017 S: Service<Request>,
1018 S::Future: 'static,
1019 S::Error: Into<Response<BoxBody>>,
1020
1021 B: MessageBody,
1022
1023 X: Service<Request, Response = Request>,
1024 X::Error: Into<Response<BoxBody>>,
1025
1026 U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
1027 U::Error: fmt::Display,
1028 {
1029 H1 { #[pin] dispatcher: h1::Dispatcher<T, S, B, X, U> },
1030 }
1031}
1032
1033#[cfg(feature = "http2")]
1034pin_project! {
1035 #[project = StateProj]
1036 enum State<T, S, B, X, U>
1037 where
1038 T: AsyncRead,
1039 T: AsyncWrite,
1040 T: Unpin,
1041
1042 S: Service<Request>,
1043 S::Future: 'static,
1044 S::Error: Into<Response<BoxBody>>,
1045
1046 B: MessageBody,
1047
1048 X: Service<Request, Response = Request>,
1049 X::Error: Into<Response<BoxBody>>,
1050
1051 U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
1052 U::Error: fmt::Display,
1053 {
1054 H1 { #[pin] dispatcher: h1::Dispatcher<T, S, B, X, U> },
1055
1056 H2 { #[pin] dispatcher: crate::h2::Dispatcher<T, S, B, X, U> },
1057
1058 H2Handshake {
1059 handshake: Option<(
1060 crate::h2::HandshakeWithTimeout<T>,
1061 ServiceConfig,
1062 Rc<HttpFlow<S, X, U>>,
1063 OnConnectData,
1064 Option<net::SocketAddr>,
1065 )>,
1066 },
1067 }
1068}
1069
1070pin_project! {
1071 pub struct HttpServiceHandlerResponse<T, S, B, X, U>
1072 where
1073 T: AsyncRead,
1074 T: AsyncWrite,
1075 T: Unpin,
1076
1077 S: Service<Request>,
1078 S::Error: Into<Response<BoxBody>>,
1079 S::Error: 'static,
1080 S::Future: 'static,
1081 S::Response: Into<Response<B>>,
1082 S::Response: 'static,
1083
1084 B: MessageBody,
1085
1086 X: Service<Request, Response = Request>,
1087 X::Error: Into<Response<BoxBody>>,
1088
1089 U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
1090 U::Error: fmt::Display,
1091 {
1092 #[pin]
1093 state: State<T, S, B, X, U>,
1094 }
1095}
1096
1097impl<T, S, B, X, U> Future for HttpServiceHandlerResponse<T, S, B, X, U>
1098where
1099 T: AsyncRead + AsyncWrite + Unpin,
1100
1101 S: Service<Request>,
1102 S::Error: Into<Response<BoxBody>> + 'static,
1103 S::Future: 'static,
1104 S::Response: Into<Response<B>> + 'static,
1105
1106 B: MessageBody + 'static,
1107
1108 X: Service<Request, Response = Request>,
1109 X::Error: Into<Response<BoxBody>>,
1110
1111 U: Service<(Request, Framed<T, h1::Codec>), Response = ()>,
1112 U::Error: fmt::Display,
1113{
1114 type Output = Result<(), DispatchError>;
1115
1116 fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
1117 match self.as_mut().project().state.project() {
1118 StateProj::H1 { dispatcher } => dispatcher.poll(cx),
1119
1120 #[cfg(feature = "http2")]
1121 StateProj::H2 { dispatcher } => dispatcher.poll(cx),
1122
1123 #[cfg(feature = "http2")]
1124 StateProj::H2Handshake { handshake: data } => {
1125 match ready!(Pin::new(&mut data.as_mut().unwrap().0).poll(cx)) {
1126 Ok((conn, timer)) => {
1127 let (_, config, flow, conn_data, peer_addr) = data.take().unwrap();
1128
1129 self.as_mut().project().state.set(State::H2 {
1130 dispatcher: crate::h2::Dispatcher::new(
1131 conn, flow, config, peer_addr, conn_data, timer,
1132 ),
1133 });
1134 self.poll(cx)
1135 }
1136 Err(err) => {
1137 tracing::trace!("H2 handshake error: {}", err);
1138 Poll::Ready(Err(err))
1139 }
1140 }
1141 }
1142 }
1143 }
1144}