pax_global_header00006660000000000000000000000064143457221170014520gustar00rootroot0000000000000052 comment=17674f6224bb0697dbd781cec7d69c1a5eaa6cc7 datachannel-1.5.5/000077500000000000000000000000001434572211700137725ustar00rootroot00000000000000datachannel-1.5.5/.github/000077500000000000000000000000001434572211700153325ustar00rootroot00000000000000datachannel-1.5.5/.github/generate-authors.sh000077500000000000000000000031401434572211700211440ustar00rootroot00000000000000#!/usr/bin/env bash # # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # set -e SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) AUTHORS_PATH="$GITHUB_WORKSPACE/AUTHORS.txt" if [ -f ${SCRIPT_PATH}/.ci.conf ] then . ${SCRIPT_PATH}/.ci.conf fi # # DO NOT EDIT THIS # EXCLUDED_CONTRIBUTORS+=('John R. Bradley' 'renovate[bot]' 'Renovate Bot' 'Pion Bot' 'pionbot') # If you want to exclude a name from all repositories, send a PR to # https://github.com/pion/.goassets instead of this repository. # If you want to exclude a name only from this repository, # add EXCLUDED_CONTRIBUTORS=('name') to .github/.ci.conf CONTRIBUTORS=() shouldBeIncluded () { for i in "${EXCLUDED_CONTRIBUTORS[@]}" do if [[ $1 =~ "$i" ]]; then return 1 fi done return 0 } IFS=$'\n' #Only split on newline for contributor in $(git log --format='%aN <%aE>' | LC_ALL=C.UTF-8 sort -uf) do if shouldBeIncluded $contributor; then CONTRIBUTORS+=("$contributor") fi done unset IFS if [ ${#CONTRIBUTORS[@]} -ne 0 ]; then cat >$AUTHORS_PATH <<-'EOH' # 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 `.github/generate-authors.sh` for the scripting EOH for i in "${CONTRIBUTORS[@]}" do echo "$i" >> $AUTHORS_PATH done exit 0 fi datachannel-1.5.5/.github/hooks/000077500000000000000000000000001434572211700164555ustar00rootroot00000000000000datachannel-1.5.5/.github/hooks/commit-msg.sh000077500000000000000000000002671434572211700210750ustar00rootroot00000000000000#!/usr/bin/env bash # # DO NOT EDIT THIS FILE DIRECTLY # # It is automatically copied from https://github.com/pion/.goassets repository. # set -e .github/lint-commit-message.sh $1 datachannel-1.5.5/.github/hooks/pre-commit.sh000077500000000000000000000004171434572211700210720ustar00rootroot00000000000000#!/bin/sh # # DO NOT EDIT THIS FILE DIRECTLY # # It is automatically copied from https://github.com/pion/.goassets repository. # # Redirect output to stderr. exec 1>&2 .github/lint-disallowed-functions-in-library.sh .github/lint-no-trailing-newline-in-log-messages.sh datachannel-1.5.5/.github/hooks/pre-push.sh000077500000000000000000000002571434572211700205630ustar00rootroot00000000000000#!/bin/sh # # DO NOT EDIT THIS FILE DIRECTLY # # It is automatically copied from https://github.com/pion/.goassets repository. # set -e .github/generate-authors.sh exit 0 datachannel-1.5.5/.github/install-hooks.sh000077500000000000000000000010361434572211700204600ustar00rootroot00000000000000#!/bin/bash # # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) cp "$SCRIPT_PATH/hooks/commit-msg.sh" "$SCRIPT_PATH/../.git/hooks/commit-msg" cp "$SCRIPT_PATH/hooks/pre-commit.sh" "$SCRIPT_PATH/../.git/hooks/pre-commit" cp "$SCRIPT_PATH/hooks/pre-push.sh" "$SCRIPT_PATH/../.git/hooks/pre-push" datachannel-1.5.5/.github/lint-commit-message.sh000077500000000000000000000035641434572211700215570ustar00rootroot00000000000000#!/usr/bin/env bash # # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # set -e display_commit_message_error() { cat << EndOfMessage $1 ------------------------------------------------- The preceding commit message is invalid it failed '$2' of the following checks * Separate subject from body with a blank line * Limit the subject line to 50 characters * Capitalize the subject line * Do not end the subject line with a period * Wrap the body at 72 characters EndOfMessage exit 1 } lint_commit_message() { if [[ "$(echo "$1" | awk 'NR == 2 {print $1;}' | wc -c)" -ne 1 ]]; then display_commit_message_error "$1" 'Separate subject from body with a blank line' fi if [[ "$(echo "$1" | head -n1 | awk '{print length}')" -gt 50 ]]; then display_commit_message_error "$1" 'Limit the subject line to 50 characters' fi if [[ ! $1 =~ ^[A-Z] ]]; then display_commit_message_error "$1" 'Capitalize the subject line' fi if [[ "$(echo "$1" | awk 'NR == 1 {print substr($0,length($0),1)}')" == "." ]]; then display_commit_message_error "$1" 'Do not end the subject line with a period' fi if [[ "$(echo "$1" | awk '{print length}' | sort -nr | head -1)" -gt 72 ]]; then display_commit_message_error "$1" 'Wrap the body at 72 characters' fi } if [ "$#" -eq 1 ]; then if [ ! -f "$1" ]; then echo "$0 was passed one argument, but was not a valid file" exit 1 fi lint_commit_message "$(sed -n '/# Please enter the commit message for your changes. Lines starting/q;p' "$1")" else for commit in $(git rev-list --no-merges origin/master..); do lint_commit_message "$(git log --format="%B" -n 1 $commit)" done fi datachannel-1.5.5/.github/lint-disallowed-functions-in-library.sh000077500000000000000000000023571434572211700250470ustar00rootroot00000000000000#!/usr/bin/env bash # # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # set -e # Disallow usages of functions that cause the program to exit in the library code SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) if [ -f ${SCRIPT_PATH}/.ci.conf ] then . ${SCRIPT_PATH}/.ci.conf fi EXCLUDE_DIRECTORIES=${DISALLOWED_FUNCTIONS_EXCLUDED_DIRECTORIES:-"examples"} DISALLOWED_FUNCTIONS=('os.Exit(' 'panic(' 'Fatal(' 'Fatalf(' 'Fatalln(' 'fmt.Println(' 'fmt.Printf(' 'log.Print(' 'log.Println(' 'log.Printf(' 'print(' 'println(') files=$( find "$SCRIPT_PATH/.." -name "*.go" \ | grep -v -e '^.*_test.go$' \ | while read file do excluded=false for ex in $EXCLUDE_DIRECTORIES do if [[ $file == */$ex/* ]] then excluded=true break fi done $excluded || echo "$file" done ) for disallowedFunction in "${DISALLOWED_FUNCTIONS[@]}" do if grep -e "\s$disallowedFunction" $files | grep -v -e 'nolint'; then echo "$disallowedFunction may only be used in example code" exit 1 fi done datachannel-1.5.5/.github/lint-filename.sh000077500000000000000000000012041434572211700204120ustar00rootroot00000000000000#!/usr/bin/env bash # # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # set -e SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) GO_REGEX="^[a-zA-Z][a-zA-Z0-9_]*\.go$" find "$SCRIPT_PATH/.." -name "*.go" | while read fullpath; do filename=$(basename -- "$fullpath") if ! [[ $filename =~ $GO_REGEX ]]; then echo "$filename is not a valid filename for Go code, only alpha, numbers and underscores are supported" exit 1 fi done datachannel-1.5.5/.github/lint-no-trailing-newline-in-log-messages.sh000077500000000000000000000016561434572211700255170ustar00rootroot00000000000000#!/usr/bin/env bash # # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # set -e # Disallow usages of functions that cause the program to exit in the library code SCRIPT_PATH=$( cd "$(dirname "${BASH_SOURCE[0]}")" ; pwd -P ) if [ -f ${SCRIPT_PATH}/.ci.conf ] then . ${SCRIPT_PATH}/.ci.conf fi files=$( find "$SCRIPT_PATH/.." -name "*.go" \ | while read file do excluded=false for ex in $EXCLUDE_DIRECTORIES do if [[ $file == */$ex/* ]] then excluded=true break fi done $excluded || echo "$file" done ) if grep -E '\.(Trace|Debug|Info|Warn|Error)f?\("[^"]*\\n"\)?' $files | grep -v -e 'nolint'; then echo "Log format strings should have trailing new-line" exit 1 fidatachannel-1.5.5/.github/workflows/000077500000000000000000000000001434572211700173675ustar00rootroot00000000000000datachannel-1.5.5/.github/workflows/codeql-analysis.yml000066400000000000000000000015411434572211700232030ustar00rootroot00000000000000name: "CodeQL" on: workflow_dispatch: schedule: - cron: '23 5 * * 0' pull_request: branches: - master paths: - '**.go' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write steps: - name: Checkout repo uses: actions/checkout@v3 # The code in examples/ might intentionally do things like log credentials # in order to show how the library is used, aid in debugging etc. We # should ignore those for CodeQL scanning, and only focus on the package # itself. - name: Remove example code run: | rm -rf examples/ - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: 'go' - name: CodeQL Analysis uses: github/codeql-action/analyze@v2 datachannel-1.5.5/.github/workflows/generate-authors.yml000066400000000000000000000047721434572211700234010ustar00rootroot00000000000000# # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # If this repository should have package specific CI config, # remove the repository name from .goassets/.github/workflows/assets-sync.yml. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # name: generate-authors on: pull_request: jobs: checksecret: permissions: contents: none runs-on: ubuntu-latest outputs: is_PIONBOT_PRIVATE_KEY_set: ${{ steps.checksecret_job.outputs.is_PIONBOT_PRIVATE_KEY_set }} steps: - id: checksecret_job env: PIONBOT_PRIVATE_KEY: ${{ secrets.PIONBOT_PRIVATE_KEY }} run: | echo "is_PIONBOT_PRIVATE_KEY_set: ${{ env.PIONBOT_PRIVATE_KEY != '' }}" echo "::set-output name=is_PIONBOT_PRIVATE_KEY_set::${{ env.PIONBOT_PRIVATE_KEY != '' }}" generate-authors: permissions: contents: write needs: [checksecret] if: needs.checksecret.outputs.is_PIONBOT_PRIVATE_KEY_set == 'true' runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: ref: ${{ github.head_ref }} fetch-depth: 0 token: ${{ secrets.PIONBOT_PRIVATE_KEY }} - name: Generate the authors file run: .github/generate-authors.sh - name: Add the authors file to git run: git add AUTHORS.txt - name: Get last commit message id: last-commit-message run: | COMMIT_MSG=$(git log -1 --pretty=%B) COMMIT_MSG="${COMMIT_MSG//'%'/'%25'}" COMMIT_MSG="${COMMIT_MSG//$'\n'/'%0A'}" COMMIT_MSG="${COMMIT_MSG//$'\r'/'%0D'}" echo "::set-output name=msg::$COMMIT_MSG" - name: Get last commit author id: last-commit-author run: | echo "::set-output name=msg::$(git log -1 --pretty='%aN <%ae>')" - name: Check if AUTHORS.txt file has changed id: git-status-output run: | echo "::set-output name=msg::$(git status -s | wc -l)" - name: Commit and push if: ${{ steps.git-status-output.outputs.msg != '0' }} run: | git config user.email $(echo "${{ steps.last-commit-author.outputs.msg }}" | sed 's/\(.\+\) <\(\S\+\)>/\2/') git config user.name $(echo "${{ steps.last-commit-author.outputs.msg }}" | sed 's/\(.\+\) <\(\S\+\)>/\1/') git add AUTHORS.txt git commit --amend --no-edit git push --force https://github.com/${GITHUB_REPOSITORY} $(git symbolic-ref -q --short HEAD) datachannel-1.5.5/.github/workflows/lint.yaml000066400000000000000000000026251434572211700212260ustar00rootroot00000000000000# # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # If this repository should have package specific CI config, # remove the repository name from .goassets/.github/workflows/assets-sync.yml. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # name: Lint on: pull_request: types: - opened - edited - synchronize permissions: contents: read jobs: lint-commit-message: name: Metadata runs-on: ubuntu-latest strategy: fail-fast: false steps: - uses: actions/checkout@v3 with: fetch-depth: 0 - name: Commit Message run: .github/lint-commit-message.sh - name: File names run: .github/lint-filename.sh - name: Functions run: .github/lint-disallowed-functions-in-library.sh - name: Logging messages should not have trailing newlines run: .github/lint-no-trailing-newline-in-log-messages.sh lint-go: name: Go permissions: contents: read pull-requests: read runs-on: ubuntu-latest strategy: fail-fast: false steps: - uses: actions/checkout@v3 - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: version: v1.45.2 args: $GOLANGCI_LINT_EXRA_ARGS datachannel-1.5.5/.github/workflows/renovate-go-mod-fix.yaml000066400000000000000000000016071434572211700240460ustar00rootroot00000000000000# # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # If this repository should have package specific CI config, # remove the repository name from .goassets/.github/workflows/assets-sync.yml. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # name: go-mod-fix on: push: branches: - renovate/* permissions: contents: write jobs: go-mod-fix: runs-on: ubuntu-latest steps: - name: checkout uses: actions/checkout@v3 with: fetch-depth: 2 - name: fix uses: at-wat/go-sum-fix-action@v0 with: git_user: Pion Bot git_email: 59523206+pionbot@users.noreply.github.com github_token: ${{ secrets.PIONBOT_PRIVATE_KEY }} commit_style: squash push: force datachannel-1.5.5/.github/workflows/test.yaml000066400000000000000000000111011434572211700212240ustar00rootroot00000000000000# # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # If this repository should have package specific CI config, # remove the repository name from .goassets/.github/workflows/assets-sync.yml. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # name: Test on: push: branches: - master pull_request: branches: - master permissions: contents: read jobs: test: runs-on: ubuntu-latest strategy: matrix: go: ["1.17", "1.18"] fail-fast: false name: Go ${{ matrix.go }} steps: - uses: actions/checkout@v3 - uses: actions/cache@v3 with: path: | ~/go/pkg/mod ~/go/bin ~/.cache key: ${{ runner.os }}-amd64-go-${{ hashFiles('**/go.sum') }} restore-keys: | ${{ runner.os }}-amd64-go- - name: Setup Go uses: actions/setup-go@v3 with: go-version: ${{ matrix.go }} - name: Setup go-acc run: go install github.com/ory/go-acc@latest - name: Set up gotestfmt uses: haveyoudebuggedit/gotestfmt-action@v2 with: token: ${{ secrets.GITHUB_TOKEN }} # Avoid getting rate limited - name: Run test run: | TEST_BENCH_OPTION="-bench=." if [ -f .github/.ci.conf ]; then . .github/.ci.conf; fi set -euo pipefail go-acc -o cover.out ./... -- \ ${TEST_BENCH_OPTION} \ -json \ -v -race 2>&1 | grep -v '^go: downloading' | tee /tmp/gotest.log | gotestfmt - name: Upload test log uses: actions/upload-artifact@v2 if: always() with: name: test-log-${{ matrix.go }} path: /tmp/gotest.log if-no-files-found: error - name: Run TEST_HOOK run: | if [ -f .github/.ci.conf ]; then . .github/.ci.conf; fi if [ -n "${TEST_HOOK}" ]; then ${TEST_HOOK}; fi - uses: codecov/codecov-action@v2 with: name: codecov-umbrella fail_ci_if_error: true flags: go test-i386: runs-on: ubuntu-latest strategy: matrix: go: ["1.17", "1.18"] fail-fast: false name: Go i386 ${{ matrix.go }} steps: - uses: actions/checkout@v3 - uses: actions/cache@v3 with: path: | ~/go/pkg/mod ~/.cache key: ${{ runner.os }}-i386-go-${{ hashFiles('**/go.sum') }} restore-keys: | ${{ runner.os }}-i386-go- - name: Run test run: | mkdir -p $HOME/go/pkg/mod $HOME/.cache docker run \ -u $(id -u):$(id -g) \ -e "GO111MODULE=on" \ -e "CGO_ENABLED=0" \ -v $GITHUB_WORKSPACE:/go/src/github.com/pion/$(basename $GITHUB_WORKSPACE) \ -v $HOME/go/pkg/mod:/go/pkg/mod \ -v $HOME/.cache:/.cache \ -w /go/src/github.com/pion/$(basename $GITHUB_WORKSPACE) \ i386/golang:${{matrix.go}}-alpine \ /usr/local/go/bin/go test \ ${TEST_EXTRA_ARGS:-} \ -v ./... test-wasm: runs-on: ubuntu-latest strategy: fail-fast: false name: WASM steps: - uses: actions/checkout@v3 - name: Use Node.js uses: actions/setup-node@v3 with: node-version: '16.x' - uses: actions/cache@v3 with: path: | ~/go/pkg/mod ~/.cache key: ${{ runner.os }}-wasm-go-${{ hashFiles('**/go.sum') }} restore-keys: | ${{ runner.os }}-wasm-go- - name: Download Go run: curl -sSfL https://dl.google.com/go/go${GO_VERSION}.linux-amd64.tar.gz | tar -C ~ -xzf - env: GO_VERSION: 1.17 - name: Set Go Root run: echo "GOROOT=${HOME}/go" >> $GITHUB_ENV - name: Set Go Path run: echo "GOPATH=${HOME}/go" >> $GITHUB_ENV - name: Set Go Path run: echo "GO_JS_WASM_EXEC=${GOROOT}/misc/wasm/go_js_wasm_exec" >> $GITHUB_ENV - name: Insall NPM modules run: yarn install - name: Run Tests run: | if [ -f .github/.ci.conf ]; then . .github/.ci.conf; fi GOOS=js GOARCH=wasm $GOPATH/bin/go test \ -coverprofile=cover.out -covermode=atomic \ -exec="${GO_JS_WASM_EXEC}" \ -v ./... - uses: codecov/codecov-action@v2 with: name: codecov-umbrella fail_ci_if_error: true flags: wasm datachannel-1.5.5/.github/workflows/tidy-check.yaml000066400000000000000000000015621434572211700223030ustar00rootroot00000000000000# # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # If this repository should have package specific CI config, # remove the repository name from .goassets/.github/workflows/assets-sync.yml. # # If you want to update the shared CI config, send a PR to # https://github.com/pion/.goassets instead of this repository. # name: Go mod tidy on: pull_request: branches: - master push: branches: - master permissions: contents: read jobs: Check: runs-on: ubuntu-latest steps: - name: checkout uses: actions/checkout@v3 - name: Setup Go uses: actions/setup-go@v3 - name: check run: | go mod download go mod tidy if ! git diff --exit-code then echo "Not go mod tidied" exit 1 fi datachannel-1.5.5/.gitignore000066400000000000000000000004661434572211700157700ustar00rootroot00000000000000### 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 datachannel-1.5.5/.golangci.yml000066400000000000000000000175411434572211700163660ustar00rootroot00000000000000linters-settings: govet: check-shadowing: true misspell: locale: US exhaustive: default-signifies-exhaustive: true gomodguard: blocked: modules: - github.com/pkg/errors: recommendations: - errors 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 - deadcode # Finds unused code - 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 - 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 - 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 - forbidigo # Forbids identifiers - 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 # Allow complex main function in examples - path: examples text: "of func `main` is high" linters: - gocognit run: skip-dirs-use-default: false datachannel-1.5.5/AUTHORS.txt000066400000000000000000000013141434572211700156570ustar00rootroot00000000000000# 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 `.github/generate-authors.sh` for the scripting Atsushi Watanabe backkem Benny Daon Chinmay Kousik Eric Daniels Hugo Arregui Hugo Arregui John Bradley Norman Rasmussen Sean DuBois Sean DuBois Yutaka Takeda datachannel-1.5.5/DESIGN.md000066400000000000000000000014671434572211700152750ustar00rootroot00000000000000

