1
#![cfg_attr(docsrs, feature(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
#![allow(clippy::cognitive_complexity)] // See arti#2556
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_time_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
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
49
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
50

            
51
// This clippy lint produces a false positive on `use strum`, below.
52
// Attempting to apply the lint to just the use statement fails to suppress
53
// this lint and instead produces another lint about a useless clippy attribute.
54
#![allow(clippy::single_component_path_imports)]
55

            
56
mod bootstrap;
57
pub mod config;
58
mod docid;
59
mod docmeta;
60
mod err;
61
mod event;
62
mod shared_ref;
63
mod state;
64
mod storage;
65

            
66
#[cfg(feature = "dir-plugin")]
67
mod as_plugin;
68
#[cfg(feature = "bridge-client")]
69
pub mod bridgedesc;
70
#[cfg(feature = "dirfilter")]
71
pub mod filter;
72

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

            
91
use async_trait::async_trait;
92
use futures::stream::BoxStream;
93
use oneshot_fused_workaround as oneshot;
94
use tor_netdoc::doc::netstatus::ProtoStatuses;
95
use tor_rtcompat::scheduler::{TaskHandle, TaskSchedule};
96
use tor_rtcompat::{Runtime, SpawnExt};
97
use tracing::{debug, info, instrument, trace, warn};
98
use web_time_compat::SystemTimeExt;
99

            
100
use std::marker::PhantomData;
101
use std::sync::atomic::{AtomicBool, Ordering};
102
use std::sync::{Arc, Mutex};
103
use std::time::Duration;
104
use std::{collections::HashMap, sync::Weak};
105
use std::{fmt::Debug, time::SystemTime};
106

            
107
use crate::state::{DirState, NetDirChange};
108
pub use config::DirMgrConfig;
109
pub use docid::DocId;
110
pub use err::Error;
111
pub use event::{DirBlockage, DirBootstrapEvents, DirBootstrapStatus};
112
pub use storage::DocumentText;
113
pub use tor_dircommon::fallback::{FallbackDir, FallbackDirBuilder};
114
pub use tor_netdir::Timeliness;
115

            
116
#[cfg(feature = "dir-plugin")]
117
pub use as_plugin::DirPlugin;
118

            
119
/// Re-export of `strum` crate for use by an internal macro
120
use strum;
121

            
122
/// A Result as returned by this crate.
123
pub type Result<T> = std::result::Result<T, Error>;
124

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

            
136
    /// Be parameterized by Runtime even though we don't use it right now
137
    pub(crate) runtime: PhantomData<R>,
138
}
139

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

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

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

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

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

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

            
204
    fn events(&self) -> BoxStream<'static, DirEvent> {
205
        Box::pin(self.events.subscribe())
206
    }
207

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

            
232
    fn protocol_statuses(&self) -> Option<(SystemTime, Arc<ProtoStatuses>)> {
233
        self.protocols.lock().expect("Poisoned lock").clone()
234
    }
235
}
236

            
237
#[async_trait]
238
impl<R: Runtime> DirProvider for Arc<DirMgr<R>> {
239
    fn reconfigure(
240
        &self,
241
        new_config: &DirMgrConfig,
242
        how: tor_config::Reconfigure,
243
    ) -> std::result::Result<(), tor_config::ReconfigureError> {
244
        DirMgr::reconfigure(self, new_config, how)
245
    }
246

            
247
    #[instrument(level = "trace", skip_all)]
248
    async fn bootstrap(&self) -> Result<()> {
249
        DirMgr::bootstrap(self).await
250
    }
251

            
252
    fn bootstrap_events(&self) -> BoxStream<'static, DirBootstrapStatus> {
253
        Box::pin(DirMgr::bootstrap_events(self))
254
    }
255

            
256
    fn download_task_handle(&self) -> Option<TaskHandle> {
257
        Some(self.task_handle.clone())
258
    }
259
}
260

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

            
291
    /// Our latest set of recommended protocols.
292
    protocols: Mutex<Option<(SystemTime, Arc<ProtoStatuses>)>>,
