BUG-3363: code optimization and cleanup - Do not open-code array copy operations
[openflowplugin.git] / openflowplugin / src / main / java / org / opendaylight / openflowplugin / openflow / md / core / sal / convertor / IpConversionUtil.java
1 /*
2  * Copyright (c) 2015 Brocade, Communications Systems, Inc
3  * Copyright (c) 2015 Cisco Systems, Inc. and others.  All rights reserved.
4  *
5  * This program and the accompanying materials are made available under the
6  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
7  * and is available at http://www.eclipse.org/legal/epl-v10.html
8  */
9
10 package org.opendaylight.openflowplugin.openflow.md.core.sal.convertor;
11
12 import com.google.common.base.Preconditions;
13 import com.google.common.base.Splitter;
14 import com.google.common.collect.Iterators;
15 import com.google.common.net.InetAddresses;
16 import com.google.common.primitives.UnsignedBytes;
17 import java.net.Inet4Address;
18 import java.net.InetAddress;
19 import java.net.UnknownHostException;
20 import java.util.Arrays;
21 import java.util.Iterator;
22 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Address;
23 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv4Prefix;
24 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Address;
25 import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev100924.Ipv6Prefix;
26
27
28 /**
29  * Created by Martin Bobak <mbobak@cisco.com> on 5.3.2015.
30  * v6 routines added by Anton Ivanov on 14.6.2015
31  */
32 public final class IpConversionUtil {
33
34     public static final String PREFIX_SEPARATOR = "/";
35     public static final Splitter PREFIX_SPLITTER = Splitter.on('/');
36     private static final int INADDR4SZ = 4;
37     private static final int INADDR6SZ = 16;
38     private static final int INT16SZ = 2;
39
40     private IpConversionUtil() {
41         throw new UnsupportedOperationException("This class should not be instantiated.");
42     }
43
44     public static Iterator<String> splitToParts(final Ipv4Prefix ipv4Prefix) {
45         return PREFIX_SPLITTER.split(ipv4Prefix.getValue()).iterator();
46     }
47
48     public static Iterator<String> splitToParts(final Ipv4Address ipv4Address) {
49         /* Invalid (Ab)use of ip address as prefix!!! */
50         String [] tempPrefix = {ipv4Address.getValue(), "32"};
51         return Iterators.forArray(tempPrefix);
52     }
53
54     public static Iterator<String> splitToParts(final Ipv6Prefix ipv6Prefix) {
55         return PREFIX_SPLITTER.split(ipv6Prefix.getValue()).iterator();
56     }
57
58     public static Iterator<String> splitToParts(final Ipv6Address ipv6Address) {
59         /* Invalid (Ab)use of ip address as prefix!!! */
60         String [] tempPrefix = {ipv6Address.getValue(), "128"};
61         return Iterators.forArray(tempPrefix);
62     }
63
64
65     /* This forest of functions has a purpose:
66      *
67      * 1. There are multiple coding styles around the plugin, this is necessary in order to have
68      *   one mechanism to convert them all, one mechanism to find them...
69      * 2. I hope that one day yangtools will actually deliver code fit for purpose in a packet
70      *   processing application (presently it is not. When this happens, these can be optimized
71      *   for "side-load" of pre-vetted data. Example. IP Address (v4 or v6) is prevetted left of the
72      *   prefix. It should be loadable into Prefix without _RERUNNING_ 100ms+ of regexps. When (and if)
73      *   that happens, it will be a simple fix here without chasing it across the whole plugin.
74     */
75
76     public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address){
77         return new Ipv4Prefix(ipv4Address.getValue() + PREFIX_SEPARATOR + 32);
78     }
79
80     public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final String mask){
81         /*
82          * Ipv4Address has already validated the address part of the prefix,
83          * It is mandated to comply to the same regexp as the address
84          * There is absolutely no point rerunning additional checks vs this
85          * Note - there is no canonical form check here!!!
86          */
87         if (null != mask && !mask.isEmpty()) {
88             return new Ipv4Prefix(ipv4Address.getValue() + PREFIX_SEPARATOR + mask);
89         } else {
90             return new Ipv4Prefix(ipv4Address.getValue() + PREFIX_SEPARATOR + "32");
91         }
92     }
93
94     public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final int intmask){
95         return createPrefix(ipv4Address, String.valueOf(intmask));
96     }
97
98     public static Ipv4Prefix createPrefix(final Ipv4Address ipv4Address, final byte [] bytemask){
99         return createPrefix(ipv4Address, String.valueOf(countBits(bytemask)));
100     }
101
102     public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address){
103         return new Ipv6Prefix(ipv6Address.getValue() + PREFIX_SEPARATOR + 128);
104     }
105
106     public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final String mask){
107         /*
108          * Ipv6Address has already validated the address part of the prefix,
109          * It is mandated to comply to the same regexp as the address
110          * There is absolutely no point rerunning additional checks vs this
111          * Note - there is no canonical form check here!!!
112          */
113         if (null != mask && !mask.isEmpty()) {
114             return new Ipv6Prefix(ipv6Address.getValue() + PREFIX_SEPARATOR + mask);
115         } else {
116             return new Ipv6Prefix(ipv6Address.getValue() + PREFIX_SEPARATOR + "128");
117         }
118     }
119
120     public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final int intmask){
121         return createPrefix(ipv6Address, String.valueOf(intmask));
122     }
123
124     public static Ipv6Prefix createPrefix(final Ipv6Address ipv6Address, final byte [] bytemask){
125         /*
126          * Ipv4Address has already validated the address part of the prefix,
127          * It is mandated to comply to the same regexp as the address
128          * There is absolutely no point rerunning additional checks vs this
129          * Note - there is no canonical form check here!!!
130          */
131          return createPrefix(ipv6Address, String.valueOf(countBits(bytemask)));
132     }
133
134     public static Integer extractPrefix(final Ipv4Prefix ipv4Prefix) {
135         Iterator<String> addressParts = splitToParts(ipv4Prefix);
136         addressParts.next();
137         Integer retval = null;
138         if (addressParts.hasNext()) {
139             retval = Integer.parseInt(addressParts.next());
140         }
141         return retval;
142     }
143
144     public static Integer extractPrefix(final Ipv6Prefix ipv6Prefix) {
145         Iterator<String> addressParts = splitToParts(ipv6Prefix);
146         addressParts.next();
147         Integer retval = null;
148         if (addressParts.hasNext()) {
149             retval = Integer.parseInt(addressParts.next());
150         }
151         return retval;
152     }
153
154     public static Integer extractPrefix(final Ipv4Address ipv4Prefix) {
155         return 32;
156     }
157
158     public static Integer extractPrefix(final Ipv6Address ipv6Prefix) {
159         return 128;
160     }
161
162     /*
163      * BIG FAT WARNING!!!
164      * Read all of the following before you touch any v6 code or decide to
165      * optimize it by invoking a "simple" Guava call
166      *
167      * Java IPv6 is fundamentally broken and Google libraries do not fix it.
168      * 1. Java will allways implicitly rewrite v4 mapped into v6 as a v4 address
169      *      and there is absolutely no way to override this behaviour
170      * 2. Guava libraries cannot parse non-canonical IPv6. They will throw an
171      *      exception. Even if they did, they re-use the same broken java code
172      *      underneath.
173      *
174      * This is why we have to parse v6 by ourselves.
175      *
176      * The following conversion code is based on inet_cidr_pton_ipv6 in NetBSD
177      *
178      * The original BSD code is licensed under standard BSD license. While we
179      * are not obliged to provide an attribution, credit where credit is due.
180      * As far as why it is similar to Sun's sun.net.util please ask Sun why
181      * their code has the same variable names, comments and code flow.
182      *
183      */
184
185
186      /**
187      * Convert Ipv6Address object to a valid Canonical v6 address in byte format
188      *
189      * @param ipv6Address - v6 Address object
190      * @return - byte array of size 16. Last byte contains netmask
191      */
192
193
194     public static byte[] canonicalBinaryV6Address(final Ipv6Address ipv6Address) {
195         /*
196          * Do not modify this routine to take direct strings input!!!
197          * Key checks have been removed based on the assumption that
198          * the input is validated via regexps in Ipv6Prefix()
199          */
200
201         String [] address =  (ipv6Address.getValue()).split("%");
202
203         int colonp;
204         char ch;
205         boolean saw_xdigit;
206
207         /* Isn't it fun - the above variable names are the same in BSD and Sun sources */
208
209         int val;
210
211         char[] src = address[0].toCharArray();
212
213         byte[] dst = new byte[INADDR6SZ];
214
215         int src_length = src.length;
216
217         colonp = -1;
218         int i = 0, j = 0;
219
220         /* Leading :: requires some special handling. */
221
222         /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
223          * We will derive our code from BSD. Shakespear always sounds better
224          * in original Clingon. So does Dilbert.
225          */
226
227         if (src[i] == ':') {
228             Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
229         }
230
231         int curtok = i;
232         saw_xdigit = false;
233
234
235         val = 0;
236         while (i < src_length) {
237             ch = src[i++];
238             int chval = Character.digit(ch, 16);
239
240             /* Business as usual - ipv6 address digit.
241              * We can remove all checks from the original BSD code because
242              * the regexp has already verified that we are not being fed
243              * anything bigger than 0xffff between the separators.
244              */
245
246             if (chval != -1) {
247                 val <<= 4;
248                 val |= chval;
249                 saw_xdigit = true;
250                 continue;
251             }
252
253             /* v6 separator */
254
255             if (ch == ':') {
256                 curtok = i;
257                 if (!saw_xdigit) {
258                     /* no need to check separator position validity - regexp does that */
259                     colonp = j;
260                     continue;
261                 }
262
263                 /* removed overrun check - the regexp checks for valid data */
264
265                 dst[j++] = (byte) ((val >>> 8) & 0xff);
266                 dst[j++] = (byte) (val & 0xff);
267                 saw_xdigit = false;
268                 val = 0;
269                 continue;
270             }
271
272             /* frankenstein - v4 attached to v6, mixed notation */
273
274             if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {
275
276                 /* this has passed the regexp so it is fairly safe to parse it
277                  * straight away. As v4 addresses do not suffer from the same
278                  * defficiencies as the java v6 implementation we can invoke it
279                  * straight away and be done with it
280                  */
281
282                 Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");
283
284                 InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length));
285
286                 Preconditions.checkArgument(_inet_form instanceof Inet4Address);
287                 System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
288                 j += INADDR4SZ;
289
290                 saw_xdigit = false;
291                 break;
292             }
293             /* removed parser exit on invalid char - no need to do it, regexp checks it */
294         }
295         if (saw_xdigit) {
296             Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
297             dst[j++] = (byte) ((val >> 8) & 0xff);
298             dst[j++] = (byte) (val & 0xff);
299         }
300
301         if (colonp != -1) {
302             int n = j - colonp;
303
304             Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
305             for (i = 1; i <= n; i++) {
306                 dst[INADDR6SZ - i] = dst[colonp + n - i];
307                 dst[colonp + n - i] = 0;
308             }
309             j = INADDR6SZ;
310         }
311
312         Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
313
314         return dst;
315     }
316
317     public static String byteArrayV6AddressToString (final byte [] _binary_form) throws UnknownHostException{
318         /* DO NOT DIY!!! - InetAddresses will actually print correct canonical
319          * zero compressed form.
320          */
321         return InetAddresses.toAddrString(InetAddress.getByAddress(_binary_form));
322     }
323
324     private static int nextNibble(final int mask) {
325         if (mask <= 0) {
326             return 0;
327         }
328         if (mask > 8) {
329             return 0xff;
330         }
331         return 0xff << (8 - mask);
332     }
333
334     /**
335      * Convert Ipv6Prefix object to a valid Canonical v6 prefix in byte format
336      *
337      * @param ipv6Prefix - v6 prefix object
338      * @return - byte array of size 16 + 1. Last byte contains netmask
339      */
340     public static byte[] canonicalBinaryV6Prefix(final Ipv6Prefix ipv6Prefix) {
341         /*
342          * Do not modify this routine to take direct strings input!!!
343          * Key checks have been removed based on the assumption that
344          * the input is validated via regexps in Ipv6Prefix()
345          */
346
347         int mask = 128;
348
349         String [] address = null;
350
351         boolean valid = true;
352
353         address =  (ipv6Prefix.getValue()).split("/");
354         try {
355             mask = Integer.parseInt(address[1]);
356             if (mask > 128) {
357                 valid = false;
358             }
359         } catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
360             valid = false;
361         }
362
363         Preconditions.checkArgument(valid, "Supplied netmask in %s is invalid", ipv6Prefix.getValue());
364
365
366         int colonp;
367         char ch;
368         boolean saw_xdigit;
369
370         /* Isn't it fun - the above variable names are the same in BSD and Sun sources */
371
372         int val;
373
374         char[] src = address[0].toCharArray();
375
376         byte[] dst = new byte[INADDR6SZ + 1];
377
378         int m = mask;
379
380         int src_length = src.length;
381
382         colonp = -1;
383         int i = 0, j = 0;
384
385         /* Leading :: requires some special handling. */
386
387         /* Isn't it fun - the above comment is again the same in BSD and Sun sources,
388          * We will derive our code from BSD. Shakespear always sounds better
389          * in original Clingon. So does Dilbert.
390          */
391
392         if (src[i] == ':') {
393             Preconditions.checkArgument(src[++i] == ':', "Invalid v6 address");
394         }
395
396         int curtok = i;
397         saw_xdigit = false;
398
399
400         val = 0;
401         while (i < src_length) {
402             ch = src[i++];
403             int chval = Character.digit(ch, 16);
404
405             /* Business as usual - ipv6 address digit.
406              * We can remove all checks from the original BSD code because
407              * the regexp has already verified that we are not being fed
408              * anything bigger than 0xffff between the separators.
409              */
410
411             if (chval != -1) {
412                 val <<= 4;
413                 val |= chval;
414                 saw_xdigit = true;
415                 continue;
416             }
417
418             /* v6 separator */
419
420             if (ch == ':') {
421                 curtok = i;
422                 if (!saw_xdigit) {
423                     /* no need to check separator position validity - regexp does that */
424                     colonp = j;
425                     continue;
426                 }
427
428                 /* removed overrun check - the regexp checks for valid data */
429
430                 saw_xdigit = false;
431
432                 if (m < 0) {
433                     /* stop parsing if we are past the mask */
434                     break;
435                 }
436
437                 dst[j] = (byte) ((val >> 8) & nextNibble(m)); j++; m = m - 8;
438
439                 if (m < 0) {
440                     /* stop parsing if we are past the mask */
441                     break;
442                 }
443
444                 dst[j] = (byte) (val & nextNibble(m)); j++; m = m - 8;
445
446                 val = 0;
447                 continue;
448             }
449
450             /* frankenstein - v4 attached to v6, mixed notation */
451
452             if (ch == '.' && ((j + INADDR4SZ) <= INADDR6SZ)) {
453
454                 /* this has passed the regexp so it is fairly safe to parse it
455                  * straight away. As v4 addresses do not suffer from the same
456                  * defficiencies as the java v6 implementation we can invoke it
457                  * straight away and be done with it
458                  */
459
460                 Preconditions.checkArgument(j != (INADDR6SZ - INADDR4SZ - 1), "Invalid v4 in v6 mapping");
461
462                 InetAddress _inet_form = InetAddresses.forString(address[0].substring(curtok, src_length));
463
464                 Preconditions.checkArgument(_inet_form instanceof Inet4Address);
465                 System.arraycopy(_inet_form.getAddress(), 0, dst, j, INADDR4SZ);
466                 j +=  INADDR4SZ;
467
468                 saw_xdigit = false;
469                 break;
470             }
471             /* removed parser exit on ivalid char - no need to do it, regexp checks it */
472         }
473         if (saw_xdigit) {
474             Preconditions.checkArgument(j + INT16SZ <= INADDR6SZ, "Overrun in v6 parsing, should not occur");
475             dst[j] = (byte) ((val >> 8) & nextNibble(m)) ; j++; m = m - 8;
476             dst[j] = (byte) (val & nextNibble(m)); j++; m = m - 8;
477         }
478
479         if ((j < INADDR6SZ) && (m < 0)) {
480             /* past the mask */
481             for (i = j; i < INADDR6SZ; i++) {
482                 dst[i] = 0;
483             }
484         } else {
485             /* normal parsing */
486             if (colonp != -1) {
487                 int n = j - colonp;
488
489                 Preconditions.checkArgument(j != INADDR6SZ, "Overrun in v6 parsing, should not occur");
490                 for (i = 1; i <= n; i++) {
491                     dst[INADDR6SZ - i] = dst[colonp + n - i];
492                     dst[colonp + n - i] = 0;
493                 }
494                 j = INADDR6SZ;
495             }
496             Preconditions.checkArgument(j == INADDR6SZ, "Overrun in v6 parsing, should not occur");
497         }
498
499         dst[INADDR6SZ] = (byte) mask;
500         return dst;
501     }
502
503     /**
504      * Print a v6 prefix in byte array + 1 notation
505      *
506      * @param _binary_form - prefix, in byte [] form, last byte is netmask
507      */
508     public static String byteArrayV6PrefixToString(final byte [] _binary_form) throws UnknownHostException {
509         /* NO DIY!!! - InetAddresses will actually print correct canonical
510          * zero compressed form
511          */
512         StringBuilder sb = new StringBuilder();
513         /* Yang RFC specifies that the normalized form is RFC 5952, note - java
514          * core type is not RFC compliant, guava is.
515          */
516         sb.append(
517             InetAddresses.toAddrString(
518                 InetAddress.getByAddress(
519                     Arrays.copyOfRange(_binary_form, 0, INADDR6SZ)
520                 )
521             )
522         );
523         sb.append('/');
524         sb.append(_binary_form[INADDR6SZ] & 0xff);
525         return sb.toString();
526     }
527
528
529      /**
530      * Canonicalize a v6 prefix while in binary form
531      *
532      * @param _prefix - prefix, in byte [] form
533      * @param mask - mask - number of bits
534      */
535     public static void canonicalizeIpv6Prefix(final byte [] _prefix, int mask) {
536
537         for (int i=0; i < INADDR6SZ; i++) {
538             _prefix[i] = (byte) (_prefix[i] & nextNibble(mask));
539             mask = mask - 8;
540         }
541     }
542
543     public static byte[] convertIpv6PrefixToByteArray(int prefix) {
544         byte[] mask = new byte[16];
545         for (int count = 0; count < 16; count++) {
546             mask[count] = (byte) nextNibble(prefix);
547             prefix = prefix - 8;
548         }
549         return mask;
550     }
551
552     public static Ipv6Address extractIpv6Address(final Ipv6Prefix ipv6Prefix) {
553         Iterator<String> addressParts = PREFIX_SPLITTER.split(ipv6Prefix.getValue()).iterator();
554         return new Ipv6Address(addressParts.next());
555     }
556
557     public static Integer extractIpv6Prefix(final Ipv6Prefix ipv6Prefix) {
558         Iterator<String> addressParts = PREFIX_SPLITTER.split(ipv6Prefix.getValue()).iterator();
559         addressParts.next();
560
561         Integer prefix = null;
562         if (addressParts.hasNext()) {
563             prefix = Integer.parseInt(addressParts.next());
564         }
565         return prefix;
566     }
567
568     public static int countBits(final byte[] mask) {
569         int netmask = 0;
570         for (byte b : mask) {
571             netmask += Integer.bitCount(UnsignedBytes.toInt(b));
572         }
573         return netmask;
574     }
575 }