1
//! `BridgeDescMgr` - downloads and caches bridges' router descriptors
2

            
3
use std::borrow::Cow;
4
use std::cmp::Ordering;
5
use std::collections::{BinaryHeap, HashMap, HashSet, VecDeque};
6
use std::fmt::{self, Debug, Display};
7
use std::num::NonZeroU8;
8
use std::panic::AssertUnwindSafe;
9
use std::sync::{Arc, Mutex, MutexGuard, Weak};
10

            
11
use async_trait::async_trait;
12
use derive_more::{Deref, DerefMut};
13
use educe::Educe;
14
use futures::FutureExt;
15
use futures::future;
16
use futures::select;
17
use futures::stream::{BoxStream, StreamExt};
18
use futures::task::SpawnError;
19
use saturating_time::SaturatingTime as _;
20
use tor_netdoc::parse2::ParseInput;
21
use tracing::{debug, info, trace};
22

            
23
use safelog::sensitive;
24
use tor_basic_utils::retry::RetryDelay;
25
use tor_checkable::TimeBound;
26
use tor_circmgr::CircMgr;
27
use tor_error::{AbsRetryTime, HasRetryTime, RetryTime, debug_report};
28
use tor_error::{ErrorKind, HasKind, error_report, internal};
29
use tor_guardmgr::bridge::{BridgeConfig, BridgeDesc};
30
use tor_guardmgr::bridge::{BridgeDescError, BridgeDescEvent, BridgeDescList, BridgeDescProvider};
31
use tor_netdoc::{doc::routerdesc::RouterDescUnverified, parse2};
32
use tor_rtcompat::{Runtime, SpawnExt as _};
33
use web_time_compat::{Duration, Instant, SystemTime};
34

            
35
use crate::event::FlagPublisher;
36
use crate::storage::CachedBridgeDescriptor;
37
use crate::{DirMgrStore, DynStore};
38

            
39
#[cfg(test)]
40
mod bdtest;
41

            
42
/// The key we use in all our data structures
43
///
44
/// This type saves typing and would make it easier to change the bridge descriptor manager
45
/// to take and handle another way of identifying the bridges it is working with.
46
type BridgeKey = BridgeConfig;
47

            
48
/// Active vs dormant state, as far as the bridge descriptor manager is concerned
49
///
50
/// This is usually derived in higher layers from `arti_client::DormantMode`,
51
/// whether `TorClient::bootstrap()` has been called, etc.
52
#[non_exhaustive]
53
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
54
// TODO: These proliferating `Dormancy` enums should be centralized and unified with `TaskHandle`
55
//     https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/845#note_2853190
56
pub enum Dormancy {
57
    /// Dormant (inactive)
58
    ///
59
    /// Bridge descriptor downloads, or refreshes, will not be started.
60
    ///
61
    /// In-progress downloads will be stopped if possible,
62
    /// but they may continue until they complete (or fail).
63
    // TODO async task cancellation: actually cancel these in this case
64
    ///
65
    /// So a dormant BridgeDescMgr may still continue to
66
    /// change the return value from [`bridges()`](BridgeDescProvider::bridges)
67
    /// and continue to report [`BridgeDescEvent`]s.
68
    ///
69
    /// When the BridgeDescMgr is dormant,
70
    /// `bridges()` may return stale descriptors
71
    /// (that is, descriptors which ought to have been refetched and may no longer be valid),
72
    /// or stale errors
73
    /// (that is, errors which occurred some time ago,
74
    /// and which would normally have been retried by now).
75
    Dormant,
76

            
77
    /// Active
78
    ///
79
    /// Bridge descriptors will be downloaded as requested.
80
    ///
81
    /// When a bridge descriptor manager has been `Dormant`,
82
    /// it may continue to provide stale data (as described)
83
    /// for a while after it is made `Active`,
84
    /// until the required refreshes and retries have taken place (or failed).
85
    Active,
86
}
87

            
88
/// **Downloader and cache for bridges' router descriptors**
89
///
90
/// This is a handle which is cheap to clone and has internal mutability.
91
#[derive(Clone)]
92
pub struct BridgeDescMgr<R: Runtime, M = ()>
93
where
94
    M: Mockable<R>,
95
{
96
    /// The actual manager
97
    ///
98
    /// We have the `Arc` in here, rather than in our callers, because this
99
    /// makes the API nicer for them, and also because some of our tasks
100
    /// want a handle they can use to relock and modify the state.
101
    mgr: Arc<Manager<R, M>>,
102
}
103

            
104
/// Configuration for the `BridgeDescMgr`
105
///
106
/// Currently, the only way to make this is via its `Default` impl.
107
// TODO: there should be some way to override the defaults.  See #629 for considerations.
108
#[derive(Debug, Clone)]
109
pub struct BridgeDescDownloadConfig {
110
    /// How many bridge descriptor downloads to attempt in parallel?
111
    parallelism: NonZeroU8,
112

            
113
    /// Default/initial time to retry a failure to download a descriptor
114
    ///
115
    /// (This has the semantics of an initial delay for [`RetryDelay`],
116
    /// and is used unless there is more specific retry information for the particular failure.)
117
    retry: Duration,
118

            
119
    /// When a downloaded descriptor is going to expire, how soon in advance to refetch it?
120
    prefetch: Duration,
121

            
122
    /// Minimum interval between successive refetches of the descriptor for the same bridge
123
    ///
124
    /// This limits the download activity which can be caused by an errant bridge.
125
    ///
126
    /// If the descriptor's validity information is shorter than this, we will use
127
    /// it after it has expired (rather than treating the bridge as broken).
128
    min_refetch: Duration,
129

            
130
    /// Maximum interval between successive refetches of the descriptor for the same bridge
131
    ///
132
    /// This sets an upper bound on how old a descriptor we are willing to use.
133
    /// When this time expires, a refetch attempt will be started even if the
134
    /// descriptor is not going to expire soon.
135
    //
136
    // TODO: When this is configurable, we need to make sure we reject
137
    // configurations with max_refresh < min_refresh, or we may panic.
138
    max_refetch: Duration,
139
}
140

            
141
impl Default for BridgeDescDownloadConfig {
142
10
    fn default() -> Self {
143
10
        let secs = Duration::from_secs;
144
10
        BridgeDescDownloadConfig {
145
10
            parallelism: 4.try_into().expect("parallelism is zero"),
146
10
            retry: secs(30),
147
10
            prefetch: secs(1000),
148
10
            min_refetch: secs(3600),
149
10
            max_refetch: secs(3600 * 3), // matches C Tor behaviour
150
10
        }
151
10
    }
152
}
153

            
154
/// Mockable internal methods for within the `BridgeDescMgr`
155
///
156
/// Implemented for `()`, meaning "do not use mocks: use the real versions of everything".
157
///
158
/// This (`()`) is the default for the type parameter in
159
/// [`BridgeDescMgr`],
160
/// and it is the only publicly available implementation,
161
/// since this trait is sealed.
162
pub trait Mockable<R>: mockable::MockableAPI<R> {}
163
impl<R: Runtime> Mockable<R> for () {}
164

            
165
/// Private module which seals [`Mockable`]
166
/// by containing [`MockableAPI`](mockable::MockableAPI)
167
mod mockable {
168
    use super::*;
169

            
170
    /// Defines the actual mockable APIs
171
    ///
172
    /// Not nameable (and therefore not implementable)
173
    /// outside the `bridgedesc` module,
174
    #[async_trait]
175
    pub trait MockableAPI<R>: Clone + Send + Sync + 'static {
176
        /// Circuit manager
177
        type CircMgr: Send + Sync + 'static;
178

            
179
        /// Download this bridge's descriptor, and return it as a string
180
        ///
181
        /// Runs in a task.
182
        /// Called by `Manager::download_descriptor`, which handles parsing and validation.
183
        ///
184
        /// If `if_modified_since` is `Some`,
185
        /// should tolerate an HTTP 304 Not Modified and return `None` in that case.
186
        /// If `if_modified_since` is `None`, returning `Ok(None,)` is forbidden.
187
        async fn download(
188
            self,
189
            runtime: &R,
190
            circmgr: &Self::CircMgr,
191
            bridge: &BridgeConfig,
192
            if_modified_since: Option<SystemTime>,
193
        ) -> Result<Option<String>, Error>;
194
    }
