1 use std::error::Error as StdError;
2 use std::fmt;
3 use std::future::Future;
4 use std::marker::Unpin;
5 #[cfg(feature = "tcp")]
6 use std::net::{SocketAddr, TcpListener as StdTcpListener};
7 use std::pin::Pin;
8 use std::task::{Context, Poll};
9 #[cfg(feature = "tcp")]
10 use std::time::Duration;
11 
12 use pin_project_lite::pin_project;
13 
14 use tokio::io::{AsyncRead, AsyncWrite};
15 use tracing::trace;
16 
17 use super::accept::Accept;
18 #[cfg(all(feature = "tcp"))]
19 use super::tcp::AddrIncoming;
20 use crate::body::{Body, HttpBody};
21 use crate::common::exec::Exec;
22 use crate::common::exec::{ConnStreamExec, NewSvcExec};
23 // Renamed `Http` as `Http_` for now so that people upgrading don't see an
24 // error that `hyper::server::Http` is private...
25 use super::conn::{Connection, Http as Http_, UpgradeableConnection};
26 use super::shutdown::{Graceful, GracefulWatcher};
27 use crate::service::{HttpService, MakeServiceRef};
28 
29 use self::new_svc::NewSvcTask;
30 
31 pin_project! {
32     /// A listening HTTP server that accepts connections in both HTTP1 and HTTP2 by default.
33     ///
34     /// `Server` is a `Future` mapping a bound listener with a set of service
35     /// handlers. It is built using the [`Builder`](Builder), and the future
36     /// completes when the server has been shutdown. It should be run by an
37     /// `Executor`.
38     pub struct Server<I, S, E = Exec> {
39         #[pin]
40         incoming: I,
41         make_service: S,
42         protocol: Http_<E>,
43     }
44 }
45 
46 /// A builder for a [`Server`](Server).
47 #[derive(Debug)]
48 #[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
49 pub struct Builder<I, E = Exec> {
50     incoming: I,
51     protocol: Http_<E>,
52 }
53 
54 // ===== impl Server =====
55 
56 #[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
57 impl<I> Server<I, ()> {
58     /// Starts a [`Builder`](Builder) with the provided incoming stream.
builder(incoming: I) -> Builder<I>59     pub fn builder(incoming: I) -> Builder<I> {
60         Builder {
61             incoming,
62             protocol: Http_::new(),
63         }
64     }
65 }
66 
67 #[cfg(feature = "tcp")]
68 #[cfg_attr(
69     docsrs,
70     doc(cfg(all(feature = "tcp", any(feature = "http1", feature = "http2"))))
71 )]
72 impl Server<AddrIncoming, ()> {
73     /// Binds to the provided address, and returns a [`Builder`](Builder).
74     ///
75     /// # Panics
76     ///
77     /// This method will panic if binding to the address fails. For a method
78     /// to bind to an address and return a `Result`, see `Server::try_bind`.
bind(addr: &SocketAddr) -> Builder<AddrIncoming>79     pub fn bind(addr: &SocketAddr) -> Builder<AddrIncoming> {
80         let incoming = AddrIncoming::new(addr).unwrap_or_else(|e| {
81             panic!("error binding to {}: {}", addr, e);
82         });
83         Server::builder(incoming)
84     }
85 
86     /// Tries to bind to the provided address, and returns a [`Builder`](Builder).
try_bind(addr: &SocketAddr) -> crate::Result<Builder<AddrIncoming>>87     pub fn try_bind(addr: &SocketAddr) -> crate::Result<Builder<AddrIncoming>> {
88         AddrIncoming::new(addr).map(Server::builder)
89     }
90 
91     /// Create a new instance from a `std::net::TcpListener` instance.
from_tcp(listener: StdTcpListener) -> Result<Builder<AddrIncoming>, crate::Error>92     pub fn from_tcp(listener: StdTcpListener) -> Result<Builder<AddrIncoming>, crate::Error> {
93         AddrIncoming::from_std(listener).map(Server::builder)
94     }
95 }
96 
97 #[cfg(feature = "tcp")]
98 #[cfg_attr(
99     docsrs,
100     doc(cfg(all(feature = "tcp", any(feature = "http1", feature = "http2"))))
101 )]
102 impl<S, E> Server<AddrIncoming, S, E> {
103     /// Returns the local address that this server is bound to.
local_addr(&self) -> SocketAddr104     pub fn local_addr(&self) -> SocketAddr {
105         self.incoming.local_addr()
106     }
107 }
108 
109 #[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
110 impl<I, IO, IE, S, E, B> Server<I, S, E>
111 where
112     I: Accept<Conn = IO, Error = IE>,
113     IE: Into<Box<dyn StdError + Send + Sync>>,
114     IO: AsyncRead + AsyncWrite + Unpin + Send + 'static,
115     S: MakeServiceRef<IO, Body, ResBody = B>,
116     S::Error: Into<Box<dyn StdError + Send + Sync>>,
117     B: HttpBody + 'static,
118     B::Error: Into<Box<dyn StdError + Send + Sync>>,
119     E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>,
120 {
121     /// Prepares a server to handle graceful shutdown when the provided future
122     /// completes.
123     ///
124     /// # Example
125     ///
126     /// ```
127     /// # fn main() {}
128     /// # #[cfg(feature = "tcp")]
129     /// # async fn run() {
130     /// # use hyper::{Body, Response, Server, Error};
131     /// # use hyper::service::{make_service_fn, service_fn};
132     /// # let make_service = make_service_fn(|_| async {
133     /// #     Ok::<_, Error>(service_fn(|_req| async {
134     /// #         Ok::<_, Error>(Response::new(Body::from("Hello World")))
135     /// #     }))
136     /// # });
137     /// // Make a server from the previous examples...
138     /// let server = Server::bind(&([127, 0, 0, 1], 3000).into())
139     ///     .serve(make_service);
140     ///
141     /// // Prepare some signal for when the server should start shutting down...
142     /// let (tx, rx) = tokio::sync::oneshot::channel::<()>();
143     /// let graceful = server
144     ///     .with_graceful_shutdown(async {
145     ///         rx.await.ok();
146     ///     });
147     ///
148     /// // Await the `server` receiving the signal...
149     /// if let Err(e) = graceful.await {
150     ///     eprintln!("server error: {}", e);
151     /// }
152     ///
153     /// // And later, trigger the signal by calling `tx.send(())`.
154     /// let _ = tx.send(());
155     /// # }
156     /// ```
with_graceful_shutdown<F>(self, signal: F) -> Graceful<I, S, F, E> where F: Future<Output = ()>, E: NewSvcExec<IO, S::Future, S::Service, E, GracefulWatcher>,157     pub fn with_graceful_shutdown<F>(self, signal: F) -> Graceful<I, S, F, E>
158     where
159         F: Future<Output = ()>,
160         E: NewSvcExec<IO, S::Future, S::Service, E, GracefulWatcher>,
161     {
162         Graceful::new(self, signal)
163     }
164 
poll_next_( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<crate::Result<Connecting<IO, S::Future, E>>>>165     fn poll_next_(
166         self: Pin<&mut Self>,
167         cx: &mut Context<'_>,
168     ) -> Poll<Option<crate::Result<Connecting<IO, S::Future, E>>>> {
169         let me = self.project();
170         match ready!(me.make_service.poll_ready_ref(cx)) {
171             Ok(()) => (),
172             Err(e) => {
173                 trace!("make_service closed");
174                 return Poll::Ready(Some(Err(crate::Error::new_user_make_service(e))));
175             }
176         }
177 
178         if let Some(item) = ready!(me.incoming.poll_accept(cx)) {
179             let io = item.map_err(crate::Error::new_accept)?;
180             let new_fut = me.make_service.make_service_ref(&io);
181             Poll::Ready(Some(Ok(Connecting {
182                 future: new_fut,
183                 io: Some(io),
184                 protocol: me.protocol.clone(),
185             })))
186         } else {
187             Poll::Ready(None)
188         }
189     }
190 
poll_watch<W>( mut self: Pin<&mut Self>, cx: &mut Context<'_>, watcher: &W, ) -> Poll<crate::Result<()>> where E: NewSvcExec<IO, S::Future, S::Service, E, W>, W: Watcher<IO, S::Service, E>,191     pub(super) fn poll_watch<W>(
192         mut self: Pin<&mut Self>,
193         cx: &mut Context<'_>,
194         watcher: &W,
195     ) -> Poll<crate::Result<()>>
196     where
197         E: NewSvcExec<IO, S::Future, S::Service, E, W>,
198         W: Watcher<IO, S::Service, E>,
199     {
200         loop {
201             if let Some(connecting) = ready!(self.as_mut().poll_next_(cx)?) {
202                 let fut = NewSvcTask::new(connecting, watcher.clone());
203                 self.as_mut().project().protocol.exec.execute_new_svc(fut);
204             } else {
205                 return Poll::Ready(Ok(()));
206             }
207         }
208     }
209 }
210 
211 #[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
212 impl<I, IO, IE, S, B, E> Future for Server<I, S, E>
213 where
214     I: Accept<Conn = IO, Error = IE>,
215     IE: Into<Box<dyn StdError + Send + Sync>>,
216     IO: AsyncRead + AsyncWrite + Unpin + Send + 'static,
217     S: MakeServiceRef<IO, Body, ResBody = B>,
218     S::Error: Into<Box<dyn StdError + Send + Sync>>,
219     B: HttpBody + 'static,
220     B::Error: Into<Box<dyn StdError + Send + Sync>>,
221     E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>,
222     E: NewSvcExec<IO, S::Future, S::Service, E, NoopWatcher>,
223 {
224     type Output = crate::Result<()>;
225 
poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>226     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
227         self.poll_watch(cx, &NoopWatcher)
228     }
229 }
230 
231 impl<I: fmt::Debug, S: fmt::Debug> fmt::Debug for Server<I, S> {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result232     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
233         let mut st = f.debug_struct("Server");
234         st.field("listener", &self.incoming);
235         st.finish()
236     }
237 }
238 
239 // ===== impl Builder =====
240 
241 #[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
242 impl<I, E> Builder<I, E> {
243     /// Start a new builder, wrapping an incoming stream and low-level options.
244     ///
245     /// For a more convenient constructor, see [`Server::bind`](Server::bind).
new(incoming: I, protocol: Http_<E>) -> Self246     pub fn new(incoming: I, protocol: Http_<E>) -> Self {
247         Builder { incoming, protocol }
248     }
249 
250     /// Sets whether to use keep-alive for HTTP/1 connections.
251     ///
252     /// Default is `true`.
253     #[cfg(feature = "http1")]
254     #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
http1_keepalive(mut self, val: bool) -> Self255     pub fn http1_keepalive(mut self, val: bool) -> Self {
256         self.protocol.http1_keep_alive(val);
257         self
258     }
259 
260     /// Set whether HTTP/1 connections should support half-closures.
261     ///
262     /// Clients can chose to shutdown their write-side while waiting
263     /// for the server to respond. Setting this to `true` will
264     /// prevent closing the connection immediately if `read`
265     /// detects an EOF in the middle of a request.
266     ///
267     /// Default is `false`.
268     #[cfg(feature = "http1")]
269     #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
http1_half_close(mut self, val: bool) -> Self270     pub fn http1_half_close(mut self, val: bool) -> Self {
271         self.protocol.http1_half_close(val);
272         self
273     }
274 
275     /// Set the maximum buffer size.
276     ///
277     /// Default is ~ 400kb.
278     #[cfg(feature = "http1")]
279     #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
http1_max_buf_size(mut self, val: usize) -> Self280     pub fn http1_max_buf_size(mut self, val: usize) -> Self {
281         self.protocol.max_buf_size(val);
282         self
283     }
284 
285     // Sets whether to bunch up HTTP/1 writes until the read buffer is empty.
286     //
287     // This isn't really desirable in most cases, only really being useful in
288     // silly pipeline benchmarks.
289     #[doc(hidden)]
290     #[cfg(feature = "http1")]
http1_pipeline_flush(mut self, val: bool) -> Self291     pub fn http1_pipeline_flush(mut self, val: bool) -> Self {
292         self.protocol.pipeline_flush(val);
293         self
294     }
295 
296     /// Set whether HTTP/1 connections should try to use vectored writes,
297     /// or always flatten into a single buffer.
298     ///
299     /// Note that setting this to false may mean more copies of body data,
300     /// but may also improve performance when an IO transport doesn't
301     /// support vectored writes well, such as most TLS implementations.
302     ///
303     /// Setting this to true will force hyper to use queued strategy
304     /// which may eliminate unnecessary cloning on some TLS backends
305     ///
306     /// Default is `auto`. In this mode hyper will try to guess which
307     /// mode to use
308     #[cfg(feature = "http1")]
http1_writev(mut self, enabled: bool) -> Self309     pub fn http1_writev(mut self, enabled: bool) -> Self {
310         self.protocol.http1_writev(enabled);
311         self
312     }
313 
314     /// Set whether HTTP/1 connections will write header names as title case at
315     /// the socket level.
316     ///
317     /// Note that this setting does not affect HTTP/2.
318     ///
319     /// Default is false.
320     #[cfg(feature = "http1")]
321     #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
http1_title_case_headers(mut self, val: bool) -> Self322     pub fn http1_title_case_headers(mut self, val: bool) -> Self {
323         self.protocol.http1_title_case_headers(val);
324         self
325     }
326 
327     /// Set whether to support preserving original header cases.
328     ///
329     /// Currently, this will record the original cases received, and store them
330     /// in a private extension on the `Request`. It will also look for and use
331     /// such an extension in any provided `Response`.
332     ///
333     /// Since the relevant extension is still private, there is no way to
334     /// interact with the original cases. The only effect this can have now is
335     /// to forward the cases in a proxy-like fashion.
336     ///
337     /// Note that this setting does not affect HTTP/2.
338     ///
339     /// Default is false.
340     #[cfg(feature = "http1")]
341     #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
http1_preserve_header_case(mut self, val: bool) -> Self342     pub fn http1_preserve_header_case(mut self, val: bool) -> Self {
343         self.protocol.http1_preserve_header_case(val);
344         self
345     }
346 
347     /// Set a timeout for reading client request headers. If a client does not
348     /// transmit the entire header within this time, the connection is closed.
349     ///
350     /// Default is None.
351     #[cfg(all(feature = "http1", feature = "runtime"))]
352     #[cfg_attr(docsrs, doc(cfg(all(feature = "http1", feature = "runtime"))))]
http1_header_read_timeout(mut self, read_timeout: Duration) -> Self353     pub fn http1_header_read_timeout(mut self, read_timeout: Duration) -> Self {
354         self.protocol.http1_header_read_timeout(read_timeout);
355         self
356     }
357 
358     /// Sets whether HTTP/1 is required.
359     ///
360     /// Default is `false`.
361     #[cfg(feature = "http1")]
362     #[cfg_attr(docsrs, doc(cfg(feature = "http1")))]
http1_only(mut self, val: bool) -> Self363     pub fn http1_only(mut self, val: bool) -> Self {
364         self.protocol.http1_only(val);
365         self
366     }
367 
368     /// Sets whether HTTP/2 is required.
369     ///
370     /// Default is `false`.
371     #[cfg(feature = "http2")]
372     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_only(mut self, val: bool) -> Self373     pub fn http2_only(mut self, val: bool) -> Self {
374         self.protocol.http2_only(val);
375         self
376     }
377 
378     /// Configures the maximum number of pending reset streams allowed before a GOAWAY will be sent.
379     ///
380     /// This will default to whatever the default in h2 is. As of v0.3.17, it is 20.
381     ///
382     /// See <https://github.com/hyperium/hyper/issues/2877> for more information.
383     #[cfg(feature = "http2")]
384     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_max_pending_accept_reset_streams(mut self, max: impl Into<Option<usize>>) -> Self385     pub fn http2_max_pending_accept_reset_streams(mut self, max: impl Into<Option<usize>>) -> Self {
386         self.protocol.http2_max_pending_accept_reset_streams(max);
387         self
388     }
389 
390     /// Sets the [`SETTINGS_INITIAL_WINDOW_SIZE`][spec] option for HTTP2
391     /// stream-level flow control.
392     ///
393     /// Passing `None` will do nothing.
394     ///
395     /// If not set, hyper will use a default.
396     ///
397     /// [spec]: https://http2.github.io/http2-spec/#SETTINGS_INITIAL_WINDOW_SIZE
398     #[cfg(feature = "http2")]
399     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_initial_stream_window_size(mut self, sz: impl Into<Option<u32>>) -> Self400     pub fn http2_initial_stream_window_size(mut self, sz: impl Into<Option<u32>>) -> Self {
401         self.protocol.http2_initial_stream_window_size(sz.into());
402         self
403     }
404 
405     /// Sets the max connection-level flow control for HTTP2
406     ///
407     /// Passing `None` will do nothing.
408     ///
409     /// If not set, hyper will use a default.
410     #[cfg(feature = "http2")]
411     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_initial_connection_window_size(mut self, sz: impl Into<Option<u32>>) -> Self412     pub fn http2_initial_connection_window_size(mut self, sz: impl Into<Option<u32>>) -> Self {
413         self.protocol
414             .http2_initial_connection_window_size(sz.into());
415         self
416     }
417 
418     /// Sets whether to use an adaptive flow control.
419     ///
420     /// Enabling this will override the limits set in
421     /// `http2_initial_stream_window_size` and
422     /// `http2_initial_connection_window_size`.
423     #[cfg(feature = "http2")]
424     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_adaptive_window(mut self, enabled: bool) -> Self425     pub fn http2_adaptive_window(mut self, enabled: bool) -> Self {
426         self.protocol.http2_adaptive_window(enabled);
427         self
428     }
429 
430     /// Sets the maximum frame size to use for HTTP2.
431     ///
432     /// Passing `None` will do nothing.
433     ///
434     /// If not set, hyper will use a default.
435     #[cfg(feature = "http2")]
436     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_max_frame_size(mut self, sz: impl Into<Option<u32>>) -> Self437     pub fn http2_max_frame_size(mut self, sz: impl Into<Option<u32>>) -> Self {
438         self.protocol.http2_max_frame_size(sz);
439         self
440     }
441 
442     /// Sets the max size of received header frames.
443     ///
444     /// Default is currently ~16MB, but may change.
445     #[cfg(feature = "http2")]
446     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_max_header_list_size(mut self, max: u32) -> Self447     pub fn http2_max_header_list_size(mut self, max: u32) -> Self {
448         self.protocol.http2_max_header_list_size(max);
449         self
450     }
451 
452     /// Sets the [`SETTINGS_MAX_CONCURRENT_STREAMS`][spec] option for HTTP2
453     /// connections.
454     ///
455     /// Default is no limit (`std::u32::MAX`). Passing `None` will do nothing.
456     ///
457     /// [spec]: https://http2.github.io/http2-spec/#SETTINGS_MAX_CONCURRENT_STREAMS
458     #[cfg(feature = "http2")]
459     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_max_concurrent_streams(mut self, max: impl Into<Option<u32>>) -> Self460     pub fn http2_max_concurrent_streams(mut self, max: impl Into<Option<u32>>) -> Self {
461         self.protocol.http2_max_concurrent_streams(max.into());
462         self
463     }
464 
465     /// Sets an interval for HTTP2 Ping frames should be sent to keep a
466     /// connection alive.
467     ///
468     /// Pass `None` to disable HTTP2 keep-alive.
469     ///
470     /// Default is currently disabled.
471     ///
472     /// # Cargo Feature
473     ///
474     /// Requires the `runtime` cargo feature to be enabled.
475     #[cfg(all(feature = "runtime", feature = "http2"))]
476     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_keep_alive_interval(mut self, interval: impl Into<Option<Duration>>) -> Self477     pub fn http2_keep_alive_interval(mut self, interval: impl Into<Option<Duration>>) -> Self {
478         self.protocol.http2_keep_alive_interval(interval);
479         self
480     }
481 
482     /// Sets a timeout for receiving an acknowledgement of the keep-alive ping.
483     ///
484     /// If the ping is not acknowledged within the timeout, the connection will
485     /// be closed. Does nothing if `http2_keep_alive_interval` is disabled.
486     ///
487     /// Default is 20 seconds.
488     ///
489     /// # Cargo Feature
490     ///
491     /// Requires the `runtime` cargo feature to be enabled.
492     #[cfg(all(feature = "runtime", feature = "http2"))]
493     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_keep_alive_timeout(mut self, timeout: Duration) -> Self494     pub fn http2_keep_alive_timeout(mut self, timeout: Duration) -> Self {
495         self.protocol.http2_keep_alive_timeout(timeout);
496         self
497     }
498 
499     /// Set the maximum write buffer size for each HTTP/2 stream.
500     ///
501     /// Default is currently ~400KB, but may change.
502     ///
503     /// # Panics
504     ///
505     /// The value must be no larger than `u32::MAX`.
506     #[cfg(feature = "http2")]
507     #[cfg_attr(docsrs, doc(cfg(feature = "http2")))]
http2_max_send_buf_size(mut self, max: usize) -> Self508     pub fn http2_max_send_buf_size(mut self, max: usize) -> Self {
509         self.protocol.http2_max_send_buf_size(max);
510         self
511     }
512 
513     /// Enables the [extended CONNECT protocol].
514     ///
515     /// [extended CONNECT protocol]: https://datatracker.ietf.org/doc/html/rfc8441#section-4
516     #[cfg(feature = "http2")]
http2_enable_connect_protocol(mut self) -> Self517     pub fn http2_enable_connect_protocol(mut self) -> Self {
518         self.protocol.http2_enable_connect_protocol();
519         self
520     }
521 
522     /// Sets the `Executor` to deal with connection tasks.
523     ///
524     /// Default is `tokio::spawn`.
executor<E2>(self, executor: E2) -> Builder<I, E2>525     pub fn executor<E2>(self, executor: E2) -> Builder<I, E2> {
526         Builder {
527             incoming: self.incoming,
528             protocol: self.protocol.with_executor(executor),
529         }
530     }
531 
532     /// Consume this `Builder`, creating a [`Server`](Server).
533     ///
534     /// # Example
535     ///
536     /// ```
537     /// # #[cfg(feature = "tcp")]
538     /// # async fn run() {
539     /// use hyper::{Body, Error, Response, Server};
540     /// use hyper::service::{make_service_fn, service_fn};
541     ///
542     /// // Construct our SocketAddr to listen on...
543     /// let addr = ([127, 0, 0, 1], 3000).into();
544     ///
545     /// // And a MakeService to handle each connection...
546     /// let make_svc = make_service_fn(|_| async {
547     ///     Ok::<_, Error>(service_fn(|_req| async {
548     ///         Ok::<_, Error>(Response::new(Body::from("Hello World")))
549     ///     }))
550     /// });
551     ///
552     /// // Then bind and serve...
553     /// let server = Server::bind(&addr)
554     ///     .serve(make_svc);
555     ///
556     /// // Run forever-ish...
557     /// if let Err(err) = server.await {
558     ///     eprintln!("server error: {}", err);
559     /// }
560     /// # }
561     /// ```
serve<S, B>(self, make_service: S) -> Server<I, S, E> where I: Accept, I::Error: Into<Box<dyn StdError + Send + Sync>>, I::Conn: AsyncRead + AsyncWrite + Unpin + Send + 'static, S: MakeServiceRef<I::Conn, Body, ResBody = B>, S::Error: Into<Box<dyn StdError + Send + Sync>>, B: HttpBody + 'static, B::Error: Into<Box<dyn StdError + Send + Sync>>, E: NewSvcExec<I::Conn, S::Future, S::Service, E, NoopWatcher>, E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>,562     pub fn serve<S, B>(self, make_service: S) -> Server<I, S, E>
563     where
564         I: Accept,
565         I::Error: Into<Box<dyn StdError + Send + Sync>>,
566         I::Conn: AsyncRead + AsyncWrite + Unpin + Send + 'static,
567         S: MakeServiceRef<I::Conn, Body, ResBody = B>,
568         S::Error: Into<Box<dyn StdError + Send + Sync>>,
569         B: HttpBody + 'static,
570         B::Error: Into<Box<dyn StdError + Send + Sync>>,
571         E: NewSvcExec<I::Conn, S::Future, S::Service, E, NoopWatcher>,
572         E: ConnStreamExec<<S::Service as HttpService<Body>>::Future, B>,
573     {
574         Server {
575             incoming: self.incoming,
576             make_service,
577             protocol: self.protocol.clone(),
578         }
579     }
580 }
581 
582 #[cfg(feature = "tcp")]
583 #[cfg_attr(
584     docsrs,
585     doc(cfg(all(feature = "tcp", any(feature = "http1", feature = "http2"))))
586 )]
587 impl<E> Builder<AddrIncoming, E> {
588     /// Set the duration to remain idle before sending TCP keepalive probes.
589     ///
590     /// If `None` is specified, keepalive is disabled.
tcp_keepalive(mut self, keepalive: Option<Duration>) -> Self591     pub fn tcp_keepalive(mut self, keepalive: Option<Duration>) -> Self {
592         self.incoming.set_keepalive(keepalive);
593         self
594     }
595 
596     /// Set the duration between two successive TCP keepalive retransmissions,
597     /// if acknowledgement to the previous keepalive transmission is not received.
tcp_keepalive_interval(mut self, interval: Option<Duration>) -> Self598     pub fn tcp_keepalive_interval(mut self, interval: Option<Duration>) -> Self {
599         self.incoming.set_keepalive_interval(interval);
600         self
601     }
602 
603     /// Set the number of retransmissions to be carried out before declaring that remote end is not available.
tcp_keepalive_retries(mut self, retries: Option<u32>) -> Self604     pub fn tcp_keepalive_retries(mut self, retries: Option<u32>) -> Self {
605         self.incoming.set_keepalive_retries(retries);
606         self
607     }
608 
609     /// Set the value of `TCP_NODELAY` option for accepted connections.
tcp_nodelay(mut self, enabled: bool) -> Self610     pub fn tcp_nodelay(mut self, enabled: bool) -> Self {
611         self.incoming.set_nodelay(enabled);
612         self
613     }
614 
615     /// Set whether to sleep on accept errors.
616     ///
617     /// A possible scenario is that the process has hit the max open files
618     /// allowed, and so trying to accept a new connection will fail with
619     /// EMFILE. In some cases, it's preferable to just wait for some time, if
620     /// the application will likely close some files (or connections), and try
621     /// to accept the connection again. If this option is true, the error will
622     /// be logged at the error level, since it is still a big deal, and then
623     /// the listener will sleep for 1 second.
624     ///
625     /// In other cases, hitting the max open files should be treat similarly
626     /// to being out-of-memory, and simply error (and shutdown). Setting this
627     /// option to false will allow that.
628     ///
629     /// For more details see [`AddrIncoming::set_sleep_on_errors`]
tcp_sleep_on_accept_errors(mut self, val: bool) -> Self630     pub fn tcp_sleep_on_accept_errors(mut self, val: bool) -> Self {
631         self.incoming.set_sleep_on_errors(val);
632         self
633     }
634 
635     /// Returns the local address that the server will be bound to.
636     ///
637     /// This might be useful when knowing the address is required before calling `Builder::serve`,
638     /// but the address is not otherwise available (for e.g. when binding to port 0).
local_addr(&self) -> SocketAddr639     pub fn local_addr(&self) -> SocketAddr {
640         self.incoming.local_addr()
641     }
642 }
643 
644 // Used by `Server` to optionally watch a `Connection` future.
645 //
646 // The regular `hyper::Server` just uses a `NoopWatcher`, which does
647 // not need to watch anything, and so returns the `Connection` untouched.
648 //
649 // The `Server::with_graceful_shutdown` needs to keep track of all active
650 // connections, and signal that they start to shutdown when prompted, so
651 // it has a `GracefulWatcher` implementation to do that.
652 pub trait Watcher<I, S: HttpService<Body>, E>: Clone {
653     type Future: Future<Output = crate::Result<()>>;
654 
watch(&self, conn: UpgradeableConnection<I, S, E>) -> Self::Future655     fn watch(&self, conn: UpgradeableConnection<I, S, E>) -> Self::Future;
656 }
657 
658 #[allow(missing_debug_implementations)]
659 #[derive(Copy, Clone)]
660 pub struct NoopWatcher;
661 
662 impl<I, S, E> Watcher<I, S, E> for NoopWatcher
663 where
664     I: AsyncRead + AsyncWrite + Unpin + Send + 'static,
665     S: HttpService<Body>,
666     E: ConnStreamExec<S::Future, S::ResBody>,
667     S::ResBody: 'static,
668     <S::ResBody as HttpBody>::Error: Into<Box<dyn StdError + Send + Sync>>,
669 {
670     type Future = UpgradeableConnection<I, S, E>;
671 
watch(&self, conn: UpgradeableConnection<I, S, E>) -> Self::Future672     fn watch(&self, conn: UpgradeableConnection<I, S, E>) -> Self::Future {
673         conn
674     }
675 }
676 
677 // used by exec.rs
678 pub(crate) mod new_svc {
679     use std::error::Error as StdError;
680     use std::future::Future;
681     use std::marker::Unpin;
682     use std::pin::Pin;
683     use std::task::{Context, Poll};
684 
685     use tokio::io::{AsyncRead, AsyncWrite};
686     use tracing::debug;
687 
688     use super::{Connecting, Watcher};
689     use crate::body::{Body, HttpBody};
690     use crate::common::exec::ConnStreamExec;
691     use crate::service::HttpService;
692     use pin_project_lite::pin_project;
693 
694     // This is a `Future<Item=(), Error=()>` spawned to an `Executor` inside
695     // the `Server`. By being a nameable type, we can be generic over the
696     // user's `Service::Future`, and thus an `Executor` can execute it.
697     //
698     // Doing this allows for the server to conditionally require `Send` futures,
699     // depending on the `Executor` configured.
700     //
701     // Users cannot import this type, nor the associated `NewSvcExec`. Instead,
702     // a blanket implementation for `Executor<impl Future>` is sufficient.
703 
704     pin_project! {
705         #[allow(missing_debug_implementations)]
706         pub struct NewSvcTask<I, N, S: HttpService<Body>, E, W: Watcher<I, S, E>> {
707             #[pin]
708             state: State<I, N, S, E, W>,
709         }
710     }
711 
712     pin_project! {
713         #[project = StateProj]
714         pub(super) enum State<I, N, S: HttpService<Body>, E, W: Watcher<I, S, E>> {
715             Connecting {
716                 #[pin]
717                 connecting: Connecting<I, N, E>,
718                 watcher: W,
719             },
720             Connected {
721                 #[pin]
722                 future: W::Future,
723             },
724         }
725     }
726 
727     impl<I, N, S: HttpService<Body>, E, W: Watcher<I, S, E>> NewSvcTask<I, N, S, E, W> {
new(connecting: Connecting<I, N, E>, watcher: W) -> Self728         pub(super) fn new(connecting: Connecting<I, N, E>, watcher: W) -> Self {
729             NewSvcTask {
730                 state: State::Connecting {
731                     connecting,
732                     watcher,
733                 },
734             }
735         }
736     }
737 
738     impl<I, N, S, NE, B, E, W> Future for NewSvcTask<I, N, S, E, W>
739     where
740         I: AsyncRead + AsyncWrite + Unpin + Send + 'static,
741         N: Future<Output = Result<S, NE>>,
742         NE: Into<Box<dyn StdError + Send + Sync>>,
743         S: HttpService<Body, ResBody = B>,
744         B: HttpBody + 'static,
745         B::Error: Into<Box<dyn StdError + Send + Sync>>,
746         E: ConnStreamExec<S::Future, B>,
747         W: Watcher<I, S, E>,
748     {
749         type Output = ();
750 
poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>751         fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
752             // If it weren't for needing to name this type so the `Send` bounds
753             // could be projected to the `Serve` executor, this could just be
754             // an `async fn`, and much safer. Woe is me.
755 
756             let mut me = self.project();
757             loop {
758                 let next = {
759                     match me.state.as_mut().project() {
760                         StateProj::Connecting {
761                             connecting,
762                             watcher,
763                         } => {
764                             let res = ready!(connecting.poll(cx));
765                             let conn = match res {
766                                 Ok(conn) => conn,
767                                 Err(err) => {
768                                     let err = crate::Error::new_user_make_service(err);
769                                     debug!("connecting error: {}", err);
770                                     return Poll::Ready(());
771                                 }
772                             };
773                             let future = watcher.watch(conn.with_upgrades());
774                             State::Connected { future }
775                         }
776                         StateProj::Connected { future } => {
777                             return future.poll(cx).map(|res| {
778                                 if let Err(err) = res {
779                                     debug!("connection error: {}", err);
780                                 }
781                             });
782                         }
783                     }
784                 };
785 
786                 me.state.set(next);
787             }
788         }
789     }
790 }
791 
792 pin_project! {
793     /// A future building a new `Service` to a `Connection`.
794     ///
795     /// Wraps the future returned from `MakeService` into one that returns
796     /// a `Connection`.
797     #[must_use = "futures do nothing unless polled"]
798     #[derive(Debug)]
799     #[cfg_attr(docsrs, doc(cfg(any(feature = "http1", feature = "http2"))))]
800     pub struct Connecting<I, F, E = Exec> {
801         #[pin]
802         future: F,
803         io: Option<I>,
804         protocol: Http_<E>,
805     }
806 }
807 
808 impl<I, F, S, FE, E, B> Future for Connecting<I, F, E>
809 where
810     I: AsyncRead + AsyncWrite + Unpin,
811     F: Future<Output = Result<S, FE>>,
812     S: HttpService<Body, ResBody = B>,
813     B: HttpBody + 'static,
814     B::Error: Into<Box<dyn StdError + Send + Sync>>,
815     E: ConnStreamExec<S::Future, B>,
816 {
817     type Output = Result<Connection<I, S, E>, FE>;
818 
poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output>819     fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
820         let mut me = self.project();
821         let service = ready!(me.future.poll(cx))?;
822         let io = Option::take(&mut me.io).expect("polled after complete");
823         Poll::Ready(Ok(me.protocol.serve_connection(io, service)))
824     }
825 }
826