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
#[cfg(feature = "trust-dns-resolver")]
mod trust_dns_resolver;
use async_trait::async_trait;
use std::{
error::Error,
fmt::{self, Display, Formatter},
hash::{Hash, Hasher},
net::{IpAddr, Ipv4Addr, Ipv6Addr},
str::FromStr,
};
pub type LookupResult<T> = Result<T, LookupError>;
#[derive(Debug)]
pub enum LookupError {
Timeout,
NoRecords,
Dns(Option<Box<dyn Error + Send + Sync>>),
}
impl Error for LookupError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Timeout | Self::NoRecords => None,
Self::Dns(e) => e.as_ref().map(|e| e.as_ref() as _),
}
}
}
impl Display for LookupError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::Timeout => write!(f, "lookup timed out"),
Self::NoRecords => write!(f, "no records found"),
Self::Dns(source) => match source {
None => write!(f, "lookup returned error"),
Some(error) => write!(f, "lookup returned error with cause: {}", error),
},
}
}
}
#[async_trait]
pub trait Lookup: Send + Sync {
async fn lookup_a<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<Ipv4Addr>>;
async fn lookup_aaaa<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<Ipv6Addr>>;
async fn lookup_mx<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<Name>>;
async fn lookup_txt<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<String>>;
async fn lookup_ptr<'lookup>(&'lookup self, ip: IpAddr) -> LookupResult<Vec<Name>>;
}
#[async_trait]
impl<T: Lookup + ?Sized> Lookup for Box<T> {
async fn lookup_a<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<Ipv4Addr>> {
(**self).lookup_a(name).await
}
async fn lookup_aaaa<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<Ipv6Addr>> {
(**self).lookup_aaaa(name).await
}
async fn lookup_mx<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<Name>> {
(**self).lookup_mx(name).await
}
async fn lookup_txt<'lookup, 'a>(&'lookup self, name: &'a Name) -> LookupResult<Vec<String>> {
(**self).lookup_txt(name).await
}
async fn lookup_ptr<'lookup>(&'lookup self, ip: IpAddr) -> LookupResult<Vec<Name>> {
(**self).lookup_ptr(ip).await
}
}
#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
pub struct ParseNameError;
impl Error for ParseNameError {}
impl Display for ParseNameError {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "could not parse domain name")
}
}
#[derive(Clone, Debug)]
pub struct Name(String);
impl Name {
pub fn new(s: &str) -> Result<Self, ParseNameError> {
if is_valid_dns_name(s, false) {
Ok(Self::root(s.to_owned()))
} else {
Err(ParseNameError)
}
}
pub(crate) fn domain(s: &str) -> Result<Self, ParseNameError> {
let s = idna::domain_to_ascii(s).map_err(|_| ParseNameError)?;
if is_valid_dns_name(&s, true) {
Ok(Self::root(s))
} else {
Err(ParseNameError)
}
}
fn root(mut s: String) -> Self {
if !s.ends_with('.') {
s.push('.');
}
Name(s)
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_subdomain_of(&self, other: &Name) -> bool {
let name = self.as_str();
let other = other.as_str();
name.len() > other.len() && {
let len = name.len() - other.len();
matches!(name.get(len..), Some(s) if s.eq_ignore_ascii_case(other))
&& matches!(name.get(..len), Some(s) if s.ends_with('.'))
}
}
}
impl PartialEq for Name {
fn eq(&self, other: &Self) -> bool {
self.0.eq_ignore_ascii_case(&other.0)
}
}
impl Eq for Name {}
impl Hash for Name {
fn hash<H: Hasher>(&self, state: &mut H) {
self.0.to_ascii_lowercase().hash(state);
}
}
impl Display for Name {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
self.0[..(self.0.len() - 1)].fmt(f)
}
}
impl AsRef<str> for Name {
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl FromStr for Name {
type Err = ParseNameError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::new(s)
}
}
fn is_valid_dns_name(mut s: &str, domain: bool) -> bool {
if let Some(sx) = s.strip_suffix('.') {
s = sx;
}
if !has_valid_domain_len(s) {
return false;
}
let mut labels = s.split('.').rev().peekable();
if domain {
if matches!(labels.next(), Some(l) if !is_tld(l)) {
return false;
}
if labels.peek().is_none() {
return false;
}
labels.all(is_label)
} else {
labels.all(|l| has_valid_label_len(l) && !l.starts_with('-') && !l.ends_with('-'))
}
}
fn is_tld(s: &str) -> bool {
is_label(s) && !s.chars().all(|c: char| c.is_ascii_digit())
}
fn is_label(s: &str) -> bool {
has_valid_label_len(s)
&& s.starts_with(|c: char| c.is_ascii_alphanumeric())
&& s.ends_with(|c: char| c.is_ascii_alphanumeric())
&& s.chars().all(|c: char| c.is_ascii_alphanumeric() || c == '-')
}
pub(crate) const MAX_DOMAIN_LENGTH: usize = 253;
fn has_valid_domain_len(s: &str) -> bool {
matches!(s.len(), 1..=MAX_DOMAIN_LENGTH)
}
fn has_valid_label_len(s: &str) -> bool {
matches!(s.len(), 1..=63)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn name_new_ok() {
assert_eq!(Name::new("ch"), Ok(Name("ch.".into())));
assert_eq!(Name::new(""), Err(ParseNameError));
assert_eq!(Name::new("mail.gluet.ch"), Ok(Name("mail.gluet.ch.".into())));
assert_eq!(Name::new("_dmarc.gluet.ch"), Ok(Name("_dmarc.gluet.ch.".into())));
assert_eq!(Name::new("185.46.57.247"), Ok(Name("185.46.57.247.".into())));
assert_eq!(Name::new("_--,"), Ok(Name("_--,.".into())));
assert_eq!(Name::new("ch."), Ok(Name("ch.".into())));
assert_eq!(Name::new("mail.gluet.ch."), Ok(Name("mail.gluet.ch.".into())));
assert_eq!(Name::new("_dmarc.gluet.ch."), Ok(Name("_dmarc.gluet.ch.".into())));
assert_eq!(Name::new("185.46.57.247."), Ok(Name("185.46.57.247.".into())));
assert_eq!(Name::new(".mail.gluet.ch"), Err(ParseNameError));
assert_eq!(Name::new("mail.g...t.ch"), Err(ParseNameError));
assert_eq!(Name::new("mail.g t.ch"), Ok(Name("mail.g t.ch.".into())));
assert_eq!(Name::new("www.Bücher.de"), Ok(Name("www.Bücher.de.".into())));
assert_eq!(Name::new("www.xn--bcher-kva.de"), Ok(Name("www.xn--bcher-kva.de.".into())));
}
#[test]
fn name_domain_ok() {
assert_eq!(Name::domain("ch"), Err(ParseNameError));
assert_eq!(Name::domain("odd-tld-lookalike"), Err(ParseNameError));
assert_eq!(Name::domain(""), Err(ParseNameError));
assert_eq!(Name::domain("mail.gluet.ch"), Ok(Name("mail.gluet.ch.".into())));
assert_eq!(Name::domain("_dmarc.gluet.ch"), Err(ParseNameError));
assert_eq!(Name::domain("185.46.57.247"), Err(ParseNameError));
assert_eq!(Name::domain("mail.gluet.ch."), Ok(Name("mail.gluet.ch.".into())));
assert_eq!(Name::domain("_dmarc.gluet.ch."), Err(ParseNameError));
assert_eq!(Name::domain("185.46.57.247."), Err(ParseNameError));
assert_eq!(Name::domain(".mail.gluet.ch"), Err(ParseNameError));
assert_eq!(Name::domain("mail.gluet.ch.."), Err(ParseNameError));
assert_eq!(Name::domain("myhost.local"), Ok(Name("myhost.local.".into())));
assert_eq!(Name::domain("www.Bücher.de"), Ok(Name("www.xn--bcher-kva.de.".into())));
assert_eq!(Name::domain("www.xn--bcher-kva.de"), Ok(Name("www.xn--bcher-kva.de.".into())));
}
#[test]
fn name_normalises_case() {
assert_eq!(
Name::domain("www.example.org").unwrap(),
Name::domain("wWw.ExAmPlE.OrG").unwrap()
);
}
#[test]
fn is_subdomain_of_ok() {
let parent = Name::new("example.org").unwrap();
assert!(Name::new("mail.example.org").unwrap().is_subdomain_of(&parent));
assert!(!Name::new("example.org").unwrap().is_subdomain_of(&parent));
assert!(!Name::new("myexample.org").unwrap().is_subdomain_of(&parent));
assert!(!Name::new("example.com").unwrap().is_subdomain_of(&parent));
assert!(!Name::new("org").unwrap().is_subdomain_of(&parent));
}
}