mediamtx/internal/core/rtsp_conn.go

238 lines
5.6 KiB
Go
Raw Normal View History

package core
2019-12-31 12:48:17 +00:00
import (
2020-05-10 20:56:46 +00:00
"errors"
2019-12-31 12:48:17 +00:00
"io"
"net"
"time"
2019-12-31 12:48:17 +00:00
2020-01-20 09:21:05 +00:00
"github.com/aler9/gortsplib"
2020-11-15 16:56:54 +00:00
"github.com/aler9/gortsplib/pkg/auth"
"github.com/aler9/gortsplib/pkg/base"
"github.com/aler9/gortsplib/pkg/headers"
2021-03-21 10:22:49 +00:00
"github.com/aler9/gortsplib/pkg/liberrors"
2020-11-01 21:56:56 +00:00
"github.com/aler9/rtsp-simple-server/internal/externalcmd"
"github.com/aler9/rtsp-simple-server/internal/logger"
2019-12-31 12:48:17 +00:00
)
const (
rtspConnPauseAfterAuthError = 2 * time.Second
)
2021-05-07 21:07:31 +00:00
func isTeardownErr(err error) bool {
_, ok := err.(liberrors.ErrServerSessionTeardown)
return ok
2021-01-31 22:11:14 +00:00
}
func isTerminatedErr(err error) bool {
_, ok := err.(liberrors.ErrServerTerminated)
return ok
}
type rtspConnParent interface {
Log(logger.Level, string, ...interface{})
2020-10-19 20:17:48 +00:00
}
type rtspConn struct {
rtspAddress string
authMethods []headers.AuthMethod
readTimeout time.Duration
runOnConnect string
runOnConnectRestart bool
pathManager *pathManager
stats *stats
2020-12-06 17:01:10 +00:00
conn *gortsplib.ServerConn
parent rtspConnParent
2020-10-19 20:17:48 +00:00
2021-05-07 21:07:31 +00:00
onConnectCmd *externalcmd.Cmd
authUser string
authPass string
authValidator *auth.Validator
authFailures int
2019-12-31 12:48:17 +00:00
}
func newRTSPConn(
rtspAddress string,
authMethods []headers.AuthMethod,
2020-10-19 20:17:48 +00:00
readTimeout time.Duration,
runOnConnect string,
runOnConnectRestart bool,
pathManager *pathManager,
stats *stats,
2020-12-06 17:01:10 +00:00
conn *gortsplib.ServerConn,
parent rtspConnParent) *rtspConn {
c := &rtspConn{
rtspAddress: rtspAddress,
authMethods: authMethods,
readTimeout: readTimeout,
runOnConnect: runOnConnect,
runOnConnectRestart: runOnConnectRestart,
pathManager: pathManager,
2020-11-01 16:33:06 +00:00
stats: stats,
2020-12-06 17:01:10 +00:00
conn: conn,
parent: parent,
2019-12-31 12:48:17 +00:00
}
2021-05-09 12:41:18 +00:00
c.log(logger.Info, "opened")
2021-05-07 21:07:31 +00:00
if c.runOnConnect != "" {
_, port, _ := net.SplitHostPort(c.rtspAddress)
c.onConnectCmd = externalcmd.New(c.runOnConnect, c.runOnConnectRestart, externalcmd.Environment{
Path: "",
Port: port,
})
}
2020-10-19 20:17:48 +00:00
return c
2019-12-31 12:48:17 +00:00
}
2021-05-09 14:12:15 +00:00
// ParentClose closes a Conn.
func (c *rtspConn) ParentClose(err error) {
if err != io.EOF && !isTeardownErr(err) && !isTerminatedErr(err) {
2021-05-07 21:07:31 +00:00
c.log(logger.Info, "ERR: %v", err)
}
2021-05-09 12:41:18 +00:00
c.log(logger.Info, "closed")
2021-05-07 21:07:31 +00:00
if c.onConnectCmd != nil {
c.onConnectCmd.Close()
}
2021-04-27 11:43:15 +00:00
}
func (c *rtspConn) log(level logger.Level, format string, args ...interface{}) {
2021-05-09 12:41:18 +00:00
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) ip() net.IP {
return c.conn.NetConn().RemoteAddr().(*net.TCPAddr).IP
}
2021-07-29 13:11:02 +00:00
func (c *rtspConn) validateCredentials(
2021-05-07 21:07:31 +00:00
pathUser string,
pathPass string,
pathName string,
req *base.Request,
) error {
// reset authValidator every time the credentials change
if c.authValidator == nil || c.authUser != pathUser || c.authPass != pathPass {
c.authUser = pathUser
c.authPass = pathPass
c.authValidator = auth.NewValidator(pathUser, pathPass, c.authMethods)
2021-05-07 21:07:31 +00:00
}
// VLC strips the control attribute
// provide an alternative URL without the control attribute
altURL := func() *base.URL {
if req.Method != base.Setup {
return nil
}
return &base.URL{
Scheme: req.URL.Scheme,
Host: req.URL.Host,
Path: "/" + pathName + "/",
}
}()
2021-05-30 10:57:23 +00:00
err := c.authValidator.ValidateRequest(req, altURL)
2021-05-07 21:07:31 +00:00
if err != nil {
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 pathErrAuthCritical{
2021-05-07 21:07:31 +00:00
Message: "unauthorized: " + err.Error(),
Response: &base.Response{
2020-12-13 12:58:56 +00:00
StatusCode: base.StatusUnauthorized,
2021-05-07 21:07:31 +00:00
},
2020-12-13 12:58:56 +00:00
}
2021-05-07 21:07:31 +00:00
}
2020-12-13 12:58:56 +00:00
2021-05-07 21:07:31 +00:00
if c.authFailures > 1 {
c.log(logger.Debug, "WARN: unauthorized: %s", err)
2020-12-13 12:58:56 +00:00
}
2021-05-07 21:07:31 +00:00
return pathErrAuthNotCritical{
Response: &base.Response{
StatusCode: base.StatusUnauthorized,
Header: base.Header{
2021-05-30 10:57:23 +00:00
"WWW-Authenticate": c.authValidator.Header(),
},
2021-05-07 21:07:31 +00:00
},
}
2020-07-13 09:12:20 +00:00
}
2020-12-13 12:58:56 +00:00
// login successful, reset authFailures
c.authFailures = 0
return nil
}
// 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)
}
// OnDescribe is called by rtspServer.
func (c *rtspConn) OnDescribe(ctx *gortsplib.ServerHandlerOnDescribeCtx) (*base.Response, *gortsplib.ServerStream, error) {
res := c.pathManager.OnDescribe(pathDescribeReq{
PathName: ctx.Path,
URL: ctx.Req.URL,
IP: c.ip(),
ValidateCredentials: func(pathUser string, pathPass string) error {
return c.validateCredentials(pathUser, pathPass, ctx.Path, ctx.Req)
},
})
if res.Err != nil {
switch terr := res.Err.(type) {
case pathErrAuthNotCritical:
return terr.Response, nil, nil
case pathErrAuthCritical:
// wait some seconds to stop brute force attacks
<-time.After(rtspConnPauseAfterAuthError)
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
}
}
if res.Redirect != "" {
return &base.Response{
StatusCode: base.StatusMovedPermanently,
Header: base.Header{
"Location": base.HeaderValue{res.Redirect},
},
}, nil, nil
}
return &base.Response{
StatusCode: base.StatusOK,
}, res.Stream, nil
}