Design

### Portable Pion Data Channels is written in Go and extremely portable. Anywhere Golang runs, Pion Data Channels 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. datachannel-1.5.5/LICENSE000066400000000000000000000020411434572211700147740ustar00rootroot00000000000000MIT License Copyright (c) 2018 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. datachannel-1.5.5/README.md000066400000000000000000000047461434572211700152640ustar00rootroot00000000000000


Pion Data Channels

A Go implementation of WebRTC Data Channels

Pion Data Channels Slack Widget
Build Status GoDoc Coverage Status Go Report Card License: MIT


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). 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: ### License MIT License - see [LICENSE](LICENSE) for full text datachannel-1.5.5/codecov.yml000066400000000000000000000005521434572211700161410ustar00rootroot00000000000000# # DO NOT EDIT THIS FILE # # It is automatically copied from https://github.com/pion/.goassets repository. # 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/**/*" datachannel-1.5.5/datachannel.go000066400000000000000000000267501434572211700165750ustar00rootroot00000000000000// Package datachannel implements WebRTC Data Channels package datachannel import ( "errors" "fmt" "io" "sync" "sync/atomic" "time" "github.com/pion/logging" "github.com/pion/sctp" ) const receiveMTU = 8192 // Reader is an extended io.Reader // that also returns if the message is text. type Reader interface { ReadDataChannel([]byte) (int, bool, error) } // ReadDeadliner extends an io.Reader to expose setting a read deadline. type ReadDeadliner interface { SetReadDeadline(time.Time) error } // Writer is an extended io.Writer // that also allows indicating if a message is text. type Writer interface { WriteDataChannel([]byte, bool) (int, error) } // ReadWriteCloser is an extended io.ReadWriteCloser // that also implements our Reader and Writer. type ReadWriteCloser interface { io.Reader io.Writer Reader Writer io.Closer } // DataChannel represents a data channel type DataChannel struct { Config // stats messagesSent uint32 messagesReceived uint32 bytesSent uint64 bytesReceived uint64 mu sync.Mutex onOpenCompleteHandler func() openCompleteHandlerOnce sync.Once stream *sctp.Stream log logging.LeveledLogger } // Config is used to configure the data channel. type Config struct { ChannelType ChannelType Negotiated bool Priority uint16 ReliabilityParameter uint32 Label string Protocol string LoggerFactory logging.LoggerFactory } func newDataChannel(stream *sctp.Stream, config *Config) (*DataChannel, error) { return &DataChannel{ Config: *config, stream: stream, log: config.LoggerFactory.NewLogger("datachannel"), }, nil } // Dial opens a data channels over SCTP func Dial(a *sctp.Association, id uint16, config *Config) (*DataChannel, error) { stream, err := a.OpenStream(id, sctp.PayloadTypeWebRTCBinary) if err != nil { return nil, err } dc, err := Client(stream, config) if err != nil { return nil, err } return dc, nil } // Client opens a data channel over an SCTP stream func Client(stream *sctp.Stream, config *Config) (*DataChannel, error) { msg := &channelOpen{ ChannelType: config.ChannelType, Priority: config.Priority, ReliabilityParameter: config.ReliabilityParameter, Label: []byte(config.Label), Protocol: []byte(config.Protocol), } if !config.Negotiated { rawMsg, err := msg.Marshal() if err != nil { return nil, fmt.Errorf("failed to marshal ChannelOpen %w", err) } if _, err = stream.WriteSCTP(rawMsg, sctp.PayloadTypeWebRTCDCEP); err != nil { return nil, fmt.Errorf("failed to send ChannelOpen %w", err) } } return newDataChannel(stream, config) } // Accept is used to accept incoming data channels over SCTP func Accept(a *sctp.Association, config *Config, existingChannels ...*DataChannel) (*DataChannel, error) { stream, err := a.AcceptStream() if err != nil { return nil, err } for _, ch := range existingChannels { if ch.StreamIdentifier() == stream.StreamIdentifier() { ch.stream.SetDefaultPayloadType(sctp.PayloadTypeWebRTCBinary) return ch, nil } } stream.SetDefaultPayloadType(sctp.PayloadTypeWebRTCBinary) dc, err := Server(stream, config) if err != nil { return nil, err } return dc, nil } // Server accepts a data channel over an SCTP stream func Server(stream *sctp.Stream, config *Config) (*DataChannel, error) { buffer := make([]byte, receiveMTU) n, ppi, err := stream.ReadSCTP(buffer) if err != nil { return nil, err } if ppi != sctp.PayloadTypeWebRTCDCEP { return nil, fmt.Errorf("%w %s", ErrInvalidPayloadProtocolIdentifier, ppi) } openMsg, err := parseExpectDataChannelOpen(buffer[:n]) if err != nil { return nil, fmt.Errorf("failed to parse DataChannelOpen packet %w", err) } config.ChannelType = openMsg.ChannelType config.Priority = openMsg.Priority config.ReliabilityParameter = openMsg.ReliabilityParameter config.Label = string(openMsg.Label) config.Protocol = string(openMsg.Protocol) dataChannel, err := newDataChannel(stream, config) if err != nil { return nil, err } err = dataChannel.writeDataChannelAck() if err != nil { return nil, err } err = dataChannel.commitReliabilityParams() if err != nil { return nil, err } return dataChannel, nil } // Read reads a packet of len(p) bytes as binary data func (c *DataChannel) Read(p []byte) (int, error) { n, _, err := c.ReadDataChannel(p) return n, err } // ReadDataChannel reads a packet of len(p) bytes func (c *DataChannel) ReadDataChannel(p []byte) (int, bool, error) { for { n, ppi, err := c.stream.ReadSCTP(p) if errors.Is(err, io.EOF) { // When the peer sees that an incoming stream was // reset, it also resets its corresponding outgoing stream. if closeErr := c.stream.Close(); closeErr != nil { return 0, false, closeErr } } if err != nil { return 0, false, err } if ppi == sctp.PayloadTypeWebRTCDCEP { if err = c.handleDCEP(p[:n]); err != nil { c.log.Errorf("Failed to handle DCEP: %s", err.Error()) } continue } else if ppi == sctp.PayloadTypeWebRTCBinaryEmpty || ppi == sctp.PayloadTypeWebRTCStringEmpty { n = 0 } atomic.AddUint32(&c.messagesReceived, 1) atomic.AddUint64(&c.bytesReceived, uint64(n)) isString := ppi == sctp.PayloadTypeWebRTCString || ppi == sctp.PayloadTypeWebRTCStringEmpty return n, isString, err } } // SetReadDeadline sets a deadline for reads to return func (c *DataChannel) SetReadDeadline(t time.Time) error { return c.stream.SetReadDeadline(t) } // MessagesSent returns the number of messages sent func (c *DataChannel) MessagesSent() uint32 { return atomic.LoadUint32(&c.messagesSent) } // MessagesReceived returns the number of messages received func (c *DataChannel) MessagesReceived() uint32 { return atomic.LoadUint32(&c.messagesReceived) } // OnOpen sets an event handler which is invoked when // a DATA_CHANNEL_ACK message is received. // The handler is called only on thefor the channel opened // https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-data-protocol-09#section-5.2 func (c *DataChannel) OnOpen(f func()) { c.mu.Lock() c.openCompleteHandlerOnce = sync.Once{} c.onOpenCompleteHandler = f c.mu.Unlock() } func (c *DataChannel) onOpenComplete() { c.mu.Lock() hdlr := c.onOpenCompleteHandler c.mu.Unlock() if hdlr != nil { go c.openCompleteHandlerOnce.Do(func() { hdlr() }) } } // BytesSent returns the number of bytes sent func (c *DataChannel) BytesSent() uint64 { return atomic.LoadUint64(&c.bytesSent) } // BytesReceived returns the number of bytes received func (c *DataChannel) BytesReceived() uint64 { return atomic.LoadUint64(&c.bytesReceived) } // StreamIdentifier returns the Stream identifier associated to the stream. func (c *DataChannel) StreamIdentifier() uint16 { return c.stream.StreamIdentifier() } func (c *DataChannel) handleDCEP(data []byte) error { msg, err := parse(data) if err != nil { return fmt.Errorf("failed to parse DataChannel packet %w", err) } switch msg := msg.(type) { case *channelAck: c.log.Debug("Received DATA_CHANNEL_ACK") if err = c.commitReliabilityParams(); err != nil { return err } c.onOpenComplete() default: return fmt.Errorf("%w %v", ErrInvalidMessageType, msg) } return nil } // Write writes len(p) bytes from p as binary data func (c *DataChannel) Write(p []byte) (n int, err error) { return c.WriteDataChannel(p, false) } // WriteDataChannel writes len(p) bytes from p func (c *DataChannel) WriteDataChannel(p []byte, isString bool) (n int, err error) { // https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-12#section-6.6 // SCTP does not support the sending of empty user messages. Therefore, // if an empty message has to be sent, the appropriate PPID (WebRTC // String Empty or WebRTC Binary Empty) is used and the SCTP user // message of one zero byte is sent. When receiving an SCTP user // message with one of these PPIDs, the receiver MUST ignore the SCTP // user message and process it as an empty message. var ppi sctp.PayloadProtocolIdentifier switch { case !isString && len(p) > 0: ppi = sctp.PayloadTypeWebRTCBinary case !isString && len(p) == 0: ppi = sctp.PayloadTypeWebRTCBinaryEmpty case isString && len(p) > 0: ppi = sctp.PayloadTypeWebRTCString case isString && len(p) == 0: ppi = sctp.PayloadTypeWebRTCStringEmpty } atomic.AddUint32(&c.messagesSent, 1) atomic.AddUint64(&c.bytesSent, uint64(len(p))) if len(p) == 0 { _, err := c.stream.WriteSCTP([]byte{0}, ppi) return 0, err } return c.stream.WriteSCTP(p, ppi) } func (c *DataChannel) writeDataChannelAck() error { ack := channelAck{} ackMsg, err := ack.Marshal() if err != nil { return fmt.Errorf("failed to marshal ChannelOpen ACK: %w", err) } if _, err = c.stream.WriteSCTP(ackMsg, sctp.PayloadTypeWebRTCDCEP); err != nil { return fmt.Errorf("failed to send ChannelOpen ACK: %w", err) } return err } // Close closes the DataChannel and the underlying SCTP stream. func (c *DataChannel) Close() error { // https://tools.ietf.org/html/draft-ietf-rtcweb-data-channel-13#section-6.7 // Closing of a data channel MUST be signaled by resetting the // corresponding outgoing streams [RFC6525]. This means that if one // side decides to close the data channel, it resets the corresponding // outgoing stream. When the peer sees that an incoming stream was // reset, it also resets its corresponding outgoing stream. Once this // is completed, the data channel is closed. Resetting a stream sets // the Stream Sequence Numbers (SSNs) of the stream back to 'zero' with // a corresponding notification to the application layer that the reset // has been performed. Streams are available for reuse after a reset // has been performed. return c.stream.Close() } // BufferedAmount returns the number of bytes of data currently queued to be // sent over this stream. func (c *DataChannel) BufferedAmount() uint64 { return c.stream.BufferedAmount() } // BufferedAmountLowThreshold returns the number of bytes of buffered outgoing // data that is considered "low." Defaults to 0. func (c *DataChannel) BufferedAmountLowThreshold() uint64 { return c.stream.BufferedAmountLowThreshold() } // SetBufferedAmountLowThreshold is used to update the threshold. // See BufferedAmountLowThreshold(). func (c *DataChannel) SetBufferedAmountLowThreshold(th uint64) { c.stream.SetBufferedAmountLowThreshold(th) } // OnBufferedAmountLow sets the callback handler which would be called when the // number of bytes of outgoing data buffered is lower than the threshold. func (c *DataChannel) OnBufferedAmountLow(f func()) { c.stream.OnBufferedAmountLow(f) } func (c *DataChannel) commitReliabilityParams() error { switch c.Config.ChannelType { case ChannelTypeReliable: c.stream.SetReliabilityParams(false, sctp.ReliabilityTypeReliable, c.Config.ReliabilityParameter) case ChannelTypeReliableUnordered: c.stream.SetReliabilityParams(true, sctp.ReliabilityTypeReliable, c.Config.ReliabilityParameter) case ChannelTypePartialReliableRexmit: c.stream.SetReliabilityParams(false, sctp.ReliabilityTypeRexmit, c.Config.ReliabilityParameter) case ChannelTypePartialReliableRexmitUnordered: c.stream.SetReliabilityParams(true, sctp.ReliabilityTypeRexmit, c.Config.ReliabilityParameter) case ChannelTypePartialReliableTimed: c.stream.SetReliabilityParams(false, sctp.ReliabilityTypeTimed, c.Config.ReliabilityParameter) case ChannelTypePartialReliableTimedUnordered: c.stream.SetReliabilityParams(true, sctp.ReliabilityTypeTimed, c.Config.ReliabilityParameter) default: return fmt.Errorf("%w %v", ErrInvalidChannelType, c.Config.ChannelType) } return nil } datachannel-1.5.5/datachannel_test.go000066400000000000000000000473711434572211700176360ustar00rootroot00000000000000package datachannel import ( "encoding/binary" "os" "reflect" "testing" "time" "github.com/pion/logging" "github.com/pion/sctp" "github.com/pion/transport/test" "github.com/stretchr/testify/assert" ) // Check we implement our ReadWriteCloser var _ ReadWriteCloser = (*DataChannel)(nil) func bridgeProcessAtLeastOne(br *test.Bridge) { nSum := 0 for { time.Sleep(10 * time.Millisecond) n := br.Tick() nSum += n if br.Len(0) == 0 && br.Len(1) == 0 && nSum > 0 { break } } } func createNewAssociationPair(br *test.Bridge) (*sctp.Association, *sctp.Association, error) { var a0, a1 *sctp.Association var err0, err1 error loggerFactory := logging.NewDefaultLoggerFactory() handshake0Ch := make(chan bool) handshake1Ch := make(chan bool) go func() { a0, err0 = sctp.Client(sctp.Config{ NetConn: br.GetConn0(), LoggerFactory: loggerFactory, }) handshake0Ch <- true }() go func() { a1, err1 = sctp.Client(sctp.Config{ NetConn: br.GetConn1(), LoggerFactory: loggerFactory, }) handshake1Ch <- true }() a0handshakeDone := false a1handshakeDone := false loop1: for i := 0; i < 100; i++ { time.Sleep(10 * time.Millisecond) br.Tick() select { case a0handshakeDone = <-handshake0Ch: if a1handshakeDone { break loop1 } case a1handshakeDone = <-handshake1Ch: if a0handshakeDone { break loop1 } default: } } if err0 != nil { return nil, nil, err0 } if err1 != nil { return nil, nil, err1 } return a0, a1, nil } func closeAssociationPair(br *test.Bridge, a0, a1 *sctp.Association) { close0Ch := make(chan bool) close1Ch := make(chan bool) go func() { //nolint:errcheck,gosec a0.Close() close0Ch <- true }() go func() { //nolint:errcheck,gosec a1.Close() close1Ch <- true }() a0closed := false a1closed := false loop1: for i := 0; i < 100; i++ { time.Sleep(10 * time.Millisecond) br.Tick() select { case a0closed = <-close0Ch: if a1closed { break loop1 } case a1closed = <-close1Ch: if a0closed { break loop1 } default: } } } func prOrderedTest(t *testing.T, channelType ChannelType) { // Limit runtime in case of deadlocks lim := test.TimeOut(time.Second * 10) defer lim.Stop() sbuf := make([]byte, 1000) rbuf := make([]byte, 2000) br := test.NewBridge() loggerFactory := logging.NewDefaultLoggerFactory() a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } cfg := &Config{ ChannelType: channelType, ReliabilityParameter: 0, Label: "data", LoggerFactory: loggerFactory, } dc0, err := Dial(a0, 100, cfg) assert.Nil(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.Nil(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) assert.True(t, reflect.DeepEqual(dc0.Config, *cfg), "local config should match") assert.True(t, reflect.DeepEqual(dc1.Config, *cfg), "remote config should match") err = dc0.commitReliabilityParams() assert.NoError(t, err, "should succeed") err = dc1.commitReliabilityParams() assert.NoError(t, err, "should succeed") var n int binary.BigEndian.PutUint32(sbuf, 1) n, err = dc0.WriteDataChannel(sbuf, true) assert.Nil(t, err, "WriteDataChannel() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") binary.BigEndian.PutUint32(sbuf, 2) n, err = dc0.WriteDataChannel(sbuf, true) assert.Nil(t, err, "WriteDataChannel() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") time.Sleep(100 * time.Millisecond) br.Drop(0, 0, 1) // drop the first packet on the wire time.Sleep(100 * time.Millisecond) bridgeProcessAtLeastOne(br) var isString bool n, isString, err = dc1.ReadDataChannel(rbuf) assert.Nil(t, err, "Read() should succeed") assert.True(t, isString, "should return isString being true") assert.Equal(t, uint32(2), binary.BigEndian.Uint32(rbuf[:n]), "data should match") //nolint:errcheck,gosec dc0.Close() //nolint:errcheck,gosec dc1.Close() bridgeProcessAtLeastOne(br) closeAssociationPair(br, a0, a1) } func prUnorderedTest(t *testing.T, channelType ChannelType) { sbuf := make([]byte, 1000) rbuf := make([]byte, 2000) br := test.NewBridge() loggerFactory := logging.NewDefaultLoggerFactory() a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } cfg := &Config{ ChannelType: channelType, ReliabilityParameter: 0, Label: "data", LoggerFactory: loggerFactory, } dc0, err := Dial(a0, 100, cfg) assert.Nil(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.Nil(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) assert.True(t, reflect.DeepEqual(dc0.Config, *cfg), "local config should match") assert.True(t, reflect.DeepEqual(dc1.Config, *cfg), "remote config should match") err = dc0.commitReliabilityParams() assert.NoError(t, err, "should succeed") err = dc1.commitReliabilityParams() assert.NoError(t, err, "should succeed") var n int binary.BigEndian.PutUint32(sbuf, 1) n, err = dc0.WriteDataChannel(sbuf, true) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") binary.BigEndian.PutUint32(sbuf, 2) n, err = dc0.WriteDataChannel(sbuf, true) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") binary.BigEndian.PutUint32(sbuf, 3) n, err = dc0.WriteDataChannel(sbuf, true) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") time.Sleep(100 * time.Millisecond) br.Drop(0, 0, 1) // drop the first packet on the wire err = br.Reorder(0) // reorder the rest of the packet assert.Nil(t, err, "reorder failed") bridgeProcessAtLeastOne(br) var isString bool n, isString, err = dc1.ReadDataChannel(rbuf) assert.Nil(t, err, "Read() should succeed") assert.True(t, isString, "should return isString being true") assert.Equal(t, uint32(3), binary.BigEndian.Uint32(rbuf[:n]), "data should match") n, isString, err = dc1.ReadDataChannel(rbuf) assert.Nil(t, err, "Read() should succeed") assert.True(t, isString, "should return isString being true") assert.Equal(t, uint32(2), binary.BigEndian.Uint32(rbuf[:n]), "data should match") //nolint:errcheck,gosec dc0.Close() //nolint:errcheck,gosec dc1.Close() bridgeProcessAtLeastOne(br) closeAssociationPair(br, a0, a1) } func TestDataChannel(t *testing.T) { loggerFactory := logging.NewDefaultLoggerFactory() sbuf := make([]byte, 1000) rbuf := make([]byte, 1500) t.Run("ChannelTypeReliableOrdered", func(t *testing.T) { // Limit runtime in case of deadlocks lim := test.TimeOut(time.Second * 10) defer lim.Stop() br := test.NewBridge() a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } cfg := &Config{ ChannelType: ChannelTypeReliable, ReliabilityParameter: 123, Label: "data", LoggerFactory: loggerFactory, } dc0, err := Dial(a0, 100, cfg) assert.Nil(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.Nil(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) assert.True(t, reflect.DeepEqual(dc0.Config, *cfg), "local config should match") assert.True(t, reflect.DeepEqual(dc1.Config, *cfg), "remote config should match") br.ReorderNextNWrites(0, 2) // reordering on the wire var n int binary.BigEndian.PutUint32(sbuf, uint32(1)) n, err = dc0.Write(sbuf) assert.Nil(t, err, "Write() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") binary.BigEndian.PutUint32(sbuf, uint32(2)) n, err = dc0.Write(sbuf) assert.Nil(t, err, "Write() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") assert.Nil(t, err, "reorder failed") bridgeProcessAtLeastOne(br) n, err = dc1.Read(rbuf) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, uint32(1), binary.BigEndian.Uint32(rbuf[:n]), "data should match") n, err = dc1.Read(rbuf) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, uint32(2), binary.BigEndian.Uint32(rbuf[:n]), "data should match") //nolint:errcheck,gosec dc0.Close() //nolint:errcheck,gosec dc1.Close() bridgeProcessAtLeastOne(br) closeAssociationPair(br, a0, a1) }) t.Run("ChannelTypeReliableUnordered", func(t *testing.T) { // Limit runtime in case of deadlocks lim := test.TimeOut(time.Second * 10) defer lim.Stop() sbuf := make([]byte, 1000) rbuf := make([]byte, 1500) br := test.NewBridge() a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } cfg := &Config{ ChannelType: ChannelTypeReliableUnordered, ReliabilityParameter: 123, Label: "data", LoggerFactory: loggerFactory, } dc0, err := Dial(a0, 100, cfg) assert.Nil(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.Nil(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) assert.True(t, reflect.DeepEqual(dc0.Config, *cfg), "local config should match") assert.True(t, reflect.DeepEqual(dc1.Config, *cfg), "remote config should match") err = dc0.commitReliabilityParams() assert.NoError(t, err, "should succeed") err = dc1.commitReliabilityParams() assert.NoError(t, err, "should succeed") var n int binary.BigEndian.PutUint32(sbuf, 1) n, err = dc0.WriteDataChannel(sbuf, true) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") binary.BigEndian.PutUint32(sbuf, 2) n, err = dc0.WriteDataChannel(sbuf, true) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") time.Sleep(100 * time.Millisecond) err = br.Reorder(0) // reordering on the wire assert.Nil(t, err, "reorder failed") bridgeProcessAtLeastOne(br) var isString bool n, isString, err = dc1.ReadDataChannel(rbuf) assert.Nil(t, err, "Read() should succeed") assert.True(t, isString, "should return isString being true") assert.Equal(t, uint32(2), binary.BigEndian.Uint32(rbuf[:n]), "data should match") n, isString, err = dc1.ReadDataChannel(rbuf) assert.Nil(t, err, "Read() should succeed") assert.True(t, isString, "should return isString being true") assert.Equal(t, uint32(1), binary.BigEndian.Uint32(rbuf[:n]), "data should match") //nolint:errcheck,gosec dc0.Close() //nolint:errcheck,gosec dc1.Close() bridgeProcessAtLeastOne(br) closeAssociationPair(br, a0, a1) }) t.Run("ChannelTypePartialReliableRexmit", func(t *testing.T) { prOrderedTest(t, ChannelTypePartialReliableRexmit) }) t.Run("ChannelTypePartialReliableRexmitUnordered", func(t *testing.T) { prUnorderedTest(t, ChannelTypePartialReliableRexmitUnordered) }) t.Run("ChannelTypePartialReliableTimed", func(t *testing.T) { prOrderedTest(t, ChannelTypePartialReliableTimed) }) t.Run("ChannelTypePartialReliableTimedUnordered", func(t *testing.T) { prUnorderedTest(t, ChannelTypePartialReliableTimedUnordered) }) } func TestDataChannelBufferedAmount(t *testing.T) { var nCbs int sData := make([]byte, 1000) rData := make([]byte, 1000) br := test.NewBridge() loggerFactory := logging.NewDefaultLoggerFactory() a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } dc0, err := Dial(a0, 100, &Config{ Label: "data", LoggerFactory: loggerFactory, }) assert.Nil(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.Nil(t, err, "Accept() should succeed") for dc0.BufferedAmount() > 0 { bridgeProcessAtLeastOne(br) } n, err := dc0.Write([]byte{}) assert.Nil(t, err, "Write() should succeed") assert.Equal(t, 0, n, "data length should match") assert.Equal(t, uint64(1), dc0.BufferedAmount(), "incorrect bufferedAmount") n, err = dc0.Write([]byte{0}) assert.Nil(t, err, "Write() should succeed") assert.Equal(t, 1, n, "data length should match") assert.Equal(t, uint64(2), dc0.BufferedAmount(), "incorrect bufferedAmount") bridgeProcessAtLeastOne(br) n, err = dc1.Read(rData) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, n, 0, "received length should match") n, err = dc1.Read(rData) assert.Nil(t, err, "Read() should succeed") assert.Equal(t, n, 1, "received length should match") dc0.SetBufferedAmountLowThreshold(1500) assert.Equal(t, uint64(1500), dc0.BufferedAmountLowThreshold(), "incorrect bufferedAmountLowThreshold") dc0.OnBufferedAmountLow(func() { nCbs++ }) // Write 10 1000-byte packets (total 10,000 bytes) for i := 0; i < 10; i++ { var n int n, err = dc0.Write(sData) assert.Nil(t, err, "Write() should succeed") assert.Equal(t, len(sData), n, "data length should match") assert.Equal(t, uint64(len(sData)*(i+1)+2), dc0.BufferedAmount(), "incorrect bufferedAmount") } go func() { for { n, err := dc1.Read(rData) if err != nil { break } assert.Equal(t, n, len(rData), "received length should match") } }() since := time.Now() for { br.Tick() time.Sleep(10 * time.Millisecond) if time.Since(since).Seconds() > 0.5 { break } } //nolint:errcheck,gosec dc0.Close() //nolint:errcheck,gosec dc1.Close() bridgeProcessAtLeastOne(br) assert.True(t, nCbs > 0, "should make at least one callback") closeAssociationPair(br, a0, a1) } func TestStats(t *testing.T) { loggerFactory := logging.NewDefaultLoggerFactory() sbuf := make([]byte, 1000) rbuf := make([]byte, 1500) br := test.NewBridge() a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } cfg := &Config{ ChannelType: ChannelTypeReliable, ReliabilityParameter: 123, Label: "data", LoggerFactory: loggerFactory, } dc0, err := Dial(a0, 100, cfg) assert.NoError(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.NoError(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) var bytesSent uint64 var n int n, err = dc0.Write(sbuf) assert.NoError(t, err, "Write() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") bytesSent += uint64(n) assert.Equal(t, dc0.BytesSent(), bytesSent) assert.Equal(t, dc0.MessagesSent(), uint32(1)) n, err = dc0.Write(sbuf) assert.NoError(t, err, "Write() should succeed") assert.Equal(t, len(sbuf), n, "data length should match") bytesSent += uint64(n) assert.Equal(t, dc0.BytesSent(), bytesSent) assert.Equal(t, dc0.MessagesSent(), uint32(2)) n, err = dc0.Write([]byte{0}) assert.NoError(t, err, "Write() should succeed") assert.Equal(t, 1, n, "data length should match") bytesSent += uint64(n) assert.Equal(t, dc0.BytesSent(), bytesSent) assert.Equal(t, dc0.MessagesSent(), uint32(3)) n, err = dc0.Write([]byte{}) assert.NoError(t, err, "Write() should succeed") assert.Equal(t, 0, n, "data length should match") assert.Equal(t, dc0.BytesSent(), bytesSent) assert.Equal(t, dc0.MessagesSent(), uint32(4)) bridgeProcessAtLeastOne(br) var bytesRead uint64 n, err = dc1.Read(rbuf) assert.NoError(t, err, "Read() should succeed") bytesRead += uint64(n) assert.Equal(t, dc1.BytesReceived(), bytesRead) assert.Equal(t, dc1.MessagesReceived(), uint32(1)) n, err = dc1.Read(rbuf) assert.NoError(t, err, "Read() should succeed") bytesRead += uint64(n) assert.Equal(t, dc1.BytesReceived(), bytesRead) assert.Equal(t, dc1.MessagesReceived(), uint32(2)) n, err = dc1.Read(rbuf) assert.NoError(t, err, "Read() should succeed") bytesRead += uint64(n) assert.Equal(t, n, 1) assert.Equal(t, dc1.BytesReceived(), bytesRead) assert.Equal(t, dc1.MessagesReceived(), uint32(3)) n, err = dc1.Read(rbuf) assert.NoError(t, err, "Read() should succeed") assert.Equal(t, n, 0) assert.Equal(t, dc1.BytesReceived(), bytesRead) assert.Equal(t, dc1.MessagesReceived(), uint32(4)) assert.NoError(t, dc0.Close()) assert.NoError(t, dc1.Close()) bridgeProcessAtLeastOne(br) closeAssociationPair(br, a0, a1) } func TestDataChannelAcceptWrite(t *testing.T) { loggerFactory := logging.NewDefaultLoggerFactory() br := test.NewBridge() in := []byte("HELLO WORLD") out := make([]byte, 100) a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } cfg := &Config{ ChannelType: ChannelTypeReliable, ReliabilityParameter: 123, Label: "data", LoggerFactory: loggerFactory, } dc0, err := Dial(a0, 100, cfg) assert.NoError(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.NoError(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) n, err := dc1.WriteDataChannel(in, true) assert.Nil(t, err) assert.Equal(t, len(in), n) bridgeProcessAtLeastOne(br) n, isString, err := dc0.ReadDataChannel(out) assert.NoError(t, err) assert.True(t, isString) assert.Equal(t, len(in), n) assert.Equal(t, in, out[:n]) assert.NoError(t, dc0.Close()) assert.NoError(t, dc1.Close()) bridgeProcessAtLeastOne(br) closeAssociationPair(br, a0, a1) } func TestOnOpen(t *testing.T) { loggerFactory := logging.NewDefaultLoggerFactory() br := test.NewBridge() a0, a1, err := createNewAssociationPair(br) assert.NoError(t, err) dc0, err := Dial(a0, 100, &Config{ ChannelType: ChannelTypeReliable, ReliabilityParameter: 123, Label: "data", LoggerFactory: loggerFactory, }) assert.NoError(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) dc1, err := Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.NoError(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) openCompleted := make(chan bool) dc0.OnOpen(func() { close(openCompleted) }) in := []byte("HELLO WORLD") out := make([]byte, 100) bridgeProcessAtLeastOne(br) _, err = dc1.WriteDataChannel(in, true) assert.NoError(t, err) bridgeProcessAtLeastOne(br) _, _, err = dc0.ReadDataChannel(out) assert.NoError(t, err) select { case <-time.After(time.Second * 10): assert.FailNow(t, "OnOpen() failed to fire 10s") case <-openCompleted: } assert.NoError(t, dc0.Close()) assert.NoError(t, dc1.Close()) bridgeProcessAtLeastOne(br) closeAssociationPair(br, a0, a1) } func TestReadDeadline(t *testing.T) { loggerFactory := logging.NewDefaultLoggerFactory() br := test.NewBridge() a0, a1, err := createNewAssociationPair(br) if !assert.Nil(t, err, "failed to create associations") { assert.FailNow(t, "failed due to earlier error") } cfg := &Config{ ChannelType: ChannelTypeReliable, ReliabilityParameter: 123, Label: "data", LoggerFactory: loggerFactory, } dc0, err := Dial(a0, 100, cfg) assert.NoError(t, err, "Dial() should succeed") bridgeProcessAtLeastOne(br) _, err = Accept(a1, &Config{ LoggerFactory: loggerFactory, }) assert.NoError(t, err, "Accept() should succeed") bridgeProcessAtLeastOne(br) err = dc0.SetReadDeadline(time.Now().Add(200 * time.Millisecond)) assert.NoError(t, err, "SetReadDeadline() should succeed") _, err = dc0.Read(make([]byte, 1500)) assert.ErrorIs(t, err, os.ErrDeadlineExceeded) } datachannel-1.5.5/errors.go000066400000000000000000000022771434572211700156450ustar00rootroot00000000000000package datachannel import "errors" var ( // ErrDataChannelMessageTooShort means that the data isn't long enough to be a valid DataChannel message ErrDataChannelMessageTooShort = errors.New("DataChannel message is not long enough to determine type") // ErrInvalidPayloadProtocolIdentifier means that we got a DataChannel messages with a Payload Protocol Identifier // we don't know how to handle ErrInvalidPayloadProtocolIdentifier = errors.New("DataChannel message Payload Protocol Identifier is value we can't handle") // ErrInvalidChannelType means that the remote requested a channel type that we don't support ErrInvalidChannelType = errors.New("invalid Channel Type") // ErrInvalidMessageType is returned when a DataChannel Message has a type we don't support ErrInvalidMessageType = errors.New("invalid Message Type") // ErrExpectedAndActualLengthMismatch is when the declared length and actual length don't match ErrExpectedAndActualLengthMismatch = errors.New("expected and actual length do not match") // ErrUnexpectedDataChannelType is when a message type does not match the expected type ErrUnexpectedDataChannelType = errors.New("expected and actual message type does not match") ) datachannel-1.5.5/go.mod000066400000000000000000000002751434572211700151040ustar00rootroot00000000000000module github.com/pion/datachannel require ( github.com/pion/logging v0.2.2 github.com/pion/sctp v1.8.5 github.com/pion/transport v0.14.1 github.com/stretchr/testify v1.8.1 ) go 1.13 datachannel-1.5.5/go.sum000066400000000000000000000126071434572211700151330ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= 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/sctp v1.8.5 h1:JCc25nghnXWOlSn3OVtEnA9PjQ2JsxQbG+CXZ1UkJKQ= github.com/pion/sctp v1.8.5/go.mod h1:SUFFfDpViyKejTAdwD1d/HQsCu+V/40cCs2nZIvC3s0= github.com/pion/transport v0.14.1 h1:XSM6olwW+o8J4SCmOBb/BpwZypkHeyM0PGFCxNQBr40= github.com/pion/transport v0.14.1/go.mod h1:4tGmbk00NeYA3rUa9+n+dzCCoKkcy3YlYb99Jn2fNnI= 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/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.1.0 h1:hZ/3BUoy5aId7sCpA/Tc5lt8DkFgdVS2onTpJsZ/fl0= golang.org/x/net v0.1.0/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.1.0/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= 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/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo= gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= datachannel-1.5.5/message.go000066400000000000000000000030711434572211700157460ustar00rootroot00000000000000package datachannel import ( "fmt" ) // message is a parsed DataChannel message type message interface { Marshal() ([]byte, error) Unmarshal([]byte) error } // messageType is the first byte in a DataChannel message that specifies type type messageType byte // DataChannel Message Types const ( dataChannelAck messageType = 0x02 dataChannelOpen messageType = 0x03 ) func (t messageType) String() string { switch t { case dataChannelAck: return "DataChannelAck" case dataChannelOpen: return "DataChannelOpen" default: return fmt.Sprintf("Unknown MessageType: %d", t) } } // parse accepts raw input and returns a DataChannel message func parse(raw []byte) (message, error) { if len(raw) == 0 { return nil, ErrDataChannelMessageTooShort } var msg message switch messageType(raw[0]) { case dataChannelOpen: msg = &channelOpen{} case dataChannelAck: msg = &channelAck{} default: return nil, fmt.Errorf("%w %v", ErrInvalidMessageType, messageType(raw[0])) } if err := msg.Unmarshal(raw); err != nil { return nil, err } return msg, nil } // parseExpectDataChannelOpen parses a DataChannelOpen message // or throws an error func parseExpectDataChannelOpen(raw []byte) (*channelOpen, error) { if len(raw) == 0 { return nil, ErrDataChannelMessageTooShort } if actualTyp := messageType(raw[0]); actualTyp != dataChannelOpen { return nil, fmt.Errorf("%w expected(%s) actual(%s)", ErrUnexpectedDataChannelType, actualTyp, dataChannelOpen) } msg := &channelOpen{} if err := msg.Unmarshal(raw); err != nil { return nil, err } return msg, nil } datachannel-1.5.5/message_channel_ack.go000066400000000000000000000010121434572211700202450ustar00rootroot00000000000000package datachannel // channelAck is used to ACK a DataChannel open type channelAck struct{} const ( channelOpenAckLength = 4 ) // Marshal returns raw bytes for the given message func (c *channelAck) Marshal() ([]byte, error) { raw := make([]byte, channelOpenAckLength) raw[0] = uint8(dataChannelAck) return raw, nil } // Unmarshal populates the struct with the given raw data func (c *channelAck) Unmarshal(raw []byte) error { // Message type already checked in Parse and there is no further data return nil } datachannel-1.5.5/message_channel_open.go000066400000000000000000000120511434572211700204550ustar00rootroot00000000000000package datachannel import ( "encoding/binary" "fmt" ) /* channelOpen represents a DATA_CHANNEL_OPEN Message 0 1 2 3 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Message Type | Channel Type | Priority | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Reliability Parameter | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Label Length | Protocol Length | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Label | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | | | Protocol | | | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ */ type channelOpen struct { ChannelType ChannelType Priority uint16 ReliabilityParameter uint32 Label []byte Protocol []byte } const ( channelOpenHeaderLength = 12 ) // ChannelType determines the reliability of the WebRTC DataChannel type ChannelType byte // ChannelType enums const ( // ChannelTypeReliable determines the Data Channel provides a // reliable in-order bi-directional communication. ChannelTypeReliable ChannelType = 0x00 // ChannelTypeReliableUnordered determines the Data Channel // provides a reliable unordered bi-directional communication. ChannelTypeReliableUnordered ChannelType = 0x80 // ChannelTypePartialReliableRexmit determines the Data Channel // provides a partially-reliable in-order bi-directional communication. // User messages will not be retransmitted more times than specified in the Reliability Parameter. ChannelTypePartialReliableRexmit ChannelType = 0x01 // ChannelTypePartialReliableRexmitUnordered determines // the Data Channel provides a partial reliable unordered bi-directional communication. // User messages will not be retransmitted more times than specified in the Reliability Parameter. ChannelTypePartialReliableRexmitUnordered ChannelType = 0x81 // ChannelTypePartialReliableTimed determines the Data Channel // provides a partial reliable in-order bi-directional communication. // User messages might not be transmitted or retransmitted after // a specified life-time given in milli- seconds in the Reliability Parameter. // This life-time starts when providing the user message to the protocol stack. ChannelTypePartialReliableTimed ChannelType = 0x02 // The Data Channel provides a partial reliable unordered bi-directional // communication. User messages might not be transmitted or retransmitted // after a specified life-time given in milli- seconds in the Reliability Parameter. // This life-time starts when providing the user message to the protocol stack. ChannelTypePartialReliableTimedUnordered ChannelType = 0x82 ) // ChannelPriority enums const ( ChannelPriorityBelowNormal uint16 = 128 ChannelPriorityNormal uint16 = 256 ChannelPriorityHigh uint16 = 512 ChannelPriorityExtraHigh uint16 = 1024 ) // Marshal returns raw bytes for the given message func (c *channelOpen) Marshal() ([]byte, error) { labelLength := len(c.Label) protocolLength := len(c.Protocol) totalLen := channelOpenHeaderLength + labelLength + protocolLength raw := make([]byte, totalLen) raw[0] = uint8(dataChannelOpen) raw[1] = byte(c.ChannelType) binary.BigEndian.PutUint16(raw[2:], c.Priority) binary.BigEndian.PutUint32(raw[4:], c.ReliabilityParameter) binary.BigEndian.PutUint16(raw[8:], uint16(labelLength)) binary.BigEndian.PutUint16(raw[10:], uint16(protocolLength)) endLabel := channelOpenHeaderLength + labelLength copy(raw[channelOpenHeaderLength:endLabel], c.Label) copy(raw[endLabel:endLabel+protocolLength], c.Protocol) return raw, nil } // Unmarshal populates the struct with the given raw data func (c *channelOpen) Unmarshal(raw []byte) error { if len(raw) < channelOpenHeaderLength { return fmt.Errorf("%w expected(%d) actual(%d)", ErrExpectedAndActualLengthMismatch, channelOpenHeaderLength, len(raw)) } c.ChannelType = ChannelType(raw[1]) c.Priority = binary.BigEndian.Uint16(raw[2:]) c.ReliabilityParameter = binary.BigEndian.Uint32(raw[4:]) labelLength := binary.BigEndian.Uint16(raw[8:]) protocolLength := binary.BigEndian.Uint16(raw[10:]) if expectedLen := int(channelOpenHeaderLength + labelLength + protocolLength); len(raw) != expectedLen { return fmt.Errorf("%w expected(%d) actual(%d)", ErrExpectedAndActualLengthMismatch, expectedLen, len(raw)) } c.Label = raw[channelOpenHeaderLength : channelOpenHeaderLength+labelLength] c.Protocol = raw[channelOpenHeaderLength+labelLength : channelOpenHeaderLength+labelLength+protocolLength] return nil } datachannel-1.5.5/message_test.go000066400000000000000000000041501434572211700170040ustar00rootroot00000000000000package datachannel import ( "testing" "github.com/stretchr/testify/assert" ) func TestChannelOpenMarshal(t *testing.T) { msg := channelOpen{ ChannelType: ChannelTypeReliable, Priority: 0, ReliabilityParameter: 0, Label: []byte("foo"), Protocol: []byte("bar"), } rawMsg, err := msg.Marshal() if err != nil { t.Errorf("Failed to marshal: %v", err) return } result := []byte{ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, } if len(rawMsg) != len(result) { t.Errorf("%q != %q", rawMsg, result) return } for i, v := range rawMsg { if v != result[i] { t.Errorf("%q != %q", rawMsg, result) break } } } func TestChannelAckMarshal(t *testing.T) { msg := channelAck{} rawMsg, err := msg.Marshal() if err != nil { t.Errorf("Failed to marshal: %v", err) return } result := []byte{0x02, 0x00, 0x00, 0x00} if len(rawMsg) != len(result) { t.Errorf("%q != %q", rawMsg, result) return } for i, v := range rawMsg { if v != result[i] { t.Errorf("%q != %q", rawMsg, result) break } } } func TestChannelOpenUnmarshal(t *testing.T) { rawMsg := []byte{ 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x66, 0x6f, 0x6f, 0x62, 0x61, 0x72, } msgUncast, err := parse(rawMsg) msg, ok := msgUncast.(*channelOpen) assert.True(t, ok, "Failed to cast to ChannelOpen") assert.NoError(t, err, "Unmarshal failed, ChannelOpen") assert.Equal(t, msg.ChannelType, ChannelTypeReliable, "ChannelType should be 0") assert.Equal(t, msg.Priority, uint16(0), "Priority should be 0") assert.Equal(t, msg.ReliabilityParameter, uint32(0), "ReliabilityParameter should be 0") assert.Equal(t, msg.Label, []uint8("foo"), "msg Label should be 'foo'") assert.Equal(t, msg.Protocol, []uint8("bar"), "msg protocol should be 'bar'") } func TestChannelAckUnmarshal(t *testing.T) { rawMsg := []byte{0x02} msgUncast, err := parse(rawMsg) if err != nil { t.Errorf("Failed to parse: %v", err) return } _, ok := msgUncast.(*channelAck) assert.True(t, ok, "Failed to cast to ChannelAck") } datachannel-1.5.5/renovate.json000066400000000000000000000011661434572211700165140ustar00rootroot00000000000000{ "extends": [ "config:base", ":disableDependencyDashboard" ], "postUpdateOptions": [ "gomodTidy" ], "commitBody": "Generated by renovateBot", "packageRules": [ { "matchUpdateTypes": ["minor", "patch", "pin", "digest"], "automerge": true }, { "packagePatterns": ["^golang.org/x/"], "schedule": ["on the first day of the month"] } ], "ignorePaths": [ ".github/workflows/generate-authors.yml", ".github/workflows/lint.yaml", ".github/workflows/renovate-go-mod-fix.yaml", ".github/workflows/test.yaml", ".github/workflows/tidy-check.yaml" ] }