// interpolationFuncCidrSubnet implements the "cidrsubnet" function that
// adds an additional subnet of the given length onto an existing
// IP block expressed in CIDR notation.
18999
func interpolationFuncCidrSubnet() ast.Function {
	return ast.Function{
		ArgTypes: []ast.Type{
			ast.TypeString, // starting CIDR mask
			ast.TypeInt,    // number of bits to extend the prefix
			ast.TypeInt,    // network number to append to the prefix
		},
		ReturnType: ast.TypeString,
		Variadic:   false,
		Callback: func(args []interface{}) (interface{}, error) {
			extraBits := args[1].(int)
			subnetNum := args[2].(int)
			_, network, err := net.ParseCIDR(args[0].(string))
			if err != nil {
				return nil, fmt.Errorf("invalid CIDR expression: %s", err)
			}

			// For portability with 32-bit systems where the subnet number
			// will be a 32-bit int, we only allow extension of 32 bits in
			// one call even if we're running on a 64-bit machine.
			// (Of course, this is significant only for IPv6.)
			if extraBits > 32 {
				return nil, fmt.Errorf("may not extend prefix by more than 32 bits")
			}

			newNetwork, err := cidr.Subnet(network, extraBits, subnetNum)
			if err != nil {
				return nil, err
			}

			return newNetwork.String(), nil
		},
	}
}
1171459
func (cache *addSubnetsCache) cacheSubnets(ctx context.ProviderCallContext) error {
	if cache.allSubnets != nil {
		// Already cached.
		logger.Tracef("using %d cached subnets", len(cache.allSubnets))
		return nil
	}

	netEnv, err := networkingEnviron(cache.api)
	if err != nil {
		return errors.Trace(err)
	}
	subnetInfo, err := netEnv.Subnets(ctx, instance.UnknownId, nil)
	if err != nil {
		return errors.Annotate(err, "cannot get provider subnets")
	}
	logger.Tracef("got %d subnets to cache from the provider", len(subnetInfo))

	if len(subnetInfo) > 0 {
		// Trying to avoid reallocations.
		cache.allSubnets = make([]network.SubnetInfo, 0, len(subnetInfo))
	}
	cache.providerIdsByCIDR = make(map[string]set.Strings)
	cache.subnetsByProviderId = make(map[string]*network.SubnetInfo)

	for i := range subnetInfo {
		subnet := subnetInfo[i]
		cidr := subnet.CIDR
		providerId := string(subnet.ProviderId)
		logger.Tracef(
			"caching subnet with CIDR %q, ProviderId %q, Zones: %q",
			cidr, providerId, subnet.AvailabilityZones,
		)

		if providerId == "" && cidr == "" {
			logger.Warningf("found subnet with empty CIDR and ProviderId")
			// But we still save it for lookups, which will probably fail anyway.
		} else if providerId == "" {
			logger.Warningf("found subnet with CIDR %q and empty ProviderId", cidr)
			// But we still save it for lookups.
		} else {
			_, ok := cache.subnetsByProviderId[providerId]
			if ok {
				logger.Warningf(
					"found subnet with CIDR %q and duplicated ProviderId %q",
					cidr, providerId,
				)
				// We just overwrite what's there for the same id.
				// It's a weird case and it shouldn't happen with
				// properly written providers, but anyway..
			}
		}
		cache.subnetsByProviderId[providerId] = &subnet

		if ids, ok := cache.providerIdsByCIDR[cidr]; !ok {
			cache.providerIdsByCIDR[cidr] = set.NewStrings(providerId)
		} else {
			ids.Add(providerId)
			logger.Debugf(
				"duplicated subnet CIDR %q; collected ProviderIds so far: %v",
				cidr, ids.SortedValues(),
			)
			cache.providerIdsByCIDR[cidr] = ids
		}

		cache.allSubnets = append(cache.allSubnets, subnet)
	}
	logger.Tracef("%d provider subnets cached", len(cache.allSubnets))
	if len(cache.allSubnets) == 0 {
		// Cached an empty list.
		return errors.Errorf("no subnets defined")
	}
	return nil
}
36687
func interpolationFuncChomp() ast.Function {
	newlines := regexp.MustCompile(`(?:\r\n?|\n)*\z`)
	return ast.Function{
		ArgTypes:   []ast.Type{ast.TypeString},
		ReturnType: ast.TypeString,
		Callback: func(args []interface{}) (interface{}, error) {
			return newlines.ReplaceAllString(args[0].(string), ""), nil
		},
	}
}
317422
func (r Account) GetLargestAllowedSubnetCidr(numberOfHosts *int, locationId *int) (resp int, err error) {
	params := []interface{}{
		numberOfHosts,
		locationId,
	}
	err = r.Session.DoRequest("SoftLayer_Account", "getLargestAllowedSubnetCidr", params, &r.Options, &resp)
	return
}
1150910
func NewNotIPAddressFunc(key Key, IPNets ...*net.IPNet) (Function, error) {
	if key != AWSSourceIP {
		return nil, fmt.Errorf("only %v key is allowed for %v condition", AWSSourceIP, notIPAddress)
	}

	return &notIPAddressFunc{ipAddressFunc{key, IPNets}}, nil
}
784685
func NextSubnetIP(subnet *net.IPNet, ipsInUse []net.IP) (net.IP, error) {
	ones, bits := subnet.Mask.Size()
	subnetMaskUint32 := ipUint32(net.IP(subnet.Mask))

	inUse := big.NewInt(0)
	for _, ip := range ipsInUse {
		if !subnet.Contains(ip) {
			continue
		}
		index := ipIndex(ip, subnetMaskUint32)
		inUse = inUse.SetBit(inUse, index, 1)
	}

	// Now iterate through all addresses in the subnet and return the
	// first address that is not in use. We start at the first non-
	// reserved address, and stop short of the last address in the
	// subnet (i.e. all non-mask bits set), which is the broadcast
	// address for the subnet.
	n := ipUint32(subnet.IP)
	for i := reservedAddressRangeEnd + 1; i < (1<<uint64(bits-ones) - 1); i++ {
		ip := uint32IP(n + uint32(i))
		if !ip.IsGlobalUnicast() {
			continue
		}
		index := ipIndex(ip, subnetMaskUint32)
		if inUse.Bit(index) == 0 {
			return ip, nil
		}
	}
	return nil, errors.Errorf("no addresses available in %s", subnet)
}
779280
func interpolationFuncFormat() ast.Function {
	return ast.Function{
		ArgTypes:     []ast.Type{ast.TypeString},
		Variadic:     true,
		VariadicType: ast.TypeAny,
		ReturnType:   ast.TypeString,
		Callback: func(args []interface{}) (interface{}, error) {
			format := args[0].(string)
			return fmt.Sprintf(format, args[1:]...), nil
		},
	}
}
1371917
func ResolveSubnet(ctx types.Context) (string, error) {
	mac, err := getMAC(ctx)
	if err != nil {
		return "", err
	}
	return ResolveSubnetWithMAC(ctx, mac)
}
196527
func subnetsInCIDR(subnets []*compute.Subnetwork, cidr *net.IPNet) ([]*compute.Subnetwork, error) {
	var res []*compute.Subnetwork
	for _, subnet := range subnets {
		_, subnetRange, err := net.ParseCIDR(subnet.IpCidrRange)
		if err != nil {
			return nil, fmt.Errorf("unable to parse CIDR %q for subnet %q: %v", subnet.IpCidrRange, subnet.Name, err)
		}
		if containsCIDR(cidr, subnetRange) {
			res = append(res, subnet)
		}
	}
	return res, nil
}
539055
func ipv4AddrInit() {
	// Sorted for human readability
	ipv4AddrAttrs = []AttrName{
		"size", // Same position as in IPv6 for output consistency
		"broadcast",
		"uint32",
	}

	ipv4AddrAttrMap = map[AttrName]func(ipv4 IPv4Addr) string{
		"broadcast": func(ipv4 IPv4Addr) string {
			return ipv4.Broadcast().String()
		},
		"size": func(ipv4 IPv4Addr) string {
			return fmt.Sprintf("%d", 1<<uint(IPv4len*8-ipv4.Maskbits()))
		},
		"uint32": func(ipv4 IPv4Addr) string {
			return fmt.Sprintf("%d", uint32(ipv4.Address))
		},
	}
}
766797
func interpolationFuncBase64Decode() ast.Function {
	return ast.Function{
		ArgTypes:   []ast.Type{ast.TypeString},
		ReturnType: ast.TypeString,
		Callback: func(args []interface{}) (interface{}, error) {
			s := args[0].(string)
			sDec, err := base64.StdEncoding.DecodeString(s)
			if err != nil {
				return "", fmt.Errorf("failed to decode base64 data '%s'", s)
			}
			return string(sDec), nil
		},
	}
}
1102671
func (s *BrokerNodeInfo) SetClientSubnet(v string) *BrokerNodeInfo {
	s.ClientSubnet = &v
	return s
}
1023036
func interpolationFuncDistinct() ast.Function {
	return ast.Function{
		ArgTypes:     []ast.Type{ast.TypeList},
		ReturnType:   ast.TypeList,
		Variadic:     true,
		VariadicType: ast.TypeList,
		Callback: func(args []interface{}) (interface{}, error) {
			var list []string

			if len(args) != 1 {
				return nil, fmt.Errorf("accepts only one argument.")
			}

			if argument, ok := args[0].([]ast.Variable); ok {
				for _, element := range argument {
					if element.Type != ast.TypeString {
						return nil, fmt.Errorf(
							"only works for flat lists, this list contains elements of %s",
							element.Type.Printable())
					}
					list = appendIfMissing(list, element.Value.(string))
				}
			}

			return stringSliceToVariableValue(list), nil
		},
	}
}
232862
func ipAddrInit() {
	// Sorted for human readability
	ipAddrAttrs = []AttrName{
		"host",
		"address",
		"port",
		"netmask",
		"network",
		"mask_bits",
		"binary",
		"hex",
		"first_usable",
		"last_usable",
		"octets",
	}

	ipAddrAttrMap = map[AttrName]func(ip IPAddr) string{
		"address": func(ip IPAddr) string {
			return ip.NetIP().String()
		},
		"binary": func(ip IPAddr) string {
			return ip.AddressBinString()
		},
		"first_usable": func(ip IPAddr) string {
			return ip.FirstUsable().String()
		},
		"hex": func(ip IPAddr) string {
			return ip.AddressHexString()
		},
		"host": func(ip IPAddr) string {
			return ip.Host().String()
		},
		"last_usable": func(ip IPAddr) string {
			return ip.LastUsable().String()
		},
		"mask_bits": func(ip IPAddr) string {
			return fmt.Sprintf("%d", ip.Maskbits())
		},
		"netmask": func(ip IPAddr) string {
			switch v := ip.(type) {
			case IPv4Addr:
				ipv4Mask := IPv4Addr{
					Address: IPv4Address(v.Mask),
					Mask:    IPv4HostMask,
				}
				return ipv4Mask.String()
			case IPv6Addr:
				ipv6Mask := new(big.Int)
				ipv6Mask.Set(v.Mask)
				ipv6MaskAddr := IPv6Addr{
					Address: IPv6Address(ipv6Mask),
					Mask:    ipv6HostMask,
				}
				return ipv6MaskAddr.String()
			default:
				return fmt.Sprintf("<unsupported type: %T>", ip)
			}
		},
		"network": func(ip IPAddr) string {
			return ip.Network().NetIP().String()
		},
		"octets": func(ip IPAddr) string {
			octets := ip.Octets()
			octetStrs := make([]string, 0, len(octets))
			for _, octet := range octets {
				octetStrs = append(octetStrs, fmt.Sprintf("%d", octet))
			}
			return strings.Join(octetStrs, " ")
		},
		"port": func(ip IPAddr) string {
			return fmt.Sprintf("%d", ip.IPPort())
		},
	}
}
504082
func interpolationFuncMin() ast.Function {
	return ast.Function{
		ArgTypes:     []ast.Type{ast.TypeFloat},
		ReturnType:   ast.TypeFloat,
		Variadic:     true,
		VariadicType: ast.TypeFloat,
		Callback: func(args []interface{}) (interface{}, error) {
			min := args[0].(float64)

			for i := 1; i < len(args); i++ {
				min = math.Min(min, args[i].(float64))
			}

			return min, nil
		},
	}
}
598948
func ConnDuplicateIPFilter() ConnFilterFunc {
	return func(cs ConnSet, c net.Conn, ips []net.IP) error {
		for _, ip := range ips {
			if cs.HasIP(ip) {
				return ErrRejected{
					conn:        c,
					err:         fmt.Errorf("IP<%v> already connected", ip),
					isDuplicate: true,
				}
			}
		}

		return nil
	}
}
71741
func interpolationFuncAbs() ast.Function {
	return ast.Function{
		ArgTypes:   []ast.Type{ast.TypeFloat},
		ReturnType: ast.TypeFloat,
		Callback: func(args []interface{}) (interface{}, error) {
			return math.Abs(args[0].(float64)), nil
		},
	}
}