Source file src/net/lookup.go

     1  // Copyright 2012 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  
     5  package net
     6  
     7  import (
     8  	"context"
     9  	"errors"
    10  	"internal/nettrace"
    11  	"internal/singleflight"
    12  	"internal/stringslite"
    13  	"net/netip"
    14  	"sync"
    15  
    16  	"golang.org/x/net/dns/dnsmessage"
    17  )
    18  
    19  // protocols contains minimal mappings between internet protocol
    20  // names and numbers for platforms that don't have a complete list of
    21  // protocol numbers.
    22  //
    23  // See https://www.iana.org/assignments/protocol-numbers
    24  //
    25  // On Unix, this map is augmented by readProtocols via lookupProtocol.
    26  var protocols = map[string]int{
    27  	"icmp":      1,
    28  	"igmp":      2,
    29  	"tcp":       6,
    30  	"udp":       17,
    31  	"ipv6-icmp": 58,
    32  }
    33  
    34  // services contains minimal mappings between services names and port
    35  // numbers for platforms that don't have a complete list of port numbers.
    36  //
    37  // See https://www.iana.org/assignments/service-names-port-numbers
    38  //
    39  // On Unix, this map is augmented by readServices via goLookupPort.
    40  var services = map[string]map[string]int{
    41  	"udp": {
    42  		"domain": 53,
    43  	},
    44  	"tcp": {
    45  		"ftp":         21,
    46  		"ftps":        990,
    47  		"gopher":      70, // ʕ◔ϖ◔ʔ
    48  		"http":        80,
    49  		"https":       443,
    50  		"imap2":       143,
    51  		"imap3":       220,
    52  		"imaps":       993,
    53  		"pop3":        110,
    54  		"pop3s":       995,
    55  		"smtp":        25,
    56  		"submissions": 465,
    57  		"ssh":         22,
    58  		"telnet":      23,
    59  	},
    60  }
    61  
    62  // dnsWaitGroup can be used by tests to wait for all DNS goroutines to
    63  // complete. This avoids races on the test hooks.
    64  var dnsWaitGroup sync.WaitGroup
    65  
    66  const maxProtoLength = len("RSVP-E2E-IGNORE") + 10 // with room to grow
    67  
    68  func lookupProtocolMap(name string) (int, error) {
    69  	var lowerProtocol [maxProtoLength]byte
    70  	n := copy(lowerProtocol[:], name)
    71  	lowerASCIIBytes(lowerProtocol[:n])
    72  	proto, found := protocols[string(lowerProtocol[:n])]
    73  	if !found || n != len(name) {
    74  		return 0, &AddrError{Err: "unknown IP protocol specified", Addr: name}
    75  	}
    76  	return proto, nil
    77  }
    78  
    79  // maxPortBufSize is the longest reasonable name of a service
    80  // (non-numeric port).
    81  // Currently the longest known IANA-unregistered name is
    82  // "mobility-header", so we use that length, plus some slop in case
    83  // something longer is added in the future.
    84  const maxPortBufSize = len("mobility-header") + 10
    85  
    86  func lookupPortMap(network, service string) (port int, error error) {
    87  	switch network {
    88  	case "ip": // no hints
    89  		if p, err := lookupPortMapWithNetwork("tcp", "ip", service); err == nil {
    90  			return p, nil
    91  		}
    92  		return lookupPortMapWithNetwork("udp", "ip", service)
    93  	case "tcp", "tcp4", "tcp6":
    94  		return lookupPortMapWithNetwork("tcp", "tcp", service)
    95  	case "udp", "udp4", "udp6":
    96  		return lookupPortMapWithNetwork("udp", "udp", service)
    97  	}
    98  	return 0, &DNSError{Err: "unknown network", Name: network + "/" + service}
    99  }
   100  
   101  func lookupPortMapWithNetwork(network, errNetwork, service string) (port int, error error) {
   102  	if m, ok := services[network]; ok {
   103  		var lowerService [maxPortBufSize]byte
   104  		n := copy(lowerService[:], service)
   105  		lowerASCIIBytes(lowerService[:n])
   106  		if port, ok := m[string(lowerService[:n])]; ok && n == len(service) {
   107  			return port, nil
   108  		}
   109  		return 0, newDNSError(errUnknownPort, errNetwork+"/"+service, "")
   110  	}
   111  	return 0, &DNSError{Err: "unknown network", Name: errNetwork + "/" + service}
   112  }
   113  
   114  // ipVersion returns the provided network's IP version: '4', '6' or 0
   115  // if network does not end in a '4' or '6' byte.
   116  func ipVersion(network string) byte {
   117  	if network == "" {
   118  		return 0
   119  	}
   120  	n := network[len(network)-1]
   121  	if n != '4' && n != '6' {
   122  		n = 0
   123  	}
   124  	return n
   125  }
   126  
   127  // DefaultResolver is the resolver used by the package-level Lookup
   128  // functions and by Dialers without a specified Resolver.
   129  var DefaultResolver = &Resolver{}
   130  
   131  // A Resolver looks up names and numbers.
   132  //
   133  // A nil *Resolver is equivalent to a zero Resolver.
   134  type Resolver struct {
   135  	// PreferGo controls whether Go's built-in DNS resolver is preferred
   136  	// on platforms where it's available. It is equivalent to setting
   137  	// GODEBUG=netdns=go, but scoped to just this resolver.
   138  	PreferGo bool
   139  
   140  	// StrictErrors controls the behavior of temporary errors
   141  	// (including timeout, socket errors, and SERVFAIL) when using
   142  	// Go's built-in resolver. For a query composed of multiple
   143  	// sub-queries (such as an A+AAAA address lookup, or walking the
   144  	// DNS search list), this option causes such errors to abort the
   145  	// whole query instead of returning a partial result. This is
   146  	// not enabled by default because it may affect compatibility
   147  	// with resolvers that process AAAA queries incorrectly.
   148  	StrictErrors bool
   149  
   150  	// Dial optionally specifies an alternate dialer for use by
   151  	// Go's built-in DNS resolver to make TCP and UDP connections
   152  	// to DNS services. The host in the address parameter will
   153  	// always be a literal IP address and not a host name, and the
   154  	// port in the address parameter will be a literal port number
   155  	// and not a service name.
   156  	// If the Conn returned is also a PacketConn, sent and received DNS
   157  	// messages must adhere to RFC 1035 section 4.2.1, "UDP usage".
   158  	// Otherwise, DNS messages transmitted over Conn must adhere
   159  	// to RFC 7766 section 5, "Transport Protocol Selection".
   160  	// If nil, the default dialer is used.
   161  	Dial func(ctx context.Context, network, address string) (Conn, error)
   162  
   163  	// lookupGroup merges LookupIPAddr calls together for lookups for the same
   164  	// host. The lookupGroup key is the LookupIPAddr.host argument.
   165  	// The return values are ([]IPAddr, error).
   166  	lookupGroup singleflight.Group
   167  
   168  	// TODO(bradfitz): optional interface impl override hook
   169  	// TODO(bradfitz): Timeout time.Duration?
   170  }
   171  
   172  func (r *Resolver) preferGo() bool     { return r != nil && r.PreferGo }
   173  func (r *Resolver) strictErrors() bool { return r != nil && r.StrictErrors }
   174  
   175  func (r *Resolver) getLookupGroup() *singleflight.Group {
   176  	if r == nil {
   177  		return &DefaultResolver.lookupGroup
   178  	}
   179  	return &r.lookupGroup
   180  }
   181  
   182  // LookupHost looks up the given host using the local resolver.
   183  // It returns a slice of that host's addresses.
   184  //
   185  // LookupHost uses [context.Background] internally; to specify the context, use
   186  // [Resolver.LookupHost].
   187  func LookupHost(host string) (addrs []string, err error) {
   188  	return DefaultResolver.LookupHost(context.Background(), host)
   189  }
   190  
   191  // LookupHost looks up the given host using the local resolver.
   192  // It returns a slice of that host's addresses.
   193  func (r *Resolver) LookupHost(ctx context.Context, host string) (addrs []string, err error) {
   194  	// Make sure that no matter what we do later, host=="" is rejected.
   195  	if host == "" {
   196  		return nil, newDNSError(errNoSuchHost, host, "")
   197  	}
   198  	if _, err := netip.ParseAddr(host); err == nil {
   199  		return []string{host}, nil
   200  	}
   201  	return r.lookupHost(ctx, host)
   202  }
   203  
   204  // LookupIP looks up host using the local resolver.
   205  // It returns a slice of that host's IPv4 and IPv6 addresses.
   206  func LookupIP(host string) ([]IP, error) {
   207  	addrs, err := DefaultResolver.LookupIPAddr(context.Background(), host)
   208  	if err != nil {
   209  		return nil, err
   210  	}
   211  	ips := make([]IP, len(addrs))
   212  	for i, ia := range addrs {
   213  		ips[i] = ia.IP
   214  	}
   215  	return ips, nil
   216  }
   217  
   218  // LookupIPAddr looks up host using the local resolver.
   219  // It returns a slice of that host's IPv4 and IPv6 addresses.
   220  func (r *Resolver) LookupIPAddr(ctx context.Context, host string) ([]IPAddr, error) {
   221  	return r.lookupIPAddr(ctx, "ip", host)
   222  }
   223  
   224  // LookupIP looks up host for the given network using the local resolver.
   225  // It returns a slice of that host's IP addresses of the type specified by
   226  // network.
   227  // network must be one of "ip", "ip4" or "ip6".
   228  func (r *Resolver) LookupIP(ctx context.Context, network, host string) ([]IP, error) {
   229  	addrs, err := r.lookupIPAddrList(ctx, network, host)
   230  	if err != nil {
   231  		return nil, err
   232  	}
   233  
   234  	ips := make([]IP, 0, len(addrs))
   235  	for _, addr := range addrs {
   236  		ips = append(ips, addr.(*IPAddr).IP)
   237  	}
   238  	return ips, nil
   239  }
   240  
   241  func (r *Resolver) lookupIPAddrList(ctx context.Context, network, host string) (addrList, error) {
   242  	afnet, _, err := parseNetwork(ctx, network, false)
   243  	if err != nil {
   244  		return nil, err
   245  	}
   246  	switch afnet {
   247  	case "ip", "ip4", "ip6":
   248  	default:
   249  		return nil, UnknownNetworkError(network)
   250  	}
   251  
   252  	if host == "" {
   253  		return nil, newDNSError(errNoSuchHost, host, "")
   254  	}
   255  	return r.internetAddrList(ctx, afnet, host)
   256  }
   257  
   258  // LookupNetIP looks up host using the local resolver.
   259  // It returns a slice of that host's IP addresses of the type specified by
   260  // network.
   261  // The network must be one of "ip", "ip4" or "ip6".
   262  func (r *Resolver) LookupNetIP(ctx context.Context, network, host string) ([]netip.Addr, error) {
   263  	// TODO(bradfitz): make this efficient, making the internal net package
   264  	// type throughout be netip.Addr and only converting to the net.IP slice
   265  	// version at the edge. But for now (2021-10-20), this is a wrapper around
   266  	// the old way.
   267  	addrs, err := r.lookupIPAddrList(ctx, network, host)
   268  	if err != nil {
   269  		return nil, err
   270  	}
   271  
   272  	ret := make([]netip.Addr, 0, len(addrs))
   273  	for _, addr := range addrs {
   274  		addr := addr.(*IPAddr)
   275  		if a, ok := netip.AddrFromSlice(addr.IP); ok {
   276  			ret = append(ret, a.WithZone(addr.Zone))
   277  		}
   278  	}
   279  	return ret, nil
   280  }
   281  
   282  // onlyValuesCtx is a context that uses an underlying context
   283  // for value lookup if the underlying context hasn't yet expired.
   284  type onlyValuesCtx struct {
   285  	context.Context
   286  	lookupValues context.Context
   287  }
   288  
   289  var _ context.Context = (*onlyValuesCtx)(nil)
   290  
   291  // Value performs a lookup if the original context hasn't expired.
   292  func (ovc *onlyValuesCtx) Value(key any) any {
   293  	select {
   294  	case <-ovc.lookupValues.Done():
   295  		return nil
   296  	default:
   297  		return ovc.lookupValues.Value(key)
   298  	}
   299  }
   300  
   301  // withUnexpiredValuesPreserved returns a context.Context that only uses lookupCtx
   302  // for its values, otherwise it is never canceled and has no deadline.
   303  // If the lookup context expires, any looked up values will return nil.
   304  // See Issue 28600.
   305  func withUnexpiredValuesPreserved(lookupCtx context.Context) context.Context {
   306  	return &onlyValuesCtx{Context: context.Background(), lookupValues: lookupCtx}
   307  }
   308  
   309  // lookupIPAddr looks up host using the local resolver and particular network.
   310  // It returns a slice of that host's IPv4 and IPv6 addresses.
   311  func (r *Resolver) lookupIPAddr(ctx context.Context, network, host string) ([]IPAddr, error) {
   312  	// Make sure that no matter what we do later, host=="" is rejected.
   313  	if host == "" {
   314  		return nil, newDNSError(errNoSuchHost, host, "")
   315  	}
   316  	if ip, err := netip.ParseAddr(host); err == nil {
   317  		return []IPAddr{{IP: IP(ip.AsSlice()).To16(), Zone: ip.Zone()}}, nil
   318  	}
   319  	trace, _ := ctx.Value(nettrace.TraceKey{}).(*nettrace.Trace)
   320  	if trace != nil && trace.DNSStart != nil {
   321  		trace.DNSStart(host)
   322  	}
   323  	// The underlying resolver func is lookupIP by default but it
   324  	// can be overridden by tests. This is needed by net/http, so it
   325  	// uses a context key instead of unexported variables.
   326  	resolverFunc := r.lookupIP
   327  	if alt, _ := ctx.Value(nettrace.LookupIPAltResolverKey{}).(func(context.Context, string, string) ([]IPAddr, error)); alt != nil {
   328  		resolverFunc = alt
   329  	}
   330  
   331  	// We don't want a cancellation of ctx to affect the
   332  	// lookupGroup operation. Otherwise if our context gets
   333  	// canceled it might cause an error to be returned to a lookup
   334  	// using a completely different context. However we need to preserve
   335  	// only the values in context. See Issue 28600.
   336  	lookupGroupCtx, lookupGroupCancel := context.WithCancel(withUnexpiredValuesPreserved(ctx))
   337  
   338  	lookupKey := network + "\000" + host
   339  	dnsWaitGroup.Add(1)
   340  	ch := r.getLookupGroup().DoChan(lookupKey, func() (any, error) {
   341  		return testHookLookupIP(lookupGroupCtx, resolverFunc, network, host)
   342  	})
   343  
   344  	dnsWaitGroupDone := func(ch <-chan singleflight.Result, cancelFn context.CancelFunc) {
   345  		<-ch
   346  		dnsWaitGroup.Done()
   347  		cancelFn()
   348  	}
   349  	select {
   350  	case <-ctx.Done():
   351  		// Our context was canceled. If we are the only
   352  		// goroutine looking up this key, then drop the key
   353  		// from the lookupGroup and cancel the lookup.
   354  		// If there are other goroutines looking up this key,
   355  		// let the lookup continue uncanceled, and let later
   356  		// lookups with the same key share the result.
   357  		// See issues 8602, 20703, 22724.
   358  		if r.getLookupGroup().ForgetUnshared(lookupKey) {
   359  			lookupGroupCancel()
   360  			go dnsWaitGroupDone(ch, func() {})
   361  		} else {
   362  			go dnsWaitGroupDone(ch, lookupGroupCancel)
   363  		}
   364  		err := newDNSError(mapErr(ctx.Err()), host, "")
   365  		if trace != nil && trace.DNSDone != nil {
   366  			trace.DNSDone(nil, false, err)
   367  		}
   368  		return nil, err
   369  	case r := <-ch:
   370  		dnsWaitGroup.Done()
   371  		lookupGroupCancel()
   372  		err := r.Err
   373  		if err != nil {
   374  			if _, ok := err.(*DNSError); !ok {
   375  				err = newDNSError(mapErr(err), host, "")
   376  			}
   377  		}
   378  		if trace != nil && trace.DNSDone != nil {
   379  			addrs, _ := r.Val.([]IPAddr)
   380  			trace.DNSDone(ipAddrsEface(addrs), r.Shared, err)
   381  		}
   382  		return lookupIPReturn(r.Val, err, r.Shared)
   383  	}
   384  }
   385  
   386  // lookupIPReturn turns the return values from singleflight.Do into
   387  // the return values from LookupIP.
   388  func lookupIPReturn(addrsi any, err error, shared bool) ([]IPAddr, error) {
   389  	if err != nil {
   390  		return nil, err
   391  	}
   392  	addrs := addrsi.([]IPAddr)
   393  	if shared {
   394  		clone := make([]IPAddr, len(addrs))
   395  		copy(clone, addrs)
   396  		addrs = clone
   397  	}
   398  	return addrs, nil
   399  }
   400  
   401  // ipAddrsEface returns an empty interface slice of addrs.
   402  func ipAddrsEface(addrs []IPAddr) []any {
   403  	s := make([]any, len(addrs))
   404  	for i, v := range addrs {
   405  		s[i] = v
   406  	}
   407  	return s
   408  }
   409  
   410  // LookupPort looks up the port for the given network and service.
   411  //
   412  // LookupPort uses [context.Background] internally; to specify the context, use
   413  // [Resolver.LookupPort].
   414  func LookupPort(network, service string) (port int, err error) {
   415  	return DefaultResolver.LookupPort(context.Background(), network, service)
   416  }
   417  
   418  // LookupPort looks up the port for the given network and service.
   419  //
   420  // The network must be one of "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6" or "ip".
   421  func (r *Resolver) LookupPort(ctx context.Context, network, service string) (port int, err error) {
   422  	port, needsLookup := parsePort(service)
   423  	if needsLookup {
   424  		switch network {
   425  		case "tcp", "tcp4", "tcp6", "udp", "udp4", "udp6", "ip":
   426  		case "": // a hint wildcard for Go 1.0 undocumented behavior
   427  			network = "ip"
   428  		default:
   429  			return 0, &AddrError{Err: "unknown network", Addr: network}
   430  		}
   431  		port, err = r.lookupPort(ctx, network, service)
   432  		if err != nil {
   433  			return 0, err
   434  		}
   435  	}
   436  	if 0 > port || port > 65535 {
   437  		return 0, &AddrError{Err: "invalid port", Addr: service}
   438  	}
   439  	return port, nil
   440  }
   441  
   442  // LookupCNAME returns the canonical name for the given host.
   443  // Callers that do not care about the canonical name can call
   444  // [LookupHost] or [LookupIP] directly; both take care of resolving
   445  // the canonical name as part of the lookup.
   446  //
   447  // A canonical name is the final name after following zero
   448  // or more CNAME records.
   449  // LookupCNAME does not return an error if host does not
   450  // contain DNS "CNAME" records, as long as host resolves to
   451  // address records.
   452  //
   453  // The returned canonical name is validated to be a properly
   454  // formatted presentation-format domain name.
   455  //
   456  // LookupCNAME uses [context.Background] internally; to specify the context, use
   457  // [Resolver.LookupCNAME].
   458  func LookupCNAME(host string) (cname string, err error) {
   459  	return DefaultResolver.LookupCNAME(context.Background(), host)
   460  }
   461  
   462  // LookupCNAME returns the canonical name for the given host.
   463  // Callers that do not care about the canonical name can call
   464  // [LookupHost] or [LookupIP] directly; both take care of resolving
   465  // the canonical name as part of the lookup.
   466  //
   467  // A canonical name is the final name after following zero
   468  // or more CNAME records.
   469  // LookupCNAME does not return an error if host does not
   470  // contain DNS "CNAME" records, as long as host resolves to
   471  // address records.
   472  //
   473  // The returned canonical name is validated to be a properly
   474  // formatted presentation-format domain name.
   475  func (r *Resolver) LookupCNAME(ctx context.Context, host string) (string, error) {
   476  	cname, err := r.lookupCNAME(ctx, host)
   477  	if err != nil {
   478  		return "", err
   479  	}
   480  	if !isDomainName(cname) {
   481  		return "", &DNSError{Err: errMalformedDNSRecordsDetail, Name: host}
   482  	}
   483  	return cname, nil
   484  }
   485  
   486  // LookupSRV tries to resolve an [SRV] query of the given service,
   487  // protocol, and domain name. The proto is "tcp" or "udp".
   488  // The returned records are sorted by priority and randomized
   489  // by weight within a priority.
   490  //
   491  // LookupSRV constructs the DNS name to look up following RFC 2782.
   492  // That is, it looks up _service._proto.name. To accommodate services
   493  // publishing SRV records under non-standard names, if both service
   494  // and proto are empty strings, LookupSRV looks up name directly.
   495  //
   496  // The returned cname is the owner name from the first SRV answer
   497  // record, which is typically the constructed DNS name
   498  // (_service._proto.name) but may differ if CNAME records redirect
   499  // the query to another name.
   500  //
   501  // The returned service names are validated to be properly
   502  // formatted presentation-format domain names. If the response contains
   503  // invalid names, those records are filtered out and an error
   504  // will be returned alongside the remaining results, if any.
   505  func LookupSRV(service, proto, name string) (cname string, addrs []*SRV, err error) {
   506  	return DefaultResolver.LookupSRV(context.Background(), service, proto, name)
   507  }
   508  
   509  // LookupSRV tries to resolve an [SRV] query of the given service,
   510  // protocol, and domain name. The proto is "tcp" or "udp".
   511  // The returned records are sorted by priority and randomized
   512  // by weight within a priority.
   513  //
   514  // LookupSRV constructs the DNS name to look up following RFC 2782.
   515  // That is, it looks up _service._proto.name. To accommodate services
   516  // publishing SRV records under non-standard names, if both service
   517  // and proto are empty strings, LookupSRV looks up name directly.
   518  //
   519  // The returned cname is the owner name from the first SRV answer
   520  // record, which is typically the constructed DNS name
   521  // (_service._proto.name) but may differ if CNAME records redirect
   522  // the query to another name.
   523  //
   524  // The returned service names are validated to be properly
   525  // formatted presentation-format domain names. If the response contains
   526  // invalid names, those records are filtered out and an error
   527  // will be returned alongside the remaining results, if any.
   528  func (r *Resolver) LookupSRV(ctx context.Context, service, proto, name string) (string, []*SRV, error) {
   529  	cname, addrs, err := r.lookupSRV(ctx, service, proto, name)
   530  	if err != nil {
   531  		return "", nil, err
   532  	}
   533  	if cname != "" && !isDomainName(cname) {
   534  		return "", nil, &DNSError{Err: "SRV header name is invalid", Name: name}
   535  	}
   536  	filteredAddrs := make([]*SRV, 0, len(addrs))
   537  	for _, addr := range addrs {
   538  		if addr == nil {
   539  			continue
   540  		}
   541  		if !isDomainName(addr.Target) {
   542  			continue
   543  		}
   544  		filteredAddrs = append(filteredAddrs, addr)
   545  	}
   546  	if len(addrs) != len(filteredAddrs) {
   547  		return cname, filteredAddrs, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name}
   548  	}
   549  	return cname, filteredAddrs, nil
   550  }
   551  
   552  // LookupMX returns the DNS MX records for the given domain name sorted by preference.
   553  //
   554  // The returned mail server names are validated to be properly
   555  // formatted presentation-format domain names, or numeric IP addresses.
   556  // If the response contains invalid names, those records are filtered out
   557  // and an error will be returned alongside the remaining results, if any.
   558  //
   559  // LookupMX uses [context.Background] internally; to specify the context, use
   560  // [Resolver.LookupMX].
   561  func LookupMX(name string) ([]*MX, error) {
   562  	return DefaultResolver.LookupMX(context.Background(), name)
   563  }
   564  
   565  // LookupMX returns the DNS MX records for the given domain name sorted by preference.
   566  //
   567  // The returned mail server names are validated to be properly
   568  // formatted presentation-format domain names, or numeric IP addresses.
   569  // If the response contains invalid names, those records are filtered out
   570  // and an error will be returned alongside the remaining results, if any.
   571  func (r *Resolver) LookupMX(ctx context.Context, name string) ([]*MX, error) {
   572  	records, err := r.lookupMX(ctx, name)
   573  	if err != nil {
   574  		return nil, err
   575  	}
   576  	filteredMX := make([]*MX, 0, len(records))
   577  	for _, mx := range records {
   578  		if mx == nil {
   579  			continue
   580  		}
   581  		if !isDomainName(mx.Host) {
   582  			// Check for IP address. In practice we observe
   583  			// these with a trailing dot, so strip that.
   584  			ip, err := netip.ParseAddr(stringslite.TrimSuffix(mx.Host, "."))
   585  			if err != nil || ip.Zone() != "" {
   586  				continue
   587  			}
   588  		}
   589  		filteredMX = append(filteredMX, mx)
   590  	}
   591  	if len(records) != len(filteredMX) {
   592  		return filteredMX, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name}
   593  	}
   594  	return filteredMX, nil
   595  }
   596  
   597  // LookupNS returns the DNS NS records for the given domain name.
   598  //
   599  // The returned name server names are validated to be properly
   600  // formatted presentation-format domain names. If the response contains
   601  // invalid names, those records are filtered out and an error
   602  // will be returned alongside the remaining results, if any.
   603  //
   604  // LookupNS uses [context.Background] internally; to specify the context, use
   605  // [Resolver.LookupNS].
   606  func LookupNS(name string) ([]*NS, error) {
   607  	return DefaultResolver.LookupNS(context.Background(), name)
   608  }
   609  
   610  // LookupNS returns the DNS NS records for the given domain name.
   611  //
   612  // The returned name server names are validated to be properly
   613  // formatted presentation-format domain names. If the response contains
   614  // invalid names, those records are filtered out and an error
   615  // will be returned alongside the remaining results, if any.
   616  func (r *Resolver) LookupNS(ctx context.Context, name string) ([]*NS, error) {
   617  	records, err := r.lookupNS(ctx, name)
   618  	if err != nil {
   619  		return nil, err
   620  	}
   621  	filteredNS := make([]*NS, 0, len(records))
   622  	for _, ns := range records {
   623  		if ns == nil {
   624  			continue
   625  		}
   626  		if !isDomainName(ns.Host) {
   627  			continue
   628  		}
   629  		filteredNS = append(filteredNS, ns)
   630  	}
   631  	if len(records) != len(filteredNS) {
   632  		return filteredNS, &DNSError{Err: errMalformedDNSRecordsDetail, Name: name}
   633  	}
   634  	return filteredNS, nil
   635  }
   636  
   637  // LookupTXT returns the DNS TXT records for the given domain name.
   638  //
   639  // If a DNS TXT record holds multiple strings, they are concatenated as a
   640  // single string.
   641  //
   642  // LookupTXT uses [context.Background] internally; to specify the context, use
   643  // [Resolver.LookupTXT].
   644  func LookupTXT(name string) ([]string, error) {
   645  	return DefaultResolver.lookupTXT(context.Background(), name)
   646  }
   647  
   648  // LookupTXT returns the DNS TXT records for the given domain name.
   649  //
   650  // If a DNS TXT record holds multiple strings, they are concatenated as a
   651  // single string.
   652  func (r *Resolver) LookupTXT(ctx context.Context, name string) ([]string, error) {
   653  	return r.lookupTXT(ctx, name)
   654  }
   655  
   656  // LookupAddr performs a reverse lookup for the given address, returning a list
   657  // of names mapping to that address.
   658  //
   659  // The returned names are validated to be properly formatted presentation-format
   660  // domain names. If the response contains invalid names, those records are filtered
   661  // out and an error will be returned alongside the remaining results, if any.
   662  //
   663  // When using the host C library resolver, at most one result will be
   664  // returned. To bypass the host resolver, use a custom [Resolver].
   665  //
   666  // LookupAddr uses [context.Background] internally; to specify the context, use
   667  // [Resolver.LookupAddr].
   668  func LookupAddr(addr string) (names []string, err error) {
   669  	return DefaultResolver.LookupAddr(context.Background(), addr)
   670  }
   671  
   672  // LookupAddr performs a reverse lookup for the given address, returning a list
   673  // of names mapping to that address.
   674  //
   675  // The returned names are validated to be properly formatted presentation-format
   676  // domain names. If the response contains invalid names, those records are filtered
   677  // out and an error will be returned alongside the remaining results, if any.
   678  func (r *Resolver) LookupAddr(ctx context.Context, addr string) ([]string, error) {
   679  	names, err := r.lookupAddr(ctx, addr)
   680  	if err != nil {
   681  		return nil, err
   682  	}
   683  	filteredNames := make([]string, 0, len(names))
   684  	for _, name := range names {
   685  		if isDomainName(name) {
   686  			filteredNames = append(filteredNames, name)
   687  		}
   688  	}
   689  	if len(names) != len(filteredNames) {
   690  		return filteredNames, &DNSError{Err: errMalformedDNSRecordsDetail, Name: addr}
   691  	}
   692  	return filteredNames, nil
   693  }
   694  
   695  // errMalformedDNSRecordsDetail is the DNSError detail which is returned when a Resolver.Lookup...
   696  // method receives DNS records which contain invalid DNS names. This may be returned alongside
   697  // results which have had the malformed records filtered out.
   698  var errMalformedDNSRecordsDetail = "DNS response contained records which contain invalid names"
   699  
   700  // dial makes a new connection to the provided server (which must be
   701  // an IP address) with the provided network type, using either r.Dial
   702  // (if both r and r.Dial are non-nil) or else Dialer.DialContext.
   703  func (r *Resolver) dial(ctx context.Context, network, server string) (Conn, error) {
   704  	// Calling Dial here is scary -- we have to be sure not to
   705  	// dial a name that will require a DNS lookup, or Dial will
   706  	// call back here to translate it. The DNS config parser has
   707  	// already checked that all the cfg.servers are IP
   708  	// addresses, which Dial will use without a DNS lookup.
   709  	var c Conn
   710  	var err error
   711  	if r != nil && r.Dial != nil {
   712  		c, err = r.Dial(ctx, network, server)
   713  	} else {
   714  		var d Dialer
   715  		c, err = d.DialContext(ctx, network, server)
   716  	}
   717  	if err != nil {
   718  		return nil, mapErr(err)
   719  	}
   720  	return c, nil
   721  }
   722  
   723  // goLookupSRV returns the SRV records for a target name, built either
   724  // from its component service ("sip"), protocol ("tcp"), and name
   725  // ("example.com."), or from name directly (if service and proto are
   726  // both empty).
   727  //
   728  // In either case, the returned target name ("_sip._tcp.example.com.")
   729  // is also returned on success.
   730  //
   731  // The records are sorted by weight.
   732  func (r *Resolver) goLookupSRV(ctx context.Context, service, proto, name string) (target string, srvs []*SRV, err error) {
   733  	if service == "" && proto == "" {
   734  		target = name
   735  	} else {
   736  		target = "_" + service + "._" + proto + "." + name
   737  	}
   738  	p, server, err := r.lookup(ctx, target, dnsmessage.TypeSRV, nil)
   739  	if err != nil {
   740  		return "", nil, err
   741  	}
   742  	var cname dnsmessage.Name
   743  	for {
   744  		h, err := p.AnswerHeader()
   745  		if err == dnsmessage.ErrSectionDone {
   746  			break
   747  		}
   748  		if err != nil {
   749  			return "", nil, &DNSError{
   750  				Err:    "cannot unmarshal DNS message",
   751  				Name:   name,
   752  				Server: server,
   753  			}
   754  		}
   755  		if h.Type != dnsmessage.TypeSRV {
   756  			if err := p.SkipAnswer(); err != nil {
   757  				return "", nil, &DNSError{
   758  					Err:    "cannot unmarshal DNS message",
   759  					Name:   name,
   760  					Server: server,
   761  				}
   762  			}
   763  			continue
   764  		}
   765  		if cname.Length == 0 && h.Name.Length != 0 {
   766  			cname = h.Name
   767  		}
   768  		srv, err := p.SRVResource()
   769  		if err != nil {
   770  			return "", nil, &DNSError{
   771  				Err:    "cannot unmarshal DNS message",
   772  				Name:   name,
   773  				Server: server,
   774  			}
   775  		}
   776  		srvs = append(srvs, &SRV{Target: srv.Target.String(), Port: srv.Port, Priority: srv.Priority, Weight: srv.Weight})
   777  	}
   778  	byPriorityWeight(srvs).sort()
   779  	return cname.String(), srvs, nil
   780  }
   781  
   782  // goLookupMX returns the MX records for name.
   783  func (r *Resolver) goLookupMX(ctx context.Context, name string) ([]*MX, error) {
   784  	p, server, err := r.lookup(ctx, name, dnsmessage.TypeMX, nil)
   785  	if err != nil {
   786  		return nil, err
   787  	}
   788  	var mxs []*MX
   789  	for {
   790  		h, err := p.AnswerHeader()
   791  		if err == dnsmessage.ErrSectionDone {
   792  			break
   793  		}
   794  		if err != nil {
   795  			return nil, &DNSError{
   796  				Err:    "cannot unmarshal DNS message",
   797  				Name:   name,
   798  				Server: server,
   799  			}
   800  		}
   801  		if h.Type != dnsmessage.TypeMX {
   802  			if err := p.SkipAnswer(); err != nil {
   803  				return nil, &DNSError{
   804  					Err:    "cannot unmarshal DNS message",
   805  					Name:   name,
   806  					Server: server,
   807  				}
   808  			}
   809  			continue
   810  		}
   811  		mx, err := p.MXResource()
   812  		if err != nil {
   813  			return nil, &DNSError{
   814  				Err:    "cannot unmarshal DNS message",
   815  				Name:   name,
   816  				Server: server,
   817  			}
   818  		}
   819  		mxs = append(mxs, &MX{Host: mx.MX.String(), Pref: mx.Pref})
   820  
   821  	}
   822  	byPref(mxs).sort()
   823  	return mxs, nil
   824  }
   825  
   826  // goLookupNS returns the NS records for name.
   827  func (r *Resolver) goLookupNS(ctx context.Context, name string) ([]*NS, error) {
   828  	p, server, err := r.lookup(ctx, name, dnsmessage.TypeNS, nil)
   829  	if err != nil {
   830  		return nil, err
   831  	}
   832  	var nss []*NS
   833  	for {
   834  		h, err := p.AnswerHeader()
   835  		if err == dnsmessage.ErrSectionDone {
   836  			break
   837  		}
   838  		if err != nil {
   839  			return nil, &DNSError{
   840  				Err:    "cannot unmarshal DNS message",
   841  				Name:   name,
   842  				Server: server,
   843  			}
   844  		}
   845  		if h.Type != dnsmessage.TypeNS {
   846  			if err := p.SkipAnswer(); err != nil {
   847  				return nil, &DNSError{
   848  					Err:    "cannot unmarshal DNS message",
   849  					Name:   name,
   850  					Server: server,
   851  				}
   852  			}
   853  			continue
   854  		}
   855  		ns, err := p.NSResource()
   856  		if err != nil {
   857  			return nil, &DNSError{
   858  				Err:    "cannot unmarshal DNS message",
   859  				Name:   name,
   860  				Server: server,
   861  			}
   862  		}
   863  		nss = append(nss, &NS{Host: ns.NS.String()})
   864  	}
   865  	return nss, nil
   866  }
   867  
   868  // goLookupTXT returns the TXT records from name.
   869  func (r *Resolver) goLookupTXT(ctx context.Context, name string) ([]string, error) {
   870  	p, server, err := r.lookup(ctx, name, dnsmessage.TypeTXT, nil)
   871  	if err != nil {
   872  		return nil, err
   873  	}
   874  	var txts []string
   875  	for {
   876  		h, err := p.AnswerHeader()
   877  		if err == dnsmessage.ErrSectionDone {
   878  			break
   879  		}
   880  		if err != nil {
   881  			return nil, &DNSError{
   882  				Err:    "cannot unmarshal DNS message",
   883  				Name:   name,
   884  				Server: server,
   885  			}
   886  		}
   887  		if h.Type != dnsmessage.TypeTXT {
   888  			if err := p.SkipAnswer(); err != nil {
   889  				return nil, &DNSError{
   890  					Err:    "cannot unmarshal DNS message",
   891  					Name:   name,
   892  					Server: server,
   893  				}
   894  			}
   895  			continue
   896  		}
   897  		txt, err := p.TXTResource()
   898  		if err != nil {
   899  			return nil, &DNSError{
   900  				Err:    "cannot unmarshal DNS message",
   901  				Name:   name,
   902  				Server: server,
   903  			}
   904  		}
   905  		// Multiple strings in one TXT record need to be
   906  		// concatenated without separator to be consistent
   907  		// with previous Go resolver.
   908  		n := 0
   909  		for _, s := range txt.TXT {
   910  			n += len(s)
   911  		}
   912  		txtJoin := make([]byte, 0, n)
   913  		for _, s := range txt.TXT {
   914  			txtJoin = append(txtJoin, s...)
   915  		}
   916  		if len(txts) == 0 {
   917  			txts = make([]string, 0, 1)
   918  		}
   919  		txts = append(txts, string(txtJoin))
   920  	}
   921  	return txts, nil
   922  }
   923  
   924  func parseCNAMEFromResources(resources []dnsmessage.Resource) (string, error) {
   925  	if len(resources) == 0 {
   926  		return "", errors.New("no CNAME record received")
   927  	}
   928  	c, ok := resources[0].Body.(*dnsmessage.CNAMEResource)
   929  	if !ok {
   930  		return "", errors.New("could not parse CNAME record")
   931  	}
   932  	return c.CNAME.String(), nil
   933  }
   934  

View as plain text