1
//! Implementation for the primary directory state machine.
2
//!
3
//! There are three (active) states that a download can be in: looking
4
//! for a consensus ([`GetConsensusState`]), looking for certificates
5
//! to validate that consensus ([`GetCertsState`]), and looking for
6
//! microdescriptors ([`GetMicrodescsState`]).
7
//!
8
//! These states have no contact with the network, and are purely
9
//! reactive to other code that drives them.  See the
10
//! [`bootstrap`](crate::bootstrap) module for functions that actually
11
//! load or download directory information.
12

            
13
use digest::Digest;
14
use saturating_time::SaturatingTime as _;
15
use std::collections::{HashMap, HashSet};
16
use std::fmt::Debug;
17
use std::mem;
18
use std::result::Result as StdResult;
19
use std::sync::{Arc, Mutex};
20
use std::time::{Duration, SystemTime};
21
use time::OffsetDateTime;
22
use tor_basic_utils::RngExt as _;
23
use tor_dircommon::retry::DownloadSchedule;
24
use tor_error::{internal, warn_report};
25
use tor_netdir::{MdReceiver, NetDir, PartialNetDir};
26
use tor_netdoc::doc::authcert::AuthCertUnverified;
27
use tor_netdoc::doc::netstatus::{ConsensusVerifiabilityError, Lifetime, ProtoStatuses};
28
use tor_netdoc::parse2::ParseInput;
29
use tracing::{debug, warn};
30

            
31
use crate::event::DirProgress;
32

            
33
use crate::storage::DynStore;
34
use crate::{
35
    CacheUsage, ClientRequest, DirMgrConfig, DocId, DocumentText, Error, Readiness, Result,
36
    docmeta::{AuthCertMeta, ConsensusMeta},
37
    event,
38
};
39
use crate::{DocSource, SharedMutArc};
40
use tor_checkable::TimeBound;
41
#[cfg(feature = "geoip")]
42
use tor_geoip::GeoipDb;
43
use tor_llcrypto::pk::rsa::RsaIdentity;
44
use tor_netdoc::doc::microdesc::{MdDigest, MicrodescAndHash};
45
use tor_netdoc::{
46
    doc::{
47
        authcert::{AuthCert, AuthCertKeyIds},
48
        microdesc::Microdesc,
49
        netstatus::{
50
            ConsensusFlavor, md::NetworkStatus as MdConsensus,
51
            md::NetworkStatusUnverified as MdConsensusUnverified,
52
        },
53
    },
54
    parse2,
55
};
56
use tor_rtcompat::Runtime;
57

            
58
/// A change to the currently running `NetDir`, returned by the state machines in this module.
59
#[derive(Debug)]
60
pub(crate) enum NetDirChange<'a> {
61
    /// If the provided `NetDir` is suitable for use (i.e. the caller determines it can build
62
    /// circuits with it), replace the current `NetDir` with it.
63
    ///
64
    /// The caller must call `DirState::on_netdir_replaced` if the replace was successful.
65
    AttemptReplace {
66
        /// The netdir to replace the current one with, if it's usable.
67
        ///
68
        /// The `Option` is always `Some` when returned from the state machine; it's there
69
        /// so that the caller can call `.take()` to avoid cloning the netdir.
70
        netdir: &'a mut Option<NetDir>,
71
        /// The consensus metadata for this netdir.
72
        consensus_meta: &'a ConsensusMeta,
73
    },
74
    /// Add the provided microdescriptors to the current `NetDir`.
75
    AddMicrodescs(&'a mut Vec<MicrodescAndHash>),
76
    /// Replace the recommended set of subprotocols.
77
    SetRequiredProtocol {
78
        /// The time at which the protocol statuses were recommended
79
        timestamp: SystemTime,
80
        /// The recommended set of protocols.
81
        protos: Arc<ProtoStatuses>,
82
    },
83
}
84

            
85
/// A "state" object used to represent our progress in downloading a
86
/// directory.
87
///
88
/// These state objects are not meant to know about the network, or
89
/// how to fetch documents at all.  Instead, they keep track of what
90
/// information they are missing, and what to do when they get that
91
/// information.
92
///
93
/// Every state object has two possible transitions: "resetting", and
94
/// "advancing".  Advancing happens when a state has no more work to
95
/// do, and needs to transform into a different kind of object.
96
/// Resetting happens when this state needs to go back to an initial
97
/// state in order to start over -- either because of an error or
98
/// because the information it has downloaded is no longer timely.
99
pub(crate) trait DirState: Send {
100
    /// Return a human-readable description of this state.
101
    fn describe(&self) -> String;
102
    /// Return a list of the documents we're missing.
103
    ///
104
    /// If every document on this list were to be loaded or downloaded, then
105
    /// the state should either become "ready to advance", or "complete."
106
    ///
107
    /// This list should never _grow_ on a given state; only advancing
108
    /// or resetting the state should add new DocIds that weren't
109
    /// there before.
110
    fn missing_docs(&self) -> Vec<DocId>;
111
    /// Describe whether this state has reached `ready` status.
112
    fn is_ready(&self, ready: Readiness) -> bool;
113
    /// If the state object wants to make changes to the currently running `NetDir`,
114
    /// return the proposed changes.
115
8
    fn get_netdir_change(&mut self) -> Option<NetDirChange<'_>> {
116
8
        None
117
8
    }
118
    /// Return true if this state can advance to another state via its
119
    /// `advance` method.
120
    fn can_advance(&self) -> bool;
121
    /// Add one or more documents from our cache; returns 'true' if there
122
    /// was any change in this state.
123
    ///
124
    /// Set `changed` to true if any semantic changes in this state were made.
125
    ///
126
    /// An error return does not necessarily mean that no data was added;
127
    /// partial successes are possible.
128
    fn add_from_cache(
129
        &mut self,
130
        docs: HashMap<DocId, DocumentText>,
131
        changed: &mut bool,
132
    ) -> Result<()>;
133

            
134
    /// Add information that we have just downloaded to this state.
135
    ///
136
    /// This method receives a copy of the original request, and should reject
137
    /// any documents that do not pertain to it.
138
    ///
139
    /// If `storage` is provided, then we should write any accepted documents
140
    /// into `storage` so they can be saved in a cache.
141
    ///
142
    /// Set `changed` to true if any semantic changes in this state were made.
143
    ///
144
    /// An error return does not necessarily mean that no data was added;
145
    /// partial successes are possible.
146
    fn add_from_download(
147
        &mut self,
148
        text: &str,
149
        request: &ClientRequest,
150
        source: DocSource,
151
        storage: Option<&Mutex<DynStore>>,
152
        changed: &mut bool,
153
    ) -> Result<()>;
154
    /// Return a summary of this state as a [`DirProgress`].
155
    fn bootstrap_progress(&self) -> event::DirProgress;
156
    /// Return a configuration for attempting downloads.
157
    fn dl_config(&self) -> DownloadSchedule;
158
    /// If possible, advance to the next state.
159
    fn advance(self: Box<Self>) -> Box<dyn DirState>;
160
    /// Return a time (if any) when downloaders should stop attempting to
161
    /// advance this state, and should instead reset it and start over.
162
    fn reset_time(&self) -> Option<SystemTime>;
163
    /// Reset this state and start over.
164
    fn reset(self: Box<Self>) -> Box<dyn DirState>;
165
}
166

            
167
/// An object that can provide a previous netdir for the bootstrapping state machines to use.
168
pub(crate) trait PreviousNetDir: Send + Sync + 'static + Debug {
169
    /// Get the previous netdir, if there still is one.
170
    fn get_netdir(&self) -> Option<Arc<NetDir>>;
