blob: 779f7bc91e8f4ad4edd27ab7f861883e5f04e9a3 [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
Fedor Kudasovc064c842019-07-09 14:13:30 +000019import static android.system.OsConstants.AF_INET;
20import static android.system.OsConstants.AF_INET6;
21
22import android.annotation.NonNull;
Artur Satayev26958002019-12-10 17:47:52 +000023import android.compat.annotation.UnsupportedAppUsage;
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +090024import android.net.shared.Inet4AddressUtils;
Paul Duffina2b34f82018-10-11 15:21:46 +010025import android.os.Build;
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +090026import android.system.ErrnoException;
Fedor Kudasovc064c842019-07-09 14:13:30 +000027import android.system.Os;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070028import android.util.Log;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +090029import android.util.Pair;
30
Chalard Jeanadbf1d02018-02-26 11:52:46 +090031import java.io.FileDescriptor;
Fedor Kudasove5cb0a22019-07-09 09:23:25 +000032import java.math.BigInteger;
Chalard Jeanadbf1d02018-02-26 11:52:46 +090033import java.net.Inet4Address;
Chalard Jeanadbf1d02018-02-26 11:52:46 +090034import java.net.InetAddress;
35import java.net.SocketException;
36import java.net.UnknownHostException;
37import java.util.Collection;
38import java.util.Locale;
Fedor Kudasove5cb0a22019-07-09 09:23:25 +000039import java.util.TreeSet;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070040
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041/**
42 * Native methods for managing network interfaces.
43 *
44 * {@hide}
45 */
46public class NetworkUtils {
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070047
48 private static final String TAG = "NetworkUtils";
49
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050 /**
markchien150e1912018-12-27 22:49:51 +080051 * Attaches a socket filter that drops all of incoming packets.
52 * @param fd the socket's {@link FileDescriptor}.
53 */
54 public static native void attachDropAllBPFFilter(FileDescriptor fd) throws SocketException;
55
56 /**
57 * Detaches a socket filter.
58 * @param fd the socket's {@link FileDescriptor}.
59 */
60 public static native void detachBPFFilter(FileDescriptor fd) throws SocketException;
61
62 /**
Paul Jensen38764952014-05-20 11:25:35 -040063 * Binds the current process to the network designated by {@code netId}. All sockets created
64 * in the future (and not explicitly bound via a bound {@link SocketFactory} (see
Paul Jensen6d3ff9e2014-05-29 10:12:39 -040065 * {@link Network#getSocketFactory}) will be bound to this network. Note that if this
Paul Jensen38764952014-05-20 11:25:35 -040066 * {@code Network} ever disconnects all sockets created in this way will cease to work. This
67 * is by design so an application doesn't accidentally use sockets it thinks are still bound to
Paul Jensenbcc76d32014-07-11 08:17:29 -040068 * a particular {@code Network}. Passing NETID_UNSET clears the binding.
Paul Jensen38764952014-05-20 11:25:35 -040069 */
Paul Jensen32a58f02014-06-20 13:58:14 -040070 public native static boolean bindProcessToNetwork(int netId);
Paul Jensen38764952014-05-20 11:25:35 -040071
72 /**
Paul Jensen38764952014-05-20 11:25:35 -040073 * Return the netId last passed to {@link #bindProcessToNetwork}, or NETID_UNSET if
74 * {@link #unbindProcessToNetwork} has been called since {@link #bindProcessToNetwork}.
75 */
Paul Jensen72db88e2015-03-10 10:54:12 -040076 public native static int getBoundNetworkForProcess();
Paul Jensen38764952014-05-20 11:25:35 -040077
78 /**
79 * Binds host resolutions performed by this process to the network designated by {@code netId}.
Paul Jensenbcc76d32014-07-11 08:17:29 -040080 * {@link #bindProcessToNetwork} takes precedence over this setting. Passing NETID_UNSET clears
81 * the binding.
Paul Jensen38764952014-05-20 11:25:35 -040082 *
83 * @deprecated This is strictly for legacy usage to support startUsingNetworkFeature().
84 */
Aurimas Liutikas514c5ef2016-05-24 15:22:55 -070085 @Deprecated
Paul Jensen32a58f02014-06-20 13:58:14 -040086 public native static boolean bindProcessToNetworkForHostResolution(int netId);
Paul Jensen38764952014-05-20 11:25:35 -040087
88 /**
Paul Jensen38764952014-05-20 11:25:35 -040089 * Explicitly binds {@code socketfd} to the network designated by {@code netId}. This
90 * overrides any binding via {@link #bindProcessToNetwork}.
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070091 * @return 0 on success or negative errno on failure.
Paul Jensen38764952014-05-20 11:25:35 -040092 */
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -070093 public native static int bindSocketToNetwork(int socketfd, int netId);
Paul Jensen38764952014-05-20 11:25:35 -040094
95 /**
Lorenzo Colitti4ff9f0f2015-03-17 17:56:10 +090096 * Protect {@code fd} 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 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100100 @UnsupportedAppUsage
Lorenzo Colitti4ff9f0f2015-03-17 17:56:10 +0900101 public static boolean protectFromVpn(FileDescriptor fd) {
102 return protectFromVpn(fd.getInt$());
103 }
104
105 /**
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400106 * Protect {@code socketfd} from VPN connections. After protecting, data sent through
107 * this socket will go directly to the underlying network, so its traffic will not be
108 * forwarded through the VPN.
109 */
110 public native static boolean protectFromVpn(int socketfd);
111
112 /**
Paul Jensencee9b512015-05-06 07:32:40 -0400113 * Determine if {@code uid} can access network designated by {@code netId}.
114 * @return {@code true} if {@code uid} can access network, {@code false} otherwise.
115 */
116 public native static boolean queryUserAccess(int uid, int netId);
117
118 /**
Luke Huang92ae35e2019-01-04 19:46:47 +0800119 * DNS resolver series jni method.
120 * Issue the query {@code msg} on the network designated by {@code netId}.
121 * {@code flags} is an additional config to control actual querying behavior.
122 * @return a file descriptor to watch for read events
123 */
124 public static native FileDescriptor resNetworkSend(
125 int netId, byte[] msg, int msglen, int flags) throws ErrnoException;
126
127 /**
128 * DNS resolver series jni method.
129 * Look up the {@code nsClass} {@code nsType} Resource Record (RR) associated
130 * with Domain Name {@code dname} on the network designated by {@code netId}.
131 * {@code flags} is an additional config to control actual querying behavior.
132 * @return a file descriptor to watch for read events
133 */
134 public static native FileDescriptor resNetworkQuery(
135 int netId, String dname, int nsClass, int nsType, int flags) throws ErrnoException;
136
137 /**
138 * DNS resolver series jni method.
139 * Read a result for the query associated with the {@code fd}.
Luke Huang4219ab62019-04-08 15:16:04 +0800140 * @return DnsResponse containing blob answer and rcode
Luke Huang92ae35e2019-01-04 19:46:47 +0800141 */
Luke Huang4219ab62019-04-08 15:16:04 +0800142 public static native DnsResolver.DnsResponse resNetworkResult(FileDescriptor fd)
143 throws ErrnoException;
Luke Huang92ae35e2019-01-04 19:46:47 +0800144
145 /**
Luke Huangc09f2d62019-03-08 14:48:59 +0800146 * DNS resolver series jni method.
147 * Attempts to cancel the in-progress query associated with the {@code fd}.
148 */
149 public static native void resNetworkCancel(FileDescriptor fd);
150
151 /**
Luke Huang247d83a2019-04-17 22:27:56 +0800152 * DNS resolver series jni method.
Luke Huangc211b272019-05-29 01:30:07 +0800153 * Attempts to get network which resolver will use if no network is explicitly selected.
Luke Huang247d83a2019-04-17 22:27:56 +0800154 */
Luke Huangc211b272019-05-29 01:30:07 +0800155 public static native Network getDnsNetwork() throws ErrnoException;
Luke Huang247d83a2019-04-17 22:27:56 +0800156
157 /**
markchien150e1912018-12-27 22:49:51 +0800158 * Get the tcp repair window associated with the {@code fd}.
159 *
160 * @param fd the tcp socket's {@link FileDescriptor}.
161 * @return a {@link TcpRepairWindow} object indicates tcp window size.
162 */
163 public static native TcpRepairWindow getTcpRepairWindow(FileDescriptor fd)
164 throws ErrnoException;
165
Remi NGUYEN VAN12da4a52018-07-04 11:15:56 +0900166 /**
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900167 * @see Inet4AddressUtils#intToInet4AddressHTL(int)
168 * @deprecated Use either {@link Inet4AddressUtils#intToInet4AddressHTH(int)}
169 * or {@link Inet4AddressUtils#intToInet4AddressHTL(int)}
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700170 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900171 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100172 @UnsupportedAppUsage
Robert Greenwalt585ac0f2010-08-27 09:24:29 -0700173 public static InetAddress intToInetAddress(int hostAddress) {
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900174 return Inet4AddressUtils.intToInet4AddressHTL(hostAddress);
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900175 }
176
177 /**
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900178 * @see Inet4AddressUtils#inet4AddressToIntHTL(Inet4Address)
179 * @deprecated Use either {@link Inet4AddressUtils#inet4AddressToIntHTH(Inet4Address)}
180 * or {@link Inet4AddressUtils#inet4AddressToIntHTL(Inet4Address)}
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700181 */
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900182 @Deprecated
Robert Greenwalt4717c262012-10-31 14:32:53 -0700183 public static int inetAddressToInt(Inet4Address inetAddr)
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700184 throws IllegalArgumentException {
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900185 return Inet4AddressUtils.inet4AddressToIntHTL(inetAddr);
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700186 }
187
188 /**
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900189 * @see Inet4AddressUtils#prefixLengthToV4NetmaskIntHTL(int)
190 * @deprecated Use either {@link Inet4AddressUtils#prefixLengthToV4NetmaskIntHTH(int)}
191 * or {@link Inet4AddressUtils#prefixLengthToV4NetmaskIntHTL(int)}
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900192 */
193 @Deprecated
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100194 @UnsupportedAppUsage
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700195 public static int prefixLengthToNetmaskInt(int prefixLength)
196 throws IllegalArgumentException {
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900197 return Inet4AddressUtils.prefixLengthToV4NetmaskIntHTL(prefixLength);
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700198 }
199
Irfan Sheriff96ca9172010-10-05 16:12:25 -0700200 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700201 * Convert a IPv4 netmask integer to a prefix length
Remi NGUYEN VAN0066bda2018-07-09 10:40:40 +0900202 * @param netmask as an integer (0xff000000 for a /8 subnet)
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700203 * @return the network prefix length
204 */
205 public static int netmaskIntToPrefixLength(int netmask) {
206 return Integer.bitCount(netmask);
207 }
208
209 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900210 * Convert an IPv4 netmask to a prefix length, checking that the netmask is contiguous.
211 * @param netmask as a {@code Inet4Address}.
212 * @return the network prefix length
213 * @throws IllegalArgumentException the specified netmask was not contiguous.
214 * @hide
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900215 * @deprecated use {@link Inet4AddressUtils#netmaskToPrefixLength(Inet4Address)}
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900216 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100217 @UnsupportedAppUsage
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900218 @Deprecated
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900219 public static int netmaskToPrefixLength(Inet4Address netmask) {
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900220 // This is only here because some apps seem to be using it (@UnsupportedAppUsage).
221 return Inet4AddressUtils.netmaskToPrefixLength(netmask);
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900222 }
223
224
225 /**
Robert Greenwalt0216e612011-01-14 16:29:58 -0800226 * Create an InetAddress from a string where the string must be a standard
227 * representation of a V4 or V6 address. Avoids doing a DNS lookup on failure
228 * but it will throw an IllegalArgumentException in that case.
229 * @param addrString
230 * @return the InetAddress
231 * @hide
Paul Duffina2b34f82018-10-11 15:21:46 +0100232 * @deprecated Use {@link InetAddresses#parseNumericAddress(String)}, if possible.
Robert Greenwalt0216e612011-01-14 16:29:58 -0800233 */
Paul Duffina2b34f82018-10-11 15:21:46 +0100234 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P)
235 @Deprecated
Robert Greenwalt0216e612011-01-14 16:29:58 -0800236 public static InetAddress numericToInetAddress(String addrString)
237 throws IllegalArgumentException {
Elliott Hughesf5bbb572011-02-15 17:11:29 -0800238 return InetAddress.parseNumericAddress(addrString);
Robert Greenwalt0216e612011-01-14 16:29:58 -0800239 }
240
241 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900242 * Masks a raw IP address byte array with the specified prefix length.
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700243 */
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900244 public static void maskRawAddress(byte[] array, int prefixLength) {
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700245 if (prefixLength < 0 || prefixLength > array.length * 8) {
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900246 throw new RuntimeException("IP address with " + array.length +
247 " bytes has invalid prefix length " + prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700248 }
249
250 int offset = prefixLength / 8;
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900251 int remainder = prefixLength % 8;
252 byte mask = (byte)(0xFF << (8 - remainder));
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700253
254 if (offset < array.length) array[offset] = (byte)(array[offset] & mask);
255
256 offset++;
257
258 for (; offset < array.length; offset++) {
259 array[offset] = 0;
260 }
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900261 }
262
263 /**
264 * Get InetAddress masked with prefixLength. Will never return null.
265 * @param address the IP address to mask with
266 * @param prefixLength the prefixLength used to mask the IP
267 */
268 public static InetAddress getNetworkPart(InetAddress address, int prefixLength) {
269 byte[] array = address.getAddress();
270 maskRawAddress(array, prefixLength);
Robert Greenwaltf43396c2011-05-06 17:10:53 -0700271
272 InetAddress netPart = null;
273 try {
274 netPart = InetAddress.getByAddress(array);
275 } catch (UnknownHostException e) {
276 throw new RuntimeException("getNetworkPart error - " + e.toString());
277 }
278 return netPart;
279 }
280
281 /**
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900282 * Returns the implicit netmask of an IPv4 address, as was the custom before 1993.
283 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100284 @UnsupportedAppUsage
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900285 public static int getImplicitNetmask(Inet4Address address) {
Remi NGUYEN VAN77dd54d2019-01-25 08:54:08 +0900286 // Only here because it seems to be used by apps
287 return Inet4AddressUtils.getImplicitNetmask(address);
Lorenzo Colitti475085b2015-03-10 01:32:40 +0900288 }
289
290 /**
Lorenzo Colitti8c6c2c32014-06-12 13:41:17 +0900291 * Utility method to parse strings such as "192.0.2.5/24" or "2001:db8::cafe:d00d/64".
292 * @hide
293 */
294 public static Pair<InetAddress, Integer> parseIpAndMask(String ipAndMaskString) {
295 InetAddress address = null;
296 int prefixLength = -1;
297 try {
298 String[] pieces = ipAndMaskString.split("/", 2);
299 prefixLength = Integer.parseInt(pieces[1]);
300 address = InetAddress.parseNumericAddress(pieces[0]);
301 } catch (NullPointerException e) { // Null string.
302 } catch (ArrayIndexOutOfBoundsException e) { // No prefix length.
303 } catch (NumberFormatException e) { // Non-numeric prefix.
304 } catch (IllegalArgumentException e) { // Invalid IP address.
305 }
306
307 if (address == null || prefixLength == -1) {
308 throw new IllegalArgumentException("Invalid IP address and mask " + ipAndMaskString);
309 }
310
311 return new Pair<InetAddress, Integer>(address, prefixLength);
312 }
313
314 /**
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700315 * Convert a 32 char hex string into a Inet6Address.
316 * throws a runtime exception if the string isn't 32 chars, isn't hex or can't be
317 * made into an Inet6Address
318 * @param addrHexString a 32 character hex string representing an IPv6 addr
319 * @return addr an InetAddress representation for the string
320 */
321 public static InetAddress hexToInet6Address(String addrHexString)
322 throws IllegalArgumentException {
323 try {
Jeff Sharkeyfea17de2013-06-11 14:13:09 -0700324 return numericToInetAddress(String.format(Locale.US, "%s:%s:%s:%s:%s:%s:%s:%s",
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700325 addrHexString.substring(0,4), addrHexString.substring(4,8),
326 addrHexString.substring(8,12), addrHexString.substring(12,16),
327 addrHexString.substring(16,20), addrHexString.substring(20,24),
328 addrHexString.substring(24,28), addrHexString.substring(28,32)));
329 } catch (Exception e) {
330 Log.e("NetworkUtils", "error in hexToInet6Address(" + addrHexString + "): " + e);
331 throw new IllegalArgumentException(e);
332 }
333 }
Robert Greenwalta10b7fd2011-07-25 16:06:25 -0700334
335 /**
336 * Create a string array of host addresses from a collection of InetAddresses
337 * @param addrs a Collection of InetAddresses
338 * @return an array of Strings containing their host addresses
339 */
340 public static String[] makeStrings(Collection<InetAddress> addrs) {
341 String[] result = new String[addrs.size()];
342 int i = 0;
343 for (InetAddress addr : addrs) {
344 result[i++] = addr.getHostAddress();
345 }
346 return result;
347 }
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800348
349 /**
350 * Trim leading zeros from IPv4 address strings
351 * Our base libraries will interpret that as octel..
352 * Must leave non v4 addresses and host names alone.
353 * For example, 192.168.000.010 -> 192.168.0.10
354 * TODO - fix base libraries and remove this function
355 * @param addr a string representing an ip addr
356 * @return a string propertly trimmed
357 */
Mathew Inwoodfa3a7462018-08-08 14:52:47 +0100358 @UnsupportedAppUsage
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800359 public static String trimV4AddrZeros(String addr) {
Robert Greenwalt0faacf02011-12-07 16:43:59 -0800360 if (addr == null) return null;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800361 String[] octets = addr.split("\\.");
362 if (octets.length != 4) return addr;
363 StringBuilder builder = new StringBuilder(16);
364 String result = null;
365 for (int i = 0; i < 4; i++) {
366 try {
Robert Greenwalt3957b5f2011-12-07 13:10:59 -0800367 if (octets[i].length() > 3) return addr;
Robert Greenwaltd4420ab2011-12-07 09:58:48 -0800368 builder.append(Integer.parseInt(octets[i]));
369 } catch (NumberFormatException e) {
370 return addr;
371 }
372 if (i < 3) builder.append('.');
373 }
374 result = builder.toString();
375 return result;
376 }
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900377
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000378 /**
379 * Returns a prefix set without overlaps.
380 *
381 * This expects the src set to be sorted from shorter to longer. Results are undefined
382 * failing this condition. The returned prefix set is sorted in the same order as the
383 * passed set, with the same comparator.
384 */
385 private static TreeSet<IpPrefix> deduplicatePrefixSet(final TreeSet<IpPrefix> src) {
386 final TreeSet<IpPrefix> dst = new TreeSet<>(src.comparator());
387 // Prefixes match addresses that share their upper part up to their length, therefore
388 // the only kind of possible overlap in two prefixes is strict inclusion of the longer
389 // (more restrictive) in the shorter (including equivalence if they have the same
390 // length).
391 // Because prefixes in the src set are sorted from shorter to longer, deduplicating
392 // is done by simply iterating in order, and not adding any longer prefix that is
393 // already covered by a shorter one.
394 newPrefixes:
395 for (IpPrefix newPrefix : src) {
396 for (IpPrefix existingPrefix : dst) {
397 if (existingPrefix.containsPrefix(newPrefix)) {
398 continue newPrefixes;
399 }
400 }
401 dst.add(newPrefix);
402 }
403 return dst;
404 }
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900405
406 /**
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000407 * Returns how many IPv4 addresses match any of the prefixes in the passed ordered set.
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900408 *
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000409 * Obviously this returns an integral value between 0 and 2**32.
410 * The behavior is undefined if any of the prefixes is not an IPv4 prefix or if the
411 * set is not ordered smallest prefix to longer prefix.
412 *
413 * @param prefixes the set of prefixes, ordered by length
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900414 */
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000415 public static long routedIPv4AddressCount(final TreeSet<IpPrefix> prefixes) {
416 long routedIPCount = 0;
417 for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) {
418 if (!prefix.isIPv4()) {
419 Log.wtf(TAG, "Non-IPv4 prefix in routedIPv4AddressCount");
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900420 }
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000421 int rank = 32 - prefix.getPrefixLength();
422 routedIPCount += 1L << rank;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900423 }
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000424 return routedIPCount;
425 }
Chalard Jeandd16d442019-07-08 16:50:44 +0900426
Fedor Kudasove5cb0a22019-07-09 09:23:25 +0000427 /**
428 * Returns how many IPv6 addresses match any of the prefixes in the passed ordered set.
429 *
430 * This returns a BigInteger between 0 and 2**128.
431 * The behavior is undefined if any of the prefixes is not an IPv6 prefix or if the
432 * set is not ordered smallest prefix to longer prefix.
433 */
434 public static BigInteger routedIPv6AddressCount(final TreeSet<IpPrefix> prefixes) {
435 BigInteger routedIPCount = BigInteger.ZERO;
436 for (final IpPrefix prefix : deduplicatePrefixSet(prefixes)) {
437 if (!prefix.isIPv6()) {
438 Log.wtf(TAG, "Non-IPv6 prefix in routedIPv6AddressCount");
439 }
440 int rank = 128 - prefix.getPrefixLength();
441 routedIPCount = routedIPCount.add(BigInteger.ONE.shiftLeft(rank));
442 }
443 return routedIPCount;
Chalard Jeanadbf1d02018-02-26 11:52:46 +0900444 }
Eran Messeria2e0ca72018-09-20 15:15:41 +0100445
446 private static final int[] ADDRESS_FAMILIES = new int[] {AF_INET, AF_INET6};
447
448 /**
449 * Returns true if the hostname is weakly validated.
450 * @param hostname Name of host to validate.
451 * @return True if it's a valid-ish hostname.
452 *
453 * @hide
454 */
455 public static boolean isWeaklyValidatedHostname(@NonNull String hostname) {
456 // TODO(b/34953048): Use a validation method that permits more accurate,
457 // but still inexpensive, checking of likely valid DNS hostnames.
458 final String weakHostnameRegex = "^[a-zA-Z0-9_.-]+$";
459 if (!hostname.matches(weakHostnameRegex)) {
460 return false;
461 }
462
463 for (int address_family : ADDRESS_FAMILIES) {
464 if (Os.inet_pton(address_family, hostname) != null) {
465 return false;
466 }
467 }
468
469 return true;
470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800471}