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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
use crate::{Error, IpType, Provider, Result};
use async_trait::async_trait;
use derive_deref::Deref;
use log::{debug, trace};
use reqwest::{Client, Proxy};
use serde::Deserialize;
use serde_json::Value;
use std::default::Default;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use std::time::Duration;
use thiserror::Error as ErrorDerive;
use trust_dns_resolver::{
config::{NameServerConfig, Protocol, ResolverConfig, ResolverOpts},
error::ResolveError,
TokioAsyncResolver,
};
#[derive(Clone, Copy, Debug, Deserialize, PartialEq)]
pub enum ProviderMethod {
#[serde(rename = "plain")]
Plain,
#[serde(rename = "json")]
Json,
#[serde(rename = "dns")]
Dns,
}
#[derive(Clone, Debug, Deserialize, PartialEq)]
pub struct ProviderInfo {
name: String,
#[serde(rename = "type")]
addr_type: IpType,
method: ProviderMethod,
url: String,
key: Option<String>,
}
impl Default for ProviderInfo {
fn default() -> Self {
Self {
name: String::default(),
addr_type: IpType::Ipv4,
method: ProviderMethod::Plain,
url: String::default(),
key: None,
}
}
}
#[derive(Debug, ErrorDerive)]
pub enum GlobalIpError {
#[error(transparent)]
ReqwestError(#[from] reqwest::Error),
#[error(transparent)]
JsonParseError(#[from] serde_json::Error),
#[error("field `{0}' does not exist in response")]
JsonNotFoundError(String),
#[error("field `{0}' in response can't be decoded")]
JsonDecodeError(String),
#[error(transparent)]
DnsError(#[from] Box<ResolveError>),
#[error("specified DNS server `{0}' has no address")]
DnsNoServerError(String),
}
macro_rules! make_get_type {
() => {
fn get_type(&self) -> IpType {
self.info.addr_type
}
};
}
macro_rules! make_new {
($name: ident) => {
impl $name {
fn new(info: &ProviderInfo, timeout: u64, proxy: &Option<(String, u16)>) -> Self {
Self(AbstractProvider {
info: info.clone(),
timeout,
proxy: proxy.clone(),
})
}
}
};
}
#[derive(Clone, Debug)]
pub struct AbstractProvider {
pub info: ProviderInfo,
pub timeout: u64,
pub proxy: Option<(String, u16)>,
}
impl Default for AbstractProvider {
fn default() -> Self {
Self {
info: ProviderInfo::default(),
timeout: 1000,
proxy: None,
}
}
}
fn build_client(timeout: u64, proxy: &Option<(String, u16)>) -> reqwest::Result<Client> {
let client = match (timeout, proxy) {
(0, None) => Client::new(),
(0, Some((host, port))) => Client::builder()
.proxy(Proxy::all(&format!("http://{}:{}", host, port))?)
.build()?,
(_, None) => Client::builder()
.timeout(Duration::from_millis(timeout))
.build()?,
(_, Some((host, port))) => Client::builder()
.proxy(Proxy::all(&format!("http://{}:{}", host, port))?)
.timeout(Duration::from_millis(timeout))
.build()?,
};
Ok(client)
}
async fn build_client_get(
url: &str,
timeout: u64,
proxy: &Option<(String, u16)>,
) -> Result<String> {
Ok((async {
let client = build_client(timeout, proxy)?;
debug!("Reqwesting {:?} through proxy {:?}", url, proxy);
client
.get(url)
.send()
.await?
.error_for_status()?
.text()
.await
})
.await
.map_err(GlobalIpError::ReqwestError)?)
}
fn create_ipaddr(addr: &str, addr_type: IpType) -> Result<IpAddr> {
Ok(match addr_type {
IpType::Ipv4 => IpAddr::V4(Ipv4Addr::from_str(addr).map_err(Error::AddrParseError)?),
IpType::Ipv6 => IpAddr::V6(Ipv6Addr::from_str(addr).map_err(Error::AddrParseError)?),
})
}
#[derive(Clone, Debug, Deref)]
pub struct ProviderPlain(AbstractProvider);
make_new! {ProviderPlain}
#[async_trait]
impl Provider for ProviderPlain {
async fn get_addr(&self) -> Result<IpAddr> {
let addr = build_client_get(&self.info.url, self.timeout, &self.proxy).await?;
debug!("Plain provider {:?} returned {:?}", self.info, addr);
create_ipaddr(&addr, self.info.addr_type)
}
make_get_type! {}
}
#[derive(Clone, Debug, Deref)]
pub struct ProviderJson(AbstractProvider);
make_new! {ProviderJson}
#[async_trait]
impl Provider for ProviderJson {
async fn get_addr(&self) -> Result<IpAddr> {
let resp = build_client_get(&self.info.url, self.timeout, &self.proxy).await?;
trace!("Provider got response {:?}", resp);
let json: Value = serde_json::from_str(&resp).map_err(GlobalIpError::JsonParseError)?;
let key = self
.info
.key
.clone()
.expect("`key' should exist for JSON providers");
let addr = json
.get(&key)
.ok_or_else(|| GlobalIpError::JsonNotFoundError(key.clone()))?
.as_str()
.ok_or(GlobalIpError::JsonDecodeError(key))?;
debug!("JSON provider {:?} returned {:?}", self.info, addr);
create_ipaddr(addr, self.info.addr_type)
}
make_get_type! {}
}
#[derive(Clone, Debug, Deref)]
pub struct ProviderDns(AbstractProvider);
make_new! {ProviderDns}
async fn host_to_addr(
resolver: TokioAsyncResolver,
host: &str,
addr_type: IpType,
) -> std::result::Result<Option<IpAddr>, ResolveError> {
Ok(match addr_type {
IpType::Ipv4 => {
let srv = resolver.ipv4_lookup(host).await?;
(|| Some(IpAddr::V4(*srv.iter().next()?)))()
}
IpType::Ipv6 => {
let srv = resolver.ipv6_lookup(host).await?;
(|| Some(IpAddr::V6(*srv.iter().next()?)))()
}
})
}
#[async_trait]
impl Provider for ProviderDns {
async fn get_addr(&self) -> Result<IpAddr> {
let (query, server) = self
.info
.url
.split_once('@')
.expect("DNS Provider URL should be like query@server");
let opts = ResolverOpts {
timeout: Duration::from_millis(self.timeout),
..ResolverOpts::default()
};
let resolver = TokioAsyncResolver::tokio(ResolverConfig::new(), opts)
.map_err(|e| GlobalIpError::DnsError(Box::new(e)))?;
debug!("Resolving {:?} on {:?}", server, resolver);
let server_addr = host_to_addr(resolver, server, self.info.addr_type)
.await
.map_err(|e| GlobalIpError::DnsError(Box::new(e)))?
.ok_or_else(|| GlobalIpError::DnsNoServerError(server.to_string()))?;
let ns = NameServerConfig {
socket_addr: std::net::SocketAddr::new(server_addr, 53),
protocol: Protocol::Udp,
tls_dns_name: None,
trust_nx_responses: false,
};
let mut config = ResolverConfig::new();
config.add_name_server(ns);
let resolver = TokioAsyncResolver::tokio(config, opts)
.map_err(|e| GlobalIpError::DnsError(Box::new(e)))?;
debug!("Resolving {:?} on {:?}", query, resolver);
let addr = host_to_addr(resolver, query, self.info.addr_type)
.await
.map_err(|e| GlobalIpError::DnsError(Box::new(e)))?
.ok_or_else(|| GlobalIpError::DnsNoServerError(server.to_string()))?;
debug!("DNS provider {:?} returned {:?}", self.info, addr);
Ok(addr)
}
make_get_type! {}
}
#[derive(Debug)]
pub struct ProviderMultiple {
providers: Vec<ProviderInfo>,
addr_type: IpType,
timeout: u64,
proxy: Option<(String, u16)>,
}
impl Default for ProviderMultiple {
fn default() -> Self {
let providers: Vec<ProviderInfo> = serde_json::from_str(DEFAULT_PROVIDERS).unwrap();
Self {
providers,
addr_type: IpType::Ipv4,
timeout: 1000,
proxy: None,
}
}
}
impl ProviderMultiple {
#[must_use]
pub fn default_v6() -> Self {
Self {
addr_type: IpType::Ipv6,
..ProviderMultiple::default()
}
}
}
#[async_trait]
impl Provider for ProviderMultiple {
async fn get_addr(&self) -> Result<IpAddr> {
let mut result: Result<IpAddr> = Err(crate::Error::NoAddress);
trace!("Registered providers: {:?}", self.providers);
for info in &self.providers {
if info.addr_type != self.addr_type {
continue;
}
let this_result = match info.method {
ProviderMethod::Plain => {
let provider = ProviderPlain::new(info, self.timeout, &self.proxy);
provider.get_addr().await
}
ProviderMethod::Json => {
let provider = ProviderJson::new(info, self.timeout, &self.proxy);
provider.get_addr().await
}
ProviderMethod::Dns => {
let provider = ProviderDns::new(info, self.timeout, &self.proxy);
provider.get_addr().await
}
};
if this_result.is_ok() {
debug!("Using result {:?} from provider {:?}", this_result, info);
result = this_result;
break;
}
}
result
}
fn get_type(&self) -> IpType {
self.addr_type
}
}
pub const DEFAULT_PROVIDERS: &str = r#"[
{
"method": "plain",
"name": "ipify",
"type": "IPv4",
"url": "https://api.ipify.org/"
},
{
"method": "plain",
"name": "ipify",
"type": "IPv6",
"url": "https://api6.ipify.org/"
},
{
"method": "plain",
"name": "ipv6-test",
"type": "IPv4",
"url": "http://v4.ipv6-test.com/api/myip.php"
},
{
"method": "plain",
"name": "ipv6-test",
"type": "IPv6",
"url": "http://v6.ipv6-test.com/api/myip.php"
},
{
"method": "plain",
"name": "ident.me",
"type": "IPv4",
"url": "http://v4.ident.me/"
},
{
"method": "plain",
"name": "ident.me",
"type": "IPv6",
"url": "http://v6.ident.me/"
},
{
"key": "ip",
"method": "json",
"name": "test-ipv6",
"padding": "callback",
"type": "IPv4",
"url": "http://ipv4.test-ipv6.com/ip/"
},
{
"key": "ip",
"method": "json",
"name": "test-ipv6",
"padding": "callback",
"type": "IPv6",
"url": "http://ipv6.test-ipv6.com/ip/"
},
{
"method": "dns",
"name": "opendns.com",
"type": "IPv4",
"url": "myip.opendns.com@resolver1.opendns.com"
},
{
"method": "dns",
"name": "opendns.com",
"type": "IPv6",
"url": "myip.opendns.com@resolver1.opendns.com"
},
{
"method": "dns",
"name": "akamai.com",
"type": "IPv4",
"url": "whoami.akamai.com@ns1-1.akamaitech.net"
},
{
"method": "plain",
"name": "akamai.com",
"type": "IPv4",
"url": "http://whatismyip.akamai.com"
},
{
"method": "plain",
"name": "akamai.com",
"type": "IPv6",
"url": "http://ipv6.whatismyip.akamai.com"
}
]"#;