293

            
294
    /// A set of network parameters to hand out when we have no directory.
295
    default_parameters: Mutex<Arc<NetParameters>>,
296

            
297
    /// A publisher handle that we notify whenever the consensus changes.
298
    events: event::FlagPublisher<DirEvent>,
299

            
300
    /// A publisher handle that we notify whenever our bootstrapping status
301
    /// changes.
302
    send_status: Mutex<watch::Sender<event::DirBootstrapStatus>>,
303

            
304
    /// A receiver handle that gets notified whenever our bootstrapping status
305
    /// changes.
306
    ///
307
    /// We don't need to keep this drained, since `postage::watch` already knows
308
    /// to discard unread events.
309
    receive_status: DirBootstrapEvents,
310

            
311
    /// A circuit manager, if this DirMgr supports downloading.
312
    circmgr: Option<Arc<CircMgr<R>>>,
313

            
314
    /// Our asynchronous runtime.
315
    runtime: R,
316

            
317
    /// Whether or not we're operating in offline mode.
318
    offline: bool,
319

            
320
    /// If we're not in offline mode, stores whether or not the `DirMgr` has attempted
321
    /// to bootstrap yet or not.
322
    ///
323
    /// This exists in order to prevent starting two concurrent bootstrap tasks.
324
    ///
325
    /// (In offline mode, this does nothing.)
326
    bootstrap_started: AtomicBool,
327

            
328
    /// A filter that gets applied to directory objects before we use them.
329
    #[cfg(feature = "dirfilter")]
330
    filter: crate::filter::FilterConfig,
331

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

            
336
    /// A task handle that we return to anybody who needs to manage our download process.
337
    task_handle: TaskHandle,
338
}
339

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

            
356
impl std::fmt::Display for DocSource {
357
2
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
358
2
        match self {
359
            DocSource::LocalCache => write!(f, "local cache"),
360
2
            DocSource::DirServer { source: None } => write!(f, "directory server"),
361
            DocSource::DirServer { source: Some(info) } => write!(f, "directory server {}", info),
362
        }
363
2
    }
364
}
365

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

            
380
        // TODO: add some way to return a directory that isn't up-to-date
381
        let attempt = AttemptId::next();
382
        trace!(%attempt, "Trying to load a full directory from cache");
383
        let outcome = dirmgr.load_directory(attempt);
384
        trace!(%attempt, "Load result: {outcome:?}");
385
        let _success = outcome?;
386

            
387
        dirmgr
388
            .netdir(Timeliness::Timely)
389
            .map_err(|_| Error::DirectoryNotPresent)
390
    }
391

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

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

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

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

            
462
        // NOTE(eta): could potentially weaken the `Ordering` here in future
463
        if self
464
            .bootstrap_started
465
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
466
            .is_err()
467
        {
468
            debug!("Attempted to bootstrap twice; ignoring.");
469
            return Ok(());
470
        }
471

            
472
        // Use a RAII guard to reset `bootstrap_started` to `false` if we return early without
473
        // completing bootstrap.
474
        let reset_bootstrap_started = scopeguard::guard(&self.bootstrap_started, |v| {
475
            v.store(false, Ordering::SeqCst);
476
        });
477

            
478
        let schedule = {
479
            let sched = self.task_schedule.lock().expect("poisoned lock").take();
480
            match sched {
481
                Some(sched) => sched,
482
                None => {
483
                    debug!("Attempted to bootstrap twice; ignoring.");
484
                    return Ok(());
485
                }
486
            }
487
        };
488

            
489
        // Try to load from the cache.
490
        let attempt_id = AttemptId::next();
491
        trace!(attempt=%attempt_id, "Starting to bootstrap directory");
492
        let have_directory = self.load_directory(attempt_id)?;
493

            
494
        let (mut sender, receiver) = if have_directory {
495
            info!("Loaded a good directory from cache.");
496
            (None, None)
497
        } else {
498
            info!("Didn't get usable directory from cache.");
499
            let (sender, receiver) = oneshot::channel();
500
            (Some(sender), Some(receiver))
501
        };
