Search in sources :

Example 6 with IPv6Address

use of com.googlecode.ipv6.IPv6Address in project OpenAM by OpenRock.

the class ResourceEnvIPCondition method matchEnvironment.

/**
     * Returns the environment condition that satisfies or matches for the client
     * environment parameter, including client's IP Address.
     */
@SuppressWarnings("unchecked")
private EnvironmentCondition matchEnvironment(Map env, SSOToken token) throws EntitlementException, SSOException {
    if (debug.messageEnabled()) {
        localDebugName = debugName + ".matchEnvironment(): ";
    }
    EnvironmentCondition matchingCondition = null;
    final List<EnvironmentCondition> conditions = parseConditions(resourceEnvIPConditionValue);
    //Check if all the keys are valid
    for (EnvironmentCondition condition : conditions) {
        final String envParamName = condition.paramName;
        final String envParamValue = condition.paramValue;
        Set<String> envSet = (Set<String>) env.get(envParamName);
        if (!Utils.isEmpty(envSet)) {
            for (String strEnv : envSet) {
                if ((strEnv != null) && (strEnv.equalsIgnoreCase(envParamValue))) {
                    matchingCondition = condition;
                    break;
                }
            }
        } else {
            String strIP = null;
            Object object = env.get(REQUEST_IP);
            if (object instanceof Set) {
                Set ipSet = (Set) object;
                if (ipSet.isEmpty()) {
                    if (token != null) {
                        strIP = token.getIPAddress().getHostAddress();
                    } else {
                        throw new EntitlementException(CLIENT_IP_EMPTY);
                    }
                } else {
                    Iterator names = ipSet.iterator();
                    strIP = (String) names.next();
                }
            } else if (object instanceof String) {
                strIP = (String) object;
                if (StringUtils.isBlank(strIP)) {
                    if (token != null) {
                        strIP = token.getIPAddress().getHostAddress();
                    } else {
                        throw new EntitlementException(CLIENT_IP_EMPTY);
                    }
                }
            }
            long requestIpV4 = 0;
            IPv6Address requestIpV6 = null;
            if (ValidateIPaddress.isIPv4(strIP)) {
                requestIpV4 = stringToIp(strIP);
            } else if (ValidateIPaddress.isIPv6(strIP)) {
                requestIpV6 = IPv6Address.fromString(strIP);
            } else {
                if (debug.messageEnabled()) {
                    debug.message(localDebugName + "invalid strIP : " + strIP);
                }
                continue;
            }
            int bIndex = envParamValue.indexOf("[");
            int lIndex = envParamValue.indexOf("]");
            String ipVal = envParamValue.substring(bIndex + 1, lIndex);
            if (ipVal.contains("-")) {
                StringTokenizer stIP = new StringTokenizer(ipVal, "-");
                int tokenCnt = stIP.countTokens();
                if (tokenCnt > 2) {
                    throw new EntitlementException(INVALID_PROPERTY_VALUE, new String[] { ipVal });
                }
                String startIp = stIP.nextToken();
                String endIp = startIp;
                if (tokenCnt == 2) {
                    endIp = stIP.nextToken();
                }
                if (ValidateIPaddress.isIPv4(strIP) && ValidateIPaddress.isIPv4(startIp) && ValidateIPaddress.isIPv4(endIp)) {
                    long lStartIP = stringToIp(startIp);
                    long lEndIP = stringToIp(endIp);
                    if ((requestIpV4 >= lStartIP) && (requestIpV4 <= lEndIP)) {
                        matchingCondition = condition;
                        break;
                    }
                } else if (ValidateIPaddress.isIPv6(strIP) && ValidateIPaddress.isIPv6(startIp) && ValidateIPaddress.isIPv6(endIp)) {
                    IPv6AddressRange ipv6Range = IPv6AddressRange.fromFirstAndLast(IPv6Address.fromString(startIp), IPv6Address.fromString(endIp));
                    if (requestIpV6 != null && ipv6Range.contains(requestIpV6)) {
                        matchingCondition = condition;
                        break;
                    }
                } else {
                    if (debug.errorEnabled()) {
                        debug.error(debugName + ".matchEnvironment(): invalid property value, " + strIP);
                    }
                    throw new EntitlementException(INVALID_PROPERTY_VALUE, new String[] { strIP });
                }
            } else if (requestIpV4 != 0 && ValidateIPaddress.isIPv4(ipVal)) {
                long longIp = stringToIp(ipVal);
                if (requestIpV4 == longIp) {
                    matchingCondition = condition;
                    break;
                }
            } else if (requestIpV6 != null && ValidateIPaddress.isIPv6(ipVal)) {
                // treat as single ip address
                IPv6Address iPv6AddressIpVal = IPv6Address.fromString(ipVal);
                if (iPv6AddressIpVal.compareTo(requestIpV6) == 0) {
                    matchingCondition = condition;
                    break;
                }
            } else if (ipVal.contains("*")) {
                matchingCondition = condition;
                break;
            } else {
                throw new EntitlementException(RESOURCE_ENV_NOT_KNOWN, new String[] { ipVal });
            }
        }
    }
    return matchingCondition;
}
Also used : Set(java.util.Set) HashSet(java.util.HashSet) IPv6AddressRange(com.googlecode.ipv6.IPv6AddressRange) IPv6Address(com.googlecode.ipv6.IPv6Address) EntitlementException(com.sun.identity.entitlement.EntitlementException) StringTokenizer(java.util.StringTokenizer) Iterator(java.util.Iterator) JSONObject(org.json.JSONObject)

