forked from joeguo/tldextract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtldextract.go
More file actions
373 lines (331 loc) · 8.81 KB
/
tldextract.go
File metadata and controls
373 lines (331 loc) · 8.81 KB
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
package tldextract
import (
"bytes"
"fmt"
"io"
"net"
"net/http"
"os"
"regexp"
"strings"
)
// used for Result.Flag
const (
Malformed = iota
Domain
Ip4
Ip6
ETld
)
type Result struct {
Flag int
Sub string
Root string
Tld string
}
type TLDExtract struct {
CacheFile string
rootNode *Trie
debug bool
noValidate bool // do not validate URL schema
noStrip bool // do not strip .html suffix from URL
}
type Trie struct {
ExceptRule bool
ValidTld bool
matches map[string]*Trie
}
var (
schemaregex = regexp.MustCompile(`^([abcdefghijklmnopqrstuvwxyz0123456789\+\-\.]+:)?//`)
domainregex = regexp.MustCompile(`^[a-z0-9-]{1,63}$`)
ip4regex = regexp.MustCompile(`(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])`)
)
// New creates a new *TLDExtract, it may be shared between goroutines, we usually need a single instance in an application.
func New(cacheFile string, debug bool) (*TLDExtract, error) {
data, err := os.ReadFile(cacheFile)
if err != nil {
data, err = download()
if err != nil {
return &TLDExtract{}, err
}
if err = os.WriteFile(cacheFile, data, 0644); err != nil {
return &TLDExtract{}, err
}
}
ts := strings.Split(string(data), "\n")
newMap := make(map[string]*Trie)
rootNode := &Trie{ExceptRule: false, ValidTld: false, matches: newMap}
for _, t := range ts {
if t != "" && !strings.HasPrefix(t, "//") {
t = strings.TrimSpace(t)
exceptionRule := t[0] == '!'
if exceptionRule {
t = t[1:]
}
addTldRule(rootNode, strings.Split(t, "."), exceptionRule)
}
}
return &TLDExtract{CacheFile: cacheFile, rootNode: rootNode, debug: debug}, nil
}
// NewFromStaticList create a new *TLDExtract, it may be shared between goroutines,we usually need a single instance in an application.
func NewFromStaticList(list string, debug bool) (*TLDExtract, error) {
ts := strings.Split(list, "\n")
newMap := make(map[string]*Trie)
rootNode := &Trie{ExceptRule: false, ValidTld: false, matches: newMap}
for _, t := range ts {
if t != "" && !strings.HasPrefix(t, "//") {
t = strings.TrimSpace(t)
exceptionRule := t[0] == '!'
if exceptionRule {
t = t[1:]
}
addTldRule(rootNode, strings.Split(t, "."), exceptionRule)
}
}
return &TLDExtract{rootNode: rootNode, debug: debug}, nil
}
// SetNoValidate disables schema check in order to increase performance.
func (extract *TLDExtract) SetNoValidate() {
extract.noValidate = true
}
// SetNoStrip disables URL stripping in order to increase performance.
func (extract *TLDExtract) SetNoStrip() {
extract.noStrip = true
}
func addTldRule(rootNode *Trie, labels []string, ex bool) {
numlabs := len(labels)
t := rootNode
for i := numlabs - 1; i >= 0; i-- {
lab := labels[i]
m, found := t.matches[lab]
if !found {
except := ex
valid := !ex && i == 0
newMap := make(map[string]*Trie)
t.matches[lab] = &Trie{ExceptRule: except, ValidTld: valid, matches: newMap}
m = t.matches[lab]
}
t = m
}
}
func (extract *TLDExtract) Extract(u string) *Result {
input := u
u = strings.ToLower(u)
if !extract.noValidate {
u = schemaregex.ReplaceAllString(u, "")
i := strings.Index(u, "@")
if i != -1 {
u = u[i+1:]
}
index := strings.IndexFunc(u, func(r rune) bool {
switch r {
case '&', ':', '#':
return true
}
return false
})
if index != -1 {
u = u[0:index]
}
}
if !extract.noStrip {
u = strings.TrimSuffix(u, ".html")
}
if extract.debug {
fmt.Printf("%s;%s\n", u, input)
}
return extract.extract(u)
}
func (extract *TLDExtract) extract(url string) *Result {
domain, tld := extract.extractTld(url)
if tld == "" {
ip := net.ParseIP(url)
if ip != nil {
if ip4regex.MatchString(url) {
return &Result{Flag: Ip4, Root: url}
}
// NOTE: IPv6 Identification does not seem to work
return &Result{Flag: Ip6, Root: url}
}
return &Result{Flag: Malformed}
}
sub, root := subdomain(domain)
if domainregex.MatchString(root) {
return &Result{Flag: Domain, Root: root, Sub: sub, Tld: tld}
}
return &Result{Flag: Malformed}
}
func (extract *TLDExtract) extractTld(url string) (domain, tld string) {
spl := strings.Split(url, ".")
tldIndex, validTld := extract.getTldIndex(spl)
if validTld {
domain = strings.Join(spl[:tldIndex], ".")
tld = strings.Join(spl[tldIndex:], ".")
} else {
domain = url
}
return
}
func (extract *TLDExtract) getTldIndex(labels []string) (int, bool) {
t := extract.rootNode
parentValid := false
for i := len(labels) - 1; i >= 0; i-- {
lab := labels[i]
n, found := t.matches[lab]
_, starfound := t.matches["*"]
switch {
case found && !n.ExceptRule:
parentValid = n.ValidTld
t = n
// Found an exception rule
case found:
fallthrough
case parentValid:
return i + 1, true
case starfound:
parentValid = true
default:
return -1, false
}
}
return -1, false
}
// return sub domain,root domain
func subdomain(d string) (string, string) {
ps := strings.Split(d, ".")
l := len(ps)
if l == 1 {
return "", d
}
return strings.Join(ps[0:l-1], "."), ps[l-1]
}
func download() ([]byte, error) {
// NOTE Upstream uses:
//u := "https://publicsuffix.org/list/public_suffix_list.dat"
u := "https://static.dnsfilter.com/effective_tld_names.dat"
resp, err := http.Get(u)
if err != nil {
return []byte(""), err
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
lines := strings.Split(string(body), "\n")
var buffer bytes.Buffer
for _, line := range lines {
line = strings.TrimSpace(line)
if line != "" && !strings.HasPrefix(line, "//") {
buffer.WriteString(line)
buffer.WriteString("\n")
}
}
return buffer.Bytes(), nil
}
// Revised functionality and modernization, named V2
// A modernized version of the Extract function that works less wrongly
// Function can apply some validation/cleanup of a URL and
// then attempt to extract the TLD/root/subdomain from it
func (extract *TLDExtract) ExtractV2(u string) *Result {
u = strings.ToLower(u)
if !extract.noValidate {
// remove a protocol from URL if present
u = schemaregex.ReplaceAllString(u, "")
i := strings.Index(u, "@")
if i != -1 {
u = u[i+1:]
}
// remove any trailing slash and path from URL
i = strings.Index(u, "/")
if i != -1 {
u = u[:i]
}
index := strings.IndexFunc(u, func(r rune) bool {
switch r {
case '&', ':', '#':
return true
}
return false
})
if index != -1 {
u = u[0:index]
}
}
// strip off .html extension.. . ok i guess that was a thing
if !extract.noStrip {
u = strings.TrimSuffix(u, ".html")
}
// call the function to perform the extraction of data
return extract.extractV2(u)
}
// function to extract TLD/Root from a URL
func (extract *TLDExtract) extractV2(url string) *Result {
// first try to pull out the eTLD (aka suffix) and subdomains
domain, tld := extract.extractTldV2(url)
// if there is no eTLD parsed out, not a resolvable domain
// maybe it's an IP
if tld == "" {
ip := net.ParseIP(url)
if ip != nil {
if ip4regex.MatchString(url) {
return &Result{Flag: Ip4, Root: url}
}
return &Result{Flag: Ip6, Root: url}
}
// this is the default return for a domain without any valid TLD
return &Result{Flag: Malformed}
}
// if TLD but no domain, means URL is a suffix/eTLD
if domain == "" {
return &Result{Flag: ETld, Root: "", Sub: "", Tld: tld}
}
// parse out the sub-domain and root
sub, root := subdomain(domain)
if domainregex.MatchString(root) {
return &Result{Flag: Domain, Root: root, Sub: sub, Tld: tld}
}
return &Result{Flag: Malformed}
}
// function to extract the eTLD and root + subdomain from URL
func (extract *TLDExtract) extractTldV2(url string) (domain, tld string) {
spl := strings.Split(url, ".")
// determine where the eTLD begins
tldIndex, validTld := extract.getTldIndexV2(spl)
if validTld {
domain = strings.Join(spl[:tldIndex], ".")
tld = strings.Join(spl[tldIndex:], ".")
} else {
domain = url
}
return
}
// function to determine where in the URL the eTLD starts
func (extract *TLDExtract) getTldIndexV2(labels []string) (int, bool) {
t := extract.rootNode
parentValid := false
for i := len(labels) - 1; i >= 0; i-- {
lab := labels[i]
n, found := t.matches[lab]
_, starfound := t.matches["*"]
switch {
case found && !n.ExceptRule:
parentValid = n.ValidTld
t = n
// Found an exception rule : example: !city.kawasaki.jp
case found:
fallthrough
case parentValid:
return i + 1, true
// Found a wildcard suffix : example: *.otap.co
case starfound:
parentValid = true
default:
return -1, false
}
}
// if we get here, full URL is an eTLD/suffix
return 0, true
}
// Function to check whether a passed in URL is in the Public suffix list
func (extract *TLDExtract) IsValidSuffix(url string) bool {
_, tld := extract.extractTldV2(url)
return tld == url
}