-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
252 lines (216 loc) · 6.16 KB
/
server.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
// +build !confonly
package dns
//go:generate errorgen
import (
"context"
"sync"
"time"
"v2ray.com/core"
"v2ray.com/core/common"
"v2ray.com/core/common/net"
"v2ray.com/core/common/session"
"v2ray.com/core/common/strmatcher"
"v2ray.com/core/common/uuid"
"v2ray.com/core/features"
"v2ray.com/core/features/dns"
"v2ray.com/core/features/routing"
)
// Server is a DNS rely server.
type Server struct {
sync.Mutex
hosts *StaticHosts
clients []Client
clientIP net.IP
domainMatcher strmatcher.IndexMatcher
domainIndexMap map[uint32]uint32
tag string
}
func generateRandomTag() string {
id := uuid.New()
return "v2ray.system." + id.String()
}
// New creates a new DNS server with given configuration.
func New(ctx context.Context, config *Config) (*Server, error) {
server := &Server{
clients: make([]Client, 0, len(config.NameServers)+len(config.NameServer)),
tag: config.Tag,
}
if len(server.tag) == 0 {
server.tag = generateRandomTag()
}
if len(config.ClientIp) > 0 {
if len(config.ClientIp) != 4 && len(config.ClientIp) != 16 {
return nil, newError("unexpected IP length", len(config.ClientIp))
}
server.clientIP = net.IP(config.ClientIp)
}
hosts, err := NewStaticHosts(config.StaticHosts, config.Hosts)
if err != nil {
return nil, newError("failed to create hosts").Base(err)
}
server.hosts = hosts
addNameServer := func(endpoint *net.Endpoint) int {
address := endpoint.Address.AsAddress()
if address.Family().IsDomain() && address.Domain() == "localhost" {
server.clients = append(server.clients, NewLocalNameServer())
} else {
dest := endpoint.AsDestination()
if dest.Network == net.Network_Unknown {
dest.Network = net.Network_UDP
}
if dest.Network == net.Network_UDP {
idx := len(server.clients)
server.clients = append(server.clients, nil)
common.Must(core.RequireFeatures(ctx, func(d routing.Dispatcher) {
server.clients[idx] = NewClassicNameServer(dest, d, server.clientIP)
}))
}
}
return len(server.clients) - 1
}
if len(config.NameServers) > 0 {
features.PrintDeprecatedFeatureWarning("simple DNS server")
}
for _, destPB := range config.NameServers {
addNameServer(destPB)
}
if len(config.NameServer) > 0 {
domainMatcher := &strmatcher.MatcherGroup{}
domainIndexMap := make(map[uint32]uint32)
for _, ns := range config.NameServer {
idx := addNameServer(ns.Address)
for _, domain := range ns.PrioritizedDomain {
matcher, err := toStrMatcher(domain.Type, domain.Domain)
if err != nil {
return nil, newError("failed to create prioritized domain").Base(err).AtWarning()
}
midx := domainMatcher.Add(matcher)
domainIndexMap[midx] = uint32(idx)
}
}
server.domainMatcher = domainMatcher
server.domainIndexMap = domainIndexMap
}
if len(server.clients) == 0 {
server.clients = append(server.clients, NewLocalNameServer())
}
return server, nil
}
// Type implements common.HasType.
func (*Server) Type() interface{} {
return dns.ClientType()
}
// Start implements common.Runnable.
func (s *Server) Start() error {
return nil
}
// Close implements common.Closable.
func (s *Server) Close() error {
return nil
}
func (s *Server) IsOwnLink(ctx context.Context) bool {
inbound := session.InboundFromContext(ctx)
return inbound != nil && inbound.Tag == s.tag
}
func (s *Server) queryIPTimeout(client Client, domain string, option IPOption) ([]net.IP, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*4)
if len(s.tag) > 0 {
ctx = session.ContextWithInbound(ctx, &session.Inbound{
Tag: s.tag,
})
}
ips, err := client.QueryIP(ctx, domain, option)
cancel()
return ips, err
}
// LookupIP implements dns.Client.
func (s *Server) LookupIP(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, IPOption{
IPv4Enable: true,
IPv6Enable: true,
})
}
// LookupIPv4 implements dns.IPv4Lookup.
func (s *Server) LookupIPv4(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, IPOption{
IPv4Enable: true,
IPv6Enable: false,
})
}
// LookupIPv6 implements dns.IPv6Lookup.
func (s *Server) LookupIPv6(domain string) ([]net.IP, error) {
return s.lookupIPInternal(domain, IPOption{
IPv4Enable: false,
IPv6Enable: true,
})
}
func (s *Server) lookupStatic(domain string, option IPOption, depth int32) []net.Address {
ips := s.hosts.LookupIP(domain, option)
if ips == nil {
return nil
}
if ips[0].Family().IsDomain() && depth < 5 {
if newIPs := s.lookupStatic(ips[0].Domain(), option, depth+1); newIPs != nil {
return newIPs
}
}
return ips
}
func toNetIP(ips []net.Address) []net.IP {
if len(ips) == 0 {
return nil
}
netips := make([]net.IP, 0, len(ips))
for _, ip := range ips {
netips = append(netips, ip.IP())
}
return netips
}
func (s *Server) lookupIPInternal(domain string, option IPOption) ([]net.IP, error) {
if len(domain) == 0 {
return nil, newError("empty domain name")
}
if domain[len(domain)-1] == '.' {
domain = domain[:len(domain)-1]
}
ips := s.lookupStatic(domain, option, 0)
if ips != nil && ips[0].Family().IsIP() {
return toNetIP(ips), nil
}
if ips != nil && ips[0].Family().IsDomain() {
newdomain := ips[0].Domain()
newError("domain replaced: ", domain, " -> ", newdomain).WriteToLog()
domain = newdomain
}
var lastErr error
if s.domainMatcher != nil {
idx := s.domainMatcher.Match(domain)
if idx > 0 {
ns := s.clients[s.domainIndexMap[idx]]
ips, err := s.queryIPTimeout(ns, domain, option)
if len(ips) > 0 {
return ips, nil
}
if err != nil {
newError("failed to lookup ip for domain ", domain, " at server ", ns.Name()).Base(err).WriteToLog()
lastErr = err
}
}
}
for _, client := range s.clients {
ips, err := s.queryIPTimeout(client, domain, option)
if len(ips) > 0 {
return ips, nil
}
if err != nil {
newError("failed to lookup ip for domain ", domain, " at server ", client.Name()).Base(err).WriteToLog()
lastErr = err
}
}
return nil, newError("returning nil for domain ", domain).Base(lastErr)
}
func init() {
common.Must(common.RegisterConfig((*Config)(nil), func(ctx context.Context, config interface{}) (interface{}, error) {
return New(ctx, config.(*Config))
}))
}