171
}
172

            
173
impl PreviousNetDir for SharedMutArc<NetDir> {
174
    fn get_netdir(&self) -> Option<Arc<NetDir>> {
175
        self.get()
176
    }
177
}
178

            
179
/// Initial state: fetching or loading a consensus directory.
180
#[derive(Clone, Debug)]
181
pub(crate) struct GetConsensusState<R: Runtime> {
182
    /// How should we get the consensus from the cache, if at all?
183
    cache_usage: CacheUsage,
184

            
185
    /// If present, a time after which we want our consensus to have
186
    /// been published.
187
    //
188
    // TODO: This is not yet used everywhere it could be.  In the future maybe
189
    // it should be inserted into the DocId::LatestConsensus  alternative rather
190
    // than being recalculated in make_consensus_request,
191
    after: Option<SystemTime>,
192

            
193
    /// If present, our next state.
194
    ///
195
    /// (This is present once we have a consensus.)
196
    next: Option<GetCertsState<R>>,
197

            
198
    /// A list of RsaIdentity for the authorities that we believe in.
199
    ///
200
    /// No consensus can be valid unless it purports to be signed by
201
    /// more than half of these authorities.
202
    authority_ids: Vec<RsaIdentity>,
203

            
204
    /// A `Runtime` implementation.
205
    rt: R,
206
    /// The configuration of the directory manager. Used for download configuration
207
    /// purposes.
208
    config: Arc<DirMgrConfig>,
209
    /// If one exists, the netdir we're trying to update.
210
    prev_netdir: Option<Arc<dyn PreviousNetDir>>,
211

            
212
    /// A filter that gets applied to directory objects before we use them.
213
    #[cfg(feature = "dirfilter")]
214
    filter: Arc<dyn crate::filter::DirFilter>,
215
}
216

            
217
impl<R: Runtime> GetConsensusState<R> {
218
    /// Create a new `GetConsensusState`, using the cache as per `cache_usage` and downloading as
219
    /// per the relevant sections of `config`. If `prev_netdir` is supplied, information from that
220
    /// directory may be used to complete the next one.
221
7
    pub(crate) fn new(
222
7
        rt: R,
223
7
        config: Arc<DirMgrConfig>,
224
7
        cache_usage: CacheUsage,
225
7
        prev_netdir: Option<Arc<dyn PreviousNetDir>>,
226
7
        #[cfg(feature = "dirfilter")] filter: Arc<dyn crate::filter::DirFilter>,
227
7
    ) -> Self {
228
7
        let authority_ids = config.authorities().v3idents().clone();
229
7
        let after = prev_netdir
230
7
            .as_ref()
231
            .and_then(|x| x.get_netdir())
232
            .map(|nd| nd.lifetime().valid_after());
233

            
234
7
        GetConsensusState {
235
7
            cache_usage,
236
7
            after,
237
7
            next: None,
238
7
            authority_ids,
239
7
            rt,
240
7
            config,
241
7
            prev_netdir,
242
7
            #[cfg(feature = "dirfilter")]
243
7
            filter,
244
7
        }
245
7
    }
246
}
247

            
248
impl<R: Runtime> DirState for GetConsensusState<R> {
249
4
    fn describe(&self) -> String {
250
4
        if self.next.is_some() {
251
1
            "About to fetch certificates."
252
        } else {
253
3
            match self.cache_usage {
254
                CacheUsage::CacheOnly => "Looking for a cached consensus.",
255
2
                CacheUsage::CacheOkay => "Looking for a consensus.",
256
1
                CacheUsage::MustDownload => "Downloading a consensus.",
257
            }
258
        }
259
        .to_string()
260
4
    }
261
2
    fn missing_docs(&self) -> Vec<DocId> {
262
2
        if self.can_advance() {
263
1
            return Vec::new();
264
1
        }
265
1
        let flavor = ConsensusFlavor::Microdesc;
266
1
        vec![DocId::LatestConsensus {
267
1
            flavor,
268
1
            cache_usage: self.cache_usage,
269
1
        }]
270
2
    }
271
2
    fn is_ready(&self, _ready: Readiness) -> bool {
272
2
        false
273
2
    }
274
5
    fn can_advance(&self) -> bool {
275
5
        self.next.is_some()
276
5
    }
277
1
    fn bootstrap_progress(&self) -> DirProgress {
278
1
        if let Some(next) = &self.next {
279
            next.bootstrap_progress()
280
        } else {
281
1
            DirProgress::NoConsensus { after: self.after }
282
        }
283
1
    }
284
1
    fn dl_config(&self) -> DownloadSchedule {
285
1
        self.config.schedule.retry_consensus()
286
1
    }
287
1
    fn add_from_cache(
288
1
        &mut self,
289
1
        docs: HashMap<DocId, DocumentText>,
290
1
        changed: &mut bool,
291
1
    ) -> Result<()> {
292
1
        let text = match docs.into_iter().next() {
293
            None => return Ok(()),
294
            Some((
295
                DocId::LatestConsensus {
296
                    flavor: ConsensusFlavor::Microdesc,
297
                    ..
298
                },
299
                text,
300
1
            )) => text,
301
            _ => return Err(Error::CacheCorruption("Not an md consensus")),
302
        };
303

            
304
1
        let source = DocSource::LocalCache;
305

            
306
1
        self.set_unverified_consensus_text(
307
1
            source,
308
1
            text.as_str().map_err(Error::BadUtf8InCache)?,
309
1
            None,
310
1
            changed,
311
        )?;
312
1
        Ok(())
313
1
    }
314
5
    fn add_from_download(
315
5
        &mut self,
316
5
        text: &str,
317
5
        request: &ClientRequest,
318
5
        source: DocSource,
319
5
        storage: Option<&Mutex<DynStore>>,
320
5
        changed: &mut bool,
321
5
    ) -> Result<()> {
322
5
        let requested_newer_than = match request {
323
5
            ClientRequest::Consensus(r) => r.last_consensus_date(),
324
            _ => None,
325
        };
326
        let meta =
327
5
            self.set_unverified_consensus_text(source, text, requested_newer_than, changed)?;
328

            
329
3
        if let Some(store) = storage {
330
1
            let mut w = store.lock().expect("Directory storage lock poisoned");
331
1
            w.store_consensus(meta, ConsensusFlavor::Microdesc, true, text)?;
332
2
        }
333
3
        Ok(())
334
5
    }
335
3
    fn advance(self: Box<Self>) -> Box<dyn DirState> {
336
3
        match self.next {
337
3
            Some(next) => Box::new(next),
338
            None => self,
339
        }
340
3
    }
341
1
    fn reset_time(&self) -> Option<SystemTime> {
342
1
        None
343
1
    }
344
    fn reset(self: Box<Self>) -> Box<dyn DirState> {
345
        self
346
    }
347
}
348

            
349
impl<R: Runtime> GetConsensusState<R> {
350
    /// Helper: try to set the current consensus text from an input string
351
    /// `text`.  Refuse it if the authorities could never be correct, or if it
352
    /// is ill-formed.
353
    ///
354
    /// If `cutoff` is provided, treat any consensus older than `cutoff` as
355
    /// older-than-requested.
356
    ///
357
    /// Errors from this method are not fatal to the download process.
358
    ///
359
    /// ## Security
360
    ///
361
    /// This function only partially checks the lifetime of the consensus,
362
    /// and does not check signatures.
363
6
    fn set_unverified_consensus_text(
364
6
        &mut self,
365
6
        source: DocSource,
366
6
        text: &str,
367
6
        cutoff: Option<SystemTime>,
368
6
        changed: &mut bool,
369
6
    ) -> Result<&ConsensusMeta> {
370
        use parse2::NetdocParseableUnverified as _;
371
        // Try to parse it and get its metadata.
372
        let (consensus_meta, unvalidated) = {
373
6
            let filename = source.for_parse_input();
374
6
            let input = ParseInput::new(text, &filename);
375
6
            let parsed = parse2::parse_netdoc::<MdConsensusUnverified>(&input)
376
1
                .map_err(|e| Error::from_parse(source.clone(), e))?;
377
5
            let (signedval, remainder) = text
378
5
                .split_at_checked(parsed.sigs.unsigned_body_len)
379
                .ok_or_else(|| internal!("parser returned invalid string index"))?;
380

            
381
5
            let lifetime = &parsed.inspect_unverified().0.preamble.lifetime;
382
5
            if let Some(cutoff) = cutoff {
383
                if lifetime.valid_after() < cutoff {
384
                    return Err(Error::Unwanted("consensus was older than requested"));
385
                }
386
5
            }
387

            
388
            let meta =
389
5
                ConsensusMeta::from_text_and_lifetime(signedval, remainder, lifetime.clone());
390

            
391
5
            (meta, parsed)
392
        };
393

            
394
        // Check out what authorities we believe in, and see if enough
395
        // of them are purported to have signed this consensus.
396
5
        let desired_certs = match unvalidated.can_verify(&self.authority_ids, &[]) {
397
            Ok(_) => {
398
                return Err(internal!(
399
                    "consensus seemed verifiable, even though we provided no certs"
400
                )
401
                .into());
402
            }
403
            Err(ConsensusVerifiabilityError::InsufficientTrustedSigners) => {
404
1
                return Err(Error::UnrecognizedAuthorities);
405
            }
406
4
            Err(ConsensusVerifiabilityError::MissingAuthCerts { missing, .. }) => missing,
407
        };
408

            
409
        // Yes, we've added the consensus.  That's a change.
410
4
        *changed = true;
411

            
412
4
        self.next = Some(GetCertsState {
413
4
            cache_usage: self.cache_usage,
414
4
            consensus_source: source,
415
4
            consensus: GetCertsConsensus::Unvalidated(unvalidated),
416
4
            consensus_meta,
417
4
            missing_certs: desired_certs,
418
4
            certs: Vec::new(),
419
4
            rt: self.rt.clone(),
420
4
            config: self.config.clone(),
421
4
            prev_netdir: self.prev_netdir.take(),
422
4
            protocol_statuses: None,
423
4
            #[cfg(feature = "dirfilter")]
424
4
            filter: self.filter.clone(),
425
4
        });
426

            
427
        // Unwrap should be safe because `next` was just assigned
428
        #[allow(clippy::unwrap_used)]
429
4
        Ok(&self.next.as_ref().unwrap().consensus_meta)
430
6
    }
431
}
432

            
433
/// One of two possible internal states for the consensus in a GetCertsState.
434
///
435
/// This inner object is advanced by `try_checking_sigs`.
436
#[derive(Clone, Debug)]
437
enum GetCertsConsensus {
438
    /// We have an unvalidated consensus; we haven't checked its signatures.
439
    Unvalidated(MdConsensusUnverified),
440
    /// A validated consensus: the signatures are fine and we can advance.
441
    Validated(MdConsensus),
442
    /// We failed to validate the consensus, even after getting enough certificates.
443
    Failed,
444
}
445

            
446
/// Second state: fetching or loading authority certificates.
447
///
448
/// TODO: we should probably do what C tor does, and try to use the
449
/// same directory that gave us the consensus.
450
///
451
/// TODO SECURITY: This needs better handling for the DOS attack where
452
/// we are given a bad consensus signed with fictional certificates
453
/// that we can never find.
454
#[derive(Clone, Debug)]
455
struct GetCertsState<R: Runtime> {
456
    /// The cache usage we had in mind when we began.  Used to reset.
457
    cache_usage: CacheUsage,
458
    /// Where did we get our consensus?
459
    consensus_source: DocSource,
460
    /// The consensus that we are trying to validate, or an error if we've given
461
    /// up on validating it.
462
    consensus: GetCertsConsensus,
463
    /// Metadata for the consensus.
464
    consensus_meta: ConsensusMeta,
465
    /// A set of the certificate keypairs for the certificates we don't
466
    /// have yet.
467
    missing_certs: HashSet<AuthCertKeyIds>,
468
    /// A list of the certificates we've been able to load or download.
469
    certs: Vec<AuthCert>,
470

            
471
    /// A `Runtime` implementation.
472
    rt: R,
473
    /// The configuration of the directory manager. Used for download configuration
474
    /// purposes.
475
    config: Arc<DirMgrConfig>,
476
    /// If one exists, the netdir we're trying to update.
477
    prev_netdir: Option<Arc<dyn PreviousNetDir>>,
478

            
479
    /// If present a set of protocols to install as our latest recommended set.
480
    protocol_statuses: Option<(SystemTime, Arc<ProtoStatuses>)>,
481

            
482
    /// A filter that gets applied to directory objects before we use them.
483
    #[cfg(feature = "dirfilter")]
484
    filter: Arc<dyn crate::filter::DirFilter>,
485
}
486

            
487
impl<R: Runtime> GetCertsState<R> {
488
    /// Handle a certificate result returned by `tor_netdoc`: checking it for timeliness
489
    /// and well-signedness.
490
    ///
491
    /// On success return the `AuthCert` and the string that represents it within the string `within`.
492
    /// On failure, return an error.
493
3
    fn check_parsed_certificate(
494
3
        &self,
495
3
        parsed: StdResult<AuthCertUnverified, parse2::ParseError>,
496
3
        source: &DocSource,
497
3
    ) -> Result<AuthCert> {
498
3
        let parsed = parsed.map_err(|e| Error::from_parse(source.clone(), e))?;
499
3
        let recognized_authorities = self.config.authorities().v3idents();
500
        let wellsigned =
501
3
            parsed
502
3
                .verify(&recognized_authorities[..])
503
                .map_err(|e| Error::VerifyError {
504
                    source: source.clone(),
505
                    cause: e,
506
                })?;
507
3
        let now = self.rt.wallclock();
508
3
        let timely_cert = self
509
3
            .config
510
3
            .tolerance
511
3
            .extend_tolerance(wellsigned)
512
3
            .if_valid_at(&now)?;
513
3
        Ok(timely_cert)
514
3
    }
515

            
516
    /// If we have enough certificates, and we have not yet checked the
517
    /// signatures on the consensus, try checking them.
518
    ///
519
    /// If the consensus is valid, remove the unvalidated consensus from `self`
520
    /// and put the validated consensus there instead.
521
    ///
522
    /// If the consensus is invalid, throw it out set a blocking error.
523
2
    fn try_checking_sigs(&mut self) -> Result<()> {
524
        use GetCertsConsensus as C;
525
        // Temporary value; we'll replace the consensus field with something
526
        // better before the method returns.
527
2
        let mut consensus = C::Failed;
528
2
        std::mem::swap(&mut consensus, &mut self.consensus);
529

            
530
2
        let unvalidated = match consensus {
531
            C::Unvalidated(uv) => {
532
2
                match uv.can_verify(self.config.authorities().v3idents(), &self.certs) {
533
1
                    Ok(()) => uv,
534
                    Err(ConsensusVerifiabilityError::InsufficientTrustedSigners) => {
535
                        self.consensus = C::Failed;
536
                        return Err(internal!(
537
                            "Previously we thought that this consensus had enough authorities, \
538
                            but now we don't!"
539
                        )
540
                        .into());
541
                    }
542
                    Err(ConsensusVerifiabilityError::MissingAuthCerts { .. }) => {
543
                        // Still can't check.
544
1
                        self.consensus = C::Unvalidated(uv);
545
1
                        return Ok(());
546
                    }
547
                }
548
            }
549
            _ => {
550
                // nothing to check at this point.  Either we already checked the consensus, or we
551
                // have an error.
552
                self.consensus = consensus;
553
                return Ok(());
554
            }
555
        };
556

            
557
        let (new_consensus, outcome) =
558
1
            match unvalidated.verify(self.config.authorities().v3idents(), &self.certs) {
559
                Ok(validated) => {
560
1
                    let timely = self.config.tolerance.extend_tolerance(validated);
561
1
                    let consensus = timely.if_valid_at(&self.rt.wallclock())?;
562
1
                    (C::Validated(consensus), Ok(()))
563
                }
564
                Err(cause) => (
565
                    C::Failed,
566
                    Err(Error::ConsensusInvalid {
567
                        source: self.consensus_source.clone(),
568
                        cause,
569
                    }),
570
                ),
571
            };
572
1
        self.consensus = new_consensus;
573

            
574
        // Update our protocol recommendations if we have a validated consensus,
575
        // and if we haven't already updated our recommendations.
576
1
        if let GetCertsConsensus::Validated(v) = &self.consensus {
577
1
            if self.protocol_statuses.is_none() {
578
1
                self.protocol_statuses = Some((
579
1
                    self.consensus_meta.lifetime().valid_after(),
580
1
                    Arc::clone(&v.preamble.proto_statuses),
581
1
                ));
582
            }
583
        }
584

            
585
1
        outcome
586
2
    }
587
}
588

            
589
impl<R: Runtime> DirState for GetCertsState<R> {
590
2
    fn describe(&self) -> String {
591
        use GetCertsConsensus as C;
592
2
        match &self.consensus {
593
            C::Unvalidated(_) => {
594
2
                let total = self.certs.len() + self.missing_certs.len();
595
2
                format!(
596
                    "Downloading certificates for consensus (we are missing {}/{}).",
597
2
                    self.missing_certs.len(),
598
2
                    total
599
                )
600
            }
601
            C::Validated(_) => "Validated consensus; about to get microdescriptors".to_string(),
602
            C::Failed => "Failed to validate consensus".to_string(),
603
        }
604
2
    }
605
5
    fn missing_docs(&self) -> Vec<DocId> {
606
5
        self.missing_certs
607
5
            .iter()
608
6
            .map(|id| DocId::AuthCert(*id))
609
            .collect()
610
5
    }
611
2
    fn is_ready(&self, _ready: Readiness) -> bool {
612
2
        false
613
2
    }
614
3
    fn can_advance(&self) -> bool {
615
3
        matches!(self.consensus, GetCertsConsensus::Validated(_))
616
3
    }
617
2
    fn bootstrap_progress(&self) -> DirProgress {
618
2
        let n_certs = self.certs.len();
619
2
        let n_missing_certs = self.missing_certs.len();
620
2
        let total_certs = n_missing_certs + n_certs;
621
2
        DirProgress::FetchingCerts {
622
2
            lifetime: self.consensus_meta.lifetime().clone(),
623
2
            usable_lifetime: self
624
2
                .config
625
2
                .tolerance
626
2
                .extend_lifetime(self.consensus_meta.lifetime()),
627
2

            
628
2
            n_certs: (n_certs as u16, total_certs as u16),
629
2
        }
630
2
    }
631
1
    fn dl_config(&self) -> DownloadSchedule {
632
1
        self.config.schedule.retry_certs()
633
1
    }
634
1
    fn add_from_cache(
635
1
        &mut self,
636
1
        docs: HashMap<DocId, DocumentText>,
637
1
        changed: &mut bool,
638
1
    ) -> Result<()> {
639
        // Here we iterate over the documents we want, taking them from
640
        // our input and remembering them.
641
1
        let source = DocSource::LocalCache;
642
1
        let mut nonfatal_error = None;
643
1
        for id in &self.missing_docs() {
644
2
            if let Some(cert) = docs.get(id) {
645
1
                let text = cert.as_str().map_err(Error::BadUtf8InCache)?;
646
1
                let filename = source.for_parse_input();
647
                let parsed =
648
1
                    parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(text, &filename));
649
1
                match self.check_parsed_certificate(parsed, &source) {
650
                    Ok(cert) => {
651
1
                        self.missing_certs.remove(&cert.key_ids());
652
1
                        self.certs.push(cert);
653
1
                        *changed = true;
654
                    }
655
                    Err(e) => {
656
                        nonfatal_error.get_or_insert(e);
657
                    }
658
                }
659
1
            }
660
        }
661
1
        if *changed {
662
1
            self.try_checking_sigs()?;
663
        }
664
1
        opt_err_to_result(nonfatal_error)
665
1
    }