502

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

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

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

            
557
    /// Returns `true` if a bootstrap attempt is in progress, or successfully completed.
558
    pub fn bootstrap_started(&self) -> bool {
559
        self.bootstrap_started.load(Ordering::SeqCst)
560
    }
561

            
562
    /// Return a new directory manager from a given configuration,
563
    /// bootstrapping from the network as necessary.
564
    #[instrument(level = "trace", skip_all)]
565
    pub async fn bootstrap_from_config(
566
        config: DirMgrConfig,
567
        runtime: R,
568
        store: DirMgrStore<R>,
569
        circmgr: Arc<CircMgr<R>>,
570
    ) -> Result<Arc<Self>> {
571
        let dirmgr = Self::create_unbootstrapped(config, runtime, store, circmgr)?;
572

            
573
        dirmgr.bootstrap().await?;
574

            
575
        Ok(dirmgr)
576
    }
577

            
578
    /// Try forever to either lock the storage (and thereby become the
579
    /// owner), or to reload the database.
580
    ///
581
    /// If we have begin to have a bootstrapped directory, send a
582
    /// message using `on_complete`.
583
    ///
584
    /// If we eventually become the owner, return Ok().
585
    async fn reload_until_owner(
586
        weak: &Weak<Self>,
587
        schedule: &mut TaskSchedule<R>,
588
        attempt_id: AttemptId,
589
        on_complete: &mut Option<oneshot::Sender<()>>,
590
    ) -> Result<()> {
591
        let mut logged = false;
592
        let mut bootstrapped;
593
        {
594
            let dirmgr = upgrade_weak_ref(weak)?;
595
            bootstrapped = dirmgr.netdir.get().is_some();
596
        }
597

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

            
615
            if !logged {
616
                logged = true;
617
                if bootstrapped {
618
                    info!("Another process is managing the directory. We'll use its cache.");
619
                } else {
620
                    info!(
621
                        "Another process is bootstrapping the directory. Waiting till it finishes or exits."
622
                    );
623
                }
624
            }
625

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

            
654
    /// Try to fetch our directory info and keep it updated, indefinitely.
655
    ///
656
    /// If we have begin to have a bootstrapped directory, send a
657
    /// message using `on_complete`.
658
    #[instrument(level = "trace", skip_all)]
659
    async fn download_forever(
660
        weak: Weak<Self>,
661
        schedule: &mut TaskSchedule<R>,
662
        mut attempt_id: AttemptId,
663
        mut on_complete: Option<oneshot::Sender<()>>,
664
    ) -> Result<()> {
665
        let mut state: Box<dyn DirState> = {
666
            let dirmgr = upgrade_weak_ref(&weak)?;
667
            Box::new(state::GetConsensusState::new(
668
                dirmgr.runtime.clone(),
669
                dirmgr.config.get(),
670
                CacheUsage::CacheOkay,
671
                Some(dirmgr.netdir.clone()),
672
                #[cfg(feature = "dirfilter")]
673
                dirmgr
674
                    .filter
675
                    .clone()
676
                    .unwrap_or_else(|| Arc::new(crate::filter::NilFilter)),
677
            ))
678
        };
679

            
680
        trace!("Entering download loop.");
681

            
682
        loop {
683
            let mut usable = false;
684

            
685
            let retry_config = {
686
                let dirmgr = upgrade_weak_ref(&weak)?;
687
                // TODO(nickm): instead of getting this every time we loop, it
688
                // might be a good idea to refresh it with each attempt, at
689
                // least at the point of checking the number of attempts.
690
                dirmgr.config.get().schedule.retry_bootstrap()
691
            };
692
            let mut retry_delay = retry_config.schedule();
693

            
694
            'retry_attempt: for try_num in retry_config.attempts() {
695
                trace!(attempt=%attempt_id, ?try_num, "Trying to download a directory.");
696
                let outcome = bootstrap::download(
697
                    Weak::clone(&weak),
698
                    &mut state,
699
                    schedule,
700
                    attempt_id,
701
                    &mut on_complete,
702
                )
703
                .await;
704
                trace!(attempt=%attempt_id, ?try_num, ?outcome, "Download is over.");
705

            
706
                if let Err(err) = outcome {
707
                    if state.is_ready(Readiness::Usable) {
708
                        usable = true;
709
                        info_report!(
710
                            err,
711
                            "Unable to completely download a directory. (Nevertheless, the directory is usable, so we'll pause for now)"
712
                        );
713
                        break 'retry_attempt;
714
                    }
715

            
716
                    match err.bootstrap_action() {
717
                        BootstrapAction::Nonfatal => {
718
                            return Err(into_internal!(
719
                                "Nonfatal error should not have propagated here"
720
                            )(err)
721
                            .into());
722
                        }
723
                        BootstrapAction::Reset => {}
724
                        BootstrapAction::Fatal => return Err(err),
725
                    }
726

            
727
                    let delay = retry_delay.next_delay(&mut rand::rng());
728
                    warn_report!(
729
                        err,
730
                        "Unable to download a usable directory. (We will restart in {})",
731
                        humantime::format_duration(delay),
732
                    );
733
                    {
734
                        let dirmgr = upgrade_weak_ref(&weak)?;
735
                        dirmgr.note_reset(attempt_id);
736
                    }
737
                    schedule.sleep(delay).await?;
738
                    state = state.reset();
739
                } else {
740
                    info!(attempt=%attempt_id, "Directory is complete.");
741
                    usable = true;
742
                    break 'retry_attempt;
743
                }
744
            }
745

            
746
            if !usable {
747
                // we ran out of attempts.
748
                warn!(
749
                    "We failed {} times to bootstrap a directory. We're going to give up.",
750
                    retry_config.n_attempts()
751
                );
752
                return Err(Error::CantAdvanceState);
753
            } else {
754
                // Report success, if appropriate.
755
                if let Some(send_done) = on_complete.take() {
756
                    let _ = send_done.send(());
757
                }
758
            }
759

            
760
            let reset_at = state.reset_time();
761
            match reset_at {
762
                Some(t) => {
763
                    trace!("Sleeping until {}", time::OffsetDateTime::from(t));
764
                    schedule.sleep_until_wallclock(t).await?;
765
                }
766
                None => return Ok(()),
767
            }
768
            attempt_id = bootstrap::AttemptId::next();
769
            trace!(attempt=%attempt_id, "Beginning new attempt to bootstrap directory");
770
            state = state.reset();
771
        }
772
    }
