1
//! A relay binary use to join the Tor network to relay anonymous communication.
2
//!
3
//! NOTE: This binary is still highly experimental as in 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_rtcompat::SpawnExt;
74
use tor_rtcompat::tokio::TokioRustlsRuntime;
75
use tor_rtcompat::{Runtime, ToplevelRuntime};
76
use tracing::{debug, info, trace};
77
use tracing_subscriber::FmtSubscriber;
78
use tracing_subscriber::filter::EnvFilter;
79
use tracing_subscriber::util::SubscriberInitExt;
80

            
81
use crate::config::{DEFAULT_LOG_LEVEL, TorRelayConfig, base_resolver};
82
use crate::relay::InertTorRelay;
83

            
84
fn main() {
85
    // Will exit if '--help' used or there's a parse error.
86
    let cli = cli::Cli::parse();
87

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

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

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

            
141
    Ok(())
142
}
143

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

            
150
    let mut cfg_sources = global_args
151
        .config()
152
        .context("Failed to get configuration sources")?;
153

            
154
    debug!(
155
        "Using override options: {}",
156
        iter_join(", ", cfg_sources.options()),
157
    );
158

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

            
173
    cfg_sources.set_mistrust(cfg_mistrust);
174

            
175
    let cfg = cfg_sources
176
        .load()
177
        .context("Failed to load configuration sources")?;
178
    let config =
179
        tor_config::resolve::<TorRelayConfig>(cfg).context("Failed to resolve configuration")?;
180

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

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

            
203
        // Configure tor-log-ratelim early before we begin logging.
204
        tor_log_ratelim::install_runtime(runtime.clone())
205
            .context("Failed to initialze tor-log-ratelim")?;
206

            
207
        let path_resolver = base_resolver();
208
        let relay =
209
            InertTorRelay::new(config, path_resolver).context("Failed to initialize the relay")?;
210

            
211
        match mainloop(&runtime, run_relay(runtime.clone(), relay))? {
212
            MainloopStatus::Finished(Err(e)) => Err(e),
213
            MainloopStatus::CtrlC => {
214
                info!("Received a ctrl-c; stopping the relay");
215
                Ok(())
216
            }
217
        }
218
    })
219
}
220

            
221
/// A helper to drive a future using a runtime.
222
///
223
/// This calls `block_on` on the runtime.
224
/// The future will be cancelled on a ctrl-c event.
225
fn mainloop<T: Send + 'static>(
226
    runtime: &impl ToplevelRuntime,
227
    fut: impl Future<Output = T> + Send + 'static,
228
) -> anyhow::Result<MainloopStatus<T>> {
229
    trace!("Starting runtime");
230

            
231
    let rv = runtime.block_on(async {
232
        // Code running in 'block_on' runs slower than in a task (in tokio at least),
233
        // so the future is run on a task.
234
        let mut handle = runtime
235
            .spawn_with_handle(fut)
236
            .context("Failed to spawn task")?
237
            .fuse();
238

            
239
        futures::select!(
240
            // Signal handler is registered on the first poll.
241
            res = tokio::signal::ctrl_c().fuse() => {
242
                let () = res.context("Failed to listen for ctrl-c event")?;
243
                trace!("Received a ctrl-c");
244
                // Dropping the handle will cancel the task, so we do that explicitly here.
245
                drop(handle);
246
                Ok(MainloopStatus::CtrlC)
247
            }
248
            x = handle => Ok(MainloopStatus::Finished(x)),
249
        )
250
    });
251

            
252
    trace!("Finished runtime");
253
    rv
254
}
255

            
256
/// Run the relay.
257
///
258
/// This blocks until the relay stops.
259
async fn run_relay<R: Runtime>(
260
    runtime: R,
261
    inert_relay: InertTorRelay,
262
) -> anyhow::Result<void::Void> {
263
    let relay = inert_relay
264
        .init(runtime)
265
        .await
266
        .context("Failed to bootstrap")?;
267
    // This blocks until end of time or an error.
268
    relay.run().await
269
}
270

            
271
/// Initialize a runtime.
272
///
273
/// Any cli commands that need a runtime should call this so that we use a consistent runtime.
274
fn init_runtime() -> std::io::Result<impl ToplevelRuntime> {
275
    // Use the tokio runtime from tor_rtcompat unless we later find a reason to use tokio directly.
276
    // See https://gitlab.torproject.org/tpo/core/arti/-/work_items/1744.
277
    // Relays must use rustls as native-tls doesn't support
278
    // `CertifiedConn::export_keying_material()`.
279

            
280
    // Note: See comments in `tor_rtcompat::impls::rustls::RustlsProvider`
281
    // about choice of default crypto provider.
282
    let _idempotent_ignore =
283
        rustls::crypto::CryptoProvider::install_default(rustls::crypto::ring::default_provider());
284

            
285
    TokioRustlsRuntime::create()
286
}
287

            
288
/// The result of [`mainloop`].
289
enum MainloopStatus<T> {
290
    /// The result from the completed future.
291
    Finished(T),
292
    /// The future was cancelled due to a ctrl-c event.
293
    CtrlC,
294
}