Example 7 with IPv6Address

use of com.googlecode.ipv6.IPv6Address in project cloudstack by apache.

the class NetUtilsTest method testGetIp6FromRange.

@Test
public void testGetIp6FromRange() {
    assertEquals(NetUtils.getIp6FromRange("1234:5678::1-1234:5678::1"), "1234:5678::1");
    for (int i = 0; i < 5; i++) {
        final String ip = NetUtils.getIp6FromRange("1234:5678::1-1234:5678::2");
        assertThat(ip, anyOf(equalTo("1234:5678::1"), equalTo("1234:5678::2")));
        s_logger.info("IP is " + ip);
    }
    String ipString = null;
    final IPv6Address ipStart = IPv6Address.fromString("1234:5678::1");
    final IPv6Address ipEnd = IPv6Address.fromString("1234:5678::ffff:ffff:ffff:ffff");
    for (int i = 0; i < 10; i++) {
        ipString = NetUtils.getIp6FromRange(ipStart.toString() + "-" + ipEnd.toString());
        s_logger.info("IP is " + ipString);
        final IPv6Address ip = IPv6Address.fromString(ipString);
        assertThat(ip, greaterThanOrEqualTo(ipStart));
        assertThat(ip, lessThanOrEqualTo(ipEnd));
    }
}
Also used : IPv6Address(com.googlecode.ipv6.IPv6Address) Test(org.junit.Test)

Example 8 with IPv6Address

use of com.googlecode.ipv6.IPv6Address in project cloudstack by apache.

the class DirectPodBasedNetworkGuru method getIp.

@DB
protected void getIp(final NicProfile nic, final Pod pod, final VirtualMachineProfile vm, final Network network) throws InsufficientVirtualNetworkCapacityException, InsufficientAddressCapacityException, ConcurrentOperationException {
    final DataCenter dc = _dcDao.findById(pod.getDataCenterId());
    Transaction.execute(new TransactionCallbackWithExceptionNoReturn<InsufficientAddressCapacityException>() {

        @Override
        public void doInTransactionWithoutResult(TransactionStatus status) throws InsufficientAddressCapacityException {
            PublicIp ip = null;
            List<PodVlanMapVO> podRefs = _podVlanDao.listPodVlanMapsByPod(pod.getId());
            VlanVO vlan = _vlanDao.findById(podRefs.get(0).getVlanDbId());
            if (nic.getIPv4Address() == null) {
                String podRangeGateway = null;
                if (!podRefs.isEmpty()) {
                    podRangeGateway = vlan.getVlanGateway();
                }
                //Get ip address from the placeholder and don't allocate a new one
                if (vm.getType() == VirtualMachine.Type.DomainRouter) {
                    Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, pod.getId());
                    if (placeholderNic != null) {
                        IPAddressVO userIp = _ipAddressDao.findByIpAndSourceNetworkId(network.getId(), placeholderNic.getIPv4Address());
                        ip = PublicIp.createFromAddrAndVlan(userIp, _vlanDao.findById(userIp.getVlanId()));
                        s_logger.debug("Nic got an ip address " + placeholderNic.getIPv4Address() + " stored in placeholder nic for the network " + network + " and gateway " + podRangeGateway);
                    }
                }
                if (ip == null) {
                    ip = _ipAddrMgr.assignPublicIpAddress(dc.getId(), pod.getId(), vm.getOwner(), VlanType.DirectAttached, network.getId(), null, false);
                }
                nic.setIPv4Address(ip.getAddress().toString());
                nic.setFormat(AddressFormat.Ip4);
                nic.setIPv4Gateway(ip.getGateway());
                nic.setIPv4Netmask(ip.getNetmask());
                if (ip.getVlanTag() != null && ip.getVlanTag().equalsIgnoreCase(Vlan.UNTAGGED)) {
                    nic.setIsolationUri(IsolationType.Ec2.toUri(Vlan.UNTAGGED));
                    nic.setBroadcastUri(BroadcastDomainType.Vlan.toUri(Vlan.UNTAGGED));
                    nic.setBroadcastType(BroadcastDomainType.Native);
                }
                nic.setReservationId(String.valueOf(ip.getVlanTag()));
                nic.setMacAddress(ip.getMacAddress());
                //save the placeholder nic if the vm is the Virtual router
                if (vm.getType() == VirtualMachine.Type.DomainRouter) {
                    Nic placeholderNic = _networkModel.getPlaceholderNicForRouter(network, pod.getId());
                    if (placeholderNic == null) {
                        s_logger.debug("Saving placeholder nic with ip4 address " + nic.getIPv4Address() + " for the network " + network);
                        _networkMgr.savePlaceholderNic(network, nic.getIPv4Address(), null, VirtualMachine.Type.DomainRouter);
                    }
                }
            }
            /**
                 * Calculate the IPv6 Address the Instance will obtain using SLAAC and IPv6 EUI-64
                 *
                 * Linux, FreeBSD and Windows all calculate the same IPv6 address when configured properly.
                 *
                 * Using Router Advertisements the routers in the network should announce the IPv6 CIDR which is configured
                 * in in the vlan table in the database.
                 *
                 * This way the NIC will be populated with a IPv6 address on which the Instance is reachable.
                 */
            if (vlan.getIp6Cidr() != null) {
                if (nic.getIPv6Address() == null) {
                    s_logger.debug("Found IPv6 CIDR " + vlan.getIp6Cidr() + " for VLAN " + vlan.getId());
                    nic.setIPv6Cidr(vlan.getIp6Cidr());
                    nic.setIPv6Gateway(vlan.getIp6Gateway());
                    IPv6Address ipv6addr = NetUtils.EUI64Address(vlan.getIp6Cidr(), nic.getMacAddress());
                    s_logger.info("Calculated IPv6 address " + ipv6addr + " using EUI-64 for NIC " + nic.getUuid());
                    nic.setIPv6Address(ipv6addr.toString());
                }
            } else {
                s_logger.debug("No IPv6 CIDR configured for VLAN " + vlan.getId());
            }
        }
    });
    nic.setIPv4Dns1(dc.getDns1());
    nic.setIPv4Dns2(dc.getDns2());
}
Also used : DataCenter(com.cloud.dc.DataCenter) PublicIp(com.cloud.network.addr.PublicIp) InsufficientAddressCapacityException(com.cloud.exception.InsufficientAddressCapacityException) IPv6Address(com.googlecode.ipv6.IPv6Address) TransactionStatus(com.cloud.utils.db.TransactionStatus) Nic(com.cloud.vm.Nic) List(java.util.List) IPAddressVO(com.cloud.network.dao.IPAddressVO) VlanVO(com.cloud.dc.VlanVO) DB(com.cloud.utils.db.DB)

