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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#![warn(rust_2018_idioms)]
use bytes::BytesMut;
use ip_network::IpNetwork;
use reqwest::{header, IntoUrl};
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::convert::TryFrom;
use std::net::IpAddr;
use std::time::Duration;
pub mod bootstrap;
pub mod parser;
#[derive(Debug)]
pub enum SearchDomain {
Name(String),
NsLdhName(String),
NsIp(IpAddr),
}
impl SearchDomain {
fn key(&self) -> &'static str {
match self {
Self::Name(..) => "name",
Self::NsLdhName(..) => "nsLdhName",
Self::NsIp(..) => "nsIp",
}
}
fn value(self) -> String {
match self {
Self::Name(value) => value,
Self::NsLdhName(value) => value,
Self::NsIp(value) => value.to_string(),
}
}
}
#[derive(Debug)]
pub enum SearchEntity {
Fn(String),
Handle(String),
}
impl SearchEntity {
fn key(&self) -> &'static str {
match self {
Self::Fn(..) => "fn",
Self::Handle(..) => "handle",
}
}
fn value(self) -> String {
match self {
Self::Fn(value) => value,
Self::Handle(value) => value,
}
}
}
#[derive(Debug)]
pub enum SearchNameserver {
Name(String),
Ip(IpAddr),
}
impl SearchNameserver {
fn key(&self) -> &'static str {
match self {
Self::Name(..) => "name",
Self::Ip(..) => "ip",
}
}
fn value(self) -> String {
match self {
Self::Name(value) => value,
Self::Ip(value) => value.to_string(),
}
}
}
#[derive(Debug)]
pub enum ClientError {
Reqwest(reqwest::Error),
Server(Box<reqwest::Response>),
JsonDecode(Box<reqwest::Response>, serde_json::error::Error),
Rdap(Box<reqwest::Url>, parser::Error),
}
impl From<reqwest::Error> for ClientError {
fn from(error: reqwest::Error) -> Self {
ClientError::Reqwest(error)
}
}
const RDAP_CONTENT_TYPES: [&str; 2] = ["application/rdap+json", "application/json"];
fn is_rdap_response(response: &reqwest::Response) -> bool {
if let Some(content_length) = response.content_length() {
if content_length == 0 {
return false;
}
}
if let Some(content_type) = response.headers().get(header::CONTENT_TYPE) {
if let Ok(content_type_str) = content_type.to_str() {
return RDAP_CONTENT_TYPES
.iter()
.any(|rdap_type| content_type_str.contains(rdap_type));
}
}
false
}
#[derive(Default)]
pub struct Client {
client: reqwest::Client,
}
impl Client {
pub fn new() -> Self {
let client = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.build()
.unwrap();
Self::with_reqwest_client(client)
}
pub fn with_reqwest_client(client: reqwest::Client) -> Self {
Self { client }
}
async fn get_boostrap<T: DeserializeOwned>(
&self,
url: &str,
) -> Result<parser::Bootstrap<T>, reqwest::Error> {
self.client.get(url).send().await?.json().await
}
pub async fn fetch_bootstrap_asn(&self) -> Result<bootstrap::Asn, Box<dyn std::error::Error>> {
let bootstrap = self
.get_boostrap("https://data.iana.org/rdap/asn.json")
.await?;
Ok(bootstrap::Asn::try_from(&bootstrap)?)
}
pub async fn fetch_bootstrap_dns(&self) -> Result<bootstrap::Dns, Box<dyn std::error::Error>> {
let bootstrap = self
.get_boostrap("https://data.iana.org/rdap/dns.json")
.await?;
Ok(bootstrap::Dns::from(&bootstrap))
}
pub async fn fetch_bootstrap_ip(&self) -> Result<bootstrap::Ip, Box<dyn std::error::Error>> {
let (parsed_ipv4, parsed_ipv6) = futures::join!(
self.get_boostrap("https://data.iana.org/rdap/ipv4.json"),
self.get_boostrap("https://data.iana.org/rdap/ipv6.json"),
);
Ok(bootstrap::Ip::try_from((&parsed_ipv4?, &parsed_ipv6?))?)
}
pub async fn fetch_bootstrap_object_tags(
&self,
) -> Result<bootstrap::ObjectTags, Box<dyn std::error::Error>> {
let bootstrap = self
.get_boostrap("https://data.iana.org/rdap/object-tags.json")
.await?;
Ok(bootstrap::ObjectTags::from(&bootstrap))
}
pub async fn fetch_bootstrap(
&self,
) -> Result<bootstrap::Bootstrap, Box<dyn std::error::Error>> {
let (asn, dns, ip, object_tags) = futures::join!(
self.fetch_bootstrap_asn(),
self.fetch_bootstrap_dns(),
self.fetch_bootstrap_ip(),
self.fetch_bootstrap_object_tags(),
);
Ok(bootstrap::Bootstrap {
ip: ip?,
dns: dns?,
asn: asn?,
object_tags: object_tags?,
})
}
async fn parse_response<T: DeserializeOwned>(
mut response: reqwest::Response,
) -> Result<T, ClientError> {
let mut buf = if let Some(content_length) = response.content_length() {
BytesMut::with_capacity(8192.min(content_length) as usize)
} else {
BytesMut::new()
};
while let Some(chunk) = response.chunk().await? {
buf.extend(chunk);
}
if buf.is_empty() {
return Err(ClientError::Server(Box::new(response)));
}
serde_json::from_slice(&buf.freeze())
.map_err(|e| ClientError::JsonDecode(Box::new(response), e))
}
async fn handle_response<T: DeserializeOwned>(
response: reqwest::Response,
) -> Result<T, ClientError> {
if response.status() == reqwest::StatusCode::OK {
Self::parse_response(response).await
} else if is_rdap_response(&response) {
Err(ClientError::Rdap(
Box::new(response.url().clone()),
Self::parse_response(response).await?,
))
} else {
Err(ClientError::Server(Box::new(response)))
}
}
fn construct_headers() -> header::HeaderMap {
let mut headers = header::HeaderMap::new();
headers.insert(
header::ACCEPT,
header::HeaderValue::from_str(&RDAP_CONTENT_TYPES.join(", "))
.expect("error during converting header value"),
);
headers
}
async fn get<T: DeserializeOwned, I: IntoUrl>(&self, url: I) -> Result<T, ClientError> {
self.client
.get(url)
.headers(Self::construct_headers())
.send()
.await
.map(Self::handle_response)?
.await
}
async fn get_with_query<T: DeserializeOwned, I: IntoUrl, Q: Serialize>(
&self,
url: I,
query: &Q,
) -> Result<T, ClientError> {
self.client
.get(url)
.query(query)
.headers(Self::construct_headers())
.send()
.await
.map(Self::handle_response)?
.await
}
pub async fn query_ip<I: Into<IpAddr>>(
&self,
server: &str,
ip: I,
) -> Result<parser::IpNetwork, ClientError> {
let url = format!("{}ip/{}", server, ip.into());
self.get(&url).await
}
pub async fn query_ip_network<I: Into<IpNetwork>>(
&self,
server: &str,
ip_network: I,
) -> Result<parser::IpNetwork, ClientError> {
let ip_network = ip_network.into();
let url = format!(
"{}ip/{}/{}",
server,
ip_network.network_address(),
ip_network.netmask()
);
self.get(&url).await
}
pub async fn query_asn(&self, server: &str, asn: u32) -> Result<parser::AutNum, ClientError> {
let url = format!("{}autnum/{}", server, asn);
self.get(&url).await
}
pub async fn query_nameserver(
&self,
server: &str,
nameserver: &str,
) -> Result<parser::Nameserver, ClientError> {
let url = format!("{}nameserver/{}", server, nameserver);
self.get(&url).await
}
pub async fn query_domain(
&self,
server: &str,
domain: &str,
) -> Result<parser::Domain, ClientError> {
let url = format!("{}domain/{}", server, domain);
self.get(&url).await
}
pub async fn query_reverse_domain<I: Into<IpAddr>>(
&self,
server: &str,
ip: I,
) -> Result<parser::Domain, ClientError> {
let domain = match ip.into() {
IpAddr::V4(ipv4) => {
let octets = ipv4.octets();
format!(
"{}.{}.{}.{}.in-addr.arpa",
octets[3], octets[2], octets[1], octets[0]
)
}
IpAddr::V6(ipv6) => {
let mut ret: [u8; 32] = Default::default();
for (i, byte) in ipv6.octets().iter().enumerate() {
ret[i * 2] = byte >> 4;
ret[i * 2 + 1] = byte & 0xf;
}
ret.reverse();
format!(
"{}.ip6.arpa",
ret.iter()
.map(|n| n.to_string())
.collect::<Vec<_>>()
.join(".")
)
}
};
self.query_domain(server, &domain).await
}
pub async fn query_entity(
&self,
server: &str,
entity: &str,
) -> Result<parser::Entity, ClientError> {
let url = format!("{}entity/{}", server, entity);
self.get(&url).await
}
pub async fn search_nameserver(
&self,
server: &str,
search_nameserver: SearchNameserver,
) -> Result<parser::NameserverSearchResults, ClientError> {
let url = &format!("{}nameservers", server);
self.get_with_query(url, &[(search_nameserver.key(), search_nameserver.value())])
.await
}
pub async fn search_domain(
&self,
server: &str,
search_domain: SearchDomain,
) -> Result<parser::DomainSearchResults, ClientError> {
let url = format!("{}domains", server);
self.get_with_query(&url, &[(search_domain.key(), search_domain.value())])
.await
}
pub async fn search_entity(
&self,
server: &str,
search_entity: SearchEntity,
) -> Result<parser::EntitySearchResults, ClientError> {
let url = format!("{}entities", server);
self.get_with_query(&url, &[(search_entity.key(), search_entity.value())])
.await
}
pub async fn search_networks_by_origin_as(
&self,
server: &str,
asn: u32,
) -> Result<parser::ArinOriginas0OriginautnumsResults, ClientError> {
let url = format!("{}arin_originas0_networksbyoriginas/{}", server, asn);
self.get(&url).await
}
pub async fn help(&self, server: &str) -> Result<parser::Help, ClientError> {
let url = format!("{}help/", server);
self.get(&url).await
}
}
#[cfg(test)]
mod tests {
use crate::Client;
#[test]
fn test_send_sync() {
fn is_send_sync<T: Send + Sync>() {}
is_send_sync::<Client>();
}
}