summaryrefslogtreecommitdiff
path: root/src/geoparsers/geoip2.rs
blob: 9f2cc8b358d280a3ff851e75b575f1f8a88796d7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
use crate::config::Config;
use maxminddb::{Reader, geoip2};
use serde::Deserialize;
use std::net::IpAddr;

// For now only MMDB because i cant found .proto schemes of 
// V2Ray GeoSite.dat :(( 
// TODO: V2Ray protobuf parsing && Test 4 ts

/// Interface enum for `dst_addr` info
#[derive(Debug, Deserialize)]
pub enum RouteType {
    /// GeoSite MMDB type, like `category-ads-all`
    GeoSite(String),
    /// Result with GeoCode like "RU"
    GeoIp(String),
    // String because enum will used as interface in result of `route_packet`.
}

/// Routing actions
#[derive(Debug, Deserialize)]
pub enum RouteAction {
    #[serde(alias = "block")]
    Block,
    #[serde(alias = "proxy")]
    Proxy,
    #[serde(alias = "direct")]
    Direct,
}

pub type Rules = Vec<Rule>;

/// Type for deserializing the routing rules like:
#[derive(serde::Deserialize)]
pub struct Rule {
    pub target: RouteType,
    pub action: RouteAction,
}

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.get(0).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())
    }
}