// Reference: zebra_read_ipv4 function in bgpd/bgp_zebra.c of Quagga1.2.x (ZAPI3)
// Reference: zebra_read_ipv4 function in bgpd/bgp_zebra.c of FRR4.x (ZAPI4)
// Reference: zapi_route_decode function in lib/zclient.c of FRR5.x (ZAPI5)
553801
func (b *IPRouteBody) DecodeFromBytes(data []byte, version uint8) error {
	if b == nil {
		return fmt.Errorf("IPRouteBody is nil")
	}
	b.Prefix.Family = addressFamilyFromApi(b.Api, version)
	/* REDSTRIBUTE_IPV4_ADD|DEL and REDSITRBUTE_IPV6_ADD|DEL have merged to
	   REDISTRIBUTE_ROUTE_ADD|DEL in ZAPI version 5.
	   Therefore it can not judge the protocol famiiy from API. */

	b.Type = ROUTE_TYPE(data[0])
	if version <= 3 {
		b.Flags = FLAG(data[1])
		data = data[2:]
	} else { // version >= 4
		b.Instance = binary.BigEndian.Uint16(data[1:3])
		b.Flags = FLAG(binary.BigEndian.Uint32(data[3:7]))
		data = data[7:]
	}

	b.Message = MESSAGE_FLAG(data[0])
	b.SAFI = SAFI(SAFI_UNICAST)
	if version >= 5 {
		b.SAFI = SAFI(data[1])
		data = data[2:]
		if b.Flags&FLAG_EVPN_ROUTE > 0 {
			// size of struct ethaddr is 6 octets defined by ETH_ALEN
			copy(b.Rmac[0:6], data[0:6])
			data = data[6:]
		}
		b.Prefix.Family = data[0]
	}

	addrByteLen, err := addressByteLength(b.Prefix.Family)
	if err != nil {
		return err
	}

	addrBitLen := uint8(addrByteLen * 8)

	b.Prefix.PrefixLen = data[1]
	if b.Prefix.PrefixLen > addrBitLen {
		return fmt.Errorf("prefix length %d is greater than %d", b.Prefix.PrefixLen, addrBitLen)
	}
	data = data[2:]
	pos := 0
	rest := len(data)

	buf := make([]byte, addrByteLen)
	byteLen := int((b.Prefix.PrefixLen + 7) / 8)
	if pos+byteLen > rest {
		return fmt.Errorf("message length invalid pos:%d rest:%d", pos, rest)
	}
	copy(buf, data[pos:pos+byteLen])
	b.Prefix.Prefix = ipFromFamily(b.Prefix.Family, buf)
	pos += byteLen
	if (version == 4 && b.Message&FRR_MESSAGE_SRCPFX > 0) ||
		(version >= 5 && b.Message&FRR_ZAPI5_MESSAGE_SRCPFX > 0) {
		if pos+1 > rest {
			return fmt.Errorf("MESSAGE_SRCPFX message length invalid pos:%d rest:%d", pos, rest)
		}
		b.SrcPrefix.PrefixLen = data[pos]
		if b.SrcPrefix.PrefixLen > addrBitLen {
			return fmt.Errorf("prefix length is greater than %d", addrByteLen*8)
		}
		pos += 1
		buf = make([]byte, addrByteLen)
		byteLen = int((b.SrcPrefix.PrefixLen + 7) / 8)
		if pos+byteLen > rest {
			return fmt.Errorf("MESSAGE_SRCPFX message length invalid pos:%d rest:%d", pos, rest)
		}
		copy(buf, data[pos:pos+byteLen])
		b.SrcPrefix.Prefix = ipFromFamily(b.Prefix.Family, buf)
		pos += byteLen
	}

	b.Nexthops = []Nexthop{}
	if (version <= 3 && b.Message&MESSAGE_NEXTHOP > 0) ||
		(version == 4 && b.Message&FRR_MESSAGE_NEXTHOP > 0) ||
		(version >= 5 && b.Message&FRR_ZAPI5_MESSAGE_NEXTHOP > 0) {
		var numNexthop uint16
		if version <= 4 {
			if pos+1 > rest {
				return fmt.Errorf("MESSAGE_NEXTHOP message length invalid pos:%d rest:%d", pos, rest)
			}
			numNexthop = uint16(data[pos])
			pos += 1
		} else { // version >= 5
			if pos+2 > rest {
				return fmt.Errorf("MESSAGE_NEXTHOP message length invalid pos:%d rest:%d", pos, rest)
			}
			numNexthop = binary.BigEndian.Uint16(data[pos : pos+2])
			pos += 2
		}
		for i := 0; i < int(numNexthop); i++ {
			var nexthop Nexthop
			if version <= 3 {
				if b.Prefix.Family == syscall.AF_INET {
					nexthop.Type = NEXTHOP_TYPE_IPV4
				} else if b.Prefix.Family == syscall.AF_INET6 {
					nexthop.Type = NEXTHOP_TYPE_IPV6
				}
			} else if version == 4 {
				if b.Prefix.Family == syscall.AF_INET {
					nexthop.Type = FRR_NEXTHOP_TYPE_IPV4
				} else if b.Prefix.Family == syscall.AF_INET6 {
					nexthop.Type = FRR_NEXTHOP_TYPE_IPV6
				}
			} else { // version >= 5
				if pos+5 > rest {
					return fmt.Errorf("MESSAGE_NEXTHOP message length invalid pos:%d rest:%d", pos, rest)
				}
				nexthop.VrfId = binary.BigEndian.Uint32(data[pos : pos+4])
				nexthop.Type = NEXTHOP_TYPE(data[pos+4])
				pos += 5
			}

			if (version <= 3 && nexthop.Type == NEXTHOP_TYPE_IPV4) ||
				(version >= 4 && nexthop.Type == FRR_NEXTHOP_TYPE_IPV4) {
				if pos+4 > rest {
					return fmt.Errorf("MESSAGE_NEXTHOP NEXTHOP_TYPE_IPV4 message length invalid pos:%d rest:%d", pos, rest)
				}
				addr := data[pos : pos+4]
				nexthop.Gate = net.IP(addr).To4()
				pos += 4
			} else if (version <= 3 && nexthop.Type == NEXTHOP_TYPE_IPV6) ||
				(version >= 4 && nexthop.Type == FRR_NEXTHOP_TYPE_IPV6) {
				if pos+16 > rest {
					return fmt.Errorf("MESSAGE_NEXTHOP NEXTHOP_TYPE_IPV6 message length invalid pos:%d rest:%d", pos, rest)
				}
				addr := data[pos : pos+16]
				nexthop.Gate = net.IP(addr).To16()
				pos += 16
			} else if version >= 5 && nexthop.Type == FRR_NEXTHOP_TYPE_IFINDEX {
				if pos+4 > rest {
					return fmt.Errorf("MESSAGE_NEXTHOP NEXTHOP_TYPE_IFINDEX message length invalid pos:%d rest:%d", pos, rest)
				}
				nexthop.Ifindex = binary.BigEndian.Uint32(data[pos : pos+4])
				pos += 4
				// barkward compatibility
				if b.Prefix.Family == syscall.AF_INET {
					nexthop.Gate = net.ParseIP("0.0.0.0")
				} else if b.Prefix.Family == syscall.AF_INET6 {
					nexthop.Gate = net.ParseIP("::")
				}
			} else if version >= 5 && nexthop.Type == FRR_NEXTHOP_TYPE_IPV4_IFINDEX {
				if pos+8 > rest {
					return fmt.Errorf("MESSAGE_NEXTHOP NEXTHOP_TYPE_IPV4_IFINDEX message length invalid pos:%d rest:%d", pos, rest)
				}
				addr := data[pos : pos+4]
				nexthop.Gate = net.IP(addr).To4()
				nexthop.Ifindex = binary.BigEndian.Uint32(data[pos+4 : pos+8])
				pos += 8
			} else if version >= 5 && nexthop.Type == FRR_NEXTHOP_TYPE_IPV6_IFINDEX {
				if pos+20 > rest {
					return fmt.Errorf("MESSAGE_NEXTHOP NEXTHOP_TYPE_IPV6_IFINDEX message length invalid pos:%d rest:%d", pos, rest)
				}
				addr := data[pos : pos+16]
				nexthop.Gate = net.IP(addr).To16()
				nexthop.Ifindex = binary.BigEndian.Uint32(data[pos+16 : pos+20])
				pos += 20
			} else if version >= 5 && nexthop.Type == FRR_NEXTHOP_TYPE_BLACKHOLE {
				if pos+1 > rest {
					return fmt.Errorf("MESSAGE_NEXTHOP NEXTHOP_TYPE_BLACKHOLE message length invalid pos:%d rest:%d", pos, rest)
				}
				nexthop.BlackholeType = data[pos]
				pos += 1
			}
			b.Nexthops = append(b.Nexthops, nexthop)
		}
	}

	if (version <= 3 && b.Message&MESSAGE_IFINDEX > 0) ||
		(version == 4 && b.Message&FRR_MESSAGE_IFINDEX > 0) {
		if pos+1 > rest {
			return fmt.Errorf("MESSAGE_IFINDEX message length invalid pos:%d rest:%d", pos, rest)
		}
		numIfIndex := uint8(data[pos])
		pos += 1
		for i := 0; i < int(numIfIndex); i++ {
			if pos+4 > rest {
				return fmt.Errorf("MESSAGE_IFINDEX message length invalid pos:%d rest:%d", pos, rest)
			}
			var nexthop Nexthop
			nexthop.Ifindex = binary.BigEndian.Uint32(data[pos : pos+4])
			if version <= 3 {
				nexthop.Type = NEXTHOP_TYPE_IFINDEX
			} else if version == 4 {
				nexthop.Type = FRR_NEXTHOP_TYPE_IFINDEX
			}
			b.Nexthops = append(b.Nexthops, nexthop)
			pos += 4
		}
	}

	if (version <= 3 && b.Message&MESSAGE_DISTANCE > 0) ||
		(version == 4 && b.Message&FRR_MESSAGE_DISTANCE > 0) ||
		(version >= 5 && b.Message&FRR_ZAPI5_MESSAGE_DISTANCE > 0) {
		if pos+1 > rest {
			return fmt.Errorf("MESSAGE_DISTANCE message length invalid pos:%d rest:%d", pos, rest)
		}
		b.Distance = data[pos]
		pos += 1
	}
	if (version <= 3 && b.Message&MESSAGE_METRIC > 0) ||
		(version == 4 && b.Message&FRR_MESSAGE_METRIC > 0) ||
		(version >= 5 && b.Message&FRR_ZAPI5_MESSAGE_METRIC > 0) {
		if pos+4 > rest {
			return fmt.Errorf("MESSAGE_METRIC message length invalid pos:%d rest:%d", pos, rest)
		}
		b.Metric = binary.BigEndian.Uint32(data[pos : pos+4])
		pos += 4
	}
	if (version <= 3 && b.Message&MESSAGE_MTU > 0) ||
		(version == 4 && b.Message&FRR_MESSAGE_MTU > 0) ||
		(version >= 5 && b.Message&FRR_ZAPI5_MESSAGE_MTU > 0) {
		if pos+4 > rest {
			return fmt.Errorf("MESSAGE_MTU message length invalid pos:%d rest:%d", pos, rest)
		}
		b.Mtu = binary.BigEndian.Uint32(data[pos : pos+4])
		pos += 4
	}
	if (version <= 3 && b.Message&MESSAGE_TAG > 0) ||
		(version == 4 && b.Message&FRR_MESSAGE_TAG > 0) ||
		(version >= 5 && b.Message&FRR_ZAPI5_MESSAGE_TAG > 0) {
		if pos+4 > rest {
			return fmt.Errorf("MESSAGE_TAG message length invalid pos:%d rest:%d", pos, rest)
		}
		b.Tag = binary.BigEndian.Uint32(data[pos : pos+4])
		pos += 4
	}
	if pos != rest {
		return fmt.Errorf("message length invalid pos:%d rest:%d", pos, rest)
	}
	return nil
}
369564
func (s *NATService) GetIpForwardingRuleByID(id string, opts ...OptionFunc) (*IpForwardingRule, int, error) {
	p := &ListIpForwardingRulesParams{}
	p.p = make(map[string]interface{})

	p.p["id"] = id

	for _, fn := range append(s.cs.options, opts...) {
		if err := fn(s.cs, p); err != nil {
			return nil, -1, err
		}
	}

	l, err := s.ListIpForwardingRules(p)
	if err != nil {
		if strings.Contains(err.Error(), fmt.Sprintf(
			"Invalid parameter id value=%s due to incorrect long value format, "+
				"or entity does not exist", id)) {
			return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
		}
		return nil, -1, err
	}

	if l.Count == 0 {
		return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
	}

	if l.Count == 1 {
		return l.IpForwardingRules[0], l.Count, nil
	}
	return nil, l.Count, fmt.Errorf("There is more then one result for IpForwardingRule UUID: %s!", id)
}
1262751
func (client *Client) GetRouteMapping(guid string) (RouteMapping, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetRouteMappingRequest,
		URIParams:   Params{"route_mapping_guid": guid},
	})
	if err != nil {
		return RouteMapping{}, nil, err
	}

	var routeMapping RouteMapping
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &routeMapping,
	}

	err = client.connection.Make(request, &response)
	return routeMapping, response.Warnings, err
}
1155969
func GetBridgedDeviceNameIPMap() (map[string]string, error) {
	m := map[string]string{}
	kvs, err := getBridgedDeviceKV("Name", "IPAddress")
	if err != nil {
		return m, err
	}
	for _, kv := range kvs {
		if kv.k != "" {
			m[kv.k] = kv.v
		}
	}
	return m, nil
}
71685
func getIPv4DefaultRoutes(input io.Reader) ([]Route, error) {
	routes := []Route{}
	scanner := bufio.NewReader(input)
	for {
		line, err := scanner.ReadString('\n')
		if err == io.EOF {
			break
		}
		//ignore the headers in the route info
		if strings.HasPrefix(line, "Iface") {
			continue
		}
		fields := strings.Fields(line)
		// Interested in fields:
		//  0 - interface name
		//  1 - destination address
		//  2 - gateway
		dest, err := parseIP(fields[1], familyIPv4)
		if err != nil {
			return nil, err
		}
		gw, err := parseIP(fields[2], familyIPv4)
		if err != nil {
			return nil, err
		}
		if !dest.Equal(net.IPv4zero) {
			continue
		}
		routes = append(routes, Route{
			Interface:   fields[0],
			Destination: dest,
			Gateway:     gw,
			Family:      familyIPv4,
		})
	}
	return routes, nil
}
803666
func IsValidIPv4(value string) bool {
	return net.ParseIP(value) != nil && net.ParseIP(value).To4() != nil
}
134432
func (_class PIFClass) GetIPConfigurationMode(sessionID SessionRef, self PIFRef) (_retval IPConfigurationMode, _err error) {
	_method := "PIF.get_ip_configuration_mode"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertPIFRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertEnumIPConfigurationModeToGo(_method + " -> ", _result.Value)
	return
}
6199
func DecimalToIPv4(addr uint32) net.IP {
	bytes := make([]byte, 4)
	binary.BigEndian.PutUint32(bytes, addr)
	return net.IP(bytes)
}
196568
func DeleteBgp(stateDriver core.StateDriver, hostname string) error {
	log.Infof("Deleting bgp neighbor for {%v}", hostname)
	bgpState := &mastercfg.CfgBgpState{}
	bgpState.StateDriver = stateDriver
	err := bgpState.Read(hostname)
	if err != nil {
		log.Errorf("Error reading bgp config for hostname %s", hostname)
		return err
	}
	err = bgpState.Clear()
	if err != nil {
		log.Errorf("Error deleing Bgp config for hostname %s", hostname)
		return err
	}
	return nil

}
373099
func (api *API) WAFRule(zoneID, packageID, ruleID string) (WAFRule, error) {
	uri := "/zones/" + zoneID + "/firewall/waf/packages/" + packageID + "/rules/" + ruleID
	res, err := api.makeRequest("GET", uri, nil)
	if err != nil {
		return WAFRule{}, errors.Wrap(err, errMakeRequestError)
	}

	var r WAFRuleResponse
	err = json.Unmarshal(res, &r)
	if err != nil {
		return WAFRule{}, errors.Wrap(err, errUnmarshalError)
	}

	return r.Result, nil
}
922778
func (d *Domain) GetBlkioParameters(flags DomainModificationImpact) (*DomainBlkioParameters, error) {
	params := &DomainBlkioParameters{}
	info := getBlkioParametersFieldInfo(params)

	var cnparams C.int
	var err C.virError
	ret := C.virDomainGetBlkioParametersWrapper(d.ptr, nil, &cnparams, 0, &err)
	if ret == -1 {
		return nil, makeError(&err)
	}

	cparams := typedParamsNew(cnparams)
	defer C.virTypedParamsFree(cparams, cnparams)
	ret = C.virDomainGetBlkioParametersWrapper(d.ptr, cparams, &cnparams, C.uint(flags), &err)
	if ret == -1 {
		return nil, makeError(&err)
	}

	_, gerr := typedParamsUnpack(cparams, cnparams, info)
	if gerr != nil {
		return nil, gerr
	}

	return params, nil
}
1362183
func parseIfNameFromIPCmd(routeOut string) [][]string {
	lines := strings.Split(routeOut, "\n")
	re := whitespaceRE.Copy()
	parsedLines := make([][]string, 0, len(lines))
	for _, line := range lines {
		kvs := re.Split(line, -1)
		if len(kvs) < 5 {
			continue
		}
		parsedLines = append(parsedLines, kvs)
	}
	return parsedLines
}
1103971
func IPv4AddrAttr(ipv4 IPv4Addr, selector AttrName) string {
	fn, found := ipv4AddrAttrMap[selector]
	if !found {
		return ""
	}

	return fn(ipv4)
}
144320
func (b *BigIP) BGPNeighbors(instance string) (*BGPNeighbors, error) {
	var bgpNeighbors BGPNeighbors
	err, _ := b.getForEntity(&bgpNeighbors, uriNet, uriRouting, uriBGP, instance, uriNeighbor)
	if err != nil {
		return nil, err
	}

	return &bgpNeighbors, nil
}
1044871
func (soc *Socket) GetIpv4only() (bool, error) {
	v, err := soc.getInt(C.ZMQ_IPV4ONLY)
	return v != 0, err
}
1322697
func (s *Switch) GetDefaultIPAddressesForVPCRouter() (string, string, string, error) {

	if s.Subnets == nil || len(s.Subnets) < 1 {
		return "", "", "", fmt.Errorf("switch[%d].Subnets is nil", s.ID)
	}

	baseAddress := net.ParseIP(s.Subnets[0].IPAddresses.Min).To4()
	address1 := net.IPv4(baseAddress[0], baseAddress[1], baseAddress[2], baseAddress[3]+1)
	address2 := net.IPv4(baseAddress[0], baseAddress[1], baseAddress[2], baseAddress[3]+2)

	return baseAddress.String(), address1.String(), address2.String(), nil
}
128540
func NetAddrIPPROTO(addr net.Addr) int {
	switch addr := addr.(type) {
	case *net.IPAddr:
		switch {
		default:
			return IPPROTO_IP

		case addr.IP.To4() != nil:
			return IPPROTO_IPV4

		case addr.IP.To16() != nil:
			return IPPROTO_IPV6
		}

	case *net.TCPAddr:
		return IPPROTO_TCP

	case *net.UDPAddr:
		return IPPROTO_UDP

	default:
		return -1
	}
}