195
}
196
#[async_trait]
197
impl<R: Runtime> mockable::MockableAPI<R> for () {
198
    type CircMgr = Arc<CircMgr<R>>;
199

            
200
    /// Actual code for downloading a descriptor document
201
    async fn download(
202
        self,
203
        runtime: &R,
204
        circmgr: &Self::CircMgr,
205
        bridge: &BridgeConfig,
206
        _if_modified_since: Option<SystemTime>,
207
    ) -> Result<Option<String>, Error> {
208
        // TODO actually support _if_modified_since
209
        let tunnel = circmgr.get_or_launch_dir_specific(bridge).await?;
210
        let mut stream = tunnel
211
            .begin_dir_stream()
212
            .await
213
            .map_err(Error::StreamFailed)?;
214
        let request = tor_dirclient::request::RoutersOwnDescRequest::new();
215
        let response = tor_dirclient::send_request(runtime, &request, &mut stream, None)
216
            .await
217
            .map_err(|dce| match dce {
218
                tor_dirclient::Error::RequestFailed(re) => Error::RequestFailed(re),
219
                _ => internal!(
220
                    "tor_dirclient::send_request gave non-RequestFailed {:?}",
221
                    dce
222
                )
223
                .into(),
224
            })?;
225
        let output = response.into_output_string()?;
226
        Ok(Some(output))
227
    }
228
}
229

            
230
/// The actual manager.
231
struct Manager<R: Runtime, M: Mockable<R>> {
232
    /// The mutable state
233
    state: Mutex<State>,
234

            
235
    /// Runtime, used for tasks and sleeping
236
    runtime: R,
237

            
238
    /// Circuit manager, used for creating circuits
239
    circmgr: M::CircMgr,
240

            
241
    /// Persistent state store
242
    store: Arc<Mutex<DynStore>>,
243

            
244
    /// Mock for testing, usually `()`
245
    mockable: M,
246
}
247

            
248
/// State: our downloaded descriptors (cache), and records of what we're doing
249
///
250
/// Various functions (both tasks and public entrypoints),
251
/// which generally start with a `Manager`,
252
/// lock the mutex and modify this.
253
///
254
/// Generally, the flow is:
255
///
256
///  * A public entrypoint, or task, obtains a [`StateGuard`].
257
///    It modifies the state to represent the callers' new requirements,
258
///    or things it has done, by updating the state,
259
///    preserving the invariants but disturbing the "liveness" (see below).
260
///
261
///  * [`StateGuard::drop`] calls [`State::process`].
262
///    This restores the liveness properties.
263
///
264
/// ### Possible states of a bridge:
265
///
266
/// A bridge can be in one of the following states,
267
/// represented by its presence in these particular data structures inside `State`:
268
///
269
///  * `running`/`queued`: newly added, no outcome yet.
270
///  * `current` + `running`/`queued`: we are fetching (or going to)
271
///  * `current = OK` + `refetch_schedule`: fetched OK, will refetch before expiry
272
///  * `current = Err` + `retry_schedule`: failed, will retry at some point
273
///
274
/// ### Invariants:
275
///
276
/// Can be disrupted in the middle of a principal function,
277
/// but should be restored on return.
278
///
279
/// * **Tracked**:
280
///   Each bridge appears at most once in
281
///   `running`, `queued`, `refetch_schedule` and `retry_schedule`.
282
///   We call such a bridge Tracked.
283
///
284
/// * **Current**
285
///   Every bridge in `current` is Tracked.
286
///   (But not every Tracked bridge is necessarily in `current`, yet.)
287
///
288
/// * **Schedules**
289
///   Every bridge in `refetch_schedule` or `retry_schedule` is also in `current`.
290
///
291
/// * **Input**:
292
///   Exactly each bridge that was passed to
293
///   the last call to [`set_bridges()`](BridgeDescMgr::set_bridges) is Tracked.
294
///   (If we encountered spawn failures, we treat this as trying to shut down,
295
///   so we cease attempts to get bridges, and discard the relevant state, violating this.)
296
///
297
/// * **Limit**:
298
///   `running` is capped at the effective parallelism: zero if we are dormant,
299
///   the configured parallelism otherwise.
300
///
301
/// ### Liveness properties:
302
///
303
/// These can be disrupted by any function which holds a [`StateGuard`].
304
/// Will be restored by [`process()`](State::process),
305
/// which is called when `StateGuard` is dropped.
306
///
307
/// Functions that take a `StateGuard` may disturb these invariants
308
/// and rely on someone else to restore them.
309
///
310
/// * **Running**:
311
///   If `queued` is nonempty, `running` is full.
312
///
313
/// * **Timeout**:
314
///   `earliest_timeout` is the earliest timeout in
315
///   either `retry_schedule` or `refetch_schedule`.
316
///   (Disturbances of this property which occur due to system time warps
317
///   are not necessarily detected and remedied in a timely way,
318
///   but will be remedied no later than after `max_refetch`.)
319
struct State {
320
    /// Our configuration
321
    config: Arc<BridgeDescDownloadConfig>,
322

            
323
    /// People who will be told when `current` changes.
324
    subscribers: FlagPublisher<BridgeDescEvent>,
325

            
326
    /// Our current idea of our output, which we give out handles onto.
327
    current: Arc<BridgeDescList>,
328

            
329
    /// Bridges whose descriptors we are currently downloading.
330
    running: HashMap<BridgeKey, RunningInfo>,
331

            
332
    /// Bridges which we want to download,
333
    /// but we're waiting for `running` to be less than `effective_parallelism()`.
334
    queued: VecDeque<QueuedEntry>,
335

            
336
    /// Are we dormant?
337
    dormancy: Dormancy,
338

            
339
    /// Bridges that we have a descriptor for,
340
    /// and when they should be refetched due to validity expiry.
341
    ///
342
    /// This is indexed by `SystemTime` because that helps avoids undesirable behaviors
343
    /// when the system clock changes.
344
    refetch_schedule: BinaryHeap<RefetchEntry<SystemTime, ()>>,
345

            
346
    /// Bridges that failed earlier, and when they should be retried.
347
    retry_schedule: BinaryHeap<RefetchEntry<Instant, RetryDelay>>,
348

            
349
    /// Earliest time from either `retry_schedule` or `refetch_schedule`
350
    ///
351
    /// `None` means "wait indefinitely".
352
    earliest_timeout: postage::watch::Sender<Option<Instant>>,
353
}
354

            
355
impl Debug for State {
356
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357
        /// Helper to format one bridge entry somewhere
358
        fn fmt_bridge(
359
            f: &mut fmt::Formatter,
360
            b: &BridgeConfig,
361
            info: &(dyn Display + '_),
362
        ) -> fmt::Result {
363
            let info = info.to_string(); // fmt::Formatter doesn't enforce precision, so do this
364
            writeln!(f, "    {:80.80} | {}", info, b)
365
        }
366

            
367
        /// Helper to format one of the schedules
368
        fn fmt_schedule<TT: Ord + Copy + Debug, RD>(
369
            f: &mut fmt::Formatter,
370
            summary: &str,
371
            name: &str,
372
            schedule: &BinaryHeap<RefetchEntry<TT, RD>>,
373
        ) -> fmt::Result {
374
            writeln!(f, "  {}:", name)?;
375
            for b in schedule {
376
                fmt_bridge(f, &b.bridge, &format_args!("{} {:?}", summary, b.when))?;
377
            }
378
            Ok(())
379
        }
380

            
381
        // We are going to have to go multi-line because of the bridge lines,
382
        // so do completely bespoke formatting rather than `std::fmt::DebugStruct`
383
        // or a derive.
384
        writeln!(f, "State {{")?;
385
        // We'd like to print earliest_timeout but watch::Sender::borrow takes &mut
386
        writeln!(f, "  earliest_timeout: ???, ..,")?;
387
        writeln!(f, "  current:")?;
388
        for (b, v) in &*self.current {
389
            fmt_bridge(
390
                f,
391
                b,
392
                &match v {
393
                    Err(e) => Cow::from(format!("C Err {}", e)),
394
                    Ok(_) => "C Ok".into(),
395
                },
396
            )?;
397
        }
398
        writeln!(f, "  running:")?;
399
        for b in self.running.keys() {
400
            fmt_bridge(f, b, &"R")?;
401
        }
402
        writeln!(f, "  queued:")?;
403
        for qe in &self.queued {
404
            fmt_bridge(f, &qe.bridge, &"Q")?;
405
        }
406
        fmt_schedule(f, "FS", "refetch_schedule", &self.refetch_schedule)?;
407
        fmt_schedule(f, "TS", "retry_schedule", &self.retry_schedule)?;
408
        write!(f, "}}")?;
409

            
410
        Ok(())
411
    }
412
}
413

            
414
/// Value of the entry in `running`
415
#[derive(Debug)]
416
struct RunningInfo {
417
    /// For cancelling downloads no longer wanted
418
    join: JoinHandle,
419

            
420
    /// If this previously failed, the persistent retry delay.
421
    retry_delay: Option<RetryDelay>,
422
}
423

            
424
/// Entry in `queued`
425
#[derive(Debug)]
426
struct QueuedEntry {
427
    /// The bridge to fetch
428
    bridge: BridgeKey,
429

            
430
    /// If this previously failed, the persistent retry delay.
431
    retry_delay: Option<RetryDelay>,
432
}
433

            
434
/// Entry in one of the `*_schedule`s
435
///
436
/// Implements `Ord` and `Eq` but *only looking at the refetch time*.
437
/// So don't deduplicate by `[Partial]Eq`, or use as a key in a map.
438
#[derive(Debug)]
439
struct RefetchEntry<TT, RD> {
440
    /// When should we requeued this bridge for fetching
441
    ///
442
    /// Either [`Instant`] (in `retry_schedule`) or [`SystemTime`] (in `refetch_schedule`).
443
    when: TT,
444

            
445
    /// The bridge to refetch
446
    bridge: BridgeKey,
447

            
448
    /// Retry delay
449
    ///
450
    /// `RetryDelay` if we previously failed (ie, if this is a retry entry);
451
    /// otherwise `()`.
452
    retry_delay: RD,
453
}
454

            
455
impl<TT: Ord, RD> Ord for RefetchEntry<TT, RD> {
456
60
    fn cmp(&self, other: &Self) -> Ordering {
457
60
        self.when.cmp(&other.when).reverse()
458
        // We don't care about the ordering of BridgeConfig or retry_delay.
459
        // Different BridgeConfig with the same fetch time will be fetched in "some order".
460
60
    }
461
}
462

            
463
impl<TT: Ord, RD> PartialOrd for RefetchEntry<TT, RD> {
464
60
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
465
60
        Some(self.cmp(other))
466
60
    }
