forked from mokeyish/smartdns-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdns_url.rs
558 lines (483 loc) · 15.8 KB
/
dns_url.rs
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
use crate::libdns::resolver::config::Protocol;
use std::collections::BTreeMap;
use std::hash::Hash;
use std::net::SocketAddr;
use std::string::ToString;
use std::{
net::{IpAddr, Ipv4Addr, Ipv6Addr},
str::FromStr,
};
use url::{Host, Url};
/// alias: system、google、cloudflare、quad9
/// udp://8.8.8.8 or 8.8.8.8 or [240e:1f:1::1] => DNS over UDP
/// tcp://8.8.8.8:53 => DNS over TCP
/// tls://8.8.8.8:853 => DoT: DNS over TLS
/// quic://8.8.8.8:853 => DoT: DNS over QUIC
/// https://1.1.1.1/dns-query => DoH: DNS over HTTPS
/// h3://1.1.1.1/dns-query => DoH3: DNS over HTTP/3
#[derive(Debug, Clone, Eq)]
pub struct DnsUrl {
proto: Protocol,
host: Host,
port: Option<u16>,
path: Option<String>,
ip: Option<IpAddr>,
params: BTreeMap<String, String>,
}
impl DnsUrl {
#[inline]
pub fn proto(&self) -> &Protocol {
&self.proto
}
#[inline]
pub fn host(&self) -> &Host {
&self.host
}
pub fn port(&self) -> u16 {
self.port
.unwrap_or_else(|| dns_proto_default_port(&self.proto))
}
pub fn is_default_port(&self) -> bool {
self.port() == dns_proto_default_port(&self.proto)
}
pub fn path(&self) -> &str {
match self.proto {
Protocol::Https | Protocol::H3 => match self.path.as_ref() {
Some(p) => p,
None => "/dns-query",
},
_ => "",
}
}
pub fn ip(&self) -> Option<IpAddr> {
self.ip
.or_else(|| match self.host() {
Host::Domain(_) => None,
Host::Ipv4(ip) => Some(ip.to_owned().into()),
Host::Ipv6(ip) => Some(ip.to_owned().into()),
})
.or_else(|| self.get_param::<IpAddr>("ip"))
}
pub fn domain(&self) -> Option<&str> {
if let Host::Domain(domain) = self.host() {
Some(domain.as_str())
} else {
self.params.get("host").map(|s| s.as_str())
}
}
#[inline]
pub fn addr(&self) -> Option<SocketAddr> {
self.ip().map(|ip| SocketAddr::new(ip, self.port()))
}
pub fn set_ip(&mut self, ip: IpAddr) {
self.ip = Some(ip)
}
pub fn set_host(&mut self, name: &str) {
match self.host() {
Host::Ipv4(ip) => self.set_ip((*ip).into()),
Host::Ipv6(ip) => self.set_ip((*ip).into()),
_ => (),
}
self.host = Host::Domain(name.to_string())
}
}
#[derive(Debug)]
pub enum DnsUrlParseErr {
ParseError(String),
ProtocolNotSupport(String),
HostUnspecified,
}
impl PartialEq for DnsUrl {
fn eq(&self, other: &Self) -> bool {
self.proto == other.proto
&& self.host == other.host
&& self.port == other.port
&& self.path == other.path
&& self.ip == other.ip
&& self.params() == other.params()
}
}
impl Hash for DnsUrl {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
format!("{:?}", self.proto).hash(state);
self.host.hash(state);
self.port.hash(state);
self.path.hash(state);
self.ip.hash(state);
self.params.hash(state);
}
}
impl FromStr for DnsUrl {
type Err = DnsUrlParseErr;
fn from_str(url: &str) -> Result<Self, Self::Err> {
let mut url = url.to_lowercase();
if !url.contains("://") {
url.insert_str(0, "udp://")
}
let is_endwith_slash = url.ends_with('/');
let url = Url::parse(url.as_str())?;
let proto = match url.scheme() {
"udp" => Protocol::Udp,
"tcp" => Protocol::Tcp,
"tls" => Protocol::Tls,
#[cfg(feature = "dns-over-https")]
"https" => Protocol::Https,
#[cfg(feature = "dns-over-quic")]
"quic" => Protocol::Quic,
#[cfg(feature = "dns-over-h3")]
"h3" => Protocol::H3,
schema => return Err(DnsUrlParseErr::ProtocolNotSupport(schema.to_string())),
};
let host = url.host();
let port = url.port();
if host.is_none() {
return Err(DnsUrlParseErr::HostUnspecified);
}
let mut host = host.unwrap().to_owned();
if let Host::Domain(ref domain) = host {
if let Ok(ip) = IpAddr::from_str(domain) {
host = match ip {
IpAddr::V4(ip) => Host::Ipv4(ip),
IpAddr::V6(ip) => Host::Ipv6(ip),
};
}
}
let params = url
.query_pairs()
.into_iter()
.map(|(n, v)| (n.into_owned(), v.into_owned()))
.collect::<BTreeMap<_, _>>();
Ok(Self {
proto,
host,
port,
path: if url.path() == "/" && !is_endwith_slash {
None
} else {
Some(url.path().to_string())
},
ip: None,
params,
})
}
}
impl ToString for DnsUrl {
fn to_string(&self) -> String {
let mut out = String::new();
use Protocol::*;
// schema
out += match self.proto {
Udp => "udp://",
Tcp => "tcp://",
Tls => "tls://",
#[cfg(feature = "dns-over-https")]
Https => "https://",
#[cfg(feature = "dns-over-quic")]
Quic => "quic://",
#[cfg(feature = "dns-over-h3")]
H3 => "h3://",
_ => unimplemented!(),
};
// host
out += &self.host().to_string();
// port
if !self.is_default_port() {
out.push(':');
out += &self.port().to_string();
}
// path
if matches!(self.proto, Protocol::Https) {
out += self.path();
}
// query
if !self.params.is_empty() {
for (i, (n, v)) in self.params.iter().enumerate() {
out.push(if i == 0 { '?' } else { '&' });
out.push_str(n);
out.push('=');
out.push_str(v);
}
}
out
}
}
impl From<url::ParseError> for DnsUrlParseErr {
fn from(value: url::ParseError) -> Self {
Self::ParseError(value.to_string())
}
}
impl From<&Ipv4Addr> for DnsUrl {
#[inline]
fn from(ip: &Ipv4Addr) -> Self {
ip.to_string().parse().unwrap()
}
}
impl From<&Ipv6Addr> for DnsUrl {
#[inline]
fn from(ip: &Ipv6Addr) -> Self {
format!("[{}]", ip).parse().unwrap()
}
}
impl From<&IpAddr> for DnsUrl {
#[inline]
fn from(ip: &IpAddr) -> Self {
match ip {
IpAddr::V4(ip) => ip.into(),
IpAddr::V6(ip) => ip.into(),
}
}
}
fn dns_proto_default_port(proto: &Protocol) -> u16 {
use Protocol::*;
match *proto {
Udp => 53,
Tcp => 53,
Tls => 853,
#[cfg(feature = "dns-over-https")]
Https => 443,
#[cfg(feature = "dns-over-h3")]
H3 => 443,
#[cfg(feature = "dns-over-quic")]
Quic => 853,
#[cfg(feature = "mdns")]
#[cfg_attr(docsrs, doc(cfg(feature = "mdns")))]
Mdns => 5353,
_ => unimplemented!(),
}
}
pub trait DnsUrlParam {
fn params(&self) -> &BTreeMap<String, String>;
fn get_param<T: FromStr>(&self, name: &str) -> Option<T>;
fn get_param_or_default<T: Default + FromStr>(&self, name: &str) -> T {
self.get_param(name).unwrap_or_default()
}
fn set_param<T: ToString>(&mut self, name: &str, value: T);
}
impl DnsUrlParam for DnsUrl {
fn params(&self) -> &BTreeMap<String, String> {
&self.params
}
fn get_param<T: FromStr>(&self, name: &str) -> Option<T> {
self.params
.get(name)
.map(|v| T::from_str(v).ok())
.unwrap_or_default()
}
fn set_param<T: ToString>(&mut self, name: &str, value: T) {
*(self.params.entry(name.to_string()).or_default()) = value.to_string()
}
}
pub trait DnsUrlParamExt: DnsUrlParam {
fn set_sni_on(&mut self, value: bool) {
self.set_param("sni", value)
}
fn set_sni_off(&mut self, value: bool) {
self.set_param("sni", !value)
}
fn sni_on(&self) -> bool {
!self.sni_off()
}
fn sni_off(&self) -> bool {
self.get_param::<bool>("sni")
.map(|v| !v)
.or_else(|| self.get_param::<bool>("enable_sni").map(|v| !v))
.unwrap_or(false)
}
fn ssl_verify(&self) -> bool {
self.get_param("ssl_verify").unwrap_or(true)
}
fn set_ssl_verify(&mut self, verify: bool) {
self.set_param("ssl_verify", verify)
}
}
impl DnsUrlParamExt for DnsUrl {}
#[cfg(test)]
mod tests {
use crate::preset_ns::CLOUDFLARE_IPS;
use super::*;
#[test]
fn test_parse_udp() {
let url = DnsUrl::from_str("8.8.8.8").unwrap();
assert_eq!(url.proto, Protocol::Udp);
assert_eq!(url.host.to_string(), "8.8.8.8");
assert_eq!(url.port(), 53);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "udp://8.8.8.8");
assert!(url.ip().is_some());
}
#[test]
fn test_parse_udp_1() {
let url = DnsUrl::from_str("udp://8.8.8.8").unwrap();
assert_eq!(url.proto, Protocol::Udp);
assert_eq!(url.host.to_string(), "8.8.8.8");
assert_eq!(url.port(), 53);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "udp://8.8.8.8");
assert!(url.ip().is_some());
}
#[test]
fn test_parse_udp_2() {
let url = DnsUrl::from_str("udp://1.1.1.1:8053").unwrap();
assert_eq!(url.proto, Protocol::Udp);
assert_eq!(url.host.to_string(), "1.1.1.1");
assert_eq!(url.port(), 8053);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "udp://1.1.1.1:8053");
assert!(url.ip().is_some());
}
#[test]
fn test_parse_udp_ipv6() {
for ip in CLOUDFLARE_IPS.iter().map(DnsUrl::from) {
assert!(ip.proto.is_datagram());
}
}
#[test]
fn test_parse_tcp() {
let url = DnsUrl::from_str("tcp://8.8.8.8").unwrap();
assert_eq!(url.proto, Protocol::Tcp);
assert_eq!(url.host.to_string(), "8.8.8.8");
assert_eq!(url.port(), 53);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "tcp://8.8.8.8");
}
#[test]
fn test_parse_tcp_1() {
let url = DnsUrl::from_str("tcp://8.8.8.8:8053").unwrap();
assert_eq!(url.proto, Protocol::Tcp);
assert_eq!(url.host.to_string(), "8.8.8.8");
assert_eq!(url.port(), 8053);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "tcp://8.8.8.8:8053");
}
#[test]
#[cfg(feature = "dns-over-tls")]
fn test_parse_tls_1() {
let url = DnsUrl::from_str("tls://8.8.8.8").unwrap();
assert_eq!(url.proto, Protocol::Tls);
assert_eq!(url.host.to_string(), "8.8.8.8");
assert_eq!(url.port(), 853);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "tls://8.8.8.8");
}
#[test]
#[cfg(feature = "dns-over-tls")]
fn test_parse_tls_2() {
let url = DnsUrl::from_str("tls://8.8.8.8:953").unwrap();
assert_eq!(url.proto, Protocol::Tls);
assert_eq!(url.host.to_string(), "8.8.8.8");
assert_eq!(url.port(), 953);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "tls://8.8.8.8:953");
}
#[test]
#[cfg(feature = "dns-over-tls")]
fn test_parse_tls_3() {
let mut url = DnsUrl::from_str("tls://8.8.8.8:953").unwrap();
url.set_host("dns.google");
assert_eq!(url.proto, Protocol::Tls);
assert_eq!(url.host.to_string(), "dns.google");
assert_eq!(url.port(), 953);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "tls://dns.google:953");
assert_eq!(url.ip(), "8.8.8.8".parse().ok())
}
#[test]
#[cfg(feature = "dns-over-https")]
fn test_parse_https() {
let url = DnsUrl::from_str("https://dns.google/dns-query").unwrap();
assert_eq!(url.proto, Protocol::Https);
assert_eq!(url.host.to_string(), "dns.google");
assert_eq!(url.port(), 443);
assert_eq!(url.path(), "/dns-query");
assert_eq!(url.to_string(), "https://dns.google/dns-query");
assert!(url.ip().is_none());
}
#[test]
#[cfg(feature = "dns-over-https")]
fn test_parse_https_1() {
let url = DnsUrl::from_str("https://dns.google/dns-query1").unwrap();
assert_eq!(url.proto, Protocol::Https);
assert_eq!(url.host.to_string(), "dns.google");
assert_eq!(url.port(), 443);
assert_eq!(url.path(), "/dns-query1");
assert_eq!(url.to_string(), "https://dns.google/dns-query1");
assert!(url.ip().is_none());
}
#[test]
#[cfg(feature = "dns-over-https")]
fn test_parse_https_2() {
let url = DnsUrl::from_str("https://dns.google").unwrap();
assert_eq!(url.proto, Protocol::Https);
assert_eq!(url.host.to_string(), "dns.google");
assert_eq!(url.port(), 443);
assert_eq!(url.path(), "/dns-query");
assert_eq!(url.to_string(), "https://dns.google/dns-query");
assert!(url.ip().is_none());
}
#[test]
#[cfg(feature = "dns-over-quic")]
fn test_parse_quic() {
let url = DnsUrl::from_str("quic://dns.adguard-dns.com").unwrap();
assert_eq!(url.proto, Protocol::Quic);
assert_eq!(url.host.to_string(), "dns.adguard-dns.com");
assert_eq!(url.port(), 853);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "quic://dns.adguard-dns.com");
assert!(url.ip().is_none());
}
#[test]
#[cfg(feature = "dns-over-h3")]
fn test_parse_h3() {
let url = DnsUrl::from_str("h3://dns.adguard-dns.com").unwrap();
assert_eq!(url.proto, Protocol::H3);
assert_eq!(url.host.to_string(), "dns.adguard-dns.com");
assert_eq!(url.port(), 443);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "h3://dns.adguard-dns.com");
assert!(url.ip().is_none());
}
#[test]
#[cfg(feature = "dns-over-https")]
fn test_url_params_equal() {
let url1 = DnsUrl::from_str("https://dns.adguard-dns.com?a=1&b=2&c=3").unwrap();
let url2 = DnsUrl::from_str("https://dns.adguard-dns.com?b=2&a=1&c=3").unwrap();
assert_eq!(url1, url2);
}
#[test]
fn test_parse_misc_01() {
let url = DnsUrl::from_str("127.0.0.1:1053").unwrap();
assert_eq!(url.proto, Protocol::Udp);
assert_eq!(url.host.to_string(), "127.0.0.1");
assert_eq!(url.port(), 1053);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "udp://127.0.0.1:1053");
assert!(url.ip().is_some());
}
#[test]
fn test_parse_misc_02() {
let url = DnsUrl::from_str("[240e:1f:1::1]").unwrap();
assert_eq!(url.proto, Protocol::Udp);
assert_eq!(url.host.to_string(), "[240e:1f:1::1]");
assert_eq!(url.port(), 53);
assert_eq!(url.path(), "");
assert_eq!(url.to_string(), "udp://[240e:1f:1::1]");
assert!(url.ip().is_some());
}
#[test]
fn test_parse_enable_sni_false() {
let url = DnsUrl::from_str("udp://cloudflare-dns.com?enable_sni=false").unwrap();
assert!(url.sni_off());
assert!(url.ip().is_none());
}
#[test]
fn test_parse_enable_sni_true() {
let url = DnsUrl::from_str("udp://cloudflare-dns.com?enable_sni=false").unwrap();
assert!(url.sni_off());
assert!(url.ip().is_none());
}
#[test]
fn test_parse_params_ip() {
let url = DnsUrl::from_str("udp://cloudflare-dns.com?ip=1.1.1.1").unwrap();
assert_eq!(url.ip(), Some("1.1.1.1".parse().unwrap()));
}
}