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
// This clippy lint produces a false positive on `use strum`, below.
48
// Attempting to apply the lint to just the use statement fails to suppress
49
// this lint and instead produces another lint about a useless clippy attribute.
50
#![allow(clippy::single_component_path_imports)]
51

            
52
pub mod authority;
53
mod bootstrap;
54
pub mod config;
55
mod docid;
56
mod docmeta;
57
mod err;
58
mod event;
59
mod retry;
60
mod shared_ref;
61
mod state;
62
mod storage;
63

            
64
#[cfg(feature = "bridge-client")]
65
pub mod bridgedesc;
66
#[cfg(feature = "dirfilter")]
67
pub mod filter;
68

            
69
use crate::docid::{CacheUsage, ClientRequest, DocQuery};
70
use crate::err::BootstrapAction;
71
#[cfg(not(feature = "experimental-api"))]
72
use crate::shared_ref::SharedMutArc;
73
#[cfg(feature = "experimental-api")]
74
pub use crate::shared_ref::SharedMutArc;
75
use crate::storage::{DynStore, Store};
76
use bootstrap::AttemptId;
77
use event::DirProgress;
78
use postage::watch;
79
pub use retry::{DownloadSchedule, DownloadScheduleBuilder};
80
use scopeguard::ScopeGuard;
81
use tor_circmgr::CircMgr;
82
use tor_dirclient::SourceInfo;
83
use tor_error::{info_report, into_internal, warn_report};
84
use tor_netdir::params::NetParameters;
85
use tor_netdir::{DirEvent, MdReceiver, NetDir, NetDirProvider};
86

            
87
use async_trait::async_trait;
88
use futures::{stream::BoxStream, task::SpawnExt};
89
use oneshot_fused_workaround as oneshot;
90
use tor_netdoc::doc::netstatus::ProtoStatuses;
91
use tor_rtcompat::scheduler::{TaskHandle, TaskSchedule};
92
use tor_rtcompat::Runtime;
93
use tracing::{debug, info, trace, warn};
94

            
95
use std::marker::PhantomData;
96
use std::sync::atomic::{AtomicBool, Ordering};
97
use std::sync::{Arc, Mutex};
98
use std::time::Duration;
99
use std::{collections::HashMap, sync::Weak};
100
use std::{fmt::Debug, time::SystemTime};
101

            
102
use crate::state::{DirState, NetDirChange};
103
pub use authority::{Authority, AuthorityBuilder};
104
pub use config::{
105
    DirMgrConfig, DirTolerance, DirToleranceBuilder, DownloadScheduleConfig,
106
    DownloadScheduleConfigBuilder, NetworkConfig, NetworkConfigBuilder,
107
};
108
pub use docid::DocId;
109
pub use err::Error;
110
pub use event::{DirBlockage, DirBootstrapEvents, DirBootstrapStatus};
111
pub use storage::DocumentText;
112
pub use tor_guardmgr::fallback::{FallbackDir, FallbackDirBuilder};
113
pub use tor_netdir::Timeliness;
114

            
115
/// Re-export of `strum` crate for use by an internal macro
116
use strum;
117

            
118
/// A Result as returned by this crate.
119
pub type Result<T> = std::result::Result<T, Error>;
120

            
121
/// Storage manager used by [`DirMgr`] and
122
/// [`BridgeDescMgr`](bridgedesc::BridgeDescMgr)
123
///
124
/// Internally, this wraps up a sqlite database.
125
///
126
/// This is a handle, which is cheap to clone; clones share state.
127
#[derive(Clone)]
128
pub struct DirMgrStore<R: Runtime> {
129
    /// The actual store
130
    pub(crate) store: Arc<Mutex<crate::DynStore>>,
131

            
132
    /// Be parameterized by Runtime even though we don't use it right now
133
    pub(crate) runtime: PhantomData<R>,
134
}
135

            
136
impl<R: Runtime> DirMgrStore<R> {
137
    /// Open the storage, according to the specified configuration
138
22
    pub fn new(config: &DirMgrConfig, runtime: R, offline: bool) -> Result<Self> {
139
22
        let store = Arc::new(Mutex::new(config.open_store(offline)?));
140
22
        drop(runtime);
141
22
        let runtime = PhantomData;
142
22
        Ok(DirMgrStore { store, runtime })
143
22
    }
144
}
145

            
146
/// Trait for DirMgr implementations
147
#[async_trait]
148
pub trait DirProvider: NetDirProvider {
149
    /// Try to change our configuration to `new_config`.
150
    ///
151
    /// Actual behavior will depend on the value of `how`.
152
    fn reconfigure(
153
        &self,
154
        new_config: &DirMgrConfig,
155
        how: tor_config::Reconfigure,
156
    ) -> std::result::Result<(), tor_config::ReconfigureError>;
157

            
158
    /// Bootstrap a `DirProvider` that hasn't been bootstrapped yet.
159
    async fn bootstrap(&self) -> Result<()>;
160

            
161
    /// Return a stream of [`DirBootstrapStatus`] events to tell us about changes
162
    /// in the latest directory's bootstrap status.
163
    ///
164
    /// Note that this stream can be lossy: the caller will not necessarily
165
    /// observe every event on the stream
166
    fn bootstrap_events(&self) -> BoxStream<'static, DirBootstrapStatus>;
167

            
168
    /// Return a [`TaskHandle`] that can be used to manage the download process.
169
    fn download_task_handle(&self) -> Option<TaskHandle> {
170
        None
171
    }
172
}
173

            
174
// NOTE(eta): We can't implement this for Arc<DirMgr<R>> due to trait coherence rules, so instead
175
//            there's a blanket impl for Arc<T> in tor-netdir.
176
impl<R: Runtime> NetDirProvider for DirMgr<R> {
177
52
    fn netdir(&self, timeliness: Timeliness) -> tor_netdir::Result<Arc<NetDir>> {
178
        use tor_netdir::Error as NetDirError;
179
52
        let netdir = self.netdir.get().ok_or(NetDirError::NoInfo)?;
180
        let lifetime = match timeliness {
181
            Timeliness::Strict => netdir.lifetime().clone(),
182
            Timeliness::Timely => self
183
                .config
184
                .get()
185
                .tolerance
186
                .extend_lifetime(netdir.lifetime()),
187
            Timeliness::Unchecked => return Ok(netdir),
188
        };
189
        let now = SystemTime::now();
190
        if lifetime.valid_after() > now {
191
            Err(NetDirError::DirNotYetValid)
192
        } else if lifetime.valid_until() < now {
193
            Err(NetDirError::DirExpired)
194
        } else {
195
            Ok(netdir)
196
        }
197
52
    }
198

            
199
72
    fn events(&self) -> BoxStream<'static, DirEvent> {
200
72
        Box::pin(self.events.subscribe())
201
72
    }
