arti_relay/
cli.rs

1//! The command-line interface.
2//!
3//! See [`Cli`].
4
5use std::ffi::OsString;
6use std::path::PathBuf;
7
8use clap::{Args, Command, Parser, Subcommand, ValueEnum};
9use fs_mistrust::anon_home::PathExt as _;
10use once_cell::sync::Lazy;
11use tor_config::{ConfigurationSource, ConfigurationSources};
12use tor_config_path::CfgPathError;
13
14use crate::config::default_config_paths;
15
16/// A cached copy of the default config paths.
17///
18/// We cache the values to ensure they are consistent between the help text and the values used.
19static DEFAULT_CONFIG_PATHS: Lazy<Result<Vec<PathBuf>, CfgPathError>> =
20    Lazy::new(default_config_paths);
21
22/// A Rust Tor relay implementation.
23#[derive(Clone, Debug, Parser)]
24#[command(author = "The Tor Project Developers")]
25#[command(version)]
26#[command(defer = cli_cmd_post_processing)]
27pub(crate) struct Cli {
28    /// Sub-commands.
29    #[command(subcommand)]
30    pub(crate) command: Commands,
31
32    /// Global arguments available for all sub-commands.
33    ///
34    /// These arguments may be specified before or after the subcommand argument.
35    #[clap(flatten)]
36    pub(crate) global: GlobalArgs,
37}
38
39/// Perform post-processing on the [`Command`] generated by clap for [`Cli`].
40///
41/// We use this to append the default config paths to the help text.
42fn cli_cmd_post_processing(cli: Command) -> Command {
43    /// Append the paths to the help text.
44    fn fmt_help(help: Option<&str>, paths: &[PathBuf]) -> String {
45        let help = help.map(|x| format!("{x}\n\n")).unwrap_or("".to_string());
46        let paths: Vec<_> = paths
47            .iter()
48            .map(|x| x.anonymize_home().to_string())
49            .collect();
50        let paths = paths.join("\n");
51
52        /// TODO MSRV 1.84: remove this comment
53        /// https://github.com/rust-lang/rust-clippy/issues/13802
54        const DESC: &str =
55            "If no paths are provided, the following config paths will be used if they exist:";
56        format!("{help}{DESC}\n\n{paths}")
57    }
58
59    // Show the default paths in the "--help" text.
60    match &*DEFAULT_CONFIG_PATHS {
61        Ok(paths) => cli.mut_arg("config", |arg| {
62            if let Some(help) = arg.get_long_help() {
63                let help = help.to_string();
64                arg.long_help(fmt_help(Some(&help), paths))
65            } else if let Some(help) = arg.get_help() {
66                let help = help.to_string();
67                arg.long_help(fmt_help(Some(&help), paths))
68            } else {
69                arg.long_help(fmt_help(None, paths))
70            }
71        }),
72        Err(_e) => cli,
73    }
74}
75
76/// Main subcommands.
77#[derive(Clone, Debug, Subcommand)]
78pub(crate) enum Commands {
79    /// Run the relay.
80    Run(RunArgs),
81    /// Print build information.
82    BuildInfo,
83}
84
85/// Global arguments for all commands.
86// NOTE: `global = true` should be set for each field
87#[derive(Clone, Debug, Args)]
88pub(crate) struct GlobalArgs {
89    /// Override the log level from the configuration.
90    #[arg(long, short, global = true)]
91    #[arg(value_name = "LEVEL")]
92    pub(crate) log_level: Option<LogLevel>,
93
94    /// Don't check permissions on the files we use.
95    #[arg(long, global = true)]
96    pub(crate) disable_fs_permission_checks: bool,
97
98    /// Override config file parameters, using TOML-like syntax.
99    #[arg(long = "option", short, global = true)]
100    #[arg(value_name = "KEY=VALUE")]
101    pub(crate) options: Vec<String>,
102
103    /// Config files and directories to read.
104    // NOTE: We append the default config paths to the help text in `cli_cmd_post_processing`.
105    // NOTE: This value does not take into account the default config paths,
106    // so this is private while the `GlobalArgs::config()` method is public instead.
107    #[arg(long, short, global = true)]
108    #[arg(value_name = "PATH")]
109    config: Vec<OsString>,
110}
111
112impl GlobalArgs {
113    /// Get the configuration sources.
114    ///
115    /// You may also want to set a [`Mistrust`](fs_mistrust::Mistrust)
116    /// and any additional configuration option overrides
117    /// using [`push_option`](ConfigurationSources::push_option).
118    pub(crate) fn config(&self) -> Result<ConfigurationSources, CfgPathError> {
119        // Use `try_from_cmdline` to be consistent with Arti.
120        let mut cfg_sources = ConfigurationSources::try_from_cmdline(
121            || {
122                Ok(DEFAULT_CONFIG_PATHS
123                    .as_ref()
124                    .map_err(Clone::clone)?
125                    .iter()
126                    .map(ConfigurationSource::from_path))
127            },
128            &self.config,
129            &self.options,
130        )?;
131
132        // TODO: These text strings may become stale if the configuration structure changes,
133        // and they're not checked at compile time.
134        // Can we change `ConfigurationSources` in some way to allow overrides from an existing
135        // builder?
136        if self.disable_fs_permission_checks {
137            cfg_sources.push_option("storage.permissions.dangerously_trust_everyone=true");
138        }
139
140        if let Some(log_level) = self.log_level {
141            cfg_sources.push_option(format!("logging.console={log_level}"));
142        }
143
144        Ok(cfg_sources)
145    }
146}
147
148/// Arguments when running an Arti relay.
149#[derive(Clone, Debug, Args)]
150pub(crate) struct RunArgs {}
151
152/// Log levels allowed by the cli.
153#[derive(Copy, Clone, Debug, Eq, PartialEq, ValueEnum)]
154pub(crate) enum LogLevel {
155    /// See [`tracing::Level::ERROR`].
156    #[value(help = None)]
157    Error,
158    /// See [`tracing::Level::WARN`].
159    #[value(help = None)]
160    Warn,
161    /// See [`tracing::Level::INFO`].
162    #[value(help = None)]
163    Info,
164    /// See [`tracing::Level::DEBUG`].
165    #[value(help = None)]
166    Debug,
167    /// See [`tracing::Level::TRACE`].
168    #[value(help = None)]
169    Trace,
170}
171
172impl std::fmt::Display for LogLevel {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        match self {
175            Self::Error => write!(f, "error"),
176            Self::Warn => write!(f, "warn"),
177            Self::Info => write!(f, "info"),
178            Self::Debug => write!(f, "debug"),
179            Self::Trace => write!(f, "trace"),
180        }
181    }
182}
183
184impl From<LogLevel> for tracing::metadata::Level {
185    fn from(x: LogLevel) -> Self {
186        match x {
187            LogLevel::Error => Self::ERROR,
188            LogLevel::Warn => Self::WARN,
189            LogLevel::Info => Self::INFO,
190            LogLevel::Debug => Self::DEBUG,
191            LogLevel::Trace => Self::TRACE,
192        }
193    }
194}
195
196#[cfg(test)]
197mod test {
198    // @@ begin test lint list maintained by maint/add_warning @@
199    #![allow(clippy::bool_assert_comparison)]
200    #![allow(clippy::clone_on_copy)]
201    #![allow(clippy::dbg_macro)]
202    #![allow(clippy::mixed_attributes_style)]
203    #![allow(clippy::print_stderr)]
204    #![allow(clippy::print_stdout)]
205    #![allow(clippy::single_char_pattern)]
206    #![allow(clippy::unwrap_used)]
207    #![allow(clippy::unchecked_duration_subtraction)]
208    #![allow(clippy::useless_vec)]
209    #![allow(clippy::needless_pass_by_value)]
210    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
211
212    use super::*;
213
214    #[test]
215    fn common_flags() {
216        Cli::parse_from(["arti-relay", "build-info"]);
217        Cli::parse_from(["arti-relay", "run"]);
218
219        let cli = Cli::parse_from(["arti-relay", "--log-level", "warn", "run"]);
220        assert_eq!(cli.global.log_level, Some(LogLevel::Warn));
221        let cli = Cli::parse_from(["arti-relay", "run", "--log-level", "warn"]);
222        assert_eq!(cli.global.log_level, Some(LogLevel::Warn));
223
224        let cli = Cli::parse_from(["arti-relay", "--disable-fs-permission-checks", "run"]);
225        assert!(cli.global.disable_fs_permission_checks);
226        let cli = Cli::parse_from(["arti-relay", "run", "--disable-fs-permission-checks"]);
227        assert!(cli.global.disable_fs_permission_checks);
228    }
229
230    #[test]
231    fn clap_bug() {
232        let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "run"]);
233        assert_eq!(cli.global.options, vec!["foo=1"]);
234
235        let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "-o", "bar=2", "run"]);
236        assert_eq!(cli.global.options, vec!["foo=1", "bar=2"]);
237
238        // this is https://github.com/clap-rs/clap/issues/3938
239        // TODO: this is a footgun, and we should consider alternatives to clap's 'global' args
240        let cli = Cli::parse_from(["arti-relay", "-o", "foo=1", "run", "-o", "bar=2"]);
241        assert_eq!(cli.global.options, vec!["bar=2"]);
242    }
243
244    #[test]
245    fn global_args_are_global() {
246        let cmd = Command::new("test");
247        let cmd = GlobalArgs::augment_args(cmd);
248
249        // check that each argument in `GlobalArgs` has "global" set
250        for arg in cmd.get_arguments() {
251            assert!(
252                arg.is_global_set(),
253                "'global' must be set for {:?}",
254                arg.get_long()
255            );
256        }
257    }
258}