1
//! Functions to download or load directory objects, using the
2
//! state machines in the `states` module.
3

            
4
use std::num::NonZeroUsize;
5
use std::ops::Deref;
6
use std::result::Result as StdResult;
7
use std::{
8
    collections::HashMap,
9
    sync::{Arc, Weak},
10
    time::{Duration, SystemTime},
11
};
12

            
13
use crate::DirMgrConfig;
14
use crate::DocSource;
15
use crate::err::BootstrapAction;
16
use crate::state::{DirState, PoisonedState};
17
use crate::{
18
    DirMgr, DocId, DocQuery, DocumentText, Error, Readiness, Result,
19
    docid::{self, ClientRequest},
20
    upgrade_weak_ref,
21
};
22

            
23
use futures::FutureExt;
24
use futures::StreamExt;
25
use oneshot_fused_workaround as oneshot;
26
use tor_dirclient::DirResponse;
27
use tor_error::{info_report, warn_report};
28
use tor_rtcompat::Runtime;
29
use tor_rtcompat::scheduler::TaskSchedule;
30
use tracing::{debug, info, instrument, trace, warn};
31

            
32
use crate::storage::Store;
33
#[cfg(test)]
34
use std::sync::LazyLock;
35
#[cfg(test)]
36
use std::sync::Mutex;
37
use tor_circmgr::{CircMgr, DirInfo};
38
use tor_netdir::{NetDir, NetDirProvider as _};
39
use tor_netdoc::doc::netstatus::ConsensusFlavor;
40

            
41
/// Given a Result<()>, exit the current function if it is anything other than
42
/// Ok(), or a nonfatal error.
43
macro_rules! propagate_fatal_errors {
44
    ( $e:expr ) => {
45
        let v: Result<()> = $e;
46
        if let Err(e) = v {
47
            match e.bootstrap_action() {
48
                BootstrapAction::Nonfatal => {}
49
                _ => return Err(e),
50
            }
51
        }
52
    };
53
}
54

            
55
/// Identifier for an attempt to bootstrap a directory.
56
///
57
/// Every time that we decide to download a new directory, _despite already
58
/// having one_, counts as a new attempt.
59
///
60
/// These are used to track the progress of each attempt independently.
61
#[derive(Copy, Clone, Debug, derive_more::Display, Eq, PartialEq, Ord, PartialOrd)]
62
#[display("{0}", id)]
63
pub(crate) struct AttemptId {
64
    /// Which attempt at downloading a directory is this?
65
    id: NonZeroUsize,
66
}
67

            
68
impl AttemptId {
69
    /// Return a new unused AtomicUsize that will be greater than any previous
70
    /// one.
71
    ///
72
    /// # Panics
73
    ///
74
    /// Panics if we have exhausted the possible space of AtomicIds.
75
4
    pub(crate) fn next() -> Self {
76
        use std::sync::atomic::{AtomicUsize, Ordering};
77
        /// atomic used to generate the next attempt.
78
        static NEXT: AtomicUsize = AtomicUsize::new(1);
79
4
        let id = NEXT.fetch_add(1, Ordering::Relaxed);
80
4
        let id = id.try_into().expect("Allocated too many AttemptIds");
81
4
        Self { id }
82
4
    }
83
}
84

            
85
/// If there were errors from a peer in `outcome`, record those errors by
86
/// marking the circuit (if any) as needing retirement, and noting the peer
87
/// (if any) as having failed.
88
fn note_request_outcome<R: Runtime>(
89
    circmgr: &CircMgr<R>,
90
    outcome: &tor_dirclient::Result<tor_dirclient::DirResponse>,
91
) {
92
    use tor_dirclient::{Error::RequestFailed, RequestFailedError};
93
    // Extract an error and a source from this outcome, if there is one.
94
    //
95
    // This is complicated because DirResponse can encapsulate the notion of
96
    // a response that failed part way through a download: in the case, it
97
    // has some data, and also an error.
98
    let (err, source) = match outcome {
99
        Ok(req) => {
100
            if let (Some(e), Some(source)) = (req.error(), req.source()) {
101
                (
102
                    RequestFailed(RequestFailedError {
103
                        error: e.clone(),
104
                        source: Some(source.clone()),
105
                    }),
106
                    source,
107
                )
108
            } else {
109
                return;
110
            }
111
        }
112
        Err(
113
            error @ RequestFailed(RequestFailedError {
114
                source: Some(source),
115
                ..
116
            }),
117
        ) => (error.clone(), source),
118
        _ => return,
119
    };
120

            
121
    note_cache_error(circmgr, source, &err.into());
122
}
123

            
124
/// Record that a problem has occurred because of a failure in an answer from `source`.
125
fn note_cache_error<R: Runtime>(
126
    circmgr: &CircMgr<R>,
127
    source: &tor_dirclient::SourceInfo,
128
    problem: &Error,
129
) {
130
    use tor_circmgr::ExternalActivity;
131

            
132
    if !problem.indicates_cache_failure() {
133
        return;
134
    }
135

            
136
    // Does the error here tell us whom to really blame?  If so, blame them
137
    // instead.
138
    //
139
    // (This can happen if we notice a problem while downloading a certificate,
140
    // but the real problem is that the consensus was no good.)
141
    let real_source = problem.cache_info().unwrap_or(source);
142

            
143
    info_report!(problem, "Marking {:?} as failed", real_source);
144
    circmgr.note_external_failure(real_source.cache_id(), ExternalActivity::DirCache);
145
    circmgr.retire_circ(source.unique_circ_id());
146
}
147

            
148
/// Record that `source` has successfully given us some directory info.
149
fn note_cache_success<R: Runtime>(circmgr: &CircMgr<R>, source: &tor_dirclient::SourceInfo) {
150
    use tor_circmgr::ExternalActivity;
151

            
152
    trace!("Marking {:?} as successful", source);
153
    circmgr.note_external_success(source.cache_id(), ExternalActivity::DirCache);
154
}
155

            
156
/// Load every document in `missing` and try to apply it to `state`.
157
6
fn load_and_apply_documents<R: Runtime>(
158
6
    missing: &[DocId],
159
6
    dirmgr: &Arc<DirMgr<R>>,
160
6
    state: &mut Box<dyn DirState>,
161
6
    changed: &mut bool,
162
6
) -> Result<()> {
163
    /// How many documents will we try to load at once?  We try to keep this from being too large,
164
    /// to avoid excessive RAM usage.
165
    ///
166
    /// TODO: we may well want to tune this.
167
    const CHUNK_SIZE: usize = 256;
168
6
    for chunk in missing.chunks(CHUNK_SIZE) {
169
        let documents = {
170
6
            let store = dirmgr.store.lock().expect("store lock poisoned");
171
6
            load_documents_from_store(chunk, &**store)?
172
        };
173

            
174
6
        state.add_from_cache(documents, changed)?;
175
    }
176

            
177
6
    Ok(())
178
6
}
179

            
180
/// Load a set of documents from a `Store`, returning all documents found in the store.
181
/// Note that this may be less than the number of documents in `missing`.
182
6
fn load_documents_from_store(
183
6
    missing: &[DocId],
184
6
    store: &dyn Store,
185
6
) -> Result<HashMap<DocId, DocumentText>> {
186
6
    let mut loaded = HashMap::new();
187
6
    for query in docid::partition_by_type(missing.iter().copied()).values() {
188
6
        query.load_from_store_into(&mut loaded, store)?;
189
    }
190
6
    Ok(loaded)
191
6
}
192

            
193
/// Try to update `state` by loading cached information, on success returns the
194
/// current wall-clock time.
195
4
fn update_state<R: Runtime>(
196
4
    dirmgr: &Arc<DirMgr<R>>,
197
4
    attempt_id: AttemptId,
198
4
    state: &mut Box<dyn DirState>,
199
4
) -> Result<SystemTime> {
200
4
    let state_desc = state.describe();
201
4
    let mut changed = false;
202
4
    trace!(attempt=%attempt_id, state=%state_desc,"Attempting to load directory information from cache.");
203
4
    let load_result = load_once(dirmgr, state, attempt_id, &mut changed);
204
4
    trace!(attempt=%attempt_id, state=%state_desc, outcome=?load_result, "Load attempt complete.");
205
4
    if let Err(e) = &load_result {
206
        // If the load failed but the error can be blamed on a directory
207
        // cache, do so.
208
        if let Some(source) = e.responsible_cache() {
209
            dirmgr.note_errors(attempt_id, 1);
210
            note_cache_error(dirmgr.circmgr()?.deref(), source, e);
211
        }
212
4
    }
213
4
    propagate_fatal_errors!(load_result);
214
4
    Ok(dirmgr.runtime.wallclock())
215
4
}
216

            
217
/// Applies changes from `state` to the manager's netdir.
218
///
219
/// Updates and broadcasts download progress based on the current `state`.
220
/// Panics if manager's store lock is poisoned.
221
// TODO(eta): Consider deprecating state.is_ready().
222
8
fn apply_state<R: Runtime>(
223
8
    dirmgr: &Arc<DirMgr<R>>,
224
8
    state: &mut Box<dyn DirState>,
225
8
    attempt_id: AttemptId,
226
8
) -> Result<()> {
227
8
    let mut store = dirmgr.store.lock().expect("store lock poisoned");
228
8
    dirmgr.apply_netdir_changes(state, &mut **store)?;
229
8
    dirmgr.update_progress(attempt_id, state.bootstrap_progress());
230
8
    Ok(())
231
8
}
232

            
233
/// Errors returned by `advance_state`.
234
enum AdvanceStateError {
235
    /// The directory has already been downloaded completely.
236
    AlreadyComplete,
237
    /// The state can't currently be advanced.
238
    CantAdvanceYet,
239
}
240

            
241
/// Advances the progress of the directory download.
242
///
243
/// Returns `Ok(())` if the state was successfully advanced.
244
///
245
/// # Errors
246
///
247
/// - Returns `AdvanceStateError::AlreadyComplete` if the directory has already been
248
///   fully downloaded.
249
/// - Returns `AdvanceStateError::CantAdvanceYet` if the directory is incomplete and
250
///   the download cannot advance yet.
251
5
fn advance_state(
252
5
    state: &mut Box<dyn DirState>,
253
5
    attempt_id: AttemptId,
254
5
) -> StdResult<(), AdvanceStateError> {
255
5
    if state.is_ready(Readiness::Complete) {
256
2
        trace!(attempt=%attempt_id, state=%state.describe(), "Directory is now Complete.");
257
2
        return Err(AdvanceStateError::AlreadyComplete);
258
3
    }
259

            
260
3
    if state.can_advance() {
261
2
        advance(state);
262
2
        trace!(attempt=%attempt_id, state=%state.describe(), "State has advanced.");
263
2
        return Ok(());
264
1
    }
265

            
266
1
    Err(AdvanceStateError::CantAdvanceYet)
267
5
}
268

            
269
/// Return value of `perform_download`.
270
///
271
/// Describes the outcome of the attempt to download the current directory's state.
272
enum DownloadOutcome {
273
    /// the download failed with a non-fatal error.
274
    DownloadFailed,
275
    /// The directory being downloaded is outdated.
276
    DirectoryOutdated,
277
    /// The download attempt was successful, and the result has been applied to
278
    /// the state.
279
    Applied,
280
}
281

            
282
/// Attempts to download the current directory's state.
283
///
284
/// On success, it reports the outcome of the download using a
285
/// `DownloadOutcome` instance and updates `now` to the current
286
/// wallclock time.
287
///
288
/// The possible outcomes are:
289
/// - `DownloadOutcome::DownloadFailed`: the download failed with a non-fatal
290
///   error; the caller should proceed to the next state.
291
/// - `DownloadOutcome::DirectoryOutdated`: The directory being downloaded is
292
///   outdated. The caller should attempt a new download. As a side effect,
293
///   the directory state has been reset.
294
/// - `DownloadOutcome::Applied`: The download attempt was successful, and the
295
///   result has been applied to the state.
296
///
297
/// Returns an error only if a fatal error occurred.
298
1
async fn perform_download<R: Runtime>(
299
1
    attempt_id: AttemptId,
300
1
    dirmgr: &Weak<DirMgr<R>>,
301
1
    now: &mut SystemTime,
302
1
    parallelism: u8,
303
1
    schedule: &mut TaskSchedule<R>,
304
1
    state: &mut Box<dyn DirState>,
305
1
) -> Result<DownloadOutcome> {
306
1
    let reset_time = no_more_than_a_week_from(*now, state.reset_time());
307

            
308
1
    *now = {
309
1
        let dirmgr = upgrade_weak_ref(dirmgr)?;
310
1
        futures::select_biased! {
311
1
            outcome = download_attempt(&dirmgr, state, parallelism.into(), attempt_id).fuse() => {
312
1
                if let Err(e) = outcome {
313
                    warn_report!(e, attempt=%attempt_id, "Error while downloading.");
314
                    propagate_fatal_errors!(Err(e));
315
                    return Ok(DownloadOutcome::DownloadFailed);
316
                } else {
317
1
                    trace!(attempt=%attempt_id, "Successfully downloaded some information.");
318
                }
319
            }
320
1
            _ = schedule.sleep_until_wallclock(reset_time).fuse() => {
321
                // We need to reset. This can happen if (for
322
                // example) we're downloading the last few
323
                // microdescriptors on a consensus that now
324
                // we're ready to replace.
325
                info!(attempt=%attempt_id, "Directory being fetched is now outdated; resetting download state.");
326
                reset(state);
327
                return Ok(DownloadOutcome::DirectoryOutdated);
328
            },
329
        };
330
1
        dirmgr.runtime.wallclock()
331
    };
332
1
    Ok(DownloadOutcome::Applied)
333
1
}
334

            
335
/// Construct an appropriate ClientRequest to download a consensus
336
/// of the given flavor.
337
4
pub(crate) fn make_consensus_request(
338
4
    now: SystemTime,
339
4
    flavor: ConsensusFlavor,
340
4
    store: &dyn Store,
341
4
    config: &DirMgrConfig,
342
4
) -> Result<ClientRequest> {
343
4
    let mut request = tor_dirclient::request::ConsensusRequest::new(flavor);
344

            
345
4
    let default_cutoff = crate::default_consensus_cutoff(now, &config.tolerance)?;
346

            
347
4
    match store.latest_consensus_meta(flavor) {
348
        Ok(Some(meta)) => {
349
2
            let valid_after = meta.lifetime().valid_after();
350
2
            request.set_last_consensus_date(std::cmp::max(valid_after, default_cutoff));
351
2
            request.push_old_consensus_digest(*meta.sha3_256_of_signed());
352
        }
353
        latest => {
354
2
            if let Err(e) = latest {
355
                warn_report!(e, "Error loading directory metadata");
356
2
            }
357
            // If we don't have a consensus, then request one that's
358
            // "reasonably new".  That way, our clock is set far in the
359
            // future, we won't download stuff we can't use.
360
2
            request.set_last_consensus_date(default_cutoff);
361
        }
362
    }
363

            
364
4
    request.set_skew_limit(
365
4
        // If we are _fast_ by at least this much, then any valid directory will
366
4
        // seem to be at least this far in the past.
367
4
        config.tolerance.post_valid_tolerance(),
368
4
        // If we are _slow_ by this much, then any valid directory will seem to
369
4
        // be at least this far in the future.
370
4
        config.tolerance.pre_valid_tolerance(),
371
4
    );
372

            
373
4
    Ok(ClientRequest::Consensus(request))
374
4
}
375

            
376
/// Construct a set of `ClientRequest`s in order to fetch the documents in `docs`.
377
7
pub(crate) fn make_requests_for_documents<R: Runtime>(
378
7
    rt: &R,
379
7
    docs: &[DocId],
380
7
    store: &dyn Store,
381
7
    config: &DirMgrConfig,
382
7
) -> Result<Vec<ClientRequest>> {
383
7
    let mut res = Vec::new();
384
7
    for q in docid::partition_by_type(docs.iter().copied())
385
7
        .into_values()
386
7
        .flat_map(|x| x.split_for_download().into_iter())
387
    {
388
9
        match q {
389
            DocQuery::LatestConsensus { flavor, .. } => {
390
2
                res.push(make_consensus_request(
391
2
                    rt.wallclock(),
392
2
                    flavor,
393
2
                    store,
394
2
                    config,
395
2
                )?);
396
            }
397
            DocQuery::AuthCert(ids) => {
398
1
                res.push(ClientRequest::AuthCert(ids.into_iter().collect()));
399
            }
400
            DocQuery::Microdesc(ids) => {
401
4
                res.push(ClientRequest::Microdescs(ids.into_iter().collect()));
402
            }
403
            #[cfg(feature = "routerdesc")]
404
            DocQuery::RouterDesc(ids) => {
405
2
                res.push(ClientRequest::RouterDescs(ids.into_iter().collect()));
406
            }
407
        }
408
    }
409
7
    Ok(res)
410
7
}
411

            
412
/// Launch a single client request and get an associated response.
413
#[instrument(level = "trace", skip_all)]
414
async fn fetch_single<R: Runtime>(
415
    rt: &R,
416
    request: ClientRequest,
417
    current_netdir: Option<&NetDir>,
418
    circmgr: Arc<CircMgr<R>>,
419
) -> Result<(ClientRequest, DirResponse)> {
420
    let dirinfo: DirInfo = match current_netdir {
421
        Some(netdir) => netdir.into(),
422
        None => tor_circmgr::DirInfo::Nothing,
423
    };
424
    let outcome =
425
        tor_dirclient::get_resource(request.as_requestable(), dirinfo, rt, circmgr.clone()).await;
426

            
427
    note_request_outcome(&circmgr, &outcome);
428

            
429
    let resource = outcome?;
430
    Ok((request, resource))
431
}
432

            
433
/// Testing helper: if this is Some, then we return it in place of any
434
/// response to fetch_multiple.
435
///
436
/// Note that only one test uses this: otherwise there would be a race
437
/// condition. :p
438
#[cfg(test)]
439
1
static CANNED_RESPONSE: LazyLock<Mutex<Vec<String>>> = LazyLock::new(|| Mutex::new(vec![]));
440

            
441
/// Launch a set of download requests for a set of missing objects in
442
/// `missing`, and return each request along with the response it received.
443
///
444
/// Don't launch more than `parallelism` requests at once.
445
#[instrument(level = "trace", skip_all)]
446
1
async fn fetch_multiple<R: Runtime>(
447
1
    dirmgr: Arc<DirMgr<R>>,
448
1
    attempt_id: AttemptId,
449
1
    missing: &[DocId],
450
1
    parallelism: usize,
451
1
) -> Result<Vec<(ClientRequest, DirResponse)>> {
452
    let requests = {
453
        let store = dirmgr.store.lock().expect("store lock poisoned");
454
        make_requests_for_documents(&dirmgr.runtime, missing, &**store, &dirmgr.config.get())?
455
    };
456

            
457
    trace!(attempt=%attempt_id, "Launching {} requests for {} documents",
458
           requests.len(), missing.len());
459

            
460
    #[cfg(test)]
461
    {
462
        let m = CANNED_RESPONSE.lock().expect("Poisoned mutex");
463
        if !m.is_empty() {
464
            return Ok(requests
465
                .into_iter()
466
                .zip(m.iter().map(DirResponse::from_get_body))
467
                .collect());
468
        }
469
    }
470

            
471
    let circmgr = dirmgr.circmgr()?;
472
    // Only use timely directories for bootstrapping directories; otherwise, we'll try fallbacks.
473
    let netdir = dirmgr.netdir(tor_netdir::Timeliness::Timely).ok();
474

            
475
    // TODO: instead of waiting for all the queries to finish, we
476
    // could stream the responses back or something.
477
    let responses: Vec<Result<(ClientRequest, DirResponse)>> = futures::stream::iter(requests)
478
        .map(|query| fetch_single(&dirmgr.runtime, query, netdir.as_deref(), circmgr.clone()))
479
        .buffer_unordered(parallelism)
480
        .collect()
481
        .await;
482

            
483
    let mut useful_responses = Vec::new();
484
    for r in responses {
485
        // TODO: on some error cases we might want to stop using this source.
486
        match r {
487
            Ok((request, response)) => {
488
                if response.status_code() == 200 {
489
                    useful_responses.push((request, response));
490
                } else {
491
                    trace!(
492
                        "cache declined request; reported status {:?}",
493
                        response.status_code()
494
                    );
495
                }
496
            }
497
            Err(e) => warn_report!(e, "error while downloading"),
498
        }
499
    }
500

            
501
    trace!(attempt=%attempt_id, "received {} useful responses from our requests.", useful_responses.len());
502

            
503
    Ok(useful_responses)
504
1
}
505

            
506
/// Try to update `state` by loading cached information from `dirmgr`.
507
7
fn load_once<R: Runtime>(
508
7
    dirmgr: &Arc<DirMgr<R>>,
509
7
    state: &mut Box<dyn DirState>,
510
7
    attempt_id: AttemptId,
511
7
    changed_out: &mut bool,
512
7
) -> Result<()> {
513
7
    let missing = state.missing_docs();
514
7
    let mut changed = false;
515
7
    let outcome: Result<()> = if missing.is_empty() {
516
1
        trace!("Found no missing documents; can't advance current state");
517
1
        Ok(())
518
    } else {
519
6
        trace!(
520
            "Found {} missing documents; trying to load them",
521
            missing.len()
522
        );
523

            
524
6
        load_and_apply_documents(&missing, dirmgr, state, &mut changed)
525
    };
526

            
527
    // We have to update the status here regardless of the outcome, if we got
528
    // any information: even if there was an error, we might have received
529
    // partial information that changed our status.
530
7
    if changed {
531
6
        dirmgr.update_progress(attempt_id, state.bootstrap_progress());
532
6
        *changed_out = true;
533
1
    }
534

            
535
7
    outcome
536
7
}
537

            
538
/// Try to load as much state as possible for a provided `state` from the
539
/// cache in `dirmgr`, advancing the state to the extent possible.
540
///
541
/// No downloads are performed; the provided state will not be reset.
542
1
pub(crate) fn load<R: Runtime>(
543
1
    dirmgr: &Arc<DirMgr<R>>,
544
1
    mut state: Box<dyn DirState>,
545
1
    attempt_id: AttemptId,
546
1
) -> Result<Box<dyn DirState>> {
547
1
    let mut safety_counter = 0_usize;
548
    loop {
549
3
        trace!(attempt=%attempt_id, state=%state.describe(), "Loading from cache");
550
3
        let mut changed = false;
551
3
        let outcome = load_once(dirmgr, &mut state, attempt_id, &mut changed);
552
3
        apply_state(dirmgr, &mut state, attempt_id)?;
553
3
        trace!(attempt=%attempt_id, ?outcome, "Load operation completed.");
554

            
555
3
        if let Err(e) = outcome {
556
            match e.bootstrap_action() {
557
                BootstrapAction::Nonfatal => {
558
                    debug!("Recoverable error loading from cache: {}", e);
559
                }
560
                BootstrapAction::Fatal | BootstrapAction::Reset => {
561
                    return Err(e);
562
                }
563
            }
564
3
        }
565

            
566
3
        if state.can_advance() {
567
1
            state = state.advance();
568
1
            trace!(attempt=%attempt_id, state=state.describe(), "State has advanced.");
569
1
            safety_counter = 0;
570
        } else {
571
2
            if !changed {
572
                // TODO: Are there more nonfatal errors that mean we should
573
                // break?
574
1
                trace!(attempt=%attempt_id, state=state.describe(), "No state advancement after load; nothing more to find in the cache.");
575
1
                break;
576
1
            }
577
1
            safety_counter += 1;
578
1
            assert!(
579
1
                safety_counter < 100,
580
                "Spent 100 iterations in the same state: this is a bug"
581
            );
582
        }
583
    }
584

            
585
1
    Ok(state)
586
1
}
587

            
588
/// Helper: Make a set of download attempts for the current directory state,
589
/// and on success feed their results into the state object.
590
///
591
/// This can launch one or more download requests, but will not launch more
592
/// than `parallelism` requests at a time.
593
#[instrument(level = "trace", skip_all)]
594
1
async fn download_attempt<R: Runtime>(
595
1
    dirmgr: &Arc<DirMgr<R>>,
596
1
    state: &mut Box<dyn DirState>,
597
1
    parallelism: usize,
598
1
    attempt_id: AttemptId,
599
1
) -> Result<()> {
600
    let missing = state.missing_docs();
601
    let fetched = fetch_multiple(Arc::clone(dirmgr), attempt_id, &missing, parallelism).await?;
602
    let mut n_errors = 0;
603
    for (client_req, dir_response) in fetched {
604
        let source = dir_response.source().cloned();
605
        let text = match String::from_utf8(dir_response.into_output_unchecked())
606
            .map_err(Error::BadUtf8FromDirectory)
607
        {
608
            Ok(t) => t,
609
            Err(e) => {
610
                if let Some(source) = source {
611
                    n_errors += 1;
612
                    note_cache_error(dirmgr.circmgr()?.deref(), &source, &e);
613
                }
614
                continue;
615
            }
616
        };
617
        match dirmgr.expand_response_text(&client_req, text) {
618
            Ok(text) => {
619
                let doc_source = DocSource::DirServer {
620
                    source: source.clone(),
621
                };
622
                let mut changed = false;
623
                let outcome = state.add_from_download(
624
                    &text,
625
                    &client_req,
626
                    doc_source,
627
                    Some(&dirmgr.store),
628
                    &mut changed,
629
                );
630

            
631
                if !changed {
632
                    debug_assert!(outcome.is_err());
633
                }
634

            
635
                if let Some(source) = source {
636
                    if let Err(e) = &outcome {
637
                        n_errors += 1;
638
                        note_cache_error(dirmgr.circmgr()?.deref(), &source, e);
639
                    } else {
640
                        note_cache_success(dirmgr.circmgr()?.deref(), &source);
641
                    }
642
                }
643

            
644
                if let Err(e) = &outcome {
645
                    dirmgr.note_errors(attempt_id, 1);
646
                    warn_report!(e, "error while adding directory info");
647
                }
648
                propagate_fatal_errors!(outcome);
649
            }
650
            Err(e) => {
651
                warn_report!(e, "Error when expanding directory text");
652
                if let Some(source) = source {
653
                    n_errors += 1;
654
                    note_cache_error(dirmgr.circmgr()?.deref(), &source, &e);
655
                }
656
                propagate_fatal_errors!(Err(e));
657
            }
658
        }
659
    }
660
    if n_errors != 0 {
661
        dirmgr.note_errors(attempt_id, n_errors);
662
    }
663
    dirmgr.update_progress(attempt_id, state.bootstrap_progress());
664

            
665
    Ok(())
666
1
}
667

            
668
/// Download information into a DirState state machine until it is
669
/// ["complete"](Readiness::Complete), or until we hit a non-recoverable error.
670
///
671
/// Use `dirmgr` to load from the cache or to launch downloads.
672
///
673
/// Keep resetting the state as needed.
674
///
675
/// The first time that the state becomes ["usable"](Readiness::Usable), notify
676
/// the sender in `tx_usable`.
677
#[instrument(level = "trace", skip_all)]
678
2
pub(crate) async fn download<R: Runtime>(
679
2
    dirmgr: Weak<DirMgr<R>>,
680
2
    state: &mut Box<dyn DirState>,
681
2
    schedule: &mut TaskSchedule<R>,
682
2
    attempt_id: AttemptId,
683
2
    tx_usable: &mut Option<oneshot::Sender<()>>,
684
2
) -> Result<()> {
685
    let runtime = upgrade_weak_ref(&dirmgr)?.runtime.clone();
686

            
687
    trace!(attempt=%attempt_id, state=%state.describe(), "Trying to download directory material.");
688

            
689
    'next_state: loop {
690
        let retry_config = state.dl_config();
691
        let parallelism = retry_config.parallelism();
692

            
693
        // In theory this could be inside the loop below maybe?  If we
694
        // want to drop the restriction that the missing() members of a
695
        // state must never grow, then we'll need to move it inside.
696
        let mut now = update_state(&upgrade_weak_ref(&dirmgr)?, attempt_id, state)?;
697

            
698
        apply_state(&upgrade_weak_ref(&dirmgr)?, state, attempt_id)?;
699

            
700
        // Skip the downloads if we can...
701

            
702
        match advance_state(state, attempt_id) {
703
            Ok(_) => continue 'next_state,
704
            Err(AdvanceStateError::AlreadyComplete) => return Ok(()),
705
            Err(AdvanceStateError::CantAdvanceYet) => {}
706
        }
707

            
708
        let reset_time = no_more_than_a_week_from(runtime.wallclock(), state.reset_time());
709

            
710
        let mut retry = retry_config.schedule();
711
        let mut delay = None;
712

            
713
        // Make several attempts to fetch whatever we're missing,
714
        // until either we can advance, or we've got a complete
715
        // document, or we run out of tries, or we run out of time.
716
        'next_attempt: for attempt in retry_config.attempts() {
717
            // We wait at the start of this loop, on all attempts but the first.
718
            // This ensures that we always wait between attempts, but not after
719
            // the final attempt.
720
            let next_delay = retry.next_delay(&mut rand::rng());
721
            if let Some(delay) = delay.replace(next_delay) {
722
                let time_until_reset = reset_time
723
                    .duration_since(now)
724
                    .unwrap_or(Duration::from_secs(0));
725
                let real_delay = delay.min(time_until_reset);
726
                debug!(attempt=%attempt_id, "Waiting {:?} for next download attempt...", real_delay);
727
                schedule.sleep(real_delay).await?;
728

            
729
                now = upgrade_weak_ref(&dirmgr)?.runtime.wallclock();
730
                if now >= reset_time {
731
                    info!(attempt=%attempt_id, "Directory being fetched is now outdated; resetting download state.");
732
                    reset(state);
733
                    continue 'next_state;
734
                }
735
            }
736

            
737
            info!(attempt=%attempt_id, "{}: {}", attempt + 1, state.describe());
738
            match perform_download(attempt_id, &dirmgr, &mut now, parallelism, schedule, state)
739
                .await?
740
            {
741
                DownloadOutcome::DownloadFailed => continue 'next_state,
742
                DownloadOutcome::DirectoryOutdated => continue 'next_attempt,
743
                DownloadOutcome::Applied => {}
744
            }
745

            
746
            propagate_fatal_errors!(apply_state(&upgrade_weak_ref(&dirmgr)?, state, attempt_id));
747

            
748
            // Exit if the download is complete. Report usable-ness if appropriate.
749
            match advance_state(state, attempt_id) {
750
                Err(AdvanceStateError::AlreadyComplete) => return Ok(()),
751
                Ok(()) => continue 'next_state,
752
                Err(AdvanceStateError::CantAdvanceYet) => {
753
                    if state.is_ready(Readiness::Usable) {
754
                        if let Some(tx) = tx_usable.take() {
755
                            trace!(attempt=%attempt_id, state=%state.describe(), "directory is now usable.");
756
                            let _ = tx.send(());
757
                        }
758
                    }
759
                }
760
            }
761
        }
