直播:后台 JWT 推流、前台画中画;WebRTC 服务与 Nginx WebSocket 代理

Made-with: Cursor
This commit is contained in:
whm
2026-03-25 15:00:14 +08:00
parent b83ec91b1a
commit 7811adca66
1050 changed files with 146524 additions and 37 deletions

28
server/vendor/github.com/pion/srtp/v2/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,28 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
### JetBrains IDE ###
#####################
.idea/
### Emacs Temporary Files ###
#############################
*~
### Folders ###
###############
bin/
vendor/
node_modules/
### Files ###
#############
*.ivf
*.ogg
tags
cover.out
*.sw[poe]
*.wasm
examples/sfu-ws/cert.pem
examples/sfu-ws/key.pem
wasm_exec.js

137
server/vendor/github.com/pion/srtp/v2/.golangci.yml generated vendored Normal file
View File

@@ -0,0 +1,137 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
linters-settings:
govet:
check-shadowing: true
misspell:
locale: US
exhaustive:
default-signifies-exhaustive: true
gomodguard:
blocked:
modules:
- github.com/pkg/errors:
recommendations:
- errors
forbidigo:
forbid:
- ^fmt.Print(f|ln)?$
- ^log.(Panic|Fatal|Print)(f|ln)?$
- ^os.Exit$
- ^panic$
- ^print(ln)?$
linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- contextcheck # check the function whether use a non-inherited context
- decorder # check declaration order and count of types, constants, variables and functions
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- exhaustive # check exhaustiveness of enum switch statements
- exportloopref # checks for pointers to enclosing loop variables
- forbidigo # Forbids identifiers
- forcetypeassert # finds forced type assertions
- gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- godox # Tool for detection of FIXME, TODO and other comment keywords
- goerr113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # noctx finds sending http request without context.Context
- predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- containedctx # containedctx is a linter that detects struct contained context.Context field
- cyclop # checks function and package cyclomatic complexity
- exhaustivestruct # Checks if all struct's fields are initialized
- funlen # Tool for detection of long functions
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- gomnd # An analyzer to detect magic numbers.
- ifshort # Checks that your code uses short syntax for if-statements whenever possible
- ireturn # Accept Interfaces, Return Concrete Types
- lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- maligned # Tool to detect Go structs that would take less memory if their fields were sorted
- nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- varnamelen # checks that the length of a variable's name matches its scope
- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines!
issues:
exclude-use-default: false
exclude-rules:
# Allow complex tests, better to be self contained
- path: _test\.go
linters:
- gocognit
- forbidigo
# Allow complex main function in examples
- path: examples
text: "of func `main` is high"
linters:
- gocognit
# Allow forbidden identifiers in examples
- path: examples
linters:
- forbidigo
# Allow forbidden identifiers in CLI commands
- path: cmd
linters:
- forbidigo
run:
skip-dirs-use-default: false

View File

@@ -0,0 +1,5 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
builds:
- skip: true

37
server/vendor/github.com/pion/srtp/v2/AUTHORS.txt generated vendored Normal file
View File

@@ -0,0 +1,37 @@
# Thank you to everyone that made Pion possible. If you are interested in contributing
# we would love to have you https://github.com/pion/webrtc/wiki/Contributing
#
# This file is auto generated, using git to list all individuals contributors.
# see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting
adamroach <adam@nostrum.com>
Adrian Cable <adrian.cable@gmail.com>
Agniva De Sarker <agnivade@yahoo.co.in>
Antoine Baché <antoine@tenten.app>
Atsushi Watanabe <atsushi.w@ieee.org>
backkem <mail@backkem.me>
chenkaiC4 <chenkaic4@gmail.com>
Chris Hiszpanski <chris@hiszpanski.name>
cnderrauber <zengjie9004@gmail.com>
cszdlt <cszdlt@qq.com>
Hugo Arregui <hugo.arregui@gmail.com>
Jerko Steiner <jerko.steiner@gmail.com>
Juliusz Chroboczek <jch@irif.fr>
Luke Curley <kixelated@gmail.com>
Luke Curley <lcurley@twitch.tv>
Max Hawkins <maxhawkins@gmail.com>
mission-liao <missionaryliao@gmail.com>
Novel Corpse <romandafe94@gmail.com>
OrlandoCo <luisorlando.co@gmail.com>
Patryk <digitalix4@gmail.com>
Patryk Rogalski <digitalix4@gmail.com>
Sean DuBois <seaduboi@amazon.com>
Sean DuBois <sean@siobud.com>
SeongGyu Park <tawny.port@kakaoenterprise.com>
Steffen <post@steffenvogel.de>
Steffen Vogel <post@steffenvogel.de>
Tobias Fridén <tobias.friden@gmail.com>
Woodrow Douglass <wdouglass@carnegierobotics.com>
Yutaka Takeda <yt0916@gmail.com>
# List of contributors not appearing in Git history

9
server/vendor/github.com/pion/srtp/v2/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,9 @@
MIT License
Copyright (c) 2023 The Pion community <https://pion.ly>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

35
server/vendor/github.com/pion/srtp/v2/README.md generated vendored Normal file
View File

@@ -0,0 +1,35 @@
<h1 align="center">
<br>
Pion SRTP
<br>
</h1>
<h4 align="center">A Go implementation of SRTP</h4>
<p align="center">
<a href="https://pion.ly"><img src="https://img.shields.io/badge/pion-srtp-gray.svg?longCache=true&colorB=brightgreen" alt="Pion SRTP"></a>
<a href="https://sourcegraph.com/github.com/pion/srtp?badge"><img src="https://sourcegraph.com/github.com/pion/srtp/-/badge.svg" alt="Sourcegraph Widget"></a>
<a href="https://pion.ly/slack"><img src="https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen" alt="Slack Widget"></a>
<br>
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pion/srtp/test.yaml">
<a href="https://pkg.go.dev/github.com/pion/srtp"><img src="https://pkg.go.dev/badge/github.com/pion/srtp.svg" alt="Go Reference"></a>
<a href="https://codecov.io/gh/pion/srtp"><img src="https://codecov.io/gh/pion/srtp/branch/master/graph/badge.svg" alt="Coverage Status"></a>
<a href="https://goreportcard.com/report/github.com/pion/srtp"><img src="https://goreportcard.com/badge/github.com/pion/srtp" alt="Go Report Card"></a>
<a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-yellow.svg" alt="License: MIT"></a>
</p>
<br>
### Roadmap
The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones.
### Community
Pion has an active community on the [Slack](https://pion.ly/slack).
Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news.
We are always looking to support **your projects**. Please reach out if you have something to build!
If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly)
### Contributing
Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible: [AUTHORS.txt](./AUTHORS.txt)
### License
MIT License - see [LICENSE](LICENSE) for full text

22
server/vendor/github.com/pion/srtp/v2/codecov.yml generated vendored Normal file
View File

@@ -0,0 +1,22 @@
#
# DO NOT EDIT THIS FILE
#
# It is automatically copied from https://github.com/pion/.goassets repository.
#
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
coverage:
status:
project:
default:
# Allow decreasing 2% of total coverage to avoid noise.
threshold: 2%
patch:
default:
target: 70%
only_pulls: true
ignore:
- "examples/*"
- "examples/**/*"

293
server/vendor/github.com/pion/srtp/v2/context.go generated vendored Normal file
View File

