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-13 02:21:00 +01:00
|
|
|
use std::sync::Arc;
|
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-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-13 02:21:00 +01:00
|
|
|
use tokio_core::net::TcpStream;
|
|
|
|
use num_cpus;
|
|
|
|
use socket2::{Socket, Domain, Type};
|
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 01:44:35 +01:00
|
|
|
use utils;
|
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-13 02:21:00 +01:00
|
|
|
fn new(addr: Option<net::SocketAddr>, secure: bool) -> Self {
|
2017-12-08 18:24:05 +01:00
|
|
|
let host = 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-08 18:48:53 +01:00
|
|
|
"unknown".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
|
|
|
///
|
|
|
|
/// `T` - async stream, anything that implements `AsyncRead` + `AsyncWrite`.
|
|
|
|
///
|
|
|
|
/// `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-14 06:38:47 +01:00
|
|
|
keep_alive: Option<u16>,
|
2017-12-13 02:21:00 +01:00
|
|
|
factory: Arc<Fn() -> U + Send + Sync>,
|
|
|
|
workers: Vec<SyncAddress<Worker<H>>>,
|
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>) {
|
|
|
|
utils::update_date();
|
|
|
|
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
|
|
|
{
|
|
|
|
/// Create new http server with vec of http handlers
|
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-14 06:38:47 +01:00
|
|
|
keep_alive: None,
|
2017-12-13 02:21:00 +01:00
|
|
|
factory: Arc::new(factory),
|
|
|
|
workers: Vec::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// 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-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
|
|
|
|
pub fn keep_alive(mut self, val: Option<u16>) -> Self {
|
|
|
|
self.keep_alive = val;
|
|
|
|
self
|
|
|
|
}
|
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
/// Start listening for incomming connections from a stream.
|
|
|
|
///
|
|
|
|
/// This method uses only one thread for handling incoming connections.
|
2017-12-08 07:54:44 +01:00
|
|
|
pub fn serve_incoming<S, Addr>(mut self, stream: S, secure: bool) -> io::Result<Addr>
|
2017-10-16 22:13:32 +02:00
|
|
|
where Self: ActorAddress<Self, Addr>,
|
|
|
|
S: Stream<Item=(T, A), Error=io::Error> + 'static
|
|
|
|
{
|
2017-12-08 18:24:05 +01:00
|
|
|
// set server settings
|
2017-12-13 02:21:00 +01:00
|
|
|
let addr: net::SocketAddr = "127.0.0.1:8080".parse().unwrap();
|
2017-12-08 18:24:05 +01:00
|
|
|
let settings = ServerSettings::new(Some(addr), secure);
|
2017-12-13 02:21:00 +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());
|
2017-12-08 18:24:05 +01:00
|
|
|
}
|
2017-12-14 06:38:47 +01:00
|
|
|
self.h = Some(Rc::new(WorkerSettings{h: apps, keep_alive: self.keep_alive}));
|
2017-12-08 07:54:44 +01:00
|
|
|
|
2017-12-08 18:24:05 +01:00
|
|
|
// start server
|
2017-10-16 22:13:32 +02:00
|
|
|
Ok(HttpServer::create(move |ctx| {
|
2017-12-08 06:52:46 +01:00
|
|
|
ctx.add_stream(stream.map(
|
2017-12-08 18:24:05 +01:00
|
|
|
move |(t, _)| IoStream{io: t, peer: None, http2: false}));
|
2017-10-16 22:13:32 +02:00
|
|
|
self
|
|
|
|
}))
|
|
|
|
}
|
2017-10-07 06:48:14 +02:00
|
|
|
|
2017-11-02 00:34:58 +01:00
|
|
|
fn bind<S: net::ToSocketAddrs>(&self, addr: S)
|
2017-12-13 02:21:00 +01:00
|
|
|
-> io::Result<Vec<(net::SocketAddr, Socket)>>
|
2017-10-07 06:48:14 +02:00
|
|
|
{
|
2017-10-15 23:53:03 +02:00
|
|
|
let mut err = None;
|
2017-12-13 02:21:00 +01:00
|
|
|
let mut sockets = Vec::new();
|
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-13 02:21:00 +01:00
|
|
|
match addr {
|
|
|
|
net::SocketAddr::V4(a) => {
|
|
|
|
let socket = Socket::new(Domain::ipv4(), Type::stream(), None)?;
|
|
|
|
match socket.bind(&a.into()) {
|
|
|
|
Ok(_) => {
|
|
|
|
socket.listen(1024)
|
|
|
|
.expect("failed to set socket backlog");
|
|
|
|
socket.set_reuse_address(true)
|
|
|
|
.expect("failed to set socket reuse address");
|
|
|
|
sockets.push((addr, socket));
|
|
|
|
},
|
|
|
|
Err(e) => err = Some(e),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
net::SocketAddr::V6(a) => {
|
|
|
|
let socket = Socket::new(Domain::ipv6(), Type::stream(), None)?;
|
|
|
|
match socket.bind(&a.into()) {
|
|
|
|
Ok(_) => {
|
|
|
|
socket.listen(1024)
|
|
|
|
.expect("failed to set socket backlog");
|
|
|
|
socket.set_reuse_address(true)
|
|
|
|
.expect("failed to set socket reuse address");
|
|
|
|
sockets.push((addr, socket))
|
|
|
|
}
|
|
|
|
Err(e) => err = Some(e),
|
|
|
|
}
|
|
|
|
}
|
2017-10-15 23:53:03 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-12-13 02:21:00 +01:00
|
|
|
|
|
|
|
if sockets.is_empty() {
|
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-13 02:21:00 +01:00
|
|
|
Ok(sockets)
|
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-14 06:38:47 +01:00
|
|
|
-> Vec<mpsc::UnboundedSender<IoStream<Socket>>>
|
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-14 06:38:47 +01:00
|
|
|
let (tx, rx) = mpsc::unbounded::<IoStream<Socket>>();
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-13 21:47:07 +01:00
|
|
|
let h = handler.clone();
|
2017-12-14 06:38:47 +01:00
|
|
|
let ka = self.keep_alive.clone();
|
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.
|
|
|
|
///
|
|
|
|
/// This methods converts address to list of `SocketAddr`
|
|
|
|
/// then binds to all available addresses.
|
2017-12-13 02:21:00 +01:00
|
|
|
/// It also starts number of http handler workers in seperate threads.
|
|
|
|
/// For each address this method starts separate thread which does `accept()` in a loop.
|
2017-12-08 07:54:44 +01:00
|
|
|
pub fn serve<S, Addr>(mut self, addr: S) -> io::Result<Addr>
|
2017-11-02 00:34:58 +01:00
|
|
|
where Self: ActorAddress<Self, Addr>,
|
|
|
|
S: net::ToSocketAddrs,
|
|
|
|
{
|
|
|
|
let addrs = self.bind(addr)?;
|
2017-12-08 18:24:05 +01:00
|
|
|
let settings = ServerSettings::new(Some(addrs[0].0), false);
|
2017-12-13 21:47:07 +01:00
|
|
|
let workers = self.start_workers(&settings, &StreamHandlerType::Normal);
|
2017-12-13 02:21:00 +01:00
|
|
|
|
|
|
|
// start acceptors threads
|
|
|
|
for (addr, sock) in addrs {
|
|
|
|
info!("Starting http server on {}", addr);
|
2017-12-13 21:47:07 +01:00
|
|
|
start_accept_thread(sock, addr, workers.clone());
|
2017-12-08 18:24:05 +01:00
|
|
|
}
|
|
|
|
|
2017-12-13 02:21:00 +01:00
|
|
|
// start http server actor
|
|
|
|
Ok(HttpServer::create(|_| {self}))
|
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.
|
|
|
|
///
|
|
|
|
/// This methods converts address to list of `SocketAddr`
|
|
|
|
/// then binds to all available addresses.
|
2017-12-13 21:47:07 +01:00
|
|
|
pub fn serve_tls<S, Addr>(mut self, addr: S, pkcs12: ::Pkcs12) -> io::Result<Addr>
|
2017-11-02 00:34:58 +01:00
|
|
|
where Self: ActorAddress<Self, Addr>,
|
|
|
|
S: net::ToSocketAddrs,
|
|
|
|
{
|
|
|
|
let addrs = self.bind(addr)?;
|
2017-12-13 02:21:00 +01:00
|
|
|
let settings = ServerSettings::new(Some(addrs[0].0), false);
|
2017-11-02 00:34:58 +01:00
|
|
|
let acceptor = match TlsAcceptor::builder(pkcs12) {
|
|
|
|
Ok(builder) => {
|
|
|
|
match builder.build() {
|
2017-12-13 02:21:00 +01:00
|
|
|
Ok(acceptor) => acceptor,
|
2017-11-02 00:34:58 +01:00
|
|
|
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
|
|
|
|
};
|
2017-12-13 21:47:07 +01:00
|
|
|
let workers = self.start_workers(&settings, &StreamHandlerType::Tls(acceptor));
|
2017-12-13 02:21:00 +01:00
|
|
|
|
|
|
|
// start acceptors threads
|
|
|
|
for (addr, sock) in addrs {
|
|
|
|
info!("Starting tls http server on {}", addr);
|
2017-12-13 21:47:07 +01:00
|
|
|
start_accept_thread(sock, addr, workers.clone());
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// start http server actor
|
|
|
|
Ok(HttpServer::create(|_| {self}))
|
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.
|
|
|
|
///
|
|
|
|
/// This methods converts address to list of `SocketAddr`
|
|
|
|
/// then binds to all available addresses.
|
2017-12-13 21:47:07 +01:00
|
|
|
pub fn serve_tls<S, Addr>(mut self, addr: S, identity: &ParsedPkcs12) -> io::Result<Addr>
|
2017-11-04 20:33:14 +01:00
|
|
|
where Self: ActorAddress<Self, Addr>,
|
|
|
|
S: net::ToSocketAddrs,
|
|
|
|
{
|
|
|
|
let addrs = self.bind(addr)?;
|
2017-12-13 02:21:00 +01:00
|
|
|
let settings = ServerSettings::new(Some(addrs[0].0), false);
|
2017-12-08 07:54:44 +01:00
|
|
|
let acceptor = match SslAcceptorBuilder::mozilla_intermediate(
|
|
|
|
SslMethod::tls(), &identity.pkey, &identity.cert, &identity.chain)
|
2017-11-04 20:33:14 +01:00
|
|
|
{
|
|
|
|
Ok(mut builder) => {
|
2017-12-13 02:21:00 +01:00
|
|
|
match builder.set_alpn_protocols(&[b"h2", b"http/1.1"]) {
|
2017-11-04 20:33:14 +01:00
|
|
|
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))
|
|
|
|
};
|
2017-12-13 21:47:07 +01:00
|
|
|
let workers = self.start_workers(&settings, &StreamHandlerType::Alpn(acceptor));
|
2017-12-13 02:21:00 +01:00
|
|
|
|
|
|
|
// start acceptors threads
|
|
|
|
for (addr, sock) in addrs {
|
|
|
|
info!("Starting tls http server on {}", addr);
|
2017-12-13 21:47:07 +01:00
|
|
|
start_accept_thread(sock, addr, workers.clone());
|
2017-12-13 02:21:00 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// start http server actor
|
|
|
|
Ok(HttpServer::create(|_| {self}))
|
2017-11-04 20:33:14 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
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-08 18:24:05 +01:00
|
|
|
impl<T> ResponseType for IoStream<T>
|
2017-10-16 22:13:32 +02:00
|
|
|
{
|
2017-10-07 06:48:14 +02:00
|
|
|
type Item = ();
|
|
|
|
type Error = ();
|
|
|
|
}
|
|
|
|
|
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 06:38:47 +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
|
|
|
|
|
|
|
|
|
|
|
/// Http workers
|
|
|
|
///
|
|
|
|
/// 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-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> {
|
|
|
|
h: Vec<H>,
|
|
|
|
keep_alive: Option<u16>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl<H> WorkerSettings<H> {
|
|
|
|
pub fn handlers(&self) -> &Vec<H> {
|
|
|
|
&self.h
|
|
|
|
}
|
|
|
|
pub fn keep_alive(&self) -> Option<u16> {
|
|
|
|
self.keep_alive
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 01:44:35 +01:00
|
|
|
impl<H: 'static> Worker<H> {
|
2017-12-14 06:38:47 +01:00
|
|
|
|
|
|
|
fn new(h: Vec<H>, handler: StreamHandlerType, keep_alive: Option<u16>) -> Worker<H> {
|
|
|
|
Worker {
|
|
|
|
h: Rc::new(WorkerSettings{h: h, keep_alive: keep_alive}),
|
|
|
|
handler: handler,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 01:44:35 +01:00
|
|
|
fn update_time(&self, ctx: &mut Context<Self>) {
|
|
|
|
utils::update_date();
|
|
|
|
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-14 06:38:47 +01:00
|
|
|
impl<H> StreamHandler<IoStream<Socket>> for Worker<H>
|
2017-12-13 02:21:00 +01:00
|
|
|
where H: HttpHandler + 'static {}
|
|
|
|
|
2017-12-14 06:38:47 +01:00
|
|
|
impl<H> Handler<IoStream<Socket>> for Worker<H>
|
2017-12-13 02:21:00 +01:00
|
|
|
where H: HttpHandler + 'static,
|
|
|
|
{
|
2017-12-14 06:38:47 +01:00
|
|
|
fn handle(&mut self, msg: IoStream<Socket>, _: &mut Context<Self>)
|
|
|
|
-> Response<Self, IoStream<Socket>>
|
2017-12-13 02:21:00 +01:00
|
|
|
{
|
2017-12-14 06:38:47 +01:00
|
|
|
if let None = self.h.keep_alive {
|
|
|
|
if msg.io.set_keepalive(Some(Duration::new(75, 0))).is_err() {
|
|
|
|
error!("Can not set socket keep-alive option");
|
|
|
|
}
|
|
|
|
}
|
2017-12-13 21:47:07 +01:00
|
|
|
self.handler.handle(Rc::clone(&self.h), 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
|
|
|
|
|
|
|
fn handle<H: HttpHandler>(&mut self, h: Rc<WorkerSettings<H>>, msg: IoStream<Socket>) {
|
2017-12-13 21:47:07 +01:00
|
|
|
match *self {
|
|
|
|
StreamHandlerType::Normal => {
|
2017-12-14 06:38:47 +01:00
|
|
|
let io = TcpStream::from_stream(msg.io.into_tcp_stream(), Arbiter::handle())
|
2017-12-13 21:47:07 +01:00
|
|
|
.expect("failed to associate TCP stream");
|
2017-12-13 02:21:00 +01:00
|
|
|
|
2017-12-13 21:47:07 +01:00
|
|
|
Arbiter::handle().spawn(HttpChannel::new(h, io, msg.peer, msg.http2));
|
|
|
|
}
|
|
|
|
#[cfg(feature="tls")]
|
|
|
|
StreamHandlerType::Tls(ref acceptor) => {
|
|
|
|
let IoStream { io, peer, http2 } = msg;
|
2017-12-14 06:38:47 +01:00
|
|
|
let io = TcpStream::from_stream(io.into_tcp_stream(), Arbiter::handle())
|
2017-12-13 21:47:07 +01:00
|
|
|
.expect("failed to associate TCP stream");
|
|
|
|
|
|
|
|
Arbiter::handle().spawn(
|
|
|
|
TlsAcceptorExt::accept_async(acceptor, io).then(move |res| {
|
|
|
|
match res {
|
|
|
|
Ok(io) => Arbiter::handle().spawn(
|
|
|
|
HttpChannel::new(h, io, peer, http2)),
|
|
|
|
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-14 06:38:47 +01:00
|
|
|
let io = TcpStream::from_stream(io.into_tcp_stream(), Arbiter::handle())
|
2017-12-13 21:47:07 +01:00
|
|
|
.expect("failed to associate TCP stream");
|
|
|
|
|
|
|
|
Arbiter::handle().spawn(
|
|
|
|
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
|
|
|
|
|
|
|
fn start_accept_thread(sock: Socket, addr: net::SocketAddr,
|
2017-12-14 06:38:47 +01:00
|
|
|
workers: Vec<mpsc::UnboundedSender<IoStream<Socket>>>) {
|
2017-12-13 21:47:07 +01:00
|
|
|
// start acceptors thread
|
|
|
|
let _ = thread::Builder::new().name(format!("Accept on {}", addr)).spawn(move || {
|
|
|
|
let mut next = 0;
|
|
|
|
loop {
|
|
|
|
match sock.accept() {
|
|
|
|
Ok((socket, addr)) => {
|
|
|
|
let addr = if let Some(addr) = addr.as_inet() {
|
|
|
|
net::SocketAddr::V4(addr)
|
|
|
|
} else {
|
|
|
|
net::SocketAddr::V6(addr.as_inet6().unwrap())
|
|
|
|
};
|
2017-12-14 06:38:47 +01:00
|
|
|
let msg = IoStream{io: socket, peer: Some(addr), http2: false};
|
2017-12-13 21:47:07 +01:00
|
|
|
workers[next].unbounded_send(msg).expect("worker thread died");
|
|
|
|
next = (next + 1) % workers.len();
|
|
|
|
}
|
|
|
|
Err(err) => error!("Error accepting connection: {:?}", err),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|