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 1c2dcde
Show file tree
Hide file tree
Showing 5 changed files with 365 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
}
219 changes: 190 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,49 @@ 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) {
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)

Check warning on line 217 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L216-L217

Added lines #L216 - L217 were not covered by tests
}

func ipv4ToBytes(ip net.IP) ([4]byte, error) {
rawIP := ip.To4()
if rawIP == nil {
return
return [4]byte{}, ipToBytesError{ip, "IPv4"}
}

ipInt := big.NewInt(0)
ipInt.SetBytes(rawIP)
copy(out[:], ipInt.Bytes())
return
// 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"}
}

Check warning on line 236 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L235-L236

Added lines #L235 - L236 were not covered by tests

// 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) {
Expand Down Expand Up @@ -242,14 +286,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 293 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L293

Added line #L293 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 +308,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 +322,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 328 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L328

Added line #L328 was not covered by tests
}

msg := dnsmessage.Message{
Expand All @@ -298,20 +341,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 352 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L351-L352

Added lines #L351 - L352 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 360 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L359-L360

Added lines #L359 - L360 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 374 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L372-L374

Added lines #L372 - L374 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 +405,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 416 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L412-L416

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

func() {
c.mu.RLock()
Expand All @@ -361,10 +440,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, netErr := net.InterfaceByIndex(ifIndex)
if netErr != nil {
c.log.Warnf("Failed to get interface for %d: %v", ifIndex, netErr)
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
}
addrs, addrsErr := ifc.Addrs()
if addrsErr != nil {
c.log.Warnf("Failed to get addresses for interface %d: %v", ifIndex, addrsErr)
continue

Check warning on line 464 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L463-L464

Added lines #L463 - L464 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 468 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L467-L468

Added lines #L467 - L468 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 480 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L476-L480

Added lines #L476 - L480 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 488 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L485-L488

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

Check warning on line 491 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L491

Added line #L491 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 497 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L497

Added line #L497 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 505 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L501-L505

Added lines #L501 - L505 were not covered by tests
}
}

c.sendAnswer(q.Name.String(), ifIndex, localAddress)
Expand Down Expand Up @@ -412,7 +551,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 +562,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 576 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L568-L576

Added lines #L568 - L576 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 583 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L579-L583

Added lines #L579 - L583 were not covered by tests
}
return true

Check warning on line 585 in conn.go

View check run for this annotation

Codecov / codecov/patch

conn.go#L585

Added line #L585 was not covered by tests
}
Loading

0 comments on commit 1c2dcde

Please sign in to comment.