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
#![allow(clippy::cognitive_complexity)] // See arti#2556
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
#![deny(clippy::string_slice)] // See arti#2571
58
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
59
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
60

            
61
#![allow(clippy::redundant_field_names)] // TODO beta clippy bug, rust-clippy/issues/17525
62

            
63
/// Dummy module
64
///
65
/// TODO MSRV 1.100, change this to `[lints.cargo]` in `Cargo.toml`.
66
/// See <https://github.com/rust-lang/cargo/issues/17461>.
67
#[allow(unused, clippy::single_component_path_imports)]
68
mod _suppress_unused_crate_warnings {
69
    // TODO RELAY drop these suppressions (deleting the dep from Cargo.toml too if not needed)
70
    #[cfg(feature = "opentelemetry")]
71
    use {opentelemetry_appender_tracing, otlp_file_exporter, tracing_opentelemetry};
72
}
73

            
74
mod cli;
75
mod client;
76
mod config;
77
mod keys;
78
mod relay;
79
mod stream;
80
mod tasks;
81
mod util;
82

            
83
use std::io::IsTerminal as _;
84

            
85
use anyhow::Context;
86
use cfg_if::cfg_if;
87
use clap::Parser;
88
use futures::FutureExt;
89
use safelog::with_safe_logging_suppressed;
90
use tor_basic_utils::iter_join;
91
use tor_error::warn_report;
92
use tor_rtcompat::SpawnExt;
93
use tor_rtcompat::tokio::TokioRustlsRuntime;
94
use tor_rtcompat::{Runtime, ToplevelRuntime};
95
use tracing::{debug, info, trace, warn};
96
use tracing_subscriber::FmtSubscriber;
97
use tracing_subscriber::filter::EnvFilter;
98
use tracing_subscriber::util::SubscriberInitExt;
99

            
100
use crate::config::{DEFAULT_LOG_LEVEL, TorRelayConfig, base_resolver};
101
use crate::relay::InertTorRelay;
102

            
103
fn main() {
104
    // Will exit if '--help' used or there's a parse error.
105
    let cli = cli::Cli::parse();
106

            
107
    if let Err(e) = main_main(cli) {
108
        // TODO: Use arti_client's `HintableError` here (see `arti::main`)?
109
        // TODO: Why do we suppress safe logging?
110
        // TODO: Do we want to log the error?
111
        // We use anyhow's error formatting here rather than `tor_error::report_and_exit` since the
112
        // latter seems to omit some error info and anyhow's error formatting is nicer.
113
        #[allow(clippy::print_stderr)]
114
        with_safe_logging_suppressed(|| {
115
            eprintln!("Error: {e:?}");
116
            // The 127 is copied from `tor_error::report_and_exit`.
117
            // It's unclear why 127 was chosen there.
118
            std::process::exit(127);
119
        });
120
    }
121
}
122

            
123
/// The real main without the error formatting.
124
fn main_main(cli: cli::Cli) -> anyhow::Result<()> {
125
    // Register a basic stderr logger until we have enough info to configure the main logger.
126
    // Unlike arti, we enable timestamps for this pre-config logger.
127
    // TODO: Consider using timestamps with reduced-granularity (see `LogPrecision`).
128
    let level: tracing::metadata::Level = cli
129
        .global
130
        .log_level
131
        .map(Into::into)
132
        .unwrap_or(DEFAULT_LOG_LEVEL);
133
    let filter = EnvFilter::builder()
134
        .with_default_directive(level.into())
135
        .parse("")
136
        .expect("empty filter directive should be trivially parsable");
137
    FmtSubscriber::builder()
138
        .with_env_filter(filter)
139
        .with_ansi(std::io::stderr().is_terminal())
140
        .with_writer(std::io::stderr)
141
        .finish()
142
        .init();
143

            
144
    match cli.command {
145
        #[allow(clippy::print_stdout)]
146
        cli::Commands::BuildInfo => {
147
            println!("Version: {}", env!("CARGO_PKG_VERSION"));
148
            // these are set by our build script
149
            println!("Features: {}", env!("BUILD_FEATURES"));
150
            println!("Profile: {}", env!("BUILD_PROFILE"));
151
            println!("Debug: {}", env!("BUILD_DEBUG"));
152
            println!("Optimization level: {}", env!("BUILD_OPT_LEVEL"));
153
            println!("Rust version: {}", env!("BUILD_RUSTC_VERSION"));
154
            println!("Target triple: {}", env!("BUILD_TARGET"));
155
            println!("Host triple: {}", env!("BUILD_HOST"));
156
        }
157
        cli::Commands::Run(args) => start_relay(args, cli.global)?,
158
    }
159

            
160
    Ok(())
161
}
162

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

            
169
    let mut cfg_sources = global_args
