This repository has been archived by the owner on Jun 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
client_connection.go
187 lines (169 loc) · 4.06 KB
/
client_connection.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
package turnc
import (
"context"
"fmt"
"net"
"sync"
"time"
"go.uber.org/zap"
"gortc.io/stun"
"gortc.io/turn"
)
// Connection represents a UDP connectivity between local transport address
// and remote transport address.
type Connection struct {
log *zap.Logger
mux sync.RWMutex
number turn.ChannelNumber
peerAddr turn.PeerAddress
peerL, peerR net.Conn
client *Client
perm *Permission
ctx context.Context
cancel func()
wg sync.WaitGroup
refreshRate time.Duration
}
// Read data from peer.
func (c *Connection) Read(b []byte) (n int, err error) {
return c.peerR.Read(b)
}
// Bound returns true if channel number is bound for current permission.
func (c *Connection) Bound() bool {
c.mux.RLock()
defer c.mux.RUnlock()
return c.number.Valid()
}
// Binding returns current channel number or 0 if not bound.
func (c *Connection) Binding() turn.ChannelNumber {
c.mux.RLock()
defer c.mux.RUnlock()
return c.number
}
func (c *Connection) startLoop(f func()) {
if c.refreshRate == 0 {
return
}
c.wg.Add(1)
go func() {
ticker := time.NewTicker(c.refreshRate)
defer c.wg.Done()
for {
select {
case <-ticker.C:
f()
case <-c.ctx.Done():
return
}
}
}()
}
// refreshBind performs rebinding of a channel.
func (c *Connection) refreshBind() error {
c.mux.Lock()
defer c.mux.Unlock()
if c.number == 0 {
return ErrNotBound
}
if err := c.bind(c.number); err != nil {
return err
}
c.log.Debug("binding refreshed")
return nil
}
func (c *Connection) bind(n turn.ChannelNumber) error {
// Starting transaction.
a := c.client.alloc
res := stun.New()
req := stun.New()
req.TransactionID = stun.NewTransactionID()
req.Type = stun.NewType(stun.MethodChannelBind, stun.ClassRequest)
req.WriteHeader()
setters := make([]stun.Setter, 0, 10)
setters = append(setters, &c.peerAddr, n)
if len(a.integrity) > 0 {
// Applying auth.
setters = append(setters,
a.nonce, a.client.username, a.client.realm, a.integrity,
)
}
setters = append(setters, stun.Fingerprint)
for _, s := range setters {
if setErr := s.AddTo(req); setErr != nil {
return setErr
}
}
if doErr := c.client.do(req, res); doErr != nil {
return doErr
}
if res.Type != stun.NewType(stun.MethodChannelBind, stun.ClassSuccessResponse) {
return fmt.Errorf("unexpected response type %s", res.Type)
}
// Success.
return nil
}
// Bind performs binding transaction, allocating channel binding for
// the connection.
func (c *Connection) Bind() error {
c.mux.Lock()
defer c.mux.Unlock()
if c.number != 0 {
return ErrAlreadyBound
}
a := c.client.alloc
a.minBound++
n := a.minBound
if err := c.bind(n); err != nil {
return err
}
c.number = n
c.startLoop(func() {
if err := c.refreshBind(); err != nil {
c.log.Error("failed to refresh bind", zap.Error(err))
}
})
return nil
}
// Write sends buffer to peer.
//
// If permission is bound, the ChannelData message will be used.
func (c *Connection) Write(b []byte) (n int, err error) {
if n := c.Binding(); n.Valid() {
c.log.Debug("using channel data to write")
return c.client.sendChan(b, n)
}
c.log.Debug("using STUN to write")
return c.client.sendData(b, &c.peerAddr)
}
// Close stops all refreshing loops for permission and removes it from
// allocation.
func (c *Connection) Close() error {
cErr := c.peerR.Close()
c.mux.Lock()
cancel := c.cancel
c.mux.Unlock()
cancel()
c.wg.Wait()
c.perm.removeConn(c)
return cErr
}
// LocalAddr is relayed address from TURN server.
func (c *Connection) LocalAddr() net.Addr {
return turn.Addr(c.client.alloc.relayed)
}
// RemoteAddr is peer address.
func (c *Connection) RemoteAddr() net.Addr {
return turn.Addr(c.peerAddr)
}
// SetDeadline implements net.Conn.
func (c *Connection) SetDeadline(t time.Time) error {
return c.peerR.SetDeadline(t)
}
// SetReadDeadline implements net.Conn.
func (c *Connection) SetReadDeadline(t time.Time) error {
return c.peerR.SetReadDeadline(t)
}
// SetWriteDeadline implements net.Conn.
func (c *Connection) SetWriteDeadline(t time.Time) error {
return ErrNotImplemented
}