1use std::env;
2use std::fs;
3use std::io;
4use std::path::PathBuf;
5
6use rings_gateway::GatewayConfig;
7use rings_gateway::GatewayPlan;
8use serde::Deserialize;
9use serde::Serialize;
10
11use crate::dns_relay::DnsRelayConfig;
12use crate::dns_relay::ServicesConfig;
13use crate::error::Error;
14use crate::error::Result;
15use crate::onion::OnionExitPolicy;
16use crate::onion::OnionServiceName;
17use crate::online::OnlineNodeType;
18use crate::prelude::rings_core::dht::default_storage_virtual_positions_per_owner;
19use crate::prelude::rings_core::dht::DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER;
20#[cfg(test)]
21use crate::prelude::rings_core::ecc::SecretKey;
22use crate::prelude::rings_core::message::OriginQuotaConfig;
23#[cfg(test)]
24use crate::prelude::DelegateeKey;
25use crate::processor::ProcessorConfig;
26use crate::processor::ProcessorConfigSerialized;
27use crate::seed::SeedPeer;
28use crate::util::ensure_parent_dir;
29use crate::util::expand_home;
30
31lazy_static::lazy_static! {
32 static ref DEFAULT_DATA_STORAGE_CONFIG: StorageConfig = StorageConfig {
33 path: get_storage_location(".rings", "data"),
34 capacity: DEFAULT_STORAGE_CAPACITY,
35 };
36 static ref DEFAULT_MEASURE_STORAGE_CONFIG: StorageConfig = StorageConfig {
37 path: get_storage_location(".rings", "measure"),
38 capacity: DEFAULT_STORAGE_CAPACITY,
39 };
40}
41
42pub const DEFAULT_NETWORK_ID: u32 = 1;
44pub const DEFAULT_INTERNAL_API_PORT: u16 = 50000;
46pub const DEFAULT_EXTERNAL_API_ADDR: &str = "127.0.0.1:50001";
48pub const DEFAULT_ENDPOINT_URL: &str = "http://127.0.0.1:50000";
50pub const DEFAULT_ICE_SERVERS: &str = "stun://stun.l.google.com:19302";
52pub const DEFAULT_STABILIZE_INTERVAL: u64 = 15;
54pub use crate::consts::DEFAULT_STORAGE_CAPACITY;
55pub const DEFAULT_GATEWAY_STATUS_REFRESH_SECS: u64 = 2;
57
58#[derive(Debug, Clone, Deserialize, Serialize)]
71pub struct NativeGatewayConfig {
72 #[serde(default)]
75 pub enabled: bool,
76 #[serde(flatten)]
78 pub runtime: GatewayConfig,
79 #[serde(default)]
81 pub interface_name: Option<String>,
82 #[serde(default = "default_gateway_route_ledger_path")]
84 pub route_ledger_path: String,
85 #[serde(default = "default_gateway_unix_helper_socket")]
87 pub unix_helper_socket: String,
88 #[serde(default)]
90 pub wintun_dll_path: Option<String>,
91 #[serde(default = "default_gateway_status_refresh_secs")]
93 pub status_refresh_secs: u64,
94}
95
96impl NativeGatewayConfig {
97 pub fn disabled_default() -> Self {
101 Self {
102 enabled: false,
103 runtime: GatewayConfig::with_default_limits(GatewayPlan::interface_only()),
104 interface_name: None,
105 route_ledger_path: default_gateway_route_ledger_path(),
106 unix_helper_socket: default_gateway_unix_helper_socket(),
107 wintun_dll_path: None,
108 status_refresh_secs: default_gateway_status_refresh_secs(),
109 }
110 }
111
112 pub fn to_yaml_section(&self) -> Result<String> {
115 serde_saphyr::to_string(&GatewaySection { gateway: self }).map_err(|_| Error::EncodeError)
116 }
117}
118
119#[derive(Serialize)]
121struct GatewaySection<'a> {
122 gateway: &'a NativeGatewayConfig,
123}
124
125const GATEWAY_KEYS: [&str; 10] = [
128 "enabled",
129 "plan",
130 "max_flows",
131 "flow_idle_timeout",
132 "tcp_buffer_bytes",
133 "interface_name",
134 "route_ledger_path",
135 "unix_helper_socket",
136 "wintun_dll_path",
137 "status_refresh_secs",
138];
139
140fn deserialize_gateway_section<'de, D>(
146 deserializer: D,
147) -> std::result::Result<Option<NativeGatewayConfig>, D::Error>
148where D: serde::Deserializer<'de> {
149 let Some(section) =
150 Option::<serde_json::Map<String, serde_json::Value>>::deserialize(deserializer)?
151 else {
152 return Ok(None);
153 };
154 if let Some(key) = section
155 .keys()
156 .map(String::as_str)
157 .find(|key| !GATEWAY_KEYS.contains(key))
158 {
159 return Err(serde::de::Error::custom(format!(
160 "unknown gateway key {key:?}; expected one of {}",
161 GATEWAY_KEYS.join(", ")
162 )));
163 }
164 serde_json::from_value(serde_json::Value::Object(section))
165 .map(Some)
166 .map_err(serde::de::Error::custom)
167}
168
169const fn default_gateway_status_refresh_secs() -> u64 {
170 DEFAULT_GATEWAY_STATUS_REFRESH_SECS
171}
172
173fn default_gateway_route_ledger_path() -> String {
174 get_storage_location(".rings", "gateway-routes.json")
175}
176
177fn default_gateway_unix_helper_socket() -> String {
178 get_storage_location(".rings", "gateway-helper.sock")
179}
180
181pub fn get_storage_location<P>(prefix: P, path: P) -> String
183where P: AsRef<std::path::Path> {
184 let home_dir = env::var_os("HOME").map(PathBuf::from);
185 let storage_path = match home_dir {
186 Some(dir) => dir.join(prefix).join(path),
187 None => std::path::Path::new("data").join(prefix).join(path),
188 };
189 storage_path.to_string_lossy().to_string()
190}
191
192#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
195pub struct BootstrapConfig {
196 #[serde(default)]
198 pub peers: Vec<SeedPeer>,
199}
200
201#[derive(Debug, Clone, Deserialize, Serialize)]
203#[serde(deny_unknown_fields)]
204pub struct Config {
205 pub network_id: u32,
207 pub delegatee_key: String,
209 #[serde(default, skip_serializing_if = "Option::is_none")]
212 pub delegator_key: Option<String>,
213 pub internal_api_port: u16,
215 pub external_api_addr: String,
217 pub endpoint_url: String,
219 #[serde(default, skip_serializing_if = "Option::is_none")]
221 pub remote_rpc_proxy_url: Option<String>,
222 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub api_token_path: Option<String>,
225 #[serde(default, skip_serializing_if = "Vec::is_empty")]
227 pub api_allowed_origins: Vec<String>,
228 #[serde(default)]
230 pub allow_remote_external_api: bool,
231 #[serde(default)]
234 pub ice_servers: String,
235 pub stabilize_interval: u64,
237 #[serde(default = "crate::registration::default_online_node_heartbeat_interval_secs")]
239 pub online_node_heartbeat_interval_secs: u64,
240 #[serde(default = "crate::registration::default_online_node_ttl_secs")]
242 pub online_node_ttl_secs: u64,
243 #[serde(default = "crate::registration::default_online_node_type")]
245 pub online_node_type: OnlineNodeType,
246 #[serde(default = "crate::registration::default_advertise_presence")]
248 pub advertise_presence: bool,
249 #[serde(default = "crate::onion::default_advertise_onion_relay")]
251 pub advertise_onion_relay: bool,
252 #[serde(default = "crate::onion::default_advertise_onion_exit")]
254 pub advertise_onion_exit: bool,
255 #[serde(default = "crate::onion::default_onion_exit_heartbeat_interval_secs")]
257 pub onion_exit_heartbeat_interval_secs: u64,
258 #[serde(default = "crate::onion::default_onion_exit_ttl_secs")]
260 pub onion_exit_ttl_secs: u64,
261 #[serde(default = "crate::onion::default_onion_exit_services")]
263 pub onion_exit_services: Vec<OnionServiceName>,
264 #[serde(default = "crate::onion::default_onion_exit_policy")]
266 pub onion_exit_policy: OnionExitPolicy,
267 #[serde(default, skip_serializing_if = "Option::is_none")]
269 pub onion_http_proxy_addr: Option<String>,
270 #[serde(default = "crate::onion::proxy::http::default_connect_header_timeout_secs")]
272 pub onion_http_proxy_header_timeout_secs: u64,
273 #[serde(default = "crate::onion::proxy::http::default_max_connect_connections")]
275 pub onion_http_proxy_max_connections: usize,
276 #[serde(
280 default,
281 deserialize_with = "deserialize_gateway_section",
282 skip_serializing_if = "Option::is_none"
283 )]
284 pub gateway: Option<NativeGatewayConfig>,
285 #[serde(default)]
287 pub bootstrap: BootstrapConfig,
288 #[serde(default, skip_serializing_if = "Option::is_none")]
291 pub services: Option<ServicesConfig>,
292 #[serde(default, skip_serializing_if = "Option::is_none")]
294 pub dns_relay: Option<DnsRelayConfig>,
295 #[serde(default = "default_storage_virtual_positions_per_owner")]
297 pub dht_virtual_nodes: u16,
298 #[serde(default)]
300 pub origin_quota: OriginQuotaConfig,
301 #[serde(skip_serializing_if = "Option::is_none")]
303 pub external_ip: Option<String>,
304 #[serde(
306 default,
307 alias = "webrtc_udp_port_min",
308 skip_serializing_if = "Option::is_none"
309 )]
310 pub udp_port_min: Option<u16>,
311 #[serde(
313 default,
314 alias = "webrtc_udp_port_max",
315 skip_serializing_if = "Option::is_none"
316 )]
317 pub udp_port_max: Option<u16>,
318 #[serde(default, skip_serializing_if = "Option::is_none")]
322 pub network: Option<crate::processor::NetworkConfigDescriptor>,
323 pub data_storage: StorageConfig,
325 pub measure_storage: StorageConfig,
327}
328
329impl TryFrom<Config> for ProcessorConfigSerialized {
330 type Error = Error;
331 fn try_from(config: Config) -> Result<Self> {
332 let delegatee_key_path = expand_home(&config.delegatee_key)?;
333 let delegatee_key = fs::read_to_string(&delegatee_key_path).map_err(|error| {
334 Error::OpenFileError(format!("{}: {error}", delegatee_key_path.display()))
335 })?;
336
337 let udp_range =
338 crate::processor::parse_udp_port_range(config.udp_port_min, config.udp_port_max)?;
339 if config.network.is_some()
340 && (!config.ice_servers.trim().is_empty()
341 || config.external_ip.is_some()
342 || udp_range.is_some())
343 {
344 return Err(Error::InvalidConfig(
345 "cannot specify both `network` and legacy flat WebRTC fields (`ice_servers`, `external_ip`, `udp_port_min`, `udp_port_max`)"
346 .to_string(),
347 ));
348 }
349
350 Ok(Self {
351 network_id: config.network_id,
352 ice_servers: config.ice_servers,
353 external_address: config.external_ip,
354 udp_port_min: udp_range.map(|range| range.min()),
355 udp_port_max: udp_range.map(|range| range.max()),
356 network: config.network,
357 delegatee_key,
358 stabilize_interval: config.stabilize_interval,
359 online_node_heartbeat_interval_secs: config.online_node_heartbeat_interval_secs,
360 online_node_ttl_secs: config.online_node_ttl_secs,
361 online_node_type: config.online_node_type,
362 advertise_presence: config.advertise_presence,
363 dht_virtual_nodes: config.dht_virtual_nodes,
364 origin_quota: config.origin_quota,
365 advertise_onion_relay: config.advertise_onion_relay,
366 advertise_onion_exit: config.advertise_onion_exit,
367 onion_exit_heartbeat_interval_secs: config.onion_exit_heartbeat_interval_secs,
368 onion_exit_ttl_secs: config.onion_exit_ttl_secs,
369 onion_exit_services: config.onion_exit_services,
370 onion_exit_policy: config.onion_exit_policy,
371 onion_invoke_offer: None,
372 remote_rpc_proxy_url: config.remote_rpc_proxy_url,
373 })
374 }
375}
376
377impl TryFrom<Config> for ProcessorConfig {
378 type Error = Error;
379 fn try_from(config: Config) -> Result<Self> {
380 ProcessorConfigSerialized::try_from(config).and_then(Self::try_from)
381 }
382}
383
384impl Config {
385 pub fn new<P>(delegatee_key: P) -> Self
387 where P: AsRef<std::path::Path> {
388 let delegatee_key = delegatee_key.as_ref().to_string_lossy().to_string();
389 Self {
390 network_id: DEFAULT_NETWORK_ID,
391 delegatee_key,
392 delegator_key: None,
393 internal_api_port: DEFAULT_INTERNAL_API_PORT,
394 external_api_addr: DEFAULT_EXTERNAL_API_ADDR.to_string(),
395 endpoint_url: DEFAULT_ENDPOINT_URL.to_string(),
396 remote_rpc_proxy_url: None,
397 api_token_path: None,
398 api_allowed_origins: Vec::new(),
399 allow_remote_external_api: false,
400 ice_servers: DEFAULT_ICE_SERVERS.to_string(),
401 stabilize_interval: DEFAULT_STABILIZE_INTERVAL,
402 online_node_heartbeat_interval_secs:
403 crate::registration::default_online_node_heartbeat_interval_secs(),
404 online_node_ttl_secs: crate::registration::default_online_node_ttl_secs(),
405 online_node_type: crate::registration::default_online_node_type(),
406 advertise_presence: crate::registration::default_advertise_presence(),
407 advertise_onion_relay: crate::onion::default_advertise_onion_relay(),
408 advertise_onion_exit: crate::onion::default_advertise_onion_exit(),
409 onion_exit_heartbeat_interval_secs:
410 crate::onion::default_onion_exit_heartbeat_interval_secs(),
411 onion_exit_ttl_secs: crate::onion::default_onion_exit_ttl_secs(),
412 onion_exit_services: crate::onion::default_onion_exit_services(),
413 onion_exit_policy: crate::onion::default_onion_exit_policy(),
414 onion_http_proxy_addr: None,
415 onion_http_proxy_header_timeout_secs:
416 crate::onion::proxy::http::default_connect_header_timeout_secs(),
417 onion_http_proxy_max_connections:
418 crate::onion::proxy::http::default_max_connect_connections(),
419 gateway: Some(NativeGatewayConfig::disabled_default()),
420 bootstrap: BootstrapConfig::default(),
421 services: None,
422 dns_relay: None,
423 dht_virtual_nodes: DEFAULT_STORAGE_VIRTUAL_POSITIONS_PER_OWNER,
424 origin_quota: OriginQuotaConfig::default(),
425 external_ip: None,
426 udp_port_min: None,
427 udp_port_max: None,
428 network: None,
429 data_storage: DEFAULT_DATA_STORAGE_CONFIG.clone(),
430 measure_storage: DEFAULT_MEASURE_STORAGE_CONFIG.clone(),
431 }
432 }
433
434 pub fn enabled_gateway(&self) -> Option<&NativeGatewayConfig> {
439 self.gateway.as_ref().filter(|gateway| gateway.enabled)
440 }
441
442 pub fn write_fs<P>(&self, path: P) -> Result<String>
444 where P: AsRef<std::path::Path> {
445 let path = expand_home(path)?;
446 ensure_parent_dir(&path)?;
447 let f =
448 fs::File::create(path.as_path()).map_err(|e| Error::CreateFileError(e.to_string()))?;
449 let mut f_writer = io::BufWriter::new(f);
450 serde_saphyr::to_io_writer(&mut f_writer, self).map_err(|source| {
451 Error::ConfigSerialize {
452 path: path.clone(),
453 source,
454 }
455 })?;
456 io::Write::flush(&mut f_writer).map_err(|e| Error::CreateFileError(e.to_string()))?;
457 let f = f_writer
458 .into_inner()
459 .map_err(|e| Error::CreateFileError(e.into_error().to_string()))?;
460 f.sync_all()
461 .map_err(|e| Error::CreateFileError(e.to_string()))?;
462 path.to_str()
463 .map(str::to_owned)
464 .ok_or_else(|| Error::PathUtf8Error(path.display().to_string()))
465 }
466
467 pub fn resolve_paths_relative_to<P>(&mut self, config_path: P) -> Result<()>
470 where P: AsRef<std::path::Path> {
471 let path = expand_home(config_path)?;
472 if let Some(delegator_key) = self.delegator_key.as_deref() {
473 let expanded = expand_home(delegator_key)?;
474 let resolved = if expanded.is_relative() {
475 match path.parent() {
476 Some(parent) if !parent.as_os_str().is_empty() => parent.join(expanded),
477 _ => expanded,
478 }
479 } else {
480 expanded
481 };
482 self.delegator_key = Some(resolved.to_string_lossy().into_owned());
483 }
484 Ok(())
485 }
486
487 pub fn read_fs<P>(path: P) -> Result<Config>
489 where P: AsRef<std::path::Path> {
490 let path = expand_home(path)?;
491 tracing::debug!("Read config from: {:?}", path);
492 let f = fs::File::open(path.as_path()).map_err(|e| Error::OpenFileError(e.to_string()))?;
493 let f_rdr = io::BufReader::new(f);
494 let mut config: Config =
495 serde_saphyr::from_reader(f_rdr).map_err(|source| Error::ConfigParse {
496 path: path.clone(),
497 source: Box::new(source),
498 })?;
499 config.resolve_paths_relative_to(&path)?;
500 Ok(config)
501 }
502}
503
504#[derive(Debug, Clone, Deserialize, Serialize)]
506pub struct StorageConfig {
507 pub path: String,
509 pub capacity: u32,
511}
512
513impl StorageConfig {
514 pub fn new(path: &str, capacity: u32) -> Self {
516 Self {
517 path: path.to_string(),
518 capacity,
519 }
520 }
521}
522
523#[cfg(test)]
524mod tests;