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
#![warn(clippy::or_fun_call)]
38
#![deny(clippy::print_stderr)]
39
#![deny(clippy::print_stdout)]
40
#![warn(clippy::rc_buffer)]
41
#![deny(clippy::ref_option_ref)]
42
#![warn(clippy::semicolon_if_nothing_returned)]
43
#![warn(clippy::trait_duplication_in_bounds)]
44
#![deny(clippy::unchecked_time_subtraction)]
45
#![deny(clippy::unnecessary_wraps)]
46
#![warn(clippy::unseparated_literal_suffix)]
47
#![deny(clippy::unwrap_used)]
48
#![deny(clippy::mod_module_files)]
49
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
50
#![allow(clippy::uninlined_format_args)]
51
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
52
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
53
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
54
#![allow(clippy::needless_lifetimes)] // See arti#1765
55
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
56
#![allow(clippy::collapsible_if)] // See arti#2342
57
#![deny(clippy::unused_async)]
58
#![deny(clippy::string_slice)] // See arti#2571
59
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
60
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
61

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

            
65
// TODO: add to the list maintained by maint/add_warning once it's available on all crates
66
#![warn(unnameable_types)]
67

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

            
79
mod cli;
80
mod client;
81
mod config;
82
mod keys;
83
mod relay;
84
mod stream;
85
mod tasks;
86
mod util;
87

            
88
use std::io::IsTerminal as _;
89

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

            
105
use crate::config::{DEFAULT_LOG_LEVEL, TorRelayConfig, base_resolver};
106
use crate::relay::InertTorRelay;
107

            
108
/// Return the protocol capabilities supported by this relay.
109
2
pub(crate) fn supported_protocols() -> tor_protover::Protocols {
110
    // WARNING: REMOVING ELEMENTS FROM THIS LIST CAN BE DANGEROUS!
111
    // SEE [`tor_protover::doc_changing`]
112
    //
113
    // TODO(relay): No DirCache capabilities just yet. Missing HSDir/HSRend/HSIntro.
114
2
    tor_proto::supported_relay_protocols().union(&tor_netdoc::supported_protocols())
115
2
}
116

            
117
fn main() {
118
    // Will exit if '--help' used or there's a parse error.
119
    let cli = cli::Cli::parse();
120

            
121
    if let Err(e) = main_main(cli) {
122
        // TODO: Use arti_client's `HintableError` here (see `arti::main`)?
123
        // TODO: Why do we suppress safe logging?
124
        // TODO: Do we want to log the error?
125
        // We use anyhow's error formatting here rather than `tor_error::report_and_exit` since the
126
        // latter seems to omit some error info and anyhow's error formatting is nicer.
127
        #[allow(clippy::print_stderr)]
128
        with_safe_logging_suppressed(|| {
129
            eprintln!("Error: {e:?}");
130
            // The 127 is copied from `tor_error::report_and_exit`.
131
            // It's unclear why 127 was chosen there.
132
            std::process::exit(127);
133
        });
134
    }
135
}
136

            
137
/// The real main without the error formatting.
138
fn main_main(cli: cli::Cli) -> anyhow::Result<()> {
139
    // Register a basic stderr logger until we have enough info to configure the main logger.
140
    // Unlike arti, we enable timestamps for this pre-config logger.
141
    // TODO: Consider using timestamps with reduced-granularity (see `LogPrecision`).
142
    let level: tracing::metadata::Level = cli
143
        .global
144
        .log_level
145
        .map(Into::into)
146
        .unwrap_or(DEFAULT_LOG_LEVEL);
147
    let filter = EnvFilter::builder()
148
        .with_default_directive(level.into())
149
        .parse("")
150
        .expect("empty filter directive should be trivially parsable");
151
    FmtSubscriber::builder()
152
        .with_env_filter(filter)
153
        .with_ansi(std::io::stderr().is_terminal())
154
        .with_writer(std::io::stderr)
155
        .finish()
156
        .init();
157

            
158
    match cli.command {
159
        #[allow(clippy::print_stdout)]
160
        cli::Commands::BuildInfo => {
161
            println!("Version: {}", env!("CARGO_PKG_VERSION"));
162
            // these are set by our build script
163
            println!("Features: {}", env!("BUILD_FEATURES"));
164
            println!("Profile: {}", env!("BUILD_PROFILE"));
165
            println!("Debug: {}", env!("BUILD_DEBUG"));
166
            println!("Optimization level: {}", env!("BUILD_OPT_LEVEL"));
167
            println!("Rust version: {}", env!("BUILD_RUSTC_VERSION"));
168
            println!("Target triple: {}", env!("BUILD_TARGET"));
169
            println!("Host triple: {}", env!("BUILD_HOST"));
170
        }
171
        cli::Commands::Run(args) => start_relay(args, cli.global)?,
172
    }
173

            
174
    Ok(())
175
}
176

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

            
183
    let mut cfg_sources = global_args