467
}
468

            
469
impl<TT: Ord, RD> PartialEq for RefetchEntry<TT, RD> {
470
    fn eq(&self, other: &Self) -> bool {
471
        self.cmp(other) == Ordering::Equal
472
    }
473
}
474

            
475
impl<TT: Ord, RD> Eq for RefetchEntry<TT, RD> {}
476

            
477
/// Dummy task join handle
478
///
479
/// We would like to be able to cancel now-redundant downloads
480
/// using something like `tokio::task::JoinHandle::abort()`.
481
/// tor-rtcompat doesn't support that so we stub it for now.
482
///
483
/// Providing this stub means the place where the cancellation needs to take place
484
/// already has the appropriate call to our [`JoinHandle::abort`].
485
#[derive(Debug)]
486
struct JoinHandle;
487

            
488
impl JoinHandle {
489
    /// Would abort this async task, if we could do that.
490
    fn abort(&self) {}
491
}
492

            
493
impl<R: Runtime> BridgeDescMgr<R> {
494
    /// Create a new `BridgeDescMgr`
495
    ///
496
    /// This is the public constructor.
497
    //
498
    // TODO: That this constructor requires a DirMgr is rather odd.
499
    // In principle there is little reason why you need a DirMgr to make a BridgeDescMgr.
500
    // However, BridgeDescMgr needs a Store, and currently that is a private trait, and the
501
    // implementation is constructible only from the dirmgr's config.  This should probably be
502
    // tidied up somehow, at some point, perhaps by exposing `Store` and its configuration.
503
    pub fn new(
504
        config: &BridgeDescDownloadConfig,
505
        runtime: R,
506
        store: DirMgrStore<R>,
507
        circmgr: Arc<tor_circmgr::CircMgr<R>>,
508
        dormancy: Dormancy,
509
    ) -> Result<Self, StartupError> {
510
        Self::new_internal(runtime, circmgr, store.store, config, dormancy, ())
511
    }
512
}
513

            
514
/// If download was successful, what we obtained
515
///
516
/// Generated by `process_document`, from a downloaded (or cached) textual descriptor.
517
#[derive(Debug)]
518
struct Downloaded {
519
    /// The bridge descriptor, fully parsed and verified
520
    desc: BridgeDesc,
521

            
522
    /// When we should start a refresh for this descriptor
523
    ///
524
    /// This is derived from the expiry time,
525
    /// and clamped according to limits in the configuration).
526
    refetch: SystemTime,
527
}
528

            
529
impl<R: Runtime, M: Mockable<R>> BridgeDescMgr<R, M> {
530
    /// Actual constructor, which takes a mockable
531
    //
532
    // Allow passing `runtime` by value, which is usual API for this kind of setup function.
533
    #[allow(clippy::needless_pass_by_value)]
534
8
    fn new_internal(
535
8
        runtime: R,
536
8
        circmgr: M::CircMgr,
537
8
        store: Arc<Mutex<DynStore>>,
538
8
        config: &BridgeDescDownloadConfig,
539
8
        dormancy: Dormancy,
540
8
        mockable: M,
541
8
    ) -> Result<Self, StartupError> {
542
        /// Convenience alias
543
48
        fn default<T: Default>() -> T {
544
48
            Default::default()
545
48
        }
546

            
547
8
        let config = config.clone().into();
548
8
        let (earliest_timeout, timeout_update) = postage::watch::channel();
549

            
550
8
        let state = Mutex::new(State {
551
8
            config,
552
8
            subscribers: default(),
553
8
            current: default(),
554
8
            running: default(),
555
8
            queued: default(),
556
8
            dormancy,
557
8
            retry_schedule: default(),
558
8
            refetch_schedule: default(),
559
8
            earliest_timeout,
560
8
        });
561
8
        let mgr = Arc::new(Manager {
562
8
            state,
563
8
            runtime: runtime.clone(),
564
8
            circmgr,
565
8
            store,
566
8
            mockable,
567
8
        });
568

            
569
8
        runtime
570
8
            .spawn(timeout_task(
571
8
                runtime.clone(),
572
8
                Arc::downgrade(&mgr),
573
8
                timeout_update,
574
8
            ))
575
            .map_err(|cause| StartupError::Spawn {
576
                spawning: "timeout task",
577
                cause: cause.into(),
578
            })?;
579

            
580
8
        Ok(BridgeDescMgr { mgr })
581
8
    }
582

            
583
    /// Consistency check convenience wrapper
584
    #[cfg(test)]
585
46
    fn check_consistency<'i, I>(&self, input_bridges: Option<I>)
586
46
    where
587
46
        I: IntoIterator<Item = &'i BridgeKey>,
588
    {
589
46
        self.mgr
590
46
            .lock_only()
591
46
            .check_consistency(&self.mgr.runtime, input_bridges);
592
46
    }
593

            
594
    /// Set whether this `BridgeDescMgr` is active
595
    // TODO this should instead be handled by a central mechanism; see TODO on Dormancy
596
4
    pub fn set_dormancy(&self, dormancy: Dormancy) {
597
4
        self.mgr.lock_then_process().dormancy = dormancy;
598
4
    }
599
}
600

            
601
impl<R: Runtime, M: Mockable<R>> BridgeDescProvider for BridgeDescMgr<R, M> {
602
58
    fn bridges(&self) -> Arc<BridgeDescList> {
603
58
        self.mgr.lock_only().current.clone()
604
58
    }
605

            
606
6
    fn events(&self) -> BoxStream<'static, BridgeDescEvent> {
607
6
        let stream = self.mgr.lock_only().subscribers.subscribe();
608
6
        Box::pin(stream) as _
609
6
    }
