mediamtx/internal/core/rtsp_session.go

420 lines
10 KiB
Go
Raw Normal View History

package core
2021-05-07 21:07:31 +00:00
import (
"errors"
"fmt"
"net"
"sync"
2021-05-07 21:07:31 +00:00
"time"
"github.com/aler9/gortsplib"
"github.com/aler9/gortsplib/pkg/base"
"github.com/pion/rtcp"
"github.com/pion/rtp"
2021-05-07 21:07:31 +00:00
"github.com/aler9/rtsp-simple-server/internal/conf"
2021-05-07 21:07:31 +00:00
"github.com/aler9/rtsp-simple-server/internal/externalcmd"
"github.com/aler9/rtsp-simple-server/internal/logger"
)
const (
pauseAfterAuthError = 2 * time.Second
)
2021-08-11 10:45:53 +00:00
type rtspSessionPathManager interface {
2021-10-27 19:01:00 +00:00
onPublisherAnnounce(req pathPublisherAnnounceReq) pathPublisherAnnounceRes
onReaderSetupPlay(req pathReaderSetupPlayReq) pathReaderSetupPlayRes
2021-08-11 10:45:53 +00:00
}
type rtspSessionParent interface {
2021-10-27 19:01:00 +00:00
log(logger.Level, string, ...interface{})
2021-05-07 21:07:31 +00:00
}
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
2021-05-07 21:07:31 +00:00
path *path
state gortsplib.ServerSessionState
stateMutex sync.Mutex
2022-01-30 16:36:42 +00:00
setuppedTracks map[int]gortsplib.Track // read
onReadCmd *externalcmd.Cmd // read
announcedTracks gortsplib.Tracks // publish
stream *stream // publish
2021-05-07 21:07:31 +00:00
}
func newRTSPSession(
isTLS bool,
protocols map[conf.Protocol]struct{},
id string,
2021-05-07 21:07:31 +00:00
ss *gortsplib.ServerSession,
sc *gortsplib.ServerConn,
externalCmdPool *externalcmd.Pool,
2021-08-11 10:45:53 +00:00
pathManager rtspSessionPathManager,
parent rtspSessionParent) *rtspSession {
s := &rtspSession{
isTLS: isTLS,
protocols: protocols,
id: id,
ss: ss,
author: sc,
externalCmdPool: externalCmdPool,
pathManager: pathManager,
parent: parent,
2021-05-07 21:07:31 +00:00
}
s.log(logger.Info, "opened by %v", s.author.NetConn().RemoteAddr())
2021-05-07 21:07:31 +00:00
return s
}
2021-05-09 14:12:15 +00:00
// Close closes a Session.
2021-10-27 19:01:00 +00:00
func (s *rtspSession) close() {
2021-05-07 21:07:31 +00:00
s.ss.Close()
}
// IsRTSPSession implements pathRTSPSession.
func (s *rtspSession) IsRTSPSession() {}
// ID returns the public ID of the session.
func (s *rtspSession) ID() string {
return s.id
}
func (s *rtspSession) safeState() gortsplib.ServerSessionState {
s.stateMutex.Lock()
defer s.stateMutex.Unlock()
return s.state
}
// RemoteAddr returns the remote address of the author of the session.
func (s *rtspSession) RemoteAddr() net.Addr {
return s.author.NetConn().RemoteAddr()
}
func (s *rtspSession) log(level logger.Level, format string, args ...interface{}) {
2021-10-27 19:01:00 +00:00
s.parent.log(level, "[session %s] "+format, append([]interface{}{s.id}, args...)...)
2021-05-07 21:07:31 +00:00
}
2021-10-27 19:01:00 +00:00
// onClose is called by rtspServer.
func (s *rtspSession) onClose(err error) {
2022-02-18 09:21:04 +00:00
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() {
2022-02-18 09:21:04 +00:00
case gortsplib.ServerSessionStatePrePlay, gortsplib.ServerSessionStatePlay:
2022-01-14 22:42:41 +00:00
s.path.onReaderRemove(pathReaderRemoveReq{author: s})
s.path = nil
2022-02-18 09:21:04 +00:00
case gortsplib.ServerSessionStatePreRecord, gortsplib.ServerSessionStateRecord:
2022-01-14 22:42:41 +00:00
s.path.onPublisherRemove(pathPublisherRemoveReq{author: s})
s.path = nil
}
s.log(logger.Info, "closed (%v)", err)
}
2021-10-27 19:01:00 +00:00
// onAnnounce is called by rtspServer.
func (s *rtspSession) onAnnounce(c *rtspConn, ctx *gortsplib.ServerHandlerOnAnnounceCtx) (*base.Response, error) {
res := s.pathManager.onPublisherAnnounce(pathPublisherAnnounceReq{
2022-01-14 22:42:41 +00:00
author: s,
pathName: ctx.Path,
authenticate: func(
pathIPs []interface{},
pathUser conf.Credential,
pathPass conf.Credential) error {
return c.authenticate(ctx.Path, pathIPs, pathUser, pathPass, "publish", ctx.Req, ctx.Query)
2021-05-07 21:07:31 +00:00
},
})
2022-01-14 22:42:41 +00:00
if res.err != nil {
switch terr := res.err.(type) {
case pathErrAuthNotCritical:
2022-01-14 22:42:41 +00:00
s.log(logger.Debug, "non-critical authentication error: %s", terr.message)
return terr.response, nil
2021-05-07 21:07:31 +00:00
case pathErrAuthCritical:
2021-05-07 21:07:31 +00:00
// wait some seconds to stop brute force attacks
<-time.After(pauseAfterAuthError)
2022-01-14 22:42:41 +00:00
return terr.response, errors.New(terr.message)
2021-05-07 21:07:31 +00:00
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
2022-01-14 22:42:41 +00:00
}, res.err
2021-05-07 21:07:31 +00:00
}
}
2022-01-14 22:42:41 +00:00
s.path = res.path
s.announcedTracks = ctx.Tracks
2021-05-07 21:07:31 +00:00
s.stateMutex.Lock()
2022-02-18 09:21:04 +00:00
s.state = gortsplib.ServerSessionStatePreRecord
s.stateMutex.Unlock()
2021-05-07 21:07:31 +00:00
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
2021-10-27 19:01:00 +00:00
// onSetup is called by rtspServer.
func (s *rtspSession) onSetup(c *rtspConn, ctx *gortsplib.ServerHandlerOnSetupCtx,
2021-09-09 21:05:54 +00:00
) (*base.Response, *gortsplib.ServerStream, error) {
2021-10-22 16:43:46 +00:00
// 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 {
2021-10-22 16:41:10 +00:00
if _, ok := s.protocols[conf.Protocol(gortsplib.TransportTCP)]; !ok {
return &base.Response{
StatusCode: base.StatusUnsupportedTransport,
}, nil, nil
2021-05-07 21:07:31 +00:00
}
}
switch s.ss.State() {
2022-02-18 09:21:04 +00:00
case gortsplib.ServerSessionStateInitial, gortsplib.ServerSessionStatePrePlay: // play
2021-10-27 19:01:00 +00:00
res := s.pathManager.onReaderSetupPlay(pathReaderSetupPlayReq{
2022-01-14 22:42:41 +00:00
author: s,
pathName: ctx.Path,
authenticate: func(
pathIPs []interface{},
pathUser conf.Credential,
pathPass conf.Credential) error {
return c.authenticate(ctx.Path, pathIPs, pathUser, pathPass, "read", ctx.Req, ctx.Query)
2021-05-07 21:07:31 +00:00
},
})
2022-01-14 22:42:41 +00:00
if res.err != nil {
switch terr := res.err.(type) {
case pathErrAuthNotCritical:
2022-01-14 22:42:41 +00:00
s.log(logger.Debug, "non-critical authentication error: %s", terr.message)
return terr.response, nil, nil
2021-05-07 21:07:31 +00:00
case pathErrAuthCritical:
2021-05-07 21:07:31 +00:00
// wait some seconds to stop brute force attacks
<-time.After(pauseAfterAuthError)
2021-05-09 15:22:24 +00:00
2022-01-14 22:42:41 +00:00
return terr.response, nil, errors.New(terr.message)
2021-05-07 21:07:31 +00:00
case pathErrNoOnePublishing:
2021-05-07 21:07:31 +00:00
return &base.Response{
StatusCode: base.StatusNotFound,
2022-01-14 22:42:41 +00:00
}, nil, res.err
2021-05-07 21:07:31 +00:00
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
2022-01-14 22:42:41 +00:00
}, nil, res.err
2021-05-07 21:07:31 +00:00
}
}
2022-01-14 22:42:41 +00:00
s.path = res.path
2021-05-07 21:07:31 +00:00
2022-01-14 22:42:41 +00:00
if ctx.TrackID >= len(res.stream.tracks()) {
2021-05-07 21:07:31 +00:00
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, fmt.Errorf("track %d does not exist", ctx.TrackID)
2021-05-07 21:07:31 +00:00
}
if s.setuppedTracks == nil {
2022-01-30 16:36:42 +00:00
s.setuppedTracks = make(map[int]gortsplib.Track)
2021-05-07 21:07:31 +00:00
}
2022-01-14 22:42:41 +00:00
s.setuppedTracks[ctx.TrackID] = res.stream.tracks()[ctx.TrackID]
s.stateMutex.Lock()
2022-02-18 09:21:04 +00:00
s.state = gortsplib.ServerSessionStatePrePlay
s.stateMutex.Unlock()
return &base.Response{
StatusCode: base.StatusOK,
2022-01-14 22:42:41 +00:00
}, res.stream.rtspStream, nil
default: // record
return &base.Response{
StatusCode: base.StatusOK,
}, nil, nil
2021-05-07 21:07:31 +00:00
}
}
2021-10-27 19:01:00 +00:00
// onPlay is called by rtspServer.
func (s *rtspSession) onPlay(ctx *gortsplib.ServerHandlerOnPlayCtx) (*base.Response, error) {
2021-05-07 21:07:31 +00:00
h := make(base.Header)
2022-02-18 09:21:04 +00:00
if s.ss.State() == gortsplib.ServerSessionStatePrePlay {
2022-01-14 22:42:41 +00:00
s.path.onReaderPlay(pathReaderPlayReq{author: s})
2021-05-07 21:07:31 +00:00
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)
})
2021-05-07 21:07:31 +00:00
}
s.stateMutex.Lock()
2022-02-18 09:21:04 +00:00
s.state = gortsplib.ServerSessionStatePlay
s.stateMutex.Unlock()
2021-05-07 21:07:31 +00:00
}
return &base.Response{
StatusCode: base.StatusOK,
Header: h,
}, nil
}
2021-10-27 19:01:00 +00:00
// onRecord is called by rtspServer.
func (s *rtspSession) onRecord(ctx *gortsplib.ServerHandlerOnRecordCtx) (*base.Response, error) {
res := s.path.onPublisherRecord(pathPublisherRecordReq{
2022-01-14 22:42:41 +00:00
author: s,
tracks: s.announcedTracks,
})
2022-01-14 22:42:41 +00:00
if res.err != nil {
2021-05-07 21:07:31 +00:00
return &base.Response{
StatusCode: base.StatusBadRequest,
2022-01-14 22:42:41 +00:00
}, res.err
2021-05-07 21:07:31 +00:00
}
2022-01-14 22:42:41 +00:00
s.stream = res.stream
s.stateMutex.Lock()
2022-02-18 09:21:04 +00:00
s.state = gortsplib.ServerSessionStateRecord
s.stateMutex.Unlock()
2021-05-07 21:07:31 +00:00
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
2021-10-27 19:01:00 +00:00
// onPause is called by rtspServer.
func (s *rtspSession) onPause(ctx *gortsplib.ServerHandlerOnPauseCtx) (*base.Response, error) {
2021-05-07 21:07:31 +00:00
switch s.ss.State() {
2022-02-18 09:21:04 +00:00
case gortsplib.ServerSessionStatePlay:
2021-05-07 21:07:31 +00:00
if s.onReadCmd != nil {
s.log(logger.Info, "runOnRead command stopped")
2021-05-07 21:07:31 +00:00
s.onReadCmd.Close()
}
2022-01-14 22:42:41 +00:00
s.path.onReaderPause(pathReaderPauseReq{author: s})
2021-05-07 21:07:31 +00:00
s.stateMutex.Lock()
2022-02-18 09:21:04 +00:00
s.state = gortsplib.ServerSessionStatePrePlay
s.stateMutex.Unlock()
2022-02-18 09:21:04 +00:00
case gortsplib.ServerSessionStateRecord:
2022-01-14 22:42:41 +00:00
s.path.onPublisherPause(pathPublisherPauseReq{author: s})
s.stateMutex.Lock()
2022-02-18 09:21:04 +00:00
s.state = gortsplib.ServerSessionStatePreRecord
s.stateMutex.Unlock()
2021-05-07 21:07:31 +00:00
}
return &base.Response{
StatusCode: base.StatusOK,
}, nil
}
2021-10-27 19:01:00 +00:00
// 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"
}(),
2021-10-22 16:41:10 +00:00
s.ss.SetuppedTransport())
}
2021-11-12 21:29:56 +00:00
// onReaderPacketRTP implements reader.
func (s *rtspSession) onReaderPacketRTP(trackID int, pkt *rtp.Packet) {
2021-12-05 13:36:57 +00:00
// packets are routed to the session by gortsplib.ServerStream.
2021-11-12 21:29:56 +00:00
}
// onReaderPacketRTCP implements reader.
func (s *rtspSession) onReaderPacketRTCP(trackID int, pkt rtcp.Packet) {
2021-12-05 13:36:57 +00:00
// packets are routed to the session by gortsplib.ServerStream.
}
2021-10-27 19:01:00 +00:00
// onReaderAPIDescribe implements reader.
func (s *rtspSession) onReaderAPIDescribe() 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}
}
2021-10-27 19:01:00 +00:00
// onSourceAPIDescribe implements source.
func (s *rtspSession) onSourceAPIDescribe() 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}
}
2021-10-27 19:01:00 +00:00
// 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"
}(),
2021-10-22 16:41:10 +00:00
s.ss.SetuppedTransport())
}
2021-11-12 21:29:56 +00:00
// onPacketRTP is called by rtspServer.
func (s *rtspSession) onPacketRTP(ctx *gortsplib.ServerHandlerOnPacketRTPCtx) {
2022-02-18 09:21:04 +00:00
if s.ss.State() != gortsplib.ServerSessionStateRecord {
2021-11-12 21:29:56 +00:00
return
}
s.stream.onPacketRTP(ctx.TrackID, ctx.Packet)
2021-11-12 21:29:56 +00:00
}
// onPacketRTCP is called by rtspServer.
func (s *rtspSession) onPacketRTCP(ctx *gortsplib.ServerHandlerOnPacketRTCPCtx) {
2022-02-18 09:21:04 +00:00
if s.ss.State() != gortsplib.ServerSessionStateRecord {
2021-05-07 21:07:31 +00:00
return
}
s.stream.onPacketRTCP(ctx.TrackID, ctx.Packet)
2021-05-07 21:07:31 +00:00
}