1
//! Logic for selecting relays from a network directory,
2
//! and reporting the outcome of such a selection.
3

            
4
use crate::{LowLevelRelayPredicate, RelayExclusion, RelayRestriction, RelayUsage};
5
use tor_basic_utils::iter::FilterCount;
6
use tor_netdir::{NetDir, Relay, WeightRole};
7

            
8
use std::fmt;
9

            
10
/// Description of the requirements that a relay must implement in order to be selected.
11
///
12
/// This object is used to pick a [`Relay`] from a [`NetDir`], or to ensure that a
13
/// previously selected `Relay` still meets its requirements.
14
///
15
/// The requirements on a relay can be _strict_ or _flexible_.
16
/// If any restriction is flexible, and relay selection fails at first,
17
/// we _relax_ the `RelaySelector` by removing that restriction,
18
/// and trying again,
19
/// before we give up completely.
20
#[derive(Clone, Debug)]
21
pub struct RelaySelector<'a> {
22
    /// A usage that the relay must support.
23
    ///
24
    /// Invariant: This is a RelayUsage.
25
    usage: Restr<'a>,
26

            
27
    /// An excludion that the relay must obey.
28
    ///
29
    /// Invariant: This a RelayExclusion.
30
    exclusion: Restr<'a>,
31

            
32
    /// Other restrictions that a Relay must obey in order to be selected.
33
    other_restrictions: Vec<Restr<'a>>,
34
}
35

            
36
/// A single restriction, along with a flag about whether it's strict.
37
#[derive(Clone, Debug)]
38
struct Restr<'a> {
39
    /// The underlying restriction.
40
    restriction: RelayRestriction<'a>,
41
    /// Is the restriction strict or flexible?
42
    strict: bool,
43
}
44

            
45
impl<'a> Restr<'a> {
46
    /// Try relaxing this restriction.
47
    ///
48
    /// (If this can't be relaxed, just return a copy of it.)
49
580
    fn maybe_relax(&self) -> Self {
50
580
        if self.strict {
51
290
            self.clone()
52
        } else {
53
290
            Self {
54
290
                restriction: self.restriction.relax(),
55
290
                // The new restriction is always strict, since we don't want to
56
290
                // relax it any further.
57
290
                strict: true,
58
290
            }
59
        }
60
580
    }
61
}
62

            
63
/// Information about how a given selection was generated.
64
///
65
/// Records the specifics of how many relays were excluded by each
66
/// requirement,
67
/// whether we had to relax the selector, and so on.
68
///
69
/// The caller should typically decide whether an error or warning is necessary,
70
/// and if so use this to generate a formattable report about what went wrong.
71
#[derive(Debug, Clone)]
72
pub struct SelectionInfo<'a> {
73
    /// Outcome of our first attempt to pick a relay.
74
    first_try: FilterCounts,
75

            
76
    /// Present if we tried again with a relaxed version of our
77
    /// flexible members.
78
    relaxed_try: Option<FilterCounts>,
79

            
80
    /// True if we eventually succeeded in picking a relay.
81
    succeeded: bool,
82

            
83
    /// The `RelaySelector` that was used.
84
    ///
85
    /// Used to produce information about which restriction is which.
86
    in_selection: &'a RelaySelector<'a>,
