Debian Codegraph @

crt/s2n/bindings/rust-examples/hyper-server-client/src/bin/server.rs

raw symbols SCIP
1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 // SPDX-License-Identifier: Apache-2.0
3
4 use clap::Parser;
5 use http_body_util::{combinators::BoxBody, BodyExt};
6 use hyper::body::Bytes;
7 use hyper::service::service_fn;
8 use hyper::{Request, Response};
9 use hyper_util::rt::TokioExecutor;
10 use std::error::Error;
11 use tokio::net::TcpListener;
12
13 /// NOTE: this certificate and key are to be used for demonstration purposes only!
14 pub const CERT_PEM: &[u8] = include_bytes!(concat!(
15 env!("CARGO_MANIFEST_DIR"),
16 "/../certs/localhost-chain.pem"
17 ));
18 pub const KEY_PEM: &[u8] = include_bytes!(concat!(
19 env!("CARGO_MANIFEST_DIR"),
20 "/../certs/localhost-key.pem"
21 ));
22
23 #[derive(Parser)]
24 struct Args {
25 #[clap(short, long, default_value = "localhost:8888")]
26 addr: String,
27 }
28
29 /// Echo the request body back to the client in the response.
30 pub async fn echo(
31 req: Request<hyper::body::Incoming>,
32 ) -> Result<Response<BoxBody<Bytes, hyper::Error>>, hyper::Error> {
33 Ok(Response::new(req.into_body().boxed()))
34 }
35
36 async fn run_server(addr: &str) -> Result<(), Box<dyn Error>> {
37 // Configure the s2n-tls server.
38 let config = {
39 let mut builder = s2n_tls::config::Builder::new();
40 builder.load_pem(CERT_PEM, KEY_PEM)?;
41 // Enable HTTP/2 by including it in the server's supported ALPN values. The "http2"
42 // hyper-util feature must also be enabled.
43 builder.set_application_protocol_preference([b"h2"])?;
44 builder.build()?
45 };
46
47 // Create a TlsAcceptor based on this configuration.
48 let acceptor = s2n_tls_tokio::TlsAcceptor::new(config);
49
50 // Listen for incoming TCP connections at the provided address.
51 let tcp_listener = TcpListener::bind(addr).await?;
52 loop {
53 // Wait for a client to connect.
54 let (tcp, _) = tcp_listener.accept().await?;
55
56 // Spawn a new task to handle the incoming TCP connection.
57 let acceptor = acceptor.clone();
58 tokio::spawn(async move {
59 // Perform the TLS handshake.
60 let tls_stream = acceptor.accept(tcp).await?;
61
62 // Use the hyper server with the `echo` service to respond to the client's HTTP request
63 // over the TlsStream.
64 let io = hyper_util::rt::TokioIo::new(tls_stream);
65 let server = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new());
66 server.serve_connection(io, service_fn(echo)).await?;
67
68 Ok::<(), Box<dyn Error + Send + Sync>>(())
69 });
70 }
71 }
72
73 #[tokio::main]
74 async fn main() -> Result<(), Box<dyn Error>> {
75 let args = Args::parse();
76 run_server(&args.addr).await?;
77 Ok(())
78 }