1
//! The onion service publisher reactor.
2
//!
3
//! Generates and publishes hidden service descriptors in response to various events.
4
//!
5
//! [`Reactor::run`] is the entry-point of the reactor. It starts the reactor,
6
//! and runs until [`Reactor::run_once`] returns [`ShutdownStatus::Terminate`]
7
//! or a fatal error occurs. `ShutdownStatus::Terminate` is returned if
8
//! any of the channels the reactor is receiving events from is closed
9
//! (i.e. when the senders are dropped).
10
//!
11
//! ## Publisher status
12
//!
13
//! The publisher has an internal [`PublishStatus`], distinct from its [`State`],
14
//! which is used for onion service status reporting.
15
//!
16
//! The main loop of the reactor reads the current `PublishStatus` from `publish_status_rx`,
17
//! and responds by generating and publishing a new descriptor if needed.
18
//!
19
//! See [`PublishStatus`] and [`Reactor::publish_status_rx`] for more details.
20
//!
21
//! ## When do we publish?
22
//!
23
//! We generate and publish a new descriptor if
24
//!   * the introduction points have changed
25
//!   * the onion service configuration has changed in a meaningful way (for example,
26
//!     if the `restricted_discovery` configuration or its [`Anonymity`](crate::Anonymity)
27
//!     has changed. See [`OnionServiceConfigPublisherView`]).
28
//!   * there is a new consensus
29
//!   * it is time to republish the descriptor (after we upload a descriptor,
30
//!     we schedule it for republishing at a random time between 60 minutes and 120 minutes
31
//!     in the future)
32
//!
33
//! ## Onion service status
34
//!
35
//! With respect to [`OnionServiceStatus`] reporting,
36
//! the following state transitions are possible:
37
//!
38
//!
39
//! ```ignore
40
//!
41
//!                 update_publish_status(UploadScheduled|AwaitingIpts|RateLimited)
42
//!                +---------------------------------------+
43
//!                |                                       |
44
//!                |                                       v
45
//!                |                               +---------------+
46
//!                |                               | Bootstrapping |
47
//!                |                               +---------------+
48
//!                |                                       |
49
//!                |                                       |           uploaded to at least
50
//!                |  not enough HsDir uploads succeeded   |        some HsDirs from each ring
51
//!                |         +-----------------------------+-----------------------+
52
//!                |         |                             |                       |
53
//!                |         |              all HsDir uploads succeeded            |
54
//!                |         |                             |                       |
55
//!                |         v                             v                       v
56
//!                |  +---------------------+         +---------+        +---------------------+
57
//!                |  | DegradedUnreachable |         | Running |        |  DegradedReachable  |
58
//! +----------+   |  +---------------------+         +---------+        +---------------------+
59
//! | Shutdown |-- |         |                           |                        |
60
//! +----------+   |         |                           |                        |
61
//!                |         |                           |                        |
62
//!                |         |                           |                        |
63
//!                |         +---------------------------+------------------------+
64
//!                |                                     |   invalid authorized_clients
65
//!                |                                     |      after handling config change
66
//!                |                                     |
67
//!                |                                     v
68
//!                |     run_once() returns an error +--------+
69
//!                +-------------------------------->| Broken |
70
//!                                                  +--------+
71
//! ```
72
//!
73
//! We can also transition from `Broken`, `DegradedReachable`, or `DegradedUnreachable`
74
//! back to `Bootstrapping` (those transitions were omitted for brevity).
75

            
76
use tor_config::file_watcher::{
77
    self, Event as FileEvent, FileEventReceiver, FileEventSender, FileWatcher, FileWatcherBuilder,
78
};
79
use tor_config_path::{CfgPath, CfgPathResolver};
80
use tor_netdir::{DirEvent, NetDir};
81

            
82
use crate::config::restricted_discovery::{
83
    DirectoryKeyProviderList, RestrictedDiscoveryConfig, RestrictedDiscoveryKeys,
84
};
85
use crate::config::OnionServiceConfigPublisherView;
86
use crate::status::{DescUploadRetryError, Problem};
87

            
88
use super::*;
89

            
90
// TODO-CLIENT-AUTH: perhaps we should add a separate CONFIG_CHANGE_REPUBLISH_DEBOUNCE_INTERVAL
91
// for rate-limiting the publish jobs triggered by a change in the config?
92
//
93
// Currently the descriptor publish tasks triggered by changes in the config
94
// are rate-limited via the usual rate limiting mechanism
95
// (which rate-limits the uploads for 1m).
96
//
97
// I think this is OK for now, but we might need to rethink this if it becomes problematic
98
// (for example, we might want an even longer rate-limit, or to reset any existing rate-limits
99
// each time the config is modified).
100

            
101
/// The upload rate-limiting threshold.
102
///
103
/// Before initiating an upload, the reactor checks if the last upload was at least
104
/// `UPLOAD_RATE_LIM_THRESHOLD` seconds ago. If so, it uploads the descriptor to all HsDirs that
105
/// need it. If not, it schedules the upload to happen `UPLOAD_RATE_LIM_THRESHOLD` seconds from the
106
/// current time.
107
//
108
// TODO: We may someday need to tune this value; it was chosen more or less arbitrarily.
109
const UPLOAD_RATE_LIM_THRESHOLD: Duration = Duration::from_secs(60);
110

            
111
/// The maximum number of concurrent upload tasks per time period.
112
//
113
// TODO: this value was arbitrarily chosen and may not be optimal.  For now, it
114
// will have no effect, since the current number of replicas is far less than
115
// this value.
116
//
117
// The uploads for all TPs happen in parallel.  As a result, the actual limit for the maximum
118
// number of concurrent upload tasks is multiplied by a number which depends on the TP parameters
119
// (currently 2, which means the concurrency limit will, in fact, be 32).
120
//
121
// We should try to decouple this value from the TP parameters.
122
const MAX_CONCURRENT_UPLOADS: usize = 16;
123

            
124
/// The maximum time allowed for uploading a descriptor to a single HSDir,
125
/// across all attempts.
126
pub(crate) const OVERALL_UPLOAD_TIMEOUT: Duration = Duration::from_secs(5 * 60);
127

            
128
/// A reactor for the HsDir [`Publisher`]
129
///
130
/// The entrypoint is [`Reactor::run`].
131
#[must_use = "If you don't call run() on the reactor, it won't publish any descriptors."]
132
pub(super) struct Reactor<R: Runtime, M: Mockable> {
133
    /// The immutable, shared inner state.
134
    imm: Arc<Immutable<R, M>>,
135
    /// A source for new network directories that we use to determine
136
    /// our HsDirs.
137
    dir_provider: Arc<dyn NetDirProvider>,
138
    /// The mutable inner state,
139
    inner: Arc<Mutex<Inner>>,
140
    /// A channel for receiving IPT change notifications.
141
    ipt_watcher: IptsPublisherView,
142
    /// A channel for receiving onion service config change notifications.
143
    config_rx: watch::Receiver<Arc<OnionServiceConfig>>,
144
    /// A channel for receiving restricted discovery key_dirs change notifications.
145
    key_dirs_rx: FileEventReceiver,
146
    /// A channel for sending restricted discovery key_dirs change notifications.
147
    ///
148
    /// A copy of this sender is handed out to every `FileWatcher` created.
149
    key_dirs_tx: FileEventSender,
150
    /// A channel for receiving updates regarding our [`PublishStatus`].
151
    ///
152
    /// The main loop of the reactor watches for updates on this channel.
153
    ///
154
    /// When the [`PublishStatus`] changes to [`UploadScheduled`](PublishStatus::UploadScheduled),
155
    /// we can start publishing descriptors.
156
    ///
157
    /// If the [`PublishStatus`] is [`AwaitingIpts`](PublishStatus::AwaitingIpts), publishing is
158
    /// paused until we receive a notification on `ipt_watcher` telling us the IPT manager has
159
    /// established some introduction points.
160
    publish_status_rx: watch::Receiver<PublishStatus>,
161
    /// A sender for updating our [`PublishStatus`].
162
    ///
163
    /// When our [`PublishStatus`] changes to [`UploadScheduled`](PublishStatus::UploadScheduled),
164
    /// we can start publishing descriptors.
165
    publish_status_tx: watch::Sender<PublishStatus>,
166
    /// A channel for sending upload completion notifications.
167
    ///
168
    /// This channel is polled in the main loop of the reactor.
169
    upload_task_complete_rx: mpsc::Receiver<TimePeriodUploadResult>,
170
    /// A channel for receiving upload completion notifications.
171
    ///
172
    /// A copy of this sender is handed to each upload task.
173
    upload_task_complete_tx: mpsc::Sender<TimePeriodUploadResult>,
174
    /// A sender for notifying any pending upload tasks that the reactor is shutting down.
175
    ///
176
    /// Receivers can use this channel to find out when reactor is dropped.
177
    ///
178
    /// This is currently only used in [`upload_for_time_period`](Reactor::upload_for_time_period).
179
    /// Any future background tasks can also use this channel to detect if the reactor is dropped.
180
    ///
181
    /// Closing this channel will cause any pending upload tasks to be dropped.
182
    shutdown_tx: broadcast::Sender<Void>,
183
    /// Path resolver for configuration files.
184
    path_resolver: Arc<CfgPathResolver>,
185
}
186

            
187
/// The immutable, shared state of the descriptor publisher reactor.
188
#[derive(Clone)]
189
struct Immutable<R: Runtime, M: Mockable> {
190
    /// The runtime.
191
    runtime: R,
192
    /// Mockable state.
193
    ///
194
    /// This is used for launching circuits and for obtaining random number generators.
195
    mockable: M,
196
    /// The service for which we're publishing descriptors.
197
    nickname: HsNickname,
198
    /// The key manager,
199
    keymgr: Arc<KeyMgr>,
200
    /// A sender for updating the status of the onion service.
201
    status_tx: PublisherStatusSender,
202
}
203

            
204
impl<R: Runtime, M: Mockable> Immutable<R, M> {
205
    /// Create an [`AesOpeKey`] for generating revision counters for the descriptors associated
206
    /// with the specified [`TimePeriod`].
207
    ///
208
    /// If the onion service is not running in offline mode, the key of the returned `AesOpeKey` is
209
    /// the private part of the blinded identity key. Otherwise, the key is the private part of the
210
    /// descriptor signing key.
211
    ///
212
    /// Returns an error if the service is running in offline mode and the descriptor signing
213
    /// keypair of the specified `period` is not available.
214
    //
215
    // TODO (#1194): we don't support "offline" mode (yet), so this always returns an AesOpeKey
216
    // built from the blinded id key
217
128
    fn create_ope_key(&self, period: TimePeriod) -> Result<AesOpeKey, FatalError> {
218
128
        let ope_key = match read_blind_id_keypair(&self.keymgr, &self.nickname, period)? {
219
128
            Some(key) => {
220
128
                let key: ed25519::ExpandedKeypair = key.into();
221
128
                key.to_secret_key_bytes()[0..32]
222
128
                    .try_into()
223
128
                    .expect("Wrong length on slice")
224
            }
225
            None => {
226
                // TODO (#1194): we don't support externally provisioned keys (yet), so this branch
227
                // is unreachable (for now).
228
                let desc_sign_key_spec =
229
                    DescSigningKeypairSpecifier::new(self.nickname.clone(), period);
230
                let key: ed25519::Keypair = self
231
                    .keymgr
232
                    .get::<HsDescSigningKeypair>(&desc_sign_key_spec)?
233
                    // TODO (#1194): internal! is not the right type for this error (we need an
234
                    // error type for the case where a hidden service running in offline mode has
235
                    // run out of its pre-previsioned keys).
236
                    //
237
                    // This will be addressed when we add support for offline hs_id mode
238
                    .ok_or_else(|| internal!("identity keys are offline, but descriptor signing key is unavailable?!"))?
239
                    .into();
240
                key.to_bytes()
241
            }
242
        };
243

            
244
128
        Ok(AesOpeKey::from_secret(&ope_key))
245
128
    }
246

            
247
    /// Generate a revision counter for a descriptor associated with the specified
248
    /// [`TimePeriod`].
249
    ///
250
    /// Returns a revision counter generated according to the [encrypted time in period] scheme.
251
    ///
252
    /// [encrypted time in period]: https://spec.torproject.org/rend-spec/revision-counter-mgt.html#encrypted-time
253
128
    fn generate_revision_counter(
254
128
        &self,
255
128
        params: &HsDirParams,
256
128
        now: SystemTime,
257
128
    ) -> Result<RevisionCounter, FatalError> {
258
        // TODO: in the future, we might want to compute ope_key once per time period (as oppposed
259
        // to each time we generate a new descriptor), for performance reasons.
260
128
        let ope_key = self.create_ope_key(params.time_period())?;
261

            
262
        // TODO: perhaps this should be moved to a new HsDirParams::offset_within_sr() function
263
128
        let srv_start = params.start_of_shard_rand_period();
264
128
        let offset = params.offset_within_srv_period(now).ok_or_else(|| {
265
            internal!(
266
                "current wallclock time not within SRV range?! (now={:?}, SRV_start={:?})",
267
                now,
268
                srv_start
269
            )
270
128
        })?;
271
128
        let rev = ope_key.encrypt(offset);
272
128

            
273
128
        Ok(RevisionCounter::from(rev))
274
128
    }
275
}
276

            
277
/// Mockable state for the descriptor publisher reactor.
278
///
279
/// This enables us to mock parts of the [`Reactor`] for testing purposes.
280
#[async_trait]
281
pub(crate) trait Mockable: Clone + Send + Sync + Sized + 'static {
282
    /// The type of random number generator.
