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
#![doc(html_root_url = "http://wooya.me/tldextract-rs/tldextract/index.html")]
#![deny(missing_docs)]
extern crate url;
#[macro_use]
extern crate failure;
extern crate futures;
extern crate hyper;
extern crate hyper_tls;
extern crate idna;
extern crate regex;
extern crate serde_json;
extern crate tokio;
#[macro_use]
extern crate log;
mod cache;
#[allow(missing_docs)]
pub mod errors;
use url::{Host, Url};
use idna::punycode;
pub use errors::{Result, TldExtractError};
use std::collections::HashSet;
#[derive(Default)]
pub struct TldOption {
pub cache_path: Option<String>,
pub private_domains: bool,
pub update_local: bool,
pub naive_mode: bool,
}
pub struct TldExtractor {
tld_cache: HashSet<String>,
naive_mode: bool,
}
impl TldExtractor {
pub fn new(option: TldOption) -> TldExtractor {
let cache_path = option.cache_path.as_ref().map(|s| &s[..]);
let tld_cache = cache::get_tld_cache(cache_path.clone(), option.private_domains);
if option.update_local {
let _ = cache::set_tld_cache(cache_path, &tld_cache);
}
TldExtractor {
tld_cache: tld_cache,
naive_mode: option.naive_mode,
}
}
pub fn extract(&self, url: &str) -> Result<TldResult> {
self._extract(url, None)
}
pub fn extract_naive(&self, url: &str) -> Result<TldResult> {
self._extract(url, true)
}
fn _extract<O: Into<Option<bool>>>(&self, url: &str, naive: O) -> Result<TldResult> {
let u = Url::parse(url)?;
let host = u.host().ok_or(TldExtractError::NoHostError(url.into()))?;
match host {
Host::Domain(host) => Ok(self.extract_triple(host, naive.into().unwrap_or(self.naive_mode))),
Host::Ipv4(ip) => Ok(TldResult {
domain: Some(ip.to_string()),
..Default::default()
}),
Host::Ipv6(ip) => Ok(TldResult {
domain: Some(ip.to_string()),
..Default::default()
}),
}
}
fn extract_triple(&self, host: &str, naive_mode: bool) -> TldResult {
let segs: Vec<_> = host
.split('.')
.filter(|&s| s != "")
.map(|seg| {
if seg.starts_with("xn--") {
punycode::decode_to_string(seg.trim_left_matches("xn--")).unwrap_or(seg.into())
} else {
seg.into()
}
})
.collect();
let mut suffix = None;
let mut subdomain = None;
let mut domain = None;
for i in 0..segs.len() {
let piece = segs[i..].join(".");
let exception_piece = "!".to_string() + &piece;
let wildcard_piece = "*.".to_string() + &segs[i + 1..].join(".");
if let Some(_) = self.tld_cache.get(&exception_piece) {
continue;
}
if let Some(_) = self.tld_cache.get(&piece).or(self.tld_cache.get(&wildcard_piece)) {
if i == 0 {
suffix = Some(piece);
} else {
suffix = Some(piece);
domain = Some(segs[i - 1].to_string());
subdomain = if segs[0..i - 1].len() == 0 { None } else { Some(segs[0..i - 1].join(".")) };
}
break;
}
}
if let (None, None, None) = (subdomain.as_ref(), domain.as_ref(), suffix.as_ref()) {
let mut iter = segs.into_iter().rev();
if naive_mode {
suffix = iter.next().map(|s| s.to_string());
}
domain = iter.next().map(|s| s.to_string());
let maybe_subdomain = iter.collect::<Vec<_>>().join(".");
subdomain = if maybe_subdomain == "" { None } else { Some(maybe_subdomain) }
}
TldResult {
suffix: suffix,
subdomain: subdomain,
domain: domain,
}
}
}
#[derive(Debug, Default, PartialEq, Eq)]
pub struct TldResult {
pub domain: Option<String>,
pub subdomain: Option<String>,
pub suffix: Option<String>,
}
impl TldResult {
pub fn new<'a, O, P, Q>(subdomain: O, domain: P, suffix: Q) -> TldResult
where
O: Into<Option<&'a str>>,
P: Into<Option<&'a str>>,
Q: Into<Option<&'a str>>,
{
TldResult {
domain: domain.into().map(|s| s.into()),
subdomain: subdomain.into().map(|s| s.into()),
suffix: suffix.into().map(|s| s.into()),
}
}
}