1// Copyright 2022 The Go Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style
3// license that can be found in the LICENSE file.
4
5package net
6
7import (
8	"internal/syscall/windows"
9	"syscall"
10	"time"
11)
12
13func dnsReadConfig(ignoredFilename string) (conf *dnsConfig) {
14	conf = &dnsConfig{
15		ndots:    1,
16		timeout:  5 * time.Second,
17		attempts: 2,
18	}
19	defer func() {
20		if len(conf.servers) == 0 {
21			conf.servers = defaultNS
22		}
23	}()
24	aas, err := adapterAddresses()
25	if err != nil {
26		return
27	}
28
29	for _, aa := range aas {
30		// Only take interfaces whose OperStatus is IfOperStatusUp(0x01) into DNS configs.
31		if aa.OperStatus != windows.IfOperStatusUp {
32			continue
33		}
34
35		// Only take interfaces which have at least one gateway
36		if aa.FirstGatewayAddress == nil {
37			continue
38		}
39
40		for dns := aa.FirstDnsServerAddress; dns != nil; dns = dns.Next {
41			sa, err := dns.Address.Sockaddr.Sockaddr()
42			if err != nil {
43				continue
44			}
45			var ip IP
46			switch sa := sa.(type) {
47			case *syscall.SockaddrInet4:
48				ip = IPv4(sa.Addr[0], sa.Addr[1], sa.Addr[2], sa.Addr[3])
49			case *syscall.SockaddrInet6:
50				ip = make(IP, IPv6len)
51				copy(ip, sa.Addr[:])
52				if ip[0] == 0xfe && ip[1] == 0xc0 {
53					// fec0/10 IPv6 addresses are site local anycast DNS
54					// addresses Microsoft sets by default if no other
55					// IPv6 DNS address is set. Site local anycast is
56					// deprecated since 2004, see
57					// https://datatracker.ietf.org/doc/html/rfc3879
58					continue
59				}
60			default:
61				// Unexpected type.
62				continue
63			}
64			conf.servers = append(conf.servers, JoinHostPort(ip.String(), "53"))
65		}
66	}
67	return conf
68}
69