// Marks all CIDRs with subNetMaskSize that belongs to serviceCIDR as used,
// so that they won't be assignable.
160087
func (r *rangeAllocator) filterOutServiceRange(serviceCIDR *net.IPNet) {
	// Checks if service CIDR has a nonempty intersection with cluster
	// CIDR. It is the case if either clusterCIDR contains serviceCIDR with
	// clusterCIDR's Mask applied (this means that clusterCIDR contains
	// serviceCIDR) or vice versa (which means that serviceCIDR contains
	// clusterCIDR).
	if !r.clusterCIDR.Contains(serviceCIDR.IP.Mask(r.clusterCIDR.Mask)) && !serviceCIDR.Contains(r.clusterCIDR.IP.Mask(serviceCIDR.Mask)) {
		return
	}

	if err := r.cidrs.Occupy(serviceCIDR); err != nil {
		klog.Errorf("Error filtering out service cidr %v: %v", serviceCIDR, err)
	}
}
564790
func (i *InterfaceInfo) CIDRAddress() string {
	if i.CIDR == "" || i.Address.Value == "" {
		return ""
	}
	_, ipNet, err := net.ParseCIDR(i.CIDR)
	if err != nil {
		return errors.Trace(err).Error()
	}
	ip := net.ParseIP(i.Address.Value)
	if ip == nil {
		return errors.Errorf("cannot parse IP address %q", i.Address.Value).Error()
	}
	ipNet.IP = ip
	return ipNet.String()
}
499792
func (api *API) AddSubnet(subnet names.SubnetTag, providerId network.Id, space names.SpaceTag, zones []string) error {
	var response params.ErrorResults
	// Prefer ProviderId when set over CIDR.
	subnetTag := subnet.String()
	if providerId != "" {
		subnetTag = ""
	}

	params := params.AddSubnetsParams{
		Subnets: []params.AddSubnetParams{{
			SubnetTag:        subnetTag,
			SubnetProviderId: string(providerId),
			SpaceTag:         space.String(),
			Zones:            zones,
		}},
	}
	err := api.facade.FacadeCall("AddSubnets", params, &response)
	if err != nil {
		return errors.Trace(err)
	}
	return response.OneError()
}
971319
func rangeToCIDRs(firstIP, lastIP net.IP) []*net.IPNet {

	// First, create a CIDR that spans both IPs.
	spanningCIDR := createSpanningCIDR(netWithRange{&firstIP, &lastIP, nil})
	spanningRange := ipNetToRange(spanningCIDR)
	firstIPSpanning := spanningRange.First
	lastIPSpanning := spanningRange.Last

	cidrList := []*net.IPNet{}

	// If the first IP of the spanning CIDR passes the lower bound (firstIP),
	// we need to split the spanning CIDR and only take the IPs that are
	// greater than the value which we split on, as we do not want the lesser
	// values since they are less than the lower-bound (firstIP).
	if bytes.Compare(*firstIPSpanning, firstIP) < 0 {
		// Split on the previous IP of the first IP so that the right list of IPs
		// of the partition includes the firstIP.
		prevFirstRangeIP := getPreviousIP(firstIP)
		var bitLen int
		if prevFirstRangeIP.To4() != nil {
			bitLen = ipv4BitLen
		} else {
			bitLen = ipv6BitLen
		}
		_, _, right := partitionCIDR(spanningCIDR, net.IPNet{IP: prevFirstRangeIP, Mask: net.CIDRMask(bitLen, bitLen)})

		// Append all CIDRs but the first, as this CIDR includes the upper
		// bound of the spanning CIDR, which we still need to partition on.
		cidrList = append(cidrList, right...)
		spanningCIDR = *right[0]
		cidrList = cidrList[1:]
	}

	// Conversely, if the last IP of the spanning CIDR passes the upper bound
	// (lastIP), we need to split the spanning CIDR and only take the IPs that
	// are greater than the value which we split on, as we do not want the greater
	// values since they are greater than the upper-bound (lastIP).
	if bytes.Compare(*lastIPSpanning, lastIP) > 0 {
		// Split on the next IP of the last IP so that the left list of IPs
		// of the partition include the lastIP.
		nextFirstRangeIP := GetNextIP(lastIP)
		var bitLen int
		if nextFirstRangeIP.To4() != nil {
			bitLen = ipv4BitLen
		} else {
			bitLen = ipv6BitLen
		}
		left, _, _ := partitionCIDR(spanningCIDR, net.IPNet{IP: nextFirstRangeIP, Mask: net.CIDRMask(bitLen, bitLen)})
		cidrList = append(cidrList, left...)
	} else {
		// Otherwise, there is no need to partition; just use add the spanning
		// CIDR to the list of networks.
		cidrList = append(cidrList, &spanningCIDR)
	}
	return cidrList
}
844184
func GetPrefixesFromCIDRSet(rules api.CIDRRuleSlice) []*net.IPNet {
	cidrs := api.ComputeResultantCIDRSet(rules)
	return getPrefixesFromCIDR(cidrs)
}
851095
func CIDR(ipBlock, count, cidrBits interface{}) string {
	return encode(fmt.Sprintf(`{ "Fn::Cidr" : [ "%v", "%v", "%v" ] }`, ipBlock, count, cidrBits))
}
734062
func ParseCIDR(s string) (*CIDR, error) {
	_, net, err := net.ParseCIDR(s)
	if err != nil {
		return nil, err
	}
	return &CIDR{*net}, nil
}
1348311
func (st *State) AllSubnets() (subnets []*Subnet, err error) {
	subnetsCollection, closer := st.db().GetCollection(subnetsC)
	defer closer()

	docs := []subnetDoc{}
	err = subnetsCollection.Find(nil).All(&docs)
	if err != nil {
		return nil, errors.Annotatef(err, "cannot get all subnets")
	}
	cidrToSpace := make(map[string]string)
	for _, doc := range docs {
		cidrToSpace[doc.CIDR] = doc.SpaceName
	}
	for _, doc := range docs {
		spaceName := doc.SpaceName
		if doc.FanLocalUnderlay != "" {
			if space, ok := cidrToSpace[doc.FanLocalUnderlay]; ok {
				spaceName = space
			}
		}
		subnets = append(subnets, &Subnet{st, doc, spaceName})
	}
	return subnets, nil
}
709002
func (group *ToGroups) GetCidrSet() ([]CIDRRule, error) {

	var ips []net.IP
	// Get per  provider CIDRSet
	if group.AWS != nil {
		callbackInterface, ok := providers.Load(AWSProvider)
		if !ok {
			return nil, fmt.Errorf("Provider %s is not registered", AWSProvider)
		}
		callback, ok := callbackInterface.(GroupProviderFunc)
		if !ok {
			return nil, fmt.Errorf("Provider callback for %s is not a valid instance", AWSProvider)
		}
		awsIPs, err := callback(group)
		if err != nil {
			return nil, fmt.Errorf(
				"Cannot retrieve data from %s provider: %s",
				AWSProvider, err)
		}
		ips = append(ips, awsIPs...)
	}

	resultIps := ip.KeepUniqueIPs(ips)
	return IPsToCIDRRules(resultIps), nil
}
283873
func (c *DNSCache) cleanupOverLimitEntries() []string {
	type IPEntry struct {
		ip    string
		entry *cacheEntry
	}
	affectedNames := []string{}

	// For global cache the limit maybe is not used at all.
	if c.perHostLimit == 0 {
		return affectedNames
	}

	for dnsName := range c.overLimit {
		entries, ok := c.forward[dnsName]
		if !ok {
			continue
		}
		overlimit := len(entries) - c.perHostLimit
		if overlimit <= 0 {
			continue
		}
		sortedEntries := []IPEntry{}
		for ip, entry := range entries {
			sortedEntries = append(sortedEntries, IPEntry{ip, entry})
		}

		sort.Slice(sortedEntries, func(i, j int) bool {
			return sortedEntries[i].entry.ExpirationTime.Before(sortedEntries[j].entry.ExpirationTime)
		})

		for i := 0; i < overlimit; i++ {
			key := sortedEntries[i]
			delete(entries, key.ip)
			c.removeReverse(key.ip, key.entry)
		}
		affectedNames = append(affectedNames, dnsName)
	}
	c.overLimit = map[string]bool{}
	return affectedNames
}
836669
func getPrefixesFromCIDR(cidrs api.CIDRSlice) []*net.IPNet {
	result, _ := ip.ParseCIDRs(cidrs.StringSlice())
	return result
}
878658
func MustParseCIDR(s string) *CIDR {
	cidr, err := ParseCIDR(s)
	if err != nil {
		panic(err)
	}

	return cidr
}
1015694
func CidrHost(prefix, hostnum cty.Value) (cty.Value, error) {
	return CidrHostFunc.Call([]cty.Value{prefix, hostnum})
}
860149
func (e *environ) Subnets(ctx context.ProviderCallContext, instId instance.Id, subnetIds []network.Id) ([]network.SubnetInfo, error) {
	var results []network.SubnetInfo
	subIdSet := make(map[string]bool)
	for _, subId := range subnetIds {
		subIdSet[string(subId)] = false
	}

	if instId != instance.UnknownId {
		interfaces, err := e.NetworkInterfaces(ctx, instId)
		if err != nil {
			return results, errors.Trace(err)
		}
		if len(subnetIds) == 0 {
			for _, iface := range interfaces {
				subIdSet[string(iface.ProviderSubnetId)] = false
			}
		}
		for _, iface := range interfaces {
			_, ok := subIdSet[string(iface.ProviderSubnetId)]
			if !ok {
				logger.Tracef("subnet %q not in %v, skipping", iface.ProviderSubnetId, subnetIds)
				continue
			}
			subIdSet[string(iface.ProviderSubnetId)] = true
			info, err := makeSubnetInfo(iface.CIDR, iface.ProviderSubnetId, iface.ProviderNetworkId, iface.AvailabilityZones)
			if err != nil {
				// Error will already have been logged.
				continue
			}
			results = append(results, info)
		}
	} else {
		resp, _, err := e.subnetsForVPC(ctx)
		if err != nil {
			return nil, errors.Annotatef(err, "failed to retrieve subnets")
		}
		if len(subnetIds) == 0 {
			for _, subnet := range resp.Subnets {
				subIdSet[subnet.Id] = false
			}
		}

		for _, subnet := range resp.Subnets {
			_, ok := subIdSet[subnet.Id]
			if !ok {
				logger.Tracef("subnet %q not in %v, skipping", subnet.Id, subnetIds)
				continue
			}
			subIdSet[subnet.Id] = true
			cidr := subnet.CIDRBlock
			info, err := makeSubnetInfo(cidr, network.Id(subnet.Id), network.Id(subnet.VPCId), []string{subnet.AvailZone})
			if err != nil {
				// Error will already have been logged.
				continue
			}
			results = append(results, info)

		}
	}

	notFound := []string{}
	for subId, found := range subIdSet {
		if !found {
			notFound = append(notFound, subId)
		}
	}
	if len(notFound) != 0 {
		return nil, errors.Errorf("failed to find the following subnet ids: %v", notFound)
	}

	return results, nil
}
1320162
func FormatAsCIDR(addresses []string) ([]string, error) {
	result := make([]string, len(addresses))
	for i, a := range addresses {
		cidr := a
		// If address is not already a cidr, add a /32 (ipv4) or /128 (ipv6).
		if _, _, err := net.ParseCIDR(a); err != nil {
			address, err := ResolverFunc("ip", a)
			if err != nil {
				return nil, errors.Trace(err)
			}
			if address.IP.To4() != nil {
				cidr = address.String() + "/32"
			} else {
				cidr = address.String() + "/128"
			}
		}
		result[i] = cidr
	}
	return result, nil
}
162451
func validateCIDRBlock(cidr string) error {
	_, ipnet, err := net.ParseCIDR(cidr)
	if err != nil {
		return err
	}
	if ipnet.String() != cidr {
		return fmt.Errorf("%s is not a valid mask; did you mean %s?", cidr, ipnet)
	}

	return nil
}
631487
func (cm *CIDRMap) CIDRExists(cidr net.IPNet) bool {
	key := cm.cidrKeyInit(cidr)
	var entry [LPM_MAP_VALUE_SIZE]byte
	return bpf.LookupElement(cm.Fd, unsafe.Pointer(&key), unsafe.Pointer(&entry)) == nil
}