nodecraft/resolver/impls/
dns.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use core::time::Duration;
use std::{io, net::SocketAddr};

use agnostic::Runtime;
pub use agnostic::{
  dns::{AsyncConnectionProvider, Dns, ResolverConfig, ResolverOpts},
  net::Net,
};
use crossbeam_skiplist::SkipMap;

use super::{super::AddressResolver, CachedSocketAddr};
use crate::{DnsName, Kind, NodeAddress};

#[derive(Debug, thiserror::Error)]
enum ResolveErrorKind {
  #[error("cannot resolve an ip address for {0}")]
  NotFound(DnsName),
  #[error(transparent)]
  Resolve(#[from] hickory_resolver::error::ResolveError),
}

/// The error type for errors that get returned when resolving fails
#[derive(Debug)]
#[repr(transparent)]
pub struct ResolveError(ResolveErrorKind);

impl core::fmt::Display for ResolveError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> std::fmt::Result {
    self.0.fmt(f)
  }
}

impl core::error::Error for ResolveError {}

impl From<ResolveErrorKind> for ResolveError {
  fn from(value: ResolveErrorKind) -> Self {
    Self(value)
  }
}

/// Errors that can occur when resolving an address.
#[derive(Debug, thiserror::Error)]
pub enum Error {
  /// Returns when there is an io error
  #[error(transparent)]
  IO(#[from] io::Error),
  /// Returns when there is an error when resolving an address
  #[error(transparent)]
  Resolve(#[from] ResolveError),
}

/// The options used to configure the DNS
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DnsOptions {
  resolver_opts: ResolverOpts,
  resolver_config: ResolverConfig,
}

const fn default_record_ttl() -> Duration {
  Duration::from_secs(60)
}

impl DnsOptions {
  /// Create a new [`DnsResolverOptions`] with the default DNS configurations.
  pub fn new() -> Self {
    Self {
      resolver_opts: ResolverOpts::default(),
      resolver_config: ResolverConfig::default(),
    }
  }

  /// Set the default dns configuration in builder pattern
  pub fn with_resolver_config(mut self, c: ResolverConfig) -> Self {
    self.resolver_config = c;
    self
  }

  /// Set the default dns configuration
  pub fn set_resolver_config(&mut self, c: ResolverConfig) -> &mut Self {
    self.resolver_config = c;
    self
  }

  /// Returns the resolver configuration
  pub fn resolver_config(&self) -> &ResolverConfig {
    &self.resolver_config
  }

  /// Set the default resolver options in builder pattern
  pub fn with_resolver_opts(mut self, o: ResolverOpts) -> Self {
    self.resolver_opts = o;
    self
  }

  /// Set the default resolver options
  pub fn set_resolver_opts(&mut self, o: ResolverOpts) -> &mut Self {
    self.resolver_opts = o;
    self
  }

  /// Returns the resolver options
  pub fn resolver_opts(&self) -> &ResolverOpts {
    &self.resolver_opts
  }
}

impl Default for DnsOptions {
  fn default() -> Self {
    Self::new()
  }
}

/// The options used to construct a [`DnsResolver`].
#[derive(Debug, Clone)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct DnsResolverOptions {
  #[cfg_attr(feature = "serde", serde(default = "default_record_ttl"))]
  record_ttl: Duration,
  dns: Option<DnsOptions>,
}

impl Default for DnsResolverOptions {
  fn default() -> Self {
    Self::new()
  }
}

impl DnsResolverOptions {
  /// Create a new [`DnsResolverOptions`] with the default DNS configurations.
  #[inline]
  pub fn new() -> Self {
    Self {
      record_ttl: default_record_ttl(),
      dns: Some(DnsOptions::default()),
    }
  }

  /// Set the default record ttl in builder pattern
  #[inline]
  pub const fn with_record_ttl(mut self, ttl: Duration) -> Self {
    self.record_ttl = ttl;
    self
  }

  /// Set the default record ttl
  #[inline]
  pub fn set_record_ttl(&mut self, ttl: Duration) -> &mut Self {
    self.record_ttl = ttl;
    self
  }

  /// Returns the record ttl
  #[inline]
  pub const fn record_ttl(&self) -> Duration {
    self.record_ttl
  }

  /// Set the default dns configuration in builder pattern
  #[inline]
  pub fn with_dns(mut self, dns: Option<DnsOptions>) -> Self {
    self.dns = dns;
    self
  }

  /// Set the default dns configuration
  #[inline]
  pub fn set_dns(&mut self, dns: Option<DnsOptions>) -> &mut Self {
    self.dns = dns;
    self
  }

  /// Returns the dns configuration
  #[inline]
  pub const fn dns(&self) -> Option<&DnsOptions> {
    self.dns.as_ref()
  }
}

/// A resolver which supports both `domain:port` and socket address.
///
/// - If you can make sure, you always play with [`SocketAddr`], you may want to
///   use [`SocketAddrResolver`](crate::resolver::socket_addr::SocketAddrResolver).
/// - If you do not want to send DNS queries, you may want to use [`AddressResolver`](crate::resolver::address::AddressResolver).
///
/// **N.B.** If a domain contains multiple ip addresses, there is no guarantee that
/// which one will be used. Users should make sure that the domain only contains
/// one ip address, to make sure that [`DnsResolver`] can work properly.
///
/// e.g. valid address format:
/// 1. `www.example.com:8080` // domain
/// 2. `[::1]:8080` // ipv6
/// 3. `127.0.0.1:8080` // ipv4
///
pub struct DnsResolver<R: Runtime> {
  dns: Option<Dns<R::Net>>,
  record_ttl: Duration,
  cache: SkipMap<DnsName, CachedSocketAddr>,
}

impl<R: Runtime> AddressResolver for DnsResolver<R> {
  type Address = NodeAddress;
  type Error = Error;
  type ResolvedAddress = SocketAddr;
  type Runtime = R;
  type Options = DnsResolverOptions;