610

            
611
22
    fn set_bridges(&self, new_bridges: &[BridgeConfig]) {
612
        /// Helper: Called for each bridge that is currently Tracked.
613
        ///
614
        /// Checks if `new_bridges` has `bridge`.  If so, removes it from `new_bridges`,
615
        /// and returns `true`, indicating that this bridge should be kept.
616
        ///
617
        /// If not, returns `false`, indicating that this bridge should be removed,
618
        /// and logs a message.
619
46
        fn note_found_keep_p(
620
46
            new_bridges: &mut HashSet<BridgeKey>,
621
46
            bridge: &BridgeKey,
622
46
            was_state: &str,
623
46
        ) -> bool {
624
46
            let keep = new_bridges.remove(bridge);
625
46
            if !keep {
626
8
                debug!(r#"forgetting bridge ({}) "{}""#, was_state, bridge);
627
38
            }
628
46
            keep
629
46
        }
630

            
631
        /// Helper: filters `*_schedule` so that it contains only things in `new_bridges`,
632
        /// removing them as we go.
633
44
        fn filter_schedule<TT: Ord + Copy, RD>(
634
44
            new_bridges: &mut HashSet<BridgeKey>,
635
44
            schedule: &mut BinaryHeap<RefetchEntry<TT, RD>>,
636
44
            was_state: &str,
637
44
        ) {
638
46
            schedule.retain(|b| note_found_keep_p(new_bridges, &b.bridge, was_state));
639
44
        }
640

            
641
22
        let mut state = self.mgr.lock_then_process();
642
22
        let state = &mut **state;
643

            
644
        // We go through our own data structures, comparing them with `new_bridges`.
645
        // Entries in our own structures that aren't in `new_bridges` are removed.
646
        // Entries that *are* are removed from `new_bridges`.
647
        // Eventually `new_bridges` is just the list of new bridges to *add*.
648
22
        let mut new_bridges: HashSet<_> = new_bridges.iter().cloned().collect();
649

            
650
        // Is there anything in `current` that ought to be deleted?
651
37
        if state.current.keys().any(|b| !new_bridges.contains(b)) {
652
            // Found a bridge In `current` but not `new`
653
            // We need to remove it (and any others like it) from `current`.
654
            //
655
            // Disturbs the invariant *Schedules*:
656
            // After this maybe the schedules have entries they shouldn't.
657
8
            let current: BridgeDescList = state
658
8
                .current
659
8
                .iter()
660
30
                .filter(|(b, _)| new_bridges.contains(&**b))
661
22
                .map(|(b, v)| (b.clone(), v.clone()))
662
                .collect();
663
8
            state.set_current_and_notify(current);
664
14
        } else {
665
14
            // Nothing is being removed, so we can keep `current`.
666
14
        }
667
        // Bridges being newly requested will be added to `current`
668
        // later, after they have been fetched.
669

            
670
        // Is there anything in running we should abort?
671
22
        state.running.retain(|b, ri| {
672
            let keep = note_found_keep_p(&mut new_bridges, b, "was downloading");
673
            if !keep {
674
                ri.join.abort();
675
            }
676
            keep
677
        });
678

            
679
        // Is there anything in queued we should forget about?
680
22
        state
681
22
            .queued
682
            .retain(|qe| note_found_keep_p(&mut new_bridges, &qe.bridge, "was queued"));
683

            
684
        // Restore the invariant *Schedules*, that the schedules contain only things in current,
685
        // by removing the same things from the schedules that we earlier removed from current.
686
22
        filter_schedule(
687
22
            &mut new_bridges,
688
22
            &mut state.retry_schedule,
689
22
            "previously failed",
690
22
        );
691
22
        filter_schedule(
692
22
            &mut new_bridges,
693
22
            &mut state.refetch_schedule,
694
22
            "previously downloaded",
695
22
        );
696

            
697
        // OK now we have the list of bridges to add (if any).
698
22
        state.queued.extend(new_bridges.into_iter().map(|bridge| {
699
22
            debug!(r#" added bridge, queueing for download "{}""#, &bridge);
700
22
            QueuedEntry {
701
22
                bridge,
702
22
                retry_delay: None,
703
22
            }
704
22
        }));
705

            
706
        // `StateGuard`, from `lock_then_process`, gets dropped here, and runs `process`,
707
        // to make further progress and restore the liveness properties.
708
22
    }
709
}
710

            
711
impl<R: Runtime, M: Mockable<R>> Manager<R, M> {
712
    /// Obtain a lock on state, for functions that want to disrupt liveness properties
713
    ///
714
    /// When `StateGuard` is dropped, the liveness properties will be restored
715
    /// by making whatever progress is required.
716
    ///
717
    /// See [`State`].
718
83
    fn lock_then_process<'s>(self: &'s Arc<Self>) -> StateGuard<'s, R, M> {
719
83
        StateGuard {
720
83
            state: self.lock_only(),
721
83
            mgr: self,
722
83
        }
723
83
    }
724

            
725
    /// Obtains the lock on state.
726
    ///
727
    /// Caller ought not to modify state
728
    /// so as to invalidate invariants or liveness properties.
729
    /// Callers which are part of the algorithms in this crate
730
    /// ought to consider [`lock_then_process`](Manager::lock_then_process) instead.
731
203
    fn lock_only(&self) -> MutexGuard<State> {
732
203
        self.state.lock().expect("bridge desc manager poisoned")
733
203
    }
734
}
735

            
736
/// Writeable reference to [`State`], entitling the holder to disrupt liveness properties.
737
///
738
/// The holder must still maintain the invariants.
739
///
740
/// Obtained from [`Manager::lock_then_process`].  See [`State`].
741
#[derive(Educe, Deref, DerefMut)]
742
#[educe(Debug)]
743
struct StateGuard<'s, R: Runtime, M: Mockable<R>> {
744
    /// Reference to the mutable state
745
    #[deref]
746
    #[deref_mut]
747
    state: MutexGuard<'s, State>,
748

            
749
    /// Reference to the outer container
750
    ///