666
2
    fn add_from_download(
667
2
        &mut self,
668
2
        text: &str,
669
2
        request: &ClientRequest,
670
2
        source: DocSource,
671
2
        storage: Option<&Mutex<DynStore>>,
672
2
        changed: &mut bool,
673
2
    ) -> Result<()> {
674
2
        let asked_for: HashSet<_> = match request {
675
2
            ClientRequest::AuthCert(a) => a.keys().collect(),
676
            _ => return Err(internal!("expected an AuthCert request").into()),
677
        };
678

            
679
2
        let mut nonfatal_error = None;
680
2
        let mut newcerts = Vec::new();
681
2
        let filename = source.for_parse_input();
682
2
        let input = ParseInput::new(text, &filename);
683
2
        for (cert, startpos, endpos) in parse2::parse_netdoc_multiple_sophisticated(&input)? {
684
2
            let cert_text = text
685
2
                .get(startpos..endpos)
686
                .ok_or_else(|| internal!("parser returned invalid string boundary"))?;
687
2
            match self.check_parsed_certificate(cert, &source) {
688
                Ok(cert) => {
689
2
                    newcerts.push((cert, cert_text));
690
                }
691
                Err(e) => {
692
                    warn_report!(e, "Problem with certificate received from {}", &source);
693
                    nonfatal_error.get_or_insert(e);
694
                }
695
            }
696
        }
697

            
698
        // Now discard any certs we didn't ask for.
699
2
        let len_orig = newcerts.len();
700
2
        newcerts.retain(|(cert, _)| asked_for.contains(&cert.key_ids()));
701
2
        if newcerts.len() != len_orig {
702
1
            warn!(
703
                "Discarding certificates from {} that we didn't ask for.",
704
                source
705
            );
706
1
            nonfatal_error.get_or_insert(Error::Unwanted("Certificate we didn't request"));
707
1
        }
708

            
709
        // We want to exit early if we aren't saving any certificates.
710
2
        if newcerts.is_empty() {
711
1
            return opt_err_to_result(nonfatal_error);
712
1
        }
713

            
714
1
        if let Some(store) = storage {
715
            // Write the certificates to the store.
716
1
            let v: Vec<_> = newcerts[..]
717
1
                .iter()
718
1
                .map(|(cert, s)| (AuthCertMeta::from_authcert(cert), *s))
719
                .collect();
720
1
            let mut w = store.lock().expect("Directory storage lock poisoned");
721
1
            w.store_authcerts(&v[..])?;
722
        }
723

            
724
        // Remember the certificates in this state, and remove them
725
        // from our list of missing certs.
726
1
        for (cert, _) in newcerts {
727
1
            let ids = cert.key_ids();
728
1
            if self.missing_certs.contains(&ids) {
729
1
                self.missing_certs.remove(&ids);
730
1
                self.certs.push(cert);
731
1
                *changed = true;
732
            }
733
        }
734

            
735
1
        if *changed {
736
1
            self.try_checking_sigs()?;
737
        }
738
1
        opt_err_to_result(nonfatal_error)
739
2
    }
