-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathserver.go
239 lines (195 loc) · 5.88 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
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package turn contains the public API for pion/turn, a toolkit for building TURN clients and servers
package turn
import (
"errors"
"fmt"
"net"
"time"
"github.com/pion/logging"
"github.com/pion/turn/v4/internal/allocation"
"github.com/pion/turn/v4/internal/proto"
"github.com/pion/turn/v4/internal/server"
)
const (
defaultInboundMTU = 1600
)
// Server is an instance of the Pion TURN Server.
type Server struct {
log logging.LeveledLogger
authHandler AuthHandler
realm string
channelBindTimeout time.Duration
nonceHash *server.NonceHash
packetConnConfigs []PacketConnConfig
listenerConfigs []ListenerConfig
allocationManagers []*allocation.Manager
inboundMTU int
}
// NewServer creates the Pion TURN server.
func NewServer(config ServerConfig) (*Server, error) { // nolint:gocognit,cyclop,funlen
if err := config.validate(); err != nil {
return nil, err
}
loggerFactory := config.LoggerFactory
if loggerFactory == nil {
loggerFactory = logging.NewDefaultLoggerFactory()
}
mtu := defaultInboundMTU
if config.InboundMTU != 0 {
mtu = config.InboundMTU
}
nonceHash, err := server.NewNonceHash()
if err != nil {
return nil, err
}
server := &Server{
log: loggerFactory.NewLogger("turn"),
authHandler: config.AuthHandler,
realm: config.Realm,
channelBindTimeout: config.ChannelBindTimeout,
packetConnConfigs: config.PacketConnConfigs,
listenerConfigs: config.ListenerConfigs,
nonceHash: nonceHash,
inboundMTU: mtu,
}
if server.channelBindTimeout == 0 {
server.channelBindTimeout = proto.DefaultLifetime
}
for _, cfg := range server.packetConnConfigs {
am, err := server.createAllocationManager(cfg.RelayAddressGenerator, cfg.PermissionHandler)
if err != nil {
return nil, fmt.Errorf("failed to create AllocationManager: %w", err)
}
go func(cfg PacketConnConfig, am *allocation.Manager) {
server.readLoop(cfg.PacketConn, am)
if err := am.Close(); err != nil {
server.log.Errorf("Failed to close AllocationManager: %s", err)
}
}(cfg, am)
}
for _, cfg := range server.listenerConfigs {
am, err := server.createAllocationManager(cfg.RelayAddressGenerator, cfg.PermissionHandler)
if err != nil {
return nil, fmt.Errorf("failed to create AllocationManager: %w", err)
}
go func(cfg ListenerConfig, am *allocation.Manager) {
server.readListener(cfg.Listener, am)
if err := am.Close(); err != nil {
server.log.Errorf("Failed to close AllocationManager: %s", err)
}
}(cfg, am)
}
return server, nil
}
// AllocationCount returns the number of active allocations.
// It can be used to drain the server before closing.
func (s *Server) AllocationCount() int {
allocs := 0
for _, am := range s.allocationManagers {
allocs += am.AllocationCount()
}
return allocs
}
// Close stops the TURN Server.
// It cleans up any associated state and closes all connections it is managing.
func (s *Server) Close() error {
var errors []error
for _, cfg := range s.packetConnConfigs {
if err := cfg.PacketConn.Close(); err != nil {
errors = append(errors, err)
}
}
for _, cfg := range s.listenerConfigs {
if err := cfg.Listener.Close(); err != nil {
errors = append(errors, err)
}
}
if len(errors) == 0 {
return nil
}
err := errFailedToClose
for _, e := range errors {
err = fmt.Errorf("%s; close error (%w) ", err, e) //nolint:errorlint
}
return err
}
func (s *Server) readListener(l net.Listener, am *allocation.Manager) {
for {
conn, err := l.Accept()
if err != nil {
s.log.Debugf("Failed to accept: %s", err)
return
}
go func() {
s.readLoop(NewSTUNConn(conn), am)
// Delete allocation
am.DeleteAllocation(&allocation.FiveTuple{
Protocol: allocation.UDP, // fixed UDP
SrcAddr: conn.RemoteAddr(),
DstAddr: conn.LocalAddr(),
})
if err := conn.Close(); err != nil && !errors.Is(err, net.ErrClosed) {
s.log.Errorf("Failed to close conn: %s", err)
}
}()
}
}
type nilAddressGenerator struct{}
func (n *nilAddressGenerator) Validate() error { return errRelayAddressGeneratorNil }
func (n *nilAddressGenerator) AllocatePacketConn(string, int) (net.PacketConn, net.Addr, error) {
return nil, nil, errRelayAddressGeneratorNil
}
func (n *nilAddressGenerator) AllocateConn(string, int) (net.Conn, net.Addr, error) {
return nil, nil, errRelayAddressGeneratorNil
}
func (s *Server) createAllocationManager(
addrGenerator RelayAddressGenerator,
handler PermissionHandler,
) (*allocation.Manager, error) {
if handler == nil {
handler = DefaultPermissionHandler
}
if addrGenerator == nil {
addrGenerator = &nilAddressGenerator{}
}
am, err := allocation.NewManager(allocation.ManagerConfig{
AllocatePacketConn: addrGenerator.AllocatePacketConn,
AllocateConn: addrGenerator.AllocateConn,
PermissionHandler: handler,
LeveledLogger: s.log,
})
if err != nil {
return am, err
}
s.allocationManagers = append(s.allocationManagers, am)
return am, err
}
func (s *Server) readLoop(conn net.PacketConn, allocationManager *allocation.Manager) {
buf := make([]byte, s.inboundMTU)
for {
n, addr, err := conn.ReadFrom(buf)
switch {
case err != nil:
s.log.Debugf("Exit read loop on error: %s", err)
return
case n >= s.inboundMTU:
s.log.Debugf("Read bytes exceeded MTU, packet is possibly truncated")
continue
}
if err := server.HandleRequest(server.Request{
Conn: conn,
SrcAddr: addr,
Buff: buf[:n],
Log: s.log,
AuthHandler: s.authHandler,
Realm: s.realm,
AllocationManager: allocationManager,
ChannelBindTimeout: s.channelBindTimeout,
NonceHash: s.nonceHash,
}); err != nil {
s.log.Errorf("Failed to handle datagram: %v", err)
}
}
}