|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::fs; |
| 3 | +use std::io::{Cursor, Read}; |
| 4 | +use std::net::IpAddr; |
| 5 | +use std::path::{Path, PathBuf}; |
| 6 | +use std::sync::Arc; |
| 7 | +use std::time::Duration; |
| 8 | + |
| 9 | +use anyhow::{anyhow, Context, Result}; |
| 10 | +use flate2::read::GzDecoder; |
| 11 | +use maxminddb::geoip2::City; |
| 12 | +use maxminddb::Reader; |
| 13 | +use reqwest::Client; |
| 14 | +use tar::Archive; |
| 15 | +use tokio::sync::RwLock; |
| 16 | +use tracing::{info, warn}; |
| 17 | + |
| 18 | +use crate::config::Config; |
| 19 | + |
| 20 | +#[derive(Clone, Debug)] |
| 21 | +pub(crate) struct GeoPoint { |
| 22 | + pub(crate) latitude: f64, |
| 23 | + pub(crate) longitude: f64, |
| 24 | + pub(crate) city: Option<String>, |
| 25 | + pub(crate) country: Option<String>, |
| 26 | +} |
| 27 | + |
| 28 | +#[derive(Clone)] |
| 29 | +pub(crate) struct GeoIpService { |
| 30 | + reader: Option<Arc<Reader<Vec<u8>>>>, |
| 31 | + cache: Arc<RwLock<HashMap<String, Option<GeoPoint>>>>, |
| 32 | +} |
| 33 | + |
| 34 | +impl GeoIpService { |
| 35 | + pub(crate) fn from_reader(reader: Reader<Vec<u8>>) -> Self { |
| 36 | + Self { |
| 37 | + reader: Some(Arc::new(reader)), |
| 38 | + cache: Arc::new(RwLock::new(HashMap::new())), |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + #[cfg(test)] |
| 43 | + pub(crate) fn from_static(entries: HashMap<String, Option<GeoPoint>>) -> Self { |
| 44 | + Self { |
| 45 | + reader: None, |
| 46 | + cache: Arc::new(RwLock::new(entries)), |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + pub(crate) async fn lookup(&self, ip: &str) -> Option<GeoPoint> { |
| 51 | + if ip.is_empty() { |
| 52 | + return None; |
| 53 | + } |
| 54 | + |
| 55 | + { |
| 56 | + let cache = self.cache.read().await; |
| 57 | + if let Some(result) = cache.get(ip) { |
| 58 | + return result.clone(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + let ip_addr: IpAddr = match ip.parse() { |
| 63 | + Ok(addr) => addr, |
| 64 | + Err(_) => { |
| 65 | + self.cache_write(ip, None).await; |
| 66 | + return None; |
| 67 | + } |
| 68 | + }; |
| 69 | + |
| 70 | + let reader = match self.reader.as_ref() { |
| 71 | + Some(reader) => reader, |
| 72 | + None => { |
| 73 | + self.cache_write(ip, None).await; |
| 74 | + return None; |
| 75 | + } |
| 76 | + }; |
| 77 | + |
| 78 | + let result = reader |
| 79 | + .lookup::<City>(ip_addr) |
| 80 | + .ok() |
| 81 | + .and_then(|city| extract_point(&city)); |
| 82 | + self.cache_write(ip, result.clone()).await; |
| 83 | + result |
| 84 | + } |
| 85 | + |
| 86 | + async fn cache_write(&self, ip: &str, value: Option<GeoPoint>) { |
| 87 | + let mut cache = self.cache.write().await; |
| 88 | + cache.insert(ip.to_string(), value); |
| 89 | + } |
| 90 | +} |
| 91 | + |
| 92 | +pub(crate) async fn load_geoip(config: &Config) -> Result<GeoIpService> { |
| 93 | + let path = resolve_database_path(config)?; |
| 94 | + if !path.exists() { |
| 95 | + download_database(config, &path).await?; |
| 96 | + } |
| 97 | + let reader = Reader::open_readfile(&path) |
| 98 | + .with_context(|| format!("failed to open MaxMind database at {}", path.display()))?; |
| 99 | + Ok(GeoIpService::from_reader(reader)) |
| 100 | +} |
| 101 | + |
| 102 | +fn resolve_database_path(config: &Config) -> Result<PathBuf> { |
| 103 | + let path = PathBuf::from(config.maxmind_db_path.clone()); |
| 104 | + if let Some(parent) = path.parent() { |
| 105 | + fs::create_dir_all(parent) |
| 106 | + .with_context(|| format!("failed to create database directory {}", parent.display()))?; |
| 107 | + } |
| 108 | + Ok(path) |
| 109 | +} |
| 110 | + |
| 111 | +async fn download_database(config: &Config, target: &Path) -> Result<()> { |
| 112 | + let timeout = std::cmp::min(config.request_timeout, Duration::from_secs(5)); |
| 113 | + let client = Client::builder() |
| 114 | + .timeout(timeout) |
| 115 | + .build() |
| 116 | + .context("failed to build HTTP client for database download")?; |
| 117 | + |
| 118 | + if let Some(url) = config.maxmind_db_download_url.as_ref() { |
| 119 | + if let Err(err) = fetch_and_write(&client, url, target, true).await { |
| 120 | + warn!( |
| 121 | + ?err, |
| 122 | + "failed to download MaxMind database from MAXMIND_DB_DOWNLOAD_URL" |
| 123 | + ); |
| 124 | + } else { |
| 125 | + info!("downloaded MaxMind database from custom URL"); |
| 126 | + return Ok(()); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + if let Some(key) = config.maxmind_license_key.as_ref() { |
| 131 | + let url = format!("https://download.maxmind.com/app/geoip_download?edition_id={}&license_key={}&suffix=tar.gz", config.maxmind_edition_id, key); |
| 132 | + if let Err(err) = fetch_and_write(&client, &url, target, false).await { |
| 133 | + warn!(?err, "failed to download MaxMind database with license key"); |
| 134 | + } else { |
| 135 | + info!("downloaded MaxMind database using license key"); |
| 136 | + return Ok(()); |
| 137 | + } |
| 138 | + } |
| 139 | + |
| 140 | + let url = config |
| 141 | + .maxmind_fallback_url |
| 142 | + .as_deref() |
| 143 | + .unwrap_or("https://raw.githubusercontent.com/maxmind/MaxMind-DB/main/test-data/GeoLite2-City-Test.mmdb"); |
| 144 | + fetch_and_write(&client, url, target, true) |
| 145 | + .await |
| 146 | + .context("failed to download fallback MaxMind database") |
| 147 | +} |
| 148 | + |
| 149 | +async fn fetch_and_write(client: &Client, url: &str, target: &Path, raw_mmdb: bool) -> Result<()> { |
| 150 | + let response = client |
| 151 | + .get(url) |
| 152 | + .send() |
| 153 | + .await |
| 154 | + .context("database request failed")? |
| 155 | + .error_for_status() |
| 156 | + .context("database request returned error status")?; |
| 157 | + |
| 158 | + let bytes = response |
| 159 | + .bytes() |
| 160 | + .await |
| 161 | + .context("failed to read database body")?; |
| 162 | + |
| 163 | + if raw_mmdb { |
| 164 | + if url.ends_with(".gz") { |
| 165 | + let mut decoder = GzDecoder::new(Cursor::new(bytes)); |
| 166 | + let mut buf = Vec::new(); |
| 167 | + decoder |
| 168 | + .read_to_end(&mut buf) |
| 169 | + .context("failed to decompress database")?; |
| 170 | + fs::write(target, &buf).context("failed to write database file")?; |
| 171 | + return Ok(()); |
| 172 | + } else { |
| 173 | + fs::write(target, &bytes).context("failed to write database file")?; |
| 174 | + return Ok(()); |
| 175 | + } |
| 176 | + } |
| 177 | + |
| 178 | + let decoder = GzDecoder::new(Cursor::new(bytes)); |
| 179 | + let mut archive = Archive::new(decoder); |
| 180 | + for entry in archive |
| 181 | + .entries() |
| 182 | + .context("failed to iterate archive entries")? |
| 183 | + { |
| 184 | + let mut entry = entry.context("failed to read archive entry")?; |
| 185 | + let path = entry |
| 186 | + .path() |
| 187 | + .context("failed to read archive path")? |
| 188 | + .into_owned(); |
| 189 | + if path.extension().map(|ext| ext == "mmdb").unwrap_or(false) { |
| 190 | + let mut buf = Vec::new(); |
| 191 | + entry |
| 192 | + .read_to_end(&mut buf) |
| 193 | + .context("failed to read mmdb entry")?; |
| 194 | + fs::write(target, &buf).context("failed to write database file")?; |
| 195 | + return Ok(()); |
| 196 | + } |
| 197 | + } |
| 198 | + |
| 199 | + Err(anyhow!("mmdb file not found in archive")) |
| 200 | +} |
| 201 | + |
| 202 | +fn extract_point(city: &City) -> Option<GeoPoint> { |
| 203 | + let location = city.location.as_ref()?; |
| 204 | + let latitude = location.latitude?; |
| 205 | + let longitude = location.longitude?; |
| 206 | + let city_name = city |
| 207 | + .city |
| 208 | + .as_ref() |
| 209 | + .and_then(|record| record.names.as_ref()) |
| 210 | + .and_then(|names| names.get("en").cloned()); |
| 211 | + let country_name = city |
| 212 | + .country |
| 213 | + .as_ref() |
| 214 | + .and_then(|record| record.names.as_ref()) |
| 215 | + .and_then(|names| names.get("en").cloned()); |
| 216 | + Some(GeoPoint { |
| 217 | + latitude, |
| 218 | + longitude, |
| 219 | + city: city_name, |
| 220 | + country: country_name, |
| 221 | + }) |
| 222 | +} |
0 commit comments