• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.annotation.NonNull;
20 import android.annotation.Nullable;
21 import android.provider.DeviceConfig;
22 import android.util.SparseArray;
23 
24 import java.io.FileDescriptor;
25 import java.io.IOException;
26 import java.net.Inet4Address;
27 import java.net.Inet6Address;
28 import java.net.InetAddress;
29 import java.net.SocketException;
30 import java.util.List;
31 import java.util.function.Predicate;
32 
33 /**
34  * Collection of utilities for the network stack.
35  */
36 public class NetworkStackUtils {
37     // TODO: Refer to DeviceConfig definition.
38     public static final String NAMESPACE_CONNECTIVITY = "connectivity";
39 
40     /**
41      * A list of captive portal detection specifications used in addition to the fallback URLs.
42      * Each spec has the format url@@/@@statusCodeRegex@@/@@contentRegex. Specs are separated
43      * by "@@,@@".
44      */
45     public static final String CAPTIVE_PORTAL_FALLBACK_PROBE_SPECS =
46             "captive_portal_fallback_probe_specs";
47 
48     /**
49      * A comma separated list of URLs used for captive portal detection in addition to the
50      * fallback HTTP url associated with the CAPTIVE_PORTAL_FALLBACK_URL settings.
51      */
52     public static final String CAPTIVE_PORTAL_OTHER_FALLBACK_URLS =
53             "captive_portal_other_fallback_urls";
54 
55     /**
56      * Which User-Agent string to use in the header of the captive portal detection probes.
57      * The User-Agent field is unset when this setting has no value (HttpUrlConnection default).
58      */
59     public static final String CAPTIVE_PORTAL_USER_AGENT = "captive_portal_user_agent";
60 
61     /**
62      * Whether to use HTTPS for network validation. This is enabled by default and the setting
63      * needs to be set to 0 to disable it. This setting is a misnomer because captive portals
64      * don't actually use HTTPS, but it's consistent with the other settings.
65      */
66     public static final String CAPTIVE_PORTAL_USE_HTTPS = "captive_portal_use_https";
67 
68     /**
69      * The URL used for HTTPS captive portal detection upon a new connection.
70      * A 204 response code from the server is used for validation.
71      */
72     public static final String CAPTIVE_PORTAL_HTTPS_URL = "captive_portal_https_url";
73 
74     /**
75      * The URL used for HTTP captive portal detection upon a new connection.
76      * A 204 response code from the server is used for validation.
77      */
78     public static final String CAPTIVE_PORTAL_HTTP_URL = "captive_portal_http_url";
79 
80     /**
81      * The URL used for fallback HTTP captive portal detection when previous HTTP
82      * and HTTPS captive portal detection attemps did not return a conclusive answer.
83      */
84     public static final String CAPTIVE_PORTAL_FALLBACK_URL = "captive_portal_fallback_url";
85 
86     /**
87      * What to do when connecting a network that presents a captive portal.
88      * Must be one of the CAPTIVE_PORTAL_MODE_* constants above.
89      *
90      * The default for this setting is CAPTIVE_PORTAL_MODE_PROMPT.
91      */
92     public static final String CAPTIVE_PORTAL_MODE = "captive_portal_mode";
93 
94     /**
95      * Don't attempt to detect captive portals.
96      */
97     public static final int CAPTIVE_PORTAL_MODE_IGNORE = 0;
98 
99     /**
100      * When detecting a captive portal, display a notification that
101      * prompts the user to sign in.
102      */
103     public static final int CAPTIVE_PORTAL_MODE_PROMPT = 1;
104 
105     /**
106      * When detecting a captive portal, immediately disconnect from the
107      * network and do not reconnect to that network in the future.
108      */
109     public static final int CAPTIVE_PORTAL_MODE_AVOID = 2;
110 
111     static {
112         System.loadLibrary("networkstackutilsjni");
113     }
114 
115     /**
116      * @return True if the array is null or 0-length.
117      */
isEmpty(T[] array)118     public static <T> boolean isEmpty(T[] array) {
119         return array == null || array.length == 0;
120     }
121 
122     /**
123      * Close a socket, ignoring any exception while closing.
124      */
closeSocketQuietly(FileDescriptor fd)125     public static void closeSocketQuietly(FileDescriptor fd) {
126         try {
127             SocketUtils.closeSocket(fd);
128         } catch (IOException ignored) {
129         }
130     }
131 
132     /**
133      * Returns an int array from the given Integer list.
134      */
convertToIntArray(@onNull List<Integer> list)135     public static int[] convertToIntArray(@NonNull List<Integer> list) {
136         int[] array = new int[list.size()];
137         for (int i = 0; i < list.size(); i++) {
138             array[i] = list.get(i);
139         }
140         return array;
141     }
142 
143     /**
144      * Returns a long array from the given long list.
145      */
convertToLongArray(@onNull List<Long> list)146     public static long[] convertToLongArray(@NonNull List<Long> list) {
147         long[] array = new long[list.size()];
148         for (int i = 0; i < list.size(); i++) {
149             array[i] = list.get(i);
150         }
151         return array;
152     }
153 
154     /**
155      * @return True if there exists at least one element in the sparse array for which
156      * condition {@code predicate}
157      */
any(SparseArray<T> array, Predicate<T> predicate)158     public static <T> boolean any(SparseArray<T> array, Predicate<T> predicate) {
159         for (int i = 0; i < array.size(); ++i) {
160             if (predicate.test(array.valueAt(i))) {
161                 return true;
162             }
163         }
164         return false;
165     }
166 
167     /**
168      * Look up the value of a property for a particular namespace from {@link DeviceConfig}.
169      * @param namespace The namespace containing the property to look up.
170      * @param name The name of the property to look up.
171      * @param defaultValue The value to return if the property does not exist or has no valid value.
172      * @return the corresponding value, or defaultValue if none exists.
173      */
174     @Nullable
getDeviceConfigProperty(@onNull String namespace, @NonNull String name, @Nullable String defaultValue)175     public static String getDeviceConfigProperty(@NonNull String namespace, @NonNull String name,
176             @Nullable String defaultValue) {
177         String value = DeviceConfig.getProperty(namespace, name);
178         return value != null ? value : defaultValue;
179     }
180 
181     /**
182      * Look up the value of a property for a particular namespace from {@link DeviceConfig}.
183      * @param namespace The namespace containing the property to look up.
184      * @param name The name of the property to look up.
185      * @param defaultValue The value to return if the property does not exist or has no non-null
186      *                     value.
187      * @return the corresponding value, or defaultValue if none exists.
188      */
getDeviceConfigPropertyInt(@onNull String namespace, @NonNull String name, int defaultValue)189     public static int getDeviceConfigPropertyInt(@NonNull String namespace, @NonNull String name,
190             int defaultValue) {
191         String value = getDeviceConfigProperty(namespace, name, null /* defaultValue */);
192         try {
193             return (value != null) ? Integer.parseInt(value) : defaultValue;
194         } catch (NumberFormatException e) {
195             return defaultValue;
196         }
197     }
198 
199     /**
200      * Attaches a socket filter that accepts DHCP packets to the given socket.
201      */
attachDhcpFilter(FileDescriptor fd)202     public static native void attachDhcpFilter(FileDescriptor fd) throws SocketException;
203 
204     /**
205      * Attaches a socket filter that accepts ICMPv6 router advertisements to the given socket.
206      * @param fd the socket's {@link FileDescriptor}.
207      * @param packetType the hardware address type, one of ARPHRD_*.
208      */
attachRaFilter(FileDescriptor fd, int packetType)209     public static native void attachRaFilter(FileDescriptor fd, int packetType)
210             throws SocketException;
211 
212     /**
213      * Attaches a socket filter that accepts L2-L4 signaling traffic required for IP connectivity.
214      *
215      * This includes: all ARP, ICMPv6 RS/RA/NS/NA messages, and DHCPv4 exchanges.
216      *
217      * @param fd the socket's {@link FileDescriptor}.
218      * @param packetType the hardware address type, one of ARPHRD_*.
219      */
attachControlPacketFilter(FileDescriptor fd, int packetType)220     public static native void attachControlPacketFilter(FileDescriptor fd, int packetType)
221             throws SocketException;
222 
223     /**
224      * Add an entry into the ARP cache.
225      */
addArpEntry(Inet4Address ipv4Addr, android.net.MacAddress ethAddr, String ifname, FileDescriptor fd)226     public static void addArpEntry(Inet4Address ipv4Addr, android.net.MacAddress ethAddr,
227             String ifname, FileDescriptor fd) throws IOException {
228         addArpEntry(ethAddr.toByteArray(), ipv4Addr.getAddress(), ifname, fd);
229     }
230 
addArpEntry(byte[] ethAddr, byte[] netAddr, String ifname, FileDescriptor fd)231     private static native void addArpEntry(byte[] ethAddr, byte[] netAddr, String ifname,
232             FileDescriptor fd) throws IOException;
233 
234     /**
235      * Return IP address and port in a string format.
236      */
addressAndPortToString(InetAddress address, int port)237     public static String addressAndPortToString(InetAddress address, int port) {
238         return String.format(
239                 (address instanceof Inet6Address) ? "[%s]:%d" : "%s:%d",
240                         address.getHostAddress(), port);
241     }
242 }
243