mediamtx/internal/core/rtsp_conn.go

212 lines
5.0 KiB
Go
Raw Normal View History

package core
2019-12-31 12:48:17 +00:00
import (
"fmt"
2019-12-31 12:48:17 +00:00
"net"
"time"
2019-12-31 12:48:17 +00:00
2023-04-01 16:39:12 +00:00
"github.com/bluenviron/gortsplib/v3"
"github.com/bluenviron/gortsplib/v3/pkg/auth"
"github.com/bluenviron/gortsplib/v3/pkg/base"
"github.com/bluenviron/gortsplib/v3/pkg/headers"
"github.com/google/uuid"
2023-05-16 14:14:20 +00:00
"github.com/bluenviron/mediamtx/internal/conf"
"github.com/bluenviron/mediamtx/internal/externalcmd"
"github.com/bluenviron/mediamtx/internal/logger"
2019-12-31 12:48:17 +00:00
)
const (
rtspConnPauseAfterAuthError = 2 * time.Second
)
type rtspConnParent interface {
logger.Writer
2020-10-19 20:17:48 +00:00
}
type rtspConn struct {
rtspAddress string
authMethods []headers.AuthMethod
readTimeout conf.StringDuration
runOnConnect string
runOnConnectRestart bool
externalCmdPool *externalcmd.Pool
pathManager *pathManager
conn *gortsplib.ServerConn
parent rtspConnParent
uuid uuid.UUID
created time.Time
onConnectCmd *externalcmd.Cmd
authNonce string
authFailures int
2019-12-31 12:48:17 +00:00
}
func newRTSPConn(
rtspAddress string,
authMethods []headers.AuthMethod,
readTimeout conf.StringDuration,
2020-10-19 20:17:48 +00:00
runOnConnect string,
runOnConnectRestart bool,
externalCmdPool *externalcmd.Pool,
pathManager *pathManager,
2020-12-06 17:01:10 +00:00
conn *gortsplib.ServerConn,
2022-04-07 10:50:35 +00:00
parent rtspConnParent,
) *rtspConn {
c := &rtspConn{
rtspAddress: rtspAddress,
authMethods: authMethods,
readTimeout: readTimeout,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
externalCmdPool: externalCmdPool,
pathManager: pathManager,
conn: conn,
parent: parent,
uuid: uuid.New(),
created: time.Now(),
2019-12-31 12:48:17 +00:00
}
c.Log(logger.Info, "opened")
2021-05-07 21:07:31 +00:00
if c.runOnConnect != "" {
c.Log(logger.Info, "runOnConnect command started")
2021-05-07 21:07:31 +00:00
_, port, _ := net.SplitHostPort(c.rtspAddress)
c.onConnectCmd = externalcmd.NewCmd(
c.externalCmdPool,
c.runOnConnect,
c.runOnConnectRestart,
externalcmd.Environment{
"RTSP_PATH": "",
"RTSP_PORT": port,
},
func(co int) {
c.Log(logger.Info, "runOnInit command exited with code %d", co)
})
2021-05-07 21:07:31 +00:00
}
2020-10-19 20:17:48 +00:00
return c
2019-12-31 12:48:17 +00:00
}
func (c *rtspConn) Log(level logger.Level, format string, args ...interface{}) {
c.parent.Log(level, "[conn %v] "+format, append([]interface{}{c.conn.NetConn().RemoteAddr()}, args...)...)
2020-10-19 20:17:48 +00:00
}
2021-05-07 21:07:31 +00:00
// Conn returns the RTSP connection.
func (c *rtspConn) Conn() *gortsplib.ServerConn {
2021-05-07 21:07:31 +00:00
return c.conn
}
func (c *rtspConn) remoteAddr() net.Addr {
return c.conn.NetConn().RemoteAddr()
}
func (c *rtspConn) ip() net.IP {
return c.conn.NetConn().RemoteAddr().(*net.TCPAddr).IP
}
2021-10-27 19:01:00 +00:00
// onClose is called by rtspServer.
func (c *rtspConn) onClose(err error) {
c.Log(logger.Info, "closed (%v)", err)
if c.onConnectCmd != nil {
c.onConnectCmd.Close()
c.Log(logger.Info, "runOnConnect command stopped")
}
}
2021-10-27 19:01:00 +00:00
// onRequest is called by rtspServer.
func (c *rtspConn) onRequest(req *base.Request) {
c.Log(logger.Debug, "[c->s] %v", req)
}
// OnResponse is called by rtspServer.
func (c *rtspConn) OnResponse(res *base.Response) {
c.Log(logger.Debug, "[s->c] %v", res)
}
2021-10-27 19:01:00 +00:00
// onDescribe is called by rtspServer.
func (c *rtspConn) onDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx,
2021-09-09 21:05:54 +00:00
) (*base.Response, *gortsplib.ServerStream, error) {
2023-01-11 00:11:05 +00:00
if len(ctx.Path) == 0 || ctx.Path[0] != '/' {
return &base.Response{
StatusCode: base.StatusBadRequest,
}, nil, fmt.Errorf("invalid path")
}
ctx.Path = ctx.Path[1:]
if c.authNonce == "" {
c.authNonce = auth.GenerateNonce()
}
res := c.pathManager.describe(pathDescribeReq{
2022-01-14 22:42:41 +00:00
pathName: ctx.Path,
2022-02-19 22:06:24 +00:00
url: ctx.Request.URL,
credentials: authCredentials{
query: ctx.Query,
ip: c.ip(),
proto: authProtocolRTSP,
id: &c.uuid,
rtspRequest: ctx.Request,
rtspNonce: c.authNonce,
},
})
2022-01-14 22:42:41 +00:00
if res.err != nil {
switch terr := res.err.(type) {
case pathErrAuth:
res, err := c.handleAuthError(terr.wrapped)
return res, nil, err
case pathErrNoOnePublishing:
return &base.Response{
StatusCode: base.StatusNotFound,
2022-01-14 22:42:41 +00:00
}, nil, res.err
default:
return &base.Response{
StatusCode: base.StatusBadRequest,
2022-01-14 22:42:41 +00:00
}, nil, res.err
}
}
2022-01-14 22:42:41 +00:00
if res.redirect != "" {
return &base.Response{
StatusCode: base.StatusMovedPermanently,
Header: base.Header{
2022-01-14 22:42:41 +00:00
"Location": base.HeaderValue{res.redirect},
},
}, nil, nil
}
return &base.Response{
StatusCode: base.StatusOK,
2022-01-14 22:42:41 +00:00
}, res.stream.rtspStream, nil
}
func (c *rtspConn) handleAuthError(authErr error) (*base.Response, error) {
c.authFailures++
// VLC with login prompt sends 4 requests:
// 1) without credentials
// 2) with password but without username
// 3) without credentials
// 4) with password and username
// therefore we must allow up to 3 failures
if c.authFailures <= 3 {
return &base.Response{
StatusCode: base.StatusUnauthorized,
Header: base.Header{
"WWW-Authenticate": auth.GenerateWWWAuthenticate(c.authMethods, "IPCAM", c.authNonce),
},
}, nil
}
// wait some seconds to stop brute force attacks
<-time.After(rtspConnPauseAfterAuthError)
return &base.Response{
StatusCode: base.StatusUnauthorized,
}, authErr
}