1use anyhow::Context;
2use arrayvec::ArrayString;
3use ipnet::IpNet;
4use maxminddb::{LookupResult, geoip2};
5use serde::{Deserialize, Serialize};
6use std::{fmt::Display, net::IpAddr, ops::Deref, path::PathBuf};
7
8use crate::{Error, TruncatesString};
9
10const CITY_NAME_MAX_LENGTH: usize = 32;
11
12#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize, Serialize)]
15pub struct CountryCode(pub ArrayString<2>);
16
17impl Deref for CountryCode {
18 type Target = str;
19
20 fn deref(&self) -> &Self::Target {
21 self.0.as_str()
22 }
23}
24
25impl Display for CountryCode {
26 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
27 write!(f, "{}", self.0)
28 }
29}
30
31pub struct Location {
33 pub lat: f64,
34 pub lon: f64,
35}
36
37pub struct City {
39 pub name: Option<ArrayString<CITY_NAME_MAX_LENGTH>>,
40 pub country_code: Option<CountryCode>,
41 pub location: Option<Location>,
42}
43
44impl From<geoip2::City<'_>> for City {
45 fn from(city: geoip2::City<'_>) -> Self {
46 Self {
47 name: city
49 .city
50 .names
51 .english
52 .or(city.city.names.german)
53 .map(|x| x.truncate_bytes(CITY_NAME_MAX_LENGTH).try_into().unwrap()),
56
57 country_code: city
58 .country
59 .iso_code
60 .and_then(|x| x.try_into().ok())
61 .map(CountryCode),
62
63 location: city
65 .location
66 .latitude
67 .zip(city.location.longitude)
68 .map(|(lat, lon)| Location { lat, lon }),
69 }
70 }
71}
72
73pub struct GeoIp {
75 db: maxminddb::Reader<Vec<u8>>,
76}
77
78impl GeoIp {
79 pub fn new(db_path: &PathBuf) -> Result<Self, Error> {
81 Ok(Self {
82 db: maxminddb::Reader::open_readfile(db_path).context("unable to load GeoIP DB")?,
83 })
84 }
85
86 fn to_ipnet(lookup: &LookupResult<'_, Vec<u8>>) -> Option<IpNet> {
87 let net = lookup.network().ok()?;
88 IpNet::new(net.ip(), net.prefix()).ok()
89 }
90
91 pub fn lookup_country(&self, ip: IpAddr) -> Option<(CountryCode, IpNet)> {
93 let lookup = self.db.lookup(ip).ok()?;
94 let country: Option<geoip2::Country> = lookup.decode().ok()?;
95
96 country?
99 .country
100 .iso_code?
101 .try_into()
102 .ok()
103 .map(CountryCode)
104 .zip(Self::to_ipnet(&lookup))
105 }
106
107 pub fn lookup_city(&self, ip: IpAddr) -> Option<(City, IpNet)> {
109 let lookup = self.db.lookup(ip).ok()?;
110 let city: geoip2::City = lookup.decode().ok()??;
111
112 Some((city.into(), Self::to_ipnet(&lookup)?))
113 }
114}
115
116#[cfg(test)]
117mod test {
118 use std::net::{Ipv4Addr, Ipv6Addr};
119
120 use super::*;
121
122 const IP_KNOWN: Ipv4Addr = Ipv4Addr::new(89, 160, 20, 112);
124 const NET_KNOWN: &str = "89.160.20.112/28";
125 const COUNTRY_KNOWN: &str = "SE";
126 const CITY_KNOWN: &str = "Linköping";
127 const LAT_KNOWN: f64 = 58.4167;
128 const LON_KNOWN: f64 = 15.6167;
129 const IP_UNKNOWN: Ipv4Addr = Ipv4Addr::new(10, 10, 10, 10);
130 const IP_NO_CITY_NAME: Ipv4Addr = Ipv4Addr::new(149, 101, 100, 1);
132 const NET_NO_CITY_NAME: &str = "149.101.100.0/28";
133 const IP_LOCATION_ONLY: Ipv6Addr = Ipv6Addr::new(0x2a02, 0xd500, 0, 0, 0, 0, 0, 1);
135 const NET_LOCATION_ONLY: &str = "2a02:d500::/29";
136 const IP_EMPTY_RECORD: Ipv4Addr = Ipv4Addr::new(2, 3, 3, 1);
138 const NET_EMPTY_RECORD: &str = "2.3.3.0/24";
139
140 fn net(s: &str) -> IpNet {
141 s.parse().unwrap()
142 }
143
144 fn test_db_path() -> PathBuf {
146 PathBuf::from(concat!(
147 env!("CARGO_MANIFEST_DIR"),
148 "/test-data/geoip-test-db.mmdb"
149 ))
150 }
151
152 fn test_city_db_path() -> PathBuf {
154 PathBuf::from(concat!(
155 env!("CARGO_MANIFEST_DIR"),
156 "/test-data/geoip-city-test-db.mmdb"
157 ))
158 }
159
160 fn geoip2_city<'a>(
162 english: Option<&'a str>,
163 german: Option<&'a str>,
164 iso_code: Option<&'a str>,
165 latitude: Option<f64>,
166 longitude: Option<f64>,
167 ) -> geoip2::City<'a> {
168 geoip2::City {
169 city: geoip2::city::City {
170 names: geoip2::Names {
171 english,
172 german,
173 ..Default::default()
174 },
175 ..Default::default()
176 },
177 country: geoip2::city::Country {
178 iso_code,
179 ..Default::default()
180 },
181 location: geoip2::city::Location {
182 latitude,
183 longitude,
184 ..Default::default()
185 },
186 ..Default::default()
187 }
188 }
189
190 #[test]
191 fn lookup_known_ip_returns_country_code_and_network() {
192 let geoip = GeoIp::new(&test_db_path()).unwrap();
193 let (country_code, network) = geoip.lookup_country(IpAddr::V4(IP_KNOWN)).unwrap();
194
195 assert_eq!(country_code.0.as_str(), COUNTRY_KNOWN);
196 assert_eq!(network, net(NET_KNOWN));
197 assert!(network.contains(&IpAddr::V4(IP_KNOWN)));
198 }
199
200 #[test]
201 fn lookup_unknown_ip_returns_none() {
202 let geoip = GeoIp::new(&test_db_path()).unwrap();
203 assert!(geoip.lookup_country(IpAddr::V4(IP_UNKNOWN)).is_none());
204 }
205
206 #[test]
207 fn lookup_city_known_ip_returns_name_country_location_and_network() {
208 let geoip = GeoIp::new(&test_city_db_path()).unwrap();
209 let (city, network) = geoip.lookup_city(IpAddr::V4(IP_KNOWN)).unwrap();
210
211 assert_eq!(city.name.unwrap().as_str(), CITY_KNOWN);
212 assert_eq!(city.country_code.unwrap().0.as_str(), COUNTRY_KNOWN);
213
214 let location = city.location.unwrap();
215 assert_eq!(location.lat, LAT_KNOWN);
216 assert_eq!(location.lon, LON_KNOWN);
217
218 assert_eq!(network, net(NET_KNOWN));
219 assert!(network.contains(&IpAddr::V4(IP_KNOWN)));
220 }
221
222 #[test]
223 fn lookup_city_unknown_ip_returns_none() {
224 let geoip = GeoIp::new(&test_city_db_path()).unwrap();
225 assert!(geoip.lookup_city(IpAddr::V4(IP_UNKNOWN)).is_none());
226 }
227
228 #[test]
229 fn lookup_city_without_name_returns_country_and_location() {
230 let geoip = GeoIp::new(&test_city_db_path()).unwrap();
231 let (city, network) = geoip.lookup_city(IpAddr::V4(IP_NO_CITY_NAME)).unwrap();
232
233 assert!(city.name.is_none());
234 assert_eq!(city.country_code.unwrap().0.as_str(), "US");
235
236 let location = city.location.unwrap();
237 assert_eq!(location.lat, 37.751);
238 assert_eq!(location.lon, -97.822);
239
240 assert_eq!(network, net(NET_NO_CITY_NAME));
241 }
242
243 #[test]
244 fn lookup_city_ipv6_with_location_only() {
245 let geoip = GeoIp::new(&test_city_db_path()).unwrap();
246 let (city, network) = geoip.lookup_city(IpAddr::V6(IP_LOCATION_ONLY)).unwrap();
247
248 assert!(city.name.is_none());
249 assert!(city.country_code.is_none());
250
251 let location = city.location.unwrap();
252 assert_eq!(location.lat, 48.69096);
253 assert_eq!(location.lon, 9.14062);
254
255 assert_eq!(network, net(NET_LOCATION_ONLY));
256 }
257
258 #[test]
259 fn lookup_city_empty_record_returns_city_without_fields() {
260 let geoip = GeoIp::new(&test_city_db_path()).unwrap();
261 let (city, network) = geoip.lookup_city(IpAddr::V4(IP_EMPTY_RECORD)).unwrap();
262
263 assert!(city.name.is_none());
264 assert!(city.country_code.is_none());
265 assert!(city.location.is_none());
266
267 assert_eq!(network, net(NET_EMPTY_RECORD));
268 }
269
270 #[test]
271 fn lookup_city_with_country_db_returns_country_only() {
272 let geoip = GeoIp::new(&test_db_path()).unwrap();
273 let (city, network) = geoip.lookup_city(IpAddr::V4(IP_KNOWN)).unwrap();
274
275 assert!(city.name.is_none());
276 assert_eq!(city.country_code.unwrap().0.as_str(), COUNTRY_KNOWN);
277 assert!(city.location.is_none());
278
279 assert_eq!(network, net(NET_KNOWN));
280 }
281
282 #[test]
283 fn city_from_geoip2_prefers_english_name() {
284 let city = City::from(geoip2_city(
285 Some("Singapore"),
286 Some("Singapur"),
287 None,
288 None,
289 None,
290 ));
291 assert_eq!(city.name.unwrap().as_str(), "Singapore");
292 }
293
294 #[test]
295 fn city_from_geoip2_falls_back_to_german_name() {
296 let city = City::from(geoip2_city(None, Some("Singapur"), None, None, None));
297 assert_eq!(city.name.unwrap().as_str(), "Singapur");
298 }
299
300 #[test]
301 fn city_from_geoip2_without_names_has_no_name() {
302 let city = City::from(geoip2_city(None, None, None, None, None));
303 assert!(city.name.is_none());
304 }
305
306 #[test]
307 fn city_from_geoip2_truncates_long_name() {
308 let long = "Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch";
310 assert!(long.len() > CITY_NAME_MAX_LENGTH);
311 let city = City::from(geoip2_city(Some(long), None, None, None, None));
312 assert_eq!(city.name.unwrap().as_str(), &long[..CITY_NAME_MAX_LENGTH]);
313
314 let name = "ä".repeat(17);
316 let city = City::from(geoip2_city(Some(&name), None, None, None, None));
317 assert_eq!(city.name.unwrap().as_str(), "ä".repeat(16).as_str());
318
319 let name = "€".repeat(11);
321 let city = City::from(geoip2_city(Some(&name), None, None, None, None));
322 assert_eq!(city.name.unwrap().as_str(), "€".repeat(10).as_str());
323
324 let city = City::from(geoip2_city(None, Some(long), None, None, None));
326 assert_eq!(city.name.unwrap().as_str(), &long[..CITY_NAME_MAX_LENGTH]);
327 }
328
329 #[test]
330 fn city_from_geoip2_country_code() {
331 let city = City::from(geoip2_city(None, None, Some("SE"), None, None));
332 assert_eq!(city.country_code.unwrap().0.as_str(), "SE");
333
334 let city = City::from(geoip2_city(None, None, Some("SWE"), None, None));
336 assert!(city.country_code.is_none());
337
338 let city = City::from(geoip2_city(None, None, None, None, None));
339 assert!(city.country_code.is_none());
340 }
341
342 #[test]
343 fn city_from_geoip2_location_requires_both_coordinates() {
344 let city = City::from(geoip2_city(
345 None,
346 None,
347 None,
348 Some(LAT_KNOWN),
349 Some(LON_KNOWN),
350 ));
351 let location = city.location.unwrap();
352 assert_eq!(location.lat, LAT_KNOWN);
353 assert_eq!(location.lon, LON_KNOWN);
354
355 let city = City::from(geoip2_city(None, None, None, Some(LAT_KNOWN), None));
356 assert!(city.location.is_none());
357
358 let city = City::from(geoip2_city(None, None, None, None, Some(LON_KNOWN)));
359 assert!(city.location.is_none());
360
361 let city = City::from(geoip2_city(None, None, None, None, None));
362 assert!(city.location.is_none());
363 }
364}