akamai.rs 2.4 KB

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