773

            
774
    /// Get a reference to the circuit manager, if we have one.
775
2
    fn circmgr(&self) -> Result<Arc<CircMgr<R>>> {
776
2
        self.circmgr.clone().ok_or(Error::NoDownloadSupport)
777
2
    }
778

            
779
    /// Try to change our configuration to `new_config`.
780
    ///
781
    /// Actual behavior will depend on the value of `how`.
782
    pub fn reconfigure(
783
        &self,
784
        new_config: &DirMgrConfig,
785
        how: tor_config::Reconfigure,
786
    ) -> std::result::Result<(), tor_config::ReconfigureError> {
787
        let config = self.config.get();
788
        // We don't support changing these: doing so basically would require us
789
        // to abort all our in-progress downloads, since they might be based on
790
        // no-longer-viable information.
791
        // NOTE: keep this in sync with the behaviour of `DirMgrConfig::update_from_config`
792
        if new_config.cache_dir != config.cache_dir {
793
            how.cannot_change("storage.cache_dir")?;
794
        }
795
        if new_config.cache_trust != config.cache_trust {
796
            how.cannot_change("storage.permissions")?;
797
        }
798
        if new_config.authorities() != config.authorities() {
799
            how.cannot_change("network.authorities")?;
800
        }
801

            
802
        if how == tor_config::Reconfigure::CheckAllOrNothing {
803
            return Ok(());
804
        }
805

            
806
        let params_changed = new_config.override_net_params != config.override_net_params;
807

            
808
        self.config
809
            .map_and_replace(|cfg| cfg.update_from_config(new_config));
810

            
811
        if params_changed {
812
            let _ignore_err = self.netdir.mutate(|netdir| {
813
                netdir.replace_overridden_parameters(&new_config.override_net_params);
814
                Ok(())
815
            });
816
            {
817
                let mut params = self.default_parameters.lock().expect("lock failed");
818
                *params = Arc::new(NetParameters::from_map(&new_config.override_net_params));
819
            }
820

            
821
            // (It's okay to ignore the error, since it just means that there
822
            // was no current netdir.)
823
            self.events.publish(DirEvent::NewConsensus);
824
        }
825

            
826
        Ok(())
827
    }
