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
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46

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

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

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

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

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

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

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

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

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

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

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

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

            
123
use tor_config::ConfigBuildError;
124

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
461
        Ok(())
462
    }
463

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
976
1434
            self.select_guard_set_based_on_filter(netdir);
977
6362
        }
978

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

            
992
    /// Update the status of every guard in `active_guards`, and expand it as
993
    /// needed.
994
    ///
995
    /// This function doesn't take `&self`, to make sure that we are only
996
    /// affecting a single `GuardSet`, and to avoid confusing the borrow
997
    /// checker.
998
    ///
999
    /// We should call this whenever the contents of the universe have changed.
    ///
    /// We should also call this whenever a new GuardSet becomes active.
17226
    fn update_guardset_internal<U: Universe>(
17226
        params: &GuardParams,
17226
        now: SystemTime,
17226
        universe_type: UniverseType,
17226
        active_guards: &mut GuardSet,
17226
        universe: Option<&U>,
17226
    ) -> ExtendedStatus {
17226
        // Expire guards.  Do that early, in case doing so makes it clear that
17226
        // we need to grab more guards or mark others as primary.
17226
        active_guards.expire_old_guards(params, now);
17226
        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
10864
            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;
10864
            }
10864
            active_guards.update_status_from_dir(universe);
10864
            active_guards.extend_sample_as_needed(now, params, universe)
        } else {
6362
            ExtendedStatus::No
        };
17226
        active_guards.select_primary_guards(params);
17226

            
17226
        extended
17226
    }
    /// 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")]
7796
    fn update_desired_descriptors(&mut self, now: Instant) {
7796
        if self.guards.active_set.universe_type() != UniverseType::BridgeSet {
7796
            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);
        }
7796
    }
    /// 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.
1434
    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.)
1434
        let offset = match self.guards.active_set {
1434
            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,
        };
1434
        let frac_permitted = self.filter.frac_bw_permitted(netdir);
1434
        let threshold = self.params.filter_threshold + offset;
1434
        let new_choice = if frac_permitted < threshold {
8
            GuardSetSelector::Restricted
        } else {
1426
            GuardSetSelector::Default
        };
1434
        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
            }
1426
        }
1434
    }
    /// 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)]
16474
    pub(crate) fn handle_msg(
16474
        &mut self,
16474
        request_id: RequestId,
16474
        status: GuardStatus,
16474
        skew: Option<ClockSkew>,
16474
        runtime: &impl tor_rtcompat::SleepProvider,
16474
    ) {
16474
        if let Some(mut pending) = self.pending.remove(&request_id) {
            // If there was a pending request matching this RequestId, great!
16474
            let guard_id = pending.guard_id();
16474
            trace!(?guard_id, ?status, "Received report of guard status");
            // First, handle the skew report (if any)
16474
            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);
16474
            }
16474
            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.
                }
402
                (GuardStatus::Success, FirstHopIdInner::Guard(sample, id)) => {
402
                    // If we had gone too long without any net activity when we
402
                    // gave out this guard, and now we're seeing a circuit
402
                    // succeed, tell the primary guards that they might be
402
                    // retriable.
402
                    if pending.net_has_been_down() {
                        self.maybe_retry_primary_guards(runtime.now());
402
                    }
                    // The guard succeeded.  Tell the GuardSet.
402
                    self.guards.guards_mut(sample).record_success(
402
                        id,
402
                        &self.params,
402
                        None,
402
                        runtime.wallclock(),
402
                    );
                    // Either tell the request whether the guard is
                    // usable, or schedule it as a "waiting" request.
402
                    if let Some(usable) = self.guard_usability_status(&pending, runtime.now()) {
402
                        trace!(?guard_id, usable, "Known usability status");
402
                        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
                }
16048
                (GuardStatus::AttemptAbandoned, FirstHopIdInner::Guard(sample, id)) => {
16048
                    self.guards.guards_mut(sample).record_attempt_abandoned(id);
16048
                    pending.reply(false);
16048
                }
                (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.
16474
        self.guards
16474
            .active_guards_mut()
16474
            .select_primary_guards(&self.params);
16474

            
16474
        // Some waiting request may just have become ready (usable or
16474
        // not); we need to give them the information they're waiting
16474
        // for.
16474
        self.expire_and_answer_pending_requests(runtime.now());
16474
    }
    /// 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.
7617
    fn guard_usability_status(&self, pending: &PendingRequest, now: Instant) -> Option<bool> {
7617
        match &pending.guard_id().0 {
7617
            FirstHopIdInner::Guard(sample, id) => self.guards.guards(sample).circ_usability_status(
7617
                id,
7617
                pending.usage(),
7617
                &self.params,
7617
                now,
7617
            ),
            // 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),
        }
7617
    }
    /// For requests that have been "waiting" for an answer for too long,
    /// expire them and tell the circuit manager that their circuits
    /// are unusable.
342530
    fn expire_and_answer_pending_requests(&mut self, now: Instant) {
342530
        // A bit ugly: we use a separate Vec here to avoid borrowing issues,
342530
        // and put it back when we're done.
342530
        let mut waiting = Vec::new();
342530
        std::mem::swap(&mut waiting, &mut self.waiting);
342530

            
342530
        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
342530
        });
342530

            
342530
        // Put the waiting list back.
342530
        std::mem::swap(&mut waiting, &mut self.waiting);
342530
    }
    /// 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.
5944
    pub(crate) fn run_periodic_events(&mut self, wallclock: SystemTime, now: Instant) -> Duration {
5944
        self.update(wallclock, now);
5944
        self.expire_and_answer_pending_requests(now);
5944
        Duration::from_secs(1) // TODO: Too aggressive.
5944
    }
    /// 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;
1436
    fn try_from(p: &NetParameters) -> Result<GuardParams, Self::Error> {
1436
        Ok(GuardParams {
1436
            lifetime_unconfirmed: p.guard_lifetime_unconfirmed.try_into()?,
1436
            lifetime_confirmed: p.guard_lifetime_confirmed.try_into()?,
1436
            lifetime_unlisted: p.guard_remove_unlisted_after.try_into()?,
1436
            max_sample_size: p.guard_max_sample_size.try_into()?,
1436
            max_sample_bw_fraction: p.guard_max_sample_threshold.as_fraction(),
1436
            min_filtered_sample_size: p.guard_filtered_min_sample_size.try_into()?,
1436
            n_primary: p.guard_n_primary.try_into()?,
1436
            data_parallelism: p.guard_use_parallelism.try_into()?,
1436
            dir_parallelism: p.guard_dir_use_parallelism.try_into()?,
1436
            np_connect_timeout: p.guard_nonprimary_connect_timeout.try_into()?,
1436
            np_idle_timeout: p.guard_nonprimary_idle_timeout.try_into()?,
1436
            internet_down_timeout: p.guard_internet_likely_down.try_into()?,
1436
            filter_threshold: p.guard_meaningful_restriction.as_fraction(),
1436
            extreme_threshold: p.guard_extreme_restriction.as_fraction(),
        })
1436
    }
}
/// 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.
6642
#[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);
    }
}