@@ -0,0 +1,293 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"bytes"
"fmt"
"github.com/pion/transport/v2/replaydetector"
)
const (
labelSRTPEncryption = 0x00
labelSRTPAuthenticationTag = 0x01
labelSRTPSalt = 0x02
labelSRTCPEncryption = 0x03
labelSRTCPAuthenticationTag = 0x04
labelSRTCPSalt = 0x05
maxSequenceNumber = 65535
maxROC = (1 << 32) - 1
seqNumMedian = 1 << 15
seqNumMax = 1 << 16
srtcpIndexSize = 4
)
// Encrypt/Decrypt state for a single SRTP SSRC
type srtpSSRCState struct {
ssrc uint32
rolloverHasProcessed bool
index uint64
replayDetector replaydetector.ReplayDetector
}
// Encrypt/Decrypt state for a single SRTCP SSRC
type srtcpSSRCState struct {
srtcpIndex uint32
ssrc uint32
replayDetector replaydetector.ReplayDetector
}
// Context represents a SRTP cryptographic context.
// Context can only be used for one-way operations.
// it must either used ONLY for encryption or ONLY for decryption.
// Note that Context does not provide any concurrency protection:
// access to a Context from multiple goroutines requires external
// synchronization.
type Context struct {
cipher srtpCipher
srtpSSRCStates map[uint32]*srtpSSRCState
srtcpSSRCStates map[uint32]*srtcpSSRCState
newSRTCPReplayDetector func() replaydetector.ReplayDetector
newSRTPReplayDetector func() replaydetector.ReplayDetector
profile ProtectionProfile
sendMKI []byte // Master Key Identifier used for encrypting RTP/RTCP packets. Set to nil if MKI is not enabled.
mkis map[string]srtpCipher // Master Key Identifier to cipher mapping. Used for decrypting packets. Empty if MKI is not enabled.
encryptSRTP bool
encryptSRTCP bool
}
// CreateContext creates a new SRTP Context.
//
// CreateContext receives variable number of ContextOption-s.
// Passing multiple options which set the same parameter let the last one valid.
// Following example create SRTP Context with replay protection with window size of 256.
//
// decCtx, err := srtp.CreateContext(key, salt, profile, srtp.SRTPReplayProtection(256))
func CreateContext(masterKey, masterSalt []byte, profile ProtectionProfile, opts ...ContextOption) (c *Context, err error) {
c = &Context{
srtpSSRCStates: map[uint32]*srtpSSRCState{},
srtcpSSRCStates: map[uint32]*srtcpSSRCState{},
profile: profile,
mkis: map[string]srtpCipher{},
}
for _, o := range append(
[]ContextOption{ // Default options
SRTPNoReplayProtection(),
SRTCPNoReplayProtection(),
SRTPEncryption(),
SRTCPEncryption(),
},
opts..., // User specified options
) {
if errOpt := o(c); errOpt != nil {
return nil, errOpt
}
}
c.cipher, err = c.createCipher(c.sendMKI, masterKey, masterSalt, c.encryptSRTP, c.encryptSRTCP)
if err != nil {
return nil, err
}
if len(c.sendMKI) != 0 {
c.mkis[string(c.sendMKI)] = c.cipher
}
return c, nil
}
// AddCipherForMKI adds new MKI with associated masker key and salt. Context must be created with MasterKeyIndicator option
// to enable MKI support. MKI must be unique and have the same length as the one used for creating Context.
// Operation is not thread-safe, you need to provide synchronization with decrypting packets.
func (c *Context) AddCipherForMKI(mki, masterKey, masterSalt []byte) error {
if len(c.mkis) == 0 {
return errMKIIsNotEnabled
}
if len(mki) == 0 || len(mki) != len(c.sendMKI) {
return errInvalidMKILength
}
if _, ok := c.mkis[string(mki)]; ok {
return errMKIAlreadyInUse
}
cipher, err := c.createCipher(mki, masterKey, masterSalt, c.encryptSRTP, c.encryptSRTCP)
if err != nil {
return err
}
c.mkis[string(mki)] = cipher
return nil
}
func (c *Context) createCipher(mki, masterKey, masterSalt []byte, encryptSRTP, encryptSRTCP bool) (srtpCipher, error) {
keyLen, err := c.profile.KeyLen()
if err != nil {
return nil, err
}
saltLen, err := c.profile.SaltLen()
if err != nil {
return nil, err
}
if masterKeyLen := len(masterKey); masterKeyLen != keyLen {
return nil, fmt.Errorf("%w expected(%d) actual(%d)", errShortSrtpMasterKey, masterKey, keyLen)
} else if masterSaltLen := len(masterSalt); masterSaltLen != saltLen {
return nil, fmt.Errorf("%w expected(%d) actual(%d)", errShortSrtpMasterSalt, saltLen, masterSaltLen)
}
switch c.profile {
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return newSrtpCipherAeadAesGcm(c.profile, masterKey, masterSalt, mki, encryptSRTP, encryptSRTCP)
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAes256CmHmacSha1_32, ProtectionProfileAes256CmHmacSha1_80:
return newSrtpCipherAesCmHmacSha1(c.profile, masterKey, masterSalt, mki, encryptSRTP, encryptSRTCP)
case ProtectionProfileNullHmacSha1_32, ProtectionProfileNullHmacSha1_80:
return newSrtpCipherAesCmHmacSha1(c.profile, masterKey, masterSalt, mki, false, false)
default:
return nil, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, c.profile)
}
}
// RemoveMKI removes one of MKIs. You cannot remove last MKI and one used for encrypting RTP/RTCP packets.
// Operation is not thread-safe, you need to provide synchronization with decrypting packets.
func (c *Context) RemoveMKI(mki []byte) error {
if _, ok := c.mkis[string(mki)]; !ok {
return ErrMKINotFound
}
if bytes.Equal(mki, c.sendMKI) {
return errMKIAlreadyInUse
}
delete(c.mkis, string(mki))
return nil
}
// SetSendMKI switches MKI and cipher used for encrypting RTP/RTCP packets.
// Operation is not thread-safe, you need to provide synchronization with encrypting packets.
func (c *Context) SetSendMKI(mki []byte) error {
cipher, ok := c.mkis[string(mki)]
if !ok {
return ErrMKINotFound
}
c.sendMKI = mki
c.cipher = cipher
return nil
}
// https://tools.ietf.org/html/rfc3550#appendix-A.1
func (s *srtpSSRCState) nextRolloverCount(sequenceNumber uint16) (roc uint32, diff int32, overflow bool) {
seq := int32(sequenceNumber)
localRoc := uint32(s.index >> 16)
localSeq := int32(s.index & (seqNumMax - 1))
guessRoc := localRoc
var difference int32
if s.rolloverHasProcessed {
// When localROC is equal to 0, and entering seq-localSeq > seqNumMedian
// judgment, it will cause guessRoc calculation error
if s.index > seqNumMedian {
if localSeq < seqNumMedian {
if seq-localSeq > seqNumMedian {
guessRoc = localRoc - 1
difference = seq - localSeq - seqNumMax
} else {
guessRoc = localRoc
difference = seq - localSeq
}
} else {
if localSeq-seqNumMedian > seq {
guessRoc = localRoc + 1
difference = seq - localSeq + seqNumMax
} else {
guessRoc = localRoc
difference = seq - localSeq
}
}
} else {
// localRoc is equal to 0
difference = seq - localSeq
}
}
return guessRoc, difference, (guessRoc == 0 && localRoc == maxROC)
}
func (s *srtpSSRCState) updateRolloverCount(sequenceNumber uint16, difference int32) {
if !s.rolloverHasProcessed {
s.index |= uint64(sequenceNumber)
s.rolloverHasProcessed = true
return
}
if difference > 0 {
s.index += uint64(difference)
}
}
func (c *Context) getSRTPSSRCState(ssrc uint32) *srtpSSRCState {
s, ok := c.srtpSSRCStates[ssrc]
if ok {
return s
}
s = &srtpSSRCState{
ssrc: ssrc,
replayDetector: c.newSRTPReplayDetector(),
}
c.srtpSSRCStates[ssrc] = s
return s
}
func (c *Context) getSRTCPSSRCState(ssrc uint32) *srtcpSSRCState {
s, ok := c.srtcpSSRCStates[ssrc]
if ok {
return s
}
s = &srtcpSSRCState{
ssrc: ssrc,
replayDetector: c.newSRTCPReplayDetector(),
}
c.srtcpSSRCStates[ssrc] = s
return s
}
// ROC returns SRTP rollover counter value of specified SSRC.
func (c *Context) ROC(ssrc uint32) (uint32, bool) {
s, ok := c.srtpSSRCStates[ssrc]
if !ok {
return 0, false
}
return uint32(s.index >> 16), true
}
// SetROC sets SRTP rollover counter value of specified SSRC.
func (c *Context) SetROC(ssrc uint32, roc uint32) {
s := c.getSRTPSSRCState(ssrc)
s.index = uint64(roc) << 16
s.rolloverHasProcessed = false
}
// Index returns SRTCP index value of specified SSRC.
func (c *Context) Index(ssrc uint32) (uint32, bool) {
s, ok := c.srtcpSSRCStates[ssrc]
if !ok {
return 0, false
}
return s.srtcpIndex, true
}
// SetIndex sets SRTCP index value of specified SSRC.
func (c *Context) SetIndex(ssrc uint32, index uint32) {
s := c.getSRTCPSSRCState(ssrc)
s.srtcpIndex = index % (maxSRTCPIndex + 1)
}

45
server/vendor/github.com/pion/srtp/v2/crypto.go generated vendored Normal file
View File

@@ -0,0 +1,45 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"crypto/cipher"
"github.com/pion/transport/v2/utils/xor"
)
// incrementCTR increments a big-endian integer of arbitrary size.
func incrementCTR(ctr []byte) {
for i := len(ctr) - 1; i >= 0; i-- {
ctr[i]++
if ctr[i] != 0 {
break
}
}
}
// xorBytesCTR performs CTR encryption and decryption.
// It is equivalent to cipher.NewCTR followed by XORKeyStream.
func xorBytesCTR(block cipher.Block, iv []byte, dst, src []byte) error {
if len(iv) != block.BlockSize() {
return errBadIVLength
}
ctr := make([]byte, len(iv))
copy(ctr, iv)
bs := block.BlockSize()
stream := make([]byte, bs)
i := 0
for i < len(src) {
block.Encrypt(stream, ctr)
incrementCTR(ctr)
n := xor.XorBytes(dst[i:], src[i:], stream)
if n == 0 {
break
}
i += n
}
return nil
}

53
server/vendor/github.com/pion/srtp/v2/errors.go generated vendored Normal file
View File

@@ -0,0 +1,53 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"errors"
"fmt"
)
var (
// ErrFailedToVerifyAuthTag is returned when decryption fails due to invalid authentication tag
ErrFailedToVerifyAuthTag = errors.New("failed to verify auth tag")
// ErrMKINotFound is returned when decryption fails due to unknown MKI value in packet
ErrMKINotFound = errors.New("MKI not found")
errDuplicated = errors.New("duplicated packet")
errShortSrtpMasterKey = errors.New("SRTP master key is not long enough")
errShortSrtpMasterSalt = errors.New("SRTP master salt is not long enough")
errNoSuchSRTPProfile = errors.New("no such SRTP Profile")
errNonZeroKDRNotSupported = errors.New("indexOverKdr > 0 is not supported yet")
errExporterWrongLabel = errors.New("exporter called with wrong label")
errNoConfig = errors.New("no config provided")
errNoConn = errors.New("no conn provided")
errTooShortRTP = errors.New("packet is too short to be RTP packet")
errTooShortRTCP = errors.New("packet is too short to be RTCP packet")
errPayloadDiffers = errors.New("payload differs")
errStartedChannelUsedIncorrectly = errors.New("started channel used incorrectly, should only be closed")
errBadIVLength = errors.New("bad iv length in xorBytesCTR")
errExceededMaxPackets = errors.New("exceeded the maximum number of packets")
errMKIAlreadyInUse = errors.New("MKI already in use")
errMKIIsNotEnabled = errors.New("MKI is not enabled")
errInvalidMKILength = errors.New("invalid MKI length")
errStreamNotInited = errors.New("stream has not been inited, unable to close")
errStreamAlreadyClosed = errors.New("stream is already closed")
errStreamAlreadyInited = errors.New("stream is already inited")
errFailedTypeAssertion = errors.New("failed to cast child")
)
type duplicatedError struct {
Proto string // srtp or srtcp
SSRC uint32
Index uint32 // sequence number or index
}
func (e *duplicatedError) Error() string {
return fmt.Sprintf("%s ssrc=%d index=%d: %v", e.Proto, e.SSRC, e.Index, errDuplicated)
}
func (e *duplicatedError) Unwrap() error {
return errDuplicated
}

View File

@@ -0,0 +1,69 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"crypto/aes"
"encoding/binary"
)
func aesCmKeyDerivation(label byte, masterKey, masterSalt []byte, indexOverKdr int, outLen int) ([]byte, error) {
if indexOverKdr != 0 {
// 24-bit "index DIV kdr" must be xored to prf input.
return nil, errNonZeroKDRNotSupported
}
// https://tools.ietf.org/html/rfc3711#appendix-B.3
// The input block for AES-CM is generated by exclusive-oring the master salt with the
// concatenation of the encryption key label 0x00 with (index DIV kdr),
// - index is 'rollover count' and DIV is 'divided by'
nMasterSalt := len(masterSalt)
prfIn := make([]byte, 16)
copy(prfIn[:nMasterSalt], masterSalt)
prfIn[7] ^= label
// The resulting value is then AES encrypted using the master key to get the cipher key.
block, err := aes.NewCipher(masterKey)
if err != nil {
return nil, err
}
nBlockSize := block.BlockSize()
out := make([]byte, ((outLen+nBlockSize-1)/nBlockSize)*nBlockSize)
var i uint16
for n := 0; n < outLen; n += nBlockSize {
binary.BigEndian.PutUint16(prfIn[len(prfIn)-2:], i)
block.Encrypt(out[n:n+nBlockSize], prfIn)
i++
}
return out[:outLen], nil
}
// Generate IV https://tools.ietf.org/html/rfc3711#section-4.1.1
// where the 128-bit integer value IV SHALL be defined by the SSRC, the
// SRTP packet index i, and the SRTP session salting key k_s, as below.
// - ROC = a 32-bit unsigned rollover counter (ROC), which records how many
// - times the 16-bit RTP sequence number has been reset to zero after
// - passing through 65,535
// i = 2^16 * ROC + SEQ
// IV = (salt*2 ^ 16) | (ssrc*2 ^ 64) | (i*2 ^ 16)
func generateCounter(sequenceNumber uint16, rolloverCounter uint32, ssrc uint32, sessionSalt []byte) (counter [16]byte) {
copy(counter[:], sessionSalt)
counter[4] ^= byte(ssrc >> 24)
counter[5] ^= byte(ssrc >> 16)
counter[6] ^= byte(ssrc >> 8)
counter[7] ^= byte(ssrc)
counter[8] ^= byte(rolloverCounter >> 24)
counter[9] ^= byte(rolloverCounter >> 16)
counter[10] ^= byte(rolloverCounter >> 8)
counter[11] ^= byte(rolloverCounter)
counter[12] ^= byte(sequenceNumber >> 8)
counter[13] ^= byte(sequenceNumber)
return counter
}

