OSDN Git Service

Make ConnectivityMetricsLogger and related classes @SystemApi
[android-x86/frameworks-base.git] / core / java / android / net / NetworkUtils.java
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      */
45     public native static void attachDhcpFilter(FileDescriptor fd) throws SocketException;
46
47     /**
48      * 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     /**
55      * 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
57      * {@link Network#getSocketFactory}) will be bound to this network.  Note that if this
58      * {@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
60      * a particular {@code Network}.  Passing NETID_UNSET clears the binding.
61      */
62     public native static boolean bindProcessToNetwork(int netId);
63
64     /**
65      * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
66      * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
67      */
68     public native static int getBoundNetworkForProcess();
69
70     /**
71      * Binds host resolutions performed by this process to the network designated by {@code netId}.
72      * {@link #bindProcessToNetwork} takes precedence over this setting.  Passing NETID_UNSET clears
73      * the binding.
74      *
75      * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
76      */
77     public native static boolean bindProcessToNetworkForHostResolution(int netId);
78
79     /**
80      * Explicitly binds {@code socketfd} to the network designated by {@code netId}.  This
81      * overrides any binding via {@link #bindProcessToNetwork}.
82      * @return 0 on success or negative errno on failure.
83      */
84     public native static int bindSocketToNetwork(int socketfd, int netId);
85
86     /**
87      * Protect {@code fd} from VPN connections.  After protecting, data sent through
88      * this socket will go directly to the underlying network, so its traffic will not be
89      * forwarded through the VPN.
90      */
91     public static boolean protectFromVpn(FileDescriptor fd) {
92         return protectFromVpn(fd.getInt$());
93     }
94
95     /**
96      * Protect {@code socketfd} from VPN connections.  After protecting, data sent through
97      * this socket will go directly to the underlying network, so its traffic will not be
98      * forwarded through the VPN.
99      */
100     public native static boolean protectFromVpn(int socketfd);
101
102     /**
103      * Determine if {@code uid} can access network designated by {@code netId}.
104      * @return {@code true} if {@code uid} can access network, {@code false} otherwise.
105      */
106     public native static boolean queryUserAccess(int uid, int netId);
107
108     /**
109      * Convert a IPv4 address from an integer to an InetAddress.
110      * @param hostAddress an int corresponding to the IPv4 address in network byte order
111      */
112     public static InetAddress intToInetAddress(int hostAddress) {
113         byte[] addressBytes = { (byte)(0xff & hostAddress),
114                                 (byte)(0xff & (hostAddress >> 8)),
115                                 (byte)(0xff & (hostAddress >> 16)),
116                                 (byte)(0xff & (hostAddress >> 24)) };
117
118         try {
119            return InetAddress.getByAddress(addressBytes);
120         } catch (UnknownHostException e) {
121            throw new AssertionError();
122         }
123     }
124
125     /**
126      * Convert a IPv4 address from an InetAddress to an integer
127      * @param inetAddr is an InetAddress corresponding to the IPv4 address
128      * @return the IP address as an integer in network byte order
129      */
130     public static int inetAddressToInt(Inet4Address inetAddr)
131             throws IllegalArgumentException {
132         byte [] addr = inetAddr.getAddress();
133         return ((addr[3] & 0xff) << 24) | ((addr[2] & 0xff) << 16) |
134                 ((addr[1] & 0xff) << 8) | (addr[0] & 0xff);
135     }
136
137     /**
138      * Convert a network prefix length to an IPv4 netmask integer
139      * @param prefixLength
140      * @return the IPv4 netmask as an integer in network byte order
141      */
142     public static int prefixLengthToNetmaskInt(int prefixLength)
143             throws IllegalArgumentException {
144         if (prefixLength < 0 || prefixLength > 32) {
145             throw new IllegalArgumentException("Invalid prefix length (0 <= prefix <= 32)");
146         }
147         int value = 0xffffffff << (32 - prefixLength);
148         return Integer.reverseBytes(value);
149     }
150
151     /**
152      * Convert a IPv4 netmask integer to a prefix length
153      * @param netmask as an integer in network byte order
154      * @return the network prefix length
155      */
156     public static int netmaskIntToPrefixLength(int netmask) {
157         return Integer.bitCount(netmask);
158     }
159
160     /**
161      * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous.
162      * @param netmask as a {@code Inet4Address}.
163      * @return the network prefix length
164      * @throws IllegalArgumentException the specified netmask was not contiguous.
165      * @hide
166      */
167     public static int netmaskToPrefixLength(Inet4Address netmask) {
168         // inetAddressToInt returns an int in *network* byte order.
169         int i = Integer.reverseBytes(inetAddressToInt(netmask));
170         int prefixLength = Integer.bitCount(i);
171         int trailingZeros = Integer.numberOfTrailingZeros(i);
172         if (trailingZeros != 32 - prefixLength) {
173             throw new IllegalArgumentException("Non-contiguous netmask: " + Integer.toHexString(i));
174         }
175         return prefixLength;
176     }
177
178
179     /**
180      * Create an InetAddress from a string where the string must be a standard
181      * representation of a V4 or V6 address.  Avoids doing a DNS lookup on failure
182      * but it will throw an IllegalArgumentException in that case.
183      * @param addrString
184      * @return the InetAddress
185      * @hide
186      */
187     public static InetAddress numericToInetAddress(String addrString)
188             throws IllegalArgumentException {
189         return InetAddress.parseNumericAddress(addrString);
190     }
191
192     /**
193      * Writes an InetAddress to a parcel. The address may be null. This is likely faster than
194      * calling writeSerializable.
195      */
196     protected static void parcelInetAddress(Parcel parcel, InetAddress address, int flags) {
197         byte[] addressArray = (address != null) ? address.getAddress() : null;
198         parcel.writeByteArray(addressArray);
199     }
200
201     /**
202      * Reads an InetAddress from a parcel. Returns null if the address that was written was null
203      * or if the data is invalid.
204      */
205     protected static InetAddress unparcelInetAddress(Parcel in) {
206         byte[] addressArray = in.createByteArray();
207         if (addressArray == null) {
208             return null;
209         }
210         try {
211             return InetAddress.getByAddress(addressArray);
212         } catch (UnknownHostException e) {
213             return null;
214         }
215     }
216
217
218     /**
219      *  Masks a raw IP address byte array with the specified prefix length.
220      */
221     public static void maskRawAddress(byte[] array, int prefixLength) {
222         if (prefixLength < 0 || prefixLength > array.length * 8) {
223             throw new RuntimeException("IP address with " + array.length +
224                     " bytes has invalid prefix length " + prefixLength);
225         }
226
227         int offset = prefixLength / 8;
228         int remainder = prefixLength % 8;
229         byte mask = (byte)(0xFF << (8 - remainder));
230
231         if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
232
233         offset++;
234
235         for (; offset < array.length; offset++) {
236             array[offset] = 0;
237         }
238     }
239
240     /**
241      * Get InetAddress masked with prefixLength.  Will never return null.
242      * @param address the IP address to mask with
243      * @param prefixLength the prefixLength used to mask the IP
244      */
245     public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
246         byte[] array = address.getAddress();
247         maskRawAddress(array, prefixLength);
248
249         InetAddress netPart = null;
250         try {
251             netPart = InetAddress.getByAddress(array);
252         } catch (UnknownHostException e) {
253             throw new RuntimeException("getNetworkPart error - " + e.toString());
254         }
255         return netPart;
256     }
257
258     /**
259      * Returns the implicit netmask of an IPv4 address, as was the custom before 1993.
260      */
261     public static int getImplicitNetmask(Inet4Address address) {
262         int firstByte = address.getAddress()[0] & 0xff;  // Convert to an unsigned value.
263         if (firstByte < 128) {
264             return 8;
265         } else if (firstByte < 192) {
266             return 16;
267         } else if (firstByte < 224) {
268             return 24;
269         } else {
270             return 32;  // Will likely not end well for other reasons.
271         }
272     }
273
274     /**
275      * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
276      * @hide
277      */
278     public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) {
279         InetAddress address = null;
280         int prefixLength = -1;
281         try {
282             String[] pieces = ipAndMaskString.split("/", 2);
283             prefixLength = Integer.parseInt(pieces[1]);
284             address = InetAddress.parseNumericAddress(pieces[0]);
285         } catch (NullPointerException e) {            // Null string.
286         } catch (ArrayIndexOutOfBoundsException e) {  // No prefix length.
287         } catch (NumberFormatException e) {           // Non-numeric prefix.
288         } catch (IllegalArgumentException e) {        // Invalid IP address.
289         }
290
291         if (address == null || prefixLength == -1) {
292             throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString);
293         }
294
295         return new Pair<InetAddress, Integer>(address, prefixLength);
296     }
297
298     /**
299      * Check if IP address type is consistent between two InetAddress.
300      * @return true if both are the same type.  False otherwise.
301      */
302     public static boolean addressTypeMatches(InetAddress left, InetAddress right) {
303         return (((left instanceof Inet4Address) && (right instanceof Inet4Address)) ||
304                 ((left instanceof Inet6Address) && (right instanceof Inet6Address)));
305     }
306
307     /**
308      * Convert a 32 char hex string into a Inet6Address.
309      * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
310      * made into an Inet6Address
311      * @param addrHexString a 32 character hex string representing an IPv6 addr
312      * @return addr an InetAddress representation for the string
313      */
314     public static InetAddress hexToInet6Address(String addrHexString)
315             throws IllegalArgumentException {
316         try {
317             return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
318                     addrHexString.substring(0,4),   addrHexString.substring(4,8),
319                     addrHexString.substring(8,12),  addrHexString.substring(12,16),
320                     addrHexString.substring(16,20), addrHexString.substring(20,24),
321                     addrHexString.substring(24,28), addrHexString.substring(28,32)));
322         } catch (Exception e) {
323             Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
324             throw new IllegalArgumentException(e);
325         }
326     }
327
328     /**
329      * Create a string array of host addresses from a collection of InetAddresses
330      * @param addrs a Collection of InetAddresses
331      * @return an array of Strings containing their host addresses
332      */
333     public static String[] makeStrings(Collection<InetAddress> addrs) {
334         String[] result = new String[addrs.size()];
335         int i = 0;
336         for (InetAddress addr : addrs) {
337             result[i++] = addr.getHostAddress();
338         }
339         return result;
340     }
341
342     /**
343      * Trim leading zeros from IPv4 address strings
344      * Our base libraries will interpret that as octel..
345      * Must leave non v4 addresses and host names alone.
346      * For example, 192.168.000.010 -> 192.168.0.10
347      * TODO - fix base libraries and remove this function
348      * @param addr a string representing an ip addr
349      * @return a string propertly trimmed
350      */
351     public static String trimV4AddrZeros(String addr) {
352         if (addr == null) return null;
353         String[] octets = addr.split("\\.");
354         if (octets.length != 4) return addr;
355         StringBuilder builder = new StringBuilder(16);
356         String result = null;
357         for (int i = 0; i < 4; i++) {
358             try {
359                 if (octets[i].length() > 3) return addr;
360                 builder.append(Integer.parseInt(octets[i]));
361             } catch (NumberFormatException e) {
362                 return addr;
363             }
364             if (i < 3) builder.append('.');
365         }
366         result = builder.toString();
367         return result;
368     }
369 }