2 * Copyright (c) 2016 Pantheon Technologies s.r.o. 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
8 package org.opendaylight.mdsal.model.ietf.util;
10 import com.google.common.annotations.Beta;
11 import com.google.common.base.Preconditions;
12 import com.google.common.net.InetAddresses;
13 import java.net.Inet4Address;
14 import java.net.Inet6Address;
15 import java.net.InetAddress;
16 import java.net.UnknownHostException;
17 import java.util.AbstractMap.SimpleImmutableEntry;
18 import java.util.Map.Entry;
19 import javax.annotation.Nonnull;
20 import javax.annotation.Nullable;
21 import org.opendaylight.yangtools.yang.binding.util.StringValueObjectFactory;
24 * A set of utility methods to efficiently instantiate various ietf-inet-types DTOs.
27 public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A> {
28 private static final int INET4_LENGTH = 4;
29 private static final int INET6_LENGTH = 16;
30 private final StringValueObjectFactory<A4> address4Factory;
31 private final StringValueObjectFactory<P4> prefix4Factory;
32 private final StringValueObjectFactory<A6> address6Factory;
33 private final StringValueObjectFactory<P6> prefix6Factory;
35 protected AbstractIetfInetUtil(final Class<A4> addr4Class, final Class<P4> prefix4Class,
36 final Class<A6> addr6Class, final Class<P6> prefix6Class) {
37 this.address4Factory = StringValueObjectFactory.create(addr4Class, "0.0.0.0");
38 this.prefix4Factory = StringValueObjectFactory.create(prefix4Class, "0.0.0.0/0");
39 this.address6Factory = StringValueObjectFactory.create(addr6Class, "::0");
40 this.prefix6Factory = StringValueObjectFactory.create(prefix6Class, "::0/0");
43 @Nonnull protected abstract A ipv4Address(@Nonnull A4 addr);
44 @Nonnull protected abstract A ipv6Address(@Nonnull A6 addr);
45 @Nullable protected abstract A4 maybeIpv4Address(@Nonnull A addr);
46 @Nullable protected abstract A6 maybeIpv6Address(@Nonnull A addr);
47 @Nonnull protected abstract String ipv4AddressString(@Nonnull A4 addr);
48 @Nonnull protected abstract String ipv6AddressString(@Nonnull A6 addr);
49 @Nonnull protected abstract String ipv4PrefixString(@Nonnull P4 prefix);
50 @Nonnull protected abstract String ipv6PrefixString(@Nonnull P6 prefix);
52 @Nonnull public final A ipAddressFor(@Nonnull final byte[] bytes) {
53 switch (bytes.length) {
55 return ipv4Address(ipv4AddressFor(bytes));
57 return ipv6Address(ipv6AddressFor(bytes));
59 throw new IllegalArgumentException("Invalid array length " + bytes.length);
63 @Nonnull public final A ipAddressFor(@Nonnull final InetAddress addr) {
64 Preconditions.checkNotNull(addr, "Address must not be null");
65 if (addr instanceof Inet4Address) {
66 return ipv4Address(ipv4AddressFor(addr));
67 } else if (addr instanceof Inet6Address) {
68 return ipv6Address(ipv6AddressFor(addr));
70 throw new IllegalArgumentException("Unhandled address " + addr);
74 @Nonnull public final InetAddress inetAddressFor(@Nonnull final A addr) {
75 final A4 v4 = maybeIpv4Address(addr);
77 return inet4AddressFor(v4);
79 final A6 v6 = maybeIpv6Address(addr);
80 Preconditions.checkArgument(v6 != null, "Address %s is neither IPv4 nor IPv6", addr);
81 return inet6AddressFor(v6);
84 @Nonnull public final Inet4Address inet4AddressFor(@Nonnull final A4 addr) {
86 return (Inet4Address) InetAddress.getByAddress(ipv4AddressBytes(addr));
87 } catch (UnknownHostException e) {
88 throw new IllegalArgumentException("Invalid address " + addr, e);
92 @Nonnull public final Inet6Address inet6AddressFor(@Nonnull final A6 addr) {
94 return (Inet6Address) InetAddress.getByAddress(ipv6AddressBytes(addr));
95 } catch (UnknownHostException e) {
96 throw new IllegalArgumentException("Invalid address " + addr, e);
101 * Create an Ipv4Address by interpreting input bytes as an IPv4 address.
103 * @param bytes 4-byte array
104 * @return An Ipv4Address object
105 * @throws IllegalArgumentException if bytes has length different from 4
106 * @throws NullPointerException if bytes is null
108 @Nonnull public final A4 ipv4AddressFor(@Nonnull final byte[] bytes) {
109 return address4Factory.newInstance(addressStringV4(bytes));
113 * Create an Ipv4Address by interpreting an {@link Inet4Address}.
115 * @param addr An {@link Inet4Address}
116 * @return An Ipv4Address object
117 * @throws IllegalArgumentException if addr is not an {@link Inet4Address}
118 * @throws NullPointerException if addr is null
120 @Nonnull public final A4 ipv4AddressFor(@Nonnull final InetAddress addr) {
121 Preconditions.checkNotNull(addr, "Address must not be null");
122 Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
123 return address4Factory.newInstance(addr.getHostAddress());
126 @Nonnull public final A4 ipv4AddressFrom(@Nonnull final P4 prefix) {
127 return prefixToAddress(address4Factory, ipv4PrefixString(prefix));
130 @Nonnull public final byte[] ipv4AddressBytes(@Nonnull final A4 addr) {
132 * This implementation relies heavily on the input string having been validated to comply with
133 * the Ipv4Address pattern, which may include a zone index.
135 final String str = ipv4AddressString(addr);
136 final byte[] bytes = new byte[INET4_LENGTH];
137 final int percent = str.indexOf('%');
138 Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, percent == -1 ? str.length() : percent);
143 * Create a /32 Ipv4Prefix by interpreting input bytes as an IPv4 address.
145 * @param bytes four-byte array
146 * @return An Ipv4Prefix object
147 * @throws IllegalArgumentException if bytes has length different from 4
148 * @throws NullPointerException if bytes is null
150 @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] bytes) {
151 return prefix4Factory.newInstance(prefixStringV4(bytes));
155 * Create a Ipv4Prefix by combining the address with a mask. The address
156 * bytes are interpreted as an address and the specified mask is concatenated to
157 * it. The address bytes are not masked, hence input <code>address = { 1, 2, 3, 4 }</code>
158 * and <code>mask=24</code> will result in <code>1.2.3.4/24</code>.
160 * @param address Input address as a 4-byte array
161 * @param mask Prefix mask
162 * @return An Ipv4Prefix object
163 * @throws IllegalArgumentException if bytes has length different from 4 or if mask is not in range 0-32
164 * @throws NullPointerException if bytes is null
166 @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] address, final int mask) {
167 return prefix4Factory.newInstance(prefixStringV4(address, mask));
170 @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] address, final int mask) {
172 // Easy case, reuse the template
173 return prefix4Factory.getTemplate();
176 return v4PrefixForShort(address, 0, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
179 @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
181 // Easy case, reuse the template
182 return prefix4Factory.getTemplate();
185 return v4PrefixForShort(array, startOffset, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
189 * Create a /32 Ipv4Prefix for an {@link Inet4Address}
191 * @param addr An {@link Inet4Address}
192 * @return An Ipv4Prefix object
193 * @throws IllegalArgumentException if addr is not an Inet4Address
194 * @throws NullPointerException if adds is null
196 @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr) {
197 Preconditions.checkNotNull(addr, "Address must not be null");
198 Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
199 return prefix4Factory.newInstance(addr.getHostAddress() + "/32");
203 * Create a Ipv4Prefix by combining the address with a mask. The address bytes are not masked.
205 * @param addr An {@link Inet4Address}
206 * @param mask Prefix mask
207 * @return An Ipv4Prefix object
208 * @throws IllegalArgumentException if addr is not an Inet4Address or if mask is not in range 0-32
209 * @throws NullPointerException if addr is null
211 @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr, final int mask) {
212 Preconditions.checkNotNull(addr, "Address must not be null");
213 Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
214 Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
215 return prefix4Factory.newInstance(addr.getHostAddress() + '/' + mask);
218 @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr) {
219 Preconditions.checkNotNull(addr, "Address must not be null");
220 return prefix4Factory.newInstance(ipv4AddressString(addr) + "/32");
223 @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr, final int mask) {
224 Preconditions.checkNotNull(addr, "Address must not be null");
225 Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
226 return prefix4Factory.newInstance(ipv4AddressString(addr) + '/' + mask);
229 @Nonnull public final Entry<A4, Integer> splitIpv4Prefix(@Nonnull final P4 prefix) {
230 return splitPrefix(address4Factory, ipv4PrefixString(prefix));
233 @Nonnull public final byte[] ipv4PrefixToBytes(@Nonnull final P4 prefix) {
234 final String str = ipv4PrefixString(prefix);
235 final int slash = str.lastIndexOf('/');
237 final byte[] bytes = new byte[INET4_LENGTH + 1];
238 Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, slash);
239 bytes[INET4_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
244 * Create an Ipv6Address by interpreting input bytes as an IPv6 address.
246 * @param bytes 16-byte array
247 * @return An Ipv6Address object
248 * @throws IllegalArgumentException if bytes has length different from 16
249 * @throws NullPointerException if bytes is null
251 @Nonnull public final A6 ipv6AddressFor(@Nonnull final byte[] bytes) {
252 return address6Factory.newInstance(addressStringV6(bytes));
256 * Create an Ipv6Address by interpreting an {@link Inet6Address}.
258 * @param addr An {@link Inet6Address}
259 * @return An Ipv6Address object
260 * @throws IllegalArgumentException if addr is not an {@link Inet6Address}
261 * @throws NullPointerException if addr is null
263 @Nonnull public final A6 ipv6AddressFor(@Nonnull final InetAddress addr) {
264 Preconditions.checkNotNull(addr, "Address must not be null");
265 Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
266 return address6Factory.newInstance(addressStringV6(addr));
269 @Nonnull public final A6 ipv6AddressFrom(@Nonnull final P6 prefix) {
270 return prefixToAddress(address6Factory, ipv6PrefixString(prefix));
273 @Nonnull public final byte[] ipv6AddressBytes(@Nonnull final A6 addr) {
274 final String str = ipv6AddressString(addr);
275 final byte[] bytes = new byte[INET6_LENGTH];
276 final int percent = str.indexOf('%');
277 Ipv6Utils.fillIpv6Bytes(bytes, str, percent == -1 ? str.length() : percent);
282 * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv6 address.
284 * @param bytes four-byte array
285 * @return An Ipv6Prefix object
286 * @throws IllegalArgumentException if bytes has length different from 16
287 * @throws NullPointerException if bytes is null
289 @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] bytes) {
290 return prefix6Factory.newInstance(addressStringV6(bytes) + "/128");
294 * Create a Ipv6Prefix by combining the address with a mask. The address
295 * bytes are interpreted as an address and the specified mask is concatenated to
296 * it. The address bytes are not masked.
298 * @param address Input address as a 4-byte array
299 * @param mask Prefix mask
300 * @return An Ipv6Prefix object
301 * @throws IllegalArgumentException if bytes has length different from 16 or if mask is not in range 0-128
302 * @throws NullPointerException if bytes is null
304 @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] address, final int mask) {
305 Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
306 return prefix6Factory.newInstance(addressStringV6(address) + '/' + mask);
309 @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] address, final int mask) {
310 return ipv6PrefixForShort(address, 0, mask);
313 @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
315 // Easy case, reuse the template
316 return prefix6Factory.getTemplate();
319 Preconditions.checkArgument(mask > 0 && mask <= 128, "Invalid mask %s", mask);
320 final int size = (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1);
322 // Until we can instantiate an IPv6 address for a partial array, use a temporary buffer
323 byte[] tmp = new byte[INET6_LENGTH];
324 System.arraycopy(array, startOffset, tmp, 0, size);
325 return ipv6PrefixFor(tmp, mask);
329 * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv4 address.
331 * @param addr an {@link Inet6Address}
332 * @return An Ipv6Prefix object
333 * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
334 * @throws NullPointerException if addr is null
336 @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr) {
337 return prefix6Factory.newInstance(addressStringV6(addr) + "/128");
341 * Create a Ipv6Prefix by combining the address with a mask. The address
342 * bytes are interpreted as an address and the specified mask is concatenated to
343 * it. The address bytes are not masked.
345 * @param addr Input address
346 * @param mask Prefix mask
347 * @return An Ipv6Prefix object
348 * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
349 * @throws NullPointerException if addr is null
351 @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr, final int mask) {
352 Preconditions.checkNotNull(addr, "Address must not be null");
353 Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
354 Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
355 return prefix6Factory.newInstance(addressStringV6(addr) + '/' + mask);
358 @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr) {
359 Preconditions.checkNotNull(addr, "Address must not be null");
360 return prefix6Factory.newInstance(ipv6AddressString(addr) + "/128");
363 @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr, final int mask) {
364 Preconditions.checkNotNull(addr, "Address must not be null");
365 Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
366 return prefix6Factory.newInstance(ipv6AddressString(addr) + '/' + mask);
369 @Nonnull public final Entry<A6, Integer> splitIpv6Prefix(@Nonnull final P6 prefix) {
370 return splitPrefix(address6Factory, ipv6PrefixString(prefix));
373 private static <T> T prefixToAddress(final StringValueObjectFactory<T> factory, final String str) {
374 return factory.newInstance(str.substring(0, str.lastIndexOf('/')));
377 private static <T> Entry<T, Integer> splitPrefix(final StringValueObjectFactory<T> factory, final String str) {
378 final int slash = str.lastIndexOf('/');
379 return new SimpleImmutableEntry<>(factory.newInstance(str.substring(0, slash)),
380 Integer.valueOf(str.substring(slash + 1)));
383 @Nonnull public final byte[] ipv6PrefixToBytes(@Nonnull final P6 prefix) {
384 final String str = ipv6PrefixString(prefix);
385 final byte[] bytes = new byte[INET6_LENGTH + 1];
386 final int slash = str.lastIndexOf('/');
387 Ipv6Utils.fillIpv6Bytes(bytes, str, slash);
388 bytes[INET6_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
392 private static void appendIpv4String(final StringBuilder sb, final byte[] bytes) {
393 Preconditions.checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
395 sb.append(Byte.toUnsignedInt(bytes[0]));
396 for (int i = 1; i < INET4_LENGTH; ++i) {
398 sb.append(Byte.toUnsignedInt(bytes[i]));
402 private static String addressStringV4(final byte[] bytes) {
403 final StringBuilder sb = new StringBuilder(15);
404 appendIpv4String(sb, bytes);
405 return sb.toString();
408 private static String addressStringV6(final byte[] bytes) {
409 Preconditions.checkArgument(bytes.length == INET6_LENGTH, "IPv6 address length is 16 bytes");
412 return addressStringV6(Inet6Address.getByAddress(bytes));
413 } catch (UnknownHostException e) {
414 throw new IllegalArgumentException(String.format("Invalid input %s", bytes), e);
418 private static String addressStringV6(final InetAddress addr) {
419 return InetAddresses.toAddrString(addr);
422 private static String prefixStringV4(final byte[] bytes) {
423 final StringBuilder sb = new StringBuilder(18);
424 appendIpv4String(sb, bytes);
426 return sb.toString();
429 private static String prefixStringV4(final byte[] bytes, final int mask) {
430 Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
432 final StringBuilder sb = new StringBuilder(18);
433 appendIpv4String(sb, bytes);
436 return sb.toString();
439 private P4 v4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int size, final int mask) {
440 if (startOffset == 0 && size == INET4_LENGTH && array.length == INET4_LENGTH) {
441 // Easy case, fall back to non-short
442 return ipv4PrefixFor(array, mask);
445 final StringBuilder sb = new StringBuilder(18);
448 sb.append(Byte.toUnsignedInt(array[startOffset]));
449 for (int i = 1; i < size; i++) {
451 sb.append(Byte.toUnsignedInt(array[startOffset + i]));
455 for (int i = size; i < INET4_LENGTH; i++) {
460 Preconditions.checkArgument(mask > 0 && mask <= 32, "Invalid mask %s", mask);
464 return prefix4Factory.newInstance(sb.toString());