pax_global_header00006660000000000000000000000064143671116140014516gustar00rootroot0000000000000052 comment=bde59ba7419409133f31f611677c24ea6bc36f22 mdns-0.0.7/000077500000000000000000000000001436711161400124635ustar00rootroot00000000000000mdns-0.0.7/.github/000077500000000000000000000000001436711161400140235ustar00rootroot00000000000000mdns-0.0.7/.github/.gitignore000066400000000000000000000000121436711161400160040ustar00rootroot00000000000000.goassets mdns-0.0.7/.github/fetch-scripts.sh000077500000000000000000000014351436711161400171430ustar00rootroot00000000000000#!/bin/sh # # 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 -eu SCRIPT_PATH="$(realpath "$(dirname "$0")")" GOASSETS_PATH="${SCRIPT_PATH}/.goassets" GOASSETS_REF=${GOASSETS_REF:-master} if [ -d "${GOASSETS_PATH}" ]; then if ! git -C "${GOASSETS_PATH}" diff --exit-code; then echo "${GOASSETS_PATH} has uncommitted changes" >&2 exit 1 fi git -C "${GOASSETS_PATH}" fetch origin git -C "${GOASSETS_PATH}" checkout ${GOASSETS_REF} git -C "${GOASSETS_PATH}" reset --hard origin/${GOASSETS_REF} else git clone -b ${GOASSETS_REF} https://github.com/pion/.goassets.git "${GOASSETS_PATH}" fi mdns-0.0.7/.github/install-hooks.sh000077500000000000000000000010771436711161400171560ustar00rootroot00000000000000#!/bin/sh # # 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="$(realpath "$(dirname "$0")")" . ${SCRIPT_PATH}/fetch-scripts.sh cp "${GOASSETS_PATH}/hooks/commit-msg.sh" "${SCRIPT_PATH}/../.git/hooks/commit-msg" cp "${GOASSETS_PATH}/hooks/pre-commit.sh" "${SCRIPT_PATH}/../.git/hooks/pre-commit" cp "${GOASSETS_PATH}/hooks/pre-push.sh" "${SCRIPT_PATH}/../.git/hooks/pre-push" mdns-0.0.7/.github/workflows/000077500000000000000000000000001436711161400160605ustar00rootroot00000000000000mdns-0.0.7/.github/workflows/codeql-analysis.yml000066400000000000000000000011551436711161400216750ustar00rootroot00000000000000# # 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: CodeQL on: workflow_dispatch: schedule: - cron: '23 5 * * 0' pull_request: branches: - master paths: - '**.go' jobs: analyze: uses: pion/.goassets/.github/workflows/codeql-analysis.reusable.yml@master mdns-0.0.7/.github/workflows/generate-authors.yml000066400000000000000000000011041436711161400220540ustar00rootroot00000000000000# # 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: generate: uses: pion/.goassets/.github/workflows/generate-authors.reusable.yml@master secrets: token: ${{ secrets.PIONBOT_PRIVATE_KEY }} mdns-0.0.7/.github/workflows/lint.yaml000066400000000000000000000007521436711161400177160ustar00rootroot00000000000000# # 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: jobs: lint: uses: pion/.goassets/.github/workflows/lint.reusable.yml@master mdns-0.0.7/.github/workflows/release.yml000066400000000000000000000011051436711161400202200ustar00rootroot00000000000000# # 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: Release on: push: tags: - 'v*' jobs: release: uses: pion/.goassets/.github/workflows/release.reusable.yml@master with: go-version: '1.19' # auto-update/latest-go-version mdns-0.0.7/.github/workflows/renovate-go-sum-fix.yaml000066400000000000000000000011241436711161400225560ustar00rootroot00000000000000# # 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: Fix go.sum on: push: branches: - renovate/* jobs: fix: uses: pion/.goassets/.github/workflows/renovate-go-sum-fix.reusable.yml@master secrets: token: ${{ secrets.PIONBOT_PRIVATE_KEY }} mdns-0.0.7/.github/workflows/test.yaml000066400000000000000000000021121436711161400177170ustar00rootroot00000000000000# # 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: jobs: test: uses: pion/.goassets/.github/workflows/test.reusable.yml@master strategy: matrix: go: ['1.19', '1.18'] # auto-update/supported-go-version-list fail-fast: false with: go-version: ${{ matrix.go }} test-i386: uses: pion/.goassets/.github/workflows/test-i386.reusable.yml@master strategy: matrix: go: ['1.19', '1.18'] # auto-update/supported-go-version-list fail-fast: false with: go-version: ${{ matrix.go }} test-wasm: uses: pion/.goassets/.github/workflows/test-wasm.reusable.yml@master with: go-version: '1.19' # auto-update/latest-go-version mdns-0.0.7/.github/workflows/tidy-check.yaml000066400000000000000000000011371436711161400207720ustar00rootroot00000000000000# # 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: push: branches: - master jobs: tidy: uses: pion/.goassets/.github/workflows/tidy-check.reusable.yml@master with: go-version: '1.19' # auto-update/latest-go-version mdns-0.0.7/.gitignore000066400000000000000000000004661436711161400144610ustar00rootroot00000000000000### 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 mdns-0.0.7/.golangci.yml000066400000000000000000000172751436711161400150630ustar00rootroot00000000000000linters-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 - 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 - stylecheck # Stylecheck is a replacement for golint - tagliatelle # Checks the struct tags. - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - wastedassign # wastedassign finds wasted assignment statements - whitespace # Tool for detection of leading and trailing whitespace disable: - containedctx # containedctx is a linter that detects struct contained context.Context field - cyclop # checks function and package cyclomatic complexity - exhaustivestruct # Checks if all struct's fields are initialized - 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 mdns-0.0.7/.goreleaser.yml000066400000000000000000000000251436711161400154110ustar00rootroot00000000000000builds: - skip: true mdns-0.0.7/AUTHORS.txt000066400000000000000000000013741436711161400143560ustar00rootroot00000000000000# Thank you to everyone that made Pion possible. If you are interested in contributing # we would love to have you https://github.com/pion/webrtc/wiki/Contributing # # This file is auto generated, using git to list all individuals contributors. # see https://github.com/pion/.goassets/blob/master/scripts/generate-authors.sh for the scripting Atsushi Watanabe Bjørn Remseth Doug Cone Hugo Arregui Javier Peletier Jonas van den Berg <24623262+vonas@users.noreply.github.com> Konstantin Itskov Sean DuBois Sean DuBois # List of contributors not appearing in Git history mdns-0.0.7/LICENSE000066400000000000000000000020411436711161400134650ustar00rootroot00000000000000MIT 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. mdns-0.0.7/README.md000066400000000000000000000046051436711161400137470ustar00rootroot00000000000000


