use std::env;
use std::fs;
use std::io;
use std::path::PathBuf;
use rings_gateway::GatewayConfig;
use rings_gateway::GatewayPlan;
use serde::Deserialize;
use serde::Serialize;
use crate::dns_relay::DnsRelayConfig;
use crate::dns_relay::ServicesConfig;
use crate::error::Error;
use crate::error::Result;
use crate::onion::OnionExitPolicy;
use crate::onion::OnionServiceName;
use crate::online::OnlineNodeType;
use crate::prelude::rings_core::dht::default_storage_virtual_positions_per_owner;
use crate::prelude::rings_core::dht::DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
#[cfg(test)]
use crate::prelude::rings_core::ecc::SecretKey;
use crate::prelude::rings_core::message::OriginQuotaConfig;
#[cfg(test)]
use crate::prelude::DelegateeKey;
use crate::processor::ProcessorConfig;
use crate::processor::ProcessorConfigSerialized;
use crate::seed::SeedPeer;
use crate::util::ensure_parent_dir;
use crate::util::expand_home;
lazy_static::lazy_static! {
static ref DEFAULT_DATA_STORAGE_CONFIG: StorageConfig = StorageConfig {
path: get_storage_location(".rings", "data"),
capacity: DEFAULT_STORAGE_CAPACITY,
};
static ref DEFAULT_MEASURE_STORAGE_CONFIG: StorageConfig = StorageConfig {
path: get_storage_location(".rings", "measure"),
capacity: DEFAULT_STORAGE_CAPACITY,
};
}
pub const DEFAULT_NETWORK_ID: u32 = 1;
pub const DEFAULT_INTERNAL_API_PORT: u16 = 50000;
pub const DEFAULT_EXTERNAL_API_ADDR: &str = "127.0.0.1:50001";
pub const DEFAULT_ENDPOINT_URL: &str = "http://127.0.0.1:50000";
pub const DEFAULT_ICE_SERVERS: &str = "stun://stun.l.google.com:19302";
pub const DEFAULT_STABILIZE_INTERVAL: u64 = 15;
pub use crate::consts::DEFAULT_STORAGE_CAPACITY;
pub const DEFAULT_GATEWAY_STATUS_REFRESH_SECS: u64 = 2;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NativeGatewayConfig {
#[serde(default)]
pub enabled: bool,
#[serde(flatten)]
pub runtime: GatewayConfig,
#[serde(default)]
pub interface_name: Option<String>,
#[serde(default = "default_gateway_route_ledger_path")]
pub route_ledger_path: String,
#[serde(default = "default_gateway_unix_helper_socket")]
pub unix_helper_socket: String,
#[serde(default)]
pub wintun_dll_path: Option<String>,
#[serde(default = "default_gateway_status_refresh_secs")]
pub status_refresh_secs: u64,
}
impl NativeGatewayConfig {
pub fn disabled_default() -> Self {
Self {
enabled: false,
runtime: GatewayConfig::with_default_limits(GatewayPlan::interface_only()),
interface_name: None,
route_ledger_path: default_gateway_route_ledger_path(),
unix_helper_socket: default_gateway_unix_helper_socket(),
wintun_dll_path: None,
status_refresh_secs: default_gateway_status_refresh_secs(),
}
}
pub fn to_yaml_section(&self) -> Result<String> {
serde_saphyr::to_string(&GatewaySection { gateway: self }).map_err(|_| Error::EncodeError)
}
}
#[derive(Serialize)]
struct GatewaySection<'a> {
gateway: &'a NativeGatewayConfig,
}
const GATEWAY_KEYS: [&str; 10] = [
"enabled",
"plan",
"max_flows",
"flow_idle_timeout",
"tcp_buffer_bytes",
"interface_name",
"route_ledger_path",
"unix_helper_socket",
"wintun_dll_path",
"status_refresh_secs",
];
fn deserialize_gateway_section<'de, D>(
deserializer: D,
) -> std::result::Result<Option<NativeGatewayConfig>, D::Error>
where D: serde::Deserializer<'de> {
let Some(section) =
Option::<serde_json::Map<String, serde_json::Value>>::deserialize(deserializer)?
else {
return Ok(None);
};
if let Some(key) = section
.keys()
.map(String::as_str)
.find(|key| !GATEWAY_KEYS.contains(key))
{
return Err(serde::de::Error::custom(format!(
"unknown gateway key {key:?}; expected one of {}",
GATEWAY_KEYS.join(", ")
)));
}
serde_json::from_value(serde_json::Value::Object(section))
.map(Some)
.map_err(serde::de::Error::custom)
}
const fn default_gateway_status_refresh_secs() -> u64 {
DEFAULT_GATEWAY_STATUS_REFRESH_SECS
}
fn default_gateway_route_ledger_path() -> String {
get_storage_location(".rings", "gateway-routes.json")
}
fn default_gateway_unix_helper_socket() -> String {
get_storage_location(".rings", "gateway-helper.sock")
}
pub fn get_storage_location<P>(prefix: P, path: P) -> String
where P: AsRef<std::path::Path> {
let home_dir = env::var_os("HOME").map(PathBuf::from);
let storage_path = match home_dir {
Some(dir) => dir.join(prefix).join(path),
None => std::path::Path::new("data").join(prefix).join(path),
};
storage_path.to_string_lossy().to_string()
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
pub struct BootstrapConfig {
#[serde(default)]
pub peers: Vec<SeedPeer>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
pub network_id: u32,
pub delegatee_key: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub delegator_key: Option<String>,
pub internal_api_port: u16,
pub external_api_addr: String,
pub endpoint_url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub remote_rpc_proxy_url: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub api_token_path: Option<String>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub api_allowed_origins: Vec<String>,
#[serde(default)]
pub allow_remote_external_api: bool,
#[serde(default)]
pub ice_servers: String,
pub stabilize_interval: u64,
#[serde(default = "crate::registration::default_online_node_heartbeat_interval_secs")]
pub online_node_heartbeat_interval_secs: u64,
#[serde(default = "crate::registration::default_online_node_ttl_secs")]
pub online_node_ttl_secs: u64,
#[serde(default = "crate::registration::default_online_node_type")]
pub online_node_type: OnlineNodeType,
#[serde(default = "crate::registration::default_advertise_presence")]
pub advertise_presence: bool,
#[serde(default = "crate::onion::default_advertise_onion_relay")]
pub advertise_onion_relay: bool,
#[serde(default = "crate::onion::default_advertise_onion_exit")]
pub advertise_onion_exit: bool,
#[serde(default = "crate::onion::default_onion_exit_heartbeat_interval_secs")]
pub onion_exit_heartbeat_interval_secs: u64,
#[serde(default = "crate::onion::default_onion_exit_ttl_secs")]
pub onion_exit_ttl_secs: u64,
#[serde(default = "crate::onion::default_onion_exit_services")]
pub onion_exit_services: Vec<OnionServiceName>,
#[serde(default = "crate::onion::default_onion_exit_policy")]
pub onion_exit_policy: OnionExitPolicy,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub onion_http_proxy_addr: Option<String>,
#[serde(default = "crate::onion::proxy::http::default_connect_header_timeout_secs")]
pub onion_http_proxy_header_timeout_secs: u64,
#[serde(default = "crate::onion::proxy::http::default_max_connect_connections")]
pub onion_http_proxy_max_connections: usize,
#[serde(
default,
deserialize_with = "deserialize_gateway_section",
skip_serializing_if = "Option::is_none"
)]
pub gateway: Option<NativeGatewayConfig>,
#[serde(default)]
pub bootstrap: BootstrapConfig,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub services: Option<ServicesConfig>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub dns_relay: Option<DnsRelayConfig>,
#[serde(default = "default_storage_virtual_positions_per_owner")]
pub dht_virtual_nodes: u16,
#[serde(default)]
pub origin_quota: OriginQuotaConfig,
#[serde(skip_serializing_if = "Option::is_none")]
pub external_ip: Option<String>,
#[serde(
default,
alias = "webrtc_udp_port_min",
skip_serializing_if = "Option::is_none"
)]
pub udp_port_min: Option<u16>,
#[serde(
default,
alias = "webrtc_udp_port_max",
skip_serializing_if = "Option::is_none"
)]
pub udp_port_max: Option<u16>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub network: Option<crate::processor::NetworkConfigDescriptor>,
pub data_storage: StorageConfig,
pub measure_storage: StorageConfig,
}
impl TryFrom<Config> for ProcessorConfigSerialized {
type Error = Error;
fn try_from(config: Config) -> Result<Self> {
let delegatee_key_path = expand_home(&config.delegatee_key)?;
let delegatee_key = fs::read_to_string(&delegatee_key_path).map_err(|error| {
Error::OpenFileError(format!("{}: {error}", delegatee_key_path.display()))
})?;
let udp_range =
crate::processor::parse_udp_port_range(config.udp_port_min, config.udp_port_max)?;
if config.network.is_some()
&& (!config.ice_servers.trim().is_empty()
|| config.external_ip.is_some()
|| udp_range.is_some())
{
return Err(Error::InvalidConfig(
"cannot specify both `network` and legacy flat WebRTC fields (`ice_servers`, `external_ip`, `udp_port_min`, `udp_port_max`)"
.to_string(),
));
}
Ok(Self {
network_id: config.network_id,
ice_servers: config.ice_servers,
external_address: config.external_ip,
udp_port_min: udp_range.map(|range| range.min()),
udp_port_max: udp_range.map(|range| range.max()),
network: config.network,
delegatee_key,
stabilize_interval: config.stabilize_interval,
online_node_heartbeat_interval_secs: config.online_node_heartbeat_interval_secs,
online_node_ttl_secs: config.online_node_ttl_secs,
online_node_type: config.online_node_type,
advertise_presence: config.advertise_presence,
dht_virtual_nodes: config.dht_virtual_nodes,
origin_quota: config.origin_quota,
advertise_onion_relay: config.advertise_onion_relay,
advertise_onion_exit: config.advertise_onion_exit,
onion_exit_heartbeat_interval_secs: config.onion_exit_heartbeat_interval_secs,
onion_exit_ttl_secs: config.onion_exit_ttl_secs,
onion_exit_services: config.onion_exit_services,
onion_exit_policy: config.onion_exit_policy,
onion_invoke_offer: None,
remote_rpc_proxy_url: config.remote_rpc_proxy_url,
})
}
}
impl TryFrom<Config> for ProcessorConfig {
type Error = Error;
fn try_from(config: Config) -> Result<Self> {
ProcessorConfigSerialized::try_from(config).and_then(Self::try_from)
}
}
impl Config {
pub fn new<P>(delegatee_key: P) -> Self
where P: AsRef<std::path::Path> {
let delegatee_key = delegatee_key.as_ref().to_string_lossy().to_string();
Self {
network_id: DEFAULT_NETWORK_ID,
delegatee_key,
delegator_key: None,
internal_api_port: DEFAULT_INTERNAL_API_PORT,
external_api_addr: DEFAULT_EXTERNAL_API_ADDR.to_string(),
endpoint_url: DEFAULT_ENDPOINT_URL.to_string(),
remote_rpc_proxy_url: None,
api_token_path: None,
api_allowed_origins: Vec::new(),
allow_remote_external_api: false,
ice_servers: DEFAULT_ICE_SERVERS.to_string(),
stabilize_interval: DEFAULT_STABILIZE_INTERVAL,
online_node_heartbeat_interval_secs:
crate::registration::default_online_node_heartbeat_interval_secs(),
online_node_ttl_secs: crate::registration::default_online_node_ttl_secs(),
online_node_type: crate::registration::default_online_node_type(),
advertise_presence: crate::registration::default_advertise_presence(),
advertise_onion_relay: crate::onion::default_advertise_onion_relay(),
advertise_onion_exit: crate::onion::default_advertise_onion_exit(),
onion_exit_heartbeat_interval_secs:
crate::onion::default_onion_exit_heartbeat_interval_secs(),
onion_exit_ttl_secs: crate::onion::default_onion_exit_ttl_secs(),
onion_exit_services: crate::onion::default_onion_exit_services(),
onion_exit_policy: crate::onion::default_onion_exit_policy(),
onion_http_proxy_addr: None,
onion_http_proxy_header_timeout_secs:
crate::onion::proxy::http::default_connect_header_timeout_secs(),
onion_http_proxy_max_connections:
crate::onion::proxy::http::default_max_connect_connections(),
gateway: Some(NativeGatewayConfig::disabled_default()),
bootstrap: BootstrapConfig::default(),
services: None,
dns_relay: None,
dht_virtual_nodes: DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER,
origin_quota: OriginQuotaConfig::default(),
external_ip: None,
udp_port_min: None,
udp_port_max: None,
network: None,
data_storage: DEFAULT_DATA_STORAGE_CONFIG.clone(),
measure_storage: DEFAULT_MEASURE_STORAGE_CONFIG.clone(),
}
}
pub fn enabled_gateway(&self) -> Option<&NativeGatewayConfig> {
self.gateway.as_ref().filter(|gateway| gateway.enabled)
}
pub fn write_fs<P>(&self, path: P) -> Result<String>
where P: AsRef<std::path::Path> {
let path = expand_home(path)?;
ensure_parent_dir(&path)?;
let f =
fs::File::create(path.as_path()).map_err(|e| Error::CreateFileError(e.to_string()))?;
let mut f_writer = io::BufWriter::new(f);
serde_saphyr::to_io_writer(&mut f_writer, self).map_err(|source| {
Error::ConfigSerialize {
path: path.clone(),
source,
}
})?;
io::Write::flush(&mut f_writer).map_err(|e| Error::CreateFileError(e.to_string()))?;
let f = f_writer
.into_inner()
.map_err(|e| Error::CreateFileError(e.into_error().to_string()))?;
f.sync_all()
.map_err(|e| Error::CreateFileError(e.to_string()))?;
path.to_str()
.map(str::to_owned)
.ok_or_else(|| Error::PathUtf8Error(path.display().to_string()))
}
pub fn resolve_paths_relative_to<P>(&mut self, config_path: P) -> Result<()>
where P: AsRef<std::path::Path> {
let path = expand_home(config_path)?;
if let Some(delegator_key) = self.delegator_key.as_deref() {
let expanded = expand_home(delegator_key)?;
let resolved = if expanded.is_relative() {
match path.parent() {
Some(parent) if !parent.as_os_str().is_empty() => parent.join(expanded),
_ => expanded,
}
} else {
expanded
};
self.delegator_key = Some(resolved.to_string_lossy().into_owned());
}
Ok(())
}
pub fn read_fs<P>(path: P) -> Result<Config>
where P: AsRef<std::path::Path> {
let path = expand_home(path)?;
tracing::debug!("Read config from: {:?}", path);
let f = fs::File::open(path.as_path()).map_err(|e| Error::OpenFileError(e.to_string()))?;
let f_rdr = io::BufReader::new(f);
let mut config: Config =
serde_saphyr::from_reader(f_rdr).map_err(|source| Error::ConfigParse {
path: path.clone(),
source: Box::new(source),
})?;
config.resolve_paths_relative_to(&path)?;
Ok(config)
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct StorageConfig {
pub path: String,
pub capacity: u32,
}
impl StorageConfig {
pub fn new(path: &str, capacity: u32) -> Self {
Self {
path: path.to_string(),
capacity,
}
}
}
#[cfg(test)]
mod tests;