751
    /// Allows the holder to obtain a `'static` (owned) handle `Arc<Manager>`,
752
    /// for use by spawned tasks.
753
    #[educe(Debug(ignore))]
754
    mgr: &'s Arc<Manager<R, M>>,
755
}
756

            
757
impl<R: Runtime, M: Mockable<R>> Drop for StateGuard<'_, R, M> {
758
83
    fn drop(&mut self) {
759
83
        self.state.process(self.mgr);
760
83
    }
761
}
762

            
763
impl State {
764
    /// Ensure progress is made, by restoring all the liveness invariants
765
    ///
766
    /// This includes launching circuits as needed.
767
83
    fn process<R: Runtime, M: Mockable<R>>(&mut self, mgr: &Arc<Manager<R, M>>) {
768
        // Restore liveness property *Running*
769
83
        self.consider_launching(mgr);
770

            
771
83
        let now_wall = mgr.runtime.wallclock();
772

            
773
        // Mitigate clock warping
774
        //
775
        // If the earliest `SystemTime` is more than `max_refetch` away,
776
        // the clock must have warped.  If that happens we clamp
777
        // them all to `max_refetch`.
778
        //
779
        // (This is not perfect but will mitigate the worst effects by ensuring
780
        // that we do *something* at least every `max_refetch`, in the worst case,
781
        // other than just getting completely stuck.)
782
83
        let max_refetch_wall = now_wall
783
83
            .checked_add(self.config.max_refetch)
784
83
            .expect("Cannot add refetch maximum to wallclock time.  Is your clock set in the distant future?");
785
83
        if self
786
83
            .refetch_schedule
787
83
            .peek()
788
53
            .map(|re| re.when > max_refetch_wall)
789
83
            == Some(true)
790
        {
791
            info!("bridge descriptor manager: clock warped, clamping refetch times");
792
            self.refetch_schedule = self
793
                .refetch_schedule
794
                .drain()
795
                .map(|mut re| {
796
                    re.when = max_refetch_wall;
797
                    re
798
                })
799
                .collect();
800
83
        }
801

            
802
        // Restore liveness property *Timeout**
803
        // postage::watch will tell up the timeout task about the new wake-up time.
804
        let new_earliest_timeout = [
805
            // First retry.  These are std Instant.
806
83
            self.retry_schedule.peek().map(|re| re.when),
807
            // First refetch.  These are SystemTime, so we must convert them.
808
83
            self.refetch_schedule.peek().map(|re| {
809
                // If duration_since gives Err, that means when is before now,
810
                // ie we should not be waiting: the wait duration should be 0.
811
53
                let wait = re.when.duration_since(now_wall).unwrap_or_default();
812

            
813
53
                mgr.runtime.now().saturating_add(wait)
814
53
            }),
815
        ]
816
        .into_iter()
817
        .flatten()
818
        .min();
819
83
        *self.earliest_timeout.borrow_mut() = new_earliest_timeout;
820
83
    }
821

            
822
    /// Launch download attempts if we can
823
    ///
824
    /// Specifically: if we have things in `queued`, and `running` is shorter than
825
    /// `effective_parallelism()`, we launch task(s) to attempt download(s).
826
    ///
827
    /// Restores liveness invariant *Running*.
828
    ///
829
    /// Idempotent.  Forms part of `process`.
830
    #[allow(clippy::blocks_in_conditions)]
831
83
    fn consider_launching<R: Runtime, M: Mockable<R>>(&mut self, mgr: &Arc<Manager<R, M>>) {
832
83
        let mut to_remove = vec![];
833

            
834
129
        while self.running.len() < self.effective_parallelism() {
835
            let QueuedEntry {
836
                bridge,
837
                retry_delay,
838
105
            } = match self.queued.pop_front() {
839
46
                Some(qe) => qe,
840
59
                None => break,
841
            };
842
46
            match mgr
843
46
                .runtime
844
                .spawn({
845
46
                    let config = self.config.clone();
846
46
                    let bridge = bridge.clone();
847
46
                    let inner = mgr.clone();
848
46
                    let mockable = inner.mockable.clone();
849

            
850
                    // The task which actually downloads a descriptor.
851
46
                    async move {
852
                        let got =
853
46
                            AssertUnwindSafe(inner.download_descriptor(mockable, &bridge, &config))
854
46
                                .catch_unwind()
855
46
                                .await
856
                                .unwrap_or_else(|_| {
857
                                    Err(internal!("download descriptor task panicked!").into())
858
                                });
859
46
                        match &got {
860
14
                            Ok(_) => debug!(r#"download succeeded for "{}""#, bridge),
861
                            Err(err) => {
862
32
                                debug_report!(err, r#"download failed for "{}"#, bridge);
863
                            }
864
                        };
865
46
                        let mut state = inner.lock_then_process();
866
46
                        state.record_download_outcome(bridge, got);
867
                        // `StateGuard`, from `lock_then_process`, gets dropped here, and runs `process`,
868
                        // to make further progress and restore the liveness properties.
869
46
                    }
870
                })
871
                .map(|()| JoinHandle)
872
            {
873
                Ok(join) => {
874
46
                    self.running
875
46
                        .insert(bridge, RunningInfo { join, retry_delay });
876
                }
877
                Err(_) => {
878
                    // Spawn failed.
879
                    //
880
                    // We are going to forget about this bridge.
881
                    // And we're going to do that without notifying anyone.
882
                    // We *do* want to remove it from `current` because simply forgetting
883
                    // about a refetch could leave expired data there.
884
                    // We amortize this, so we don't do a lot of O(n^2) work on shutdown.
885
                    to_remove.push(bridge);
886
                }
887
            }
888
        }
889

            
890
83
        if !to_remove.is_empty() {
891
            self.modify_current(|current| {
892
                for bridge in to_remove {
893
                    current.remove(&bridge);
894
                }
895
            });
896
83
        }
897
83
    }
898

            
899
    /// Modify `current` and notify subscribers
900
    ///
901
    /// Helper function which modifies only `current`, not any of the rest of the state.
902
    /// it is the caller's responsibility to ensure that the invariants are upheld.
903
    ///
904
    /// The implementation actually involves cloning `current`,
905
    /// so it is best to amortize calls to this function.
906
46
    fn modify_current<T, F: FnOnce(&mut BridgeDescList) -> T>(&mut self, f: F) -> T {
907
46
        let mut current = (*self.current).clone();
908
46
        let r = f(&mut current);
909
46
        self.set_current_and_notify(current);
910
46
        r
911
46
    }
912

            
913
    /// Set `current` to a value and notify
914
    ///
915
    /// Helper function which modifies only `current`, not any of the rest of the state.
916
    /// it is the caller's responsibility to ensure that the invariants are upheld.
917
54
    fn set_current_and_notify<BDL: Into<Arc<BridgeDescList>>>(&mut self, new: BDL) {
918
54
        self.current = new.into();
919
54
        self.subscribers.publish(BridgeDescEvent::SomethingChanged);
920
54
    }
921

            
922
    /// Obtain the currently-desired level of parallelism
923
    ///
924
    /// Helper function.  The return value depends the mutable state and also the `config`.
925
    ///
926
    /// This is how we implement dormancy.
927
175
    fn effective_parallelism(&self) -> usize {
928
175
        match self.dormancy {
929
171
            Dormancy::Active => usize::from(u8::from(self.config.parallelism)),
930
4
            Dormancy::Dormant => 0,
931
        }
932
175
    }
933
}
934

            
935
impl<R: Runtime, M: Mockable<R>> StateGuard<'_, R, M> {
936
    /// Record a download outcome.
937
    ///
938
    /// Final act of the descriptor download task.
939
    /// `got` is from [`download_descriptor`](Manager::download_descriptor).
940
46
    fn record_download_outcome(&mut self, bridge: BridgeKey, got: Result<Downloaded, Error>) {
941
46
        let RunningInfo { retry_delay, .. } = match self.running.remove(&bridge) {
942
46
            Some(ri) => ri,
943
            None => {
944
                debug!("bridge descriptor download completed for no-longer-configured bridge");
945
                return;
946
            }
947
        };
948

            
949
46
        let insert = match got {
950
            Ok(Downloaded { desc, refetch }) => {
951
                // Successful download.  Schedule the refetch, and we'll insert Ok.
952

            
953
14
                self.refetch_schedule.push(RefetchEntry {
954
14
                    when: refetch,
955
14
                    bridge: bridge.clone(),
956
14
                    retry_delay: (),
957
14
                });
958

            
959
14
                Ok(desc)
960
            }
961
            Err(err) => {
962
                // Failed.  Schedule the retry, and we'll insert Err.
963

            
964
                let mut retry_delay =
965
32
                    retry_delay.unwrap_or_else(|| RetryDelay::from_duration(self.config.retry));
966

            
967
32
                let retry = err.retry_time();
968
                // We retry at least as early as
969
32
                let now = self.mgr.runtime.now();
970
32
                let retry = retry.absolute(now, || retry_delay.next_delay(&mut rand::rng()));
971
                // Retry at least as early as max_refetch.  That way if a bridge is
972
                // misconfigured we will see it be fixed eventually.
973
                let retry = {
974
32
                    let earliest = now;
975
32
                    let latest = || now.saturating_add(self.config.max_refetch);
976
32
                    match retry {
977
                        AbsRetryTime::Immediate => earliest,
978
                        AbsRetryTime::Never => latest(),
979
32
                        AbsRetryTime::At(i) => i.clamp(earliest, latest()),
980
                    }
981
                };
982
32
                self.retry_schedule.push(RefetchEntry {
983
32
                    when: retry,
984
32
                    bridge: bridge.clone(),
985
32
                    retry_delay,
986
32
                });
987

            
988
32
                Err(Box::new(err) as _)
989
            }
990
        };
991

            
992
46
        self.modify_current(|current| current.insert(bridge, insert));
993
46
    }
994
}
995

            
996
impl<R: Runtime, M: Mockable<R>> Manager<R, M> {
997
    /// Downloads a descriptor.
998
    ///
999
    /// The core of the descriptor download task
    /// launched by `State::consider_launching`.
    ///
    /// Uses Mockable::download to actually get the document.
    /// So most of this function is parsing and checking.
    ///
    /// The returned value is precisely the `got` input to
    /// [`record_download_outcome`](StateGuard::record_download_outcome).
46
    async fn download_descriptor(
46
        &self,
46
        mockable: M,
46
        bridge: &BridgeConfig,
46
        config: &BridgeDescDownloadConfig,
46
    ) -> Result<Downloaded, Error> {
        // convenience alias, capturing the usual parameters from our variables.
18
        let process_document = |text| process_document(&self.runtime, config, text);
58
        let store = || {
58
            self.store
58
                .lock()
                .map_err(|_| internal!("bridge descriptor store poisoned"))
58
        };
46
        let cache_entry: Option<CachedBridgeDescriptor> = (|| store()?.lookup_bridgedesc(bridge))()
            .unwrap_or_else(|err| {
                error_report!(
                    err,
                    r#"bridge descriptor cache lookup failed, for "{}""#,
                    sensitive(bridge),
                );
                None
            });
46
        let now = self.runtime.wallclock();
46
        let cached_good: Option<Downloaded> = if let Some(cached) = &cache_entry {
8
            if cached.fetched > now {
                // was fetched "in the future"
                None
            } else {
                // let's see if it's any use
8
                match process_document(&cached.document) {
                    Err(err) => {
                        // We had a doc in the cache but our attempt to use it failed
                        // We wouldn't have written a bad cache entry.
                        // So one of the following must be true:
                        //  * We were buggy or are stricter now or something
                        //  * The document was valid but its validity time has expired
                        // In any case we can't reuse it.
                        // (This happens in normal operation, when a document expires.)
2
                        trace!(r#"cached document for "{}" invalid: {}"#, &bridge, err);
2
                        None
                    }
                    Ok(got) => {
                        // The cached document looks valid.
                        // But how long ago did we fetch it?
                        // We need to enforce max_refresh even for still-valid documents.
6
                        if now.duration_since(cached.fetched).ok() <= Some(config.max_refetch) {
                            // Was fetched recently, too.  We can just reuse it.
2
                            return Ok(got);
4
                        }
4
                        Some(got)
                    }
                }
            }
        } else {
38
            None
        };
        // If cached_good is Some, we found a plausible cache entry; if we got here, it was
        // past its max_refresh.  So in that case we want to send a request with
        // if-modified-since.  If we get Not Modified, we can reuse it (and update the fetched time).
44
        let if_modified_since = cached_good
44
            .as_ref()
4
            .map(|got| got.desc.as_ref().published());
44
        debug!(
            r#"starting download for "{}"{}"#,
            bridge,
            match if_modified_since {
                Some(ims) => format!(
                    " if-modified-since {}",
                    humantime::format_rfc3339_seconds(ims),
                ),
                None => "".into(),
            }
        );
44
        let text = mockable
44
            .clone()
44
            .download(&self.runtime, &self.circmgr, bridge, if_modified_since)
44
            .await?;
12
        let (document, got) = if let Some(text) = text {
10
            let got = process_document(&text)?;
10
            (text, got)
2
        } else if let Some(cached) = cached_good {
2
            (
2
                cache_entry
2
                    .expect("cached_good but not cache_entry")
2
                    .document,
2
                cached,
2
            )
        } else {
            return Err(internal!("download gave None but no if-modified-since").into());
        };
        // IEFI catches cache store errors, which we log but don't do anything else with
12
        (|| {
12
            let cached = CachedBridgeDescriptor {
12
                document,
12
                fetched: now, // this is from before we started the fetch, which is correct
12
            };
            // Calculate when the cache should forget about this.
            // We want to add a bit of slop for the purposes of mild clock skew handling,
            // etc., and the prefetch time is a good proxy for that.
12
            let until = got
12
                .refetch
12
                .checked_add(config.prefetch)
12
                .unwrap_or(got.refetch /*uh*/);
12
            store()?.store_bridgedesc(bridge, cached, until)?;
12
            Ok(())
        })()
        .unwrap_or_else(|err: crate::Error| {
            error_report!(err, "failed to cache downloaded bridge descriptor",);
        });
12
        Ok(got)
46
    }
}
/// Processes and analyses a textual descriptor document into a `Downloaded`
///
/// Parses it, checks the signature, checks the document validity times,
/// and if that's all good, calculates when will want to refetch it.
32
fn process_document<R: Runtime>(
32
    runtime: &R,
32
    config: &BridgeDescDownloadConfig,
32
    text: &str,
32
) -> Result<Downloaded, Error> {
    // Some Tor bridges like to serve their routerdesc with an extra newline;
    // we strip that off here.
32
    let text = text.trim_ascii_end();
    // TODO: We should say whether it is a download or a cached object, at least.
32
    let desc = parse2::parse_netdoc::<RouterDescUnverified>(&ParseInput::new(text, "bridge"))?;
30
    let desc = desc.verify()?;
    // TODO: We should in theory extend this by our tolerance:
    // let desc = dir_config.tolerance.extend_bounds(desc);
28
    let expires = desc.bounds().end();
28
    let now = runtime.wallclock();
28
    let desc = desc.if_valid_at(&now)?;
    // Our refetch schedule, and enforcement of descriptor expiry, is somewhat approximate.
    // The following situations can result in a nominally-expired descriptor being used:
    //
    // 1. We primarily enforce the timeout by looking at the expiry time,
    //    subtracting a configured constant, and scheduling the start of a refetch then.
    //    If it takes us longer to do the retry, than the prefetch constant,
    //    we'll still be providing the old descriptor to consumers in the meantime.
    //
    // 2. We apply a minimum time before we will refetch a descriptor.
    //    So if the validity time is unreasonably short, we'll use it beyond that time.
    //
    // 3. Clock warping could confuse this algorithm.  This is inevitable because we
    //    are relying on calendar times (SystemTime) in the descriptor, and because
    //    we don't have a mechanism for being told about clock warps rather than the
    //    passage of time.
    //
    // We think this is all OK given that a bridge descriptor is used for trying to
    // connect to the bridge itself.  In particular, we don't want to completely trust
    // bridges to control our retry logic.
24
    let refetch = match expires {
24
        Some(expires) => expires
24
            .checked_sub(config.prefetch)
24
            .ok_or(Error::ExtremeValidityTime)?,
        None => now
            .checked_add(config.max_refetch)
            .ok_or(Error::ExtremeValidityTime)?,
    };
24
    let refetch = refetch.clamp(
24
        now.saturating_add(config.min_refetch),
24
        now.saturating_add(config.max_refetch),
24
    );
24
    let desc = BridgeDesc::new(Arc::new(desc));
24
    Ok(Downloaded { desc, refetch })
32
}
/// Task which waits for the timeout, and requeues bridges that need to be refetched
///
/// This task's job is to execute the wakeup instructions provided via `updates`.
///
/// `updates` is the receiving end of [`State`]'s `earliest_timeout`,
/// which is maintained to be the earliest time any of the schedules says we should wake up
/// (liveness property *Timeout*).
8
async fn timeout_task<R: Runtime, M: Mockable<R>>(
8
    runtime: R,
8
    inner: Weak<Manager<R, M>>,
8
    update: postage::watch::Receiver<Option<Instant>>,
8
) {
    /// Requeue things in `*_schedule` whose time for action has arrived
    ///
    /// `retry_delay_map` converts `retry_delay` from the schedule (`RetryDelay` or `()`)
    /// into the `Option` which appears in [`QueuedEntry`].
    ///
    /// Helper function.  Idempotent.
22
    fn requeue_as_required<TT: Ord + Copy + Debug, RD, RDM: Fn(RD) -> Option<RetryDelay>>(
22
        queued: &mut VecDeque<QueuedEntry>,
22
        schedule: &mut BinaryHeap<RefetchEntry<TT, RD>>,
22
        now: TT,
22
        retry_delay_map: RDM,
22
    ) {
46
        while let Some(ent) = schedule.peek() {
27
            if ent.when > now {
3
                break;
24
            }
24
            let re = schedule.pop().expect("schedule became empty!");
24
            let bridge = re.bridge;
24
            let retry_delay = retry_delay_map(re.retry_delay);
24
            queued.push_back(QueuedEntry {
24
                bridge,
24
                retry_delay,
24
            });
        }
22
    }
8
    let mut next_wakeup = Some(runtime.now());
8
    let mut update = update.fuse();
    loop {
57
        select! {
            // Someone modified the schedules, and sent us a new earliest timeout
57
            changed = update.next() => {
                // changed is Option<Option< >>.
                // The outer Option is from the Stream impl for watch::Receiver - None means EOF.
                // The inner Option is Some(wakeup_time), or None meaning "wait indefinitely"
44
                next_wakeup = if let Some(changed) = changed {
38
                    changed
                } else {
                    // Oh, actually, the watch::Receiver is EOF - we're to shut down
6
                    break
                }
            },
            // Wait until the specified earliest wakeup time
46
            () = async {
46
                if let Some(next_wakeup) = next_wakeup {
35
                    let now = runtime.now();
35
                    if next_wakeup > now {
23
                        let duration = next_wakeup.saturating_duration_since(now);
23
                        runtime.sleep(duration).await;
12
                    }
                } else {
                    #[allow(clippy::semicolon_if_nothing_returned)] // rust-clippy/issues/9729
11
                    { future::pending().await }
                }
13
            }.fuse() => {
                // We have reached the pre-programmed time.  Check what needs doing.
13
                let inner = if let Some(i) = inner.upgrade() { i } else { break; };
11
                let mut state = inner.lock_then_process();
11
                let state = &mut **state; // Do the DerefMut once so we can borrow fields
11
                requeue_as_required(
11
                    &mut state.queued,
11
                    &mut state.refetch_schedule,
11
                    runtime.wallclock(),
                    |()| None,
                );
11
                requeue_as_required(
11
                    &mut state.queued,
11
                    &mut state.retry_schedule,
11
                    runtime.now(),
11
                    Some,
11
                );
                // `StateGuard`, from `lock_then_process`, gets dropped here, and runs `process`,
                // to make further progress and restore the liveness properties.
            }
        }
    }
8
}
/// Error which occurs during bridge descriptor manager startup
#[derive(Clone, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum StartupError {
    /// No circuit manager in the directory manager
    #[error(
        "tried to create bridge descriptor manager from directory manager with no circuit manager"
    )]
    MissingCircMgr,
    /// Unable to spawn task
    //
    // TODO lots of our Errors have a variant exactly like this.
    // Maybe we should make a struct tor_error::SpawnError.
    #[error("Unable to spawn {spawning}")]
    Spawn {
        /// What we were trying to spawn.
        spawning: &'static str,
        /// What happened when we tried to spawn it.
        #[source]
        cause: Arc<SpawnError>,
    },
}
impl HasKind for StartupError {
    fn kind(&self) -> ErrorKind {
        use ErrorKind as EK;
        use StartupError as SE;
        match self {
            SE::MissingCircMgr => EK::Internal,
            SE::Spawn { cause, .. } => cause.kind(),
        }
    }
}
/// An error which occurred trying to obtain the descriptor for a particular bridge
#[derive(Clone, Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// Couldn't establish a circuit to the bridge
    #[error("Failed to establish circuit")]
    CircuitFailed(#[from] tor_circmgr::Error),
    /// Couldn't establish a directory stream to the bridge
    #[error("Failed to establish directory stream")]
    StreamFailed(#[source] tor_circmgr::Error),
    /// Directory request failed
    #[error("Directory request failed")]
    RequestFailed(#[from] tor_dirclient::RequestFailedError),
    /// Failed to parse descriptor in response
    #[error("Failed to parse descriptor in response")]
    ParseFailed(#[from] parse2::ParseError),
    /// Signature check failed
    #[error("Signature check failed")]
    SignatureCheckFailed(#[from] parse2::VerifyFailed),
    /// Obtained descriptor but it is outside its validity time
    #[error("Descriptor is outside its validity time, as supplied")]
    BadValidityTime(#[from] tor_checkable::TimeValidityError),
    /// A bridge descriptor has very extreme validity times
    /// such that our refetch time calculations overflow.
    #[error("Descriptor validity time range is too extreme for us to cope with")]
    ExtremeValidityTime,
    /// There was a programming error somewhere in our code, or the calling code.
    #[error("Programming error")]
    Bug(#[from] tor_error::Bug),
    /// Error used for testing
    #[cfg(test)]
    #[error("Error for testing, {0:?}, retry at {1:?}")]
    TestError(&'static str, RetryTime),
}
impl HasKind for Error {
32
    fn kind(&self) -> ErrorKind {
        use Error as E;
        use ErrorKind as EK;
32
        let bridge_protocol_violation = EK::TorAccessFailed;
32
        match self {
            // We trust that tor_circmgr returns TorAccessFailed when it ought to.
            E::CircuitFailed(e) => e.kind(),
            E::StreamFailed(e) => e.kind(),
            E::RequestFailed(e) => e.kind(),
            E::ParseFailed(..) => bridge_protocol_violation,
            E::SignatureCheckFailed(..) => bridge_protocol_violation,
            E::ExtremeValidityTime => bridge_protocol_violation,
            E::BadValidityTime(..) => EK::ClockSkew,
            E::Bug(e) => e.kind(),
            #[cfg(test)]
32
            E::TestError(..) => EK::Internal,
        }
32
    }
}
impl HasRetryTime for Error {
32
    fn retry_time(&self) -> RetryTime {
        use Error as E;
        use RetryTime as R;
32
        match self {
            // Errors with their own retry times
            E::CircuitFailed(e) => e.retry_time(),
            // Remote misbehavior, maybe the network is being strange?
            E::StreamFailed(..) => R::AfterWaiting,
            E::RequestFailed(..) => R::AfterWaiting,
            // Remote misconfiguration, detected *after* we successfully made the channel
            // (so not a network problem).  We'll say "never" for RetryTime,
            // even though actually we will in fact retry in at most `max_refetch`.
            E::ParseFailed(..) => R::Never,
            E::SignatureCheckFailed(..) => R::Never,
            E::BadValidityTime(..) => R::Never,
            E::ExtremeValidityTime => R::Never,
            // Probably, things are broken here, rather than remotely.
            E::Bug(..) => R::Never,
            #[cfg(test)]
32
            E::TestError(_, retry) => *retry,
        }
32
    }
}
impl BridgeDescError for Error {}
impl State {
    /// Consistency check (for testing)
    ///
    /// `input` should be what was passed to `set_bridges` (or `None` if not known).
    ///
    /// Does not make any changes.
    /// Only takes `&mut` because postage::watch::Sender::borrow` wants it.
    #[cfg(test)]
46
    fn check_consistency<'i, R, I>(&mut self, runtime: &R, input: Option<I>)
46
    where
46
        R: Runtime,
46
        I: IntoIterator<Item = &'i BridgeKey>,
    {
        /// Where we found a thing was Tracked
        #[derive(Debug, Clone, Copy, Eq, PartialEq)]
        enum Where {
            /// Found in `running`
            Running,
            /// Found in `queued`
            Queued,
            /// Found in the schedule `sch`
            Schedule {
                sch_name: &'static str,
                /// Starts out as `false`, set to `true` when we find this in `current`
                found_in_current: bool,
            },
        }
        /// Records the expected input from `input`, and what we have found so far
        struct Tracked {
            /// Were we told what the last `set_bridges` call got as input?
            known_input: bool,
            /// `Some` means we have seen this bridge in one our records (other than `current`)
            tracked: HashMap<BridgeKey, Option<Where>>,
            /// Earliest instant found in any schedule
            earliest: Option<Instant>,
        }
46
        let mut tracked = if let Some(input) = input {
260
            let tracked = input.into_iter().map(|b| (b.clone(), None)).collect();
46
            Tracked {
46
                tracked,
46
                known_input: true,
46
                earliest: None,
46
            }
        } else {
            Tracked {
                tracked: HashMap::new(),
                known_input: false,
                earliest: None,
            }
        };
        impl Tracked {
            /// Note that `bridge` is Tracked
260
            fn note(&mut self, where_: Where, b: &BridgeKey) {
260
                match self.tracked.get(b) {
                    // Invariant *Tracked* - ie appears at most once
                    Some(Some(prev_where)) => {
                        panic!("duplicate {:?} {:?} {:?}", prev_where, where_, b);
                    }
                    // Invariant *Input (every tracked bridge is was in input)*
                    None if self.known_input => {
                        panic!("unexpected {:?} {:?}", where_, b);
                    }
                    // OK, we've not seen it before, note it as being here
                    _ => {
260
                        self.tracked.insert(b.clone(), Some(where_));
                    }
                }
260
            }
        }
        /// Walk `schedule` and update `tracked` (including `tracked.earliest`)
        ///
        /// Check invariant *Tracked* and *Schedule* wrt this schedule.
        #[cfg(test)]
92
        fn walk_sch<TT: Ord + Copy + Debug, RD, CT: Fn(TT) -> Instant>(
92
            tracked: &mut Tracked,
92
            sch_name: &'static str,
92
            schedule: &BinaryHeap<RefetchEntry<TT, RD>>,
92
            conv_time: CT,
92
        ) {
92
            let where_ = Where::Schedule {
92
                sch_name,
92
                found_in_current: false,
92
            };
92
            if let Some(first) = schedule.peek() {
                // Of course this is a heap, so this ought to be a wasteful scan,
                // but, indirectly,this tests our implementation of `Ord` for `RefetchEntry`.
77
                for re in schedule {
223
                    tracked.note(where_, &re.bridge);
                }
77
                let scanned = schedule
77
                    .iter()
223
                    .map(|re| re.when)
                    .min()
77
                    .expect("schedule empty!");
77
                assert_eq!(scanned, first.when);
77
                tracked.earliest = Some(
77
                    [tracked.earliest, Some(conv_time(scanned))]
77
                        .into_iter()
77
                        .flatten()
77
                        .min()
77
                        .expect("flatten of chain Some was empty"),
77
                );
15
            }
92
        }
        // *Timeout* (prep)
        //
        // This will fail if there is clock skew, but won't mind if
        // the earliest refetch time is in the past.
46
        let now_wall = runtime.wallclock();
46
        let now_mono = runtime.now();
39
        let adj_wall = |wallclock: SystemTime| {
            // Good grief what a palaver!
39
            if let Ok(ahead) = wallclock.duration_since(now_wall) {
33
                now_mono.saturating_add(ahead)
6
            } else if let Ok(behind) = now_wall.duration_since(wallclock) {
6
                now_mono
6
                    .checked_sub(behind)
6
                    .expect("time subtraction underflow")
            } else {
                panic!("times should be totally ordered!")
            }
39
        };
        // *Tracked*
        //
        // We walk our data structures in turn
46
        for b in self.running.keys() {
33
            tracked.note(Where::Running, b);
        }
46
        for qe in &self.queued {
4
            tracked.note(Where::Queued, &qe.bridge);
        }
46
        walk_sch(&mut tracked, "refetch", &self.refetch_schedule, adj_wall);
46
        walk_sch(&mut tracked, "retry", &self.retry_schedule, |t| t);
        // *Current*
46
        for b in self.current.keys() {
238
            let found = tracked
238
                .tracked
238
                .get_mut(b)
238
                .and_then(Option::as_mut)
                .unwrap_or_else(|| panic!("current but untracked {:?}", b));
238
            if let Where::Schedule {
238
                found_in_current, ..
238
            } = found
            {
223
                *found_in_current = true;
15
            }
        }
        // *Input (sense: every input bridge is tracked)*
        //
        // (Will not cope if spawn ever failed, since that violates the invariant.)
46
        for (b, where_) in &tracked.tracked {
260
            match where_ {
                None => panic!("missing {}", b),
                Some(Where::Schedule {
                    sch_name,
                    found_in_current,
                }) => {
223
                    assert!(found_in_current, "not-Schedule {} {}", b, sch_name);
                }
37
                _ => {}
            }
        }
        // *Limit*
46
        let parallelism = self.effective_parallelism();
46
        assert!(self.running.len() <= parallelism);
        // *Running*
46
        assert!(self.running.len() == parallelism || self.queued.is_empty());
        // *Timeout* (final)
46
        assert_eq!(tracked.earliest, *self.earliest_timeout.borrow());
46
    }
}