87
}
88

            
89
impl<'a> SelectionInfo<'a> {
90
    /// Return true if we eventually picked at least one relay.
91
    ///
92
    /// (We report success on `pick_n_relays` if we returned a nonzero
93
    /// number of relays, even if it is smaller than the requested number.)
94
200
    pub fn success(&self) -> bool {
95
200
        self.succeeded
96
200
    }
97

            
98
    /// Return true if picked at least one relay,
99
    /// but only after relaxing our initial selector.
100
200
    pub fn result_is_relaxed_success(&self) -> bool {
101
200
        self.relaxed_try.is_some() && self.succeeded
102
200
    }
103
}
104

            
105
impl<'a> fmt::Display for SelectionInfo<'a> {
106
510
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
107
510
        match (self.succeeded, &self.relaxed_try) {
108
2
            (true, None) => write!(f, "Success: {}", FcDisp(&self.first_try, self.in_selection))?,
109
506
            (false, None) => write!(f, "Failed: {}", FcDisp(&self.first_try, self.in_selection))?,
110
2
            (true, Some(retry)) => write!(
111
2
                f,
112
2
                "Failed at first, then succeeded. At first, {}. After relaxing requirements, {}",
113
2
                FcDisp(&self.first_try, self.in_selection),
114
2
                FcDisp(retry, self.in_selection)
115
2
            )?,
116
            (false, Some(retry)) => write!(
117
                f,
118
                "Failed even after relaxing requirement. At first, {}. After relaxing requirements, {}",
119
                FcDisp(&self.first_try, self.in_selection),
120
                FcDisp(retry, self.in_selection)
121
            )?,
122
        };
123
510
        Ok(())
124
510
    }
125
}
126

            
127
/// A list of [`FilterCount`], associated with a [`RelaySelector`].
128
#[derive(Debug, Clone)]
129
struct FilterCounts {
130
    /// The [`FilterCount`] created by each restriction.
131
    ///
132
    /// This `Vec` has the same length as the list of restrictions; its items
133
    /// refer to them one by one.
134
    ///
135
    /// Because restrictions are applied as a set of filters, each successive
136
    /// count will only include the relays not excluded by the previous filters.
137
    counts: Vec<FilterCount>,
138
}
139

            
140
impl FilterCounts {
141
    /// Create a new empty `FilterCounts`.
142
622076
    fn new(selector: &RelaySelector) -> Self {
143
622076
        let counts = vec![FilterCount::default(); selector.n_restrictions()];
144
622076
        FilterCounts { counts }
145
622076
    }
146
}
147

            
148
/// Helper to display filter counts
149
struct FcDisp<'a>(&'a FilterCounts, &'a RelaySelector<'a>);
150
impl<'a> fmt::Display for FcDisp<'a> {
151
512
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152
512
        let counts = &self.0.counts;
153
512
        let restrictions = self.1.all_restrictions();
154
512
        write!(f, "rejected ")?;
155
512
        let mut first = true;
156
512
        let mut found_any_rejected = false;
157
1024
        for (c, r) in counts.iter().zip(restrictions) {
158
1024
            if let Some(desc) = r.restriction.rejection_description() {
159
1024
                if first {
160
512
                    first = false;
161
512
                } else {
162
512
                    write!(f, "; ")?;
163
                }
164
1024
                write!(f, "{} as {}", c.display_frac_rejected(), desc)?;
165
1024
                found_any_rejected = true;
166
            } else {
167
                debug_assert_eq!(c.n_rejected, 0);
168
            }
169
        }
170
512
        if !found_any_rejected {
171
            write!(f, "none")?;
172
512
        }
173
512
        Ok(())
174
512
    }
