001 /*
002 * Copyright (C) 2008 The Guava Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017 package com.google.common.net;
018
019 import com.google.common.annotations.Beta;
020 import com.google.common.annotations.VisibleForTesting;
021 import com.google.common.base.Preconditions;
022 import com.google.common.io.ByteStreams;
023 import com.google.common.primitives.Ints;
024
025 import java.net.Inet4Address;
026 import java.net.Inet6Address;
027 import java.net.InetAddress;
028 import java.net.UnknownHostException;
029 import java.nio.ByteBuffer;
030 import java.util.Arrays;
031
032 import javax.annotation.Nullable;
033
034 /**
035 * Static utility methods pertaining to {@link InetAddress} instances.
036 *
037 * <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the
038 * methods of this class never cause DNS services to be accessed. For
039 * this reason, you should prefer these methods as much as possible over
040 * their JDK equivalents whenever you are expecting to handle only
041 * IP address string literals -- there is no blocking DNS penalty for a
042 * malformed string.
043 *
044 * <p>This class hooks into the {@code sun.net.util.IPAddressUtil} class
045 * to make use of the {@code textToNumericFormatV4} and
046 * {@code textToNumericFormatV6} methods directly as a means to avoid
047 * accidentally traversing all nameservices (it can be vitally important
048 * to avoid, say, blocking on DNS at times).
049 *
050 * <p>When dealing with {@link Inet4Address} and {@link Inet6Address}
051 * objects as byte arrays (vis. {@code InetAddress.getAddress()}) they
052 * are 4 and 16 bytes in length, respectively, and represent the address
053 * in network byte order.
054 *
055 * <p>Examples of IP addresses and their byte representations:
056 * <ul>
057 * <li>The IPv4 loopback address, {@code "127.0.0.1"}.<br/>
058 * {@code 7f 00 00 01}
059 *
060 * <li>The IPv6 loopback address, {@code "::1"}.<br/>
061 * {@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01}
062 *
063 * <li>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}),
064 * {@code "2001:db8::1"}.<br/>
065 * {@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01}
066 *
067 * <li>An IPv6 "IPv4 compatible" (or "compat") address,
068 * {@code "::192.168.0.1"}.<br/>
069 * {@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01}
070 *
071 * <li>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.<br/>
072 * {@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01}
073 * </ul>
074 *
075 * <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed
076 * use in Java.
077 * <br><br>
078 * "IPv4 mapped" addresses were originally a representation of IPv4
079 * addresses for use on an IPv6 socket that could receive both IPv4
080 * and IPv6 connections (by disabling the {@code IPV6_V6ONLY} socket
081 * option on an IPv6 socket). Yes, it's confusing. Nevertheless,
082 * these "mapped" addresses were never supposed to be seen on the
083 * wire. That assumption was dropped, some say mistakenly, in later
084 * RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler.
085 *
086 * <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire
087 * format of a "mapped" address, as shown above, and transmit it in an
088 * IPv6 packet header. However, Java's InetAddress creation methods
089 * appear to adhere doggedly to the original intent of the "mapped"
090 * address: all "mapped" addresses return {@link Inet4Address} objects.
091 *
092 * <p>For added safety, it is common for IPv6 network operators to filter
093 * all packets where either the source or destination address appears to
094 * be a "compat" or "mapped" address. Filtering suggestions usually
095 * recommend discarding any packets with source or destination addresses
096 * in the invalid range {@code ::/3}, which includes both of these bizarre
097 * address formats. For more information on "bogons", including lists
098 * of IPv6 bogon space, see:
099 *
100 * <ul>
101 * <li><a target="_parent"
102 * href="http://en.wikipedia.org/wiki/Bogon_filtering"
103 * >http://en.wikipedia.org/wiki/Bogon_filtering</a>
104 * <li><a target="_parent"
105 * href="http://www.cymru.com/Bogons/ipv6.txt"
106 * >http://www.cymru.com/Bogons/ipv6.txt</a>
107 * <li><a target="_parent"
108 * href="http://www.cymru.com/Bogons/v6bogon.html"
109 * >http://www.cymru.com/Bogons/v6bogon.html</a>
110 * <li><a target="_parent"
111 * href="http://www.space.net/~gert/RIPE/ipv6-filters.html"
112 * >http://www.space.net/~gert/RIPE/ipv6-filters.html</a>
113 * </ul>
114 *
115 * @author Erik Kline
116 * @since 5
117 */
118 @Beta
119 public final class InetAddresses {
120 private static final int IPV4_PART_COUNT = 4;
121 private static final int IPV6_PART_COUNT = 8;
122 private static final Inet4Address LOOPBACK4 =
123 (Inet4Address) forString("127.0.0.1");
124 private static final Inet4Address ANY4 =
125 (Inet4Address) forString("0.0.0.0");
126
127 private InetAddresses() {}
128
129 /**
130 * Returns an {@link Inet4Address}, given a byte array representation
131 * of the IPv4 address.
132 *
133 * @param bytes byte array representing an IPv4 address (should be
134 * of length 4).
135 * @return {@link Inet4Address} corresponding to the supplied byte
136 * array.
137 * @throws IllegalArgumentException if a valid {@link Inet4Address}
138 * can not be created.
139 */
140 private static Inet4Address getInet4Address(byte[] bytes) {
141 Preconditions.checkArgument(bytes.length == 4,
142 "Byte array has invalid length for an IPv4 address: %s != 4.",
143 bytes.length);
144
145 try {
146 InetAddress ipv4 = InetAddress.getByAddress(bytes);
147 if (!(ipv4 instanceof Inet4Address)) {
148 throw new UnknownHostException(
149 String.format("'%s' is not an IPv4 address.",
150 ipv4.getHostAddress()));
151 }
152
153 return (Inet4Address) ipv4;
154 } catch (UnknownHostException e) {
155
156 /*
157 * This really shouldn't happen in practice since all our byte
158 * sequences should be valid IP addresses.
159 *
160 * However {@link InetAddress#getByAddress} is documented as
161 * potentially throwing this "if IP address is of illegal length".
162 *
163 * This is mapped to IllegalArgumentException since, presumably,
164 * the argument triggered some bizarre processing bug.
165 */
166 throw new IllegalArgumentException(
167 String.format("Host address '%s' is not a valid IPv4 address.",
168 Arrays.toString(bytes)),
169 e);
170 }
171 }
172
173 /**
174 * Returns the {@link InetAddress} having the given string
175 * representation.
176 *
177 * <p>This deliberately avoids all nameservice lookups (e.g. no DNS).
178 *
179 * @param ipString {@code String} containing an IPv4 or IPv6 string literal,
180 * e.g. {@code "192.168.0.1"} or {@code "2001:db8::1"}
181 * @return {@link InetAddress} representing the argument
182 * @throws IllegalArgumentException if the argument is not a valid
183 * IP string literal
184 */
185 public static InetAddress forString(String ipString) {
186 byte[] addr = textToNumericFormatV4(ipString);
187 if (addr == null) {
188 // Scanning for IPv4 string literal failed; try IPv6.
189 addr = textToNumericFormatV6(ipString);
190 }
191
192 // The argument was malformed, i.e. not an IP string literal.
193 if (addr == null) {
194 throw new IllegalArgumentException(
195 String.format("'%s' is not an IP string literal.", ipString));
196 }
197
198 try {
199 return InetAddress.getByAddress(addr);
200 } catch (UnknownHostException e) {
201
202 /*
203 * This really shouldn't happen in practice since all our byte
204 * sequences should be valid IP addresses.
205 *
206 * However {@link InetAddress#getByAddress} is documented as
207 * potentially throwing this "if IP address is of illegal length".
208 *
209 * This is mapped to IllegalArgumentException since, presumably,
210 * the argument triggered some processing bug in either
211 * {@link IPAddressUtil#textToNumericFormatV4} or
212 * {@link IPAddressUtil#textToNumericFormatV6}.
213 */
214 throw new IllegalArgumentException(
215 String.format("'%s' is extremely broken.", ipString), e);
216 }
217 }
218
219 /**
220 * Returns {@code true} if the supplied string is a valid IP string
221 * literal, {@code false} otherwise.
222 *
223 * @param ipString {@code String} to evaluated as an IP string literal
224 * @return {@code true} if the argument is a valid IP string literal
225 */
226 public static boolean isInetAddress(String ipString) {
227 try {
228 forString(ipString);
229 return true;
230 } catch (IllegalArgumentException e) {
231 return false;
232 }
233 }
234
235 private static byte[] textToNumericFormatV4(String ipString) {
236 if (ipString.contains(":")) {
237 // For the special mapped address cases (e.g. "::ffff:192.0.2.1") passing
238 // InetAddress.getByAddress() the output of textToNumericFormatV6()
239 // below will "do the right thing", i.e. construct an Inet4Address.
240 return null;
241 }
242
243 String[] address = ipString.split("\\.");
244 if (address.length != IPV4_PART_COUNT) {
245 return null;
246 }
247
248 byte[] bytes = new byte[IPV4_PART_COUNT];
249 try {
250 for (int i = 0; i < bytes.length; i++) {
251 int piece = Integer.parseInt(address[i]);
252 if (piece < 0 || piece > 255) {
253 return null;
254 }
255
256 // No leading zeroes are allowed. See
257 // http://tools.ietf.org/html/draft-main-ipaddr-text-rep-00
258 // section 2.1 for discussion.
259
260 if (address[i].startsWith("0") && address[i].length() != 1) {
261 return null;
262 }
263 bytes[i] = (byte) piece;
264 }
265 } catch (NumberFormatException ex) {
266 return null;
267 }
268
269 return bytes;
270 }
271
272 private static byte[] textToNumericFormatV6(String ipString) {
273 if (!ipString.contains(":")) {
274 return null;
275 }
276 if (ipString.contains(":::")) {
277 return null;
278 }
279
280 if (ipString.contains(".")) {
281 ipString = convertDottedQuadToHex(ipString);
282 if (ipString == null) {
283 return null;
284 }
285 }
286
287 ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
288 // Keep a record of the number of parts specified above/before a "::"
289 // (partsHi), and below/after any "::" (partsLo).
290 int partsHi = 0;
291 int partsLo = 0;
292
293 String[] addressHalves = ipString.split("::", 2); // At most 1 "::".
294 // Parse parts above any "::", or the whole string if no "::" present.
295 if (!addressHalves[0].equals("")) {
296 String[] parts = addressHalves[0].split(":", IPV6_PART_COUNT);
297 try {
298 for (int i = 0; i < parts.length; i++) {
299 if (parts[i].equals("")) {
300 // No empty segments permitted.
301 return null;
302 }
303 int piece = Integer.parseInt(parts[i], 16);
304 rawBytes.putShort(2 * i, (short) piece);
305 }
306 partsHi = parts.length;
307 } catch (NumberFormatException ex) {
308 return null;
309 }
310 } else {
311 // A leading "::". At least one 16bit segment must be zero.
312 partsHi = 1;
313 }
314
315 // Parse parts below "::" (if any), into the tail end of the byte array,
316 // working backwards.
317 if (addressHalves.length > 1) {
318 if (!addressHalves[1].equals("")) {
319 String[] parts = addressHalves[1].split(":", IPV6_PART_COUNT);
320 try {
321 for (int i = 0; i < parts.length; i++) {
322 int partsIndex = parts.length - i - 1;
323 if (parts[partsIndex].equals("")) {
324 // No empty segments permitted.
325 return null;
326 }
327 int piece = Integer.parseInt(parts[partsIndex], 16);
328 int bytesIndex = 2 * (IPV6_PART_COUNT - i - 1);
329 rawBytes.putShort(bytesIndex, (short) piece);
330 }
331 partsLo = parts.length;
332 } catch (NumberFormatException ex) {
333 return null;
334 }
335 } else {
336 // A trailing "::". At least one 16bit segment must be zero.
337 partsLo = 1;
338 }
339 }
340
341 // Some extra sanity checks.
342 int totalParts = partsHi + partsLo;
343 if (totalParts > IPV6_PART_COUNT) {
344 return null;
345 }
346 if (addressHalves.length == 1 && totalParts != IPV6_PART_COUNT) {
347 // If no "::" shortening is used then all bytes must have been specified.
348 return null;
349 }
350
351 return rawBytes.array();
352 }
353
354 private static String convertDottedQuadToHex(String ipString) {
355 int lastColon = ipString.lastIndexOf(':');
356 String initialPart = ipString.substring(0, lastColon + 1);
357 String dottedQuad = ipString.substring(lastColon + 1);
358 byte[] quad = textToNumericFormatV4(dottedQuad);
359 if (quad == null) {
360 return null;
361 }
362 String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff));
363 String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff));
364 return initialPart + penultimate + ":" + ultimate;
365 }
366
367 /**
368 * Returns the string representation of an {@link InetAddress} suitable
369 * for inclusion in a URI.
370 *
371 * <p>For IPv4 addresses, this is identical to
372 * {@link InetAddress#getHostAddress()}, but for IPv6 addresses it
373 * surrounds this text with square brackets; for example
374 * {@code "[2001:db8::1]"}.
375 *
376 * <p>Per section 3.2.2 of
377 * <a target="_parent"
378 * href="http://tools.ietf.org/html/rfc3986#section-3.2.2"
379 * >http://tools.ietf.org/html/rfc3986</a>,
380 * a URI containing an IPv6 string literal is of the form
381 * {@code "http://[2001:db8::1]:8888/index.html"}.
382 *
383 * <p>Use of either {@link InetAddress#getHostAddress()} or this
384 * method is recommended over {@link InetAddress#toString()} when an
385 * IP address string literal is desired. This is because
386 * {@link InetAddress#toString()} prints the hostname and the IP
387 * address string joined by a "/".
388 *
389 * @param ip {@link InetAddress} to be converted to URI string literal
390 * @return {@code String} containing URI-safe string literal
391 */
392 public static String toUriString(InetAddress ip) {
393 if (ip instanceof Inet6Address) {
394 return "[" + ip.getHostAddress() + "]";
395 }
396 return ip.getHostAddress();
397 }
398
399 /**
400 * Returns an InetAddress representing the literal IPv4 or IPv6 host
401 * portion of a URL, encoded in the format specified by RFC 3986 section 3.2.2.
402 *
403 * <p>This function is similar to {@link InetAddresses#forString(String)},
404 * however, it requires that IPv6 addresses are surrounded by square brackets.
405 *
406 * <p>This function is the inverse of
407 * {@link InetAddresses#toUriString(java.net.InetAddress)}.
408 *
409 * @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
410 * @return an InetAddress representing the address in {@code hostAddr}
411 * @throws IllegalArgumentException if {@code hostAddr} is not a valid
412 * IPv4 address, or IPv6 address surrounded by square brackets
413 */
414 public static InetAddress forUriString(String hostAddr) {
415 Preconditions.checkNotNull(hostAddr);
416 Preconditions.checkArgument(hostAddr.length() > 0, "host string is empty");
417 InetAddress retval = null;
418
419 // IPv4 address?
420 try {
421 retval = forString(hostAddr);
422 if (retval instanceof Inet4Address) {
423 return retval;
424 }
425 } catch (IllegalArgumentException e) {
426 // Not a valid IP address, fall through.
427 }
428
429 // IPv6 address
430 if (!(hostAddr.startsWith("[") && hostAddr.endsWith("]"))) {
431 throw new IllegalArgumentException("Not a valid address: \"" + hostAddr + '"');
432 }
433
434 retval = forString(hostAddr.substring(1, hostAddr.length() - 1));
435 if (retval instanceof Inet6Address) {
436 return retval;
437 }
438
439 throw new IllegalArgumentException("Not a valid address: \"" + hostAddr + '"');
440 }
441
442 /**
443 * Returns {@code true} if the supplied string is a valid URI IP string
444 * literal, {@code false} otherwise.
445 *
446 * @param ipString {@code String} to evaluated as an IP URI host string literal
447 * @return {@code true} if the argument is a valid IP URI host
448 */
449 public static boolean isUriInetAddress(String ipString) {
450 try {
451 forUriString(ipString);
452 return true;
453 } catch (IllegalArgumentException e) {
454 return false;
455 }
456 }
457
458 /**
459 * Evaluates whether the argument is an IPv6 "compat" address.
460 *
461 * <p>An "IPv4 compatible", or "compat", address is one with 96 leading
462 * bits of zero, with the remaining 32 bits interpreted as an
463 * IPv4 address. These are conventionally represented in string
464 * literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is
465 * also considered an IPv4 compatible address (and equivalent to
466 * {@code "::192.168.0.1"}).
467 *
468 * <p>For more on IPv4 compatible addresses see section 2.5.5.1 of
469 * <a target="_parent"
470 * href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1"
471 * >http://tools.ietf.org/html/rfc4291</a>
472 *
473 * <p>NOTE: This method is different from
474 * {@link Inet6Address#isIPv4CompatibleAddress} in that it more
475 * correctly classifies {@code "::"} and {@code "::1"} as
476 * proper IPv6 addresses (which they are), NOT IPv4 compatible
477 * addresses (which they are generally NOT considered to be).
478 *
479 * @param ip {@link Inet6Address} to be examined for embedded IPv4
480 * compatible address format
481 * @return {@code true} if the argument is a valid "compat" address
482 */
483 public static boolean isCompatIPv4Address(Inet6Address ip) {
484 if (!ip.isIPv4CompatibleAddress()) {
485 return false;
486 }
487
488 byte[] bytes = ip.getAddress();
489 if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0)
490 && ((bytes[15] == 0) || (bytes[15] == 1))) {
491 return false;
492 }
493
494 return true;
495 }
496
497 /**
498 * Returns the IPv4 address embedded in an IPv4 compatible address.
499 *
500 * @param ip {@link Inet6Address} to be examined for an embedded
501 * IPv4 address
502 * @return {@link Inet4Address} of the embedded IPv4 address
503 * @throws IllegalArgumentException if the argument is not a valid
504 * IPv4 compatible address
505 */
506 public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
507 Preconditions.checkArgument(isCompatIPv4Address(ip),
508 "Address '%s' is not IPv4-compatible.", ip.getHostAddress());
509
510 return getInet4Address(copyOfRange(ip.getAddress(), 12, 16));
511 }
512
513 /**
514 * Evaluates whether the argument is a 6to4 address.
515 *
516 * <p>6to4 addresses begin with the {@code "2002::/16"} prefix.
517 * The next 32 bits are the IPv4 address of the host to which
518 * IPv6-in-IPv4 tunneled packets should be routed.
519 *
520 * <p>For more on 6to4 addresses see section 2 of
521 * <a target="_parent" href="http://tools.ietf.org/html/rfc3056#section-2"
522 * >http://tools.ietf.org/html/rfc3056</a>
523 *
524 * @param ip {@link Inet6Address} to be examined for 6to4 address
525 * format
526 * @return {@code true} if the argument is a 6to4 address
527 */
528 public static boolean is6to4Address(Inet6Address ip) {
529 byte[] bytes = ip.getAddress();
530 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
531 }
532
533 /**
534 * Returns the IPv4 address embedded in a 6to4 address.
535 *
536 * @param ip {@link Inet6Address} to be examined for embedded IPv4
537 * in 6to4 address.
538 * @return {@link Inet4Address} of embedded IPv4 in 6to4 address.
539 * @throws IllegalArgumentException if the argument is not a valid
540 * IPv6 6to4 address.
541 */
542 public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
543 Preconditions.checkArgument(is6to4Address(ip),
544 "Address '%s' is not a 6to4 address.", ip.getHostAddress());
545
546 return getInet4Address(copyOfRange(ip.getAddress(), 2, 6));
547 }
548
549 /**
550 * A simple data class to encapsulate the information to be found in a
551 * Teredo address.
552 *
553 * <p>All of the fields in this class are encoded in various portions
554 * of the IPv6 address as part of the protocol. More protocols details
555 * can be found at:
556 * <a target="_parent" href="http://en.wikipedia.org/wiki/Teredo_tunneling"
557 * >http://en.wikipedia.org/wiki/Teredo_tunneling</a>.
558 *
559 * <p>The RFC can be found here:
560 * <a target="_parent" href="http://tools.ietf.org/html/rfc4380"
561 * >http://tools.ietf.org/html/rfc4380</a>.
562 *
563 * @since 5
564 */
565 @Beta
566 public static final class TeredoInfo {
567 private final Inet4Address server;
568 private final Inet4Address client;
569 private final int port;
570 private final int flags;
571
572 /**
573 * Constructs a TeredoInfo instance.
574 *
575 * <p>Both server and client can be {@code null}, in which case the
576 * value {@code "0.0.0.0"} will be assumed.
577 *
578 * @throws IllegalArgumentException if either of the {@code port}
579 * or the {@code flags} arguments are out of range of an
580 * unsigned short
581 */
582 // TODO: why is this public?
583 public TeredoInfo(@Nullable Inet4Address server,
584 @Nullable Inet4Address client,
585 int port, int flags) {
586 Preconditions.checkArgument((port >= 0) && (port <= 0xffff),
587 "port '%d' is out of range (0 <= port <= 0xffff)", port);
588 Preconditions.checkArgument((flags >= 0) && (flags <= 0xffff),
589 "flags '%d' is out of range (0 <= flags <= 0xffff)", flags);
590
591 if (server != null) {
592 this.server = server;
593 } else {
594 this.server = ANY4;
595 }
596
597 if (client != null) {
598 this.client = client;
599 } else {
600 this.client = ANY4;
601 }
602
603 this.port = port;
604 this.flags = flags;
605 }
606
607 public Inet4Address getServer() {
608 return server;
609 }
610
611 public Inet4Address getClient() {
612 return client;
613 }
614
615 public int getPort() {
616 return port;
617 }
618
619 public int getFlags() {
620 return flags;
621 }
622 }
623
624 /**
625 * Evaluates whether the argument is a Teredo address.
626 *
627 * <p>Teredo addresses begin with the {@code "2001::/32"} prefix.
628 *
629 * @param ip {@link Inet6Address} to be examined for Teredo address
630 * format.
631 * @return {@code true} if the argument is a Teredo address
632 */
633 public static boolean isTeredoAddress(Inet6Address ip) {
634 byte[] bytes = ip.getAddress();
635 return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01)
636 && (bytes[2] == 0) && (bytes[3] == 0);
637 }
638
639 /**
640 * Returns the Teredo information embedded in a Teredo address.
641 *
642 * @param ip {@link Inet6Address} to be examined for embedded Teredo
643 * information
644 * @return extracted {@code TeredoInfo}
645 * @throws IllegalArgumentException if the argument is not a valid
646 * IPv6 Teredo address
647 */
648 public static TeredoInfo getTeredoInfo(Inet6Address ip) {
649 Preconditions.checkArgument(isTeredoAddress(ip),
650 "Address '%s' is not a Teredo address.", ip.getHostAddress());
651
652 byte[] bytes = ip.getAddress();
653 Inet4Address server = getInet4Address(copyOfRange(bytes, 4, 8));
654
655 int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;
656
657 // Teredo obfuscates the mapped client port, per section 4 of the RFC.
658 int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;
659
660 byte[] clientBytes = copyOfRange(bytes, 12, 16);
661 for (int i = 0; i < clientBytes.length; i++) {
662 // Teredo obfuscates the mapped client IP, per section 4 of the RFC.
663 clientBytes[i] = (byte) ~clientBytes[i];
664 }
665 Inet4Address client = getInet4Address(clientBytes);
666
667 return new TeredoInfo(server, client, port, flags);
668 }
669
670 /**
671 * Evaluates whether the argument is an ISATAP address.
672 *
673 * <p>From RFC 5214: "ISATAP interface identifiers are constructed in
674 * Modified EUI-64 format [...] by concatenating the 24-bit IANA OUI
675 * (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit IPv4
676 * address in network byte order [...]"
677 *
678 * <p>For more on ISATAP addresses see section 6.1 of
679 * <a target="_parent" href="http://tools.ietf.org/html/rfc5214#section-6.1"
680 * >http://tools.ietf.org/html/rfc5214</a>
681 *
682 * @param ip {@link Inet6Address} to be examined for ISATAP address
683 * format.
684 * @return {@code true} if the argument is an ISATAP address
685 */
686 public static boolean isIsatapAddress(Inet6Address ip) {
687
688 // If it's a Teredo address with the right port (41217, or 0xa101)
689 // which would be encoded as 0x5efe then it can't be an ISATAP address.
690 if (isTeredoAddress(ip)) {
691 return false;
692 }
693
694 byte[] bytes = ip.getAddress();
695
696 if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {
697
698 // Verify that high byte of the 64 bit identifier is zero, modulo
699 // the U/L and G bits, with which we are not concerned.
700 return false;
701 }
702
703 return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e)
704 && (bytes[11] == (byte) 0xfe);
705 }
706
707 /**
708 * Returns the IPv4 address embedded in an ISATAP address.
709 *
710 * @param ip {@link Inet6Address} to be examined for embedded IPv4
711 * in ISATAP address
712 * @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
713 * @throws IllegalArgumentException if the argument is not a valid
714 * IPv6 ISATAP address
715 */
716 public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
717 Preconditions.checkArgument(isIsatapAddress(ip),
718 "Address '%s' is not an ISATAP address.", ip.getHostAddress());
719
720 return getInet4Address(copyOfRange(ip.getAddress(), 12, 16));
721 }
722
723 /**
724 * Examines the Inet6Address to determine if it is an IPv6 address of one
725 * of the specified address types that contain an embedded IPv4 address.
726 *
727 * <p>NOTE: ISATAP addresses are explicitly excluded from this method
728 * due to their trivial spoofability. With other transition addresses
729 * spoofing involves (at least) infection of one's BGP routing table.
730 *
731 * @param ip {@link Inet6Address} to be examined for embedded IPv4
732 * client address.
733 * @return {@code true} if there is an embedded IPv4 client address.
734 * @since 7
735 */
736 public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) {
737 return isCompatIPv4Address(ip) || is6to4Address(ip) ||
738 isTeredoAddress(ip);
739 }
740
741 /**
742 * Examines the Inet6Address to extract the embedded IPv4 client address
743 * if the InetAddress is an IPv6 address of one of the specified address
744 * types that contain an embedded IPv4 address.
745 *
746 * <p>NOTE: ISATAP addresses are explicitly excluded from this method
747 * due to their trivial spoofability. With other transition addresses
748 * spoofing involves (at least) infection of one's BGP routing table.
749 *
750 * @param ip {@link Inet6Address} to be examined for embedded IPv4
751 * client address.
752 * @return {@link Inet4Address} of embedded IPv4 client address.
753 * @throws IllegalArgumentException if the argument does not have a valid
754 * embedded IPv4 address.
755 */
756 public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
757 if (isCompatIPv4Address(ip)) {
758 return getCompatIPv4Address(ip);
759 }
760
761 if (is6to4Address(ip)) {
762 return get6to4IPv4Address(ip);
763 }
764
765 if (isTeredoAddress(ip)) {
766 return getTeredoInfo(ip).getClient();
767 }
768
769 throw new IllegalArgumentException(
770 String.format("'%s' has no embedded IPv4 address.",
771 ip.getHostAddress()));
772 }
773
774 /**
775 * Coerces an IPv6 address into an IPv4 address.
776 *
777 * <p>HACK: As long as applications continue to use IPv4 addresses for
778 * indexing into tables, accounting, et cetera, it may be necessary to
779 * <b>coerce</b> IPv6 addresses into IPv4 addresses. This function does
780 * so by hashing the upper 64 bits into {@code 224.0.0.0/3}
781 * (64 bits into 29 bits).
782 *
783 * <p>A "coerced" IPv4 address is equivalent to itself.
784 *
785 * <p>NOTE: This function is failsafe for security purposes: ALL IPv6
786 * addresses (except localhost (::1)) are hashed to avoid the security
787 * risk associated with extracting an embedded IPv4 address that might
788 * permit elevated privileges.
789 *
790 * @param ip {@link InetAddress} to "coerce"
791 * @return {@link Inet4Address} represented "coerced" address
792 * @since 7
793 */
794 public static Inet4Address getCoercedIPv4Address(InetAddress ip) {
795 if (ip instanceof Inet4Address) {
796 return (Inet4Address) ip;
797 }
798
799 // Special cases:
800 byte[] bytes = ip.getAddress();
801 boolean leadingBytesOfZero = true;
802 for (int i = 0; i < 15; ++i) {
803 if (bytes[i] != 0) {
804 leadingBytesOfZero = false;
805 break;
806 }
807 }
808 if (leadingBytesOfZero && (bytes[15] == 1)) {
809 return LOOPBACK4; // ::1
810 } else if (leadingBytesOfZero && (bytes[15] == 0)) {
811 return ANY4; // ::0
812 }
813
814 Inet6Address ip6 = (Inet6Address) ip;
815 long addressAsLong = 0;
816 if (hasEmbeddedIPv4ClientAddress(ip6)) {
817 addressAsLong = (long) getEmbeddedIPv4ClientAddress(ip6).hashCode();
818 } else {
819
820 // Just extract the high 64 bits (assuming the rest is user-modifiable).
821 addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong();
822 }
823
824 // Many strategies for hashing are possible. This might suffice for now.
825 int coercedHash = hash64To32(addressAsLong);
826
827 // Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3).
828 coercedHash |= 0xe0000000;
829
830 // Fixup to avoid some "illegal" values. Currently the only potential
831 // illegal value is 255.255.255.255.
832 if (coercedHash == 0xffffffff) {
833 coercedHash = 0xfffffffe;
834 }
835
836 return getInet4Address(Ints.toByteArray(coercedHash));
837 }
838
839 /**
840 * Returns an {@code int} hash of a 64-bit long.
841 *
842 * This comes from http://www.concentric.net/~ttwang/tech/inthash.htm
843 *
844 * This hash gives no guarantees on the cryptographic suitability nor the
845 * quality of randomness produced, and the mapping may change in the future.
846 *
847 * @param key A 64-bit number to hash
848 * @return {@code int} the input hashed into 32 bits
849 */
850 @VisibleForTesting static int hash64To32(long key) {
851 key = (~key) + (key << 18);
852 key = key ^ (key >>> 31);
853 key = key * 21;
854 key = key ^ (key >>> 11);
855 key = key + (key << 6);
856 key = key ^ (key >>> 22);
857 return (int) key;
858 }
859
860 /**
861 * Returns an integer representing an IPv4 address regardless of
862 * whether the supplied argument is an IPv4 address or not.
863 *
864 * <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being
865 * converted to integers.
866 *
867 * <p>As long as there are applications that assume that all IP addresses
868 * are IPv4 addresses and can therefore be converted safely to integers
869 * (for whatever purpose) this function can be used to handle IPv6
870 * addresses as well until the application is suitably fixed.
871 *
872 * <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used
873 * for such purposes as rudimentary identification or indexing into a
874 * collection of real {@link InetAddress}es. They cannot be used as
875 * real addresses for the purposes of network communication.
876 *
877 * @param ip {@link InetAddress} to convert
878 * @return {@code int}, "coerced" if ip is not an IPv4 address
879 * @since 7
880 */
881 public static int coerceToInteger(InetAddress ip) {
882 return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt();
883 }
884
885 /**
886 * Returns an Inet4Address having the integer value specified by
887 * the argument.
888 *
889 * @param address {@code int}, the 32bit integer address to be converted
890 * @return {@link Inet4Address} equivalent of the argument
891 */
892 public static Inet4Address fromInteger(int address) {
893 return getInet4Address(Ints.toByteArray(address));
894 }
895
896 /**
897 * Returns an address from a <b>little-endian ordered</b> byte array
898 * (the opposite of what {@link InetAddress#getByAddress} expects).
899 *
900 * <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array
901 * must be 16 bytes long.
902 *
903 * @param addr the raw IP address in little-endian byte order
904 * @return an InetAddress object created from the raw IP address
905 * @throws UnknownHostException if IP address is of illegal length
906 */
907 public static InetAddress fromLittleEndianByteArray(byte[] addr)
908 throws UnknownHostException {
909 byte[] reversed = new byte[addr.length];
910 for (int i = 0; i < addr.length; i++) {
911 reversed[i] = addr[addr.length - i - 1];
912 }
913 return InetAddress.getByAddress(reversed);
914 }
915
916 /**
917 * This method emulates the Java 6 method
918 * {@code Arrays.copyOfRange(byte, int, int)}, which is not available in
919 * Java 5, and thus cannot be used in Guava code.
920 */
921 private static byte[] copyOfRange(byte[] original, int from, int to) {
922 Preconditions.checkNotNull(original);
923
924 int end = Math.min(to, original.length);
925 byte[] result = new byte[to - from];
926
927 System.arraycopy(original, from, result, 0, end - from);
928 return result;
929 }
930 }