1
#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![warn(clippy::cognitive_complexity)]
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_duration_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
45

            
46
// TODO #1645 (either remove this, or decide to have it everywhere)
47
#![cfg_attr(not(all(feature = "full", feature = "experimental")), allow(unused))]
48

            
49
// Glossary:
50
//     Primary guard
51
//     Sample
52
//     confirmed
53
//     filtered
54

            
55
use futures::channel::mpsc;
56
use futures::task::SpawnExt;
57
use serde::{Deserialize, Serialize};
58
use std::collections::HashMap;
59
use std::net::SocketAddr;
60
use std::sync::{Arc, Mutex, Weak};
61
use std::time::{Duration, Instant, SystemTime};
62
#[cfg(feature = "bridge-client")]
63
use tor_error::internal;
64
use tor_linkspec::{OwnedChanTarget, OwnedCircTarget, RelayId, RelayIdSet};
65
use tor_netdir::NetDirProvider;
66
use tor_proto::ClockSkew;
67
use tor_units::BoundedInt32;
68
use tracing::{debug, info, trace, warn};
69

            
70
use tor_config::{define_list_builder_accessors, define_list_builder_helper};
71
use tor_config::{impl_not_auto_value, ReconfigureError};
72
use tor_config::{impl_standard_builder, ExplicitOrAuto};
73
use tor_netdir::{params::NetParameters, NetDir, Relay};
74
use tor_persist::{DynStorageHandle, StateMgr};
75
use tor_rtcompat::Runtime;
76

            
77
#[cfg(feature = "bridge-client")]
78
pub mod bridge;
79
mod config;
80
mod daemon;
81
mod dirstatus;
82
mod err;
83
mod events;
84
pub mod fallback;
85
mod filter;
86
mod guard;
87
mod ids;
88
mod pending;
89
mod sample;
90
mod skew;
91
mod util;
92
#[cfg(feature = "vanguards")]
93
pub mod vanguards;
94

            
95
#[cfg(not(feature = "bridge-client"))]
96
#[path = "bridge_disabled.rs"]
97
pub mod bridge;
98

            
99
#[cfg(any(test, feature = "testing"))]
100
pub use config::testing::TestConfig;
101

            
102
#[cfg(test)]
103
use oneshot_fused_workaround as oneshot;
104

            
105
pub use config::GuardMgrConfig;
106
pub use err::{GuardMgrConfigError, GuardMgrError, PickGuardError};
107
pub use events::ClockSkewEvents;
108
pub use filter::GuardFilter;
109
pub use ids::FirstHopId;
110
pub use pending::{GuardMonitor, GuardStatus, GuardUsable};
111
pub use skew::SkewEstimate;
112

            
113
#[cfg(feature = "vanguards")]
114
#[cfg_attr(docsrs, doc(cfg(feature = "vanguards")))]
115
pub use vanguards::VanguardMgrError;
116

            
117
use pending::{PendingRequest, RequestId};
118
use sample::{GuardSet, Universe, UniverseRef};
119

            
120
use crate::ids::{FirstHopIdInner, GuardId};
121

            
122
use tor_config::ConfigBuildError;
123

            
124
/// A "guard manager" that selects and remembers a persistent set of
125
/// guard nodes.
126
///
127
/// This is a "handle"; clones of it share state.
128
#[derive(Clone)]
129
pub struct GuardMgr<R: Runtime> {
130
    /// An asynchronous runtime object.
131
    ///
132
    /// GuardMgr uses this runtime for timing, timeouts, and spawning
133
    /// tasks.
134
    runtime: R,
135

            
136
    /// Internal state for the guard manager.
137
    inner: Arc<Mutex<GuardMgrInner>>,
138
}
139

            
140
/// Helper type that holds the data used by a [`GuardMgr`].
141
///
142
/// This would just be a [`GuardMgr`], except that it needs to sit inside
143
/// a `Mutex` and get accessed by daemon tasks.
144
struct GuardMgrInner {
145
    /// Last time when marked all of our primary guards as retriable.
146
    ///
147
    /// We keep track of this time so that we can rate-limit
148
    /// these attempts.
149
    last_primary_retry_time: Instant,
150

            
151
    /// Persistent guard manager state.
152
    ///
153
    /// This object remembers one or more persistent set of guards that we can
154
    /// use, along with their relative priorities and statuses.
155
    guards: GuardSets,
156

            
157
    /// The current filter that we're using to decide which guards are
158
    /// supported.
159
    //
160
    // TODO: This field is duplicated in the current active [`GuardSet`]; we
161
    // should fix that.
162
    filter: GuardFilter,
163

            
164
    /// Configuration values derived from the consensus parameters.
165
    ///
166
    /// This is updated whenever the consensus parameters change.
167
    params: GuardParams,
168

            
169
    /// A mpsc channel, used to tell the task running in
170
    /// [`daemon::report_status_events`] about a new event to monitor.
171
    ///
172
    /// This uses an `UnboundedSender` so that we don't have to await
173
    /// while sending the message, which in turn allows the GuardMgr
174
    /// API to be simpler.  The risk, however, is that there's no
175
    /// backpressure in the event that the task running
176
    /// [`daemon::report_status_events`] fails to read from this
177
    /// channel.
178
    ctrl: mpsc::UnboundedSender<daemon::Msg>,
179

            
180
    /// Information about guards that we've given out, but where we have
181
    /// not yet heard whether the guard was successful.
182
    ///
183
    /// Upon leaning whether the guard was successful, the pending
184
    /// requests in this map may be either moved to `waiting`, or
185
    /// discarded.
186
    ///
187
    /// There can be multiple pending requests corresponding to the
188
    /// same guard.
189
    pending: HashMap<RequestId, PendingRequest>,
190

            
191
    /// A list of pending requests for which we have heard that the
192
    /// guard was successful, but we have not yet decided whether the
193
    /// circuit may be used.
194
    ///
195
    /// There can be multiple waiting requests corresponding to the
196
    /// same guard.
197
    waiting: Vec<PendingRequest>,
198

            
199
    /// A list of fallback directories used to access the directory system
200
    /// when no other directory information is yet known.
201
    fallbacks: fallback::FallbackState,
202

            
203
    /// Location in which to store persistent state.
204
    storage: DynStorageHandle<GuardSets>,
205

            
206
    /// A sender object to publish changes in our estimated clock skew.
207
    send_skew: postage::watch::Sender<Option<SkewEstimate>>,
208

            
209
    /// A receiver object to hand out to observers who want to know about
210
    /// changes in our estimated clock skew.
211
    recv_skew: events::ClockSkewEvents,
212

            
213
    /// A netdir provider that we can use for adding new guards when
214
    /// insufficient guards are available.
215
    ///
216
    /// This has to be an Option so it can be initialized from None: at the
217
    /// time a GuardMgr is created, there is no NetDirProvider for it to use.
218
    netdir_provider: Option<Weak<dyn NetDirProvider>>,
219

            
220
    /// A netdir provider that we can use for discovering bridge descriptors.
221
    ///
222
    /// This has to be an Option so it can be initialized from None: at the time
223
    /// a GuardMgr is created, there is no BridgeDescProvider for it to use.
224
    #[cfg(feature = "bridge-client")]
225
    bridge_desc_provider: Option<Weak<dyn bridge::BridgeDescProvider>>,
226

            
227
    /// A list of the bridges that we are configured to use, or "None" if we are
228
    /// not configured to use bridges.
229
    #[cfg(feature = "bridge-client")]
230
    configured_bridges: Option<Arc<[bridge::BridgeConfig]>>,
231
}
232

            
233
/// A selector that tells us which [`GuardSet`] of several is currently in use.
234
80
#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd, strum::EnumIter)]
235
enum GuardSetSelector {
236
    /// The default guard set is currently in use: that's the one that we use
237
    /// when we have no filter installed, or the filter permits most of the
238
    /// guards on the network.
239
    #[default]
240
    Default,
241
    /// A "restrictive" guard set is currently in use: that's the one that we
242
    /// use when we have a filter that excludes a large fraction of the guards
243
    /// on the network.
244
    Restricted,
245
    /// The "bridges" guard set is currently in use: we are selecting our guards
246
    /// from among the universe of configured bridges.
247
    #[cfg(feature = "bridge-client")]
248
    Bridges,
249
}
250

            
251
/// Describes the [`Universe`] that a guard sample should take its guards from.
252
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
253
enum UniverseType {
254
    /// Take information from the network directory.
255
    NetDir,
256
    /// Take information from the configured bridges.
257
    #[cfg(feature = "bridge-client")]
258
    BridgeSet,
259
}
260

            
261
impl GuardSetSelector {
262
    /// Return a description of which [`Universe`] this guard sample should take
263
    /// its guards from.
264
746182
    fn universe_type(&self) -> UniverseType {
265
746182
        match self {
266
746182
            GuardSetSelector::Default | GuardSetSelector::Restricted => UniverseType::NetDir,
267
            #[cfg(feature = "bridge-client")]
268
            GuardSetSelector::Bridges => UniverseType::BridgeSet,
269
        }
270
746182
    }
271
}
272

            
273
/// Persistent state for a guard manager, as serialized to disk.
274
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
275
struct GuardSets {
276
    /// Which set of guards is currently in use?
277
    #[serde(skip)]
278
    active_set: GuardSetSelector,
279

            
280
    /// The default set of guards to use.
281
    ///
282
    /// We use this one when there is no filter, or the filter permits most of the
283
    /// guards on the network.
284
    default: GuardSet,
285

            
286
    /// A guard set to use when we have a restrictive filter.
287
    #[serde(default)]
288
    restricted: GuardSet,
289

            
290
    /// A guard set sampled from our configured bridges.
291
    #[serde(default)]
292
    #[cfg(feature = "bridge-client")]
293
    bridges: GuardSet,
294

            
295
    /// Unrecognized fields, including (possibly) other guard sets.
296
    #[serde(flatten)]
297
    remaining: HashMap<String, tor_persist::JsonValue>,
298
}
299

            
300
/// The key (filename) we use for storing our persistent guard state in the
301
/// `StateMgr`.
302
///
303
/// We used to store this in a different format in a filename called
304
/// "default_guards" (before Arti 0.1.0).
305
const STORAGE_KEY: &str = "guards";
306

            
307
/// A description of which circuits to retire because of a configuration change.
308
///
309
/// TODO(nickm): Eventually we will want to add a "Some" here, to support
310
/// removing only those circuits that correspond to no-longer-usable guards.
311
#[derive(Clone, Debug, Eq, PartialEq)]
312
#[must_use]
313
#[non_exhaustive]
314
pub enum RetireCircuits {
315
    /// There's no need to retire any circuits.
316
    None,
317
    /// All circuits should be retired.
318
    All,
319
}
320

            
321
impl<R: Runtime> GuardMgr<R> {
322
    /// Create a new "empty" guard manager and launch its background tasks.
323
    ///
324
    /// It won't be able to hand out any guards until a [`NetDirProvider`] has
325
    /// been installed.
326
640
    pub fn new<S>(
327
640
        runtime: R,
328
640
        state_mgr: S,
329
640
        config: &impl GuardMgrConfig,
330
640
    ) -> Result<Self, GuardMgrError>
331
640
    where
332
640
        S: StateMgr + Send + Sync + 'static,
333
640
    {
334
640
        let (ctrl, rcv) = mpsc::unbounded();
335
640
        let storage: DynStorageHandle<GuardSets> = state_mgr.create_handle(STORAGE_KEY);
336
        // TODO(nickm): We should do something about the old state in
337
        // `default_guards`.  Probably it would be best to delete it.  We could
338
        // try to migrate it instead, but that's beyond the stability guarantee
339
        // that we're getting at this stage of our (pre-0.1) development.
340
640
        let state = storage.load()?.unwrap_or_default();
341
640

            
342
640
        let (send_skew, recv_skew) = postage::watch::channel();
343
640
        let recv_skew = ClockSkewEvents { inner: recv_skew };
344
640

            
345
640
        let inner = Arc::new(Mutex::new(GuardMgrInner {
346
640
            guards: state,
347
640
            filter: GuardFilter::unfiltered(),
348
640
            last_primary_retry_time: runtime.now(),
349
640
            params: GuardParams::default(),
350
640
            ctrl,
351
640
            pending: HashMap::new(),
352
640
            waiting: Vec::new(),
353
640
            fallbacks: config.fallbacks().into(),
354
640
            storage,
355
640
            send_skew,
356
640
            recv_skew,
357
640
            netdir_provider: None,
358
640
            #[cfg(feature = "bridge-client")]
359
640
            bridge_desc_provider: None,
360
640
            #[cfg(feature = "bridge-client")]
361
640
            configured_bridges: None,
362
640
        }));
363
640
        #[cfg(feature = "bridge-client")]
364
640
        {
365
640
            let mut inner = inner.lock().expect("lock poisoned");
366
            // TODO(nickm): This calls `GuardMgrInner::update`. Will we mind doing so before any
367
            // providers are configured? I think not, but we should make sure.
368
640
            let _: RetireCircuits =
369
640
                inner.replace_bridge_config(config, runtime.wallclock(), runtime.now())?;
370
        }
371
        {
372
640
            let weak_inner = Arc::downgrade(&inner);
373
640
            let rt_clone = runtime.clone();
374
640
            runtime
375
640
                .spawn(daemon::report_status_events(rt_clone, weak_inner, rcv))
376
640
                .map_err(|e| GuardMgrError::from_spawn("guard status event reporter", e))?;
377
        }
378
        {
379
640
            let rt_clone = runtime.clone();
380
640
            let weak_inner = Arc::downgrade(&inner);
381
640
            runtime
382
640
                .spawn(daemon::run_periodic(rt_clone, weak_inner))
383
640
                .map_err(|e| GuardMgrError::from_spawn("periodic guard updater", e))?;
384
        }
385
640
        Ok(GuardMgr { runtime, inner })
386
640
    }
387

            
388
    /// Install a [`NetDirProvider`] for use by this guard manager.
389
    ///
390
    /// It will be used to keep the guards up-to-date with changes from the
391
    /// network directory, and to find new guards when no NetDir is provided to
392
    /// select_guard().
393
    ///
394
    /// TODO: we should eventually return some kind of a task handle from this
395
    /// task, even though it is not strictly speaking periodic.
396
    ///
397
    /// The guardmgr retains only a `Weak` reference to `provider`,
398
    /// `install_netdir_provider` downgrades it on entry,
399
    // TODO add ref to document when https://gitlab.torproject.org/tpo/core/arti/-/issues/624
400
    // is fixed.  Also, maybe take an owned `Weak` to start with.
401
    //
402
    /// # Panics
403
    ///
404
    /// Panics if a [`NetDirProvider`] is already installed.
405
568
    pub fn install_netdir_provider(
406
568
        &self,
407
568
        provider: &Arc<dyn NetDirProvider>,
408
568
    ) -> Result<(), GuardMgrError> {
409
568
        let weak_provider = Arc::downgrade(provider);
410
568
        {
411
568
            let mut inner = self.inner.lock().expect("Poisoned lock");
412
568
            assert!(inner.netdir_provider.is_none());
413
568
            inner.netdir_provider = Some(weak_provider.clone());
414
568
        }
415
568
        let weak_inner = Arc::downgrade(&self.inner);
416
568
        let rt_clone = self.runtime.clone();
417
568
        self.runtime
418
568
            .spawn(daemon::keep_netdir_updated(
419
568
                rt_clone,
420
568
                weak_inner,
421
568
                weak_provider,
422
568
            ))
423
568
            .map_err(|e| GuardMgrError::from_spawn("periodic guard netdir updater", e))?;
424
568
        Ok(())
425
568
    }
426

            
427
    /// Configure a new [`bridge::BridgeDescProvider`] for this [`GuardMgr`].
428
    ///
429
    /// It will be used to learn about changes in the set of available bridge
430
    /// descriptors; we'll inform it whenever our desired set of bridge
431
    /// descriptors changes.
432
    ///
433
    /// TODO: Same todo as in `install_netdir_provider` about task handles.
434
    ///
435
    /// # Panics
436
    ///
437
    /// Panics if a [`bridge::BridgeDescProvider`] is already installed.
438
    #[cfg(feature = "bridge-client")]
439
    pub fn install_bridge_desc_provider(
440
        &self,
441
        provider: &Arc<dyn bridge::BridgeDescProvider>,
442
    ) -> Result<(), GuardMgrError> {
443
        let weak_provider = Arc::downgrade(provider);
444
        {
445
            let mut inner = self.inner.lock().expect("Poisoned lock");
446
            assert!(inner.bridge_desc_provider.is_none());
447
            inner.bridge_desc_provider = Some(weak_provider.clone());
448
        }
449

            
450
        let weak_inner = Arc::downgrade(&self.inner);
451
        let rt_clone = self.runtime.clone();
452
        self.runtime
453
            .spawn(daemon::keep_bridge_descs_updated(
454
                rt_clone,
455
                weak_inner,
456
                weak_provider,
457
            ))
458
            .map_err(|e| GuardMgrError::from_spawn("periodic guard netdir updater", e))?;
459

            
460
        Ok(())
461
    }
462

            
463
    /// Flush our current guard state to the state manager, if there
464
    /// is any unsaved state.
465
20
    pub fn store_persistent_state(&self) -> Result<(), GuardMgrError> {
466
20
        let inner = self.inner.lock().expect("Poisoned lock");
467
20
        trace!("Flushing guard state to disk.");
468
20
        inner.storage.store(&inner.guards)?;
469
20
        Ok(())
470
20
    }
471

            
472
    /// Reload state from the state manager.
473
    ///
474
    /// We only call this method if we _don't_ have the lock on the state
475
    /// files.  If we have the lock, we only want to save.
476
    pub fn reload_persistent_state(&self) -> Result<(), GuardMgrError> {
477
        let mut inner = self.inner.lock().expect("Poisoned lock");
478
        if let Some(new_guards) = inner.storage.load()? {
479
            inner.replace_guards_with(new_guards, self.runtime.wallclock(), self.runtime.now());
480
        }
481
        Ok(())
482
    }
483

            
484
    /// Switch from having an unowned persistent state to having an owned one.
485
    ///
486
    /// Requires that we hold the lock on the state files.
487
    pub fn upgrade_to_owned_persistent_state(&self) -> Result<(), GuardMgrError> {
488
        let mut inner = self.inner.lock().expect("Poisoned lock");
489
        debug_assert!(inner.storage.can_store());
490
        let new_guards = inner.storage.load()?.unwrap_or_default();
491
        let wallclock = self.runtime.wallclock();
492
        let now = self.runtime.now();
493
        inner.replace_guards_with(new_guards, wallclock, now);
494
        Ok(())
495
    }
496

            
497
    /// Return true if `netdir` has enough information to safely become our new netdir.
498
    pub fn netdir_is_sufficient(&self, netdir: &NetDir) -> bool {
499
        let mut inner = self.inner.lock().expect("Poisoned lock");
500
        if inner.guards.active_set.universe_type() != UniverseType::NetDir {
501
            // If we aren't using the netdir, this isn't something we want to look at.
502
            return true;
503
        }
504
        inner
505
            .guards
506
            .active_guards_mut()
507
            .n_primary_without_id_info_in(netdir)
508
            == 0
509
    }
510

            
511
    /// Mark every guard as potentially retriable, regardless of how recently we
512
    /// failed to connect to it.
513
    pub fn mark_all_guards_retriable(&self) {
514
        let mut inner = self.inner.lock().expect("Poisoned lock");
515
        inner.guards.active_guards_mut().mark_all_guards_retriable();
516
    }
517

            
518
    /// Configure this guardmgr to use a fixed [`NetDir`] instead of a provider.
519
    ///
520
    /// This function is for testing only, and is exclusive with
521
    /// `install_netdir_provider`.
522
    ///
523
    /// # Panics
524
    ///
525
    /// Panics if any [`NetDirProvider`] has already been installed.
526
    #[cfg(any(test, feature = "testing"))]
527
96
    pub fn install_test_netdir(&self, netdir: &NetDir) {
528
        use tor_netdir::testprovider::TestNetDirProvider;
529
96
        let wallclock = self.runtime.wallclock();
530
96
        let now = self.runtime.now();
531
96
        let netdir_provider: Arc<dyn NetDirProvider> =
532
96
            Arc::new(TestNetDirProvider::from(netdir.clone()));
533
96
        self.install_netdir_provider(&netdir_provider)
534
96
            .expect("Couldn't install testing network provider");
535
96

            
536
96
        let mut inner = self.inner.lock().expect("Poisoned lock");
537
96
        inner.update(wallclock, now);
538
96
    }
539

            
540
    /// Replace the configuration in this `GuardMgr` with `config`.
541
2
    pub fn reconfigure(
542
2
        &self,
543
2
        config: &impl GuardMgrConfig,
544
2
    ) -> Result<RetireCircuits, ReconfigureError> {
545
2
        let mut inner = self.inner.lock().expect("Poisoned lock");
546
2
        // Change the set of configured fallbacks.
547
2
        {
548
2
            let mut fallbacks: fallback::FallbackState = config.fallbacks().into();
549
2
            std::mem::swap(&mut inner.fallbacks, &mut fallbacks);
550
2
            inner.fallbacks.take_status_from(fallbacks);
551
2
        }
552
2
        // If we are built to use bridges, change the bridge configuration.
553
2
        #[cfg(feature = "bridge-client")]
554
2
        {
555
2
            let wallclock = self.runtime.wallclock();
556
2
            let now = self.runtime.now();
557
2
            Ok(inner.replace_bridge_config(config, wallclock, now)?)
558
        }
559
        // If we are built to use bridges, change the bridge configuration.
560
        #[cfg(not(feature = "bridge-client"))]
561
        {
562
            Ok(RetireCircuits::None)
563
        }
564
2
    }
565

            
566
    /// Replace the current [`GuardFilter`] used by this `GuardMgr`.
567
    // TODO should this be part of the config?
568
40
    pub fn set_filter(&self, filter: GuardFilter) {
569
40
        let wallclock = self.runtime.wallclock();
570
40
        let now = self.runtime.now();
571
40
        let mut inner = self.inner.lock().expect("Poisoned lock");
572
40
        inner.set_filter(filter, wallclock, now);
573
40
    }
574

            
575
    /// Select a guard for a given [`GuardUsage`].
576
    ///
577
    /// On success, we return a [`FirstHop`] object to identify which
578
    /// guard we have picked, a [`GuardMonitor`] object that the
579
    /// caller can use to report whether its attempt to use the guard
580
    /// succeeded or failed, and a [`GuardUsable`] future that the
581
    /// caller can use to decide whether a circuit built through the
582
    /// guard is actually safe to use.
583
    ///
584
    /// That last point is important: It's okay to build a circuit
585
    /// through the guard returned by this function, but you can't
586
    /// actually use it for traffic unless the [`GuardUsable`] future
587
    /// yields "true".
588
17084
    pub fn select_guard(
589
17084
        &self,
590
17084
        usage: GuardUsage,
591
17084
    ) -> Result<(FirstHop, GuardMonitor, GuardUsable), PickGuardError> {
592
17084
        let now = self.runtime.now();
593
17084
        let wallclock = self.runtime.wallclock();
594
17084

            
595
17084
        let mut inner = self.inner.lock().expect("Poisoned lock");
596
17084

            
597
17084
        // (I am not 100% sure that we need to consider_all_retries here, but
598
17084
        // it should _probably_ not hurt.)
599
17084
        inner.guards.active_guards_mut().consider_all_retries(now);
600

            
601
17084
        let (origin, guard) = inner.select_guard_with_expand(&usage, now, wallclock)?;
602
17084
        trace!(?guard, ?usage, "Guard selected");
603

            
604
17084
        let (usable, usable_sender) = if origin.usable_immediately() {
605
17068
            (GuardUsable::new_usable_immediately(), None)
606
        } else {
607
16
            let (u, snd) = GuardUsable::new_uncertain();
608
16
            (u, Some(snd))
609
        };
610
17084
        let request_id = pending::RequestId::next();
611
17084
        let ctrl = inner.ctrl.clone();
612
17084
        let monitor = GuardMonitor::new(request_id, ctrl);
613

            
614
        // Note that the network can be down even if all the primary guards
615
        // are not yet marked as unreachable.  But according to guard-spec we
616
        // don't want to acknowledge the net as down before that point, since
617
        // we don't mark all the primary guards as retriable unless
618
        // we've been forced to non-primary guards.
619
17084
        let net_has_been_down =
620
17084
            if let Some(duration) = tor_proto::time_since_last_incoming_traffic() {
621
                inner
622
                    .guards
623
                    .active_guards_mut()
624
                    .all_primary_guards_are_unreachable()
625
                    && duration >= inner.params.internet_down_timeout
626
            } else {
627
                // TODO: Is this the correct behavior in this case?
628
17084
                false
629
            };
630

            
631
17084
        let pending_request = pending::PendingRequest::new(
632
17084
            guard.first_hop_id(),
633
17084
            usage,
634
17084
            usable_sender,
635
17084
            net_has_been_down,
636
17084
        );
637
17084
        inner.pending.insert(request_id, pending_request);
638
17084

            
639
17084
        match &guard.sample {
640
17084
            Some(sample) => {
641
17084
                let guard_id = GuardId::from_relay_ids(&guard);
642
17084
                inner
643
17084
                    .guards
644
17084
                    .guards_mut(sample)
645
17084
                    .record_attempt(&guard_id, now);
646
17084
            }
647
            None => {
648
                // We don't record attempts for fallbacks; we only care when
649
                // they have failed.
650
            }
651
        }
652

            
653
17084
        Ok((guard, monitor, usable))
654
17084
    }
655

            
656
    /// Record that _after_ we built a circuit with a guard, something described
657
    /// in `external_failure` went wrong with it.
658
8
    pub fn note_external_failure<T>(&self, identity: &T, external_failure: ExternalActivity)
659
8
    where
660
8
        T: tor_linkspec::HasRelayIds + ?Sized,
661
8
    {
662
8
        let now = self.runtime.now();
663
8
        let mut inner = self.inner.lock().expect("Poisoned lock");
664
8
        let ids = inner.lookup_ids(identity);
665
16
        for id in ids {
666
8
            match &id.0 {
667
8
                FirstHopIdInner::Guard(sample, id) => {
668
8
                    inner
669
8
                        .guards
670
8
                        .guards_mut(sample)
671
8
                        .record_failure(id, Some(external_failure), now);
672
8
                }
673
                FirstHopIdInner::Fallback(id) => {
674
                    if external_failure == ExternalActivity::DirCache {
675
                        inner.fallbacks.note_failure(id, now);
676
                    }
677
                }
678
            }
679
        }
680
8
    }
681

            
682
    /// Record that _after_ we built a circuit with a guard, some activity
683
    /// described in `external_activity` was successful with it.
684
8
    pub fn note_external_success<T>(&self, identity: &T, external_activity: ExternalActivity)
685
8
    where
686
8
        T: tor_linkspec::HasRelayIds + ?Sized,
687
8
    {
688
8
        let mut inner = self.inner.lock().expect("Poisoned lock");
689
8

            
690
8
        inner.record_external_success(identity, external_activity, self.runtime.wallclock());
691
8
    }
692

            
693
    /// Return a stream of events about our estimated clock skew; these events
694
    /// are `None` when we don't have enough information to make an estimate,
695
    /// and `Some(`[`SkewEstimate`]`)` otherwise.
696
    ///
697
    /// Note that this stream can be lossy: if the estimate changes more than
698
    /// one before you read from the stream, you might only get the most recent
699
    /// update.
700
8
    pub fn skew_events(&self) -> ClockSkewEvents {
701
8
        let inner = self.inner.lock().expect("Poisoned lock");
702
8
        inner.recv_skew.clone()
703
8
    }
704

            
705
    /// Ensure that the message queue is flushed before proceeding to
706
    /// the next step.  Used for testing.
707
    #[cfg(test)]
708
48
    async fn flush_msg_queue(&self) {
709
48
        let (snd, rcv) = oneshot::channel();
710
48
        let pingmsg = daemon::Msg::Ping(snd);
711
48
        {
712
48
            let inner = self.inner.lock().expect("Poisoned lock");
713
48
            inner
714
48
                .ctrl
715
48
                .unbounded_send(pingmsg)
716
48
                .expect("Guard observer task exited prematurely.");
717
48
        }
718
48
        let _ = rcv.await;
719
48
    }
720
}
721

            
722
/// An activity that can succeed or fail, and whose success or failure can be
723
/// attributed to a guard.
724
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
725
#[non_exhaustive]
726
pub enum ExternalActivity {
727
    /// The activity of using the guard as a directory cache.
728
    DirCache,
729
}
730

            
731
impl GuardSets {
732
    /// Return a reference to the currently active set of guards.
733
    ///
734
    /// (That's easy enough for now, since there is never more than one set of
735
    /// guards.  But eventually that will change, as we add support for more
736
    /// complex filter types, and for bridge relays. Those will use separate
737
    /// `GuardSet` instances, and this accessor will choose the right one.)
738
8247
    fn active_guards(&self) -> &GuardSet {
739
8247
        self.guards(&self.active_set)
740
8247
    }
741

            
742
    /// Return the set of guards corresponding to the provided selector.
743
375783
    fn guards(&self, selector: &GuardSetSelector) -> &GuardSet {
744
375783
        match selector {
745
375735
            GuardSetSelector::Default => &self.default,
746
32
            GuardSetSelector::Restricted => &self.restricted,
747
            #[cfg(feature = "bridge-client")]
748
16
            GuardSetSelector::Bridges => &self.bridges,
749
        }
750
375783
    }
751

            
752
    /// Return a mutable reference to the currently active set of guards.
753
705134
    fn active_guards_mut(&mut self) -> &mut GuardSet {
754
705134
        self.guards_mut(&self.active_set.clone())
755
705134
    }
756

            
757
    /// Return a mutable reference to the set of guards corresponding to the
758
    /// provided selector.
759
1391935
    fn guards_mut(&mut self, selector: &GuardSetSelector) -> &mut GuardSet {
760
1391935
        match selector {
761
1391891
            GuardSetSelector::Default => &mut self.default,
762
44
            GuardSetSelector::Restricted => &mut self.restricted,
763
            #[cfg(feature = "bridge-client")]
764
            GuardSetSelector::Bridges => &mut self.bridges,
765
        }
766
1391935
    }
767

            
768
    /// Update all non-persistent state for the guards in this object with the
769
    /// state in `other`.
770
    fn copy_status_from(&mut self, mut other: GuardSets) {
771
        use strum::IntoEnumIterator;
772
        for sample in GuardSetSelector::iter() {
773
            self.guards_mut(&sample)
774
                .copy_ephemeral_status_into_newly_loaded_state(std::mem::take(
775
                    other.guards_mut(&sample),
776
                ));
777
        }
778
        self.active_set = other.active_set;
779
    }
780
}
781

            
782
impl GuardMgrInner {
783
    /// Look up the latest [`NetDir`] (if there is one) from our
784
    /// [`NetDirProvider`] (if we have one).
785
25924
    fn timely_netdir(&self) -> Option<Arc<NetDir>> {
786
25924
        self.netdir_provider
787
25924
            .as_ref()
788
25924
            .and_then(Weak::upgrade)
789
26250
            .and_then(|np| np.timely_netdir().ok())
790
25924
    }
791

            
792
    /// Look up the latest [`BridgeDescList`](bridge::BridgeDescList) (if there
793
    /// is one) from our [`BridgeDescProvider`](bridge::BridgeDescProvider) (if
794
    /// we have one).
795
    #[cfg(feature = "bridge-client")]
796
    fn latest_bridge_desc_list(&self) -> Option<Arc<bridge::BridgeDescList>> {
797
        self.bridge_desc_provider
798
            .as_ref()
799
            .and_then(Weak::upgrade)
800
            .map(|bp| bp.bridges())
801
    }
802

            
803
    /// Run a function that takes `&mut self` and an optional NetDir.
804
    ///
805
    /// We try to use the netdir from our [`NetDirProvider`] (if we have one).
806
    /// Therefore, although its _parameters_ are suitable for every
807
    /// [`GuardSet`], its _contents_ might not be. For those, call
808
    /// [`with_opt_universe`](Self::with_opt_universe) instead.
809
    //
810
    // This function exists to handle the lifetime mess where sometimes the
811
    // resulting NetDir will borrow from `netdir`, and sometimes it will borrow
812
    // from an Arc returned by `self.latest_netdir()`.
813
8247
    fn with_opt_netdir<F, T>(&mut self, func: F) -> T
814
8247
    where
815
8247
        F: FnOnce(&mut Self, Option<&NetDir>) -> T,
816
8247
    {
817
8247
        if let Some(nd) = self.timely_netdir() {
818
1188
            func(self, Some(nd.as_ref()))
819
        } else {
820
7059
            func(self, None)
821
        }
822
8247
    }
823

            
824
    /// Return the latest `BridgeSet` based on our `BridgeDescProvider` and our
825
    /// configured bridges.
826
    ///
827
    /// Returns `None` if we are not configured to use bridges.
828
    #[cfg(feature = "bridge-client")]
829
    fn latest_bridge_set(&self) -> Option<bridge::BridgeSet> {
830
        let bridge_config = self.configured_bridges.as_ref()?.clone();
831
        let bridge_descs = self.latest_bridge_desc_list();
832
        Some(bridge::BridgeSet::new(bridge_config, bridge_descs))
833
    }
834

            
835
    /// Run a function that takes `&mut self` and an optional [`UniverseRef`].
836
    ///
837
    /// We try to get a universe from the appropriate source for the current
838
    /// active guard set.
839
17677
    fn with_opt_universe<F, T>(&mut self, func: F) -> T
840
17677
    where
841
17677
        F: FnOnce(&mut Self, Option<&UniverseRef>) -> T,
842
17677
    {
843
17677
        // TODO: it might be nice to make `func` take an GuardSet and a set of
844
17677
        // parameters, so we can't get the active set wrong. Doing that will
845
17677
        // require a fair amount of refactoring so that the borrow checker is
846
17677
        // happy, however.
847
17677
        match self.guards.active_set.universe_type() {
848
            UniverseType::NetDir => {
849
17677
                if let Some(nd) = self.timely_netdir() {
850
10618
                    func(self, Some(&UniverseRef::NetDir(nd)))
851
                } else {
852
7059
                    func(self, None)
853
                }
854
            }
855
            #[cfg(feature = "bridge-client")]
856
            UniverseType::BridgeSet => func(
857
                self,
858
                self.latest_bridge_set()
859
                    .map(UniverseRef::BridgeSet)
860
                    .as_ref(),
861
            ),
862
        }
863
17677
    }
864

            
865
    /// Update the status of all guards in the active set, based on the passage
866
    /// of time, our configuration, and the relevant Universe for our active
867
    /// set.
868
8247
    fn update(&mut self, wallclock: SystemTime, now: Instant) {
869
8490
        self.with_opt_netdir(|this, netdir| {
870
8247
            // Here we update our parameters from the latest NetDir, and check
871
8247
            // whether we need to change to a (non)-restrictive GuardSet based
872
8247
            // on those parameters and our configured filter.
873
8247
            //
874
8247
            // This uses a NetDir unconditionally, since we always want to take
875
8247
            // the network parameters our parameters from the consensus even if
876
8247
            // the guards themselves are from a BridgeSet.
877
8247
            this.update_active_set_params_and_filter(netdir);
878
8490
        });
879
8490
        self.with_opt_universe(|this, univ| {
880
8247
            // Now we update the set of guards themselves based on the
881
8247
            // Universe, which is either the latest NetDir, or the latest
882
8247
            // BridgeSet—depending on what the GuardSet wants.
883
8247
            Self::update_guardset_internal(
884
8247
                &this.params,
885
8247
                wallclock,
886
8247
                this.guards.active_set.universe_type(),
887
8247
                this.guards.active_guards_mut(),
888
8247
                univ,
889
8247
            );
890
8247
            #[cfg(feature = "bridge-client")]
891
8247
            this.update_desired_descriptors(now);
892
8247
            #[cfg(not(feature = "bridge-client"))]
893
8247
            let _ = now;
894
8490
        });
895
8247
    }
896

            
897
    /// Replace our bridge configuration with the one from `new_config`.
898
    #[cfg(feature = "bridge-client")]
899
642
    fn replace_bridge_config(
900
642
        &mut self,
901
642
        new_config: &impl GuardMgrConfig,
902
642
        wallclock: SystemTime,
903
642
        now: Instant,
904
642
    ) -> Result<RetireCircuits, GuardMgrConfigError> {
905
642
        match (&self.configured_bridges, new_config.bridges_enabled()) {
906
            (None, false) => {
907
642
                assert_ne!(
908
642
                    self.guards.active_set.universe_type(),
909
642
                    UniverseType::BridgeSet
910
642
                );
911
642
                return Ok(RetireCircuits::None); // nothing to do
912
            }
913
            (_, true) if !self.storage.can_store() => {
914
                // TODO: Ideally we would try to upgrade, obtaining an exclusive lock,
915
                // but `StorageHandle` currently lacks a method for that.
916
                return Err(GuardMgrConfigError::NoLock("bridges configured".into()));
917
            }
918
            (Some(current_bridges), true) if new_config.bridges() == current_bridges.as_ref() => {
919
                assert_eq!(
920
                    self.guards.active_set.universe_type(),
921
                    UniverseType::BridgeSet
922
                );
923
                return Ok(RetireCircuits::None); // nothing to do.
924
            }
925
            (_, true) => {
926
                self.configured_bridges = Some(new_config.bridges().into());
927
                self.guards.active_set = GuardSetSelector::Bridges;
928
            }
929
            (_, false) => {
930
                self.configured_bridges = None;
931
                self.guards.active_set = GuardSetSelector::Default;
932
            }
933
        }
934

            
935
        // If we have gotten here, we have changed the set of bridges, changed
936
        // which set is active, or changed them both.  We need to make sure that
937
        // our `GuardSet` object is up-to-date with our configuration.
938
        self.update(wallclock, now);
939

            
940
        // We also need to tell the caller that its circuits are no good any
941
        // more.
942
        //
943
        // TODO(nickm): Someday we can do this more judiciously by retuning
944
        // "Some" in the case where we're still using bridges but our new bridge
945
        // set contains different elements; see comment on RetireCircuits.
946
        //
947
        // TODO(nickm): We could also safely return RetireCircuits::None if we
948
        // are using bridges, and our new bridge list is a superset of the older
949
        // one.
950
        Ok(RetireCircuits::All)
951
642
    }
952

            
953
    /// Update our parameters, our selection (based on network parameters and
954
    /// configuration), and make sure the active GuardSet has the right
955
    /// configuration itself.
956
    ///
957
    /// We should call this whenever the NetDir's parameters change, or whenever
958
    /// our filter changes.  We do not need to call it for new elements arriving
959
    /// in our Universe, since those do not affect anything here.
960
    ///
961
    /// We should also call this whenever a new GuardSet becomes active for any
962
    /// reason _other_ than just having called this function.
963
    ///
964
    /// (This function is only invoked from `update`, which should be called
965
    /// under the above circumstances.)
966
8247
    fn update_active_set_params_and_filter(&mut self, netdir: Option<&NetDir>) {
967
        // Set the parameters.  These always come from the NetDir, even if this
968
        // is a bridge set.
969
8247
        if let Some(netdir) = netdir {
970
1188
            match GuardParams::try_from(netdir.params()) {
971
1188
                Ok(params) => self.params = params,
972
                Err(e) => warn!("Unusable guard parameters from consensus: {}", e),
973
            }
974

            
975
1188
            self.select_guard_set_based_on_filter(netdir);
976
7059
        }
977

            
978
        // Change the filter, if it doesn't match what the guards have.
979
        //
980
        // TODO(nickm): We could use a "dirty" flag or something to decide
981
        // whether we need to call set_filter, if this comparison starts to show
982
        // up in profiles.
983
8247
        if self.guards.active_guards().filter() != &self.filter {
984
672
            let restrictive = self.guards.active_set == GuardSetSelector::Restricted;
985
672
            self.guards
986
672
                .active_guards_mut()
987
672
                .set_filter(self.filter.clone(), restrictive);
988
7575
        }
989
8247
    }
990

            
991
    /// Update the status of every guard in `active_guards`, and expand it as
992
    /// needed.
993
    ///
994
    /// This function doesn't take `&self`, to make sure that we are only
995
    /// affecting a single `GuardSet`, and to avoid confusing the borrow
996
    /// checker.
997
    ///
998
    /// We should call this whenever the contents of the universe have changed.
999
    ///
    /// We should also call this whenever a new GuardSet becomes active.
17677
    fn update_guardset_internal<U: Universe>(
17677
        params: &GuardParams,
17677
        now: SystemTime,
17677
        universe_type: UniverseType,
17677
        active_guards: &mut GuardSet,
17677
        universe: Option<&U>,
17677
    ) -> ExtendedStatus {
17677
        // Expire guards.  Do that early, in case doing so makes it clear that
17677
        // we need to grab more guards or mark others as primary.
17677
        active_guards.expire_old_guards(params, now);
17677
        let extended = if let Some(universe) = universe {
            // TODO: This check here may be completely unnecessary. I inserted
            // it back in 5ac0fcb7ef603e0d14 because I was originally concerned
            // it might be undesirable to list a primary guard as "missing dir
            // info" (and therefore unusable) if we were expecting to get its
            // microdescriptor "very soon."
            //
            // But due to the other check in `netdir_is_sufficient`, we
            // shouldn't be installing a netdir until it has microdescs for all
            // of the (non-bridge) primary guards that it lists. - nickm
10618
            if active_guards.n_primary_without_id_info_in(universe) > 0
                && universe_type == UniverseType::NetDir
            {
                // We are missing the information from a NetDir needed to see
                // whether our primary guards are listed, so we shouldn't update
                // our guard status.
                //
                // We don't want to do this check if we are using bridges, since
                // a missing bridge descriptor is not guaranteed to temporary
                // problem in the same way that a missing microdescriptor is.
                // (When a bridge desc is missing, the bridge could be down or
                // unreachable, and nobody else can help us. But if a microdesc
                // is missing, we just need to find a cache that has it.)
                return ExtendedStatus::No;
10618
            }
10618
            active_guards.update_status_from_dir(universe);
10618
            active_guards.extend_sample_as_needed(now, params, universe)
        } else {
7059
            ExtendedStatus::No
        };
17677
        active_guards.select_primary_guards(params);
17677

            
17677
        extended
17677
    }
    /// If using bridges, tell the BridgeDescProvider which descriptors we want.
    /// We need to check this *after* we select our primary guards.
    #[cfg(feature = "bridge-client")]
8247
    fn update_desired_descriptors(&mut self, now: Instant) {
8247
        if self.guards.active_set.universe_type() != UniverseType::BridgeSet {
8247
            return;
        }
        let provider = self.bridge_desc_provider.as_ref().and_then(Weak::upgrade);
        let bridge_set = self.latest_bridge_set();
        if let (Some(provider), Some(bridge_set)) = (provider, bridge_set) {
            let desired: Vec<_> = self
                .guards
                .active_guards()
                .descriptors_to_request(now, &self.params)
                .into_iter()
                .flat_map(|guard| bridge_set.bridge_by_guard(guard))
                .cloned()
                .collect();
            provider.set_bridges(&desired);
        }
8247
    }
    /// Replace the active guard state with `new_state`, preserving
    /// non-persistent state for any guards that are retained.
    fn replace_guards_with(
        &mut self,
        mut new_guards: GuardSets,
        wallclock: SystemTime,
        now: Instant,
    ) {
        std::mem::swap(&mut self.guards, &mut new_guards);
        self.guards.copy_status_from(new_guards);
        self.update(wallclock, now);
    }
    /// Update which guard set is active based on the current filter and the
    /// provided netdir.
    ///
    /// After calling this function, the new guard set's filter may be
    /// out-of-date: be sure to call `set_filter` as appropriate.
1188
    fn select_guard_set_based_on_filter(&mut self, netdir: &NetDir) {
        // In general, we'd like to use the restricted set if we're under the
        // threshold, and the default set if we're over the threshold.  But if
        // we're sitting close to the threshold, we want to avoid flapping back
        // and forth, so we only change when we're more than 5% "off" from
        // whatever our current setting is.
        //
        // (See guard-spec section 2 for more information.)
1188
        let offset = match self.guards.active_set {
1188
            GuardSetSelector::Default => -0.05,
            GuardSetSelector::Restricted => 0.05,
            // If we're using bridges, then we don't switch between the other guard sets based on on the filter at all.
            #[cfg(feature = "bridge-client")]
            GuardSetSelector::Bridges => return,
        };
1188
        let frac_permitted = self.filter.frac_bw_permitted(netdir);
1188
        let threshold = self.params.filter_threshold + offset;
1188
        let new_choice = if frac_permitted < threshold {
8
            GuardSetSelector::Restricted
        } else {
1180
            GuardSetSelector::Default
        };
1188
        if new_choice != self.guards.active_set {
8
            info!(
                "Guard selection changed; we are now using the {:?} guard set",
                &new_choice
            );
8
            self.guards.active_set = new_choice;
8

            
8
            if frac_permitted < self.params.extreme_threshold {
                warn!(
                      "The number of guards permitted is smaller than the recommended minimum of {:.0}%.",
                      self.params.extreme_threshold * 100.0,
                );
8
            }
1180
        }
1188
    }
    /// Mark all of our primary guards as retriable, if we haven't done
    /// so since long enough before `now`.
    ///
    /// We want to call this function whenever a guard attempt succeeds,
    /// if the internet seemed to be down when the guard attempt was
    /// first launched.
    fn maybe_retry_primary_guards(&mut self, now: Instant) {
        // We don't actually want to mark our primary guards as
        // retriable more than once per internet_down_timeout: after
        // the first time, we would just be noticing the same "coming
        // back online" event more than once.
        let interval = self.params.internet_down_timeout;
        if self.last_primary_retry_time + interval <= now {
            debug!("Successfully reached a guard after a while off the internet; marking all primary guards retriable.");
            self.guards
                .active_guards_mut()
                .mark_primary_guards_retriable();
            self.last_primary_retry_time = now;
        }
    }
    /// Replace the current GuardFilter with `filter`.
664
    fn set_filter(&mut self, filter: GuardFilter, wallclock: SystemTime, now: Instant) {
664
        self.filter = filter;
664
        self.update(wallclock, now);
664
    }
    /// Called when the circuit manager reports (via [`GuardMonitor`]) that
    /// a guard succeeded or failed.
    ///
    /// Changes the guard's status as appropriate, and updates the pending
    /// request as needed.
    #[allow(clippy::cognitive_complexity)]
16568
    pub(crate) fn handle_msg(
16568
        &mut self,
16568
        request_id: RequestId,
16568
        status: GuardStatus,
16568
        skew: Option<ClockSkew>,
16568
        runtime: &impl tor_rtcompat::SleepProvider,
16568
    ) {
16568
        if let Some(mut pending) = self.pending.remove(&request_id) {
            // If there was a pending request matching this RequestId, great!
16568
            let guard_id = pending.guard_id();
16568
            trace!(?guard_id, ?status, "Received report of guard status");
            // First, handle the skew report (if any)
16568
            if let Some(skew) = skew {
                let now = runtime.now();
                let observation = skew::SkewObservation { skew, when: now };
                match &guard_id.0 {
                    FirstHopIdInner::Guard(_, id) => {
                        self.guards.active_guards_mut().record_skew(id, observation);
                    }
                    FirstHopIdInner::Fallback(id) => {
                        self.fallbacks.note_skew(id, observation);
                    }
                }
                // TODO: We call this whenever we receive an observed clock
                // skew. That's not the perfect timing for two reasons.  First
                // off, it might be too frequent: it does an O(n) calculation,
                // which isn't ideal.  Second, it might be too infrequent: after
                // an hour has passed, a given observation won't be up-to-date
                // any more, and we might want to recalculate the skew
                // accordingly.
                self.update_skew(now);
16568
            }
16568
            match (status, &guard_id.0) {
                (GuardStatus::Failure, FirstHopIdInner::Fallback(id)) => {
                    // We used a fallback, and we weren't able to build a circuit through it.
                    self.fallbacks.note_failure(id, runtime.now());
                }
                (_, FirstHopIdInner::Fallback(_)) => {
                    // We don't record any other kind of circuit activity if we
                    // took the entry from the fallback list.
                }
504
                (GuardStatus::Success, FirstHopIdInner::Guard(sample, id)) => {
504
                    // If we had gone too long without any net activity when we
504
                    // gave out this guard, and now we're seeing a circuit
504
                    // succeed, tell the primary guards that they might be
504
                    // retriable.
504
                    if pending.net_has_been_down() {
                        self.maybe_retry_primary_guards(runtime.now());
504
                    }
                    // The guard succeeded.  Tell the GuardSet.
504
                    self.guards.guards_mut(sample).record_success(
504
                        id,
504
                        &self.params,
504
                        None,
504
                        runtime.wallclock(),
504
                    );
                    // Either tell the request whether the guard is
                    // usable, or schedule it as a "waiting" request.
504
                    if let Some(usable) = self.guard_usability_status(&pending, runtime.now()) {
504
                        trace!(?guard_id, usable, "Known usability status");
504
                        pending.reply(usable);
                    } else {
                        // This is the one case where we can't use the
                        // guard yet.
                        trace!(?guard_id, "Not able to answer right now");
                        pending.mark_waiting(runtime.now());
                        self.waiting.push(pending);
                    }
                }
24
                (GuardStatus::Failure, FirstHopIdInner::Guard(sample, id)) => {
24
                    self.guards
24
                        .guards_mut(sample)
24
                        .record_failure(id, None, runtime.now());
24
                    pending.reply(false);
24
                }
16040
                (GuardStatus::AttemptAbandoned, FirstHopIdInner::Guard(sample, id)) => {
16040
                    self.guards.guards_mut(sample).record_attempt_abandoned(id);
16040
                    pending.reply(false);
16040
                }
                (GuardStatus::Indeterminate, FirstHopIdInner::Guard(sample, id)) => {
                    self.guards
                        .guards_mut(sample)
                        .record_indeterminate_result(id);
                    pending.reply(false);
                }
            };
        } else {
            warn!(
                "Got a status {:?} for a request {:?} that wasn't pending",
                status, request_id
            );
        }
        // We might need to update the primary guards based on changes in the
        // status of guards above.
16568
        self.guards
16568
            .active_guards_mut()
16568
            .select_primary_guards(&self.params);
16568

            
16568
        // Some waiting request may just have become ready (usable or
16568
        // not); we need to give them the information they're waiting
16568
        // for.
16568
        self.expire_and_answer_pending_requests(runtime.now());
16568
    }
    /// Helper to implement `GuardMgr::note_external_success()`.
    ///
    /// (This has to be a separate function so that we can borrow params while
    /// we have `mut self` borrowed.)
8
    fn record_external_success<T>(
8
        &mut self,
8
        identity: &T,
8
        external_activity: ExternalActivity,
8
        now: SystemTime,
8
    ) where
8
        T: tor_linkspec::HasRelayIds + ?Sized,
8
    {
8
        for id in self.lookup_ids(identity) {
8
            match &id.0 {
8
                FirstHopIdInner::Guard(sample, id) => {
8
                    self.guards.guards_mut(sample).record_success(
8
                        id,
8
                        &self.params,
8
                        Some(external_activity),
8
                        now,
8
                    );
8
                }
                FirstHopIdInner::Fallback(id) => {
                    if external_activity == ExternalActivity::DirCache {
                        self.fallbacks.note_success(id);
                    }
                }
            }
        }
8
    }
    /// Return an iterator over all of the clock skew observations we've made
    /// for guards or fallbacks.
    fn skew_observations(&self) -> impl Iterator<Item = &skew::SkewObservation> {
        self.fallbacks
            .skew_observations()
            .chain(self.guards.active_guards().skew_observations())
    }
    /// Recalculate our estimated clock skew, and publish it to anybody who
    /// cares.
    fn update_skew(&mut self, now: Instant) {
        let estimate = skew::SkewEstimate::estimate_skew(self.skew_observations(), now);
        // TODO: we might want to do this only conditionally, when the skew
        // estimate changes.
        *self.send_skew.borrow_mut() = estimate;
    }
    /// If the circuit built because of a given [`PendingRequest`] may
    /// now be used (or discarded), return `Some(true)` or
    /// `Some(false)` respectively.
    ///
    /// Return None if we can't yet give an answer about whether such
    /// a circuit is usable.
9552
    fn guard_usability_status(&self, pending: &PendingRequest, now: Instant) -> Option<bool> {
9552
        match &pending.guard_id().0 {
9552
            FirstHopIdInner::Guard(sample, id) => self.guards.guards(sample).circ_usability_status(
9552
                id,
9552
                pending.usage(),
9552
                &self.params,
9552
                now,
9552
            ),
            // Fallback circuits are usable immediately, since we don't have to wait to
            // see whether any _other_ circuit succeeds or fails.
            FirstHopIdInner::Fallback(_) => Some(true),
        }
9552
    }
    /// For requests that have been "waiting" for an answer for too long,
    /// expire them and tell the circuit manager that their circuits
    /// are unusable.
344674
    fn expire_and_answer_pending_requests(&mut self, now: Instant) {
344674
        // A bit ugly: we use a separate Vec here to avoid borrowing issues,
344674
        // and put it back when we're done.
344674
        let mut waiting = Vec::new();
344674
        std::mem::swap(&mut waiting, &mut self.waiting);
344674

            
344674
        waiting.retain_mut(|pending| {
            let expired = pending
                .waiting_since()
                .and_then(|w| now.checked_duration_since(w))
                .map(|d| d >= self.params.np_idle_timeout)
                == Some(true);
            if expired {
                trace!(?pending, "Pending request expired");
                pending.reply(false);
                return false;
            }
            // TODO-SPEC: guard_usability_status isn't what the spec says.  It
            // says instead that we should look at _circuit_ status, saying:
            //  "   Definition: In the algorithm above, C2 "blocks" C1 if:
            // * C2 obeys all the restrictions that C1 had to obey, AND
            // * C2 has higher priority than C1, AND
            // * Either C2 is <complete>, or C2 is <waiting_for_better_guard>,
            // or C2 has been <usable_if_no_better_guard> for no more than
            // {NONPRIMARY_GUARD_CONNECT_TIMEOUT} seconds."
            //
            // See comments in sample::GuardSet::circ_usability_status.
            if let Some(answer) = self.guard_usability_status(pending, now) {
                trace!(?pending, answer, "Pending request now ready");
                pending.reply(answer);
                return false;
            }
            true
344674
        });
344674

            
344674
        // Put the waiting list back.
344674
        std::mem::swap(&mut waiting, &mut self.waiting);
344674
    }
    /// Return every currently extant FirstHopId for a guard or fallback
    /// directory matching (or possibly matching) the provided keys.
    ///
    /// An identity is _possibly matching_ if it contains some of the IDs in the
    /// provided identity, and it has no _contradictory_ identities, but it does
    /// not necessarily contain _all_ of those identities.
    ///
    /// # TODO
    ///
    /// This function should probably not exist; it's only used so that dirmgr
    /// can report successes or failures, since by the time it observes them it
    /// doesn't know whether its circuit came from a guard or a fallback.  To
    /// solve that, we'll need CircMgr to record and report which one it was
    /// using, which will take some more plumbing.
    ///
    /// TODO relay: we will have to make the change above when we implement
    /// relays; otherwise, it would be possible for an attacker to exploit it to
    /// mislead us about our guard status.
16
    fn lookup_ids<T>(&self, identity: &T) -> Vec<FirstHopId>
16
    where
16
        T: tor_linkspec::HasRelayIds + ?Sized,
16
    {
        use strum::IntoEnumIterator;
16
        let mut vec = Vec::with_capacity(2);
16

            
16
        let id = ids::GuardId::from_relay_ids(identity);
64
        for sample in GuardSetSelector::iter() {
48
            let guard_id = match self.guards.guards(&sample).contains(&id) {
16
                Ok(true) => &id,
                Err(other) => other,
32
                Ok(false) => continue,
            };
16
            vec.push(FirstHopId(FirstHopIdInner::Guard(sample, guard_id.clone())));
        }
16
        let id = ids::FallbackId::from_relay_ids(identity);
16
        if self.fallbacks.contains(&id) {
            vec.push(id.into());
16
        }
16
        vec
16
    }
    /// Run any periodic events that update guard status, and return a
    /// duration after which periodic events should next be run.
6395
    pub(crate) fn run_periodic_events(&mut self, wallclock: SystemTime, now: Instant) -> Duration {
6395
        self.update(wallclock, now);
6395
        self.expire_and_answer_pending_requests(now);
6395
        Duration::from_secs(1) // TODO: Too aggressive.
6395
    }
    /// Try to select a guard, expanding the sample if the first attempt fails.
348506
    fn select_guard_with_expand(
348506
        &mut self,
348506
        usage: &GuardUsage,
348506
        now: Instant,
348506
        wallclock: SystemTime,
348506
    ) -> Result<(sample::ListKind, FirstHop), PickGuardError> {
        // Try to find a guard.
348506
        let first_error = match self.select_guard_once(usage, now) {
339076
            Ok(res1) => return Ok(res1),
9430
            Err(e) => {
9430
                trace!("Couldn't select guard on first attempt: {}", e);
9430
                e
9430
            }
9430
        };
9430

            
9430
        // That didn't work. If we have a netdir, expand the sample and try again.
9660
        let res = self.with_opt_universe(|this, univ| {
9430
            let univ = univ?;
9430
            trace!("No guards available, trying to extend the sample.");
            // Make sure that the status on all of our guards are accurate, and
            // expand the sample if we can.
            //
            // Our parameters and configuration did not change, so we do not
            // need to call update() or update_active_set_and_filter(). This
            // call is sufficient to  extend the sample and recompute primary
            // guards.
9430
            let extended = Self::update_guardset_internal(
9430
                &this.params,
9430
                wallclock,
9430
                this.guards.active_set.universe_type(),
9430
                this.guards.active_guards_mut(),
9430
                Some(univ),
9430
            );
9430
            if extended == ExtendedStatus::Yes {
9430
                match this.select_guard_once(usage, now) {
9430
                    Ok(res) => return Some(res),
                    Err(e) => {
                        trace!("Couldn't select guard after update: {}", e);
                    }
                }
            }
            None
9660
        });
9430
        if let Some(res) = res {
9430
            return Ok(res);
        }
        // Okay, that didn't work either.  If we were asked for a directory
        // guard, and we aren't using bridges, then we may be able to use a
        // fallback.
        if usage.kind == GuardUsageKind::OneHopDirectory
            && self.guards.active_set.universe_type() == UniverseType::NetDir
        {
            return self.select_fallback(now);
        }
        // Couldn't extend the sample or use a fallback; return the original error.
        Err(first_error)
348506
    }
    /// Helper: try to pick a single guard, without retrying on failure.
357936
    fn select_guard_once(
357936
        &self,
357936
        usage: &GuardUsage,
357936
        now: Instant,
357936
    ) -> Result<(sample::ListKind, FirstHop), PickGuardError> {
357936
        let active_set = &self.guards.active_set;
        #[cfg_attr(not(feature = "bridge-client"), allow(unused_mut))]
348506
        let (list_kind, mut first_hop) =
357936
            self.guards
357936
                .guards(active_set)
357936
                .pick_guard(active_set, usage, &self.params, now)?;
        #[cfg(feature = "bridge-client")]
348506
        if self.guards.active_set.universe_type() == UniverseType::BridgeSet {
            // See if we can promote first_hop to a viable CircTarget.
            let bridges = self.latest_bridge_set().ok_or_else(|| {
                PickGuardError::Internal(internal!(
                    "No bridge set available, even though this is the Bridges sample"
                ))
            })?;
            first_hop.lookup_bridge_circ_target(&bridges);
            if usage.kind == GuardUsageKind::Data && !first_hop.contains_circ_target() {
                return Err(PickGuardError::Internal(internal!(
                    "Tried to return a non-circtarget guard with Data usage!"
                )));
            }
348506
        }
348506
        Ok((list_kind, first_hop))
357936
    }
    /// Helper: Select a fallback directory.
    ///
    /// Called when we have no guard information to use. Return values are as
    /// for [`GuardMgr::select_guard()`]
    fn select_fallback(
        &self,
        now: Instant,
    ) -> Result<(sample::ListKind, FirstHop), PickGuardError> {
        let filt = self.guards.active_guards().filter();
        let fallback = self
            .fallbacks
            .choose(&mut rand::rng(), now, filt)?
            .as_guard();
        let fallback = filt.modify_hop(fallback)?;
        Ok((sample::ListKind::Fallback, fallback))
    }
}
/// A possible outcome of trying to extend a guard sample.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
enum ExtendedStatus {
    /// The guard sample was extended. (At least one guard was added to it.)
    Yes,
    /// The guard sample was not extended.
    No,
}
/// A set of parameters, derived from the consensus document, controlling
/// the behavior of a guard manager.
#[derive(Debug, Clone)]
#[cfg_attr(test, derive(PartialEq))]
struct GuardParams {
    /// How long should a sampled, un-confirmed guard be kept in the sample before it expires?
    lifetime_unconfirmed: Duration,
    /// How long should a confirmed guard be kept in the sample before
    /// it expires?
    lifetime_confirmed: Duration,
    /// How long may  a guard be unlisted before we remove it from the sample?
    lifetime_unlisted: Duration,
    /// Largest number of guards we're willing to add to the sample.
    max_sample_size: usize,
    /// Largest fraction of the network's guard bandwidth that we're
    /// willing to add to the sample.
    max_sample_bw_fraction: f64,
    /// Smallest number of guards that we're willing to have in the
    /// sample, after applying a [`GuardFilter`].
    min_filtered_sample_size: usize,
    /// How many guards are considered "Primary"?
    n_primary: usize,
    /// When making a regular circuit, how many primary guards should we
    /// be willing to try?
    data_parallelism: usize,
    /// When making a one-hop directory circuit, how many primary
    /// guards should we be willing to try?
    dir_parallelism: usize,
    /// For how long does a pending attempt to connect to a guard
    /// block an attempt to use a less-favored non-primary guard?
    np_connect_timeout: Duration,
    /// How long do we allow a circuit to a successful but unfavored
    /// non-primary guard to sit around before deciding not to use it?
    np_idle_timeout: Duration,
    /// After how much time without successful activity does a
    /// successful circuit indicate that we should retry our primary
    /// guards?
    internet_down_timeout: Duration,
    /// What fraction of the guards can be can be filtered out before we
    /// decide that our filter is "very restrictive"?
    filter_threshold: f64,
    /// What fraction of the guards determine that our filter is "very
    /// restrictive"?
    extreme_threshold: f64,
}
impl Default for GuardParams {
12372
    fn default() -> Self {
12372
        let one_day = Duration::from_secs(86400);
12372
        GuardParams {
12372
            lifetime_unconfirmed: one_day * 120,
12372
            lifetime_confirmed: one_day * 60,
12372
            lifetime_unlisted: one_day * 20,
12372
            max_sample_size: 60,
12372
            max_sample_bw_fraction: 0.2,
12372
            min_filtered_sample_size: 20,
12372
            n_primary: 3,
12372
            data_parallelism: 1,
12372
            dir_parallelism: 3,
12372
            np_connect_timeout: Duration::from_secs(15),
12372
            np_idle_timeout: Duration::from_secs(600),
12372
            internet_down_timeout: Duration::from_secs(600),
12372
            filter_threshold: 0.2,
12372
            extreme_threshold: 0.01,
12372
        }
12372
    }
}
impl TryFrom<&NetParameters> for GuardParams {
    type Error = tor_units::Error;
1190
    fn try_from(p: &NetParameters) -> Result<GuardParams, Self::Error> {
1190
        Ok(GuardParams {
1190
            lifetime_unconfirmed: p.guard_lifetime_unconfirmed.try_into()?,
1190
            lifetime_confirmed: p.guard_lifetime_confirmed.try_into()?,
1190
            lifetime_unlisted: p.guard_remove_unlisted_after.try_into()?,
1190
            max_sample_size: p.guard_max_sample_size.try_into()?,
1190
            max_sample_bw_fraction: p.guard_max_sample_threshold.as_fraction(),
1190
            min_filtered_sample_size: p.guard_filtered_min_sample_size.try_into()?,
1190
            n_primary: p.guard_n_primary.try_into()?,
1190
            data_parallelism: p.guard_use_parallelism.try_into()?,
1190
            dir_parallelism: p.guard_dir_use_parallelism.try_into()?,
1190
            np_connect_timeout: p.guard_nonprimary_connect_timeout.try_into()?,
1190
            np_idle_timeout: p.guard_nonprimary_idle_timeout.try_into()?,
1190
            internet_down_timeout: p.guard_internet_likely_down.try_into()?,
1190
            filter_threshold: p.guard_meaningful_restriction.as_fraction(),
1190
            extreme_threshold: p.guard_extreme_restriction.as_fraction(),
        })
1190
    }
}
/// Representation of a guard or fallback, as returned by [`GuardMgr::select_guard()`].
#[derive(Debug, Clone)]
pub struct FirstHop {
    /// The sample from which this guard was taken, or `None` if this is a fallback.
    sample: Option<GuardSetSelector>,
    /// Information about connecting to (or through) this guard.
    inner: FirstHopInner,
}
/// The enumeration inside a FirstHop that holds information about how to
/// connect to (and possibly through) a guard or fallback.
#[derive(Debug, Clone)]
enum FirstHopInner {
    /// We have enough information to connect to a guard.
    Chan(OwnedChanTarget),
    /// We have enough information to connect to a guards _and_ to build
    /// multihop circuits through it.
    #[cfg_attr(not(feature = "bridge-client"), allow(dead_code))]
    Circ(OwnedCircTarget),
}
impl FirstHop {
    /// Return a new [`FirstHopId`] for this `FirstHop`.
348506
    fn first_hop_id(&self) -> FirstHopId {
348506
        match &self.sample {
348506
            Some(sample) => {
348506
                let guard_id = GuardId::from_relay_ids(self);
348506
                FirstHopId::in_sample(sample.clone(), guard_id)
            }
            None => {
                let fallback_id = crate::ids::FallbackId::from_relay_ids(self);
                FirstHopId::from(fallback_id)
            }
        }
348506
    }
    /// Look up this guard in `netdir`.
341694
    pub fn get_relay<'a>(&self, netdir: &'a NetDir) -> Option<Relay<'a>> {
