1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.net; 18 19 import java.io.FileDescriptor; 20 import java.net.InetAddress; 21 import java.net.Inet4Address; 22 import java.net.Inet6Address; 23 import java.net.SocketException; 24 import java.net.UnknownHostException; 25 import java.util.Collection; 26 import java.util.Locale; 27 28 import android.os.Parcel; 29 import android.util.Log; 30 import android.util.Pair; 31 32 33 /** 34 * Native methods for managing network interfaces. 35 * 36 * {@hide} 37 */ 38 public class NetworkUtils { 39 40 private static final String TAG = "NetworkUtils"; 41 42 /** 43 * Attaches a socket filter that accepts DHCP packets to the given socket. 44 */ attachDhcpFilter(FileDescriptor fd)45 public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException; 46 47 /** 48 * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket. 49 * @param fd the socket's {@link FileDescriptor}. 50 * @param packetType the hardware address type, one of ARPHRD_*. 51 */ attachRaFilter(FileDescriptor fd, int packetType)52 public native static void attachRaFilter(FileDescriptor fd, int packetType) throws SocketException; 53 54 /** 55 * Attaches a socket filter that accepts L2-L4 signaling traffic required for IP connectivity. 56 * 57 * This includes: all ARP, ICMPv6 RS/RA/NS/NA messages, and DHCPv4 exchanges. 58 * 59 * @param fd the socket's {@link FileDescriptor}. 60 * @param packetType the hardware address type, one of ARPHRD_*. 61 */ attachControlPacketFilter(FileDescriptor fd, int packetType)62 public native static void attachControlPacketFilter(FileDescriptor fd, int packetType) 63 throws SocketException; 64 65 /** 66 * Configures a socket for receiving ICMPv6 router solicitations and sending advertisements. 67 * @param fd the socket's {@link FileDescriptor}. 68 * @param ifIndex the interface index. 69 */ setupRaSocket(FileDescriptor fd, int ifIndex)70 public native static void setupRaSocket(FileDescriptor fd, int ifIndex) throws SocketException; 71 72 /** 73 * Binds the current process to the network designated by {@code netId}. All sockets created 74 * in the future (and not explicitly bound via a bound {@link SocketFactory} (see 75 * {@link Network#getSocketFactory}) will be bound to this network. Note that if this 76 * {@code Network} ever disconnects all sockets created in this way will cease to work. This 77 * is by design so an application doesn't accidentally use sockets it thinks are still bound to 78 * a particular {@code Network}. Passing NETID_UNSET clears the binding. 79 */ bindProcessToNetwork(int netId)80 public native static boolean bindProcessToNetwork(int netId); 81 82 /** 83 * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if 84 * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}. 85 */ getBoundNetworkForProcess()86 public native static int getBoundNetworkForProcess(); 87 88 /** 89 * Binds host resolutions performed by this process to the network designated by {@code netId}. 90 * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears 91 * the binding. 92 * 93 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature(). 94 */ bindProcessToNetworkForHostResolution(int netId)95 public native static boolean bindProcessToNetworkForHostResolution(int netId); 96 97 /** 98 * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This 99 * overrides any binding via {@link #bindProcessToNetwork}. 100 * @return 0 on success or negative errno on failure. 101 */ bindSocketToNetwork(int socketfd, int netId)102 public native static int bindSocketToNetwork(int socketfd, int netId); 103 104 /** 105 * Protect {@code fd} from VPN connections. After protecting, data sent through 106 * this socket will go directly to the underlying network, so its traffic will not be 107 * forwarded through the VPN. 108 */ protectFromVpn(FileDescriptor fd)109 public static boolean protectFromVpn(FileDescriptor fd) { 110 return protectFromVpn(fd.getInt$()); 111 } 112 113 /** 114 * Protect {@code socketfd} from VPN connections. After protecting, data sent through 115 * this socket will go directly to the underlying network, so its traffic will not be 116 * forwarded through the VPN. 117 */ protectFromVpn(int socketfd)118 public native static boolean protectFromVpn(int socketfd); 119 120 /** 121 * Determine if {@code uid} can access network designated by {@code netId}. 122 * @return {@code true} if {@code uid} can access network, {@code false} otherwise. 123 */ queryUserAccess(int uid, int netId)124 public native static boolean queryUserAccess(int uid, int netId); 125 126 /** 127 * Convert a IPv4 address from an integer to an InetAddress. 128 * @param hostAddress an int corresponding to the IPv4 address in network byte order 129 */ intToInetAddress(int hostAddress)130 public static InetAddress intToInetAddress(int hostAddress) { 131 byte[] addressBytes = { (byte)(0xff & hostAddress), 132 (byte)(0xff & (hostAddress >> 8)), 133 (byte)(0xff & (hostAddress >> 16)), 134 (byte)(0xff & (hostAddress >> 24)) }; 135 136 try { 137 return InetAddress.getByAddress(addressBytes); 138 } catch (UnknownHostException e) { 139 throw new AssertionError(); 140 } 141 } 142 143 /** 144 * Convert a IPv4 address from an InetAddress to an integer 145 * @param inetAddr is an InetAddress corresponding to the IPv4 address 146 * @return the IP address as an integer in network byte order 147 */ inetAddressToInt(Inet4Address inetAddr)148 public static int inetAddressToInt(Inet4Address inetAddr) 149 throws IllegalArgumentException { 150 byte [] addr = inetAddr.getAddress(); 151 return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) | 152 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff); 153 } 154 155 /** 156 * Convert a network prefix length to an IPv4 netmask integer 157 * @param prefixLength 158 * @return the IPv4 netmask as an integer in network byte order 159 */ prefixLengthToNetmaskInt(int prefixLength)160 public static int prefixLengthToNetmaskInt(int prefixLength) 161 throws IllegalArgumentException { 162 if (prefixLength < 0 || prefixLength > 32) { 163 throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)"); 164 } 165 int value = 0xffffffff << (32 - prefixLength); 166 return Integer.reverseBytes(value); 167 } 168 169 /** 170 * Convert a IPv4 netmask integer to a prefix length 171 * @param netmask as an integer in network byte order 172 * @return the network prefix length 173 */ netmaskIntToPrefixLength(int netmask)174 public static int netmaskIntToPrefixLength(int netmask) { 175 return Integer.bitCount(netmask); 176 } 177 178 /** 179 * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous. 180 * @param netmask as a {@code Inet4Address}. 181 * @return the network prefix length 182 * @throws IllegalArgumentException the specified netmask was not contiguous. 183 * @hide 184 */ netmaskToPrefixLength(Inet4Address netmask)185 public static int netmaskToPrefixLength(Inet4Address netmask) { 186 // inetAddressToInt returns an int in *network* byte order. 187 int i = Integer.reverseBytes(inetAddressToInt(netmask)); 188 int prefixLength = Integer.bitCount(i); 189 int trailingZeros = Integer.numberOfTrailingZeros(i); 190 if (trailingZeros != 32 - prefixLength) { 191 throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i)); 192 } 193 return prefixLength; 194 } 195 196 197 /** 198 * Create an InetAddress from a string where the string must be a standard 199 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure 200 * but it will throw an IllegalArgumentException in that case. 201 * @param addrString 202 * @return the InetAddress 203 * @hide 204 */ numericToInetAddress(String addrString)205 public static InetAddress numericToInetAddress(String addrString) 206 throws IllegalArgumentException { 207 return InetAddress.parseNumericAddress(addrString); 208 } 209 210 /** 211 * Writes an InetAddress to a parcel. The address may be null. This is likely faster than 212 * calling writeSerializable. 213 */ parcelInetAddress(Parcel parcel, InetAddress address, int flags)214 protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) { 215 byte[] addressArray = (address != null) ? address.getAddress() : null; 216 parcel.writeByteArray(addressArray); 217 } 218 219 /** 220 * Reads an InetAddress from a parcel. Returns null if the address that was written was null 221 * or if the data is invalid. 222 */ unparcelInetAddress(Parcel in)223 protected static InetAddress unparcelInetAddress(Parcel in) { 224 byte[] addressArray = in.createByteArray(); 225 if (addressArray == null) { 226 return null; 227 } 228 try { 229 return InetAddress.getByAddress(addressArray); 230 } catch (UnknownHostException e) { 231 return null; 232 } 233 } 234 235 236 /** 237 * Masks a raw IP address byte array with the specified prefix length. 238 */ maskRawAddress(byte[] array, int prefixLength)239 public static void maskRawAddress(byte[] array, int prefixLength) { 240 if (prefixLength < 0 || prefixLength > array.length * 8) { 241 throw new RuntimeException("IP address with " + array.length + 242 " bytes has invalid prefix length " + prefixLength); 243 } 244 245 int offset = prefixLength / 8; 246 int remainder = prefixLength % 8; 247 byte mask = (byte)(0xFF << (8 - remainder)); 248 249 if (offset < array.length) array[offset] = (byte)(array[offset] & mask); 250 251 offset++; 252 253 for (; offset < array.length; offset++) { 254 array[offset] = 0; 255 } 256 } 257 258 /** 259 * Get InetAddress masked with prefixLength. Will never return null. 260 * @param address the IP address to mask with 261 * @param prefixLength the prefixLength used to mask the IP 262 */ getNetworkPart(InetAddress address, int prefixLength)263 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) { 264 byte[] array = address.getAddress(); 265 maskRawAddress(array, prefixLength); 266 267 InetAddress netPart = null; 268 try { 269 netPart = InetAddress.getByAddress(array); 270 } catch (UnknownHostException e) { 271 throw new RuntimeException("getNetworkPart error - " + e.toString()); 272 } 273 return netPart; 274 } 275 276 /** 277 * Returns the implicit netmask of an IPv4 address, as was the custom before 1993. 278 */ getImplicitNetmask(Inet4Address address)279 public static int getImplicitNetmask(Inet4Address address) { 280 int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value. 281 if (firstByte < 128) { 282 return 8; 283 } else if (firstByte < 192) { 284 return 16; 285 } else if (firstByte < 224) { 286 return 24; 287 } else { 288 return 32; // Will likely not end well for other reasons. 289 } 290 } 291 292 /** 293 * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64". 294 * @hide 295 */ parseIpAndMask(String ipAndMaskString)296 public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) { 297 InetAddress address = null; 298 int prefixLength = -1; 299 try { 300 String[] pieces = ipAndMaskString.split("/", 2); 301 prefixLength = Integer.parseInt(pieces[1]); 302 address = InetAddress.parseNumericAddress(pieces[0]); 303 } catch (NullPointerException e) { // Null string. 304 } catch (ArrayIndexOutOfBoundsException e) { // No prefix length. 305 } catch (NumberFormatException e) { // Non-numeric prefix. 306 } catch (IllegalArgumentException e) { // Invalid IP address. 307 } 308 309 if (address == null || prefixLength == -1) { 310 throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString); 311 } 312 313 return new Pair<InetAddress, Integer>(address, prefixLength); 314 } 315 316 /** 317 * Check if IP address type is consistent between two InetAddress. 318 * @return true if both are the same type. False otherwise. 319 */ addressTypeMatches(InetAddress left, InetAddress right)320 public static boolean addressTypeMatches(InetAddress left, InetAddress right) { 321 return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) || 322 ((left instanceof Inet6Address) && (right instanceof Inet6Address))); 323 } 324 325 /** 326 * Convert a 32 char hex string into a Inet6Address. 327 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be 328 * made into an Inet6Address 329 * @param addrHexString a 32 character hex string representing an IPv6 addr 330 * @return addr an InetAddress representation for the string 331 */ hexToInet6Address(String addrHexString)332 public static InetAddress hexToInet6Address(String addrHexString) 333 throws IllegalArgumentException { 334 try { 335 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s", 336 addrHexString.substring(0,4), addrHexString.substring(4,8), 337 addrHexString.substring(8,12), addrHexString.substring(12,16), 338 addrHexString.substring(16,20), addrHexString.substring(20,24), 339 addrHexString.substring(24,28), addrHexString.substring(28,32))); 340 } catch (Exception e) { 341 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e); 342 throw new IllegalArgumentException(e); 343 } 344 } 345 346 /** 347 * Create a string array of host addresses from a collection of InetAddresses 348 * @param addrs a Collection of InetAddresses 349 * @return an array of Strings containing their host addresses 350 */ makeStrings(Collection<InetAddress> addrs)351 public static String[] makeStrings(Collection<InetAddress> addrs) { 352 String[] result = new String[addrs.size()]; 353 int i = 0; 354 for (InetAddress addr : addrs) { 355 result[i++] = addr.getHostAddress(); 356 } 357 return result; 358 } 359 360 /** 361 * Trim leading zeros from IPv4 address strings 362 * Our base libraries will interpret that as octel.. 363 * Must leave non v4 addresses and host names alone. 364 * For example, 192.168.000.010 -> 192.168.0.10 365 * TODO - fix base libraries and remove this function 366 * @param addr a string representing an ip addr 367 * @return a string propertly trimmed 368 */ trimV4AddrZeros(String addr)369 public static String trimV4AddrZeros(String addr) { 370 if (addr == null) return null; 371 String[] octets = addr.split("\\."); 372 if (octets.length != 4) return addr; 373 StringBuilder builder = new StringBuilder(16); 374 String result = null; 375 for (int i = 0; i < 4; i++) { 376 try { 377 if (octets[i].length() > 3) return addr; 378 builder.append(Integer.parseInt(octets[i])); 379 } catch (NumberFormatException e) { 380 return addr; 381 } 382 if (i < 3) builder.append('.'); 383 } 384 result = builder.toString(); 385 return result; 386 } 387 } 388