Example 9 with IPv6Address

use of com.googlecode.ipv6.IPv6Address in project cloudstack by apache.

the class NetUtils method isIp6InRange.

public static boolean isIp6InRange(final String ip6, final String ip6Range) {
    if (ip6Range == null) {
        return false;
    }
    final String[] ips = ip6Range.split("-");
    final String startIp = ips[0];
    String endIp = null;
    if (ips.length > 1) {
        endIp = ips[1];
    }
    final IPv6Address start = IPv6Address.fromString(startIp);
    final IPv6Address end = IPv6Address.fromString(endIp);
    final IPv6Address ip = IPv6Address.fromString(ip6);
    if (start.compareTo(ip) <= 0 && end.compareTo(ip) >= 0) {
        return true;
    }
    return false;
}
Also used : IPv6Address(com.googlecode.ipv6.IPv6Address)

Example 10 with IPv6Address

use of com.googlecode.ipv6.IPv6Address in project cloudstack by apache.

the class NetUtils method isIp6InNetwork.

public static boolean isIp6InNetwork(final String ip6, final String ip6Cidr) {
    IPv6Network network = null;
    try {
        network = IPv6Network.fromString(ip6Cidr);
    } catch (final IllegalArgumentException ex) {
        return false;
    }
    final IPv6Address ip = IPv6Address.fromString(ip6);
    return network.contains(ip);
}
Also used : IPv6Address(com.googlecode.ipv6.IPv6Address) IPv6Network(com.googlecode.ipv6.IPv6Network)

Aggregations

IPv6Address (com.googlecode.ipv6.IPv6Address)11 IPv6AddressRange (com.googlecode.ipv6.IPv6AddressRange)5 IPv6Network (com.googlecode.ipv6.IPv6Network)2 HashSet (java.util.HashSet)2 Iterator (java.util.Iterator)2 Set (java.util.Set)2 StringTokenizer (java.util.StringTokenizer)2 DataCenter (com.cloud.dc.DataCenter)1 VlanVO (com.cloud.dc.VlanVO)1 InsufficientAddressCapacityException (com.cloud.exception.InsufficientAddressCapacityException)1 PublicIp (com.cloud.network.addr.PublicIp)1 IPAddressVO (com.cloud.network.dao.IPAddressVO)1 DB (com.cloud.utils.db.DB)1 TransactionStatus (com.cloud.utils.db.TransactionStatus)1 Nic (com.cloud.vm.Nic)1 EntitlementException (com.sun.identity.entitlement.EntitlementException)1 PolicyException (com.sun.identity.policy.PolicyException)1 BigInteger (java.math.BigInteger)1 InetAddress (java.net.InetAddress)1 UnknownHostException (java.net.UnknownHostException)1