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
#![recursion_limit = "1024"]
#[macro_use]
extern crate error_chain;
extern crate psl;
#[macro_use]
extern crate rental;
#[macro_use]
extern crate lazy_static;
extern crate regex;
extern crate idna;
pub mod errors;
use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;
use std::cmp::PartialEq;
use psl::{Psl, List};
use regex::RegexSet;
use errors::ErrorKind;
use idna::{domain_to_unicode, uts46};
pub use errors::{Result, Error};
lazy_static! {
static ref LABEL: RegexSet = {
let exprs = vec![
r"^[[:alnum:]]+$",
r"^[[:alnum:]]+[[:alnum:]-]*[[:alnum:]]+$",
];
RegexSet::new(exprs).unwrap()
};
static ref LOCAL: RegexSet = {
let global = r#"[[:alnum:]!#$%&'*+/=?^_`{|}~-]"#;
let non_ascii = r#"[^\x00-\x7F]"#;
let quoted = r#"["(),\\:;<>@\[\]. ]"#;
let combined = format!(r#"({}*{}*)"#, global, non_ascii);
let exprs = vec![
format!(r#"^{}+$"#, combined),
format!(r#"^({0}+[.]?{0}+)+$"#, combined),
format!(r#"^"({}*{}*)*"$"#, combined, quoted),
];
RegexSet::new(exprs).unwrap()
};
}
rental! {
mod inner {
use psl::Domain as Root;
#[rental(debug)]
pub struct Domain {
full: String,
root: Root<'full>,
}
#[rental(debug)]
pub struct Dns {
full: String,
root: Root<'full>,
}
}
}
#[derive(Debug)]
pub struct DomainName {
inner: inner::Domain,
}
#[derive(Debug)]
pub struct DnsName {
inner: inner::Dns,
}
#[derive(Debug)]
pub enum Host {
Ip(IpAddr),
Domain(DomainName),
}
#[derive(Debug)]
pub struct Email {
name: String,
host: Host,
}
impl FromStr for DomainName {
type Err = Error;
fn from_str(domain: &str) -> Result<Self> {
use inner::Domain;
if !Self::has_valid_syntax(domain) {
return Err(ErrorKind::InvalidDomain(domain.into()).into());
}
let input = to_unicode(domain.trim_right_matches('.'))?;
let inner = Domain::try_new_or_drop(input + ".", |full| {
match List::new().domain(&full) {
Some(root) => { Ok(root) }
None => { Err(Error::from(ErrorKind::InvalidDomain(domain.into()))) }
}
})?;
Ok(DomainName { inner })
}
}
impl FromStr for DnsName {
type Err = Error;
fn from_str(host: &str) -> Result<Self> {
use inner::Dns;
let non_fqdn = if host.ends_with('.') { &host[..host.len()-1] } else { host };
let domain = to_unicode(non_fqdn)?;
let inner = Dns::try_new_or_drop(domain + ".", |full| {
match List::new().domain(&full) {
Some(root) => {
if !DomainName::has_valid_syntax(root.to_str()) {
return Err(Error::from(ErrorKind::InvalidDomain(host.into())));
}
Ok(root)
}
None => { Err(Error::from(ErrorKind::InvalidDomain(host.into()))) }
}
})?;
Ok(DnsName { inner })
}
}
impl DnsName {
pub fn as_str(&self) -> &str {
self.inner.head()
}
pub fn root<'a>(&'a self) -> psl::Domain<'a> {
let rental = unsafe { self.inner.all_erased() };
*rental.root
}
}
impl FromStr for Host {
type Err = Error;
fn from_str(mut host: &str) -> Result<Host> {
if let Ok(domain) = DomainName::from_str(host) {
return Ok(Host::Domain(domain));
}
if host.starts_with("[")
&& !host.starts_with("[[")
&& host.ends_with("]")
&& !host.ends_with("]]")
{
host = host
.trim_left_matches("[")
.trim_right_matches("]");
};
if let Ok(ip) = IpAddr::from_str(host) {
return Ok(Host::Ip(ip));
}
Err(ErrorKind::InvalidHost.into())
}
}
impl Host {
pub fn is_ip(&self) -> bool {
if let &Host::Ip(_) = self {
return true;
}
false
}
pub fn is_domain(&self) -> bool {
if let &Host::Domain(_) = self {
return true;
}
false
}
}
impl fmt::Display for Host {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&Host::Ip(ref ip) => write!(f, "{}", ip),
&Host::Domain(ref domain) => write!(f, "{}", domain),
}
}
}
impl DomainName {
pub fn as_str(&self) -> &str {
self.inner.head()
}
pub fn root<'a>(&'a self) -> psl::Domain<'a> {
let rental = unsafe { self.inner.all_erased() };
*rental.root
}
fn has_valid_syntax(domain: &str) -> bool {
if domain.starts_with('.') { return false; }
let domain = match to_ascii(domain) {
Ok(domain) => { domain }
Err(_) => { return false; }
};
let mut labels: Vec<&str> = domain.split('.').collect();
if domain.ends_with(".") { labels.pop(); }
if labels.len() > 127 { return false; }
labels.reverse();
for (i, label) in labels.iter().enumerate() {
if i == 0 && label.parse::<f64>().is_ok() { return false; }
if !LABEL.is_match(label) { return false; }
}
true
}
}
impl FromStr for Email {
type Err = Error;
fn from_str(address: &str) -> Result<Email> {
let mut parts = address.rsplitn(2, "@");
let host = match parts.next() {
Some(host) => host,
None => { return Err(ErrorKind::InvalidEmail.into()); }
};
let local = match parts.next() {
Some(local) => local,
None => { return Err(ErrorKind::InvalidEmail.into()); }
};
if local.chars().count() > 64
|| address.chars().count() > 254
|| (!local.starts_with('"') && local.contains(".."))
|| !LOCAL.is_match(local)
{
return Err(ErrorKind::InvalidEmail.into());
}
let host = Host::from_str(host)?;
let name = local.to_owned();
Ok(Email { name, host })
}
}
impl Email {
pub fn user(&self) -> &str {
&self.name
}
pub fn host(&self) -> &Host {
&self.host
}
}
fn to_ascii(domain: &str) -> Result<String> {
let result = uts46::to_ascii(domain, uts46::Flags {
use_std3_ascii_rules: false,
transitional_processing: true,
verify_dns_length: true,
});
result.map_err(|error| ErrorKind::Uts46(error).into())
}
fn to_unicode(input: &str) -> Result<String> {
let (domain, res) = domain_to_unicode(input);
if let Err(errors) = res {
return Err(ErrorKind::Uts46(errors).into());
}
Ok(domain)
}
impl fmt::Display for DomainName {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Display for DnsName {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl fmt::Display for Email {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}@{}", self.name, self.host)
}
}
impl PartialEq for DomainName {
fn eq(&self, other: &DomainName) -> bool {
self.as_str() == other.as_str()
}
}
impl PartialEq for DnsName {
fn eq(&self, other: &DnsName) -> bool {
self.as_str() == other.as_str()
}
}
impl PartialEq<str> for Host {
fn eq(&self, other: &str) -> bool {
self.to_string() == other
}
}