-
Notifications
You must be signed in to change notification settings - Fork 34
/
mdns.go
561 lines (474 loc) · 14.4 KB
/
mdns.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
package dnssd
import (
"context"
"fmt"
"net"
"time"
"github.com/brutella/dnssd/log"
"github.com/miekg/dns"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
var (
// IPv4LinkLocalMulticast is the IPv4 link-local multicast address.
IPv4LinkLocalMulticast = net.ParseIP("224.0.0.251")
// IPv6LinkLocalMulticast is the IPv6 link-local multicast address.
IPv6LinkLocalMulticast = net.ParseIP("ff02::fb")
// AddrIPv4LinkLocalMulticast is the IPv4 link-local multicast UDP address.
AddrIPv4LinkLocalMulticast = &net.UDPAddr{
IP: IPv4LinkLocalMulticast,
Port: 5353,
}
// AddrIPv6LinkLocalMulticast is the IPv5 link-local multicast UDP address.
AddrIPv6LinkLocalMulticast = &net.UDPAddr{
IP: IPv6LinkLocalMulticast,
Port: 5353,
}
// TTLDefault is the default time-to-live for mDNS resource records.
TTLDefault uint32 = 75 * 6
// TTLHostname is the default time-to-livefor mDNS hostname records.
TTLHostname uint32 = 120
)
// Query is a mDNS query
type Query struct {
msg *dns.Msg // The query message
iface *net.Interface // The network interface to which the message is sent
}
// IfaceName returns the name of the network interface where the request was received.
// If the network interface is unknown, the string "?" is returned.
func (q Query) IfaceName() string {
if q.iface != nil {
return q.iface.Name
}
return "?"
}
// Response is a mDNS response
type Response struct {
msg *dns.Msg // The response message
addr *net.UDPAddr // Is nil for multicast response
iface *net.Interface // The network interface to which the message is sent
}
// Request represents an incoming mDNS message
type Request struct {
msg *dns.Msg // The message
from *net.UDPAddr // The source addr of the message
iface *net.Interface // The network interface from which the message was received
}
func (r Request) String() string {
return fmt.Sprintf("%s@%s\n%v", r.from.IP, r.IfaceName(), r.msg)
}
// Raw returns the raw DNS maessage.
func (r Request) Raw() *dns.Msg {
return r.msg
}
// From returns the sender address.
func (r Request) From() *net.UDPAddr {
return r.from
}
// IfaceName returns the name of the network interface where the request was received.
// If the network interface is unknown, the string "?" is returned.
func (r Request) IfaceName() string {
if r.iface != nil {
return r.iface.Name
}
return "?"
}
// IsLegacyUnicast returns `true` if the request came from a non-5353 port and thus, the resolver is a simple resolver by https://datatracker.ietf.org/doc/html/rfc6762#section-6.7).
// For legacy unicast requests, the response needs to look like a normal unicast DNS response.
func isLegacyUnicastSource(addr *net.UDPAddr) bool {
return addr != nil && addr.Port != 5353
}
// MDNSConn represents a mDNS connection. It encapsulates an IPv4 and IPv6 UDP connection.
type MDNSConn interface {
// SendQuery sends a mDNS query.
SendQuery(q *Query) error
// SendResponse sends a mDNS response
SendResponse(resp *Response) error
// Read returns a channel which receives mDNS messages
Read(ctx context.Context) <-chan *Request
// Clears the connection buffer
Drain(ctx context.Context)
// Close closes the connection
Close()
}
type mdnsConn struct {
ipv4 *ipv4.PacketConn
ipv6 *ipv6.PacketConn
ch chan *Request
}
// NewMDNSConn returns a new mdns connection.
func NewMDNSConn() (MDNSConn, error) {
return newMDNSConn()
}
// SendQuery sends a query.
func (c *mdnsConn) SendQuery(q *Query) error {
return c.sendQuery(q.msg, q.iface)
}
// SendResponse sends a response.
// The message is sent as unicast, if an receiver address is specified in the response.
func (c *mdnsConn) SendResponse(resp *Response) error {
if resp.addr != nil {
return c.sendResponseTo(resp.msg, resp.iface, resp.addr)
}
return c.sendResponse(resp.msg, resp.iface)
}
// Read returns a channel, which receives mDNS requests.
func (c *mdnsConn) Read(ctx context.Context) <-chan *Request {
return c.read(ctx)
}
// Drain drains the incoming requests channel.
func (c *mdnsConn) Drain(ctx context.Context) {
log.Debug.Println("Draining connection")
for {
select {
case req := <-c.Read(ctx):
log.Debug.Println("Ignoring msg from", req.from.IP)
default:
return
}
}
}
// Close closes the mDNS connection.
func (c *mdnsConn) Close() {
c.close()
}
func newMDNSConn(ifs ...string) (*mdnsConn, error) {
var errs []error
var connIPv4 *ipv4.PacketConn
var connIPv6 *ipv6.PacketConn
if conn, err := net.ListenUDP("udp4", AddrIPv4LinkLocalMulticast); err != nil {
errs = append(errs, err)
} else {
connIPv4 = ipv4.NewPacketConn(conn)
if err := connIPv4.SetControlMessage(ipv4.FlagInterface, true); err != nil {
log.Debug.Printf("IPv4 interface socket opt: %v", err)
}
// Enable multicast loopback to receive all sent data
if err := connIPv4.SetMulticastLoopback(true); err != nil {
log.Debug.Println("IPv4 set multicast loopback:", err)
}
// Set TTL to 255 (rfc6762)
if err := connIPv4.SetTTL(255); err != nil {
log.Debug.Println("IPv4 set TTL:", err)
}
if err := connIPv4.SetMulticastTTL(255); err != nil {
log.Debug.Println("IPv4 set multicast TTL:", err)
}
for _, iface := range MulticastInterfaces(ifs...) {
if err := connIPv4.JoinGroup(iface, &net.UDPAddr{IP: IPv4LinkLocalMulticast}); err != nil {
log.Debug.Printf("Failed joining IPv4 %v: %v", iface.Name, err)
} else {
log.Debug.Printf("Joined IPv4 %v", iface.Name)
}
}
}
if conn, err := net.ListenUDP("udp6", AddrIPv6LinkLocalMulticast); err != nil {
errs = append(errs, err)
} else {
connIPv6 = ipv6.NewPacketConn(conn)
if err := connIPv6.SetControlMessage(ipv6.FlagInterface, true); err != nil {
log.Debug.Printf("IPv6 interface socket opt: %v", err)
}
// Enable multicast loopback to receive all sent data
if err := connIPv6.SetMulticastLoopback(true); err != nil {
log.Debug.Println("IPv6 set multicast loopback:", err)
}
// Set TTL to 255 (rfc6762)
if err := connIPv6.SetHopLimit(255); err != nil {
log.Debug.Println("IPv4 set TTL:", err)
}
if err := connIPv6.SetMulticastHopLimit(255); err != nil {
log.Debug.Println("IPv4 set multicast TTL:", err)
}
for _, iface := range MulticastInterfaces(ifs...) {
if err := connIPv6.JoinGroup(iface, &net.UDPAddr{IP: IPv6LinkLocalMulticast}); err != nil {
log.Debug.Printf("Failed joining IPv6 %v: %v", iface.Name, err)
} else {
log.Debug.Printf("Joined IPv6 %v", iface.Name)
}
}
}
if err := first(errs...); connIPv4 == nil && connIPv6 == nil {
return nil, fmt.Errorf("Failed setting up UDP server: %v", err)
}
return &mdnsConn{
ipv4: connIPv4,
ipv6: connIPv6,
ch: make(chan *Request),
}, nil
}
func (c *mdnsConn) close() {
if c.ipv4 != nil {
c.ipv4.Close()
}
if c.ipv6 != nil {
c.ipv6.Close()
}
}
func (c *mdnsConn) read(ctx context.Context) <-chan *Request {
c.readInto(ctx, c.ch)
return c.ch
}
func (c *mdnsConn) readInto(ctx context.Context, ch chan *Request) {
isDone := func(ctx context.Context) bool {
return ctx.Err() == context.Canceled
}
if c.ipv4 != nil {
go func() {
buf := make([]byte, 65536)
for {
if isDone(ctx) {
return
}
n, cm, from, err := c.ipv4.ReadFrom(buf)
if err != nil {
continue
}
udpAddr, ok := from.(*net.UDPAddr)
if !ok {
log.Info.Println("dnssd: invalid source address")
continue
}
var iface *net.Interface
if cm != nil {
iface, err = net.InterfaceByIndex(cm.IfIndex)
if err != nil {
continue
}
} else {
//On Windows, the ControlMessage for ReadFrom and WriteTo methods of PacketConn is not implemented.
//ref https://pkg.go.dev/golang.org/x/net/ipv4#pkg-note-BUG
iface, err = getInterfaceByIp(udpAddr.IP)
if err != nil {
continue
}
}
if n > 0 {
m := new(dns.Msg)
if err := m.Unpack(buf); err == nil && !shouldIgnore(m) {
ch <- &Request{m, udpAddr, iface}
}
}
}
}()
}
if c.ipv6 != nil {
go func() {
buf := make([]byte, 65536)
for {
if isDone(ctx) {
return
}
n, cm, from, err := c.ipv6.ReadFrom(buf)
if err != nil {
continue
}
udpAddr, ok := from.(*net.UDPAddr)
if !ok {
log.Info.Println("dnssd: invalid source address")
continue
}
var iface *net.Interface
if cm != nil {
iface, err = net.InterfaceByIndex(cm.IfIndex)
if err != nil {
continue
}
} else {
//On Windows, the ControlMessage for ReadFrom and WriteTo methods of PacketConn is not implemented.
//ref https://pkg.go.dev/golang.org/x/net/ipv6#pkg-note-BUG
//The zone specifies the scope of the literal IPv6 address as defined in RFC 4007.
iface, err = net.InterfaceByName(udpAddr.Zone)
if err != nil {
continue
}
}
if n > 0 {
m := new(dns.Msg)
if err := m.Unpack(buf); err == nil && !shouldIgnore(m) {
ch <- &Request{m, udpAddr, iface}
}
}
}
}()
}
}
func (c *mdnsConn) sendQuery(m *dns.Msg, iface *net.Interface) error {
sanitizeQuery(m)
return c.writeMsg(m, iface)
}
func (c *mdnsConn) sendResponse(m *dns.Msg, iface *net.Interface) error {
sanitizeResponse(m)
return c.writeMsg(m, iface)
}
func (c *mdnsConn) sendResponseTo(m *dns.Msg, iface *net.Interface, addr *net.UDPAddr) error {
// Don't sanitize legacy unicast responses.
if !isLegacyUnicastSource(addr) {
sanitizeResponse(m)
}
return c.writeMsgTo(m, iface, addr)
}
func (c *mdnsConn) writeMsg(m *dns.Msg, iface *net.Interface) error {
var err error
if c.ipv4 != nil {
err = c.writeMsgTo(m, iface, AddrIPv4LinkLocalMulticast)
}
if c.ipv6 != nil {
err = c.writeMsgTo(m, iface, AddrIPv6LinkLocalMulticast)
}
return err
}
func (c *mdnsConn) writeMsgTo(m *dns.Msg, iface *net.Interface, addr *net.UDPAddr) error {
// Don't sanitize legacy unicast responses.
if !isLegacyUnicastSource(addr) {
sanitizeMsg(m)
}
if c.ipv4 != nil && addr.IP.To4() != nil {
if out, err := m.Pack(); err == nil {
var ctrl *ipv4.ControlMessage
if iface != nil {
ctrl = &ipv4.ControlMessage{
IfIndex: iface.Index,
}
}
c.ipv4.PacketConn.SetWriteDeadline(time.Now().Add(time.Second))
if _, err = c.ipv4.WriteTo(out, ctrl, addr); err != nil {
return err
}
}
}
if c.ipv6 != nil && addr.IP.To4() == nil {
if out, err := m.Pack(); err == nil {
var ctrl *ipv6.ControlMessage
if iface != nil {
ctrl = &ipv6.ControlMessage{
IfIndex: iface.Index,
}
}
c.ipv6.PacketConn.SetWriteDeadline(time.Now().Add(time.Second))
if _, err = c.ipv6.WriteTo(out, ctrl, addr); err != nil {
return err
}
}
}
return nil
}
func shouldIgnore(m *dns.Msg) bool {
if m.Opcode != 0 {
return true
}
if m.Rcode != 0 {
return true
}
return false
}
func sanitizeResponse(m *dns.Msg) {
if m.Question != nil && len(m.Question) > 0 {
log.Info.Println("dnssd: Multicast DNS responses MUST NOT contain any questions in the Question Section. (RFC6762 6)")
m.Question = nil
}
if !m.Response {
log.Info.Println("dnssd: In response messages the QR bit MUST be one (RFC6762 18.2)")
m.Response = true
}
if !m.Authoritative {
log.Info.Println("dnssd: AA Bit bit MUST be set to one in response messages (RFC6762 18.4)")
m.Authoritative = true
}
if m.Truncated {
log.Info.Println("dnssd: In multicast response messages, the TC bit MUST be zero on transmission. (RFC6762 18.5)")
m.Truncated = false
}
}
func sanitizeQuery(m *dns.Msg) {
if m.Response {
log.Info.Println("dnssd: In query messages the QR bit MUST be zero (RFC6762 18.2)")
m.Response = false
}
if m.Authoritative {
log.Info.Println("dnssd: AA Bit MUST be zero in query messages (RFC6762 18.4)")
m.Authoritative = false
}
}
func sanitizeMsg(m *dns.Msg) {
if m.Opcode != 0 {
log.Info.Println("dnssd: In both multicast query and multicast response messages, the OPCODE MUST be zero on transmission (RFC6762 18.3)")
m.Opcode = 0
}
if m.RecursionDesired {
log.Info.Println("dnssd: In both multicast query and multicast response messages, the Recursion Available bit MUST be zero on transmission. (RFC6762 18.7)")
m.RecursionDesired = false
}
if m.Zero {
log.Info.Println("dnssd: In both query and response messages, the Zero bit MUST be zero on transmission (RFC6762 18.8)")
m.Zero = false
}
if m.AuthenticatedData {
log.Info.Println("dnssd: In both multicast query and multicast response messages, the Authentic Data bit MUST be zero on transmission (RFC6762 18.9)")
m.AuthenticatedData = false
}
if m.CheckingDisabled {
log.Info.Println("dnssd: In both multicast query and multicast response messages, the Checking Disabled bit MUST be zero on transmission (RFC6762 18.10)")
m.CheckingDisabled = false
}
if m.Rcode != 0 {
log.Info.Println("dnssd: In both multicast query and multicast response messages, the Response Code MUST be zero on transmission. (RFC6762 18.11)")
m.Rcode = 0
}
}
func first(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
}
// Sets the Top Bit of rrclass for all answer records (except PTR) to trigger a cache flush in the receivers.
func setAnswerCacheFlushBit(msg *dns.Msg) {
// From RFC6762
// The most significant bit of the rrclass for a record in the Answer
// Section of a response message is the Multicast DNS cache-flush bit
// and is discussed in more detail below in Section 10.2, "Announcements
// to Flush Outdated Cache Entries".
for _, a := range msg.Answer {
switch a.(type) {
case *dns.PTR:
continue
default:
a.Header().Class |= (1 << 15)
}
}
}
// Sets the Top Bit of class to indicate the unicast responses are preferred for this question.
func setQuestionUnicast(q *dns.Question) {
q.Qclass |= (1 << 15)
}
// Returns true if q requires unicast responses.
func isUnicastQuestion(q dns.Question) bool {
// From RFC6762
// 18.12. Repurposing of Top Bit of qclass in Question Section
//
// In the Question Section of a Multicast DNS query, the top bit of the
// qclass field is used to indicate that unicast responses are preferred
// for this particular question. (See Section 5.4.)
return q.Qclass&(1<<15) != 0
}
func getInterfaceByIp(ip net.IP) (*net.Interface, error) {
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
for _, iface := range interfaces {
// check interface running flag
if iface.Flags&net.FlagRunning != 0 {
addrs, _ := iface.Addrs()
for _, addr := range addrs {
if ipnet, ok := addr.(*net.IPNet); ok && ipnet.Contains(ip) {
return &iface, nil
}
}
}
}
return nil, fmt.Errorf("could not find interface by %v", ip)
}