740

            
741
1
    fn advance(self: Box<Self>) -> Box<dyn DirState> {
742
        use GetCertsConsensus::*;
743
1
        match self.consensus {
744
1
            Validated(validated) => Box::new(GetMicrodescsState::new(
745
1
                self.cache_usage,
746
1
                validated,
747
1
                self.consensus_meta,
748
1
                self.rt,
749
1
                self.config,
750
1
                self.prev_netdir,
751
1
                #[cfg(feature = "dirfilter")]
752
1
                self.filter,
753
1
            )),
754
            _ => self,
755
        }
756
1
    }
757

            
758
    fn get_netdir_change(&mut self) -> Option<NetDirChange<'_>> {
759
        self.protocol_statuses.as_ref().map(|(timestamp, protos)| {
760
            NetDirChange::SetRequiredProtocol {
761
                timestamp: *timestamp,
762
                protos: Arc::clone(protos),
763
            }
764
        })
765
    }
766

            
767
1
    fn reset_time(&self) -> Option<SystemTime> {
768
1
        Some(
769
1
            self.consensus_meta
770
1
                .lifetime()
771
1
                .valid_until()
772
1
                .saturating_add(self.config.tolerance.post_valid_tolerance()),
773
1
        )
774
1
    }
775
1
    fn reset(self: Box<Self>) -> Box<dyn DirState> {
776
1
        let cache_usage = if self.cache_usage == CacheUsage::CacheOnly {
777
            // Cache only means we can't ever download.
778
            CacheUsage::CacheOnly
779
        } else {
780
            // If we reset in this state, we should always go to "must
781
            // download": Either we've failed to get the certs we needed, or we
782
            // have found that the consensus wasn't valid.  Either case calls
783
            // for a fresh consensus download attempt.
784
1
            CacheUsage::MustDownload
785
        };
786

            
787
1
        Box::new(GetConsensusState::new(
788
1
            self.rt,
789
1
            self.config,
790
1
            cache_usage,
791
1
            self.prev_netdir,
792
1
            #[cfg(feature = "dirfilter")]
793
1
            self.filter,
794
1
        ))
795
1
    }
796
}
797

            
798
/// Final state: we're fetching or loading microdescriptors
799
#[derive(Debug, Clone)]
800
struct GetMicrodescsState<R: Runtime> {
801
    /// How should we get the consensus from the cache, if at all?
802
    cache_usage: CacheUsage,
803
    /// Total number of microdescriptors listed in the consensus.
804
    n_microdescs: usize,
805
    /// The current status of our netdir.
806
    partial: PendingNetDir,
807
    /// Metadata for the current consensus.
808
    meta: ConsensusMeta,
809
    /// A pending list of microdescriptor digests whose
810
    /// "last-listed-at" times we should update.
811
    newly_listed: Vec<MdDigest>,
812
    /// A time after which we should try to replace this directory and
813
    /// find a new one.  Since this is randomized, we only compute it
814
    /// once.
815
    reset_time: SystemTime,
816

            
817
    /// A `Runtime` implementation.
818
    rt: R,
819
    /// The configuration of the directory manager. Used for download configuration
820
    /// purposes.
821
    config: Arc<DirMgrConfig>,
822
    /// If one exists, the netdir we're trying to update.
823
    prev_netdir: Option<Arc<dyn PreviousNetDir>>,
824

            
825
    /// A filter that gets applied to directory objects before we use them.
826
    #[cfg(feature = "dirfilter")]
827
    filter: Arc<dyn crate::filter::DirFilter>,
828
}
829

            
830
/// Information about a network directory that might not be ready to become _the_ current network
831
/// directory.
832
#[derive(Debug, Clone)]
833
enum PendingNetDir {
834
    /// A NetDir for which we have a consensus, but not enough microdescriptors.
835
    Partial(PartialNetDir),
836
    /// A NetDir we're either trying to get our caller to replace, or that the caller
837
    /// has already taken from us.
838
    ///
839
    /// After the netdir gets taken, the `collected_microdescs` and `missing_microdescs`
840
    /// fields get used. Before then, we just do operations on the netdir.
841
    Yielding {
842
        /// The actual netdir. This starts out as `Some`, but our caller can `take()` it
843
        /// from us.
844
        netdir: Option<NetDir>,
845
        /// Microdescs we have collected in order to yield to our caller.
846
        collected_microdescs: Vec<MicrodescAndHash>,
847
        /// Which microdescs we need for the netdir that either is or used to be in `netdir`.
848
        ///
849
        /// NOTE(eta): This MUST always match the netdir's own idea of which microdescs we need.
850
        ///            We do this by copying the netdir's missing microdescs into here when we
851
        ///            instantiate it.
852
        ///            (This code assumes that it doesn't add more needed microdescriptors later!)
853
        missing_microdescs: HashSet<MdDigest>,
854
        /// The time at which we should renew this netdir, assuming we have
855
        /// driven it to a "usable" state.
856
        replace_dir_time: SystemTime,
857
    },
858
    /// A dummy value, so we can use `mem::replace`.
859
    Dummy,
860
}
861

            
862
impl MdReceiver for PendingNetDir {
863
3
    fn missing_microdescs(&self) -> Box<dyn Iterator<Item = &MdDigest> + '_> {
864
3
        match self {
865
2
            PendingNetDir::Partial(partial) => partial.missing_microdescs(),
866
            PendingNetDir::Yielding {
867
                netdir,
868
                missing_microdescs,
869
                ..
870
            } => {
871
1
                if let Some(nd) = netdir.as_ref() {
872
                    nd.missing_microdescs()
873
                } else {
874
1
                    Box::new(missing_microdescs.iter())
875
                }
876
            }
877
            PendingNetDir::Dummy => unreachable!(),
878
        }
879
3
    }
880

            
881
4
    fn add_microdesc(&mut self, md: MicrodescAndHash) -> bool {
882
4
        match self {
883
4
            PendingNetDir::Partial(partial) => partial.add_microdesc(md),
884
            PendingNetDir::Yielding {
885
                netdir,
886
                missing_microdescs,
887
                collected_microdescs,
888
                ..
889
            } => {
890
                let wanted = missing_microdescs.remove(md.digest());
891
                if let Some(nd) = netdir.as_mut() {
892
                    let nd_wanted = nd.add_microdesc(md);
893
                    // This shouldn't ever happen; if it does, our invariants are violated.
894
                    debug_assert_eq!(wanted, nd_wanted);
895
                    nd_wanted
896
                } else {
897
                    collected_microdescs.push(md);
898
                    wanted
899
                }
900
            }
901
            PendingNetDir::Dummy => unreachable!(),
902
        }
903
4
    }
