1 /*
2  * Copyright (C) 2019 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.util;
18 
19 import android.content.Context;
20 import android.content.pm.PackageManager.NameNotFoundException;
21 import android.provider.DeviceConfig;
22 import android.util.Log;
23 import android.util.SparseArray;
24 
25 import androidx.annotation.NonNull;
26 import androidx.annotation.Nullable;
27 
28 import java.io.FileDescriptor;
29 import java.io.IOException;
30 import java.net.Inet4Address;
31 import java.net.Inet6Address;
32 import java.net.InetAddress;
33 import java.net.SocketException;
34 import java.util.List;
35 import java.util.function.Predicate;
36 
37 /**
38  * Collection of utilities for the network stack.
39  */
40 public class NetworkStackUtils {
41     private static final String TAG = "NetworkStackUtils";
42 
43     /**
44      * A list of captive portal detection specifications used in addition to the fallback URLs.
45      * Each spec has the format url@@/@@statusCodeRegex@@/@@contentRegex. Specs are separated
46      * by "@@,@@".
47      */
48     public static final String CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS =
49             "captive_portal_fallback_probe_specs";
50 
51     /**
52      * A comma separated list of URLs used for captive portal detection in addition to the
53      * fallback HTTP url associated with the CAPTIVE_PORTAL_FALLBACK_URL settings.
54      */
55     public static final String CAPTIVE_PORTAL_OTHER_FALLBACK_URLS =
56             "captive_portal_other_fallback_urls";
57 
58     /**
59      * A comma separated list of URLs used for captive portal detection in addition to the HTTP url
60      * associated with the CAPTIVE_PORTAL_HTTP_URL settings.
61      */
62     public static final String CAPTIVE_PORTAL_OTHER_HTTP_URLS = "captive_portal_other_http_urls";
63 
64     /**
65      * A comma separated list of URLs used for network validation. in addition to the HTTPS url
66      * associated with the CAPTIVE_PORTAL_HTTPS_URL settings.
67      */
68     public static final String CAPTIVE_PORTAL_OTHER_HTTPS_URLS = "captive_portal_other_https_urls";
69 
70     /**
71      * Which User-Agent string to use in the header of the captive portal detection probes.
72      * The User-Agent field is unset when this setting has no value (HttpUrlConnection default).
73      */
74     public static final String CAPTIVE_PORTAL_USER_AGENT = "captive_portal_user_agent";
75 
76     /**
77      * Whether to use HTTPS for network validation. This is enabled by default and the setting
78      * needs to be set to 0 to disable it. This setting is a misnomer because captive portals
79      * don't actually use HTTPS, but it's consistent with the other settings.
80      */
81     public static final String CAPTIVE_PORTAL_USE_HTTPS = "captive_portal_use_https";
82 
83     /**
84      * The URL used for HTTPS captive portal detection upon a new connection.
85      * A 204 response code from the server is used for validation.
86      */
87     public static final String CAPTIVE_PORTAL_HTTPS_URL = "captive_portal_https_url";
88 
89     /**
90      * The URL used for HTTP captive portal detection upon a new connection.
91      * A 204 response code from the server is used for validation.
92      */
93     public static final String CAPTIVE_PORTAL_HTTP_URL = "captive_portal_http_url";
94 
95     /**
96      * A test URL used to override configuration settings and overlays for the network validation
97      * HTTPS URL, when set in {@link android.provider.DeviceConfig} configuration.
98      *
99      * <p>This URL will be ignored if the host is not "localhost" (it can only be used to test with
100      * a local test server), and must not be set in production scenarios (as enforced by CTS tests).
101      *
102      * <p>{@link #TEST_URL_EXPIRATION_TIME} must also be set to use this setting.
103      */
104     public static final String TEST_CAPTIVE_PORTAL_HTTPS_URL = "test_captive_portal_https_url";
105 
106     /**
107      * A test URL used to override configuration settings and overlays for the network validation
108      * HTTP URL, when set in {@link android.provider.DeviceConfig} configuration.
109      *
110      * <p>This URL will be ignored if the host is not "localhost" (it can only be used to test with
111      * a local test server), and must not be set in production scenarios (as enforced by CTS tests).
112      *
113      * <p>{@link #TEST_URL_EXPIRATION_TIME} must also be set to use this setting.
114      */
115     public static final String TEST_CAPTIVE_PORTAL_HTTP_URL = "test_captive_portal_http_url";
116 
117     /**
118      * Expiration time of the test URL, in ms, relative to {@link System#currentTimeMillis()}.
119      *
120      * <p>After this expiration time, test URLs will be ignored. They will also be ignored if
121      * the expiration time is more than 10 minutes in the future, to avoid misconfiguration
122      * following test runs.
123      */
124     public static final String TEST_URL_EXPIRATION_TIME = "test_url_expiration_time";
125 
126     /**
127      * The URL used for fallback HTTP captive portal detection when previous HTTP
128      * and HTTPS captive portal detection attemps did not return a conclusive answer.
129      */
130     public static final String CAPTIVE_PORTAL_FALLBACK_URL = "captive_portal_fallback_url";
131 
132     /**
133      * What to do when connecting a network that presents a captive portal.
134      * Must be one of the CAPTIVE_PORTAL_MODE_* constants above.
135      *
136      * The default for this setting is CAPTIVE_PORTAL_MODE_PROMPT.
137      */
138     public static final String CAPTIVE_PORTAL_MODE = "captive_portal_mode";
139 
140     /**
141      * Don't attempt to detect captive portals.
142      */
143     public static final int CAPTIVE_PORTAL_MODE_IGNORE = 0;
144 
145     /**
146      * When detecting a captive portal, display a notification that
147      * prompts the user to sign in.
148      */
149     public static final int CAPTIVE_PORTAL_MODE_PROMPT = 1;
150 
151     /**
152      * When detecting a captive portal, immediately disconnect from the
153      * network and do not reconnect to that network in the future.
154      */
155     public static final int CAPTIVE_PORTAL_MODE_AVOID = 2;
156 
157     /**
158      * DNS probe timeout for network validation. Enough for 3 DNS queries 5 seconds apart.
159      */
160     public static final int DEFAULT_CAPTIVE_PORTAL_DNS_PROBE_TIMEOUT = 12500;
161 
162     /**
163      * List of fallback probe specs to use for detecting captive portals. This is an alternative to
164      * fallback URLs that provides more flexibility on detection rules. Empty, so unused by default.
165      */
166     public static final String[] DEFAULT_CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS =
167             new String[] {};
168 
169     /**
170      * The default list of HTTP URLs to use for detecting captive portals.
171      */
172     public static final String[] DEFAULT_CAPTIVE_PORTAL_HTTP_URLS =
173             new String [] {"http://connectivitycheck.gstatic.com/generate_204"};
174 
175     /**
176      * The default list of HTTPS URLs for network validation, to use for confirming internet
177      * connectivity.
178      */
179     public static final String[] DEFAULT_CAPTIVE_PORTAL_HTTPS_URLS =
180             new String [] {"https://www.google.com/generate_204"};
181 
182     /**
183      * @deprecated Considering boolean experiment flag is likely to cause misconfiguration
184      *             particularly when NetworkStack module rolls back to previous version. It's
185      *             much safer to determine whether or not to enable one specific experimental
186      *             feature by comparing flag version with module version.
187      */
188     @Deprecated
189     public static final String DHCP_INIT_REBOOT_ENABLED = "dhcp_init_reboot_enabled";
190 
191     /**
192      * @deprecated See above explanation.
193      */
194     @Deprecated
195     public static final String DHCP_RAPID_COMMIT_ENABLED = "dhcp_rapid_commit_enabled";
196 
197     /**
198      * Minimum module version at which to enable the DHCP INIT-REBOOT state.
199      */
200     public static final String DHCP_INIT_REBOOT_VERSION = "dhcp_init_reboot_version";
201 
202     /**
203      * Minimum module version at which to enable the DHCP Rapid Commit option.
204      */
205     public static final String DHCP_RAPID_COMMIT_VERSION = "dhcp_rapid_commit_version";
206 
207     /**
208      * Minimum module version at which to enable the IP address conflict detection feature.
209      */
210     public static final String DHCP_IP_CONFLICT_DETECT_VERSION = "dhcp_ip_conflict_detect_version";
211 
212     /**
213      * Minimum module version at which to enable dismissal CaptivePortalLogin app in validated
214      * network feature. CaptivePortalLogin app will also use validation facilities in
215      * {@link NetworkMonitor} to perform portal validation if feature is enabled.
216      */
217     public static final String DISMISS_PORTAL_IN_VALIDATED_NETWORK =
218             "dismiss_portal_in_validated_network";
219 
220     /**
221      * Experiment flag to enable considering DNS probes returning private IP addresses as failed
222      * when attempting to detect captive portals.
223      *
224      * This flag is enabled if !=0 and less than the module APK version.
225      */
226     public static final String DNS_PROBE_PRIVATE_IP_NO_INTERNET_VERSION =
227             "dns_probe_private_ip_no_internet";
228 
229     /**
230      * Experiment flag to enable validation metrics sent by NetworkMonitor.
231      *
232      * Metrics are sent by default. They can be disabled by setting the flag to a number greater
233      * than the APK version (for example 999999999).
234      * @see #isFeatureEnabled(Context, String, String, boolean)
235      */
236     public static final String VALIDATION_METRICS_VERSION = "validation_metrics_version";
237 
238     static {
239         System.loadLibrary("networkstackutilsjni");
240     }
241 
242     /**
243      * @return True if the array is null or 0-length.
244      */
isEmpty(T[] array)245     public static <T> boolean isEmpty(T[] array) {
246         return array == null || array.length == 0;
247     }
248 
249     /**
250      * Close a socket, ignoring any exception while closing.
251      */
closeSocketQuietly(FileDescriptor fd)252     public static void closeSocketQuietly(FileDescriptor fd) {
253         try {
254             SocketUtils.closeSocket(fd);
255         } catch (IOException ignored) {
256         }
257     }
258 
259     /**
260      * Returns an int array from the given Integer list.
261      */
convertToIntArray(@onNull List<Integer> list)262     public static int[] convertToIntArray(@NonNull List<Integer> list) {
263         int[] array = new int[list.size()];
264         for (int i = 0; i < list.size(); i++) {
265             array[i] = list.get(i);
266         }
267         return array;
268     }
269 
270     /**
271      * Returns a long array from the given long list.
272      */
convertToLongArray(@onNull List<Long> list)273     public static long[] convertToLongArray(@NonNull List<Long> list) {
274         long[] array = new long[list.size()];
275         for (int i = 0; i < list.size(); i++) {
276             array[i] = list.get(i);
277         }
278         return array;
279     }
280 
281     /**
282      * @return True if there exists at least one element in the sparse array for which
283      * condition {@code predicate}
284      */
any(SparseArray<T> array, Predicate<T> predicate)285     public static <T> boolean any(SparseArray<T> array, Predicate<T> predicate) {
286         for (int i = 0; i < array.size(); ++i) {
287             if (predicate.test(array.valueAt(i))) {
288                 return true;
289             }
290         }
291         return false;
292     }
293 
294     /**
295      * Look up the value of a property for a particular namespace from {@link DeviceConfig}.
296      * @param namespace The namespace containing the property to look up.
297      * @param name The name of the property to look up.
298      * @param defaultValue The value to return if the property does not exist or has no valid value.
299      * @return the corresponding value, or defaultValue if none exists.
300      */
301     @Nullable
getDeviceConfigProperty(@onNull String namespace, @NonNull String name, @Nullable String defaultValue)302     public static String getDeviceConfigProperty(@NonNull String namespace, @NonNull String name,
303             @Nullable String defaultValue) {
304         String value = DeviceConfig.getProperty(namespace, name);
305         return value != null ? value : defaultValue;
306     }
307 
308     /**
309      * Look up the value of a property for a particular namespace from {@link DeviceConfig}.
310      * @param namespace The namespace containing the property to look up.
311      * @param name The name of the property to look up.
312      * @param defaultValue The value to return if the property does not exist or its value is null.
313      * @return the corresponding value, or defaultValue if none exists.
314      */
getDeviceConfigPropertyInt(@onNull String namespace, @NonNull String name, int defaultValue)315     public static int getDeviceConfigPropertyInt(@NonNull String namespace, @NonNull String name,
316             int defaultValue) {
317         String value = getDeviceConfigProperty(namespace, name, null /* defaultValue */);
318         try {
319             return (value != null) ? Integer.parseInt(value) : defaultValue;
320         } catch (NumberFormatException e) {
321             return defaultValue;
322         }
323     }
324 
325     /**
326      * Look up the value of a property for a particular namespace from {@link DeviceConfig}.
327      * @param namespace The namespace containing the property to look up.
328      * @param name The name of the property to look up.
329      * @param minimumValue The minimum value of a property.
330      * @param maximumValue The maximum value of a property.
331      * @param defaultValue The value to return if the property does not exist or its value is null.
332      * @return the corresponding value, or defaultValue if none exists or the fetched value is
333      *         greater than maximumValue.
334      */
getDeviceConfigPropertyInt(@onNull String namespace, @NonNull String name, int minimumValue, int maximumValue, int defaultValue)335     public static int getDeviceConfigPropertyInt(@NonNull String namespace, @NonNull String name,
336             int minimumValue, int maximumValue, int defaultValue) {
337         int value = getDeviceConfigPropertyInt(namespace, name, defaultValue);
338         if (value < minimumValue || value > maximumValue) return defaultValue;
339         return value;
340     }
341 
342     /**
343      * Look up the value of a property for a particular namespace from {@link DeviceConfig}.
344      * @param namespace The namespace containing the property to look up.
345      * @param name The name of the property to look up.
346      * @param defaultValue The value to return if the property does not exist or its value is null.
347      * @return the corresponding value, or defaultValue if none exists.
348      */
getDeviceConfigPropertyBoolean(@onNull String namespace, @NonNull String name, boolean defaultValue)349     public static boolean getDeviceConfigPropertyBoolean(@NonNull String namespace,
350             @NonNull String name, boolean defaultValue) {
351         String value = getDeviceConfigProperty(namespace, name, null /* defaultValue */);
352         return (value != null) ? Boolean.parseBoolean(value) : defaultValue;
353     }
354 
355     /**
356      * Check whether or not one specific experimental feature for a particular namespace from
357      * {@link DeviceConfig} is enabled by comparing NetworkStack module version {@link NetworkStack}
358      * with current version of property. If this property version is valid, the corresponding
359      * experimental feature would be enabled, otherwise disabled.
360      *
361      * This is useful to ensure that if a module install is rolled back, flags are not left fully
362      * rolled out on a version where they have not been well tested.
363      * @param context The global context information about an app environment.
364      * @param namespace The namespace containing the property to look up.
365      * @param name The name of the property to look up.
366      * @return true if this feature is enabled, or false if disabled.
367      */
isFeatureEnabled(@onNull Context context, @NonNull String namespace, @NonNull String name)368     public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace,
369             @NonNull String name) {
370         return isFeatureEnabled(context, namespace, name, false /* defaultEnabled */);
371     }
372 
373     /**
374      * Check whether or not one specific experimental feature for a particular namespace from
375      * {@link DeviceConfig} is enabled by comparing NetworkStack module version {@link NetworkStack}
376      * with current version of property. If this property version is valid, the corresponding
377      * experimental feature would be enabled, otherwise disabled.
378      *
379      * This is useful to ensure that if a module install is rolled back, flags are not left fully
380      * rolled out on a version where they have not been well tested.
381      * @param context The global context information about an app environment.
382      * @param namespace The namespace containing the property to look up.
383      * @param name The name of the property to look up.
384      * @param defaultEnabled The value to return if the property does not exist or its value is
385      *                       null.
386      * @return true if this feature is enabled, or false if disabled.
387      */
isFeatureEnabled(@onNull Context context, @NonNull String namespace, @NonNull String name, boolean defaultEnabled)388     public static boolean isFeatureEnabled(@NonNull Context context, @NonNull String namespace,
389             @NonNull String name, boolean defaultEnabled) {
390         try {
391             final int propertyVersion = getDeviceConfigPropertyInt(namespace, name,
392                     0 /* default value */);
393             final long packageVersion = context.getPackageManager().getPackageInfo(
394                     context.getPackageName(), 0).getLongVersionCode();
395             return (propertyVersion == 0 && defaultEnabled)
396                     || (propertyVersion != 0 && packageVersion >= (long) propertyVersion);
397         } catch (NameNotFoundException e) {
398             Log.e(TAG, "Could not find the package name", e);
399             return false;
400         }
401     }
402 
403     /**
404      * Attaches a socket filter that accepts DHCP packets to the given socket.
405      */
attachDhcpFilter(FileDescriptor fd)406     public static native void attachDhcpFilter(FileDescriptor fd) throws SocketException;
407 
408     /**
409      * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket.
410      * @param fd the socket's {@link FileDescriptor}.
411      * @param packetType the hardware address type, one of ARPHRD_*.
412      */
attachRaFilter(FileDescriptor fd, int packetType)413     public static native void attachRaFilter(FileDescriptor fd, int packetType)
414             throws SocketException;
415 
416     /**
417      * Attaches a socket filter that accepts L2-L4 signaling traffic required for IP connectivity.
418      *
419      * This includes: all ARP, ICMPv6 RS/RA/NS/NA messages, and DHCPv4 exchanges.
420      *
421      * @param fd the socket's {@link FileDescriptor}.
422      * @param packetType the hardware address type, one of ARPHRD_*.
423      */
attachControlPacketFilter(FileDescriptor fd, int packetType)424     public static native void attachControlPacketFilter(FileDescriptor fd, int packetType)
425             throws SocketException;
426 
427     /**
428      * Add an entry into the ARP cache.
429      */
addArpEntry(Inet4Address ipv4Addr, android.net.MacAddress ethAddr, String ifname, FileDescriptor fd)430     public static void addArpEntry(Inet4Address ipv4Addr, android.net.MacAddress ethAddr,
431             String ifname, FileDescriptor fd) throws IOException {
432         addArpEntry(ethAddr.toByteArray(), ipv4Addr.getAddress(), ifname, fd);
433     }
434 
addArpEntry(byte[] ethAddr, byte[] netAddr, String ifname, FileDescriptor fd)435     private static native void addArpEntry(byte[] ethAddr, byte[] netAddr, String ifname,
436             FileDescriptor fd) throws IOException;
437 
438     /**
439      * Return IP address and port in a string format.
440      */
addressAndPortToString(InetAddress address, int port)441     public static String addressAndPortToString(InetAddress address, int port) {
442         return String.format(
443                 (address instanceof Inet6Address) ? "[%s]:%d" : "%s:%d",
444                         address.getHostAddress(), port);
445     }
446 
447     /**
448      * Return true if the provided address is non-null and an IPv6 Unique Local Address (RFC4193).
449      */
isIPv6ULA(@ullable InetAddress addr)450     public static boolean isIPv6ULA(@Nullable InetAddress addr) {
451         return addr instanceof Inet6Address
452                 && ((addr.getAddress()[0] & 0xfe) == 0xfc);
453     }
454 
455     /**
456      * Returns the {@code int} nearest in value to {@code value}.
457      *
458      * @param value any {@code long} value
459      * @return the same value cast to {@code int} if it is in the range of the {@code int}
460      * type, {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if
461      * it is too small
462      */
saturatedCast(long value)463     public static int saturatedCast(long value) {
464         if (value > Integer.MAX_VALUE) {
465             return Integer.MAX_VALUE;
466         }
467         if (value < Integer.MIN_VALUE) {
468             return Integer.MIN_VALUE;
469         }
470         return (int) value;
471     }
472 }
473