202

            
203
12
    fn params(&self) -> Arc<dyn AsRef<tor_netdir::params::NetParameters>> {
204
12
        if let Some(netdir) = self.netdir.get() {
205
            // We have a directory, so we'd like to give it out for its
206
            // parameters.
207
            //
208
            // We do this even if the directory is expired, since parameters
209
            // don't really expire on any plausible timescale.
210
            netdir
211
        } else {
212
            // We have no directory, so we'll give out the default parameters as
213
            // modified by the provided override_net_params configuration.
214
            //
215
12
            self.default_parameters
216
12
                .lock()
217
12
                .expect("Poisoned lock")
218
12
                .clone()
219
        }
220
        // TODO(nickm): If we felt extremely clever, we could add a third case
221
        // where, if we have a pending directory with a validated consensus, we
222
        // give out that consensus's network parameters even if we _don't_ yet
223
        // have a full directory.  That's significant refactoring, though, for
224
        // an unclear amount of benefit.
225
12
    }
226

            
227
8
    fn protocol_statuses(&self) -> Option<(SystemTime, Arc<ProtoStatuses>)> {
228
8
        self.protocols.lock().expect("Poisoned lock").clone()
229
8
    }
230
}
231

            
232
#[async_trait]
233
impl<R: Runtime> DirProvider for Arc<DirMgr<R>> {
234
4
    fn reconfigure(
235
4
        &self,
236
4
        new_config: &DirMgrConfig,
237
4
        how: tor_config::Reconfigure,
238
4
    ) -> std::result::Result<(), tor_config::ReconfigureError> {
239
4
        DirMgr::reconfigure(self, new_config, how)
240
4
    }
241

            
242
    async fn bootstrap(&self) -> Result<()> {
243
        DirMgr::bootstrap(self).await
244
    }
245

            
246
8
    fn bootstrap_events(&self) -> BoxStream<'static, DirBootstrapStatus> {
247
8
        Box::pin(DirMgr::bootstrap_events(self))
248
8
    }
249

            
250
8
    fn download_task_handle(&self) -> Option<TaskHandle> {
251
8
        Some(self.task_handle.clone())
252
8
    }
253
}
254

            
255
/// A directory manager to download, fetch, and cache a Tor directory.
256
///
257
/// A DirMgr can operate in three modes:
258
///   * In **offline** mode, it only reads from the cache, and can
259
///     only read once.
260
///   * In **read-only** mode, it reads from the cache, but checks
261
///     whether it can acquire an associated lock file.  If it can, then
262
///     it enters read-write mode.  If not, it checks the cache
263
///     periodically for new information.
264
///   * In **read-write** mode, it knows that no other process will be
265
///     writing to the cache, and it takes responsibility for fetching
266
///     data from the network and updating the directory with new
267
///     directory information.
268
pub struct DirMgr<R: Runtime> {
269
    /// Configuration information: where to find directories, how to
270
    /// validate them, and so on.
271
    config: tor_config::MutCfg<DirMgrConfig>,
272
    /// Handle to our sqlite cache.
273
    // TODO(nickm): I'd like to use an rwlock, but that's not feasible, since
274
    // rusqlite::Connection isn't Sync.
275
    // TODO is needed?
276
    store: Arc<Mutex<DynStore>>,
277
    /// Our latest sufficiently bootstrapped directory, if we have one.
278
    ///
279
    /// We use the RwLock so that we can give this out to a bunch of other
280
    /// users, and replace it once a new directory is bootstrapped.
281
    // TODO(eta): Eurgh! This is so many Arcs! (especially considering this
282
    //            gets wrapped in an Arc)
283
    netdir: Arc<SharedMutArc<NetDir>>,
284

            
285
    /// Our latest set of recommended protocols.
286
    protocols: Mutex<Option<(SystemTime, Arc<ProtoStatuses>)>>,
287

            
288
    /// A set of network parameters to hand out when we have no directory.
289
    default_parameters: Mutex<Arc<NetParameters>>,
290

            
291
    /// A publisher handle that we notify whenever the consensus changes.
292
    events: event::FlagPublisher<DirEvent>,
293

            
294
    /// A publisher handle that we notify whenever our bootstrapping status
295
    /// changes.
296
    send_status: Mutex<watch::Sender<event::DirBootstrapStatus>>,
297

            
298
    /// A receiver handle that gets notified whenever our bootstrapping status
299
    /// changes.
300
    ///
301
    /// We don't need to keep this drained, since `postage::watch` already knows
302
    /// to discard unread events.
303
    receive_status: DirBootstrapEvents,
304

            
305
    /// A circuit manager, if this DirMgr supports downloading.
306
    circmgr: Option<Arc<CircMgr<R>>>,
307

            
308
    /// Our asynchronous runtime.
309
    runtime: R,
310

            
311
    /// Whether or not we're operating in offline mode.
312
    offline: bool,
313

            
314
    /// If we're not in offline mode, stores whether or not the `DirMgr` has attempted
315
    /// to bootstrap yet or not.
316
    ///
317
    /// This exists in order to prevent starting two concurrent bootstrap tasks.
318
    ///
319
    /// (In offline mode, this does nothing.)
320
    bootstrap_started: AtomicBool,
321

            
322
    /// A filter that gets applied to directory objects before we use them.
323
    #[cfg(feature = "dirfilter")]
324
    filter: crate::filter::FilterConfig,
325

            
326
    /// A task schedule that can be used if we're bootstrapping.  If this is
327
    /// None, then there's currently a scheduled task in progress.
328
    task_schedule: Mutex<Option<TaskSchedule<R>>>,
329

            
330
    /// A task handle that we return to anybody who needs to manage our download process.
331
    task_handle: TaskHandle,
332
}
333

            
334
/// The possible origins of a document.
335
///
336
/// Used (for example) to report where we got a document from if it fails to
337
/// parse.
338
#[derive(Debug, Clone)]
339
#[non_exhaustive]
340
pub enum DocSource {
341
    /// We loaded the document from our cache.
342
    LocalCache,
343
    /// We fetched the document from a server.
344
    DirServer {
345
        /// Information about the server we fetched the document from.
346
        source: Option<SourceInfo>,
347
    },
348
}
349

            
350
impl std::fmt::Display for DocSource {
351
2
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352
2
        match self {
353
            DocSource::LocalCache => write!(f, "local cache"),
354
2
            DocSource::DirServer { source: None } => write!(f, "directory server"),
355
            DocSource::DirServer { source: Some(info) } => write!(f, "directory server {}", info),
356
        }
357
2
    }
