1#![cfg_attr(docsrs, feature(doc_auto_cfg, 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#![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)] #![allow(clippy::uninlined_format_args)]
40#![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)] #![cfg_attr(not(all(feature = "full", feature = "experimental")), allow(unused))]
49#![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
60macro_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
131fn 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
156fn list_enabled_features() -> &'static [&'static str] {
158 &[
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#[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 let mut config_file_help = "Specify which config file(s) to read.".to_string();
194 if let Ok(default) = default_config_files() {
195 write!(config_file_help, " Defaults to {:?}", default).expect("Can't write to string");
199 }
200
201 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 .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 .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 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 let pre_config_logging_writer = || {
317 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 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 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 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 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 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 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
428pub 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}