Skip to content

Commit

Permalink
Use loopback address in responses when configured
Browse files Browse the repository at this point in the history
  • Loading branch information
edaniels committed Feb 6, 2024
1 parent 1d4f9bc commit b7d104b
Show file tree
Hide file tree
Showing 5 changed files with 356 additions and 63 deletions.
6 changes: 6 additions & 0 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,10 @@ type Config struct {
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
}
210 changes: 181 additions & 29 deletions conn.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ package mdns
import (
"context"
"errors"
"math/big"
"fmt"
"net"
"sync"
"time"
Expand Down Expand Up @@ -57,22 +57,32 @@ const (

var errNoPositiveMTUFound = errors.New("no positive MTU found")

// Server establishes a mDNS connection over an existing conn
// 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, err := net.Interfaces()
if err != nil {
return nil, err
ifaces := config.Interfaces
if ifaces == nil {
var err error
ifaces, err = net.Interfaces()
if err != nil {
return nil, err
}

Check warning on line 75 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L74-L75

Added lines #L74 - L75 were not covered by tests
}

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 {
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
}
Expand Down Expand Up @@ -127,6 +137,14 @@ func Server(conn *ipv4.PacketConn, config *Config) (*Conn, error) {
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)
}

Check warning on line 145 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L144-L145

Added lines #L144 - L145 were not covered by tests
}

// 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
Expand Down Expand Up @@ -178,23 +196,40 @@ func (c *Conn) Query(ctx context.Context, name string) (dnsmessage.ResourceHeade
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
}
}
}