283
    type Rng: rand::Rng + rand::CryptoRng;
284

            
285
    /// The type of client circuit.
286
    type ClientCirc: MockableClientCirc;
287

            
288
    /// Return a random number generator.
289
    fn thread_rng(&self) -> Self::Rng;
290

            
291
    /// Create a circuit of the specified `kind` to `target`.
292
    async fn get_or_launch_specific<T>(
293
        &self,
294
        netdir: &NetDir,
295
        kind: HsCircKind,
296
        target: T,
297
    ) -> Result<Arc<Self::ClientCirc>, tor_circmgr::Error>
298
    where
299
        T: CircTarget + Send + Sync;
300

            
301
    /// Return an estimate-based value for how long we should allow a single
302
    /// directory upload operation to complete.
303
    ///
304
    /// Includes circuit construction, stream opening, upload, and waiting for a
305
    /// response.
306
    fn estimate_upload_timeout(&self) -> Duration;
307
}
308

            
309
/// Mockable client circuit
310
#[async_trait]
311
pub(crate) trait MockableClientCirc: Send + Sync {
312
    /// The data stream type.
313
    type DataStream: AsyncRead + AsyncWrite + Send + Unpin;
314

            
315
    /// Start a new stream to the last relay in the circuit, using
316
    /// a BEGIN_DIR cell.
317
    async fn begin_dir_stream(self: Arc<Self>) -> Result<Self::DataStream, tor_proto::Error>;
318
}
319

            
320
#[async_trait]
321
impl MockableClientCirc for ClientCirc {
322
    type DataStream = tor_proto::stream::DataStream;
323

            
324
    async fn begin_dir_stream(self: Arc<Self>) -> Result<Self::DataStream, tor_proto::Error> {
325
        ClientCirc::begin_dir_stream(self).await
326
    }
327
}
328

            
329
/// The real version of the mockable state of the reactor.
330
#[derive(Clone, From, Into)]
331
pub(crate) struct Real<R: Runtime>(Arc<HsCircPool<R>>);
332

            
333
#[async_trait]
334
impl<R: Runtime> Mockable for Real<R> {
335
    type Rng = rand::rngs::ThreadRng;
336
    type ClientCirc = ClientCirc;
337

            
338
    fn thread_rng(&self) -> Self::Rng {
339
        rand::thread_rng()
340
    }
341

            
342
    async fn get_or_launch_specific<T>(
343
        &self,
344
        netdir: &NetDir,
345
        kind: HsCircKind,
346
        target: T,
347
    ) -> Result<Arc<ClientCirc>, tor_circmgr::Error>
348
    where
349
        T: CircTarget + Send + Sync,
350
    {
351
        self.0.get_or_launch_specific(netdir, kind, target).await
352
    }
353

            
354
    fn estimate_upload_timeout(&self) -> Duration {
355
        use tor_circmgr::timeouts::Action;
356
        let est_build = self.0.estimate_timeout(&Action::BuildCircuit { length: 4 });
357
        let est_roundtrip = self.0.estimate_timeout(&Action::RoundTrip { length: 4 });
358
        // We assume that in the worst case we'll have to wait for an entire
359
        // circuit construction and two round-trips to the hsdir.
360
        let est_total = est_build + est_roundtrip * 2;
361
        // We always allow _at least_ this much time, in case our estimate is
362
        // ridiculously low.
363
        let min_timeout = Duration::from_secs(30);
364
        max(est_total, min_timeout)
365
    }
366
}
367

            
368
/// The mutable state of a [`Reactor`].
369
struct Inner {
370
    /// The onion service config.
371
    config: Arc<OnionServiceConfigPublisherView>,
372
    /// Watcher for key_dirs.
373
    ///
374
    /// Set to `None` if the reactor is not running, or if `watch_configuration` is false.
375
    ///
376
    /// The watcher is recreated whenever the `restricted_discovery.key_dirs` change.
377
    file_watcher: Option<FileWatcher>,
378
    /// The relevant time periods.
379
    ///
380
    /// This includes the current time period, as well as any other time periods we need to be
381
    /// publishing descriptors for.
382
    ///
383
    /// This is empty until we fetch our first netdir in [`Reactor::run`].
384
    time_periods: Vec<TimePeriodContext>,
385
    /// Our most up to date netdir.
386
    ///
387
    /// This is initialized in [`Reactor::run`].
388
    netdir: Option<Arc<NetDir>>,
389
    /// The timestamp of our last upload.
390
    ///
391
    /// This is the time when the last update was _initiated_ (rather than completed), to prevent
392
    /// the publisher from spawning multiple upload tasks at once in response to multiple external
393
    /// events happening in quick succession, such as the IPT manager sending multiple IPT change
394
    /// notifications in a short time frame (#1142), or an IPT change notification that's
395
    /// immediately followed by a consensus change. Starting two upload tasks at once is not only
396
    /// inefficient, but it also causes the publisher to generate two different descriptors with
397
    /// the same revision counter (the revision counter is derived from the current timestamp),
398
    /// which ultimately causes the slower upload task to fail (see #1142).
399
    ///
400
    /// Note: This is only used for deciding when to reschedule a rate-limited upload. It is _not_
401
    /// used for retrying failed uploads (these are handled internally by
402
    /// [`Reactor::upload_descriptor_with_retries`]).
403
    last_uploaded: Option<Instant>,
404
    /// A max-heap containing the time periods for which we need to reupload the descriptor.
405
    // TODO: we are currently reuploading more than nececessary.
406
    // Ideally, this shouldn't contain contain duplicate TimePeriods,
407
    // because we only need to retain the latest reupload time for each time period.
408
    //
409
    // Currently, if, for some reason, we upload the descriptor multiple times for the same TP,
410
    // we will end up with multiple ReuploadTimer entries for that TP,
411
    // each of which will (eventually) result in a reupload.
412
    //
413
    // TODO: maybe this should just be a HashMap<TimePeriod, Instant>
414
    //
415
    // See https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/1971#note_2994950
416
    reupload_timers: BinaryHeap<ReuploadTimer>,
417
    /// The restricted discovery authorized clients.
418
    ///
419
    /// `None`, unless the service is running in restricted discovery mode.
420
    authorized_clients: Option<Arc<RestrictedDiscoveryKeys>>,
421
}
422

            
423
/// The part of the reactor state that changes with every time period.
424
struct TimePeriodContext {
425
    /// The HsDir params.
426
    params: HsDirParams,
427
    /// The HsDirs to use in this time period.
428
    ///
429
    // We keep a list of `RelayIds` because we can't store a `Relay<'_>` inside the reactor
430
    // (the lifetime of a relay is tied to the lifetime of its corresponding `NetDir`. To
431
    // store `Relay<'_>`s in the reactor, we'd need a way of atomically swapping out both the
432
    // `NetDir` and the cached relays, and to convince Rust what we're doing is sound)
433
    hs_dirs: Vec<(RelayIds, DescriptorStatus)>,
434
    /// The revision counter of the last successful upload, if any.
435
    last_successful: Option<RevisionCounter>,
436
    /// The outcome of the last upload, if any.
437
    upload_results: Vec<HsDirUploadStatus>,
438
}
439

            
440
impl TimePeriodContext {
441
    /// Create a new `TimePeriodContext`.
442
    ///
443
    /// Any of the specified `old_hsdirs` also present in the new list of HsDirs
444
    /// (returned by `NetDir::hs_dirs_upload`) will have their `DescriptorStatus` preserved.
445
8
    fn new<'r>(
446
8
        params: HsDirParams,
447
8
        blind_id: HsBlindId,
448
8
        netdir: &Arc<NetDir>,
449
8
        old_hsdirs: impl Iterator<Item = &'r (RelayIds, DescriptorStatus)>,
450
8
        old_upload_results: Vec<HsDirUploadStatus>,
451
8
    ) -> Result<Self, FatalError> {
452
8
        let period = params.time_period();
453
8
        let hs_dirs = Self::compute_hsdirs(period, blind_id, netdir, old_hsdirs)?;
454
8
        let upload_results = old_upload_results
455
8
            .into_iter()
456
8
            .filter(|res|
457
                // Check if the HsDir of this result still exists
458
                hs_dirs
459
                    .iter()
460
8
                    .any(|(relay_ids, _status)| relay_ids == &res.relay_ids))
461
8
            .collect();
462
8

            
463
8
        Ok(Self {
464
8
            params,
465
8
            hs_dirs,
466
8
            last_successful: None,
467
8
            upload_results,
468
8
        })
469
8
    }