57
server/vendor/github.com/pion/srtp/v2/keying.go generated vendored Normal file
View File

@@ -0,0 +1,57 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
const labelExtractorDtlsSrtp = "EXTRACTOR-dtls_srtp"
// KeyingMaterialExporter allows package SRTP to extract keying material
type KeyingMaterialExporter interface {
ExportKeyingMaterial(label string, context []byte, length int) ([]byte, error)
}
// ExtractSessionKeysFromDTLS allows setting the Config SessionKeys by
// extracting them from DTLS. This behavior is defined in RFC5764:
// https://tools.ietf.org/html/rfc5764
func (c *Config) ExtractSessionKeysFromDTLS(exporter KeyingMaterialExporter, isClient bool) error {
keyLen, err := c.Profile.KeyLen()
if err != nil {
return err
}
saltLen, err := c.Profile.SaltLen()
if err != nil {
return err
}
keyingMaterial, err := exporter.ExportKeyingMaterial(labelExtractorDtlsSrtp, nil, (keyLen*2)+(saltLen*2))
if err != nil {
return err
}
offset := 0
clientWriteKey := append([]byte{}, keyingMaterial[offset:offset+keyLen]...)
offset += keyLen
serverWriteKey := append([]byte{}, keyingMaterial[offset:offset+keyLen]...)
offset += keyLen
clientWriteKey = append(clientWriteKey, keyingMaterial[offset:offset+saltLen]...)
offset += saltLen
serverWriteKey = append(serverWriteKey, keyingMaterial[offset:offset+saltLen]...)
if isClient {
c.Keys.LocalMasterKey = clientWriteKey[0:keyLen]
c.Keys.LocalMasterSalt = clientWriteKey[keyLen:]
c.Keys.RemoteMasterKey = serverWriteKey[0:keyLen]
c.Keys.RemoteMasterSalt = serverWriteKey[keyLen:]
return nil
}
c.Keys.LocalMasterKey = serverWriteKey[0:keyLen]
c.Keys.LocalMasterSalt = serverWriteKey[keyLen:]
c.Keys.RemoteMasterKey = clientWriteKey[0:keyLen]
c.Keys.RemoteMasterSalt = clientWriteKey[keyLen:]
return nil
}

120
server/vendor/github.com/pion/srtp/v2/option.go generated vendored Normal file
View File

@@ -0,0 +1,120 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"github.com/pion/transport/v2/replaydetector"
)
// ContextOption represents option of Context using the functional options pattern.
type ContextOption func(*Context) error
// SRTPReplayProtection sets SRTP replay protection window size.
func SRTPReplayProtection(windowSize uint) ContextOption { // nolint:revive
return func(c *Context) error {
c.newSRTPReplayDetector = func() replaydetector.ReplayDetector {
return replaydetector.New(windowSize, maxROC<<16|maxSequenceNumber)
}
return nil
}
}
// SRTCPReplayProtection sets SRTCP replay protection window size.
func SRTCPReplayProtection(windowSize uint) ContextOption {
return func(c *Context) error {
c.newSRTCPReplayDetector = func() replaydetector.ReplayDetector {
return replaydetector.New(windowSize, maxSRTCPIndex)
}
return nil
}
}
// SRTPNoReplayProtection disables SRTP replay protection.
func SRTPNoReplayProtection() ContextOption { // nolint:revive
return func(c *Context) error {
c.newSRTPReplayDetector = func() replaydetector.ReplayDetector {
return &nopReplayDetector{}
}
return nil
}
}
// SRTCPNoReplayProtection disables SRTCP replay protection.
func SRTCPNoReplayProtection() ContextOption {
return func(c *Context) error {
c.newSRTCPReplayDetector = func() replaydetector.ReplayDetector {
return &nopReplayDetector{}
}
return nil
}
}
// SRTPReplayDetectorFactory sets custom SRTP replay detector.
func SRTPReplayDetectorFactory(fn func() replaydetector.ReplayDetector) ContextOption { // nolint:revive
return func(c *Context) error {
c.newSRTPReplayDetector = fn
return nil
}
}
// SRTCPReplayDetectorFactory sets custom SRTCP replay detector.
func SRTCPReplayDetectorFactory(fn func() replaydetector.ReplayDetector) ContextOption {
return func(c *Context) error {
c.newSRTCPReplayDetector = fn
return nil
}
}
type nopReplayDetector struct{}
func (s *nopReplayDetector) Check(uint64) (func(), bool) {
return func() {}, true
}
// MasterKeyIndicator sets RTP/RTCP MKI for the initial master key. Array passed as an argument will be
// copied as-is to encrypted SRTP/SRTCP packets, so it must be of proper length and in Big Endian format.
// All MKIs added later using Context.AddCipherForMKI must have the same length as the one used here.
func MasterKeyIndicator(mki []byte) ContextOption {
return func(c *Context) error {
if len(mki) > 0 {
c.sendMKI = make([]byte, len(mki))
copy(c.sendMKI, mki)
}
return nil
}
}
// SRTPEncryption enables SRTP encryption.
func SRTPEncryption() ContextOption { // nolint:revive
return func(c *Context) error {
c.encryptSRTP = true
return nil
}
}
// SRTPNoEncryption disables SRTP encryption. This option is useful when you want to use NullCipher for SRTP and keep authentication only.
// It simplifies debugging and testing, but it is not recommended for production use.
func SRTPNoEncryption() ContextOption { // nolint:revive
return func(c *Context) error {
c.encryptSRTP = false
return nil
}
}
// SRTCPEncryption enables SRTCP encryption.
func SRTCPEncryption() ContextOption {
return func(c *Context) error {
c.encryptSRTCP = true
return nil
}
}
// SRTCPNoEncryption disables SRTCP encryption. This option is useful when you want to use NullCipher for SRTCP and keep authentication only.
// It simplifies debugging and testing, but it is not recommended for production use.
func SRTCPNoEncryption() ContextOption {
return func(c *Context) error {
c.encryptSRTCP = false
return nil
}
}

View File

@@ -0,0 +1,128 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import "fmt"
// ProtectionProfile specifies Cipher and AuthTag details, similar to TLS cipher suite
type ProtectionProfile uint16
// Supported protection profiles
// See https://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
//
// AES128_CM_HMAC_SHA1_80 and AES128_CM_HMAC_SHA1_32 are valid SRTP profiles, but they do not have an DTLS-SRTP Protection Profiles ID assigned
// in RFC 5764. They were in earlier draft of this RFC: https://datatracker.ietf.org/doc/html/draft-ietf-avt-dtls-srtp-03#section-4.1.2
// Their IDs are now marked as reserved in the IANA registry. Despite this Chrome supports them:
// https://chromium.googlesource.com/chromium/deps/libsrtp/+/84122798bb16927b1e676bd4f938a6e48e5bf2fe/srtp/include/srtp.h#694
//
// Null profiles disable encryption, they are used for debugging and testing. They are not recommended for production use.
// Use of them is equivalent to using ProtectionProfileAes128CmHmacSha1_NN profile with SRTPNoEncryption and SRTCPNoEncryption options.
const (
ProtectionProfileAes128CmHmacSha1_80 ProtectionProfile = 0x0001
ProtectionProfileAes128CmHmacSha1_32 ProtectionProfile = 0x0002
ProtectionProfileAes256CmHmacSha1_80 ProtectionProfile = 0x0003
ProtectionProfileAes256CmHmacSha1_32 ProtectionProfile = 0x0004
ProtectionProfileNullHmacSha1_80 ProtectionProfile = 0x0005
ProtectionProfileNullHmacSha1_32 ProtectionProfile = 0x0006
ProtectionProfileAeadAes128Gcm ProtectionProfile = 0x0007
ProtectionProfileAeadAes256Gcm ProtectionProfile = 0x0008
)
// KeyLen returns length of encryption key in bytes. For all profiles except NullHmacSha1_32 and NullHmacSha1_80 is is also the length of the session key.
func (p ProtectionProfile) KeyLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAeadAes128Gcm, ProtectionProfileNullHmacSha1_32, ProtectionProfileNullHmacSha1_80:
return 16, nil
case ProtectionProfileAeadAes256Gcm, ProtectionProfileAes256CmHmacSha1_32, ProtectionProfileAes256CmHmacSha1_80:
return 32, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
// SaltLen returns length of salt key in bytes. For all profiles except NullHmacSha1_32 and NullHmacSha1_80 is is also the length of the session salt.
func (p ProtectionProfile) SaltLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAes256CmHmacSha1_32, ProtectionProfileAes256CmHmacSha1_80, ProtectionProfileNullHmacSha1_32, ProtectionProfileNullHmacSha1_80:
return 14, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 12, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
// AuthTagRTPLen returns length of RTP authentication tag in bytes for AES protection profiles. For AEAD ones it returns zero.
func (p ProtectionProfile) AuthTagRTPLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAes256CmHmacSha1_80, ProtectionProfileNullHmacSha1_80:
return 10, nil
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes256CmHmacSha1_32, ProtectionProfileNullHmacSha1_32:
return 4, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 0, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
// AuthTagRTCPLen returns length of RTCP authentication tag in bytes for AES protection profiles. For AEAD ones it returns zero.
func (p ProtectionProfile) AuthTagRTCPLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAes256CmHmacSha1_32, ProtectionProfileAes256CmHmacSha1_80, ProtectionProfileNullHmacSha1_32, ProtectionProfileNullHmacSha1_80:
return 10, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 0, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
// AEADAuthTagLen returns length of authentication tag in bytes for AEAD protection profiles. For AES ones it returns zero.
func (p ProtectionProfile) AEADAuthTagLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAes256CmHmacSha1_32, ProtectionProfileAes256CmHmacSha1_80, ProtectionProfileNullHmacSha1_32, ProtectionProfileNullHmacSha1_80:
return 0, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 16, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
// AuthKeyLen returns length of authentication key in bytes for AES protection profiles. For AEAD ones it returns zero.
func (p ProtectionProfile) AuthKeyLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAes256CmHmacSha1_32, ProtectionProfileAes256CmHmacSha1_80, ProtectionProfileNullHmacSha1_32, ProtectionProfileNullHmacSha1_80:
return 20, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 0, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
// String returns the name of the protection profile.
func (p ProtectionProfile) String() string {
switch p {
case ProtectionProfileAes128CmHmacSha1_80:
return "SRTP_AES128_CM_HMAC_SHA1_80"
case ProtectionProfileAes128CmHmacSha1_32:
return "SRTP_AES128_CM_HMAC_SHA1_32"
case ProtectionProfileAes256CmHmacSha1_80:
return "SRTP_AES256_CM_HMAC_SHA1_80"
case ProtectionProfileAes256CmHmacSha1_32:
return "SRTP_AES256_CM_HMAC_SHA1_32"
case ProtectionProfileAeadAes128Gcm:
return "SRTP_AEAD_AES_128_GCM"
case ProtectionProfileAeadAes256Gcm:
return "SRTP_AEAD_AES_256_GCM"
case ProtectionProfileNullHmacSha1_80:
return "SRTP_NULL_HMAC_SHA1_80"
case ProtectionProfileNullHmacSha1_32:
return "SRTP_NULL_HMAC_SHA1_32"
default:
return fmt.Sprintf("Unknown SRTP profile: %#v", p)
}
}