175
}
176

            
177
impl<'a> RelaySelector<'a> {
178
    /// Create a new RelaySelector to pick relays with a given
179
    /// [`RelayUsage`] and [`RelayExclusion`].
180
    ///
181
    /// Both arguments are required, since every caller should consider them explicitly.
182
    ///
183
    /// The provided usage and exclusion are strict by default.
184
    ///
185
    // TODO: Possibly have this take a struct with named pieces instead, when we
186
    // get a third thing that we want everybody to think about.
187
621588
    pub fn new(usage: RelayUsage, exclusion: RelayExclusion<'a>) -> Self {
188
621588
        Self {
189
621588
            usage: Restr {
190
621588
                restriction: RelayRestriction::for_usage(usage),
191
621588
                strict: true,
192
621588
            },
193
621588
            exclusion: Restr {
194
621588
                restriction: exclusion.into(),
195
621588
                strict: true,
196
621588
            },
197
621588
            other_restrictions: vec![],
198
621588
        }
199
621588
    }
200

            
201
    /// Mark the originally provided `RelayUsage` as flexible.
202
432
    pub fn mark_usage_flexible(&mut self) {
203
432
        self.usage.strict = false;
204
432
    }
205

            
206
    /// Mark the originally provided `RelayExclusion` as flexible.
207
2
    pub fn mark_exclusion_flexible(&mut self) {
208
2
        self.exclusion.strict = false;
209
2
    }
210

            
211
    /// Add a new _strict_ [`RelayRestriction`] to this selector.
212
288
    pub fn push_restriction(&mut self, restriction: RelayRestriction<'a>) {
213
288
        self.push_inner(restriction, true);
214
288
    }
215

            
216
    /// Add a new _flexible_ [`RelayRestriction`] to this selector.
217
    pub fn push_flexible_restriction(&mut self, restriction: RelayRestriction<'a>) {
218
        self.push_inner(restriction, false);
219
    }
220

            
221
    /// Helper to implement adding a new restriction.
222
288
    fn push_inner(&mut self, restriction: RelayRestriction<'a>, strict: bool) {
223
288
        self.other_restrictions.push(Restr {
224
288
            restriction,
225
288
            strict,
226
288
        });
227
288
    }
228

            
229
    /// Return the usage for this selector.
230
920766
    pub fn usage(&self) -> &RelayUsage {
231
920766
        // See invariants for explanation of why these `expects` are safe.
232
920766
        self.usage
233
920766
            .restriction
234
920766
            .as_usage()
235
920766
            .expect("Usage not a usage!?")
236
920766
    }
237

            
238
    /// Return the [`WeightRole`] to use when randomly picking relays according
239
    /// to this selector.
240
622074
    fn weight_role(&self) -> WeightRole {
241
622074
        self.usage().selection_weight_role()
242
622074
    }
243

            
244
    /// Return true if `relay` is one that this selector would pick.
245
    pub fn permits_relay(&self, relay: &tor_netdir::Relay<'_>) -> bool {
246
        self.low_level_predicate_permits_relay(relay)
247
    }
248

            
249
    /// Return an iterator that yields each restriction from this selector,
250
    /// including the usage and exclusion.
251
24183960
    fn all_restrictions(&self) -> impl Iterator<Item = &Restr<'a>> {
252
        use std::iter::once;
253
24183960
        once(&self.usage)
254
24183960
            .chain(once(&self.exclusion))
255
24183960
            .chain(self.other_restrictions.iter())
256
24183960
    }
257

            
258
    /// Return the number of restrictions in this selector,
259
    /// including the usage and exclusion.
260
24794332
    fn n_restrictions(&self) -> usize {
261
24794332
        self.other_restrictions.len() + 2
262
24794332
    }
263

            
264
    /// Try to pick a random relay from `netdir`,
265
    /// according to the rules of this selector.
266
33378
    pub fn select_relay<'s, 'd, R: rand::Rng>(
267
33378
        &'s self,
268
33378
        rng: &mut R,
269
33378
        netdir: &'d NetDir,
270
33378
    ) -> (Option<Relay<'d>>, SelectionInfo<'s>) {
271
33378
        with_possible_relaxation(
272
33378
            self,
273
33396
            |selector| {
274
33396
                let role = selector.weight_role();
275
33396
                let mut fc = FilterCounts::new(selector);
276
1318760
                let relay = netdir.pick_relay(rng, role, |r| selector.relay_usable(r, &mut fc));
277
33396
                (relay, fc)
278
33396
            },
279
33378
            Option::is_some,
280
33378
        )
281
33378
    }
282

            
283
    /// Try to pick `n_relays` distinct random relay from `netdir`,
284
    /// according to the rules of this selector.
285
20205
    pub fn select_n_relays<'s, 'd, R: rand::Rng>(
286
20205
        &'s self,
287
20205
        rng: &mut R,
288
20205
        n_relays: usize,
289
20205
        netdir: &'d NetDir,
290
20205
    ) -> (Vec<Relay<'d>>, SelectionInfo<'s>) {
291
20205
        with_possible_relaxation(
292
20205
            self,
293
20205
            |selector| {
294
20205
                let role = selector.weight_role();
295
20205
                let mut fc = FilterCounts::new(selector);
296
20205
                let relays = netdir
297
416126
                    .pick_n_relays(rng, n_relays, role, |r| selector.relay_usable(r, &mut fc));
298
20205
                (relays, fc)
299
20205
            },
300
20205
            |relays| !relays.is_empty(),
301
20205
        )
302
20205
    }
