-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconnection_handler.go
492 lines (390 loc) · 11.6 KB
/
connection_handler.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
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
// Connection handler
package main
import (
"strings"
"sync"
"time"
"github.com/gorilla/websocket"
)
// Period to send HEARTBEAT messages to the client
const HEARTBEAT_MSG_PERIOD_SECONDS = 30
// Max time with no HEARTBEAT messages to consider the connection dead
const HEARTBEAT_TIMEOUT_MS = 2 * HEARTBEAT_MSG_PERIOD_SECONDS * 1000
// Request types
const REQUEST_TYPE_PUBLISH = 1
const REQUEST_TYPE_PLAY = 2
// Connection_Handler - Stores status data
// of an active connection
type Connection_Handler struct {
id uint64 // Connection ID
ip string // Client IP address
node *WebRTC_CDN_Node // Reference to the node
connection *websocket.Conn // Reference to the websocket connection
lastHeartbeat int64 // Timestamp: Last time a HEARTBEAT message was received
closed bool // True if the connection is closed
sendingMutex *sync.Mutex // Mutex to control sending messages
statusMutex *sync.Mutex // Mutex to control access to the status data
requests map[string]int // List of requests
requestCount uint32 // Request count
sources map[string]*WRTC_Source // References to associated WebRTCs sources
sinks map[string]*WRTC_Sink // References to associated WebRTC sinks
}
// Initialize
func (h *Connection_Handler) init() {
h.closed = false
h.sendingMutex = &sync.Mutex{}
h.statusMutex = &sync.Mutex{}
h.requestCount = 0
h.requests = make(map[string]int)
h.sources = make(map[string]*WRTC_Source)
h.sinks = make(map[string]*WRTC_Sink)
}
// Runs the handler
// Reads messages, parses them and applies them
func (h *Connection_Handler) run() {
defer func() {
if err := recover(); err != nil {
switch x := err.(type) {
case string:
h.log("Error: " + x)
case error:
h.log("Error: " + x.Error())
default:
h.log("Connection Crashed!")
}
}
h.log("Connection closed.")
// Ensure connection is closed
h.connection.Close()
h.closed = true
// Release resources
h.onClose()
// Remove connection
h.node.onConnectionClose(h.id, h.ip)
}()
c := h.connection
h.log("Connection established.")
h.lastHeartbeat = time.Now().UnixMilli()
go h.sendHeartbeatMessages() // Start heartbeat
for {
mt, message, err := c.ReadMessage()
if err != nil {
break // Closed
}
if mt != websocket.TextMessage {
continue
}
msg := parseSignalingMessage(string(message))
h.logDebug("Received msg: " + msg.method)
switch msg.method {
case "HEARTBEAT":
h.receiveHeartbeat()
case "PUBLISH":
h.receivePublishMessage(msg)
case "PLAY":
h.receivePlayMessage(msg)
case "ANSWER":
h.receiveAnswerMessage(msg)
case "CANDIDATE":
h.receiveCandidateMessage(msg)
case "CLOSE":
h.receiveCloseMessage(msg)
default:
h.logDebug("Unknown message: " + msg.method)
}
}
}
// Called when a HEARTBEAT message is received from the client
func (h *Connection_Handler) receiveHeartbeat() {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
h.lastHeartbeat = time.Now().UnixMilli()
}
// Checks if the client is sending HEARTBEAT messages
// If not, closes the connection
func (h *Connection_Handler) checkHeartbeat() {
h.statusMutex.Lock()
now := time.Now().UnixMilli()
mustClose := (now - h.lastHeartbeat) >= HEARTBEAT_TIMEOUT_MS
defer h.statusMutex.Unlock()
if mustClose {
h.connection.Close()
}
}
// Task to send HEARTBEAT periodically
func (h *Connection_Handler) sendHeartbeatMessages() {
for {
time.Sleep(HEARTBEAT_MSG_PERIOD_SECONDS * time.Second)
if h.closed {
return // Closed
}
// Send heartbeat message
msg := SignalingMessage{
method: "HEARTBEAT",
params: nil,
body: "",
}
h.send(msg)
// Check heartbeat
h.checkHeartbeat()
}
}
// Called when a PUBLISH message is received from the client
func (h *Connection_Handler) receivePublishMessage(msg SignalingMessage) {
requestId := msg.params["request-id"]
streamId := msg.params["stream-id"]
streamType := strings.ToUpper(msg.params["stream-type"])
auth := msg.params["auth"]
// Validate params
if len(requestId) == 0 || len(requestId) > 255 {
h.sendErrorMessage("INVALID_REQUEST_ID", "Request ID must be an string from 1 to 255 characters.", requestId)
return
}
if len(streamId) == 0 || len(streamId) > 255 {
h.sendErrorMessage("INVALID_STREAM_ID", "Stream ID must be an string from 1 to 255 characters.", requestId)
return
}
if !checkAuthentication(auth, "stream_publish", streamId) {
h.sendErrorMessage("INVALID_AUTH", "Invalid authentication provided.", requestId)
return
}
hasAudio := true
hasVideo := true
if streamType == "AUDIO" {
hasVideo = false
} else if streamType == "VIDEO" {
hasAudio = false
}
// Create source
source := WRTC_Source{
requestId: requestId,
sid: streamId,
node: h.node,
hasAudio: hasAudio,
hasVideo: hasVideo,
connection: h,
}
source.init()
// Register the source
func() {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
if h.requests[requestId] != 0 {
h.sendErrorMessage("PROTOCOL_ERROR", "You reused the same request ID for 2 different requests.", requestId)
return
}
if h.requestCount > h.node.requestLimit {
h.sendErrorMessage("LIMIT_REQUESTS", "Too many requests on the same socket.", requestId)
return
}
h.requestCount++
h.requests[requestId] = REQUEST_TYPE_PUBLISH
h.sources[requestId] = &source
h.sendOkMessage(requestId)
h.node.registerSource(&source) // Register source
go source.run() // Run source
}()
}
// Called when a PLAY message is received from the client
func (h *Connection_Handler) receivePlayMessage(msg SignalingMessage) {
requestId := msg.params["request-id"]
streamId := msg.params["stream-id"]
auth := msg.params["auth"]
// Validate params
if len(requestId) == 0 || len(requestId) > 255 {
h.sendErrorMessage("INVALID_REQUEST_ID", "Request ID must be an string from 1 to 255 characters.", requestId)
return
}
if len(streamId) == 0 || len(streamId) > 255 {
h.sendErrorMessage("INVALID_STREAM_ID", "Stream ID must be an string from 1 to 255 characters.", requestId)
return
}
if !checkAuthentication(auth, "stream_play", streamId) {
h.sendErrorMessage("INVALID_AUTH", "Invalid authentication provided.", requestId)
return
}
sinkId := h.node.getSinkID()
// Create sink
sink := WRTC_Sink{
sinkId: sinkId,
requestId: requestId,
sid: streamId,
node: h.node,
connection: h,
}
sink.init()
// Register the sink
func() {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
if h.requests[requestId] != 0 {
h.sendErrorMessage("PROTOCOL_ERROR", "You reused the same request ID for 2 different requests.", requestId)
return
}
if h.requestCount > h.node.requestLimit {
h.sendErrorMessage("LIMIT_REQUESTS", "Too many requests on the same socket.", requestId)
return
}
h.requestCount++
h.requests[requestId] = REQUEST_TYPE_PLAY
h.sinks[requestId] = &sink
h.sendOkMessage(requestId)
h.sendStandbyMessage(requestId)
h.node.registerSink(&sink) // Register sink
}()
}
// Called when an ANSWER message is received from the client
func (h *Connection_Handler) receiveAnswerMessage(msg SignalingMessage) {
requestId := msg.params["request-id"]
func() {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
if h.requests[requestId] == 0 {
return // IGNORE
} else if h.requests[requestId] == REQUEST_TYPE_PUBLISH && h.sources[requestId] != nil {
h.sources[requestId].onAnswer(msg.body)
} else if h.requests[requestId] == REQUEST_TYPE_PLAY && h.sinks[requestId] != nil {
h.sinks[requestId].onAnswer(msg.body)
}
}()
}
// Called when a CANDIDATE message is received from the client
func (h *Connection_Handler) receiveCandidateMessage(msg SignalingMessage) {
requestId := msg.params["request-id"]
func() {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
if h.requests[requestId] == 0 {
return // IGNORE
} else if h.requests[requestId] == REQUEST_TYPE_PUBLISH {
h.sources[requestId].onICECandidate(msg.body)
} else if h.requests[requestId] == REQUEST_TYPE_PLAY {
h.sinks[requestId].onICECandidate(msg.body)
}
}()
}
// Called when a CLOSE message is received from the client
func (h *Connection_Handler) receiveCloseMessage(msg SignalingMessage) {
requestId := msg.params["request-id"]
func() {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
if h.requests[requestId] == 0 {
return // IGNORE
} else if h.requests[requestId] == REQUEST_TYPE_PUBLISH {
h.sources[requestId].close(false, true)
delete(h.sources, requestId)
delete(h.requests, requestId)
h.requestCount--
} else if h.requests[requestId] == REQUEST_TYPE_PLAY {
h.sinks[requestId].close()
delete(h.sinks, requestId)
delete(h.requests, requestId)
h.requestCount--
}
}()
}
// Sends a message to the client
func (h *Connection_Handler) send(msg SignalingMessage) {
h.sendingMutex.Lock()
defer h.sendingMutex.Unlock()
h.connection.WriteMessage(websocket.TextMessage, []byte(msg.serialize()))
}
// Sends an ERROR message to the client
func (h *Connection_Handler) sendErrorMessage(code string, errMsg string, requestID string) {
msg := SignalingMessage{
method: "ERROR",
params: make(map[string]string),
body: "",
}
msg.params["Error-Code"] = code
msg.params["Error-Message"] = errMsg
msg.params["Request-ID"] = requestID
h.send(msg)
}
// Sends an OK message to the client
func (h *Connection_Handler) sendOkMessage(requestID string) {
msg := SignalingMessage{
method: "OK",
params: make(map[string]string),
body: "",
}
msg.params["Request-ID"] = requestID
h.send(msg)
}
// Sends a STANDBY message
func (h *Connection_Handler) sendStandbyMessage(requestID string) {
msg := SignalingMessage{
method: "STANDBY",
params: make(map[string]string),
body: "",
}
msg.params["Request-ID"] = requestID
h.send(msg)
}
// Sends an OFFER message to the client
func (h *Connection_Handler) sendOffer(reqId string, sid string, offerJSON string) {
msg := SignalingMessage{
method: "OFFER",
params: make(map[string]string),
body: offerJSON,
}
msg.params["Request-ID"] = reqId
msg.params["Stream-ID"] = sid
h.send(msg)
}
// Sends a CANDIDATE message to the client
func (h *Connection_Handler) sendICECandidate(reqId string, sid string, candidateJSON string) {
msg := SignalingMessage{
method: "CANDIDATE",
params: make(map[string]string),
body: candidateJSON,
}
msg.params["Request-ID"] = reqId
msg.params["Stream-ID"] = sid
h.send(msg)
}
// Removes a source and send a message to the client
func (h *Connection_Handler) sendSourceClose(reqId string, sid string) {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
delete(h.sources, reqId)
delete(h.requests, reqId)
h.requestCount--
msg := SignalingMessage{
method: "CLOSE",
params: make(map[string]string),
body: "",
}
msg.params["Request-ID"] = reqId
msg.params["Stream-ID"] = sid
h.send(msg)
}
// Logs a message for this connection
func (h *Connection_Handler) log(msg string) {
LogRequest(h.id, h.ip, msg)
}
// Logs a debug message for this connection
func (h *Connection_Handler) logDebug(msg string) {
LogDebugSession(h.id, h.ip, msg)
}
// Called when connection is closed to release resources
func (h *Connection_Handler) onClose() {
h.statusMutex.Lock()
defer h.statusMutex.Unlock()
for requestId := range h.requests {
if h.requests[requestId] == 0 {
return // IGNORE
} else if h.requests[requestId] == REQUEST_TYPE_PUBLISH {
h.sources[requestId].close(false, true)
delete(h.sources, requestId)
delete(h.requests, requestId)
h.requestCount--
} else if h.requests[requestId] == REQUEST_TYPE_PLAY {
h.sinks[requestId].close()
delete(h.sinks, requestId)
delete(h.requests, requestId)
h.requestCount--
}
}
}