904

            
905
7
    fn n_missing(&self) -> usize {
906
7
        match self {
907
6
            PendingNetDir::Partial(partial) => partial.n_missing(),
908
            PendingNetDir::Yielding {
909
                netdir,
910
                missing_microdescs,
911
                ..
912
            } => {
913
1
                if let Some(nd) = netdir.as_ref() {
914
                    // This shouldn't ever happen; if it does, our invariants are violated.
915
                    debug_assert_eq!(nd.n_missing(), missing_microdescs.len());
916
                    nd.n_missing()
917
                } else {
918
1
                    missing_microdescs.len()
919
                }
920
            }
921
            PendingNetDir::Dummy => unreachable!(),
922
        }
923
7
    }
924
}
925

            
926
impl PendingNetDir {
927
    /// If this PendingNetDir is Partial and could not be partial, upgrade it.
928
5
    fn upgrade_if_necessary(&mut self) {
929
5
        if matches!(self, PendingNetDir::Partial(..)) {
930
5
            match mem::replace(self, PendingNetDir::Dummy) {
931
5
                PendingNetDir::Partial(p) => match p.unwrap_if_sufficient() {
932
                    Ok(nd) => {
933
1
                        let missing: HashSet<_> = nd.missing_microdescs().copied().collect();
934
1
                        let replace_dir_time = pick_download_time(nd.lifetime());
935
1
                        debug!(
936
                            "Consensus now usable, with {} microdescriptors missing. \
937
                                The current consensus is fresh until {}, and valid until {}. \
938
                                I've picked {} as the earliest time to replace it.",
939
                            missing.len(),
940
                            OffsetDateTime::from(nd.lifetime().fresh_until()),
941
                            OffsetDateTime::from(nd.lifetime().valid_until()),
942
                            OffsetDateTime::from(replace_dir_time)
943
                        );
944
1
                        *self = PendingNetDir::Yielding {
945
1
                            netdir: Some(nd),
946
1
                            collected_microdescs: vec![],
947
1
                            missing_microdescs: missing,
948
1
                            replace_dir_time,
949
1
                        };
950
                    }
951
                    Err(p) => {
952
4
                        *self = PendingNetDir::Partial(p);
953
                    }
954
                },
955
                _ => unreachable!(),
956
            }
957
        }
958
5
        assert!(!matches!(self, PendingNetDir::Dummy));
959
5
    }
960
}
961

            
962
impl<R: Runtime> GetMicrodescsState<R> {
963
    /// Create a new [`GetMicrodescsState`] from a provided
964
    /// microdescriptor consensus.
965
3
    fn new(
966
3
        cache_usage: CacheUsage,
967
3
        consensus: MdConsensus,
968
3
        meta: ConsensusMeta,
969
3
        rt: R,
970
3
        config: Arc<DirMgrConfig>,
971
3
        prev_netdir: Option<Arc<dyn PreviousNetDir>>,
972
3
        #[cfg(feature = "dirfilter")] filter: Arc<dyn crate::filter::DirFilter>,
973
3
    ) -> Self {
974
3
        let reset_time = SystemTime::from(consensus.preamble.lifetime.valid_until)
975
3
            .saturating_add(config.tolerance.post_valid_tolerance());
976
3
        let n_microdescs = consensus.routers.len();
977

            
978
3
        let params = &config.override_net_params;
979
        #[cfg(not(feature = "geoip"))]
980
        let mut partial_dir = PartialNetDir::new(consensus, Some(params));
981
        // TODO(eta): Make this embedded database configurable using the `DirMgrConfig`.
982
        #[cfg(feature = "geoip")]
983
        let mut partial_dir =
984
3
            PartialNetDir::new_with_geoip(consensus, Some(params), &GeoipDb::new_embedded());
985

            
986
3
        if let Some(old_dir) = prev_netdir.as_ref().and_then(|x| x.get_netdir()) {
987
            partial_dir.fill_from_previous_netdir(old_dir);
988
3
        }
989

            
990
        // Always upgrade at least once: otherwise, we won't notice we're ready unless we
991
        // add a microdescriptor.
992
3
        let mut partial = PendingNetDir::Partial(partial_dir);
993
3
        partial.upgrade_if_necessary();
994

            
995
3
        GetMicrodescsState {
996
3
            cache_usage,
997
3
            n_microdescs,
998
3
            partial,
999
3
            meta,
3
            newly_listed: Vec::new(),
3
            reset_time,
3
            rt,
3
            config,
3
            prev_netdir,
3

            
3
            #[cfg(feature = "dirfilter")]
3
            filter,
3
        }
3
    }
    /// Add a bunch of microdescriptors to the in-progress netdir.
2
    fn register_microdescs<I>(&mut self, mds: I, _source: &DocSource, changed: &mut bool)
2
    where
2
        I: IntoIterator<Item = (Microdesc, MdDigest)>,
    {
2
        let md_iter = mds
2
            .into_iter()
4
            .map(|(md, sha256)| MicrodescAndHash { md, sha256 });
        #[cfg(feature = "dirfilter")]
4
        let md_iter = md_iter.filter_map(|md| self.filter.filter_md(md).ok());
2
        let mds: Vec<MicrodescAndHash> = md_iter.collect();
2
        let is_partial = matches!(self.partial, PendingNetDir::Partial(..));
2
        for md in mds {
4
            if is_partial {
4
                self.newly_listed.push(*md.digest());
            }
4
            self.partial.add_microdesc(md);
4
            *changed = true;
        }
2
        self.partial.upgrade_if_necessary();
2
    }
}
impl<R: Runtime> DirState for GetMicrodescsState<R> {
2
    fn describe(&self) -> String {
2
        format!(
            "Downloading microdescriptors (we are missing {}).",
2
            self.partial.n_missing()
        )
2
    }
3
    fn missing_docs(&self) -> Vec<DocId> {
3
        self.partial
3
            .missing_microdescs()
7
            .map(|d| DocId::Microdesc(*d))
            .collect()
3
    }
1
    fn get_netdir_change(&mut self) -> Option<NetDirChange<'_>> {
1
        match self.partial {
            PendingNetDir::Yielding {
                ref mut netdir,
                ref mut collected_microdescs,
                ..
            } => {
1
                if netdir.is_some() {
1
                    Some(NetDirChange::AttemptReplace {
1
                        netdir,
1
                        consensus_meta: &self.meta,
1
                    })
                } else {
                    collected_microdescs
                        .is_empty()
                        .then_some(NetDirChange::AddMicrodescs(collected_microdescs))
                }
            }
            _ => None,
        }
1
    }
9
    fn is_ready(&self, ready: Readiness) -> bool {
9
        match ready {
3
            Readiness::Complete => self.partial.n_missing() == 0,
            Readiness::Usable => {
                // We're "usable" if the calling code thought our netdir was usable enough to
                // steal it.
6
                matches!(self.partial, PendingNetDir::Yielding { ref netdir, .. } if netdir.is_none())
            }
        }
9
    }
2
    fn can_advance(&self) -> bool {
2
        false
2
    }
2
    fn bootstrap_progress(&self) -> DirProgress {
2
        let n_present = self.n_microdescs - self.partial.n_missing();
2
        DirProgress::Validated {
2
            lifetime: self.meta.lifetime().clone(),
2
            usable_lifetime: self.config.tolerance.extend_lifetime(self.meta.lifetime()),
2
            n_mds: (n_present as u32, self.n_microdescs as u32),
2
            usable: self.is_ready(Readiness::Usable),
2
        }
2
    }
1
    fn dl_config(&self) -> DownloadSchedule {
1
        self.config.schedule.retry_microdescs()
1
    }
1
    fn add_from_cache(
1
        &mut self,
1
        docs: HashMap<DocId, DocumentText>,
1
        changed: &mut bool,
1
    ) -> Result<()> {
1
        let mut microdescs = Vec::new();
1
        for (id, text) in docs {
1
            if let DocId::Microdesc(digest) = id {
1
                let filename = DocSource::LocalCache.for_parse_input();
                let input =
1
                    ParseInput::new(text.as_str().map_err(Error::BadUtf8InCache)?, &filename);
1
                if let Ok(md) = parse2::parse_netdoc::<Microdesc>(&input) {
1
                    let digest_found: MdDigest = tor_llcrypto::d::Sha256::digest(text).into();
1
                    if digest == digest_found {
1
                        microdescs.push((md, digest));
1
                        continue;
                    }
                }
                warn!("Found a mismatched microdescriptor in cache; ignoring");
            }
        }
1
        self.register_microdescs(microdescs, &DocSource::LocalCache, changed);
1
        Ok(())
1
    }
