Debian Codegraph @

third_party/rust/h2/examples/akamai.rs

raw
1 use h2::client;
2 use http::{Method, Request};
3 use tokio::net::TcpStream;
4 use tokio_rustls::TlsConnector;
5
6 use tokio_rustls::rustls::{OwnedTrustAnchor, RootCertStore, ServerName};
7
8 use std::convert::TryFrom;
9 use std::error::Error;
10 use std::net::ToSocketAddrs;
11
12 const ALPN_H2: &str = "h2";
13
14 #[tokio::main]
15 pub async fn main() -> Result<(), Box<dyn Error>> {
16 let _ = env_logger::try_init();
17
18 let tls_client_config = std::sync::Arc::new({
19 let mut root_store = RootCertStore::empty();
20 root_store.add_trust_anchors(webpki_roots::TLS_SERVER_ROOTS.iter().map(|ta| {
21 OwnedTrustAnchor::from_subject_spki_name_constraints(
22 ta.subject,
23 ta.spki,
24 ta.name_constraints,
25 )
26 }));
27
28 let mut c = tokio_rustls::rustls::ClientConfig::builder()
29 .with_safe_defaults()
30 .with_root_certificates(root_store)
31 .with_no_client_auth();
32 c.alpn_protocols.push(ALPN_H2.as_bytes().to_owned());
33 c
34 });
35
36 // Sync DNS resolution.
37 let addr = "http2.akamai.com:443"
38 .to_socket_addrs()
39 .unwrap()
40 .next()
41 .unwrap();
42
43 println!("ADDR: {:?}", addr);
44
45 let tcp = TcpStream::connect(&addr).await?;
46 let dns_name = ServerName::try_from("http2.akamai.com").unwrap();
47 let connector = TlsConnector::from(tls_client_config);
48 let res = connector.connect(dns_name, tcp).await;
49 let tls = res.unwrap();
50 {
51 let (_, session) = tls.get_ref();
52 let negotiated_protocol = session.alpn_protocol();
53 assert_eq!(Some(ALPN_H2.as_bytes()), negotiated_protocol);
54 }
55
56 println!("Starting client handshake");
57 let (mut client, h2) = client::handshake(tls).await?;
58
59 println!("building request");
60 let request = Request::builder()
61 .method(Method::GET)
62 .uri("https://http2.akamai.com/")
63 .body(())
64 .unwrap();
65
66 println!("sending request");
67 let (response, other) = client.send_request(request, true).unwrap();
68
69 tokio::spawn(async move {
70 if let Err(e) = h2.await {
71 println!("GOT ERR={:?}", e);
72 }
73 });
74
75 println!("waiting on response : {:?}", other);
76 let (_, mut body) = response.await?.into_parts();
77 println!("processing body");
78 while let Some(chunk) = body.data().await {
79 println!("RX: {:?}", chunk?);
80 }
81 Ok(())
82 }