6
server/vendor/github.com/pion/srtp/v2/renovate.json generated vendored Normal file
View File

@@ -0,0 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"github>pion/renovate-config"
]
}

161
server/vendor/github.com/pion/srtp/v2/session.go generated vendored Normal file
View File

@@ -0,0 +1,161 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"errors"
"io"
"net"
"sync"
"time"
"github.com/pion/logging"
"github.com/pion/transport/v2/packetio"
)
type streamSession interface {
Close() error
write([]byte) (int, error)
decrypt([]byte) error
}
type session struct {
localContextMutex sync.Mutex
localContext, remoteContext *Context
localOptions, remoteOptions []ContextOption
newStream chan readStream
acceptStreamTimeout time.Time
started chan interface{}
closed chan interface{}
readStreamsClosed bool
readStreams map[uint32]readStream
readStreamsLock sync.Mutex
log logging.LeveledLogger
bufferFactory func(packetType packetio.BufferPacketType, ssrc uint32) io.ReadWriteCloser
nextConn net.Conn
}
// Config is used to configure a session.
// You can provide either a KeyingMaterialExporter to export keys
// or directly pass the keys themselves.
// After a Config is passed to a session it must not be modified.
type Config struct {
Keys SessionKeys
Profile ProtectionProfile
BufferFactory func(packetType packetio.BufferPacketType, ssrc uint32) io.ReadWriteCloser
LoggerFactory logging.LoggerFactory
AcceptStreamTimeout time.Time
// List of local/remote context options.
// ReplayProtection is enabled on remote context by default.
// Default replay protection window size is 64.
LocalOptions, RemoteOptions []ContextOption
}
// SessionKeys bundles the keys required to setup an SRTP session
type SessionKeys struct {
LocalMasterKey []byte
LocalMasterSalt []byte
RemoteMasterKey []byte
RemoteMasterSalt []byte
}
func (s *session) getOrCreateReadStream(ssrc uint32, child streamSession, proto func() readStream) (readStream, bool) {
s.readStreamsLock.Lock()
defer s.readStreamsLock.Unlock()
if s.readStreamsClosed {
return nil, false
}
r, ok := s.readStreams[ssrc]
if ok {
return r, false
}
// Create the readStream.
r = proto()
if err := r.init(child, ssrc); err != nil {
return nil, false
}
s.readStreams[ssrc] = r
return r, true
}
func (s *session) removeReadStream(ssrc uint32) {
s.readStreamsLock.Lock()
defer s.readStreamsLock.Unlock()
if s.readStreamsClosed {
return
}
delete(s.readStreams, ssrc)
}
func (s *session) close() error {
if s.nextConn == nil {
return nil
} else if err := s.nextConn.Close(); err != nil {
return err
}
<-s.closed
return nil
}
func (s *session) start(localMasterKey, localMasterSalt, remoteMasterKey, remoteMasterSalt []byte, profile ProtectionProfile, child streamSession) error {
var err error
s.localContext, err = CreateContext(localMasterKey, localMasterSalt, profile, s.localOptions...)
if err != nil {
return err
}
s.remoteContext, err = CreateContext(remoteMasterKey, remoteMasterSalt, profile, s.remoteOptions...)
if err != nil {
return err
}
if err = s.nextConn.SetReadDeadline(s.acceptStreamTimeout); err != nil {
return err
}
go func() {
defer func() {
close(s.newStream)
s.readStreamsLock.Lock()
s.readStreamsClosed = true
s.readStreamsLock.Unlock()
close(s.closed)
}()
b := make([]byte, 8192)
for {
var i int
i, err = s.nextConn.Read(b)
if err != nil {
if !errors.Is(err, io.EOF) {
s.log.Error(err.Error())
}
return
}
if err = child.decrypt(b[:i]); err != nil {
s.log.Info(err.Error())
}
}
}()
close(s.started)
return nil
}

190
server/vendor/github.com/pion/srtp/v2/session_srtcp.go generated vendored Normal file
View File

@@ -0,0 +1,190 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"net"
"time"
"github.com/pion/logging"
"github.com/pion/rtcp"
)
const defaultSessionSRTCPReplayProtectionWindow = 64
// SessionSRTCP implements io.ReadWriteCloser and provides a bi-directional SRTCP session
// SRTCP itself does not have a design like this, but it is common in most applications
// for local/remote to each have their own keying material. This provides those patterns
// instead of making everyone re-implement
type SessionSRTCP struct {
session
writeStream *WriteStreamSRTCP
}
// NewSessionSRTCP creates a SRTCP session using conn as the underlying transport.
func NewSessionSRTCP(conn net.Conn, config *Config) (*SessionSRTCP, error) { //nolint:dupl
if config == nil {
return nil, errNoConfig
} else if conn == nil {
return nil, errNoConn
}
loggerFactory := config.LoggerFactory
if loggerFactory == nil {
loggerFactory = logging.NewDefaultLoggerFactory()
}
localOpts := append(
[]ContextOption{},
config.LocalOptions...,
)
remoteOpts := append(
[]ContextOption{
// Default options
SRTCPReplayProtection(defaultSessionSRTCPReplayProtectionWindow),
},
config.RemoteOptions...,
)
s := &SessionSRTCP{
session: session{
nextConn: conn,
localOptions: localOpts,
remoteOptions: remoteOpts,
readStreams: map[uint32]readStream{},
newStream: make(chan readStream),
acceptStreamTimeout: config.AcceptStreamTimeout,
started: make(chan interface{}),
closed: make(chan interface{}),
bufferFactory: config.BufferFactory,
log: loggerFactory.NewLogger("srtp"),
},
}
s.writeStream = &WriteStreamSRTCP{s}
err := s.session.start(
config.Keys.LocalMasterKey, config.Keys.LocalMasterSalt,
config.Keys.RemoteMasterKey, config.Keys.RemoteMasterSalt,
config.Profile,
s,
)
if err != nil {
return nil, err
}
return s, nil
}
// OpenWriteStream returns the global write stream for the Session
func (s *SessionSRTCP) OpenWriteStream() (*WriteStreamSRTCP, error) {
return s.writeStream, nil
}
// OpenReadStream opens a read stream for the given SSRC, it can be used
// if you want a certain SSRC, but don't want to wait for AcceptStream
func (s *SessionSRTCP) OpenReadStream(ssrc uint32) (*ReadStreamSRTCP, error) {
r, _ := s.session.getOrCreateReadStream(ssrc, s, newReadStreamSRTCP)
if readStream, ok := r.(*ReadStreamSRTCP); ok {
return readStream, nil
}
return nil, errFailedTypeAssertion
}
// AcceptStream returns a stream to handle RTCP for a single SSRC
func (s *SessionSRTCP) AcceptStream() (*ReadStreamSRTCP, uint32, error) {
stream, ok := <-s.newStream
if !ok {
return nil, 0, errStreamAlreadyClosed
}
readStream, ok := stream.(*ReadStreamSRTCP)
if !ok {
return nil, 0, errFailedTypeAssertion
}
return readStream, stream.GetSSRC(), nil
}
// Close ends the session
func (s *SessionSRTCP) Close() error {
return s.session.close()
}
// Private
func (s *SessionSRTCP) write(buf []byte) (int, error) {
if _, ok := <-s.session.started; ok {
return 0, errStartedChannelUsedIncorrectly
}
ibuf := bufferpool.Get()
defer bufferpool.Put(ibuf)
s.session.localContextMutex.Lock()
encrypted, err := s.localContext.EncryptRTCP(ibuf.([]byte), buf, nil)
s.session.localContextMutex.Unlock()
if err != nil {
return 0, err
}
return s.session.nextConn.Write(encrypted)
}
func (s *SessionSRTCP) setWriteDeadline(t time.Time) error {
return s.session.nextConn.SetWriteDeadline(t)
}
// create a list of Destination SSRCs
// that's a superset of all Destinations in the slice.
func destinationSSRC(pkts []rtcp.Packet) []uint32 {
ssrcSet := make(map[uint32]struct{})
for _, p := range pkts {
for _, ssrc := range p.DestinationSSRC() {
ssrcSet[ssrc] = struct{}{}
}
}
out := make([]uint32, 0, len(ssrcSet))
for ssrc := range ssrcSet {
out = append(out, ssrc)
}
return out
}
func (s *SessionSRTCP) decrypt(buf []byte) error {
decrypted, err := s.remoteContext.DecryptRTCP(buf, buf, nil)
if err != nil {
return err
}
pkt, err := rtcp.Unmarshal(decrypted)
if err != nil {
return err
}
for _, ssrc := range destinationSSRC(pkt) {
r, isNew := s.session.getOrCreateReadStream(ssrc, s, newReadStreamSRTCP)
if r == nil {
return nil // Session has been closed
} else if isNew {
if !s.session.acceptStreamTimeout.IsZero() {
_ = s.session.nextConn.SetReadDeadline(time.Time{})
}
s.session.newStream <- r // Notify AcceptStream
}
readStream, ok := r.(*ReadStreamSRTCP)
if !ok {
return errFailedTypeAssertion
}
_, err = readStream.write(decrypted)
if err != nil {
return err
}
}
return nil
}

200
server/vendor/github.com/pion/srtp/v2/session_srtp.go generated vendored Normal file
View File

