1
//! Entry point of a Tor relay that is the [`TorRelay`] objects
2

            
3
use std::net::SocketAddr;
4
use std::num::NonZero;
5
use std::path::{Path, PathBuf};
6
use std::sync::{Arc, Weak};
7

            
8
use anyhow::Context;
9
use hickory_net::runtime::TokioRuntimeProvider;
10
use hickory_resolver::{Resolver, ResolverBuilder};
11
use tokio::task::JoinSet;
12
#[cfg(unix)]
13
use tracing::warn;
14
use tracing::{debug, info};
15

            
16
use fs_mistrust::Mistrust;
17
use tor_async_utils::bw_pool::{BandwidthPool, BandwidthRefiller};
18
use tor_basic_utils::iter_join;
19
use tor_cell::relaycell::RelayCmd;
20
use tor_chanmgr::{ChanMgr, ChanMgrConfig, Dormancy};
21
use tor_config_path::CfgPathResolver;
22
use tor_dircommon::authority::AuthorityContacts;
23
use tor_dircommon::config::{DirTolerance, DownloadScheduleConfig};
24
use tor_dirmgr::{DirMgrConfig, DirPlugin};
25
use tor_dirserver::mirror::{DirMirror, DirMirrorWithBackend};
26
use tor_keymgr::{ArtiNativeKeystore, KeyMgr, KeyMgrBuilder};
27
use tor_memquota::MemoryQuotaTracker;
28
use tor_netdir::params::NetParameters;
29
use tor_persist::state_dir::StateDirectory;
30
use tor_persist::{FsStateMgr, StateMgr};
31
use tor_proto::relay::{CircuitIncomingStreamReceiver, CreateRequestHandler};
32
use tor_rtcompat::{NetStreamProvider, Runtime};
33

            
34
use crate::client::RelayClient;
35
use crate::config::{DnsConfig, TorRelayConfig};
36
use crate::stream::RequestFilter;
37
use crate::stream::dns::resolver::DnsResolverReactor;
38
use crate::tasks::channel::build_circ_net_params;
39
use crate::tasks::crypto::InitKeyMaterial;
40

            
41
use futures::channel::mpsc;
42

            
43
// TODO(relay): this is in the client module, but not client-specific
44
use tor_proto::client::stream::DataStream;
45

            
46
/// Smallest grant of a bandwidth pool which is one cell max payload.
47
// TODO(relay): Should this be here? I wonder if we should have a file solely holding
48
// these magic constant for the relay or getting it from tor-proto?
49
const BW_MIN_GRANT: u64 = 514;
50

            
51
/// An initialized but unbootstrapped relay.
52
///
53
/// This intentionally does not have access to the runtime to prevent it from doing network io.
54
///
55
/// The idea is that we can build up the relay's components in an `InertTorRelay` without a runtime,
56
/// and then call `init()` on it and provide a runtime to turn it into a network-capable relay.
57
/// This gives us two advantages:
58
///
59
/// - We can initialize the internal data structures in the `InertTorRelay` (load the keystores,
60
///   configure memquota, etc), which leaves `TorRelay` to just "running" the relay (bootstrapping,
61
///   setting up listening sockets, etc). We don't need to combine the initialization and "running
62
///   the relay" all within the same object.
63
/// - We will likely want to share some of arti's key management subcommands in the future.
64
///   arti-client has an `InertTorClient` which is used so that arti subcommands can access the
65
///   keystore. If we do a similar thing here in arti-relay in the future, it might be nice to have
66
///   an `InertTorRelay` which has these internal data structures, but doesn't need a runtime or
67
///   have any networking capabilities.
68
///
69
/// Time will tell if this ends up being a bad design decision in practice, and we can always change
70
/// it later.
71
pub(crate) struct InertTorRelay {
72
    /// The configuration options for the relay.
73
    config: TorRelayConfig,
74

            
75
    /// The configuration options for the client's directory manager.
76
    dirmgr_config: DirMgrConfig,
77

            
78
    /// Path resolver for expanding variables in [`CfgPath`](tor_config_path::CfgPath)s.
79
    #[expect(unused)] // TODO RELAY remove
80
    path_resolver: CfgPathResolver,
81

            
82
    /// State directory path.
83
    ///
84
    /// The [`StateDirectory`] stored in `state_dir` doesn't seem to have a way of getting the state
85
    /// directory path, so we need to store a copy of the path here.
86
    #[expect(unused)] // TODO RELAY remove
87
    state_path: PathBuf,
88

            
89
    /// Relay's state directory.
90
    #[expect(unused)] // TODO RELAY remove
91
    state_dir: StateDirectory,
92

            
93
    /// Location on disk where we store persistent data.
94
    state_mgr: FsStateMgr,
95

            
96
    /// Key manager.
97
    keymgr: KeyMgr,
98
}
99

            
100
impl InertTorRelay {
101
    /// Create a new Tor relay with the given configuration.
102
    pub(crate) fn new(
103
        config: TorRelayConfig,
104
        path_resolver: CfgPathResolver,
105
    ) -> anyhow::Result<Self> {
106
        let state_path = config.storage.state_dir(&path_resolver)?;
107
        let cache_path = config.storage.cache_dir(&path_resolver)?;
108

            
109
        let state_dir = StateDirectory::new(&state_path, config.storage.permissions())
110
            .context("Failed to create `StateDirectory`")?;
111
        let state_mgr =
112
            FsStateMgr::from_path_and_mistrust(&state_path, config.storage.permissions())
113
                .context("Failed to create `FsStateMgr`")?;
114

            
115
        // Try to take state ownership early, so we'll know if we have it.
116
        // Note that this `try_lock()` may return `Ok` even if we can't acquire the lock.
117
        // (At this point we don't yet care if we have it.)
118
        let _ignore_status = state_mgr
119
            .try_lock()
120
            .context("Failed to try locking the state manager")?;
121

            
122
        let keymgr = Self::create_keymgr(&state_path, config.storage.permissions())
123
            .context("Failed to create key manager")?;
124

            
125
        // Disable CBT learning as the relay has no use for this. It prevents the client
126
        // to continously open testing circuits.
127
        //
128
        // TODO(relay): We disable this via an override of the consensus parameter. Could
129
        // be that the future we can do that explicitly?
130
        let mut override_net_params = tor_netdoc::doc::netstatus::NetParamValues::default();
131
        override_net_params.set("cbtdisabled".to_string(), 1);
132

            
133
        let dirmgr_config = DirMgrConfig {
134
            cache_dir: cache_path,
135
            cache_trust: config.storage.permissions().clone(),
136
            network: config.tor_network.clone(),
137
            schedule: Default::default(),
138
            tolerance: Default::default(),
139
            override_net_params,
140
            extensions: Default::default(),
141
        };
142

            
143
        Ok(Self {
144
            config,
145
            dirmgr_config,
146
            path_resolver,
147
            state_path,
148
            state_dir,
149
            state_mgr,
150
            keymgr,
151
        })
152
    }
153

            
154
    /// Connect the [`InertTorRelay`] to the Tor network.
155
    pub(crate) async fn init<R: Runtime>(self, runtime: R) -> anyhow::Result<TorRelay<R>> {
156
        // Attempt to generate any missing keys/cert from the KeyMgr.
157
        let init_key_material = crate::tasks::crypto::init_keys(&runtime, &self.keymgr)
158
            .context("Failed to generate keys")?;
159

            
160
        TorRelay::init(runtime, self, init_key_material).await
161
    }
162

            
163
    /// Create the [key manager](KeyMgr).
164
    fn create_keymgr(state_path: &Path, mistrust: &Mistrust) -> anyhow::Result<KeyMgr> {
165
        let key_store_dir = state_path.join("keystore");
166

            
167
        let persistent_store = ArtiNativeKeystore::from_path_and_mistrust(&key_store_dir, mistrust)
168
            .context("Failed to construct the native keystore")?;
169

            
170
        // Should only log fs paths at debug level or lower,
171
        // unless they're part of a diagnostic message.
172
        debug!("Using relay keystore from {key_store_dir:?}");
173

            
174
        let keymgr = KeyMgrBuilder::default()
175
            .primary_store(Box::new(persistent_store))
176
            .build()
177
            .context("Failed to build the 'KeyMgr'")?;
178

            
179
        // TODO: support C-tor keystore
180

            
181
        Ok(keymgr)
182
    }
183
}
184

            
185
/// Represent an active Relay on the Tor network.
186
pub(crate) struct TorRelay<R: Runtime> {
187
    /// Asynchronous runtime object.
188
    runtime: R,
189

            
190
    /// Memory quota tracker.
191
    #[expect(unused)] // TODO RELAY remove
192
    memquota: Arc<MemoryQuotaTracker>,
193

            
194
    /// A "client" used by relays to construct circuits.
195
    client: RelayClient<R>,
196

            
197
    /// The directory authorities that were either configured or the compiled-in defaults.
198
    ///
199
    /// We keep a copy here so we can pass it to the descriptor publisher task. These are not
200
    /// exposed by a [`tor_dirmgr::DirProvider`] hence why we keep that copy from the config.
201
    authorities: AuthorityContacts,
202

            
203
    /// Relay information used to build our descriptor.
204
    ///
205
    /// We keep a copy here from the config so we can pass it to the descriptor publisher task.
206
    desc_info: crate::tasks::descriptor::RouterDescInfo,
207

            
208
    /// The directory mirror object, used for handling BEGIN_DIR.
209
    dir_mirror: DirMirrorWithBackend<DirPlugin>,
210

            
211
    /// Channel manager, used by circuits etc.
212
    chanmgr: Arc<ChanMgr<R>>,
213

            
214
    /// Refillers of the global bandwidth pools. None if unlimited bandwidth.
215
    bw_refillers: Option<BandwidthRefillers>,
216

            
217
    /// Handles CREATE* requests on channels.
218
    ///
219
    /// Given to the [`ChanMgr`],
220
    /// which gives it to each channel.
221
    /// We can access this handler directly to update consensus parameters or keys.
222
    create_request_handler: Arc<CreateRequestHandler>,
223

            
224
    /// The receiver for the [`Stream`](futures::Stream)s of `IncomingStream` of all circuits.
225
    ///
226
    /// Receives one [`Stream`](futures::Stream) (of tor streams) per circuit.
227
    /// Each of these is handled in a new task.
228
    circuit_stream_rx: CircuitIncomingStreamReceiver,
229

            
230
    /// See [`InertTorRelay::keymgr`].
231
    keymgr: KeyMgr,
232

            
233
    /// Listening OR ports.
234
    or_listeners: Vec<<R as NetStreamProvider<SocketAddr>>::Listener>,
235

            
236
    /// The hickory stub resolver, used for building the DNS resolver reactor.
237
    //
238
    // TODO(relay): this should be optional, and only set to Some
239
    // if we're configured to run as an exit.
240
    //
241
    // Right now, because there is no exit config,
242
    // arti-relay unconditionally spawns the DNS resolver task,
243
    // and unconditionally accepts all RESOLVE.
244
    resolver: Arc<Resolver<TokioRuntimeProvider>>,
245
}
246

            
247
impl<R: Runtime> TorRelay<R> {
248
    /// Create a new Tor relay with the given [`runtime`][tor_rtcompat].
249
    ///
250
    /// We use this to initialize components, open sockets, etc.
251
    /// Doing work with these components should happen in [`TorRelay::run()`].
252
    ///
253
    /// Expected to be called from [`InertTorRelay::init()`].
254
    async fn init(
255
        runtime: R,
256
        inert: InertTorRelay,
257
        init_key_material: InitKeyMaterial,
258
    ) -> anyhow::Result<Self> {
259
        let memquota = MemoryQuotaTracker::new(&runtime, inert.config.system.memory.clone())
260
            .context("Failed to initialize memquota tracker")?;
261

            
262
        // Init the channel manager.
263
        let mut config = ChanMgrConfig::new(inert.config.channel.clone())
264
            .with_my_addrs(inert.config.relay.advertise.all_addr())
265
            .allow_any_addrs(inert.config.relay.testing.allow_channels_to_all_addrs)
266
            .with_auth_material(Arc::new(init_key_material.chan_auth_keys));
267

            
268
        // Global bandwidth rate limiting with one pool per direction. This is what C-tor
269
        // does as sharing a bw pool with both directions is usually not a great idea
270
        // because clogging one side then clogs the other side creating all sorts of side
271
        // channel possibilities or DoS vector.
272
        let bw = &inert.config.relay.bandwidth;
273
        let bw_refillers = if let (Some(rate), Some(burst)) = (bw.rate, bw.burst) {
274
            info!("Bandwidth rate limit per direction: rate {rate}/s, burst {burst}");
275
            let rate = u64::try_from(*rate).expect("bw rate to u64");
276
            let burst = u64::try_from(*burst).expect("bw burst to u64");
277
            let burst = NonZero::new(burst).expect("bw burst is zero");
278
            let (read_pool, read_refiller) = BandwidthPool::new(burst, BW_MIN_GRANT);
279
            let (write_pool, write_refiller) = BandwidthPool::new(burst, BW_MIN_GRANT);
280
            config = config.with_bandwidth_pools(read_pool, write_pool);
281
            Some(BandwidthRefillers {
282
                read: read_refiller,
283
                write: write_refiller,
284
                rate,
285
            })
286
        } else {
287
            info!("No bandwidth rate limit configured, bandwidth is unlimited");
288
            None
289
        };
290
        let chanmgr = Arc::new(
291
            ChanMgr::new(
292
                runtime.clone(),
293
                config,
294
                Dormancy::Active,
295
                // TODO: It seems wrong to start with the compiled-in defaults when we might have
296
                // a newer network status on disk that would provide a better initial value,
297
                // but `TorClient` does this too so let's not worry about it.
298
                &NetParameters::default(),
299
                memquota.clone(),
300
            )
301
            .context("Failed to build chan manager")?,
302
        );
303

            
304
        let authorities = inert.dirmgr_config.authorities().clone();
305
        let desc_info = crate::tasks::descriptor::RouterDescInfo {
306
            nickname: inert.config.relay.nickname.clone(),
307
            contact: inert.config.relay.contact.clone(),
308
            advertise: inert.config.relay.advertise.clone(),
309
            bandwidth: inert.config.relay.bandwidth.clone(),
310
        };
311

            
312
        // Init the relay's client.
313
        let client = RelayClient::new(
314
            runtime.clone(),
315
            Arc::clone(&chanmgr),
316
            &inert.config,
317
            &inert.config,
318
            inert.dirmgr_config,
319
            inert.state_mgr,
320
        )
321
        .context("Failed to construct the relay's client")?;
322

            
323
        // Circuit-related network status parameters.
324
        let circ_net_params = build_circ_net_params(client.dirmgr().params().as_ref().as_ref())
325
            .context("Failed to build circuit parameters for CREATE* request handler")?;
326

            
327
        // TODO(relay): add exit configuration, and update this to reject BEGIN and RESOLVE
328
        // if we are not configured to run as an exit
329
        let allow_incoming = &[RelayCmd::BEGIN, RelayCmd::BEGIN_DIR, RelayCmd::RESOLVE];
330

            
331
        // A handler that will process CREATE* requests on channels.
332
        let (create_request_handler, circuit_stream_rx) = CreateRequestHandler::new(
333
            Arc::downgrade(&chanmgr) as Weak<_>,
334
            circ_net_params,
335
            init_key_material.ntor_keys,
336
            Box::new(|| Box::new(RequestFilter::default()) as Box<_>),
337
            allow_incoming,
338
        );
339
        let create_request_handler = Arc::new(create_request_handler);
340

            
341
        // Configure the channel manager to handle CREATE* requests.
342
        //
343
        // We do this once, and can later update its network parameters and keys using the
344
        // `Arc` handle that we store.
345
        // The `ChanMgr` will hold an `Arc<CreateRequestHandler>` and
346
        // the `CreateRequestHandler` will hold a `Weak<ChanMgr>`.
347
        //
348
        // We could technically do something fancier by creating the `ChanMgr` and handler
349
        // inside an `Arc::new_cyclic()` and pass the handler as part of the `ChanMgrConfig`,
350
        // but the code becomes a mess.
351
        chanmgr
352
            .set_create_request_handler(Arc::clone(&create_request_handler))
353
            .context("Failed to set the CREATE* request handler")?;
354

            
355
        // We don't use any custom options on the listening socket.
356
        let listen_options = Default::default();
357

            
358
        // An iterator of `listen()` futures with some extra error handling.
359
        let or_listeners = inert.config.relay.listen.addrs().map(async |addr| {
360
            match runtime.listen(addr, &listen_options).await {
361
                Ok(x) => Some(Ok(x)),
362
                // If we don't support the address family (typically IPv6), only warn.
363
                #[cfg(unix)]
364
                Err(ref e) if e.raw_os_error() == Some(libc::EAFNOSUPPORT) => {
365
                    let message =
366
                        format!("Could not listen at {addr}: address family not supported");
367
                    if addr.is_ipv6() {
368
                        warn!("{message}");
369
                    } else {
370
                        // If we got `EAFNOSUPPORT` for a non-IPv6 address, then warn louder.
371
                        tor_error::warn_report!(e, "{message}");
372
                    }
373
                    None
374
                }
375
                Err(e) => {
376
                    Some(Err(e).with_context(|| format!("Failed to listen at address {addr}")))
377
                }
378
            }
379
        });
380

            
381
        // We await the futures sequentially rather than with something like `join_all` to make
382
        // errors more reproducible.
383
        let or_listeners = {
384
            let mut awaited_listeners = vec![];
385
            for listener in or_listeners {
386
                match listener.await {
387
                    Some(Ok(x)) => awaited_listeners.push(x),
388
                    Some(Err(e)) => return Err(e),
389
                    None => {}
390
                };
391
            }
392
            awaited_listeners
393
        };
394

            
395
        // Typically we would have returned with an error if we failed to listen on an address,
396
        // but we ignore `EAFNOSUPPORT` errors above, so it's possible that all failed with
397
        // `EAFNOSUPPORT` and we ended up here.
398
        if or_listeners.is_empty() {
399
            return Err(anyhow::anyhow!(
400
                "Could not listen at any OR port addresses: {}",
401
                iter_join(", ", inert.config.relay.listen.addrs()),
402
            ));
403
        }
404

            
405
        // TODO DIRMIRROR: Need a config for the DirMirror and should be same as our
406
        // TorRelay one.
407
        let path: PathBuf = PathBuf::from("/dev/null");
408
        let dir_mirror_authorities: AuthorityContacts = Default::default();
409
        let schedule: DownloadScheduleConfig = Default::default();
410
        let tolerance: DirTolerance = Default::default();
411

            
412
        let dir_mirror = DirMirror::new(path, dir_mirror_authorities, schedule, tolerance);
413

            
414
        // TODO: This is temporary until the directory mirror has support for downloading documents.
415
        let dir_mirror = DirMirrorWithBackend::new(dir_mirror, client.dirmgr_plugin().clone());
416

            
417
        let resolver = Arc::new(build_hickory_resolver(&inert.config)?);
418

            
419
        Ok(Self {
420
            runtime,
421
            memquota,
422
            client,
423
            authorities,
424
            desc_info,
425
            dir_mirror,
426
            chanmgr,
427
            bw_refillers,
428
            create_request_handler,
429
            keymgr: inert.keymgr,
430
            or_listeners,
431
            circuit_stream_rx,
432
            resolver,
433
        })
434
    }
435

            
436
    /// Run the actual relay.
437
    ///
438
    /// This only returns if something has gone wrong.
439
    /// Otherwise it runs forever.
440
    pub(crate) async fn run(self) -> anyhow::Result<void::Void> {
441
        let mut task_handles = JoinSet::new();
442

            
443
        // Channel housekeeping task.
444
        task_handles.spawn({
445
            let mut t = crate::tasks::ChannelHouseKeepingTask::new(&self.chanmgr);
446
            async move {
447
                t.start()
448
                    .await
449
                    .context("Failed to run channel house keeping task")
450
            }
451
        });
452

            
453
        // Launch the refillers of the global bandwidth pool if any.
454
        if let Some(bw_refillers) = self.bw_refillers {
455
            bw_refillers.spawn(&self.runtime, &mut task_handles);
456
        }
457

            
458
        // Update the CREATE* request handler when there are new network parameters.
459
        task_handles.spawn({
460
            let create_request_handler = Arc::clone(&self.create_request_handler);
461
            let dir_provider = Arc::clone(self.client.dirmgr());
462
            async {
463
                crate::tasks::channel::update_create_request_handler_netparams(
464
                    create_request_handler,
465
                    dir_provider as Arc<_>,
466
                )
467
                .await
468
                .context("Failed to run create request handler update task")
469
            }
470
        });
471

            
472
        // Listen for new Tor (OR) connections.
473
        task_handles.spawn({
474
            let runtime = self.runtime.clone();
475
            let chanmgr = Arc::clone(&self.chanmgr);
476
            async {
477
                // TODO: Should we give all tasks a `start` method?
478
                crate::tasks::listeners::or_listener(runtime, chanmgr, self.or_listeners)
479
                    .await
480
                    .context("Failed to run OR listener task")
481
            }
482
        });
483

            
484
        // TODO DIRMIRROR: The buffer size here was picked mostly arbitrarily
485
        // (on my new and not-very-busy relay, I noticed bursts of ~5000 BEGIN_DIR requests per second,
486
        // but I'm not sure how representative this is).
487
        //
488
        // We may be able to make this buffer even smaller, assuming the consumer (i.e. DirMirror)
489
        // reads from it quickly enough (presumably it will read from this in a loop,
490
        // dispatching each request to a new task?)
491
        #[allow(clippy::disallowed_methods)]
492
        let (begin_dir_tx, begin_dir_rx) = mpsc::channel::<tor_proto::Result<DataStream>>(4096);
493

            
494
        // Spawn a directory mirror server task, if we are a dir cache.
495
        task_handles.spawn(async {
496
            // TODO DIRMIRROR: it would be nicer if serve() returned
497
            // Result<Void, _> to statically prove that it indeed never
498
            // returns with a non-error.
499
            // Plus, if we do that, we can simplify this invocation,
500
            // because we won't need the anyhow! error below.
501
            self.dir_mirror.serve(begin_dir_rx).await?;
502
            Err(anyhow::anyhow!("dir mirror exited"))
503
        });
504

            
505
        // TODO(relay): enable DoT
506
        //
507
        // TODO(relay): disable hickory's internal cache
508
        // (this will involve patching hickory to make its moka dependency optional)
509
        //
510
        // Note: the hickory resolver spawns various background tasks
511

            
512
        let (reactor, resolver) = DnsResolverReactor::new(self.runtime.clone(), self.resolver)?;
513
        // Spawn the DNS reactor
514
        //
515
        // TODO(relay): only spawn this if we're configured to run as an exit
516
        task_handles.spawn(async move {
517
            reactor.run().await?;
518
            Err(anyhow::anyhow!("DNS reactor exited"))
519
        });
520

            
521
        let runtime = self.runtime.clone();
522
        // Listen for new Tor streams
523
        task_handles.spawn(
524
            // TODO: Should we give all tasks a `start` method?
525
            crate::stream::handle_incoming_streams(
526
                runtime,
527
                begin_dir_tx,
528
                self.circuit_stream_rx,
529
                resolver,
530
            ),
531
        );
532

            
533
        // Channel used to ask the descriptor publisher to rebuild and re-publish the descriptor.
534
        let (desc_command_tx, desc_command_rx) = crate::tasks::descriptor::new_command_channel();
535
        let (crypto_command_tx, crypto_command_rx) = crate::tasks::crypto::new_command_channel();
536

            
537
        // Start the crypto task.
538
        task_handles.spawn({
539
            let reactor = crate::tasks::crypto::Reactor::new(
540
                self.runtime.clone(),
541
                self.chanmgr.clone(),
542
                self.create_request_handler.clone(),
543
                self.keymgr,
544
                self.client.dirmgr().clone(),
545
                desc_command_tx,
546
                crypto_command_rx,
547
            )?;
548
            async {
549
                reactor
550
                    .run()
551
                    .await
552
                    .context("Failed to run key rotation task")
553
            }
554
        });
555

            
556
        // Build and publish the relay's own descriptor.
557
        task_handles.spawn({
558
            let netdir = Arc::clone(self.client.dirmgr()) as Arc<_>;
559
            let authorities = self.authorities;
560
            let desc_info = self.desc_info;
561
            async move {
562
                crate::tasks::RelayDescriptorPublisherTask::new(
563
                    &self.runtime,
564
                    netdir,
565
                    authorities,
566
                    desc_info,
567
                    crypto_command_tx,
568
                    desc_command_rx,
569
                )
570
                .context("Failed to create descriptor publisher task")?
571
                .start()
572
                .await
573
                .context("Failed to run descriptor publisher task")
574
            }
575
        });
576

            
577
        // Launch client tasks.
578
        //
579
        // We need to hold on to these handles until the relay stops, otherwise dropping these
580
        // handles would stop the background tasks.
581
        //
582
        // These are `tor_rtcompat::scheduler::TaskHandle`s, which don't notify us if they
583
        // stop/crash.
584
        //
585
        // TODO: Whose responsibility is it to ensure that these background tasks don't crash?
586
        // Should we have a way of monitoring these tasks? Or should the circuit manager re-launch
587
        // crashed tasks?
588
        let _client_task_handles = self.client.launch_background_tasks();
589

            
590
        // TODO: More tasks will be spawned here.
591

            
592
        // Now that background tasks are started, bootstrap the client.
593
        self.client
594
            .bootstrap()
595
            .await
596
            .context("Failed to bootstrap the relay's client")?;
597

            
598
        // We block until facism is erradicated or a task ends which means the relay will shutdown
599
        // and facism will have one more chance.
600
        let void = task_handles
601
            .join_next()
602
            .await
603
            .context("Relay task set is empty")?
604
            .context("Relay task join failed")?
605
            .context("Relay task stopped unexpectedly")?;
606

            
607
        // We can never get here since a `Void` cannot be constructed.
608
        void::unreachable(void);
609
    }
610
}
611

            
612
/// Refillers of the global read and write bandwidth pools.
613
struct BandwidthRefillers {
614
    /// Refiller of the read pool.
615
    read: BandwidthRefiller,
616
    /// Refiller of the write pool.
617
    write: BandwidthRefiller,
618
    /// Refill rate in bytes per second for both pools.
619
    rate: u64,
620
}
621

            
622
impl BandwidthRefillers {
623
    /// Spawn the read and write refiller tasks into `task_handles`, a tokio [`JoinSet`].
624
    fn spawn<R: Runtime>(
625
        self,
626
        runtime: &R,
627
        task_handles: &mut JoinSet<anyhow::Result<void::Void>>,
628
    ) {
629
        let rate = self.rate;
630
        for (refiller, name) in [(self.read, "read"), (self.write, "write")] {
631
            let runtime = runtime.clone();
632
            task_handles.spawn(async move {
633
                refiller.run(runtime, rate).await;
634
                Err(anyhow::anyhow!("{name} bandwidth refiller exited"))
635
            });
636
        }
637
    }
638
}
639

            
640
/// Build the hickory resolver, configuring it using
641
/// the settings from our [`DnsConfig`].
642
fn build_hickory_resolver(
643
    config: &TorRelayConfig,
644
) -> anyhow::Result<Resolver<TokioRuntimeProvider>> {
645
    let mut builder = prepare_hickory_builder(config)?;
646

            
647
    // Set the hickory's internal cache size to 0
648
    // (we will be implementing our own cache separately)
649
    builder.options_mut().cache_size = 0;
650

            
651
    // Unconditionally enable case randomization,
652
    // equivalent to C Tor's ServerDNSRandomizeCase.
653
    builder.options_mut().case_randomization = true;
654

            
655
    Ok(builder.build()?)
656
}
657

            
658
/// Prepare the hickory resolver builder, using the settings from
659
/// our [`DnsConfig`].
660
#[cfg(all(unix, not(any(target_os = "android", target_vendor = "apple"))))]
661
fn prepare_hickory_builder(
662
    config: &TorRelayConfig,
663
) -> anyhow::Result<ResolverBuilder<TokioRuntimeProvider>> {
664
    use hickory_resolver::system_conf::parse_resolv_conf;
665
    let DnsConfig { resolv_conf } = &config.relay.dns;
666
    let builder = if let Some(resolv_conf) = resolv_conf {
667
        let mistrust = config.storage.permissions();
668
        let resolv_conf = mistrust.verifier().file_access().read(resolv_conf)?;
669
        let (config, opts) = parse_resolv_conf(resolv_conf)?;
670

            
671
        let rt_provider = TokioRuntimeProvider::default();
672
        let mut builder = Resolver::builder_with_config(config, rt_provider);
673
        // Setting the options like this is a bit funky,
674
        // but hickory doesn't have any other API for setting them
675
        *builder.options_mut() = opts;
676

            
677
        builder
678
    } else {
679
        Resolver::builder_tokio()?
680
    };
681

            
682
    Ok(builder)
683
}
684

            
685
/// Prepare the hickory resolver builder, using the settings from
686
/// our [`DnsConfig`](crate::config::DnsConfig).
687
///
688
// Note: currently this returns a default-initialized hickory resolver,
689
// because all of the DnsConfig options we have today are unavailable
690
// on these platforms.
691
#[cfg(not(all(unix, not(any(target_os = "android", target_vendor = "apple")))))]
692
fn prepare_hickory_builder(
693
    config: &TorRelayConfig,
694
) -> anyhow::Result<ResolverBuilder<TokioRuntimeProvider>> {
695
    // We can't use resolv_conf on this platform,
696
    // but we deconstruct DnsConfig here to make sure that
697
    // if we add new fields, this will fail to compile,
698
    // reminding us to handle them here
699
    let DnsConfig { resolv_conf: _ } = &config.relay.dns;
700
    Ok(Resolver::builder_tokio()?)
701
}