// dnsLookupScan tests that DNS resolution of the host returns at least one address
177490
func dnsLookupScan(addr, hostname string) (grade Grade, output Output, err error) {
	addrs, err := net.LookupHost(hostname)
	if err != nil {
		return
	}

	if len(addrs) == 0 {
		err = errors.New("no addresses found for host")
	}

	grade, output = Good, addrs
	return
}
868521
func ResolvableHostnames(addrs []Address) []Address {
	resolveableAddrs := make([]Address, 0, len(addrs))
	for _, addr := range addrs {
		if addr.Value == "localhost" || net.ParseIP(addr.Value) != nil {
			resolveableAddrs = append(resolveableAddrs, addr)
			continue
		}
		_, err := netLookupIP(addr.Value)
		if err != nil {
			logger.Infof("removing unresolvable address %q: %v", addr.Value, err)
			continue
		}
		resolveableAddrs = append(resolveableAddrs, addr)
	}
	return resolveableAddrs
}
595119
func (r Spec) Hostname() string {
	i := strings.Index(r.Locator, "/")

	if i < 0 {
		i = len(r.Locator) + 1
	}
	return r.Locator[:i]
}
474472
func (dnsClient *DNSClientImpl) LookupCAA(ctx context.Context, hostname string) ([]*dns.CAA, error) {
	dnsType := dns.TypeCAA
	r, err := dnsClient.exchangeOne(ctx, hostname, dnsType)
	if err != nil {
		return nil, &DNSError{dnsType, hostname, err, -1}
	}

	if r.Rcode == dns.RcodeServerFailure {
		return nil, &DNSError{dnsType, hostname, nil, r.Rcode}
	}

	var CAAs []*dns.CAA
	for _, answer := range r.Answer {
		if caaR, ok := answer.(*dns.CAA); ok {
			CAAs = append(CAAs, caaR)
		}
	}
	return CAAs, nil
}
62561
func (r *ClearNet) LookupHost(host string) ([]string, error) {
	return net.LookupHost(host)
}
711484
func (d *DNSServer) nodeLookup(cfg *dnsConfig, network, datacenter, node string, req, resp *dns.Msg, maxRecursionLevel int) {
	// Only handle ANY, A, AAAA, and TXT type requests
	qType := req.Question[0].Qtype
	if qType != dns.TypeANY && qType != dns.TypeA && qType != dns.TypeAAAA && qType != dns.TypeTXT {
		return
	}

	// Make an RPC request
	args := &structs.NodeSpecificRequest{
		Datacenter: datacenter,
		Node:       node,
		QueryOptions: structs.QueryOptions{
			Token:      d.agent.tokens.UserToken(),
			AllowStale: cfg.AllowStale,
		},
	}
	out, err := d.lookupNode(cfg, args)
	if err != nil {
		d.logger.Printf("[ERR] dns: rpc error: %v", err)
		resp.SetRcode(req, dns.RcodeServerFailure)
		return
	}

	// If we have no address, return not found!
	if out.NodeServices == nil {
		d.addSOA(cfg, resp)
		resp.SetRcode(req, dns.RcodeNameError)
		return
	}

	generateMeta := false
	metaInAnswer := false
	if qType == dns.TypeANY || qType == dns.TypeTXT {
		generateMeta = true
		metaInAnswer = true
	} else if cfg.NodeMetaTXT {
		generateMeta = true
	}

	// Add the node record
	n := out.NodeServices.Node
	edns := req.IsEdns0() != nil
	addr := d.agent.TranslateAddress(datacenter, n.Address, n.TaggedAddresses)
	records, meta := d.formatNodeRecord(cfg, out.NodeServices.Node, addr, req.Question[0].Name, qType, cfg.NodeTTL, edns, maxRecursionLevel, generateMeta)
	if records != nil {
		resp.Answer = append(resp.Answer, records...)
	}
	if meta != nil && metaInAnswer && generateMeta {
		resp.Answer = append(resp.Answer, meta...)
	} else if meta != nil && cfg.NodeMetaTXT {
		resp.Extra = append(resp.Extra, meta...)
	}
}
612938
func (nl *NetAddrList) Addresses() []string {
	var ns []string
	for _, n := range *nl {
		ns = append(ns, n.FullAddress())
	}
	return ns
}
1324735
func Host(host string) {
	if !hostnameRegex.MatchString(host) {
		dslengine.ReportError(`invalid hostname value "%s"`, host)
		return
	}

	if a, ok := apiDefinition(); ok {
		a.Host = host
	}
}
387186
func (d *DNSServer) lookupServiceNodes(cfg *dnsConfig, datacenter, service, tag string, connect bool, maxRecursionLevel int) (structs.IndexedCheckServiceNodes, error) {
	args := structs.ServiceSpecificRequest{
		Connect:     connect,
		Datacenter:  datacenter,
		ServiceName: service,
		ServiceTags: []string{tag},
		TagFilter:   tag != "",
		QueryOptions: structs.QueryOptions{
			Token:      d.agent.tokens.UserToken(),
			AllowStale: cfg.AllowStale,
			MaxAge:     cfg.CacheMaxAge,
		},
	}

	var out structs.IndexedCheckServiceNodes

	if cfg.UseCache {
		raw, m, err := d.agent.cache.Get(cachetype.HealthServicesName, &args)
		if err != nil {
			return out, err
		}
		reply, ok := raw.(*structs.IndexedCheckServiceNodes)
		if !ok {
			// This should never happen, but we want to protect against panics
			return out, fmt.Errorf("internal error: response type not correct")
		}
		d.logger.Printf("[TRACE] dns: cache hit: %v for service %s", m.Hit, service)

		out = *reply
	} else {
		if err := d.agent.RPC("Health.ServiceNodes", &args, &out); err != nil {
			return out, err
		}
	}

	if args.AllowStale && out.LastContact > staleCounterThreshold {
		metrics.IncrCounter([]string{"dns", "stale_queries"}, 1)
	}

	// redo the request the response was too stale
	if args.AllowStale && out.LastContact > cfg.MaxStale {
		args.AllowStale = false
		d.logger.Printf("[WARN] dns: Query results too stale, re-requesting")

		if err := d.agent.RPC("Health.ServiceNodes", &args, &out); err != nil {
			return structs.IndexedCheckServiceNodes{}, err
		}
	}

	// Filter out any service nodes due to health checks
	// We copy the slice to avoid modifying the result if it comes from the cache
	nodes := make(structs.CheckServiceNodes, len(out.Nodes))
	copy(nodes, out.Nodes)
	out.Nodes = nodes.Filter(cfg.OnlyPassing)
	return out, nil
}
1344823
func HostAddress(hostname string) (network.Address, error) {
	if ip := net.ParseIP(hostname); ip != nil {
		addr := network.Address{
			Value: ip.String(),
			Type:  network.DeriveAddressType(ip.String()),
			Scope: network.ScopePublic,
		}
		return addr, nil
	}
	// Only a resolvable hostname may be used as a public address.
	if _, err := netLookupHost(hostname); err != nil {
		return network.Address{}, err
	}
	addr := network.Address{
		Value: hostname,
		Type:  network.HostName,
		Scope: network.ScopePublic,
	}
	return addr, nil
}
896189
func (dnsClient *DNSClientImpl) LookupMX(ctx context.Context, hostname string) ([]string, error) {
	dnsType := dns.TypeMX
	r, err := dnsClient.exchangeOne(ctx, hostname, dnsType)
	if err != nil {
		return nil, &DNSError{dnsType, hostname, err, -1}
	}
	if r.Rcode != dns.RcodeSuccess {
		return nil, &DNSError{dnsType, hostname, nil, r.Rcode}
	}

	var results []string
	for _, answer := range r.Answer {
		if mx, ok := answer.(*dns.MX); ok {
			results = append(results, mx.Mx)
		}
	}

	return results, nil
}
465097
func LookupNS(host string, server string, c *dns.Client, m *dns.Msg) (addrs []string, err error) {
	m.SetQuestion(dns.Fqdn(host), dns.TypeNS)
	r, _, err := c.Exchange(m, net.JoinHostPort(server, "53"))
	if err != nil {
		return nil, err
	}

	for _, ans := range r.Answer {
		if t, ok := ans.(*dns.NS); ok {
			addrs = append(addrs, t.Ns)
		}
	}

	return
}
798671
func warnOnLocalhostDNS(hostConfig container.HostConfig, stderr io.Writer) {
	for _, dnsIP := range hostConfig.DNS {
		if isLocalhost(dnsIP) {
			fmt.Fprintf(stderr, "WARNING: Localhost DNS setting (--dns=%s) may fail in containers.\n", dnsIP)
			return
		}
	}
}
631257
func (c *DNSCache) Dump() (lookups []*cacheEntry) {
	c.RLock()
	defer c.RUnlock()

	now := time.Now()

	// Collect all the still-valid entries
	lookups = make([]*cacheEntry, 0, len(c.forward))
	for _, entries := range c.forward {
		for _, entry := range entries {
			if !entry.isExpiredBy(now) {
				lookups = append(lookups, entry)
			}
		}
	}

	// Dedup the entries. They are created once and are immutable so the address
	// is a unique identifier.
	// We iterate through the list, keeping unique pointers. This is correct
	// because the list is sorted and, if two consecutive entries are the same,
	// it is safe to overwrite the second duplicate.
	sort.Slice(lookups, func(i, j int) bool {
		return uintptr(unsafe.Pointer(lookups[i])) < uintptr(unsafe.Pointer(lookups[j]))
	})

	deduped := lookups[:0] // len==0 but cap==cap(lookups)
	for readIdx, lookup := range lookups {
		if readIdx == 0 || deduped[len(deduped)-1] != lookups[readIdx] {
			deduped = append(deduped, lookup)
		}
	}

	return deduped
}
1143413
func (p Proxy) Lookup(state request.Request, name string, typ uint16) (*dns.Msg, error) {
	req := new(dns.Msg)
	req.SetQuestion(name, typ)
	state.SizeAndDo(req)

	state2 := request.Request{W: state.W, Req: req}

	return p.lookup(state2)
}
652018
func (logTags) DNS(d *accesslog.LogRecordDNS) LogTag {
	return func(lr *LogRecord) {
		lr.DNS = d
	}
}
123176
func (s *DomainsService) GetDnssec(accountID string, domainIdentifier string) (*dnssecResponse, error) {
	path := versioned(dnssecPath(accountID, domainIdentifier))
	dnssecResponse := &dnssecResponse{}

	resp, err := s.client.get(path, dnssecResponse)
	if err != nil {
		return nil, err
	}

	dnssecResponse.HttpResponse = resp
	return dnssecResponse, nil
}