341694
        match &self.sample {
341694
            #[cfg(feature = "bridge-client")]
341694
            // Always return "None" for anything that isn't in the netdir.
341694
            Some(s) if s.universe_type() == UniverseType::BridgeSet => None,
            // Otherwise ask the netdir.
341694
            _ => netdir.by_ids(self),
        }
341694
    }
    /// Return true if this guard is a bridge.
    pub fn is_bridge(&self) -> bool {
        match &self.sample {
            #[cfg(feature = "bridge-client")]
            Some(s) if s.universe_type() == UniverseType::BridgeSet => true,
            _ => false,
        }
    }
    /// If possible, return a view of this object that can be used to build a circuit.
341694
    pub fn as_circ_target(&self) -> Option<&OwnedCircTarget> {
341694
        match &self.inner {
341694
            FirstHopInner::Chan(_) => None,
            FirstHopInner::Circ(ct) => Some(ct),
        }
341694
    }
    /// Return a view of this as an OwnedChanTarget.
8
    fn chan_target_mut(&mut self) -> &mut OwnedChanTarget {
8
        match &mut self.inner {
8
            FirstHopInner::Chan(ct) => ct,
            FirstHopInner::Circ(ct) => ct.chan_target_mut(),
        }
8
    }
    /// If possible and appropriate, find a circuit target in `bridges` for this
    /// `FirstHop`, and make this `FirstHop` a viable circuit target.
    ///
    /// (By default, any `FirstHop` that a `GuardSet` returns will have enough
    /// information to be a `ChanTarget`, but it will be lacking the additional
    /// network information in `CircTarget`[^1] necessary for us to build a
    /// multi-hop circuit through it.  If this FirstHop is a regular non-bridge
    /// `Relay`, then the `CircMgr` will later look up that circuit information
    /// itself from the network directory. But if this `FirstHop` *is* a bridge,
    /// then we need to find that information in the `BridgeSet`, since the
    /// CircMgr does not keep track of the `BridgeSet`.)
    ///
    /// [^1]: For example, supported protocol versions and ntor keys.
    #[cfg(feature = "bridge-client")]
    fn lookup_bridge_circ_target(&mut self, bridges: &bridge::BridgeSet) {
        use crate::sample::CandidateStatus::Present;
        if self.sample.as_ref().map(|s| s.universe_type()) == Some(UniverseType::BridgeSet)
            && matches!(self.inner, FirstHopInner::Chan(_))
        {
            if let Present(bridge_relay) = bridges.bridge_relay_by_guard(self) {
                if let Some(circ_target) = bridge_relay.as_relay_with_desc() {
                    self.inner =
                        FirstHopInner::Circ(OwnedCircTarget::from_circ_target(&circ_target));
                }
            }
        }
    }
    /// Return true if this `FirstHop` contains circuit target information.
    ///
    /// This is true if `lookup_bridge_circ_target()` has been called, and it
    /// successfully found the circuit target information.
    #[cfg(feature = "bridge-client")]
    fn contains_circ_target(&self) -> bool {
        matches!(self.inner, FirstHopInner::Circ(_))
    }
}
// This is somewhat redundant with the implementations in crate::guard::Guard.
impl tor_linkspec::HasAddrs for FirstHop {
6732
    fn addrs(&self) -> &[SocketAddr] {
6732
        match &self.inner {
6732
            FirstHopInner::Chan(ct) => ct.addrs(),
            FirstHopInner::Circ(ct) => ct.addrs(),
        }
6732
    }
}
impl tor_linkspec::HasRelayIds for FirstHop {
2091036
    fn identity(
2091036
        &self,
2091036
        key_type: tor_linkspec::RelayIdType,
2091036
    ) -> Option<tor_linkspec::RelayIdRef<'_>> {
2091036
        match &self.inner {
2091036
            FirstHopInner::Chan(ct) => ct.identity(key_type),
            FirstHopInner::Circ(ct) => ct.identity(key_type),
        }
2091036
    }
}
impl tor_linkspec::HasChanMethod for FirstHop {
6724
    fn chan_method(&self) -> tor_linkspec::ChannelMethod {
6724
        match &self.inner {
6724
            FirstHopInner::Chan(ct) => ct.chan_method(),
            FirstHopInner::Circ(ct) => ct.chan_method(),
        }
6724
    }
}
impl tor_linkspec::ChanTarget for FirstHop {}
/// The purpose for which we plan to use a guard.
///
/// This can affect the guard selection algorithm.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[non_exhaustive]
pub enum GuardUsageKind {
    /// We want to use this guard for a data circuit.
    ///
    /// (This encompasses everything except the `OneHopDirectory` case.)
    #[default]
    Data,
    /// We want to use this guard for a one-hop, non-anonymous
    /// directory request.
    ///
    /// (Our algorithm allows more parallelism for the guards that we use
    /// for these circuits.)
    OneHopDirectory,
}
/// A set of parameters describing how a single guard should be selected.
///
/// Used as an argument to [`GuardMgr::select_guard`].
1045430
#[derive(Clone, Debug, derive_builder::Builder)]
#[builder(build_fn(error = "tor_config::ConfigBuildError"))]
pub struct GuardUsage {
    /// The purpose for which this guard will be used.
    #[builder(default)]
    kind: GuardUsageKind,
    /// A list of restrictions on which guard may be used.
    ///
    /// The default is the empty list.
    #[builder(sub_builder, setter(custom))]
    restrictions: GuardRestrictionList,
}
impl_standard_builder! { GuardUsage: !Deserialize }
/// List of socket restrictions, as configured
pub type GuardRestrictionList = Vec<GuardRestriction>;
define_list_builder_helper! {
    pub struct GuardRestrictionListBuilder {
        restrictions: [GuardRestriction],
    }
    built: GuardRestrictionList = restrictions;
    default = vec![];
4153
    item_build: |restriction| Ok(restriction.clone());
}
define_list_builder_accessors! {
    struct GuardUsageBuilder {
        pub restrictions: [GuardRestriction],
    }
}
impl GuardUsageBuilder {
    /// Create a new empty [`GuardUsageBuilder`].
24
    pub fn new() -> Self {
24
        Self::default()
24
    }
}
/// A restriction that applies to a single request for a guard.
///
/// Restrictions differ from filters (see [`GuardFilter`]) in that
/// they apply to single requests, not to our entire set of guards.
/// They're suitable for things like making sure that we don't start
/// and end a circuit at the same relay, or requiring a specific
/// subprotocol version for certain kinds of requests.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[non_exhaustive]
pub enum GuardRestriction {
    /// Don't pick a guard with the provided identity.
    AvoidId(RelayId),
    /// Don't pick a guard with any of the provided Ed25519 identities.
    AvoidAllIds(RelayIdSet),
}
/// The kind of vanguards to use.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] //
#[derive(Serialize, Deserialize)] //
#[derive(derive_more::Display)] //
#[serde(rename_all = "lowercase")]
#[cfg(feature = "vanguards")]
#[non_exhaustive]
pub enum VanguardMode {
    /// "Lite" vanguards.
    #[default]
    #[display("lite")]
    Lite = 1,
    /// "Full" vanguards.
    #[display("full")]
    Full = 2,
    /// Vanguards are disabled.
    #[display("disabled")]
    Disabled = 0,
}
#[cfg(feature = "vanguards")]
impl VanguardMode {
    /// Build a `VanguardMode` from a [`NetParameters`] parameter.
    ///
    /// Used for converting [`vanguards_enabled`](NetParameters::vanguards_enabled)
    /// or [`vanguards_hs_service`](NetParameters::vanguards_hs_service)
    /// to the corresponding `VanguardMode`.
4896
    pub(crate) fn from_net_parameter(val: BoundedInt32<0, 2>) -> Self {
4896
        match val.get() {
            0 => VanguardMode::Disabled,
2480
            1 => VanguardMode::Lite,
2416
            2 => VanguardMode::Full,
            _ => unreachable!("BoundedInt32 was not bounded?!"),
        }
4896
    }
}
impl_not_auto_value!(VanguardMode);
/// Vanguards configuration.
6478
#[derive(Debug, Default, Clone, Eq, PartialEq, derive_builder::Builder)]
#[builder(build_fn(error = "ConfigBuildError"))]
#[builder(derive(Debug, Serialize, Deserialize))]
pub struct VanguardConfig {
    /// The kind of vanguards to use.
    #[builder_field_attr(serde(default))]
    #[builder(default)]
    mode: ExplicitOrAuto<VanguardMode>,
}
impl VanguardConfig {
    /// Return the configured [`VanguardMode`].
    ///
    /// Returns the [`Default`] `VanguardMode`
    /// if the mode is [`Auto`](ExplicitOrAuto) or unspecified.
3205
    pub fn mode(&self) -> VanguardMode {
3205
        match self.mode {
1763
            ExplicitOrAuto::Auto => Default::default(),
1442
            ExplicitOrAuto::Explicit(mode) => mode,
        }
3205
    }
}
/// The kind of vanguards to use.
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)] //
#[derive(Serialize, Deserialize)] //
#[derive(derive_more::Display)] //
#[serde(rename_all = "lowercase")]
#[cfg(not(feature = "vanguards"))]
#[non_exhaustive]
pub enum VanguardMode {
    /// Vanguards are disabled.
    #[default]
    #[display("disabled")]
    Disabled = 0,
}
#[cfg(test)]
mod test {
    // @@ begin test lint list maintained by maint/add_warning @@
    #![allow(clippy::bool_assert_comparison)]
    #![allow(clippy::clone_on_copy)]
    #![allow(clippy::dbg_macro)]
    #![allow(clippy::mixed_attributes_style)]
    #![allow(clippy::print_stderr)]
    #![allow(clippy::print_stdout)]
    #![allow(clippy::single_char_pattern)]
    #![allow(clippy::unwrap_used)]
    #![allow(clippy::unchecked_duration_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
    use super::*;
    use tor_linkspec::{HasAddrs, HasRelayIds};
    use tor_persist::TestingStateMgr;
    use tor_rtcompat::test_with_all_runtimes;
    #[test]
    fn guard_param_defaults() {
        let p1 = GuardParams::default();
        let p2: GuardParams = (&NetParameters::default()).try_into().unwrap();
        assert_eq!(p1, p2);
    }
    fn init<R: Runtime>(rt: R) -> (GuardMgr<R>, TestingStateMgr, NetDir) {
        use tor_netdir::{testnet, MdReceiver, PartialNetDir};
        let statemgr = TestingStateMgr::new();
        let have_lock = statemgr.try_lock().unwrap();
        assert!(have_lock.held());
        let guardmgr = GuardMgr::new(rt, statemgr.clone(), &TestConfig::default()).unwrap();
        let (con, mds) = testnet::construct_network().unwrap();
        let param_overrides = vec![
            // We make the sample size smaller than usual to compensate for the
            // small testing network.  (Otherwise, we'd sample the whole network,
            // and not be able to observe guards in the tests.)
            "guard-min-filtered-sample-size=5",
            // We choose only two primary guards, to make the tests easier to write.
            "guard-n-primary-guards=2",
            // We define any restriction that allows 75% or fewer of relays as "meaningful",
            // so that we can test the "restrictive" guard sample behavior, and to avoid
            "guard-meaningful-restriction-percent=75",
        ];
        let param_overrides: String =
            itertools::Itertools::intersperse(param_overrides.into_iter(), " ").collect();
        let override_p = param_overrides.parse().unwrap();
        let mut netdir = PartialNetDir::new(con, Some(&override_p));
        for md in mds {
            netdir.add_microdesc(md);
        }
        let netdir = netdir.unwrap_if_sufficient().unwrap();
        (guardmgr, statemgr, netdir)
    }
    #[test]
    #[allow(clippy::clone_on_copy)]
    fn simple_case() {
        test_with_all_runtimes!(|rt| async move {
            let (guardmgr, statemgr, netdir) = init(rt.clone());
            let usage = GuardUsage::default();
            guardmgr.install_test_netdir(&netdir);
            let (id, mon, usable) = guardmgr.select_guard(usage).unwrap();
            // Report that the circuit succeeded.
            mon.succeeded();
            // May we use the circuit?
            let usable = usable.await.unwrap();
            assert!(usable);
            // Save the state...
            guardmgr.flush_msg_queue().await;
            guardmgr.store_persistent_state().unwrap();
            drop(guardmgr);
            // Try reloading from the state...
            let guardmgr2 =
                GuardMgr::new(rt.clone(), statemgr.clone(), &TestConfig::default()).unwrap();
            guardmgr2.install_test_netdir(&netdir);
            // Since the guard was confirmed, we should get the same one this time!
            let usage = GuardUsage::default();
            let (id2, _mon, _usable) = guardmgr2.select_guard(usage).unwrap();
            assert!(id2.same_relay_ids(&id));
        });
    }
    #[test]
    fn simple_waiting() {
        // TODO(nickm): This test fails in rare cases; I suspect a
        // race condition somewhere.
        //
        // I've doubled up on the queue flushing in order to try to make the
        // race less likely, but we should investigate.
        test_with_all_runtimes!(|rt| async move {
            let (guardmgr, _statemgr, netdir) = init(rt);
            let u = GuardUsage::default();
            guardmgr.install_test_netdir(&netdir);
            // We'll have the first two guard fail, which should make us
            // try a non-primary guard.
            let (id1, mon, _usable) = guardmgr.select_guard(u.clone()).unwrap();
            mon.failed();
            guardmgr.flush_msg_queue().await; // avoid race
            guardmgr.flush_msg_queue().await; // avoid race
            let (id2, mon, _usable) = guardmgr.select_guard(u.clone()).unwrap();
            mon.failed();
            guardmgr.flush_msg_queue().await; // avoid race
            guardmgr.flush_msg_queue().await; // avoid race
            assert!(!id1.same_relay_ids(&id2));
            // Now we should get two sampled guards. They should be different.
            let (id3, mon3, usable3) = guardmgr.select_guard(u.clone()).unwrap();
            let (id4, mon4, usable4) = guardmgr.select_guard(u.clone()).unwrap();
            assert!(!id3.same_relay_ids(&id4));
            let (u3, u4) = futures::join!(
                async {
                    mon3.failed();
                    guardmgr.flush_msg_queue().await; // avoid race
                    usable3.await.unwrap()
                },
                async {
                    mon4.succeeded();
                    usable4.await.unwrap()
                }
            );
            assert_eq!((u3, u4), (false, true));
        });
    }
    #[test]
    fn filtering_basics() {
        test_with_all_runtimes!(|rt| async move {
            let (guardmgr, _statemgr, netdir) = init(rt);
            let u = GuardUsage::default();
            let filter = {
                let mut f = GuardFilter::default();
                // All the addresses in the test network are {0,1,2,3,4}.0.0.3:9001.
                // Limit to only 2.0.0.0/8
                f.push_reachable_addresses(vec!["2.0.0.0/8:9001".parse().unwrap()]);
                f
            };
            guardmgr.set_filter(filter);
            guardmgr.install_test_netdir(&netdir);
            let (guard, _mon, _usable) = guardmgr.select_guard(u).unwrap();
            // Make sure that the filter worked.
            let addr = guard.addrs()[0];
            assert_eq!(addr, "2.0.0.3:9001".parse().unwrap());
        });
    }
    #[test]
    fn external_status() {
        test_with_all_runtimes!(|rt| async move {
            let (guardmgr, _statemgr, netdir) = init(rt);
            let data_usage = GuardUsage::default();
            let dir_usage = GuardUsageBuilder::new()
                .kind(GuardUsageKind::OneHopDirectory)
                .build()
                .unwrap();
            guardmgr.install_test_netdir(&netdir);
            {
                // Override this parameter, so that we can get deterministic results below.
                let mut inner = guardmgr.inner.lock().unwrap();
                inner.params.dir_parallelism = 1;
            }
            let (guard, mon, _usable) = guardmgr.select_guard(data_usage.clone()).unwrap();
            mon.succeeded();
            // Record that this guard gave us a bad directory object.
            guardmgr.note_external_failure(&guard, ExternalActivity::DirCache);
            // We ask for another guard, for data usage.  We should get the same
            // one as last time, since the director failure doesn't mean this
            // guard is useless as a primary guard.
            let (g2, mon, _usable) = guardmgr.select_guard(data_usage).unwrap();
            assert_eq!(g2.ed_identity(), guard.ed_identity());
            mon.succeeded();
            // But if we ask for a guard for directory usage, we should get a
            // different one, since the last guard we gave out failed.
            let (g3, mon, _usable) = guardmgr.select_guard(dir_usage.clone()).unwrap();
            assert_ne!(g3.ed_identity(), guard.ed_identity());
            mon.succeeded();
            // Now record a success for for directory usage.
            guardmgr.note_external_success(&guard, ExternalActivity::DirCache);
            // Now that the guard is working as a cache, asking for it should get us the same guard.
            let (g4, _mon, _usable) = guardmgr.select_guard(dir_usage).unwrap();
            assert_eq!(g4.ed_identity(), guard.ed_identity());
        });
    }
    #[cfg(feature = "vanguards")]
    #[test]
    fn vanguard_mode_ord() {
        assert!(VanguardMode::Disabled < VanguardMode::Lite);
        assert!(VanguardMode::Disabled < VanguardMode::Full);
        assert!(VanguardMode::Lite < VanguardMode::Full);
    }
}