Signalling V2 protocol implementation start (#3794)

* WIP

* name

* refactor validate

* WIP

* WIP

* signal cache initial impl

* HandleConnect in room manager

* generate subscriber offer

* handle ConnectRequest as stand alone

* segmentation, reassembly

* clean up

* rearrange

* lock scope

* support metadata in connect request

* prom

* add SifTrailer to ConnectResponse

* prom for get offer error counter

* RtcInit counter

* Jie feedback

* signal client

* consolidate v1 and v2 into SignalClient

* clean up

* comment

* deps

* mage generate

* fix tests

* pass around roomName and participantIdentity

* mage generate
This commit is contained in:
Raja Subramanian
2025-07-18 00:01:21 +05:30
committed by GitHub
parent ba702a5323
commit b9a44c3fbf
32 changed files with 2299 additions and 394 deletions
+1
View File
@@ -28,6 +28,7 @@ var (
ErrNameExceedsLimits = psrpc.NewErrorf(psrpc.InvalidArgument, "name length exceeds limits")
ErrMetadataExceedsLimits = psrpc.NewErrorf(psrpc.InvalidArgument, "metadata size exceeds limits")
ErrAttributeExceedsLimits = psrpc.NewErrorf(psrpc.InvalidArgument, "attribute size exceeds limits")
ErrNoRoomName = psrpc.NewErrorf(psrpc.InvalidArgument, "no room name")
ErrRoomNameExceedsLimits = psrpc.NewErrorf(psrpc.InvalidArgument, "room name length exceeds limits")
ErrParticipantIdentityExceedsLimits = psrpc.NewErrorf(psrpc.InvalidArgument, "participant identity length exceeds limits")
ErrDestinationSameAsSourceRoom = psrpc.NewErrorf(psrpc.InvalidArgument, "destination room cannot be the same as source room")
+197 -2
View File
@@ -333,7 +333,8 @@ func (r *RoomManager) StartSession(
return errors.New("could not restart closed participant")
}
participant.GetLogger().Infow("resuming RTC session",
participant.GetLogger().Infow(
"resuming RTC session",
"nodeID", r.currentNode.NodeID(),
"participantInit", &pi,
"numParticipants", room.GetParticipantCount(),
@@ -393,7 +394,8 @@ func (r *RoomManager) StartSession(
sid,
false,
)
pLogger.Infow("starting RTC session",
pLogger.Infow(
"starting RTC session",
"room", room.Name(),
"nodeID", r.currentNode.NodeID(),
"numParticipants", room.GetParticipantCount(),
@@ -561,6 +563,197 @@ func (r *RoomManager) StartSession(
return nil
}
// SIGNALLING-V2-TODO: consolidate common parts beteen this and `StartSession`
func (r *RoomManager) HandleConnect(
ctx context.Context,
grants *auth.ClaimGrants,
rscr *rpc.RelaySignalv2ConnectRequest,
) (*rpc.RelaySignalv2ConnectResponse, error) {
sessionStartTime := time.Now()
createRoom := rscr.CreateRoom
room, err := r.getOrCreateRoom(ctx, createRoom)
if err != nil {
return nil, err
}
defer room.Release()
protoRoom, roomInternal := room.ToProto(), room.Internal()
participantIdentity := livekit.ParticipantIdentity(grants.Identity)
// should not error out, error is logged in iceServersForParticipant even if it fails
// since this is used for TURN server credentials, we don't want to fail the request even if there's no TURN for the session
apiKey, _, _ := r.getFirstKeyPair()
/* SIGNALLING-V2-TODO - v2 should not have ICERestart, but leaving reminder here (similar location as `StartSession` code check on this path */
sid := livekit.ParticipantID(guid.New(utils.ParticipantPrefix))
pLogger := rtc.LoggerWithParticipant(
rtc.LoggerWithRoom(logger.GetLogger(), room.Name(), room.ID()),
participantIdentity,
sid,
false,
)
pLogger.Infow(
"starting RTC session",
"room", room.Name(),
"nodeID", r.currentNode.NodeID(),
"numParticipants", room.GetParticipantCount(),
"grants", grants,
"connectRequest", logger.Proto(rscr),
)
clientInfo := rscr.ConnectRequest.ClientInfo
clientConf := r.clientConfManager.GetConfiguration(clientInfo)
rtcConf := *r.rtcConfig
rtcConf.SetBufferFactory(room.GetBufferFactory())
if rscr.ConnectRequest.ConnectionSettings.DisableIceLite {
rtcConf.SettingEngine.SetLite(false)
}
// default allow forceTCP
allowFallback := true
if r.config.RTC.AllowTCPFallback != nil {
allowFallback = *r.config.RTC.AllowTCPFallback
}
// default do not force full reconnect on a publication error
reconnectOnPublicationError := false
if r.config.RTC.ReconnectOnPublicationError != nil {
reconnectOnPublicationError = *r.config.RTC.ReconnectOnPublicationError
}
// default do not force full reconnect on a subscription error
reconnectOnSubscriptionError := false
if r.config.RTC.ReconnectOnSubscriptionError != nil {
reconnectOnSubscriptionError = *r.config.RTC.ReconnectOnSubscriptionError
}
// default do not force full reconnect on a data channel error
reconnectOnDataChannelError := false
if r.config.RTC.ReconnectOnDataChannelError != nil {
reconnectOnDataChannelError = *r.config.RTC.ReconnectOnDataChannelError
}
subscriberAllowPause := r.config.RTC.CongestionControl.AllowPause
if rscr.ConnectRequest.ConnectionSettings.SubscriberAllowPause != nil {
subscriberAllowPause = *rscr.ConnectRequest.ConnectionSettings.SubscriberAllowPause
}
participant, err := rtc.NewParticipant(rtc.ParticipantParams{
Identity: participantIdentity,
Name: livekit.ParticipantName(grants.Name),
SID: sid,
Config: &rtcConf,
AudioConfig: r.config.Audio,
VideoConfig: r.config.Video,
LimitConfig: r.config.Limit,
ProtocolVersion: types.ProtocolVersion(clientInfo.Protocol),
SessionStartTime: sessionStartTime,
Telemetry: r.telemetry,
Trailer: room.Trailer(),
PLIThrottleConfig: r.config.RTC.PLIThrottle,
CongestionControlConfig: r.config.RTC.CongestionControl,
PublishEnabledCodecs: protoRoom.EnabledCodecs,
SubscribeEnabledCodecs: protoRoom.EnabledCodecs,
Grants: grants,
Logger: pLogger,
Reporter: roomobs.NewNoopParticipantSessionReporter(),
ClientConf: clientConf,
ClientInfo: rtc.ClientInfo{ClientInfo: clientInfo},
// SIGNALLING-V@-TODO Region: pi.Region,
AdaptiveStream: rscr.ConnectRequest.ConnectionSettings.AdaptiveStream,
AllowTCPFallback: allowFallback,
TURNSEnabled: r.config.IsTURNSEnabled(),
ParticipantHelper: &roomManagerParticipantHelper{
room: room,
codecRegressionThreshold: r.config.Video.CodecRegressionThreshold,
},
ReconnectOnPublicationError: reconnectOnPublicationError,
ReconnectOnSubscriptionError: reconnectOnSubscriptionError,
ReconnectOnDataChannelError: reconnectOnDataChannelError,
VersionGenerator: r.versionGenerator,
SubscriberAllowPause: subscriberAllowPause,
SubscriptionLimitAudio: r.config.Limit.SubscriptionLimitAudio,
SubscriptionLimitVideo: r.config.Limit.SubscriptionLimitVideo,
PlayoutDelay: roomInternal.GetPlayoutDelay(),
SyncStreams: roomInternal.GetSyncStreams(),
ForwardStats: r.forwardStats,
MetricConfig: r.config.Metric,
DataChannelMaxBufferedAmount: r.config.RTC.DataChannelMaxBufferedAmount,
DatachannelSlowThreshold: r.config.RTC.DatachannelSlowThreshold,
FireOnTrackBySdp: true,
SynchronousLocalCandidatesMode: true,
})
if err != nil {
return nil, err
}
iceConfig := r.setIceConfig(room.Name(), participant)
// join room
opts := rtc.ParticipantOptions{
AutoSubscribe: rscr.ConnectRequest.ConnectionSettings.AutoSubscribe,
}
iceServers := r.iceServersForParticipant(
apiKey,
participant,
iceConfig.PreferenceSubscriber == livekit.ICECandidateType_ICT_TLS,
)
connectResponse, err := room.Joinv2(participant, &opts, iceServers)
if err != nil {
pLogger.Errorw("could not join room", err)
_ = participant.Close(true, types.ParticipantCloseReasonJoinFailed, false)
return nil, err
}
if err = r.roomStore.StoreParticipant(ctx, room.Name(), participant.ToProto()); err != nil {
pLogger.Errorw("could not store participant", err)
}
persistRoomForParticipantCount := func(proto *livekit.Room) {
if !participant.Hidden() && !room.IsClosed() {
err = r.roomStore.StoreRoom(ctx, proto, room.Internal())
if err != nil {
logger.Errorw("could not store room", err)
}
}
}
// update room store with new numParticipants
persistRoomForParticipantCount(room.ToProto())
clientMeta := &livekit.AnalyticsClientMeta{
Region: r.currentNode.Region(),
Node: string(r.currentNode.NodeID()),
}
r.telemetry.ParticipantJoined(ctx, protoRoom, participant.ToProto(), clientInfo, clientMeta, true)
participant.OnClose(func(p types.LocalParticipant) {
if err := r.roomStore.DeleteParticipant(ctx, room.Name(), p.Identity()); err != nil {
pLogger.Errorw("could not delete participant", err)
}
// update room store with new numParticipants
proto := room.ToProto()
persistRoomForParticipantCount(proto)
r.telemetry.ParticipantLeft(ctx, proto, p.ToProto(), true)
})
participant.OnClaimsChanged(func(participant types.LocalParticipant) {
pLogger.Debugw("refreshing client token after claims change")
if err := r.refreshToken(participant); err != nil {
pLogger.Errorw("could not refresh token", err)
}
})
participant.OnICEConfigChanged(func(participant types.LocalParticipant, iceConfig *livekit.ICEConfig) {
r.iceConfigCache.Put(iceConfigCacheKey{room.Name(), participant.Identity()}, iceConfig)
})
return &rpc.RelaySignalv2ConnectResponse{
ConnectResponse: connectResponse,
}, nil
}
// create the actual room object, to be used on RTC node
func (r *RoomManager) getOrCreateRoom(ctx context.Context, createRoom *livekit.CreateRoomRequest) (*rtc.Room, error) {
roomName := livekit.RoomName(createRoom.Name)
@@ -1041,6 +1234,8 @@ func iceServerForStunServers(servers []string) *livekit.ICEServer {
return iceServer
}
// ------------------------------------
type roomManagerParticipantHelper struct {
room *rtc.Room
codecRegressionThreshold int
+30 -30
View File
@@ -201,7 +201,7 @@ func (s *RTCRestService) validateCreate(r *http.Request) (*createRequest, int, e
func (s *RTCRestService) handleCreate(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/sdp" {
handleError("Create", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
s.handleError("Create", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
@@ -209,25 +209,25 @@ func (s *RTCRestService) handleCreate(w http.ResponseWriter, r *http.Request) {
req, status, err := s.validateCreate(r)
if err != nil {
handleError("Create", w, r, status, err)
s.handleError("Create", w, r, status, err)
return
}
if err := s.roomAllocator.SelectRoomNode(r.Context(), req.RoomName, ""); err != nil {
handleError("Create", w, r, http.StatusInternalServerError, err)
s.handleError("Create", w, r, http.StatusInternalServerError, err)
return
}
rtcNode, err := s.router.GetNodeForRoom(r.Context(), req.RoomName)
if err != nil {
handleError("Create", w, r, http.StatusInternalServerError, err)
s.handleError("Create", w, r, http.StatusInternalServerError, err)
return
}
connID := livekit.ConnectionID(guid.New("CO_"))
starSession, err := req.ParticipantInit.ToStartSession(req.RoomName, connID)
if err != nil {
handleError("Create", w, r, http.StatusInternalServerError, err)
s.handleError("Create", w, r, http.StatusInternalServerError, err)
return
}
@@ -244,7 +244,7 @@ func (s *RTCRestService) handleCreate(w http.ResponseWriter, r *http.Request) {
SubscribedParticipantTracks: subscribedParticipantTracks,
})
if err != nil {
handleError("Create", w, r, http.StatusServiceUnavailable, err)
s.handleError("Create", w, r, http.StatusServiceUnavailable, err)
return
}
@@ -331,20 +331,20 @@ func (s *RTCRestService) iceTrickle(
if errors.As(err, &pe) {
switch pe.Code() {
case psrpc.NotFound:
handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error()))
case psrpc.InvalidArgument:
switch pe.Error() {
case rtc.ErrInvalidSDPFragment.Error(), rtc.ErrMidMismatch.Error(), rtc.ErrICECredentialMismatch.Error():
handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error()))
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
} else {
handleError("Patch", w, r, http.StatusInternalServerError, nil)
s.handleError("Patch", w, r, http.StatusInternalServerError, nil)
}
return
}
@@ -383,20 +383,20 @@ func (s *RTCRestService) iceRestart(
if errors.As(err, &pe) {
switch pe.Code() {
case psrpc.NotFound:
handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusNotFound, errors.New(pe.Error()))
case psrpc.InvalidArgument:
switch pe.Error() {
case rtc.ErrInvalidSDPFragment.Error():
handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusBadRequest, errors.New(pe.Error()))
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
default:
handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
s.handleError("Patch", w, r, http.StatusInternalServerError, errors.New(pe.Error()))
}
} else {
handleError("Patch", w, r, http.StatusInternalServerError, nil)
s.handleError("Patch", w, r, http.StatusInternalServerError, nil)
}
return
}
@@ -419,7 +419,7 @@ func (s *RTCRestService) iceRestart(
func (s *RTCRestService) handleParticipantPatch(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/trickle-ice-sdpfrag" {
handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
s.handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
@@ -428,38 +428,38 @@ func (s *RTCRestService) handleParticipantPatch(w http.ResponseWriter, r *http.R
// https://www.rfc-editor.org/rfc/rfc9725.html#name-http-patch-request-usage
ifMatch := r.Header.Get("If-Match")
if ifMatch == "" {
handleError("Patch", w, r, http.StatusPreconditionRequired, errors.New("missing entity tag"))
s.handleError("Patch", w, r, http.StatusPreconditionRequired, errors.New("missing entity tag"))
return
}
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
handleError("Patch", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
s.handleError("Patch", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
return
}
roomName, err := EnsureJoinPermission(r.Context())
if err != nil {
handleError("Patch", w, r, http.StatusUnauthorized, err)
s.handleError("Patch", w, r, http.StatusUnauthorized, err)
return
}
if roomName == "" {
handleError("Patch", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty"))
s.handleError("Patch", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty"))
return
}
if claims.Identity == "" {
handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty"))
s.handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty"))
return
}
pID := livekit.ParticipantID(r.PathValue("participant_id"))
if pID == "" {
handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant ID cannot be empty"))
s.handleError("Patch", w, r, http.StatusUnauthorized, errors.New("participant ID cannot be empty"))
return
}
sdpFragmentBytes, err := ioutil.ReadAll(r.Body)
if err != nil {
handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("body does not have SDP fragment: %s", err))
s.handleError("Patch", w, r, http.StatusBadRequest, fmt.Errorf("body does not have SDP fragment: %s", err))
}
sdpFragment := string(sdpFragmentBytes)
@@ -473,21 +473,21 @@ func (s *RTCRestService) handleParticipantPatch(w http.ResponseWriter, r *http.R
func (s *RTCRestService) handleParticipantDelete(w http.ResponseWriter, r *http.Request) {
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
handleError("Delete", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
s.handleError("Delete", w, r, http.StatusUnauthorized, rtc.ErrPermissionDenied)
return
}
roomName, err := EnsureJoinPermission(r.Context())
if err != nil {
handleError("Delete", w, r, http.StatusUnauthorized, err)
s.handleError("Delete", w, r, http.StatusUnauthorized, err)
return
}
if roomName == "" {
handleError("Delete", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty"))
s.handleError("Delete", w, r, http.StatusUnauthorized, errors.New("room name cannot be empty"))
return
}
if claims.Identity == "" {
handleError("Delete", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty"))
s.handleError("Delete", w, r, http.StatusUnauthorized, errors.New("participant identity cannot be empty"))
return
}
@@ -501,7 +501,7 @@ func (s *RTCRestService) handleParticipantDelete(w http.ResponseWriter, r *http.
},
)
if err != nil {
handleError("Delete", w, r, http.StatusNotFound, err)
s.handleError("Delete", w, r, http.StatusNotFound, err)
return
}
@@ -515,7 +515,7 @@ func (s *RTCRestService) handleParticipantDelete(w http.ResponseWriter, r *http.
w.WriteHeader(http.StatusOK)
}
func handleError(method string, w http.ResponseWriter, r *http.Request, status int, err error) {
func (s *RTCRestService) handleError(method string, w http.ResponseWriter, r *http.Request, status int, err error) {
sutils.GetLogger(r.Context()).Warnw(
fmt.Sprintf("API RTCRest.%s", method), err,
"status", status,
+45 -123
View File
@@ -37,7 +37,6 @@ import (
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/routing/selector"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/telemetry"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
@@ -87,12 +86,13 @@ func NewRTCService(
}
func (s *RTCService) SetupRoutes(mux *http.ServeMux) {
mux.Handle("/rtc", s)
mux.HandleFunc("/rtc/validate", s.validate)
}
func (s *RTCService) validate(w http.ResponseWriter, r *http.Request) {
log := utils.GetLogger(r.Context())
_, _, code, err := s.validateInternal(log, r, true)
lgr := utils.GetLogger(r.Context())
_, _, code, err := s.validateInternal(lgr, r, true)
if err != nil {
HandleError(w, r, code, err)
return
@@ -112,144 +112,66 @@ func decodeAttributes(str string) (map[string]string, error) {
return attrs, nil
}
func (s *RTCService) validateInternal(log logger.Logger, r *http.Request, strict bool) (livekit.RoomName, routing.ParticipantInit, int, error) {
claims := GetGrants(r.Context())
var pi routing.ParticipantInit
func (s *RTCService) validateInternal(lgr logger.Logger, r *http.Request, strict bool) (livekit.RoomName, routing.ParticipantInit, int, error) {
var params ValidateConnectRequestParams
params.publish = r.FormValue("publish")
// require a claim
if claims == nil || claims.Video == nil {
return "", pi, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
onlyName, err := EnsureJoinPermission(r.Context())
if err != nil {
return "", pi, http.StatusUnauthorized, err
}
if claims.Identity == "" {
return "", pi, http.StatusBadRequest, ErrIdentityEmpty
}
if !s.config.Limit.CheckParticipantIdentityLength(claims.Identity) {
return "", pi, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrParticipantIdentityExceedsLimits, s.config.Limit.MaxParticipantIdentityLength)
}
if claims.RoomConfig != nil {
if err := claims.RoomConfig.CheckCredentials(); err != nil {
logger.Warnw("credentials found in token", nil)
// TODO(dz): in a future version, we'll reject these connections
}
}
roomName := livekit.RoomName(r.FormValue("room"))
reconnectParam := r.FormValue("reconnect")
reconnectReason, _ := strconv.Atoi(r.FormValue("reconnect_reason")) // 0 means unknown reason
autoSubParam := r.FormValue("auto_subscribe")
publishParam := r.FormValue("publish")
adaptiveStreamParam := r.FormValue("adaptive_stream")
participantID := r.FormValue("sid")
subscriberAllowPauseParam := r.FormValue("subscriber_allow_pause")
disableICELite := r.FormValue("disable_ice_lite")
attributesStr := r.FormValue("attributes")
if onlyName != "" {
roomName = onlyName
}
if !s.config.Limit.CheckRoomNameLength(string(roomName)) {
return "", pi, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrRoomNameExceedsLimits, s.config.Limit.MaxRoomNameLength)
}
// this is new connection for existing participant - with publish only permissions
if publishParam != "" {
// Make sure grant has GetCanPublish set,
if !claims.Video.GetCanPublish() {
return "", routing.ParticipantInit{}, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
// Make sure by default subscribe is off
claims.Video.SetCanSubscribe(false)
claims.Identity += "#" + publishParam
}
// room allocator validations
err = s.roomAllocator.ValidateCreateRoom(r.Context(), roomName)
if err != nil {
if errors.Is(err, ErrRoomNotFound) {
return "", pi, http.StatusNotFound, err
} else {
return "", pi, http.StatusInternalServerError, err
}
}
region := ""
if router, ok := s.router.(routing.Router); ok {
region = router.GetRegion()
if foundNode, err := router.GetNodeForRoom(r.Context(), roomName); err == nil {
if selector.LimitsReached(s.limits, foundNode.Stats) {
return "", pi, http.StatusServiceUnavailable, rtc.ErrLimitExceeded
}
}
}
createRequest := &livekit.CreateRoomRequest{
Name: string(roomName),
RoomPreset: claims.RoomPreset,
}
SetRoomConfiguration(createRequest, claims.GetRoomConfiguration())
// Add extra attributes to the participant
if attributesStr != "" {
// Make sure grant has GetCanUpdateOwnMetadata set
if !claims.Video.GetCanUpdateOwnMetadata() {
return "", routing.ParticipantInit{}, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
attrs, err := decodeAttributes(attributesStr)
attributesStrParam := r.FormValue("attributes")
if attributesStrParam != "" {
attrs, err := decodeAttributes(attributesStrParam)
if err != nil {
if strict {
return "", pi, http.StatusBadRequest, errors.New("cannot decode attributes")
return "", routing.ParticipantInit{}, http.StatusBadRequest, errors.New("cannot decode attributes")
}
log.Debugw("failed to decode attributes", "error", err)
lgr.Debugw("failed to decode attributes", "error", err)
// attrs will be empty here, so just proceed
}
if len(attrs) != 0 && claims.Attributes == nil {
claims.Attributes = make(map[string]string, len(attrs))
}
for k, v := range attrs {
if v == "" {
continue // do not allow deleting existing attributes
}
claims.Attributes[k] = v
}
params.attributes = attrs
}
pi = routing.ParticipantInit{
Reconnect: boolValue(reconnectParam),
ReconnectReason: livekit.ReconnectReason(reconnectReason),
Identity: livekit.ParticipantIdentity(claims.Identity),
Name: livekit.ParticipantName(claims.Name),
AutoSubscribe: true,
Client: ParseClientInfo(r),
Grants: claims,
Region: region,
CreateRoom: createRequest,
res, code, err := ValidateConnectRequest(
lgr,
r,
s.limits,
params,
s.router,
s.roomAllocator,
)
if err != nil {
return res.roomName, routing.ParticipantInit{}, code, err
}
pi := routing.ParticipantInit{
Reconnect: boolValue(r.FormValue("reconnect")),
Identity: livekit.ParticipantIdentity(res.grants.Identity),
Name: livekit.ParticipantName(res.grants.Name),
Client: ParseClientInfo(r),
Grants: res.grants,
Region: res.region,
CreateRoom: res.createRoomRequest,
AutoSubscribe: true,
AdaptiveStream: boolValue(r.FormValue("adaptive_stream")),
DisableICELite: boolValue(r.FormValue("disable_ice_lite")),
}
reconnectReason, _ := strconv.Atoi(r.FormValue("reconnect_reason")) // 0 means unknown reason
pi.ReconnectReason = livekit.ReconnectReason(reconnectReason)
if pi.Reconnect {
pi.ID = livekit.ParticipantID(participantID)
pi.ID = livekit.ParticipantID(r.FormValue("sid"))
}
if autoSubParam != "" {
pi.AutoSubscribe = boolValue(autoSubParam)
}
if adaptiveStreamParam != "" {
pi.AdaptiveStream = boolValue(adaptiveStreamParam)
if autoSubscribe := r.FormValue("auto_subscribe"); autoSubscribe != "" {
pi.AutoSubscribe = boolValue(autoSubscribe)
}
subscriberAllowPauseParam := r.FormValue("subscriber_allow_pause")
if subscriberAllowPauseParam != "" {
subscriberAllowPause := boolValue(subscriberAllowPauseParam)
pi.SubscriberAllowPause = &subscriberAllowPause
}
if disableICELite != "" {
pi.DisableICELite = boolValue(disableICELite)
}
return roomName, pi, http.StatusOK, nil
return res.roomName, pi, code, err
}
func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+163
View File
@@ -0,0 +1,163 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package service
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
"google.golang.org/protobuf/proto"
)
const (
cRTCv2Path = "/rtc/v2"
)
type RTCv2Service struct {
http.Handler
limits config.LimitConfig
roomAllocator RoomAllocator
router routing.MessageRouter
}
func NewRTCv2Service(
config *config.Config,
roomAllocator RoomAllocator,
router routing.MessageRouter,
) *RTCv2Service {
return &RTCv2Service{
limits: config.Limit,
router: router,
roomAllocator: roomAllocator,
}
}
func (s *RTCv2Service) SetupRoutes(mux *http.ServeMux) {
mux.HandleFunc("POST "+cRTCv2Path, s.handlePost)
}
func (s *RTCv2Service) validateInternal(
lgr logger.Logger,
r *http.Request,
connectRequest *livekit.ConnectRequest,
) (livekit.RoomName, livekit.ParticipantIdentity, *rpc.RelaySignalv2ConnectRequest, int, error) {
params := ValidateConnectRequestParams{
metadata: connectRequest.Metadata,
attributes: connectRequest.ParticipantAttributes,
}
res, code, err := ValidateConnectRequest(
lgr,
r,
s.limits,
params,
s.router,
s.roomAllocator,
)
if err != nil {
return "", "", nil, code, err
}
grantsJson, err := json.Marshal(res.grants)
if err != nil {
return "", "", nil, http.StatusInternalServerError, err
}
AugmentClientInfo(connectRequest.ClientInfo, r)
return res.roomName,
livekit.ParticipantIdentity(res.grants.Identity),
&rpc.RelaySignalv2ConnectRequest{
GrantsJson: string(grantsJson),
CreateRoom: res.createRoomRequest,
ConnectRequest: connectRequest,
},
code,
err
}
func (s *RTCv2Service) handlePost(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-type") != "application/x-protobuf" {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("unsupported content-type: %s", r.Header.Get("Content-type")))
return
}
body, err := ioutil.ReadAll(r.Body)
if err != nil {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("could not read request body: %s", err))
return
}
clientMessage := &livekit.Signalv2ClientMessage{}
err = proto.Unmarshal(body, clientMessage)
if err != nil {
HandleErrorJson(w, r, http.StatusBadRequest, fmt.Errorf("could not unmarshal request: %s", err))
return
}
switch msg := clientMessage.GetMessage().(type) {
case *livekit.Signalv2ClientMessage_ConnectRequest:
roomName, participantIdentity, rscr, code, err := s.validateInternal(logger.GetLogger(), r, msg.ConnectRequest)
if err != nil {
HandleErrorJson(w, r, code, err)
return
}
if err := s.roomAllocator.SelectRoomNode(r.Context(), roomName, ""); err != nil {
HandleErrorJson(w, r, http.StatusInternalServerError, err)
return
}
resp, err := s.router.HandleParticipantConnectRequest(r.Context(), roomName, participantIdentity, rscr)
if err != nil {
HandleErrorJson(w, r, http.StatusInternalServerError, err)
return
}
serverMessage := &livekit.Signalv2ServerMessage{
Message: &livekit.Signalv2ServerMessage_ConnectResponse{
ConnectResponse: resp.ConnectResponse,
},
}
marshalled, err := proto.Marshal(serverMessage)
if err != nil {
HandleErrorJson(w, r, http.StatusInternalServerError, err)
return
}
w.Header().Add("Content-type", "application/x-protobuf")
w.Write(marshalled)
case *livekit.Signalv2ClientMessage_Envelope:
for _, cm := range msg.Envelope.ClientMessages {
switch oneOf := cm.GetMessage().(type) {
case *livekit.Signalv2ClientMessage_ConnectRequest:
logger.Errorw("should not get ConnectRequest in envelope", nil)
default:
logger.Debugw("unhandled message", "message", oneOf)
}
}
}
w.WriteHeader(http.StatusOK)
}
+11 -1
View File
@@ -49,6 +49,7 @@ type LivekitServer struct {
config *config.Config
ioService *IOInfoService
rtcService *RTCService
rtcv2Service *RTCv2Service
rtcRestService *RTCRestService
agentService *AgentService
httpServer *http.Server
@@ -56,6 +57,7 @@ type LivekitServer struct {
router routing.Router
roomManager *RoomManager
signalServer *SignalServer
signalv2Server *Signalv2Server
turnServer *turn.Server
currentNode routing.LocalNode
running atomic.Bool
@@ -71,12 +73,14 @@ func NewLivekitServer(conf *config.Config,
sipService *SIPService,
ioService *IOInfoService,
rtcService *RTCService,
rtcv2Service *RTCv2Service,
rtcRestService *RTCRestService,
agentService *AgentService,
keyProvider auth.KeyProvider,
router routing.Router,
roomManager *RoomManager,
signalServer *SignalServer,
signalv2Server *Signalv2Server,
turnServer *turn.Server,
currentNode routing.LocalNode,
) (s *LivekitServer, err error) {
@@ -84,11 +88,13 @@ func NewLivekitServer(conf *config.Config,
config: conf,
ioService: ioService,
rtcService: rtcService,
rtcv2Service: rtcv2Service,
rtcRestService: rtcRestService,
agentService: agentService,
router: router,
roomManager: roomManager,
signalServer: signalServer,
signalv2Server: signalv2Server,
// turn server starts automatically
turnServer: turnServer,
currentNode: currentNode,
@@ -143,8 +149,8 @@ func NewLivekitServer(conf *config.Config,
xtwirp.RegisterServer(mux, egressServer)
xtwirp.RegisterServer(mux, ingressServer)
xtwirp.RegisterServer(mux, sipServer)
mux.Handle("/rtc", rtcService)
rtcService.SetupRoutes(mux)
rtcv2Service.SetupRoutes(mux)
rtcRestService.SetupRoutes(mux)
mux.Handle("/agent", agentService)
mux.HandleFunc("/", s.defaultHandler)
@@ -275,6 +281,10 @@ func (s *LivekitServer) Start() error {
return err
}
if err := s.signalv2Server.Start(); err != nil {
return err
}
httpGroup := &errgroup.Group{}
for _, ln := range listeners {
l := ln
@@ -0,0 +1,200 @@
// Code generated by counterfeiter. DO NOT EDIT.
package servicefakes
import (
"context"
"sync"
"github.com/livekit/livekit-server/pkg/service"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
)
type FakeConnectHandler struct {
HandleConnectStub func(context.Context, logger.Logger, *auth.ClaimGrants, *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error)
handleConnectMutex sync.RWMutex
handleConnectArgsForCall []struct {
arg1 context.Context
arg2 logger.Logger
arg3 *auth.ClaimGrants
arg4 *rpc.RelaySignalv2ConnectRequest
}
handleConnectReturns struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}
handleConnectReturnsOnCall map[int]struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}
LoggerStub func(context.Context) logger.Logger
loggerMutex sync.RWMutex
loggerArgsForCall []struct {
arg1 context.Context
}
loggerReturns struct {
result1 logger.Logger
}
loggerReturnsOnCall map[int]struct {
result1 logger.Logger
}
invocations map[string][][]interface{}
invocationsMutex sync.RWMutex
}
func (fake *FakeConnectHandler) HandleConnect(arg1 context.Context, arg2 logger.Logger, arg3 *auth.ClaimGrants, arg4 *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error) {
fake.handleConnectMutex.Lock()
ret, specificReturn := fake.handleConnectReturnsOnCall[len(fake.handleConnectArgsForCall)]
fake.handleConnectArgsForCall = append(fake.handleConnectArgsForCall, struct {
arg1 context.Context
arg2 logger.Logger
arg3 *auth.ClaimGrants
arg4 *rpc.RelaySignalv2ConnectRequest
}{arg1, arg2, arg3, arg4})
stub := fake.HandleConnectStub
fakeReturns := fake.handleConnectReturns
fake.recordInvocation("HandleConnect", []interface{}{arg1, arg2, arg3, arg4})
fake.handleConnectMutex.Unlock()
if stub != nil {
return stub(arg1, arg2, arg3, arg4)
}
if specificReturn {
return ret.result1, ret.result2
}
return fakeReturns.result1, fakeReturns.result2
}
func (fake *FakeConnectHandler) HandleConnectCallCount() int {
fake.handleConnectMutex.RLock()
defer fake.handleConnectMutex.RUnlock()
return len(fake.handleConnectArgsForCall)
}
func (fake *FakeConnectHandler) HandleConnectCalls(stub func(context.Context, logger.Logger, *auth.ClaimGrants, *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error)) {
fake.handleConnectMutex.Lock()
defer fake.handleConnectMutex.Unlock()
fake.HandleConnectStub = stub
}
func (fake *FakeConnectHandler) HandleConnectArgsForCall(i int) (context.Context, logger.Logger, *auth.ClaimGrants, *rpc.RelaySignalv2ConnectRequest) {
fake.handleConnectMutex.RLock()
defer fake.handleConnectMutex.RUnlock()
argsForCall := fake.handleConnectArgsForCall[i]
return argsForCall.arg1, argsForCall.arg2, argsForCall.arg3, argsForCall.arg4
}
func (fake *FakeConnectHandler) HandleConnectReturns(result1 *rpc.RelaySignalv2ConnectResponse, result2 error) {
fake.handleConnectMutex.Lock()
defer fake.handleConnectMutex.Unlock()
fake.HandleConnectStub = nil
fake.handleConnectReturns = struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}{result1, result2}
}
func (fake *FakeConnectHandler) HandleConnectReturnsOnCall(i int, result1 *rpc.RelaySignalv2ConnectResponse, result2 error) {
fake.handleConnectMutex.Lock()
defer fake.handleConnectMutex.Unlock()
fake.HandleConnectStub = nil
if fake.handleConnectReturnsOnCall == nil {
fake.handleConnectReturnsOnCall = make(map[int]struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
})
}
fake.handleConnectReturnsOnCall[i] = struct {
result1 *rpc.RelaySignalv2ConnectResponse
result2 error
}{result1, result2}
}
func (fake *FakeConnectHandler) Logger(arg1 context.Context) logger.Logger {
fake.loggerMutex.Lock()
ret, specificReturn := fake.loggerReturnsOnCall[len(fake.loggerArgsForCall)]
fake.loggerArgsForCall = append(fake.loggerArgsForCall, struct {
arg1 context.Context
}{arg1})
stub := fake.LoggerStub
fakeReturns := fake.loggerReturns
fake.recordInvocation("Logger", []interface{}{arg1})
fake.loggerMutex.Unlock()
if stub != nil {
return stub(arg1)
}
if specificReturn {
return ret.result1
}
return fakeReturns.result1
}
func (fake *FakeConnectHandler) LoggerCallCount() int {
fake.loggerMutex.RLock()
defer fake.loggerMutex.RUnlock()
return len(fake.loggerArgsForCall)
}
func (fake *FakeConnectHandler) LoggerCalls(stub func(context.Context) logger.Logger) {
fake.loggerMutex.Lock()
defer fake.loggerMutex.Unlock()
fake.LoggerStub = stub
}
func (fake *FakeConnectHandler) LoggerArgsForCall(i int) context.Context {
fake.loggerMutex.RLock()
defer fake.loggerMutex.RUnlock()
argsForCall := fake.loggerArgsForCall[i]
return argsForCall.arg1
}
func (fake *FakeConnectHandler) LoggerReturns(result1 logger.Logger) {
fake.loggerMutex.Lock()
defer fake.loggerMutex.Unlock()
fake.LoggerStub = nil
fake.loggerReturns = struct {
result1 logger.Logger
}{result1}
}
func (fake *FakeConnectHandler) LoggerReturnsOnCall(i int, result1 logger.Logger) {
fake.loggerMutex.Lock()
defer fake.loggerMutex.Unlock()
fake.LoggerStub = nil
if fake.loggerReturnsOnCall == nil {
fake.loggerReturnsOnCall = make(map[int]struct {
result1 logger.Logger
})
}
fake.loggerReturnsOnCall[i] = struct {
result1 logger.Logger
}{result1}
}
func (fake *FakeConnectHandler) Invocations() map[string][][]interface{} {
fake.invocationsMutex.RLock()
defer fake.invocationsMutex.RUnlock()
fake.handleConnectMutex.RLock()
defer fake.handleConnectMutex.RUnlock()
fake.loggerMutex.RLock()
defer fake.loggerMutex.RUnlock()
copiedInvocations := map[string][][]interface{}{}
for key, value := range fake.invocations {
copiedInvocations[key] = value
}
return copiedInvocations
}
func (fake *FakeConnectHandler) recordInvocation(key string, args []interface{}) {
fake.invocationsMutex.Lock()
defer fake.invocationsMutex.Unlock()
if fake.invocations == nil {
fake.invocations = map[string][][]interface{}{}
}
if fake.invocations[key] == nil {
fake.invocations[key] = [][]interface{}{}
}
fake.invocations[key] = append(fake.invocations[key], args)
}
var _ service.ConnectHandler = new(FakeConnectHandler)
+155
View File
@@ -0,0 +1,155 @@
// Copyright 2023 LiveKit, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package service
import (
"context"
"encoding/json"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/telemetry/prometheus"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/livekit/protocol/rpc"
"github.com/livekit/psrpc"
"github.com/livekit/psrpc/pkg/middleware"
)
//counterfeiter:generate . ConnectHandler
type ConnectHandler interface {
Logger(ctx context.Context) logger.Logger
HandleConnect(
ctx context.Context,
lgr logger.Logger,
grants *auth.ClaimGrants,
rscr *rpc.RelaySignalv2ConnectRequest,
) (*rpc.RelaySignalv2ConnectResponse, error)
}
type Signalv2Server struct {
server rpc.TypedSignalv2Server
nodeID livekit.NodeID
}
func NewSignalv2Server(
nodeID livekit.NodeID,
region string,
bus psrpc.MessageBus,
connectHandler ConnectHandler,
) (*Signalv2Server, error) {
s, err := rpc.NewTypedSignalv2Server(
nodeID,
&signalv2Service{region, connectHandler},
bus,
middleware.WithServerMetrics(rpc.PSRPCMetricsObserver{}),
)
if err != nil {
return nil, err
}
return &Signalv2Server{s, nodeID}, nil
}
func (s *Signalv2Server) Start() error {
logger.Debugw("starting relay signal v2 server", "topic", s.nodeID)
return s.server.RegisterAllNodeTopics(s.nodeID)
}
func (r *Signalv2Server) Stop() {
r.server.Kill()
}
// -------------------------------------------------
func NewDefaultSignalv2Server(
currentNode routing.LocalNode,
bus psrpc.MessageBus,
router routing.Router,
roomManager *RoomManager,
) (*Signalv2Server, error) {
return NewSignalv2Server(
currentNode.NodeID(),
currentNode.Region(),
bus,
&defaultSignalv2Handler{currentNode, router, roomManager},
)
}
// -------------------------------------------------
type defaultSignalv2Handler struct {
currentNode routing.LocalNode
router routing.Router
roomManager *RoomManager
}
func (s *defaultSignalv2Handler) Logger(ctx context.Context) logger.Logger {
return utils.GetLogger(ctx)
}
func (s *defaultSignalv2Handler) HandleConnect(
ctx context.Context,
lgr logger.Logger,
grants *auth.ClaimGrants,
rscr *rpc.RelaySignalv2ConnectRequest,
) (*rpc.RelaySignalv2ConnectResponse, error) {
prometheus.IncrementParticipantRtcInit(1)
rtcNode, err := s.router.GetNodeForRoom(ctx, livekit.RoomName(rscr.CreateRoom.Name))
if err != nil {
return nil, err
}
if livekit.NodeID(rtcNode.Id) != s.currentNode.NodeID() {
err = routing.ErrIncorrectRTCNode
lgr.Errorw(
"called participant on incorrect node", err,
"rtcNode", rtcNode,
)
return nil, err
}
return s.roomManager.HandleConnect(ctx, grants, rscr)
}
// ------------------------------------------
type signalv2Service struct {
region string
connectHandler ConnectHandler
}
func (r *signalv2Service) RelaySignalv2Connect(ctx context.Context, rscr *rpc.RelaySignalv2ConnectRequest) (*rpc.RelaySignalv2ConnectResponse, error) {
grants := &auth.ClaimGrants{}
if err := json.Unmarshal([]byte(rscr.GrantsJson), grants); err != nil {
return nil, err
}
lgr := r.connectHandler.Logger(ctx).WithValues(
"room", grants.Video.Room,
"participant", grants.Identity,
// SIGNALLING-V2-TODO - maybe add a connection ID to rscr for tracking/debugging only
)
resp, err := r.connectHandler.HandleConnect(ctx, lgr, grants, rscr)
if err != nil {
lgr.Errorw("could not handle new participant", err)
}
return resp, err
}
// ------------------------------------------
+155 -4
View File
@@ -16,19 +16,27 @@ package service
import (
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"regexp"
"strconv"
"strings"
"github.com/livekit/livekit-server/pkg/config"
"github.com/livekit/livekit-server/pkg/routing"
"github.com/livekit/livekit-server/pkg/routing/selector"
"github.com/livekit/livekit-server/pkg/rtc"
"github.com/livekit/livekit-server/pkg/utils"
"github.com/livekit/protocol/auth"
"github.com/livekit/protocol/livekit"
"github.com/livekit/protocol/logger"
"github.com/ua-parser/uap-go/uaparser"
)
func HandleError(w http.ResponseWriter, r *http.Request, status int, err error, keysAndValues ...interface{}) {
func handleError(w http.ResponseWriter, r *http.Request, status int, err error, keysAndValues ...interface{}) {
keysAndValues = append(keysAndValues, "status", status)
if r != nil && r.URL != nil {
keysAndValues = append(keysAndValues, "method", r.Method, "path", r.URL.Path)
@@ -37,9 +45,22 @@ func HandleError(w http.ResponseWriter, r *http.Request, status int, err error,
utils.GetLogger(r.Context()).WithCallDepth(1).Warnw("error handling request", err, keysAndValues...)
}
w.WriteHeader(status)
}
func HandleError(w http.ResponseWriter, r *http.Request, status int, err error, keysAndValues ...interface{}) {
handleError(w, r, status, err, keysAndValues...)
_, _ = w.Write([]byte(err.Error()))
}
func HandleErrorJson(w http.ResponseWriter, r *http.Request, status int, err error, keysAndValues ...interface{}) {
handleError(w, r, status, err, keysAndValues...)
json.NewEncoder(w).Encode(struct {
Error string `json:"error"`
}{
Error: err.Error(),
})
}
func boolValue(s string) bool {
return s == "1" || s == "true"
}
@@ -127,14 +148,20 @@ func ParseClientInfo(r *http.Request) *livekit.ClientInfo {
ci.DeviceModel = values.Get("device_model")
ci.Network = values.Get("network")
// get real address (forwarded http header) - check Cloudflare headers first, fall back to X-Forwarded-For
ci.Address = GetClientIP(r)
AugmentClientInfo(ci, r)
return ci
}
func AugmentClientInfo(ci *livekit.ClientInfo, req *http.Request) {
ci.Address = GetClientIP(req)
// attempt to parse types for SDKs that support browser as a platform
if ci.Sdk == livekit.ClientInfo_JS ||
ci.Sdk == livekit.ClientInfo_REACT_NATIVE ||
ci.Sdk == livekit.ClientInfo_FLUTTER ||
ci.Sdk == livekit.ClientInfo_UNITY {
client := uaparser.NewFromSaved().Parse(r.UserAgent())
client := uaparser.NewFromSaved().Parse(req.UserAgent())
if ci.Browser == "" {
ci.Browser = client.UserAgent.Family
ci.BrowserVersion = client.UserAgent.ToVersionString()
@@ -152,6 +179,130 @@ func ParseClientInfo(r *http.Request) *livekit.ClientInfo {
ci.DeviceModel = model
}
}
}
return ci
type ValidateConnectRequestParams struct {
roomName livekit.RoomName
publish string
metadata string
attributes map[string]string
}
type ValidateConnectRequestResult struct {
roomName livekit.RoomName
grants *auth.ClaimGrants
region string
createRoomRequest *livekit.CreateRoomRequest
}
func ValidateConnectRequest(
lgr logger.Logger,
r *http.Request,
limitConfig config.LimitConfig,
params ValidateConnectRequestParams,
router routing.MessageRouter,
roomAllocator RoomAllocator,
) (ValidateConnectRequestResult, int, error) {
var res ValidateConnectRequestResult
// require a claim
claims := GetGrants(r.Context())
if claims == nil || claims.Video == nil {
return res, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
roomNameInToken, err := EnsureJoinPermission(r.Context())
if err != nil {
return res, http.StatusUnauthorized, err
}
if claims.Identity == "" {
return res, http.StatusBadRequest, ErrIdentityEmpty
}
if !limitConfig.CheckParticipantIdentityLength(claims.Identity) {
return res, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrParticipantIdentityExceedsLimits, limitConfig.MaxParticipantIdentityLength)
}
if claims.RoomConfig != nil {
if err := claims.RoomConfig.CheckCredentials(); err != nil {
lgr.Warnw("credentials found in token", nil)
// TODO(dz): in a future version, we'll reject these connections
}
}
res.roomName = params.roomName
if roomNameInToken != "" {
res.roomName = roomNameInToken
}
if res.roomName == "" {
return res, http.StatusBadRequest, ErrNoRoomName
}
if !limitConfig.CheckRoomNameLength(string(res.roomName)) {
return res, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrRoomNameExceedsLimits, limitConfig.MaxRoomNameLength)
}
// this is new connection for existing participant - with publish only permissions
if params.publish != "" {
// Make sure grant has GetCanPublish set,
if !claims.Video.GetCanPublish() {
return res, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
// Make sure by default subscribe is off
claims.Video.SetCanSubscribe(false)
claims.Identity += "#" + params.publish
}
// room allocator validations
err = roomAllocator.ValidateCreateRoom(r.Context(), res.roomName)
if err != nil {
if errors.Is(err, ErrRoomNotFound) {
return res, http.StatusNotFound, err
} else {
return res, http.StatusInternalServerError, err
}
}
if router, ok := router.(routing.Router); ok {
res.region = router.GetRegion()
if foundNode, err := router.GetNodeForRoom(r.Context(), res.roomName); err == nil {
if selector.LimitsReached(limitConfig, foundNode.Stats) {
return res, http.StatusServiceUnavailable, rtc.ErrLimitExceeded
}
}
}
createRequest := &livekit.CreateRoomRequest{
Name: string(res.roomName),
RoomPreset: claims.RoomPreset,
}
SetRoomConfiguration(createRequest, claims.GetRoomConfiguration())
res.createRoomRequest = createRequest
if len(params.metadata) != 0 {
// Make sure grant has GetCanUpdateOwnMetadata set
if !claims.Video.GetCanUpdateOwnMetadata() {
return res, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
claims.Metadata = params.metadata
}
// Add extra attributes to the participant
if len(params.attributes) != 0 {
// Make sure grant has GetCanUpdateOwnMetadata set
if !claims.Video.GetCanUpdateOwnMetadata() {
return res, http.StatusUnauthorized, rtc.ErrPermissionDenied
}
if claims.Attributes == nil {
claims.Attributes = make(map[string]string, len(params.attributes))
}
for k, v := range params.attributes {
if v == "" {
continue // do not allow deleting existing attributes
}
claims.Attributes[k] = v
}
}
res.grants = claims
return res, http.StatusOK, nil
}
+2
View File
@@ -77,6 +77,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
NewRoomAllocator,
NewRoomService,
NewRTCService,
NewRTCv2Service,
NewRTCRestService,
NewAgentService,
NewAgentDispatchService,
@@ -84,6 +85,7 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
getAgentStore,
getSignalRelayConfig,
NewDefaultSignalServer,
NewDefaultSignalv2Server,
routing.NewSignalClient,
getRoomConfig,
routing.NewRoomManagerClient,
+13 -8
View File
@@ -89,23 +89,23 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
}
rtcEgressLauncher := NewEgressLauncher(egressClient, ioInfoService, objectStore)
topicFormatter := rpc.NewTopicFormatter()
roomClient, err := rpc.NewTypedRoomClient(clientParams)
v, err := rpc.NewTypedRoomClient(clientParams)
if err != nil {
return nil, err
}
participantClient, err := rpc.NewTypedParticipantClient(clientParams)
v2, err := rpc.NewTypedParticipantClient(clientParams)
if err != nil {
return nil, err
}
roomService, err := NewRoomService(limitConfig, apiConfig, router, roomAllocator, objectStore, rtcEgressLauncher, topicFormatter, roomClient, participantClient)
roomService, err := NewRoomService(limitConfig, apiConfig, router, roomAllocator, objectStore, rtcEgressLauncher, topicFormatter, v, v2)
if err != nil {
return nil, err
}
agentDispatchInternalClient, err := rpc.NewTypedAgentDispatchInternalClient(clientParams)
v3, err := rpc.NewTypedAgentDispatchInternalClient(clientParams)
if err != nil {
return nil, err
}
agentDispatchService := NewAgentDispatchService(agentDispatchInternalClient, topicFormatter, roomAllocator, router)
agentDispatchService := NewAgentDispatchService(v3, topicFormatter, roomAllocator, router)
egressService := NewEgressService(egressClient, rtcEgressLauncher, ioInfoService, roomService)
ingressConfig := getIngressConfig(conf)
ingressClient, err := rpc.NewIngressClient(clientParams)
@@ -120,11 +120,12 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
}
sipService := NewSIPService(sipConfig, nodeID, messageBus, sipClient, sipStore, roomService, telemetryService)
rtcService := NewRTCService(conf, roomAllocator, router, telemetryService)
rtcRestParticipantClient, err := rpc.NewTypedRTCRestParticipantClient(clientParams)
rtCv2Service := NewRTCv2Service(conf, roomAllocator, router)
v4, err := rpc.NewTypedRTCRestParticipantClient(clientParams)
if err != nil {
return nil, err
}
serviceRTCRestService, err := NewRTCRestService(conf, router, roomAllocator, clientParams, topicFormatter, rtcRestParticipantClient)
serviceRTCRestService, err := NewRTCRestService(conf, router, roomAllocator, clientParams, topicFormatter, v4)
if err != nil {
return nil, err
}
@@ -148,12 +149,16 @@ func InitializeServer(conf *config.Config, currentNode routing.LocalNode) (*Live
if err != nil {
return nil, err
}
signalv2Server, err := NewDefaultSignalv2Server(currentNode, messageBus, router, roomManager)
if err != nil {
return nil, err
}
authHandler := getTURNAuthHandlerFunc(turnAuthHandler)
server, err := newInProcessTurnServer(conf, authHandler)
if err != nil {
return nil, err
}
livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, serviceRTCRestService, agentService, keyProvider, router, roomManager, signalServer, server, currentNode)
livekitServer, err := NewLivekitServer(conf, roomService, agentDispatchService, egressService, ingressService, sipService, ioInfoService, rtcService, rtCv2Service, serviceRTCRestService, agentService, keyProvider, router, roomManager, signalServer, signalv2Server, server, currentNode)
if err != nil {
return nil, err
}