Skip to content

Commit

Permalink
Allow to start tls server with HttpServer::serve_tls
Browse files Browse the repository at this point in the history
  • Loading branch information
fafhrd91 committed Nov 1, 2017
1 parent a12e5e9 commit ec3b139
Show file tree
Hide file tree
Showing 8 changed files with 152 additions and 19 deletions.
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ before_script:
- export PATH=$PATH:~/.cargo/bin

script:
- cargo test --no-default-features
- USE_SKEPTIC=1 cargo test --no-default-features
- |
if [[ "$TRAVIS_RUST_VERSION" == "nightly" && $CLIPPY ]]; then
cargo clippy
Expand Down
4 changes: 4 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
# Changes


## 0.2.1 (2017-11-xx)

* Allow to start tls server with `HttpServer::serve_tls`

## 0.2.0 (2017-10-30)

* Do not use `http::Uri` as it can not parse some valid paths
Expand Down
8 changes: 7 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,9 @@ path = "src/lib.rs"
[features]
default = []

# http/2
# tls
tls = ["native-tls", "tokio-tls"]

# http2 = ["h2"]

[dependencies]
Expand All @@ -49,6 +51,10 @@ tokio-io = "0.1"
tokio-core = "0.1"
# 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]
version = ">=0.3.1"
#path = "../actix"
Expand Down
14 changes: 14 additions & 0 deletions examples/tls/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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"] }
Binary file added examples/tls/identity.pfx
Binary file not shown.
46 changes: 46 additions & 0 deletions examples/tls/src/main.rs
Original file line number Diff line number Diff line change
@@ -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();
}
8 changes: 8 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ extern crate url;
extern crate percent_encoding;
extern crate actix;

#[cfg(feature="tls")]
extern crate native_tls;
#[cfg(feature="tls")]
extern crate tokio_tls;

mod application;
mod body;
mod context;
Expand Down Expand Up @@ -64,3 +69,6 @@ pub use http::{Method, StatusCode, Version};
pub use cookie::{Cookie, CookieBuilder};
pub use cookie::{ParseError as CookieParseError};
pub use http_range::{HttpRange, HttpRangeParseError};

#[cfg(feature="tls")]
pub use native_tls::Pkcs12;
89 changes: 72 additions & 17 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ use tokio_core::reactor::Timeout;
use tokio_core::net::{TcpListener, TcpStream};
use tokio_io::{AsyncRead, AsyncWrite};

#[cfg(feature="tls")]
use native_tls::TlsAcceptor;
#[cfg(feature="tls")]
use tokio_tls::{TlsStream, TlsAcceptorExt};

use task::Task;
use reader::{Reader, ReaderError};
use payload::Payload;
Expand Down Expand Up @@ -69,17 +74,9 @@ impl<T, A, H> HttpServer<T, A, H>
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,
fn bind<S: net::ToSocketAddrs>(&self, addr: S)
-> io::Result<Vec<(net::SocketAddr, TcpListener)>>
{
let mut err = None;
let mut addrs = Vec::new();
Expand All @@ -98,17 +95,71 @@ impl<H: HttpHandler> HttpServer<TcpStream, net::SocketAddr, H> {
Err(io::Error::new(io::ErrorKind::Other, "Can not bind to address."))
}
} else {
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
}))
Ok(addrs)
}
}
}

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);

impl<T, A> ResponseType for IoStream<T, A>
Expand All @@ -129,6 +180,10 @@ impl<T, A, H> Handler<IoStream<T, A>, io::Error> for HttpServer<T, A, H>
A: '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>)
-> Response<Self, IoStream<T, A>>
{
Expand Down

0 comments on commit ec3b139

Please sign in to comment.