Skip to main content

ntex/web/
server.rs

1use std::{io, marker::PhantomData, net, sync::Arc, sync::Mutex};
2
3#[cfg(feature = "openssl")]
4use tls_openssl::ssl::{AlpnError, SslAcceptor, SslAcceptorBuilder};
5#[cfg(feature = "rustls")]
6use tls_rustls::ServerConfig as RustlsServerConfig;
7
8use crate::error::IntoFailure;
9use crate::http::{self, Request, Response, ResponseError};
10use crate::server::{Affinity, LoadBalancing, NoConfig, Server, ServerAppConfig, ServerBuilder};
11use crate::service::{IntoServiceFactory, Service, ServiceFactory, State, fn_service};
12use crate::{SharedCfg, time::Seconds};
13
14struct Config {
15    host: Option<String>,
16}
17
18/// An HTTP Server.
19///
20/// Create new http server with application factory.
21///
22/// ```rust,no_run
23/// use ntex::web::{self, App, HttpResponse, HttpServer};
24///
25/// #[ntex::main]
26/// async fn main() -> std::io::Result<()> {
27///     HttpServer::new(
28///         async |_| App::new()
29///             .service(web::resource("/").to(async || { HttpResponse::Ok() })))
30///         .bind("127.0.0.1:59090", ntex::SharedCfg::default())?
31///         .run()
32///         .await
33/// }
34/// ```
35#[derive(derive_more::Debug)]
36#[debug("HttpServer")]
37pub struct HttpServer<Cfg, F, I, Sf>
38where
39    Cfg: ServerAppConfig,
40    Cfg::State: Clone,
41    F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
42    I: IntoServiceFactory<Sf, Cfg::State, Request>,
43    Sf: ServiceFactory<Cfg::State, Request>,
44    Sf::Res: Into<Response>,
45    Sf::Error: ResponseError,
46    Sf::InitError: IntoFailure,
47{
48    factory: F,
49    config: Arc<Mutex<Config>>,
50    backlog: i32,
51    builder: ServerBuilder<Cfg>,
52    _t: PhantomData<Sf>,
53}
54
55impl<F, I, Sf> HttpServer<NoConfig, F, I, Sf>
56where
57    F: AsyncFn(&()) -> I + Send + Clone + 'static,
58    I: IntoServiceFactory<Sf, (), Request>,
59    Sf: ServiceFactory<(), Request> + 'static,
60    Sf::Res: Into<Response>,
61    Sf::Error: ResponseError,
62    Sf::InitError: IntoFailure,
63{
64    #[must_use]
65    /// Create new http server with application factory
66    pub fn new(factory: F) -> Self {
67        HttpServer {
68            factory,
69            config: Arc::new(Mutex::new(Config { host: None })),
70            backlog: 1024,
71            builder: ServerBuilder::default(),
72            _t: PhantomData,
73        }
74    }
75}
76
77impl<Cfg, F, I, Sf> HttpServer<Cfg, F, I, Sf>
78where
79    Cfg: ServerAppConfig,
80    Cfg::State: Clone,
81    F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
82    I: IntoServiceFactory<Sf, Cfg::State, Request>,
83    Sf: ServiceFactory<Cfg::State, Request> + 'static,
84    Sf::Res: Into<Response>,
85    Sf::Error: ResponseError,
86    Sf::InitError: IntoFailure,
87{
88    #[must_use]
89    /// Create new http server with application factory and state mapping
90    pub fn with_config(cfg: Cfg, factory: F) -> Self
91    where
92        Cfg: ServerAppConfig,
93    {
94        HttpServer {
95            factory,
96            config: Arc::new(Mutex::new(Config { host: None })),
97            backlog: 1024,
98            builder: ServerBuilder::new(cfg),
99            _t: PhantomData,
100        }
101    }
102
103    #[must_use]
104    /// Set number of workers to start.
105    ///
106    /// By default http server uses number of available logical cpu as threads
107    /// count.
108    ///
109    /// # Panics
110    ///
111    /// Panics if `num` is zero.
112    pub fn workers(mut self, num: usize) -> Self {
113        self.builder = self.builder.workers(num);
114        self
115    }
116
117    #[must_use]
118    /// Set the maximum number of pending connections.
119    ///
120    /// This refers to the number of clients that can be waiting to be served.
121    /// Exceeding this number results in the client getting an error when
122    /// attempting to connect. It should only affect servers under significant
123    /// load.
124    ///
125    /// Generally set in the 64-2048 range. Default value is 1024.
126    ///
127    /// This method should be called before `bind()` method call.
128    pub fn backlog(mut self, backlog: i32) -> Self {
129        self.backlog = backlog;
130        self.builder = self.builder.backlog(backlog);
131        self
132    }
133
134    #[must_use]
135    /// Sets the number of accept threads.
136    ///
137    /// Each accept thread has its own `SO_REUSEPORT` copy of every TCP
138    /// listener, and the kernel spreads incoming connections between them.
139    /// This raises the connection rate the server can accept. Unix domain
140    /// listeners are served by a single accept thread.
141    ///
142    /// Multiple accept threads are supported on Linux and Android. On other
143    /// platforms, a single thread is used.
144    ///
145    /// By default, the server uses a single accept thread. One thread is
146    /// usually enough, add more only if the accept thread is saturated.
147    pub fn acceptors(mut self, num: usize) -> Self {
148        self.builder = self.builder.acceptors(num);
149        self
150    }
151
152    #[must_use]
153    /// Sets the maximum per-worker number of concurrent connections.
154    ///
155    /// All socket listeners of this server stop accepting connections when
156    /// every worker reaches this limit. The limit applies only to this server.
157    ///
158    /// By default max connections is set to a 25k.
159    pub fn max_connections(mut self, num: usize) -> Self {
160        self.builder = self.builder.max_connections(num);
161        self
162    }
163
164    #[must_use]
165    /// Sets the per-worker soft limit on concurrent TLS handshakes.
166    ///
167    /// This limit applies only to TLS acceptors (OpenSSL and rustls), which apply
168    /// readiness backpressure when it is reached. Independent listener or service
169    /// pipelines with cached readiness can still start handshakes and exceed the
170    /// limit; it is not a strict admission limit. Plain TCP listeners are not
171    /// affected.
172    ///
173    /// By default the limit is 256.
174    pub fn max_tls_handshakes(self, num: usize) -> Self {
175        ntex_tls::max_concurrent_ssl_accept(num);
176        self
177    }
178
179    #[must_use]
180    /// Set server host name.
181    ///
182    /// Host name is used by application router as a hostname for url generation.
183    /// Check [`ConnectionInfo::host()`](crate::web::dev::ConnectionInfo::host)
184    /// documentation for more information.
185    ///
186    /// By default host name is set to a "localhost:8080" value.
187    pub fn server_hostname<T: AsRef<str>>(self, val: T) -> Self {
188        self.config.lock().unwrap().host = Some(val.as_ref().to_owned());
189        self
190    }
191
192    #[must_use]
193    /// Stop ntex runtime when server get dropped.
194    ///
195    /// By default "stop runtime" is disabled.
196    pub fn stop_runtime(mut self) -> Self {
197        self.builder = self.builder.stop_runtime();
198        self
199    }
200
201    #[must_use]
202    /// Stops the server when one of the workers panics.
203    ///
204    /// By default, "stop on panic" is disabled.
205    pub fn stop_on_panic(mut self) -> Self {
206        self.builder = self.builder.stop_on_panic();
207        self
208    }
209
210    #[must_use]
211    /// Disable signal handling.
212    ///
213    /// By default, signal handling is enabled.
214    pub fn disable_signals(mut self) -> Self {
215        self.builder = self.builder.disable_signals();
216        self
217    }
218
219    #[must_use]
220    /// Timeout for graceful worker shutdown.
221    ///
222    /// After receiving a stop signal, workers have this much time to finish
223    /// serving requests. Workers that are still alive after the timeout are
224    /// forcefully dropped.
225    ///
226    /// This bounds the worker as a whole, not an individual connection. Each
227    /// connection is bound separately by `IoConfig::set_shutdown_timeout`, so
228    /// this value should leave room for the connections a worker is still
229    /// draining to shut down themselves.
230    ///
231    /// By default, the timeout is set to 30 seconds.
232    pub fn graceful_shutdown_timeout(mut self, sec: Seconds) -> Self {
233        self.builder = self.builder.graceful_shutdown_timeout(sec);
234        self
235    }
236
237    #[must_use]
238    #[deprecated(
239        since = "4.4.0",
240        note = "affinity is enabled by default, use `affinity()` to change it"
241    )]
242    /// Does nothing, affinity is enabled by default.
243    pub fn enable_affinity(self) -> Self {
244        self
245    }
246
247    #[must_use]
248    /// Sets the CPU affinity of worker threads.
249    ///
250    /// Workers are spread over physical cores first, see [`Affinity`].
251    ///
252    /// By default, [`Affinity::Soft`] is used on Windows and
253    /// [`Affinity::Core`] on other platforms.
254    pub fn affinity(mut self, affinity: Affinity) -> Self {
255        self.builder = self.builder.affinity(affinity);
256        self
257    }
258
259    #[must_use]
260    /// Sets how new connections are distributed between workers.
261    ///
262    /// By default, [`LoadBalancing::IncomingCpu`] sends new connections to idle
263    /// workers, which helps when connections are long-lived or their load is
264    /// uneven, and prefers the worker on the CPU that receives a connection's
265    /// network packets. [`LoadBalancing::RoundRobin`] sends them to the
266    /// workers in turn. [`LoadBalancing::Reuseport`] lets each worker accept
267    /// TCP connections on its own `SO_REUSEPORT` socket on Linux.
268    pub fn load_balancing(mut self, balancing: LoadBalancing) -> Self {
269        self.builder = self.builder.load_balancing(balancing);
270        self
271    }
272
273    #[must_use]
274    /// Graceful shutdown.
275    ///
276    /// When enabled, SIGQUIT, SIGSEGV, SIGABRT, and application panics stop the
277    /// server gracefully. SIGTERM always stops the server gracefully, and SIGINT
278    /// always stops it immediately. SIGSEGV and SIGABRT require runtime fatal
279    /// signal handling, application panics require runtime panic handling.
280    ///
281    /// By default, these events stop the server immediately.
282    pub fn graceful_shutdown(mut self) -> Self {
283        self.builder = self.builder.graceful_shutdown();
284        self
285    }
286
287    /// Use listener for accepting incoming connection requests
288    ///
289    /// `HttpServer` does not change any configuration for `TcpListener`,
290    /// it needs to be configured before passing it to `listen()` method.
291    pub fn listen(mut self, lst: net::TcpListener, cfg: impl Into<SharedCfg>) -> io::Result<Self> {
292        let factory = self.factory.clone();
293        let addr = lst.local_addr().unwrap();
294
295        self.builder = self.builder.listen(
296            format!("ntex-web-service-{addr}"),
297            lst,
298            cfg.into(),
299            async move |st| {
300                let state = st.clone();
301                fn_service(async move |req| {
302                    Ok(State {
303                        req,
304                        state: state.clone(),
305                    })
306                })
307                .and_then(http::HttpService::new(factory(st).await))
308            },
309        )?;
310        Ok(self)
311    }
312
313    #[cfg(feature = "openssl")]
314    /// Use listener for accepting incoming tls connection requests.
315    ///
316    /// This method sets alpn protocols to "h2" and "http/1.1"
317    pub fn listen_openssl(
318        self,
319        lst: net::TcpListener,
320        cfg: impl Into<SharedCfg>,
321        builder: SslAcceptorBuilder,
322    ) -> io::Result<Self> {
323        self.listen_openssl_inner(lst, cfg.into(), openssl_acceptor(builder)?)
324    }
325
326    #[cfg(feature = "openssl")]
327    fn listen_openssl_inner(
328        mut self,
329        lst: net::TcpListener,
330        cfg: SharedCfg,
331        acceptor: SslAcceptor,
332    ) -> io::Result<Self> {
333        let factory = self.factory.clone();
334        let addr = lst.local_addr().unwrap();
335
336        self.builder = self.builder.listen(
337            format!("ntex-web-service-{addr}"),
338            lst,
339            cfg,
340            async move |st| {
341                let state = st.clone();
342
343                http::openssl(
344                    acceptor.clone(),
345                    fn_service(async move |req| {
346                        Ok(State {
347                            req,
348                            state: state.clone(),
349                        })
350                    })
351                    .and_then(http::HttpService::new(factory(st).await)),
352                )
353            },
354        )?;
355        Ok(self)
356    }
357
358    #[cfg(feature = "rustls")]
359    /// Use listener for accepting incoming tls connection requests.
360    ///
361    /// This method sets alpn protocols to "h2" and "http/1.1"
362    pub fn listen_rustls(
363        self,
364        lst: net::TcpListener,
365        cfg: impl Into<SharedCfg>,
366        config: RustlsServerConfig,
367    ) -> io::Result<Self> {
368        self.listen_rustls_inner(lst, cfg.into(), config)
369    }
370
371    #[cfg(feature = "rustls")]
372    fn listen_rustls_inner(
373        mut self,
374        lst: net::TcpListener,
375        cfg: SharedCfg,
376        config: RustlsServerConfig,
377    ) -> io::Result<Self> {
378        let factory = self.factory.clone();
379        let addr = lst.local_addr().unwrap();
380
381        self.builder = self.builder.listen(
382            format!("ntex-web-rustls-service-{addr}"),
383            lst,
384            cfg,
385            async move |st| {
386                let state = st.clone();
387                http::rustls(
388                    config.clone(),
389                    http::ALPN_PROTOS,
390                    fn_service(async move |req| {
391                        Ok(State {
392                            req,
393                            state: state.clone(),
394                        })
395                    })
396                    .and_then(http::HttpService::new(factory(st).await)),
397                )
398            },
399        )?;
400        Ok(self)
401    }
402
403    /// The socket address to bind.
404    ///
405    /// To bind multiple addresses this method can be called multiple times.
406    pub fn bind<A: net::ToSocketAddrs>(
407        mut self,
408        addr: A,
409        cfg: impl Into<SharedCfg>,
410    ) -> io::Result<Self> {
411        let cfg = cfg.into();
412        for lst in self.bind2(addr)? {
413            self = self.listen(lst, cfg.clone())?;
414        }
415
416        Ok(self)
417    }
418
419    fn bind2<A: net::ToSocketAddrs>(&self, addr: A) -> io::Result<Vec<net::TcpListener>> {
420        let mut err = None;
421        let mut succ = false;
422        let mut sockets = Vec::new();
423        for addr in addr.to_socket_addrs()? {
424            match crate::server::create_tcp_listener(addr, self.backlog) {
425                Ok(lst) => {
426                    succ = true;
427                    sockets.push(lst);
428                }
429                Err(e) => err = Some(e),
430            }
431        }
432
433        if succ {
434            Ok(sockets)
435        } else if let Some(e) = err.take() {
436            Err(e)
437        } else {
438            Err(io::Error::new(
439                io::ErrorKind::InvalidInput,
440                "Cannot bind to address.",
441            ))
442        }
443    }
444
445    #[cfg(feature = "openssl")]
446    /// Start listening for incoming tls connections.
447    ///
448    /// This method sets alpn protocols to "h2" and "http/1.1"
449    pub fn bind_openssl<A>(
450        mut self,
451        addr: A,
452        builder: SslAcceptorBuilder,
453        cfg: impl Into<SharedCfg>,
454    ) -> io::Result<Self>
455    where
456        A: net::ToSocketAddrs,
457    {
458        let cfg = cfg.into();
459        let sockets = self.bind2(addr)?;
460        let acceptor = openssl_acceptor(builder)?;
461
462        for lst in sockets {
463            self = self.listen_openssl_inner(lst, cfg.clone(), acceptor.clone())?;
464        }
465
466        Ok(self)
467    }
468
469    #[cfg(feature = "rustls")]
470    /// Start listening for incoming tls connections.
471    ///
472    /// This method sets alpn protocols to "h2" and "http/1.1"
473    pub fn bind_rustls<A: net::ToSocketAddrs>(
474        mut self,
475        addr: A,
476        config: &RustlsServerConfig,
477        cfg: impl Into<SharedCfg>,
478    ) -> io::Result<Self> {
479        let cfg = cfg.into();
480        let sockets = self.bind2(addr)?;
481        for lst in sockets {
482            self = self.listen_rustls_inner(lst, cfg.clone(), config.clone())?;
483        }
484        Ok(self)
485    }
486
487    #[cfg(unix)]
488    /// Start listening for unix domain connections on existing listener.
489    ///
490    /// This method is available only on Unix.
491    pub fn listen_uds(
492        mut self,
493        lst: std::os::unix::net::UnixListener,
494        cfg: impl Into<SharedCfg>,
495    ) -> io::Result<Self> {
496        let factory = self.factory.clone();
497        let addr = format!("ntex-web-service-{:?}", lst.local_addr()?);
498
499        self.builder = self
500            .builder
501            .listen_uds(addr, lst, cfg.into(), async move |st| {
502                let state = st.clone();
503                fn_service(async move |req| {
504                    Ok(State {
505                        req,
506                        state: state.clone(),
507                    })
508                })
509                .and_then(http::HttpService::new(factory(st).await))
510            })?;
511        Ok(self)
512    }
513
514    #[cfg(unix)]
515    /// Start listening for incoming unix domain connections.
516    ///
517    /// This method is available only on Unix.
518    pub fn bind_uds<A>(mut self, addr: A, cfg: impl Into<SharedCfg>) -> io::Result<Self>
519    where
520        A: AsRef<std::path::Path>,
521    {
522        let factory = self.factory.clone();
523
524        self.builder = self.builder.bind_uds(
525            format!("ntex-web-service-{:?}", addr.as_ref().display()),
526            addr,
527            cfg.into(),
528            async move |st| {
529                let state = st.clone();
530                fn_service(async move |req| {
531                    Ok(State {
532                        req,
533                        state: state.clone(),
534                    })
535                })
536                .and_then(http::HttpService::new(factory(st).await))
537            },
538        )?;
539        Ok(self)
540    }
541}
542
543impl<Cfg, F, I, Sf> HttpServer<Cfg, F, I, Sf>
544where
545    Cfg: ServerAppConfig,
546    Cfg::State: Clone,
547    F: AsyncFn(&Cfg::State) -> I + Send + Clone + 'static,
548    I: IntoServiceFactory<Sf, Cfg::State, Request>,
549    Sf: ServiceFactory<Cfg::State, Request> + 'static,
550    Sf::Res: Into<Response>,
551    Sf::Error: ResponseError,
552    Sf::InitError: IntoFailure,
553{
554    /// Start listening for incoming connections.
555    ///
556    /// This method starts number of http workers in separate threads.
557    /// For each address this method starts separate thread which does
558    /// `accept()` in a loop.
559    ///
560    /// # Panics
561    ///
562    /// Panics if no listener was registered before calling this method.
563    ///
564    /// ```rust,no_run
565    /// use ntex::web::{self, App, HttpResponse, HttpServer};
566    ///
567    /// #[ntex::main]
568    /// async fn main() -> std::io::Result<()> {
569    ///     HttpServer::new(
570    ///         async |_| App::new().service(web::resource("/").to(async || { HttpResponse::Ok() }))
571    ///     )
572    ///         .bind("127.0.0.1:0", ntex::SharedCfg::default())?
573    ///         .run()
574    ///         .await
575    /// }
576    /// ```
577    pub fn run(self) -> Server {
578        self.builder.run()
579    }
580}
581
582#[cfg(feature = "openssl")]
583/// Configure `SslAcceptorBuilder` with custom server flags.
584fn openssl_acceptor(mut builder: SslAcceptorBuilder) -> io::Result<SslAcceptor> {
585    builder.set_alpn_select_callback(|_, protos| {
586        const H2: &[u8] = b"\x02h2";
587        const H11: &[u8] = b"\x08http/1.1";
588        if protos.windows(3).any(|window| window == H2) {
589            Ok(b"h2")
590        } else if protos.windows(9).any(|window| window == H11) {
591            Ok(b"http/1.1")
592        } else {
593            Err(AlpnError::NOACK)
594        }
595    });
596    builder.set_alpn_protos(b"\x08http/1.1\x02h2")?;
597
598    Ok(builder.build())
599}