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

View as plain text