1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![doc = include_str!("../README.md")]
3#![allow(renamed_and_removed_lints)] #![allow(unknown_lints)] #![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#![allow(clippy::cognitive_complexity)] #![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#![warn(clippy::or_fun_call)]
28#![deny(clippy::print_stderr)]
29#![deny(clippy::print_stdout)]
30#![warn(clippy::rc_buffer)]
31#![deny(clippy::ref_option_ref)]
32#![warn(clippy::semicolon_if_nothing_returned)]
33#![warn(clippy::trait_duplication_in_bounds)]
34#![deny(clippy::unchecked_time_subtraction)]
35#![deny(clippy::unnecessary_wraps)]
36#![warn(clippy::unseparated_literal_suffix)]
37#![deny(clippy::unwrap_used)]
38#![deny(clippy::mod_module_files)]
39#![allow(clippy::let_unit_value)] #![allow(clippy::uninlined_format_args)]
41#![allow(clippy::significant_drop_in_scrutinee)] #![allow(clippy::result_large_err)] #![allow(clippy::needless_raw_string_hashes)] #![allow(clippy::needless_lifetimes)] #![allow(mismatched_lifetime_syntaxes)] #![allow(clippy::collapsible_if)] #![deny(clippy::unused_async)]
48#![deny(clippy::string_slice)] #![allow(recursion_depth_exceeding_limit)] #![cfg_attr(not(all(feature = "full", feature = "experimental")), allow(unused))]
54#![allow(clippy::print_stderr)]
56#![allow(clippy::print_stdout)]
57
58mod subcommands;
59
60macro_rules! semipublic_mod {
67 {
68 $(
69 $( #[$meta:meta] )*
70 $dflt_vis:vis mod $name:ident ;
71 )*
72 } => {
73 $(
74 cfg_if::cfg_if! {
75 if #[cfg(feature="experimental-api")] {
76 $( #[$meta])*
77 pub mod $name;
78 } else {
79 $( #[$meta])*
80 $dflt_vis mod $name;
81 }
82 }
83 )*
84 }
85}
86
87macro_rules! semipublic_use {
91 {
92 $dflt_vis:vis use $($tok:tt)+
93 } => {
94 cfg_if::cfg_if! {
95 if #[cfg(feature="experimental-api")] {
96 pub use $($tok)+
97 } else {
98 $dflt_vis use $($tok)+
99 }
100 }
101 }
102}
103
104semipublic_mod! {
105 mod cfg;
106 #[cfg(feature = "dns-proxy")]
107 mod dns;
108 mod exit;
109 mod logging;
110 #[cfg(feature="onion-service-service")]
111 mod onion_proxy;
112 mod process;
113 mod reload_cfg;
114 mod proxy;
115}
116
117cfg_if::cfg_if! {
118 if #[cfg(all(feature="experimental-api", feature="rpc"))] {
119 pub mod rpc;
120 } else if #[cfg(all(feature="experimental-api", not(feature="rpc")))] {
121 #[path = "rpc_stub.rs"]
122 pub mod rpc;
123 } else if #[cfg(feature = "rpc")] {
124 mod rpc;
125 } else {
126 #[path = "rpc_stub.rs"]
127 mod rpc;
128 }
129}
130
131use std::ffi::OsString;
132use std::fmt::Write;
133
134semipublic_use! {
135 use cfg::{
136 ARTI_EXAMPLE_CONFIG, ApplicationConfig, ApplicationConfigBuilder, ArtiCombinedConfig,
137 ArtiConfig, ArtiConfigBuilder, ProxyConfig, ProxyConfigBuilder, SystemConfig,
138 SystemConfigBuilder,
139 };
140}
141semipublic_use! {
142 use logging::{LoggingConfig, LoggingConfigBuilder};
143}
144
145use arti_client::TorClient;
146use arti_client::config::default_config_files;
147use safelog::with_safe_logging_suppressed;
148use tor_config::ConfigurationSources;
149use tor_config::mistrust::BuilderExt as _;
150use tor_rtcompat::ToplevelRuntime;
151
152use anyhow::{Context, Error, Result};
153use clap::{Arg, ArgAction, Command, value_parser};
154#[allow(unused_imports)]
155use tracing::{error, info, instrument, warn};
156
157#[cfg(any(
158 feature = "hsc",
159 feature = "onion-service-service",
160 feature = "onion-service-cli-extra",
161))]
162use clap::Subcommand as _;
163
164#[cfg(feature = "experimental-api")]
165#[cfg_attr(docsrs, doc(cfg(feature = "experimental-api")))]
166pub use subcommands::proxy::run_proxy;
167
168#[allow(dead_code)]
170#[cfg(feature = "rustls-base")]
171fn rustls_crypto_provider() -> rustls_crate::crypto::CryptoProvider {
172 cfg_if::cfg_if! {
173 if #[cfg(feature = "rustls-aws-lc-rs")] {
174 rustls_crate::crypto::aws_lc_rs::default_provider()
175 } else if #[cfg(feature = "rustls-ring")]{
176 rustls_crate::crypto::ring::default_provider()
177 } else {
178 compile_error!(r#"When building with rustls, you must select "rustls-aws-lc-rs" or "rustls-ring". \
179 "rustls" is an alias for one of these."#);
180 }
182 }
183}
184
185fn create_runtime() -> std::io::Result<impl ToplevelRuntime> {
187 cfg_if::cfg_if! {
188 if #[cfg(all(feature="tokio", feature="native-tls"))] {
189 use tor_rtcompat::tokio::TokioNativeTlsRuntime as ChosenRuntime;
190 } else if #[cfg(all(feature="tokio", feature="rustls-base"))] {
191 use tor_rtcompat::tokio::TokioRustlsRuntime as ChosenRuntime;
192 let _idempotent_ignore = rustls_crate::crypto::CryptoProvider::install_default(
195 rustls_crypto_provider()
196 );
197 } else if #[cfg(all(feature="async-std", feature="native-tls"))] {
198 use tor_rtcompat::async_std::AsyncStdNativeTlsRuntime as ChosenRuntime;
199 } else if #[cfg(all(feature="async-std", feature="rustls-base"))] {
200 use tor_rtcompat::async_std::AsyncStdRustlsRuntime as ChosenRuntime;
201 let _idempotent_ignore = rustls_crate::crypto::CryptoProvider::install_default(
204 rustls_crypto_provider()
205 );
206 } else {
207 compile_error!("You must configure both an async runtime and a TLS stack. See doc/TROUBLESHOOTING.md for more.");
208 }
209 }
210 ChosenRuntime::create()
211}
212
213fn list_enabled_features() -> &'static [&'static str] {
215 &[
219 #[cfg(feature = "journald")]
220 "journald",
221 #[cfg(any(feature = "static-sqlite", feature = "static"))]
222 "static-sqlite",
223 #[cfg(any(feature = "static-native-tls", feature = "static"))]
224 "static-native-tls",
225 ]
226}
227
228#[cfg_attr(feature = "experimental-api", visibility::make(pub))]
241#[instrument(skip_all, level = "trace")]
242fn main_main<I, T>(cli_args: I) -> Result<()>
243where
244 I: IntoIterator<Item = T>,
245 T: Into<std::ffi::OsString> + Clone,
246{
247 let mut config_file_help = "Specify which config file(s) to read.".to_string();
251 if let Ok(default) = default_config_files() {
252 write!(config_file_help, " Defaults to {:?}", default).expect("Can't write to string");
256 }
257
258 let runtime = create_runtime()?;
259
260 tor_log_ratelim::install_runtime(runtime.clone())
262 .context("Failed to initialize tor-log-ratelim")?;
263
264 let features = list_enabled_features();
266 let long_version = format!(
267 "{}\nusing runtime: {:?}\noptional features: {}",
268 env!("CARGO_PKG_VERSION"),
269 runtime,
270 if features.is_empty() {
271 "<none>".into()
272 } else {
273 features.join(", ")
274 }
275 );
276
277 let clap_app = Command::new("Arti")
278 .override_usage("arti <SUBCOMMAND> [OPTIONS]")
284 .arg(
285 Arg::new("config-files")
286 .short('c')
287 .long("config")
288 .action(ArgAction::Set)
289 .value_name("FILE")
290 .value_parser(value_parser!(OsString))
291 .action(ArgAction::Append)
292 .global(true)
294 .help(config_file_help),
295 )
296 .arg(
297 Arg::new("option")
298 .short('o')
299 .action(ArgAction::Set)
300 .value_name("KEY=VALUE")
301 .action(ArgAction::Append)
302 .global(true)
303 .help("Override config file parameters, using TOML-like syntax."),
304 )
305 .arg(
306 Arg::new("loglevel")
307 .short('l')
308 .long("log-level")
309 .global(true)
310 .action(ArgAction::Set)
311 .value_name("LEVEL")
312 .help("Override the log level (usually one of 'trace', 'debug', 'info', 'warn', 'error')."),
313 )
314 .arg(
315 Arg::new("disable-fs-permission-checks")
316 .long("disable-fs-permission-checks")
317 .global(true)
318 .action(ArgAction::SetTrue)
319 .help("Don't check permissions on the files we use."),
320 )
321 .subcommand(
322 Command::new("proxy")
323 .about(
324 "Run Arti in proxy mode, proxying connections through the Tor network.",
325 )
326 .arg(
327 Arg::new("socks-port")
329 .short('p')
330 .action(ArgAction::Set)
331 .value_name("PORT")
332 .value_parser(clap::value_parser!(u16))
333 .help(r#"Localhost port to listen on for SOCKS connections (0 means "disabled"; overrides addresses in the config if specified)."#)
334 )
335 .arg(
336 Arg::new("dns-port")
337 .short('d')
338 .action(ArgAction::Set)
339 .value_name("PORT")
340 .value_parser(clap::value_parser!(u16))
341 .help(r#"Localhost port to listen on for DNS requests (0 means "disabled"; overrides addresses in the config if specified)."#)
342 )
343 )
344 .subcommand_required(true)
345 .arg_required_else_help(true);
346
347 cfg_if::cfg_if! {
351 if #[cfg(feature = "onion-service-service")] {
352 let clap_app = subcommands::hss::HssSubcommands::augment_subcommands(clap_app);
353 }
354 }
355
356 cfg_if::cfg_if! {
357 if #[cfg(feature = "hsc")] {
358 let clap_app = subcommands::hsc::HscSubcommands::augment_subcommands(clap_app);
359 }
360 }
361
362 cfg_if::cfg_if! {
363 if #[cfg(feature = "onion-service-cli-extra")] {
364 let clap_app = subcommands::keys::KeysSubcommands::augment_subcommands(clap_app);
365 let clap_app = subcommands::raw::RawSubcommands::augment_subcommands(clap_app);
366 }
367 }
368
369 let clap_app = clap_app
370 .version(env!("CARGO_PKG_VERSION"))
371 .long_version(long_version)
372 .author("The Tor Project Developers")
373 .about("A Rust Tor implementation.");
374
375 let pre_config_logging_writer = || {
384 eprint!("arti:");
386 std::io::stderr()
387 };
388 let pre_config_logging = tracing_subscriber::fmt()
389 .without_time()
390 .with_writer(pre_config_logging_writer)
391 .finish();
392 let pre_config_logging = tracing::Dispatch::new(pre_config_logging);
393 let pre_config_logging_ret = tracing::dispatcher::with_default(&pre_config_logging, || {
394 let matches = clap_app.try_get_matches_from(cli_args)?;
395
396 let fs_mistrust_disabled = matches.get_flag("disable-fs-permission-checks");
397
398 let cfg_mistrust = if fs_mistrust_disabled {
401 fs_mistrust::Mistrust::new_dangerously_trust_everyone()
402 } else {
403 fs_mistrust::MistrustBuilder::default()
404 .build_for_arti()
405 .expect("Could not construct default fs-mistrust")
406 };
407
408 let mut override_options: Vec<String> = matches
409 .get_many::<String>("option")
410 .unwrap_or_default()
411 .cloned()
412 .collect();
413 if fs_mistrust_disabled {
414 override_options.push("storage.permissions.dangerously_trust_everyone=true".to_owned());
415 }
416
417 let cfg_sources = {
418 let mut cfg_sources = ConfigurationSources::try_from_cmdline(
419 || default_config_files().context("identify default config file locations"),
420 matches
421 .get_many::<OsString>("config-files")
422 .unwrap_or_default(),
423 override_options,
424 )?;
425 cfg_sources.set_mistrust(cfg_mistrust);
426 cfg_sources
427 };
428
429 let cfg = cfg_sources.load()?;
430 let (config, client_config) =
431 tor_config::resolve::<ArtiCombinedConfig>(&cfg).context("read configuration")?;
432
433 let log_mistrust = client_config.fs_mistrust().clone();
434
435 Ok::<_, Error>((
436 matches,
437 cfg_sources,
438 cfg,
439 config,
440 client_config,
441 log_mistrust,
442 ))
443 })?;
444 let (matches, cfg_sources, loaded_cfg_tree, config, client_config, log_mistrust) =
447 pre_config_logging_ret;
448
449 let _log_guards = logging::setup_logging(
450 config.logging(),
451 &log_mistrust,
452 client_config.as_ref(),
453 matches.get_one::<String>("loglevel").map(|s| s.as_str()),
454 )?;
455
456 if !config.application().allow_running_as_root {
457 process::exit_if_root();
458 }
459
460 #[cfg(feature = "harden")]
461 if !config.application().permit_debugging {
462 if let Err(e) = tor_bin_common::process::harden::enable_process_hardening() {
463 error!(
464 "Encountered a problem while enabling hardening. To disable this feature, set application.permit_debugging to true."
465 );
466 return Err(e.into());
467 }
468 }
469
470 if let Some(proxy_matches) = matches.subcommand_matches("proxy") {
472 return subcommands::proxy::run(
473 runtime,
474 proxy_matches,
475 cfg_sources,
476 loaded_cfg_tree,
477 config,
478 client_config,
479 );
480 }
481
482 cfg_if::cfg_if! {
484 if #[cfg(feature = "onion-service-cli-extra")] {
485 if let Some(keys_matches) = matches.subcommand_matches("keys") {
486 return subcommands::keys::run(runtime, keys_matches, &config, &client_config);
487 } else if let Some(raw_matches) = matches.subcommand_matches("keys-raw") {
488 return subcommands::raw::run(runtime, raw_matches, &client_config);
489 }
490 }
491 }
492
493 cfg_if::cfg_if! {
495 if #[cfg(feature = "onion-service-service")] {
496 if let Some(hss_matches) = matches.subcommand_matches("hss") {
497 return subcommands::hss::run(runtime, hss_matches, &config, &client_config);
498 }
499 }
500 }
501
502 cfg_if::cfg_if! {
504 if #[cfg(feature = "hsc")] {
505 if let Some(hsc_matches) = matches.subcommand_matches("hsc") {
506 return subcommands::hsc::run(runtime, hsc_matches, &client_config);
507 }
508 }
509 }
510
511 panic!("Subcommand added to clap subcommand list, but not yet implemented");
512}
513
514pub fn main() {
540 match main_main(std::env::args_os()) {
541 Ok(()) => {}
542 Err(e) => {
543 use arti_client::HintableError;
544 if let Some(hint) = e.hint() {
545 info!("{}", hint);
546 }
547
548 match e.downcast_ref::<clap::Error>() {
549 Some(clap_err) => clap_err.exit(),
550 None => with_safe_logging_suppressed(|| tor_error::report_and_exit(e)),
551 }
552 }
553 }
554}