358
}
359

            
360
impl<R: Runtime> DirMgr<R> {
361
    /// Try to load the directory from disk, without launching any
362
    /// kind of update process.
363
    ///
364
    /// This function runs in **offline** mode: it will give an error
365
    /// if the result is not up-to-date, or not fully downloaded.
366
    ///
367
    /// In general, you shouldn't use this function in a long-running
368
    /// program; it's only suitable for command-line or batch tools.
369
    // TODO: I wish this function didn't have to be async or take a runtime.
370
    pub async fn load_once(runtime: R, config: DirMgrConfig) -> Result<Arc<NetDir>> {
371
        let store = DirMgrStore::new(&config, runtime.clone(), true)?;
372
        let dirmgr = Arc::new(Self::from_config(config, runtime, store, None, true)?);
373

            
374
        // TODO: add some way to return a directory that isn't up-to-date
375
        let attempt = AttemptId::next();
376
        trace!(%attempt, "Trying to load a full directory from cache");
377
        let outcome = dirmgr.load_directory(attempt).await;
378
        trace!(%attempt, "Load result: {outcome:?}");
379
        let _success = outcome?;
380

            
381
        dirmgr
382
            .netdir(Timeliness::Timely)
383
            .map_err(|_| Error::DirectoryNotPresent)
384
    }
385

            
386
    /// Return a current netdir, either loading it or bootstrapping it
387
    /// as needed.
388
    ///
389
    /// Like load_once, but will try to bootstrap (or wait for another
390
    /// process to bootstrap) if we don't have an up-to-date
391
    /// bootstrapped directory.
392
    ///
393
    /// In general, you shouldn't use this function in a long-running
394
    /// program; it's only suitable for command-line or batch tools.
395
    pub async fn load_or_bootstrap_once(
396
        config: DirMgrConfig,
397
        runtime: R,
398
        store: DirMgrStore<R>,
399
        circmgr: Arc<CircMgr<R>>,
400
    ) -> Result<Arc<NetDir>> {
401
        let dirmgr = DirMgr::bootstrap_from_config(config, runtime, store, circmgr).await?;
402
        dirmgr
403
            .timely_netdir()
404
            .map_err(|_| Error::DirectoryNotPresent)
405
    }
406

            
407
    /// Create a new `DirMgr` in online mode, but don't bootstrap it yet.
408
    ///
409
    /// The `DirMgr` can be bootstrapped later with `bootstrap`.
410
8
    pub fn create_unbootstrapped(
411
8
        config: DirMgrConfig,
412
8
        runtime: R,
413
8
        store: DirMgrStore<R>,
414
8
        circmgr: Arc<CircMgr<R>>,
415
8
    ) -> Result<Arc<Self>> {
416
8
        Ok(Arc::new(DirMgr::from_config(
417
8
            config,
418
8
            runtime,
419
8
            store,
420
8
            Some(circmgr),
421
8
            false,
422
8
        )?))
423
8
    }
424

            
425
    /// Bootstrap a `DirMgr` created in online mode that hasn't been bootstrapped yet.
426
    ///
427
    /// This function will not return until the directory is bootstrapped enough to build circuits.
428
    /// It will also launch a background task that fetches any missing information, and that
429
    /// replaces the directory when a new one is available.
430
    ///
431
    /// This function is intended to be used together with `create_unbootstrapped`. There is no
432
    /// need to call this function otherwise.
433
    ///
434
    /// If bootstrapping has already successfully taken place, returns early with success.
435
    ///
436
    /// # Errors
437
    ///
438
    /// Returns an error if bootstrapping fails. If the error is [`Error::CantAdvanceState`],
439
    /// it may be possible to successfully bootstrap later on by calling this function again.
440
    ///
441
    /// # Panics
442
    ///
443
    /// Panics if the `DirMgr` passed to this function was not created in online mode, such as
444
    /// via `load_once`.
445
    #[allow(clippy::cognitive_complexity)] // TODO: Refactor
446
    pub async fn bootstrap(self: &Arc<Self>) -> Result<()> {
447
        if self.offline {
448
            return Err(Error::OfflineMode);
449
        }
450

            
451
        // The semantics of this are "attempt to replace a 'false' value with 'true'.
452
        // If the value in bootstrap_started was not 'false' when the attempt was made, returns
453
        // `Err`; this means another bootstrap attempt is in progress or has completed, so we
454
        // return early.
455

            
456
        // NOTE(eta): could potentially weaken the `Ordering` here in future
457
        if self
458
            .bootstrap_started
459
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
460
            .is_err()
461
        {
462
            debug!("Attempted to bootstrap twice; ignoring.");
463
            return Ok(());
464
        }
465

            
466
        // Use a RAII guard to reset `bootstrap_started` to `false` if we return early without
467
        // completing bootstrap.
468
        let reset_bootstrap_started = scopeguard::guard(&self.bootstrap_started, |v| {
469
            v.store(false, Ordering::SeqCst);
470
        });
471

            
472
        let schedule = {
473
            let sched = self.task_schedule.lock().expect("poisoned lock").take();
474
            match sched {
475
                Some(sched) => sched,
476
                None => {
477
                    debug!("Attempted to bootstrap twice; ignoring.");
478
                    return Ok(());
479
                }
480
            }
481
        };
482

            
483
        // Try to load from the cache.
484
        let attempt_id = AttemptId::next();
485
        trace!(attempt=%attempt_id, "Starting to bootstrap directory");
486
        let have_directory = self.load_directory(attempt_id).await?;
487

            
488
        let (mut sender, receiver) = if have_directory {
489
            info!("Loaded a good directory from cache.");
490
            (None, None)
491
        } else {
492
            info!("Didn't get usable directory from cache.");
493
            let (sender, receiver) = oneshot::channel();
494
            (Some(sender), Some(receiver))
495
        };
496

            
497
        // Whether we loaded or not, we now start downloading.
498
        let dirmgr_weak = Arc::downgrade(self);
499
        self.runtime
500
            .spawn(async move {
501
                // Use an RAII guard to make sure that when this task exits, the
502
                // TaskSchedule object is put back.
503
                //
504
                // TODO(nick): Putting the schedule back isn't actually useful
505
                // if the task exits _after_ we've bootstrapped for the first
506
                // time, because of how bootstrap_started works.
507
                let mut schedule = scopeguard::guard(schedule, |schedule| {
508
                    if let Some(dm) = Weak::upgrade(&dirmgr_weak) {
509
                        *dm.task_schedule.lock().expect("poisoned lock") = Some(schedule);
510
                    }
511
                });
512

            
513
                // Don't warn when these are Error::ManagerDropped: that
514
                // means that the DirMgr has been shut down.
515
                if let Err(e) =
516
                    Self::reload_until_owner(&dirmgr_weak, &mut schedule, attempt_id, &mut sender)
517
                        .await
518
                {
519
                    match e {
520
                        Error::ManagerDropped => {}
521
                        _ => warn_report!(e, "Unrecovered error while waiting for bootstrap",),
522
                    }
523
                } else if let Err(e) =
524
                    Self::download_forever(dirmgr_weak.clone(), &mut schedule, attempt_id, sender)
525
                        .await
526
                {
527
                    match e {
528
                        Error::ManagerDropped => {}
529
                        _ => warn_report!(e, "Unrecovered error while downloading"),
530
                    }
531
                }
532
            })
533
            .map_err(|e| Error::from_spawn("directory updater task", e))?;
534

            
535
        if let Some(receiver) = receiver {
536
            match receiver.await {
537
                Ok(()) => {
538
                    info!("We have enough information to build circuits.");
539
                    // Disarm the RAII guard, since we succeeded.  Now bootstrap_started will remain true.
540
                    let _ = ScopeGuard::into_inner(reset_bootstrap_started);
541
                }
542
                Err(_) => {
543
                    warn!("Bootstrapping task exited before finishing.");
544
                    return Err(Error::CantAdvanceState);
545
                }
546
            }
547
        }
548
        Ok(())
549
    }
550

            
551
    /// Returns `true` if a bootstrap attempt is in progress, or successfully completed.
552
    pub fn bootstrap_started(&self) -> bool {
553
        self.bootstrap_started.load(Ordering::SeqCst)
554
    }
555

            
556
    /// Return a new directory manager from a given configuration,
557
    /// bootstrapping from the network as necessary.
558
    pub async fn bootstrap_from_config(
559
        config: DirMgrConfig,
560
        runtime: R,
561
        store: DirMgrStore<R>,
562
        circmgr: Arc<CircMgr<R>>,
563
    ) -> Result<Arc<Self>> {
564
        let dirmgr = Self::create_unbootstrapped(config, runtime, store, circmgr)?;
565

            
566
        dirmgr.bootstrap().await?;
567

            
568
        Ok(dirmgr)
569
    }
570

            
571
    /// Try forever to either lock the storage (and thereby become the
572
    /// owner), or to reload the database.
573
    ///
574
    /// If we have begin to have a bootstrapped directory, send a
575
    /// message using `on_complete`.
576
    ///
577
    /// If we eventually become the owner, return Ok().
578
    #[allow(clippy::cognitive_complexity)] // TODO: Refactor?
579
    async fn reload_until_owner(
580
        weak: &Weak<Self>,
581
        schedule: &mut TaskSchedule<R>,
582
        attempt_id: AttemptId,
583
        on_complete: &mut Option<oneshot::Sender<()>>,
584
    ) -> Result<()> {
585
        let mut logged = false;
586
        let mut bootstrapped;
587
        {
588
            let dirmgr = upgrade_weak_ref(weak)?;
589
            bootstrapped = dirmgr.netdir.get().is_some();
590
        }
591

            
592
        loop {
593
            {
594
                let dirmgr = upgrade_weak_ref(weak)?;
595
                trace!("Trying to take ownership of the directory cache lock");
596
                if dirmgr.try_upgrade_to_readwrite()? {
597
                    // We now own the lock!  (Maybe we owned it before; the
598
                    // upgrade_to_readwrite() function is idempotent.)  We can
599
                    // do our own bootstrapping.
600
                    if logged {
601
                        info!("The previous owning process has given up the lock. We are now in charge of managing the directory.");
602
                    }
603
                    return Ok(());
604
                }
605
            }
606

            
607
            if !logged {
608
                logged = true;
609
                if bootstrapped {
610
                    info!("Another process is managing the directory. We'll use its cache.");
611
                } else {
612
                    info!("Another process is bootstrapping the directory. Waiting till it finishes or exits.");
613
                }
614
            }
615

            
616
            // We don't own the lock.  Somebody else owns the cache.  They
617
            // should be updating it.  Wait a bit, then try again.
618
            let pause = if bootstrapped {
619
                std::time::Duration::new(120, 0)
620
            } else {
621
                std::time::Duration::new(5, 0)
622
            };
623
            schedule.sleep(pause).await?;
624
            // TODO: instead of loading the whole thing we should have a
625
            // database entry that says when the last update was, or use
626
            // our state functions.
627
            {
628
                let dirmgr = upgrade_weak_ref(weak)?;
629
                trace!("Trying to load from the directory cache");
630
                if dirmgr.load_directory(attempt_id).await? {
631
                    // Successfully loaded a bootstrapped directory.
632
                    if let Some(send_done) = on_complete.take() {
633
                        let _ = send_done.send(());
634
                    }
635
                    if !bootstrapped {
636
                        info!("The directory is now bootstrapped.");
637
                    }
638
                    bootstrapped = true;
639
                }
640
            }
641
        }
642
    }
643

            
644
    /// Try to fetch our directory info and keep it updated, indefinitely.
645
    ///
646
    /// If we have begin to have a bootstrapped directory, send a
647
    /// message using `on_complete`.
648
    #[allow(clippy::cognitive_complexity)] // TODO: Refactor?
649
    async fn download_forever(
650
        weak: Weak<Self>,
651
        schedule: &mut TaskSchedule<R>,
652
        mut attempt_id: AttemptId,
653
        mut on_complete: Option<oneshot::Sender<()>>,
654
    ) -> Result<()> {
655
        let mut state: Box<dyn DirState> = {
656
            let dirmgr = upgrade_weak_ref(&weak)?;
657
            Box::new(state::GetConsensusState::new(
658
                dirmgr.runtime.clone(),
659
                dirmgr.config.get(),
660
                CacheUsage::CacheOkay,
661
                Some(dirmgr.netdir.clone()),
662
                #[cfg(feature = "dirfilter")]
663
                dirmgr
664
                    .filter
665
                    .clone()
666
                    .unwrap_or_else(|| Arc::new(crate::filter::NilFilter)),
667
            ))
668
        };
669

            
670
        trace!("Entering download loop.");
671

            
672
        loop {
673
            let mut usable = false;
674

            
675
            let retry_config = {
676
                let dirmgr = upgrade_weak_ref(&weak)?;
677
                // TODO(nickm): instead of getting this every time we loop, it
678
                // might be a good idea to refresh it with each attempt, at
679
                // least at the point of checking the number of attempts.
680
                dirmgr.config.get().schedule.retry_bootstrap
681
            };
682
            let mut retry_delay = retry_config.schedule();
683

            
684
            'retry_attempt: for try_num in retry_config.attempts() {
685
                trace!(attempt=%attempt_id, ?try_num, "Trying to download a directory.");
686
                let outcome = bootstrap::download(
687
                    Weak::clone(&weak),
688
                    &mut state,
689
                    schedule,
690
                    attempt_id,
691
                    &mut on_complete,
692
                )
693
                .await;
694
                trace!(attempt=%attempt_id, ?try_num, ?outcome, "Download is over.");
695

            
696
                if let Err(err) = outcome {
697
                    if state.is_ready(Readiness::Usable) {
698
                        usable = true;
699
                        info_report!(err, "Unable to completely download a directory. (Nevertheless, the directory is usable, so we'll pause for now)");
700
                        break 'retry_attempt;
701
                    }
702

            
703
                    match err.bootstrap_action() {
704
                        BootstrapAction::Nonfatal => {
705
                            return Err(into_internal!(
706
                                "Nonfatal error should not have propagated here"
707
                            )(err)
708
                            .into());
709
                        }
710
                        BootstrapAction::Reset => {}
711
                        BootstrapAction::Fatal => return Err(err),
712
                    }
713

            
714
                    let delay = retry_delay.next_delay(&mut rand::rng());
715
                    warn_report!(
716
                        err,
717
                        "Unable to download a usable directory. (We will restart in {})",
718
                        humantime::format_duration(delay),
719
                    );
720
                    {
721
                        let dirmgr = upgrade_weak_ref(&weak)?;
722
                        dirmgr.note_reset(attempt_id);
723
                    }
724
                    schedule.sleep(delay).await?;
725
                    state = state.reset();
726
                } else {
727
                    info!(attempt=%attempt_id, "Directory is complete.");
728
                    usable = true;
729
                    break 'retry_attempt;
730
                }
731
            }
732

            
733
            if !usable {
734
                // we ran out of attempts.
735
                warn!(
736
                    "We failed {} times to bootstrap a directory. We're going to give up.",
737
                    retry_config.n_attempts()
738
                );
739
                return Err(Error::CantAdvanceState);
740
            } else {
741
                // Report success, if appropriate.
742
                if let Some(send_done) = on_complete.take() {
743
                    let _ = send_done.send(());
744
                }
745
            }
746

            
747
            let reset_at = state.reset_time();
748
            match reset_at {
749
                Some(t) => {
750
                    trace!("Sleeping until {}", time::OffsetDateTime::from(t));
751
                    schedule.sleep_until_wallclock(t).await?;
752
                }
753
                None => return Ok(()),
754
            }
755
            attempt_id = bootstrap::AttemptId::next();
756
            trace!(attempt=%attempt_id, "Beginning new attempt to bootstrap directory");
757
            state = state.reset();
758
        }
759
    }
