forked from SagerNet/sing-dns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
transport_udp.go
251 lines (231 loc) · 5.54 KB
/
transport_udp.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
package dns
import (
"context"
"net"
"net/netip"
"net/url"
"os"
"sync"
"github.com/sagernet/sing/common"
"github.com/sagernet/sing/common/buf"
E "github.com/sagernet/sing/common/exceptions"
"github.com/sagernet/sing/common/logger"
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"github.com/sagernet/sing/common/task"
"github.com/miekg/dns"
)
var _ Transport = (*UDPTransport)(nil)
func init() {
RegisterTransport([]string{"udp", ""}, func(options TransportOptions) (Transport, error) {
return NewUDPTransport(options)
})
}
type UDPTransport struct {
name string
optCtx context.Context
ctx context.Context
cancel context.CancelFunc
dialer N.Dialer
logger logger.ContextLogger
serverAddr M.Socksaddr
clientAddr netip.Prefix
udpSize int
tcpTransport *TCPTransport
access sync.Mutex
conn *dnsConnection
}
func NewUDPTransport(options TransportOptions) (*UDPTransport, error) {
var serverAddr M.Socksaddr
if serverURL, err := url.Parse(options.Address); err != nil || serverURL.Scheme == "" {
serverAddr = M.ParseSocksaddr(options.Address)
} else {
serverAddr = M.ParseSocksaddr(serverURL.Host)
}
if !serverAddr.IsValid() {
return nil, E.New("invalid server address")
}
if serverAddr.Port == 0 {
serverAddr.Port = 53
}
ctx, cancel := context.WithCancel(options.Context)
return &UDPTransport{
name: options.Name,
optCtx: options.Context,
ctx: ctx,
cancel: cancel,
dialer: options.Dialer,
logger: options.Logger,
serverAddr: serverAddr,
clientAddr: options.ClientSubnet,
udpSize: 512,
tcpTransport: newTCPTransport(options, serverAddr),
}, nil
}
func (t *UDPTransport) Name() string {
return t.name
}
func (t *UDPTransport) Start() error {
return nil
}
func (t *UDPTransport) Reset() {
t.cancel()
t.ctx, t.cancel = context.WithCancel(t.optCtx)
}
func (t *UDPTransport) Close() error {
t.cancel()
return nil
}
func (t *UDPTransport) Raw() bool {
return true
}
func (t *UDPTransport) Lookup(ctx context.Context, domain string, strategy DomainStrategy) ([]netip.Addr, error) {
return nil, os.ErrInvalid
}
func (t *UDPTransport) Exchange(ctx context.Context, message *dns.Msg) (*dns.Msg, error) {
response, err := t.exchange(ctx, message)
if err != nil {
return nil, err
}
if response.Truncated {
t.logger.InfoContext(ctx, "response truncated, retrying with TCP")
return t.tcpTransport.Exchange(ctx, message)
}
return response, nil
}
func (t *UDPTransport) exchange(ctx context.Context, message *dns.Msg) (*dns.Msg, error) {
conn, err := t.open(ctx)
if err != nil {
return nil, err
}
if edns0Opt := message.IsEdns0(); edns0Opt != nil {
if udpSize := int(edns0Opt.UDPSize()); udpSize > t.udpSize {
t.udpSize = udpSize
}
}
buffer := buf.NewSize(1 + message.Len())
defer buffer.Release()
exMessage := *message
exMessage.Compress = true
messageId := message.Id
callback := &dnsCallback{
done: make(chan struct{}),
}
conn.access.Lock()
conn.queryId++
exMessage.Id = conn.queryId
conn.callbacks[exMessage.Id] = callback
conn.access.Unlock()
defer func() {
conn.access.Lock()
delete(conn.callbacks, messageId)
conn.access.Unlock()
callback.access.Lock()
select {
case <-callback.done:
default:
close(callback.done)
}
callback.access.Unlock()
}()
rawMessage, err := exMessage.PackBuffer(buffer.FreeBytes())
if err != nil {
return nil, err
}
_, err = conn.Write(rawMessage)
if err != nil {
conn.Close()
return nil, err
}
select {
case <-callback.done:
callback.message.Id = messageId
return callback.message, nil
case <-conn.ctx.Done():
return nil, E.Errors(conn.err, conn.ctx.Err())
case <-ctx.Done():
conn.Close()
return nil, ctx.Err()
}
}
func (t *UDPTransport) open(ctx context.Context) (*dnsConnection, error) {
connection := t.conn
if connection != nil && !common.Done(connection.ctx) {
return connection, nil
}
t.access.Lock()
defer t.access.Unlock()
connection = t.conn
if connection != nil && !common.Done(connection.ctx) {
return connection, nil
}
conn, err := t.dialer.DialContext(ctx, "udp", t.serverAddr)
if err != nil {
return nil, err
}
connCtx, cancel := context.WithCancel(t.ctx)
connection = &dnsConnection{
Conn: conn,
ctx: connCtx,
cancel: cancel,
callbacks: make(map[uint16]*dnsCallback),
}
t.conn = connection
go t.recvLoop(connection)
return connection, nil
}
func (t *UDPTransport) recvLoop(conn *dnsConnection) {
var group task.Group
group.Append0(func(ctx context.Context) error {
for {
buffer := buf.NewSize(t.udpSize)
_, err := buffer.ReadOnceFrom(conn)
if err != nil {
buffer.Release()
return err
}
var message dns.Msg
err = message.Unpack(buffer.Bytes())
buffer.Release()
if err != nil {
return err
}
conn.access.RLock()
callback, loaded := conn.callbacks[message.Id]
conn.access.RUnlock()
if !loaded {
continue
}
callback.access.Lock()
select {
case <-callback.done:
default:
callback.message = &message
close(callback.done)
}
callback.access.Unlock()
}
})
group.Cleanup(func() {
conn.Close()
})
group.Run(conn.ctx)
}
type dnsConnection struct {
net.Conn
ctx context.Context
cancel context.CancelFunc
access sync.RWMutex
err error
queryId uint16
callbacks map[uint16]*dnsCallback
}
func (c *dnsConnection) Close() error {
c.cancel()
return c.Conn.Close()
}
type dnsCallback struct {
access sync.Mutex
message *dns.Msg
done chan struct{}
}