2017-12-13 02:21:00 +01:00
|
|
|
use std::{io, net, thread};
|
2017-10-07 06:48:14 +02:00
|
|
|
use std::rc::Rc;
|
2017-12-26 18:00:45 +01:00
|
|
|
use std::cell::{RefCell, RefMut};
|
2017-12-27 21:58:32 +01:00
|
|
|
use std::sync::{Arc, mpsc as sync_mpsc};
|
2017-12-14 01:44:35 +01:00
|
|
|
use std::time::Duration;
|
2017-10-16 22:13:32 +02:00
|
|
|
use std::marker::PhantomData;
|
2017-12-17 21:35:04 +01:00
|
|
|
use std::collections::HashMap;
|
2017-10-07 06:48:14 +02:00
|
|
|
|
|
|
|
use actix::dev::*;
|
2017-11-04 20:33:14 +01:00
|
|
|
use futures::Stream;
|
2017-12-13 02:21:00 +01:00
|
|
|
use futures::sync::mpsc;
|
2017-10-16 22:13:32 +02:00
|
|
|
use tokio_io::{AsyncRead, AsyncWrite};
|
2017-12-27 20:22:27 +01:00
|
|
|
use tokio_core::reactor::Handle;
|
2017-12-13 02:21:00 +01:00
|
|
|
use tokio_core::net::TcpStream;
|
2017-12-27 20:22:27 +01:00
|
|
|
use mio;
|
2017-12-13 02:21:00 +01:00
|
|
|
use num_cpus;
|
2017-12-27 20:22:27 +01:00
|
|
|
use net2::{TcpBuilder, TcpStreamExt};
|
2017-10-07 06:48:14 +02:00
|
|
|
|
2017-11-10 22:08:15 +01:00
|
|
|
#[cfg(feature="tls")]
|
2017-12-13 02:21:00 +01:00
|
|
|
use futures::{future, Future};
|
2017-11-02 00:34:58 +01:00
|
|
|
#[cfg(feature="tls")]
|
|
|
|
use native_tls::TlsAcceptor;
|
|
|
|
#[cfg(feature="tls")]
|
|
|
|
use tokio_tls::{TlsStream, TlsAcceptorExt};
|
|
|
|
|
2017-11-04 21:24:57 +01:00
|
|
|
#[cfg(feature="alpn")]
|
2017-12-13 02:21:00 +01:00
|
|
|
use futures::{future, Future};
|
2017-11-04 20:33:14 +01:00
|
|
|
#[cfg(feature="alpn")]
|
2017-12-13 02:21:00 +01:00
|
|
|
use openssl::ssl::{SslMethod, SslAcceptor, SslAcceptorBuilder};
|
2017-11-04 20:33:14 +01:00
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
use openssl::pkcs12::ParsedPkcs12;
|
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
use tokio_openssl::{SslStream, SslAcceptorExt};
|
|
|
|
|
2017-12-14 07:54:52 +01:00
|
|
|
use helpers;
|
2017-12-06 20:00:39 +01:00
|
|
|
use channel::{HttpChannel, HttpHandler, IntoHttpHandler};
|
2017-10-22 03:54:24 +02:00
|
|
|
|
2017-12-08 07:54:44 +01:00
|
|
|
/// Various server settings
|
2017-12-08 18:24:05 +01:00
|
|
|
#[derive(Debug, Clone)]
|
|
|
|
pub struct ServerSettings {
|
2017-12-13 02:21:00 +01:00
|
|
|
addr: Option<net::SocketAddr>,
|
2017-12-08 07:54:44 +01:00
|
|
|
secure: bool,
|
2017-12-08 18:48:53 +01:00
|
|
|
host: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Default for ServerSettings {
|
|
|
|
fn default() -> Self {
|
|
|
|
ServerSettings {
|
|
|
|
addr: None,
|
|
|
|
secure: false,
|
|
|
|
host: "localhost:8080".to_owned(),
|
|
|
|
}
|
|
|
|
}
|
2017-12-08 07:54:44 +01:00
|
|
|
}
|
|
|
|
|
2017-12-08 18:24:05 +01:00
|
|
|
impl ServerSettings {
|
2017-12-08 07:54:44 +01:00
|
|
|
/// Crate server settings instance
|
2017-12-26 23:36:03 +01:00
|
|
|
fn new(addr: Option<net::SocketAddr>, host: &Option<String>, secure: bool) -> Self {
|
|
|
|
let host = if let Some(ref host) = *host {
|
|
|
|
host.clone()
|
|
|
|
} else if let Some(ref addr) = addr {
|
2017-12-08 18:48:53 +01:00
|
|
|
format!("{}", addr)
|
2017-12-08 18:24:05 +01:00
|
|
|
} else {
|
2017-12-26 23:36:03 +01:00
|
|
|
"localhost".to_owned()
|
2017-12-08 18:24:05 +01:00
|
|
|
};
|
|
|
|
ServerSettings {
|
|
|
|
addr: addr,
|
|
|
|
secure: secure,
|
|
|
|
host: host,
|
|
|
|
}
|
2017-12-08 07:54:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns the socket address of the local half of this TCP connection
|
2017-12-13 02:21:00 +01:00
|
|
|
pub fn local_addr(&self) -> Option<net::SocketAddr> {
|
2017-12-08 18:24:05 +01:00
|
|
|
self.addr
|
2017-12-08 07:54:44 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns true if connection is secure(https)
|
|
|
|
pub fn secure(&self) -> bool {
|
2017-12-08 18:24:05 +01:00
|
|
|
self.secure
|
2017-12-08 07:54:44 +01:00
|
|
|
}
|
|
|
|
|
2017-12-08 18:24:05 +01:00
|
|
|
/// Returns host header value
|
2017-12-08 18:48:53 +01:00
|
|
|
pub fn host(&self) -> &str {
|
|
|
|
&self.host
|
2017-12-08 07:54:44 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-08 23:56:51 +02:00
|
|
|
/// An HTTP Server
|
2017-10-16 22:13:32 +02:00
|
|
|
///
|
2017-12-14 08:09:20 +01:00
|
|
|
/// `T` - async stream, anything that implements `AsyncRead` + `AsyncWrite`.
|
2017-10-16 22:13:32 +02:00
|
|
|
///
|
|
|
|
/// `A` - peer address
|
2017-10-22 03:54:24 +02:00
|
|
|
///
|
|
|
|
/// `H` - request handler
|
2017-12-13 02:21:00 +01:00
|
|
|
pub struct HttpServer<T, A, H, U>
|
|
|
|
where H: 'static
|
|
|
|
{
|
2017-12-14 06:38:47 +01:00
|
|
|
h: Option<Rc<WorkerSettings<H>>>,
|
2017-10-16 22:13:32 +02:00
|
|
|
io: PhantomData<T>,
|
|
|
|
addr: PhantomData<A>,
|
2017-12-13 02:21:00 +01:00
|
|
|
threads: usize,
|
2017-12-17 21:35:04 +01:00
|
|
|
backlog: i32,
|
2017-12-26 23:36:03 +01:00
|
|
|
host: Option<String>,
|
2017-12-14 07:36:28 +01:00
|
|
|
keep_alive: Option<u64>,
|
2017-12-13 02:21:00 +01:00
|
|
|
factory: Arc<Fn() -> U + Send + Sync>,
|
|
|
|
workers: Vec<SyncAddress<Worker<H>>>,
|
2017-12-27 20:22:27 +01:00
|
|
|
sockets: HashMap<net::SocketAddr, net::TcpListener>,
|
2017-12-27 21:58:32 +01:00
|
|
|
accept: Vec<(mio::SetReadiness, sync_mpsc::Sender<Command>)>,
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<T: 'static, A: 'static, H, U: 'static> Actor for HttpServer<T, A, H, U> {
|
2017-10-07 06:48:14 +02:00
|
|
|
type Context = Context<Self>;
|
2017-12-14 01:44:35 +01:00
|
|
|
|
|
|
|
fn started(&mut self, ctx: &mut Self::Context) {
|
|
|
|
self.update_time(ctx);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T: 'static, A: 'static, H, U: 'static> HttpServer<T, A, H, U> {
|
|
|
|
fn update_time(&self, ctx: &mut Context<Self>) {
|
2017-12-14 07:54:52 +01:00
|
|
|
helpers::update_date();
|
2017-12-14 01:44:35 +01:00
|
|
|
ctx.run_later(Duration::new(1, 0), |slf, ctx| slf.update_time(ctx));
|
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<T, A, H, U, V> HttpServer<T, A, H, U>
|
2017-12-14 01:44:35 +01:00
|
|
|
where A: 'static,
|
|
|
|
T: AsyncRead + AsyncWrite + 'static,
|
|
|
|
H: HttpHandler,
|
2017-12-13 02:21:00 +01:00
|
|
|
U: IntoIterator<Item=V> + 'static,
|
|
|
|
V: IntoHttpHandler<Handler=H>,
|
2017-10-22 03:54:24 +02:00
|
|
|
{
|
2017-12-14 08:09:20 +01:00
|
|
|
/// Create new http server with application factory
|
2017-12-13 02:21:00 +01:00
|
|
|
pub fn new<F>(factory: F) -> Self
|
|
|
|
where F: Sync + Send + 'static + Fn() -> U,
|
2017-12-06 20:00:39 +01:00
|
|
|
{
|
2017-12-14 06:38:47 +01:00
|
|
|
HttpServer{ h: None,
|
2017-10-22 03:54:24 +02:00
|
|
|
io: PhantomData,
|
2017-12-13 02:21:00 +01:00
|
|
|
addr: PhantomData,
|
|
|
|
threads: num_cpus::get(),
|
2017-12-17 21:35:04 +01:00
|
|
|
backlog: 2048,
|
2017-12-26 23:36:03 +01:00
|
|
|
host: None,
|
2017-12-14 06:38:47 +01:00
|
|
|
keep_alive: None,
|
2017-12-13 02:21:00 +01:00
|
|
|
factory: Arc::new(factory),
|
|
|
|
workers: Vec::new(),
|
2017-12-17 21:35:04 +01:00
|
|
|
sockets: HashMap::new(),
|
2017-12-27 21:58:32 +01:00
|
|
|
accept: Vec::new(),
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Set number of workers to start.
|
|
|
|
///
|
|
|
|
/// By default http server uses number of available logical cpu as threads count.
|
|
|
|
pub fn threads(mut self, num: usize) -> Self {
|
|
|
|
self.threads = num;
|
|
|
|
self
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
2017-10-16 22:13:32 +02:00
|
|
|
|
2017-12-17 21:35:04 +01:00
|
|
|
/// Set the maximum number of pending connections.
|
|
|
|
///
|
|
|
|
/// This refers to the number of clients that can be waiting to be served.
|
|
|
|
/// Exceeding this number results in the client getting an error when
|
|
|
|
/// attempting to connect. It should only affect servers under significant load.
|
|
|
|
///
|
|
|
|
/// Generally set in the 64-2048 range. Default value is 2048.
|
2017-12-27 20:22:27 +01:00
|
|
|
///
|
|
|
|
/// This method should be called before `bind()` method call.
|
2017-12-17 21:35:04 +01:00
|
|
|
pub fn backlog(mut self, num: i32) -> Self {
|
|
|
|
self.backlog = num;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-14 06:38:47 +01:00
|
|
|
/// Set server keep-alive setting.
|
|
|
|
///
|
|
|
|
/// By default keep alive is enabled.
|
|
|
|
///
|
|
|
|
/// - `Some(75)` - enable
|
|
|
|
///
|
|
|
|
/// - `Some(0)` - disable
|
|
|
|
///
|
|
|
|
/// - `None` - use `SO_KEEPALIVE` socket option
|
2017-12-14 07:36:28 +01:00
|
|
|
pub fn keep_alive(mut self, val: Option<u64>) -> Self {
|
2017-12-14 06:38:47 +01:00
|
|
|
self.keep_alive = val;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-26 23:36:03 +01:00
|
|
|
/// Set server host name.
|
|
|
|
///
|
|
|
|
/// Host name is used by application router aa a hostname for url generation.
|
|
|
|
/// Check [ConnectionInfo](./dev/struct.ConnectionInfo.html#method.host) documentation
|
|
|
|
/// for more information.
|
|
|
|
pub fn server_hostname(mut self, val: String) -> Self {
|
|
|
|
self.host = Some(val);
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-26 23:45:38 +01:00
|
|
|
/// Get addresses of bound sockets.
|
|
|
|
pub fn addrs(&self) -> Vec<net::SocketAddr> {
|
2017-12-27 01:35:00 +01:00
|
|
|
self.sockets.keys().cloned().collect()
|
2017-12-26 23:45:38 +01:00
|
|
|
}
|
|
|
|
|
2017-12-17 21:35:04 +01:00
|
|
|
/// The socket address to bind
|
|
|
|
///
|
|
|
|
/// To mind multiple addresses this method can be call multiple times.
|
|
|
|
pub fn bind<S: net::ToSocketAddrs>(mut self, addr: S) -> io::Result<Self> {
|
2017-10-15 23:53:03 +02:00
|
|
|
let mut err = None;
|
2017-12-17 21:35:04 +01:00
|
|
|
let mut succ = false;
|
2017-10-16 10:19:23 +02:00
|
|
|
if let Ok(iter) = addr.to_socket_addrs() {
|
2017-10-15 23:53:03 +02:00
|
|
|
for addr in iter {
|
2017-12-27 21:58:32 +01:00
|
|
|
match create_tcp_listener(addr, self.backlog) {
|
|
|
|
Ok(lst) => {
|
|
|
|
succ = true;
|
|
|
|
self.sockets.insert(lst.local_addr().unwrap(), lst);
|
2017-12-27 20:22:27 +01:00
|
|
|
},
|
|
|
|
Err(e) => err = Some(e),
|
|
|
|
}
|
2017-10-15 23:53:03 +02:00
|
|
|
}
|
|
|
|
}
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-17 21:35:04 +01:00
|
|
|
if !succ {
|
2017-10-15 23:53:03 +02:00
|
|
|
if let Some(e) = err.take() {
|
|
|
|
Err(e)
|
|
|
|
} else {
|
|
|
|
Err(io::Error::new(io::ErrorKind::Other, "Can not bind to address."))
|
|
|
|
}
|
|
|
|
} else {
|
2017-12-17 21:35:04 +01:00
|
|
|
Ok(self)
|
2017-10-15 23:53:03 +02:00
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
|
2017-12-13 21:47:07 +01:00
|
|
|
fn start_workers(&mut self, settings: &ServerSettings, handler: &StreamHandlerType)
|
2017-12-27 20:22:27 +01:00
|
|
|
-> Vec<mpsc::UnboundedSender<IoStream<net::TcpStream>>>
|
2017-12-13 02:21:00 +01:00
|
|
|
{
|
|
|
|
// start workers
|
|
|
|
let mut workers = Vec::new();
|
|
|
|
for _ in 0..self.threads {
|
|
|
|
let s = settings.clone();
|
2017-12-27 20:22:27 +01:00
|
|
|
let (tx, rx) = mpsc::unbounded::<IoStream<net::TcpStream>>();
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-13 21:47:07 +01:00
|
|
|
let h = handler.clone();
|
2017-12-14 07:36:28 +01:00
|
|
|
let ka = self.keep_alive;
|
2017-12-13 02:21:00 +01:00
|
|
|
let factory = Arc::clone(&self.factory);
|
|
|
|
let addr = Arbiter::start(move |ctx: &mut Context<_>| {
|
|
|
|
let mut apps: Vec<_> = (*factory)()
|
|
|
|
.into_iter().map(|h| h.into_handler()).collect();
|
|
|
|
for app in &mut apps {
|
|
|
|
app.server_settings(s.clone());
|
|
|
|
}
|
|
|
|
ctx.add_stream(rx);
|
2017-12-14 06:38:47 +01:00
|
|
|
Worker::new(apps, h, ka)
|
2017-12-13 02:21:00 +01:00
|
|
|
});
|
|
|
|
workers.push(tx);
|
|
|
|
self.workers.push(addr);
|
|
|
|
}
|
|
|
|
info!("Starting {} http workers", self.threads);
|
|
|
|
workers
|
|
|
|
}
|
|
|
|
}
|
2017-11-02 00:34:58 +01:00
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<H: HttpHandler, U, V> HttpServer<TcpStream, net::SocketAddr, H, U>
|
|
|
|
where U: IntoIterator<Item=V> + 'static,
|
|
|
|
V: IntoHttpHandler<Handler=H>,
|
|
|
|
{
|
2017-11-02 00:34:58 +01:00
|
|
|
/// Start listening for incomming connections.
|
|
|
|
///
|
2017-12-17 21:35:04 +01:00
|
|
|
/// This method starts number of http handler workers in seperate threads.
|
2017-12-13 02:21:00 +01:00
|
|
|
/// For each address this method starts separate thread which does `accept()` in a loop.
|
2017-12-19 18:08:36 +01:00
|
|
|
///
|
|
|
|
/// This methods panics if no socket addresses get bound.
|
2017-12-26 21:46:27 +01:00
|
|
|
///
|
|
|
|
/// This method requires to run within properly configured `Actix` system.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// extern crate actix;
|
|
|
|
/// extern crate actix_web;
|
|
|
|
/// use actix_web::*;
|
|
|
|
///
|
|
|
|
/// fn main() {
|
|
|
|
/// let sys = actix::System::new("example"); // <- create Actix system
|
|
|
|
///
|
|
|
|
/// HttpServer::new(
|
|
|
|
/// || Application::new()
|
|
|
|
/// .resource("/", |r| r.h(httpcodes::HTTPOk)))
|
|
|
|
/// .bind("127.0.0.1:8088").expect("Can not bind to 127.0.0.1:8088")
|
|
|
|
/// .start();
|
|
|
|
/// # actix::Arbiter::system().send(actix::msgs::SystemExit(0));
|
|
|
|
///
|
|
|
|
/// let _ = sys.run(); // <- Run actix system, this method actually starts all async processes
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-12-19 18:08:36 +01:00
|
|
|
pub fn start(mut self) -> SyncAddress<Self>
|
2017-11-02 00:34:58 +01:00
|
|
|
{
|
2017-12-17 21:35:04 +01:00
|
|
|
if self.sockets.is_empty() {
|
2017-12-19 18:08:36 +01:00
|
|
|
panic!("HttpServer::bind() has to be called befor start()");
|
2017-12-17 21:35:04 +01:00
|
|
|
} else {
|
2017-12-27 20:22:27 +01:00
|
|
|
let addrs: Vec<(net::SocketAddr, net::TcpListener)> =
|
|
|
|
self.sockets.drain().collect();
|
2017-12-26 23:36:03 +01:00
|
|
|
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
|
2017-12-17 21:35:04 +01:00
|
|
|
let workers = self.start_workers(&settings, &StreamHandlerType::Normal);
|
|
|
|
|
|
|
|
// start acceptors threads
|
|
|
|
for (addr, sock) in addrs {
|
|
|
|
info!("Starting http server on {}", addr);
|
2017-12-27 21:58:32 +01:00
|
|
|
self.accept.push(
|
|
|
|
start_accept_thread(sock, addr, self.backlog, workers.clone()));
|
2017-12-17 21:35:04 +01:00
|
|
|
}
|
2017-12-08 18:24:05 +01:00
|
|
|
|
2017-12-17 21:35:04 +01:00
|
|
|
// start http server actor
|
2017-12-19 18:08:36 +01:00
|
|
|
HttpServer::create(|_| {self})
|
2017-12-17 21:35:04 +01:00
|
|
|
}
|
2017-11-02 00:34:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(feature="tls")]
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<H: HttpHandler, U, V> HttpServer<TlsStream<TcpStream>, net::SocketAddr, H, U>
|
|
|
|
where U: IntoIterator<Item=V> + 'static,
|
|
|
|
V: IntoHttpHandler<Handler=H>,
|
|
|
|
{
|
2017-11-02 00:34:58 +01:00
|
|
|
/// Start listening for incomming tls connections.
|
2017-12-18 22:06:41 +01:00
|
|
|
pub fn start_tls(mut self, pkcs12: ::Pkcs12) -> io::Result<SyncAddress<Self>> {
|
2017-12-17 21:35:04 +01:00
|
|
|
if self.sockets.is_empty() {
|
|
|
|
Err(io::Error::new(io::ErrorKind::Other, "No socket addresses are bound"))
|
|
|
|
} else {
|
2017-12-27 21:58:32 +01:00
|
|
|
let addrs: Vec<(net::SocketAddr, net::TcpListener)> = self.sockets.drain().collect();
|
2017-12-27 00:17:20 +01:00
|
|
|
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
|
2017-12-17 21:35:04 +01:00
|
|
|
let acceptor = match TlsAcceptor::builder(pkcs12) {
|
|
|
|
Ok(builder) => {
|
|
|
|
match builder.build() {
|
|
|
|
Ok(acceptor) => acceptor,
|
|
|
|
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
|
|
|
|
}
|
2017-11-02 00:34:58 +01:00
|
|
|
}
|
2017-12-17 21:35:04 +01:00
|
|
|
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
|
|
|
|
};
|
|
|
|
let workers = self.start_workers(&settings, &StreamHandlerType::Tls(acceptor));
|
|
|
|
|
|
|
|
// start acceptors threads
|
|
|
|
for (addr, sock) in addrs {
|
|
|
|
info!("Starting tls http server on {}", addr);
|
2017-12-27 21:58:32 +01:00
|
|
|
self.accept.push(
|
|
|
|
start_accept_thread(sock, addr, self.backlog, workers.clone()));
|
2017-11-02 00:34:58 +01:00
|
|
|
}
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-17 21:35:04 +01:00
|
|
|
// start http server actor
|
|
|
|
Ok(HttpServer::create(|_| {self}))
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
2017-11-02 00:34:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-04 20:33:14 +01:00
|
|
|
#[cfg(feature="alpn")]
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<H: HttpHandler, U, V> HttpServer<SslStream<TcpStream>, net::SocketAddr, H, U>
|
|
|
|
where U: IntoIterator<Item=V> + 'static,
|
|
|
|
V: IntoHttpHandler<Handler=H>,
|
|
|
|
{
|
2017-11-04 20:33:14 +01:00
|
|
|
/// Start listening for incomming tls connections.
|
|
|
|
///
|
2017-12-17 21:35:04 +01:00
|
|
|
/// This method sets alpn protocols to "h2" and "http/1.1"
|
2017-12-18 22:06:41 +01:00
|
|
|
pub fn start_ssl(mut self, identity: &ParsedPkcs12) -> io::Result<SyncAddress<Self>> {
|
2017-12-17 21:35:04 +01:00
|
|
|
if self.sockets.is_empty() {
|
|
|
|
Err(io::Error::new(io::ErrorKind::Other, "No socket addresses are bound"))
|
|
|
|
} else {
|
2017-12-27 21:58:32 +01:00
|
|
|
let addrs: Vec<(net::SocketAddr, net::TcpListener)> = self.sockets.drain().collect();
|
2017-12-27 00:17:20 +01:00
|
|
|
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
|
2017-12-17 21:35:04 +01:00
|
|
|
let acceptor = match SslAcceptorBuilder::mozilla_intermediate(
|
|
|
|
SslMethod::tls(), &identity.pkey, &identity.cert, &identity.chain)
|
|
|
|
{
|
|
|
|
Ok(mut builder) => {
|
|
|
|
match builder.set_alpn_protocols(&[b"h2", b"http/1.1"]) {
|
|
|
|
Ok(_) => builder.build(),
|
|
|
|
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err)),
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
|
|
|
|
};
|
|
|
|
let workers = self.start_workers(&settings, &StreamHandlerType::Alpn(acceptor));
|
|
|
|
|
|
|
|
// start acceptors threads
|
|
|
|
for (addr, sock) in addrs {
|
|
|
|
info!("Starting tls http server on {}", addr);
|
2017-12-27 21:58:32 +01:00
|
|
|
self.accept.push(
|
|
|
|
start_accept_thread(sock, addr, workers.clone(), self.backlog));
|
2017-12-17 21:35:04 +01:00
|
|
|
}
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-17 21:35:04 +01:00
|
|
|
// start http server actor
|
|
|
|
Ok(HttpServer::create(|_| {self}))
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
2017-11-04 20:33:14 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-19 03:56:58 +01:00
|
|
|
impl<T, A, H, U, V> HttpServer<T, A, H, U>
|
|
|
|
where A: 'static,
|
|
|
|
T: AsyncRead + AsyncWrite + 'static,
|
|
|
|
H: HttpHandler,
|
|
|
|
U: IntoIterator<Item=V> + 'static,
|
|
|
|
V: IntoHttpHandler<Handler=H>,
|
|
|
|
{
|
|
|
|
/// Start listening for incomming connections from a stream.
|
|
|
|
///
|
|
|
|
/// This method uses only one thread for handling incoming connections.
|
2017-12-19 18:08:36 +01:00
|
|
|
pub fn start_incoming<S>(mut self, stream: S, secure: bool) -> SyncAddress<Self>
|
2017-12-19 03:56:58 +01:00
|
|
|
where S: Stream<Item=(T, A), Error=io::Error> + 'static
|
|
|
|
{
|
|
|
|
if !self.sockets.is_empty() {
|
2017-12-27 20:22:27 +01:00
|
|
|
let addrs: Vec<(net::SocketAddr, net::TcpListener)> =
|
|
|
|
self.sockets.drain().collect();
|
2017-12-26 23:36:03 +01:00
|
|
|
let settings = ServerSettings::new(Some(addrs[0].0), &self.host, false);
|
2017-12-19 03:56:58 +01:00
|
|
|
let workers = self.start_workers(&settings, &StreamHandlerType::Normal);
|
|
|
|
|
|
|
|
// start acceptors threads
|
|
|
|
for (addr, sock) in addrs {
|
|
|
|
info!("Starting http server on {}", addr);
|
2017-12-27 21:58:32 +01:00
|
|
|
self.accept.push(
|
|
|
|
start_accept_thread(sock, addr, self.backlog, workers.clone()));
|
2017-12-19 03:56:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// set server settings
|
|
|
|
let addr: net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
|
2017-12-26 23:36:03 +01:00
|
|
|
let settings = ServerSettings::new(Some(addr), &self.host, secure);
|
2017-12-19 03:56:58 +01:00
|
|
|
let mut apps: Vec<_> = (*self.factory)().into_iter().map(|h| h.into_handler()).collect();
|
|
|
|
for app in &mut apps {
|
|
|
|
app.server_settings(settings.clone());
|
|
|
|
}
|
|
|
|
self.h = Some(Rc::new(WorkerSettings::new(apps, self.keep_alive)));
|
|
|
|
|
|
|
|
// start server
|
2017-12-19 18:08:36 +01:00
|
|
|
HttpServer::create(move |ctx| {
|
2017-12-19 03:56:58 +01:00
|
|
|
ctx.add_stream(stream.map(
|
|
|
|
move |(t, _)| IoStream{io: t, peer: None, http2: false}));
|
|
|
|
self
|
2017-12-19 18:08:36 +01:00
|
|
|
})
|
2017-12-19 03:56:58 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-27 21:58:32 +01:00
|
|
|
#[derive(Message)]
|
2017-12-08 18:24:05 +01:00
|
|
|
struct IoStream<T> {
|
2017-12-08 06:52:46 +01:00
|
|
|
io: T,
|
2017-12-13 02:21:00 +01:00
|
|
|
peer: Option<net::SocketAddr>,
|
2017-12-08 06:52:46 +01:00
|
|
|
http2: bool,
|
|
|
|
}
|
2017-10-22 00:21:16 +02:00
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<T, A, H, U> StreamHandler<IoStream<T>, io::Error> for HttpServer<T, A, H, U>
|
2017-10-22 03:54:24 +02:00
|
|
|
where T: AsyncRead + AsyncWrite + 'static,
|
2017-11-10 22:08:15 +01:00
|
|
|
H: HttpHandler + 'static,
|
2017-12-13 02:21:00 +01:00
|
|
|
U: 'static,
|
2017-11-10 22:08:15 +01:00
|
|
|
A: 'static {}
|
2017-10-07 06:48:14 +02:00
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<T, A, H, U> Handler<IoStream<T>, io::Error> for HttpServer<T, A, H, U>
|
2017-10-16 22:13:32 +02:00
|
|
|
where T: AsyncRead + AsyncWrite + 'static,
|
2017-10-22 03:54:24 +02:00
|
|
|
H: HttpHandler + 'static,
|
2017-12-13 02:21:00 +01:00
|
|
|
U: 'static,
|
2017-11-10 22:08:15 +01:00
|
|
|
A: 'static,
|
2017-10-16 22:13:32 +02:00
|
|
|
{
|
2017-11-02 00:34:58 +01:00
|
|
|
fn error(&mut self, err: io::Error, _: &mut Context<Self>) {
|
2017-11-04 17:07:44 +01:00
|
|
|
debug!("Error handling request: {}", err)
|
2017-11-02 00:34:58 +01:00
|
|
|
}
|
|
|
|
|
2017-12-08 18:24:05 +01:00
|
|
|
fn handle(&mut self, msg: IoStream<T>, _: &mut Context<Self>)
|
|
|
|
-> Response<Self, IoStream<T>>
|
2017-10-07 06:48:14 +02:00
|
|
|
{
|
|
|
|
Arbiter::handle().spawn(
|
2017-12-14 07:36:28 +01:00
|
|
|
HttpChannel::new(Rc::clone(self.h.as_ref().unwrap()), msg.io, msg.peer, msg.http2));
|
2017-10-07 09:22:09 +02:00
|
|
|
Self::empty()
|
2017-10-07 06:48:14 +02:00
|
|
|
}
|
|
|
|
}
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-27 21:58:32 +01:00
|
|
|
/// Pause connection accepting process
|
|
|
|
#[derive(Message)]
|
|
|
|
pub struct PauseServer;
|
|
|
|
|
|
|
|
/// Resume connection accepting process
|
|
|
|
#[derive(Message)]
|
|
|
|
pub struct ResumeServer;
|
|
|
|
|
|
|
|
/// Stop connection processing and exit
|
|
|
|
#[derive(Message)]
|
|
|
|
pub struct StopServer;
|
|
|
|
|
|
|
|
impl<T, A, H, U> Handler<PauseServer> for HttpServer<T, A, H, U>
|
|
|
|
where T: AsyncRead + AsyncWrite + 'static,
|
|
|
|
H: HttpHandler + 'static,
|
|
|
|
U: 'static,
|
|
|
|
A: 'static,
|
|
|
|
{
|
|
|
|
fn handle(&mut self, _: PauseServer, _: &mut Context<Self>) -> Response<Self, PauseServer>
|
|
|
|
{
|
|
|
|
for item in &self.accept {
|
|
|
|
let _ = item.1.send(Command::Pause);
|
|
|
|
let _ = item.0.set_readiness(mio::Ready::readable());
|
|
|
|
}
|
|
|
|
Self::empty()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T, A, H, U> Handler<ResumeServer> for HttpServer<T, A, H, U>
|
|
|
|
where T: AsyncRead + AsyncWrite + 'static,
|
|
|
|
H: HttpHandler + 'static,
|
|
|
|
U: 'static,
|
|
|
|
A: 'static,
|
|
|
|
{
|
|
|
|
fn handle(&mut self, _: ResumeServer, _: &mut Context<Self>) -> Response<Self, ResumeServer>
|
|
|
|
{
|
|
|
|
for item in &self.accept {
|
|
|
|
let _ = item.1.send(Command::Resume);
|
|
|
|
let _ = item.0.set_readiness(mio::Ready::readable());
|
|
|
|
}
|
|
|
|
Self::empty()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<T, A, H, U> Handler<StopServer> for HttpServer<T, A, H, U>
|
|
|
|
where T: AsyncRead + AsyncWrite + 'static,
|
|
|
|
H: HttpHandler + 'static,
|
|
|
|
U: 'static,
|
|
|
|
A: 'static,
|
|
|
|
{
|
|
|
|
fn handle(&mut self, _: StopServer, ctx: &mut Context<Self>) -> Response<Self, StopServer>
|
|
|
|
{
|
|
|
|
for item in &self.accept {
|
|
|
|
let _ = item.1.send(Command::Stop);
|
|
|
|
let _ = item.0.set_readiness(mio::Ready::readable());
|
|
|
|
}
|
|
|
|
ctx.stop();
|
|
|
|
Self::empty()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 08:35:21 +01:00
|
|
|
/// Http worker
|
2017-12-13 02:21:00 +01:00
|
|
|
///
|
|
|
|
/// Worker accepts Socket objects via unbounded channel and start requests processing.
|
|
|
|
struct Worker<H> {
|
2017-12-14 06:38:47 +01:00
|
|
|
h: Rc<WorkerSettings<H>>,
|
2017-12-27 20:22:27 +01:00
|
|
|
hnd: Handle,
|
2017-12-13 21:47:07 +01:00
|
|
|
handler: StreamHandlerType,
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
|
|
|
|
2017-12-14 06:38:47 +01:00
|
|
|
pub(crate) struct WorkerSettings<H> {
|
2017-12-26 18:00:45 +01:00
|
|
|
h: RefCell<Vec<H>>,
|
2017-12-14 20:20:45 +01:00
|
|
|
enabled: bool,
|
|
|
|
keep_alive: u64,
|
2017-12-15 04:34:31 +01:00
|
|
|
bytes: Rc<helpers::SharedBytesPool>,
|
|
|
|
messages: Rc<helpers::SharedMessagePool>,
|
2017-12-14 06:38:47 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<H> WorkerSettings<H> {
|
2017-12-15 05:29:49 +01:00
|
|
|
pub(crate) fn new(h: Vec<H>, keep_alive: Option<u64>) -> WorkerSettings<H> {
|
2017-12-14 20:20:45 +01:00
|
|
|
WorkerSettings {
|
2017-12-26 18:00:45 +01:00
|
|
|
h: RefCell::new(h),
|
2017-12-14 20:20:45 +01:00
|
|
|
enabled: if let Some(ka) = keep_alive { ka > 0 } else { false },
|
|
|
|
keep_alive: keep_alive.unwrap_or(0),
|
2017-12-15 04:34:31 +01:00
|
|
|
bytes: Rc::new(helpers::SharedBytesPool::new()),
|
|
|
|
messages: Rc::new(helpers::SharedMessagePool::new()),
|
2017-12-14 20:20:45 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-26 18:00:45 +01:00
|
|
|
pub fn handlers(&self) -> RefMut<Vec<H>> {
|
|
|
|
self.h.borrow_mut()
|
2017-12-14 06:38:47 +01:00
|
|
|
}
|
2017-12-14 20:20:45 +01:00
|
|
|
pub fn keep_alive(&self) -> u64 {
|
2017-12-14 06:38:47 +01:00
|
|
|
self.keep_alive
|
|
|
|
}
|
2017-12-14 20:20:45 +01:00
|
|
|
pub fn keep_alive_enabled(&self) -> bool {
|
|
|
|
self.enabled
|
|
|
|
}
|
2017-12-15 04:34:31 +01:00
|
|
|
pub fn get_shared_bytes(&self) -> helpers::SharedBytes {
|
|
|
|
helpers::SharedBytes::new(self.bytes.get_bytes(), Rc::clone(&self.bytes))
|
|
|
|
}
|
|
|
|
pub fn get_http_message(&self) -> helpers::SharedHttpMessage {
|
|
|
|
helpers::SharedHttpMessage::new(self.messages.get(), Rc::clone(&self.messages))
|
|
|
|
}
|
2017-12-14 06:38:47 +01:00
|
|
|
}
|
|
|
|
|
2017-12-14 01:44:35 +01:00
|
|
|
impl<H: 'static> Worker<H> {
|
2017-12-14 06:38:47 +01:00
|
|
|
|
2017-12-14 07:36:28 +01:00
|
|
|
fn new(h: Vec<H>, handler: StreamHandlerType, keep_alive: Option<u64>) -> Worker<H> {
|
2017-12-14 06:38:47 +01:00
|
|
|
Worker {
|
2017-12-14 20:20:45 +01:00
|
|
|
h: Rc::new(WorkerSettings::new(h, keep_alive)),
|
2017-12-27 20:22:27 +01:00
|
|
|
hnd: Arbiter::handle().clone(),
|
2017-12-14 06:38:47 +01:00
|
|
|
handler: handler,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 01:44:35 +01:00
|
|
|
fn update_time(&self, ctx: &mut Context<Self>) {
|
2017-12-14 07:54:52 +01:00
|
|
|
helpers::update_date();
|
2017-12-14 01:44:35 +01:00
|
|
|
ctx.run_later(Duration::new(1, 0), |slf, ctx| slf.update_time(ctx));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
impl<H: 'static> Actor for Worker<H> {
|
|
|
|
type Context = Context<Self>;
|
|
|
|
|
2017-12-13 21:47:07 +01:00
|
|
|
fn started(&mut self, ctx: &mut Self::Context) {
|
2017-12-14 01:44:35 +01:00
|
|
|
self.update_time(ctx);
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-27 20:22:27 +01:00
|
|
|
impl<H> StreamHandler<IoStream<net::TcpStream>> for Worker<H>
|
2017-12-13 02:21:00 +01:00
|
|
|
where H: HttpHandler + 'static {}
|
|
|
|
|
2017-12-27 20:22:27 +01:00
|
|
|
impl<H> Handler<IoStream<net::TcpStream>> for Worker<H>
|
2017-12-13 02:21:00 +01:00
|
|
|
where H: HttpHandler + 'static,
|
|
|
|
{
|
2017-12-27 20:22:27 +01:00
|
|
|
fn handle(&mut self, msg: IoStream<net::TcpStream>, _: &mut Context<Self>)
|
|
|
|
-> Response<Self, IoStream<net::TcpStream>>
|
2017-12-13 02:21:00 +01:00
|
|
|
{
|
2017-12-14 20:20:45 +01:00
|
|
|
if !self.h.keep_alive_enabled() &&
|
2017-12-14 07:36:28 +01:00
|
|
|
msg.io.set_keepalive(Some(Duration::new(75, 0))).is_err()
|
|
|
|
{
|
|
|
|
error!("Can not set socket keep-alive option");
|
2017-12-14 06:38:47 +01:00
|
|
|
}
|
2017-12-27 20:22:27 +01:00
|
|
|
self.handler.handle(Rc::clone(&self.h), &self.hnd, msg);
|
2017-12-13 02:21:00 +01:00
|
|
|
Self::empty()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-13 21:47:07 +01:00
|
|
|
#[derive(Clone)]
|
|
|
|
enum StreamHandlerType {
|
|
|
|
Normal,
|
|
|
|
#[cfg(feature="tls")]
|
|
|
|
Tls(TlsAcceptor),
|
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
Alpn(SslAcceptor),
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
|
|
|
|
2017-12-13 21:47:07 +01:00
|
|
|
impl StreamHandlerType {
|
2017-12-14 06:38:47 +01:00
|
|
|
|
2017-12-27 20:22:27 +01:00
|
|
|
fn handle<H: HttpHandler>(&mut self,
|
|
|
|
h: Rc<WorkerSettings<H>>,
|
|
|
|
hnd: &Handle,
|
|
|
|
msg: IoStream<net::TcpStream>) {
|
2017-12-13 21:47:07 +01:00
|
|
|
match *self {
|
|
|
|
StreamHandlerType::Normal => {
|
2017-12-27 20:22:27 +01:00
|
|
|
let io = TcpStream::from_stream(msg.io, hnd)
|
2017-12-13 21:47:07 +01:00
|
|
|
.expect("failed to associate TCP stream");
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-27 20:22:27 +01:00
|
|
|
hnd.spawn(HttpChannel::new(h, io, msg.peer, msg.http2));
|
2017-12-13 21:47:07 +01:00
|
|
|
}
|
|
|
|
#[cfg(feature="tls")]
|
|
|
|
StreamHandlerType::Tls(ref acceptor) => {
|
|
|
|
let IoStream { io, peer, http2 } = msg;
|
2017-12-27 20:22:27 +01:00
|
|
|
let io = TcpStream::from_stream(io, hnd)
|
2017-12-13 21:47:07 +01:00
|
|
|
.expect("failed to associate TCP stream");
|
|
|
|
|
2017-12-27 21:58:32 +01:00
|
|
|
hnd.spawn(
|
2017-12-13 21:47:07 +01:00
|
|
|
TlsAcceptorExt::accept_async(acceptor, io).then(move |res| {
|
|
|
|
match res {
|
2017-12-27 21:58:32 +01:00
|
|
|
Ok(io) => Arbiter::handle().spawn(
|
|
|
|
HttpChannel::new(h, io, peer, http2)),
|
2017-12-13 21:47:07 +01:00
|
|
|
Err(err) =>
|
|
|
|
trace!("Error during handling tls connection: {}", err),
|
2017-12-13 02:21:00 +01:00
|
|
|
};
|
2017-12-13 21:47:07 +01:00
|
|
|
future::result(Ok(()))
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
#[cfg(feature="alpn")]
|
|
|
|
StreamHandlerType::Alpn(ref acceptor) => {
|
|
|
|
let IoStream { io, peer, .. } = msg;
|
2017-12-27 20:22:27 +01:00
|
|
|
let io = TcpStream::from_stream(io, hnd)
|
2017-12-13 21:47:07 +01:00
|
|
|
.expect("failed to associate TCP stream");
|
|
|
|
|
2017-12-27 20:22:27 +01:00
|
|
|
hnd.spawn(
|
2017-12-13 21:47:07 +01:00
|
|
|
SslAcceptorExt::accept_async(acceptor, io).then(move |res| {
|
|
|
|
match res {
|
|
|
|
Ok(io) => {
|
|
|
|
let http2 = if let Some(p) = io.get_ref().ssl().selected_alpn_protocol()
|
|
|
|
{
|
|
|
|
p.len() == 2 && &p == b"h2"
|
|
|
|
} else {
|
|
|
|
false
|
|
|
|
};
|
|
|
|
Arbiter::handle().spawn(HttpChannel::new(h, io, peer, http2));
|
|
|
|
},
|
|
|
|
Err(err) =>
|
|
|
|
trace!("Error during handling tls connection: {}", err),
|
|
|
|
};
|
|
|
|
future::result(Ok(()))
|
|
|
|
})
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
|
|
|
}
|
2017-12-13 21:47:07 +01:00
|
|
|
|
2017-12-27 21:58:32 +01:00
|
|
|
enum Command {
|
|
|
|
Pause,
|
|
|
|
Resume,
|
|
|
|
Stop,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn start_accept_thread(sock: net::TcpListener, addr: net::SocketAddr, backlog: i32,
|
|
|
|
workers: Vec<mpsc::UnboundedSender<IoStream<net::TcpStream>>>)
|
|
|
|
-> (mio::SetReadiness, sync_mpsc::Sender<Command>)
|
|
|
|
{
|
|
|
|
let (tx, rx) = sync_mpsc::channel();
|
|
|
|
let (reg, readiness) = mio::Registration::new2();
|
|
|
|
|
2017-12-27 20:22:27 +01:00
|
|
|
// start accept thread
|
2017-12-13 21:47:07 +01:00
|
|
|
let _ = thread::Builder::new().name(format!("Accept on {}", addr)).spawn(move || {
|
2017-12-27 21:58:32 +01:00
|
|
|
const SRV: mio::Token = mio::Token(0);
|
|
|
|
const CMD: mio::Token = mio::Token(1);
|
|
|
|
|
|
|
|
let mut server = Some(
|
|
|
|
mio::net::TcpListener::from_listener(sock, &addr)
|
|
|
|
.expect("Can not create mio::net::TcpListener"));
|
2017-12-27 20:22:27 +01:00
|
|
|
|
|
|
|
// Create a poll instance
|
|
|
|
let poll = match mio::Poll::new() {
|
|
|
|
Ok(poll) => poll,
|
|
|
|
Err(err) => panic!("Can not create mio::Poll: {}", err),
|
|
|
|
};
|
|
|
|
|
|
|
|
// Start listening for incoming connections
|
2017-12-27 21:58:32 +01:00
|
|
|
if let Some(ref srv) = server {
|
|
|
|
if let Err(err) = poll.register(
|
|
|
|
srv, SRV, mio::Ready::readable(), mio::PollOpt::edge()) {
|
|
|
|
panic!("Can not register io: {}", err);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Start listening for incommin commands
|
|
|
|
if let Err(err) = poll.register(®, CMD,
|
2017-12-27 20:22:27 +01:00
|
|
|
mio::Ready::readable(), mio::PollOpt::edge()) {
|
2017-12-27 21:58:32 +01:00
|
|
|
panic!("Can not register Registration: {}", err);
|
2017-12-27 20:22:27 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Create storage for events
|
|
|
|
let mut events = mio::Events::with_capacity(128);
|
|
|
|
|
2017-12-27 21:58:32 +01:00
|
|
|
let mut next = 0;
|
2017-12-13 21:47:07 +01:00
|
|
|
loop {
|
2017-12-27 20:22:27 +01:00
|
|
|
if let Err(err) = poll.poll(&mut events, None) {
|
|
|
|
panic!("Poll error: {}", err);
|
|
|
|
}
|
|
|
|
|
|
|
|
for event in events.iter() {
|
|
|
|
match event.token() {
|
2017-12-27 21:58:32 +01:00
|
|
|
SRV => {
|
|
|
|
if let Some(ref server) = server {
|
|
|
|
loop {
|
|
|
|
match server.accept_std() {
|
|
|
|
Ok((sock, addr)) => {
|
|
|
|
let msg = IoStream{
|
|
|
|
io: sock, peer: Some(addr), http2: false};
|
|
|
|
workers[next].unbounded_send(msg)
|
|
|
|
.expect("worker thread died");
|
|
|
|
next = (next + 1) % workers.len();
|
|
|
|
},
|
|
|
|
Err(err) => if err.kind() == io::ErrorKind::WouldBlock {
|
|
|
|
break
|
|
|
|
} else {
|
|
|
|
error!("Error accepting connection: {:?}", err);
|
|
|
|
return
|
|
|
|
}
|
2017-12-27 20:22:27 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-12-27 21:58:32 +01:00
|
|
|
},
|
|
|
|
CMD => match rx.try_recv() {
|
|
|
|
Ok(cmd) => match cmd {
|
|
|
|
Command::Pause => if let Some(server) = server.take() {
|
|
|
|
if let Err(err) = poll.deregister(&server) {
|
|
|
|
error!("Can not deregister server socket {}", err);
|
|
|
|
} else {
|
|
|
|
info!("Paused accepting connections on {}", addr);
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Command::Resume => {
|
|
|
|
let lst = create_tcp_listener(addr, backlog)
|
|
|
|
.expect("Can not create net::TcpListener");
|
|
|
|
|
|
|
|
server = Some(
|
|
|
|
mio::net::TcpListener::from_listener(lst, &addr)
|
|
|
|
.expect("Can not create mio::net::TcpListener"));
|
|
|
|
|
|
|
|
if let Some(ref server) = server {
|
|
|
|
if let Err(err) = poll.register(
|
|
|
|
server, SRV, mio::Ready::readable(), mio::PollOpt::edge())
|
|
|
|
{
|
|
|
|
error!("Can not resume socket accept process: {}", err);
|
|
|
|
} else {
|
|
|
|
info!("Accepting connections on {} has been resumed",
|
|
|
|
addr);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Command::Stop => return,
|
|
|
|
},
|
|
|
|
Err(err) => match err {
|
|
|
|
sync_mpsc::TryRecvError::Empty => (),
|
|
|
|
sync_mpsc::TryRecvError::Disconnected => return,
|
|
|
|
}
|
2017-12-27 20:22:27 +01:00
|
|
|
}
|
|
|
|
_ => unreachable!(),
|
2017-12-13 21:47:07 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
2017-12-27 21:58:32 +01:00
|
|
|
|
|
|
|
(readiness, tx)
|
|
|
|
}
|
|
|
|
|
|
|
|
fn create_tcp_listener(addr: net::SocketAddr, backlog: i32) -> io::Result<net::TcpListener> {
|
|
|
|
let builder = match addr {
|
|
|
|
net::SocketAddr::V4(_) => TcpBuilder::new_v4()?,
|
|
|
|
net::SocketAddr::V6(_) => TcpBuilder::new_v6()?,
|
|
|
|
};
|
|
|
|
builder.bind(addr)?;
|
|
|
|
builder.reuse_address(true)?;
|
|
|
|
Ok(builder.listen(backlog)?)
|
2017-12-13 21:47:07 +01:00
|
|
|
}
|