760

            
761
    /// Get a reference to the circuit manager, if we have one.
762
2
    fn circmgr(&self) -> Result<Arc<CircMgr<R>>> {
763
2
        self.circmgr.clone().ok_or(Error::NoDownloadSupport)
764
2
    }
765

            
766
    /// Try to change our configuration to `new_config`.
767
    ///
768
    /// Actual behavior will depend on the value of `how`.
769
4
    pub fn reconfigure(
770
4
        &self,
771
4
        new_config: &DirMgrConfig,
772
4
        how: tor_config::Reconfigure,
773
4
    ) -> std::result::Result<(), tor_config::ReconfigureError> {
774
4
        let config = self.config.get();
775
4
        // We don't support changing these: doing so basically would require us
776
4
        // to abort all our in-progress downloads, since they might be based on
777
4
        // no-longer-viable information.
778
4
        // NOTE: keep this in sync with the behaviour of `DirMgrConfig::update_from_config`
779
4
        if new_config.cache_dir != config.cache_dir {
780
            how.cannot_change("storage.cache_dir")?;
781
4
        }
782
4
        if new_config.cache_trust != config.cache_trust {
783
            how.cannot_change("storage.permissions")?;
784
4
        }
785
4
        if new_config.authorities() != config.authorities() {
786
            how.cannot_change("network.authorities")?;
787
4
        }
788

            
789
4
        if how == tor_config::Reconfigure::CheckAllOrNothing {
790
2
            return Ok(());
791
2
        }
792
2

            
793
2
        let params_changed = new_config.override_net_params != config.override_net_params;
794
2

            
795
2
        self.config
796
2
            .map_and_replace(|cfg| cfg.update_from_config(new_config));
797
2

            
798
2
        if params_changed {
799
            let _ignore_err = self.netdir.mutate(|netdir| {
800
                netdir.replace_overridden_parameters(&new_config.override_net_params);
801
                Ok(())
802
            });
803
            {
804
                let mut params = self.default_parameters.lock().expect("lock failed");
805
                *params = Arc::new(NetParameters::from_map(&new_config.override_net_params));
806
            }
807

            
808
            // (It's okay to ignore the error, since it just means that there
809
            // was no current netdir.)
810
            self.events.publish(DirEvent::NewConsensus);
811
2
        }
812

            
813
2
        Ok(())
814
4
    }