170
        .config()
171
        .context("Failed to get configuration sources")?;
172

            
173
    debug!(
174
        "Using override options: {}",
175
        iter_join(", ", cfg_sources.options()),
176
    );
177

            
178
    // A Mistrust object to use for loading our configuration.
179
    // Elsewhere, we use the value _from_ the configuration.
180
    let cfg_mistrust = if global_args.disable_fs_permission_checks {
181
        fs_mistrust::Mistrust::new_dangerously_trust_everyone()
182
    } else {
183
        fs_mistrust::MistrustBuilder::default()
184
            // By default, a `Mistrust` checks an environment variable.
185
            // We do not (at the moment) want this behaviour for relays:
186
            // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/2699#note_3147502
187
            .ignore_environment()
188
            .build()
189
            .expect("default fs-mistrust should be buildable")
190
    };
191

            
192
    cfg_sources.set_mistrust(cfg_mistrust);
193

            
194
    let cfg = cfg_sources
195
        .load()
196
        .context("Failed to load configuration sources")?;
197
    let config =
198
        tor_config::resolve::<TorRelayConfig>(cfg).context("Failed to resolve configuration")?;
199

            
200
    // TODO: Configure a proper logger, not just a simple stderr logger.
201
    // TODO: We may want this to be the global logger, but if we use arti's `setup_logging` in the
202
    // future, it returns a `LogGuards` which we'd have no way of holding on to until the
203
    // application exits (see https://gitlab.torproject.org/tpo/core/arti/-/issues/1791).
204
    let filter = EnvFilter::builder()
205
        .parse(&config.logging.console)
206
        .with_context(|| {
207
            format!(
208
                "Failed to parse console logging directive {:?}",
209
                config.logging.console,
210
            )
211
        })?;
212
    let logger = tracing_subscriber::FmtSubscriber::builder()
213
        .with_env_filter(filter)
214
        .with_ansi(std::io::stderr().is_terminal())
215
        .with_writer(std::io::stderr)
216
        .finish();
217
    let logger = tracing::Dispatch::new(logger);
218

            
219
    // Disable safe logging if requested.
220
    // This guard will be dropped at the end of this function,
221
    // which means we effectively re-enable safe logging once this function returns.
222
    // TODO: Do we want this guard behaviour?
223
    // I think it would be better to enable safe-logging forever?
224
    let _safelog_guard = if config.logging.log_sensitive_information {
225
        match safelog::disable_safe_logging() {
226
            Ok(guard) => Some(guard),
227
            Err(e) => {
228
                // We don't need to propagate this error;
229
                // it isn't the end of the world if we were unable to disable safe logging.
230
                warn_report!(e, "Unable to disable safe logging");
231
                None
232
            }
233
        }
234
    } else {
235
        None
236
    };
237

            
238
    if let Some(listen) = {
239
        // https://github.com/metrics-rs/metrics/issues/567
240
        config
241
            .metrics
242
            .prometheus
243
            .listen
244
            .single_address_legacy()
245
            .context("can only listen on a single address for Prometheus metrics")?
246
    } {
247
        cfg_if! {
248
            if #[cfg(feature = "metrics")] {
249
                metrics_exporter_prometheus::PrometheusBuilder::new()
250
                    .with_http_listener(listen)
251
                    .install()
252
                    .with_context(|| format!(
253
                        "set up Prometheus metrics exporter on {listen}"
254
                    ))?;
255
                info!("Arti Prometheus metrics export scraper endpoint http://{listen}");
256
            } else {
257
                let _ = listen;
258
                warn!("`metrics.prometheus.listen` config set but `metrics` cargo feature compiled out in `arti-relay` crate");
259
            }
260
        }
