Skip to content

Commit

Permalink
feat(server): Add an ssl example
Browse files Browse the repository at this point in the history
Adds an example using hyper + ssl for a server.

Should resolve the closed issue hyperium#1942
  • Loading branch information
trezm committed Nov 14, 2019
1 parent 71d088d commit 3c2648e
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
7 changes: 7 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ serde_json = "1.0"
tokio = "=0.2.0-alpha.6" # using #[tokio::test] attributes
tokio-fs = "=0.2.0-alpha.6"
tokio-test = "=0.2.0-alpha.6"
tokio-tls = "=0.3.0-alpha.6"
native-tls = "0.2"
url = "1.0"

[features]
Expand Down Expand Up @@ -149,6 +151,11 @@ name = "state"
path = "examples/state.rs"
required-features = ["runtime"]

[[example]]
name = "ssl_server"
path = "examples/ssl_server.rs"
required-features = ["runtime", "unstable-stream"]

[[example]]
name = "tower_client"
path = "examples/tower_client.rs"
Expand Down
Binary file added examples/ssl_server.p12
Binary file not shown.
69 changes: 69 additions & 0 deletions examples/ssl_server.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use std::net::SocketAddr;
use futures_util::stream::StreamExt;

use hyper::{Body, Response, Request};
use hyper::service::{make_service_fn, service_fn};
use hyper::server::conn::Http;
use hyper::server::Builder;
use std::sync::Arc;
use tokio::net::TcpListener;

use native_tls;
use native_tls::Identity;
use tokio_tls;
use std::convert::Infallible;

async fn hello(_: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("Hello World!")))
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let addr: SocketAddr = ([127, 0, 0, 1], 8443).into();

let cert = include_bytes!("./ssl_server.p12").to_vec();
let cert_pass = "password";
let cert = Identity::from_pkcs12(&cert, cert_pass)
.expect("Could not decrypt p12 file");
let tls_acceptor =
tokio_tls::TlsAcceptor::from(
native_tls::TlsAcceptor::builder(cert)
.build()
.expect("Could not create TLS acceptor.")
);
let _arc_acceptor = Arc::new(tls_acceptor);

let service = make_service_fn(|_| {
async {
Ok::<_, Infallible>(service_fn(hello))
}
});

let listener = TcpListener::bind(&addr).await.unwrap();
let incoming = listener.incoming();
let server = Builder
::new(hyper::server::accept::from_stream(incoming.filter_map(|socket| {
async {
match socket {
Ok(stream) => {
match _arc_acceptor.clone().accept(stream).await {
Ok(val) => Some(Ok::<_, hyper::Error>(val)),
Err(e) => {
println!("TLS error: {}", e);
None
}
}
},
Err(e) => {
println!("TCP socket error: {}", e);
None
}
}
}
})), Http::new())
.serve(service);

server.await?;

Ok(())
}

0 comments on commit 3c2648e

Please sign in to comment.