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