1
    fn add_from_download(
1
        &mut self,
1
        text: &str,
1
        request: &ClientRequest,
1
        source: DocSource,
1
        storage: Option<&Mutex<DynStore>>,
1
        changed: &mut bool,
1
    ) -> Result<()> {
1
        let requested: HashSet<_> = if let ClientRequest::Microdescs(req) = request {
1
            req.digests().collect()
        } else {
            return Err(internal!("expected a microdesc request").into());
        };
1
        let mut new_mds = Vec::new();
1
        let mut nonfatal_err = None;
1
        let file = source.for_parse_input();
1
        let input = ParseInput::new(text, &file);
        for (microdesc, start, end) in
1
            parse2::parse_netdoc_multiple_sophisticated::<Microdesc>(&input)?
        {
3
            let md = match microdesc {
                Err(e) => {
                    nonfatal_err.get_or_insert_with(|| Error::from_parse(source.clone(), e));
                    continue;
                }
3
                Ok(a) => a,
            };
3
            let txt = text
3
                .get(start..end)
                .ok_or_else(|| internal!("Parser returned invalid string indices"))?;
3
            let digest: MdDigest = tor_llcrypto::d::Sha256::digest(txt).into();
3
            if !requested.contains(&digest) {
                warn!(
                    "Received microdescriptor from {} we did not ask for: {:?}",
                    source, digest
                );
                nonfatal_err.get_or_insert(Error::Unwanted("un-requested microdescriptor"));
                continue;
3
            }
3
            new_mds.push((txt, md, digest));
        }
1
        let mark_listed = self.meta.lifetime().valid_after();
1
        if let Some(store) = storage {
1
            let mut s = store
1
                .lock()
1
                //.get_mut()
1
                .expect("Directory storage lock poisoned");
1
            if !self.newly_listed.is_empty() {
1
                s.update_microdescs_listed(&self.newly_listed, mark_listed)?;
1
                self.newly_listed.clear();
            }
1
            if !new_mds.is_empty() {
1
                s.store_microdescs(
1
                    &new_mds
1
                        .iter()
3
                        .map(|(text, _md, digest)| (*text, digest))
                        .collect::<Vec<_>>(),
1
                    mark_listed,
                )?;
            }
        }
1
        self.register_microdescs(
3
            new_mds.into_iter().map(|(_text, md, digest)| (md, digest)),
1
            &source,
1
            changed,
        );
1
        opt_err_to_result(nonfatal_err)
1
    }
    fn advance(self: Box<Self>) -> Box<dyn DirState> {
        self
    }
1
    fn reset_time(&self) -> Option<SystemTime> {
        // TODO(nickm): The reset logic is a little wonky here: we don't truly
        // want to _reset_ this state at `replace_dir_time`.  In fact, we ought
        // to be able to have multiple states running in parallel: one filling
        // in the mds for an old consensus, and one trying to fetch a better
        // one.  That's likely to require some amount of refactoring of the
        // bootstrap code.
1
        Some(match self.partial {
            // If the client has taken a completed netdir, the netdir is now
            // usable: We can reset our download attempt when we choose to try
            // to replace this directory.
            PendingNetDir::Yielding {
                replace_dir_time,
                netdir: None,
                ..
            } => replace_dir_time,
            // We don't have a completed netdir: Keep trying to fill this one in
            // until it is _definitely_ unusable.  (Our clock might be skewed;
            // there might be no up-to-date consensus.)
1
            _ => self.reset_time,
        })
1
    }
