-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
rtsp_session.go
406 lines (342 loc) · 9.97 KB
/
rtsp_session.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
package core
import (
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/aler9/gortsplib"
"github.com/aler9/gortsplib/pkg/base"
"github.com/aler9/rtsp-simple-server/internal/conf"
"github.com/aler9/rtsp-simple-server/internal/externalcmd"
"github.com/aler9/rtsp-simple-server/internal/logger"
)
const (
pauseAfterAuthError = 2 * time.Second
)
type rtspSessionPathManager interface {
publisherAnnounce(req pathPublisherAnnounceReq) pathPublisherAnnounceRes
readerSetupPlay(req pathReaderSetupPlayReq) pathReaderSetupPlayRes
}
type rtspSessionParent interface {
log(logger.Level, string, ...interface{})
}
type rtspSession struct {
isTLS bool
protocols map[conf.Protocol]struct{}
id string
ss *gortsplib.ServerSession
author *gortsplib.ServerConn
externalCmdPool *externalcmd.Pool
pathManager rtspSessionPathManager
parent rtspSessionParent
created time.Time
path *path
state gortsplib.ServerSessionState
stateMutex sync.Mutex
onReadCmd *externalcmd.Cmd // read
announcedTracks gortsplib.Tracks // publish
stream *stream // publish
}
func newRTSPSession(
isTLS bool,
protocols map[conf.Protocol]struct{},
id string,
ss *gortsplib.ServerSession,
sc *gortsplib.ServerConn,
externalCmdPool *externalcmd.Pool,
pathManager rtspSessionPathManager,
parent rtspSessionParent,
) *rtspSession {
s := &rtspSession{
isTLS: isTLS,
protocols: protocols,
id: id,
ss: ss,
author: sc,
externalCmdPool: externalCmdPool,
pathManager: pathManager,
parent: parent,
created: time.Now(),
}
s.log(logger.Info, "created by %v", s.author.NetConn().RemoteAddr())
return s
}
// Close closes a Session.
func (s *rtspSession) close() {
s.ss.Close()
}
// isRTSPSession implements pathRTSPSession.
func (s *rtspSession) isRTSPSession() {}
func (s *rtspSession) safeState() gortsplib.ServerSessionState {
s.stateMutex.Lock()
defer s.stateMutex.Unlock()
return s.state
}
func (s *rtspSession) remoteAddr() net.Addr {
return s.author.NetConn().RemoteAddr()
}
func (s *rtspSession) log(level logger.Level, format string, args ...interface{}) {
s.parent.log(level, "[session %s] "+format, append([]interface{}{s.id}, args...)...)
}
// onClose is called by rtspServer.
func (s *rtspSession) onClose(err error) {
if s.ss.State() == gortsplib.ServerSessionStatePlay {
if s.onReadCmd != nil {
s.onReadCmd.Close()
s.onReadCmd = nil
s.log(logger.Info, "runOnRead command stopped")
}
}
switch s.ss.State() {
case gortsplib.ServerSessionStatePrePlay, gortsplib.ServerSessionStatePlay:
s.path.readerRemove(pathReaderRemoveReq{author: s})
s.path = nil
case gortsplib.ServerSessionStatePreRecord, gortsplib.ServerSessionStateRecord:
s.path.publisherRemove(pathPublisherRemoveReq{author: s})
s.path = nil
}
s.log(logger.Info, "destroyed (%v)", err)
}
// onAnnounce is called by rtspServer.
func (s *rtspSession) onAnnounce(c *rtspConn, ctx *gortsplib.ServerHandlerOnAnnounceCtx) (*base.Response, error) {
res := s.pathManager.publisherAnnounce(pathPublisherAnnounceReq{
author: s,
pathName: ctx.Path,
authenticate: func(
pathIPs []fmt.Stringer,
pathUser conf.Credential,
pathPass conf.Credential,
) error {
return c.authenticate(ctx.Path, pathIPs, pathUser, pathPass, "publish", ctx.Request, ctx.Query)
},
})
if res.err != nil {
switch terr := res.err.(type) {
case pathErrAuthNotCritical:
s.log(logger.Debug, "non-critical authentication error: %s", terr.message)
return terr.response, nil
case pathErrAuthCritical:
// wait some seconds to stop brute force attacks
<-time.After(pauseAfterAuthError)
return terr.response, errors.New(terr.message)
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
}, res.err
}
}
s.path = res.path
s.announcedTracks = ctx.Tracks
s.stateMutex.Lock()
s.state = gortsplib.ServerSessionStatePreRecord
s.stateMutex.Unlock()
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
// onSetup is called by rtspServer.
func (s *rtspSession) onSetup(c *rtspConn, ctx *gortsplib.ServerHandlerOnSetupCtx,
) (*base.Response, *gortsplib.ServerStream, error) {
// in case the client is setupping a stream with UDP or UDP-multicast, and these
// transport protocols are disabled, gortsplib already blocks the request.
// we have only to handle the case in which the transport protocol is TCP
// and it is disabled.
if ctx.Transport == gortsplib.TransportTCP {
if _, ok := s.protocols[conf.Protocol(gortsplib.TransportTCP)]; !ok {
return &base.Response{
StatusCode: base.StatusUnsupportedTransport,
}, nil, nil
}
}
switch s.ss.State() {
case gortsplib.ServerSessionStateInitial, gortsplib.ServerSessionStatePrePlay: // play
res := s.pathManager.readerSetupPlay(pathReaderSetupPlayReq{
author: s,
pathName: ctx.Path,
authenticate: func(
pathIPs []fmt.Stringer,
pathUser conf.Credential,
pathPass conf.Credential,
) error {
return c.authenticate(ctx.Path, pathIPs, pathUser, pathPass, "read", ctx.Request, ctx.Query)
},
})
if res.err != nil {
switch terr := res.err.(type) {
case pathErrAuthNotCritical:
s.log(logger.Debug, "non-critical authentication error: %s", terr.message)
return terr.response, nil, nil
case pathErrAuthCritical:
// wait some seconds to stop brute force attacks
<-time.After(pauseAfterAuthError)
return terr.response, nil, errors.New(terr.message)
case pathErrNoOnePublishing:
return &base.Response{
StatusCode: base.StatusNotFound,
}, nil, res.err
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, res.err
}
}
s.path = res.path
if ctx.TrackID >= len(res.stream.tracks()) {
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, fmt.Errorf("track %d does not exist", ctx.TrackID)
}
s.stateMutex.Lock()
s.state = gortsplib.ServerSessionStatePrePlay
s.stateMutex.Unlock()
return &base.Response{
StatusCode: base.StatusOK,
}, res.stream.rtspStream, nil
default: // record
return &base.Response{
StatusCode: base.StatusOK,
}, nil, nil
}
}
// onPlay is called by rtspServer.
func (s *rtspSession) onPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
h := make(base.Header)
if s.ss.State() == gortsplib.ServerSessionStatePrePlay {
s.path.readerPlay(pathReaderPlayReq{author: s})
if s.path.Conf().RunOnRead != "" {
s.log(logger.Info, "runOnRead command started")
s.onReadCmd = externalcmd.NewCmd(
s.externalCmdPool,
s.path.Conf().RunOnRead,
s.path.Conf().RunOnReadRestart,
s.path.externalCmdEnv(),
func(co int) {
s.log(logger.Info, "runOnRead command exited with code %d", co)
})
}
s.stateMutex.Lock()
s.state = gortsplib.ServerSessionStatePlay
s.stateMutex.Unlock()
}
return &base.Response{
StatusCode: base.StatusOK,
Header: h,
}, nil
}
// onRecord is called by rtspServer.
func (s *rtspSession) onRecord(ctx *gortsplib.ServerHandlerOnRecordCtx) (*base.Response, error) {
res := s.path.publisherRecord(pathPublisherRecordReq{
author: s,
tracks: s.announcedTracks,
})
if res.err != nil {
return &base.Response{
StatusCode: base.StatusBadRequest,
}, res.err
}
s.stream = res.stream
s.stateMutex.Lock()
s.state = gortsplib.ServerSessionStateRecord
s.stateMutex.Unlock()
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
// onPause is called by rtspServer.
func (s *rtspSession) onPause(ctx *gortsplib.ServerHandlerOnPauseCtx) (*base.Response, error) {
switch s.ss.State() {
case gortsplib.ServerSessionStatePlay:
if s.onReadCmd != nil {
s.log(logger.Info, "runOnRead command stopped")
s.onReadCmd.Close()
}
s.path.readerPause(pathReaderPauseReq{author: s})
s.stateMutex.Lock()
s.state = gortsplib.ServerSessionStatePrePlay
s.stateMutex.Unlock()
case gortsplib.ServerSessionStateRecord:
s.path.publisherPause(pathPublisherPauseReq{author: s})
s.stateMutex.Lock()
s.state = gortsplib.ServerSessionStatePreRecord
s.stateMutex.Unlock()
}
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
// onReaderAccepted implements reader.
func (s *rtspSession) onReaderAccepted() {
tracksLen := len(s.ss.SetuppedTracks())
s.log(logger.Info, "is reading from path '%s', %d %s with %s",
s.path.Name(),
tracksLen,
func() string {
if tracksLen == 1 {
return "track"
}
return "tracks"
}(),
s.ss.SetuppedTransport())
}
// onReaderData implements reader.
func (s *rtspSession) onReaderData(data *data) {
// packets are routed to the session by gortsplib.ServerStream.
}
// apiReaderDescribe implements reader.
func (s *rtspSession) apiReaderDescribe() interface{} {
var typ string
if s.isTLS {
typ = "rtspsSession"
} else {
typ = "rtspSession"
}
return struct {
Type string `json:"type"`
ID string `json:"id"`
}{typ, s.id}
}
// apiSourceDescribe implements source.
func (s *rtspSession) apiSourceDescribe() interface{} {
var typ string
if s.isTLS {
typ = "rtspsSession"
} else {
typ = "rtspSession"
}
return struct {
Type string `json:"type"`
ID string `json:"id"`
}{typ, s.id}
}
// onPublisherAccepted implements publisher.
func (s *rtspSession) onPublisherAccepted(tracksLen int) {
s.log(logger.Info, "is publishing to path '%s', %d %s with %s",
s.path.Name(),
tracksLen,
func() string {
if tracksLen == 1 {
return "track"
}
return "tracks"
}(),
s.ss.SetuppedTransport())
}
// onPacketRTP is called by rtspServer.
func (s *rtspSession) onPacketRTP(ctx *gortsplib.ServerHandlerOnPacketRTPCtx) {
if ctx.H264NALUs != nil {
s.stream.writeData(&data{
trackID: ctx.TrackID,
rtp: ctx.Packet,
ptsEqualsDTS: ctx.PTSEqualsDTS,
h264NALUs: append([][]byte(nil), ctx.H264NALUs...),
h264PTS: ctx.H264PTS,
})
} else {
s.stream.writeData(&data{
trackID: ctx.TrackID,
rtp: ctx.Packet,
ptsEqualsDTS: ctx.PTSEqualsDTS,
})
}
}