func ipToBytes(ip net.IP) (out [4]byte) {
func ipv4ToBytes(ip net.IP) ([4]byte, error) {
rawIP := ip.To4()
if rawIP == nil {
return
return [4]byte{}, fmt.Errorf("ip (%s) is not IPv4", ip)

Check failure on line 214 in conn.go

View workflow job for this annotation

GitHub Actions / lint / Go

err113: do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf(\"ip (%s) is not IPv4\", ip)" (goerr113)
}

ipInt := big.NewInt(0)
ipInt.SetBytes(rawIP)
copy(out[:], ipInt.Bytes())
return
// because the IP is stored as a []byte, we know its little endian
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{}, fmt.Errorf("ip (%s) is not IPv6", ip)

Check failure on line 226 in conn.go

View workflow job for this annotation

GitHub Actions / lint / Go

err113: do not define dynamic errors, use wrapped static errors instead: "fmt.Errorf(\"ip (%s) is not IPv6\", ip)" (goerr113)
}

Check warning on line 227 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L226-L227

Added lines #L226 - L227 were not covered by tests

// because the IP is stored as a []byte, we know its little endian
var out [16]byte
copy(out[:], rawIP[:])
return out, nil
}

func interfaceForRemote(remote string) (net.IP, error) {
Expand Down Expand Up @@ -242,14 +277,14 @@ func (c *Conn) sendQuestion(name string) {
c.writeToSocket(0, rawQuery, false)
}

func (c *Conn) writeToSocket(ifIndex int, b []byte, onlyLooback bool) {
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 interface for %d: %v", ifIndex, err)
c.log.Warnf("Failed to get interface for %d: %v", ifIndex, err)

Check warning on line 284 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L284

Added line #L284 was not covered by tests
return
}
if onlyLooback && ifc.Flags&net.FlagLoopback == 0 {
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
Expand All @@ -264,7 +299,7 @@ func (c *Conn) writeToSocket(ifIndex int, b []byte, onlyLooback bool) {
return
}
for ifcIdx := range c.ifaces {
if onlyLooback && c.ifaces[ifcIdx].Flags&net.FlagLoopback == 0 {
if srcIfcIsLoopback && c.ifaces[ifcIdx].Flags&net.FlagLoopback == 0 {
// avoid accidentally tricking the destination that itself is the same as us
continue
}
Expand All @@ -278,11 +313,10 @@ func (c *Conn) writeToSocket(ifIndex int, b []byte, onlyLooback bool) {
}
}

func (c *Conn) sendAnswer(name string, ifIndex int, dst net.IP) {
func createAnswer(name string, addr net.IP) (dnsmessage.Message, error) {
packedName, err := dnsmessage.NewName(name)
if err != nil {
c.log.Warnf("Failed to construct mDNS packet %v", err)
return
return dnsmessage.Message{}, err

Check warning on line 319 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L319

Added line #L319 was not covered by tests
}

msg := dnsmessage.Message{
Expand All @@ -298,20 +332,45 @@ func (c *Conn) sendAnswer(name string, ifIndex int, dst net.IP) {
Name: packedName,
TTL: responseTTL,
},
Body: &dnsmessage.AResource{
A: ipToBytes(dst),
},
},
},
}

rawAnswer, err := msg.Pack()
if ip4 := addr.To4(); ip4 != nil {
ipBuf, err := ipv4ToBytes(addr)
if err != nil {
return dnsmessage.Message{}, err
}

Check warning on line 343 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L342-L343

Added lines #L342 - L343 were not covered by tests
msg.Answers[0].Body = &dnsmessage.AResource{
A: ipBuf,
}
} else {
ipBuf, err := ipv6ToBytes(addr)
if err != nil {
return dnsmessage.Message{}, err
}

Check warning on line 351 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L350-L351

Added lines #L350 - L351 were not covered by tests
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
}

Check warning on line 365 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L363-L365

Added lines #L363 - L365 were not covered by tests

rawAnswer, err := answer.Pack()
if err != nil {
c.log.Warnf("Failed to construct mDNS packet %v", err)
return
}

c.writeToSocket(ifIndex, rawAnswer, dst.IsLoopback())
c.writeToSocket(ifIndex, rawAnswer, addr.IsLoopback())
}

func (c *Conn) start(inboundBufferSize int, config *Config) { //nolint gocognit
Expand All @@ -337,6 +396,17 @@ func (c *Conn) start(inboundBufferSize int, config *Config) { //nolint gocognit
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

Check warning on line 407 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L403-L407

Added lines #L403 - L407 were not covered by tests
}
srcIsIPv4 := srcIP.To4() != nil

func() {
c.mu.RLock()
Expand All @@ -361,10 +431,70 @@ func (c *Conn) start(inboundBufferSize int, config *Config) { //nolint gocognit
if config.LocalAddress != nil {
c.sendAnswer(q.Name.String(), ifIndex, config.LocalAddress)
} else {
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
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, err := net.InterfaceByIndex(ifIndex)

Check failure on line 447 in conn.go

View workflow job for this annotation

GitHub Actions / lint / Go

shadow: declaration of "err" shadows declaration at line 421 (govet)
if err != nil {
c.log.Warnf("Failed to get interface for %d: %v", ifIndex, err)
continue

Check warning on line 450 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L449-L450

Added lines #L449 - L450 were not covered by tests
}
addrs, err := ifc.Addrs()
if err != nil {
c.log.Warnf("Failed to get addresses for interface %d: %v", ifIndex, err)
continue

Check warning on line 455 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L454-L455

Added lines #L454 - L455 were not covered by tests
}
if len(addrs) == 0 {
c.log.Warnf("Expected more than one address for interface %d", ifIndex)
continue

Check warning on line 459 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L458-L459

Added lines #L458 - L459 were not covered by tests
}
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 for interface %d", addr, ifIndex)
continue

Check warning on line 471 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L467-L471

Added lines #L467 - L471 were not covered by tests
}

// match up respective IP types
if ipv4 := ip.To4(); ipv4 == nil {
if srcIsIPv4 {
continue
} else if !isSupportedIPv6(ip) {
continue

Check warning on line 479 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L476-L479

Added lines #L476 - L479 were not covered by tests
}
} else if !srcIsIPv4 {
continue

Check warning on line 482 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L482

Added line #L482 was not covered by tests
}
selectedIP = ip
break
}
if selectedIP == nil {
c.log.Warnf("Failed to find suitable IP for interface %d; using source address instead", ifIndex)

Check warning on line 488 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L488

Added line #L488 was not covered by tests
} 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

Check warning on line 496 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L492-L496

Added lines #L492 - L496 were not covered by tests
}
}

c.sendAnswer(q.Name.String(), ifIndex, localAddress)
Expand Down Expand Up @@ -412,7 +542,7 @@ func ipFromAnswerHeader(a dnsmessage.ResourceHeader, p dnsmessage.Parser) (ip []
if err != nil {
return nil, err
}
ip = net.IP(resource.A[:])
ip = resource.A[:]
} else {
resource, err := p.AAAAResource()
if err != nil {
Expand All @@ -423,3 +553,25 @@ func ipFromAnswerHeader(a dnsmessage.ResourceHeader, p dnsmessage.Parser) (ip []

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

Check warning on line 567 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L559-L567

Added lines #L559 - L567 were not covered by tests
}

func isZeros(ip net.IP) bool {
for i := 0; i < len(ip); i++ {
if ip[i] != 0 {
return false
}

Check warning on line 574 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L570-L574

Added lines #L570 - L574 were not covered by tests
}
return true

Check warning on line 576 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L576

Added line #L576 was not covered by tests
}
Loading

0 comments on commit b7d104b

Please sign in to comment.