1
    fn reset(self: Box<Self>) -> Box<dyn DirState> {
1
        let cache_usage = if self.cache_usage == CacheUsage::CacheOnly {
            // Cache only means we can't ever download.
            CacheUsage::CacheOnly
1
        } else if self.is_ready(Readiness::Usable) {
            // If we managed to bootstrap a usable consensus, then we won't
            // accept our next consensus from the cache.
            CacheUsage::MustDownload
        } else {
            // If we didn't manage to bootstrap a usable consensus, then we can
            // indeed try again with the one in the cache.
            // TODO(nickm) is this right?
1
            CacheUsage::CacheOkay
        };
1
        Box::new(GetConsensusState::new(
1
            self.rt,
1
            self.config,
1
            cache_usage,
1
            self.prev_netdir,
1
            #[cfg(feature = "dirfilter")]
1
            self.filter,
1
        ))
1
    }
}
/// Choose a random download time to replace a consensus whose lifetime
/// is `lifetime`.
101
fn pick_download_time(lifetime: &Lifetime) -> SystemTime {
101
    let (lowbound, uncertainty) = client_download_range(lifetime);
101
    lowbound + rand::rng().gen_range_infallible(..=uncertainty)
101
}
/// Based on the lifetime for a consensus, return the time range during which
/// clients should fetch the next one.
102
fn client_download_range(lt: &Lifetime) -> (SystemTime, Duration) {
102
    let valid_after = lt.valid_after();
102
    let valid_until = lt.valid_until();
102
    let voting_interval = lt.voting_period();
    // This is checked in the `Lifetime` constructor.
102
    let whole_lifetime = valid_until
102
        .duration_since(valid_after)
102
        .expect("valid-after must precede valid-until");
    // From dir-spec:
    // "This time is chosen uniformly at random from the interval
    // between the time 3/4 into the first interval after the
    // consensus is no longer fresh, and 7/8 of the time remaining
    // after that before the consensus is invalid."
102
    let lowbound = voting_interval + (voting_interval * 3) / 4;
102
    if lowbound > whole_lifetime {
        warn!(
            "Consensus lifetime validity period is too short for given voting interval. \
             This should not happen if directory authorities are operating according to the spec."
        );
102
    }
102
    let remainder = whole_lifetime.saturating_sub(lowbound);
102
    let uncertainty = (remainder * 7) / 8;
102
    (valid_after + lowbound, uncertainty)
102
}
/// If `err` is some, return `Err(err)`.  Otherwise return Ok(()).
4
fn opt_err_to_result(e: Option<Error>) -> Result<()> {
4
    match e {
1
        Some(e) => Err(e),
3
        None => Ok(()),
    }
4
}
/// A dummy state implementation, used when we need to temporarily write a
/// placeholder into a box.
///
/// Calling any method on this state will panic.
#[derive(Clone, Debug)]
pub(crate) struct PoisonedState;
impl DirState for PoisonedState {
    fn describe(&self) -> String {
        unimplemented!()
    }
    fn missing_docs(&self) -> Vec<DocId> {
        unimplemented!()
    }
    fn is_ready(&self, _ready: Readiness) -> bool {
        unimplemented!()
    }
    fn can_advance(&self) -> bool {
        unimplemented!()
    }
    fn add_from_cache(
        &mut self,
        _docs: HashMap<DocId, DocumentText>,
        _changed: &mut bool,
    ) -> Result<()> {
        unimplemented!()
    }
    fn add_from_download(
        &mut self,
        _text: &str,
        _request: &ClientRequest,
        _source: DocSource,
        _storage: Option<&Mutex<DynStore>>,
        _changed: &mut bool,
    ) -> Result<()> {
        unimplemented!()
    }
    fn bootstrap_progress(&self) -> event::DirProgress {
        unimplemented!()
    }
    fn dl_config(&self) -> DownloadSchedule {
        unimplemented!()
    }
    fn advance(self: Box<Self>) -> Box<dyn DirState> {
        unimplemented!()
    }
    fn reset_time(&self) -> Option<SystemTime> {
        unimplemented!()
    }
    fn reset(self: Box<Self>) -> Box<dyn DirState> {
        unimplemented!()
    }
}
#[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 std::convert::TryInto;
    use std::sync::Arc;
    use tempfile::TempDir;
    use time::macros::datetime;
    use tor_dircommon::{
        authority::{AuthorityContacts, AuthorityContactsBuilder},
        config::{DownloadScheduleConfig, NetworkConfig},
    };
    use tor_netdoc::{
        AllowAnnotations,
        doc::{authcert::AuthCertKeyIds, microdesc::MicrodescReader},
    };
    use tor_rtcompat::RuntimeSubstExt as _;
    use tor_rtmock::simple_time::SimpleMockTimeProvider;
    #[test]
    fn download_schedule() {
        let va = datetime!(2008-08-02 20:00 UTC).into();
        let fu = datetime!(2008-08-02 21:00 UTC).into();
        let vu = datetime!(2008-08-02 23:00 UTC).into();
        let lifetime = Lifetime::new(va, fu, vu).unwrap();
        let expected_start: SystemTime = datetime!(2008-08-02 21:45 UTC).into();
        let expected_range = Duration::from_millis((75 * 60 * 1000) * 7 / 8);
        let (start, range) = client_download_range(&lifetime);
        assert_eq!(start, expected_start);
        assert_eq!(range, expected_range);
        for _ in 0..100 {
            let when = pick_download_time(&lifetime);
            assert!(when > va);
            assert!(when >= expected_start);
            assert!(when < vu);
            assert!(when <= expected_start + range);
        }
    }
    /// Makes a memory-backed storage.
    fn temp_store() -> (TempDir, Mutex<DynStore>) {
        let tempdir = TempDir::new().unwrap();
        let store = crate::storage::SqliteStore::from_path_and_mistrust(
            tempdir.path(),
            &fs_mistrust::Mistrust::new_dangerously_trust_everyone(),
            false,
        )
        .unwrap();
        (tempdir, Mutex::new(Box::new(store)))
    }
    fn make_time_shifted_runtime(now: SystemTime, rt: impl Runtime) -> impl Runtime {
        let msp = SimpleMockTimeProvider::from_wallclock(now);
        rt.with_sleep_provider(msp.clone())
            .with_coarse_time_provider(msp)
    }
    fn make_dirmgr_config(authorities: Option<AuthorityContactsBuilder>) -> Arc<DirMgrConfig> {
        let mut netcfg = NetworkConfig::builder();
        netcfg.set_fallback_caches(vec![]);
        if let Some(a) = authorities {
            *netcfg.authorities() = a;
        }
        let cfg = DirMgrConfig {
            cache_dir: "/we_will_never_use_this/".into(),
            network: netcfg.build().unwrap(),
            ..Default::default()
        };
        Arc::new(cfg)
    }
    // Test data
    const CONSENSUS: &str = include_str!("../testdata/mdconsensus1.txt");
    const CONSENSUS2: &str = include_str!("../testdata/mdconsensus2.txt");
    const AUTHCERT_5696: &str = include_str!("../testdata/cert-5696.txt");
    const AUTHCERT_5A23: &str = include_str!("../testdata/cert-5A23.txt");
    #[allow(unused)]
    const AUTHCERT_7C47: &str = include_str!("../testdata/cert-7C47.txt");
    fn test_time() -> SystemTime {
        datetime!(2020-08-07 12:42:45 UTC).into()
    }
    fn rsa(s: &str) -> RsaIdentity {
        RsaIdentity::from_hex(s).unwrap()
    }
    fn test_authorities() -> AuthorityContactsBuilder {
        let mut builder = AuthorityContacts::builder();
        builder
            .v3idents()
            .push(rsa("5696AB38CB3852AFA476A5C07B2D4788963D5567"));
        builder
            .v3idents()
            .push(rsa("5A23BA701776C9C1AB1C06E734E92AB3D5350D64"));
        builder
    }
    fn authcert_id_5696() -> AuthCertKeyIds {
        AuthCertKeyIds {
            id_fingerprint: rsa("5696ab38cb3852afa476a5c07b2d4788963d5567"),
            sk_fingerprint: rsa("f6ed4aa64d83caede34e19693a7fcf331aae8a6a"),
        }
    }
    fn authcert_id_5a23() -> AuthCertKeyIds {
        AuthCertKeyIds {
            id_fingerprint: rsa("5a23ba701776c9c1ab1c06e734e92ab3d5350d64"),
            sk_fingerprint: rsa("d08e965cc6dcb6cb6ed776db43e616e93af61177"),
        }
    }
    // remember, we're saying that we don't recognize this one as an authority.
    fn authcert_id_7c47() -> AuthCertKeyIds {
        AuthCertKeyIds {
            id_fingerprint: rsa("7C47DCB4A90E2C2B7C7AD27BD641D038CF5D7EBE"),
            sk_fingerprint: rsa("D3C013E0E6C82E246090D1C0798B75FCB7ACF120"),
        }
    }
    fn microdescs() -> HashMap<MdDigest, String> {
        const MICRODESCS: &str = include_str!("../testdata/microdescs.txt");
        let text = MICRODESCS;
        MicrodescReader::new(text, &AllowAnnotations::AnnotationsNotAllowed)
            .unwrap()
            .map(|res| {
                let anno = res.unwrap();
                let text = anno.within(text).unwrap();
                let md = anno.into_microdesc();
                (*md.digest(), text.to_owned())
            })
            .collect()
    }
    #[test]
    fn get_consensus_state() {
        tor_rtcompat::test_with_one_runtime!(|rt| async move {
            let rt = make_time_shifted_runtime(test_time(), rt);
            let cfg = make_dirmgr_config(None);
            let (_tempdir, store) = temp_store();
            let mut state = GetConsensusState::new(
                rt.clone(),
                cfg,
                CacheUsage::CacheOkay,
                None,
                #[cfg(feature = "dirfilter")]
                Arc::new(crate::filter::NilFilter),
            );
            // Is description okay?
            assert_eq!(&state.describe(), "Looking for a consensus.");
            // Basic properties: without a consensus it is not ready to advance.
            assert!(!state.can_advance());
            assert!(!state.is_ready(Readiness::Complete));
            assert!(!state.is_ready(Readiness::Usable));
            // Basic properties: it doesn't want to reset.
            assert!(state.reset_time().is_none());
            // Its starting DirStatus is "fetching a consensus".
            assert_eq!(
                state.bootstrap_progress().to_string(),
                "fetching a consensus"
            );
            // Download configuration is simple: only 1 request can be done in
            // parallel.  It uses a consensus retry schedule.
            let retry = state.dl_config();
            assert_eq!(retry, DownloadScheduleConfig::default().retry_consensus());
            // Do we know what we want?
            let docs = state.missing_docs();
            assert_eq!(docs.len(), 1);
            let docid = docs[0];
            assert!(matches!(
                docid,
                DocId::LatestConsensus {
                    flavor: ConsensusFlavor::Microdesc,
                    cache_usage: CacheUsage::CacheOkay,
                }
            ));
            let source = DocSource::DirServer { source: None };
            // Now suppose that we get some complete junk from a download.
            let req = tor_dirclient::request::ConsensusRequest::new(ConsensusFlavor::Microdesc);
            let req = crate::docid::ClientRequest::Consensus(req);
            let mut changed = false;
            let outcome = state.add_from_download(
                "this isn't a consensus",
                &req,
                source.clone(),
                Some(&store),
                &mut changed,
            );
            assert!(matches!(outcome, Err(Error::ParseError { .. })));
            assert!(!changed);
            // make sure it wasn't stored...
            assert!(
                store
                    .lock()
                    .unwrap()
                    .latest_consensus(ConsensusFlavor::Microdesc, None)
                    .unwrap()
                    .is_none()
            );
            // Now try again, with a real consensus... but the wrong authorities.
            let mut changed = false;
            let outcome = state.add_from_download(
                CONSENSUS,
                &req,
                source.clone(),
                Some(&store),
                &mut changed,
            );
            assert!(matches!(outcome, Err(Error::UnrecognizedAuthorities)));
            assert!(!changed);
            assert!(
                store
                    .lock()
                    .unwrap()
                    .latest_consensus(ConsensusFlavor::Microdesc, None)
                    .unwrap()
                    .is_none()
            );
            // Great. Change the receiver to use a configuration where these test
            // authorities are recognized.
            let cfg = make_dirmgr_config(Some(test_authorities()));
            let mut state = GetConsensusState::new(
                rt.clone(),
                cfg,
                CacheUsage::CacheOkay,
                None,
                #[cfg(feature = "dirfilter")]
                Arc::new(crate::filter::NilFilter),
            );
            let mut changed = false;
            let outcome =
                state.add_from_download(CONSENSUS, &req, source, Some(&store), &mut changed);
            assert!(outcome.is_ok());
            assert!(changed);
            assert!(
                store
                    .lock()
                    .unwrap()
                    .latest_consensus(ConsensusFlavor::Microdesc, None)
                    .unwrap()
                    .is_some()
            );
            // And with that, we should be asking for certificates
            assert!(state.can_advance());
            assert_eq!(&state.describe(), "About to fetch certificates.");
            assert_eq!(state.missing_docs(), Vec::new());
            let next = Box::new(state).advance();
            assert_eq!(
                &next.describe(),
                "Downloading certificates for consensus (we are missing 2/2)."
            );
            // Try again, but this time get the state from the cache.
            let cfg = make_dirmgr_config(Some(test_authorities()));
            let mut state = GetConsensusState::new(
                rt,
                cfg,
                CacheUsage::CacheOkay,
                None,
                #[cfg(feature = "dirfilter")]
                Arc::new(crate::filter::NilFilter),
            );
            let text: crate::storage::InputString = CONSENSUS.to_owned().into();
            let map = vec![(docid, text.into())].into_iter().collect();
            let mut changed = false;
            let outcome = state.add_from_cache(map, &mut changed);
            assert!(outcome.is_ok());
            assert!(changed);
            assert!(state.can_advance());
        });
    }
    #[test]
    fn get_certs_state() {
        tor_rtcompat::test_with_one_runtime!(|rt| async move {
            /// Construct a GetCertsState with our test data
            fn new_getcerts_state(rt: impl Runtime) -> Box<dyn DirState> {
                let rt = make_time_shifted_runtime(test_time(), rt);
                let cfg = make_dirmgr_config(Some(test_authorities()));
                let mut state = GetConsensusState::new(
                    rt,
                    cfg,
                    CacheUsage::CacheOkay,
                    None,
                    #[cfg(feature = "dirfilter")]
                    Arc::new(crate::filter::NilFilter),
                );
                let source = DocSource::DirServer { source: None };
                let req = tor_dirclient::request::ConsensusRequest::new(ConsensusFlavor::Microdesc);
                let req = crate::docid::ClientRequest::Consensus(req);
                let mut changed = false;
                let outcome = state.add_from_download(CONSENSUS, &req, source, None, &mut changed);
                assert!(outcome.is_ok());
                Box::new(state).advance()
            }
            let (_tempdir, store) = temp_store();
            let mut state = new_getcerts_state(rt.clone());
            // Basic properties: description, status, reset time.
            assert_eq!(
                &state.describe(),
                "Downloading certificates for consensus (we are missing 2/2)."
            );
            assert!(!state.can_advance());
            assert!(!state.is_ready(Readiness::Complete));
            assert!(!state.is_ready(Readiness::Usable));
            let consensus_expires: SystemTime = datetime!(2020-08-07 12:43:20 UTC).into();
            let post_valid_tolerance = crate::DirTolerance::default().post_valid_tolerance();
            assert_eq!(
                state.reset_time(),
                Some(consensus_expires + post_valid_tolerance)
            );
            let retry = state.dl_config();
            assert_eq!(retry, DownloadScheduleConfig::default().retry_certs());
            // Bootstrap status okay?
            assert_eq!(
                state.bootstrap_progress().to_string(),
                "fetching authority certificates (0/2)"
            );
            // Check that we get the right list of missing docs.
            let missing = state.missing_docs();
            assert_eq!(missing.len(), 2); // We are missing two certificates.
            assert!(missing.contains(&DocId::AuthCert(authcert_id_5696())));
            assert!(missing.contains(&DocId::AuthCert(authcert_id_5a23())));
            // we don't ask for this one because we don't recognize its authority
            assert!(!missing.contains(&DocId::AuthCert(authcert_id_7c47())));
            // Add one from the cache; make sure the list is still right
            let text1: crate::storage::InputString = AUTHCERT_5696.to_owned().into();
            // let text2: crate::storage::InputString = AUTHCERT_5A23.to_owned().into();
            let docs = vec![(DocId::AuthCert(authcert_id_5696()), text1.into())]
                .into_iter()
                .collect();
            let mut changed = false;
            let outcome = state.add_from_cache(docs, &mut changed);
            assert!(changed);
            assert!(outcome.is_ok()); // no error, and something changed.
            assert!(!state.can_advance()); // But we aren't done yet.
            let missing = state.missing_docs();
            assert_eq!(missing.len(), 1); // Now we're only missing one!
            assert!(missing.contains(&DocId::AuthCert(authcert_id_5a23())));
            assert_eq!(
                state.bootstrap_progress().to_string(),
                "fetching authority certificates (1/2)"
            );
            // Now try to add the other from a download ... but fail
            // because we didn't ask for it.
            let source = DocSource::DirServer { source: None };
            let mut req = tor_dirclient::request::AuthCertRequest::new();
            req.push(authcert_id_5696()); // it's the wrong id.
            let req = ClientRequest::AuthCert(req);
            let mut changed = false;
            let outcome = state.add_from_download(
                AUTHCERT_5A23,
                &req,
                source.clone(),
                Some(&store),
                &mut changed,
            );
            assert!(matches!(outcome, Err(Error::Unwanted(_))));
            assert!(!changed);
            let missing2 = state.missing_docs();
            assert_eq!(missing, missing2); // No change.
            assert!(
                store
                    .lock()
                    .unwrap()
                    .authcerts(&[authcert_id_5a23()])
                    .unwrap()
                    .is_empty()
            );
            // Now try to add the other from a download ... for real!
            let mut req = tor_dirclient::request::AuthCertRequest::new();
            req.push(authcert_id_5a23()); // Right idea this time!
            let req = ClientRequest::AuthCert(req);
            let mut changed = false;
            let outcome =
                state.add_from_download(AUTHCERT_5A23, &req, source, Some(&store), &mut changed);
            assert!(outcome.is_ok()); // No error, _and_ something changed!
            assert!(changed);
            let missing3 = state.missing_docs();
            assert!(missing3.is_empty());
            assert!(state.can_advance());
            assert!(
                !store
                    .lock()
                    .unwrap()
                    .authcerts(&[authcert_id_5a23()])
                    .unwrap()
                    .is_empty()
            );
            let next = state.advance();
            assert_eq!(
                &next.describe(),
                "Downloading microdescriptors (we are missing 6)."
            );
            // If we start from scratch and reset, we're back in GetConsensus.
            let state = new_getcerts_state(rt);
            let state = state.reset();
            assert_eq!(&state.describe(), "Downloading a consensus.");
            // TODO: I'd like even more tests to make sure that we never
            // accept a certificate for an authority we don't believe in.
        });
    }
    #[test]
    fn get_microdescs_state() {
        use parse2::NetdocParseableUnverified as _;
        tor_rtcompat::test_with_one_runtime!(|rt| async move {
            /// Construct a GetCertsState with our test data
            fn new_getmicrodescs_state(rt: impl Runtime) -> GetMicrodescsState<impl Runtime> {
                let rt = make_time_shifted_runtime(test_time(), rt);
                let cfg = make_dirmgr_config(Some(test_authorities()));
                let consensus = parse2::parse_netdoc::<MdConsensusUnverified>(&ParseInput::new(
                    CONSENSUS2, "~",
                ))
                .unwrap();
                let consensus = consensus.unwrap_unverified().0;
                // (Using junk values for hashes here, but that's ok in the context of this test)
                let meta = ConsensusMeta::from_text_and_lifetime(
                    "",
                    "",
                    consensus.preamble.lifetime.clone(),
                );
                GetMicrodescsState::new(
                    CacheUsage::CacheOkay,
                    consensus,
                    meta,
                    rt,
                    cfg,
                    None,
                    #[cfg(feature = "dirfilter")]
                    Arc::new(crate::filter::NilFilter),
                )
            }
            fn d64(s: &str) -> MdDigest {
                use base64ct::{Base64Unpadded, Encoding as _};
                Base64Unpadded::decode_vec(s).unwrap().try_into().unwrap()
            }
            // If we start from scratch and reset, we're back in GetConsensus.
            let state = new_getmicrodescs_state(rt.clone());
            let state = Box::new(state).reset();
            assert_eq!(&state.describe(), "Looking for a consensus.");
            // Check the basics.
            let mut state = new_getmicrodescs_state(rt.clone());
            assert_eq!(
                &state.describe(),
                "Downloading microdescriptors (we are missing 4)."
            );
            assert!(!state.can_advance());
            assert!(!state.is_ready(Readiness::Complete));
            assert!(!state.is_ready(Readiness::Usable));
            {
                let reset_time = state.reset_time().unwrap();
                let fresh_until: SystemTime = datetime!(2021-10-27 21:27:00 UTC).into();
                let valid_until: SystemTime = datetime!(2021-10-27 21:27:20 UTC).into();
                assert!(reset_time >= fresh_until);
                assert!(reset_time <= valid_until + state.config.tolerance.post_valid_tolerance());
            }
            let retry = state.dl_config();
            assert_eq!(retry, DownloadScheduleConfig::default().retry_microdescs());
            assert_eq!(
                state.bootstrap_progress().to_string(),
                "fetching microdescriptors (0/4)"
            );
            // Now check whether we're missing all the right microdescs.
            let missing = state.missing_docs();
            let md_text = microdescs();
            assert_eq!(missing.len(), 4);
            assert_eq!(md_text.len(), 4);
            let md1 = d64("LOXRj8YZP0kwpEAsYOvBZWZWGoWv5b/Bp2Mz2Us8d8g");
            let md2 = d64("iOhVp33NyZxMRDMHsVNq575rkpRViIJ9LN9yn++nPG0");
            let md3 = d64("/Cd07b3Bl0K0jX2/1cAvsYXJJMi5d8UBU+oWKaLxoGo");
            let md4 = d64("z+oOlR7Ga6cg9OoC/A3D3Ey9Rtc4OldhKlpQblMfQKo");
            for md_digest in [md1, md2, md3, md4] {
                assert!(missing.contains(&DocId::Microdesc(md_digest)));
                assert!(md_text.contains_key(&md_digest));
            }
            // Try adding a microdesc from the cache.
            let (_tempdir, store) = temp_store();
            let doc1: crate::storage::InputString = md_text.get(&md1).unwrap().clone().into();
            let docs = vec![(DocId::Microdesc(md1), doc1.into())]
                .into_iter()
                .collect();
            let mut changed = false;
            let outcome = state.add_from_cache(docs, &mut changed);
            assert!(outcome.is_ok()); // successfully loaded one MD.
            assert!(changed);
            assert!(!state.can_advance());
            assert!(!state.is_ready(Readiness::Complete));
            assert!(!state.is_ready(Readiness::Usable));
            // Now we should be missing 3.
            let missing = state.missing_docs();
            assert_eq!(missing.len(), 3);
            assert!(!missing.contains(&DocId::Microdesc(md1)));
            assert_eq!(
                state.bootstrap_progress().to_string(),
                "fetching microdescriptors (1/4)"
            );
            // Try adding the rest as if from a download.
            let mut req = tor_dirclient::request::MicrodescRequest::new();
            let mut response = "".to_owned();
            for md_digest in [md2, md3, md4] {
                response.push_str(md_text.get(&md_digest).unwrap());
                req.push(md_digest);
            }
            let req = ClientRequest::Microdescs(req);
            let source = DocSource::DirServer { source: None };
            let mut changed = false;
            let outcome = state.add_from_download(
                response.as_str(),
                &req,
                source,
                Some(&store),
                &mut changed,
            );
            assert!(outcome.is_ok()); // successfully loaded MDs
            assert!(changed);
            match state.get_netdir_change().unwrap() {
                NetDirChange::AttemptReplace { netdir, .. } => {
                    assert!(netdir.take().is_some());
                }
                x => panic!("wrong netdir change: {:?}", x),
            }
            assert!(state.is_ready(Readiness::Complete));
            assert!(state.is_ready(Readiness::Usable));
            assert_eq!(
                store
                    .lock()
                    .unwrap()
                    .microdescs(&[md2, md3, md4])
                    .unwrap()
                    .len(),
                3
            );
            let missing = state.missing_docs();
            assert!(missing.is_empty());
        });
    }
}