4
0

https.rs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. use async_trait::async_trait;
  2. use hyper_tls::HttpsConnector;
  3. use hyper::Body;
  4. use hyper::body::HttpBody as _;
  5. use hyper::Client;
  6. use log::*;
  7. use dns::{Request, Response};
  8. use super::{Transport, Error};
  9. /// The **HTTPS transport**, which uses Hyper.
  10. ///
  11. /// # Examples
  12. ///
  13. /// ```no_run
  14. /// use dns_transport::{Transport, HttpsTransport};
  15. /// use dns::{Request, Flags, Query, Labels, QClass, qtype, record::A};
  16. ///
  17. /// let query = Query {
  18. /// qname: Labels::encode("dns.lookup.dog").unwrap(),
  19. /// qclass: QClass::IN,
  20. /// qtype: qtype!(A),
  21. /// };
  22. ///
  23. /// let request = Request {
  24. /// transaction_id: 0xABCD,
  25. /// flags: Flags::query(),
  26. /// query: query,
  27. /// additional: None,
  28. /// };
  29. ///
  30. /// let transport = HttpsTransport::new("https://cloudflare-dns.com/dns-query");
  31. /// transport.send(&request);
  32. /// ```
  33. #[derive(Debug)]
  34. pub struct HttpsTransport {
  35. url: String,
  36. }
  37. impl HttpsTransport {
  38. /// Creates a new HTTPS transport that connects to the given URL.
  39. pub fn new(url: impl Into<String>) -> Self {
  40. Self { url: url.into() }
  41. }
  42. }
  43. #[async_trait]
  44. impl Transport for HttpsTransport {
  45. async fn send(&self, request: &Request) -> Result<Response, Error> {
  46. let https = HttpsConnector::new();
  47. let client = Client::builder().build::<_, hyper::Body>(https);
  48. let bytes = request.to_bytes().expect("failed to serialise request");
  49. info!("Sending {} bytes of data to {:?}", bytes.len(), self.url);
  50. let request = hyper::Request::builder()
  51. .method("POST")
  52. .uri(&self.url)
  53. .header("Content-Type", "application/dns-message")
  54. .header("Accept", "application/dns-message")
  55. .body(Body::from(bytes))
  56. .expect("Failed to build request"); // we control the request, so this should never fail
  57. let mut response = client.request(request).await?;
  58. debug!("Response: {}", response.status());
  59. debug!("Headers: {:#?}", response.headers());
  60. if response.status() != 200 {
  61. return Err(Error::BadRequest);
  62. }
  63. debug!("Reading body...");
  64. let mut buf = Vec::new();
  65. while let Some(chunk) = response.body_mut().data().await {
  66. buf.extend(&chunk?);
  67. }
  68. info!("Received {} bytes of data", buf.len());
  69. let response = Response::from_bytes(&buf)?;
  70. Ok(response)
  71. }
  72. }