blob: 069d2270b0ba2c8fe5d712cfbfdb55e815d512ab [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
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
17package android.net;
18
Lorenzo Colitti566e0cb2015-03-06 19:57:39 +090019import java.io.FileDescriptor;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import java.net.InetAddress;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070021import java.net.Inet4Address;
22import java.net.Inet6Address;
Lorenzo Colitti566e0cb2015-03-06 19:57:39 +090023import java.net.SocketException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import java.net.UnknownHostException;
Robert Greenwalta10b7fd2011-07-25 16:06:25 -070025import java.util.Collection;
Jeff Sharkeyfea17de2013-06-11 14:13:09 -070026import java.util.Locale;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027
Lorenzo Colitti0a82e802014-07-31 00:48:01 +090028import android.os.Parcel;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070029import android.util.Log;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +090030import android.util.Pair;
31
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070032
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033/**
34 * Native methods for managing network interfaces.
35 *
36 * {@hide}
37 */
38public class NetworkUtils {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070039
40 private static final String TAG = "NetworkUtils";
41
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042 /**
Lorenzo Colitti566e0cb2015-03-06 19:57:39 +090043 * Attaches a socket filter that accepts DHCP packets to the given socket.
44 */
45 public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException;
46
47 /**
Paul Jensen578a76e2016-01-14 14:54:39 -050048 * Attaches a socket filter that accepts ICMP6 router advertisement packets to the given socket.
49 * @param fd the socket's {@link FileDescriptor}.
50 * @param packetType the hardware address type, one of ARPHRD_*.
51 */
52 public native static void attachRaFilter(FileDescriptor fd, int packetType) throws SocketException;
53
54 /**
Paul Jensen38764952014-05-20 11:25:35 -040055 * Binds the current process to the network designated by {@code netId}. All sockets created
56 * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
Paul Jensen6d3ff9e2014-05-29 10:12:39 -040057 * {@link Network#getSocketFactory}) will be bound to this network. Note that if this
Paul Jensen38764952014-05-20 11:25:35 -040058 * {@code Network} ever disconnects all sockets created in this way will cease to work. This
59 * is by design so an application doesn't accidentally use sockets it thinks are still bound to
Paul Jensenbcc76d32014-07-11 08:17:29 -040060 * a particular {@code Network}. Passing NETID_UNSET clears the binding.
Paul Jensen38764952014-05-20 11:25:35 -040061 */
Paul Jensen32a58f02014-06-20 13:58:14 -040062 public native static boolean bindProcessToNetwork(int netId);
Paul Jensen38764952014-05-20 11:25:35 -040063
64 /**
Paul Jensen38764952014-05-20 11:25:35 -040065 * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
66 * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
67 */
Paul Jensen72db88e2015-03-10 10:54:12 -040068 public native static int getBoundNetworkForProcess();
Paul Jensen38764952014-05-20 11:25:35 -040069
70 /**
71 * Binds host resolutions performed by this process to the network designated by {@code netId}.
Paul Jensenbcc76d32014-07-11 08:17:29 -040072 * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears
73 * the binding.
Paul Jensen38764952014-05-20 11:25:35 -040074 *
75 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
76 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -070077 @Deprecated
Paul Jensen32a58f02014-06-20 13:58:14 -040078 public native static boolean bindProcessToNetworkForHostResolution(int netId);
Paul Jensen38764952014-05-20 11:25:35 -040079
80 /**
Paul Jensen38764952014-05-20 11:25:35 -040081 * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This
82 * overrides any binding via {@link #bindProcessToNetwork}.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070083 * @return 0 on success or negative errno on failure.
Paul Jensen38764952014-05-20 11:25:35 -040084 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070085 public native static int bindSocketToNetwork(int socketfd, int netId);
Paul Jensen38764952014-05-20 11:25:35 -040086
87 /**
Lorenzo Colitti4ff9f0f2015-03-17 17:56:10 +090088 * Protect {@code fd} from VPN connections. After protecting, data sent through
89 * this socket will go directly to the underlying network, so its traffic will not be
90 * forwarded through the VPN.
91 */
92 public static boolean protectFromVpn(FileDescriptor fd) {
93 return protectFromVpn(fd.getInt$());
94 }
95
96 /**
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040097 * Protect {@code socketfd} from VPN connections. After protecting, data sent through
98 * this socket will go directly to the underlying network, so its traffic will not be
99 * forwarded through the VPN.
100 */
101 public native static boolean protectFromVpn(int socketfd);
102
103 /**
Paul Jensencee9b512015-05-06 07:32:40 -0400104 * Determine if {@code uid} can access network designated by {@code netId}.
105 * @return {@code true} if {@code uid} can access network, {@code false} otherwise.
106 */
107 public native static boolean queryUserAccess(int uid, int netId);
108
109 /**
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700110 * Convert a IPv4 address from an integer to an InetAddress.
Jesse Wilson07481cc2011-01-06 17:18:23 -0800111 * @param hostAddress an int corresponding to the IPv4 address in network byte order
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700112 */
113 public static InetAddress intToInetAddress(int hostAddress) {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700114 byte[] addressBytes = { (byte)(0xff & hostAddress),
115 (byte)(0xff & (hostAddress >> 8)),
116 (byte)(0xff & (hostAddress >> 16)),
117 (byte)(0xff & (hostAddress >> 24)) };
118
119 try {
Jesse Wilson07481cc2011-01-06 17:18:23 -0800120 return InetAddress.getByAddress(addressBytes);
121 } catch (UnknownHostException e) {
122 throw new AssertionError();
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700123 }
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700124 }
125
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700126 /**
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700127 * Convert a IPv4 address from an InetAddress to an integer
128 * @param inetAddr is an InetAddress corresponding to the IPv4 address
129 * @return the IP address as an integer in network byte order
130 */
Robert Greenwalt4717c262012-10-31 14:32:53 -0700131 public static int inetAddressToInt(Inet4Address inetAddr)
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700132 throws IllegalArgumentException {
133 byte [] addr = inetAddr.getAddress();
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700134 return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
135 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
136 }
137
138 /**
139 * Convert a network prefix length to an IPv4 netmask integer
140 * @param prefixLength
141 * @return the IPv4 netmask as an integer in network byte order
142 */
143 public static int prefixLengthToNetmaskInt(int prefixLength)
144 throws IllegalArgumentException {
145 if (prefixLength < 0 || prefixLength > 32) {
146 throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
147 }
148 int value = 0xffffffff << (32 - prefixLength);
149 return Integer.reverseBytes(value);
150 }
151
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700152 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700153 * Convert a IPv4 netmask integer to a prefix length
154 * @param netmask as an integer in network byte order
155 * @return the network prefix length
156 */
157 public static int netmaskIntToPrefixLength(int netmask) {
158 return Integer.bitCount(netmask);
159 }
160
161 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900162 * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous.
163 * @param netmask as a {@code Inet4Address}.
164 * @return the network prefix length
165 * @throws IllegalArgumentException the specified netmask was not contiguous.
166 * @hide
167 */
168 public static int netmaskToPrefixLength(Inet4Address netmask) {
169 // inetAddressToInt returns an int in *network* byte order.
170 int i = Integer.reverseBytes(inetAddressToInt(netmask));
171 int prefixLength = Integer.bitCount(i);
172 int trailingZeros = Integer.numberOfTrailingZeros(i);
173 if (trailingZeros != 32 - prefixLength) {
174 throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i));
175 }
176 return prefixLength;
177 }
178
179
180 /**
Robert Greenwalt0216e612011-01-14 16:29:58 -0800181 * Create an InetAddress from a string where the string must be a standard
182 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
183 * but it will throw an IllegalArgumentException in that case.
184 * @param addrString
185 * @return the InetAddress
186 * @hide
187 */
188 public static InetAddress numericToInetAddress(String addrString)
189 throws IllegalArgumentException {
Elliott Hughesf5bbb572011-02-15 17:11:29 -0800190 return InetAddress.parseNumericAddress(addrString);
Robert Greenwalt0216e612011-01-14 16:29:58 -0800191 }
192
193 /**
Lorenzo Colitti0a82e802014-07-31 00:48:01 +0900194 * Writes an InetAddress to a parcel. The address may be null. This is likely faster than
195 * calling writeSerializable.
196 */
197 protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) {
198 byte[] addressArray = (address != null) ? address.getAddress() : null;
199 parcel.writeByteArray(addressArray);
200 }
201
202 /**
203 * Reads an InetAddress from a parcel. Returns null if the address that was written was null
204 * or if the data is invalid.
205 */
206 protected static InetAddress unparcelInetAddress(Parcel in) {
207 byte[] addressArray = in.createByteArray();
208 if (addressArray == null) {
209 return null;
210 }
211 try {
212 return InetAddress.getByAddress(addressArray);
213 } catch (UnknownHostException e) {
214 return null;
215 }
216 }
217
218
219 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900220 * Masks a raw IP address byte array with the specified prefix length.
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700221 */
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900222 public static void maskRawAddress(byte[] array, int prefixLength) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700223 if (prefixLength < 0 || prefixLength > array.length * 8) {
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900224 throw new RuntimeException("IP address with " + array.length +
225 " bytes has invalid prefix length " + prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700226 }
227
228 int offset = prefixLength / 8;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900229 int remainder = prefixLength % 8;
230 byte mask = (byte)(0xFF << (8 - remainder));
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700231
232 if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
233
234 offset++;
235
236 for (; offset < array.length; offset++) {
237 array[offset] = 0;
238 }
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900239 }
240
241 /**
242 * Get InetAddress masked with prefixLength. Will never return null.
243 * @param address the IP address to mask with
244 * @param prefixLength the prefixLength used to mask the IP
245 */
246 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
247 byte[] array = address.getAddress();
248 maskRawAddress(array, prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700249
250 InetAddress netPart = null;
251 try {
252 netPart = InetAddress.getByAddress(array);
253 } catch (UnknownHostException e) {
254 throw new RuntimeException("getNetworkPart error - " + e.toString());
255 }
256 return netPart;
257 }
258
259 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900260 * Returns the implicit netmask of an IPv4 address, as was the custom before 1993.
261 */
262 public static int getImplicitNetmask(Inet4Address address) {
263 int firstByte = address.getAddress()[0] & 0xff; // Convert to an unsigned value.
264 if (firstByte < 128) {
265 return 8;
266 } else if (firstByte < 192) {
267 return 16;
268 } else if (firstByte < 224) {
269 return 24;
270 } else {
271 return 32; // Will likely not end well for other reasons.
272 }
273 }
274
275 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900276 * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
277 * @hide
278 */
279 public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) {
280 InetAddress address = null;
281 int prefixLength = -1;
282 try {
283 String[] pieces = ipAndMaskString.split("/", 2);
284 prefixLength = Integer.parseInt(pieces[1]);
285 address = InetAddress.parseNumericAddress(pieces[0]);
286 } catch (NullPointerException e) { // Null string.
287 } catch (ArrayIndexOutOfBoundsException e) { // No prefix length.
288 } catch (NumberFormatException e) { // Non-numeric prefix.
289 } catch (IllegalArgumentException e) { // Invalid IP address.
290 }
291
292 if (address == null || prefixLength == -1) {
293 throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString);
294 }
295
296 return new Pair<InetAddress, Integer>(address, prefixLength);
297 }
298
299 /**
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700300 * Check if IP address type is consistent between two InetAddress.
301 * @return true if both are the same type. False otherwise.
302 */
303 public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
304 return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
305 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
306 }
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700307
308 /**
309 * Convert a 32 char hex string into a Inet6Address.
310 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
311 * made into an Inet6Address
312 * @param addrHexString a 32 character hex string representing an IPv6 addr
313 * @return addr an InetAddress representation for the string
314 */
315 public static InetAddress hexToInet6Address(String addrHexString)
316 throws IllegalArgumentException {
317 try {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700318 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700319 addrHexString.substring(0,4), addrHexString.substring(4,8),
320 addrHexString.substring(8,12), addrHexString.substring(12,16),
321 addrHexString.substring(16,20), addrHexString.substring(20,24),
322 addrHexString.substring(24,28), addrHexString.substring(28,32)));
323 } catch (Exception e) {
324 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
325 throw new IllegalArgumentException(e);
326 }
327 }
Robert Greenwalta10b7fd2011-07-25 16:06:25 -0700328
329 /**
330 * Create a string array of host addresses from a collection of InetAddresses
331 * @param addrs a Collection of InetAddresses
332 * @return an array of Strings containing their host addresses
333 */
334 public static String[] makeStrings(Collection<InetAddress> addrs) {
335 String[] result = new String[addrs.size()];
336 int i = 0;
337 for (InetAddress addr : addrs) {
338 result[i++] = addr.getHostAddress();
339 }
340 return result;
341 }
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800342
343 /**
344 * Trim leading zeros from IPv4 address strings
345 * Our base libraries will interpret that as octel..
346 * Must leave non v4 addresses and host names alone.
347 * For example, 192.168.000.010 -> 192.168.0.10
348 * TODO - fix base libraries and remove this function
349 * @param addr a string representing an ip addr
350 * @return a string propertly trimmed
351 */
352 public static String trimV4AddrZeros(String addr) {
Robert Greenwalt0faacf02011-12-07 16:43:59 -0800353 if (addr == null) return null;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800354 String[] octets = addr.split("\\.");
355 if (octets.length != 4) return addr;
356 StringBuilder builder = new StringBuilder(16);
357 String result = null;
358 for (int i = 0; i < 4; i++) {
359 try {
Robert Greenwalt3957b5f2011-12-07 13:10:59 -0800360 if (octets[i].length() > 3) return addr;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800361 builder.append(Integer.parseInt(octets[i]));
362 } catch (NumberFormatException e) {
363 return addr;
364 }
365 if (i < 3) builder.append('.');
366 }
367 result = builder.toString();
368 return result;
369 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800370}