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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
use std::sync::Arc;

use bytes::Bytes;
use maxminddb::Reader;
use once_cell::sync::Lazy;

type Result<T, E = Error> = std::result::Result<T, E>;

static HTTP: Lazy<
    hyper::Client<
        hyper_rustls::HttpsConnector<hyper::client::connect::HttpConnector>,
        hyper::body::Body,
    >,
> = Lazy::new(|| {
    hyper::Client::builder().build(
        hyper_rustls::HttpsConnectorBuilder::new()
            .with_webpki_roots()
            .https_or_http()
            .enable_http1()
            .enable_http2()
            .build(),
    )
});
pub static CLIENT: Lazy<arc_swap::ArcSwapOption<MaxmindDb>> = Lazy::new(<_>::default);

#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, schemars::JsonSchema)]
#[serde(tag = "kind")]
pub enum Source {
    File { path: std::path::PathBuf },
    Url { url: url::Url },
}

impl std::str::FromStr for Source {
    type Err = eyre::Error;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        if let Ok(url) = input.parse() {
            Ok(Self::Url { url })
        } else if let Ok(path) = input.parse() {
            Ok(Self::File { path })
        } else {
            Err(eyre::eyre!("'{}' is not a valid URL or path", input))
        }
    }
}

#[derive(Debug)]
pub struct MaxmindDb {
    reader: Reader<Bytes>,
}

impl MaxmindDb {
    fn new(reader: Reader<Bytes>) -> Self {
        Self { reader }
    }

    pub fn instance() -> arc_swap::Guard<Option<Arc<MaxmindDb>>> {
        CLIENT.load()
    }

    pub fn lookup(ip: std::net::IpAddr) -> Option<IpNetEntry> {
        let mmdb = match crate::MaxmindDb::instance().clone() {
            Some(mmdb) => mmdb,
            None => {
                tracing::debug!("skipping mmdb telemetry, no maxmind database available");
                return None;
            }
        };

        match mmdb.lookup::<IpNetEntry>(ip) {
            Ok(asn) => {
                tracing::info!(
                    number = asn.r#as,
                    organization = asn.as_name,
                    country_code = asn.as_cc,
                    prefix = asn.prefix,
                    prefix_entity = asn.prefix_entity,
                    prefix_name = asn.prefix_name,
                    "maxmind information"
                );

                Some(asn)
            }
            Err(error) => {
                tracing::warn!(%ip, %error, "ip not found in maxmind database");
                None
            }
        }
    }

    #[tracing::instrument(skip_all)]
    pub async fn update(source: Source) -> Result<()> {
        let db = Self::from_source(source).await?;
        CLIENT.store(Some(Arc::new(db)));
        tracing::info!("maxmind database updated");
        Ok(())
    }

    #[tracing::instrument(skip_all)]
    pub async fn from_source(source: Source) -> Result<Self> {
        match source {
            Source::File { path } => Self::open(path).await,
            Source::Url { url } => Self::open_url(&url).await,
        }
    }

    #[tracing::instrument(skip_all, fields(path = %path.as_ref().display()))]
    pub async fn open<A: AsRef<std::path::Path>>(path: A) -> Result<Self> {
        let path = path.as_ref();
        tracing::info!(path=%path.display(), "trying to read local maxmind database");
        let bytes = Bytes::from(tokio::fs::read(path).await?);
        Reader::from_source(bytes)
            .map(Self::new)
            .map_err(From::from)
    }

    /// Reads a Maxmind DB from `url`, and if `cache` is `true`, then will use
    /// the cached result, retreiving a fresh copy otherwise.
    #[tracing::instrument(skip_all, fields(url = %url))]
    pub async fn open_url(url: &url::Url) -> Result<Self> {
        tracing::info!("requesting maxmind database from network");
        let data = hyper::body::to_bytes(
            HTTP.get(url.as_str().try_into().unwrap())
                .await?
                .into_body(),
        )
        .await?;

        tracing::debug!("finished download");
        let reader = Reader::from_source(data)?;

        Ok(Self { reader })
    }
}

impl std::ops::Deref for MaxmindDb {
    type Target = Reader<Bytes>;

    fn deref(&self) -> &Self::Target {
        &self.reader
    }
}

impl std::ops::DerefMut for MaxmindDb {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.reader
    }
}

#[derive(Debug, serde::Deserialize)]
pub struct IpNetEntry {
    #[serde(default)]
    pub allocation: String,
    #[serde(default)]
    pub allocation_cc: String,
    #[serde(default)]
    pub allocation_registry: String,
    #[serde(default)]
    pub allocation_status: String,
    #[serde(default)]
    pub r#as: u64,
    #[serde(default)]
    pub as_cc: String,
    #[serde(default)]
    pub as_entity: String,
    #[serde(default)]
    pub as_name: String,
    #[serde(default)]
    pub as_private: bool,
    #[serde(default)]
    pub as_registry: String,
    #[serde(default)]
    pub prefix: String,
    #[serde(default)]
    pub prefix_asset: Vec<String>,
    #[serde(default)]
    pub prefix_assignment: String,
    #[serde(default)]
    pub prefix_bogon: bool,
    #[serde(default)]
    pub prefix_entity: String,
    #[serde(default)]
    pub prefix_name: String,
    #[serde(default)]
    pub prefix_origins: Vec<u64>,
    #[serde(default)]
    pub prefix_registry: String,
    #[serde(default)]
    pub rpki_status: String,
}

#[derive(Debug, thiserror::Error)]
pub enum Error {
    #[error(transparent)]
    MaxmindDb(#[from] maxminddb::MaxMindDBError),
    #[error(transparent)]
    Http(#[from] hyper::Error),
    #[error(transparent)]
    Io(#[from] std::io::Error),
}