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_allocation.go
315 lines (288 loc) · 7.22 KB
/
client_allocation.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
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
package turnc
import (
"context"
"errors"
"fmt"
"net"
"time"
"go.uber.org/zap"
"gortc.io/stun"
"gortc.io/turn"
)
// Allocation reflects TURN Allocation, which is basically an IP:Port on
// TURN server allocated for client.
type Allocation struct {
log *zap.Logger
client *Client
relayed turn.RelayedAddress
reflexive stun.XORMappedAddress
perms []*Permission // protected with client.mux
minBound turn.ChannelNumber
integrity stun.MessageIntegrity
nonce stun.Nonce
refreshRate time.Duration
ctx context.Context
cancel context.CancelFunc
}
func (a *Allocation) removePermission(p *Permission) {
a.client.mux.Lock()
newPerms := make([]*Permission, 0, len(a.perms))
for _, permission := range a.perms {
if p == permission {
continue
}
newPerms = append(newPerms, permission)
}
a.perms = newPerms
a.client.mux.Unlock()
}
var errUnauthorised = errors.New("unauthorized")
// allocate expects client.mux locked.
func (c *Client) allocate(req, res *stun.Message) (*Allocation, error) {
if doErr := c.do(req, res); doErr != nil {
return nil, doErr
}
if res.Type == stun.NewType(stun.MethodAllocate, stun.ClassSuccessResponse) {
var (
relayed turn.RelayedAddress
reflexive stun.XORMappedAddress
nonce stun.Nonce
)
// Getting relayed and reflexive addresses from response.
if err := relayed.GetFrom(res); err != nil {
return nil, err
}
if err := reflexive.GetFrom(res); err != nil && err != stun.ErrAttributeNotFound {
return nil, err
}
// Getting nonce from request.
if err := nonce.GetFrom(req); err != nil && err != stun.ErrAttributeNotFound {
return nil, err
}
a := &Allocation{
client: c,
log: c.log,
reflexive: reflexive,
relayed: relayed,
minBound: turn.MinChannelNumber,
integrity: c.integrity,
nonce: nonce,
refreshRate: c.refreshRate,
}
c.alloc = a
return a, nil
}
// Anonymous allocate failed, trying to authenticate.
if res.Type.Method != stun.MethodAllocate {
return nil, fmt.Errorf("unexpected response type %s", res.Type)
}
var (
code stun.ErrorCodeAttribute
)
if err := code.GetFrom(res); err != nil {
return nil, err
}
if code.Code != stun.CodeUnauthorized {
return nil, fmt.Errorf("unexpected error code %d", code)
}
return nil, errUnauthorised
}
// Allocate creates an allocation for current 5-tuple. Currently there can be
// only one allocation per client, because client wraps one net.Conn.
func (c *Client) Allocate() (*Allocation, error) {
var (
nonce stun.Nonce
res = stun.New()
)
req, reqErr := stun.Build(stun.TransactionID,
turn.AllocateRequest, turn.RequestedTransportUDP,
stun.Fingerprint,
)
if reqErr != nil {
return nil, reqErr
}
a, allocErr := c.allocate(req, res)
if allocErr == nil {
return a, nil
}
if allocErr != errUnauthorised {
return nil, allocErr
}
// Anonymous allocate failed, trying to authenticate.
if err := nonce.GetFrom(res); err != nil {
return nil, err
}
if err := c.realm.GetFrom(res); err != nil {
return nil, err
}
c.realm = append([]byte(nil), c.realm...)
c.integrity = stun.NewLongTermIntegrity(
c.username.String(), c.realm.String(), c.password,
)
// Trying to authorize.
if reqErr = req.Build(stun.TransactionID,
turn.AllocateRequest, turn.RequestedTransportUDP,
&c.username, &c.realm,
&nonce,
&c.integrity, stun.Fingerprint,
); reqErr != nil {
return nil, reqErr
}
a, err := c.allocate(req, res)
if err != nil {
return a, err
}
a.ctx, a.cancel = context.WithCancel(context.Background())
a.startRefreshLoop()
return a, nil
}
func (a *Allocation) Close() error {
a.cancel()
a.client.mux.Lock()
for _, perm := range a.perms {
perm.Close()
}
a.client.mux.Unlock()
return nil
}
func (a *Allocation) allocate(peer turn.PeerAddress) error {
req := stun.New()
req.TransactionID = stun.NewTransactionID()
req.Type = stun.NewType(stun.MethodCreatePermission, stun.ClassRequest)
req.WriteHeader()
setters := make([]stun.Setter, 0, 10)
setters = append(setters, &peer)
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
}
}
res := stun.New()
if doErr := a.client.do(req, res); doErr != nil {
return doErr
}
if res.Type.Class == stun.ClassErrorResponse {
var code stun.ErrorCodeAttribute
err := fmt.Errorf("unexpected error response: %s", res.Type)
if getErr := code.GetFrom(res); getErr == nil {
err = fmt.Errorf("unexpected error response: %s (error %s)",
res.Type, code,
)
}
return err
}
return nil
}
// Relayed returns the relayed address for the allocation.
func (a *Allocation) Relayed() turn.RelayedAddress {
return a.relayed
}
// CreateUDP creates new UDP Permission to peer with provided addr.
func (a *Allocation) Create(ip net.IP) (*Permission, error) {
peer := turn.PeerAddress{
IP: ip,
Port: 0, // Does not matter.
}
if err := a.allocate(peer); err != nil {
return nil, err
}
p := &Permission{
log: a.log,
ip: ip,
client: a.client,
refreshRate: a.client.refreshRate,
}
p.ctx, p.cancel = context.WithCancel(context.Background())
p.startRefreshLoop()
a.client.mux.Lock()
a.perms = append(a.perms, p)
a.client.mux.Unlock()
return p, nil
}
func (a *Allocation) startRefreshLoop() {
a.startLoop(func() {
if err := a.refresh(); err != nil {
a.log.Error("failed to refresh allocation", zap.Error(err))
}
a.log.Debug("allocation refreshed")
})
}
func (a *Allocation) refresh() error {
res := stun.New()
req := stun.New()
err := a.doRefresh(res, req)
if err != nil {
return err
}
if res.Type == stun.NewType(stun.MethodRefresh, stun.ClassErrorResponse) {
var errCode stun.ErrorCodeAttribute
if codeErr := errCode.GetFrom(res); codeErr != nil {
return codeErr
}
if errCode.Code == stun.CodeStaleNonce {
var nonce stun.Nonce
if nonceErr := nonce.GetFrom(res); nonceErr != nil {
return nonceErr
}
a.nonce = nonce
res = stun.New()
req = stun.New()
err = a.doRefresh(res, req)
if err != nil {
return err
}
}
}
if res.Type != stun.NewType(stun.MethodRefresh, stun.ClassSuccessResponse) {
return fmt.Errorf("unexpected response type %s", res.Type)
}
// Success.
return nil
}
func (a *Allocation) doRefresh(res, req *stun.Message) error {
req.TransactionID = stun.NewTransactionID()
req.Type = stun.NewType(stun.MethodRefresh, stun.ClassRequest)
req.WriteHeader()
setters := make([]stun.Setter, 0, 10)
if len(a.integrity) > 0 {
// Applying auth.
setters = append(setters,
a.nonce, a.client.username, a.client.realm, a.integrity, turn.Lifetime{
Duration: a.refreshRate,
},
)
}
setters = append(setters, stun.Fingerprint)
for _, s := range setters {
if setErr := s.AddTo(req); setErr != nil {
return setErr
}
}
if doErr := a.client.do(req, res); doErr != nil {
return doErr
}
return nil
}
func (a *Allocation) startLoop(f func()) {
if a.refreshRate == 0 {
return
}
go func() {
ticker := time.NewTicker(a.refreshRate)
for {
select {
case <-ticker.C:
f()
case <-a.ctx.Done():
return
}
}
}()
}