Add ipPrefixFor() methods to IetfInetUtil
[mdsal.git] / model / ietf / ietf-type-util / src / main / java / org / opendaylight / mdsal / model / ietf / util / AbstractIetfInetUtil.java
1 /*
2  * Copyright (c) 2016 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.model.ietf.util;
9
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;
22
23 /**
24  * A set of utility methods to efficiently instantiate various ietf-inet-types DTOs.
25  */
26 @Beta
27 public abstract class AbstractIetfInetUtil<A4, P4, A6, P6, A, P> {
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;
34
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");
41     }
42
43     @Nonnull protected abstract A ipv4Address(@Nonnull A4 addr);
44     @Nonnull protected abstract A ipv6Address(@Nonnull A6 addr);
45     @Nonnull protected abstract P ipv4Prefix(@Nonnull P4 addr);
46     @Nonnull protected abstract P ipv6Prefix(@Nonnull P6 addr);
47     @Nullable protected abstract A4 maybeIpv4Address(@Nonnull A addr);
48     @Nullable protected abstract A6 maybeIpv6Address(@Nonnull A addr);
49     @Nonnull protected abstract String ipv4AddressString(@Nonnull A4 addr);
50     @Nonnull protected abstract String ipv6AddressString(@Nonnull A6 addr);
51     @Nonnull protected abstract String ipv4PrefixString(@Nonnull P4 prefix);
52     @Nonnull protected abstract String ipv6PrefixString(@Nonnull P6 prefix);
53
54     /**
55      * Create an IpAddress by interpreting input bytes as an IPv4 or IPv6 address, based on array length.
56      *
57      * @param bytes 4-byte (IPv4) or 6-byte (IPv6) array
58      * @return An IpAddress object
59      * @throws IllegalArgumentException if bytes has length different from 4 or 6
60      * @throws NullPointerException if bytes is null
61      */
62     @Nonnull public final A ipAddressFor(@Nonnull final byte[] bytes) {
63         switch (bytes.length) {
64             case INET4_LENGTH:
65                 return ipv4Address(ipv4AddressFor(bytes));
66             case INET6_LENGTH:
67                 return ipv6Address(ipv6AddressFor(bytes));
68             default:
69                 throw new IllegalArgumentException("Invalid array length " + bytes.length);
70         }
71     }
72
73     @Nonnull public final A ipAddressFor(@Nonnull final InetAddress addr) {
74         Preconditions.checkNotNull(addr, "Address must not be null");
75         if (addr instanceof Inet4Address) {
76             return ipv4Address(ipv4AddressFor(addr));
77         } else if (addr instanceof Inet6Address) {
78             return ipv6Address(ipv6AddressFor(addr));
79         } else {
80             throw new IllegalArgumentException("Unhandled address " + addr);
81         }
82     }
83
84     /**
85      * Create an IpPrefix by combining the address with a mask. The address
86      * bytes are interpreted as an address and the specified mask is concatenated to
87      * it. The address bytes are not masked.
88      *
89      * @param bytes Input address as a 4-byte (IPv4) or 16-byte (IPv6) array
90      * @param mask Prefix mask
91      * @return An IpPrefix object
92      * @throws IllegalArgumentException if bytes has length different from 4 or 16 or if mask is not
93      *         in range 0-32 or 0-128 respectively
94      * @throws NullPointerException if bytes is null
95      */
96
97     @Nonnull public final P ipPrefixFor(@Nonnull final byte[] bytes, final int mask) {
98         switch (bytes.length) {
99             case INET4_LENGTH:
100                 return ipv4Prefix(ipv4PrefixFor(bytes, mask));
101             case INET6_LENGTH:
102                 return ipv6Prefix(ipv6PrefixFor(bytes, mask));
103             default:
104                 throw new IllegalArgumentException("Invalid array length " + bytes.length);
105         }
106     }
107
108     @Nonnull public final P ipPrefixFor(@Nonnull final InetAddress addr, final int mask) {
109         Preconditions.checkNotNull(addr, "Address must not be null");
110         if (addr instanceof Inet4Address) {
111             return ipv4Prefix(ipv4PrefixFor(addr, mask));
112         } else if (addr instanceof Inet6Address) {
113             return ipv6Prefix(ipv6PrefixFor(addr, mask));
114         } else {
115             throw new IllegalArgumentException("Unhandled address " + addr);
116         }
117     }
118
119     @Nonnull public final InetAddress inetAddressFor(@Nonnull final A addr) {
120         final A4 v4 = maybeIpv4Address(addr);
121         if (v4 != null) {
122             return inet4AddressFor(v4);
123         }
124         final A6 v6 = maybeIpv6Address(addr);
125         Preconditions.checkArgument(v6 != null, "Address %s is neither IPv4 nor IPv6", addr);
126         return inet6AddressFor(v6);
127     }
128
129     @Nonnull public final Inet4Address inet4AddressFor(@Nonnull final A4 addr) {
130         try {
131             return (Inet4Address) InetAddress.getByAddress(ipv4AddressBytes(addr));
132         } catch (UnknownHostException e) {
133             throw new IllegalArgumentException("Invalid address " + addr, e);
134         }
135     }
136
137     @Nonnull public final Inet6Address inet6AddressFor(@Nonnull final A6 addr) {
138         try {
139             return (Inet6Address) InetAddress.getByAddress(ipv6AddressBytes(addr));
140         } catch (UnknownHostException e) {
141             throw new IllegalArgumentException("Invalid address " + addr, e);
142         }
143     }
144
145     /**
146      * Create an Ipv4Address by interpreting input bytes as an IPv4 address.
147      *
148      * @param bytes 4-byte array
149      * @return An Ipv4Address object
150      * @throws IllegalArgumentException if bytes has length different from 4
151      * @throws NullPointerException if bytes is null
152      */
153     @Nonnull public final A4 ipv4AddressFor(@Nonnull final byte[] bytes) {
154         return address4Factory.newInstance(addressStringV4(bytes));
155     }
156
157     /**
158      * Create an Ipv4Address by interpreting an {@link Inet4Address}.
159      *
160      * @param addr An {@link Inet4Address}
161      * @return An Ipv4Address object
162      * @throws IllegalArgumentException if addr is not an {@link Inet4Address}
163      * @throws NullPointerException if addr is null
164      */
165     @Nonnull public final A4 ipv4AddressFor(@Nonnull final InetAddress addr) {
166         Preconditions.checkNotNull(addr, "Address must not be null");
167         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
168         return address4Factory.newInstance(addr.getHostAddress());
169     }
170
171     @Nonnull public final A4 ipv4AddressFrom(@Nonnull final P4 prefix) {
172         return prefixToAddress(address4Factory, ipv4PrefixString(prefix));
173     }
174
175     @Nonnull public final byte[] ipv4AddressBytes(@Nonnull final A4 addr) {
176         /*
177          * This implementation relies heavily on the input string having been validated to comply with
178          * the Ipv4Address pattern, which may include a zone index.
179          */
180         final String str = ipv4AddressString(addr);
181         final byte[] bytes = new byte[INET4_LENGTH];
182         final int percent = str.indexOf('%');
183         Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, percent == -1 ? str.length() : percent);
184         return bytes;
185     }
186
187     /**
188      * Create a /32 Ipv4Prefix by interpreting input bytes as an IPv4 address.
189      *
190      * @param bytes four-byte array
191      * @return An Ipv4Prefix object
192      * @throws IllegalArgumentException if bytes has length different from 4
193      * @throws NullPointerException if bytes is null
194      */
195     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] bytes) {
196         return prefix4Factory.newInstance(prefixStringV4(bytes));
197     }
198
199     /**
200      * Create a Ipv4Prefix by combining the address with a mask. The address
201      * bytes are interpreted as an address and the specified mask is concatenated to
202      * it. The address bytes are not masked, hence input <code>address = { 1, 2, 3, 4 }</code>
203      * and <code>mask=24</code> will result in <code>1.2.3.4/24</code>.
204      *
205      * @param address Input address as a 4-byte array
206      * @param mask Prefix mask
207      * @return An Ipv4Prefix object
208      * @throws IllegalArgumentException if bytes has length different from 4 or if mask is not in range 0-32
209      * @throws NullPointerException if bytes is null
210      */
211     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] address, final int mask) {
212         return prefix4Factory.newInstance(prefixStringV4(address, mask));
213     }
214
215     @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] address, final int mask) {
216         if (mask == 0) {
217             // Easy case, reuse the template
218             return prefix4Factory.getTemplate();
219         }
220
221         return v4PrefixForShort(address, 0, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
222     }
223
224     @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
225         if (mask == 0) {
226             // Easy case, reuse the template
227             return prefix4Factory.getTemplate();
228         }
229
230         return v4PrefixForShort(array, startOffset, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
231     }
232
233     /**
234      * Create a /32 Ipv4Prefix for an {@link Inet4Address}
235      *
236      * @param addr An {@link Inet4Address}
237      * @return An Ipv4Prefix object
238      * @throws IllegalArgumentException if addr is not an Inet4Address
239      * @throws NullPointerException if adds is null
240      */
241     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr) {
242         Preconditions.checkNotNull(addr, "Address must not be null");
243         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
244         return prefix4Factory.newInstance(addr.getHostAddress() + "/32");
245     }
246
247     /**
248      * Create a Ipv4Prefix by combining the address with a mask. The address bytes are not masked.
249      *
250      * @param addr An {@link Inet4Address}
251      * @param mask Prefix mask
252      * @return An Ipv4Prefix object
253      * @throws IllegalArgumentException if addr is not an Inet4Address or if mask is not in range 0-32
254      * @throws NullPointerException if addr is null
255      */
256     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr, final int mask) {
257         Preconditions.checkNotNull(addr, "Address must not be null");
258         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
259         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
260         return prefix4Factory.newInstance(addr.getHostAddress() + '/' + mask);
261     }
262
263     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr) {
264         Preconditions.checkNotNull(addr, "Address must not be null");
265         return prefix4Factory.newInstance(ipv4AddressString(addr) + "/32");
266     }
267
268     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr, final int mask) {
269         Preconditions.checkNotNull(addr, "Address must not be null");
270         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
271         return prefix4Factory.newInstance(ipv4AddressString(addr) + '/' + mask);
272     }
273
274     @Nonnull public final Entry<A4, Integer> splitIpv4Prefix(@Nonnull final P4 prefix) {
275         return splitPrefix(address4Factory, ipv4PrefixString(prefix));
276     }
277
278     @Nonnull public final byte[] ipv4PrefixToBytes(@Nonnull final P4 prefix) {
279         final String str = ipv4PrefixString(prefix);
280         final int slash = str.lastIndexOf('/');
281
282         final byte[] bytes = new byte[INET4_LENGTH + 1];
283         Ipv4Utils.fillIpv4Bytes(bytes, 0, str, 0, slash);
284         bytes[INET4_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
285         return bytes;
286     }
287
288     /**
289      * Create an Ipv6Address by interpreting input bytes as an IPv6 address.
290      *
291      * @param bytes 16-byte array
292      * @return An Ipv6Address object
293      * @throws IllegalArgumentException if bytes has length different from 16
294      * @throws NullPointerException if bytes is null
295      */
296     @Nonnull public final A6 ipv6AddressFor(@Nonnull final byte[] bytes) {
297         return address6Factory.newInstance(addressStringV6(bytes));
298     }
299
300     /**
301      * Create an Ipv6Address by interpreting an {@link Inet6Address}.
302      *
303      * @param addr An {@link Inet6Address}
304      * @return An Ipv6Address object
305      * @throws IllegalArgumentException if addr is not an {@link Inet6Address}
306      * @throws NullPointerException if addr is null
307      */
308     @Nonnull public final A6 ipv6AddressFor(@Nonnull final InetAddress addr) {
309         Preconditions.checkNotNull(addr, "Address must not be null");
310         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
311         return address6Factory.newInstance(addressStringV6(addr));
312     }
313
314     @Nonnull public final A6 ipv6AddressFrom(@Nonnull final P6 prefix) {
315         return prefixToAddress(address6Factory, ipv6PrefixString(prefix));
316     }
317
318     @Nonnull public final byte[] ipv6AddressBytes(@Nonnull final A6 addr) {
319         final String str = ipv6AddressString(addr);
320         final byte[] bytes = new byte[INET6_LENGTH];
321         final int percent = str.indexOf('%');
322         Ipv6Utils.fillIpv6Bytes(bytes, str, percent == -1 ? str.length() : percent);
323         return bytes;
324     }
325
326     /**
327      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv6 address.
328      *
329      * @param bytes four-byte array
330      * @return An Ipv6Prefix object
331      * @throws IllegalArgumentException if bytes has length different from 16
332      * @throws NullPointerException if bytes is null
333      */
334     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] bytes) {
335         return prefix6Factory.newInstance(addressStringV6(bytes) + "/128");
336     }
337
338     /**
339      * Create a Ipv6Prefix by combining the address with a mask. The address
340      * bytes are interpreted as an address and the specified mask is concatenated to
341      * it. The address bytes are not masked.
342      *
343      * @param address Input address as a 16-byte array
344      * @param mask Prefix mask
345      * @return An Ipv6Prefix object
346      * @throws IllegalArgumentException if bytes has length different from 16 or if mask is not in range 0-128
347      * @throws NullPointerException if bytes is null
348      */
349     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] address, final int mask) {
350         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
351         return prefix6Factory.newInstance(addressStringV6(address) + '/' + mask);
352     }
353
354     @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] address, final int mask) {
355         return ipv6PrefixForShort(address, 0, mask);
356     }
357
358     @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
359         if (mask == 0) {
360             // Easy case, reuse the template
361             return prefix6Factory.getTemplate();
362         }
363
364         Preconditions.checkArgument(mask > 0 && mask <= 128, "Invalid mask %s", mask);
365         final int size = (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1);
366
367         // Until we can instantiate an IPv6 address for a partial array, use a temporary buffer
368         byte[] tmp = new byte[INET6_LENGTH];
369         System.arraycopy(array, startOffset, tmp, 0, size);
370         return ipv6PrefixFor(tmp, mask);
371     }
372
373     /**
374      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv4 address.
375      *
376      * @param addr an {@link Inet6Address}
377      * @return An Ipv6Prefix object
378      * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
379      * @throws NullPointerException if addr is null
380      */
381     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr) {
382         return prefix6Factory.newInstance(addressStringV6(addr) + "/128");
383     }
384
385     /**
386      * Create a Ipv6Prefix by combining the address with a mask. The address
387      * bytes are interpreted as an address and the specified mask is concatenated to
388      * it. The address bytes are not masked.
389      *
390      * @param addr Input address
391      * @param mask Prefix mask
392      * @return An Ipv6Prefix object
393      * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
394      * @throws NullPointerException if addr is null
395      */
396     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr, final int mask) {
397         Preconditions.checkNotNull(addr, "Address must not be null");
398         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
399         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
400         return prefix6Factory.newInstance(addressStringV6(addr) + '/' + mask);
401     }
402
403     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr) {
404         Preconditions.checkNotNull(addr, "Address must not be null");
405         return prefix6Factory.newInstance(ipv6AddressString(addr) + "/128");
406     }
407
408     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr, final int mask) {
409         Preconditions.checkNotNull(addr, "Address must not be null");
410         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
411         return prefix6Factory.newInstance(ipv6AddressString(addr) + '/' + mask);
412     }
413
414     @Nonnull public final Entry<A6, Integer> splitIpv6Prefix(@Nonnull final P6 prefix) {
415         return splitPrefix(address6Factory, ipv6PrefixString(prefix));
416     }
417
418     private static <T> T prefixToAddress(final StringValueObjectFactory<T> factory, final String str) {
419         return factory.newInstance(str.substring(0, str.lastIndexOf('/')));
420     }
421
422     private static <T> Entry<T, Integer> splitPrefix(final StringValueObjectFactory<T> factory, final String str) {
423         final int slash = str.lastIndexOf('/');
424         return new SimpleImmutableEntry<>(factory.newInstance(str.substring(0, slash)),
425                 Integer.valueOf(str.substring(slash + 1)));
426     }
427
428     @Nonnull public final byte[] ipv6PrefixToBytes(@Nonnull final P6 prefix) {
429         final String str = ipv6PrefixString(prefix);
430         final byte[] bytes = new byte[INET6_LENGTH + 1];
431         final int slash = str.lastIndexOf('/');
432         Ipv6Utils.fillIpv6Bytes(bytes, str, slash);
433         bytes[INET6_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
434         return bytes;
435     }
436
437     private static void appendIpv4String(final StringBuilder sb, final byte[] bytes) {
438         Preconditions.checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
439
440         sb.append(Byte.toUnsignedInt(bytes[0]));
441         for (int i = 1; i < INET4_LENGTH; ++i) {
442             sb.append('.');
443             sb.append(Byte.toUnsignedInt(bytes[i]));
444         }
445     }
446
447     private static String addressStringV4(final byte[] bytes) {
448         final StringBuilder sb = new StringBuilder(15);
449         appendIpv4String(sb, bytes);
450         return sb.toString();
451     }
452
453     private static String addressStringV6(final byte[] bytes) {
454         Preconditions.checkArgument(bytes.length == INET6_LENGTH, "IPv6 address length is 16 bytes");
455
456         try {
457             return addressStringV6(Inet6Address.getByAddress(bytes));
458         } catch (UnknownHostException e) {
459             throw new IllegalArgumentException(String.format("Invalid input %s", bytes), e);
460         }
461     }
462
463     private static String addressStringV6(final InetAddress addr) {
464         return InetAddresses.toAddrString(addr);
465     }
466
467     private static String prefixStringV4(final byte[] bytes) {
468         final StringBuilder sb = new StringBuilder(18);
469         appendIpv4String(sb, bytes);
470         sb.append("/32");
471         return sb.toString();
472     }
473
474     private static String prefixStringV4(final byte[] bytes, final int mask) {
475         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
476
477         final StringBuilder sb = new StringBuilder(18);
478         appendIpv4String(sb, bytes);
479         sb.append('/');
480         sb.append(mask);
481         return sb.toString();
482     }
483
484     private P4 v4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int size, final int mask) {
485         if (startOffset == 0 && size == INET4_LENGTH && array.length == INET4_LENGTH) {
486             // Easy case, fall back to non-short
487             return ipv4PrefixFor(array, mask);
488         }
489
490         final StringBuilder sb = new StringBuilder(18);
491
492         // Add from address
493         sb.append(Byte.toUnsignedInt(array[startOffset]));
494         for (int i = 1; i < size; i++) {
495             sb.append('.');
496             sb.append(Byte.toUnsignedInt(array[startOffset + i]));
497         }
498
499         // Add zeros
500         for (int i = size; i < INET4_LENGTH; i++) {
501             sb.append(".0");
502         }
503
504         // Add mask
505         Preconditions.checkArgument(mask > 0 && mask <= 32, "Invalid mask %s", mask);
506         sb.append('/');
507         sb.append(mask);
508
509         return prefix4Factory.newInstance(sb.toString());
510     }
511 }