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

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

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

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

126
server/vendor/github.com/pion/mdns/.golangci.yml generated vendored Normal file
View File

@@ -0,0 +1,126 @@
# SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
# SPDX-License-Identifier: MIT
linters-settings:
govet:
check-shadowing: true
misspell:
locale: US
exhaustive:
default-signifies-exhaustive: true
gomodguard:
blocked:
modules:
- github.com/pkg/errors:
recommendations:
- errors
forbidigo:
forbid:
- ^fmt.Print(f|ln)?$
- ^log.(Panic|Fatal|Print)(f|ln)?$
- ^os.Exit$
- ^panic$
- ^print(ln)?$
linters:
enable:
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- contextcheck # check the function whether use a non-inherited context
- decorder # check declaration order and count of types, constants, variables and functions
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- exhaustive # check exhaustiveness of enum switch statements
- exportloopref # checks for pointers to enclosing loop variables
- forbidigo # Forbids identifiers
- forcetypeassert # finds forced type assertions
- gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- godox # Tool for detection of FIXME, TODO and other comment keywords
- goerr113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # noctx finds sending http request without context.Context
- predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace
disable:
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- 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
- nakedret # Finds naked returns in functions greater than a specified function length
- 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 and examples, better to be self contained
- path: (examples|main\.go|_test\.go)
linters:
- forbidigo
- gocognit
# Allow forbidden identifiers in CLI commands
- path: cmd
linters:
- forbidigo
run:
skip-dirs-use-default: false

5
server/vendor/github.com/pion/mdns/.goreleaser.yml generated vendored Normal file
View File

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

21
server/vendor/github.com/pion/mdns/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT 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.

72
server/vendor/github.com/pion/mdns/README.md generated vendored Normal file
View File