303

            
304
    /// Check whether a given relay `r` obeys the restrictions of this selector,
305
    /// updating `fc` according to which restrictions (if any) accepted or
306
    /// rejected it.
307
    ///
308
    /// Requires that `fc` has the same length as self.restrictions.
309
    ///
310
    /// This differs from `<Self as RelayPredicate>::permits_relay` in taking
311
    /// `fc` as an argument.
312
24172256
    fn relay_usable(&self, r: &Relay<'_>, fc: &mut FilterCounts) -> bool {
313
24172256
        debug_assert_eq!(self.n_restrictions(), fc.counts.len());
314

            
315
24172256
        self.all_restrictions()
316
24172256
            .zip(fc.counts.iter_mut())
317
41481704
            .all(|(restr, restr_count)| {
318
40806248
                restr_count.count(restr.restriction.low_level_predicate_permits_relay(r))
319
41481704
            })
320
24172256
    }
321

            
322
    /// Return true if this selector has any flexible restrictions.
323
10952
    fn can_relax(&self) -> bool {
324
22068
        self.all_restrictions().any(|restr| !restr.strict)
325
10952
    }
326

            
327
    /// Return a new selector created by relaxing every flexible restriction in
328
    /// this selector.
329
290
    fn relax(&self) -> Self {
330
290
        let new_selector = RelaySelector {
331
290
            usage: self.usage.maybe_relax(),
332
290
            exclusion: self.exclusion.maybe_relax(),
333
290
            other_restrictions: self
334
290
                .other_restrictions
335
290
                .iter()
336
290
                .map(Restr::maybe_relax)
337
290
                .collect(),
338
290
        };
339
290
        debug_assert!(!new_selector.can_relax());
340
290
        new_selector
341
290
    }
342
}
343

            
344
impl<'a> LowLevelRelayPredicate for RelaySelector<'a> {
345
240
    fn low_level_predicate_permits_relay(&self, relay: &tor_netdir::Relay<'_>) -> bool {
346
240
        self.all_restrictions()
347
528
            .all(|r| r.restriction.low_level_predicate_permits_relay(relay))
348
240
    }
349
}
350

            
351
/// Re-run relay selection, relaxing our selector as necessary.
352
///
353
/// This is a helper to implement our relay selection logic.
354
/// We try to run `select` to find one or more random relays
355
/// conforming to `selector`.
356
/// If `ok` says that the result is good (by returning true),
357
/// we return that result.
358
/// Otherwise, we try to _relax_ the selector (if possible),
359
/// and try again.
360
/// If the selector can't be relaxed any further,
361
/// we return the original (not-ok) result.
362
//
363
// TODO: Later, we might want to relax our restrictions one by one,
364
// rather than all at once.
365
53583
fn with_possible_relaxation<'a, SEL, OK, T>(
366
53583
    selector: &'a RelaySelector,
367
53583
    mut select: SEL,
368
53583
    ok: OK,