762

            
763
        // We didn't advance the state, after all the retries.
764
        warn!(n_attempts=retry_config.n_attempts(),
765
              state=%state.describe(),
766
              "Unable to advance downloading state");
767
        return Err(Error::CantAdvanceState);
768
    }
769
2
}
770

            
771
/// Replace `state` with `state.reset()`.
772
fn reset(state: &mut Box<dyn DirState>) {
773
    let cur_state = std::mem::replace(state, Box::new(PoisonedState));
774
    *state = cur_state.reset();
775
}
776

            
777
/// Replace `state` with `state.advance()`.
778
2
fn advance(state: &mut Box<dyn DirState>) {
779
2
    let cur_state = std::mem::replace(state, Box::new(PoisonedState));
780
2
    *state = cur_state.advance();
781
2
}
782

            
783
/// Helper: Clamp `v` so that it is no more than one week from `now`.
784
///
785
/// If `v` is absent, return the time that's one week from now.
786
///
787
/// We use this to determine a reset time when no reset time is
788
/// available, or when it is too far in the future.
789
6
fn no_more_than_a_week_from(now: SystemTime, v: Option<SystemTime>) -> SystemTime {
790
6
    let one_week_later = now + Duration::new(86400 * 7, 0);
791
6
    match v {
792
3
        Some(t) => std::cmp::min(t, one_week_later),
793
3
        None => one_week_later,
794
    }
795
6
}
796

            
797
#[cfg(test)]
798
mod test {
799
    // @@ begin test lint list maintained by maint/add_warning @@
800
    #![allow(clippy::bool_assert_comparison)]
801
    #![allow(clippy::clone_on_copy)]
802
    #![allow(clippy::dbg_macro)]
803
    #![allow(clippy::mixed_attributes_style)]
804
    #![allow(clippy::print_stderr)]
805
    #![allow(clippy::print_stdout)]
806
    #![allow(clippy::single_char_pattern)]
807
    #![allow(clippy::unwrap_used)]
808
    #![allow(clippy::unchecked_time_subtraction)]
809
    #![allow(clippy::useless_vec)]
810
    #![allow(clippy::needless_pass_by_value)]
811
    #![allow(clippy::string_slice)] // See arti#2571
812
    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
813
    use super::*;
814
    use crate::storage::DynStore;
815
    use crate::test::new_mgr;
816
    use std::sync::Mutex;
817
    use tor_dircommon::retry::DownloadSchedule;
818
    use tor_netdoc::doc::microdesc::MdDigest;
819
    use tor_rtcompat::SleepProvider;
820
    use web_time_compat::SystemTimeExt;
821

            
822
    #[test]
823
    fn week() {
824
        let now = SystemTime::get();
825
        let one_day = Duration::new(86400, 0);
826

            
827
        assert_eq!(no_more_than_a_week_from(now, None), now + one_day * 7);
828
        assert_eq!(
829
            no_more_than_a_week_from(now, Some(now + one_day)),
830
            now + one_day
831
        );
832
        assert_eq!(
833
            no_more_than_a_week_from(now, Some(now - one_day)),
834
            now - one_day
835
        );
836
        assert_eq!(
837
            no_more_than_a_week_from(now, Some(now + 30 * one_day)),
838
            now + one_day * 7
839
        );
840
    }
841

            
842
    /// A fake implementation of DirState that just wants a fixed set
843
    /// of microdescriptors.  It doesn't care if it gets them: it just
844
    /// wants to be told that the IDs exist.
845
    #[derive(Debug, Clone)]
846
    struct DemoState {
847
        second_time_around: bool,
848
        got_items: HashMap<MdDigest, bool>,
849
    }
850

            
851
    // Constants from Lou Reed
852
    const H1: MdDigest = *b"satellite's gone up to the skies";
853
    const H2: MdDigest = *b"things like that drive me out of";
854
    const H3: MdDigest = *b"my mind i watched it for a littl";
855
    const H4: MdDigest = *b"while i like to watch things on ";
856
    const H5: MdDigest = *b"TV Satellite of love Satellite--";
857

            
858
    impl DemoState {
859
        fn new1() -> Self {
860
            DemoState {
861
                second_time_around: false,
862
                got_items: vec![(H1, false), (H2, false)].into_iter().collect(),
863
            }
864
        }
865
        fn new2() -> Self {
866
            DemoState {
867
                second_time_around: true,
868
                got_items: vec![(H3, false), (H4, false), (H5, false)]
869
                    .into_iter()
870
                    .collect(),
871
            }
872
        }
873
        fn n_ready(&self) -> usize {
874
            self.got_items.values().filter(|x| **x).count()
875
        }
876
    }
877

            
878
    impl DirState for DemoState {
879
        fn describe(&self) -> String {
880
            format!("{:?}", self)
881
        }
882
        fn bootstrap_progress(&self) -> crate::event::DirProgress {
883
            crate::event::DirProgress::default()
884
        }
885
        fn is_ready(&self, ready: Readiness) -> bool {
886
            match (ready, self.second_time_around) {
887
                (_, false) => false,
888
                (Readiness::Complete, true) => self.n_ready() == self.got_items.len(),
889
                (Readiness::Usable, true) => self.n_ready() >= self.got_items.len() - 1,
890
            }
891
        }
892
        fn can_advance(&self) -> bool {
893
            if self.second_time_around {
894
                false
895
            } else {
896
                self.n_ready() == self.got_items.len()
897
            }
898
        }
899
        fn missing_docs(&self) -> Vec<DocId> {
900
            self.got_items
901
                .iter()
902
                .filter_map(|(id, have)| {
903
                    if *have {
904
                        None
905
                    } else {
906
                        Some(DocId::Microdesc(*id))
907
                    }
908
                })
909
                .collect()
910
        }
911
        fn add_from_cache(
912
            &mut self,
913
            docs: HashMap<DocId, DocumentText>,
914
            changed: &mut bool,
915
        ) -> Result<()> {
916
            for id in docs.keys() {
917
                if let DocId::Microdesc(id) = id {
918
                    if self.got_items.get(id) == Some(&false) {
919
                        self.got_items.insert(*id, true);
920
                        *changed = true;
921
                    }
922
                }
923
            }
924
            Ok(())
925
        }
926
        fn add_from_download(
927
            &mut self,
928
            text: &str,
929
            _request: &ClientRequest,
930
            _source: DocSource,
931
            _storage: Option<&Mutex<DynStore>>,
932
            changed: &mut bool,
933
        ) -> Result<()> {
934
            for token in text.split_ascii_whitespace() {
935
                if let Ok(v) = hex::decode(token) {
936
                    if let Ok(id) = v.try_into() {
937
                        if self.got_items.get(&id) == Some(&false) {
938
                            self.got_items.insert(id, true);
939
                            *changed = true;
940
                        }
941
                    }
942
                }
943
            }
944
            Ok(())
945
        }
946
        fn dl_config(&self) -> DownloadSchedule {
947
            DownloadSchedule::default()
948
        }
949
        fn advance(self: Box<Self>) -> Box<dyn DirState> {
950
            if self.can_advance() {
951
                Box::new(Self::new2())
952
            } else {
953
                self
954
            }
955
        }
956
        fn reset_time(&self) -> Option<SystemTime> {
957
            None
958
        }
959
        fn reset(self: Box<Self>) -> Box<dyn DirState> {
960
            Box::new(Self::new1())
961
        }
962
    }
963

            
964
    #[test]
965
    fn all_in_cache() {
966
        // Let's try bootstrapping when everything is in the cache.
967
        tor_rtcompat::test_with_one_runtime!(|rt| async {
968
            let now = rt.wallclock();
969
            let (_tempdir, mgr) = new_mgr(rt.clone());
970
            let (mut schedule, _handle) = TaskSchedule::new(rt);
971

            
972
            {
973
                let mut store = mgr.store_if_rw().unwrap().lock().unwrap();
974
                for h in [H1, H2, H3, H4, H5] {
975
                    store.store_microdescs(&[("ignore", &h)], now).unwrap();
976
                }
977
            }
978
            let mgr = Arc::new(mgr);
979
            let attempt_id = AttemptId::next();
980

            
981
            // Try just a load.
982
            let state = Box::new(DemoState::new1());
983
            let result = super::load(&mgr, state, attempt_id).unwrap();
984
            assert!(result.is_ready(Readiness::Complete));
985

            
986
            // Try a bootstrap that could (but won't!) download.
987
            let mut state: Box<dyn DirState> = Box::new(DemoState::new1());
988

            
989
            let mut tx_usable = None;
990
            super::download(
991
                Arc::downgrade(&mgr),
992
                &mut state,
993
                &mut schedule,
994
                attempt_id,
995
                &mut tx_usable,
996
            )
997
            .await
998
            .unwrap();
999
            assert!(state.is_ready(Readiness::Complete));
        });
    }
    #[test]
    fn partly_in_cache() {
        // Let's try bootstrapping with all of phase1 and part of
        // phase 2 in cache.
        tor_rtcompat::test_with_one_runtime!(|rt| async {
            let now = rt.wallclock();
            let (_tempdir, mgr) = new_mgr(rt.clone());
            let (mut schedule, _handle) = TaskSchedule::new(rt);
            {
                let mut store = mgr.store_if_rw().unwrap().lock().unwrap();
                for h in [H1, H2, H3] {
                    store.store_microdescs(&[("ignore", &h)], now).unwrap();
                }
            }
            {
                let mut resp = CANNED_RESPONSE.lock().unwrap();
                // H4 and H5.
                *resp = vec![
                    "7768696c652069206c696b6520746f207761746368207468696e6773206f6e20
                     545620536174656c6c697465206f66206c6f766520536174656c6c6974652d2d"
                        .to_owned(),
                ];
            }
            let mgr = Arc::new(mgr);
            let mut tx_usable = None;
            let attempt_id = AttemptId::next();
            let mut state: Box<dyn DirState> = Box::new(DemoState::new1());
            super::download(
                Arc::downgrade(&mgr),
                &mut state,
                &mut schedule,
                attempt_id,
                &mut tx_usable,
            )
            .await
            .unwrap();
            assert!(state.is_ready(Readiness::Complete));
        });
    }
}