forked from aler9/rtsp-simple-proxy
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server-client.go
653 lines (543 loc) · 15.4 KB
/
server-client.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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
package main
import (
"errors"
"fmt"
"github.com/aler9/gortsplib"
"io"
"log"
"net"
"strings"
"time"
)
func interleavedChannelToTrack(channel uint8) (int, trackFlow) {
if (channel % 2) == 0 {
return int(channel / 2), _TRACK_FLOW_RTP
}
return int((channel - 1) / 2), _TRACK_FLOW_RTCP
}
func trackToInterleavedChannel(id int, flow trackFlow) uint8 {
if flow == _TRACK_FLOW_RTP {
return uint8(id * 2)
}
return uint8((id * 2) + 1)
}
type clientState int
const (
_CLIENT_STATE_STARTING clientState = iota
_CLIENT_STATE_PRE_PLAY
_CLIENT_STATE_PLAY
)
func (cs clientState) String() string {
switch cs {
case _CLIENT_STATE_STARTING:
return "STARTING"
case _CLIENT_STATE_PRE_PLAY:
return "PRE_PLAY"
case _CLIENT_STATE_PLAY:
return "PLAY"
}
return "UNKNOWN"
}
type serverClient struct {
p *program
conn *gortsplib.ConnServer
state clientState
path string
readAuth *gortsplib.AuthServer
streamProtocol streamProtocol
streamTracks []*track
write chan *gortsplib.InterleavedFrame
done chan struct{}
}
func newServerClient(p *program, nconn net.Conn) *serverClient {
c := &serverClient{
p: p,
conn: gortsplib.NewConnServer(gortsplib.ConnServerConf{
NConn: nconn,
ReadTimeout: p.readTimeout,
WriteTimeout: p.writeTimeout,
}),
state: _CLIENT_STATE_STARTING,
path: "",
write: make(chan *gortsplib.InterleavedFrame),
done: make(chan struct{}),
}
c.p.tcpl.mutex.Lock()
c.p.tcpl.clients[c] = struct{}{}
c.p.tcpl.mutex.Unlock()
go c.run()
return c
}
func (c *serverClient) close() error {
// already deleted
if _, ok := c.p.tcpl.clients[c]; !ok {
c.log("client already deleted")
return nil
}
delete(c.p.tcpl.clients, c)
c.conn.NetConn().Close()
close(c.write)
if len(c.p.tcpl.clients) == 0 {
c.log("closing path %s", c.path)
if len(c.p.streams) == 0 {
c.log("no streams")
return nil
}
str, ok := c.p.streams[c.path]
if !ok {
c.log("no stream for path %s", c.path)
return nil
} else {
// delete stream from list
delete (c.p.streams, c.path)
if str == nil {
c.log("stream for path %s not created", c.path)
return nil
}
c.log ("closing stream for path %s", str.path)
if str.state == _STREAM_STATE_READY {
c.log ("closing ready stream")
str.close()
} else {
c.log("stream not ready")
}
}
}
return nil
}
func (c *serverClient) log(format string, args ...interface{}) {
// keep remote address outside format, since it can contain %
log.Println("[RTSP client " + c.conn.NetConn().RemoteAddr().String() + "] " +
fmt.Sprintf(format, args...))
}
func (c *serverClient) ip() net.IP {
return c.conn.NetConn().RemoteAddr().(*net.TCPAddr).IP
}
func (c *serverClient) zone() string {
return c.conn.NetConn().RemoteAddr().(*net.TCPAddr).Zone
}
func (c *serverClient) run() {
c.log("connected")
for {
req, err := c.conn.ReadRequest()
if err != nil {
if err != io.EOF {
c.log("Read ERR: %s", err)
}
break
}
ok := c.handleRequest(req)
if !ok {
break
}
}
func() {
c.log("locking")
c.p.tcpl.mutex.Lock()
defer c.p.tcpl.mutex.Unlock()
c.log("closing")
c.close()
c.log("closed")
}()
c.log("disconnected")
close(c.done)
}
func (c *serverClient) writeResError(req *gortsplib.Request, code gortsplib.StatusCode, err error) {
c.log("WRITE RES ERR: %s", err)
header := gortsplib.Header{}
if cseq, ok := req.Header["CSeq"]; ok && len(cseq) == 1 {
header["CSeq"] = []string{cseq[0]}
}
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: code,
Header: header,
})
}
var errAuthCritical = errors.New("auth critical")
var errAuthNotCritical = errors.New("auth not critical")
func (c *serverClient) validateAuth(req *gortsplib.Request, user string, pass string, auth **gortsplib.AuthServer) error {
if user == "" {
return nil
}
initialRequest := false
if *auth == nil {
initialRequest = true
*auth = gortsplib.NewAuthServer(user, pass, nil)
}
err := (*auth).ValidateHeader(req.Header["Authorization"], req.Method, req.Url)
if err != nil {
if !initialRequest {
c.log("ERR: Unauthorized: %s", err)
}
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusUnauthorized,
Header: gortsplib.Header{
"CSeq": []string{req.Header["CSeq"][0]},
"WWW-Authenticate": (*auth).GenerateHeader(),
},
})
if !initialRequest {
return errAuthCritical
}
return errAuthNotCritical
}
return nil
}
func (c *serverClient) handleRequest(req *gortsplib.Request) bool {
c.log("Method %s, URL %s", string(req.Method), req.Url.String())
cseq, ok := req.Header["CSeq"]
if !ok || len(cseq) != 1 {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("cseq missing"))
return false
}
path := func() string {
ret := req.Url.Path
// remove leading slash
if len(ret) > 0 {
ret = ret[1:]
}
// strip any subpath
if n := strings.Index(ret, "/"); n >= 0 {
ret = ret[:n]
}
return ret
}()
switch req.Method {
case gortsplib.OPTIONS:
// do not check state, since OPTIONS can be requested
// in any state
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusOK,
Header: gortsplib.Header{
"CSeq": []string{cseq[0]},
"Public": []string{strings.Join([]string{
string(gortsplib.DESCRIBE),
string(gortsplib.SETUP),
string(gortsplib.PLAY),
string(gortsplib.PAUSE),
string(gortsplib.TEARDOWN),
}, ", ")},
},
})
return true
case gortsplib.DESCRIBE:
if c.state != _CLIENT_STATE_STARTING {
c.writeResError(req, gortsplib.StatusBadRequest,
fmt.Errorf("client is in state '%s' instead of '%s'", c.state, _CLIENT_STATE_STARTING))
return false
}
// set up path now as valid from DESCRIBE onwards
c.path = path
err := c.validateAuth(req, c.p.conf.Server.ReadUser, c.p.conf.Server.ReadPass, &c.readAuth)
if err != nil {
if err == errAuthCritical {
return false
}
return true
}
svrSdpText, err := func() ([]byte, error) {
var serverSdpText []byte
c.p.tcpl.mutex.Lock()
str, ok := c.p.streams[path]
if !ok {
// create new stream
c.p.streams[path], err = newStream(c.p, req.Url, c.streamProtocol)
if err != nil {
c.p.tcpl.mutex.Unlock()
return nil, fmt.Errorf("unable to create new stream on path '%s'", path)
}
c.log("created new stream %s path %s", req.Url.Host, path)
str, ok = c.p.streams[path]
if !ok {
c.p.tcpl.mutex.Unlock()
return nil, fmt.Errorf("Unexpected Error")
}
// run the stream
go str.run()
}
wait := time.Tick(time.Second * 15)
c.p.tcpl.mutex.Unlock()
select {
case <-wait:
return nil, fmt.Errorf("ERR: stream '%s' is not ready", path)
case result, ok := <-str.ready:
c.p.tcpl.mutex.Lock()
if ok {
c.log("chan returned %s", result)
close(str.ready)
} else {
c.log("chan closed")
}
serverSdpText = str.serverSdpText
c.p.tcpl.mutex.Unlock()
}
return serverSdpText, nil
}()
if err != nil {
c.writeResError(req, gortsplib.StatusBadRequest, err)
return false
}
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusOK,
Header: gortsplib.Header{
"CSeq": []string{cseq[0]},
"Content-Base": []string{req.Url.String() + "/"},
"Content-Type": []string{"application/sdp"},
},
Content: svrSdpText,
})
return true
case gortsplib.SETUP:
tsRaw, ok := req.Header["Transport"]
if !ok || len(tsRaw) != 1 {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("transport header missing"))
return false
}
th := gortsplib.ReadHeaderTransport(tsRaw[0])
if _, ok := th["multicast"]; ok {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("multicast is not supported"))
return false
}
switch c.state {
// play
case _CLIENT_STATE_STARTING, _CLIENT_STATE_PRE_PLAY:
err := c.validateAuth(req, c.p.conf.Server.ReadUser, c.p.conf.Server.ReadPass, &c.readAuth)
if err != nil {
if err == errAuthCritical {
return false
}
return true
}
// play via UDP
if func() bool {
_, ok := th["RTP/AVP"]
if ok {
return true
}
_, ok = th["RTP/AVP/UDP"]
if ok {
return true
}
return false
}() {
if _, ok := c.p.protocols[_STREAM_PROTOCOL_UDP]; !ok {
c.writeResError(req, gortsplib.StatusUnsupportedTransport, fmt.Errorf("UDP streaming is disabled"))
return false
}
rtpPort, rtcpPort := th.GetPorts("client_port")
if rtpPort == 0 || rtcpPort == 0 {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("transport header does not have valid client ports (%s)", tsRaw[0]))
return false
}
if c.path != "" && path != c.path {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("path %s has changed", path))
return false
}
err := func() error {
c.p.tcpl.mutex.Lock()
defer c.p.tcpl.mutex.Unlock()
str, ok := c.p.streams[path]
if !ok {
return fmt.Errorf("there is no stream on path %s", path)
} else if str == nil {
return fmt.Errorf("stream for path %s not set up yet", path)
}
if str.state != _STREAM_STATE_READY {
return fmt.Errorf("stream '%s' is not ready yet", path)
}
if len(c.streamTracks) > 0 && c.streamProtocol != _STREAM_PROTOCOL_UDP {
return fmt.Errorf("client want to send tracks with different protocols")
}
if len(c.streamTracks) >= len(str.serverSdpParsed.Medias) {
return fmt.Errorf("all the tracks have already been setup")
}
c.streamProtocol = _STREAM_PROTOCOL_UDP
c.streamTracks = append(c.streamTracks, &track{
rtpPort: rtpPort,
rtcpPort: rtcpPort,
})
c.state = _CLIENT_STATE_PRE_PLAY
return nil
}()
if err != nil {
c.writeResError(req, gortsplib.StatusBadRequest, err)
return false
}
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusOK,
Header: gortsplib.Header{
"CSeq": []string{cseq[0]},
"Transport": []string{strings.Join([]string{
"RTP/AVP/UDP",
"unicast",
fmt.Sprintf("client_port=%d-%d", rtpPort, rtcpPort),
fmt.Sprintf("server_port=%d-%d", c.p.conf.Server.RtpPort, c.p.conf.Server.RtcpPort),
}, ";")},
"Session": []string{"12345678"},
},
})
return true
// play via TCP
} else if _, ok := th["RTP/AVP/TCP"]; ok {
if _, ok := c.p.protocols[_STREAM_PROTOCOL_TCP]; !ok {
c.writeResError(req, gortsplib.StatusUnsupportedTransport, fmt.Errorf("TCP streaming is disabled"))
return false
}
if c.path != "" && path != c.path {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("path %s has changed", path))
return false
}
err := func() error {
c.p.tcpl.mutex.Lock()
defer c.p.tcpl.mutex.Unlock()
str, ok := c.p.streams[path]
if !ok {
return fmt.Errorf("there is no stream on path '%s'", path)
}
if len(c.streamTracks) > 0 && c.streamProtocol != _STREAM_PROTOCOL_TCP {
return fmt.Errorf("client want to send tracks with different protocols")
}
if len(c.streamTracks) >= len(str.serverSdpParsed.Medias) {
return fmt.Errorf("all the tracks have already been setup")
}
c.path = path
c.streamProtocol = _STREAM_PROTOCOL_TCP
c.streamTracks = append(c.streamTracks, &track{
rtpPort: 0,
rtcpPort: 0,
})
c.state = _CLIENT_STATE_PRE_PLAY
return nil
}()
if err != nil {
c.writeResError(req, gortsplib.StatusBadRequest, err)
return false
}
interleaved := fmt.Sprintf("%d-%d", ((len(c.streamTracks) - 1) * 2), ((len(c.streamTracks)-1)*2)+1)
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusOK,
Header: gortsplib.Header{
"CSeq": []string{cseq[0]},
"Transport": []string{strings.Join([]string{
"RTP/AVP/TCP",
"unicast",
fmt.Sprintf("interleaved=%s", interleaved),
}, ";")},
"Session": []string{"12345678"},
},
})
return true
} else {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("transport header does not contain a valid protocol (RTP/AVP, RTP/AVP/UDP or RTP/AVP/TCP) (%s)", tsRaw[0]))
return false
}
default:
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("client is in state '%s'", c.state))
return false
}
case gortsplib.PLAY:
if c.state != _CLIENT_STATE_PRE_PLAY {
c.writeResError(req, gortsplib.StatusBadRequest,
fmt.Errorf("client is in state '%s' instead of '%s'", c.state, _CLIENT_STATE_PRE_PLAY))
return false
}
if path != c.path {
// c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("path %s has changed (was %s) for PLAY", path, c.path))
// return false
c.log("path %s has changed (was %s)", path, c.path)
}
err := func() error {
c.p.tcpl.mutex.Lock()
defer c.p.tcpl.mutex.Unlock()
str, ok := c.p.streams[c.path]
if !ok {
return fmt.Errorf("no one is streaming on path %s", c.path)
} else if str == nil {
return fmt.Errorf("stream on path %s is not valid", c.path)
}
if len(c.streamTracks) != len(str.serverSdpParsed.Medias) {
return fmt.Errorf("not all tracks have been setup")
}
return nil
}()
if err != nil {
c.writeResError(req, gortsplib.StatusBadRequest, err)
return false
}
// first write response, then set state
// otherwise, in case of TCP connections, RTP packets could be written
// before the response
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusOK,
Header: gortsplib.Header{
"CSeq": []string{cseq[0]},
"Session": []string{"12345678"},
},
})
c.log("is receiving on path '%s', %d %s via %s", c.path, len(c.streamTracks), func() string {
if len(c.streamTracks) == 1 {
return "track"
}
return "tracks"
}(), c.streamProtocol)
c.p.tcpl.mutex.Lock()
c.state = _CLIENT_STATE_PLAY
c.p.tcpl.mutex.Unlock()
// when protocol is TCP, the RTSP connection becomes a RTP connection
if c.streamProtocol == _STREAM_PROTOCOL_TCP {
// write RTP frames sequentially
go func() {
for frame := range c.write {
c.conn.WriteInterleavedFrame(frame)
}
}()
// receive RTP feedback, do not parse it, wait until connection closes
buf := make([]byte, 2048)
for {
_, err := c.conn.NetConn().Read(buf)
if err != nil {
if err != io.EOF {
c.log("Read ERR: %s", err)
}
return false
}
}
}
return true
case gortsplib.PAUSE:
if c.state != _CLIENT_STATE_PLAY {
c.writeResError(req, gortsplib.StatusBadRequest,
fmt.Errorf("client is in state '%s' instead of '%s'", c.state, _CLIENT_STATE_PLAY))
return false
}
if path != c.path {
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("path %s has changed (was %s) for PAUSE", path, c.path))
return false
}
c.log("paused")
c.p.tcpl.mutex.Lock()
c.state = _CLIENT_STATE_PRE_PLAY
c.p.tcpl.mutex.Unlock()
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusOK,
Header: gortsplib.Header{
"CSeq": []string{cseq[0]},
"Session": []string{"12345678"},
},
})
return true
case gortsplib.TEARDOWN:
// respond
c.conn.WriteResponse(&gortsplib.Response{
StatusCode: gortsplib.StatusOK,
Header: gortsplib.Header{
"CSeq": []string{cseq[0]},
},
})
// close
return false
default:
c.writeResError(req, gortsplib.StatusBadRequest, fmt.Errorf("unhandled method '%s'", req.Method))
return false
}
}