Pion mDNS

A Go implementation of mDNS

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


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 ``` ### 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 ``` ### References https://tools.ietf.org/html/rfc6762 https://tools.ietf.org/id/draft-ietf-rtcweb-mdns-ice-candidates-02.html ### 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 mdns-0.0.7/codecov.yml000066400000000000000000000005521436711161400146320ustar00rootroot00000000000000# # 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/**/*" mdns-0.0.7/config.go000066400000000000000000000011441436711161400142570ustar00rootroot00000000000000package mdns import ( "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 LoggerFactory logging.LoggerFactory } mdns-0.0.7/conn.go000066400000000000000000000201271436711161400137510ustar00rootroot00000000000000package mdns import ( "context" "errors" "math/big" "net" "runtime" "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 ) var errNoPositiveMTUFound = errors.New("no positive MTU found") // Server establishes a mDNS connection over an existing conn func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) { if config == nil { return nil, errNilConfig } 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 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 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 } // 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) 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) c.mu.Lock() c.queries = append(c.queries, query{nameWithSuffix, queryChan}) ticker := time.NewTicker(c.queryInterval) c.mu.Unlock() 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: return res.answer, res.addr, nil case <-ctx.Done(): return dnsmessage.ResourceHeader{}, nil, errContextElapsed } } } func ipToBytes(ip net.IP) (out [4]byte) { rawIP := ip.To4() if rawIP == nil { return } ipInt := big.NewInt(0) ipInt.SetBytes(rawIP) copy(out[:], ipInt.Bytes()) return } 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(rawQuery) } const isWindows = runtime.GOOS == "windows" func (c *Conn) writeToSocket(b []byte) { var wcm ipv4.ControlMessage for i := range c.ifaces { if isWindows { if err := c.socket.SetMulticastInterface(&c.ifaces[i]); err != nil { c.log.Warnf("Failed to set multicast interface for %d: %v", i, err) } } else { wcm.IfIndex = c.ifaces[i].Index } if _, err := c.socket.WriteTo(b, &wcm, c.dstAddr); err != nil { c.log.Warnf("Failed to send mDNS packet on interface %d: %v", i, err) } } } func (c *Conn) sendAnswer(name string, dst net.IP) { 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{ Response: true, Authoritative: true, }, Answers: []dnsmessage.Resource{ { Header: dnsmessage.ResourceHeader{ Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, Name: packedName, TTL: responseTTL, }, Body: &dnsmessage.AResource{ A: ipToBytes(dst), }, }, }, } rawAnswer, err := msg.Pack() if err != nil { c.log.Warnf("Failed to construct mDNS packet %v", err) return } c.writeToSocket(rawAnswer) } func (c *Conn) start(inboundBufferSize int) { //nolint gocognit defer func() { c.mu.Lock() defer c.mu.Unlock() close(c.closed) }() b := make([]byte, inboundBufferSize) p := dnsmessage.Parser{} for { n, _, 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 } 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() { 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(), 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 = net.IP(resource.A[:]) } else { resource, err := p.AAAAResource() if err != nil { return nil, err } ip = resource.AAAA[:] } return } mdns-0.0.7/conn_test.go000066400000000000000000000103541436711161400150110ustar00rootroot00000000000000//go:build !js // +build !js package mdns import ( "bytes" "context" "errors" "net" "testing" "time" "github.com/pion/transport/v2/test" "golang.org/x/net/dns/dnsmessage" "golang.org/x/net/ipv4" ) func check(err error, t *testing.T) { if err != nil { t.Fatal(err) } } func createListener(t *testing.T) *net.UDPConn { addr, err := net.ResolveUDPAddr("udp", DefaultAddress) check(err, t) sock, err := net.ListenUDP("udp4", addr) check(err, t) return sock } func TestValidCommunication(t *testing.T) { lim := test.TimeOut(time.Second * 10) defer lim.Stop() report := test.CheckRoutines(t) defer report() aSock := createListener(t) bSock := createListener(t) aServer, err := Server(ipv4.NewPacketConn(aSock), &Config{ LocalNames: []string{"pion-mdns-1.local", "pion-mdns-2.local"}, }) check(err, t) bServer, err := Server(ipv4.NewPacketConn(bSock), &Config{}) check(err, t) _, _, err = bServer.Query(context.TODO(), "pion-mdns-1.local") check(err, t) _, _, err = bServer.Query(context.TODO(), "pion-mdns-2.local") check(err, t) check(aServer.Close(), t) check(bServer.Close(), t) } func TestMultipleClose(t *testing.T) { lim := test.TimeOut(time.Second * 10) defer lim.Stop() report := test.CheckRoutines(t) defer report() aSock := createListener(t) server, err := Server(ipv4.NewPacketConn(aSock), &Config{}) check(err, t) check(server.Close(), t) check(server.Close(), t) } func TestQueryRespectTimeout(t *testing.T) { lim := test.TimeOut(time.Second * 10) defer lim.Stop() report := test.CheckRoutines(t) defer report() aSock := createListener(t) server, err := Server(ipv4.NewPacketConn(aSock), &Config{}) check(err, t) ctx, cancel := context.WithTimeout(context.Background(), 500*time.Millisecond) defer cancel() if _, _, err = server.Query(ctx, "invalid-host"); !errors.Is(err, errContextElapsed) { t.Fatalf("Query expired but returned unexpected error %v", err) } if closeErr := server.Close(); closeErr != nil { t.Fatal(closeErr) } } func TestQueryRespectClose(t *testing.T) { lim := test.TimeOut(time.Second * 10) defer lim.Stop() report := test.CheckRoutines(t) defer report() aSock := createListener(t) server, err := Server(ipv4.NewPacketConn(aSock), &Config{}) check(err, t) go func() { time.Sleep(3 * time.Second) check(server.Close(), t) }() if _, _, err = server.Query(context.TODO(), "invalid-host"); !errors.Is(err, errConnectionClosed) { t.Fatalf("Query on closed server but returned unexpected error %v", err) } if _, _, err = server.Query(context.TODO(), "invalid-host"); !errors.Is(err, errConnectionClosed) { t.Fatalf("Query on closed server but returned unexpected error %v", err) } } func TestResourceParsing(t *testing.T) { lookForIP := func(msg dnsmessage.Message, expectedIP []byte) { buf, err := msg.Pack() if err != nil { t.Fatal(err) } var p dnsmessage.Parser if _, err = p.Start(buf); err != nil { t.Fatal(err) } if err = p.SkipAllQuestions(); err != nil { t.Fatal(err) } h, err := p.AnswerHeader() if err != nil { t.Fatal(err) } actualIP, err := ipFromAnswerHeader(h, p) if err != nil { t.Fatal(err) } if !bytes.Equal(actualIP, expectedIP) { t.Fatalf("Expected(%v) and Actual(%v) IP don't match", expectedIP, actualIP) } } name, err := dnsmessage.NewName("test-server.") if err != nil { t.Fatal(err) } t.Run("A Record", func(t *testing.T) { lookForIP(dnsmessage.Message{ Header: dnsmessage.Header{Response: true, Authoritative: true}, Answers: []dnsmessage.Resource{ { Header: dnsmessage.ResourceHeader{ Name: name, Type: dnsmessage.TypeA, Class: dnsmessage.ClassINET, }, Body: &dnsmessage.AResource{A: [4]byte{127, 0, 0, 1}}, }, }, }, []byte{127, 0, 0, 1}) }) t.Run("AAAA Record", func(t *testing.T) { lookForIP(dnsmessage.Message{ Header: dnsmessage.Header{Response: true, Authoritative: true}, Answers: []dnsmessage.Resource{ { Header: dnsmessage.ResourceHeader{ Name: name, Type: dnsmessage.TypeAAAA, Class: dnsmessage.ClassINET, }, Body: &dnsmessage.AAAAResource{AAAA: [16]byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}}, }, }, }, []byte{0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}) }) } mdns-0.0.7/errors.go000066400000000000000000000006311436711161400143260ustar00rootroot00000000000000package 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") ) mdns-0.0.7/examples/000077500000000000000000000000001436711161400143015ustar00rootroot00000000000000mdns-0.0.7/examples/query/000077500000000000000000000000001436711161400154465ustar00rootroot00000000000000mdns-0.0.7/examples/query/main.go000066400000000000000000000007771436711161400167340ustar00rootroot00000000000000package main import ( "context" "fmt" "net" "github.com/pion/mdns" "golang.org/x/net/ipv4" ) func main() { addr, err := net.ResolveUDPAddr("udp", mdns.DefaultAddress) if err != nil { panic(err) } l, err := net.ListenUDP("udp4", addr) if err != nil { panic(err) } server, err := mdns.Server(ipv4.NewPacketConn(l), &mdns.Config{}) if err != nil { panic(err) } answer, src, err := server.Query(context.TODO(), "pion-test.local") fmt.Println(answer) fmt.Println(src) fmt.Println(err) } mdns-0.0.7/examples/server/000077500000000000000000000000001436711161400156075ustar00rootroot00000000000000mdns-0.0.7/examples/server/main.go000066400000000000000000000006411436711161400170630ustar00rootroot00000000000000package main import ( "net" "github.com/pion/mdns" "golang.org/x/net/ipv4" ) func main() { addr, err := net.ResolveUDPAddr("udp", mdns.DefaultAddress) if err != nil { panic(err) } l, err := net.ListenUDP("udp4", addr) if err != nil { panic(err) } _, err = mdns.Server(ipv4.NewPacketConn(l), &mdns.Config{ LocalNames: []string{"pion-test.local"}, }) if err != nil { panic(err) } select {} } mdns-0.0.7/go.mod000066400000000000000000000002201436711161400135630ustar00rootroot00000000000000module github.com/pion/mdns go 1.12 require ( github.com/pion/logging v0.2.2 github.com/pion/transport/v2 v2.0.0 golang.org/x/net v0.5.0 ) mdns-0.0.7/go.sum000066400000000000000000000110561436711161400136210ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= github.com/pion/transport/v2 v2.0.0 h1:bsMYyqHCbkvHwj+eNCFBuxtlKndKfyGI2vaQmM3fIE4= github.com/pion/transport/v2 v2.0.0/go.mod h1:HS2MEBJTwD+1ZI2eSXSvHJx/HnzQqRy2/LXxt6eVMHc= 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/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/go.mod h1:Cx3nUiGt4eDBEyega/BKRp+/AlGL8hYe7U9odMt2Cco= golang.org/x/net v0.5.0 h1:GyT4nK/YDHSqa1c4753ouYCDajOYKTja9Xb/OHtgvSw= golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws= 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/sys v0.4.0 h1:Zr2JFtRQNX3BCZ8YtxRE9hNJYC8J6I1MVbMg6owUp18= golang.org/x/sys v0.4.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/term v0.4.0/go.mod h1:9P2UbLfCdcvo3p/nzKvsmas4TnlujnuoV9hGgYzW1lQ= 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/text v0.6.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/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= mdns-0.0.7/mdns.go000066400000000000000000000000751436711161400137550ustar00rootroot00000000000000// Package mdns implements mDNS (multicast DNS) package mdns mdns-0.0.7/renovate.json000066400000000000000000000001731436711161400152020ustar00rootroot00000000000000{ "$schema": "https://docs.renovatebot.com/renovate-schema.json", "extends": [ "github>pion/renovate-config" ] }