90 lines
2.5 KiB
Rust
90 lines
2.5 KiB
Rust
use crate::config::Config;
|
|
use maxminddb::{Reader, geoip2};
|
|
use serde::{Deserialize, Serialize};
|
|
use std::net::IpAddr;
|
|
|
|
// For now only MMDB because i cant found .proto schemes of
|
|
// V2Ray GeoSite.dat/GeoIP.dat :((
|
|
// TODO: V2Ray protobuf parsing && Test 4 ts
|
|
|
|
/// Interface enum for `dst_addr` info
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
|
#[serde(try_from = "String", into = "String")]
|
|
pub enum RouteType {
|
|
/// GeoSite type, like `category-ads-all`
|
|
GeoSite(String),
|
|
/// Result with GeoCode like "RU"
|
|
GeoIp(String),
|
|
Clearnet,
|
|
// 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
|
|
#[allow(dead_code)]
|
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
|
#[serde(rename_all = "lowercase")]
|
|
pub enum RouteAction {
|
|
Block,
|
|
Proxy,
|
|
Direct,
|
|
}
|
|
|
|
pub type Rules = Vec<Rule>;
|
|
|
|
/// Type for deserializing the routing rules like:
|
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize, Serialize)]
|
|
pub struct Rule {
|
|
pub target: RouteType,
|
|
pub action: RouteAction,
|
|
#[serde(skip_serializing_if = "Option::is_none")]
|
|
pub proxy_name: Option<String>,
|
|
}
|
|
|
|
pub struct GeoIpService {
|
|
reader: Reader<Vec<u8>>,
|
|
}
|
|
|
|
impl GeoIpService {
|
|
pub fn new(config: Config) -> Result<Self, Box<dyn std::error::Error>> {
|
|
let path = config.geo_files.first().unwrap();
|
|
let reader = Reader::open_readfile(path)?;
|
|
Ok(Self { reader })
|
|
}
|
|
|
|
pub fn lookup_country<'a>(
|
|
&'a self,
|
|
ip: IpAddr,
|
|
) -> Result<maxminddb::geoip2::Country<'a>, Box<dyn std::error::Error>> {
|
|
let result = self.reader.lookup(ip)?;
|
|
|
|
result
|
|
.decode::<geoip2::Country>()?
|
|
.ok_or_else(|| "Couldnt lookup IP geo.".into())
|
|
}
|
|
}
|