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