-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathudp_conn.go
More file actions
512 lines (434 loc) · 12.8 KB
/
udp_conn.go
File metadata and controls
512 lines (434 loc) · 12.8 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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
// SPDX-FileCopyrightText: 2026 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package client implements the API for a TURN client
package client
import (
"errors"
"fmt"
"io"
"math"
"net"
"time"
"github.com/pion/stun/v3"
"github.com/pion/turn/v5/internal/proto"
)
const (
maxReadQueueSize = 1024
defaultPermRefreshInterval = 120 * time.Second
defaultBindingRefreshInterval = 5 * time.Minute
defaultBindingCheckInterval = 30 * time.Second
maxRetryAttempts = 3
)
const (
timerIDRefreshAlloc int = iota
timerIDRefreshPerms
timerIDCheckBindings
)
type inboundData struct {
data []byte
from net.Addr
}
// UDPConn is the implementation of the Conn and PacketConn interfaces for UDP network connections.
// compatible with net.PacketConn and net.Conn.
type UDPConn struct {
bindingMgr *bindingManager // Thread-safe
checkBindingsTimer *PeriodicTimer // Thread-safe
readCh chan *inboundData // Thread-safe
closeCh chan struct{} // Thread-safe
bindingRefreshInterval time.Duration // Read-only
allocation
}
// NewUDPConn creates a new instance of UDPConn.
func NewUDPConn(config *AllocationConfig) *UDPConn {
conn := &UDPConn{
bindingMgr: newBindingManager(),
readCh: make(chan *inboundData, maxReadQueueSize),
closeCh: make(chan struct{}),
bindingRefreshInterval: defaultBindingRefreshInterval,
allocation: allocation{
client: config.Client,
relayedAddr: config.RelayedAddr,
serverAddr: config.ServerAddr,
readTimer: time.NewTimer(time.Duration(math.MaxInt64)),
permMap: newPermissionMap(),
username: config.Username,
realm: config.Realm,
integrity: config.Integrity,
_nonce: config.Nonce,
_lifetime: config.Lifetime,
net: config.Net,
log: config.Log,
},
}
if config.BindingRefreshInterval != 0 {
conn.bindingRefreshInterval = config.BindingRefreshInterval
}
conn.log.Debugf("Initial lifetime: %d seconds", int(conn.lifetime().Seconds()))
conn.refreshAllocTimer = NewPeriodicTimer(
timerIDRefreshAlloc,
conn.onRefreshTimers,
conn.lifetime()/2,
)
permRefreshInterval := defaultPermRefreshInterval
if config.PermissionRefreshInterval != 0 {
permRefreshInterval = config.PermissionRefreshInterval
}
conn.refreshPermsTimer = NewPeriodicTimer(
timerIDRefreshPerms,
conn.onRefreshTimers,
permRefreshInterval,
)
bindingCheckInterval := defaultBindingCheckInterval
if config.BindingCheckInterval != 0 {
bindingCheckInterval = config.BindingCheckInterval
}
conn.checkBindingsTimer = NewPeriodicTimer(
timerIDCheckBindings,
func(timerID int) {
for _, bound := range conn.bindingMgr.all() {
conn.maybeBind(bound)
}
},
bindingCheckInterval,
)
if conn.refreshAllocTimer.Start() {
conn.log.Debugf("Started refresh allocation timer")
}
if conn.refreshPermsTimer.Start() {
conn.log.Debugf("Started refresh permission timer")
}
if conn.checkBindingsTimer.Start() {
conn.log.Debugf("Started check bindings timer")
}
return conn
}
// ReadFrom reads a packet from the connection,
// copying the payload into p. It returns the number of
// bytes copied into p and the return address that
// was on the packet.
// It returns the number of bytes read (0 <= n <= len(p))
// and any error encountered. Callers should always process
// the n > 0 bytes returned before considering the error err.
// ReadFrom can be made to time out and return
// an Error with Timeout() == true after a fixed time limit;
// see SetDeadline and SetReadDeadline.
func (c *UDPConn) ReadFrom(p []byte) (n int, addr net.Addr, err error) {
for {
select {
case ibData := <-c.readCh:
n := copy(p, ibData.data)
if n < len(ibData.data) {
return 0, nil, io.ErrShortBuffer
}
return n, ibData.from, nil
case <-c.readTimer.C:
return 0, nil, &net.OpError{
Op: "read",
Net: c.LocalAddr().Network(),
Addr: c.LocalAddr(),
Err: newTimeoutError("i/o timeout"),
}
case <-c.closeCh:
return 0, nil, &net.OpError{
Op: "read",
Net: c.LocalAddr().Network(),
Addr: c.LocalAddr(),
Err: errClosed,
}
}
}
}
func (a *allocation) createPermission(perm *permission, addr net.Addr) error {
perm.mutex.Lock()
defer perm.mutex.Unlock()
if perm.state() == permStateIdle {
// Punch a hole! (this would block a bit..)
if err := a.CreatePermissions(addr); err != nil {
a.permMap.delete(addr)
return err
}
perm.setState(permStatePermitted)
}
return nil
}
// WriteTo writes a packet with payload to addr.
// WriteTo can be made to time out and return
// an Error with Timeout() == true after a fixed time limit;
// see SetDeadline and SetWriteDeadline.
// On packet-oriented connections, write timeouts are rare.
func (c *UDPConn) WriteTo(payload []byte, addr net.Addr) (int, error) { //nolint:gocognit,cyclop
var err error
_, ok := addr.(*net.UDPAddr)
if !ok {
return 0, errUDPAddrCast
}
// Check if we have a permission for the destination IP addr
perm, ok := c.permMap.find(addr)
if !ok {
perm = &permission{}
c.permMap.insert(addr, perm)
}
for i := 0; i < maxRetryAttempts; i++ {
// c.createPermission() would block, per destination IP (, or perm),
// until the perm state becomes "requested". Purpose of this is to
// guarantee the order of packets (within the same perm).
// Note that CreatePermission transaction may not be complete before
// all the data transmission. This is done assuming that the request
// will be most likely successful and we can tolerate some loss of
// UDP packet (or reorder), inorder to minimize the latency in most cases.
if err = c.createPermission(perm, addr); !errors.Is(err, errTryAgain) {
break
}
}
if err != nil {
return 0, err
}
// Bind channel
bound, ok := c.bindingMgr.findByAddr(addr)
if !ok {
bound = c.bindingMgr.create(addr)
}
//nolint:nestif
if !bound.ok() {
// Try to establish an initial binding with the server.
// Writes still occur via indications meanwhile.
c.maybeBind(bound)
// Send data using SendIndication
peerAddr := addr2PeerAddress(addr)
var msg *stun.Message
msg, err = stun.Build(
stun.TransactionID,
stun.NewType(stun.MethodSend, stun.ClassIndication),
proto.Data(payload),
peerAddr,
stun.Fingerprint,
)
if err != nil {
return 0, err
}
if _, err = c.client.WriteTo(msg.Raw, c.serverAddr); err != nil {
return 0, err
}
return len(payload), nil
}
// Binding is ready beyond this point, so send over it.
_, err = c.sendChannelData(payload, bound.number)
if err != nil {
return 0, err
}
return len(payload), nil
}
// Close closes the connection.
// Any blocked ReadFrom or WriteTo operations will be unblocked and return errors.
func (c *UDPConn) Close() error {
c.refreshAllocTimer.Stop()
c.refreshPermsTimer.Stop()
c.checkBindingsTimer.Stop()
select {
case <-c.closeCh:
return errAlreadyClosed
default:
close(c.closeCh)
}
c.client.OnDeallocated(c.relayedAddr)
return c.refreshAllocation(0, true /* dontWait=true */)
}
// LocalAddr returns the local network address.
func (c *UDPConn) LocalAddr() net.Addr {
return c.relayedAddr
}
// SetDeadline sets the read and write deadlines associated
// with the connection. It is equivalent to calling both
// SetReadDeadline and SetWriteDeadline.
//
// A deadline is an absolute time after which I/O operations
// fail with a timeout (see type Error) instead of
// blocking. The deadline applies to all future and pending
// I/O, not just the immediately following call to ReadFrom or
// WriteTo. After a deadline has been exceeded, the connection
// can be refreshed by setting a deadline in the future.
//
// An idle timeout can be implemented by repeatedly extending
// the deadline after successful ReadFrom or WriteTo calls.
//
// A zero value for t means I/O operations will not time out.
func (c *UDPConn) SetDeadline(t time.Time) error {
return c.SetReadDeadline(t)
}
// SetReadDeadline sets the deadline for future ReadFrom calls
// and any currently-blocked ReadFrom call.
// A zero value for t means ReadFrom will not time out.
func (c *UDPConn) SetReadDeadline(t time.Time) error {
var d time.Duration
if t.Equal(noDeadline()) {
d = time.Duration(math.MaxInt64)
} else {
d = time.Until(t)
}
c.readTimer.Reset(d)
return nil
}
// SetWriteDeadline sets the deadline for future WriteTo calls
// and any currently-blocked WriteTo call.
// Even if write times out, it may return n > 0, indicating that
// some of the data was successfully written.
// A zero value for t means WriteTo will not time out.
func (c *UDPConn) SetWriteDeadline(time.Time) error {
// Write never blocks.
return nil
}
func addr2PeerAddress(addr net.Addr) proto.PeerAddress {
var peerAddr proto.PeerAddress
switch a := addr.(type) {
case *net.UDPAddr:
peerAddr.IP = a.IP
peerAddr.Port = a.Port
case *net.TCPAddr:
peerAddr.IP = a.IP
peerAddr.Port = a.Port
}
return peerAddr
}
// CreatePermissions Issues a CreatePermission request for the supplied addresses
// as described in https://datatracker.ietf.org/doc/html/rfc5766#section-9
func (a *allocation) CreatePermissions(addrs ...net.Addr) error {
setters := []stun.Setter{
stun.TransactionID,
stun.NewType(stun.MethodCreatePermission, stun.ClassRequest),
}
for _, addr := range addrs {
setters = append(setters, addr2PeerAddress(addr))
}
setters = append(setters,
a.username,
a.realm,
a.nonce(),
a.integrity,
stun.Fingerprint)
msg, err := stun.Build(setters...)
if err != nil {
return err
}
trRes, err := a.client.PerformTransaction(msg, a.serverAddr, false)
if err != nil {
return err
}
res := trRes.Msg
if res.Type.Class == stun.ClassErrorResponse {
var code stun.ErrorCodeAttribute
if err = code.GetFrom(res); err == nil {
if code.Code == stun.CodeStaleNonce {
a.setNonceFromMsg(res)
return errTryAgain
}
turnError := &stun.TurnError{
StunMessageType: res.Type,
ErrorCodeAttr: code,
}
return turnError
}
return fmt.Errorf("%s", res.Type) //nolint // dynamic errors
}
return nil
}
// HandleInbound passes inbound data in UDPConn.
func (c *UDPConn) HandleInbound(data []byte, from net.Addr) {
// Copy data
copied := make([]byte, len(data))
copy(copied, data)
select {
case c.readCh <- &inboundData{data: copied, from: from}:
default:
c.log.Warnf("Receive buffer full")
}
}
// FindAddrByChannelNumber returns a peer address associated with the
// channel number on this UDPConn.
func (c *UDPConn) FindAddrByChannelNumber(chNum uint16) (net.Addr, bool) {
b, ok := c.bindingMgr.findByNumber(chNum)
if !ok {
return nil, false
}
return b.addr, true
}
func (c *UDPConn) maybeBind(bound *binding) {
bind := func() {
var err error
for i := 0; i < maxRetryAttempts; i++ {
if err = c.bind(bound); !errors.Is(err, errTryAgain) {
break
}
}
if err != nil {
c.log.Warnf("Failed to bind channel %d: %s", bound.number, err)
bound.setState(bindingStateFailed)
return
}
bound.setRefreshedAt(time.Now())
bound.setState(bindingStateReady)
}
// Block only callers with the same binding until
// the binding transaction has been complete
bound.muBind.Lock()
defer bound.muBind.Unlock()
state := bound.state()
switch {
case state == bindingStateIdle:
bound.setState(bindingStateRequest)
case state == bindingStateReady && time.Since(bound.refreshedAt()) > c.bindingRefreshInterval:
bound.setState(bindingStateRefresh)
default:
return
}
// Establish binding with the server if eligible
// with regard to cases right above.
go bind()
}
func (c *UDPConn) bind(bound *binding) error {
setters := []stun.Setter{
stun.TransactionID,
stun.NewType(stun.MethodChannelBind, stun.ClassRequest),
addr2PeerAddress(bound.addr),
proto.ChannelNumber(bound.number),
c.username,
c.realm,
c.nonce(),
c.integrity,
stun.Fingerprint,
}
msg, err := stun.Build(setters...)
if err != nil {
return err
}
trRes, err := c.client.PerformTransaction(msg, c.serverAddr, false)
if err != nil {
return err
}
res := trRes.Msg
if res.Type.Class == stun.ClassErrorResponse {
var code stun.ErrorCodeAttribute
if err = code.GetFrom(res); err == nil {
if code.Code == stun.CodeStaleNonce {
c.setNonceFromMsg(res)
return errTryAgain
}
return fmt.Errorf("%w: received error %d", errCannotBindChannel, code.Code) // nolint:err113
}
return fmt.Errorf("%w: unexpected response type %s", errCannotBindChannel, res.Type) // nolint:err113
}
c.log.Debugf("Channel binding successful: %s %d", bound.addr, bound.number)
// Success.
return nil
}
func (c *UDPConn) sendChannelData(data []byte, chNum uint16) (int, error) {
chData := &proto.ChannelData{
Data: data,
Number: proto.ChannelNumber(chNum),
}
chData.Encode()
_, err := c.client.WriteTo(chData.Raw, c.serverAddr)
if err != nil {
return 0, err
}
return len(data), nil
}