// IPNSHostnameOption rewrites an incoming request if its Host: header contains
// an IPNS name.
// The rewritten request points at the resolved name on the gateway handler.
517063
func IPNSHostnameOption() ServeOption {
	return func(n *core.IpfsNode, _ net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
		childMux := http.NewServeMux()
		mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
			ctx, cancel := context.WithCancel(n.Context())
			defer cancel()

			host := strings.SplitN(r.Host, ":", 2)[0]
			if len(host) > 0 && isd.IsDomain(host) {
				name := "/ipns/" + host
				_, err := n.Namesys.Resolve(ctx, name, nsopts.Depth(1))
				if err == nil || err == namesys.ErrResolveRecursion {
					r.Header.Set("X-Ipns-Original-Path", r.URL.Path)
					r.URL.Path = name + r.URL.Path
				}
			}
			childMux.ServeHTTP(w, r)
		})
		return childMux, nil
	}
}
1056723
func PrepareNetworkConfigFromInterfaces(interfaces []network.InterfaceInfo) *PreparedConfig {
	dnsServers := set.NewStrings()
	dnsSearchDomains := set.NewStrings()
	gateway4Address := ""
	gateway6Address := ""
	namesInOrder := make([]string, 1, len(interfaces)+1)
	nameToAddress := make(map[string]string)
	nameToRoutes := make(map[string][]network.Route)
	nameToMTU := make(map[string]int)

	// Always include the loopback.
	namesInOrder[0] = "lo"
	autoStarted := set.NewStrings("lo")

	// We need to check if we have a host-provided default GW and use it.
	// Otherwise we'll use the first device with a gateway address,
	// it'll be filled in the second loop.
	for _, info := range interfaces {
		if info.IsDefaultGateway {
			switch info.GatewayAddress.Type {
			case network.IPv4Address:
				gateway4Address = info.GatewayAddress.Value
			case network.IPv6Address:
				gateway6Address = info.GatewayAddress.Value
			}
		}
	}

	for _, info := range interfaces {
		ifaceName := strings.Replace(info.MACAddress, ":", "_", -1)
		// prepend eth because .format of python wont like a tag starting with numbers.
		ifaceName = fmt.Sprintf("{eth%s}", ifaceName)

		if !info.NoAutoStart {
			autoStarted.Add(ifaceName)
		}

		if cidr := info.CIDRAddress(); cidr != "" {
			nameToAddress[ifaceName] = cidr
		} else if info.ConfigType == network.ConfigDHCP {
			nameToAddress[ifaceName] = string(network.ConfigDHCP)
		}
		nameToRoutes[ifaceName] = info.Routes

		for _, dns := range info.DNSServers {
			dnsServers.Add(dns.Value)
		}

		dnsSearchDomains = dnsSearchDomains.Union(set.NewStrings(info.DNSSearchDomains...))

		if info.GatewayAddress.Value != "" {
			switch {
			case gateway4Address == "" && info.GatewayAddress.Type == network.IPv4Address:
				gateway4Address = info.GatewayAddress.Value

			case gateway6Address == "" && info.GatewayAddress.Type == network.IPv6Address:
				gateway6Address = info.GatewayAddress.Value
			}
		}

		if info.MTU != 0 && info.MTU != 1500 {
			nameToMTU[ifaceName] = info.MTU
		}

		namesInOrder = append(namesInOrder, ifaceName)
	}

	prepared := &PreparedConfig{
		InterfaceNames:   namesInOrder,
		NameToAddress:    nameToAddress,
		NameToRoutes:     nameToRoutes,
		NameToMTU:        nameToMTU,
		AutoStarted:      autoStarted.SortedValues(),
		DNSServers:       dnsServers.SortedValues(),
		DNSSearchDomains: dnsSearchDomains.SortedValues(),
		Gateway4Address:  gateway4Address,
		Gateway6Address:  gateway6Address,
	}

	logger.Debugf("prepared network config for rendering: %+v", prepared)
	return prepared
}
1200252
func (s *FileSystem) SetDNSName(v string) *FileSystem {
	s.DNSName = &v
	return s
}
192903
func (r *IpnsResolver) resolveOnceAsync(ctx context.Context, name string, options opts.ResolveOpts) <-chan onceResult {
	out := make(chan onceResult, 1)
	log.Debugf("RoutingResolver resolving %s", name)
	cancel := func() {}

	if options.DhtTimeout != 0 {
		// Resolution must complete within the timeout
		ctx, cancel = context.WithTimeout(ctx, options.DhtTimeout)
	}

	name = strings.TrimPrefix(name, "/ipns/")
	pid, err := peer.IDB58Decode(name)
	if err != nil {
		log.Debugf("RoutingResolver: could not convert public key hash %s to peer ID: %s\n", name, err)
		out <- onceResult{err: err}
		close(out)
		cancel()
		return out
	}

	// Name should be the hash of a public key retrievable from ipfs.
	// We retrieve the public key here to make certain that it's in the peer
	// store before calling GetValue() on the DHT - the DHT will call the
	// ipns validator, which in turn will get the public key from the peer
	// store to verify the record signature
	_, err = routing.GetPublicKey(r.routing, ctx, pid)
	if err != nil {
		log.Debugf("RoutingResolver: could not retrieve public key %s: %s\n", name, err)
		out <- onceResult{err: err}
		close(out)
		cancel()
		return out
	}

	// Use the routing system to get the name.
	// Note that the DHT will call the ipns validator when retrieving
	// the value, which in turn verifies the ipns record signature
	ipnsKey := ipns.RecordKey(pid)

	vals, err := r.routing.SearchValue(ctx, ipnsKey, dht.Quorum(int(options.DhtRecordCount)))
	if err != nil {
		log.Debugf("RoutingResolver: dht get for name %s failed: %s", name, err)
		out <- onceResult{err: err}
		close(out)
		cancel()
		return out
	}

	go func() {
		defer cancel()
		defer close(out)
		for {
			select {
			case val, ok := <-vals:
				if !ok {
					return
				}

				entry := new(pb.IpnsEntry)
				err = proto.Unmarshal(val, entry)
				if err != nil {
					log.Debugf("RoutingResolver: could not unmarshal value for name %s: %s", name, err)
					emitOnceResult(ctx, out, onceResult{err: err})
					return
				}

				var p path.Path
				// check for old style record:
				if valh, err := mh.Cast(entry.GetValue()); err == nil {
					// Its an old style multihash record
					log.Debugf("encountered CIDv0 ipns entry: %s", valh)
					p = path.FromCid(cid.NewCidV0(valh))
				} else {
					// Not a multihash, probably a new style record
					p, err = path.ParsePath(string(entry.GetValue()))
					if err != nil {
						emitOnceResult(ctx, out, onceResult{err: err})
						return
					}
				}

				ttl := DefaultResolverCacheTTL
				if entry.Ttl != nil {
					ttl = time.Duration(*entry.Ttl)
				}
				switch eol, err := ipns.GetEOL(entry); err {
				case ipns.ErrUnrecognizedValidity:
					// No EOL.
				case nil:
					ttEol := time.Until(eol)
					if ttEol < 0 {
						// It *was* valid when we first resolved it.
						ttl = 0
					} else if ttEol < ttl {
						ttl = ttEol
					}
				default:
					log.Errorf("encountered error when parsing EOL: %s", err)
					emitOnceResult(ctx, out, onceResult{err: err})
					return
				}

				emitOnceResult(ctx, out, onceResult{value: p, ttl: ttl})
			case <-ctx.Done():
				return
			}
		}
	}()

	return out
}
550208
func Nameservers(nameservers ...string) Option {
	return func(c *Client) error {
		c.nameservers = nameservers
		return nil
	}
}
391003
func (edgeHostname *EdgeHostname) GetEdgeHostname(options string) error {
	if options != "" {
		options = "&options=" + options
	}

	req, err := client.NewRequest(
		Config,
		"GET",
		fmt.Sprintf(
			"/papi/v1/edgehostnames/%s?contractId=%s&groupId=%s%s",
			edgeHostname.EdgeHostnameID,
			edgeHostname.parent.ContractID,
			edgeHostname.parent.GroupID,
			options,
		),
		nil,
	)
	if err != nil {
		return err
	}

	res, err := client.Do(Config, req)
	if err != nil {
		return err
	}

	if client.IsError(res) {
		if res.StatusCode == 404 {
			// Check collection for current hostname
			contract := NewContract(NewContracts())
			contract.ContractID = edgeHostname.parent.ContractID
			group := NewGroup(NewGroups())
			group.GroupID = edgeHostname.parent.GroupID

			edgeHostname.parent.GetEdgeHostnames(contract, group, "")
			newEdgeHostname, err := edgeHostname.parent.FindEdgeHostname(edgeHostname)
			if err != nil || newEdgeHostname == nil {
				return client.NewAPIError(res)
			}

			edgeHostname.EdgeHostnameID = newEdgeHostname.EdgeHostnameID
			edgeHostname.EdgeHostnameDomain = newEdgeHostname.EdgeHostnameDomain
			edgeHostname.ProductID = newEdgeHostname.ProductID
			edgeHostname.DomainPrefix = newEdgeHostname.DomainPrefix
			edgeHostname.DomainSuffix = newEdgeHostname.DomainSuffix
			edgeHostname.Status = newEdgeHostname.Status
			edgeHostname.Secure = newEdgeHostname.Secure
			edgeHostname.IPVersionBehavior = newEdgeHostname.IPVersionBehavior
			edgeHostname.MapDetailsSerialNumber = newEdgeHostname.MapDetailsSerialNumber
			edgeHostname.MapDetailsSlotNumber = newEdgeHostname.MapDetailsSlotNumber
			edgeHostname.MapDetailsMapDomain = newEdgeHostname.MapDetailsMapDomain

			return nil
		}

		return client.NewAPIError(res)
	}

	newEdgeHostnames := NewEdgeHostnames()
	if err := client.BodyJSON(res, newEdgeHostnames); err != nil {
		return err
	}

	edgeHostname.EdgeHostnameID = newEdgeHostnames.EdgeHostnames.Items[0].EdgeHostnameID
	edgeHostname.EdgeHostnameDomain = newEdgeHostnames.EdgeHostnames.Items[0].EdgeHostnameDomain
	edgeHostname.ProductID = newEdgeHostnames.EdgeHostnames.Items[0].ProductID
	edgeHostname.DomainPrefix = newEdgeHostnames.EdgeHostnames.Items[0].DomainPrefix
	edgeHostname.DomainSuffix = newEdgeHostnames.EdgeHostnames.Items[0].DomainSuffix
	edgeHostname.Status = newEdgeHostnames.EdgeHostnames.Items[0].Status
	edgeHostname.Secure = newEdgeHostnames.EdgeHostnames.Items[0].Secure
	edgeHostname.IPVersionBehavior = newEdgeHostnames.EdgeHostnames.Items[0].IPVersionBehavior
	edgeHostname.MapDetailsSerialNumber = newEdgeHostnames.EdgeHostnames.Items[0].MapDetailsSerialNumber
	edgeHostname.MapDetailsSlotNumber = newEdgeHostnames.EdgeHostnames.Items[0].MapDetailsSlotNumber
	edgeHostname.MapDetailsMapDomain = newEdgeHostnames.EdgeHostnames.Items[0].MapDetailsMapDomain

	return nil
}
907324
func (s *ElasticLoadBalancer) SetDnsName(v string) *ElasticLoadBalancer {
	s.DnsName = &v
	return s
}
755013
func MustHostname(domain, ip string, enabled bool) *Hostname {
	hostname, err := NewHostname(domain, ip, enabled)
	if err != nil {
		panic(err)
	}
	return hostname
}
498540
func (s *LoadBalancer) SetDNSName(v string) *LoadBalancer {
	s.DNSName = &v
	return s
}
243475
func NewHostname(parent *Hostnames) *Hostname {
	hostname := &Hostname{parent: parent, CnameType: CnameTypeEdgeHostname}
	hostname.Init()

	return hostname
}
366778
func ValidateIngressName(name string, prefix bool) (bool, string) {
	return apivalidation.NameIsDNSSubdomain(name, prefix)
}
262073
func (s *HostService) GetHostByName(name string, opts ...OptionFunc) (*Host, int, error) {
	id, count, err := s.GetHostID(name, opts...)
	if err != nil {
		return nil, count, err
	}

	r, count, err := s.GetHostByID(id, opts...)
	if err != nil {
		return nil, count, err
	}
	return r, count, nil
}
873078
func (s *IspPlacement) SetIspName(v string) *IspPlacement {
	s.IspName = &v
	return s
}
786584
func WithHostname(name string) SpecOpts {
	return func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {
		s.Hostname = name
		return nil
	}
}
398323
func CheckHostnameIPMismatch(local string, hostsMap map[string][]string) ([]string, error) {
	var message string

	test := func(message string, filter func(string) bool) ([]string, error) {
		var mismatched []string

		for _, hostports := range hostsMap {
			for _, hostport := range hostports {
				if filter(hostport) {
					mismatched = append(mismatched, hostport)
				}
			}
		}

		if len(mismatched) > 0 {
			return mismatched, errors.New(message)
		}

		return nil, nil
	}

	if HostportPattern.MatchString(local) {
		message = "Your host identifier looks like an IP address and there are bootstrap " +
			"hosts that appear to be specified with hostnames. These inconsistencies may " +
			"lead to subtle node communication issues."
		return test(message, func(hostport string) bool {
			return !HostportPattern.MatchString(hostport)
		})
	}

	message = "Your host identifier looks like a hostname and there are bootstrap hosts " +
		"that appear to be specified with IP addresses. These inconsistencies may lead " +
		"to subtle node communication issues"

	return test(message, func(hostport string) bool {
		return HostportPattern.MatchString(hostport)
	})
}
790278
func (edgeHostnames *EdgeHostnames) NewEdgeHostname() *EdgeHostname {
	edgeHostname := NewEdgeHostname(edgeHostnames)
	edgeHostnames.EdgeHostnames.Items = append(edgeHostnames.EdgeHostnames.Items, edgeHostname)
	return edgeHostname
}
1207295
func Name(n string) Option {
	return func(o *Options) {
		o.Server.Init(server.Name(n))
	}
}