@@ -0,0 +1,200 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"net"
"sync"
"time"
"github.com/pion/logging"
"github.com/pion/rtp"
)
const defaultSessionSRTPReplayProtectionWindow = 64
// SessionSRTP implements io.ReadWriteCloser and provides a bi-directional SRTP session
// SRTP itself does not have a design like this, but it is common in most applications
// for local/remote to each have their own keying material. This provides those patterns
// instead of making everyone re-implement
type SessionSRTP struct {
session
writeStream *WriteStreamSRTP
}
// NewSessionSRTP creates a SRTP session using conn as the underlying transport.
func NewSessionSRTP(conn net.Conn, config *Config) (*SessionSRTP, error) { //nolint:dupl
if config == nil {
return nil, errNoConfig
} else if conn == nil {
return nil, errNoConn
}
loggerFactory := config.LoggerFactory
if loggerFactory == nil {
loggerFactory = logging.NewDefaultLoggerFactory()
}
localOpts := append(
[]ContextOption{},
config.LocalOptions...,
)
remoteOpts := append(
[]ContextOption{
// Default options
SRTPReplayProtection(defaultSessionSRTPReplayProtectionWindow),
},
config.RemoteOptions...,
)
s := &SessionSRTP{
session: session{
nextConn: conn,
localOptions: localOpts,
remoteOptions: remoteOpts,
readStreams: map[uint32]readStream{},
newStream: make(chan readStream),
acceptStreamTimeout: config.AcceptStreamTimeout,
started: make(chan interface{}),
closed: make(chan interface{}),
bufferFactory: config.BufferFactory,
log: loggerFactory.NewLogger("srtp"),
},
}
s.writeStream = &WriteStreamSRTP{s}
err := s.session.start(
config.Keys.LocalMasterKey, config.Keys.LocalMasterSalt,
config.Keys.RemoteMasterKey, config.Keys.RemoteMasterSalt,
config.Profile,
s,
)
if err != nil {
return nil, err
}
return s, nil
}
// OpenWriteStream returns the global write stream for the Session
func (s *SessionSRTP) OpenWriteStream() (*WriteStreamSRTP, error) {
return s.writeStream, nil
}
// OpenReadStream opens a read stream for the given SSRC, it can be used
// if you want a certain SSRC, but don't want to wait for AcceptStream
func (s *SessionSRTP) OpenReadStream(ssrc uint32) (*ReadStreamSRTP, error) {
r, _ := s.session.getOrCreateReadStream(ssrc, s, newReadStreamSRTP)
if readStream, ok := r.(*ReadStreamSRTP); ok {
return readStream, nil
}
return nil, errFailedTypeAssertion
}
// AcceptStream returns a stream to handle RTCP for a single SSRC
func (s *SessionSRTP) AcceptStream() (*ReadStreamSRTP, uint32, error) {
stream, ok := <-s.newStream
if !ok {
return nil, 0, errStreamAlreadyClosed
}
readStream, ok := stream.(*ReadStreamSRTP)
if !ok {
return nil, 0, errFailedTypeAssertion
}
return readStream, stream.GetSSRC(), nil
}
// Close ends the session
func (s *SessionSRTP) Close() error {
return s.session.close()
}
func (s *SessionSRTP) write(b []byte) (int, error) {
packet := &rtp.Packet{}
if err := packet.Unmarshal(b); err != nil {
return 0, err
}
return s.writeRTP(&packet.Header, packet.Payload)
}
// bufferpool is a global pool of buffers used for encrypted packets in
// writeRTP below. Since it's global, buffers can be shared between
// different sessions, which amortizes the cost of allocating the pool.
//
// 1472 is the maximum Ethernet UDP payload. We give ourselves 20 bytes
// of slack for any authentication tags, which is more than enough for
// either CTR or GCM. If the buffer is too small, no harm, it will just
// get expanded by growBuffer.
var bufferpool = sync.Pool{ // nolint:gochecknoglobals
New: func() interface{} {
return make([]byte, 1492)
},
}
func (s *SessionSRTP) writeRTP(header *rtp.Header, payload []byte) (int, error) {
if _, ok := <-s.session.started; ok {
return 0, errStartedChannelUsedIncorrectly
}
// encryptRTP will either return our buffer, or, if it is too
// small, allocate a new buffer itself. In either case, it is
// safe to put the buffer back into the pool, but only after
// nextConn.Write has returned.
ibuf := bufferpool.Get()
defer bufferpool.Put(ibuf)
s.session.localContextMutex.Lock()
encrypted, err := s.localContext.encryptRTP(ibuf.([]byte), header, payload)
s.session.localContextMutex.Unlock()
if err != nil {
return 0, err
}
return s.session.nextConn.Write(encrypted)
}
func (s *SessionSRTP) setWriteDeadline(t time.Time) error {
return s.session.nextConn.SetWriteDeadline(t)
}
func (s *SessionSRTP) decrypt(buf []byte) error {
h := &rtp.Header{}
headerLen, err := h.Unmarshal(buf)
if err != nil {
return err
}
r, isNew := s.session.getOrCreateReadStream(h.SSRC, s, newReadStreamSRTP)
if r == nil {
return nil // Session has been closed
} else if isNew {
if !s.session.acceptStreamTimeout.IsZero() {
_ = s.session.nextConn.SetReadDeadline(time.Time{})
}
s.session.newStream <- r // Notify AcceptStream
}
readStream, ok := r.(*ReadStreamSRTP)
if !ok {
return errFailedTypeAssertion
}
decrypted, err := s.remoteContext.decryptRTP(buf, buf, h, headerLen)
if err != nil {
return err
}
_, err = readStream.write(decrypted)
if err != nil {
return err
}
return nil
}

109
server/vendor/github.com/pion/srtp/v2/srtcp.go generated vendored Normal file
View File

@@ -0,0 +1,109 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"encoding/binary"
"fmt"
"github.com/pion/rtcp"
)
const maxSRTCPIndex = 0x7FFFFFFF
const srtcpHeaderSize = 8
func (c *Context) decryptRTCP(dst, encrypted []byte) ([]byte, error) {
authTagLen, err := c.cipher.AuthTagRTCPLen()
if err != nil {
return nil, err
}
aeadAuthTagLen, err := c.cipher.AEADAuthTagLen()
if err != nil {
return nil, err
}
mkiLen := len(c.sendMKI)
// Verify that encrypted packet is long enough
if len(encrypted) < (srtcpHeaderSize + aeadAuthTagLen + srtcpIndexSize + mkiLen + authTagLen) {
return nil, fmt.Errorf("%w: %d", errTooShortRTCP, len(encrypted))
}
index := c.cipher.getRTCPIndex(encrypted)
ssrc := binary.BigEndian.Uint32(encrypted[4:])
s := c.getSRTCPSSRCState(ssrc)
markAsValid, ok := s.replayDetector.Check(uint64(index))
if !ok {
return nil, &duplicatedError{Proto: "srtcp", SSRC: ssrc, Index: index}
}
cipher := c.cipher
if len(c.mkis) > 0 {
// Find cipher for MKI
actualMKI := c.cipher.getMKI(encrypted, false)
cipher, ok = c.mkis[string(actualMKI)]
if !ok {
return nil, ErrMKINotFound
}
}
out := allocateIfMismatch(dst, encrypted)
out, err = cipher.decryptRTCP(out, encrypted, index, ssrc)
if err != nil {
return nil, err
}
markAsValid()
return out, nil
}
// DecryptRTCP decrypts a buffer that contains a RTCP packet
func (c *Context) DecryptRTCP(dst, encrypted []byte, header *rtcp.Header) ([]byte, error) {
if header == nil {
header = &rtcp.Header{}
}
if err := header.Unmarshal(encrypted); err != nil {
return nil, err
}
return c.decryptRTCP(dst, encrypted)
}
func (c *Context) encryptRTCP(dst, decrypted []byte) ([]byte, error) {
if len(decrypted) < srtcpHeaderSize {
return nil, fmt.Errorf("%w: %d", errTooShortRTCP, len(decrypted))
}
ssrc := binary.BigEndian.Uint32(decrypted[4:])
s := c.getSRTCPSSRCState(ssrc)
if s.srtcpIndex >= maxSRTCPIndex {
// ... when 2^48 SRTP packets or 2^31 SRTCP packets have been secured with the same key
// (whichever occurs before), the key management MUST be called to provide new master key(s)
// (previously stored and used keys MUST NOT be used again), or the session MUST be terminated.
// https://www.rfc-editor.org/rfc/rfc3711#section-9.2
return nil, errExceededMaxPackets
}
// We roll over early because MSB is used for marking as encrypted
s.srtcpIndex++
return c.cipher.encryptRTCP(dst, decrypted, s.srtcpIndex, ssrc)
}
// EncryptRTCP Encrypts a RTCP packet
func (c *Context) EncryptRTCP(dst, decrypted []byte, header *rtcp.Header) ([]byte, error) {
if header == nil {
header = &rtcp.Header{}
}
if err := header.Unmarshal(decrypted); err != nil {
return nil, err
}
return c.encryptRTCP(dst, decrypted)
}

109
server/vendor/github.com/pion/srtp/v2/srtp.go generated vendored Normal file
View File

@@ -0,0 +1,109 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package srtp implements Secure Real-time Transport Protocol
package srtp
import (
"fmt"
"github.com/pion/rtp"
)
func (c *Context) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int) ([]byte, error) {
authTagLen, err := c.cipher.AuthTagRTPLen()
if err != nil {
return nil, err
}
aeadAuthTagLen, err := c.cipher.AEADAuthTagLen()
if err != nil {
return nil, err
}
mkiLen := len(c.sendMKI)
// Verify that encrypted packet is long enough
if len(ciphertext) < (headerLen + aeadAuthTagLen + mkiLen + authTagLen) {
return nil, fmt.Errorf("%w: %d", errTooShortRTP, len(ciphertext))
}
s := c.getSRTPSSRCState(header.SSRC)
roc, diff, _ := s.nextRolloverCount(header.SequenceNumber)
markAsValid, ok := s.replayDetector.Check(
(uint64(roc) << 16) | uint64(header.SequenceNumber),
)
if !ok {
return nil, &duplicatedError{
Proto: "srtp", SSRC: header.SSRC, Index: uint32(header.SequenceNumber),
}
}
cipher := c.cipher
if len(c.mkis) > 0 {
// Find cipher for MKI
actualMKI := c.cipher.getMKI(ciphertext, true)
cipher, ok = c.mkis[string(actualMKI)]
if !ok {
return nil, ErrMKINotFound
}
}
dst = growBufferSize(dst, len(ciphertext)-authTagLen-len(c.sendMKI))
dst, err = cipher.decryptRTP(dst, ciphertext, header, headerLen, roc)
if err != nil {
return nil, err
}
markAsValid()
s.updateRolloverCount(header.SequenceNumber, diff)
return dst, nil
}
// DecryptRTP decrypts a RTP packet with an encrypted payload
func (c *Context) DecryptRTP(dst, encrypted []byte, header *rtp.Header) ([]byte, error) {
if header == nil {
header = &rtp.Header{}
}
headerLen, err := header.Unmarshal(encrypted)
if err != nil {
return nil, err
}
return c.decryptRTP(dst, encrypted, header, headerLen)
}
// EncryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided.
// If the dst buffer does not have the capacity to hold `len(plaintext) + 10` bytes, a new one will be allocated and returned.
// If a rtp.Header is provided, it will be Unmarshaled using the plaintext.
func (c *Context) EncryptRTP(dst []byte, plaintext []byte, header *rtp.Header) ([]byte, error) {
if header == nil {
header = &rtp.Header{}
}
headerLen, err := header.Unmarshal(plaintext)
if err != nil {
return nil, err
}
return c.encryptRTP(dst, header, plaintext[headerLen:])
}
// encryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided.
// If the dst buffer does not have the capacity, a new one will be allocated and returned.
// Similar to above but faster because it can avoid unmarshaling the header and marshaling the payload.
func (c *Context) encryptRTP(dst []byte, header *rtp.Header, payload []byte) (ciphertext []byte, err error) {
s := c.getSRTPSSRCState(header.SSRC)
roc, diff, ovf := s.nextRolloverCount(header.SequenceNumber)
if ovf {
// ... when 2^48 SRTP packets or 2^31 SRTCP packets have been secured with the same key
// (whichever occurs before), the key management MUST be called to provide new master key(s)
// (previously stored and used keys MUST NOT be used again), or the session MUST be terminated.
// https://www.rfc-editor.org/rfc/rfc3711#section-9.2
return nil, errExceededMaxPackets
}
s.updateRolloverCount(header.SequenceNumber, diff)
return c.cipher.encryptRTP(dst, header, payload, roc)
}

