-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
289 lines (253 loc) · 5.72 KB
/
main.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
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
package main
import (
"encoding/json"
"errors"
"flag"
"fmt"
"io/ioutil"
"net"
"os"
"strings"
"time"
"github.com/bluele/gcache"
"github.com/miekg/dns"
"github.com/yl2chen/cidranger"
)
var cacheData gcache.Cache
var ranger cidranger.Ranger
var configPath string
var mConfig config
var version = ""
type config struct {
Cache int
LocalPublicIP string
RemotePublicIP string
Listen string
DNSServer string
NetRange string
Forward []struct {
Domain string
Server string
}
}
func checkCache(name string) (*dns.Msg, error) {
if item, err := cacheData.Get(name); err == nil {
return item.(*dns.Msg), nil
}
return nil, errors.New("cache key not found")
}
func addCache(name string, item *dns.Msg) {
if len(item.Answer)==0 {
return
}
ttl := item.Answer[len(item.Answer)-1].Header().Ttl
cacheData.SetWithExpire(name, item, time.Second*time.Duration(ttl))
}
func query(request *dns.Msg, subnet string, server string, tls bool, ecs bool) (*dns.Msg, error) {
if ecs {
o := &dns.OPT{
Hdr: dns.RR_Header{
Name: ".",
Rrtype: dns.TypeOPT,
},
}
e := &dns.EDNS0_SUBNET{
Code: dns.EDNS0SUBNET,
Address: net.ParseIP(subnet),
Family: 1, // IP4
SourceNetmask: net.IPv4len * 8,
}
o.Option = append(o.Option, e)
request.Extra = append(request.Extra, o)
}
client := new(dns.Client)
if tls {
client.Net = "tcp-tls"
} else {
client.Net = "udp"
}
in, _, err := client.Exchange(request, server)
if err != nil {
fmt.Println("ERROR:", err)
return nil, err
}
return in, nil
}
func serve() {
dns.HandleFunc(".", func(w dns.ResponseWriter, r *dns.Msg) {
name := r.Question[0].Name
//check local
isForward := handleForward(name, r, w)
if isForward {
return
}
//check query
if cacheValue, err := checkCache(name); err == nil {
cacheValue.SetReply(r)
w.WriteMsg(cacheValue)
log(name, true, false, false)
return
}
//first query and check if the result is in CIDR range
rstLocal, err := query(r, mConfig.LocalPublicIP, mConfig.DNSServer, true, true)
if err != nil {
return
}
if len(rstLocal.Answer) == 0 {
fmt.Println(name + " no answer!")
w.WriteMsg(rstLocal)
return
}
localIP, ok := rstLocal.Answer[len(rstLocal.Answer)-1].(*dns.A)
if !ok {
fmt.Println(name + " last record is not A")
w.WriteMsg(rstLocal)
return
}
isInRange := checkCIDRRange(localIP.A)
if isInRange {
w.WriteMsg(rstLocal)
addCache(name, rstLocal)
log(name, false, false, true)
return
}
//world query
rstRemote, err := query(r, mConfig.RemotePublicIP, mConfig.DNSServer, true, true)
if err != nil {
return
}
w.WriteMsg(rstRemote)
addCache(name, rstRemote)
log(name, false, false, false)
})
srv := &dns.Server{Addr: mConfig.Listen, Net: "udp"}
err := srv.ListenAndServe()
fmt.Println(err)
}
func log(domain string, hitCache bool, isLocal bool, isChina bool) {
logRst := domain + "|"
if hitCache {
logRst += "cache hit"
fmt.Println(logRst)
return
}
if isLocal {
logRst += "locale domain"
fmt.Println(logRst)
return
}
if isChina {
logRst += "C"
} else {
logRst += "W"
}
fmt.Println(logRst)
}
func handleForward(name string, request *dns.Msg, w dns.ResponseWriter) bool {
isForward := false
serverToQuery := ""
if len(mConfig.Forward) <= 0 {
return false
}
for _, item := range mConfig.Forward {
if name == item.Domain+"." || strings.HasSuffix(name, "."+item.Domain+".") {
isForward = true
serverToQuery = item.Server
break
}
}
if !isForward {
return false
}
fmt.Println(name, "to forward to ", serverToQuery)
rst, err := query(request, "", serverToQuery, false, false)
if err != nil {
fmt.Println(err)
return true
}
w.WriteMsg(rst)
return true
}
func loadNetRange() error {
fileBytes, err := ioutil.ReadFile(mConfig.NetRange)
if err != nil {
return err
}
ipSlice := strings.Split(string(fileBytes), "\n")
ranger = cidranger.NewPCTrieRanger()
for _, item := range ipSlice {
_, network, _ := net.ParseCIDR(item)
ranger.Insert(cidranger.NewBasicRangerEntry(*network))
}
return nil
}
func checkCIDRRange(address net.IP) bool {
contains, err := ranger.Contains(address)
if err != nil {
fmt.Println(err)
return false
}
return contains
}
func readConfig() error {
file, err := os.Open(configPath)
defer file.Close()
if err != nil {
return err
}
decoder := json.NewDecoder(file)
mConfig = config{}
decodeErr := decoder.Decode(&mConfig)
if decodeErr != nil {
return decodeErr
}
if len(mConfig.LocalPublicIP) == 0 {
return errors.New("locale public ip not found in config")
}
if len(mConfig.RemotePublicIP) == 0 {
return errors.New("remote public ip not found in config")
}
if len(mConfig.LocalPublicIP) == 0 {
return errors.New("remote public ip not found in config")
}
if len(mConfig.Listen) == 0 {
return errors.New("listen address not found in config")
}
if len(mConfig.DNSServer) == 0 {
return errors.New("dnsServer address not found in config")
}
if len(mConfig.NetRange) == 0 {
return errors.New("netRange not found in config")
}
return nil
}
func readFlag() error {
flagConfigPath := flag.String("config", "config.json", "path of config file")
flagVersion := flag.Bool("v", false, "get version")
flag.Parse()
configPath = *flagConfigPath
if *flagVersion {
return errors.New("only version")
}
return nil
}
func main() {
flagErr := readFlag()
if flagErr != nil {
fmt.Println("Version:", version)
return
}
configError := readConfig()
if configError != nil {
fmt.Println(configError)
return
}
cacheData = gcache.New(mConfig.Cache).LRU().Build()
fmt.Println("start listening on ", mConfig.Listen)
netRangeErr := loadNetRange()
if netRangeErr != nil {
fmt.Println(netRangeErr)
return
}
serve()
}