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 com.google.common.base.Preconditions;
12 import com.google.common.base.Splitter;
13 import com.google.common.base.Strings;
14 import com.google.common.collect.Iterators;
15 import com.google.common.net.InetAddresses;
16 import com.google.common.primitives.UnsignedBytes;
17 import java.net.Inet4Address;
18 import java.net.InetAddress;
19 import java.net.UnknownHostException;
20 import java.util.Arrays;
21 import java.util.Iterator;
22 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.IetfInetUtil;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
26 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Prefix;
30 * Created by Martin Bobak <mbobak@cisco.com> on 5.3.2015.
31 * v6 routines added by Anton Ivanov on 14.6.2015
33 public final class IpConversionUtil {
35 public static final String PREFIX_SEPARATOR = "/";
36 public static final Splitter PREFIX_SPLITTER = Splitter.on('/');
37 private static final int INADDR4SZ = 4;
38 private static final int INADDR6SZ = 16;
39 private static final int INT16SZ = 2;
40 private static final int IPV4_ADDRESS_LENGTH = 32;
41 private static final int IPV6_ADDRESS_LENGTH = 128;
44 * Prefix bytearray lookup table. We concatenate the prefixes
45 * to a single byte array and perform offset lookups to ensure
46 * the table is contiguous and save some space.
48 private static final byte[] PREFIX_BYTEARRAYS;
50 final byte[] a = new byte[(INADDR6SZ * Byte.SIZE + 1) * INADDR6SZ];
53 for (int p = 0; p <= INADDR6SZ * Byte.SIZE; ++p) {
55 for (int i = 0; i < INADDR6SZ; ++i) {
56 a[offset++] = (byte) nextNibble(prefix);
61 PREFIX_BYTEARRAYS = a;
64 private IpConversionUtil() {
65 throw new UnsupportedOperationException("This class should not be instantiated.");
68 public static Iterator<String> splitToParts(final Ipv4Prefix ipv4Prefix) {
69 return PREFIX_SPLITTER.split(ipv4Prefix.getValue()).iterator();
72 public static Iterator<String> splitToParts(final Ipv4Address ipv4Address) {
73 /* Invalid (Ab)use of ip address as prefix!!! */
74 return Iterators.forArray(ipv4Address.getValue(), String.valueOf(IPV4_ADDRESS_LENGTH));
77 public static Iterator<String> splitToParts(final Ipv6Prefix ipv6Prefix) {
78 return PREFIX_SPLITTER.split(ipv6Prefix.getValue()).iterator();
81 public static Iterator<String> splitToParts(final Ipv6Address ipv6Address) {
82 /* Invalid (Ab)use of ip address as prefix!!! */
83 return Iterators.forArray(ipv6Address.getValue(), String.valueOf(IPV6_ADDRESS_LENGTH));
86 /* This forest of functions has a purpose:
88 * 1. There are multiple coding styles around the plugin, this is necessary in order to have
89 * one mechanism to convert them all, one mechanism to find them...
90 * 2. I hope that one day yangtools will actually deliver code fit for purpose in a packet
91 * processing application (presently it is not. When this happens, these can be optimized
92 * for "side-load" of pre-vetted data. Example. IP Address (v4 or v6) is prevetted left of the
93 * prefix. It should be loadable into Prefix without _RERUNNING_ 100ms+ of regexps. When (and if)
94 * that happens, it will be a simple fix here without chasing it across the whole plugin.
97 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address){
98 return IetfInetUtil.INSTANCE.ipv4PrefixFor(ipv4Address);
101 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final String mask){
103 * Ipv4Address has already validated the address part of the prefix,
104 * It is mandated to comply to the same regexp as the address
105 * There is absolutely no point rerunning additional checks vs this
106 * Note - there is no canonical form check here!!!
108 if (null != mask && !mask.isEmpty()) {
109 return new Ipv4Prefix(ipv4Address.getValue() + PREFIX_SEPARATOR + mask);
111 return new Ipv4Prefix(ipv4Address.getValue() + PREFIX_SEPARATOR + IPV4_ADDRESS_LENGTH);
115 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final int intmask){
116 return IetfInetUtil.INSTANCE.ipv4PrefixFor(ipv4Address, intmask);
119 public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final byte [] bytemask){
120 return IetfInetUtil.INSTANCE.ipv4PrefixFor(ipv4Address, countBits(bytemask));
123 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address){
124 return IetfInetUtil.INSTANCE.ipv6PrefixFor(ipv6Address);
127 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final String mask){
129 * Ipv6Address has already validated the address part of the prefix,
130 * It is mandated to comply to the same regexp as the address
131 * There is absolutely no point rerunning additional checks vs this
132 * Note - there is no canonical form check here!!!
134 if (Strings.isNullOrEmpty(mask)) {
135 return new Ipv6Prefix(ipv6Address.getValue() + PREFIX_SEPARATOR + String.valueOf(IPV6_ADDRESS_LENGTH));
137 return new Ipv6Prefix(ipv6Address.getValue() + PREFIX_SEPARATOR + mask);
141 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final int intmask){
142 return IetfInetUtil.INSTANCE.ipv6PrefixFor(ipv6Address, intmask);
145 public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final byte [] bytemask){
146 return IetfInetUtil.INSTANCE.ipv6PrefixFor(ipv6Address, countBits(bytemask));
149 public static Integer extractPrefix(final Ipv4Prefix ipv4Prefix) {
150 return IetfInetUtil.INSTANCE.splitIpv4Prefix(ipv4Prefix).getValue();
153 public static Integer extractPrefix(final Ipv6Prefix ipv6Prefix) {
154 return IetfInetUtil.INSTANCE.splitIpv6Prefix(ipv6Prefix).getValue();
157 public static Integer extractPrefix(final Ipv4Address ipv4Prefix) {
158 return IPV4_ADDRESS_LENGTH;
161 public static Integer extractPrefix(final Ipv6Address ipv6Prefix) {
167 * Read all of the following before you touch any v6 code or decide to
168 * optimize it by invoking a "simple" Guava call
170 * Java IPv6 is fundamentally broken and Google libraries do not fix it.
171 * 1. Java will allways implicitly rewrite v4 mapped into v6 as a v4 address
172 * and there is absolutely no way to override this behaviour
173 * 2. Guava libraries cannot parse non-canonical IPv6. They will throw an
174 * exception. Even if they did, they re-use the same broken java code
177 * This is why we have to parse v6 by ourselves.
179 * The following conversion code is based on inet_cidr_pton_ipv6 in NetBSD
181 * The original BSD code is licensed under standard BSD license. While we
182 * are not obliged to provide an attribution, credit where credit is due.
183 * As far as why it is similar to Sun's sun.net.util please ask Sun why
184 * their code has the same variable names, comments and code flow.
190 * Convert Ipv6Address object to a valid Canonical v6 address in byte format
192 * @param ipv6Address - v6 Address object
193 * @return - byte array of size 16. Last byte contains netmask
197 public static byte[] canonicalBinaryV6Address(final Ipv6Address ipv6Address) {
199 * Do not modify this routine to take direct strings input!!!
200 * Key checks have been removed based on the assumption that
201 * the input is validated via regexps in Ipv6Prefix()
204 String [] address = (ipv6Address.getValue()).split("%");
210 /* Isn't it fun - the above variable names are the same in BSD and Sun sources */
214 char[] src = address[0].toCharArray();
216 byte[] dst = new byte[INADDR6SZ];
218 int src_length = src.length;
223 /* Leading :: requires some special handling. */
225 /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
226 * We will derive our code from BSD. Shakespear always sounds better
227 * in original Clingon. So does Dilbert.
231 Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
239 while (i < src_length) {
241 int chval = Character.digit(ch, 16);
243 /* Business as usual - ipv6 address digit.
244 * We can remove all checks from the original BSD code because
245 * the regexp has already verified that we are not being fed
246 * anything bigger than 0xffff between the separators.
261 /* no need to check separator position validity - regexp does that */
266 /* removed overrun check - the regexp checks for valid data */
268 dst[j++] = (byte) ((val >>> 8) & 0xff);
269 dst[j++] = (byte) (val & 0xff);
275 /* frankenstein - v4 attached to v6, mixed notation */
277 if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {
279 /* this has passed the regexp so it is fairly safe to parse it
280 * straight away. As v4 addresses do not suffer from the same
281 * defficiencies as the java v6 implementation we can invoke it
282 * straight away and be done with it
285 Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");
287 InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length));
289 Preconditions.checkArgument(_inet_form instanceof Inet4Address);
290 System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
296 /* removed parser exit on invalid char - no need to do it, regexp checks it */
299 Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
300 dst[j++] = (byte) ((val >> 8) & 0xff);
301 dst[j++] = (byte) (val & 0xff);
307 Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
308 for (i = 1; i <= n; i++) {
309 dst[INADDR6SZ - i] = dst[colonp + n - i];
310 dst[colonp + n - i] = 0;
315 Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
320 public static String byteArrayV6AddressToString (final byte [] _binary_form) throws UnknownHostException{
321 /* DO NOT DIY!!! - InetAddresses will actually print correct canonical
322 * zero compressed form.
324 return InetAddresses.toAddrString(InetAddress.getByAddress(_binary_form));
327 private static int nextNibble(final int mask) {
334 return 0xff << (8 - mask);
338 * Convert Ipv6Prefix object to a valid Canonical v6 prefix in byte format
340 * @param ipv6Prefix - v6 prefix object
341 * @return - byte array of size 16 + 1. Last byte contains netmask
343 public static byte[] canonicalBinaryV6Prefix(final Ipv6Prefix ipv6Prefix) {
345 * Do not modify this routine to take direct strings input!!!
346 * Key checks have been removed based on the assumption that
347 * the input is validated via regexps in Ipv6Prefix()
352 String [] address = null;
354 boolean valid = true;
356 address = (ipv6Prefix.getValue()).split("/");
358 mask = Integer.parseInt(address[1]);
362 } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
366 Preconditions.checkArgument(valid, "Supplied netmask in %s is invalid", ipv6Prefix.getValue());
373 /* Isn't it fun - the above variable names are the same in BSD and Sun sources */
377 char[] src = address[0].toCharArray();
379 byte[] dst = new byte[INADDR6SZ + 1];
383 int src_length = src.length;
388 /* Leading :: requires some special handling. */
390 /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
391 * We will derive our code from BSD. Shakespear always sounds better
392 * in original Clingon. So does Dilbert.
396 Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
404 while (i < src_length) {
406 int chval = Character.digit(ch, 16);
408 /* Business as usual - ipv6 address digit.
409 * We can remove all checks from the original BSD code because
410 * the regexp has already verified that we are not being fed
411 * anything bigger than 0xffff between the separators.
426 /* no need to check separator position validity - regexp does that */
431 /* removed overrun check - the regexp checks for valid data */
436 /* stop parsing if we are past the mask */
440 dst[j] = (byte) ((val >> 8) & nextNibble(m)); j++; m = m - 8;
443 /* stop parsing if we are past the mask */
447 dst[j] = (byte) (val & nextNibble(m)); j++; m = m - 8;
453 /* frankenstein - v4 attached to v6, mixed notation */
455 if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {
457 /* this has passed the regexp so it is fairly safe to parse it
458 * straight away. As v4 addresses do not suffer from the same
459 * defficiencies as the java v6 implementation we can invoke it
460 * straight away and be done with it
463 Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");
465 InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length));
467 Preconditions.checkArgument(_inet_form instanceof Inet4Address);
468 System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
474 /* removed parser exit on ivalid char - no need to do it, regexp checks it */
477 Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
478 dst[j] = (byte) ((val >> 8) & nextNibble(m)) ; j++; m = m - 8;
479 dst[j] = (byte) (val & nextNibble(m)); j++; m = m - 8;
482 if ((j < INADDR6SZ) && (m < 0)) {
484 for (i = j; i < INADDR6SZ; i++) {
492 Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
493 for (i = 1; i <= n; i++) {
494 dst[INADDR6SZ - i] = dst[colonp + n - i];
495 dst[colonp + n - i] = 0;
499 Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
502 dst[INADDR6SZ] = (byte) mask;
507 * Print a v6 prefix in byte array + 1 notation
508 * @param _binary_form - prefix, in byte [] form, last byte is netmask
509 * @return string of v6 prefix
510 * @throws UnknownHostException unknown host exception
512 public static String byteArrayV6PrefixToString(final byte [] _binary_form) throws UnknownHostException {
513 /* NO DIY!!! - InetAddresses will actually print correct canonical
514 * zero compressed form
516 StringBuilder sb = new StringBuilder();
517 /* Yang RFC specifies that the normalized form is RFC 5952, note - java
518 * core type is not RFC compliant, guava is.
521 InetAddresses.toAddrString(
522 InetAddress.getByAddress(
523 Arrays.copyOf(_binary_form, INADDR6SZ)
528 sb.append(_binary_form[INADDR6SZ] & 0xff);
529 return sb.toString();
532 private static int ipv6PrefixByteArrayOffset(final int mask) {
537 final int ret = mask * INADDR6SZ;
538 if (ret < PREFIX_BYTEARRAYS.length) {
541 return PREFIX_BYTEARRAYS.length - INADDR6SZ;
546 * Canonicalize a v6 prefix while in binary form
548 * @param prefix - prefix, in byte [] form
549 * @param mask - mask - number of bits
551 public static void canonicalizeIpv6Prefix(final byte [] prefix, final int mask) {
552 final int offset = ipv6PrefixByteArrayOffset(mask);
554 for (int i = 0; i < INADDR6SZ; i++) {
555 prefix[i] &= PREFIX_BYTEARRAYS[offset + i];
559 public static byte[] convertIpv6PrefixToByteArray(final int prefix) {
560 final int offset = ipv6PrefixByteArrayOffset(prefix);
562 return Arrays.copyOfRange(PREFIX_BYTEARRAYS, offset, offset + INADDR6SZ);
565 public static Ipv6Address extractIpv6Address(final Ipv6Prefix ipv6Prefix) {
566 return IetfInetUtil.INSTANCE.ipv6AddressFrom(ipv6Prefix);
569 public static Integer extractIpv6Prefix(final Ipv6Prefix ipv6Prefix) {
570 return IetfInetUtil.INSTANCE.splitIpv6Prefix(ipv6Prefix).getValue();
573 public static int countBits(final byte[] mask) {
575 for (byte b : mask) {
576 netmask += Integer.bitCount(UnsignedBytes.toInt(b));