-
Notifications
You must be signed in to change notification settings - Fork 2
/
fileresolver.go
91 lines (77 loc) · 1.82 KB
/
fileresolver.go
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
package main
import (
"bufio"
"errors"
"net"
"os"
"strings"
"github.com/miekg/dns"
)
// FileResolver File based host resolver
type FileResolver struct {
files []string
hosts map[string][]string
Host
}
// NewFileResolver New FileResolver
func NewFileResolver() *FileResolver {
host := &FileResolver{
files: Conf.Hosts.Resolves,
hosts: make(map[string][]string),
}
host.Refresh()
return host
}
// Get host from cache
func (host *FileResolver) Get(domain string) ([]string, error) {
addrs, ok := host.hosts[domain]
if ok {
Logger.Debugf("[HitHost] Domain %s found in hosts files.", domain)
return addrs, nil
}
return nil, errors.New("not found")
}
// Refresh the cached records
func (host *FileResolver) Refresh() {
for _, file := range host.files {
buf, err := os.OpenFile(file, os.O_RDONLY, 0777)
if err != nil {
Logger.Warningf("Update hosts records from file %s failed by %s.", file, err)
return
}
defer buf.Close()
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
line := scanner.Text()
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "#") || line == "" {
continue
}
sli := strings.Split(line, " ")
if len(sli) == 1 {
sli = strings.Split(line, "\t")
}
if len(sli) < 2 {
continue
}
domain := sli[len(sli)-1]
ipString := sli[0]
if !host.isDomain(domain) {
Logger.Debugf("Cannot parse an invalid domain: `%s` from %s .", domain, file)
continue
}
if !host.isIP(ipString) {
Logger.Debugf("Cannot parse an invalid ip: `%s` from %s .", ipString, file)
continue
}
domain = strings.ToLower(domain)
domain = dns.Fqdn(domain)
ip := net.ParseIP(ipString)
if ip == nil {
continue
}
host.hosts[domain] = append(host.hosts[domain], ipString)
}
Logger.Debugf("Cached hosts records from %s .", file)
}
}