1
//! A relay binary used to join the Tor network to relay anonymous communication.
2
//!
3
//! NOTE: This binary is still highly experimental as in active development, not stable and
4
//! without any type of guarantee of running or even working.
5
//!
6
//! ## Error handling
7
//!
8
//! We return [`anyhow::Error`] for functions whose errors will always result in an exit and don't
9
//! need to be handled individually.
10
//! When we do need to handle errors, functions should return a more comprehensive error type (for
11
//! example one created with `thiserror`).
12

            
13
// @@ begin lint list maintained by maint/add_warning @@
14
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
15
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
16
#![warn(missing_docs)]
17
#![warn(noop_method_call)]
18
#![warn(unreachable_pub)]
19
#![warn(clippy::all)]
20
#![deny(clippy::await_holding_lock)]
21
#![deny(clippy::cargo_common_metadata)]
22
#![deny(clippy::cast_lossless)]
23
#![deny(clippy::checked_conversions)]
24
#![warn(clippy::cognitive_complexity)]
25
#![deny(clippy::debug_assert_with_mut_call)]
26
#![deny(clippy::exhaustive_enums)]
27
#![deny(clippy::exhaustive_structs)]
28
#![deny(clippy::expl_impl_clone_on_copy)]
29
#![deny(clippy::fallible_impl_from)]
30
#![deny(clippy::implicit_clone)]
31
#![deny(clippy::large_stack_arrays)]
32
#![warn(clippy::manual_ok_or)]
33
#![deny(clippy::missing_docs_in_private_items)]
34
#![warn(clippy::needless_borrow)]
35
#![warn(clippy::needless_pass_by_value)]
36
#![warn(clippy::option_option)]
37
#![deny(clippy::print_stderr)]
38
#![deny(clippy::print_stdout)]
39
#![warn(clippy::rc_buffer)]
40
#![deny(clippy::ref_option_ref)]
41
#![warn(clippy::semicolon_if_nothing_returned)]
42
#![warn(clippy::trait_duplication_in_bounds)]
43
#![deny(clippy::unchecked_time_subtraction)]
44
#![deny(clippy::unnecessary_wraps)]
45
#![warn(clippy::unseparated_literal_suffix)]
46
#![deny(clippy::unwrap_used)]
47
#![deny(clippy::mod_module_files)]
48
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
49
#![allow(clippy::uninlined_format_args)]
50
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
51
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
52
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
53
#![allow(clippy::needless_lifetimes)] // See arti#1765
54
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
55
#![allow(clippy::collapsible_if)] // See arti#2342
56
#![deny(clippy::unused_async)]
57
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
58

            
59
mod cli;
60
mod client;
61
mod config;
62
mod relay;
63
mod tasks;
64
mod util;
65

            
66
use std::io::IsTerminal as _;
67

            
68
use anyhow::Context;
69
use clap::Parser;
70
use futures::FutureExt;
71
use safelog::with_safe_logging_suppressed;
72
use tor_basic_utils::iter_join;
73
use tor_error::warn_report;
74
use tor_relay_crypto::pk::{
75
    RelayIdentityKeypair, RelayIdentityKeypairSpecifier, RelayIdentityRsaKeypair,
76
    RelayIdentityRsaKeypairSpecifier,
77
};
78
use tor_rtcompat::SpawnExt;
79
use tor_rtcompat::tokio::TokioRustlsRuntime;
80
use tor_rtcompat::{Runtime, ToplevelRuntime};
81
use tracing::{debug, info, trace};
82
use tracing_subscriber::FmtSubscriber;
83
use tracing_subscriber::filter::EnvFilter;
84
use tracing_subscriber::util::SubscriberInitExt;
85

            
86
use crate::config::{DEFAULT_LOG_LEVEL, TorRelayConfig, base_resolver};
87
use crate::relay::InertTorRelay;
88

            
89
fn main() {
90
    // Will exit if '--help' used or there's a parse error.
91
    let cli = cli::Cli::parse();
92

            
93
    if let Err(e) = main_main(cli) {
94
        // TODO: Use arti_client's `HintableError` here (see `arti::main`)?
95
        // TODO: Why do we suppress safe logging?
96
        // TODO: Do we want to log the error?
97
        // We use anyhow's error formatting here rather than `tor_error::report_and_exit` since the
98
        // latter seems to omit some error info and anyhow's error formatting is nicer.
99
        #[allow(clippy::print_stderr)]
100
        with_safe_logging_suppressed(|| {
101
            eprintln!("Error: {e:?}");
102
            // The 127 is copied from `tor_error::report_and_exit`.
103
            // It's unclear why 127 was chosen there.
104
            std::process::exit(127);
105
        });
106
    }
107
}
108

            
109
/// The real main without the error formatting.
110
fn main_main(cli: cli::Cli) -> anyhow::Result<()> {
111
    // Register a basic stderr logger until we have enough info to configure the main logger.
112
    // Unlike arti, we enable timestamps for this pre-config logger.
113
    // TODO: Consider using timestamps with reduced-granularity (see `LogPrecision`).
114
    let level: tracing::metadata::Level = cli
115
        .global
116
        .log_level
117
        .map(Into::into)
118
        .unwrap_or(DEFAULT_LOG_LEVEL);
119
    let filter = EnvFilter::builder()
120
        .with_default_directive(level.into())
121
        .parse("")
122
        .expect("empty filter directive should be trivially parsable");
123
    FmtSubscriber::builder()
124
        .with_env_filter(filter)
125
        .with_ansi(std::io::stderr().is_terminal())
126
        .with_writer(std::io::stderr)
127
        .finish()
128
        .init();
129

            
130
    match cli.command {
131
        #[allow(clippy::print_stdout)]
132
        cli::Commands::BuildInfo => {
133
            println!("Version: {}", env!("CARGO_PKG_VERSION"));
134
            // these are set by our build script
135
            println!("Features: {}", env!("BUILD_FEATURES"));
136
            println!("Profile: {}", env!("BUILD_PROFILE"));
137
            println!("Debug: {}", env!("BUILD_DEBUG"));
138
            println!("Optimization level: {}", env!("BUILD_OPT_LEVEL"));
139
            println!("Rust version: {}", env!("BUILD_RUSTC_VERSION"));
140
            println!("Target triple: {}", env!("BUILD_TARGET"));
141
            println!("Host triple: {}", env!("BUILD_HOST"));
142
        }
143
        cli::Commands::Run(args) => start_relay(args, cli.global)?,
144
    }
145

            
146
    Ok(())
147
}
148

            
149
/// Initialize and start the relay.
150
// Pass by value so that we don't need to clone fields, which keeps the code simpler.
151
#[allow(clippy::needless_pass_by_value)]
152
fn start_relay(_args: cli::RunArgs, global_args: cli::GlobalArgs) -> anyhow::Result<()> {
153
    // TODO: Warn (or exit?) if running as root; see 'arti::process::running_as_root()'.
154

            
155
    let mut cfg_sources = global_args
156
        .config()
157
        .context("Failed to get configuration sources")?;
158

            
159
    debug!(
160
        "Using override options: {}",
161
        iter_join(", ", cfg_sources.options()),
162
    );
163

            
164
    // A Mistrust object to use for loading our configuration.
165
    // Elsewhere, we use the value _from_ the configuration.
166
    let cfg_mistrust = if global_args.disable_fs_permission_checks {
167
        fs_mistrust::Mistrust::new_dangerously_trust_everyone()
168
    } else {
169
        fs_mistrust::MistrustBuilder::default()
170
            // By default, a `Mistrust` checks an environment variable.
171
            // We do not (at the moment) want this behaviour for relays:
172
            // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/2699#note_3147502
173
            .ignore_environment()
174
            .build()
175
            .expect("default fs-mistrust should be buildable")
176
    };
177

            
178
    cfg_sources.set_mistrust(cfg_mistrust);
179

            
180
    let cfg = cfg_sources
181
        .load()
182
        .context("Failed to load configuration sources")?;
183
    let config =
184
        tor_config::resolve::<TorRelayConfig>(cfg).context("Failed to resolve configuration")?;
185

            
186
    // TODO: Configure a proper logger, not just a simple stderr logger.
187
    // TODO: We may want this to be the global logger, but if we use arti's `setup_logging` in the
188
    // future, it returns a `LogGuards` which we'd have no way of holding on to until the
189
    // application exits (see https://gitlab.torproject.org/tpo/core/arti/-/issues/1791).
190
    let filter = EnvFilter::builder()
191
        .parse(&config.logging.console)
192
        .with_context(|| {
193
            format!(
194
                "Failed to parse console logging directive {:?}",
195
                config.logging.console,
196
            )
197
        })?;
198
    let logger = tracing_subscriber::FmtSubscriber::builder()
199
        .with_env_filter(filter)
200
        .with_ansi(std::io::stderr().is_terminal())
201
        .with_writer(std::io::stderr)
202
        .finish();
203
    let logger = tracing::Dispatch::new(logger);
204

            
205
    // Disable safe logging if requested.
206
    // This guard will be dropped at the end of this function,
207
    // which means we effectively re-enable safe logging once this function returns.
208
    // TODO: Do we want this guard behaviour?
209
    // I think it would be better to enable safe-logging forever?
210
    let _safelog_guard = if config.logging.log_sensitive_information {
211
        match safelog::disable_safe_logging() {
212
            Ok(guard) => Some(guard),
213
            Err(e) => {
214
                // We don't need to propagate this error;
215
                // it isn't the end of the world if we were unable to disable safe logging.
216
                warn_report!(e, "Unable to disable safe logging");
217
                None
218
            }
219
        }
220
    } else {
221
        None
222
    };
223

            
224
    tracing::dispatcher::with_default(&logger, || {
225
        let runtime = init_runtime().context("Failed to initialize the runtime")?;
226

            
227
        // Configure tor-log-ratelim early before we begin logging.
228
        tor_log_ratelim::install_runtime(runtime.clone())
229
            .context("Failed to initialize tor-log-ratelim")?;
230

            
231
        let path_resolver = base_resolver();
232
        let relay =
233
            InertTorRelay::new(config, path_resolver).context("Failed to initialize the relay")?;
234

            
235
        match mainloop(&runtime, run_relay(runtime.clone(), relay))? {
236
            MainloopStatus::Finished(Err(e)) => Err(e),
237
            MainloopStatus::CtrlC => {
238
                info!("Received a ctrl-c; stopping the relay");
239
                Ok(())
240
            }
241
        }
242
    })
243
}
244

            
245
/// A helper to drive a future using a runtime.
246
///
247
/// This calls `block_on` on the runtime.
248
/// The future will be cancelled on a ctrl-c event.
249
fn mainloop<T: Send + 'static>(
250
    runtime: &impl ToplevelRuntime,