184
        .config()
185
        .context("Failed to get configuration sources")?;
186

            
187
    debug!(
188
        "Using override options: {}",
189
        iter_join(", ", cfg_sources.options()),
190
    );
191

            
192
    // A Mistrust object to use for loading our configuration.
193
    // Elsewhere, we use the value _from_ the configuration.
194
    let cfg_mistrust = if global_args.disable_fs_permission_checks {
195
        fs_mistrust::Mistrust::new_dangerously_trust_everyone()
196
    } else {
197
        fs_mistrust::MistrustBuilder::default()
198
            // By default, a `Mistrust` checks an environment variable.
199
            // We do not (at the moment) want this behaviour for relays:
200
            // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/2699#note_3147502
201
            .ignore_environment()
202
            .build()
203
            .expect("default fs-mistrust should be buildable")
204
    };
205

            
206
    cfg_sources.set_mistrust(cfg_mistrust);
207

            
208
    let cfg = cfg_sources
209
        .load()
210
        .context("Failed to load configuration sources")?;
211
    let config =
212
        tor_config::resolve::<TorRelayConfig>(&cfg).context("Failed to resolve configuration")?;
213

            
214
    // TODO: Configure a proper logger, not just a simple stderr logger.
215
    // TODO: We may want this to be the global logger, but if we use arti's `setup_logging` in the
216
    // future, it returns a `LogGuards` which we'd have no way of holding on to until the
217
    // application exits (see https://gitlab.torproject.org/tpo/core/arti/-/issues/1791).
218
    let filter = EnvFilter::builder()
219
        .parse(&config.logging.console)
220
        .with_context(|| {
221
            format!(
222
                "Failed to parse console logging directive {:?}",
223
                config.logging.console,
224
            )
225
        })?;
226
    let logger = tracing_subscriber::FmtSubscriber::builder()
227
        .with_env_filter(filter)
228
        .with_ansi(std::io::stderr().is_terminal())
229
        .with_writer(std::io::stderr)
230
        .finish();
231
    let logger = tracing::Dispatch::new(logger);
232

            
233
    // Disable safe logging if requested.
234
    // This guard will be dropped at the end of this function,
235
    // which means we effectively re-enable safe logging once this function returns.
236
    // TODO: Do we want this guard behaviour?
237
    // I think it would be better to enable safe-logging forever?
238
    let _safelog_guard = if config.logging.log_sensitive_information {
239
        match safelog::disable_safe_logging() {
240
            Ok(guard) => Some(guard),
241
            Err(e) => {
242
                // We don't need to propagate this error;
243
                // it isn't the end of the world if we were unable to disable safe logging.
244
                warn_report!(e, "Unable to disable safe logging");
245
                None
246
            }
247
        }
248
    } else {
249
        None
250
    };
251

            
252
    if let Some(listen) = {
253
        // https://github.com/metrics-rs/metrics/issues/567
254
        config
255
            .metrics
256
            .prometheus
257
            .listen
258
            .single_address_legacy()
259
            .context("can only listen on a single address for Prometheus metrics")?
260
    } {
261
        cfg_if! {
262
            if #[cfg(feature = "metrics")] {
263
                metrics_exporter_prometheus::PrometheusBuilder::new()
264
                    .with_http_listener(listen)
265
                    .install()
266
                    .with_context(|| format!(
267
                        "set up Prometheus metrics exporter on {listen}"
268
                    ))?;
269
                info!("Arti Prometheus metrics export scraper endpoint http://{listen}");
270
            } else {
271
                let _ = listen;
272
                warn!("`metrics.prometheus.listen` config set but `metrics` cargo feature compiled out in `arti-relay` crate");
273
            }
274
        }