470

            
471
    /// Recompute the HsDirs for this time period.
472
8
    fn compute_hsdirs<'r>(
473
8
        period: TimePeriod,
474
8
        blind_id: HsBlindId,
475
8
        netdir: &Arc<NetDir>,
476
8
        mut old_hsdirs: impl Iterator<Item = &'r (RelayIds, DescriptorStatus)>,
477
8
    ) -> Result<Vec<(RelayIds, DescriptorStatus)>, FatalError> {
478
8
        let hs_dirs = netdir.hs_dirs_upload(blind_id, period)?;
479

            
480
8
        Ok(hs_dirs
481
64
            .map(|hs_dir| {
482
64
                let mut builder = RelayIds::builder();
483
64
                if let Some(ed_id) = hs_dir.ed_identity() {
484
64
                    builder.ed_identity(*ed_id);
485
64
                }
486

            
487
64
                if let Some(rsa_id) = hs_dir.rsa_identity() {
488
64
                    builder.rsa_identity(*rsa_id);
489
64
                }
490

            
491
64
                let relay_id = builder.build().unwrap_or_else(|_| RelayIds::empty());
492

            
493
                // Have we uploaded the descriptor to thiw relay before? If so, we don't need to
494
                // reupload it unless it was already dirty and due for a reupload.
495
64
                let status = match old_hsdirs.find(|(id, _)| *id == relay_id) {
496
                    Some((_, status)) => *status,
497
64
                    None => DescriptorStatus::Dirty,
498
                };
499

            
500
64
                (relay_id, status)
501
64
            })
502
8
            .collect::<Vec<_>>())
503
8
    }
504

            
505
    /// Mark the descriptor dirty for all HSDirs of this time period.
