// 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" "errors" "fmt" "math/rand" "net/http" "os" "strconv" "sync" "time" "github.com/gorilla/websocket" "github.com/ua-parser/uap-go/uaparser" "go.uber.org/atomic" "golang.org/x/exp/maps" "github.com/livekit/livekit-server/pkg/agent" "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" "github.com/livekit/livekit-server/pkg/utils" "github.com/livekit/protocol/livekit" "github.com/livekit/psrpc" ) const ( // TODO: make these configurable initialBackoffSeconds = 1 maxBackoffSecondsPow = 6 // 64 seconds startConnectionMaxTries = 3 ) type RTCService struct { router routing.MessageRouter roomAllocator RoomAllocator store ServiceStore upgrader websocket.Upgrader currentNode routing.LocalNode config *config.Config isDev bool limits config.LimitConfig parser *uaparser.Parser agentClient agent.Client telemetry telemetry.TelemetryService mu sync.Mutex connections map[*websocket.Conn]struct{} } func NewRTCService( conf *config.Config, ra RoomAllocator, store ServiceStore, router routing.MessageRouter, currentNode routing.LocalNode, agentClient agent.Client, telemetry telemetry.TelemetryService, ) *RTCService { s := &RTCService{ router: router, roomAllocator: ra, store: store, upgrader: websocket.Upgrader{}, currentNode: currentNode, config: conf, isDev: conf.Development, limits: conf.Limit, parser: uaparser.NewFromSaved(), agentClient: agentClient, telemetry: telemetry, connections: map[*websocket.Conn]struct{}{}, } // allow connections from any origin, since script may be hosted anywhere // security is enforced by access tokens s.upgrader.CheckOrigin = func(r *http.Request) bool { return true } return s } func (s *RTCService) Validate(w http.ResponseWriter, r *http.Request) { _, _, code, err := s.validate(r) if err != nil { handleError(w, r, code, err) return } _, _ = w.Write([]byte("success")) } func (s *RTCService) validate(r *http.Request) (livekit.RoomName, routing.ParticipantInit, int, error) { claims := GetGrants(r.Context()) var pi routing.ParticipantInit // 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 limit := s.config.Limit.MaxParticipantIdentityLength; limit > 0 && len(claims.Identity) > limit { return "", pi, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrParticipantIdentityExceedsLimits, limit) } 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") if onlyName != "" { roomName = onlyName } if limit := s.config.Limit.MaxRoomNameLength; limit > 0 && len(roomName) > limit { return "", pi, http.StatusBadRequest, fmt.Errorf("%w: max length %d", ErrRoomNameExceedsLimits, limit) } // 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 } } } pi = routing.ParticipantInit{ Reconnect: boolValue(reconnectParam), ReconnectReason: livekit.ReconnectReason(reconnectReason), Identity: livekit.ParticipantIdentity(claims.Identity), Name: livekit.ParticipantName(claims.Name), AutoSubscribe: true, Client: s.ParseClientInfo(r), Grants: claims, Region: region, CreateRoom: &livekit.CreateRoomRequest{ Name: string(roomName), ConfigName: GetRoomConfiguration(r.Context()), }, } if pi.Reconnect { pi.ID = livekit.ParticipantID(participantID) } if autoSubParam != "" { pi.AutoSubscribe = boolValue(autoSubParam) } if adaptiveStreamParam != "" { pi.AdaptiveStream = boolValue(adaptiveStreamParam) } if subscriberAllowPauseParam != "" { subscriberAllowPause := boolValue(subscriberAllowPauseParam) pi.SubscriberAllowPause = &subscriberAllowPause } if disableICELite != "" { pi.DisableICELite = boolValue(disableICELite) } return roomName, pi, http.StatusOK, nil } func (s *RTCService) ServeHTTP(w http.ResponseWriter, r *http.Request) { // reject non websocket requests if !websocket.IsWebSocketUpgrade(r) { w.WriteHeader(404) return } roomName, pi, code, err := s.validate(r) if err != nil { handleError(w, r, code, err) return } loggerFields := []any{ "participant", pi.Identity, "pID", pi.ID, "room", roomName, "remote", false, } pLogger := utils.GetLogger(r.Context()).WithValues(loggerFields...) // give it a few attempts to start session var cr connectionResult var initialResponse *livekit.SignalResponse for attempt := 0; attempt < startConnectionMaxTries && r.Context().Err() == nil; attempt++ { connectionTimeout := 3 * time.Second * time.Duration(attempt+1) ctx := utils.ContextWithAttempt(r.Context(), attempt) cr, initialResponse, err = s.startConnection(ctx, roomName, pi, connectionTimeout) if err == nil || errors.Is(err, context.Canceled) { break } if attempt < startConnectionMaxTries-1 { // exponential backoff delay. powers of 2. backoffDelay := time.NewTimer(time.Duration(initialBackoffSeconds<