275
    }
276

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

            
280
        // Configure tor-log-ratelim early before we begin logging.
281
        tor_log_ratelim::install_runtime(runtime.clone())
282
            .context("Failed to initialize tor-log-ratelim")?;
283

            
284
        let path_resolver = base_resolver();
285
        let relay =
286
            InertTorRelay::new(config, path_resolver).context("Failed to initialize the relay")?;
287

            
288
        match mainloop(&runtime, run_relay(runtime.clone(), relay))? {
289
            MainloopStatus::Finished(Err(e)) => Err(e),
290
            MainloopStatus::CtrlC => {
291
                info!("Received a ctrl-c; stopping the relay");
292
                Ok(())
293
            }
294
        }
295
    })
296
}
297

            
298
/// A helper to drive a future using a runtime.
299
///
300
/// This calls `block_on` on the runtime.
301
/// The future will be cancelled on a ctrl-c event.
302
fn mainloop<T: Send + 'static>(
303
    runtime: &impl ToplevelRuntime,
304
    fut: impl Future<Output = T> + Send + 'static,
305
) -> anyhow::Result<MainloopStatus<T>> {
306
    trace!("Starting runtime");
307

            
308
    let rv = runtime.block_on(async {
309
        // Code running in 'block_on' runs slower than in a task (in tokio at least),
310
        // so the future is run on a task.
311
        let mut handle = runtime
312
            .spawn_with_handle(fut)
313
            .context("Failed to spawn task")?
314
            .fuse();
315

            
316
        futures::select!(
317
            // Signal handler is registered on the first poll.
318
            res = tokio::signal::ctrl_c().fuse() => {
319
                let () = res.context("Failed to listen for ctrl-c event")?;
320
                trace!("Received a ctrl-c");
321
                // Dropping the handle will cancel the task, so we do that explicitly here.
322
                drop(handle);
323
                Ok(MainloopStatus::CtrlC)
324
            }
325
            x = handle => Ok(MainloopStatus::Finished(x)),
326
        )
327
    });
328

            
329
    trace!("Finished runtime");
330
    rv
331
}
332

            
333
/// Run the relay.
334
///
335
/// This blocks until the relay stops.
336
async fn run_relay<R: Runtime>(
337
    runtime: R,
338
    inert_relay: InertTorRelay,
339
) -> anyhow::Result<void::Void> {
340
    let relay = inert_relay
341
        .init(runtime)
342
        .await
343
        .context("Failed to bootstrap")?;
344

            
345
    // This blocks until end of time or an error.
346
    relay.run().await
347
}
348

            
349
/// Initialize a runtime.
350
///
351
/// Any cli commands that need a runtime should call this so that we use a consistent runtime.
352
fn init_runtime() -> std::io::Result<impl ToplevelRuntime> {
353
    // Use the tokio runtime from tor_rtcompat unless we later find a reason to use tokio directly.
354
    // See https://gitlab.torproject.org/tpo/core/arti/-/work_items/1744.
355
    // Relays must use rustls as native-tls doesn't support
356
    // `CertifiedConn::export_keying_material()`.
357

            
358
    // Note: See comments in `tor_rtcompat::impls::rustls::RustlsProvider`
359
    // about choice of default crypto provider.
360
    let _idempotent_ignore = rustls::crypto::CryptoProvider::install_default(
361
        rustls::crypto::aws_lc_rs::default_provider(),
362
    );
363

            
364
    TokioRustlsRuntime::create()
365
}
366

            
367
/// The result of [`mainloop`].
368
enum MainloopStatus<T> {
369
    /// The result from the completed future.
370
    Finished(T),
371
    /// The future was cancelled due to a ctrl-c event.
372
    CtrlC,
373
}