251
    fut: impl Future<Output = T> + Send + 'static,
252
) -> anyhow::Result<MainloopStatus<T>> {
253
    trace!("Starting runtime");
254

            
255
    let rv = runtime.block_on(async {
256
        // Code running in 'block_on' runs slower than in a task (in tokio at least),
257
        // so the future is run on a task.
258
        let mut handle = runtime
259
            .spawn_with_handle(fut)
260
            .context("Failed to spawn task")?
261
            .fuse();
262

            
263
        futures::select!(
264
            // Signal handler is registered on the first poll.
265
            res = tokio::signal::ctrl_c().fuse() => {
266
                let () = res.context("Failed to listen for ctrl-c event")?;
267
                trace!("Received a ctrl-c");
268
                // Dropping the handle will cancel the task, so we do that explicitly here.
269
                drop(handle);
270
                Ok(MainloopStatus::CtrlC)
271
            }
272
            x = handle => Ok(MainloopStatus::Finished(x)),
273
        )
274
    });
275

            
276
    trace!("Finished runtime");
277
    rv
278
}
279

            
280
/// Run the relay.
281
///
282
/// This blocks until the relay stops.
283
async fn run_relay<R: Runtime>(
284
    runtime: R,
285
    inert_relay: InertTorRelay,
286
) -> anyhow::Result<void::Void> {
287
    let relay = inert_relay
288
        .init(runtime)
289
        .await
290
        .context("Failed to bootstrap")?;
291

            
292
    let keymgr = relay.keymgr();
293
    let rsa_id = keymgr
294
        .get::<RelayIdentityRsaKeypair>(&RelayIdentityRsaKeypairSpecifier::new())
295
        .context("Failed to get RSA identity from key manager")?
296
        .context("Missing RSA identity")?
297
        .to_rsa_identity();
298
    let ed_id = keymgr
299
        .get::<RelayIdentityKeypair>(&RelayIdentityKeypairSpecifier::new())
300
        .context("Failed to get Ed25519 identity from key manager")?
301
        .context("Missing Ed25519 identity")?
302
        .to_ed25519_id();
303

            
304
    // Log the relay's identities.
305
    // TODO: We should also log this after a key rotation:
306
    // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/3773#note_3367789
307
    // TODO: This is useful at info level while we're developing,
308
    // but the level should probably be lowered in the future.
309
    tracing::info!("RSA identity: {rsa_id}");
310
    tracing::info!("Ed25519 identity: {ed_id}");
311

            
312
    // TODO: I'd like to log the ntor key here as well so that we can build ntor circuits to the
313
    // relay.
314

            
315
    // This blocks until end of time or an error.
316
    relay.run().await
317
}
318

            
319
/// Initialize a runtime.
320
///
321
/// Any cli commands that need a runtime should call this so that we use a consistent runtime.
322
fn init_runtime() -> std::io::Result<impl ToplevelRuntime> {
323
    // Use the tokio runtime from tor_rtcompat unless we later find a reason to use tokio directly.
324
    // See https://gitlab.torproject.org/tpo/core/arti/-/work_items/1744.
325
    // Relays must use rustls as native-tls doesn't support
326
    // `CertifiedConn::export_keying_material()`.
327

            
328
    // Note: See comments in `tor_rtcompat::impls::rustls::RustlsProvider`
329
    // about choice of default crypto provider.
330
    let _idempotent_ignore =
331
        rustls::crypto::CryptoProvider::install_default(rustls::crypto::ring::default_provider());
332

            
333
    TokioRustlsRuntime::create()
334
}
335

            
336
/// The result of [`mainloop`].
337
enum MainloopStatus<T> {
338
    /// The result from the completed future.
339
    Finished(T),
340
    /// The future was cancelled due to a ctrl-c event.
341
    CtrlC,
342
}