369
53583
) -> (T, SelectionInfo<'a>)
370
53583
where
371
53583
    SEL: FnMut(&RelaySelector) -> (T, FilterCounts),
372
53583
    OK: Fn(&T) -> bool,
373
53583
{
374
53583
    let (outcome, count_strict) = select(selector);
375
53583
    let succeeded = ok(&outcome);
376
53583
    if succeeded || !selector.can_relax() {
377
53565
        let info = SelectionInfo {
378
53565
            first_try: count_strict,
379
53565
            relaxed_try: None,
380
53565
            succeeded,
381
53565
            in_selection: selector,
382
53565
        };
383
53565
        return (outcome, info);
384
18
    }
385
18
    let relaxed_selector = selector.relax();
386
18
    let (relaxed_outcome, count_relaxed) = select(&relaxed_selector);
387
18
    let info = SelectionInfo {
388
18
        first_try: count_strict,
389
18
        relaxed_try: Some(count_relaxed),
390
18
        succeeded: ok(&relaxed_outcome),
391
18
        in_selection: selector,
392
18
    };
393
18
    (relaxed_outcome, info)
394
53583
}
395

            
396
#[cfg(test)]
397
mod test {
398
    // @@ begin test lint list maintained by maint/add_warning @@
399
    #![allow(clippy::bool_assert_comparison)]
400
    #![allow(clippy::clone_on_copy)]
401
    #![allow(clippy::dbg_macro)]
402
    #![allow(clippy::mixed_attributes_style)]
403
    #![allow(clippy::print_stderr)]
404
    #![allow(clippy::print_stdout)]
405
    #![allow(clippy::single_char_pattern)]
406
    #![allow(clippy::unwrap_used)]
407
    #![allow(clippy::unchecked_duration_subtraction)]
408
    #![allow(clippy::useless_vec)]
409
    #![allow(clippy::needless_pass_by_value)]
410
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
411

            
412
    use std::collections::HashSet;
413

            
414
    use tor_basic_utils::test_rng::testing_rng;
415
    use tor_linkspec::{HasRelayIds, RelayId};
416
    use tor_netdir::{Relay, SubnetConfig};
417

            
418
    use super::*;
419
    use crate::{
420
        testing::{cfg, split_netdir, testnet},
421
        RelaySelectionConfig, TargetPort,
422
    };
423

            
424
    #[test]
425
    fn selector_as_predicate() {
426
        let nd = testnet();
427
        let id_4 = "$0404040404040404040404040404040404040404".parse().unwrap();
428
        let usage = RelayUsage::middle_relay(None);
429
        let exclusion = RelayExclusion::exclude_identities([id_4].into_iter().collect());
430
        let sel = RelaySelector::new(usage.clone(), exclusion.clone());
431

            
432
        let (yes, no) = split_netdir(&nd, &sel);
433
        let p = |r: &Relay<'_>| {
434
            usage.low_level_predicate_permits_relay(r)
435
                && exclusion.low_level_predicate_permits_relay(r)
436
        };
437
        assert!(yes.iter().all(p));
438
        assert!(no.iter().all(|r| !p(r)));
439
    }
440

            
441
    #[test]
442
    fn selector_as_filter() {
443
        let nd = testnet();
444
        let id_4 = "$0404040404040404040404040404040404040404".parse().unwrap();
445
        let usage = RelayUsage::middle_relay(None);
446
        let exclusion = RelayExclusion::exclude_identities([id_4].into_iter().collect());
447
        let sel = RelaySelector::new(usage.clone(), exclusion.clone());
448
        let mut fc = FilterCounts::new(&sel);
449

            
450
        let (yes, _no) = split_netdir(&nd, &sel);
451
        let filtered: Vec<_> = nd
452
            .relays()
453
            .filter(|r| sel.relay_usable(r, &mut fc))
454
            .collect();
455
        assert_eq!(yes.len(), filtered.len());
456

            
457
        let k1: HashSet<_> = yes.iter().map(|r| r.rsa_identity().unwrap()).collect();
458
        let k2: HashSet<_> = filtered.iter().map(|r| r.rsa_identity().unwrap()).collect();
459
        assert_eq!(k1, k2);
460

            
461
        // 6 relays are rejected for not being suitable as a general-purpose middle relay
462
        // (no Fast flag or no stable flag)
463
        assert_eq!(fc.counts[0].n_rejected, 12);
464
        // 1 additional relay is rejected for having id_4.
465
        assert_eq!(fc.counts[1].n_rejected, 1);
466
        // The remainder are accepted.
467
        assert_eq!(fc.counts[1].n_accepted, yes.len());
468
    }
469

            
470
    #[test]
471
    fn selector_pick_random() {
472
        let nd = testnet();
473
        let id_4 = "$0404040404040404040404040404040404040404".parse().unwrap();
474
        let usage = RelayUsage::middle_relay(None);
475
        let exclusion = RelayExclusion::exclude_identities([id_4].into_iter().collect());
476
        let sel = RelaySelector::new(usage.clone(), exclusion.clone());
477

            
478
        let (yes, _no) = split_netdir(&nd, &sel);
479
        let k_yes: HashSet<_> = yes.iter().map(|r| r.rsa_identity().unwrap()).collect();
480
        let p = |r: Relay<'_>| k_yes.contains(r.rsa_identity().unwrap());
481

            
482
        let mut rng = testing_rng();
483
        for _ in 0..50 {
484
            // Select one relay; make sure it is ok.
485
            let (r_rand, si) = sel.select_relay(&mut rng, &nd);
486
            assert!(si.success());
487
            assert!(!si.result_is_relaxed_success());
488
            assert!(p(r_rand.unwrap()));
489

            
490
            // Select 20 random relays; make sure they are distinct and ok.
491
            let (rs_rand, si) = sel.select_n_relays(&mut rng, 20, &nd);
492
            assert_eq!(rs_rand.len(), 20);
493
            assert!(si.success());
494
            assert!(!si.result_is_relaxed_success());
495
            assert!(rs_rand.iter().cloned().all(p));
496
            let k_got: HashSet<_> = rs_rand.iter().map(|r| r.rsa_identity().unwrap()).collect();
497
            assert_eq!(k_got.len(), 20);
498
        }
499
    }
500

            
501
    #[test]
502
    fn selector_report() {
503
        let nd = testnet();
504
        let id_4 = "$0404040404040404040404040404040404040404".parse().unwrap();
505
        let usage = RelayUsage::middle_relay(None);
506
        let exclusion = RelayExclusion::exclude_identities([id_4].into_iter().collect());
507
        let sel = RelaySelector::new(usage.clone(), exclusion.clone());
508

            
509
        let mut rng = testing_rng();
510
        let (_, si) = sel.select_relay(&mut rng, &nd);
511
        assert_eq!(
512
            si.to_string(),
513
            "Success: rejected 12/40 as useless for middle relay; 1/28 as already selected"
514
        );
515

            
516
        // Now try failing.
517
        // (The test network doesn't have ipv6 support.)
518
        let unreachable_port = TargetPort::ipv6(80);
519
        let sel = RelaySelector::new(
520
            RelayUsage::exit_to_all_ports(&cfg(), vec![unreachable_port]),
521
            exclusion.clone(),
522
        );
523
        let (r_none, si) = sel.select_relay(&mut rng, &nd);
524
        assert!(r_none.is_none());
525
        assert_eq!(
526
            si.to_string(),
527
            "Failed: rejected 40/40 as not exiting to desired ports; 0/0 as already selected"
528
        );
529
    }
530

            
531
    #[test]
532
    fn relax() {
533
        let nd = testnet();
534
        let id_4: RelayId = "$0404040404040404040404040404040404040404".parse().unwrap();
535
        let r4 = nd.by_id(&id_4).unwrap();
536
        let usage = RelayUsage::middle_relay(None);
537
        let very_silly_cfg = RelaySelectionConfig {
538
            long_lived_ports: cfg().long_lived_ports,
539
            // This should exclude everyone.
540
            subnet_config: SubnetConfig::new(1, 1),
541
        };
542
        let exclude_relays = vec![r4];
543
        let exclude_everyone =
544
            RelayExclusion::exclude_relays_in_same_family(&very_silly_cfg, exclude_relays);
545

            
546
        let mut sel = RelaySelector::new(usage.clone(), exclude_everyone.clone());
547
        let mut rng = testing_rng();
548
        let (r_none, _) = sel.select_relay(&mut rng, &nd);
549
        assert!(r_none.is_none());
550

            
551
        sel.mark_exclusion_flexible();
552
        let (r_some, si) = sel.select_relay(&mut rng, &nd);
553
        assert!(r_some.is_some());
554
        assert_eq!(si.to_string(), "Failed at first, then succeeded. At first, rejected 12/40 as useless for middle relay; \
555
                                    28/28 as in same family as already selected. \
556
                                    After relaxing requirements, rejected 12/40 as useless for middle relay; \
557
                                    0/28 as in same family as already selected");
558
    }
559
}