1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-25 19:11:10 +00:00

Allow to start tls server with HttpServer::serve_tls

This commit is contained in:
Nikolay Kim 2017-11-01 16:34:58 -07:00
parent a12e5e9cf5
commit ec3b139273
8 changed files with 152 additions and 19 deletions

View file

@ -33,7 +33,7 @@ before_script:
- export PATH=$PATH:~/.cargo/bin - export PATH=$PATH:~/.cargo/bin
script: script:
- cargo test --no-default-features - USE_SKEPTIC=1 cargo test --no-default-features
- | - |
if [[ "$TRAVIS_RUST_VERSION" == "nightly" && $CLIPPY ]]; then if [[ "$TRAVIS_RUST_VERSION" == "nightly" && $CLIPPY ]]; then
cargo clippy cargo clippy

View file

@ -1,6 +1,10 @@
# Changes # Changes
## 0.2.1 (2017-11-xx)
* Allow to start tls server with `HttpServer::serve_tls`
## 0.2.0 (2017-10-30) ## 0.2.0 (2017-10-30)
* Do not use `http::Uri` as it can not parse some valid paths * Do not use `http::Uri` as it can not parse some valid paths

View file

@ -25,7 +25,9 @@ path = "src/lib.rs"
[features] [features]
default = [] default = []
# http/2 # tls
tls = ["native-tls", "tokio-tls"]
# http2 = ["h2"] # http2 = ["h2"]
[dependencies] [dependencies]
@ -49,6 +51,10 @@ tokio-io = "0.1"
tokio-core = "0.1" tokio-core = "0.1"
# h2 = { git = 'https://github.com/carllerche/h2', optional = true } # h2 = { git = 'https://github.com/carllerche/h2', optional = true }
# tls
native-tls = { version="0.1", optional = true }
tokio-tls = { version="0.1", optional = true }
[dependencies.actix] [dependencies.actix]
version = ">=0.3.1" version = ">=0.3.1"
#path = "../actix" #path = "../actix"

14
examples/tls/Cargo.toml Normal file
View file

@ -0,0 +1,14 @@
[package]
name = "ssl-example"
version = "0.1.0"
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
[[bin]]
name = "server"
path = "src/main.rs"
[dependencies]
env_logger = "0.4"
actix = "0.3.1"
actix-web = { path = "../../", features=["tls"] }

BIN
examples/tls/identity.pfx Normal file

Binary file not shown.

46
examples/tls/src/main.rs Normal file
View file

@ -0,0 +1,46 @@
#![allow(unused_variables)]
extern crate actix;
extern crate actix_web;
extern crate env_logger;
//use tokio_tls;
use std::fs::File;
use std::io::Read;
// use native_tls::{TlsAcceptor, TlsStream};
use actix_web::*;
/// somple handle
fn index(req: &mut HttpRequest, _payload: Payload, state: &()) -> HttpResponse {
println!("{:?}", req);
httpcodes::HTTPOk.with_body("Welcome!")
}
fn main() {
::std::env::set_var("RUST_LOG", "actix_web=info");
let _ = env_logger::init();
let sys = actix::System::new("ws-example");
let mut file = File::open("identity.pfx").unwrap();
let mut pkcs12 = vec![];
file.read_to_end(&mut pkcs12).unwrap();
let pkcs12 = Pkcs12::from_der(&pkcs12, "12345").unwrap();
HttpServer::new(
Application::default("/")
// enable logger
.middleware(Logger::new(None))
// register simple handler, handle all methods
.handler("/index.html", index)
// with path parameters
.resource("/", |r| r.handler(Method::GET, |req, _, _| {
Ok(httpcodes::HTTPFound
.builder()
.header("LOCATION", "/index.html")
.body(Body::Empty)?)
})))
.serve_tls::<_, ()>("127.0.0.1:8080", pkcs12).unwrap();
println!("Started http server: 127.0.0.1:8080");
let _ = sys.run();
}

View file

@ -21,6 +21,11 @@ extern crate url;
extern crate percent_encoding; extern crate percent_encoding;
extern crate actix; extern crate actix;
#[cfg(feature="tls")]
extern crate native_tls;
#[cfg(feature="tls")]
extern crate tokio_tls;
mod application; mod application;
mod body; mod body;
mod context; mod context;
@ -64,3 +69,6 @@ pub use http::{Method, StatusCode, Version};
pub use cookie::{Cookie, CookieBuilder}; pub use cookie::{Cookie, CookieBuilder};
pub use cookie::{ParseError as CookieParseError}; pub use cookie::{ParseError as CookieParseError};
pub use http_range::{HttpRange, HttpRangeParseError}; pub use http_range::{HttpRange, HttpRangeParseError};
#[cfg(feature="tls")]
pub use native_tls::Pkcs12;