828

            
829
    /// Return a stream of [`DirBootstrapStatus`] events to tell us about changes
830
    /// in the latest directory's bootstrap status.
831
    ///
832
    /// Note that this stream can be lossy: the caller will not necessarily
833
    /// observe every event on the stream
834
    pub fn bootstrap_events(&self) -> event::DirBootstrapEvents {
835
        self.receive_status.clone()
836
    }
837

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

            
845
30
        status.update_progress(attempt_id, progress);
846
30
    }
847

            
848
    /// Update our status tracker to note that some number of errors has
849
    /// occurred.
850
    fn note_errors(&self, attempt_id: AttemptId, n_errors: usize) {
851
        if n_errors == 0 {
852
            return;
853
        }
854
        let mut sender = self.send_status.lock().expect("poisoned lock");
855
        let mut status = sender.borrow_mut();
856

            
857
        status.note_errors(attempt_id, n_errors);
858
    }
859

            
860
    /// Update our status tracker to note that we've needed to reset our download attempt.
861
    fn note_reset(&self, attempt_id: AttemptId) {
862
        let mut sender = self.send_status.lock().expect("poisoned lock");
863
        let mut status = sender.borrow_mut();
864

            
865
        status.note_reset(attempt_id);
866
    }
867

            
868
    /// Try to make this a directory manager with read-write access to its
869
    /// storage.
870
    ///
871
    /// Return true if we got the lock, or if we already had it.
872
    ///
873
    /// Return false if another process has the lock
874
    fn try_upgrade_to_readwrite(&self) -> Result<bool> {
875
        self.store
876
            .lock()
877
            .expect("Directory storage lock poisoned")
878
            .upgrade_to_readwrite()
879
    }
880

            
881
    /// Return a reference to the store, if it is currently read-write.
882
    #[cfg(test)]
883
4
    fn store_if_rw(&self) -> Option<&Mutex<DynStore>> {
884
4
        let rw = !self
885
4
            .store
886
4
            .lock()
887
4
            .expect("Directory storage lock poisoned")
888
4
            .is_readonly();
889
        // A race-condition is possible here, but I believe it's harmless.
890
4
        if rw { Some(&self.store) } else { None }
891
4
    }
892

            
893
    /// Construct a DirMgr from a DirMgrConfig.
894
    ///
895
    /// If `offline` is set, opens the SQLite store read-only and sets the offline flag in the
896
    /// returned manager.
897
    #[allow(clippy::unnecessary_wraps)] // API compat and future-proofing
