1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
|
/**
* Standalone signaling server for the Nextcloud Spreed app.
* Copyright (C) 2020 struktur AG
*
* @author Joachim Bauch <bauch@struktur.de>
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package main
import (
"context"
"fmt"
"log"
"sync"
"sync/atomic"
"time"
signaling "github.com/strukturag/nextcloud-spreed-signaling"
)
const (
// Sessions expire if they have not been used for one minute.
sessionExpirationTime = time.Minute
)
type remotePublisherData struct {
hostname string
port int
rtcpPort int
}
type ProxySession struct {
proxy *ProxyServer
id string
sid uint64
lastUsed atomic.Int64
ctx context.Context
closeFunc context.CancelFunc
clientLock sync.Mutex
client *ProxyClient
pendingMessages []*signaling.ProxyServerMessage
publishersLock sync.Mutex
publishers map[string]signaling.McuPublisher
publisherIds map[signaling.McuPublisher]string
subscribersLock sync.Mutex
subscribers map[string]signaling.McuSubscriber
subscriberIds map[signaling.McuSubscriber]string
remotePublishersLock sync.Mutex
remotePublishers map[signaling.McuPublisher]map[string]*remotePublisherData
}
func NewProxySession(proxy *ProxyServer, sid uint64, id string) *ProxySession {
ctx, closeFunc := context.WithCancel(context.Background())
result := &ProxySession{
proxy: proxy,
id: id,
sid: sid,
ctx: ctx,
closeFunc: closeFunc,
publishers: make(map[string]signaling.McuPublisher),
publisherIds: make(map[signaling.McuPublisher]string),
subscribers: make(map[string]signaling.McuSubscriber),
subscriberIds: make(map[signaling.McuSubscriber]string),
}
result.MarkUsed()
return result
}
func (s *ProxySession) Context() context.Context {
return s.ctx
}
func (s *ProxySession) PublicId() string {
return s.id
}
func (s *ProxySession) Sid() uint64 {
return s.sid
}
func (s *ProxySession) LastUsed() time.Time {
lastUsed := s.lastUsed.Load()
return time.Unix(0, lastUsed)
}
func (s *ProxySession) IsExpired() bool {
expiresAt := s.LastUsed().Add(sessionExpirationTime)
return expiresAt.Before(time.Now())
}
func (s *ProxySession) MarkUsed() {
now := time.Now()
s.lastUsed.Store(now.UnixNano())
}
func (s *ProxySession) Close() {
prev := s.SetClient(nil)
if prev != nil {
reason := "session_closed"
if s.IsExpired() {
reason = "session_expired"
}
prev.SendMessage(&signaling.ProxyServerMessage{
Type: "bye",
Bye: &signaling.ByeProxyServerMessage{
Reason: reason,
},
})
}
s.closeFunc()
s.clearPublishers()
s.clearSubscribers()
s.clearRemotePublishers()
s.proxy.DeleteSession(s.Sid())
}
func (s *ProxySession) SetClient(client *ProxyClient) *ProxyClient {
s.clientLock.Lock()
prev := s.client
s.client = client
var messages []*signaling.ProxyServerMessage
if client != nil {
messages, s.pendingMessages = s.pendingMessages, nil
}
s.clientLock.Unlock()
if prev != nil {
prev.SetSession(nil)
}
if client != nil {
s.MarkUsed()
client.SetSession(s)
for _, msg := range messages {
client.SendMessage(msg)
}
}
return prev
}
func (s *ProxySession) OnUpdateOffer(client signaling.McuClient, offer map[string]interface{}) {
id := s.proxy.GetClientId(client)
if id == "" {
log.Printf("Received offer %+v from unknown %s client %s (%+v)", offer, client.StreamType(), client.Id(), client)
return
}
msg := &signaling.ProxyServerMessage{
Type: "payload",
Payload: &signaling.PayloadProxyServerMessage{
Type: "offer",
ClientId: id,
Payload: map[string]interface{}{
"offer": offer,
},
},
}
s.sendMessage(msg)
}
func (s *ProxySession) OnIceCandidate(client signaling.McuClient, candidate interface{}) {
id := s.proxy.GetClientId(client)
if id == "" {
log.Printf("Received candidate %+v from unknown %s client %s (%+v)", candidate, client.StreamType(), client.Id(), client)
return
}
msg := &signaling.ProxyServerMessage{
Type: "payload",
Payload: &signaling.PayloadProxyServerMessage{
Type: "candidate",
ClientId: id,
Payload: map[string]interface{}{
"candidate": candidate,
},
},
}
s.sendMessage(msg)
}
func (s *ProxySession) sendMessage(message *signaling.ProxyServerMessage) {
var client *ProxyClient
s.clientLock.Lock()
client = s.client
if client == nil {
s.pendingMessages = append(s.pendingMessages, message)
}
s.clientLock.Unlock()
if client != nil {
client.SendMessage(message)
}
}
func (s *ProxySession) OnIceCompleted(client signaling.McuClient) {
id := s.proxy.GetClientId(client)
if id == "" {
log.Printf("Received ice completed event from unknown %s client %s (%+v)", client.StreamType(), client.Id(), client)
return
}
msg := &signaling.ProxyServerMessage{
Type: "event",
Event: &signaling.EventProxyServerMessage{
Type: "ice-completed",
ClientId: id,
},
}
s.sendMessage(msg)
}
func (s *ProxySession) SubscriberSidUpdated(subscriber signaling.McuSubscriber) {
id := s.proxy.GetClientId(subscriber)
if id == "" {
log.Printf("Received subscriber sid updated event from unknown %s subscriber %s (%+v)", subscriber.StreamType(), subscriber.Id(), subscriber)
return
}
msg := &signaling.ProxyServerMessage{
Type: "event",
Event: &signaling.EventProxyServerMessage{
Type: "subscriber-sid-updated",
ClientId: id,
Sid: subscriber.Sid(),
},
}
s.sendMessage(msg)
}
func (s *ProxySession) PublisherClosed(publisher signaling.McuPublisher) {
if id := s.DeletePublisher(publisher); id != "" {
if s.proxy.DeleteClient(id, publisher) {
statsPublishersCurrent.WithLabelValues(string(publisher.StreamType())).Dec()
}
msg := &signaling.ProxyServerMessage{
Type: "event",
Event: &signaling.EventProxyServerMessage{
Type: "publisher-closed",
ClientId: id,
},
}
s.sendMessage(msg)
}
}
func (s *ProxySession) SubscriberClosed(subscriber signaling.McuSubscriber) {
if id := s.DeleteSubscriber(subscriber); id != "" {
if s.proxy.DeleteClient(id, subscriber) {
statsSubscribersCurrent.WithLabelValues(string(subscriber.StreamType())).Dec()
}
msg := &signaling.ProxyServerMessage{
Type: "event",
Event: &signaling.EventProxyServerMessage{
Type: "subscriber-closed",
ClientId: id,
},
}
s.sendMessage(msg)
}
}
func (s *ProxySession) StorePublisher(ctx context.Context, id string, publisher signaling.McuPublisher) {
s.publishersLock.Lock()
defer s.publishersLock.Unlock()
s.publishers[id] = publisher
s.publisherIds[publisher] = id
}
func (s *ProxySession) DeletePublisher(publisher signaling.McuPublisher) string {
s.publishersLock.Lock()
defer s.publishersLock.Unlock()
id, found := s.publisherIds[publisher]
if !found {
return ""
}
delete(s.publishers, id)
delete(s.publisherIds, publisher)
delete(s.remotePublishers, publisher)
go s.proxy.PublisherDeleted(publisher)
return id
}
func (s *ProxySession) StoreSubscriber(ctx context.Context, id string, subscriber signaling.McuSubscriber) {
s.subscribersLock.Lock()
defer s.subscribersLock.Unlock()
s.subscribers[id] = subscriber
s.subscriberIds[subscriber] = id
}
func (s *ProxySession) DeleteSubscriber(subscriber signaling.McuSubscriber) string {
s.subscribersLock.Lock()
defer s.subscribersLock.Unlock()
id, found := s.subscriberIds[subscriber]
if !found {
return ""
}
delete(s.subscribers, id)
delete(s.subscriberIds, subscriber)
return id
}
func (s *ProxySession) clearPublishers() {
s.publishersLock.Lock()
defer s.publishersLock.Unlock()
go func(publishers map[string]signaling.McuPublisher) {
for id, publisher := range publishers {
if s.proxy.DeleteClient(id, publisher) {
statsPublishersCurrent.WithLabelValues(string(publisher.StreamType())).Dec()
}
publisher.Close(context.Background())
}
}(s.publishers)
// Can't use clear(...) here as the map is processed by the goroutine above.
s.publishers = make(map[string]signaling.McuPublisher)
clear(s.publisherIds)
}
func (s *ProxySession) clearRemotePublishers() {
s.remotePublishersLock.Lock()
defer s.remotePublishersLock.Unlock()
go func(remotePublishers map[signaling.McuPublisher]map[string]*remotePublisherData) {
for publisher, entries := range remotePublishers {
for _, data := range entries {
if err := publisher.UnpublishRemote(context.Background(), s.PublicId(), data.hostname, data.port, data.rtcpPort); err != nil {
log.Printf("Error unpublishing %s %s from remote %s: %s", publisher.StreamType(), publisher.Id(), data.hostname, err)
}
}
}
}(s.remotePublishers)
s.remotePublishers = nil
}
func (s *ProxySession) clearSubscribers() {
s.publishersLock.Lock()
defer s.publishersLock.Unlock()
go func(subscribers map[string]signaling.McuSubscriber) {
for id, subscriber := range subscribers {
if s.proxy.DeleteClient(id, subscriber) {
statsSubscribersCurrent.WithLabelValues(string(subscriber.StreamType())).Dec()
}
subscriber.Close(context.Background())
}
}(s.subscribers)
// Can't use clear(...) here as the map is processed by the goroutine above.
s.subscribers = make(map[string]signaling.McuSubscriber)
clear(s.subscriberIds)
}
func (s *ProxySession) NotifyDisconnected() {
s.clearPublishers()
s.clearSubscribers()
s.clearRemotePublishers()
}
func (s *ProxySession) AddRemotePublisher(publisher signaling.McuPublisher, hostname string, port int, rtcpPort int) bool {
s.remotePublishersLock.Lock()
defer s.remotePublishersLock.Unlock()
remote, found := s.remotePublishers[publisher]
if !found {
remote = make(map[string]*remotePublisherData)
if s.remotePublishers == nil {
s.remotePublishers = make(map[signaling.McuPublisher]map[string]*remotePublisherData)
}
s.remotePublishers[publisher] = remote
}
key := fmt.Sprintf("%s:%d%d", hostname, port, rtcpPort)
if _, found := remote[key]; found {
return false
}
data := &remotePublisherData{
hostname: hostname,
port: port,
rtcpPort: rtcpPort,
}
remote[key] = data
return true
}
func (s *ProxySession) RemoveRemotePublisher(publisher signaling.McuPublisher, hostname string, port int, rtcpPort int) {
s.remotePublishersLock.Lock()
defer s.remotePublishersLock.Unlock()
remote, found := s.remotePublishers[publisher]
if !found {
return
}
key := fmt.Sprintf("%s:%d%d", hostname, port, rtcpPort)
delete(remote, key)
if len(remote) == 0 {
delete(s.remotePublishers, publisher)
if len(s.remotePublishers) == 0 {
s.remotePublishers = nil
}
}
}
func (s *ProxySession) OnPublisherDeleted(publisher signaling.McuPublisher) {
s.remotePublishersLock.Lock()
defer s.remotePublishersLock.Unlock()
delete(s.remotePublishers, publisher)
}
|