51
server/vendor/github.com/pion/srtp/v2/srtp_cipher.go generated vendored Normal file
View File

@@ -0,0 +1,51 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import "github.com/pion/rtp"
// cipher represents a implementation of one
// of the SRTP Specific ciphers
type srtpCipher interface {
// AuthTagRTPLen/AuthTagRTCPLen return auth key length of the cipher.
// See the note below.
AuthTagRTPLen() (int, error)
AuthTagRTCPLen() (int, error)
// AEADAuthTagLen returns AEAD auth key length of the cipher.
// See the note below.
AEADAuthTagLen() (int, error)
getRTCPIndex([]byte) uint32
getMKI([]byte, bool) []byte
encryptRTP([]byte, *rtp.Header, []byte, uint32) ([]byte, error)
encryptRTCP([]byte, []byte, uint32, uint32) ([]byte, error)
decryptRTP([]byte, []byte, *rtp.Header, int, uint32) ([]byte, error)
decryptRTCP([]byte, []byte, uint32, uint32) ([]byte, error)
}
/*
NOTE: Auth tag and AEAD auth tag are placed at the different position in SRTCP
In non-AEAD cipher, the authentication tag is placed *after* the ESRTCP word
(Encrypted-flag and SRTCP index).
> AES_128_CM_HMAC_SHA1_80
> | RTCP Header | Encrypted payload |E| SRTCP Index | Auth tag |
> ^ |----------|
> | ^
> | authTagLen=10
> aeadAuthTagLen=0
In AEAD cipher, the AEAD authentication tag is embedded in the ciphertext.
It is *before* the ESRTCP word (Encrypted-flag and SRTCP index).
> AEAD_AES_128_GCM
> | RTCP Header | Encrypted payload | AEAD auth tag |E| SRTCP Index |
> |---------------| ^
> ^ authTagLen=0
> aeadAuthTagLen=16
See https://tools.ietf.org/html/rfc7714 for the full specifications.
*/

View File

@@ -0,0 +1,285 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"crypto/aes"
"crypto/cipher"
"encoding/binary"
"fmt"
"github.com/pion/rtp"
)
const (
rtcpEncryptionFlag = 0x80
)
type srtpCipherAeadAesGcm struct {
ProtectionProfile
srtpCipher, srtcpCipher cipher.AEAD
srtpSessionSalt, srtcpSessionSalt []byte
mki []byte
srtpEncrypted, srtcpEncrypted bool
}
func newSrtpCipherAeadAesGcm(profile ProtectionProfile, masterKey, masterSalt, mki []byte, encryptSRTP, encryptSRTCP bool) (*srtpCipherAeadAesGcm, error) {
s := &srtpCipherAeadAesGcm{
ProtectionProfile: profile,
srtpEncrypted: encryptSRTP,
srtcpEncrypted: encryptSRTCP,
}
srtpSessionKey, err := aesCmKeyDerivation(labelSRTPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
return nil, err
}
srtpBlock, err := aes.NewCipher(srtpSessionKey)
if err != nil {
return nil, err
}
s.srtpCipher, err = cipher.NewGCM(srtpBlock)
if err != nil {
return nil, err
}
srtcpSessionKey, err := aesCmKeyDerivation(labelSRTCPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
return nil, err
}
srtcpBlock, err := aes.NewCipher(srtcpSessionKey)
if err != nil {
return nil, err
}
s.srtcpCipher, err = cipher.NewGCM(srtcpBlock)
if err != nil {
return nil, err
}
if s.srtpSessionSalt, err = aesCmKeyDerivation(labelSRTPSalt, masterKey, masterSalt, 0, len(masterSalt)); err != nil {
return nil, err
} else if s.srtcpSessionSalt, err = aesCmKeyDerivation(labelSRTCPSalt, masterKey, masterSalt, 0, len(masterSalt)); err != nil {
return nil, err
}
mkiLen := len(mki)
if mkiLen > 0 {
s.mki = make([]byte, mkiLen)
copy(s.mki, mki)
}
return s, nil
}
func (s *srtpCipherAeadAesGcm) encryptRTP(dst []byte, header *rtp.Header, payload []byte, roc uint32) (ciphertext []byte, err error) {
// Grow the given buffer to fit the output.
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
dst = growBufferSize(dst, header.MarshalSize()+len(payload)+authTagLen+len(s.mki))
n, err := header.MarshalTo(dst)
if err != nil {
return nil, err
}
iv := s.rtpInitializationVector(header, roc)
if s.srtpEncrypted {
s.srtpCipher.Seal(dst[n:n], iv[:], payload, dst[:n])
} else {
clearLen := n + len(payload)
copy(dst[n:], payload)
s.srtpCipher.Seal(dst[clearLen:clearLen], iv[:], nil, dst[:clearLen])
}
// Add MKI after the encrypted payload
if len(s.mki) > 0 {
copy(dst[len(dst)-len(s.mki):], s.mki)
}
return dst, nil
}
func (s *srtpCipherAeadAesGcm) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int, roc uint32) ([]byte, error) {
// Grow the given buffer to fit the output.
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
nDst := len(ciphertext) - authTagLen - len(s.mki)
if nDst < headerLen {
// Size of ciphertext is shorter than AEAD auth tag len.
return nil, ErrFailedToVerifyAuthTag
}
dst = growBufferSize(dst, nDst)
iv := s.rtpInitializationVector(header, roc)
nEnd := len(ciphertext) - len(s.mki)
if s.srtpEncrypted {
if _, err := s.srtpCipher.Open(
dst[headerLen:headerLen], iv[:], ciphertext[headerLen:nEnd], ciphertext[:headerLen],
); err != nil {
return nil, fmt.Errorf("%s: %s", ErrFailedToVerifyAuthTag, err)
}
} else {
nDataEnd := nEnd - authTagLen
if _, err := s.srtpCipher.Open(
nil, iv[:], ciphertext[nDataEnd:nEnd], ciphertext[:nDataEnd],
); err != nil {
return nil, fmt.Errorf("%s: %w", ErrFailedToVerifyAuthTag, err)
}
copy(dst[headerLen:], ciphertext[headerLen:nDataEnd])
}
copy(dst[:headerLen], ciphertext[:headerLen])
return dst, nil
}
func (s *srtpCipherAeadAesGcm) encryptRTCP(dst, decrypted []byte, srtcpIndex uint32, ssrc uint32) ([]byte, error) {
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
aadPos := len(decrypted) + authTagLen
// Grow the given buffer to fit the output.
dst = growBufferSize(dst, aadPos+srtcpIndexSize+len(s.mki))
iv := s.rtcpInitializationVector(srtcpIndex, ssrc)
if s.srtcpEncrypted {
aad := s.rtcpAdditionalAuthenticatedData(decrypted, srtcpIndex)
copy(dst[:8], decrypted[:8])
copy(dst[aadPos:aadPos+4], aad[8:12])
s.srtcpCipher.Seal(dst[8:8], iv[:], decrypted[8:], aad[:])
} else {
// Copy the packet unencrypted.
copy(dst, decrypted)
// Append the SRTCP index to the end of the packet - this will form the AAD.
binary.BigEndian.PutUint32(dst[len(decrypted):], srtcpIndex)
// Generate the authentication tag.
tag := make([]byte, authTagLen)
s.srtcpCipher.Seal(tag[0:0], iv[:], nil, dst[:len(decrypted)+4])
// Copy index to the proper place.
copy(dst[aadPos:], dst[len(decrypted):len(decrypted)+4])
// Copy the auth tag after RTCP payload.
copy(dst[len(decrypted):], tag)
}
copy(dst[aadPos+4:], s.mki)
return dst, nil
}
func (s *srtpCipherAeadAesGcm) decryptRTCP(dst, encrypted []byte, srtcpIndex, ssrc uint32) ([]byte, error) {
aadPos := len(encrypted) - srtcpIndexSize - len(s.mki)
// Grow the given buffer to fit the output.
authTagLen, err := s.AEADAuthTagLen()
if err != nil {
return nil, err
}
nDst := aadPos - authTagLen
if nDst < 0 {
// Size of ciphertext is shorter than AEAD auth tag len.
return nil, ErrFailedToVerifyAuthTag
}
dst = growBufferSize(dst, nDst)
isEncrypted := encrypted[aadPos]>>7 != 0
iv := s.rtcpInitializationVector(srtcpIndex, ssrc)
if isEncrypted {
aad := s.rtcpAdditionalAuthenticatedData(encrypted, srtcpIndex)
if _, err := s.srtcpCipher.Open(dst[8:8], iv[:], encrypted[8:aadPos], aad[:]); err != nil {
return nil, fmt.Errorf("%s: %w", ErrFailedToVerifyAuthTag, err)
}
} else {
// Prepare AAD for received packet.
dataEnd := aadPos - authTagLen
aad := make([]byte, dataEnd+4)
copy(aad, encrypted[:dataEnd])
copy(aad[dataEnd:], encrypted[aadPos:aadPos+4])
// Verify the auth tag.
if _, err := s.srtcpCipher.Open(nil, iv[:], encrypted[dataEnd:aadPos], aad); err != nil {
return nil, fmt.Errorf("%s: %w", ErrFailedToVerifyAuthTag, err)
}
// Copy the unencrypted payload.
copy(dst[8:], encrypted[8:dataEnd])
}
copy(dst[:8], encrypted[:8])
return dst, nil
}
// The 12-octet IV used by AES-GCM SRTP is formed by first concatenating
// 2 octets of zeroes, the 4-octet SSRC, the 4-octet rollover counter
// (ROC), and the 2-octet sequence number (SEQ). The resulting 12-octet
// value is then XORed to the 12-octet salt to form the 12-octet IV.
//
// https://tools.ietf.org/html/rfc7714#section-8.1
func (s *srtpCipherAeadAesGcm) rtpInitializationVector(header *rtp.Header, roc uint32) [12]byte {
var iv [12]byte
binary.BigEndian.PutUint32(iv[2:], header.SSRC)
binary.BigEndian.PutUint32(iv[6:], roc)
binary.BigEndian.PutUint16(iv[10:], header.SequenceNumber)
for i := range iv {
iv[i] ^= s.srtpSessionSalt[i]
}
return iv
}
// The 12-octet IV used by AES-GCM SRTCP is formed by first
// concatenating 2 octets of zeroes, the 4-octet SSRC identifier,
// 2 octets of zeroes, a single "0" bit, and the 31-bit SRTCP index.
// The resulting 12-octet value is then XORed to the 12-octet salt to
// form the 12-octet IV.
//
// https://tools.ietf.org/html/rfc7714#section-9.1
func (s *srtpCipherAeadAesGcm) rtcpInitializationVector(srtcpIndex uint32, ssrc uint32) [12]byte {
var iv [12]byte
binary.BigEndian.PutUint32(iv[2:], ssrc)
binary.BigEndian.PutUint32(iv[8:], srtcpIndex)
for i := range iv {
iv[i] ^= s.srtcpSessionSalt[i]
}
return iv
}
// In an SRTCP packet, a 1-bit Encryption flag is prepended to the
// 31-bit SRTCP index to form a 32-bit value we shall call the
// "ESRTCP word"
//
// https://tools.ietf.org/html/rfc7714#section-17
func (s *srtpCipherAeadAesGcm) rtcpAdditionalAuthenticatedData(rtcpPacket []byte, srtcpIndex uint32) [12]byte {
var aad [12]byte
copy(aad[:], rtcpPacket[:8])
binary.BigEndian.PutUint32(aad[8:], srtcpIndex)
aad[8] |= rtcpEncryptionFlag
return aad
}
func (s *srtpCipherAeadAesGcm) getRTCPIndex(in []byte) uint32 {
return binary.BigEndian.Uint32(in[len(in)-len(s.mki)-4:]) &^ (rtcpEncryptionFlag << 24)
}
func (s *srtpCipherAeadAesGcm) getMKI(in []byte, _ bool) []byte {
mkiLen := len(s.mki)
if mkiLen == 0 {
return nil
}
tailOffset := len(in) - mkiLen
return in[tailOffset:]
}