815

            
816
    /// Return a stream of [`DirBootstrapStatus`] events to tell us about changes
817
    /// in the latest directory's bootstrap status.
818
    ///
819
    /// Note that this stream can be lossy: the caller will not necessarily
820
    /// observe every event on the stream
821
8
    pub fn bootstrap_events(&self) -> event::DirBootstrapEvents {
822
8
        self.receive_status.clone()
823
8
    }
824

            
825
    /// Replace the latest status with `progress` and broadcast to anybody
826
    /// watching via a [`DirBootstrapEvents`] stream.
827
30
    fn update_progress(&self, attempt_id: AttemptId, progress: DirProgress) {
828
30
        // TODO(nickm): can I kill off this lock by having something else own the sender?
829
30
        let mut sender = self.send_status.lock().expect("poisoned lock");
830
30
        let mut status = sender.borrow_mut();
831
30

            
832
30
        status.update_progress(attempt_id, progress);
833
30
    }
834

            
835
    /// Update our status tracker to note that some number of errors has
836
    /// occurred.
837
    fn note_errors(&self, attempt_id: AttemptId, n_errors: usize) {
838
        if n_errors == 0 {
839
            return;
840
        }
841
        let mut sender = self.send_status.lock().expect("poisoned lock");
842
        let mut status = sender.borrow_mut();
843

            
844
        status.note_errors(attempt_id, n_errors);
845
    }
846

            
847
    /// Update our status tracker to note that we've needed to reset our download attempt.
848
    fn note_reset(&self, attempt_id: AttemptId) {
849
        let mut sender = self.send_status.lock().expect("poisoned lock");
850
        let mut status = sender.borrow_mut();
851

            
852
        status.note_reset(attempt_id);
853
    }
854

            
855
    /// Try to make this a directory manager with read-write access to its
856
    /// storage.
857
    ///
858
    /// Return true if we got the lock, or if we already had it.
859
    ///
860
    /// Return false if another process has the lock
861
    fn try_upgrade_to_readwrite(&self) -> Result<bool> {
862
        self.store
863
            .lock()
864
            .expect("Directory storage lock poisoned")
865
            .upgrade_to_readwrite()
866
    }
867

            
868
    /// Return a reference to the store, if it is currently read-write.
869
    #[cfg(test)]
870
4
    fn store_if_rw(&self) -> Option<&Mutex<DynStore>> {
871
4
        let rw = !self
872
4
            .store
873
4
            .lock()
874
4
            .expect("Directory storage lock poisoned")
875
4
            .is_readonly();
876
4
        // A race-condition is possible here, but I believe it's harmless.
877
4
        if rw {
878
4
            Some(&self.store)
879
        } else {
880
            None
881
        }
882
4
    }
883

            
884
    /// Construct a DirMgr from a DirMgrConfig.
885
    ///
886
    /// If `offline` is set, opens the SQLite store read-only and sets the offline flag in the
887
    /// returned manager.
888
    #[allow(clippy::unnecessary_wraps)] // API compat and future-proofing
889
22
    fn from_config(
890
22
        config: DirMgrConfig,
891
22
        runtime: R,
892
22
        store: DirMgrStore<R>,
893
22
        circmgr: Option<Arc<CircMgr<R>>>,
894
22
        offline: bool,
895
22
    ) -> Result<Self> {
896
22
        let netdir = Arc::new(SharedMutArc::new());
897
22
        let events = event::FlagPublisher::new();
898
22
        let default_parameters = NetParameters::from_map(&config.override_net_params);
899
22
        let default_parameters = Mutex::new(Arc::new(default_parameters));
900
22

            
901
22
        let (send_status, receive_status) = postage::watch::channel();
902
22
        let send_status = Mutex::new(send_status);
903
22
        let receive_status = DirBootstrapEvents {
904
22
            inner: receive_status,
905
22
        };
906
22
        #[cfg(feature = "dirfilter")]
907
22
        let filter = config.extensions.filter.clone();
908
22

            
909
22
        // We create these early so the client code can access task_handle before bootstrap() returns.
910
22
        let (task_schedule, task_handle) = TaskSchedule::new(runtime.clone());
911
22
        let task_schedule = Mutex::new(Some(task_schedule));
912

            
913
        // We load the cached protocol recommendations unconditionally: the caller needs them even
914
        // if it does not try to load the reset of the cache.
915
22
        let protocols = {
916
22
            let store = store.store.lock().expect("lock poisoned");
917
22
            store
918
22
                .cached_protocol_recommendations()?
919
22
                .map(|(t, p)| (t, Arc::new(p)))
920
22
        };
921
22

            
922
22
        Ok(DirMgr {
923
22
            config: config.into(),
924
22
            store: store.store,
925
22
            netdir,
926
22
            protocols: Mutex::new(protocols),
927
22
            default_parameters,
928
22
            events,
929
22
            send_status,
930
22
            receive_status,
931
22
            circmgr,
932
22
            runtime,
933
22
            offline,
934
22
            bootstrap_started: AtomicBool::new(false),
935
22
            #[cfg(feature = "dirfilter")]
936
22
            filter,
937
22
            task_schedule,
938
22
            task_handle,
939
22
        })
940
22
    }
