-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
416 lines (349 loc) · 10.1 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
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
package turn
import (
"crypto/md5" // #nosec
"fmt"
"io"
"math/rand"
"net"
"strconv"
"sync"
"time"
"github.com/gortc/turn"
"github.com/pion/logging"
"github.com/pion/stun"
"github.com/pion/transport/vnet"
"github.com/pion/turn/internal/allocation"
"github.com/pkg/errors"
)
const (
maxStunMessageSize = 1500
)
// AuthHandler is a callback used to handle incoming auth requests, allowing users to customize Pion TURN
// with custom behavior
type AuthHandler func(username string, srcAddr net.Addr) (password string, ok bool)
// ServerConfig is a bag of config parameters for Server.
type ServerConfig struct {
// Realm sets the realm for this server
Realm string
// AuthHandler is the handler called on each incoming auth requests.
AuthHandler AuthHandler
// ChannelBindTimeout sets the lifetime of channel binding. Defaults to 10 minutes.
ChannelBindTimeout time.Duration
// ListeningPort sets the listening port number. Defaults to 3478.
ListeningPort int
// LoggerFactory must be set for logging from this server.
LoggerFactory logging.LoggerFactory
// Net is used by pion developers. Do not use in your application.
Net *vnet.Net
// Software is the STUN SOFTWARE attribute. Useful for debugging purpose.
Software *stun.Software
// Sender is a custom implementation of the request Sender.
Sender Sender
}
type listener struct {
conn net.PacketConn
closeCh chan struct{}
}
// Server is an instance of the Pion TURN server
type Server struct {
lock sync.RWMutex
listeners []*listener
listenIPs []net.IP
relayIPs []net.IP
listenPort int
realm string
authHandler AuthHandler
manager *allocation.Manager
reservationManager *allocation.ReservationManager
channelBindTimeout time.Duration
log logging.LeveledLogger
net *vnet.Net
software *stun.Software
sender Sender
}
// NewServer creates the Pion TURN server
func NewServer(config *ServerConfig) *Server {
log := config.LoggerFactory.NewLogger("turn")
if config.Net == nil {
config.Net = vnet.NewNet(nil) // defaults to native operation
} else {
log.Warn("vnet is enabled")
}
if config.Sender == nil {
config.Sender = defaultBuildAndSend
}
manager := allocation.NewManager(&allocation.ManagerConfig{
LeveledLogger: log,
Net: config.Net,
})
listenPort := config.ListeningPort
if listenPort == 0 {
listenPort = 3478
}
channelBindTimeout := config.ChannelBindTimeout
if channelBindTimeout == 0 {
channelBindTimeout = turn.DefaultLifetime
}
return &Server{
listenPort: listenPort,
realm: config.Realm,
authHandler: config.AuthHandler,
manager: manager,
reservationManager: &allocation.ReservationManager{},
channelBindTimeout: channelBindTimeout,
log: log,
net: config.Net,
software: config.Software,
sender: config.Sender,
}
}
// AddListeningIPAddr adds a listening IP address.
// If not specified, it will automatically assigns the listening IP addresses
// from the system.
// This method must be called before calling Start().
func (s *Server) AddListeningIPAddr(addrStr string) error {
ip := net.ParseIP(addrStr)
if ip.To4() == nil {
return fmt.Errorf("Non-IPv4 address is not supported")
}
if ip.IsLinkLocalUnicast() {
return fmt.Errorf("link-local unicast address is not allowed")
}
s.listenIPs = append(s.listenIPs, ip)
return nil
}
// AddRelayIPAddr adds a listening IP address.
// Note: current implementation can have only one relay IP address.
// If not specified, it will automatically assigns the relay IP addresses
// from the system.
// This method must be called before calling Start().
func (s *Server) AddRelayIPAddr(addrStr string) error {
ip := net.ParseIP(addrStr)
if ip.To4() == nil {
return fmt.Errorf("Non-IPv4 address is not supported")
}
if ip.IsLinkLocalUnicast() {
return fmt.Errorf("link-local unicast address is not allowed")
}
if ip.IsUnspecified() {
return fmt.Errorf("unspecified IP is not allowed")
}
s.relayIPs = append(s.relayIPs, ip)
return nil
}
// caller must hold the mutex
func (s *Server) gatherSystemIPAddrs() ([]net.IP, error) {
s.log.Debug("gathering local IP address...")
var ips []net.IP
ifs, err := s.net.Interfaces()
if err != nil {
return nil, err
}
for _, ifc := range ifs {
if ifc.Flags&net.FlagUp == 0 {
continue // skip if interface is not up
}
if ifc.Flags&net.FlagLoopback != 0 {
continue // skip loopback address
}
addrs, err := ifc.Addrs()
if err != nil {
continue
}
for _, addr := range addrs {
var ip net.IP
switch addr := addr.(type) {
case *net.IPNet:
ip = addr.IP
case *net.IPAddr:
ip = addr.IP
}
if ip == nil {
return nil, fmt.Errorf("invalid IP address: %s", addr.String())
}
if ip.To4() == nil {
continue // skip non-IPv4 address
}
if ip.IsLinkLocalUnicast() {
continue
}
s.log.Debugf("- found local IP: %s", ip.String())
ips = append(ips, ip)
}
}
return ips, nil
}
// Listen starts listening and handling TURN traffic
// caller must hold the mutex
func (s *Server) listen(localIP net.IP) error {
network := "udp4"
listenAddr := fmt.Sprintf("%s:%d", localIP.String(), s.listenPort)
conn, err := s.net.ListenPacket(network, listenAddr)
if err != nil {
return errors.Wrap(err, fmt.Sprintf("Failed to listen on %s", listenAddr))
}
laddr := conn.LocalAddr()
s.log.Infof("Listening on %s:%s", laddr.Network(), laddr.String())
closeCh := make(chan struct{})
s.listeners = append(s.listeners, &listener{
conn: conn,
closeCh: closeCh,
})
go func() {
buf := make([]byte, maxStunMessageSize)
for {
n, addr, err := conn.ReadFrom(buf)
if err != nil {
s.log.Debugf("exit read loop on error: %s", err.Error())
break
}
if err := s.handleUDPPacket(conn, addr, buf[:n]); err != nil {
s.log.Error(err.Error())
}
}
close(closeCh)
}()
return nil
}
// Start starts the server.
func (s *Server) Start() error {
s.lock.Lock()
defer s.lock.Unlock()
var ips []net.IP
if len(s.listenIPs) == 0 {
var err error
ips, err = s.gatherSystemIPAddrs()
if err != nil {
return err
}
if len(ips) == 0 {
return fmt.Errorf("no local IP address found")
}
s.listenIPs = ips
}
// If s.relayIPs is empty, use s.listenIPs
if len(s.relayIPs) == 0 {
s.relayIPs = s.listenIPs
}
for _, localIP := range s.listenIPs {
err := s.listen(localIP)
if err != nil {
return err
}
}
return nil
}
// Close closes the connection.
func (s *Server) Close() error {
s.lock.Lock()
defer s.lock.Unlock()
if err := s.manager.Close(); err != nil {
return err
}
for _, l := range s.listeners {
err := l.conn.Close()
if err != nil {
s.log.Debugf("Close() returned error: %s", err.Error())
}
}
for _, l := range s.listeners {
<-l.closeCh
}
return nil
}
// caller must hold the mutex
func (s *Server) handleUDPPacket(conn net.PacketConn, srcAddr net.Addr, buf []byte) error {
s.lock.Lock()
defer s.lock.Unlock()
s.log.Debugf("received %d bytes of udp from %s on %s",
len(buf),
srcAddr.String(),
conn.LocalAddr().String(),
)
if turn.IsChannelData(buf) {
return s.handleDataPacket(conn, srcAddr, buf)
}
return s.handleTURNPacket(conn, srcAddr, buf)
}
// caller must hold the mutex
func (s *Server) handleDataPacket(conn net.PacketConn, srcAddr net.Addr, buf []byte) error {
c := turn.ChannelData{Raw: buf}
if err := c.Decode(); err != nil {
return errors.Wrap(err, "Failed to create channel data from packet")
}
err := s.handleChannelData(conn, srcAddr, &c)
if err != nil {
err = errors.Errorf("unable to handle ChannelData from %v: %v", srcAddr, err)
}
return err
}
// caller must hold the mutex
func (s *Server) handleTURNPacket(conn net.PacketConn, srcAddr net.Addr, buf []byte) error {
m := &stun.Message{Raw: append([]byte{}, buf...)}
if err := m.Decode(); err != nil {
return errors.Wrap(err, "failed to create stun message from packet")
}
h, err := s.getMessageHandler(m.Type.Class, m.Type.Method)
if err != nil {
return errors.Errorf("unhandled STUN packet %v-%v from %v: %v", m.Type.Method, m.Type.Class, srcAddr, err)
}
err = h(conn, srcAddr, m)
if err != nil {
return errors.Errorf("failed to handle %v-%v from %v: %v", m.Type.Method, m.Type.Class, srcAddr, err)
}
return nil
}
type messageHandler func(conn net.PacketConn, srcAddr net.Addr, m *stun.Message) error
func (s *Server) getMessageHandler(class stun.MessageClass, method stun.Method) (messageHandler, error) {
switch class {
case stun.ClassIndication:
switch method {
case stun.MethodSend:
return s.handleSendIndication, nil
default:
return nil, errors.Errorf("unexpected method: %s", method)
}
case stun.ClassRequest:
switch method {
case stun.MethodAllocate:
return s.handleAllocateRequest, nil
case stun.MethodRefresh:
return s.handleRefreshRequest, nil
case stun.MethodCreatePermission:
return s.handleCreatePermissionRequest, nil
case stun.MethodChannelBind:
return s.handleChannelBindRequest, nil
case stun.MethodBinding:
return s.handleBindingRequest, nil
default:
return nil, errors.Errorf("unexpected method: %s", method)
}
default:
return nil, errors.Errorf("unexpected class: %s", class)
}
}
func randSeq(n int) string {
letters := []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
b := make([]rune, n)
for i := range b {
b[i] = letters[rand.Intn(len(letters))]
}
return string(b)
}
// TODO, include time info support stale nonces
func buildNonce() (string, error) {
/* #nosec */
h := md5.New()
now := time.Now().Unix()
if _, err := io.WriteString(h, strconv.FormatInt(now, 10)); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed generating nonce %v \n", err))
}
if _, err := io.WriteString(h, strconv.FormatInt(rand.Int63(), 10)); err != nil {
return "", errors.Wrap(err, fmt.Sprintf("Failed generating nonce %v \n", err))
}
return fmt.Sprintf("%x", h.Sum(nil)), nil
}
func assertMessageIntegrity(m *stun.Message, ourKey []byte) error {
messageIntegrityAttr := stun.MessageIntegrity(ourKey)
return messageIntegrityAttr.Check(m)
}