1
//! The DNS resolver reactor, for resolving DNS queries asynchronously.
2
//!
3
//! The [`DnsResolverReactor`] is meant to be run as a background task.
4
//! It is paired with a [`DnsResolver`], which exposes an async interface
5
//! for sending DNS queries to the reactor.
6

            
7
use std::collections::HashMap;
8
use std::collections::hash_map::Entry;
9
use std::sync::Arc;
10
use std::time::{Duration, Instant};
11

            
12
use async_trait::async_trait;
13
use derive_more::Constructor;
14
use futures::FutureExt as _;
15
use futures::channel::mpsc;
16
use futures::select_biased;
17
use futures::stream::StreamExt as _;
18
use futures::task::SpawnError;
19
use hickory_resolver::lookup::Lookup;
20
use hickory_resolver::net::runtime::TokioRuntimeProvider;
21
use smallvec::SmallVec;
22
use tracing::debug;
23

            
24
use tor_async_utils::oneshot_broadcast;
25
use tor_error::{Bug, internal, into_internal};
26
use tor_log_ratelim::log_ratelim;
27
use tor_rtcompat::{JoinSet, JoinSetProvider, Runtime, SleepProviderExt as _};
28

            
29
use crate::stream::dns::resolver::{
30
    DnsRequest, DnsResolver, DnsResponseReceiver, LookupAnswers, LookupError, RecordData,
31
};
32

            
33
/// The hickory stub resolver.
34
pub(crate) type HickoryResolver = hickory_resolver::Resolver<TokioRuntimeProvider>;
35

            
36
/// The ASCII-encoded hostname from a RESOLVE, in canonical form.
37
type Query = Arc<str>;
38

            
39
// TODO(relay): check the TTLs against C Tor and the relevant DNS RFCs
40
// to make sure they're fit for purpose
41

            
42
/// The TTL to use for responses that have an empty answer section (not NXDOMAIN).
43
const TTL_FOR_EMPTY_ANS: Duration = Duration::from_mins(5);
44

            
45
/// The TTL for error responses.
46
const TTL_FOR_ERRORS: Duration = Duration::from_mins(5);
47

            
48
/// Our "low" TTL value. Any TTLs below this are clipped to this value.
49
///
50
/// Must be greater than FUZZY_DNS_TTL_SECONDS, otherwise our calculations can underflow.
51
const MIN_DNS_TTL: Duration = Duration::from_mins(5);
52

            
53
/// Our "high" TTL value. Any TTLs above MIN_DNS_TTL are clipped to this value.
54
const MAX_DNS_TTL: Duration = Duration::from_mins(60);
55

            
56
/// The amount we +- to the clipped TTL to make it "fuzzy".
57
///
58
/// Must be less than MIN_DNS_TTL, otherwise our calculations can underflow.
59
///
60
/// See "The effect of DNS on Tor's Anonymity" by Greschbach et al.
61
const FUZZY_DNS_TTL: Duration = Duration::from_mins(4);
62

            
63
/// How frequently do we want to garbage-collect the expired entries?
64
///
65
/// Note(gabi): doing this every 1h seems sensible, although we could
66
/// probably do it even less frequently.
67
///
68
/// Eventually, we might want a more principled approach here.
69
/// For example, we might want to remove the expired entries
70
/// from the cache as soon as their TTL runs out,
71
/// but there are some trade-offs:
72
///
73
///   * we would need some sort of data structure for determining
74
///     when the next cache entry is due to expire.
75
///     This would likely be a min-heap, so it would be an additional
76
///     O(n) space to store
77
///   * in addition to the extra memory usage, removing the expired
78
///     entries right away will likely have an impact on performance too.
79
///     If our cache regularly fills up with lots of short-lived (TTL = 5 min)
80
///     unpopular entries (possibly tracking domains?), the reactor will
81
///     have to a bunch of frequent removals, essentially interrupting
82
///     its incoming request handling
83
///
84
/// For these reasons, right now, it seems better to remove the expired
85
/// entries in batches.
86
const CACHE_PURGE_INTERVAL: Duration = Duration::from_mins(60);
87

            
88
/// A reactor that performs DNS lookups on behalf of incoming streams (RESOLVE, BEGIN).
89
///
90
/// De-duplicates queries, and uses hickory-resolver under the hood.
91
///
92
/// Queries are de-duplicated using [`PendingQueries`], which keeps track
93
/// of all the currently running lookup tasks.
94
#[must_use = "the reactor doesn't do anything unless you run it"]
95
pub(crate) struct DnsResolverReactor<R: Runtime, M: MockableAsyncResolver = HickoryResolver> {
96
    /// The async stub resolver.
97
    resolver: Arc<M>,
98
    /// The runtime.
99
    runtime: R,
100
    /// The DNS lookups we have launched that we are still waiting on.
101
    pending: PendingQueries<<R as JoinSetProvider>::JoinSet<(Query, DnsResponse)>>,
102
    /// The DNS cache.
103
    cache: DnsCache,
104
    /// MPSC channel for receiving DNS queries.
105
    query_rx: mpsc::Receiver<DnsRequest>,
106
}
107

            
108
/// A DNS response.
109
///
110
/// We cache the response as a whole, not the individual answers.
111
#[derive(Clone, Debug, Constructor)]
112
pub(crate) struct DnsResponse {
113
    /// The answer records.
114
    pub(crate) answers: Result<LookupAnswers<RecordData>, LookupError>,
115
    /// The timestamp when this response becomes invalid.
116
    ///
117
    /// This is computed by clipping + fuzzing the max TTL of all the answers.
118
    ///
119
    // TODO(relay): This does mean we'll be serving stale Records sometimes,
120
    // but I think that might be fine?
121
    //
122
    // RFC-8767 says resolvers are allowed to serve stale data,
123
    // **if** they're unable to refresh it
124
    // (that's not necessarily the case here,
125
    // although with a flexible enough interpretation of the RFC,
126
    // maybe it could be?):
127
    //
128
    // "If the data is unable to be authoritatively refreshed when the TTL expires,
129
    // the record MAY be used as though it is unexpired"
130
    valid_until: Instant,
131
}
132

            
133
impl DnsResponse {
134
    /// Returns `true` if this response is expired at `now`.
135
572
    fn is_expired(&self, now: Instant) -> bool {
136
572
        self.valid_until <= now
137
572
    }
138
}
139

            
140
/// An answer record.
141
#[derive(Clone, Debug, Constructor)]
142
pub(crate) struct AnswerRecord {
143
    /// The answer record.
144
    data: RecordData,
145
    /// The TTL, used to compute the valid_until of the corresponding [`DnsResponse`].
146
    ttl: u32,
147
}
148

            
149
/// Type-alias for the hickory record type, for convenience
150
type HickoryRecord = hickory_proto::rr::Record<hickory_proto::rr::RData>;
151

            
152
impl TryFrom<&HickoryRecord> for AnswerRecord {
153
    type Error = LookupError;
154

            
155
    fn try_from(rec: &HickoryRecord) -> Result<Self, Self::Error> {
156
        Ok(Self {
157
            data: RecordData::try_from(&rec.data)?,
158
            ttl: rec.ttl,
159
        })
160
    }
161
}
162

            
163
/// A mockable stub resolver.
164
///
165
/// Used for mocking the hickory resolver in the
166
/// [`DnsResolverReactor`] tests.
167
#[async_trait]
168
pub(crate) trait MockableAsyncResolver: Send + Sync + 'static {
169
    /// A random number generator