941

            
942
    /// Load the latest non-pending non-expired directory from the
943
    /// cache, if it is newer than the one we have.
944
    ///
945
    /// Return false if there is no such consensus.
946
    async fn load_directory(self: &Arc<Self>, attempt_id: AttemptId) -> Result<bool> {
947
        let state = state::GetConsensusState::new(
948
            self.runtime.clone(),
949
            self.config.get(),
950
            CacheUsage::CacheOnly,
951
            None,
952
            #[cfg(feature = "dirfilter")]
953
            self.filter
954
                .clone()
955
                .unwrap_or_else(|| Arc::new(crate::filter::NilFilter)),
956
        );
957
        let _ = bootstrap::load(Arc::clone(self), Box::new(state), attempt_id).await?;
958

            
959
        Ok(self.netdir.get().is_some())
960
    }
961

            
962
    /// Return a new asynchronous stream that will receive notification
963
    /// whenever the consensus has changed.
964
    ///
965
    /// Multiple events may be batched up into a single item: each time
966
    /// this stream yields an event, all you can assume is that the event has
967
    /// occurred at least once.
968
    pub fn events(&self) -> impl futures::Stream<Item = DirEvent> {
969
        self.events.subscribe()
970
    }
971

            
972
    /// Try to load the text of a single document described by `doc` from
973
    /// storage.
974
6
    pub fn text(&self, doc: &DocId) -> Result<Option<DocumentText>> {
975
        use itertools::Itertools;
976
6
        let mut result = HashMap::new();
977
6
        let query: DocQuery = (*doc).into();
978
6
        let store = self.store.lock().expect("store lock poisoned");
979
6
        query.load_from_store_into(&mut result, &**store)?;
980
6
        let item = result.into_iter().at_most_one().map_err(|_| {
981
            Error::CacheCorruption("Found more than one entry in storage for given docid")
982
6
        })?;
983
6
        if let Some((docid, doctext)) = item {
984
4
            if &docid != doc {
985
                return Err(Error::CacheCorruption(
986
                    "Item from storage had incorrect docid.",
987
                ));
988
4
            }
989
4
            Ok(Some(doctext))
990
        } else {
991
2
            Ok(None)
992
        }
993
6
    }
994

            
995
    /// Load the text for a collection of documents.
996
    ///
997
    /// If many of the documents have the same type, this can be more
998
    /// efficient than calling [`text`](Self::text).
999
2
    pub fn texts<T>(&self, docs: T) -> Result<HashMap<DocId, DocumentText>>
2
    where
2
        T: IntoIterator<Item = DocId>,
2
    {
2
        let partitioned = docid::partition_by_type(docs);
2
        let mut result = HashMap::new();
2
        let store = self.store.lock().expect("store lock poisoned");
6
        for (_, query) in partitioned.into_iter() {
6
            query.load_from_store_into(&mut result, &**store)?;
        }
2
        Ok(result)
2
    }
    /// Given a request we sent and the response we got from a
    /// directory server, see whether we should expand that response
    /// into "something larger".
    ///
    /// Currently, this handles expanding consensus diffs, and nothing
    /// else.  We do it at this stage of our downloading operation
    /// because it requires access to the store.
12
    fn expand_response_text(&self, req: &ClientRequest, text: String) -> Result<String> {
12
        if let ClientRequest::Consensus(req) = req {
8
            if tor_consdiff::looks_like_diff(&text) {
4
                if let Some(old_d) = req.old_consensus_digests().next() {
4
                    let db_val = {
4
                        let s = self.store.lock().expect("Directory storage lock poisoned");
4
                        s.consensus_by_sha3_digest_of_signed_part(old_d)?
                    };
4
                    if let Some((old_consensus, meta)) = db_val {
4
                        info!("Applying a consensus diff");
4
                        let new_consensus = tor_consdiff::apply_diff(
4
                            old_consensus.as_str()?,
4
                            &text,
4
                            Some(*meta.sha3_256_of_signed()),
                        )?;
4
                        new_consensus.check_digest()?;
2
                        return Ok(new_consensus.to_string());
                    }
                }
                return Err(Error::Unwanted(
                    "Received a consensus diff we did not ask for",
                ));
4
            }
4
        }
8
        Ok(text)
12
    }
    /// If `state` has netdir changes to apply, apply them to our netdir.
    #[allow(clippy::cognitive_complexity)]