  async fn new(opts: Self::Options) -> Result<Self, Self::Error>
  where
    Self: Sized,
  {
    let dns = if let Some(opts) = opts.dns {
      Some(Dns::new(
        opts.resolver_config,
        opts.resolver_opts,
        AsyncConnectionProvider::new(),
      ))
    } else {
      None
    };
    Ok(Self {
      dns,
      record_ttl: opts.record_ttl,
      cache: Default::default(),
    })
  }

  async fn resolve(&self, address: &Self::Address) -> Result<Self::ResolvedAddress, Self::Error> {
    match &address.kind {
      Kind::Ip(ip) => Ok(SocketAddr::new(*ip, address.port)),
      Kind::Dns(name) => {
        // First, check cache
        if let Some(ent) = self.cache.get(name.as_str()) {
          let val = ent.value();
          if !val.is_expired() {
            return Ok(val.val);
          } else {
            ent.remove();
          }
        }

        // Second, TCP lookup ip address
        if let Some(ref dns) = self.dns {
          if let Some(ip) = dns
            .lookup_ip(name.terminate_str())
            .await
            .map_err(|e| ResolveError::from(ResolveErrorKind::from(e)))?
            .into_iter()
            .next()
          {
            let addr = SocketAddr::new(ip, address.port);
            self
              .cache
              .insert(name.clone(), CachedSocketAddr::new(addr, self.record_ttl));
            return Ok(addr);
          }
        }

        // Finally, try to find the socket addr locally
        let port = address.port;
        let tsafe = name.clone();

        let res =
          agnostic::net::ToSocketAddrs::<R>::to_socket_addrs(&(tsafe.as_str(), port)).await?;

        if let Some(addr) = res.into_iter().next() {
          self
            .cache
            .insert(name.clone(), CachedSocketAddr::new(addr, self.record_ttl));
          return Ok(addr);
        }

        Err(Error::Resolve(ResolveError(ResolveErrorKind::NotFound(
          name.clone(),
        ))))
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use super::*;

  #[tokio::test]
  async fn test_dns_resolver() {
    use agnostic::tokio::TokioRuntime;

    let resolver = DnsResolver::<TokioRuntime>::new(Default::default())
      .await
      .unwrap();
    let google_addr = NodeAddress::try_from("google.com:8080").unwrap();
    let ip = resolver.resolve(&google_addr).await.unwrap();
    println!("google.com:8080 resolved to: {}", ip);
  }

  #[tokio::test]
  async fn test_dns_resolver_with_record_ttl() {
    use agnostic::tokio::TokioRuntime;

    let resolver = DnsResolver::<TokioRuntime>::new(
      DnsResolverOptions::default().with_record_ttl(Duration::from_millis(100)),
    )
    .await
    .unwrap();
    let google_addr = NodeAddress::try_from("google.com:8080").unwrap();
    resolver.resolve(&google_addr).await.unwrap();
    let dns_name = DnsName::try_from("google.com").unwrap();
    assert!(!resolver
      .cache
      .get(dns_name.as_str())
      .unwrap()
      .value()
      .is_expired());

    tokio::time::sleep(Duration::from_millis(100)).await;
    assert!(resolver
      .cache
      .get(dns_name.as_str())
      .unwrap()
      .value()
      .is_expired());
  }

  #[tokio::test]
  async fn test_dns_resolver_without_dns() {
    use agnostic::tokio::TokioRuntime;

    let resolver = DnsResolver::<TokioRuntime>::new(
      DnsResolverOptions::default()
        .with_dns(None)
        .with_record_ttl(Duration::from_millis(100)),
    )
    .await
    .unwrap();
    let google_addr = NodeAddress::try_from("google.com:8080").unwrap();
    resolver.resolve(&google_addr).await.unwrap();
    resolver.resolve(&google_addr).await.unwrap();
    let ip_addr = NodeAddress::try_from(("127.0.0.1", 8080)).unwrap();
    resolver.resolve(&ip_addr).await.unwrap();
    let dns_name = DnsName::try_from("google.com").unwrap();
    assert!(!resolver
      .cache
      .get(dns_name.as_str())
      .unwrap()
      .value()
      .is_expired());

    tokio::time::sleep(Duration::from_millis(100)).await;
    assert!(resolver
      .cache
      .get(dns_name.as_str())
      .unwrap()
      .value()
      .is_expired());
    resolver.resolve(&google_addr).await.unwrap();

    let err = ResolveError::from(ResolveErrorKind::NotFound(dns_name.clone()));
    println!("{err}");
    println!("{err:?}");

    let bad_addr = NodeAddress::try_from("adasdjkljasidjaosdjaisudnaisudibasd.com:8080").unwrap();
    assert!(resolver.resolve(&bad_addr).await.is_err());
  }

  #[test]
  fn test_opts() {
    let opts = DnsOptions::new();
    let opts = opts.with_resolver_config(Default::default());
    opts.resolver_config();
    let mut opts = opts.with_resolver_opts(Default::default());
    opts.resolver_opts();
    opts.set_resolver_config(Default::default());
    opts.set_resolver_opts(Default::default());

    let mut opts = DnsResolverOptions::new().with_dns(Some(opts));
    opts.dns();
    opts.set_dns(Some(Default::default()));
    opts.set_record_ttl(Duration::from_secs(100));
    opts.record_ttl();
  }
}