170
    type Rng: rand::Rng + rand::CryptoRng;
171

            
172
    /// Performs a dual-stack DNS lookup for the IP for the given hostname.
173
    async fn lookup_ip(&self, query: &str) -> Result<LookupAnswers<AnswerRecord>, LookupError>;
174

            
175
    /// Performs a lookup for the associated type.
176
    async fn reverse_lookup(&self, query: &str)
177
    -> Result<LookupAnswers<AnswerRecord>, LookupError>;
178

            
179
    /// Return a random number generator
180
    fn thread_rng(&self) -> Self::Rng;
181
}
182

            
183
// TODO(relay): do we want hickory_resolver::ConnectionProvider to be a supertrait of tor_rtcompat::Runtime?
184
// It would enable us to write some unit tests involving the hickory resolver,
185
// without having to mock the whole thing like we do today.
186
//
187
// For now, this seems more trouble than it's worth.
188

            
189
#[async_trait]
190
impl MockableAsyncResolver for HickoryResolver {
191
    type Rng = rand::rngs::ThreadRng;
192

            
193
    async fn lookup_ip(&self, query: &str) -> Result<LookupAnswers<AnswerRecord>, LookupError> {
194
        let lookup = self.lookup_ip(query).await?;
195

            
196
        extract_hickory_answers(lookup.as_lookup())
197
    }
198

            
199
    async fn reverse_lookup(
200
        &self,
201
        query: &str,
202
    ) -> Result<LookupAnswers<AnswerRecord>, LookupError> {
203
        let lookup = self.reverse_lookup(query).await?;
204

            
205
        extract_hickory_answers(&lookup)
206
    }
207

            
208
    fn thread_rng(&self) -> Self::Rng {
209
        rand::rng()
210
    }
211
}
212

            
213
/// Convert a hickory [`Lookup`] into a collection of [`AnswerRecord`]s.
214
///
215
/// Note: we need our own AnswerRecord type here, because the hickory Record type
216
/// is quite big (272 bytes) and includes various fields we don't actually use
217
/// (such as the domain name that was looked up and the DNS record class).
218
fn extract_hickory_answers(lookup: &Lookup) -> Result<LookupAnswers<AnswerRecord>, LookupError> {
219
    // Note on TTLs: you might think we could use the valid_until timestamp
220
    // from the Lookup object here. However, that wouldn't give us
221
    // the real TTL, because hickory-resolver always sets this to the maximum
222
    // allowed TTL of 1 day (see the Future impl for LookupIpFuture in hickory_resolver).
223
    lookup
224
        .answers()
225
        .iter()
226
        .map(AnswerRecord::try_from)
227
        .collect::<Result<_, LookupError>>()
228
}
229

            
230
/// A response cache for the [`DnsResolverReactor`].
231
///
232
/// Maps [`Query`]s to [`DnsResponse`]s. In other words, we cache whole responses,
233
/// which may contain multiple answer records, each with its own TTL.
234
/// The TTL of a *cache entry* is calculated using the TTLs of the answers it contains:
235
///
236
///   * if the lookup failed, we use [`TTL_FOR_ERRORS`]
237
///   * if the lookup succeeded, but the answer section is empty,
238
///     we use [`TTL_FOR_EMPTY_ANS`]
239
///   * if the lookup succeded, and we got some answers, we calculate the TTL of the response
240
///     by taking the maximum TTL of the answers it contains
241
///
242
/// Finally, we clip and fuzz the resulting TTL before using it to calculate the
243
/// `valid_until` expiration timestamp of the cache entry (see [`clip_dns_fuzzy_ttl`]).
244
struct DnsCache {
245
    /// Our DNS cache, keyed by the ASCII encoded address extracted
246
    /// from RESOLVE queries.
247
    //
248
    // TODO(relay): make this memquota-aware, and have memquota
249
    // evict entries using an LRU policy if we're under
250
    // memory pressure
251
    inner: HashMap<Query, DnsResponse>,
252
    /// The timestamp when the expired entries should be purged using
253
    /// [`remove_expired`](Self::remove_expired).
254
    ///
255
    /// This is recalculated each time `remove_expired is called.
256
    ///
257
    /// This shouldn't happen too frequently, because it's an O(n) operation
258
    /// that blocks all incoming requests until it completes.
259
    purge_expired_at: Instant,
260
}
261

            
262
impl DnsCache {
263
    /// Create an empty [`DnsCache`].
264
10
    fn new(now: Instant) -> Self {
265
10
        Self {
266
10
            inner: Default::default(),
267
10
            purge_expired_at: Self::next_expired_purge(now),
268
10
        }
269
10
    }
270

            
271
    /// Return the cached response for `query` if it still fresh at `now`,
272
    /// or `None` otherwise.
273
    ///
274
    /// If the query response is cached, but is expired at `now`,
275
    /// this will remove it from the cache.
276
588
    fn get_or_remove_expired(&mut self, query: &Query, now: Instant) -> Option<DnsResponse> {
277
588
        match self.inner.entry(Arc::clone(query)) {
278
            Entry::Occupied(e) => {
279
522
                let entry = e.get();
280
522
                if !entry.is_expired(now) {
281
520
                    Some(entry.clone())
282
                } else {
283
                    // The entry is expired, we should remove it from the cache
284
2
                    let _ = e.remove();
285
2
                    None
286
                }
287
            }
288
66
            Entry::Vacant(_) => None,
289
        }
290
588
    }
291

            
292
    /// Insert the specified response into the cache.
293
60
    fn insert(&mut self, query: Query, res: DnsResponse) {
294
60
        self.inner.insert(query, res);
295
60
    }
296

            
297
    /// Remove all the entries that are expired at `now`.
298
    ///
299
    /// This is an O(n) operation, so it should be used sparingly.
300
    /// Currently called on a timer from the main loop of the reactor.
301
    ///
302
    /// Returns the number of entries removed.
303
10
    fn remove_expired(&mut self, now: Instant) -> usize {
304
10
        let before = self.inner.len();
305
50
        self.inner.retain(|_, res| !res.is_expired(now));
306
10
        self.purge_expired_at = Self::next_expired_purge(now);
307
10
        before - self.inner.len()
308
10
    }
309

            
310
    /// When remove_expired() should be called next to purge leftover expired entries.
311
20
    fn next_expired_purge(now: Instant) -> Instant {
312
20
        now + CACHE_PURGE_INTERVAL
313
20
    }
314
}
315

            
316
/// A collection of in-flight DNS queries.
317
///
318
/// Used by the [`DnsResolverReactor`] to prevent launching multiple lookups for the same query.
319
struct PendingQueries<J: JoinSet<(Query, DnsResponse)>> {
320
    // TODO(relay): investigate if it would make sense to use the InternCache
321
    // from tor-basic-utils for the for the hostnames
322
    /// A list of streams that are waiting on responses to the DNS queries.
323
    /// Each of these has an entry in self.inflight.
324
    ///
325
    /// Keyed by the ASCII-encoded hostname from the RESOLVE, in canonical form.
326
    pending_response: HashMap<Query, oneshot_broadcast::Sender<DnsResponse>>,
327
    /// DNS queries we're currently waiting a response for.
328
    inflight: J,
329
}
330

            
331
impl<J: JoinSet<(Query, DnsResponse)>> PendingQueries<J> {
332
    /// Returns a [`DnsResponseReceiver`] for the specified `query`
333
    /// if there is currently an in-flight lookup for it,
334
    /// or spawn a new lookup, returning the [`DnsResponseReceiver`] for awaiting the response.
335
68
    fn get_or_launch_lookup<M: MockableAsyncResolver>(
336
68
        &mut self,
337
68
        query: Query,
338
68
        resolver: &Arc<M>,
339
68
        now: Instant,
340
68
    ) -> DnsResponseReceiver {
341
        let should_spawn_lookup =
342
68
            if let Entry::Occupied(e) = self.pending_response.entry(Arc::clone(&query)) {
343
                // If we already have an inflight query for the same request,
344
                // we just return a new watcher for that particular query
345
8
                if let Ok(rx) = e.get().subscribe() {
346
8
                    return DnsResponseReceiver::from(rx);
347
                } else {
348
                    // All the other receivers that were waiting on this query were dropped!
349
                    // This can happen, for example, if all the other pending DnsResolver::resolve()
350
                    // futures for this `guery` are canceled, for whatever reason.
351
                    //
352
                    // In practice, however, this won't happen, because in arti-relay,
353
                    // each RESOLVE is handled in a separate task,
354
                    // but it's better to handle it gracefully, rather than by returning an error,
355
                    // because returning an error here will cause the DnsResolverReactor to shut down.
356

            
357
                    // The existing pending_response entry is unusable,
358
                    // because its broadcast channel has closed.
359
                    e.remove();
360

            
361
                    // We will insert a new pending_response entry below
362
                    false
363
                }
364
            } else {
365
                // If we *don't* already have an in-flight lookup,
366
                // we need to launch one.
367
60
                true
368
            };
369

            
370
        // The channel on which to broadcast the lookup result
371
        // to all the tasks waiting on it
372
        // (used for deduplicating queries)
373
60
        let (res_tx, res_rx) = oneshot_broadcast::channel();
374

            
375
60
        if should_spawn_lookup {
376
60
            let resolver = Arc::clone(resolver);
377

            
378
            // Time to launch a new lookup
379
60
            let res = self.inflight.spawn({
380
60
                let query = Arc::clone(&query);
381
60
                async move {
382
60
                    let res = resolve_query(Arc::clone(&query), resolver, now).await;
383
60
                    (query, res)
384
60
                }
385
            });
386

            
387
60
            if res.is_ok() {
388
60
                let previous = self.pending_response.insert(query, res_tx);
389

            
390
                // This should be impossible, because we remove any dangling channels above
391
60
                debug_assert!(previous.is_none());
392
            }
393

            
394
            // If we failed to spawn the task, we drop the res_tx channel,
395
            // which will cause its receiver to error.
396

            
397
            // This roundabout way of reporting the error is because SpawnError is not cloneable,
398
            // but log_ratelim! expects an owned Result.
399
            //
400
            // See also https://gitlab.torproject.org/tpo/core/arti/-/work_items/2632
401
60
            let report_outcome: Result<(), _> = res.map_err(into_internal!("spawn failed"));
402
60
            log_ratelim!("spawning DNS task"; report_outcome);
403
        }
404

            
405
60
        DnsResponseReceiver::from(res_rx)
406
68
    }
407

            
408
    /// Remove the pending entry that was waiting for an answer to the specified `query`.
409
60
    fn remove(&mut self, query: &str) -> Result<oneshot_broadcast::Sender<DnsResponse>, Bug> {
410
60
        self.pending_response
411
60
            .remove(query)
412
            .ok_or_else(|| internal!("got response for a query we didn't ask for?!"))
413
60
    }
414
}
415

            
416
/// Try to resolve the specified `host`,
417
/// returning a `DnsResponse` to send back to the client.
418
///
419
/// The `host` must be a hostname.
420
/// If it ends in `in-addr.arpa.` or `ip6.arpa.`, this function will perform a reverse lookup.
421
60
async fn resolve_query<M: MockableAsyncResolver>(
422
60
    host: Query,
423
60
    resolver: Arc<M>,
424
60
    now: Instant,
425
60
) -> DnsResponse {
426
    // Note the trailing dot (this expects canonicalize_hostname() to turn
427
    // the hostname into a FQDN)
428
60
    let lookup = if host.ends_with(".in-addr.arpa.") || host.ends_with(".ip6.arpa.") {
429
6
        resolver.reverse_lookup(&host)
430
    } else {
431
54
        resolver.lookup_ip(&host)
432
    };
433

            
434
60
    let (answers, ttl) = match lookup.await {
435
        Ok(res) => {
436
58
            let answers: SmallVec<_> = res;
437
            // Use the max TTL of all the answers
438
58
            let ttl = answers
439
58
                .iter()
440
60
                .map(|ans: &AnswerRecord| u64::from(ans.ttl))
441
                .max()
442
58
                .map(Duration::from_secs)
443
58
                .unwrap_or(TTL_FOR_EMPTY_ANS);
444

            
445
60
            let answers = answers.into_iter().map(|res| res.data).collect();
446

            
447
58
            (Ok(answers), ttl)
448
        }
449
2
        Err(e) => (Err(e), TTL_FOR_ERRORS),
450
    };
451

            
452
60
    let valid_until = now + clip_dns_fuzzy_ttl(ttl, &mut resolver.thread_rng());
453
60
    DnsResponse::new(answers, valid_until)
454
60
}
455

            
456
/// Clip the `ttl` to be either 5 minutes or 60 minutes.
457
///
458
/// If `ttl` is below 5 minutes, returns a TTL of 5 minutes.
459
/// If `ttl` is 5 minutes or above, returns a TTL of 60 minutes.
460
///
461
/// Like in C Tor, this logic is a defense against [DefectTor]
462
/// DNS-based traffic confirmation attacks.
463
///
464
/// [DefectTor]: https://nymity.ch/tor-dns/tor-dns.pdf
465
74
fn clip_dns_ttl(ttl: Duration) -> Duration {
466
74
    if ttl < MIN_DNS_TTL {
467
58
        MIN_DNS_TTL
468
    } else {
469
16
        MAX_DNS_TTL
470
    }
471
74
}
472

            
473
/// Clip and randomize the specified `ttl`.
474
///
475
/// This clips the `ttl` (see [`clip_dns_ttl`]),
476
/// and adds a random duration (sampled uniformly from [-4 min, 4min]),
477
/// in order to make it harder to infer when the corresponding domain
478
/// was visited from this exit relay (see "Website Fingerprinting with Website Oracles").
479
65
fn clip_dns_fuzzy_ttl<R: rand::Rng + rand::CryptoRng>(ttl: Duration, rng: &mut R) -> Duration {
480
    use tor_basic_utils::RngExt;
481

            
482
65
    let fuzzy_ttl_seconds = FUZZY_DNS_TTL.as_secs() as i32;
483

            
484
65
    let fuzz: i32 = rng
485
65
        .gen_range_checked(-fuzzy_ttl_seconds..=fuzzy_ttl_seconds)
486
65
        .expect("low as not < high");
487

            
488
65
    let ttl_secs: i32 = clip_dns_ttl(ttl)
489
65
        .as_secs()
490
65
        .try_into()
491
65
        .expect("clip_dns_ttl returned a humonguous TTL?!");
492

            
493
65
    debug_assert!(ttl_secs > fuzz, "FUZZY_DNS_TTL > MIN_DNS_TTL?!");
494

            
495
65
    let fuzzed_ttl_secs: u64 = (ttl_secs + fuzz)
496
65
        .try_into()
497
65
        .expect("a TTL of minutes does not fit in a u64?!");
498

            
499
65
    Duration::from_secs(fuzzed_ttl_secs)
500
65
}
501

            
502
impl<R: Runtime, M: MockableAsyncResolver> DnsResolverReactor<R, M> {
503
    /// Build a new reactor that uses the specified mockable resolver.
504
    ///
505
    /// Note: for per-circuit caches (option 3),
506
    /// there will be one DnsResolverReactor per circuit,
507
    /// all of them sharing an Arc::clone of the same underlying
508
    /// hickory Resolver
509
    ///
510
    // Question: should we try to make to make this generic over
511
    // the runtime? If so, we will need to add a (hickory) RuntimeProvider
512
    // trait bound to tor_rtcompat::Runtime.
513
10
    pub(crate) fn new(runtime: R, resolver: Arc<M>) -> Result<(Self, DnsResolver), SpawnError> {
514
        // TODO(relay-tuning): pick an appropriate buffer size here
515
        //
516
        // Alternatively, we might want to rework this so that this cannot becomes a bottleneck
517
        // (maybe it wants to be an unbounded channel? Or maybe we can somehow make it
518
        // memquota-aware?)
519
        const DNS_QUERY_BUF_SIZE: usize = 512;
520

            
521
        #[allow(clippy::disallowed_methods)]
522
10
        let (query_tx, query_rx) = mpsc::channel(DNS_QUERY_BUF_SIZE);
523

            
524
10
        let mut inflight = runtime.new_join_set();
525
        // The inflight list has an always-pending task to prevent it from
526
        // yielding None when empty
527
10
        inflight.spawn(std::future::pending())?;
528

            
529
10
        let pending = PendingQueries {
530
10
            pending_response: Default::default(),
531
10
            inflight,
532
10
        };
533

            
534
10
        let now = runtime.now();
535
10
        let reactor = Self {
536
10
            resolver,
537
10
            runtime,
538
10
            pending,
539
10
            cache: DnsCache::new(now),
540
10
            query_rx,
541
10
        };
542

            
543
10
        let handle = DnsResolver::new(query_tx);
544

            
545
10
        Ok((reactor, handle))
546
10
    }
547

            
548
    /// Run the reactor.
549
10
    pub(crate) async fn run(mut self) -> Result<(), Bug> {
550
        loop {
551
668
            select_biased! {
552
668
                () = self.runtime.sleep_until(self.cache.purge_expired_at).fuse() => {
553
10
                    let now = self.runtime.now();
554
10
                    let purged = self.cache.remove_expired(now);
555
10
                    let remaining = self.cache.inner.len();
556
10
                    debug!(purged, remaining, "Purged expired entries from DNS cache");
557
                },
558
668
                res = self.pending.inflight.join_next().fuse() => {
559
                    // inflight can never yield None because
560
                    // we pushed a forever pending future in it
561
60
                    let res = res.expect("pending future resolved?!");
562

            
563
                    // This can only happen if a task panics, or is aborted.
564
                    // We never abort tasks, so this can only happen on panic.
565
60
                    let (query, response) = res.map_err(|_| internal!("A DNS lookup panicked?!"))?;
566

            
567
60
                    self.handle_response(query, response)?;
568
                },
569
668
                query = self.query_rx.next() => {
570
598
                    let Some(query) = query else {
571
                        // All DnsResolvers were dropped
572
10
                        return Ok(());
573
                    };
574
588
                    self.handle_request(query);
575
                }
576
            }
577
        }
578
10
    }
579

            
580
    /// Handles new queries coming from DnsResolver::resolve()
581
588
    fn handle_request(&mut self, req: DnsRequest) {
582
588
        let DnsRequest { query, tx } = req;
583

            
584
588
        let query = canonicalize_hostname(&query).into();
585
588
        let now = self.runtime.now();
586

            
587
588
        let response_rx = if let Some(res) = self.cache.get_or_remove_expired(&query, now) {
588
            // First, if the query is already cached,
589
            // we can respond immediately
590
520
            DnsResponseReceiver::from(res)
591
        } else {
592
            // If we don't have a cached answer,
593
            // we need to launch a new lookup,
594
            // unless we already have a pending one for this query
595
68
            self.pending
596
68
                .get_or_launch_lookup(query, &self.resolver, now)
597
        };
598

            
599
588
        let _ = tx.send(response_rx);
600
588
    }
601

            
602
    /// Called when one of our pending queries completes.
603
60
    fn handle_response(&mut self, query: Query, res: DnsResponse) -> Result<(), Bug> {
604
60
        let response_tx = self.pending.remove(&query)?;
605

            
606
        // Update the cache
607
60
        self.cache.insert(query, res.clone());
608

            
609
        // Notify all the tasks waiting on this response.
610
        // If all the receivers have gone away, this will be ignored
611
        // (and the lookup response will be dropped).
612
60
        response_tx.send(res);
613

            
614
60
        Ok(())
615
60
    }
616
}
617

            
618
/// Return the hostname in canonical form.
619
///
620
/// Converts `hostname` to lowercase, and trims any leading or trailing whitespace.
621
/// The returned hostname is in FQDN form (it ends with '.').
622
///
623
/// This function assumes that `hostname` is an ASCII string.
624
593
fn canonicalize_hostname(hostname: &str) -> String {
625
593
    let mut hostname = hostname.trim().to_lowercase();
626
593
    if !hostname.ends_with('.') {
627
566
        hostname.push('.');
628
27
    }
629

            
630
593
    hostname
631
593
}
632

            
633
#[cfg(test)]
634
mod test {
635
    // @@ begin test lint list maintained by maint/add_warning @@
636
    #![allow(clippy::bool_assert_comparison)]
637
    #![allow(clippy::clone_on_copy)]
638
    #![allow(clippy::dbg_macro)]
639
    #![allow(clippy::mixed_attributes_style)]
640
    #![allow(clippy::print_stderr)]
641
    #![allow(clippy::print_stdout)]
642
    #![allow(clippy::single_char_pattern)]
643
    #![allow(clippy::unwrap_used)]
644
    #![allow(clippy::unchecked_time_subtraction)]
645
    #![allow(clippy::useless_vec)]
646
    #![allow(clippy::needless_pass_by_value)]
647
    #![allow(clippy::string_slice)] // See arti#2571
648
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
649

            
650
    use super::*;
651

            
652
    use async_trait::async_trait;
653
    use smallvec::smallvec;
654
    use tor_basic_utils::test_rng::{TestingRng, testing_rng};
655
    use tor_rtcompat::{Runtime, SpawnExt as _};
656
    use tor_rtmock::MockRuntime;
657
    use tracing_test::traced_test;
658

            
659
    use crate::stream::dns::resolver::reactor::{AnswerRecord, MockableAsyncResolver};
660

            
661
    use std::net::IpAddr;
662
    use std::str::FromStr;
663
    use std::sync::{Arc, Mutex};
664

            
665
    type Ans = Result<LookupAnswers<AnswerRecord>, LookupError>;
666

            
667
    /// A mock resolver, for testing
668
    ///
669
    /// The mock resolver returns a list of pre-configured answers
670
    /// (see [`MockResolverInner`]).
671
    struct MockResolver {
672
        /// The mutable state of the resolver.
673
        inner: Mutex<MockResolverInner>,
674
    }
675

            
676
    #[derive(Default)]
677
    struct MockResolverInner {
678
        /// A list of replies to return from [`MockableAsyncResolver::lookup_ip`].
679
        lookup_ip_replies: Vec<Ans>,
680
        /// A list of replies to return from [`MockableAsyncResolver::reverse_lookup`].
681
        reverse_lookup_replies: Vec<Ans>,
682
        /// The number of times lookup_with_ip() was called.
683
        query_count: usize,
684
        /// The number of times reverse_lookup() was called.
685
        reverse_query_count: usize,
686
    }
687

            
688
    impl MockResolver {
689
        /// Build a new mock resolver.
690
        fn new() -> Arc<Self> {
691
            Arc::new(Self {
692
                inner: Mutex::new(Default::default()),
693
            })
694
        }
695

            
696
        fn with_lookup_ip_replies(
697
            self: Arc<Self>,
698
            replies: impl IntoIterator<Item = Ans>,
699
        ) -> Arc<Self> {
700
            self.inner.lock().unwrap().lookup_ip_replies = replies.into_iter().collect();
701
            self
702
        }
703

            
704
        fn with_reverse_lookup_replies(
705
            self: Arc<Self>,
706
            replies: impl IntoIterator<Item = Ans>,
707
        ) -> Arc<Self> {
708
            self.inner.lock().unwrap().reverse_lookup_replies = replies.into_iter().collect();
709
            self
710
        }
711

            
712
        /// Spawns the reactor and returns the DnsResolver handle,
713
        /// and a handle to `MockResolver` for controlling
714
        /// the values returned by the resolver.
715
        fn launch<R: Runtime>(self: &Arc<Self>, rt: R) -> DnsResolver {
716
            let (reactor, resolver) =
717
                DnsResolverReactor::new(rt.clone(), Arc::clone(self)).unwrap();
718

            
719
            rt.spawn(async move {
720
                reactor.run().await.unwrap();
721
            })
722
            .unwrap();
723

            
724
            resolver
725
        }
726

            
727
        fn query_count(&self) -> usize {
728
            self.inner.lock().unwrap().query_count
729
        }
730

            
731
        fn reverse_query_count(&self) -> usize {
732
            self.inner.lock().unwrap().reverse_query_count
733
        }
734
    }
735

            
736
    #[async_trait]
737
    impl MockableAsyncResolver for MockResolver {
738
        type Rng = TestingRng;
739

            
740
        async fn lookup_ip(
741
            &self,
742
            _query: &str,
743
        ) -> Result<LookupAnswers<AnswerRecord>, LookupError> {
744
            let mut inner = self.inner.lock().unwrap();
745
            inner.query_count += 1;
746
            if !inner.lookup_ip_replies.is_empty() {
747
                inner.lookup_ip_replies.remove(0)
748
            } else {
749
                Err(internal!("mock resolver is out of replies").into())
750
            }
751
        }
752

            
753
        async fn reverse_lookup(
754
            &self,
755
            _query: &str,
756
        ) -> Result<LookupAnswers<AnswerRecord>, LookupError> {
757
            let mut inner = self.inner.lock().unwrap();
758
            inner.reverse_query_count += 1;
759
            if !inner.reverse_lookup_replies.is_empty() {
760
                inner.reverse_lookup_replies.remove(0)
761
            } else {
762
                Ok(smallvec![])
763
            }
764
        }
765

            
766
        fn thread_rng(&self) -> Self::Rng {
767
            testing_rng()
768
        }
769
    }
770

            
771
    // Convenience impls to more easily build test RecordData
772
    impl From<IpAddr> for RecordData {
773
        fn from(addr: IpAddr) -> Self {
774
            Self::Ip(addr)
775
        }
776
    }
777

            
778
    impl From<String> for RecordData {
779
        fn from(host: String) -> Self {
780
            Self::Hostname(host)
781
        }
782
    }
783

            
784
    impl From<(IpAddr, u32)> for AnswerRecord {
785
        fn from((addr, ttl): (IpAddr, u32)) -> Self {
786
            AnswerRecord {
787
                data: addr.into(),
788
                ttl,
789
            }
790
        }
791
    }
792

            
793
    impl From<(String, u32)> for AnswerRecord {
794
        fn from((host, ttl): (String, u32)) -> Self {
795
            AnswerRecord {
796
                data: host.into(),
797
                ttl,
798
            }
799
        }
800
    }
801

            
802
    /// Build a `lookup_ip` response out of some addresses
803
    #[allow(clippy::unnecessary_wraps)]
804
    fn addrs_to_response(addrs: impl IntoIterator<Item = impl Into<AnswerRecord>>) -> Ans {
805
        let mut ans = smallvec![];
806
        for addr in addrs {
807
            ans.push(addr.into());
808
        }
809
        Ok(ans)
810
    }
811

            
812
    #[test]
813
    fn canonicalize_hostname() {
814
        use super::canonicalize_hostname as ch;
815

            
816
        assert_eq!(ch("example.com"), "example.com.");
817
        assert_eq!(ch("example.com."), "example.com.");
818
        assert_eq!(ch("eXaMple.com"), "example.com.");
819
        assert_eq!(ch("   \t  eXaMple.com \t\r\n"), "example.com.");
820
        assert_eq!(
821
            ch("   \t  1.2.3.4.in-addr.arpa \t\r\n"),
822
            "1.2.3.4.in-addr.arpa."
823
        );
824
    }
825

            
826
    #[test]
827
    fn clip_ttl() {
828
        assert_eq!(clip_dns_ttl(Duration::from_mins(0)), Duration::from_mins(5));
829
        assert_eq!(clip_dns_ttl(Duration::from_mins(1)), Duration::from_mins(5));
830
        assert_eq!(
831
            clip_dns_ttl(Duration::from_mins(5)),
832
            Duration::from_mins(60)
833
        );
834
        assert_eq!(
835
            clip_dns_ttl(Duration::from_mins(15)),
836
            Duration::from_mins(60)
837
        );
838
    }
839

            
840
    /// Assert that `fuzzy` is within the range
841
    /// [clip_dns_ttl(ttl) - FUZZY_DNS_TTL, clip_dns_ttl(ttl) + FUZZY_DNS_TTL]
842
    fn assert_in_fuzzy_range(fuzzy: Duration, ttl: Duration) {
843
        let clipped = clip_dns_ttl(ttl);
844
        assert!(fuzzy >= clipped - FUZZY_DNS_TTL);
845
        assert!(fuzzy <= clipped + FUZZY_DNS_TTL);
846
    }
847

            
848
    #[test]
849
    fn clip_and_fuzz_ttl() {
850
        let mut rng = testing_rng();
851

            
852
        for ttl_mins in [0, 5, 15, 60, 120] {
853
            let ttl = Duration::from_mins(ttl_mins);
854
            let fuzzy_ttl = clip_dns_fuzzy_ttl(ttl, &mut rng);
855
            assert_in_fuzzy_range(fuzzy_ttl, ttl);
856
        }
857
    }
858

            
859
    #[test]
860
    fn reject_nonascii_hostname() {
861
        MockRuntime::test_with_various(|rt| async move {
862
            let mock = MockResolver::new();
863
            let mut resolver = mock.launch(rt);
864
            // Non-ASCII domains aren't allowed
865
            let err = resolver
866
                .resolve("example👍️.com".as_bytes())
867
                .await
868
                .unwrap_err();
869
            assert!(matches!(err, LookupError::NonAsciiHostname));
870
        });
871
    }
872

            
873
    #[test]
874
    fn simple_dns_query() {
875
        MockRuntime::test_with_various(|rt| async move {
876
            /// The TTL of the mock answer records, in seconds.
877
            const TTL: u32 = 300;
878

            
879
            let ipv4 = IpAddr::from_str("1.2.3.4").unwrap();
880
            let ipv6 = IpAddr::from_str("::1").unwrap();
881
            let ip_replies = addrs_to_response(vec![(ipv4, TTL), (ipv6, TTL)]);
882
            let mock = MockResolver::new().with_lookup_ip_replies(vec![ip_replies]);
883
            let mut resolver = mock.launch(rt);
884
            let records = resolver.resolve(b"example.com").await.unwrap();
885

            
886
            // Expect two answers (one IPv4 and one IPv6)
887
            assert_eq!(records.len(), 2);
888
            assert!(records.contains(&ipv4.into()));
889
            assert!(records.contains(&ipv6.into()));
890

            
891
            // The mock resolver has no answers for our reverse lookup
892
            let records = resolver.resolve(b"1.2.3.4.in-addr.arpa.").await.unwrap();
893
            assert!(records.is_empty());
894

            
895
            let ip_replies = addrs_to_response(vec![("example.com".to_string(), TTL)]);
896
            let _ = mock.with_reverse_lookup_replies(vec![ip_replies]);
897
            // The next reverse lookup should *not* yield the mock result we set above,
898
            // because the DnsResolver cached the negative response
899
            let records = resolver.resolve(b"1.2.3.4.in-addr.arpa.").await.unwrap();
900
            assert!(records.is_empty());
901
        });
902
    }
903

            
904
    #[test]
905
    fn simple_cached_response() {
906
        MockRuntime::test_with_various(|rt| async move {
907
            /// The TTL of the mock answer records, in seconds.
908
            const TTL: u32 = 30;
909

            
910
            /// The address to do a reverse lookup for
911
            const ADDR: &[u8] = b"1.2.3.4.in-addr.arpa.";
912

            
913
            let reply1 = addrs_to_response(vec![
914
                ("example.com".to_string(), TTL),
915
                ("sub.example.com".to_string(), TTL),
916
            ]);
917
            let reply2 = addrs_to_response(vec![("foo.com".to_string(), TTL)]);
918
            let mock = MockResolver::new().with_reverse_lookup_replies(vec![reply1, reply2]);
919
            let mut resolver = mock.launch(rt.clone());
920

            
921
            // We can query the resolver a bunch of times,
922
            // and it will keep returning the cached example.com answer.
923
            // It won't make any additional queries until we advance
924
            // the mocked time, causing the cached answer to expire.
925
            for _ in 0..10 {
926
                let records = resolver.resolve(ADDR).await.unwrap();
927
                // The DnsResolver reactor has sent out one query
928
                assert_eq!(mock.reverse_query_count(), 1);
929
                assert_eq!(records.len(), 2);
930
                assert_eq!(records[0], RecordData::from("example.com".to_string()));
931
                assert_eq!(records[1], RecordData::from("sub.example.com".to_string()));
932
            }
933

            
934
            rt.advance_by(MIN_DNS_TTL + FUZZY_DNS_TTL).await;
935

            
936
            let records = resolver.resolve(ADDR).await.unwrap();
937
            // The DnsResolver reactor has sent a second query!
938
            assert_eq!(mock.reverse_query_count(), 2);
939
            assert_eq!(records.len(), 1);
940
            assert_eq!(records[0], RecordData::from("foo.com".to_string()));
941
        });
942
    }
943

            
944
    #[traced_test]
945
    #[test]
946
    fn periodic_cache_purges() {
947
        MockRuntime::test_with_various(|rt| async move {
948
            /// The number of lookup_ip() queries we will make in between cache purges
949
            const QUERY_COUNT: usize = 5;
950
            /// The number of cache purge intervals we will simulate in this test
951
            const CACHE_PURGE_INTERVALS: usize = 5;
952
            /// The TTL of the mock responses, in seconds.
953
            const TTL: u32 = 60;
954

            
955
            let mut responses = vec![];
956
            // This is multiplied by CACHE_PURGE_INTERVALS,
957
            // because we will make a total of QUERY_COUNT * CACHE_PURGE_INTERVALS
958
            // queries that will cause the reactor to reach out to the (mock) resolver
959
            for _ in 0..QUERY_COUNT * CACHE_PURGE_INTERVALS {
960
                responses.push(addrs_to_response(vec![(
961
                    IpAddr::from_str("1.2.3.4").unwrap(),
962
                    TTL,
963
                )]));
964
            }
965

            
966
            let mock = MockResolver::new().with_lookup_ip_replies(responses);
967
            let mut resolver = mock.launch(rt.clone());
968

            
969
            for i in 0..CACHE_PURGE_INTERVALS {
970
                // Make a bunch of queries, causing them to be cached
971
                for j in 0..QUERY_COUNT {
972
                    let records = resolver
973
                        .resolve(format!("{j}.example.com").as_bytes())
974
                        .await
975
                        .unwrap();
976
                    // The DnsResolver reactor sends out one query per request
977
                    assert_eq!(mock.query_count(), i * QUERY_COUNT + j + 1);
978
                    // One record per dummy response
979
                    assert_eq!(records.len(), 1);
980
                    assert_eq!(
981
                        records[0],
982
                        RecordData::from(IpAddr::from_str("1.2.3.4").unwrap())
983
                    );
984
                }
985

            
986
                let current_query_count = mock.query_count();
987
                // No matter how many times we try to re-reresolve the same domains again,
988
                // the reactor won't reach out to our resolver (because it continues
989
                // serving the responses from the cache)
990
                for _ in 0..10 {
991
                    for j in 0..QUERY_COUNT {
992
                        let _ = resolver
993
                            .resolve(format!("{j}.example.com").as_bytes())
994
                            .await
995
                            .unwrap();
996
                        // The query count measured at the mock resolver remains stable,
997
                        // because the resolver is able to respond from the cache
998
                        assert_eq!(mock.query_count(), current_query_count);
999
                    }
                }
                // Advance time such that the expired entries are purged once per interval
                rt.advance_by(CACHE_PURGE_INTERVAL).await;
            }
            // Unfortunately we can't test how many times this appears in the logs,
            // because MockRuntime::test_with_various runs this test runs in a loop,
            // and the logs are preserved across runs (each test would need to know
            // its position in the MockRuntime::test_with_various's loop to be able
            // to accurately assert how many of these logs there should be)
            assert!(logs_contain("Purged expired entries from DNS cache"));
        });
    }
    #[traced_test]
    #[test]
    fn query_deduplication() {
        MockRuntime::test_with_various(|rt| async move {
            /// The number of concurrent queries to send
            const QUERY_COUNT: usize = 5;
            let mock = MockResolver::new();
            let resolver = mock.launch(rt.clone());
            // Make a bunch of queries, all at the same time
            let mut queries = vec![];
            for _ in 0..QUERY_COUNT {
                let mut resolver = resolver.clone();
                queries.push(async move { resolver.resolve(b"example.com").await });
            }
            let _ = futures::future::join_all(queries).await;
            // The reactor only reached out to the resolver once
            assert_eq!(mock.query_count(), 1);
        });
    }
}