16
    fn apply_netdir_changes(
16
        self: &Arc<Self>,
16
        state: &mut Box<dyn DirState>,
16
        store: &mut dyn Store,
16
    ) -> Result<()> {
16
        if let Some(change) = state.get_netdir_change() {
            match change {
                NetDirChange::AttemptReplace {
                    netdir,
                    consensus_meta,
                } => {
                    // Check the new netdir is sufficient, if we have a circmgr.
                    // (Unwraps are fine because the `Option` is `Some` until we take it.)
                    if let Some(ref cm) = self.circmgr {
                        if !cm
                            .netdir_is_sufficient(netdir.as_ref().expect("AttemptReplace had None"))
                        {
                            debug!("Got a new NetDir, but it doesn't have enough guards yet.");
                            return Ok(());
                        }
                    }
                    let is_stale = {
                        // Done inside a block to not hold a long-lived copy of the NetDir.
                        self.netdir
                            .get()
                            .map(|x| {
                                x.lifetime().valid_after()
                                    > netdir
                                        .as_ref()
                                        .expect("AttemptReplace had None")
                                        .lifetime()
                                        .valid_after()
                            })
                            .unwrap_or(false)
                    };
                    if is_stale {
                        warn!("Got a new NetDir, but it's older than the one we currently have!");
                        return Err(Error::NetDirOlder);
                    }
                    let cfg = self.config.get();
                    let mut netdir = netdir.take().expect("AttemptReplace had None");
                    netdir.replace_overridden_parameters(&cfg.override_net_params);
                    self.netdir.replace(netdir);
                    self.events.publish(DirEvent::NewConsensus);
                    self.events.publish(DirEvent::NewDescriptors);
                    info!("Marked consensus usable.");
                    if !store.is_readonly() {
                        store.mark_consensus_usable(consensus_meta)?;
                        // Now that a consensus is usable, older consensuses may
                        // need to expire.
                        store.expire_all(&crate::storage::EXPIRATION_DEFAULTS)?;
                    }
                    Ok(())
                }
                NetDirChange::AddMicrodescs(mds) => {
                    self.netdir.mutate(|netdir| {
                        for md in mds.drain(..) {
                            netdir.add_microdesc(md);
                        }
                        Ok(())
                    })?;
                    self.events.publish(DirEvent::NewDescriptors);
                    Ok(())
                }
                NetDirChange::SetRequiredProtocol { timestamp, protos } => {
                    if !store.is_readonly() {
                        store.update_protocol_recommendations(timestamp, protos.as_ref())?;
                    }
                    let mut pr = self.protocols.lock().expect("Poisoned lock");
                    *pr = Some((timestamp, protos));
                    self.events.publish(DirEvent::NewProtocolRecommendation);
                    Ok(())
                }
            }
        } else {
16
            Ok(())
        }
16
    }
}
/// A degree of readiness for a given directory state object.
#[derive(Debug, Copy, Clone)]
enum Readiness {
    /// There is no more information to download.
    Complete,
    /// There is more information to download, but we don't need to
    Usable,
}
/// Try to upgrade a weak reference to a DirMgr, and give an error on
/// failure.
24
fn upgrade_weak_ref<T>(weak: &Weak<T>) -> Result<Arc<T>> {
24
    Weak::upgrade(weak).ok_or(Error::ManagerDropped)
24
}
/// Given a time `now`, and an amount of tolerated clock skew `tolerance`,
/// return the age of the oldest consensus that we should request at that time.
8
pub(crate) fn default_consensus_cutoff(
8
    now: SystemTime,
8
    tolerance: &DirTolerance,
8
) -> Result<SystemTime> {
    /// We _always_ allow at least this much age in our consensuses, to account
    /// for the fact that consensuses have some lifetime.
    const MIN_AGE_TO_ALLOW: Duration = Duration::from_secs(3 * 3600);
8
    let allow_skew = std::cmp::max(MIN_AGE_TO_ALLOW, tolerance.post_valid_tolerance);
8
    let cutoff = time::OffsetDateTime::from(now - allow_skew);
8
    // We now round cutoff to the next hour, so that we aren't leaking our exact
8
    // time to the directory cache.
8
    //
8
    // With the time crate, it's easier to calculate the "next hour" by rounding
8
    // _down_ then adding an hour; rounding up would sometimes require changing
8
    // the date too.
8
    let (h, _m, _s) = cutoff.to_hms();
8
    let cutoff = cutoff.replace_time(
8
        time::Time::from_hms(h, 0, 0)
8
            .map_err(tor_error::into_internal!("Failed clock calculation"))?,
    );
8
    let cutoff = cutoff + Duration::from_secs(3600);
8

            
8
    Ok(cutoff.into())
8
}
/// Return a list of the protocols [supported](tor_protover::doc_supported) by this crate
/// when running as a client.
177
pub fn supported_client_protocols() -> tor_protover::Protocols {
    use tor_protover::named::*;
    // WARNING: REMOVING ELEMENTS FROM THIS LIST CAN BE DANGEROUS!
    // SEE [`tor_protover::doc_changing`]
177
    [
177
        //
177
        DIRCACHE_CONSDIFF,
177
    ]
177
    .into_iter()
177
    .collect()
177
}
#[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 crate::docmeta::{AuthCertMeta, ConsensusMeta};
    use std::time::Duration;
    use tempfile::TempDir;
    use tor_basic_utils::test_rng::testing_rng;
    use tor_netdoc::doc::netstatus::ConsensusFlavor;
    use tor_netdoc::doc::{authcert::AuthCertKeyIds, netstatus::Lifetime};
    use tor_rtcompat::SleepProvider;
    #[test]
    fn protocols() {
        let pr = supported_client_protocols();
        let expected = "DirCache=2".parse().unwrap();
        assert_eq!(pr, expected);
    }
    pub(crate) fn new_mgr<R: Runtime>(runtime: R) -> (TempDir, DirMgr<R>) {
        let dir = TempDir::new().unwrap();
        let config = DirMgrConfig {
            cache_dir: dir.path().into(),
            ..Default::default()
        };
        let store = DirMgrStore::new(&config, runtime.clone(), false).unwrap();
        let dirmgr = DirMgr::from_config(config, runtime, store, None, false).unwrap();
        (dir, dirmgr)
    }
    #[test]
    fn failing_accessors() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let (_tempdir, mgr) = new_mgr(rt);
            assert!(mgr.circmgr().is_err());
            assert!(mgr.netdir(Timeliness::Unchecked).is_err());
        });
    }
    #[test]
    fn load_and_store_internals() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let now = rt.wallclock();
            let tomorrow = now + Duration::from_secs(86400);
            let later = tomorrow + Duration::from_secs(86400);
            let (_tempdir, mgr) = new_mgr(rt);
            // Seed the storage with a bunch of junk.
            let d1 = [5_u8; 32];
            let d2 = [7; 32];
            let d3 = [42; 32];
            let d4 = [99; 20];
            let d5 = [12; 20];
            let certid1 = AuthCertKeyIds {
                id_fingerprint: d4.into(),
                sk_fingerprint: d5.into(),
            };
            let certid2 = AuthCertKeyIds {
                id_fingerprint: d5.into(),
                sk_fingerprint: d4.into(),
            };
            {
                let mut store = mgr.store.lock().unwrap();
                store
                    .store_microdescs(
                        &[
                            ("Fake micro 1", &d1),
                            ("Fake micro 2", &d2),
                            ("Fake micro 3", &d3),
                        ],
                        now,
                    )
                    .unwrap();
                #[cfg(feature = "routerdesc")]
                store
                    .store_routerdescs(&[("Fake rd1", now, &d4), ("Fake rd2", now, &d5)])
                    .unwrap();
                store
                    .store_authcerts(&[
                        (
                            AuthCertMeta::new(certid1, now, tomorrow),
                            "Fake certificate one",
                        ),
                        (
                            AuthCertMeta::new(certid2, now, tomorrow),
                            "Fake certificate two",
                        ),
                    ])
                    .unwrap();
                let cmeta = ConsensusMeta::new(
                    Lifetime::new(now, tomorrow, later).unwrap(),
                    [102; 32],
                    [103; 32],
                );
                store
                    .store_consensus(&cmeta, ConsensusFlavor::Microdesc, false, "Fake consensus!")
                    .unwrap();
            }
            // Try to get it with text().
            let t1 = mgr.text(&DocId::Microdesc(d1)).unwrap().unwrap();
            assert_eq!(t1.as_str(), Ok("Fake micro 1"));
            let t2 = mgr
                .text(&DocId::LatestConsensus {
                    flavor: ConsensusFlavor::Microdesc,
                    cache_usage: CacheUsage::CacheOkay,
                })
                .unwrap()
                .unwrap();
            assert_eq!(t2.as_str(), Ok("Fake consensus!"));
            let t3 = mgr.text(&DocId::Microdesc([255; 32])).unwrap();
            assert!(t3.is_none());
            // Now try texts()
            let d_bogus = DocId::Microdesc([255; 32]);
            let res = mgr
                .texts(vec![
                    DocId::Microdesc(d2),
                    DocId::Microdesc(d3),
                    d_bogus,
                    DocId::AuthCert(certid2),
                    #[cfg(feature = "routerdesc")]
                    DocId::RouterDesc(d5),
                ])
                .unwrap();
            assert_eq!(
                res.get(&DocId::Microdesc(d2)).unwrap().as_str(),
                Ok("Fake micro 2")
            );
            assert_eq!(
                res.get(&DocId::Microdesc(d3)).unwrap().as_str(),
                Ok("Fake micro 3")
            );
            assert!(!res.contains_key(&d_bogus));
            assert_eq!(
                res.get(&DocId::AuthCert(certid2)).unwrap().as_str(),
                Ok("Fake certificate two")
            );
            #[cfg(feature = "routerdesc")]
            assert_eq!(
                res.get(&DocId::RouterDesc(d5)).unwrap().as_str(),
                Ok("Fake rd2")
            );
        });
    }
    #[test]
    fn make_consensus_request() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let now = rt.wallclock();
            let tomorrow = now + Duration::from_secs(86400);
            let later = tomorrow + Duration::from_secs(86400);
            let (_tempdir, mgr) = new_mgr(rt);
            let config = DirMgrConfig::default();
            // Try with an empty store.
            let req = {
                let store = mgr.store.lock().unwrap();
                bootstrap::make_consensus_request(
                    now,
                    ConsensusFlavor::Microdesc,
                    &**store,
                    &config,
                )
                .unwrap()
            };
            let tolerance = DirTolerance::default().post_valid_tolerance;
            match req {
                ClientRequest::Consensus(r) => {
                    assert_eq!(r.old_consensus_digests().count(), 0);
                    let date = r.last_consensus_date().unwrap();
                    assert!(date >= now - tolerance);
                    assert!(date <= now - tolerance + Duration::from_secs(3600));
                }
                _ => panic!("Wrong request type"),
            }
            // Add a fake consensus record.
            let d_prev = [42; 32];
            {
                let mut store = mgr.store.lock().unwrap();
                let cmeta = ConsensusMeta::new(
                    Lifetime::new(now, tomorrow, later).unwrap(),
                    d_prev,
                    [103; 32],
                );
                store
                    .store_consensus(&cmeta, ConsensusFlavor::Microdesc, false, "Fake consensus!")
                    .unwrap();
            }
            // Now try again.
            let req = {
                let store = mgr.store.lock().unwrap();
                bootstrap::make_consensus_request(
                    now,
                    ConsensusFlavor::Microdesc,
                    &**store,
                    &config,
                )
                .unwrap()
            };
            match req {
                ClientRequest::Consensus(r) => {
                    let ds: Vec<_> = r.old_consensus_digests().collect();
                    assert_eq!(ds.len(), 1);
                    assert_eq!(ds[0], &d_prev);
                    assert_eq!(r.last_consensus_date(), Some(now));
                }
                _ => panic!("Wrong request type"),
            }
        });
    }
    #[test]
    fn make_other_requests() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            use rand::Rng;
            let (_tempdir, mgr) = new_mgr(rt);
            let certid1 = AuthCertKeyIds {
                id_fingerprint: [99; 20].into(),
                sk_fingerprint: [100; 20].into(),
            };
            let mut rng = testing_rng();
            #[cfg(feature = "routerdesc")]
            let rd_ids: Vec<DocId> = (0..1000).map(|_| DocId::RouterDesc(rng.random())).collect();
            let md_ids: Vec<DocId> = (0..1000).map(|_| DocId::Microdesc(rng.random())).collect();
            let config = DirMgrConfig::default();
            // Try an authcert.
            let query = DocId::AuthCert(certid1);
            let store = mgr.store.lock().unwrap();
            let reqs =
                bootstrap::make_requests_for_documents(&mgr.runtime, &[query], &**store, &config)
                    .unwrap();
            assert_eq!(reqs.len(), 1);
            let req = &reqs[0];
            if let ClientRequest::AuthCert(r) = req {
                assert_eq!(r.keys().next(), Some(&certid1));
            } else {
                panic!();
            }
            // Try a bunch of mds.
            let reqs =
                bootstrap::make_requests_for_documents(&mgr.runtime, &md_ids, &**store, &config)
                    .unwrap();
            assert_eq!(reqs.len(), 2);
            assert!(matches!(reqs[0], ClientRequest::Microdescs(_)));
            // Try a bunch of rds.
            #[cfg(feature = "routerdesc")]
            {
                let reqs = bootstrap::make_requests_for_documents(
                    &mgr.runtime,
                    &rd_ids,
                    &**store,
                    &config,
                )
                .unwrap();
                assert_eq!(reqs.len(), 2);
                assert!(matches!(reqs[0], ClientRequest::RouterDescs(_)));
            }
        });
    }
    #[test]
    fn expand_response() {
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let now = rt.wallclock();
            let day = Duration::from_secs(86400);
            let config = DirMgrConfig::default();
            let (_tempdir, mgr) = new_mgr(rt);
            // Try a simple request: nothing should happen.
            let q = DocId::Microdesc([99; 32]);
            let r = {
                let store = mgr.store.lock().unwrap();
                bootstrap::make_requests_for_documents(&mgr.runtime, &[q], &**store, &config)
                    .unwrap()
            };
            let expanded = mgr.expand_response_text(&r[0], "ABC".to_string());
            assert_eq!(&expanded.unwrap(), "ABC");
            // Try a consensus response that doesn't look like a diff in
            // response to a query that doesn't ask for one.
            let latest_id = DocId::LatestConsensus {
                flavor: ConsensusFlavor::Microdesc,
                cache_usage: CacheUsage::CacheOkay,
            };
            let r = {
                let store = mgr.store.lock().unwrap();
                bootstrap::make_requests_for_documents(
                    &mgr.runtime,
                    &[latest_id],
                    &**store,
                    &config,
                )
                .unwrap()
            };
            let expanded = mgr.expand_response_text(&r[0], "DEF".to_string());
            assert_eq!(&expanded.unwrap(), "DEF");
            // Now stick some metadata and a string into the storage so that
            // we can ask for a diff.
            {
                let mut store = mgr.store.lock().unwrap();
                let d_in = [0x99; 32]; // This one, we can fake.
                let cmeta = ConsensusMeta::new(
                    Lifetime::new(now, now + day, now + 2 * day).unwrap(),
                    d_in,
                    d_in,
                );
                store
                    .store_consensus(
                        &cmeta,
                        ConsensusFlavor::Microdesc,
                        false,
                        "line 1\nline2\nline 3\n",
                    )
                    .unwrap();
            }
            // Try expanding something that isn't a consensus, even if we'd like
            // one.
            let r = {
                let store = mgr.store.lock().unwrap();
                bootstrap::make_requests_for_documents(
                    &mgr.runtime,
                    &[latest_id],
                    &**store,
                    &config,
                )
                .unwrap()
            };
            let expanded = mgr.expand_response_text(&r[0], "hello".to_string());
            assert_eq!(&expanded.unwrap(), "hello");
            // Finally, try "expanding" a diff (by applying it and checking the digest.
            let diff = "network-status-diff-version 1
hash 9999999999999999999999999999999999999999999999999999999999999999 8382374ca766873eb0d2530643191c6eaa2c5e04afa554cbac349b5d0592d300
2c
replacement line
.
".to_string();
            let expanded = mgr.expand_response_text(&r[0], diff);
            assert_eq!(expanded.unwrap(), "line 1\nreplacement line\nline 3\n");
            // If the digest is wrong, that should get rejected.
            let diff = "network-status-diff-version 1
hash 9999999999999999999999999999999999999999999999999999999999999999 9999999999999999999999999999999999999999999999999999999999999999
2c
replacement line
.
".to_string();
            let expanded = mgr.expand_response_text(&r[0], diff);
            assert!(expanded.is_err());
        });
    }
}