Skip to content
Myr

main.rs

This file

Path

examples/low-level-rustls/src/main.rs

109 lines · 3.6 KiB · Rust

Last changed by

Not known.

History of this file

Take it

1//! Run with2//!3//! ```not_rust4//! cargo run -p example-low-level-rustls5//! ```67use axum::{extract::Request, routing::get, Router};8use hyper::body::Incoming;9use hyper_util::rt::{TokioExecutor, TokioIo};10use std::{11    path::{Path, PathBuf},12    sync::Arc,13};14use tokio::net::TcpListener;15use tokio_rustls::{16    rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer},17    rustls::ServerConfig,18    TlsAcceptor,19};20use tower_service::Service;21use tracing::{error, info, warn};22use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};2324#[tokio::main]25async fn main() {26    tracing_subscriber::registry()27        .with(28            tracing_subscriber::EnvFilter::try_from_default_env()29                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),30        )31        .with(tracing_subscriber::fmt::layer())32        .init();3334    let rustls_config = rustls_server_config(35        PathBuf::from(env!("CARGO_MANIFEST_DIR"))36            .join("self_signed_certs")37            .join("key.pem"),38        PathBuf::from(env!("CARGO_MANIFEST_DIR"))39            .join("self_signed_certs")40            .join("cert.pem"),41    );4243    let tls_acceptor = TlsAcceptor::from(rustls_config);44    let bind = "[::1]:3000";45    let tcp_listener = TcpListener::bind(bind).await.unwrap();46    info!("HTTPS server listening on {bind}. To contact curl -k https://localhost:3000");47    let app = Router::new().route("/", get(handler));4849    loop {50        let tower_service = app.clone();51        let tls_acceptor = tls_acceptor.clone();5253        // Wait for new tcp connection54        let (cnx, addr) = tcp_listener.accept().await.unwrap();5556        tokio::spawn(async move {57            // Wait for tls handshake to happen58            let Ok(stream) = tls_acceptor.accept(cnx).await else {59                error!("error during tls handshake connection from {}", addr);60                return;61            };6263            // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio.64            // `TokioIo` converts between them.65            let stream = TokioIo::new(stream);6667            // Hyper also has its own `Service` trait and doesn't use tower. We can use68            // `hyper::service::service_fn` to create a hyper `Service` that calls our app through69            // `tower::Service::call`.70            let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| {71                // We have to clone `tower_service` because hyper's `Service` uses `&self` whereas72                // tower's `Service` requires `&mut self`.73                //74                // We don't need to call `poll_ready` since `Router` is always ready.75                tower_service.clone().call(request)76            });7778            let ret = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())79                .serve_connection_with_upgrades(stream, hyper_service)80                .await;8182            if let Err(err) = ret {83                warn!("error serving connection from {}: {}", addr, err);84            }85        });86    }87}8889async fn handler() -> &'static str {90    "Hello, World!"91}9293fn rustls_server_config(key: impl AsRef<Path>, cert: impl AsRef<Path>) -> Arc<ServerConfig> {94    let key = PrivateKeyDer::from_pem_file(key).unwrap();9596    let certs = CertificateDer::pem_file_iter(cert)97        .unwrap()98        .map(|cert| cert.unwrap())99        .collect();100101    let mut config = ServerConfig::builder()102        .with_no_client_auth()103        .with_single_cert(certs, key)104        .expect("bad certificate/key");105106    config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()];107108    Arc::new(config)109}