View file

@ -11,6 +11,11 @@ use tokio_core::reactor::Timeout;
use tokio_core::net::{TcpListener, TcpStream}; use tokio_core::net::{TcpListener, TcpStream};
use tokio_io::{AsyncRead, AsyncWrite}; use tokio_io::{AsyncRead, AsyncWrite};
#[cfg(feature="tls")]
use native_tls::TlsAcceptor;
#[cfg(feature="tls")]
use tokio_tls::{TlsStream, TlsAcceptorExt};
use task::Task; use task::Task;
use reader::{Reader, ReaderError}; use reader::{Reader, ReaderError};
use payload::Payload; use payload::Payload;
@ -69,17 +74,9 @@ impl<T, A, H> HttpServer<T, A, H>
self self
})) }))
} }
}
impl<H: HttpHandler> HttpServer<TcpStream, net::SocketAddr, H> { fn bind<S: net::ToSocketAddrs>(&self, addr: S)
-> io::Result<Vec<(net::SocketAddr, TcpListener)>>
/// Start listening for incomming connections.
///
/// This methods converts address to list of `SocketAddr`
/// then binds to all available addresses.
pub fn serve<S, Addr>(self, addr: S) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{ {
let mut err = None; let mut err = None;
let mut addrs = Vec::new(); let mut addrs = Vec::new();
@ -98,17 +95,71 @@ impl<H: HttpHandler> HttpServer<TcpStream, net::SocketAddr, H> {
Err(io::Error::new(io::ErrorKind::Other, "Can not bind to address.")) Err(io::Error::new(io::ErrorKind::Other, "Can not bind to address."))
} }
} else { } else {
Ok(HttpServer::create(move |ctx| { Ok(addrs)
for (addr, tcp) in addrs {
info!("Starting http server on {}", addr);
ctx.add_stream(tcp.incoming().map(|(t, a)| IoStream(t, a)));
}
self
}))
} }
} }
} }
impl<H: HttpHandler> HttpServer<TcpStream, net::SocketAddr, H> {
/// Start listening for incomming connections.
///
/// This methods converts address to list of `SocketAddr`
/// then binds to all available addresses.
pub fn serve<S, Addr>(self, addr: S) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{
let addrs = self.bind(addr)?;
Ok(HttpServer::create(move |ctx| {
for (addr, tcp) in addrs {
info!("Starting http server on {}", addr);
ctx.add_stream(tcp.incoming().map(|(t, a)| IoStream(t, a)));
}
self
}))
}
}
#[cfg(feature="tls")]
impl<H: HttpHandler> HttpServer<TlsStream<TcpStream>, net::SocketAddr, H> {
/// Start listening for incomming tls connections.
///
/// This methods converts address to list of `SocketAddr`
/// then binds to all available addresses.
pub fn serve_tls<S, Addr>(self, addr: S, pkcs12: ::Pkcs12) -> io::Result<Addr>
where Self: ActorAddress<Self, Addr>,
S: net::ToSocketAddrs,
{
let addrs = self.bind(addr)?;
let acceptor = match TlsAcceptor::builder(pkcs12) {
Ok(builder) => {
match builder.build() {
Ok(acceptor) => Rc::new(acceptor),
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
}
}
Err(err) => return Err(io::Error::new(io::ErrorKind::Other, err))
};
Ok(HttpServer::create(move |ctx| {
for (addr, tcp) in addrs {
info!("Starting tls http server on {}", addr);
let acc = acceptor.clone();
ctx.add_stream(tcp.incoming().and_then(move |(stream, addr)| {
TlsAcceptorExt::accept_async(acc.as_ref(), stream)
.map(move |t| IoStream(t, addr))
.map_err(|err| io::Error::new(io::ErrorKind::Other, err))
}));
}
self
}))
}
}
struct IoStream<T, A>(T, A); struct IoStream<T, A>(T, A);
impl<T, A> ResponseType for IoStream<T, A> impl<T, A> ResponseType for IoStream<T, A>
@ -129,6 +180,10 @@ impl<T, A, H> Handler<IoStream<T, A>, io::Error> for HttpServer<T, A, H>
A: 'static, A: 'static,
H: HttpHandler + 'static, H: HttpHandler + 'static,
{ {
fn error(&mut self, err: io::Error, _: &mut Context<Self>) {
trace!("Error handling request: {}", err)
}
fn handle(&mut self, msg: IoStream<T, A>, _: &mut Context<Self>) fn handle(&mut self, msg: IoStream<T, A>, _: &mut Context<Self>)
-> Response<Self, IoStream<T, A>> -> Response<Self, IoStream<T, A>>
{ {