arti/
lib.rs

1#![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg))]
2#![doc = include_str!("../README.md")]
3// @@ begin lint list maintained by maint/add_warning @@
4#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6#![warn(missing_docs)]
7#![warn(noop_method_call)]
8#![warn(unreachable_pub)]
9#![warn(clippy::all)]
10#![deny(clippy::await_holding_lock)]
11#![deny(clippy::cargo_common_metadata)]
12#![deny(clippy::cast_lossless)]
13#![deny(clippy::checked_conversions)]
14#![warn(clippy::cognitive_complexity)]
15#![deny(clippy::debug_assert_with_mut_call)]
16#![deny(clippy::exhaustive_enums)]
17#![deny(clippy::exhaustive_structs)]
18#![deny(clippy::expl_impl_clone_on_copy)]
19#![deny(clippy::fallible_impl_from)]
20#![deny(clippy::implicit_clone)]
21#![deny(clippy::large_stack_arrays)]
22#![warn(clippy::manual_ok_or)]
23#![deny(clippy::missing_docs_in_private_items)]
24#![warn(clippy::needless_borrow)]
25#![warn(clippy::needless_pass_by_value)]
26#![warn(clippy::option_option)]
27#![deny(clippy::print_stderr)]
28#![deny(clippy::print_stdout)]
29#![warn(clippy::rc_buffer)]
30#![deny(clippy::ref_option_ref)]
31#![warn(clippy::semicolon_if_nothing_returned)]
32#![warn(clippy::trait_duplication_in_bounds)]
33#![deny(clippy::unchecked_duration_subtraction)]
34#![deny(clippy::unnecessary_wraps)]
35#![warn(clippy::unseparated_literal_suffix)]
36#![deny(clippy::unwrap_used)]
37#![deny(clippy::mod_module_files)]
38#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39#![allow(clippy::uninlined_format_args)]
40#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43#![allow(clippy::needless_lifetimes)] // See arti#1765
44#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46
47// TODO #1645 (either remove this, or decide to have it everywhere)
48#![cfg_attr(not(all(feature = "full", feature = "experimental")), allow(unused))]
49// Overrides specific to this crate:
50#![allow(clippy::print_stderr)]
51#![allow(clippy::print_stdout)]
52
53pub mod cfg;
54pub mod logging;
55#[cfg(not(feature = "onion-service-service"))]
56mod onion_proxy_disabled;
57
58mod subcommands;
59
60/// Helper:
61/// Declare a series of modules as public if experimental_api is set,
62/// and as non-public otherwise.
63//
64// TODO: We'd like to use visibility::make(pub) here, but it doesn't
65// work on modules.
66macro_rules! semipublic_mod {
67    {
68        $(
69            $( #[$meta:meta] )*
70            mod $name:ident ;
71        )*
72    }  => {
73        $(
74            $( #[$meta])*
75            cfg_if::cfg_if! {
76                if #[cfg(feature="experimental-api")] {
77                   pub mod $name;
78                } else {
79                   mod $name;
80                }
81            }
82         )*
83    }
84}
85
86semipublic_mod! {
87    #[cfg(feature = "dns-proxy")]
88    mod dns;
89    mod exit;
90    #[cfg(feature="onion-service-service")]
91    mod onion_proxy;
92    mod process;
93    mod reload_cfg;
94    mod socks;
95}
96#[cfg_attr(not(feature = "rpc"), path = "rpc_stub.rs")]
97mod rpc;
98
99use std::ffi::OsString;
100use std::fmt::Write;
101
102pub use cfg::{
103    ApplicationConfig, ApplicationConfigBuilder, ArtiCombinedConfig, ArtiConfig, ArtiConfigBuilder,
104    ProxyConfig, ProxyConfigBuilder, SystemConfig, SystemConfigBuilder, ARTI_EXAMPLE_CONFIG,
105};
106pub use logging::{LoggingConfig, LoggingConfigBuilder};
107
108use arti_client::config::default_config_files;
109use arti_client::TorClient;
110use safelog::with_safe_logging_suppressed;
111use tor_config::mistrust::BuilderExt as _;
112use tor_config::ConfigurationSources;
113use tor_rtcompat::ToplevelRuntime;
114
115use anyhow::{Context, Error, Result};
116use clap::{value_parser, Arg, ArgAction, Command};
117#[allow(unused_imports)]
118use tracing::{error, info, warn};
119
120#[cfg(any(
121    feature = "hsc",
122    feature = "onion-service-service",
123    feature = "onion-service-cli-extra"
124))]
125use clap::Subcommand as _;
126
127#[cfg(feature = "experimental-api")]
128#[cfg_attr(docsrs, doc(cfg(feature = "experimental-api")))]
129pub use subcommands::proxy::run_proxy as run;
130
131/// Create a runtime for Arti to use.
132fn create_runtime() -> std::io::Result<impl ToplevelRuntime> {
133    cfg_if::cfg_if! {
134        if #[cfg(all(feature="tokio", feature="native-tls"))] {
135            use tor_rtcompat::tokio::TokioNativeTlsRuntime as ChosenRuntime;
136        } else if #[cfg(all(feature="tokio", feature="rustls"))] {
137            use tor_rtcompat::tokio::TokioRustlsRuntime as ChosenRuntime;
138            let _idempotent_ignore = rustls_crate::crypto::CryptoProvider::install_default(
139                rustls_crate::crypto::ring::default_provider(),
140
141            );
142        } else if #[cfg(all(feature="async-std", feature="native-tls"))] {
143            use tor_rtcompat::async_std::AsyncStdNativeTlsRuntime as ChosenRuntime;
144        } else if #[cfg(all(feature="async-std", feature="rustls"))] {
145            use tor_rtcompat::async_std::AsyncStdRustlsRuntime as ChosenRuntime;
146            let _idempotent_ignore = rustls_crate::crypto::CryptoProvider::install_default(
147                rustls_crate::crypto::ring::default_provider(),
148            );
149        } else {
150            compile_error!("You must configure both an async runtime and a TLS stack. See doc/TROUBLESHOOTING.md for more.");
151        }
152    }
153    ChosenRuntime::create()
154}
155
156/// Return a (non-exhaustive) array of enabled Cargo features, for version printing purposes.
157fn list_enabled_features() -> &'static [&'static str] {
158    // HACK(eta): We can't get this directly, so we just do this awful hack instead.
159    // Note that we only list features that aren't about the runtime used, since that already
160    // gets printed separately.
161    &[
162        #[cfg(feature = "journald")]
163        "journald",
164        #[cfg(any(feature = "static-sqlite", feature = "static"))]
165        "static-sqlite",
166        #[cfg(any(feature = "static-native-tls", feature = "static"))]
167        "static-native-tls",
168    ]
169}
170
171/// Inner function, to handle a set of CLI arguments and return a single
172/// `Result<()>` for convenient handling.
173///
174/// # ⚠️ Warning! ⚠️
175///
176/// If your program needs to call this function, you are setting yourself up for
177/// some serious maintenance headaches.  See discussion on [`main`] and please
178/// reach out to help us build you a better API.
179///
180/// # Panics
181///
182/// Currently, might panic if wrong arguments are specified.
183#[cfg_attr(feature = "experimental-api", visibility::make(pub))]
184#[allow(clippy::cognitive_complexity)]
185fn main_main<I, T>(cli_args: I) -> Result<()>
186where
187    I: IntoIterator<Item = T>,
188    T: Into<std::ffi::OsString> + Clone,
189{
190    // We describe a default here, rather than using `default()`, because the
191    // correct behavior is different depending on whether the filename is given
192    // explicitly or not.
193    let mut config_file_help = "Specify which config file(s) to read.".to_string();
194    if let Ok(default) = default_config_files() {
195        // If we couldn't resolve the default config file, then too bad.  If something
196        // actually tries to use it, it will produce an error, but don't fail here
197        // just for that reason.
198        write!(config_file_help, " Defaults to {:?}", default).expect("Can't write to string");
199    }
200
201    // We create the runtime now so that we can use its `Debug` impl to describe it for
202    // the version string.
203    let runtime = create_runtime()?;
204    let features = list_enabled_features();
205    let long_version = format!(
206        "{}\nusing runtime: {:?}\noptional features: {}",
207        env!("CARGO_PKG_VERSION"),
208        runtime,
209        if features.is_empty() {
210            "<none>".into()
211        } else {
212            features.join(", ")
213        }
214    );
215
216    let clap_app = Command::new("Arti")
217            .version(env!("CARGO_PKG_VERSION"))
218            .long_version(long_version)
219            .author("The Tor Project Developers")
220            .about("A Rust Tor implementation.")
221            // HACK(eta): clap generates "arti [OPTIONS] <SUBCOMMAND>" for this usage string by
222            //            default, but then fails to parse options properly if you do put them
223            //            before the subcommand.
224            //            We just declare all options as `global` and then require them to be
225            //            put after the subcommand, hence this new usage string.
226            .override_usage("arti <SUBCOMMAND> [OPTIONS]")
227            .arg(
228                Arg::new("config-files")
229                    .short('c')
230                    .long("config")
231                    .action(ArgAction::Set)
232                    .value_name("FILE")
233                    .value_parser(value_parser!(OsString))
234                    .action(ArgAction::Append)
235                    // NOTE: don't forget the `global` flag on all arguments declared at this level!
236                    .global(true)
237                    .help(config_file_help),
238            )
239            .arg(
240                Arg::new("option")
241                    .short('o')
242                    .action(ArgAction::Set)
243                    .value_name("KEY=VALUE")
244                    .action(ArgAction::Append)
245                    .global(true)
246                    .help("Override config file parameters, using TOML-like syntax."),
247            )
248            .arg(
249                Arg::new("loglevel")
250                    .short('l')
251                    .long("log-level")
252                    .global(true)
253                    .action(ArgAction::Set)
254                    .value_name("LEVEL")
255                    .help("Override the log level (usually one of 'trace', 'debug', 'info', 'warn', 'error')."),
256            )
257            .arg(
258                Arg::new("disable-fs-permission-checks")
259                    .long("disable-fs-permission-checks")
260                    .global(true)
261                    .action(ArgAction::SetTrue)
262                    .help("Don't check permissions on the files we use."),
263            )
264            .subcommand(
265                Command::new("proxy")
266                    .about(
267                        "Run Arti in SOCKS proxy mode, proxying connections through the Tor network.",
268                    )
269                    .arg(
270                        Arg::new("socks-port")
271                            .short('p')
272                            .action(ArgAction::Set)
273                            .value_name("PORT")
274                            .help("Port to listen on for SOCKS connections (overrides the port in the config if specified).")
275                    )
276                    .arg(
277                        Arg::new("dns-port")
278                            .short('d')
279                            .action(ArgAction::Set)
280                            .value_name("PORT")
281                            .help("Port to listen on for DNS request (overrides the port in the config if specified).")
282                    )
283            )
284            .subcommand_required(true)
285            .arg_required_else_help(true);
286
287    // When adding a subcommand, it may be necessary to add an entry in
288    // `maint/check-cli-help`, to the function `help_arg`.
289
290    cfg_if::cfg_if! {
291        if #[cfg(feature = "onion-service-service")] {
292            let clap_app = subcommands::hss::HssSubcommands::augment_subcommands(clap_app);
293        }
294    }
295
296    cfg_if::cfg_if! {
297        if #[cfg(feature = "hsc")] {
298            let clap_app = subcommands::hsc::HscSubcommands::augment_subcommands(clap_app);
299        }
300    }
301
302    cfg_if::cfg_if! {
303        if #[cfg(feature = "onion-service-cli-extra")] {
304            let clap_app = subcommands::keys::KeysSubcommands::augment_subcommands(clap_app);
305        }
306    }
307
308    // Tracing doesn't log anything when there is no subscriber set.  But we want to see
309    // logging messages from config parsing etc.  We can't set the global default subscriber
310    // because we can only set it once.  The other ways involve a closure.  So we have a
311    // closure for all the startup code which runs *before* we set the logging properly.
312    //
313    // There is no cooked way to print our program name, so we do it like this.  This
314    // closure is called to "make" a "Writer" for each message, so it runs at the right time:
315    // before each message.
316    let pre_config_logging_writer = || {
317        // Weirdly, with .without_time(), tracing produces messages with a leading space.
318        eprint!("arti:");
319        std::io::stderr()
320    };
321    let pre_config_logging = tracing_subscriber::fmt()
322        .without_time()
323        .with_writer(pre_config_logging_writer)
324        .finish();
325    let pre_config_logging = tracing::Dispatch::new(pre_config_logging);
326    let pre_config_logging_ret = tracing::dispatcher::with_default(&pre_config_logging, || {
327        let matches = clap_app.try_get_matches_from(cli_args)?;
328
329        let fs_mistrust_disabled = matches.get_flag("disable-fs-permission-checks");
330
331        // A Mistrust object to use for loading our configuration.  Elsewhere, we
332        // use the value _from_ the configuration.
333        let cfg_mistrust = if fs_mistrust_disabled {
334            fs_mistrust::Mistrust::new_dangerously_trust_everyone()
335        } else {
336            fs_mistrust::MistrustBuilder::default()
337                .build_for_arti()
338                .expect("Could not construct default fs-mistrust")
339        };
340
341        let mut override_options: Vec<String> = matches
342            .get_many::<String>("option")
343            .unwrap_or_default()
344            .cloned()
345            .collect();
346        if fs_mistrust_disabled {
347            override_options.push("storage.permissions.dangerously_trust_everyone=true".to_owned());
348        }
349
350        let cfg_sources = {
351            let mut cfg_sources = ConfigurationSources::try_from_cmdline(
352                || default_config_files().context("identify default config file locations"),
353                matches
354                    .get_many::<OsString>("config-files")
355                    .unwrap_or_default(),
356                override_options,
357            )?;
358            cfg_sources.set_mistrust(cfg_mistrust);
359            cfg_sources
360        };
361
362        let cfg = cfg_sources.load()?;
363        let (config, client_config) =
364            tor_config::resolve::<ArtiCombinedConfig>(cfg).context("read configuration")?;
365
366        let log_mistrust = client_config.fs_mistrust().clone();
367
368        Ok::<_, Error>((matches, cfg_sources, config, client_config, log_mistrust))
369    })?;
370    // Sadly I don't seem to be able to persuade rustfmt to format the two lists of
371    // variable names identically.
372    let (matches, cfg_sources, config, client_config, log_mistrust) = pre_config_logging_ret;
373
374    let _log_guards = logging::setup_logging(
375        config.logging(),
376        &log_mistrust,
377        client_config.as_ref(),
378        matches.get_one::<String>("loglevel").map(|s| s.as_str()),
379    )?;
380
381    if !config.application().allow_running_as_root {
382        process::exit_if_root();
383    }
384
385    #[cfg(feature = "harden")]
386    if !config.application().permit_debugging {
387        if let Err(e) = process::enable_process_hardening() {
388            error!("Encountered a problem while enabling hardening. To disable this feature, set application.permit_debugging to true.");
389            return Err(e);
390        }
391    }
392
393    // Check for the "proxy" subcommand.
394    if let Some(proxy_matches) = matches.subcommand_matches("proxy") {
395        return subcommands::proxy::run(runtime, proxy_matches, cfg_sources, config, client_config);
396    }
397
398    // Check for the optional "keys" subcommand.
399    cfg_if::cfg_if! {
400        if #[cfg(feature = "onion-service-cli-extra")] {
401            if let Some(keys_matches) = matches.subcommand_matches("keys") {
402                return subcommands::keys::run(runtime, keys_matches, &client_config);
403            }
404        }
405    }
406
407    // Check for the optional "hss" subcommand.
408    cfg_if::cfg_if! {
409        if #[cfg(feature = "onion-service-service")] {
410            if let Some(hss_matches) = matches.subcommand_matches("hss") {
411                return subcommands::hss::run(hss_matches, &config, &client_config);
412            }
413        }
414    }
415
416    // Check for the optional "hsc" subcommand.
417    cfg_if::cfg_if! {
418        if #[cfg(feature = "hsc")] {
419            if let Some(hsc_matches) = matches.subcommand_matches("hsc") {
420                return subcommands::hsc::run(runtime, hsc_matches, &client_config);
421            }
422        }
423    }
424
425    panic!("Subcommand added to clap subcommand list, but not yet implemented");
426}
427
428/// Main program, callable directly from a binary crate's `main`
429///
430/// This function behaves the same as `main_main()`, except:
431///   * It takes command-line arguments from `std::env::args_os` rather than
432///     from an argument.
433///   * It exits the process with an appropriate error code on error.
434///
435/// # ⚠️ Warning ⚠️
436///
437/// Calling this function, or the related experimental function `main_main`, is
438/// probably a bad idea for your code.  It means that you are invoking Arti as
439/// if from the command line, but keeping it embedded inside your process. Doing
440/// this will block your process take over handling for several signal types,
441/// possibly disable debugger attachment, and a lot more junk that a library
442/// really has no business doing for you.  It is not designed to run in this
443/// way, and may give you strange results.
444///
445/// If the functionality you want is available in [`arti_client`] crate, or from
446/// a *non*-experimental API in this crate, it would be better for you to use
447/// that API instead.
448///
449/// Alternatively, if you _do_ need some underlying function from the `arti`
450/// crate, it would be better for all of us if you had a stable interface to that
451/// function. Please reach out to the Arti developers, so we can work together
452/// to get you the stable API you need.
453pub fn main() {
454    match main_main(std::env::args_os()) {
455        Ok(()) => {}
456        Err(e) => {
457            use arti_client::HintableError;
458            if let Some(hint) = e.hint() {
459                info!("{}", hint);
460            }
461
462            match e.downcast_ref::<clap::Error>() {
463                Some(clap_err) => clap_err.exit(),
464                None => with_safe_logging_suppressed(|| tor_error::report_and_exit(e)),
465            }
466        }
467    }
468}