261
    }
262

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

            
266
        // Configure tor-log-ratelim early before we begin logging.
267
        tor_log_ratelim::install_runtime(runtime.clone())
268
            .context("Failed to initialize tor-log-ratelim")?;
269

            
270
        let path_resolver = base_resolver();
271
        let relay =
272
            InertTorRelay::new(config, path_resolver).context("Failed to initialize the relay")?;
273

            
274
        match mainloop(&runtime, run_relay(runtime.clone(), relay))? {
275
            MainloopStatus::Finished(Err(e)) => Err(e),
276
            MainloopStatus::CtrlC => {
277
                info!("Received a ctrl-c; stopping the relay");
278
                Ok(())
279
            }
280
        }
281
    })
282
}
283

            
284
/// A helper to drive a future using a runtime.
285
///
286
/// This calls `block_on` on the runtime.
287
/// The future will be cancelled on a ctrl-c event.
288
fn mainloop<T: Send + 'static>(
289
    runtime: &impl ToplevelRuntime,
290
    fut: impl Future<Output = T> + Send + 'static,
291
) -> anyhow::Result<MainloopStatus<T>> {
292
    trace!("Starting runtime");
293

            
294
    let rv = runtime.block_on(async {
295
        // Code running in 'block_on' runs slower than in a task (in tokio at least),
296
        // so the future is run on a task.
297
        let mut handle = runtime
298
            .spawn_with_handle(fut)
299
            .context("Failed to spawn task")?
300
            .fuse();
301

            
302
        futures::select!(
303
            // Signal handler is registered on the first poll.
304
            res = tokio::signal::ctrl_c().fuse() => {
305
                let () = res.context("Failed to listen for ctrl-c event")?;
306
                trace!("Received a ctrl-c");
307
                // Dropping the handle will cancel the task, so we do that explicitly here.
308
                drop(handle);
309
                Ok(MainloopStatus::CtrlC)
310
            }
311
            x = handle => Ok(MainloopStatus::Finished(x)),
312
        )
313
    });
314

            
315
    trace!("Finished runtime");
316
    rv
317
}
318

            
319
/// Run the relay.
320
///
321
/// This blocks until the relay stops.
322
async fn run_relay<R: Runtime>(
323
    runtime: R,
324
    inert_relay: InertTorRelay,
325
) -> anyhow::Result<void::Void> {
326
    let relay = inert_relay
327
        .init(runtime)
328
        .await
329
        .context("Failed to bootstrap")?;
330

            
331
    // This blocks until end of time or an error.
332
    relay.run().await
333
}
334

            
335
/// Initialize a runtime.
336
///
337
/// Any cli commands that need a runtime should call this so that we use a consistent runtime.
338
fn init_runtime() -> std::io::Result<impl ToplevelRuntime> {
339
    // Use the tokio runtime from tor_rtcompat unless we later find a reason to use tokio directly.
340
    // See https://gitlab.torproject.org/tpo/core/arti/-/work_items/1744.
341
    // Relays must use rustls as native-tls doesn't support
342
    // `CertifiedConn::export_keying_material()`.
343

            
344
    // Note: See comments in `tor_rtcompat::impls::rustls::RustlsProvider`
345
    // about choice of default crypto provider.
346
    let _idempotent_ignore = rustls::crypto::CryptoProvider::install_default(
347
        rustls::crypto::aws_lc_rs::default_provider(),
348
    );
349

            
350
    TokioRustlsRuntime::create()
351
}
352

            
353
/// The result of [`mainloop`].
354
enum MainloopStatus<T> {
355
    /// The result from the completed future.
356
    Finished(T),
357
    /// The future was cancelled due to a ctrl-c event.
358
    CtrlC,
359
}