feat: updated config parser to new scheme

This commit is contained in:
Namilsk 2026-10-20 19:24:24 +03:00
parent 5502f21605
commit 07f9ceb12f
No known key found for this signature in database
GPG key ID: 2B2F0A4D870B4F9F
2 changed files with 169 additions and 29 deletions

View file

@ -1,47 +1,56 @@
use crate::geoparsers::geoip2::Rules;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::str::FromStr;
#[derive(Deserialize, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum KillSwitchPolicy { pub enum KillSwitchPolicy {
#[serde(alias = "allow-proxy")] #[serde(rename = "allow-proxy")]
AllowProxies, AllowProxies,
#[serde(alias = "full")] #[serde(rename = "full")]
Strict, Strict,
} }
#[derive(Deserialize, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub enum ClearnetPolicy { pub enum ClearnetPolicy {
#[serde(alias = "killswitched")] #[serde(rename = "killswitched")]
Killwitched, Killswitched,
#[serde(alias = "allowed")] #[serde(rename = "allowed")]
Allowed, Allowed,
} }
#[derive(Deserialize, Serialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Policy { pub struct Policy {
pub clearnet: Option<ClearnetPolicy>, pub clearnet: Option<ClearnetPolicy>,
pub killswitch_mode: Option<KillSwitchPolicy>, pub killswitch_mode: Option<KillSwitchPolicy>,
} }
#[derive(Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Proxy {
pub alias: String,
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Config { pub struct Config {
/// Paths to `geosite.dat', `geolite2.mmdb` /// Paths to `geolite2.mmdb`, `geosite.dat`.
pub geo_files: [String; 2], pub geo_files: [String; 2],
/// Routing settings similar to v2ray /// Path used by the legacy separate rules loader.
pub routing: String, pub routing: String,
/// Clearnet routing policies #[serde(rename = "rule")]
pub rules: Rules,
#[serde(rename = "proxy")]
pub proxies: Vec<Proxy>,
pub policy: Option<Policy>, pub policy: Option<Policy>,
} }
// TODO: Think how to add other anonymisers impl FromStr for Config {
// Like VPN on localhost:10808 type Err = toml::de::Error;
// it can be like:
// ```toml fn from_str(data: &str) -> Result<Self, Self::Err> {
// [[proxy]] toml::from_str(data)
// name = "VPN" }
// addr = "127.0.0.1:10808" }
// type = "SOCKS5" # ...
// ```
//
impl Default for Config { impl Default for Config {
fn default() -> Self { fn default() -> Self {
@ -51,6 +60,8 @@ impl Default for Config {
String::from("/var/nsc/geodata/geosite.dat"), String::from("/var/nsc/geodata/geosite.dat"),
], ],
routing: String::from("/etc/nsc/routing.toml"), routing: String::from("/etc/nsc/routing.toml"),
rules: Vec::new(),
proxies: Vec::new(),
policy: Some(Policy { policy: Some(Policy {
clearnet: Some(ClearnetPolicy::Allowed), clearnet: Some(ClearnetPolicy::Allowed),
killswitch_mode: Some(KillSwitchPolicy::AllowProxies), killswitch_mode: Some(KillSwitchPolicy::AllowProxies),
@ -58,3 +69,105 @@ impl Default for Config {
} }
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use crate::geoparsers::geoip2::{RouteAction, RouteType};
#[test]
fn parses_inline_rules_proxies_and_policy() {
let data = r#"
[[rule]]
action = "block"
target = "geosite:category-ads-all"
[[rule]]
action = "block"
target = "geosite:win-spy"
[[rule]]
action = "proxy"
proxy_name = "xray"
target = "clearnet"
[[proxy]]
alias = "xray"
url = "socks5://localhost:10808"
[[proxy]]
alias = "i2p_outproxy"
url = "http://localhost:4444"
[policy]
clearnet = "killswitched"
killswitch_mode = "allow-proxy"
"#;
let config: Config = data.parse().unwrap();
assert_eq!(config.rules.len(), 3);
assert_eq!(config.rules[0].action, RouteAction::Block);
assert_eq!(
config.rules[0].target,
RouteType::GeoSite("category-ads-all".to_owned())
);
assert_eq!(
config.rules[1].target,
RouteType::GeoSite("win-spy".to_owned())
);
assert_eq!(config.rules[0].proxy_name, None);
assert_eq!(config.rules[2].action, RouteAction::Proxy);
assert_eq!(config.rules[2].target, RouteType::Clearnet);
assert_eq!(config.rules[2].proxy_name.as_deref(), Some("xray"));
assert_eq!(config.proxies.len(), 2);
assert_eq!(config.proxies[0].alias, "xray");
assert_eq!(config.proxies[0].url, "socks5://localhost:10808");
assert_eq!(config.proxies[1].alias, "i2p_outproxy");
assert_eq!(config.proxies[1].url, "http://localhost:4444");
assert_eq!(
config.policy,
Some(Policy {
clearnet: Some(ClearnetPolicy::Killswitched),
killswitch_mode: Some(KillSwitchPolicy::AllowProxies),
})
);
let serialized = toml::to_string(&config).unwrap();
assert_eq!(serialized.parse::<Config>().unwrap(), config);
}
#[test]
fn parses_direct_geoip_and_full_killswitch() {
let config: Config = r#"
[[rule]]
action = "direct"
target = "geoip:RU"
[policy]
clearnet = "allowed"
killswitch_mode = "full"
"#
.parse()
.unwrap();
assert_eq!(config.rules[0].action, RouteAction::Direct);
assert_eq!(config.rules[0].target, RouteType::GeoIp("RU".to_owned()));
assert!(config.proxies.is_empty());
assert_eq!(
config.policy.unwrap().killswitch_mode,
Some(KillSwitchPolicy::Strict)
);
assert_eq!(config.geo_files, Config::default().geo_files);
}
#[test]
fn rejects_unknown_enum_values_and_empty_targets() {
for data in [
"[[rule]]\naction = 'unknown'\ntarget = 'clearnet'",
"[[rule]]\naction = 'block'\ntarget = 'unknown'",
"[[rule]]\naction = 'block'\ntarget = 'geosite:'",
"[[rule]]\naction = 'block'\ntarget = 'geoip:'",
"[policy]\nclearnet = 'unknown'",
"[policy]\nkillswitch_mode = 'unknown'",
] {
assert!(data.parse::<Config>().is_err(), "accepted {data}");
}
}
}

View file

@ -1,6 +1,6 @@
use crate::config::Config; use crate::config::Config;
use maxminddb::{Reader, geoip2}; use maxminddb::{Reader, geoip2};
use serde::Deserialize; use serde::{Deserialize, Serialize};
use std::net::IpAddr; use std::net::IpAddr;
// For now only MMDB because i cant found .proto schemes of // For now only MMDB because i cant found .proto schemes of
@ -9,34 +9,61 @@ use std::net::IpAddr;
/// Interface enum for `dst_addr` info /// Interface enum for `dst_addr` info
#[allow(dead_code)] #[allow(dead_code)]
#[derive(Debug, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(try_from = "String", into = "String")]
pub enum RouteType { pub enum RouteType {
/// GeoSite type, like `category-ads-all` /// GeoSite type, like `category-ads-all`
GeoSite(String), GeoSite(String),
/// Result with GeoCode like "RU" /// Result with GeoCode like "RU"
GeoIp(String), GeoIp(String),
Clearnet,
// String because enum will used as interface in result of `route_packet`. // String because enum will used as interface in result of `route_packet`.
} }
impl TryFrom<String> for RouteType {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
if value == "clearnet" {
return Ok(Self::Clearnet);
}
match value.split_once(':') {
Some(("geosite", name)) if !name.is_empty() => Ok(Self::GeoSite(name.to_owned())),
Some(("geoip", name)) if !name.is_empty() => Ok(Self::GeoIp(name.to_owned())),
_ => Err(format!("invalid rule target: {value}")),
}
}
}
impl From<RouteType> for String {
fn from(target: RouteType) -> Self {
match target {
RouteType::GeoSite(name) => format!("geosite:{name}"),
RouteType::GeoIp(name) => format!("geoip:{name}"),
RouteType::Clearnet => "clearnet".to_owned(),
}
}
}
/// Routing actions /// Routing actions
#[allow(dead_code)] #[allow(dead_code)]
#[derive(Debug, Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum RouteAction { pub enum RouteAction {
#[serde(alias = "block")]
Block, Block,
#[serde(alias = "proxy")]
Proxy, Proxy,
#[serde(alias = "direct")]
Direct, Direct,
} }
pub type Rules = Vec<Rule>; pub type Rules = Vec<Rule>;
/// Type for deserializing the routing rules like: /// Type for deserializing the routing rules like:
#[derive(serde::Deserialize)] #[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
pub struct Rule { pub struct Rule {
pub target: RouteType, pub target: RouteType,
pub action: RouteAction, pub action: RouteAction,
#[serde(skip_serializing_if = "Option::is_none")]
pub proxy_name: Option<String>,
} }
pub struct GeoIpService { pub struct GeoIpService {