View File

@@ -0,0 +1,331 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import ( //nolint:gci
"crypto/aes"
"crypto/cipher"
"crypto/hmac"
"crypto/sha1" //nolint:gosec
"crypto/subtle"
"encoding/binary"
"hash"
"github.com/pion/rtp"
)
type srtpCipherAesCmHmacSha1 struct {
ProtectionProfile
srtpSessionSalt []byte
srtpSessionAuth hash.Hash
srtpBlock cipher.Block
srtpEncrypted bool
srtcpSessionSalt []byte
srtcpSessionAuth hash.Hash
srtcpBlock cipher.Block
srtcpEncrypted bool
mki []byte
}
func newSrtpCipherAesCmHmacSha1(profile ProtectionProfile, masterKey, masterSalt, mki []byte, encryptSRTP, encryptSRTCP bool) (*srtpCipherAesCmHmacSha1, error) {
if profile == ProtectionProfileNullHmacSha1_80 || profile == ProtectionProfileNullHmacSha1_32 {
encryptSRTP = false
encryptSRTCP = false
}
s := &srtpCipherAesCmHmacSha1{
ProtectionProfile: profile,
srtpEncrypted: encryptSRTP,
srtcpEncrypted: encryptSRTCP,
}
srtpSessionKey, err := aesCmKeyDerivation(labelSRTPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
return nil, err
} else if s.srtpBlock, err = aes.NewCipher(srtpSessionKey); err != nil {
return nil, err
}
srtcpSessionKey, err := aesCmKeyDerivation(labelSRTCPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
return nil, err
} else if s.srtcpBlock, err = aes.NewCipher(srtcpSessionKey); err != nil {
return nil, err
}
if s.srtpSessionSalt, err = aesCmKeyDerivation(labelSRTPSalt, masterKey, masterSalt, 0, len(masterSalt)); err != nil {
return nil, err
} else if s.srtcpSessionSalt, err = aesCmKeyDerivation(labelSRTCPSalt, masterKey, masterSalt, 0, len(masterSalt)); err != nil {
return nil, err
}
authKeyLen, err := profile.AuthKeyLen()
if err != nil {
return nil, err
}
srtpSessionAuthTag, err := aesCmKeyDerivation(labelSRTPAuthenticationTag, masterKey, masterSalt, 0, authKeyLen)
if err != nil {
return nil, err
}
srtcpSessionAuthTag, err := aesCmKeyDerivation(labelSRTCPAuthenticationTag, masterKey, masterSalt, 0, authKeyLen)
if err != nil {
return nil, err
}
s.srtcpSessionAuth = hmac.New(sha1.New, srtcpSessionAuthTag)
s.srtpSessionAuth = hmac.New(sha1.New, srtpSessionAuthTag)
mkiLen := len(mki)
if mkiLen > 0 {
s.mki = make([]byte, mkiLen)
copy(s.mki, mki)
}
return s, nil
}
func (s *srtpCipherAesCmHmacSha1) encryptRTP(dst []byte, header *rtp.Header, payload []byte, roc uint32) (ciphertext []byte, err error) {
// Grow the given buffer to fit the output.
authTagLen, err := s.AuthTagRTPLen()
if err != nil {
return nil, err
}
dst = growBufferSize(dst, header.MarshalSize()+len(payload)+len(s.mki)+authTagLen)
// Copy the header unencrypted.
n, err := header.MarshalTo(dst)
if err != nil {
return nil, err
}
// Encrypt the payload
if s.srtpEncrypted {
counter := generateCounter(header.SequenceNumber, roc, header.SSRC, s.srtpSessionSalt)
if err = xorBytesCTR(s.srtpBlock, counter[:], dst[n:], payload); err != nil {
return nil, err
}
} else {
copy(dst[n:], payload)
}
n += len(payload)
// Generate the auth tag.
authTag, err := s.generateSrtpAuthTag(dst[:n], roc)
if err != nil {
return nil, err
}
// Append the MKI (if used)
if len(s.mki) > 0 {
copy(dst[n:], s.mki)
n += len(s.mki)
}
// Write the auth tag to the dest.
copy(dst[n:], authTag)
return dst, nil
}
func (s *srtpCipherAesCmHmacSha1) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int, roc uint32) ([]byte, error) {
// Split the auth tag and the cipher text into two parts.
authTagLen, err := s.AuthTagRTPLen()
if err != nil {
return nil, err
}
// Split the auth tag and the cipher text into two parts.
actualTag := ciphertext[len(ciphertext)-authTagLen:]
ciphertext = ciphertext[:len(ciphertext)-len(s.mki)-authTagLen]
// Generate the auth tag we expect to see from the ciphertext.
expectedTag, err := s.generateSrtpAuthTag(ciphertext, roc)
if err != nil {
return nil, err
}
// See if the auth tag actually matches.
// We use a constant time comparison to prevent timing attacks.
if subtle.ConstantTimeCompare(actualTag, expectedTag) != 1 {
return nil, ErrFailedToVerifyAuthTag
}
// Write the plaintext header to the destination buffer.
copy(dst, ciphertext[:headerLen])
// Decrypt the ciphertext for the payload.
if s.srtpEncrypted {
counter := generateCounter(header.SequenceNumber, roc, header.SSRC, s.srtpSessionSalt)
err = xorBytesCTR(
s.srtpBlock, counter[:], dst[headerLen:], ciphertext[headerLen:],
)
if err != nil {
return nil, err
}
} else {
copy(dst[headerLen:], ciphertext[headerLen:])
}
return dst, nil
}
func (s *srtpCipherAesCmHmacSha1) encryptRTCP(dst, decrypted []byte, srtcpIndex uint32, ssrc uint32) ([]byte, error) {
dst = allocateIfMismatch(dst, decrypted)
// Encrypt everything after header
if s.srtcpEncrypted {
counter := generateCounter(uint16(srtcpIndex&0xffff), srtcpIndex>>16, ssrc, s.srtcpSessionSalt)
if err := xorBytesCTR(s.srtcpBlock, counter[:], dst[8:], dst[8:]); err != nil {
return nil, err
}
// Add SRTCP Index and set Encryption bit
dst = append(dst, make([]byte, 4)...)
binary.BigEndian.PutUint32(dst[len(dst)-4:], srtcpIndex)
dst[len(dst)-4] |= 0x80
} else {
// Copy the decrypted payload as is
copy(dst[8:], decrypted[8:])
// Add SRTCP Index with Encryption bit cleared
dst = append(dst, make([]byte, 4)...)
binary.BigEndian.PutUint32(dst[len(dst)-4:], srtcpIndex)
}
// Generate the authentication tag
authTag, err := s.generateSrtcpAuthTag(dst)
if err != nil {
return nil, err
}
// Include the MKI if provided
if len(s.mki) > 0 {
dst = append(dst, s.mki...)
}
// Append the auth tag at the end of the buffer
return append(dst, authTag...), nil
}
func (s *srtpCipherAesCmHmacSha1) decryptRTCP(out, encrypted []byte, index, ssrc uint32) ([]byte, error) {
authTagLen, err := s.AuthTagRTCPLen()
if err != nil {
return nil, err
}
tailOffset := len(encrypted) - (authTagLen + len(s.mki) + srtcpIndexSize)
if tailOffset < 8 {
return nil, errTooShortRTCP
}
out = out[0:tailOffset]
expectedTag, err := s.generateSrtcpAuthTag(encrypted[:len(encrypted)-len(s.mki)-authTagLen])
if err != nil {
return nil, err
}
actualTag := encrypted[len(encrypted)-authTagLen:]
if subtle.ConstantTimeCompare(actualTag, expectedTag) != 1 {
return nil, ErrFailedToVerifyAuthTag
}
isEncrypted := encrypted[tailOffset]>>7 != 0
if isEncrypted {
counter := generateCounter(uint16(index&0xffff), index>>16, ssrc, s.srtcpSessionSalt)
err = xorBytesCTR(s.srtcpBlock, counter[:], out[8:], out[8:])
} else {
copy(out[8:], encrypted[8:])
}
return out, err
}
func (s *srtpCipherAesCmHmacSha1) generateSrtpAuthTag(buf []byte, roc uint32) ([]byte, error) {
// https://tools.ietf.org/html/rfc3711#section-4.2
// In the case of SRTP, M SHALL consist of the Authenticated
// Portion of the packet (as specified in Figure 1) concatenated with
// the ROC, M = Authenticated Portion || ROC;
//
// The pre-defined authentication transform for SRTP is HMAC-SHA1
// [RFC2104]. With HMAC-SHA1, the SRTP_PREFIX_LENGTH (Figure 3) SHALL
// be 0. For SRTP (respectively SRTCP), the HMAC SHALL be applied to
// the session authentication key and M as specified above, i.e.,
// HMAC(k_a, M). The HMAC output SHALL then be truncated to the n_tag
// left-most bits.
// - Authenticated portion of the packet is everything BEFORE MKI
// - k_a is the session message authentication key
// - n_tag is the bit-length of the output authentication tag
s.srtpSessionAuth.Reset()
if _, err := s.srtpSessionAuth.Write(buf); err != nil {
return nil, err
}
// For SRTP only, we need to hash the rollover counter as well.
rocRaw := [4]byte{}
binary.BigEndian.PutUint32(rocRaw[:], roc)
_, err := s.srtpSessionAuth.Write(rocRaw[:])
if err != nil {
return nil, err
}
// Truncate the hash to the size indicated by the profile
authTagLen, err := s.AuthTagRTPLen()
if err != nil {
return nil, err
}
return s.srtpSessionAuth.Sum(nil)[0:authTagLen], nil
}
func (s *srtpCipherAesCmHmacSha1) generateSrtcpAuthTag(buf []byte) ([]byte, error) {
// https://tools.ietf.org/html/rfc3711#section-4.2
//
// The pre-defined authentication transform for SRTP is HMAC-SHA1
// [RFC2104]. With HMAC-SHA1, the SRTP_PREFIX_LENGTH (Figure 3) SHALL
// be 0. For SRTP (respectively SRTCP), the HMAC SHALL be applied to
// the session authentication key and M as specified above, i.e.,
// HMAC(k_a, M). The HMAC output SHALL then be truncated to the n_tag
// left-most bits.
// - Authenticated portion of the packet is everything BEFORE MKI
// - k_a is the session message authentication key
// - n_tag is the bit-length of the output authentication tag
s.srtcpSessionAuth.Reset()
if _, err := s.srtcpSessionAuth.Write(buf); err != nil {
return nil, err
}
authTagLen, err := s.AuthTagRTCPLen()
if err != nil {
return nil, err
}
return s.srtcpSessionAuth.Sum(nil)[0:authTagLen], nil
}
func (s *srtpCipherAesCmHmacSha1) getRTCPIndex(in []byte) uint32 {
authTagLen, _ := s.AuthTagRTCPLen()
tailOffset := len(in) - (authTagLen + srtcpIndexSize + len(s.mki))
srtcpIndexBuffer := in[tailOffset : tailOffset+srtcpIndexSize]
return binary.BigEndian.Uint32(srtcpIndexBuffer) &^ (1 << 31)
}
func (s *srtpCipherAesCmHmacSha1) getMKI(in []byte, rtp bool) []byte {
mkiLen := len(s.mki)
if mkiLen == 0 {
return nil
}
var authTagLen int
if rtp {
authTagLen, _ = s.AuthTagRTPLen()
} else {
authTagLen, _ = s.AuthTagRTCPLen()
}
tailOffset := len(in) - (authTagLen + mkiLen)
return in[tailOffset : tailOffset+mkiLen]
}

