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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use crate::errors::*;
use crate::lazy::LazyInit;
use maxminddb::{self, geoip2};
use std::fmt;
use std::fs::{self, File};
use std::io::Read;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;

pub mod models;
use self::models::AsnLookup;
use self::models::GeoLookup;

pub trait Maxmind: Sized {
    fn filename() -> &'static str;

    fn new(reader: maxminddb::Reader<Vec<u8>>) -> Self;

    fn cache_path(cache_dir: &Path) -> Result<PathBuf> {
        // use system path if exists
        for path in &[
            // Archlinux
            "/usr/share/GeoIP/",
            // OpenBSD
            "/usr/local/share/examples/libmaxminddb/",
            // geoipupdate
            "/var/lib/GeoIP/",
        ] {
            let path = Path::new(path);
            let path = path.join(Self::filename());

            if path.exists() {
                return Ok(path);
            }
        }

        // use cache path
        let path = cache_dir.join(Self::filename());
        Ok(path)
    }

    fn from_buf(buf: Vec<u8>) -> Result<Self> {
        let reader =
            maxminddb::Reader::from_source(buf).context("Failed to read geoip database")?;
        Ok(Self::new(reader))
    }

    fn open(path: &Path) -> Result<Self> {
        let buf = fs::read(path)?;
        Self::from_buf(buf)
    }

    fn try_open_reader(cache_dir: &Path) -> Result<Option<MaxmindReader>> {
        let path = Self::cache_path(cache_dir)?;

        if path.exists() {
            let db = MaxmindReader::open_path(path)?;
            Ok(Some(db))
        } else {
            Ok(None)
        }
    }
}

pub struct MaxmindReader {
    reader: File,
}

impl MaxmindReader {
    fn open_path<P: AsRef<Path>>(path: P) -> Result<MaxmindReader> {
        let reader = File::open(path)?;
        Ok(MaxmindReader { reader })
    }
}

impl fmt::Debug for MaxmindReader {
    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
        write!(w, "MaxmindReader {{ ... }}")
    }
}

impl LazyInit<Arc<GeoIP>> for MaxmindReader {
    fn initialize(mut self) -> Result<Arc<GeoIP>> {
        let mut buf = Vec::new();
        self.reader.read_to_end(&mut buf)?;
        Ok(Arc::new(GeoIP::from_buf(buf)?))
    }
}

impl LazyInit<Arc<AsnDB>> for MaxmindReader {
    fn initialize(mut self) -> Result<Arc<AsnDB>> {
        let mut buf = Vec::new();
        self.reader.read_to_end(&mut buf)?;
        Ok(Arc::new(AsnDB::from_buf(buf)?))
    }
}

pub struct GeoIP {
    reader: maxminddb::Reader<Vec<u8>>,
}

impl fmt::Debug for GeoIP {
    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
        write!(w, "GeoIP {{ ... }}")
    }
}

impl Maxmind for GeoIP {
    #[inline]
    fn filename() -> &'static str {
        "GeoLite2-City.mmdb"
    }

    #[inline]
    fn new(reader: maxminddb::Reader<Vec<u8>>) -> Self {
        GeoIP { reader }
    }
}

impl GeoIP {
    pub fn lookup(&self, ip: IpAddr) -> Result<GeoLookup> {
        let city: geoip2::City = self.reader.lookup(ip)?;
        debug!("GeoIP result: {:?}", city);
        Ok(GeoLookup::from(city))
    }
}

pub struct AsnDB {
    reader: maxminddb::Reader<Vec<u8>>,
}

impl fmt::Debug for AsnDB {
    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {
        write!(w, "GeoIP {{ ... }}")
    }
}

impl Maxmind for AsnDB {
    #[inline]
    fn filename() -> &'static str {
        "GeoLite2-ASN.mmdb"
    }

    #[inline]
    fn new(reader: maxminddb::Reader<Vec<u8>>) -> Self {
        AsnDB { reader }
    }
}

impl AsnDB {
    pub fn lookup(&self, ip: IpAddr) -> Result<AsnLookup> {
        let isp: geoip2::Isp = self.reader.lookup(ip)?;
        debug!("ASN result: {:?}", isp);
        AsnLookup::try_from(isp)
    }
}

#[cfg(test)]
mod tests {
    // You need geoip setup on your system to run this
    /*
    use super::*;

    #[test]
    #[ignore]
    fn test_geoip_lookup() {
        let ip = "1.1.1.1".parse().unwrap();
        let path = GeoIP::cache_path().unwrap();
        let geoip = GeoIP::open(&path).unwrap();
        let lookup = geoip.lookup(ip).expect("GeoIP lookup failed");
        println!("{:#?}", lookup);
        assert_eq!(lookup.city, None);
    }

    #[test]
    #[ignore]
    fn test_asn_lookup() {
        let ip = "1.1.1.1".parse().unwrap();
        let path = AsnDB::cache_path().unwrap();
        let asndb = AsnDB::open(&path).unwrap();
        let lookup = asndb.lookup(ip).expect("ASN lookup failed");
        println!("{:#?}", lookup);
    }
    */
}