1
0
Fork 0
mirror of https://github.com/ossrs/srs.git synced 2025-03-09 15:49:59 +00:00

TEST: Upgrade pion to v3.2.9. (#3567)

------

Co-authored-by: chundonglinlin <chundonglinlin@163.com>
This commit is contained in:
Winlin 2023-06-05 11:25:04 +08:00 committed by GitHub
parent 104cf14d68
commit df854339ea
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
1383 changed files with 118469 additions and 41421 deletions

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
### JetBrains IDE ###
#####################
.idea/
@ -22,3 +25,4 @@ cover.out
*.wasm
examples/sfu-ws/cert.pem
examples/sfu-ws/key.pem
wasm_exec.js

View file

@ -1,3 +1,6 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
linters-settings:
govet:
check-shadowing: true
@ -10,19 +13,34 @@ linters-settings:
modules:
- github.com/pkg/errors:
recommendations:
- errors
- 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
- deadcode # Finds unused code
- 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
@ -35,40 +53,59 @@ linters:
- 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
- golint # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
- 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
- scopelint # Scopelint checks for unpinned variables in go programs
- 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
- structcheck # Finds unused struct fields
- 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
- varcheck # Finds unused global variables and constants
- 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:
@ -78,12 +115,23 @@ issues:
- 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

View file

@ -0,0 +1,36 @@
# 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>
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

View file

@ -1,20 +0,0 @@
<h1 align="center">
Design
</h1>
### Portable
Pion SRTP is written in Go and extremely portable. Anywhere Golang runs, Pion SRTP should work as well! Instead of dealing with complicated
cross-compiling of multiple libraries, you now can run anywhere with one `go build`
### Simple API
The API is based on an io.ReadWriteCloser.
### Readable
If code comes from an RFC we try to make sure everything is commented with a link to the spec.
This makes learning and debugging easier, this library was written to also serve as a guide for others.
### Tested
Every commit is tested via travis-ci Go provides fantastic facilities for testing, and more will be added as time goes on.
### Shared libraries
Every pion product is built using shared libraries, allowing others to review and reuse our libraries.

View file

@ -1,21 +1,9 @@
MIT License
Copyright (c) 2018
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:
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 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.
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.

View file

@ -9,46 +9,27 @@
<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>
<a href="https://travis-ci.org/pion/srtp"><img src="https://travis-ci.org/pion/srtp.svg?branch=master" alt="Build Status"></a>
<a href="https://pkg.go.dev/github.com/pion/srtp"><img src="https://godoc.org/github.com/pion/srtp?status.svg" alt="GoDoc"></a>
<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>
See [DESIGN.md](DESIGN.md) for an overview of features and future goals.
### 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 [Golang Slack](https://invite.slack.golangbridge.org/). Sign up and join the **#pion** channel for discussions and support. You can also use [Pion mailing list](https://groups.google.com/forum/#!forum/pion).
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:
* [Sean DuBois](https://github.com/Sean-Der) - *Original Author*
* [Michiel De Backker](https://github.com/backkem) - *io.Writer interfaces*
* [Tobias Fridén](https://github.com/tobiasfriden) *SRTP authentication verification*
* [chenkaiC4](https://github.com/chenkaiC4) - *Fix GolangCI Linter*
* [Luke Curley](https://github.com/kixelated) - *Performance*
* [Chris Hiszpanski](https://github.com/thinkski) - *Fix out-of-bounds access*
* [Yutaka Takeda](https://github.com/enobufs) - *Fix log messages*
* [Max Hawkins](https://github.com/maxhawkins)
* [Woodrow Douglass](https://github.com/wdouglass)
* [Hugo Arregui](https://github.com/hugoArregui)
* [Atsushi Watanabe](https://github.com/at-wat)
* [Novel Corpse](https://github.com/NovelCorpse)
* [Jerko Steiner](https://github.com/jeremija)
* [Juliusz Chroboczek](https://github.com/jech)
* [Mission Liao](https://github.com/mission-liao)
* [Orlando](https://github.com/OrlandoCo)
* [Tarrence van As](https://github.com/tarrencev)
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

View file

@ -3,6 +3,8 @@
#
# 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:

View file

@ -1,9 +1,12 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"fmt"
"github.com/pion/transport/replaydetector"
"github.com/pion/transport/v2/replaydetector"
)
const (
@ -15,8 +18,11 @@ const (
labelSRTCPAuthenticationTag = 0x04
labelSRTCPSalt = 0x05
maxROCDisorder = 100
maxSequenceNumber = 65535
maxROC = (1 << 32) - 1
seqNumMedian = 1 << 15
seqNumMax = 1 << 16
srtcpIndexSize = 4
)
@ -24,9 +30,8 @@ const (
// Encrypt/Decrypt state for a single SRTP SSRC
type srtpSSRCState struct {
ssrc uint32
rolloverCounter uint32
rolloverHasProcessed bool
lastSequenceNumber uint16
index uint64
replayDetector replaydetector.ReplayDetector
}
@ -40,6 +45,9 @@ type srtcpSSRCState struct {
// 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
@ -56,8 +64,7 @@ type Context struct {
// 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))
//
// decCtx, err := srtp.CreateContext(key, salt, profile, srtp.SRTPReplayProtection(256))
func CreateContext(masterKey, masterSalt []byte, profile ProtectionProfile, opts ...ContextOption) (c *Context, err error) {
keyLen, err := profile.keyLen()
if err != nil {
@ -81,10 +88,10 @@ func CreateContext(masterKey, masterSalt []byte, profile ProtectionProfile, opts
}
switch profile {
case ProtectionProfileAeadAes128Gcm:
c.cipher, err = newSrtpCipherAeadAesGcm(masterKey, masterSalt)
case ProtectionProfileAes128CmHmacSha1_80:
c.cipher, err = newSrtpCipherAesCmHmacSha1(masterKey, masterSalt)
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
c.cipher, err = newSrtpCipherAeadAesGcm(profile, masterKey, masterSalt)
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80:
c.cipher, err = newSrtpCipherAesCmHmacSha1(profile, masterKey, masterSalt)
default:
return nil, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, profile)
}
@ -108,32 +115,52 @@ func CreateContext(masterKey, masterSalt []byte, profile ProtectionProfile, opts
}
// https://tools.ietf.org/html/rfc3550#appendix-A.1
func (s *srtpSSRCState) nextRolloverCount(sequenceNumber uint16) (uint32, func()) {
roc := s.rolloverCounter
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))
switch {
case !s.rolloverHasProcessed:
case sequenceNumber == 0: // We exactly hit the rollover count
// Only update rolloverCounter if lastSequenceNumber is greater then maxROCDisorder
// otherwise we already incremented for disorder
if s.lastSequenceNumber > maxROCDisorder {
roc++
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
}
case s.lastSequenceNumber < maxROCDisorder &&
sequenceNumber > (maxSequenceNumber-maxROCDisorder):
// Our last sequence number incremented because we crossed 0, but then our current number was within maxROCDisorder of the max
// So we fell behind, drop to account for jitter
roc--
case sequenceNumber < maxROCDisorder &&
s.lastSequenceNumber > (maxSequenceNumber-maxROCDisorder):
// our current is within a maxROCDisorder of 0
// and our last sequence number was a high sequence number, increment to account for jitter
roc++
}
return roc, func() {
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
s.lastSequenceNumber = sequenceNumber
s.rolloverCounter = roc
return
}
if difference > 0 {
s.index += uint64(difference)
}
}
@ -171,13 +198,14 @@ func (c *Context) ROC(ssrc uint32) (uint32, bool) {
if !ok {
return 0, false
}
return s.rolloverCounter, true
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.rolloverCounter = roc
s.index = uint64(roc) << 16
s.rolloverHasProcessed = false
}
// Index returns SRTCP index value of specified SSRC.

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
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
@ -18,6 +21,8 @@ var (
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")
errStreamNotInited = errors.New("stream has not been inited, unable to close")
errStreamAlreadyClosed = errors.New("stream is already closed")
@ -25,16 +30,16 @@ var (
errFailedTypeAssertion = errors.New("failed to cast child")
)
type errorDuplicated struct {
type duplicatedError struct {
Proto string // srtp or srtcp
SSRC uint32
Index uint32 // sequence number or index
}
func (e *errorDuplicated) Error() string {
func (e *duplicatedError) Error() string {
return fmt.Sprintf("%s ssrc=%d index=%d: %v", e.Proto, e.SSRC, e.Index, errDuplicated)
}
func (e *errorDuplicated) Unwrap() error {
func (e *duplicatedError) Unwrap() error {
return errDuplicated
}

View file

@ -1,11 +0,0 @@
module github.com/pion/srtp/v2
go 1.14
require (
github.com/pion/logging v0.2.2
github.com/pion/rtcp v1.2.6
github.com/pion/rtp v1.6.2
github.com/pion/transport v0.12.2
github.com/stretchr/testify v1.6.1
)

View file

@ -1,32 +0,0 @@
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY=
github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms=
github.com/pion/randutil v0.1.0 h1:CFG1UdESneORglEsnimhUjf33Rwjubwj6xfiOXBa3mA=
github.com/pion/randutil v0.1.0/go.mod h1:XcJrSMMbbMRhASFVOlj/5hQial/Y8oH/HVo7TBZq+j8=
github.com/pion/rtcp v1.2.6 h1:1zvwBbyd0TeEuuWftrd/4d++m+/kZSeiguxU61LFWpo=
github.com/pion/rtcp v1.2.6/go.mod h1:52rMNPWFsjr39z9B9MhnkqhPLoeHTv1aN63o/42bWE0=
github.com/pion/rtp v1.6.2 h1:iGBerLX6JiDjB9NXuaPzHyxHFG9JsIEdgwTC0lp5n/U=
github.com/pion/rtp v1.6.2/go.mod h1:bDb5n+BFZxXx0Ea7E5qe+klMuqiBrP+w8XSjiWtCUko=
github.com/pion/transport v0.12.2 h1:WYEjhloRHt1R86LhUKjC5y+P52Y11/QqEUalvtzVoys=
github.com/pion/transport v0.12.2/go.mod h1:N3+vZQD9HlDP5GWkZ85LohxNsDcNgofQmyL6ojX5d8Q=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20201201195509-5d6afe98e0b7 h1:3uJsdck53FDIpWwLeAXlia9p4C8j0BO2xZrqzKpL0D8=
golang.org/x/net v0.0.0-20201201195509-5d6afe98e0b7/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
@ -19,7 +22,7 @@ func aesCmKeyDerivation(label byte, masterKey, masterSalt []byte, indexOverKdr i
nMasterKey := len(masterKey)
nMasterSalt := len(masterSalt)
prfIn := make([]byte, nMasterKey)
prfIn := make([]byte, 16)
copy(prfIn[:nMasterSalt], masterSalt)
prfIn[7] ^= label
@ -32,8 +35,8 @@ func aesCmKeyDerivation(label byte, masterKey, masterSalt []byte, indexOverKdr i
out := make([]byte, ((outLen+nMasterKey)/nMasterKey)*nMasterKey)
var i uint16
for n := 0; n < outLen; n += nMasterKey {
binary.BigEndian.PutUint16(prfIn[nMasterKey-2:], i)
for n := 0; n < outLen; n += block.BlockSize() {
binary.BigEndian.PutUint16(prfIn[len(prfIn)-2:], i)
block.Encrypt(out[n:n+nMasterKey], prfIn)
i++
}
@ -48,16 +51,19 @@ func aesCmKeyDerivation(label byte, masterKey, masterSalt []byte, indexOverKdr i
// - 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) []byte {
counter := make([]byte, 16)
func generateCounter(sequenceNumber uint16, rolloverCounter uint32, ssrc uint32, sessionSalt []byte) (counter [16]byte) {
copy(counter[:], sessionSalt)
binary.BigEndian.PutUint32(counter[4:], ssrc)
binary.BigEndian.PutUint32(counter[8:], rolloverCounter)
binary.BigEndian.PutUint32(counter[12:], uint32(sequenceNumber)<<16)
for i := range sessionSalt {
counter[i] ^= sessionSalt[i]
}
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
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
const labelExtractorDtlsSrtp = "EXTRACTOR-dtls_srtp"

View file

@ -1,17 +1,20 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"github.com/pion/transport/replaydetector"
"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:golint
func SRTPReplayProtection(windowSize uint) ContextOption { // nolint:revive
return func(c *Context) error {
c.newSRTPReplayDetector = func() replaydetector.ReplayDetector {
return replaydetector.WithWrap(windowSize, maxSequenceNumber)
return replaydetector.New(windowSize, maxROC<<16|maxSequenceNumber)
}
return nil
}
@ -21,14 +24,14 @@ func SRTPReplayProtection(windowSize uint) ContextOption { // nolint:golint
func SRTCPReplayProtection(windowSize uint) ContextOption {
return func(c *Context) error {
c.newSRTCPReplayDetector = func() replaydetector.ReplayDetector {
return replaydetector.WithWrap(windowSize, maxSRTCPIndex)
return replaydetector.New(windowSize, maxSRTCPIndex)
}
return nil
}
}
// SRTPNoReplayProtection disables SRTP replay protection.
func SRTPNoReplayProtection() ContextOption { // nolint:golint
func SRTPNoReplayProtection() ContextOption { // nolint:revive
return func(c *Context) error {
c.newSRTPReplayDetector = func() replaydetector.ReplayDetector {
return &nopReplayDetector{}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import "fmt"
@ -6,17 +9,20 @@ import "fmt"
type ProtectionProfile uint16
// Supported protection profiles
// See https://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
const (
ProtectionProfileAes128CmHmacSha1_80 ProtectionProfile = 0x0001
ProtectionProfileAes128CmHmacSha1_32 ProtectionProfile = 0x0002
ProtectionProfileAeadAes128Gcm ProtectionProfile = 0x0007
ProtectionProfileAeadAes256Gcm ProtectionProfile = 0x0008
)
func (p ProtectionProfile) keyLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_80:
fallthrough
case ProtectionProfileAeadAes128Gcm:
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80, ProtectionProfileAeadAes128Gcm:
return 16, nil
case ProtectionProfileAeadAes256Gcm:
return 32, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
@ -24,21 +30,45 @@ func (p ProtectionProfile) keyLen() (int, error) {
func (p ProtectionProfile) saltLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_80:
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80:
return 14, nil
case ProtectionProfileAeadAes128Gcm:
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 12, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
func (p ProtectionProfile) authTagLen() (int, error) {
func (p ProtectionProfile) rtpAuthTagLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_80:
return (&srtpCipherAesCmHmacSha1{}).authTagLen(), nil
case ProtectionProfileAeadAes128Gcm:
return (&srtpCipherAeadAesGcm{}).authTagLen(), nil
return 10, nil
case ProtectionProfileAes128CmHmacSha1_32:
return 4, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 0, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
func (p ProtectionProfile) rtcpAuthTagLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80:
return 10, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 0, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
}
func (p ProtectionProfile) aeadAuthTagLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80:
return 0, nil
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 16, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)
}
@ -46,9 +76,9 @@ func (p ProtectionProfile) authTagLen() (int, error) {
func (p ProtectionProfile) authKeyLen() (int, error) {
switch p {
case ProtectionProfileAes128CmHmacSha1_80:
case ProtectionProfileAes128CmHmacSha1_32, ProtectionProfileAes128CmHmacSha1_80:
return 20, nil
case ProtectionProfileAeadAes128Gcm:
case ProtectionProfileAeadAes128Gcm, ProtectionProfileAeadAes256Gcm:
return 0, nil
default:
return 0, fmt.Errorf("%w: %#v", errNoSuchSRTPProfile, p)

View file

@ -1,15 +1,6 @@
{
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
"extends": [
"config:base"
],
"postUpdateOptions": [
"gomodTidy"
],
"commitBody": "Generated by renovateBot",
"packageRules": [
{
"packagePatterns": ["^golang.org/x/"],
"schedule": ["on the first day of the month"]
}
"github>pion/renovate-config"
]
}

View file

@ -1,12 +1,17 @@
// 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/packetio"
"github.com/pion/transport/v2/packetio"
)
type streamSession interface {
@ -20,7 +25,8 @@ type session struct {
localContext, remoteContext *Context
localOptions, remoteOptions []ContextOption
newStream chan readStream
newStream chan readStream
acceptStreamTimeout time.Time
started chan interface{}
closed chan interface{}
@ -40,10 +46,11 @@ type session struct {
// 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
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.
@ -117,6 +124,10 @@ func (s *session) start(localMasterKey, localMasterSalt, remoteMasterKey, remote
return err
}
if err = s.nextConn.SetReadDeadline(s.acceptStreamTimeout); err != nil {
return err
}
go func() {
defer func() {
close(s.newStream)
@ -132,7 +143,7 @@ func (s *session) start(localMasterKey, localMasterSalt, remoteMasterKey, remote
var i int
i, err = s.nextConn.Read(b)
if err != nil {
if err != io.EOF {
if !errors.Is(err, io.EOF) {
s.log.Error(err.Error())
}
return

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
@ -46,15 +49,16 @@ func NewSessionSRTCP(conn net.Conn, config *Config) (*SessionSRTCP, error) { //n
s := &SessionSRTCP{
session: session{
nextConn: conn,
localOptions: localOpts,
remoteOptions: remoteOpts,
readStreams: map[uint32]readStream{},
newStream: make(chan readStream),
started: make(chan interface{}),
closed: make(chan interface{}),
bufferFactory: config.BufferFactory,
log: loggerFactory.NewLogger("srtp"),
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}
@ -114,8 +118,11 @@ func (s *SessionSRTCP) write(buf []byte) (int, error) {
return 0, errStartedChannelUsedIncorrectly
}
ibuf := bufferpool.Get()
defer bufferpool.Put(ibuf)
s.session.localContextMutex.Lock()
encrypted, err := s.localContext.EncryptRTCP(nil, buf, nil)
encrypted, err := s.localContext.EncryptRTCP(ibuf.([]byte), buf, nil)
s.session.localContextMutex.Unlock()
if err != nil {
@ -162,6 +169,9 @@ func (s *SessionSRTCP) decrypt(buf []byte) error {
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
}

View file

@ -1,7 +1,11 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
"net"
"sync"
"time"
"github.com/pion/logging"
@ -46,15 +50,16 @@ func NewSessionSRTP(conn net.Conn, config *Config) (*SessionSRTP, error) { //nol
s := &SessionSRTP{
session: session{
nextConn: conn,
localOptions: localOpts,
remoteOptions: remoteOpts,
readStreams: map[uint32]readStream{},
newStream: make(chan readStream),
started: make(chan interface{}),
closed: make(chan interface{}),
bufferFactory: config.BufferFactory,
log: loggerFactory.NewLogger("srtp"),
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}
@ -111,21 +116,41 @@ func (s *SessionSRTP) Close() error {
func (s *SessionSRTP) write(b []byte) (int, error) {
packet := &rtp.Packet{}
err := packet.Unmarshal(b)
if err != nil {
return 0, nil
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(nil, header, payload)
encrypted, err := s.localContext.encryptRTP(ibuf.([]byte), header, payload)
s.session.localContextMutex.Unlock()
if err != nil {
@ -141,7 +166,8 @@ func (s *SessionSRTP) setWriteDeadline(t time.Time) error {
func (s *SessionSRTP) decrypt(buf []byte) error {
h := &rtp.Header{}
if err := h.Unmarshal(buf); err != nil {
headerLen, err := h.Unmarshal(buf)
if err != nil {
return err
}
@ -149,6 +175,9 @@ func (s *SessionSRTP) decrypt(buf []byte) error {
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
}
@ -157,7 +186,7 @@ func (s *SessionSRTP) decrypt(buf []byte) error {
return errFailedTypeAssertion
}
decrypted, err := s.remoteContext.decryptRTP(buf, buf, h)
decrypted, err := s.remoteContext.decryptRTP(buf, buf, h, headerLen)
if err != nil {
return err
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
@ -11,9 +14,18 @@ const maxSRTCPIndex = 0x7FFFFFFF
func (c *Context) decryptRTCP(dst, encrypted []byte) ([]byte, error) {
out := allocateIfMismatch(dst, encrypted)
tailOffset := len(encrypted) - (c.cipher.authTagLen() + srtcpIndexSize)
if tailOffset < 0 {
authTagLen, err := c.cipher.rtcpAuthTagLen()
if err != nil {
return nil, err
}
aeadAuthTagLen, err := c.cipher.aeadAuthTagLen()
if err != nil {
return nil, err
}
tailOffset := len(encrypted) - (authTagLen + srtcpIndexSize)
if tailOffset < aeadAuthTagLen {
return nil, fmt.Errorf("%w: %d", errTooShortRTCP, len(encrypted))
} else if isEncrypted := encrypted[tailOffset] >> 7; isEncrypted == 0 {
return out, nil
@ -25,10 +37,10 @@ func (c *Context) decryptRTCP(dst, encrypted []byte) ([]byte, error) {
s := c.getSRTCPSSRCState(ssrc)
markAsValid, ok := s.replayDetector.Check(uint64(index))
if !ok {
return nil, &errorDuplicated{Proto: "srtcp", SSRC: ssrc, Index: index}
return nil, &duplicatedError{Proto: "srtcp", SSRC: ssrc, Index: index}
}
out, err := c.cipher.decryptRTCP(out, encrypted, index, ssrc)
out, err = c.cipher.decryptRTCP(out, encrypted, index, ssrc)
if err != nil {
return nil, err
}
@ -54,11 +66,16 @@ func (c *Context) encryptRTCP(dst, decrypted []byte) ([]byte, error) {
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++
if s.srtcpIndex > maxSRTCPIndex {
s.srtcpIndex = 0
}
return c.cipher.encryptRTCP(dst, decrypted, s.srtcpIndex, ssrc)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package srtp implements Secure Real-time Transport Protocol
package srtp
@ -5,26 +8,32 @@ import (
"github.com/pion/rtp"
)
func (c *Context) decryptRTP(dst, ciphertext []byte, header *rtp.Header) ([]byte, error) {
func (c *Context) decryptRTP(dst, ciphertext []byte, header *rtp.Header, headerLen int) ([]byte, error) {
s := c.getSRTPSSRCState(header.SSRC)
markAsValid, ok := s.replayDetector.Check(uint64(header.SequenceNumber))
roc, diff, _ := s.nextRolloverCount(header.SequenceNumber)
markAsValid, ok := s.replayDetector.Check(
(uint64(roc) << 16) | uint64(header.SequenceNumber),
)
if !ok {
return nil, &errorDuplicated{
return nil, &duplicatedError{
Proto: "srtp", SSRC: header.SSRC, Index: uint32(header.SequenceNumber),
}
}
dst = growBufferSize(dst, len(ciphertext)-c.cipher.authTagLen())
roc, updateROC := s.nextRolloverCount(header.SequenceNumber)
authTagLen, err := c.cipher.rtpAuthTagLen()
if err != nil {
return nil, err
}
dst = growBufferSize(dst, len(ciphertext)-authTagLen)
dst, err := c.cipher.decryptRTP(dst, ciphertext, header, roc)
dst, err = c.cipher.decryptRTP(dst, ciphertext, header, headerLen, roc)
if err != nil {
return nil, err
}
markAsValid()
updateROC()
s.updateRolloverCount(header.SequenceNumber, diff)
return dst, nil
}
@ -34,11 +43,12 @@ func (c *Context) DecryptRTP(dst, encrypted []byte, header *rtp.Header) ([]byte,
header = &rtp.Header{}
}
if err := header.Unmarshal(encrypted); err != nil {
headerLen, err := header.Unmarshal(encrypted)
if err != nil {
return nil, err
}
return c.decryptRTP(dst, encrypted, header)
return c.decryptRTP(dst, encrypted, header, headerLen)
}
// EncryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided.
@ -49,11 +59,12 @@ func (c *Context) EncryptRTP(dst []byte, plaintext []byte, header *rtp.Header) (
header = &rtp.Header{}
}
if err := header.Unmarshal(plaintext); err != nil {
headerLen, err := header.Unmarshal(plaintext)
if err != nil {
return nil, err
}
return c.encryptRTP(dst, header, plaintext[header.PayloadOffset:])
return c.encryptRTP(dst, header, plaintext[headerLen:])
}
// encryptRTP marshals and encrypts an RTP packet, writing to the dst buffer provided.
@ -61,8 +72,15 @@ func (c *Context) EncryptRTP(dst []byte, plaintext []byte, header *rtp.Header) (
// 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, updateROC := s.nextRolloverCount(header.SequenceNumber)
updateROC()
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)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import "github.com/pion/rtp"
@ -5,12 +8,43 @@ import "github.com/pion/rtp"
// cipher represents a implementation of one
// of the SRTP Specific ciphers
type srtpCipher interface {
authTagLen() int
// authTagLen returns auth key length of the cipher.
// See the note below.
rtpAuthTagLen() (int, error)
rtcpAuthTagLen() (int, error)
// aeadAuthTagLen returns AEAD auth key length of the cipher.
// See the note below.
aeadAuthTagLen() (int, error)
getRTCPIndex([]byte) uint32
encryptRTP([]byte, *rtp.Header, []byte, uint32) ([]byte, error)
encryptRTCP([]byte, []byte, uint32, uint32) ([]byte, error)
decryptRTP([]byte, []byte, *rtp.Header, 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

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
@ -13,13 +16,15 @@ const (
)
type srtpCipherAeadAesGcm struct {
ProtectionProfile
srtpCipher, srtcpCipher cipher.AEAD
srtpSessionSalt, srtcpSessionSalt []byte
}
func newSrtpCipherAeadAesGcm(masterKey, masterSalt []byte) (*srtpCipherAeadAesGcm, error) {
s := &srtpCipherAeadAesGcm{}
func newSrtpCipherAeadAesGcm(profile ProtectionProfile, masterKey, masterSalt []byte) (*srtpCipherAeadAesGcm, error) {
s := &srtpCipherAeadAesGcm{ProtectionProfile: profile}
srtpSessionKey, err := aesCmKeyDerivation(labelSRTPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
@ -60,59 +65,91 @@ func newSrtpCipherAeadAesGcm(masterKey, masterSalt []byte) (*srtpCipherAeadAesGc
return s, nil
}
func (s *srtpCipherAeadAesGcm) authTagLen() int {
return 16
}
func (s *srtpCipherAeadAesGcm) encryptRTP(dst []byte, header *rtp.Header, payload []byte, roc uint32) (ciphertext []byte, err error) {
hdr, err := header.Marshal()
// 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)
n, err := header.MarshalTo(dst)
if err != nil {
return nil, err
}
iv := s.rtpInitializationVector(header, roc)
out := s.srtpCipher.Seal(nil, iv, payload, hdr)
return append(hdr, out...), nil
s.srtpCipher.Seal(dst[n:n], iv[:], payload, dst[:n])
return dst, nil
}
func (s *srtpCipherAeadAesGcm) decryptRTP(dst, ciphertext []byte, header *rtp.Header, roc uint32) ([]byte, error) {
iv := s.rtpInitializationVector(header, roc)
out, err := s.srtpCipher.Open(nil, iv, ciphertext[header.PayloadOffset:], ciphertext[:header.PayloadOffset])
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
if nDst < 0 {
// Size of ciphertext is shorter than AEAD auth tag len.
return nil, errFailedToVerifyAuthTag
}
dst = growBufferSize(dst, nDst)
out = append(make([]byte, header.PayloadOffset), out...)
copy(out, ciphertext[:header.PayloadOffset])
iv := s.rtpInitializationVector(header, roc)
return out, nil
if _, err := s.srtpCipher.Open(
dst[headerLen:headerLen], iv[:], ciphertext[headerLen:], ciphertext[:headerLen],
); err != nil {
return nil, err
}
copy(dst[:headerLen], ciphertext[:headerLen])
return dst, nil
}
func (s *srtpCipherAeadAesGcm) encryptRTCP(dst, decrypted []byte, srtcpIndex uint32, ssrc uint32) ([]byte, error) {
iv := s.rtcpInitializationVector(srtcpIndex, ssrc)
aad := s.rtcpAdditionalAuthenticatedData(decrypted, srtcpIndex)
out := s.srtcpCipher.Seal(nil, iv, decrypted[8:], aad)
out = append(make([]byte, 8), out...)
copy(out, decrypted[:8])
out = append(out, aad[8:]...)
return out, nil
}
func (s *srtpCipherAeadAesGcm) decryptRTCP(out, encrypted []byte, srtcpIndex, ssrc uint32) ([]byte, error) {
iv := s.rtcpInitializationVector(srtcpIndex, ssrc)
aad := s.rtcpAdditionalAuthenticatedData(encrypted, srtcpIndex)
decrypted, err := s.srtcpCipher.Open(nil, iv, encrypted[8:len(encrypted)-srtcpIndexSize], aad)
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)
decrypted = append(encrypted[:8], decrypted...)
return decrypted, nil
iv := s.rtcpInitializationVector(srtcpIndex, ssrc)
aad := s.rtcpAdditionalAuthenticatedData(decrypted, srtcpIndex)
s.srtcpCipher.Seal(dst[8:8], iv[:], decrypted[8:], aad[:])
copy(dst[:8], decrypted[:8])
copy(dst[aadPos:aadPos+4], aad[8:12])
return dst, nil
}
func (s *srtpCipherAeadAesGcm) decryptRTCP(dst, encrypted []byte, srtcpIndex, ssrc uint32) ([]byte, error) {
aadPos := len(encrypted) - srtcpIndexSize
// 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)
iv := s.rtcpInitializationVector(srtcpIndex, ssrc)
aad := s.rtcpAdditionalAuthenticatedData(encrypted, srtcpIndex)
if _, err := s.srtcpCipher.Open(dst[8:8], iv[:], encrypted[8:aadPos], aad[:]); err != nil {
return nil, err
}
copy(dst[:8], encrypted[:8])
return dst, nil
}
// The 12-octet IV used by AES-GCM SRTP is formed by first concatenating
@ -121,8 +158,8 @@ func (s *srtpCipherAeadAesGcm) decryptRTCP(out, encrypted []byte, srtcpIndex, ss
// 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) []byte {
iv := make([]byte, 12)
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)
@ -140,8 +177,8 @@ func (s *srtpCipherAeadAesGcm) rtpInitializationVector(header *rtp.Header, roc u
// form the 12-octet IV.
//
// https://tools.ietf.org/html/rfc7714#section-9.1
func (s *srtpCipherAeadAesGcm) rtcpInitializationVector(srtcpIndex uint32, ssrc uint32) []byte {
iv := make([]byte, 12)
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)
@ -157,10 +194,10 @@ func (s *srtpCipherAeadAesGcm) rtcpInitializationVector(srtcpIndex uint32, ssrc
// "ESRTCP word"
//
// https://tools.ietf.org/html/rfc7714#section-17
func (s *srtpCipherAeadAesGcm) rtcpAdditionalAuthenticatedData(rtcpPacket []byte, srtcpIndex uint32) []byte {
aad := make([]byte, 12)
func (s *srtpCipherAeadAesGcm) rtcpAdditionalAuthenticatedData(rtcpPacket []byte, srtcpIndex uint32) [12]byte {
var aad [12]byte
copy(aad, rtcpPacket[:8])
copy(aad[:], rtcpPacket[:8])
binary.BigEndian.PutUint32(aad[8:], srtcpIndex)
aad[8] |= rtcpEncryptionFlag

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import ( //nolint:gci
@ -13,6 +16,8 @@ import ( //nolint:gci
)
type srtpCipherAesCmHmacSha1 struct {
ProtectionProfile
srtpSessionSalt []byte
srtpSessionAuth hash.Hash
srtpBlock cipher.Block
@ -22,8 +27,8 @@ type srtpCipherAesCmHmacSha1 struct {
srtcpBlock cipher.Block
}
func newSrtpCipherAesCmHmacSha1(masterKey, masterSalt []byte) (*srtpCipherAesCmHmacSha1, error) {
s := &srtpCipherAesCmHmacSha1{}
func newSrtpCipherAesCmHmacSha1(profile ProtectionProfile, masterKey, masterSalt []byte) (*srtpCipherAesCmHmacSha1, error) {
s := &srtpCipherAesCmHmacSha1{ProtectionProfile: profile}
srtpSessionKey, err := aesCmKeyDerivation(labelSRTPEncryption, masterKey, masterSalt, 0, len(masterKey))
if err != nil {
return nil, err
@ -44,7 +49,7 @@ func newSrtpCipherAesCmHmacSha1(masterKey, masterSalt []byte) (*srtpCipherAesCmH
return nil, err
}
authKeyLen, err := ProtectionProfileAes128CmHmacSha1_80.authKeyLen()
authKeyLen, err := profile.authKeyLen()
if err != nil {
return nil, err
}
@ -64,13 +69,13 @@ func newSrtpCipherAesCmHmacSha1(masterKey, masterSalt []byte) (*srtpCipherAesCmH
return s, nil
}
func (s *srtpCipherAesCmHmacSha1) authTagLen() int {
return 10
}
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.
dst = growBufferSize(dst, header.MarshalSize()+len(payload)+s.authTagLen())
authTagLen, err := s.rtpAuthTagLen()
if err != nil {
return nil, err
}
dst = growBufferSize(dst, header.MarshalSize()+len(payload)+authTagLen)
// Copy the header unencrypted.
n, err := header.MarshalTo(dst)
@ -80,8 +85,9 @@ func (s *srtpCipherAesCmHmacSha1) encryptRTP(dst []byte, header *rtp.Header, pay
// Encrypt the payload
counter := generateCounter(header.SequenceNumber, roc, header.SSRC, s.srtpSessionSalt)
stream := cipher.NewCTR(s.srtpBlock, counter)
stream.XORKeyStream(dst[n:], payload)
if err = xorBytesCTR(s.srtpBlock, counter[:], dst[n:], payload); err != nil {
return nil, err
}
n += len(payload)
// Generate the auth tag.
@ -96,10 +102,14 @@ func (s *srtpCipherAesCmHmacSha1) encryptRTP(dst []byte, header *rtp.Header, pay
return dst, nil
}
func (s *srtpCipherAesCmHmacSha1) decryptRTP(dst, ciphertext []byte, header *rtp.Header, roc uint32) ([]byte, error) {
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.
actualTag := ciphertext[len(ciphertext)-s.authTagLen():]
ciphertext = ciphertext[:len(ciphertext)-s.authTagLen()]
authTagLen, err := s.rtpAuthTagLen()
if err != nil {
return nil, err
}
actualTag := ciphertext[len(ciphertext)-authTagLen:]
ciphertext = ciphertext[:len(ciphertext)-authTagLen]
// Generate the auth tag we expect to see from the ciphertext.
expectedTag, err := s.generateSrtpAuthTag(ciphertext, roc)
@ -114,21 +124,24 @@ func (s *srtpCipherAesCmHmacSha1) decryptRTP(dst, ciphertext []byte, header *rtp
}
// Write the plaintext header to the destination buffer.
copy(dst, ciphertext[:header.PayloadOffset])
copy(dst, ciphertext[:headerLen])
// Decrypt the ciphertext for the payload.
counter := generateCounter(header.SequenceNumber, roc, header.SSRC, s.srtpSessionSalt)
stream := cipher.NewCTR(s.srtpBlock, counter)
stream.XORKeyStream(dst[header.PayloadOffset:], ciphertext[header.PayloadOffset:])
return dst, nil
err = xorBytesCTR(
s.srtpBlock, counter[:], dst[headerLen:], ciphertext[headerLen:],
)
return dst, err
}
func (s *srtpCipherAesCmHmacSha1) encryptRTCP(dst, decrypted []byte, srtcpIndex uint32, ssrc uint32) ([]byte, error) {
dst = allocateIfMismatch(dst, decrypted)
// Encrypt everything after header
stream := cipher.NewCTR(s.srtcpBlock, generateCounter(uint16(srtcpIndex&0xffff), srtcpIndex>>16, ssrc, s.srtcpSessionSalt))
stream.XORKeyStream(dst[8:], dst[8:])
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)...)
@ -143,23 +156,27 @@ func (s *srtpCipherAesCmHmacSha1) encryptRTCP(dst, decrypted []byte, srtcpIndex
}
func (s *srtpCipherAesCmHmacSha1) decryptRTCP(out, encrypted []byte, index, ssrc uint32) ([]byte, error) {
tailOffset := len(encrypted) - (s.authTagLen() + srtcpIndexSize)
authTagLen, err := s.rtcpAuthTagLen()
if err != nil {
return nil, err
}
tailOffset := len(encrypted) - (authTagLen + srtcpIndexSize)
out = out[0:tailOffset]
expectedTag, err := s.generateSrtcpAuthTag(encrypted[:len(encrypted)-s.authTagLen()])
expectedTag, err := s.generateSrtcpAuthTag(encrypted[:len(encrypted)-authTagLen])
if err != nil {
return nil, err
}
actualTag := encrypted[len(encrypted)-s.authTagLen():]
actualTag := encrypted[len(encrypted)-authTagLen:]
if subtle.ConstantTimeCompare(actualTag, expectedTag) != 1 {
return nil, errFailedToVerifyAuthTag
}
stream := cipher.NewCTR(s.srtcpBlock, generateCounter(uint16(index&0xffff), index>>16, ssrc, s.srtcpSessionSalt))
stream.XORKeyStream(out[8:], out[8:])
counter := generateCounter(uint16(index&0xffff), index>>16, ssrc, s.srtcpSessionSalt)
err = xorBytesCTR(s.srtcpBlock, counter[:], out[8:], out[8:])
return out, nil
return out, err
}
func (s *srtpCipherAesCmHmacSha1) generateSrtpAuthTag(buf []byte, roc uint32) ([]byte, error) {
@ -192,8 +209,12 @@ func (s *srtpCipherAesCmHmacSha1) generateSrtpAuthTag(buf []byte, roc uint32) ([
return nil, err
}
// Truncate the hash to the first 10 bytes.
return s.srtpSessionAuth.Sum(nil)[0:s.authTagLen()], nil
// Truncate the hash to the size indicated by the profile
authTagLen, err := s.rtpAuthTagLen()
if err != nil {
return nil, err
}
return s.srtpSessionAuth.Sum(nil)[0:authTagLen], nil
}
func (s *srtpCipherAesCmHmacSha1) generateSrtcpAuthTag(buf []byte) ([]byte, error) {
@ -213,12 +234,17 @@ func (s *srtpCipherAesCmHmacSha1) generateSrtcpAuthTag(buf []byte) ([]byte, erro
if _, err := s.srtcpSessionAuth.Write(buf); err != nil {
return nil, err
}
authTagLen, err := s.rtcpAuthTagLen()
if err != nil {
return nil, err
}
return s.srtcpSessionAuth.Sum(nil)[0:s.authTagLen()], nil
return s.srtcpSessionAuth.Sum(nil)[0:authTagLen], nil
}
func (s *srtpCipherAesCmHmacSha1) getRTCPIndex(in []byte) uint32 {
tailOffset := len(in) - (s.authTagLen() + srtcpIndexSize)
authTagLen, _ := s.rtcpAuthTagLen()
tailOffset := len(in) - (authTagLen + srtcpIndexSize)
srtcpIndexBuffer := in[tailOffset : tailOffset+srtcpIndexSize]
return binary.BigEndian.Uint32(srtcpIndexBuffer) &^ (1 << 31)
}

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
type readStream interface {

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
@ -7,7 +10,7 @@ import (
"time"
"github.com/pion/rtcp"
"github.com/pion/transport/packetio"
"github.com/pion/transport/v2/packetio"
)
// Limit the buffer size to 100KB
@ -17,11 +20,11 @@ const srtcpBufferSize = 100 * 1000
type ReadStreamSRTCP struct {
mu sync.Mutex
isInited bool
isClosed chan bool
session *SessionSRTCP
ssrc uint32
session *SessionSRTCP
ssrc uint32
isInited bool
buffer io.ReadWriteCloser
}
@ -66,7 +69,12 @@ func (r *ReadStreamSRTCP) Read(buf []byte) (int, error) {
// SetReadDeadline sets the deadline for the Read operation.
// Setting to zero means no deadline.
func (r *ReadStreamSRTCP) SetReadDeadline(t time.Time) error {
return r.buffer.(*packetio.Buffer).SetReadDeadline(t)
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

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import (
@ -7,7 +10,7 @@ import (
"time"
"github.com/pion/rtp"
"github.com/pion/transport/packetio"
"github.com/pion/transport/v2/packetio"
)
// Limit the buffer size to 1MB
@ -17,11 +20,11 @@ const srtpBufferSize = 1000 * 1000
type ReadStreamSRTP struct {
mu sync.Mutex
isInited bool
isClosed chan bool
session *SessionSRTP
ssrc uint32
session *SessionSRTP
ssrc uint32
isInited bool
buffer io.ReadWriteCloser
}
@ -85,7 +88,7 @@ func (r *ReadStreamSRTP) ReadRTP(buf []byte) (int, *rtp.Header, error) {
header := &rtp.Header{}
err = header.Unmarshal(buf[:n])
_, err = header.Unmarshal(buf[:n])
if err != nil {
return 0, nil, err
}
@ -96,7 +99,12 @@ func (r *ReadStreamSRTP) ReadRTP(buf []byte) (int, *rtp.Header, error) {
// SetReadDeadline sets the deadline for the Read operation.
// Setting to zero means no deadline.
func (r *ReadStreamSRTP) SetReadDeadline(t time.Time) error {
return r.buffer.(*packetio.Buffer).SetReadDeadline(t)
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

View file

@ -1,3 +1,6 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package srtp
import "bytes"