780e06760270c4b6e7c1f1b8ade1d8c5580631d6
[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> {
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     @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);
51
52     @Nonnull public final A ipAddressFor(@Nonnull final byte[] bytes) {
53         switch (bytes.length) {
54             case 4:
55                 return ipv4Address(ipv4AddressFor(bytes));
56             case 16:
57                 return ipv6Address(ipv6AddressFor(bytes));
58             default:
59                 throw new IllegalArgumentException("Invalid array length " + bytes.length);
60         }
61     }
62
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));
69         } else {
70             throw new IllegalArgumentException("Unhandled address " + addr);
71         }
72     }
73
74     @Nonnull public final InetAddress inetAddressFor(@Nonnull final A addr) {
75         final A4 v4 = maybeIpv4Address(addr);
76         if (v4 != null) {
77             return inet4AddressFor(v4);
78         }
79         final A6 v6 = maybeIpv6Address(addr);
80         Preconditions.checkArgument(v6 != null, "Address %s is neither IPv4 nor IPv6", addr);
81         return inet6AddressFor(v6);
82     }
83
84     @Nonnull public final Inet4Address inet4AddressFor(@Nonnull final A4 addr) {
85         try {
86             return (Inet4Address) InetAddress.getByAddress(ipv4AddressBytes(addr));
87         } catch (UnknownHostException e) {
88             throw new IllegalArgumentException("Invalid address " + addr, e);
89         }
90     }
91
92     @Nonnull public final Inet6Address inet6AddressFor(@Nonnull final A6 addr) {
93         try {
94             return (Inet6Address) InetAddress.getByAddress(ipv6AddressBytes(addr));
95         } catch (UnknownHostException e) {
96             throw new IllegalArgumentException("Invalid address " + addr, e);
97         }
98     }
99
100     /**
101      * Create an Ipv4Address by interpreting input bytes as an IPv4 address.
102      *
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
107      */
108     @Nonnull public final A4 ipv4AddressFor(@Nonnull final byte[] bytes) {
109         return address4Factory.newInstance(addressStringV4(bytes));
110     }
111
112     /**
113      * Create an Ipv4Address by interpreting an {@link Inet4Address}.
114      *
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
119      */
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());
124     }
125
126     @Nonnull public final A4 ipv4AddressFrom(@Nonnull final P4 prefix) {
127         return prefixToAddress(address4Factory, ipv4PrefixString(prefix));
128     }
129
130     @Nonnull public final byte[] ipv4AddressBytes(@Nonnull final A4 addr) {
131         /*
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.
134          */
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);
139         return bytes;
140     }
141
142     /**
143      * Create a /32 Ipv4Prefix by interpreting input bytes as an IPv4 address.
144      *
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
149      */
150     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] bytes) {
151         return prefix4Factory.newInstance(prefixStringV4(bytes));
152     }
153
154     /**
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>.
159      *
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
165      */
166     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] address, final int mask) {
167         return prefix4Factory.newInstance(prefixStringV4(address, mask));
168     }
169
170     @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] address, final int mask) {
171         if (mask == 0) {
172             // Easy case, reuse the template
173             return prefix4Factory.getTemplate();
174         }
175
176         return v4PrefixForShort(address, 0, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
177     }
178
179     @Nonnull public final P4 ipv4PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
180         if (mask == 0) {
181             // Easy case, reuse the template
182             return prefix4Factory.getTemplate();
183         }
184
185         return v4PrefixForShort(array, startOffset, (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1), mask);
186     }
187
188     /**
189      * Create a /32 Ipv4Prefix for an {@link Inet4Address}
190      *
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
195      */
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");
200     }
201
202     /**
203      * Create a Ipv4Prefix by combining the address with a mask. The address bytes are not masked.
204      *
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
210      */
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);
216     }
217
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");
221     }
222
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);
227     }
228
229     @Nonnull public final Entry<A4, Integer> splitIpv4Prefix(@Nonnull final P4 prefix) {
230         return splitPrefix(address4Factory, ipv4PrefixString(prefix));
231     }
232
233     @Nonnull public final byte[] ipv4PrefixToBytes(@Nonnull final P4 prefix) {
234         final String str = ipv4PrefixString(prefix);
235         final int slash = str.lastIndexOf('/');
236
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);
240         return bytes;
241     }
242
243     /**
244      * Create an Ipv6Address by interpreting input bytes as an IPv6 address.
245      *
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
250      */
251     @Nonnull public final A6 ipv6AddressFor(@Nonnull final byte[] bytes) {
252         return address6Factory.newInstance(addressStringV6(bytes));
253     }
254
255     /**
256      * Create an Ipv6Address by interpreting an {@link Inet6Address}.
257      *
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
262      */
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));
267     }
268
269     @Nonnull public final A6 ipv6AddressFrom(@Nonnull final P6 prefix) {
270         return prefixToAddress(address6Factory, ipv6PrefixString(prefix));
271     }
272
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);
278         return bytes;
279     }
280
281     /**
282      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv6 address.
283      *
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
288      */
289     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] bytes) {
290         return prefix6Factory.newInstance(addressStringV6(bytes) + "/128");
291     }
292
293     /**
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.
297      *
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
303      */
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);
307     }
308
309     @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] address, final int mask) {
310         return ipv6PrefixForShort(address, 0, mask);
311     }
312
313     @Nonnull public final P6 ipv6PrefixForShort(@Nonnull final byte[] array, final int startOffset, final int mask) {
314         if (mask == 0) {
315             // Easy case, reuse the template
316             return prefix6Factory.getTemplate();
317         }
318
319         Preconditions.checkArgument(mask > 0 && mask <= 128, "Invalid mask %s", mask);
320         final int size = (mask / Byte.SIZE) + ((mask % Byte.SIZE == 0) ? 0 : 1);
321
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);
326     }
327
328     /**
329      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv4 address.
330      *
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
335      */
336     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr) {
337         return prefix6Factory.newInstance(addressStringV6(addr) + "/128");
338     }
339
340     /**
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.
344      *
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
350      */
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);
356     }
357
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");
361     }
362
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);
367     }
368
369     @Nonnull public final Entry<A6, Integer> splitIpv6Prefix(@Nonnull final P6 prefix) {
370         return splitPrefix(address6Factory, ipv6PrefixString(prefix));
371     }
372
373     private static <T> T prefixToAddress(final StringValueObjectFactory<T> factory, final String str) {
374         return factory.newInstance(str.substring(0, str.lastIndexOf('/')));
375     }
376
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)));
381     }
382
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);
389         return bytes;
390     }
391
392     private static void appendIpv4String(final StringBuilder sb, final byte[] bytes) {
393         Preconditions.checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
394
395         sb.append(Byte.toUnsignedInt(bytes[0]));
396         for (int i = 1; i < INET4_LENGTH; ++i) {
397             sb.append('.');
398             sb.append(Byte.toUnsignedInt(bytes[i]));
399         }
400     }
401
402     private static String addressStringV4(final byte[] bytes) {
403         final StringBuilder sb = new StringBuilder(15);
404         appendIpv4String(sb, bytes);
405         return sb.toString();
406     }
407
408     private static String addressStringV6(final byte[] bytes) {
409         Preconditions.checkArgument(bytes.length == INET6_LENGTH, "IPv6 address length is 16 bytes");
410
411         try {
412             return addressStringV6(Inet6Address.getByAddress(bytes));
413         } catch (UnknownHostException e) {
414             throw new IllegalArgumentException(String.format("Invalid input %s", bytes), e);
415         }
416     }
417
418     private static String addressStringV6(final InetAddress addr) {
419         return InetAddresses.toAddrString(addr);
420     }
421
422     private static String prefixStringV4(final byte[] bytes) {
423         final StringBuilder sb = new StringBuilder(18);
424         appendIpv4String(sb, bytes);
425         sb.append("/32");
426         return sb.toString();
427     }
428
429     private static String prefixStringV4(final byte[] bytes, final int mask) {
430         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
431
432         final StringBuilder sb = new StringBuilder(18);
433         appendIpv4String(sb, bytes);
434         sb.append('/');
435         sb.append(mask);
436         return sb.toString();
437     }
438
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);
443         }
444
445         final StringBuilder sb = new StringBuilder(18);
446
447         // Add from address
448         sb.append(Byte.toUnsignedInt(array[startOffset]));
449         for (int i = 1; i < size; i++) {
450             sb.append('.');
451             sb.append(Byte.toUnsignedInt(array[startOffset + i]));
452         }
453
454         // Add zeros
455         for (int i = size; i < INET4_LENGTH; i++) {
456             sb.append(".0");
457         }
458
459         // Add mask
460         Preconditions.checkArgument(mask > 0 && mask <= 32, "Invalid mask %s", mask);
461         sb.append('/');
462         sb.append(mask);
463
464         return prefix4Factory.newInstance(sb.toString());
465     }
466 }