11
server/vendor/github.com/pion/srtp/v2/stream.go generated vendored Normal file
View File

@@ -0,0 +1,11 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
type readStream interface {
init(child streamSession, ssrc uint32) error
Read(buf []byte) (int, error)
GetSSRC() uint32
}

160
server/vendor/github.com/pion/srtp/v2/stream_srtcp.go generated vendored Normal file
View File

@@ -0,0 +1,160 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"errors"
"io"
"sync"
"time"
"github.com/pion/rtcp"
"github.com/pion/transport/v2/packetio"
)
// Limit the buffer size to 100KB
const srtcpBufferSize = 100 * 1000
// ReadStreamSRTCP handles decryption for a single RTCP SSRC
type ReadStreamSRTCP struct {
mu sync.Mutex
isClosed chan bool
session *SessionSRTCP
ssrc uint32
isInited bool
buffer io.ReadWriteCloser
}
func (r *ReadStreamSRTCP) write(buf []byte) (n int, err error) {
n, err = r.buffer.Write(buf)
if errors.Is(err, packetio.ErrFull) {
// Silently drop data when the buffer is full.
return len(buf), nil
}
return n, err
}
// Used by getOrCreateReadStream
func newReadStreamSRTCP() readStream {
return &ReadStreamSRTCP{}
}
// ReadRTCP reads and decrypts full RTCP packet and its header from the nextConn
func (r *ReadStreamSRTCP) ReadRTCP(buf []byte) (int, *rtcp.Header, error) {
n, err := r.Read(buf)
if err != nil {
return 0, nil, err
}
header := &rtcp.Header{}
err = header.Unmarshal(buf[:n])
if err != nil {
return 0, nil, err
}
return n, header, nil
}
// Read reads and decrypts full RTCP packet from the nextConn
func (r *ReadStreamSRTCP) Read(buf []byte) (int, error) {
return r.buffer.Read(buf)
}
// SetReadDeadline sets the deadline for the Read operation.
// Setting to zero means no deadline.
func (r *ReadStreamSRTCP) SetReadDeadline(t time.Time) error {
if b, ok := r.buffer.(interface {
SetReadDeadline(time.Time) error
}); ok {
return b.SetReadDeadline(t)
}
return nil
}
// Close removes the ReadStream from the session and cleans up any associated state
func (r *ReadStreamSRTCP) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
if !r.isInited {
return errStreamNotInited
}
select {
case <-r.isClosed:
return errStreamAlreadyClosed
default:
err := r.buffer.Close()
if err != nil {
return err
}
r.session.removeReadStream(r.ssrc)
return nil
}
}
func (r *ReadStreamSRTCP) init(child streamSession, ssrc uint32) error {
sessionSRTCP, ok := child.(*SessionSRTCP)
r.mu.Lock()
defer r.mu.Unlock()
if !ok {
return errFailedTypeAssertion
} else if r.isInited {
return errStreamAlreadyInited
}
r.session = sessionSRTCP
r.ssrc = ssrc
r.isInited = true
r.isClosed = make(chan bool)
if r.session.bufferFactory != nil {
r.buffer = r.session.bufferFactory(packetio.RTCPBufferPacket, ssrc)
} else {
// Create a buffer and limit it to 100KB
buff := packetio.NewBuffer()
buff.SetLimitSize(srtcpBufferSize)
r.buffer = buff
}
return nil
}
// GetSSRC returns the SSRC we are demuxing for
func (r *ReadStreamSRTCP) GetSSRC() uint32 {
return r.ssrc
}
// WriteStreamSRTCP is stream for a single Session that is used to encrypt RTCP
type WriteStreamSRTCP struct {
session *SessionSRTCP
}
// WriteRTCP encrypts a RTCP header and its payload to the nextConn
func (w *WriteStreamSRTCP) WriteRTCP(header *rtcp.Header, payload []byte) (int, error) {
headerRaw, err := header.Marshal()
if err != nil {
return 0, err
}
return w.session.write(append(headerRaw, payload...))
}
// Write encrypts and writes a full RTCP packets to the nextConn
func (w *WriteStreamSRTCP) Write(b []byte) (int, error) {
return w.session.write(b)
}
// SetWriteDeadline sets the deadline for the Write operation.
// Setting to zero means no deadline.
func (w *WriteStreamSRTCP) SetWriteDeadline(t time.Time) error {
return w.session.setWriteDeadline(t)
}

157
server/vendor/github.com/pion/srtp/v2/stream_srtp.go generated vendored Normal file
View File

@@ -0,0 +1,157 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"errors"
"io"
"sync"
"time"
"github.com/pion/rtp"
"github.com/pion/transport/v2/packetio"
)
// Limit the buffer size to 1MB
const srtpBufferSize = 1000 * 1000
// ReadStreamSRTP handles decryption for a single RTP SSRC
type ReadStreamSRTP struct {
mu sync.Mutex
isClosed chan bool
session *SessionSRTP
ssrc uint32
isInited bool
buffer io.ReadWriteCloser
}
// Used by getOrCreateReadStream
func newReadStreamSRTP() readStream {
return &ReadStreamSRTP{}
}
func (r *ReadStreamSRTP) init(child streamSession, ssrc uint32) error {
sessionSRTP, ok := child.(*SessionSRTP)
r.mu.Lock()
defer r.mu.Unlock()
if !ok {
return errFailedTypeAssertion
} else if r.isInited {
return errStreamAlreadyInited
}
r.session = sessionSRTP
r.ssrc = ssrc
r.isInited = true
r.isClosed = make(chan bool)
// Create a buffer with a 1MB limit
if r.session.bufferFactory != nil {
r.buffer = r.session.bufferFactory(packetio.RTPBufferPacket, ssrc)
} else {
buff := packetio.NewBuffer()
buff.SetLimitSize(srtpBufferSize)
r.buffer = buff
}
return nil
}
func (r *ReadStreamSRTP) write(buf []byte) (n int, err error) {
n, err = r.buffer.Write(buf)
if errors.Is(err, packetio.ErrFull) {
// Silently drop data when the buffer is full.
return len(buf), nil
}
return n, err
}
// Read reads and decrypts full RTP packet from the nextConn
func (r *ReadStreamSRTP) Read(buf []byte) (int, error) {
return r.buffer.Read(buf)
}
// ReadRTP reads and decrypts full RTP packet and its header from the nextConn
func (r *ReadStreamSRTP) ReadRTP(buf []byte) (int, *rtp.Header, error) {
n, err := r.Read(buf)
if err != nil {
return 0, nil, err
}
header := &rtp.Header{}
_, err = header.Unmarshal(buf[:n])
if err != nil {
return 0, nil, err
}
return n, header, nil
}
// SetReadDeadline sets the deadline for the Read operation.
// Setting to zero means no deadline.
func (r *ReadStreamSRTP) SetReadDeadline(t time.Time) error {
if b, ok := r.buffer.(interface {
SetReadDeadline(time.Time) error
}); ok {
return b.SetReadDeadline(t)
}
return nil
}
// Close removes the ReadStream from the session and cleans up any associated state
func (r *ReadStreamSRTP) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
if !r.isInited {
return errStreamNotInited
}
select {
case <-r.isClosed:
return errStreamAlreadyClosed
default:
err := r.buffer.Close()
if err != nil {
return err
}
r.session.removeReadStream(r.ssrc)
return nil
}
}
// GetSSRC returns the SSRC we are demuxing for
func (r *ReadStreamSRTP) GetSSRC() uint32 {
return r.ssrc
}
// WriteStreamSRTP is stream for a single Session that is used to encrypt RTP
type WriteStreamSRTP struct {
session *SessionSRTP
}
// WriteRTP encrypts a RTP packet and writes to the connection
func (w *WriteStreamSRTP) WriteRTP(header *rtp.Header, payload []byte) (int, error) {
return w.session.writeRTP(header, payload)
}
// Write encrypts and writes a full RTP packets to the nextConn
func (w *WriteStreamSRTP) Write(b []byte) (int, error) {
return w.session.write(b)
}
// SetWriteDeadline sets the deadline for the Write operation.
// Setting to zero means no deadline.
func (w *WriteStreamSRTP) SetWriteDeadline(t time.Time) error {
return w.session.setWriteDeadline(t)
}

36
server/vendor/github.com/pion/srtp/v2/util.go generated vendored Normal file
View File

@@ -0,0 +1,36 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import "bytes"
// Grow the buffer size to the given number of bytes.
func growBufferSize(buf []byte, size int) []byte {
if size <= cap(buf) {
return buf[:size]
}
buf2 := make([]byte, size)
copy(buf2, buf)
return buf2
}
// Check if buffers match, if not allocate a new buffer and return it
func allocateIfMismatch(dst, src []byte) []byte {
if dst == nil {
dst = make([]byte, len(src))
copy(dst, src)
} else if !bytes.Equal(dst, src) { // bytes.Equal returns on ref equality, no optimization needed
extraNeeded := len(src) - len(dst)
if extraNeeded > 0 {
dst = append(dst, make([]byte, extraNeeded)...)
} else if extraNeeded < 0 {
dst = dst[:len(dst)+extraNeeded]
}
copy(dst, src)
}
return dst
}