898
14
    fn from_config(
899
14
        config: DirMgrConfig,
900
14
        runtime: R,
901
14
        store: DirMgrStore<R>,
902
14
        circmgr: Option<Arc<CircMgr<R>>>,
903
14
        offline: bool,
904
14
    ) -> Result<Self> {
905
14
        let netdir = Arc::new(SharedMutArc::new());
906
14
        let events = event::FlagPublisher::new();
907
14
        let default_parameters = NetParameters::from_map(&config.override_net_params);
908
14
        let default_parameters = Mutex::new(Arc::new(default_parameters));
909

            
910
14
        let (send_status, receive_status) = postage::watch::channel();
911
14
        let send_status = Mutex::new(send_status);
912
14
        let receive_status = DirBootstrapEvents {
913
14
            inner: receive_status,
914
14
        };
915
        #[cfg(feature = "dirfilter")]
916
14
        let filter = config.extensions.filter.clone();
917

            
918
        // We create these early so the client code can access task_handle before bootstrap() returns.
919
14
        let (task_schedule, task_handle) = TaskSchedule::new(runtime.clone());
920
14
        let task_schedule = Mutex::new(Some(task_schedule));
921

            
922
        // We load the cached protocol recommendations unconditionally: the caller needs them even
923
        // if it does not try to load the reset of the cache.
924
14
        let protocols = {
925
14
            let store = store.store.lock().expect("lock poisoned");
926
14
            store
927
14
                .cached_protocol_recommendations()?
928
14
                .map(|(t, p)| (t, Arc::new(p)))
929
        };
930

            
931
14
        Ok(DirMgr {
932
14
            config: config.into(),
933
14
            store: store.store,
934
14
            netdir,
935
14
            protocols: Mutex::new(protocols),
936
14
            default_parameters,
937
14
            events,
938
14
            send_status,
939
14
            receive_status,
940
14
            circmgr,
941
14
            runtime,
942
14
            offline,
943
14
            bootstrap_started: AtomicBool::new(false),
944
14
            #[cfg(feature = "dirfilter")]
945
14
            filter,
946
14
            task_schedule,
947
14
            task_handle,
948
14
        })
949
14
    }
950

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

            
968
        Ok(self.netdir.get().is_some())
969
    }
970

            
971
    /// Return a new asynchronous stream that will receive notification
972
    /// whenever the consensus has changed.
973
    ///
974
    /// Multiple events may be batched up into a single item: each time
975
    /// this stream yields an event, all you can assume is that the event has
976
    /// occurred at least once.
977
    pub fn events(&self) -> impl futures::Stream<Item = DirEvent> + use<R> {
978
        self.events.subscribe()
979
    }
980

            
981
    /// Try to load the text of a single document described by `doc` from
982
    /// storage.
983
6
    pub fn text(&self, doc: &DocId) -> Result<Option<DocumentText>> {
984
        use itertools::Itertools;
985
6
        let mut result = HashMap::new();
986
6
        let query: DocQuery = (*doc).into();
987
6
        let store = self.store.lock().expect("store lock poisoned");
988
6
        query.load_from_store_into(&mut result, &**store)?;
989
6
        let item = result.into_iter().at_most_one().map_err(|_| {
990
            Error::CacheCorruption("Found more than one entry in storage for given docid")
991
        })?;
992
6
        if let Some((docid, doctext)) = item {
993
4
            if &docid != doc {
994
                return Err(Error::CacheCorruption(
995
                    "Item from storage had incorrect docid.",
996
                ));
997
4
            }
998
4
            Ok(Some(doctext))
999
        } else {
2
            Ok(None)
        }
6
    }
    /// Load the text for a collection of documents.
    ///
    /// If many of the documents have the same type, this can be more
    /// efficient than calling [`text`](Self::text).
2
    pub fn texts<T>(&self, docs: T) -> Result<HashMap<DocId, DocumentText>>
2
    where
2
        T: IntoIterator<Item = DocId>,
    {
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.
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
    }
    /// Experimental; temporary: Return a directory plugin to be used while tor-dirserver is a work
    /// in progress.
    #[cfg(feature = "dir-plugin")]
    pub fn get_plugin(&self) -> as_plugin::DirPlugin {
        as_plugin::DirPlugin {
            store: Arc::clone(&self.store),
        }
    }
}
/// 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);
    // We now round cutoff to the next hour, so that we aren't leaking our exact
    // time to the directory cache.
    //
    // With the time crate, it's easier to calculate the "next hour" by rounding
    // _down_ then adding an hour; rounding up would sometimes require changing
    // 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
    Ok(cutoff.into())
8
}
/// Return a list of the protocols [supported](tor_protover::doc_supported) by this crate
/// when running as a client.
38
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`]
38
    [
38
        //
38
        DIRCACHE_CONSDIFF,
38
    ]
38
    .into_iter()
38
    .collect()
38
}
#[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_time_subtraction)]
    #![allow(clippy::useless_vec)]
    #![allow(clippy::needless_pass_by_value)]
    #![allow(clippy::string_slice)] // See arti#2571
    //! <!-- @@ 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::RngExt;
            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());
        });
    }
}