506
16
    fn mark_all_dirty(&mut self) {
507
16
        self.hs_dirs
508
16
            .iter_mut()
509
136
            .for_each(|(_relay_id, status)| *status = DescriptorStatus::Dirty);
510
16
    }
511

            
512
    /// Update the upload result for this time period.
513
12
    fn set_upload_results(&mut self, upload_results: Vec<HsDirUploadStatus>) {
514
12
        self.upload_results = upload_results;
515
12
    }
516
}
517

            
518
/// An error that occurs while trying to upload a descriptor.
519
#[derive(Clone, Debug, thiserror::Error)]
520
#[non_exhaustive]
521
pub enum UploadError {
522
    /// An error that has occurred after we have contacted a directory cache and made a circuit to it.
523
    #[error("descriptor upload request failed: {}", _0.error)]
524
    Request(#[from] RequestFailedError),
525

            
526
    /// Failed to establish circuit to hidden service directory
527
    #[error("could not build circuit to HsDir")]
528
    Circuit(#[from] tor_circmgr::Error),
529

            
530
    /// Failed to establish stream to hidden service directory
531
    #[error("failed to establish directory stream to HsDir")]
532
    Stream(#[source] tor_proto::Error),
533

            
534
    /// An internal error.
535
    #[error("Internal error")]
536
    Bug(#[from] tor_error::Bug),
537
}
538
define_asref_dyn_std_error!(UploadError);
539

            
540
impl<R: Runtime, M: Mockable> Reactor<R, M> {
541
    /// Create a new `Reactor`.
542
    #[allow(clippy::too_many_arguments)]
543
8
    pub(super) fn new(
544
8
        runtime: R,
545
8
        nickname: HsNickname,
546
8
        dir_provider: Arc<dyn NetDirProvider>,
547
8
        mockable: M,
548
8
        config: &OnionServiceConfig,
549
8
        ipt_watcher: IptsPublisherView,
550
8
        config_rx: watch::Receiver<Arc<OnionServiceConfig>>,
551
8
        status_tx: PublisherStatusSender,
552
8
        keymgr: Arc<KeyMgr>,
553
8
        path_resolver: Arc<CfgPathResolver>,
554
8
    ) -> Self {
555
        /// The maximum size of the upload completion notifier channel.
556
        ///
557
        /// The channel we use this for is a futures::mpsc channel, which has a capacity of
558
        /// `UPLOAD_CHAN_BUF_SIZE + num-senders`. We don't need the buffer size to be non-zero, as
559
        /// each sender will send exactly one message.
560
        const UPLOAD_CHAN_BUF_SIZE: usize = 0;
561

            
562
        // Internally-generated instructions, no need for mq.
563
8
        let (upload_task_complete_tx, upload_task_complete_rx) =
564
8
            mpsc_channel_no_memquota(UPLOAD_CHAN_BUF_SIZE);
565
8

            
566
8
        let (publish_status_tx, publish_status_rx) = watch::channel();
567
8
        // Setting the buffer size to zero here is OK,
568
8
        // since we never actually send anything on this channel.
569
8
        let (shutdown_tx, _shutdown_rx) = broadcast::channel(0);
570
8

            
571
8
        let authorized_clients =
572
8
            Self::read_authorized_clients(&config.restricted_discovery, &path_resolver);
573
8

            
574
8
        // Create a channel for watching for changes in the configured
575
8
        // restricted_discovery.key_dirs.
576
8
        let (key_dirs_tx, key_dirs_rx) = file_watcher::channel();
577
8

            
578
8
        let imm = Immutable {
579
8
            runtime,
580
8
            mockable,
581
8
            nickname,
582
8
            keymgr,
583
8
            status_tx,
584
8
        };
585
8

            
586
8
        let inner = Inner {
587
8
            time_periods: vec![],
588
8
            config: Arc::new(config.into()),
589
8
            file_watcher: None,
590
8
            netdir: None,
591
8
            last_uploaded: None,
592
8
            reupload_timers: Default::default(),
593
8
            authorized_clients,
594
8
        };
595
8

            
596
8
        Self {
597
8
            imm: Arc::new(imm),
598
8
            inner: Arc::new(Mutex::new(inner)),
599
8
            dir_provider,
600
8
            ipt_watcher,
601
8
            config_rx,
602
8
            key_dirs_rx,
603
8
            key_dirs_tx,
604
8
            publish_status_rx,
605
8
            publish_status_tx,
606
8
            upload_task_complete_rx,
607
8
            upload_task_complete_tx,
608
8
            shutdown_tx,
609
8
            path_resolver,
610
8
        }
611
8
    }
612

            
613
    /// Start the reactor.
614
    ///
615
    /// Under normal circumstances, this function runs indefinitely.
616
    ///
617
    /// Note: this also spawns the "reminder task" that we use to reschedule uploads whenever an
618
    /// upload fails or is rate-limited.
619
8
    pub(super) async fn run(mut self) -> Result<(), FatalError> {
620
8
        debug!(nickname=%self.imm.nickname, "starting descriptor publisher reactor");
621

            
622
        {
623
8
            let netdir = self
624
8
                .dir_provider
625
8
                .wait_for_netdir(Timeliness::Timely)
626
8
                .await?;
627
8
            let time_periods = self.compute_time_periods(&netdir, &[])?;
628

            
629
8
            let mut inner = self.inner.lock().expect("poisoned lock");
630
8

            
631
8
            inner.netdir = Some(netdir);
632
8
            inner.time_periods = time_periods;
633
8
        }
634
8

            
635
8
        // Create the initial key_dirs watcher.
636
8
        self.update_file_watcher();
637

            
638
        loop {
639
92
            match self.run_once().await {
640
84
                Ok(ShutdownStatus::Continue) => continue,
641
                Ok(ShutdownStatus::Terminate) => {
642
                    debug!(nickname=%self.imm.nickname, "descriptor publisher is shutting down!");
643

            
644
                    self.imm.status_tx.send_shutdown();
645
                    return Ok(());
646
                }
647
                Err(e) => {
648
                    error_report!(
649
                        e,
650
                        "HS service {}: descriptor publisher crashed!",
651
                        self.imm.nickname
652
                    );
653

            
654
                    self.imm.status_tx.send_broken(e.clone());
655

            
656
                    return Err(e);
657
                }
658
            }
659
        }
660
    }
661

            
662
    /// Run one iteration of the reactor loop.
663
92
    async fn run_once(&mut self) -> Result<ShutdownStatus, FatalError> {
664
92
        let mut netdir_events = self.dir_provider.events();
665
92

            
666
92
        // Note: TrackingNow tracks the values it is compared with.
667
92
        // This is equivalent to sleeping for (until - now) units of time,
668
92
        let upload_rate_lim: TrackingNow = TrackingNow::now(&self.imm.runtime);
669
92
        if let PublishStatus::RateLimited(until) = self.status() {
670
            if upload_rate_lim > until {
671
                // We are no longer rate-limited
672
                self.expire_rate_limit().await?;
673
            }
674
92
        }
675

            
676
92
        let reupload_tracking = TrackingNow::now(&self.imm.runtime);
677
92
        let mut reupload_periods = vec![];
678
92
        {
679
92
            let mut inner = self.inner.lock().expect("poisoned lock");
680
92
            let inner = &mut *inner;
681
100
            while let Some(reupload) = inner.reupload_timers.peek().copied() {
682
                // First, extract all the timeouts that already elapsed.
683
20
                if reupload.when <= reupload_tracking {
684
8
                    inner.reupload_timers.pop();
685
8
                    reupload_periods.push(reupload.period);
686
8
                } else {
687
                    // We are not ready to schedule any more reuploads.
688
                    //
689
                    // How much we need to sleep is implicitly
690
                    // tracked in reupload_tracking (through
691
                    // the TrackingNow implementation)
692
12
                    break;
693
                }
694
            }
695
        }
696

            
697
        // Check if it's time to schedule any reuploads.
698
100
        for period in reupload_periods {
699
8
            if self.mark_dirty(&period) {
700
8
                debug!(
701
                    time_period=?period,
702
                    "descriptor reupload timer elapsed; scheduling reupload",
703
                );
704
8
                self.update_publish_status_unless_rate_lim(PublishStatus::UploadScheduled)
705
8
                    .await?;
706
            }
707
        }
708

            
709
92
        select_biased! {
710
92
            res = self.upload_task_complete_rx.next().fuse() => {
711
12
                let Some(upload_res) = res else {
712
                    return Ok(ShutdownStatus::Terminate);
713
                };
714

            
715
12
                self.handle_upload_results(upload_res);
716
12
                self.upload_result_to_svc_status()?;
717
            },
718
92
            () = upload_rate_lim.wait_for_earliest(&self.imm.runtime).fuse() => {
719
                self.expire_rate_limit().await?;
720
            },
721
92
            () = reupload_tracking.wait_for_earliest(&self.imm.runtime).fuse() => {
722
                // Run another iteration, executing run_once again. This time, we will remove the
723
                // expired reupload from self.reupload_timers, mark the descriptor dirty for all
724
                // relevant HsDirs, and schedule the upload by setting our status to
725
                // UploadScheduled.
726
8
                return Ok(ShutdownStatus::Continue);
727
            },
728
92
            netdir_event = netdir_events.next().fuse() => {
729
                let Some(netdir_event) = netdir_event else {
730
                    debug!("netdir event stream ended");
731
                    return Ok(ShutdownStatus::Terminate);
732
                };
733

            
734
                if !matches!(netdir_event, DirEvent::NewConsensus) {
735
                    return Ok(ShutdownStatus::Continue);
736
                };
737

            
738
                // The consensus changed. Grab a new NetDir.
739
                let netdir = match self.dir_provider.netdir(Timeliness::Timely) {
740
                    Ok(y) => y,
741
                    Err(e) => {
742
                        error_report!(e, "HS service {}: netdir unavailable. Retrying...", self.imm.nickname);
743
                        // Hopefully a netdir will appear in the future.
744
                        // in the meantime, suspend operations.
745
                        //
746
                        // TODO (#1218): there is a bug here: we stop reading on our inputs
747
                        // including eg publish_status_rx, but it is our job to log some of
748
                        // these things.  While we are waiting for a netdir, all those messages
749
                        // are "stuck"; they'll appear later, with misleading timestamps.
750
                        //
751
                        // Probably this should be fixed by moving the logging
752
                        // out of the reactor, where it won't be blocked.
753
                        self.dir_provider.wait_for_netdir(Timeliness::Timely)
754
                            .await?
755
                    }
756
                };
757
                let relevant_periods = netdir.hs_all_time_periods();
758
                self.handle_consensus_change(netdir).await?;
759
                expire_publisher_keys(
760
                    &self.imm.keymgr,
761
                    &self.imm.nickname,
762
                    &relevant_periods,
763
                ).unwrap_or_else(|e| {
764
                    error_report!(e, "failed to remove expired keys");
765
                });
766
            }
767
92
            update = self.ipt_watcher.await_update().fuse() => {
768
8
                if self.handle_ipt_change(update).await? == ShutdownStatus::Terminate {
769
                    return Ok(ShutdownStatus::Terminate);
770
8
                }
771
            },
772
92
            config = self.config_rx.next().fuse() => {
773
8
                let Some(config) = config else {
774
                    return Ok(ShutdownStatus::Terminate);
775
                };
776

            
777
8
                self.handle_svc_config_change(&config).await?;
778
            },
779
92
            res = self.key_dirs_rx.next().fuse() => {
780
8
                let Some(event) = res else {
781
                    return Ok(ShutdownStatus::Terminate);
782
                };
783

            
784
8
                while let Some(_ignore) = self.key_dirs_rx.try_recv() {
785
                    // Discard other events, so that we only reload once.
786
                }
787

            
788
8
                self.handle_key_dirs_change(event).await?;
789
            }
790
92
            should_upload = self.publish_status_rx.next().fuse() => {
791
40
                let Some(should_upload) = should_upload else {
792
                    return Ok(ShutdownStatus::Terminate);
793
                };
794

            
795
                // Our PublishStatus changed -- are we ready to publish?
796
40
                if should_upload == PublishStatus::UploadScheduled {
797
16
                    self.update_publish_status_unless_waiting(PublishStatus::Idle).await?;
798
16
                    self.upload_all().await?;
799
24
                }
800
            }
801
        }
802

            
803
76
        Ok(ShutdownStatus::Continue)
804
84
    }
805

            
806
    /// Returns the current status of the publisher
807
156
    fn status(&self) -> PublishStatus {
808
156
        *self.publish_status_rx.borrow()
809
156
    }
810

            
811
    /// Handle a batch of upload outcomes,
812
    /// possibly updating the status of the descriptor for the corresponding HSDirs.
813
12
    fn handle_upload_results(&self, results: TimePeriodUploadResult) {
814
12
        let mut inner = self.inner.lock().expect("poisoned lock");
815
12
        let inner = &mut *inner;
816
12

            
817
12
        // Check which time period these uploads pertain to.
818
12
        let period = inner
819
12
            .time_periods
820
12
            .iter_mut()
821
12
            .find(|ctx| ctx.params.time_period() == results.time_period);
822

            
823
12
        let Some(period) = period else {
824
            // The uploads were for a time period that is no longer relevant, so we
825
            // can ignore the result.
826
            return;
827
        };
828

            
829
        // We will need to reupload this descriptor at at some point, so we pick
830
        // a random time between 60 minutes and 120 minutes in the future.
831
        //
832
        // See https://spec.torproject.org/rend-spec/deriving-keys.html#WHEN-HSDESC
833
12
        let mut rng = self.imm.mockable.thread_rng();
834
12
        // TODO SPEC: Control republish period using a consensus parameter?
835
12
        let minutes = rng.gen_range_checked(60..=120).expect("low > high?!");
836
12
        let duration = Duration::from_secs(minutes * 60);
837
12
        let reupload_when = self.imm.runtime.now() + duration;
838
12
        let time_period = period.params.time_period();
839
12

            
840
12
        info!(
841
            time_period=?time_period,
842
            "reuploading descriptor in {}",
843
            humantime::format_duration(duration),
844
        );
845

            
846
12
        inner.reupload_timers.push(ReuploadTimer {
847
12
            period: time_period,
848
12
            when: reupload_when,
849
12
        });
850
12

            
851
12
        let mut upload_results = vec![];
852
108
        for upload_res in results.hsdir_result {
853
96
            let relay = period
854
96
                .hs_dirs
855
96
                .iter_mut()
856
432
                .find(|(relay_ids, _status)| relay_ids == &upload_res.relay_ids);
857

            
858
96
            let Some((_relay, status)): Option<&mut (RelayIds, _)> = relay else {
859
                // This HSDir went away, so the result doesn't matter.
860
                // Continue processing the rest of the results
861
                continue;
862
            };
863

            
864
96
            if upload_res.upload_res.is_ok() {
865
96
                let update_last_successful = match period.last_successful {
866
4
                    None => true,
867
92
                    Some(counter) => counter <= upload_res.revision_counter,
868
                };
869

            
870
96
                if update_last_successful {
871
96
                    period.last_successful = Some(upload_res.revision_counter);
872
96
                    // TODO (#1098): Is it possible that this won't update the statuses promptly
873
96
                    // enough. For example, it's possible for the reactor to see a Dirty descriptor
874
96
                    // and start an upload task for a descriptor has already been uploaded (or is
875
96
                    // being uploaded) in another task, but whose upload results have not yet been
876
96
                    // processed.
877
96
                    //
878
96
                    // This is probably made worse by the fact that the statuses are updated in
879
96
                    // batches (grouped by time period), rather than one by one as the upload tasks
880
96
                    // complete (updating the status involves locking the inner mutex, and I wanted
881
96
                    // to minimize the locking/unlocking overheads). I'm not sure handling the
882
96
                    // updates in batches was the correct decision here.
883
96
                    *status = DescriptorStatus::Clean;
884
96
                }
885
            }
886

            
887
96
            upload_results.push(upload_res);
888
        }
889

            
890
12
        period.set_upload_results(upload_results);
891
12
    }
892

            
893
    /// Maybe update our list of HsDirs.
894
    async fn handle_consensus_change(&mut self, netdir: Arc<NetDir>) -> Result<(), FatalError> {
895
        trace!("the consensus has changed; recomputing HSDirs");
896

            
897
        let _old: Option<Arc<NetDir>> = self.replace_netdir(netdir);
898

            
899
        self.recompute_hs_dirs()?;
900
        self.update_publish_status_unless_waiting(PublishStatus::UploadScheduled)
901
            .await?;
902

            
903
        // If the time period has changed, some of our upload results may now be irrelevant,
904
        // so we might need to update our status (for example, if our uploads are
905
        // for a no-longer-relevant time period, it means we might be able to update
906
        // out status from "degraded" to "running")
907
        self.upload_result_to_svc_status()?;
908

            
909
        Ok(())
910
    }
911

            
912
    /// Recompute the HsDirs for all relevant time periods.
913
    fn recompute_hs_dirs(&self) -> Result<(), FatalError> {
914
        let mut inner = self.inner.lock().expect("poisoned lock");
915
        let inner = &mut *inner;
916

            
917
        let netdir = Arc::clone(
918
            inner
919
                .netdir
920
                .as_ref()
921
                .ok_or_else(|| internal!("started upload task without a netdir"))?,
922
        );
923

            
924
        // Update our list of relevant time periods.
925
        let new_time_periods = self.compute_time_periods(&netdir, &inner.time_periods)?;
926
        inner.time_periods = new_time_periods;
927

            
928
        Ok(())
929
    }
930

            
931
    /// Compute the [`TimePeriodContext`]s for the time periods from the specified [`NetDir`].
932
    ///
933
    /// The specified `time_periods` are used to preserve the `DescriptorStatus` of the
934
    /// HsDirs where possible.
935
8
    fn compute_time_periods(
936
8
        &self,
937
8
        netdir: &Arc<NetDir>,
938
8
        time_periods: &[TimePeriodContext],
939
8
    ) -> Result<Vec<TimePeriodContext>, FatalError> {
940
8
        netdir
941
8
            .hs_all_time_periods()
942
8
            .iter()
943
8
            .map(|params| {
944
8
                let period = params.time_period();
945
8
                let blind_id_kp =
946
8
                    read_blind_id_keypair(&self.imm.keymgr, &self.imm.nickname, period)?
947
                        // Note: for now, read_blind_id_keypair cannot return Ok(None).
948
                        // It's supposed to return Ok(None) if we're in offline hsid mode,
949
                        // but that might change when we do #1194
950
8
                        .ok_or_else(|| internal!("offline hsid mode not supported"))?;
951

            
952
8
                let blind_id: HsBlindIdKey = (&blind_id_kp).into();
953

            
954
                // If our previous `TimePeriodContext`s also had an entry for `period`, we need to
955
                // preserve the `DescriptorStatus` of its HsDirs. This helps prevent unnecessarily
956
                // publishing the descriptor to the HsDirs that already have it (the ones that are
957
                // marked with DescriptorStatus::Clean).
958
                //
959
                // In other words, we only want to publish to those HsDirs that
960
                //   * are part of a new time period (which we have never published the descriptor
961
                //   for), or
962
                //   * have just been added to the ring of a time period we already knew about
963
8
                if let Some(ctx) = time_periods
964
8
                    .iter()
965
8
                    .find(|ctx| ctx.params.time_period() == period)
966
                {
967
                    TimePeriodContext::new(
968
                        params.clone(),
969
                        blind_id.into(),
970
                        netdir,
971
                        ctx.hs_dirs.iter(),
972
                        ctx.upload_results.clone(),
973
                    )
974
                } else {
975
                    // Passing an empty iterator here means all HsDirs in this TimePeriodContext
976
                    // will be marked as dirty, meaning we will need to upload our descriptor to them.
977
8
                    TimePeriodContext::new(
978
8
                        params.clone(),
979
8
                        blind_id.into(),
980
8
                        netdir,
981
8
                        iter::empty(),
982
8
                        vec![],
983
8
                    )
984
                }
985
8
            })
986
8
            .collect::<Result<Vec<TimePeriodContext>, FatalError>>()
987
8
    }
988

            
989
    /// Replace the old netdir with the new, returning the old.
990
    fn replace_netdir(&self, new_netdir: Arc<NetDir>) -> Option<Arc<NetDir>> {
991
        self.inner
992
            .lock()
993
            .expect("poisoned lock")
994
            .netdir
995
            .replace(new_netdir)
996
    }
997

            
998
    /// Replace our view of the service config with `new_config` if `new_config` contains changes
999
    /// that would cause us to generate a new descriptor.
8
    fn replace_config_if_changed(&self, new_config: Arc<OnionServiceConfigPublisherView>) -> bool {
8
        let mut inner = self.inner.lock().expect("poisoned lock");
8
        let old_config = &mut inner.config;
8

            
8
        // The fields we're interested in haven't changed, so there's no need to update
8
        // `inner.config`.
8
        if *old_config == new_config {
8
            return false;
        }
        let log_change = match (
            old_config.restricted_discovery.enabled,
            new_config.restricted_discovery.enabled,
        ) {
            (true, false) => Some("Disabling restricted discovery mode"),
            (false, true) => Some("Enabling restricted discovery mode"),
            _ => None,
        };
        if let Some(msg) = log_change {
            info!(nickname=%self.imm.nickname, "{}", msg);
        }
        let _old: Arc<OnionServiceConfigPublisherView> = std::mem::replace(old_config, new_config);
        true
8
    }
    /// Recreate the FileWatcher for watching the restricted discovery key_dirs.
16
    fn update_file_watcher(&self) {
16
        let mut inner = self.inner.lock().expect("poisoned lock");
16
        if inner.config.restricted_discovery.watch_configuration() {
            debug!("The restricted_discovery.key_dirs have changed, updating file watcher");
            let mut watcher = FileWatcher::builder(self.imm.runtime.clone());
            let dirs = inner.config.restricted_discovery.key_dirs().clone();
            watch_dirs(&mut watcher, &dirs, &self.path_resolver);
            let watcher = watcher
                .start_watching(self.key_dirs_tx.clone())
                .map_err(|e| {
                    // TODO: update the publish status (see also the module-level TODO about this).
                    error_report!(e, "Cannot set file watcher");
                })
                .ok();
            inner.file_watcher = watcher;
        } else {
16
            if inner.file_watcher.is_some() {
                debug!("removing key_dirs watcher");
16
            }
16
            inner.file_watcher = None;
        }
16
    }
    /// Read the intro points from `ipt_watcher`, and decide whether we're ready to start
    /// uploading.
8
    fn note_ipt_change(&self) -> PublishStatus {
8
        let mut ipts = self.ipt_watcher.borrow_for_publish();
8
        match ipts.ipts.as_mut() {
8
            Some(_ipts) => PublishStatus::UploadScheduled,
            None => PublishStatus::AwaitingIpts,
        }
8
    }
    /// Update our list of introduction points.
8
    async fn handle_ipt_change(
8
        &mut self,
8
        update: Option<Result<(), crate::FatalError>>,
8
    ) -> Result<ShutdownStatus, FatalError> {
8
        trace!(nickname=%self.imm.nickname, "received IPT change notification from IPT manager");
8
        match update {
            Some(Ok(())) => {
8
                let should_upload = self.note_ipt_change();
8
                debug!(nickname=%self.imm.nickname, "the introduction points have changed");
8
                self.mark_all_dirty();
8
                self.update_publish_status_unless_rate_lim(should_upload)
8
                    .await?;
8
                Ok(ShutdownStatus::Continue)
            }
            Some(Err(e)) => Err(e),
            None => {
                debug!(nickname=%self.imm.nickname, "received shut down signal from IPT manager");
                Ok(ShutdownStatus::Terminate)
            }
        }
8
    }
    /// Update the `PublishStatus` of the reactor with `new_state`,
    /// unless the current state is `AwaitingIpts`.
16
    async fn update_publish_status_unless_waiting(
16
        &mut self,
16
        new_state: PublishStatus,
16
    ) -> Result<(), FatalError> {
16
        // Only update the state if we're not waiting for intro points.
16
        if self.status() != PublishStatus::AwaitingIpts {
16
            self.update_publish_status(new_state).await?;
        }
16
        Ok(())
16
    }
    /// Update the `PublishStatus` of the reactor with `new_state`,
    /// unless the current state is `RateLimited`.
16
    async fn update_publish_status_unless_rate_lim(
16
        &mut self,
16
        new_state: PublishStatus,
16
    ) -> Result<(), FatalError> {
        // We can't exit this state until the rate-limit expires.
16
        if !matches!(self.status(), PublishStatus::RateLimited(_)) {
16
            self.update_publish_status(new_state).await?;
        }
16
        Ok(())
16
    }
    /// Unconditionally update the `PublishStatus` of the reactor with `new_state`.
32
    async fn update_publish_status(&mut self, new_state: PublishStatus) -> Result<(), Bug> {
32
        let onion_status = match new_state {
16
            PublishStatus::Idle => None,
            PublishStatus::UploadScheduled
            | PublishStatus::AwaitingIpts
16
            | PublishStatus::RateLimited(_) => Some(State::Bootstrapping),
        };
32
        if let Some(onion_status) = onion_status {
16
            self.imm.status_tx.send(onion_status, None);
16
        }
32
        trace!(
            "publisher reactor status change: {:?} -> {:?}",
            self.status(),
            new_state
        );
32
        self.publish_status_tx.send(new_state).await.map_err(
32
            |_: postage::sink::SendError<_>| internal!("failed to send upload notification?!"),
32
        )?;
32
        Ok(())
32
    }
    /// Update the onion svc status based on the results of the last descriptor uploads.
12
    fn upload_result_to_svc_status(&self) -> Result<(), FatalError> {
12
        let inner = self.inner.lock().expect("poisoned lock");
12
        let netdir = inner
12
            .netdir
12
            .as_ref()
12
            .ok_or_else(|| internal!("handling upload results without netdir?!"))?;
12
        let (state, err) = upload_result_state(netdir, &inner.time_periods);
12
        self.imm.status_tx.send(state, err);
12

            
12
        Ok(())
12
    }
    /// Update the descriptors based on the config change.
8
    async fn handle_svc_config_change(
8
        &mut self,
8
        config: &OnionServiceConfig,
8
    ) -> Result<(), FatalError> {
8
        let new_config = Arc::new(config.into());
8
        if self.replace_config_if_changed(Arc::clone(&new_config)) {
            self.update_file_watcher();
            self.update_authorized_clients_if_changed().await?;
            info!(nickname=%self.imm.nickname, "Config has changed, generating a new descriptor");
            self.mark_all_dirty();
            // Schedule an upload, unless we're still waiting for IPTs.
            self.update_publish_status_unless_waiting(PublishStatus::UploadScheduled)
                .await?;
8
        }
8
        Ok(())
8
    }
    /// Update the descriptors based on a restricted discovery key_dirs change.
    ///
    /// If the authorized clients from the [`RestrictedDiscoveryConfig`] have changed,
    /// this marks the descriptor as dirty for all time periods,
    /// and schedules a reupload.
8
    async fn handle_key_dirs_change(&mut self, event: FileEvent) -> Result<(), FatalError> {
8
        debug!("The configured key_dirs have changed");
8
        match event {
8
            FileEvent::Rescan | FileEvent::FileChanged => {
8
                // These events are handled in the same way, by re-reading the keys from disk
8
                // and republishing the descriptor if necessary
8
            }
            _ => return Err(internal!("file watcher event {event:?}").into()),
        };
        // Update the file watcher, in case the change was triggered by a key_dir move.
8
        self.update_file_watcher();
8

            
8
        if self.update_authorized_clients_if_changed().await? {
            self.mark_all_dirty();
            // Schedule an upload, unless we're still waiting for IPTs.
            self.update_publish_status_unless_waiting(PublishStatus::UploadScheduled)
                .await?;
8
        }
8
        Ok(())
8
    }
    /// Recreate the authorized_clients based on the current config.
    ///
    /// Returns `true` if the authorized clients have changed.
8
    async fn update_authorized_clients_if_changed(&mut self) -> Result<bool, FatalError> {
8
        let mut inner = self.inner.lock().expect("poisoned lock");
8
        let authorized_clients =
8
            Self::read_authorized_clients(&inner.config.restricted_discovery, &self.path_resolver);
8

            
8
        let clients = &mut inner.authorized_clients;
8
        let changed = clients.as_ref() != authorized_clients.as_ref();
8

            
8
        if changed {
            info!("The restricted discovery mode authorized clients have changed");
            *clients = authorized_clients;
8
        }
8
        Ok(changed)
8
    }
    /// Read the authorized `RestrictedDiscoveryKeys` from `config`.
16
    fn read_authorized_clients(
16
        config: &RestrictedDiscoveryConfig,
16
        path_resolver: &CfgPathResolver,
16
    ) -> Option<Arc<RestrictedDiscoveryKeys>> {
16
        let authorized_clients = config.read_keys(path_resolver);
16
        if matches!(authorized_clients.as_ref(), Some(c) if c.is_empty()) {
            warn!(
                "Running in restricted discovery mode, but we have no authorized clients. Service will be unreachable"
            );
16
        }
16
        authorized_clients.map(Arc::new)
16
    }
    /// Mark the descriptor dirty for all time periods.
8
    fn mark_all_dirty(&self) {
8
        trace!("marking the descriptor dirty for all time periods");
8
        self.inner
8
            .lock()
8
            .expect("poisoned lock")
8
            .time_periods
8
            .iter_mut()
8
            .for_each(|tp| tp.mark_all_dirty());
8
    }
    /// Mark the descriptor dirty for the specified time period.
    ///
    /// Returns `true` if the specified period is still relevant, and `false` otherwise.
8
    fn mark_dirty(&self, period: &TimePeriod) -> bool {
8
        let mut inner = self.inner.lock().expect("poisoned lock");
8
        let period_ctx = inner
8
            .time_periods
8
            .iter_mut()
8
            .find(|tp| tp.params.time_period() == *period);
8

            
8
        match period_ctx {
8
            Some(ctx) => {
8
                trace!(time_period=?period, "marking the descriptor dirty");
8
                ctx.mark_all_dirty();
8
                true
            }
            None => false,
        }
8
    }
    /// Try to upload our descriptor to the HsDirs that need it.
    ///
    /// If we've recently uploaded some descriptors, we return immediately and schedule the upload
    /// to happen after [`UPLOAD_RATE_LIM_THRESHOLD`].
    ///
    /// Failed uploads are retried
    /// (see [`upload_descriptor_with_retries`](Reactor::upload_descriptor_with_retries)).
    ///
    /// If restricted discovery mode is enabled and there are no authorized clients,
    /// we abort the upload and set our status to [`State::Broken`].
    //
    // Note: a broken restricted discovery config won't prevent future uploads from being scheduled
    // (for example if the IPTs change),
    // which can can cause the publisher's status to oscillate between `Bootstrapping` and `Broken`.
    // TODO: we might wish to refactor the publisher to be more sophisticated about this.
    //
    /// For each current time period, we spawn a task that uploads the descriptor to
    /// all the HsDirs on the HsDir ring of that time period.
    /// Each task shuts down on completion, or when the reactor is dropped.
    ///
    /// Each task reports its upload results (`TimePeriodUploadResult`)
    /// via the `upload_task_complete_tx` channel.
    /// The results are received and processed in the main loop of the reactor.
    ///
    /// Returns an error if it fails to spawn a task, or if an internal error occurs.
16
    async fn upload_all(&mut self) -> Result<(), FatalError> {
16
        trace!("starting descriptor upload task...");
        // Abort the upload entirely if we have an empty list of authorized clients
16
        let authorized_clients = match self.authorized_clients() {
16
            Ok(authorized_clients) => authorized_clients,
            Err(e) => {
                error_report!(e, "aborting upload");
                self.imm.status_tx.send_broken(e.clone());
                // Returning an error would shut down the reactor, so we have to return Ok here.
                return Ok(());
            }
        };
16
        let last_uploaded = self.inner.lock().expect("poisoned lock").last_uploaded;
16
        let now = self.imm.runtime.now();
        // Check if we should rate-limit this upload.
16
        if let Some(ts) = last_uploaded {
8
            let duration_since_upload = now.duration_since(ts);
8

            
8
            if duration_since_upload < UPLOAD_RATE_LIM_THRESHOLD {
                return Ok(self.start_rate_limit(UPLOAD_RATE_LIM_THRESHOLD).await?);
8
            }
8
        }
16
        let mut inner = self.inner.lock().expect("poisoned lock");
16
        let inner = &mut *inner;
16

            
16
        let _ = inner.last_uploaded.insert(now);
16
        for period_ctx in inner.time_periods.iter_mut() {
16
            let upload_task_complete_tx = self.upload_task_complete_tx.clone();
16

            
16
            // Figure out which HsDirs we need to upload the descriptor to (some of them might already
16
            // have our latest descriptor, so we filter them out).
16
            let hs_dirs = period_ctx
16
                .hs_dirs
16
                .iter()
128
                .filter_map(|(relay_id, status)| {
128
                    if *status == DescriptorStatus::Dirty {
128
                        Some(relay_id.clone())
                    } else {
                        None
                    }
128
                })
16
                .collect::<Vec<_>>();
16

            
16
            if hs_dirs.is_empty() {
                trace!("the descriptor is clean for all HSDirs. Nothing to do");
                return Ok(());
16
            }
16

            
16
            let time_period = period_ctx.params.time_period();
            // This scope exists because rng is not Send, so it needs to fall out of scope before we
            // await anything.
16
            let netdir = Arc::clone(
16
                inner
16
                    .netdir
16
                    .as_ref()
16
                    .ok_or_else(|| internal!("started upload task without a netdir"))?,
            );
16
            let imm = Arc::clone(&self.imm);
16
            let ipt_upload_view = self.ipt_watcher.upload_view();
16
            let config = Arc::clone(&inner.config);
16
            let authorized_clients = authorized_clients.clone();
16

            
16
            trace!(nickname=%self.imm.nickname, time_period=?time_period,
                "spawning upload task"
            );
16
            let params = period_ctx.params.clone();
16
            let shutdown_rx = self.shutdown_tx.subscribe();
            // Spawn a task to upload the descriptor to all HsDirs of this time period.
            //
            // This task will shut down when the reactor is dropped (i.e. when shutdown_rx is
            // dropped).
16
            let _handle: () = self
16
                .imm
16
                .runtime
16
                .spawn(async move {
16
                    if let Err(e) = Self::upload_for_time_period(
16
                        hs_dirs,
16
                        &netdir,
16
                        config,
16
                        params,
16
                        Arc::clone(&imm),
16
                        ipt_upload_view.clone(),
16
                        authorized_clients.clone(),
16
                        upload_task_complete_tx,
16
                        shutdown_rx,
16
                    )
16
                    .await
                    {
                        error_report!(
                            e,
                            "descriptor upload failed for HS service {} and time period {:?}",
                            imm.nickname,
                            time_period
                        );
12
                    }
16
                })
16
                .map_err(|e| FatalError::from_spawn("upload_for_time_period task", e))?;
        }
16
        Ok(())
16
    }
    /// Upload the descriptor for the time period specified in `params`.
    ///
    /// Failed uploads are retried
    /// (see [`upload_descriptor_with_retries`](Reactor::upload_descriptor_with_retries)).
    #[allow(clippy::too_many_arguments)] // TODO: refactor
16
    async fn upload_for_time_period(
16
        hs_dirs: Vec<RelayIds>,
16
        netdir: &Arc<NetDir>,
16
        config: Arc<OnionServiceConfigPublisherView>,
16
        params: HsDirParams,
16
        imm: Arc<Immutable<R, M>>,
16
        ipt_upload_view: IptsPublisherUploadView,
16
        authorized_clients: Option<Arc<RestrictedDiscoveryKeys>>,
16
        mut upload_task_complete_tx: mpsc::Sender<TimePeriodUploadResult>,
16
        shutdown_rx: broadcast::Receiver<Void>,
16
    ) -> Result<(), FatalError> {
16
        let time_period = params.time_period();
16
        trace!(time_period=?time_period, "uploading descriptor to all HSDirs for this time period");
16
        let hsdir_count = hs_dirs.len();
        /// An error returned from an upload future.
        //
        // Exhaustive, because this is a private type.
        #[derive(Clone, Debug, thiserror::Error)]
        enum PublishError {
            /// The upload was aborted because there are no IPTs.
            ///
            /// This happens because of an inevitable TOCTOU race, where after being notified by
            /// the IPT manager that the IPTs have changed (via `self.ipt_watcher.await_update`),
            /// we find out there actually are no IPTs, so we can't build the descriptor.
            ///
            /// This is a special kind of error that interrupts the current upload task, and is
            /// logged at `debug!` level rather than `warn!` or `error!`.
            ///
            /// Ideally, this shouldn't happen very often (if at all).
            #[error("No IPTs")]
            NoIpts,
            /// The reactor has shut down
            #[error("The reactor has shut down")]
            Shutdown,
            /// An fatal error.
            #[error("{0}")]
            Fatal(#[from] FatalError),
        }
16
        let upload_results = futures::stream::iter(hs_dirs)
128
            .map(|relay_ids| {
128
                let netdir = netdir.clone();
128
                let config = Arc::clone(&config);
128
                let imm = Arc::clone(&imm);
128
                let ipt_upload_view = ipt_upload_view.clone();
128
                let authorized_clients = authorized_clients.clone();
128
                let params = params.clone();
128
                let mut shutdown_rx = shutdown_rx.clone();
128

            
128
                let ed_id = relay_ids
128
                    .rsa_identity()
128
                    .map(|id| id.to_string())
128
                    .unwrap_or_else(|| "unknown".into());
128
                let rsa_id = relay_ids
128
                    .rsa_identity()
128
                    .map(|id| id.to_string())
128
                    .unwrap_or_else(|| "unknown".into());
128
                async move {
128
                    let run_upload = |desc| async {
128
                        let Some(hsdir) = netdir.by_ids(&relay_ids) else {
                            // This should never happen (all of our relay_ids are from the stored
                            // netdir).
                            let err =
                                "tried to upload descriptor to relay not found in consensus?!";
                            warn!(
                                nickname=%imm.nickname, hsdir_id=%ed_id, hsdir_rsa_id=%rsa_id,
                                "{err}"
                            );
                            return Err(internal!("{err}").into());
                        };
128
                        Self::upload_descriptor_with_retries(
128
                            desc,
128
                            &netdir,
128
                            &hsdir,
128
                            &ed_id,
128
                            &rsa_id,
128
                            Arc::clone(&imm),
128
                        )
128
                        .await
224
                    };
                    // How long until we're supposed to time out?
128
                    let worst_case_end = imm.runtime.now() + OVERALL_UPLOAD_TIMEOUT;
                    // We generate a new descriptor before _each_ HsDir upload. This means each
                    // HsDir could, in theory, receive a different descriptor (not just in terms of
                    // revision-counters, but also with a different set of IPTs). It may seem like
                    // this could lead to some HsDirs being left with an outdated descriptor, but
                    // that's not the case: after the upload completes, the publisher will be
                    // notified by the ipt_watcher of the IPT change event (if there was one to
                    // begin with), which will trigger another upload job.
128
                    let hsdesc = {
                        // This scope is needed because the ipt_set MutexGuard is not Send, so it
                        // needs to fall out of scope before the await point below
128
                        let mut ipt_set = ipt_upload_view.borrow_for_publish();