@@ -0,0 +1,72 @@
<h1 align="center">
<br>
Pion mDNS
<br>
</h1>
<h4 align="center">A Go implementation of mDNS</h4>
<p align="center">
<a href="https://pion.ly"><img src="https://img.shields.io/badge/pion-mdns-gray.svg?longCache=true&colorB=brightgreen" alt="Pion mDNS"></a>
<a href="https://pion.ly/slack"><img src="https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen" alt="Slack Widget"></a>
<br>
<img alt="GitHub Workflow Status" src="https://img.shields.io/github/actions/workflow/status/pion/mdns/test.yaml">
<a href="https://pkg.go.dev/github.com/pion/mdns"><img src="https://pkg.go.dev/badge/github.com/pion/mdsn.svg" alt="Go Reference"></a>
<a href="https://codecov.io/gh/pion/mdns"><img src="https://codecov.io/gh/pion/mdns/branch/master/graph/badge.svg" alt="Coverage Status"></a>
<a href="https://goreportcard.com/report/github.com/pion/mdns"><img src="https://goreportcard.com/badge/github.com/pion/mdns" 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>
Go mDNS implementation. The original user is Pion WebRTC, but we would love to see it work for everyone.
### Running Server
For a mDNS server that responds to queries for `pion-test.local`
```sh
go run examples/server/main.go
```
For a mDNS server that responds to queries for `pion-test.local` with a given address
```sh
go run examples/server/publish_ip/main.go -ip=[IP]
```
If you don't set the `ip` parameter, "1.2.3.4" will be used instead.
### Running Client
To query using Pion you can run the `query` example
```sh
go run examples/query/main.go
```
You can use the macOS client
```
dns-sd -q pion-test.local
```
Or the avahi client
```
avahi-resolve -a pion-test.local
```
### RFCs
#### Implemented
- **RFC 6762** [Multicast DNS][rfc6762]
- **draft-ietf-rtcweb-mdns-ice-candidates-02** [Using Multicast DNS to protect privacy when exposing ICE candidates](https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-mdns-ice-candidates-02.html)
[rfc6762]: https://tools.ietf.org/html/rfc6762
### Roadmap
The library is used as a part of our WebRTC implementation. Please refer to that [roadmap](https://github.com/pion/webrtc/issues/9) to track our major milestones.
### Community
Pion has an active community on the [Slack](https://pion.ly/slack).
Follow the [Pion Twitter](https://twitter.com/_pion) for project updates and important WebRTC news.
We are always looking to support **your projects**. Please reach out if you have something to build!
If you need commercial support or don't want to use public methods you can contact us at [team@pion.ly](mailto:team@pion.ly)
### Contributing
Check out the [contributing wiki](https://github.com/pion/webrtc/wiki/Contributing) to join the group of amazing people making this project possible
### License
MIT License - see [LICENSE](LICENSE) for full text

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

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

41
server/vendor/github.com/pion/mdns/config.go generated vendored Normal file
View File

@@ -0,0 +1,41 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package mdns
import (
"net"
"time"
"github.com/pion/logging"
)
const (
// DefaultAddress is the default used by mDNS
// and in most cases should be the address that the
// net.Conn passed to Server is bound to
DefaultAddress = "224.0.0.0:5353"
)
// Config is used to configure a mDNS client or server.
type Config struct {
// QueryInterval controls how often we sends Queries until we
// get a response for the requested name
QueryInterval time.Duration
// LocalNames are the names that we will generate answers for
// when we get questions
LocalNames []string
// LocalAddress will override the published address with the given IP
// when set. Otherwise, the automatically determined address will be used.
LocalAddress net.IP
LoggerFactory logging.LoggerFactory
// IncludeLoopback will include loopback interfaces to be eligble for queries and answers.
IncludeLoopback bool
// Interfaces will override the interfaces used for queries and answers.
Interfaces []net.Interface
}

597
server/vendor/github.com/pion/mdns/conn.go generated vendored Normal file
View File

@@ -0,0 +1,597 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package mdns
import (
"context"
"errors"
"fmt"
"net"
"sync"
"time"
"github.com/pion/logging"
"golang.org/x/net/dns/dnsmessage"
"golang.org/x/net/ipv4"
)
// Conn represents a mDNS Server
type Conn struct {
mu sync.RWMutex
log logging.LeveledLogger
socket *ipv4.PacketConn
dstAddr *net.UDPAddr
queryInterval time.Duration
localNames []string
queries []*query
ifaces []net.Interface
closed chan interface{}
}
type query struct {
nameWithSuffix string
queryResultChan chan queryResult
}
type queryResult struct {
answer dnsmessage.ResourceHeader
addr net.Addr
}
const (
defaultQueryInterval = time.Second
destinationAddress = "224.0.0.251:5353"
maxMessageRecords = 3
responseTTL = 120
// maxPacketSize is the maximum size of a mdns packet.
// From RFC 6762:
// Even when fragmentation is used, a Multicast DNS packet, including IP
// and UDP headers, MUST NOT exceed 9000 bytes.
// https://datatracker.ietf.org/doc/html/rfc6762#section-17
maxPacketSize = 9000
)
var errNoPositiveMTUFound = errors.New("no positive MTU found")
// Server establishes a mDNS connection over an existing conn.
//
// Currently, the server only supports listening on an IPv4 connection, but internally
// it supports answering with IPv6 AAAA records if this were ever to change.
func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) {
if config == nil {
return nil, errNilConfig
}
ifaces := config.Interfaces
if ifaces == nil {
var err error
ifaces, err = net.Interfaces()
if err != nil {
return nil, err
}
}
inboundBufferSize := 0
joinErrCount := 0
ifacesToUse := make([]net.Interface, 0, len(ifaces))
for i, ifc := range ifaces {
if !config.IncludeLoopback && ifc.Flags&net.FlagLoopback == net.FlagLoopback {
continue
}
if err := conn.JoinGroup(&ifaces[i], &net.UDPAddr{IP: net.IPv4(224, 0, 0, 251)}); err != nil {
joinErrCount++
continue
}
ifcCopy := ifc
ifacesToUse = append(ifacesToUse, ifcCopy)
if ifaces[i].MTU > inboundBufferSize {
inboundBufferSize = ifaces[i].MTU
}
}
if inboundBufferSize == 0 {
return nil, errNoPositiveMTUFound
}
if inboundBufferSize > maxPacketSize {
inboundBufferSize = maxPacketSize
}
if joinErrCount >= len(ifaces) {
return nil, errJoiningMulticastGroup
}
dstAddr, err := net.ResolveUDPAddr("udp", destinationAddress)
if err != nil {
return nil, err
}
loggerFactory := config.LoggerFactory
if loggerFactory == nil {
loggerFactory = logging.NewDefaultLoggerFactory()
}
localNames := []string{}
for _, l := range config.LocalNames {
localNames = append(localNames, l+".")
}
c := &Conn{
queryInterval: defaultQueryInterval,
queries: []*query{},
socket: conn,
dstAddr: dstAddr,
localNames: localNames,
ifaces: ifacesToUse,
log: loggerFactory.NewLogger("mdns"),
closed: make(chan interface{}),
}
if config.QueryInterval != 0 {
c.queryInterval = config.QueryInterval
}
if err := conn.SetControlMessage(ipv4.FlagInterface, true); err != nil {
c.log.Warnf("Failed to SetControlMessage on PacketConn %v", err)
}
if config.IncludeLoopback {
// this is an efficient way for us to send ourselves a message faster instead of it going
// further out into the network stack.
if err := conn.SetMulticastLoopback(true); err != nil {
c.log.Warnf("Failed to SetMulticastLoopback(true) on PacketConn %v; this may cause inefficient network path communications", err)
}
}
// https://www.rfc-editor.org/rfc/rfc6762.html#section-17
// Multicast DNS messages carried by UDP may be up to the IP MTU of the
// physical interface, less the space required for the IP header (20
// bytes for IPv4; 40 bytes for IPv6) and the UDP header (8 bytes).
go c.start(inboundBufferSize-20-8, config)
return c, nil
}
// Close closes the mDNS Conn
func (c *Conn) Close() error {
select {
case <-c.closed:
return nil
default:
}
if err := c.socket.Close(); err != nil {
return err
}
<-c.closed
return nil
}
// Query sends mDNS Queries for the following name until
// either the Context is canceled/expires or we get a result
func (c *Conn) Query(ctx context.Context, name string) (dnsmessage.ResourceHeader, net.Addr, error) {
select {
case <-c.closed:
return dnsmessage.ResourceHeader{}, nil, errConnectionClosed
default:
}
nameWithSuffix := name + "."
queryChan := make(chan queryResult, 1)
query := &query{nameWithSuffix, queryChan}
c.mu.Lock()
c.queries = append(c.queries, query)
c.mu.Unlock()
defer func() {
c.mu.Lock()
defer c.mu.Unlock()
for i := len(c.queries) - 1; i >= 0; i-- {
if c.queries[i] == query {
c.queries = append(c.queries[:i], c.queries[i+1:]...)
}
}
}()
ticker := time.NewTicker(c.queryInterval)
defer ticker.Stop()
c.sendQuestion(nameWithSuffix)
for {
select {
case <-ticker.C:
c.sendQuestion(nameWithSuffix)
case <-c.closed:
return dnsmessage.ResourceHeader{}, nil, errConnectionClosed
case res := <-queryChan:
// Given https://datatracker.ietf.org/doc/html/draft-ietf-mmusic-mdns-ice-candidates#section-3.2.2-2
// An ICE agent SHOULD ignore candidates where the hostname resolution returns more than one IP address.
//
// We will take the first we receive which could result in a race between two suitable addresses where
// one is better than the other (e.g. localhost vs LAN).
return res.answer, res.addr, nil
case <-ctx.Done():
return dnsmessage.ResourceHeader{}, nil, errContextElapsed
}
}
}
type ipToBytesError struct {
ip net.IP
expectedType string
}
func (err ipToBytesError) Error() string {
return fmt.Sprintf("ip (%s) is not %s", err.ip, err.expectedType)
}
func ipv4ToBytes(ip net.IP) ([4]byte, error) {
rawIP := ip.To4()
if rawIP == nil {
return [4]byte{}, ipToBytesError{ip, "IPv4"}
}
// net.IPs are stored in big endian / network byte order
var out [4]byte
copy(out[:], rawIP[:])
return out, nil
}
func ipv6ToBytes(ip net.IP) ([16]byte, error) {
rawIP := ip.To16()
if rawIP == nil {
return [16]byte{}, ipToBytesError{ip, "IPv6"}
}
// net.IPs are stored in big endian / network byte order
var out [16]byte
copy(out[:], rawIP[:])
return out, nil
}
func interfaceForRemote(remote string) (net.IP, error) {
conn, err := net.Dial("udp", remote)
if err != nil {
return nil, err
}
localAddr, ok := conn.LocalAddr().(*net.UDPAddr)
if !ok {
return nil, errFailedCast
}
if err := conn.Close(); err != nil {
return nil, err
}
return localAddr.IP, nil
}
func (c *Conn) sendQuestion(name string) {
packedName, err := dnsmessage.NewName(name)
if err != nil {
c.log.Warnf("Failed to construct mDNS packet %v", err)
return
}
msg := dnsmessage.Message{
Header: dnsmessage.Header{},
Questions: []dnsmessage.Question{
{
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
Name: packedName,
},
},
}
rawQuery, err := msg.Pack()
if err != nil {
c.log.Warnf("Failed to construct mDNS packet %v", err)
return
}
c.writeToSocket(0, rawQuery, false)
}
func (c *Conn) writeToSocket(ifIndex int, b []byte, srcIfcIsLoopback bool) {
if ifIndex != 0 {
ifc, err := net.InterfaceByIndex(ifIndex)
if err != nil {
c.log.Warnf("Failed to get interface for %d: %v", ifIndex, err)
return
}
if srcIfcIsLoopback && ifc.Flags&net.FlagLoopback == 0 {
// avoid accidentally tricking the destination that itself is the same as us
c.log.Warnf("Interface is not loopback %d", ifIndex)
return
}
if err := c.socket.SetMulticastInterface(ifc); err != nil {
c.log.Warnf("Failed to set multicast interface for %d: %v", ifIndex, err)
} else {
if _, err := c.socket.WriteTo(b, nil, c.dstAddr); err != nil {
c.log.Warnf("Failed to send mDNS packet on interface %d: %v", ifIndex, err)
}
}
return
}
for ifcIdx := range c.ifaces {
if srcIfcIsLoopback && c.ifaces[ifcIdx].Flags&net.FlagLoopback == 0 {
// avoid accidentally tricking the destination that itself is the same as us
continue
}
if err := c.socket.SetMulticastInterface(&c.ifaces[ifcIdx]); err != nil {
c.log.Warnf("Failed to set multicast interface for %d: %v", c.ifaces[ifcIdx].Index, err)
} else {
if _, err := c.socket.WriteTo(b, nil, c.dstAddr); err != nil {
c.log.Warnf("Failed to send mDNS packet on interface %d: %v", c.ifaces[ifcIdx].Index, err)
}
}
}
}
func createAnswer(name string, addr net.IP) (dnsmessage.Message, error) {
packedName, err := dnsmessage.NewName(name)
if err != nil {
return dnsmessage.Message{}, err
}
msg := dnsmessage.Message{
Header: dnsmessage.Header{
Response: true,
Authoritative: true,
},
Answers: []dnsmessage.Resource{
{
Header: dnsmessage.ResourceHeader{
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET,
Name: packedName,
TTL: responseTTL,
},
},
},
}
if ip4 := addr.To4(); ip4 != nil {
ipBuf, err := ipv4ToBytes(addr)
if err != nil {
return dnsmessage.Message{}, err
}
msg.Answers[0].Body = &dnsmessage.AResource{
A: ipBuf,
}
} else {
ipBuf, err := ipv6ToBytes(addr)
if err != nil {
return dnsmessage.Message{}, err
}
msg.Answers[0].Body = &dnsmessage.AAAAResource{
AAAA: ipBuf,
}
}
return msg, nil
}
func (c *Conn) sendAnswer(name string, ifIndex int, addr net.IP) {
answer, err := createAnswer(name, addr)
if err != nil {
c.log.Warnf("Failed to create mDNS answer %v", err)
return
}
rawAnswer, err := answer.Pack()
if err != nil {
c.log.Warnf("Failed to construct mDNS packet %v", err)
return
}
c.writeToSocket(ifIndex, rawAnswer, addr.IsLoopback())
}
func (c *Conn) start(inboundBufferSize int, config *Config) { //nolint gocognit
defer func() {
c.mu.Lock()
defer c.mu.Unlock()
close(c.closed)
}()
b := make([]byte, inboundBufferSize)
p := dnsmessage.Parser{}
for {
n, cm, src, err := c.socket.ReadFrom(b)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
c.log.Warnf("Failed to ReadFrom %q %v", src, err)
continue
}
var ifIndex int
if cm != nil {
ifIndex = cm.IfIndex
}
var srcIP net.IP
switch addr := src.(type) {
case *net.UDPAddr:
srcIP = addr.IP
case *net.TCPAddr:
srcIP = addr.IP
default:
c.log.Warnf("Failed to determine address type %T for source address %s", src, src)
continue
}
srcIsIPv4 := srcIP.To4() != nil
func() {
c.mu.RLock()
defer c.mu.RUnlock()
if _, err := p.Start(b[:n]); err != nil {
c.log.Warnf("Failed to parse mDNS packet %v", err)
return
}
for i := 0; i <= maxMessageRecords; i++ {
q, err := p.Question()
if errors.Is(err, dnsmessage.ErrSectionDone) {
break
} else if err != nil {
c.log.Warnf("Failed to parse mDNS packet %v", err)
return
}
for _, localName := range c.localNames {
if localName == q.Name.String() {
if config.LocalAddress != nil {
c.sendAnswer(q.Name.String(), ifIndex, config.LocalAddress)
} else {
var localAddress net.IP
// prefer the address of the interface if we know its index, but otherwise
// derive it from the address we read from. We do this because even if
// multicast loopback is in use or we send from a loopback interface,
// there are still cases where the IP packet will contain the wrong
// source IP (e.g. a LAN interface).
// For example, we can have a packet that has:
// Source: 192.168.65.3
// Destination: 224.0.0.251
// Interface Index: 1
// Interface Addresses @ 1: [127.0.0.1/8 ::1/128]
if ifIndex != 0 {
ifc, netErr := net.InterfaceByIndex(ifIndex)
if netErr != nil {
c.log.Warnf("Failed to get interface for %d: %v", ifIndex, netErr)
continue
}
addrs, addrsErr := ifc.Addrs()
if addrsErr != nil {
c.log.Warnf("Failed to get addresses for interface %d: %v", ifIndex, addrsErr)
continue
}
if len(addrs) == 0 {
c.log.Warnf("Expected more than one address for interface %d", ifIndex)
continue
}
var selectedIP net.IP
for _, addr := range addrs {
var ip net.IP
switch addr := addr.(type) {
case *net.IPNet:
ip = addr.IP
case *net.IPAddr:
ip = addr.IP
default:
c.log.Warnf("Failed to determine address type %T from interface %d", addr, ifIndex)
continue
}
// match up respective IP types
if ipv4 := ip.To4(); ipv4 == nil {
if srcIsIPv4 {
continue
} else if !isSupportedIPv6(ip) {
continue
}
} else if !srcIsIPv4 {
continue
}
selectedIP = ip
break
}
if selectedIP == nil {
c.log.Warnf("Failed to find suitable IP for interface %d; deriving address from source address instead", ifIndex)
} else {
localAddress = selectedIP
}
} else if ifIndex == 0 || localAddress == nil {
localAddress, err = interfaceForRemote(src.String())
if err != nil {
c.log.Warnf("Failed to get local interface to communicate with %s: %v", src.String(), err)
continue
}
}
c.sendAnswer(q.Name.String(), ifIndex, localAddress)
}
}
}
}
for i := 0; i <= maxMessageRecords; i++ {
a, err := p.AnswerHeader()
if errors.Is(err, dnsmessage.ErrSectionDone) {
return
}
if err != nil {
c.log.Warnf("Failed to parse mDNS packet %v", err)
return
}
if a.Type != dnsmessage.TypeA && a.Type != dnsmessage.TypeAAAA {
continue
}
for i := len(c.queries) - 1; i >= 0; i-- {
if c.queries[i].nameWithSuffix == a.Name.String() {
ip, err := ipFromAnswerHeader(a, p)
if err != nil {
c.log.Warnf("Failed to parse mDNS answer %v", err)
return
}
c.queries[i].queryResultChan <- queryResult{a, &net.IPAddr{
IP: ip,
}}
c.queries = append(c.queries[:i], c.queries[i+1:]...)
}
}
}
}()
}
}
func ipFromAnswerHeader(a dnsmessage.ResourceHeader, p dnsmessage.Parser) (ip []byte, err error) {
if a.Type == dnsmessage.TypeA {
resource, err := p.AResource()
if err != nil {
return nil, err
}
ip = resource.A[:]
} else {
resource, err := p.AAAAResource()
if err != nil {
return nil, err
}
ip = resource.AAAA[:]
}
return
}
// The conditions of invalidation written below are defined in
// https://tools.ietf.org/html/rfc8445#section-5.1.1.1
func isSupportedIPv6(ip net.IP) bool {
if len(ip) != net.IPv6len ||
isZeros(ip[0:12]) || // !(IPv4-compatible IPv6)
ip[0] == 0xfe && ip[1]&0xc0 == 0xc0 || // !(IPv6 site-local unicast)
ip.IsLinkLocalUnicast() ||
ip.IsLinkLocalMulticast() {
return false
}
return true
}
func isZeros(ip net.IP) bool {
for i := 0; i < len(ip); i++ {
if ip[i] != 0 {
return false
}
}
return true
}

14
server/vendor/github.com/pion/mdns/errors.go generated vendored Normal file
View File

@@ -0,0 +1,14 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package mdns
import "errors"
var (
errJoiningMulticastGroup = errors.New("mDNS: failed to join multicast group")
errConnectionClosed = errors.New("mDNS: connection is closed")
errContextElapsed = errors.New("mDNS: context has elapsed")
errNilConfig = errors.New("mDNS: config must not be nil")
errFailedCast = errors.New("mDNS: failed to cast listener to UDPAddr")
)

5
server/vendor/github.com/pion/mdns/mdns.go generated vendored Normal file
View File

@@ -0,0 +1,5 @@
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
// Package mdns implements mDNS (multicast DNS)
package mdns

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

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