2 * Copyright (c) 2015 Cisco Systems, Inc., Brocade, Communications Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
9 package org.opendaylight.openflowplugin.openflow.md.core.sal.convertor;
11 import java.math.BigInteger;
12 import java.net.Inet4Address;
13 import java.net.InetAddress;
14 import java.net.UnknownHostException;
15 import java.util.ArrayList;
16 import java.util.Arrays;
17 import java.util.Iterator;
18 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IetfInetUtil;
19 import org.slf4j.Logger;
20 import org.slf4j.LoggerFactory;
21 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
22 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Prefix;
25 import com.google.common.base.Preconditions;
26 import com.google.common.base.Splitter;
27 import com.google.common.base.Strings;
28 import com.google.common.collect.Iterators;
29 import com.google.common.net.InetAddresses;
30 import com.google.common.primitives.UnsignedBytes;
31 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.yang.types.rev130715.DottedQuad;
35 * Created by Martin Bobak <mbobak@cisco.com> on 5.3.2015.
36 * v6 routines added by Anton Ivanov on 14.6.2015
37 * Arbitrary masks by sai.marapareddy@gmail.com
39 public final class IpConversionUtil {
41 private static final Logger LOG = LoggerFactory.getLogger(IpConversionUtil.class);
42 public static final String PREFIX_SEPARATOR = "/";
43 public static final Splitter PREFIX_SPLITTER = Splitter.on('/');
44 private static final int INADDR4SZ = 4;
45 private static final int INADDR6SZ = 16;
46 private static final int INT16SZ = 2;
47 private static final int IPV4_ADDRESS_LENGTH = 32;
48 private static final int IPV6_ADDRESS_LENGTH = 128;
49 private static final String DEFAULT_ARBITRARY_BIT_MASK = "255.255.255.255";
52 * Prefix bytearray lookup table. We concatenate the prefixes
53 * to a single byte array and perform offset lookups to ensure
54 * the table is contiguous and save some space.
56 private static final byte[] PREFIX_BYTEARRAYS;
58 final byte[] a = new byte[(INADDR6SZ * Byte.SIZE + 1) * INADDR6SZ];
61 for (int p = 0; p <= INADDR6SZ * Byte.SIZE; ++p) {
63 for (int i = 0; i < INADDR6SZ; ++i) {
64 a[offset++] = (byte) nextNibble(prefix);
69 PREFIX_BYTEARRAYS = a;
72 private IpConversionUtil() {
73 throw new UnsupportedOperationException("This class should not be instantiated.");
76 public static Iterator<String> splitToParts(final Ipv4Prefix ipv4Prefix) {
77 return PREFIX_SPLITTER.split(ipv4Prefix.getValue()).iterator();
80 public static Iterator<String> splitToParts(final Ipv4Address ipv4Address) {
81 /* Invalid (Ab)use of ip address as prefix!!! */
82 return Iterators.forArray(ipv4Address.getValue(), String.valueOf(IPV4_ADDRESS_LENGTH));
85 public static Iterator<String> splitToParts(final Ipv6Prefix ipv6Prefix) {
86 return PREFIX_SPLITTER.split(ipv6Prefix.getValue()).iterator();
89 public static Iterator<String> splitToParts(final Ipv6Address ipv6Address) {
90 /* Invalid (Ab)use of ip address as prefix!!! */
91 return Iterators.forArray(ipv6Address.getValue(), String.valueOf(IPV6_ADDRESS_LENGTH));
94 /* This forest of functions has a purpose:
96 * 1. There are multiple coding styles around the plugin, this is necessary in order to have
97 * one mechanism to convert them all, one mechanism to find them...
98 * 2. I hope that one day yangtools will actually deliver code fit for purpose in a packet
99 * processing application (presently it is not. When this happens, these can be optimized
100 * for "side-load" of pre-vetted data. Example. IP Address (v4 or v6) is prevetted left of the
101 * prefix. It should be loadable into Prefix without _RERUNNING_ 100ms+ of regexps. When (and if)
102 * that happens, it will be a simple fix here without chasing it across the whole plugin.
105 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address){
106 return IetfInetUtil.INSTANCE.ipv4PrefixFor(ipv4Address);
109 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final String mask){
111 * Ipv4Address has already validated the address part of the prefix,
112 * It is mandated to comply to the same regexp as the address
113 * There is absolutely no point rerunning additional checks vs this
114 * Note - there is no canonical form check here!!!
116 if (null != mask && !mask.isEmpty()) {
117 return new Ipv4Prefix(ipv4Address.getValue() + PREFIX_SEPARATOR + mask);
119 return new Ipv4Prefix(ipv4Address.getValue() + PREFIX_SEPARATOR + IPV4_ADDRESS_LENGTH);
123 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final int intmask){
124 return IetfInetUtil.INSTANCE.ipv4PrefixFor(ipv4Address, intmask);
127 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final byte [] bytemask){
128 return IetfInetUtil.INSTANCE.ipv4PrefixFor(ipv4Address, countBits(bytemask));
131 public static DottedQuad createArbitraryBitMask(final byte [] bytemask) {
132 DottedQuad dottedQuad = new DottedQuad(DEFAULT_ARBITRARY_BIT_MASK);
134 dottedQuad = new DottedQuad(InetAddress.getByAddress(bytemask).getHostAddress());
135 } catch (UnknownHostException e) {
136 LOG.error("Failed to create the dottedQuad notation for the given mask ", e);
141 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address){
142 return IetfInetUtil.INSTANCE.ipv6PrefixFor(ipv6Address);
145 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final String mask){
147 * Ipv6Address has already validated the address part of the prefix,
148 * It is mandated to comply to the same regexp as the address
149 * There is absolutely no point rerunning additional checks vs this
150 * Note - there is no canonical form check here!!!
152 if (Strings.isNullOrEmpty(mask)) {
153 return new Ipv6Prefix(ipv6Address.getValue() + PREFIX_SEPARATOR + String.valueOf(IPV6_ADDRESS_LENGTH));
155 return new Ipv6Prefix(ipv6Address.getValue() + PREFIX_SEPARATOR + mask);
159 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final int intmask){
160 return IetfInetUtil.INSTANCE.ipv6PrefixFor(ipv6Address, intmask);
163 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final byte [] bytemask){
164 return IetfInetUtil.INSTANCE.ipv6PrefixFor(ipv6Address, countBits(bytemask));
167 public static Integer extractPrefix(final Ipv4Prefix ipv4Prefix) {
168 return IetfInetUtil.INSTANCE.splitIpv4Prefix(ipv4Prefix).getValue();
171 public static Integer extractPrefix(final Ipv6Prefix ipv6Prefix) {
172 return IetfInetUtil.INSTANCE.splitIpv6Prefix(ipv6Prefix).getValue();
175 public static Integer extractPrefix(final Ipv4Address ipv4Prefix) {
176 return IPV4_ADDRESS_LENGTH;
179 public static Integer extractPrefix(final Ipv6Address ipv6Prefix) {
185 * Read all of the following before you touch any v6 code or decide to
186 * optimize it by invoking a "simple" Guava call
188 * Java IPv6 is fundamentally broken and Google libraries do not fix it.
189 * 1. Java will allways implicitly rewrite v4 mapped into v6 as a v4 address
190 * and there is absolutely no way to override this behaviour
191 * 2. Guava libraries cannot parse non-canonical IPv6. They will throw an
192 * exception. Even if they did, they re-use the same broken java code
195 * This is why we have to parse v6 by ourselves.
197 * The following conversion code is based on inet_cidr_pton_ipv6 in NetBSD
199 * The original BSD code is licensed under standard BSD license. While we
200 * are not obliged to provide an attribution, credit where credit is due.
201 * As far as why it is similar to Sun's sun.net.util please ask Sun why
202 * their code has the same variable names, comments and code flow.
208 * Convert Ipv6Address object to a valid Canonical v6 address in byte format
210 * @param ipv6Address - v6 Address object
211 * @return - byte array of size 16. Last byte contains netmask
215 public static byte[] canonicalBinaryV6Address(final Ipv6Address ipv6Address) {
217 * Do not modify this routine to take direct strings input!!!
218 * Key checks have been removed based on the assumption that
219 * the input is validated via regexps in Ipv6Prefix()
222 String [] address = (ipv6Address.getValue()).split("%");
228 /* Isn't it fun - the above variable names are the same in BSD and Sun sources */
232 char[] src = address[0].toCharArray();
234 byte[] dst = new byte[INADDR6SZ];
236 int src_length = src.length;
241 /* Leading :: requires some special handling. */
243 /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
244 * We will derive our code from BSD. Shakespear always sounds better
245 * in original Clingon. So does Dilbert.
249 Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
257 while (i < src_length) {
259 int chval = Character.digit(ch, 16);
261 /* Business as usual - ipv6 address digit.
262 * We can remove all checks from the original BSD code because
263 * the regexp has already verified that we are not being fed
264 * anything bigger than 0xffff between the separators.
279 /* no need to check separator position validity - regexp does that */
284 /* removed overrun check - the regexp checks for valid data */
286 dst[j++] = (byte) ((val >>> 8) & 0xff);
287 dst[j++] = (byte) (val & 0xff);
293 /* frankenstein - v4 attached to v6, mixed notation */
295 if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {
297 /* this has passed the regexp so it is fairly safe to parse it
298 * straight away. As v4 addresses do not suffer from the same
299 * defficiencies as the java v6 implementation we can invoke it
300 * straight away and be done with it
303 Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");
305 InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length));
307 Preconditions.checkArgument(_inet_form instanceof Inet4Address);
308 System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
314 /* removed parser exit on invalid char - no need to do it, regexp checks it */
317 Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
318 dst[j++] = (byte) ((val >> 8) & 0xff);
319 dst[j++] = (byte) (val & 0xff);
325 Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
326 for (i = 1; i <= n; i++) {
327 dst[INADDR6SZ - i] = dst[colonp + n - i];
328 dst[colonp + n - i] = 0;
333 Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
338 public static String byteArrayV6AddressToString (final byte [] _binary_form) throws UnknownHostException{
339 /* DO NOT DIY!!! - InetAddresses will actually print correct canonical
340 * zero compressed form.
342 return InetAddresses.toAddrString(InetAddress.getByAddress(_binary_form));
345 private static int nextNibble(final int mask) {
352 return 0xff << (8 - mask);
356 * Convert Ipv6Prefix object to a valid Canonical v6 prefix in byte format
358 * @param ipv6Prefix - v6 prefix object
359 * @return - byte array of size 16 + 1. Last byte contains netmask
361 public static byte[] canonicalBinaryV6Prefix(final Ipv6Prefix ipv6Prefix) {
363 * Do not modify this routine to take direct strings input!!!
364 * Key checks have been removed based on the assumption that
365 * the input is validated via regexps in Ipv6Prefix()
370 String [] address = null;
372 boolean valid = true;
374 address = (ipv6Prefix.getValue()).split("/");
376 mask = Integer.parseInt(address[1]);
380 } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
384 Preconditions.checkArgument(valid, "Supplied netmask in %s is invalid", ipv6Prefix.getValue());
391 /* Isn't it fun - the above variable names are the same in BSD and Sun sources */
395 char[] src = address[0].toCharArray();
397 byte[] dst = new byte[INADDR6SZ + 1];
401 int src_length = src.length;
406 /* Leading :: requires some special handling. */
408 /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
409 * We will derive our code from BSD. Shakespear always sounds better
410 * in original Clingon. So does Dilbert.
414 Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
422 while (i < src_length) {
424 int chval = Character.digit(ch, 16);
426 /* Business as usual - ipv6 address digit.
427 * We can remove all checks from the original BSD code because
428 * the regexp has already verified that we are not being fed
429 * anything bigger than 0xffff between the separators.
444 /* no need to check separator position validity - regexp does that */
449 /* removed overrun check - the regexp checks for valid data */
454 /* stop parsing if we are past the mask */
458 dst[j] = (byte) ((val >> 8) & nextNibble(m)); j++; m = m - 8;
461 /* stop parsing if we are past the mask */
465 dst[j] = (byte) (val & nextNibble(m)); j++; m = m - 8;
471 /* frankenstein - v4 attached to v6, mixed notation */
473 if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {
475 /* this has passed the regexp so it is fairly safe to parse it
476 * straight away. As v4 addresses do not suffer from the same
477 * defficiencies as the java v6 implementation we can invoke it
478 * straight away and be done with it
481 Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");
483 InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length));
485 Preconditions.checkArgument(_inet_form instanceof Inet4Address);
486 System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
492 /* removed parser exit on ivalid char - no need to do it, regexp checks it */
495 Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
496 dst[j] = (byte) ((val >> 8) & nextNibble(m)) ; j++; m = m - 8;
497 dst[j] = (byte) (val & nextNibble(m)); j++; m = m - 8;
500 if ((j < INADDR6SZ) && (m < 0)) {
502 for (i = j; i < INADDR6SZ; i++) {
510 Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
511 for (i = 1; i <= n; i++) {
512 dst[INADDR6SZ - i] = dst[colonp + n - i];
513 dst[colonp + n - i] = 0;
517 Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
520 dst[INADDR6SZ] = (byte) mask;
525 * Print a v6 prefix in byte array + 1 notation
526 * @param _binary_form - prefix, in byte [] form, last byte is netmask
527 * @return string of v6 prefix
528 * @throws UnknownHostException unknown host exception
530 public static String byteArrayV6PrefixToString(final byte [] _binary_form) throws UnknownHostException {
531 /* NO DIY!!! - InetAddresses will actually print correct canonical
532 * zero compressed form
534 StringBuilder sb = new StringBuilder();
535 /* Yang RFC specifies that the normalized form is RFC 5952, note - java
536 * core type is not RFC compliant, guava is.
539 InetAddresses.toAddrString(
540 InetAddress.getByAddress(
541 Arrays.copyOf(_binary_form, INADDR6SZ)
546 sb.append(_binary_form[INADDR6SZ] & 0xff);
547 return sb.toString();
550 private static int ipv6PrefixByteArrayOffset(final int mask) {
555 final int ret = mask * INADDR6SZ;
556 if (ret < PREFIX_BYTEARRAYS.length) {
559 return PREFIX_BYTEARRAYS.length - INADDR6SZ;
564 * Canonicalize a v6 prefix while in binary form
566 * @param prefix - prefix, in byte [] form
567 * @param mask - mask - number of bits
569 public static void canonicalizeIpv6Prefix(final byte [] prefix, final int mask) {
570 final int offset = ipv6PrefixByteArrayOffset(mask);
572 for (int i = 0; i < INADDR6SZ; i++) {
573 prefix[i] &= PREFIX_BYTEARRAYS[offset + i];
577 public static byte[] convertIpv6PrefixToByteArray(final int prefix) {
578 final int offset = ipv6PrefixByteArrayOffset(prefix);
580 return Arrays.copyOfRange(PREFIX_BYTEARRAYS, offset, offset + INADDR6SZ);
583 public static Ipv6Address extractIpv6Address(final Ipv6Prefix ipv6Prefix) {
584 return IetfInetUtil.INSTANCE.ipv6AddressFrom(ipv6Prefix);
587 public static Integer extractIpv6Prefix(final Ipv6Prefix ipv6Prefix) {
588 return IetfInetUtil.INSTANCE.splitIpv6Prefix(ipv6Prefix).getValue();
591 public static int countBits(final byte[] mask) {
593 for (byte b : mask) {
594 netmask += Integer.bitCount(UnsignedBytes.toInt(b));
599 public static final byte[] convertArbitraryMaskToByteArray(DottedQuad mask) {
601 if (mask != null && mask.getValue() != null){
602 maskValue = mask.getValue();
605 maskValue = DEFAULT_ARBITRARY_BIT_MASK;
607 InetAddress maskInIpFormat = null;
609 maskInIpFormat = InetAddress.getByName(maskValue);
610 } catch (UnknownHostException e) {
611 LOG.error ("Failed to resolve the ip address of the mask",e);
613 byte[] bytes = maskInIpFormat.getAddress();
617 public static boolean isArbitraryBitMask(byte[] byteMask) {
618 if (byteMask == null) {
622 ArrayList<Integer> integerMaskArrayList = new ArrayList<Integer>();
624 // converting byte array to bits
625 maskInBits = new BigInteger(1, byteMask).toString(2);
626 ArrayList<String> stringMaskArrayList = new ArrayList<String>(Arrays.asList(maskInBits.split("(?!^)")));
627 for(String string:stringMaskArrayList){
628 integerMaskArrayList.add(Integer.parseInt(string));
630 return checkArbitraryBitMask(integerMaskArrayList);
634 private static boolean checkArbitraryBitMask(ArrayList<Integer> arrayList) {
635 // checks 0*1* case - Leading zeros in arrayList are truncated
636 if(arrayList.size()>0 && arrayList.size()<32) {
641 for(int i=0; i<arrayList.size()-1;i++) {
642 if(arrayList.get(i) ==0 && arrayList.get(i+1) == 1) {