-
Notifications
You must be signed in to change notification settings - Fork 34
/
conn.go
1220 lines (1097 loc) · 35.4 KB
/
conn.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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
// SPDX-License-Identifier: MIT
package mdns
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"sync"
"time"
"github.com/pion/logging"
"golang.org/x/net/dns/dnsmessage"
"golang.org/x/net/ipv4"
"golang.org/x/net/ipv6"
)
// Conn represents a mDNS Server
type Conn struct {
mu sync.RWMutex
name string
log logging.LeveledLogger
multicastPktConnV4 ipPacketConn
multicastPktConnV6 ipPacketConn
dstAddr4 *net.UDPAddr
dstAddr6 *net.UDPAddr
unicastPktConnV4 ipPacketConn
unicastPktConnV6 ipPacketConn
queryInterval time.Duration
localNames []string
queries []*query
ifaces map[int]netInterface
closed chan interface{}
}
type query struct {
nameWithSuffix string
queryResultChan chan queryResult
}
type queryResult struct {
answer dnsmessage.ResourceHeader
addr netip.Addr
}
const (
defaultQueryInterval = time.Second
destinationAddress4 = "224.0.0.251:5353"
destinationAddress6 = "[FF02::FB]: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")
errNoPacketConn = errors.New("must supply at least a multicast IPv4 or IPv6 PacketConn")
errNoUsableInterfaces = errors.New("no usable interfaces found for mDNS")
errFailedToClose = errors.New("failed to close mDNS Conn")
)
type netInterface struct {
net.Interface
ipAddrs []netip.Addr
supportsV4 bool
supportsV6 bool
}
// Server establishes a mDNS connection over an existing conn.
// Either one or both of the multicast packet conns should be provided.
// The presence of each IP type of PacketConn will dictate what kinds
// of questions are sent for queries. That is, if an ipv6.PacketConn is
// provided, then AAAA questions will be sent. A questions will only be
// sent if an ipv4.PacketConn is also provided. In the future, we may
// add a QueryAddr method that allows specifying this more clearly.
//
//nolint:gocognit
func Server(
multicastPktConnV4 *ipv4.PacketConn,
multicastPktConnV6 *ipv6.PacketConn,
config *Config,
) (*Conn, error) {
if config == nil {
return nil, errNilConfig
}
loggerFactory := config.LoggerFactory
if loggerFactory == nil {
loggerFactory = logging.NewDefaultLoggerFactory()
}
log := loggerFactory.NewLogger("mdns")
c := &Conn{
queryInterval: defaultQueryInterval,
log: log,
closed: make(chan interface{}),
}
c.name = config.Name
if c.name == "" {
c.name = fmt.Sprintf("%p", &c)
}
if multicastPktConnV4 == nil && multicastPktConnV6 == nil {
return nil, errNoPacketConn
}
ifaces := config.Interfaces
if ifaces == nil {
var err error
ifaces, err = net.Interfaces()
if err != nil {
return nil, err
}
}
var unicastPktConnV4 *ipv4.PacketConn
{
addr4, err := net.ResolveUDPAddr("udp4", "0.0.0.0:0")
if err != nil {
return nil, err
}
unicastConnV4, err := net.ListenUDP("udp4", addr4)
if err != nil {
log.Warnf("[%s] failed to listen on unicast IPv4 %s: %s; will not be able to receive unicast responses on IPv4", c.name, addr4, err)
} else {
unicastPktConnV4 = ipv4.NewPacketConn(unicastConnV4)
}
}
var unicastPktConnV6 *ipv6.PacketConn
{
addr6, err := net.ResolveUDPAddr("udp6", "[::]:")
if err != nil {
return nil, err
}
unicastConnV6, err := net.ListenUDP("udp6", addr6)
if err != nil {
log.Warnf("[%s] failed to listen on unicast IPv6 %s: %s; will not be able to receive unicast responses on IPv6", c.name, addr6, err)
} else {
unicastPktConnV6 = ipv6.NewPacketConn(unicastConnV6)
}
}
mutlicastGroup4 := net.IPv4(224, 0, 0, 251)
multicastGroupAddr4 := &net.UDPAddr{IP: mutlicastGroup4}
// FF02::FB
mutlicastGroup6 := net.IP{0xff, 0x2, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xfb}
multicastGroupAddr6 := &net.UDPAddr{IP: mutlicastGroup6}
inboundBufferSize := 0
joinErrCount := 0
ifacesToUse := make(map[int]netInterface, len(ifaces))
for i := range ifaces {
ifc := ifaces[i]
if !config.IncludeLoopback && ifc.Flags&net.FlagLoopback == net.FlagLoopback {
continue
}
if ifc.Flags&net.FlagUp == 0 {
continue
}
addrs, err := ifc.Addrs()
if err != nil {
continue
}
var supportsV4, supportsV6 bool
ifcIPAddrs := make([]netip.Addr, 0, len(addrs))
for _, addr := range addrs {
var ipToConv net.IP
switch addr := addr.(type) {
case *net.IPNet:
ipToConv = addr.IP
case *net.IPAddr:
ipToConv = addr.IP
default:
continue
}
ipAddr, ok := netip.AddrFromSlice(ipToConv)
if !ok {
continue
}
if multicastPktConnV4 != nil {
// don't want mapping since we also support IPv4/A
ipAddr = ipAddr.Unmap()
}
ipAddr = addrWithOptionalZone(ipAddr, ifc.Name)
if ipAddr.Is6() && !ipAddr.Is4In6() {
supportsV6 = true
} else {
// we'll claim we support v4 but defer if we send it or not
// based on IPv4-to-IPv6 mapping rules later (search for Is4In6 below)
supportsV4 = true
}
ifcIPAddrs = append(ifcIPAddrs, ipAddr)
}
if !(supportsV4 || supportsV6) {
continue
}
var atLeastOneJoin bool
if supportsV4 && multicastPktConnV4 != nil {
if err := multicastPktConnV4.JoinGroup(&ifc, multicastGroupAddr4); err == nil {
atLeastOneJoin = true
}
}
if supportsV6 && multicastPktConnV6 != nil {
if err := multicastPktConnV6.JoinGroup(&ifc, multicastGroupAddr6); err == nil {
atLeastOneJoin = true
}
}
if !atLeastOneJoin {
joinErrCount++
continue
}
ifacesToUse[ifc.Index] = netInterface{
Interface: ifc,
ipAddrs: ifcIPAddrs,
supportsV4: supportsV4,
supportsV6: supportsV6,
}
if ifc.MTU > inboundBufferSize {
inboundBufferSize = ifc.MTU
}
}
if len(ifacesToUse) == 0 {
return nil, errNoUsableInterfaces
}
if inboundBufferSize == 0 {
return nil, errNoPositiveMTUFound
}
if inboundBufferSize > maxPacketSize {
inboundBufferSize = maxPacketSize
}
if joinErrCount >= len(ifaces) {
return nil, errJoiningMulticastGroup
}
dstAddr4, err := net.ResolveUDPAddr("udp4", destinationAddress4)
if err != nil {
return nil, err
}
dstAddr6, err := net.ResolveUDPAddr("udp6", destinationAddress6)
if err != nil {
return nil, err
}
var localNames []string
for _, l := range config.LocalNames {
localNames = append(localNames, l+".")
}
c.dstAddr4 = dstAddr4
c.dstAddr6 = dstAddr6
c.localNames = localNames
c.ifaces = ifacesToUse
if config.QueryInterval != 0 {
c.queryInterval = config.QueryInterval
}
if multicastPktConnV4 != nil {
if err := multicastPktConnV4.SetControlMessage(ipv4.FlagInterface, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv4.FlagInterface) on multicast IPv4 PacketConn %v", c.name, err)
}
if err := multicastPktConnV4.SetControlMessage(ipv4.FlagDst, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv4.FlagDst) on multicast IPv4 PacketConn %v", c.name, err)
}
c.multicastPktConnV4 = ipPacketConn4{c.name, multicastPktConnV4, log}
}
if multicastPktConnV6 != nil {
if err := multicastPktConnV6.SetControlMessage(ipv6.FlagInterface, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv6.FlagInterface) on multicast IPv6 PacketConn %v", c.name, err)
}
if err := multicastPktConnV6.SetControlMessage(ipv6.FlagDst, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv6.FlagInterface) on multicast IPv6 PacketConn %v", c.name, err)
}
c.multicastPktConnV6 = ipPacketConn6{c.name, multicastPktConnV6, log}
}
if unicastPktConnV4 != nil {
if err := unicastPktConnV4.SetControlMessage(ipv4.FlagInterface, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv4.FlagInterface) on unicast IPv4 PacketConn %v", c.name, err)
}
if err := unicastPktConnV4.SetControlMessage(ipv4.FlagDst, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv4.FlagInterface) on unicast IPv4 PacketConn %v", c.name, err)
}
c.unicastPktConnV4 = ipPacketConn4{c.name, unicastPktConnV4, log}
}
if unicastPktConnV6 != nil {
if err := unicastPktConnV6.SetControlMessage(ipv6.FlagInterface, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv6.FlagInterface) on unicast IPv6 PacketConn %v", c.name, err)
}
if err := unicastPktConnV6.SetControlMessage(ipv6.FlagDst, true); err != nil {
c.log.Warnf("[%s] failed to SetControlMessage(ipv6.FlagInterface) on unicast IPv6 PacketConn %v", c.name, err)
}
c.unicastPktConnV6 = ipPacketConn6{c.name, unicastPktConnV6, log}
}
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 multicastPktConnV4 != nil {
if err := multicastPktConnV4.SetMulticastLoopback(true); err != nil {
c.log.Warnf("[%s] failed to SetMulticastLoopback(true) on multicast IPv4 PacketConn %v; this may cause inefficient network path c.name,communications", c.name, err)
}
}
if multicastPktConnV6 != nil {
if err := multicastPktConnV6.SetMulticastLoopback(true); err != nil {
c.log.Warnf("[%s] failed to SetMulticastLoopback(true) on multicast IPv6 PacketConn %v; this may cause inefficient network path c.name,communications", c.name, err)
}
}
if unicastPktConnV4 != nil {
if err := unicastPktConnV4.SetMulticastLoopback(true); err != nil {
c.log.Warnf("[%s] failed to SetMulticastLoopback(true) on unicast IPv4 PacketConn %v; this may cause inefficient network path c.name,communications", c.name, err)
}
}
if unicastPktConnV6 != nil {
if err := unicastPktConnV6.SetMulticastLoopback(true); err != nil {
c.log.Warnf("[%s] failed to SetMulticastLoopback(true) on unicast IPv6 PacketConn %v; this may cause inefficient network path c.name,communications", c.name, 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).
started := make(chan struct{})
go c.start(started, inboundBufferSize-20-8, config)
<-started
return c, nil
}
// Close closes the mDNS Conn
func (c *Conn) Close() error {
select {
case <-c.closed:
return nil
default:
}
// Once on go1.20, can use errors.Join
var errs []error
if c.multicastPktConnV4 != nil {
if err := c.multicastPktConnV4.Close(); err != nil {
errs = append(errs, err)
}
}
if c.multicastPktConnV6 != nil {
if err := c.multicastPktConnV6.Close(); err != nil {
errs = append(errs, err)
}
}
if c.unicastPktConnV4 != nil {
if err := c.unicastPktConnV4.Close(); err != nil {
errs = append(errs, err)
}
}
if c.unicastPktConnV6 != nil {
if err := c.unicastPktConnV6.Close(); err != nil {
errs = append(errs, err)
}
}
if len(errs) == 0 {
<-c.closed
return nil
}
rtrn := errFailedToClose
for _, err := range errs {
rtrn = fmt.Errorf("%w\n%w", err, rtrn)
}
return rtrn
}
// Query sends mDNS Queries for the following name until
// either the Context is canceled/expires or we get a result
//
// Deprecated: Use QueryAddr instead as it supports the easier to use netip.Addr.
func (c *Conn) Query(ctx context.Context, name string) (dnsmessage.ResourceHeader, net.Addr, error) {
header, addr, err := c.QueryAddr(ctx, name)
if err != nil {
return header, nil, err
}
return header, &net.IPAddr{
IP: addr.AsSlice(),
Zone: addr.Zone(),
}, nil
}
// QueryAddr sends mDNS Queries for the following name until
// either the Context is canceled/expires or we get a result
func (c *Conn) QueryAddr(ctx context.Context, name string) (dnsmessage.ResourceHeader, netip.Addr, error) {
select {
case <-c.closed:
return dnsmessage.ResourceHeader{}, netip.Addr{}, 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{}, netip.Addr{}, 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{}, netip.Addr{}, errContextElapsed
}
}
}
type ipToBytesError struct {
addr netip.Addr
expectedType string
}
func (err ipToBytesError) Error() string {
return fmt.Sprintf("ip (%s) is not %s", err.addr, err.expectedType)
}
// assumes ipv4-to-ipv6 mapping has been checked
func ipv4ToBytes(ipAddr netip.Addr) ([4]byte, error) {
if !ipAddr.Is4() {
return [4]byte{}, ipToBytesError{ipAddr, "IPv4"}
}
md, err := ipAddr.MarshalBinary()
if err != nil {
return [4]byte{}, err
}
// net.IPs are stored in big endian / network byte order
var out [4]byte
copy(out[:], md)
return out, nil
}
// assumes ipv4-to-ipv6 mapping has been checked
func ipv6ToBytes(ipAddr netip.Addr) ([16]byte, error) {
if !ipAddr.Is6() {
return [16]byte{}, ipToBytesError{ipAddr, "IPv6"}
}
md, err := ipAddr.MarshalBinary()
if err != nil {
return [16]byte{}, err
}
// net.IPs are stored in big endian / network byte order
var out [16]byte
copy(out[:], md)
return out, nil
}
type ipToAddrError struct {
ip []byte
}
func (err ipToAddrError) Error() string {
return fmt.Sprintf("failed to convert ip address '%s' to netip.Addr", err.ip)
}
func interfaceForRemote(remote string) (*netip.Addr, 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
}
ipAddr, ok := netip.AddrFromSlice(localAddr.IP)
if !ok {
return nil, ipToAddrError{localAddr.IP}
}
ipAddr = addrWithOptionalZone(ipAddr, localAddr.Zone)
return &ipAddr, nil
}
type writeType byte
const (
writeTypeQuestion writeType = iota
writeTypeAnswer
)
func (c *Conn) sendQuestion(name string) {
packedName, err := dnsmessage.NewName(name)
if err != nil {
c.log.Warnf("[%s] failed to construct mDNS packet %v", c.name, err)
return
}
// https://datatracker.ietf.org/doc/html/draft-ietf-rtcweb-mdns-ice-candidates-04#section-3.2.1
//
// 2. Otherwise, resolve the candidate using mDNS. The ICE agent
// SHOULD set the unicast-response bit of the corresponding mDNS
// query message; this minimizes multicast traffic, as the response
// is probably only useful to the querying node.
//
// 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.)
//
// We'll follow this up sending on our unicast based packet connections so that we can
// get a unicast response back.
msg := dnsmessage.Message{
Header: dnsmessage.Header{},
}
// limit what we ask for based on what IPv is available. In the future,
// this could be an option since there's no reason you cannot get an
// A record on an IPv6 sourced question and vice versa.
if c.multicastPktConnV4 != nil {
msg.Questions = append(msg.Questions, dnsmessage.Question{
Type: dnsmessage.TypeA,
Class: dnsmessage.ClassINET | (1 << 15),
Name: packedName,
})
}
if c.multicastPktConnV6 != nil {
msg.Questions = append(msg.Questions, dnsmessage.Question{
Type: dnsmessage.TypeAAAA,
Class: dnsmessage.ClassINET | (1 << 15),
Name: packedName,
})
}
rawQuery, err := msg.Pack()
if err != nil {
c.log.Warnf("[%s] failed to construct mDNS packet %v", c.name, err)
return
}
c.writeToSocket(-1, rawQuery, false, false, writeTypeQuestion, nil)
}
//nolint:gocognit
func (c *Conn) writeToSocket(
ifIndex int,
b []byte,
hasLoopbackData bool,
hasIPv6Zone bool,
wType writeType,
unicastDst *net.UDPAddr,
) {
var dst4, dst6 net.Addr
if wType == writeTypeAnswer {
if unicastDst == nil {
dst4 = c.dstAddr4
dst6 = c.dstAddr6
} else {
if unicastDst.IP.To4() == nil {
dst6 = unicastDst
} else {
dst4 = unicastDst
}
}
}
if ifIndex != -1 {
if wType == writeTypeQuestion {
c.log.Errorf("[%s] Unexpected question using specific interface index %d; dropping question", c.name, ifIndex)
return
}
ifc, ok := c.ifaces[ifIndex]
if !ok {
c.log.Warnf("[%s] no interface for %d", c.name, ifIndex)
return
}
if hasLoopbackData && ifc.Flags&net.FlagLoopback == 0 {
// avoid accidentally tricking the destination that itself is the same as us
c.log.Debugf("[%s] interface is not loopback %d", c.name, ifIndex)
return
}
c.log.Debugf("[%s] writing answer to IPv4: %v, IPv6: %v", c.name, dst4, dst6)
if ifc.supportsV4 && c.multicastPktConnV4 != nil && dst4 != nil {
if !hasIPv6Zone {
if _, err := c.multicastPktConnV4.WriteTo(b, &ifc.Interface, nil, dst4); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet on IPv4 interface %d: %v", c.name, ifIndex, err)
}
} else {
c.log.Debugf("[%s] refusing to send mDNS packet with IPv6 zone over IPv4", c.name)
}
}
if ifc.supportsV6 && c.multicastPktConnV6 != nil && dst6 != nil {
if _, err := c.multicastPktConnV6.WriteTo(b, &ifc.Interface, nil, dst6); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet on IPv6 interface %d: %v", c.name, ifIndex, err)
}
}
return
}
for ifcIdx := range c.ifaces {
ifc := c.ifaces[ifcIdx]
if hasLoopbackData {
c.log.Debugf("[%s] Refusing to send loopback data with non-specific interface", c.name)
continue
}
if wType == writeTypeQuestion {
// we'll write via unicast if we can in case the responder chooses to respond to the address the request
// came from (i.e. not respecting unicast-response bit). If we were to use the multicast packet
// conn here, we'd be writing from a specific multicast address which won't be able to receive unicast
// traffic (it only works when listening on 0.0.0.0/[::]).
if c.unicastPktConnV4 == nil && c.unicastPktConnV6 == nil {
c.log.Debugf("[%s] writing question to multicast IPv4/6 %s", c.name, c.dstAddr4)
if ifc.supportsV4 && c.multicastPktConnV4 != nil {
if _, err := c.multicastPktConnV4.WriteTo(b, &ifc.Interface, nil, c.dstAddr4); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv4 interface %d: %v", c.name, ifc.Index, err)
}
}
if ifc.supportsV6 && c.multicastPktConnV6 != nil {
if _, err := c.multicastPktConnV6.WriteTo(b, &ifc.Interface, nil, c.dstAddr6); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv6 interface %d: %v", c.name, ifc.Index, err)
}
}
}
if ifc.supportsV4 && c.unicastPktConnV4 != nil {
c.log.Debugf("[%s] writing question to unicast IPv4 %s", c.name, c.dstAddr4)
if _, err := c.unicastPktConnV4.WriteTo(b, &ifc.Interface, nil, c.dstAddr4); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet (unicast) on interface %d: %v", c.name, ifc.Index, err)
}
}
if ifc.supportsV6 && c.unicastPktConnV6 != nil {
c.log.Debugf("[%s] writing question to unicast IPv6 %s", c.name, c.dstAddr6)
if _, err := c.unicastPktConnV6.WriteTo(b, &ifc.Interface, nil, c.dstAddr6); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet (unicast) on interface %d: %v", c.name, ifc.Index, err)
}
}
} else {
c.log.Debugf("[%s] writing answer to IPv4: %v, IPv6: %v", c.name, dst4, dst6)
if ifc.supportsV4 && c.multicastPktConnV4 != nil && dst4 != nil {
if !hasIPv6Zone {
if _, err := c.multicastPktConnV4.WriteTo(b, &ifc.Interface, nil, dst4); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv4 interface %d: %v", c.name, ifIndex, err)
}
} else {
c.log.Debugf("[%s] refusing to send mDNS packet with IPv6 zone over IPv4", c.name)
}
}
if ifc.supportsV6 && c.multicastPktConnV6 != nil && dst6 != nil {
if _, err := c.multicastPktConnV6.WriteTo(b, &ifc.Interface, nil, dst6); err != nil {
c.log.Warnf("[%s] failed to send mDNS packet (multicast) on IPv6 interface %d: %v", c.name, ifIndex, err)
}
}
}
}
}
func createAnswer(id uint16, name string, addr netip.Addr) (dnsmessage.Message, error) {
packedName, err := dnsmessage.NewName(name)
if err != nil {
return dnsmessage.Message{}, err
}
msg := dnsmessage.Message{
Header: dnsmessage.Header{
ID: id,
Response: true,
Authoritative: true,
},
Answers: []dnsmessage.Resource{
{
Header: dnsmessage.ResourceHeader{
Class: dnsmessage.ClassINET,
Name: packedName,
TTL: responseTTL,
},
},
},
}
if addr.Is4() {
ipBuf, err := ipv4ToBytes(addr)
if err != nil {
return dnsmessage.Message{}, err
}
msg.Answers[0].Header.Type = dnsmessage.TypeA
msg.Answers[0].Body = &dnsmessage.AResource{
A: ipBuf,
}
} else if addr.Is6() {
// we will lose the zone here, but the receiver can reconstruct it
ipBuf, err := ipv6ToBytes(addr)
if err != nil {
return dnsmessage.Message{}, err
}
msg.Answers[0].Header.Type = dnsmessage.TypeAAAA
msg.Answers[0].Body = &dnsmessage.AAAAResource{
AAAA: ipBuf,
}
}
return msg, nil
}
func (c *Conn) sendAnswer(queryID uint16, name string, ifIndex int, result netip.Addr, dst *net.UDPAddr) {
answer, err := createAnswer(queryID, name, result)
if err != nil {
c.log.Warnf("[%s] failed to create mDNS answer %v", c.name, err)
return
}
rawAnswer, err := answer.Pack()
if err != nil {
c.log.Warnf("[%s] failed to construct mDNS packet %v", c.name, err)
return
}
c.writeToSocket(
ifIndex,
rawAnswer,
result.IsLoopback(),
result.Is6() && result.Zone() != "",
writeTypeAnswer,
dst,
)
}
type ipControlMessage struct {
IfIndex int
Dst net.IP
}
type ipPacketConn interface {
ReadFrom(b []byte) (n int, cm *ipControlMessage, src net.Addr, err error)
WriteTo(b []byte, via *net.Interface, cm *ipControlMessage, dst net.Addr) (n int, err error)
Close() error
}
type ipPacketConn4 struct {
name string
conn *ipv4.PacketConn
log logging.LeveledLogger
}
func (c ipPacketConn4) ReadFrom(b []byte) (n int, cm *ipControlMessage, src net.Addr, err error) {
n, cm4, src, err := c.conn.ReadFrom(b)
if err != nil || cm4 == nil {
return n, nil, src, err
}
return n, &ipControlMessage{IfIndex: cm4.IfIndex, Dst: cm4.Dst}, src, err
}
func (c ipPacketConn4) WriteTo(b []byte, via *net.Interface, cm *ipControlMessage, dst net.Addr) (n int, err error) {
var cm4 *ipv4.ControlMessage
if cm != nil {
cm4 = &ipv4.ControlMessage{
IfIndex: cm.IfIndex,
}
}
if err := c.conn.SetMulticastInterface(via); err != nil {
c.log.Warnf("[%s] failed to set multicast interface for %d: %v", c.name, via.Index, err)
return 0, err
}
return c.conn.WriteTo(b, cm4, dst)
}
func (c ipPacketConn4) Close() error {
return c.conn.Close()
}
type ipPacketConn6 struct {
name string
conn *ipv6.PacketConn
log logging.LeveledLogger
}
func (c ipPacketConn6) ReadFrom(b []byte) (n int, cm *ipControlMessage, src net.Addr, err error) {
n, cm6, src, err := c.conn.ReadFrom(b)
if err != nil || cm6 == nil {
return n, nil, src, err
}
return n, &ipControlMessage{IfIndex: cm6.IfIndex, Dst: cm6.Dst}, src, err
}
func (c ipPacketConn6) WriteTo(b []byte, via *net.Interface, cm *ipControlMessage, dst net.Addr) (n int, err error) {
var cm6 *ipv6.ControlMessage
if cm != nil {
cm6 = &ipv6.ControlMessage{
IfIndex: cm.IfIndex,
}
}
if err := c.conn.SetMulticastInterface(via); err != nil {
c.log.Warnf("[%s] failed to set multicast interface for %d: %v", c.name, via.Index, err)
return 0, err
}
return c.conn.WriteTo(b, cm6, dst)
}
func (c ipPacketConn6) Close() error {
return c.conn.Close()
}
func (c *Conn) readLoop(name string, pktConn ipPacketConn, inboundBufferSize int, config *Config) { //nolint:gocognit
b := make([]byte, inboundBufferSize)
p := dnsmessage.Parser{}
for {
n, cm, src, err := pktConn.ReadFrom(b)
if err != nil {
if errors.Is(err, net.ErrClosed) {
return
}
c.log.Warnf("[%s] failed to ReadFrom %q %v", c.name, src, err)
continue
}
c.log.Debugf("[%s] got read on %s from %s", c.name, name, src)
var ifIndex int
var pktDst net.IP
if cm != nil {
ifIndex = cm.IfIndex
pktDst = cm.Dst
} else {
ifIndex = -1
}
srcAddr, ok := src.(*net.UDPAddr)
if !ok {
c.log.Warnf("[%s] expected source address %s to be UDP but got %", c.name, src, src)
continue
}
func() {
header, err := p.Start(b[:n])
if err != nil {
c.log.Warnf("[%s] failed to parse mDNS packet %v", c.name, 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("[%s] failed to parse mDNS packet %v", c.name, err)
return
}
if q.Type != dnsmessage.TypeA && q.Type != dnsmessage.TypeAAAA {
continue
}
// https://datatracker.ietf.org/doc/html/rfc6762#section-6
// The destination UDP port in all Multicast DNS responses MUST be 5353,
// and the destination address MUST be the mDNS IPv4 link-local
// multicast address 224.0.0.251 or its IPv6 equivalent FF02::FB, except
// when generating a reply to a query that explicitly requested a
// unicast response
shouldUnicastResponse := (q.Class&(1<<15)) != 0 || // via the unicast-response bit
srcAddr.Port != 5353 || // by virtue of being a legacy query (Section 6.7), or
(len(pktDst) != 0 && !(pktDst.Equal(c.dstAddr4.IP) || // by virtue of being a direct unicast query
pktDst.Equal(c.dstAddr6.IP)))
var dst *net.UDPAddr
if shouldUnicastResponse {
dst = srcAddr
}
queryWantsV4 := q.Type == dnsmessage.TypeA
for _, localName := range c.localNames {
if localName == q.Name.String() {
var localAddress *netip.Addr
if config.LocalAddress != nil {
// this means the LocalAddress does not support link-local since
// we have no zone to set here.
ipAddr, ok := netip.AddrFromSlice(config.LocalAddress)
if !ok {
c.log.Warnf("[%s] failed to convert config.LocalAddress '%s' to netip.Addr", c.name, config.LocalAddress)
continue
}
if c.multicastPktConnV4 != nil {
// don't want mapping since we also support IPv4/A
ipAddr = ipAddr.Unmap()
}
localAddress = &ipAddr
} else {
// 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 != -1 {
ifc, ok := c.ifaces[ifIndex]
if !ok {
c.log.Warnf("[%s] no interface for %d", c.name, ifIndex)
return
}
var selectedAddrs []netip.Addr
for _, addr := range ifc.ipAddrs {
addrCopy := addr
// match up respective IP types based on question
if queryWantsV4 {
if addrCopy.Is4In6() {
// we may allow 4-in-6, but the question wants an A record
addrCopy = addrCopy.Unmap()
}
if !addrCopy.Is4() {
continue
}
} else { // queryWantsV6
if !addrCopy.Is6() {
continue
}
if !isSupportedIPv6(addrCopy, c.multicastPktConnV4 == nil) {
c.log.Debugf("[%s] interface %d address not a supported IPv6 address %s", c.name, ifIndex, &addrCopy)
continue
}
}
selectedAddrs = append(selectedAddrs, addrCopy)
}
if len(selectedAddrs) == 0 {
c.log.Debugf("[%s] failed to find suitable IP for interface %d; deriving address from source address c.name,instead", c.name, ifIndex)
} else {
// choose the best match
var choice *netip.Addr
for _, option := range selectedAddrs {
optCopy := option
if option.Is4() {
// select first
choice = &optCopy
break
}
// we're okay with 4In6 for now but ideally we get a an actual IPv6.
// Maybe in the future we never want this but it does look like Docker
// can route IPv4 over IPv6.
if choice == nil {
choice = &optCopy
} else if !optCopy.Is4In6() {
choice = &optCopy