changelog shortlog graph tags branches changeset files revisions annotate raw help

Mercurial > core / rust/lib/net/src/engine/dns/resolver.rs

changeset 698: 96958d3eb5b0
parent: 3d78bed56188
author: Richard Westhaver <ellis@rwest.io>
date: Fri, 04 Oct 2024 22:04:59 -0400
permissions: -rw-r--r--
description: fixes
1 use crate::Result;
2 
3 use hickory_resolver::{
4  config::{NameServerConfig, Protocol, ResolverConfig, ResolverOpts},
5  error::ResolveErrorKind,
6  TokioAsyncResolver,
7 };
8 use std::{
9  future::Future,
10  net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4},
11 };
12 
13 pub trait Lookup: Send + 'static {
14  fn lookup(
15  &self,
16  ip: IpAddr,
17  ) -> impl Future<Output = Option<String>> + Send + '_;
18 }
19 
20 #[repr(transparent)]
21 pub struct Resolver(pub TokioAsyncResolver);
22 unsafe impl Send for Resolver {}
23 impl Resolver {
24  pub async fn new(dns_server: &Option<Ipv4Addr>) -> Result<Self> {
25  let resolver = match dns_server {
26  Some(dns_server_address) => {
27  let mut config = ResolverConfig::new();
28  let options = ResolverOpts::default();
29  let socket = SocketAddr::V4(SocketAddrV4::new(*dns_server_address, 53));
30  let nameserver_config = NameServerConfig {
31  socket_addr: socket,
32  protocol: Protocol::Udp,
33  tls_dns_name: None,
34  trust_negative_responses: false,
35  bind_addr: None,
36  };
37  config.add_name_server(nameserver_config);
38  TokioAsyncResolver::tokio(config, options)
39  }
40  None => TokioAsyncResolver::tokio_from_system_conf().unwrap(),
41  };
42  Ok(Self(resolver))
43  }
44 }
45 
46 impl Lookup for Resolver {
47  async fn lookup(&self, ip: IpAddr) -> Option<String> {
48  let lookup_future = self.0.reverse_lookup(ip);
49  match lookup_future.await {
50  Ok(names) => {
51  // Take the first result and convert it to a string
52  names.into_iter().next().map(|x| x.to_string())
53  }
54  Err(e) => match e.kind() {
55  // If the IP is not associated with a hostname, store the IP
56  // so that we don't retry indefinitely
57  ResolveErrorKind::NoRecordsFound { .. } => Some(ip.to_string()),
58  _ => None,
59  },
60  }
61  }
62 }