Add prefix-to-bytes conversion
[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 com.google.common.primitives.UnsignedBytes;
14 import java.net.Inet4Address;
15 import java.net.Inet6Address;
16 import java.net.InetAddress;
17 import java.net.UnknownHostException;
18 import java.util.AbstractMap.SimpleImmutableEntry;
19 import java.util.Map.Entry;
20 import javax.annotation.Nonnull;
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     protected abstract A ipv4Address(A4 addr);
44     protected abstract A ipv6Address(A6 addr);
45     protected abstract String ipv4AddressString(A4 addr);
46     protected abstract String ipv6AddressString(A6 addr);
47     protected abstract String ipv4PrefixString(P4 prefix);
48     protected abstract String ipv6PrefixString(P6 prefix);
49
50     @Nonnull public final A ipAddressFor(@Nonnull final byte[] bytes) {
51         switch (bytes.length) {
52             case 4:
53                 return ipv4Address(ipv4AddressFor(bytes));
54             case 16:
55                 return ipv6Address(ipv6AddressFor(bytes));
56             default:
57                 throw new IllegalArgumentException("Invalid array length " + bytes.length);
58         }
59     }
60
61     @Nonnull public final A ipAddressFor(@Nonnull final InetAddress addr) {
62         Preconditions.checkNotNull(addr, "Address must not be null");
63         if (addr instanceof Inet4Address) {
64             return ipv4Address(ipv4AddressFor(addr));
65         } else if (addr instanceof Inet6Address) {
66             return ipv6Address(ipv6AddressFor(addr));
67         } else {
68             throw new IllegalArgumentException("Unhandled address " + addr);
69         }
70     }
71
72     /**
73      * Create an Ipv4Address by interpreting input bytes as an IPv4 address.
74      *
75      * @param bytes 4-byte array
76      * @return An Ipv4Address object
77      * @throws IllegalArgumentException if bytes has length different from 4
78      * @throws NullPointerException if bytes is null
79      */
80     @Nonnull public final A4 ipv4AddressFor(@Nonnull final byte[] bytes) {
81         return address4Factory.newInstance(addressStringV4(bytes));
82     }
83
84     /**
85      * Create an Ipv4Address by interpreting an {@link Inet4Address}.
86      *
87      * @param addr An {@link Inet4Address}
88      * @return An Ipv4Address object
89      * @throws IllegalArgumentException if addr is not an {@link Inet4Address}
90      * @throws NullPointerException if addr is null
91      */
92     @Nonnull public final A4 ipv4AddressFor(@Nonnull final InetAddress addr) {
93         Preconditions.checkNotNull(addr, "Address must not be null");
94         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
95         return address4Factory.newInstance(addr.getHostAddress());
96     }
97
98     @Nonnull public final A4 ipv4AddressFrom(@Nonnull final P4 prefix) {
99         return prefixToAddress(address4Factory, ipv4PrefixString(prefix));
100     }
101
102     @Nonnull public final byte[] ipv4AddressBytes(@Nonnull final A4 addr) {
103         /*
104          * This implementation relies heavily on the input string having been validated to comply with
105          * the Ipv4Address pattern, which may include a zone index.
106          */
107         final String str = ipv4AddressString(addr);
108         final byte[] bytes = new byte[INET4_LENGTH];
109         final int percent = str.indexOf('%');
110         fillIpv4Bytes(bytes, str, percent == -1 ? str.length() : percent);
111         return bytes;
112     }
113
114     /**
115      * Create a /32 Ipv4Prefix by interpreting input bytes as an IPv4 address.
116      *
117      * @param bytes four-byte array
118      * @return An Ipv4Prefix object
119      * @throws IllegalArgumentException if bytes has length different from 4
120      * @throws NullPointerException if bytes is null
121      */
122     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] bytes) {
123         return prefix4Factory.newInstance(prefixStringV4(bytes));
124     }
125
126     /**
127      * Create a Ipv4Prefix by combining the address with a mask. The address
128      * bytes are interpreted as an address and the specified mask is concatenated to
129      * it. The address bytes are not masked, hence input <code>address = { 1, 2, 3, 4 }</code>
130      * and <code>mask=24</code> will result in <code>1.2.3.4/24</code>.
131      *
132      * @param address Input address as a 4-byte array
133      * @param mask Prefix mask
134      * @return An Ipv4Prefix object
135      * @throws IllegalArgumentException if bytes has length different from 4 or if mask is not in range 0-32
136      * @throws NullPointerException if bytes is null
137      */
138     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final byte[] address, final int mask) {
139         return prefix4Factory.newInstance(prefixStringV4(address, mask));
140     }
141
142     /**
143      * Create a /32 Ipv4Prefix for an {@link Inet4Address}
144      *
145      * @param addr An {@link Inet4Address}
146      * @return An Ipv4Prefix object
147      * @throws IllegalArgumentException if addr is not an Inet4Address
148      * @throws NullPointerException if adds is null
149      */
150     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr) {
151         Preconditions.checkNotNull(addr, "Address must not be null");
152         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
153         return prefix4Factory.newInstance(addr.getHostAddress() + "/32");
154     }
155
156     /**
157      * Create a Ipv4Prefix by combining the address with a mask. The address bytes are not masked.
158      *
159      * @param addr An {@link Inet4Address}
160      * @param mask Prefix mask
161      * @return An Ipv4Prefix object
162      * @throws IllegalArgumentException if addr is not an Inet4Address or if mask is not in range 0-32
163      * @throws NullPointerException if addr is null
164      */
165     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final InetAddress addr, final int mask) {
166         Preconditions.checkNotNull(addr, "Address must not be null");
167         Preconditions.checkArgument(addr instanceof Inet4Address, "Address has to be an Inet4Address");
168         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
169         return prefix4Factory.newInstance(addr.getHostAddress() + '/' + mask);
170     }
171
172     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr) {
173         Preconditions.checkNotNull(addr, "Address must not be null");
174         return prefix4Factory.newInstance(ipv4AddressString(addr) + "/32");
175     }
176
177     @Nonnull public final P4 ipv4PrefixFor(@Nonnull final A4 addr, final int mask) {
178         Preconditions.checkNotNull(addr, "Address must not be null");
179         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
180         return prefix4Factory.newInstance(ipv4AddressString(addr) + '/' + mask);
181     }
182
183     @Nonnull public final Entry<A4, Integer> splitIpv4Prefix(@Nonnull final P4 prefix) {
184         return splitPrefix(address4Factory, ipv4PrefixString(prefix));
185     }
186
187     @Nonnull public final byte[] ipv4PrefixToBytes(@Nonnull final P4 prefix) {
188         final String str = ipv4PrefixString(prefix);
189         final int slash = str.lastIndexOf('/');
190
191         final byte[] bytes = new byte[INET4_LENGTH + 1];
192         fillIpv4Bytes(bytes, str, slash);
193         bytes[INET4_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
194         return bytes;
195     }
196
197     private static void fillIpv4Bytes(final byte[] bytes, final String str, final int limit) {
198         int out = 0;
199         int val = 0;
200         for (int i = 0; i < limit; ++i) {
201             final char c = str.charAt(i);
202             if (c == '.') {
203                 bytes[out++] = (byte) val;
204                 val = 0;
205             } else {
206                 val = 10 * val + (c - '0');
207             }
208         }
209
210         bytes[out] = (byte) val;
211     }
212
213     /**
214      * Create an Ipv6Address by interpreting input bytes as an IPv6 address.
215      *
216      * @param bytes 16-byte array
217      * @return An Ipv6Address object
218      * @throws IllegalArgumentException if bytes has length different from 16
219      * @throws NullPointerException if bytes is null
220      */
221     @Nonnull public final A6 ipv6AddressFor(@Nonnull final byte[] bytes) {
222         return address6Factory.newInstance(addressStringV6(bytes));
223     }
224
225     /**
226      * Create an Ipv6Address by interpreting an {@link Inet6Address}.
227      *
228      * @param addr An {@link Inet6Address}
229      * @return An Ipv6Address object
230      * @throws IllegalArgumentException if addr is not an {@link Inet6Address}
231      * @throws NullPointerException if addr is null
232      */
233     @Nonnull public final A6 ipv6AddressFor(@Nonnull final InetAddress addr) {
234         Preconditions.checkNotNull(addr, "Address must not be null");
235         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
236         return address6Factory.newInstance(addressStringV6(addr));
237     }
238
239     @Nonnull public final A6 ipv6AddressFrom(@Nonnull final P6 prefix) {
240         return prefixToAddress(address6Factory, ipv6PrefixString(prefix));
241     }
242
243     @Nonnull public final byte[] ipv6AddressBytes(@Nonnull final A6 addr) {
244         String str = ipv6AddressString(addr);
245         final int percent = str.indexOf('%');
246         if (percent != -1) {
247             str = str.substring(0, percent);
248         }
249
250         return InetAddresses.forString(str).getAddress();
251     }
252
253     /**
254      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv6 address.
255      *
256      * @param bytes four-byte array
257      * @return An Ipv6Prefix object
258      * @throws IllegalArgumentException if bytes has length different from 16
259      * @throws NullPointerException if bytes is null
260      */
261     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] bytes) {
262         return prefix6Factory.newInstance(addressStringV6(bytes) + "/128");
263     }
264
265     /**
266      * Create a Ipv6Prefix by combining the address with a mask. The address
267      * bytes are interpreted as an address and the specified mask is concatenated to
268      * it. The address bytes are not masked.
269      *
270      * @param address Input address as a 4-byte array
271      * @param mask Prefix mask
272      * @return An Ipv6Prefix object
273      * @throws IllegalArgumentException if bytes has length different from 16 or if mask is not in range 0-128
274      * @throws NullPointerException if bytes is null
275      */
276     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final byte[] address, final int mask) {
277         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
278         return prefix6Factory.newInstance(addressStringV6(address) + '/' + mask);
279     }
280
281     /**
282      * Create a /128 Ipv6Prefix by interpreting input bytes as an IPv4 address.
283      *
284      * @param addr an {@link Inet6Address}
285      * @return An Ipv6Prefix object
286      * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
287      * @throws NullPointerException if addr is null
288      */
289     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr) {
290         return prefix6Factory.newInstance(addressStringV6(addr) + "/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 addr Input address
299      * @param mask Prefix mask
300      * @return An Ipv6Prefix object
301      * @throws IllegalArgumentException if addr is not an Inet6Address or if mask is not in range 0-128
302      * @throws NullPointerException if addr is null
303      */
304     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final InetAddress addr, final int mask) {
305         Preconditions.checkNotNull(addr, "Address must not be null");
306         Preconditions.checkArgument(addr instanceof Inet6Address, "Address has to be an Inet6Address");
307         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
308         return prefix6Factory.newInstance(addressStringV6(addr) + '/' + mask);
309     }
310
311     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr) {
312         Preconditions.checkNotNull(addr, "Address must not be null");
313         return prefix6Factory.newInstance(ipv6AddressString(addr) + "/128");
314     }
315
316     @Nonnull public final P6 ipv6PrefixFor(@Nonnull final A6 addr, final int mask) {
317         Preconditions.checkNotNull(addr, "Address must not be null");
318         Preconditions.checkArgument(mask >= 0 && mask <= 128, "Invalid mask %s", mask);
319         return prefix6Factory.newInstance(ipv6AddressString(addr) + '/' + mask);
320     }
321
322     @Nonnull public final Entry<A6, Integer> splitIpv6Prefix(@Nonnull final P6 prefix) {
323         return splitPrefix(address6Factory, ipv6PrefixString(prefix));
324     }
325
326     private static <T> T prefixToAddress(final StringValueObjectFactory<T> factory, final String str) {
327         return factory.newInstance(str.substring(0, str.lastIndexOf('/')));
328     }
329
330     private static <T> Entry<T, Integer> splitPrefix(final StringValueObjectFactory<T> factory, final String str) {
331         final int slash = str.lastIndexOf('/');
332         return new SimpleImmutableEntry<>(factory.newInstance(str.substring(0, slash)),
333                 Integer.valueOf(str.substring(slash + 1)));
334     }
335
336     @Nonnull public final byte[] ipv6PrefixToBytes(@Nonnull final P6 prefix) {
337         final String str = ipv6PrefixString(prefix);
338         final int slash = str.lastIndexOf('/');
339
340         final byte[] bytes = new byte[INET6_LENGTH + 1];
341         System.arraycopy(InetAddresses.forString(str.substring(0, slash)).getAddress(), 0, bytes, 0, INET6_LENGTH);
342         bytes[INET6_LENGTH] = (byte)Integer.parseInt(str.substring(slash + 1), 10);
343         return bytes;
344     }
345
346     private static void appendIpv4String(final StringBuilder sb, final byte[] bytes) {
347         Preconditions.checkArgument(bytes.length == INET4_LENGTH, "IPv4 address length is 4 bytes");
348
349         sb.append(UnsignedBytes.toInt(bytes[0]));
350         for (int i = 1; i < INET4_LENGTH; ++i) {
351             sb.append('.');
352             sb.append(UnsignedBytes.toInt(bytes[i]));
353         }
354     }
355
356     private static String addressStringV4(final byte[] bytes) {
357         final StringBuilder sb = new StringBuilder(15);
358         appendIpv4String(sb, bytes);
359         return sb.toString();
360     }
361
362     private static String addressStringV6(final byte[] bytes) {
363         Preconditions.checkArgument(bytes.length == INET6_LENGTH, "IPv6 address length is 16 bytes");
364
365         try {
366             return addressStringV6(Inet6Address.getByAddress(bytes));
367         } catch (UnknownHostException e) {
368             throw new IllegalArgumentException(String.format("Invalid input %s", bytes), e);
369         }
370     }
371
372     private static String addressStringV6(final InetAddress addr) {
373         return InetAddresses.toAddrString(addr);
374     }
375
376     private static String prefixStringV4(final byte[] bytes) {
377         final StringBuilder sb = new StringBuilder(18);
378         appendIpv4String(sb, bytes);
379         sb.append("/32");
380         return sb.toString();
381     }
382
383     private static String prefixStringV4(final byte[] bytes, final int mask) {
384         Preconditions.checkArgument(mask >= 0 && mask <= 32, "Invalid mask %s", mask);
385
386         final StringBuilder sb = new StringBuilder(18);
387         appendIpv4String(sb, bytes);
388         sb.append('/');
389         sb.append(mask);
390         return sb.toString();
391     }
392 }