1
//! Relay descriptor publishing task.
2
//!
3
//! This task is responsible for building our relay descriptor and uploading it to the directory
4
//! authorities using [`tor_dirpublish`].
5
//!
6
//! It is driven by two sources of input:
7
//!   * When receiving a [`DescriptorCommand`]. For instance, the crypto task
8
//!     ([`crate::tasks::crypto`]) will send a [`DescriptorCommand::Publish`] when at least
9
//!     one of the relay keys changes. It triggers a rebuild and publish of the relay descriptor.
10
//!   * Consensus events from the [`NetDirProvider`], so that we can pick up new consensus
11
//!     parameters when a new consensus arrives.
12
use std::collections::HashSet;
13
use std::net::SocketAddr;
14
use std::sync::Arc;
15
use std::time::Duration;
16

            
17
use anyhow::Context;
18
use futures::channel::mpsc;
19
use futures::{StreamExt as _, select_biased};
20
use tracing::{debug, info, trace};
21

            
22
use tor_async_utils::{mpsc_channel_no_memquota, oneshot};
23
use tor_dirclient::request::{Requestable, UploadRouterDesc};
24
use tor_dircommon::authority::AuthorityContacts;
25
use tor_dirpublish::{Publisher, http::DirectHttpUploader};
26
use tor_netdir::{DirEvent, NetDirProvider};
27
use tor_netdoc::types::{ContactInfo, Nickname};
28
use tor_rtcompat::{DynTimeProvider, Runtime, SleepProvider as _};
29
use web_time_compat::Instant;
30

            
31
use crate::config;
32
use crate::tasks::crypto::{CryptoCommand, CryptoCommandSender};
33

            
34
mod cert;
35
mod encode;
36

            
37
/// Initial delay before retrying a failed descriptor upload.
38
///
39
/// This is simply the initial delay then the [`tor_dirpublish::Publisher`] has its back off
40
/// algorithm seeded with this value.
41
const INITIAL_RETRY_DELAY: Duration = Duration::from_secs(60);
42

            
43
/// A command sent to the [`RelayDescriptorPublisherTask`] over its control channel.
44
#[derive(Clone, Debug)]
45
#[non_exhaustive]
46
pub(crate) enum DescriptorCommand {
47
    /// Rebuild the relay descriptor and publish it to the directory authorities. This
48
    /// task asks the crypto task for the latest known identities/keys in order to
49
    /// rebuild a new descriptor.
50
    Publish,
51
}
52

            
53
/// The sending side of the [`DescriptorCommand`] channel.
54
pub(crate) type DescriptorCommandSender = mpsc::Sender<DescriptorCommand>;
55

            
56
/// The receiving side of the [`DescriptorCommand`] channel.
57
pub(crate) type DescriptorCommandReceiver = mpsc::Receiver<DescriptorCommand>;
58

            
59
/// Returns a new [`DescriptorCommand`] channel.
60
///
61
/// This is a bounded to limit descriptor publication spamming (in case of a bug).
62
pub(crate) fn new_command_channel() -> (DescriptorCommandSender, DescriptorCommandReceiver) {
63
    // TODO(relay): We might want to make those memquota actually?
64
    mpsc_channel_no_memquota(16)
65
}
66

            
67
/// Relay information used by the [`RelayDescriptorPublisherTask`] to build our descriptor.
68
#[derive(Clone, Debug)]
69
pub(crate) struct RouterDescInfo {
70
    /// The nickname of this relay.
71
    pub(crate) nickname: Nickname,
72
    /// Contact information for the operator(s) of this relay.
73
    pub(crate) contact: Option<ContactInfo>,
74
    /// Addresses advertised on the network for receiving OR connections.
75
    pub(crate) advertise: config::Advertise,
76
    /// The bandwidth rate limiting configuration.
77
    pub(crate) bandwidth: config::BandwidthConfig,
78
}
79

            
80
/// Background task that builds and publishes the relay's descriptor.
81
pub(crate) struct RelayDescriptorPublisherTask {
82
    /// Time provider for descriptor publication timestamps.
83
    runtime: DynTimeProvider,
84

            
85
    /// Directory provider, used to learn about new consensus documents and parameters.
86
    netdir: Arc<dyn NetDirProvider>,
87

            
88
    /// The directory authorities we upload our descriptor to.
89
    ///
90
    /// This is either from the config file or the compiled-in default list.
91
    authorities: AuthorityContacts,
92

            
93
    /// Channel on which we receive [`DescriptorCommand`]s from other tasks.
94
    command_rx: DescriptorCommandReceiver,
95

            
96
    /// The [`tor_dirpublish`] publisher that manages uploads to all targets.
97
    publisher: Arc<Publisher<dyn Requestable, Vec<SocketAddr>>>,
98

            
99
    /// The crypto task sender channel.
100
    crypto_tx: CryptoCommandSender,
101

            
102
    /// Relay information used to build our descriptor.
103
    desc_info: RouterDescInfo,
104

            
105
    /// Monotonic time at which this relay started. Needed for the descriptor uptime.
106
    started_at: Instant,
107
}
108

            
109
impl RelayDescriptorPublisherTask {
110
    /// Construct a new descriptor publisher task.
111
    ///
112
    /// This launches the underlying [`tor_dirpublish`] publisher (which spawns its own reactor),
113
    /// but does not start listening for commands or consensus events until start() is called.
114
    ///
115
    /// The publisher reactor won't try to upload until the
116
    /// [`tor_dirpublish::Publisher::set_document`] is called.
117
    pub(crate) fn new<R: Runtime>(
118
        runtime: &R,
119
        netdir: Arc<dyn NetDirProvider>,
120
        authorities: AuthorityContacts,
121
        desc_info: RouterDescInfo,
122
        crypto_tx: CryptoCommandSender,
123
        command_rx: DescriptorCommandReceiver,
124
    ) -> anyhow::Result<Self> {
125
        let uploader = Arc::new(DirectHttpUploader::new(runtime.clone()));
126

            
127
        // We start with no document and no targets. Both are populated once we build a descriptor.
128
        // This way we catch any new directory authorities showing up in the config or consensus.
129
        let publisher = Publisher::launch(
130
            runtime,
131
            "relay descriptor".to_string(),
132
            /* initial_document=*/ None,
133
            /* initial_targets=*/ HashSet::new(),
134
            INITIAL_RETRY_DELAY,
135
            uploader,
136
        )
137
        .context("Failed to launch descriptor publisher")?;
138

            
139
        Ok(Self {
140
            runtime: DynTimeProvider::new(runtime.clone()),
141
            netdir,
142
            authorities,
143
            command_rx,
144
            publisher,
145
            crypto_tx,
146
            desc_info,
147
            started_at: runtime.now(),
148
        })
149
    }
150

            
151
    /// Build the relay's descriptor document as ready to be uploaded.
152
    ///
153
    /// Returns `None` if we don't have everything we need to build a descriptor.
154
    async fn build_descriptor(&mut self) -> anyhow::Result<Option<Arc<str>>> {
155
        // Get all descriptor key material in one snapshot from the crypto task.
156
        let (tx, rx) = oneshot::channel();
157
        self.crypto_tx
158
            .try_send(CryptoCommand::GetRouterDescKeyMaterial { tx })
159
            .context("Crypto task try_send failed")?;
160
        let key_material = rx
161
            .await
162
            .context("Crypto task key material reply channel closed")?
163
            .context("Unable to get router descriptor key material")?;
164

            
165
        let encoded = encode::encode_and_sign_router_desc(
166
            &self.desc_info,
167
            key_material,
168
            self.runtime.wallclock(),
169
            self.runtime
170
                .now()
171
                .saturating_duration_since(self.started_at),
172
        )?;
173
        Ok(Some(encoded.into()))
174
    }
175

            
176
    /// Recompute the set of directory authorities we upload to.
177
    ///
178
    /// Each authority becomes one target, carrying all of its upload addresses so the
179
    /// [`DirectHttpUploader`] can try them in turn.
180
    ///
181
    /// Returns an empty set if we somehow have no authorities at all.
182
    fn compute_targets(&self) -> HashSet<Vec<SocketAddr>> {
183
        // This should never be empty because we have compiled in authorities by default.
184
        // If that case ever happens, the publisher will just do nothing.
185
        //
186
        // TODO(relay): We have to check those against our relay capabilities as in if we
187
        // support IPv6 or if we have an IPv4. For now, we pass all targets and let any
188
        // failures be handled at the connect() attempt.
189
        self.authorities
190
            .uploads()
191
            .iter()
192
            .filter(|&addrs| !addrs.is_empty())
193
            .cloned()
194
            .collect()
195
    }
196

            
197
    /// Rebuild the descriptor (and refresh targets) and hand it to the publisher.
198
    async fn rebuild_and_publish(&mut self) -> anyhow::Result<()> {
199
        // TODO(relay): Never upload to any default real network authorities. Only use
200
        // custom ones so testing works. arti-relay MUST not join the network just yet.
201
        if self.authorities.intersects(&AuthorityContacts::default()) {
202
            info!("Descriptor publishing skipped: At least one authority is a default one");
203
            return Ok(());
204
        }
205

            
206
        // Adjust the targets onto our publisher if we have any targets. An empty set
207
        // means something has gone wrong somehow so don't touch the publisher in an
208
        // attempt to use what was there before.
209
        let targets = self.compute_targets();
210
        if !targets.is_empty() {
211
            let targets = targets.into_iter().map(Arc::new).collect();
212
            self.publisher.adjust_targets(|t| *t = targets);
213
        }
214

            
215
        // Get the latest descriptor.
216
        let desc = self
217
            .build_descriptor()
218
            .await
219
            .context("Failed to build relay descriptor")?;
220
        // Turn the encoded descriptor into a request and erase its concrete type for the
221
        // generic HTTP publisher.
222
        let doc = desc.map(|desc| Arc::new(UploadRouterDesc::new(desc)) as Arc<dyn Requestable>);
223
        // Tell the publisher to publish the new document. Failing to build the descriptor, as in a
224
        // None value, will make the publisher wait and do nothing.
225
        self.publisher.set_document(doc, false);
226
        Ok(())
227
    }
228

            
229
    /// Start the task.
230
    ///
231
    /// This runs forever. It listens for [`DescriptorCommand`] and consensus events.
232
    pub(crate) async fn start(mut self) -> anyhow::Result<void::Void> {
233
        debug!("Starting Relay descriptor publisher task");
234

            
235
        // Subscribe before the first run so we don't miss any events that arrive between
236
        // startup and entering the select loop.
237
        let mut consensus_events = self
238
            .netdir
239
            .events()
240
            .filter(|ev| std::future::ready(matches!(ev, DirEvent::NewConsensus)))
241
            .fuse();
242

            
243
        // Do an initial build now, in case we already have a consensus.
244
        self.rebuild_and_publish()
245
            .await
246
            .context("Failed initial descriptor publish")?;
247

            
248
        loop {
249
            select_biased! {
250
                command = self.command_rx.next() => {
251
                    let command = command
252
                        .context("descriptor command channel closed unexpectedly")?;
253
                    trace!(?command, "Descriptor publisher received command");
254
                    match command {
255
                        DescriptorCommand::Publish => {
256
                            self.rebuild_and_publish()
257
                                .await
258
                                .context("Failed to publish descriptor on command")?;
259
                        }
260
                    }
261
                }
262
                event = consensus_events.next() => {
263
                    let _event = event
264
                        .context("netdir consensus event stream ended unexpectedly")?;
265
                    trace!("Descriptor publisher task saw new consensus. Rebuilding and publishing.");
266
                    self.rebuild_and_publish()
267
                        .await
268
                        .context("Failed to publish descriptor on new consensus")?;
269
                }
270
                // TODO(relay)
271
                //
272
                // Here are the other conditions documented in the spec for when we
273
                // upload a new descriptor:
274
                // https://spec.torproject.org/dir-spec/uploading-relay-documents.html
275
                //
276
                //  - A period of time (18 hrs by default) has passed since the last
277
                //  upload.
278
                //  - A descriptor field other than bandwidth or uptime has changed.
279
                //  Its uptime is less than 24h and bandwidth has changed by a factor of
280
                //  2 from the last time a descriptor was generated, and at least a given
281
                //  interval of time (3 hours by default) has passed since then.
282
                //  - Its uptime has been reset (by restarting).
283
                //  - It receives a networkstatus consensus in which it is not listed.
284
                //  - It receives a networkstatus consensus in which it is listed with
285
                //  the StaleDesc flag.
286
            }
287
        }
288
    }
289
}