use std::borrow::Cow;
use std::path::PathBuf;
use derive_builder::Builder;
use derive_more::AsRef;
use directories::ProjectDirs;
use fs_mistrust::{Mistrust, MistrustBuilder};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use tor_chanmgr::{ChannelConfig, ChannelConfigBuilder};
use tor_config::{impl_standard_builder, mistrust::BuilderExt, ConfigBuildError};
use tor_config_path::{CfgPath, CfgPathError, CfgPathResolver};
use tor_keymgr::config::{ArtiKeystoreConfig, ArtiKeystoreConfigBuilder};
use tracing::metadata::Level;
use tracing_subscriber::filter::EnvFilter;
pub(crate) fn default_config_paths() -> Result<Vec<PathBuf>, CfgPathError> {
let resolver = base_resolver();
[
"${ARTI_RELAY_CONFIG}/arti-relay.toml",
"${ARTI_RELAY_CONFIG}/arti-relay.d/",
]
.into_iter()
.map(|f| CfgPath::new(f.into()).path(&resolver))
.collect()
}
pub(crate) fn base_resolver() -> CfgPathResolver {
let arti_relay_cache = project_dirs().map(|x| Cow::Owned(x.cache_dir().to_owned()));
let arti_relay_config = project_dirs().map(|x| Cow::Owned(x.config_dir().to_owned()));
let arti_relay_shared_data = project_dirs().map(|x| Cow::Owned(x.data_dir().to_owned()));
let arti_relay_local_data = project_dirs().map(|x| Cow::Owned(x.data_local_dir().to_owned()));
let program_dir = get_program_dir().map(Cow::Owned);
let user_home = tor_config_path::home().map(Cow::Borrowed);
let mut resolver = CfgPathResolver::default();
resolver.set_var("ARTI_RELAY_CACHE", arti_relay_cache);
resolver.set_var("ARTI_RELAY_CONFIG", arti_relay_config);
resolver.set_var("ARTI_RELAY_SHARED_DATA", arti_relay_shared_data);
resolver.set_var("ARTI_RELAY_LOCAL_DATA", arti_relay_local_data);
resolver.set_var("PROGRAM_DIR", program_dir);
resolver.set_var("USER_HOME", user_home);
resolver
}
fn get_program_dir() -> Result<PathBuf, CfgPathError> {
let binary = std::env::current_exe().map_err(|_| CfgPathError::NoProgramPath)?;
let directory = binary.parent().ok_or(CfgPathError::NoProgramDir)?;
Ok(directory.to_owned())
}
fn project_dirs() -> Result<&'static ProjectDirs, CfgPathError> {
static PROJECT_DIRS: Lazy<Option<ProjectDirs>> =
Lazy::new(|| ProjectDirs::from("org", "torproject", "Arti-Relay"));
PROJECT_DIRS.as_ref().ok_or(CfgPathError::NoProjectDirs)
}
#[derive(Clone, Builder, Debug, Eq, PartialEq, AsRef)]
#[builder(build_fn(error = "ConfigBuildError"))]
#[builder(derive(Serialize, Deserialize, Debug))]
#[non_exhaustive]
pub(crate) struct TorRelayConfig {
#[builder(sub_builder)]
#[builder_field_attr(serde(default))]
pub(crate) logging: LoggingConfig,
#[builder(sub_builder)]
#[builder_field_attr(serde(default))]
pub(crate) storage: StorageConfig,
#[builder(sub_builder)]
#[builder_field_attr(serde(default))]
pub(crate) channel: ChannelConfig,
}
impl_standard_builder! { TorRelayConfig }
impl tor_config::load::TopLevel for TorRelayConfig {
type Builder = TorRelayConfigBuilder;
}
pub(crate) const DEFAULT_LOG_LEVEL: Level = Level::INFO;
#[derive(Debug, Clone, Builder, Eq, PartialEq)]
#[builder(build_fn(error = "ConfigBuildError", validate = "Self::validate"))]
#[builder(derive(Debug, Serialize, Deserialize))]
#[non_exhaustive]
pub(crate) struct LoggingConfig {
#[builder(default = "DEFAULT_LOG_LEVEL.to_string()", setter(into))]
pub(crate) console: String,
}
impl LoggingConfigBuilder {
fn validate(&self) -> Result<(), ConfigBuildError> {
if let Some(console) = &self.console {
EnvFilter::builder()
.parse(console)
.map_err(|e| ConfigBuildError::Invalid {
field: "console".to_string(),
problem: e.to_string(),
})?;
}
Ok(())
}
}
#[derive(Debug, Clone, Builder, Eq, PartialEq)]
#[builder(build_fn(error = "ConfigBuildError"))]
#[builder(derive(Debug, Serialize, Deserialize))]
#[non_exhaustive]
pub(crate) struct StorageConfig {
#[builder(setter(into), default = "default_cache_dir()")]
cache_dir: CfgPath,
#[builder(setter(into), default = "default_state_dir()")]
state_dir: CfgPath,
#[builder(sub_builder)]
#[builder_field_attr(serde(default))]
keystore: ArtiKeystoreConfig,
#[builder(sub_builder(fn_name = "build_for_arti"))]
#[builder_field_attr(serde(default))]
permissions: Mistrust,
}
impl_standard_builder! { StorageConfig }
impl StorageConfig {
pub(crate) fn permissions(&self) -> &Mistrust {
&self.permissions
}
pub(crate) fn keystore_dir(
&self,
resolver: &CfgPathResolver,
) -> Result<PathBuf, ConfigBuildError> {
Ok(self
.state_dir
.path(resolver)
.map_err(|e| ConfigBuildError::Invalid {
field: "state_dir".to_owned(),
problem: e.to_string(),
})?
.join("keystore"))
}
}
fn default_cache_dir() -> CfgPath {
CfgPath::new("${ARTI_RELAY_CACHE}".to_owned())
}
fn default_state_dir() -> CfgPath {
CfgPath::new("${ARTI_RELAY_LOCAL_DATA}".to_owned())
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_duration_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
use super::*;
#[test]
fn defaults() {
let dflt = TorRelayConfig::default();
let b2 = TorRelayConfigBuilder::default();
let dflt2 = b2.build().unwrap();
assert_eq!(&dflt, &dflt2);
}
#[test]
fn builder() {
let mut bld = TorRelayConfigBuilder::default();
bld.storage()
.cache_dir(CfgPath::new("/var/tmp/foo".to_owned()))
.state_dir(CfgPath::new("/var/tmp/bar".to_owned()));
let val = bld.build().unwrap();
assert_ne!(val, TorRelayConfig::default());
}
fn cfg_variables() -> impl IntoIterator<Item = (&'static str, PathBuf)> {
let project_dirs = project_dirs().unwrap();
let list = [
("ARTI_RELAY_CACHE", project_dirs.cache_dir()),
("ARTI_RELAY_CONFIG", project_dirs.config_dir()),
("ARTI_RELAY_SHARED_DATA", project_dirs.data_dir()),
("ARTI_RELAY_LOCAL_DATA", project_dirs.data_local_dir()),
("PROGRAM_DIR", &get_program_dir().unwrap()),
("USER_HOME", tor_config_path::home().unwrap()),
];
list.into_iter()
.map(|(a, b)| (a, b.to_owned()))
.collect::<Vec<_>>()
}
#[cfg(not(target_family = "windows"))]
#[test]
fn expand_variables() {
let path_resolver = base_resolver();
for (var, val) in cfg_variables() {
let p = CfgPath::new(format!("${{{var}}}/example"));
assert_eq!(p.to_string(), format!("${{{var}}}/example"));
let expected = val.join("example");
assert_eq!(p.path(&path_resolver).unwrap().to_str(), expected.to_str());
}
let p = CfgPath::new("${NOT_A_REAL_VAR}/example".to_string());
assert!(p.path(&path_resolver).is_err());
}
#[cfg(target_family = "windows")]
#[test]
fn expand_variables() {
let path_resolver = base_resolver();
for (var, val) in cfg_variables() {
let p = CfgPath::new(format!("${{{var}}}\\example"));
assert_eq!(p.to_string(), format!("${{{var}}}\\example"));
let expected = val.join("example");
assert_eq!(p.path(&path_resolver).unwrap().to_str(), expected.to_str());
}
let p = CfgPath::new("${NOT_A_REAL_VAR}\\example".to_string());
assert!(p.path(&path_resolver).is_err());
}
}