blob: eeddff53e8cedaff651ffb85315acbbe62b32bf9 [file] [log] [blame]
Paul Jensenca8f16a2014-05-09 12:47:55 -04001/*
2 * Copyright (C) 2014 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 com.android.server.connectivity;
18
Paul Jensen49e3edf2015-05-22 10:50:39 -040019import static android.net.CaptivePortal.APP_RETURN_DISMISSED;
20import static android.net.CaptivePortal.APP_RETURN_UNWANTED;
21import static android.net.CaptivePortal.APP_RETURN_WANTED_AS_IS;
22
Paul Jensen79a08052014-08-21 12:44:07 -040023import android.app.AlarmManager;
Paul Jensen869868be2014-05-15 10:33:05 -040024import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
Paul Jensenca8f16a2014-05-09 12:47:55 -040027import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040028import android.content.Intent;
29import android.content.IntentFilter;
Paul Jensen49e3edf2015-05-22 10:50:39 -040030import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040031import android.net.ConnectivityManager;
Paul Jensen49e3edf2015-05-22 10:50:39 -040032import android.net.ICaptivePortal;
Paul Jensen2c311d62014-11-17 12:34:51 -050033import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050034import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040035import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040036import android.net.Uri;
Hugo Benichicfddd682016-05-31 16:28:06 +090037import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090038import android.net.metrics.NetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090039import android.net.metrics.ValidationProbeEvent;
Paul Jensen306f1a42014-08-04 10:59:01 -040040import android.net.wifi.WifiInfo;
41import android.net.wifi.WifiManager;
Erik Klinea488c232016-04-15 15:49:42 +090042import android.net.util.Stopwatch;
Paul Jensenca8f16a2014-05-09 12:47:55 -040043import android.os.Handler;
44import android.os.Message;
Paul Jensend7b6ca92015-05-13 14:05:12 -040045import android.os.Process;
Paul Jensen306f1a42014-08-04 10:59:01 -040046import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040047import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040048import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040049import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040050import android.telephony.CellIdentityCdma;
51import android.telephony.CellIdentityGsm;
52import android.telephony.CellIdentityLte;
53import android.telephony.CellIdentityWcdma;
54import android.telephony.CellInfo;
55import android.telephony.CellInfoCdma;
56import android.telephony.CellInfoGsm;
57import android.telephony.CellInfoLte;
58import android.telephony.CellInfoWcdma;
59import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040060import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070061import android.util.LocalLog;
62import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050063import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040064
Paul Jensend7b6ca92015-05-13 14:05:12 -040065import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040066import com.android.internal.util.Protocol;
67import com.android.internal.util.State;
68import com.android.internal.util.StateMachine;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +090069import com.android.internal.util.WakeupMessage;
Paul Jensenca8f16a2014-05-09 12:47:55 -040070
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040072import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040073import java.net.InetAddress;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090074import java.net.MalformedURLException;
75import java.net.UnknownHostException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040076import java.net.URL;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090077import java.util.concurrent.CountDownLatch;
78import java.util.concurrent.atomic.AtomicReference;
Paul Jensen306f1a42014-08-04 10:59:01 -040079import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040080import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040081
82/**
83 * {@hide}
84 */
85public class NetworkMonitor extends StateMachine {
Joe Onorato12acbd72016-02-01 17:49:31 -080086 private static final boolean DBG = false;
Erik Klinea488c232016-04-15 15:49:42 +090087 private static final String TAG = NetworkMonitor.class.getSimpleName();
Erik Klinee7d01792015-07-20 23:37:15 +090088 private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040089 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040090 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
91 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
92 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
93 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
94 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
95 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
96 public static final String EXTRA_CELL_ID = "extra_cellid";
97 public static final String EXTRA_SSID = "extra_ssid";
98 public static final String EXTRA_BSSID = "extra_bssid";
99 /** real time since boot */
100 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
101 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
102
103 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
104 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400105
Paul Jensenad50a1f2014-09-05 12:06:44 -0400106 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
107 // The network should be used as a default internet connection. It was found to be:
108 // 1. a functioning network providing internet access, or
109 // 2. a captive portal and the user decided to use it as is.
110 public static final int NETWORK_TEST_RESULT_VALID = 0;
111 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
112 // The network should not be used as a default internet connection. It was found to be:
113 // 1. a captive portal and the user is prompted to sign-in, or
114 // 2. a captive portal and the user did not want to use it, or
115 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
116 public static final int NETWORK_TEST_RESULT_INVALID = 1;
117
Paul Jensenca8f16a2014-05-09 12:47:55 -0400118 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
119
120 /**
121 * Inform NetworkMonitor that their network is connected.
122 * Initiates Network Validation.
123 */
124 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
125
126 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400127 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400128 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400129 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400130 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400131 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400132 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400133
134 /**
135 * Inform NetworkMonitor to linger a network. The Monitor should
136 * start a timer and/or start watching for zero live connections while
137 * moving towards LINGER_COMPLETE. After the Linger period expires
138 * (or other events mark the end of the linger state) the LINGER_COMPLETE
139 * event should be sent and the network will be shut down. If a
140 * CMD_NETWORK_CONNECTED happens before the LINGER completes
141 * it indicates further desire to keep the network alive and so
142 * the LINGER is aborted.
143 */
144 public static final int CMD_NETWORK_LINGER = BASE + 3;
145
146 /**
147 * Message to self indicating linger delay has expired.
148 * arg1 = Token to ignore old messages.
149 */
150 private static final int CMD_LINGER_EXPIRED = BASE + 4;
151
152 /**
153 * Inform ConnectivityService that the network LINGER period has
154 * expired.
155 * obj = NetworkAgentInfo
156 */
157 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
158
159 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400160 * Message to self indicating it's time to evaluate a network's connectivity.
161 * arg1 = Token to ignore old messages.
162 */
Paul Jensen869868be2014-05-15 10:33:05 -0400163 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400164
165 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400166 * Inform NetworkMonitor that the network has disconnected.
167 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400168 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400169
170 /**
171 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400172 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400173 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400174 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400175
176 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400177 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400178 * arg1 = one of: APP_RETURN_DISMISSED,
179 * APP_RETURN_UNWANTED,
180 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500181 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400182 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400183 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400184
185 /**
186 * Request ConnectivityService display provisioning notification.
187 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400188 * arg2 = NetID.
189 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400190 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400191 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400192
193 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500194 * Message to self indicating sign-in app should be launched.
195 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
196 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400197 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500198 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400199
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400200 /**
201 * Retest network to see if captive portal is still in place.
202 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
203 * 0 indicates self-initiated, so nobody to blame.
204 */
205 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
206
Paul Jensenca8f16a2014-05-09 12:47:55 -0400207 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400208 // Default to 30s linger time-out. Modifyable only for testing.
209 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400210 private final int mLingerDelayMs;
211 private int mLingerToken = 0;
212
Paul Jensend0491e9a2015-05-05 14:52:22 -0400213 // Start mReevaluateDelayMs at this value and double.
214 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
215 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
216 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
217 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400218 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400219 private static final int INVALID_UID = -1;
220 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400221 // Stop blaming UID that requested re-evaluation after this many attempts.
222 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400223 // Delay between reevaluations once a captive portal has been found.
224 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400225
226 private final Context mContext;
227 private final Handler mConnectivityServiceHandler;
228 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900229 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400230 private final TelephonyManager mTelephonyManager;
231 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400232 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500233 private final NetworkRequest mDefaultRequest;
Hugo Benichicfddd682016-05-31 16:28:06 +0900234 private final IpConnectivityLog mMetricsLog = new IpConnectivityLog();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400235
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900236 private boolean mIsCaptivePortalCheckEnabled;
237 private boolean mUseHttps;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400238
Paul Jensenad50a1f2014-09-05 12:06:44 -0400239 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
240 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400241 // Avoids surfacing "Sign in to network" notification.
242 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400243
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700244 public boolean systemReady = false;
245
Paul Jensen71b645f2014-10-13 14:13:07 -0400246 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400247 private final State mValidatedState = new ValidatedState();
248 private final State mMaybeNotifyState = new MaybeNotifyState();
249 private final State mEvaluatingState = new EvaluatingState();
250 private final State mCaptivePortalState = new CaptivePortalState();
251 private final State mLingeringState = new LingeringState();
252
Paul Jensen25a217c2015-02-27 22:55:47 -0500253 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400254
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700255 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
256
Erik Klinea488c232016-04-15 15:49:42 +0900257 private final Stopwatch mEvaluationTimer = new Stopwatch();
258
Paul Jensen2c311d62014-11-17 12:34:51 -0500259 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
260 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400261 // Add suffix indicating which NetworkMonitor we're talking about.
262 super(TAG + networkAgentInfo.name());
263
264 mContext = context;
265 mConnectivityServiceHandler = handler;
266 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900267 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400268 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
269 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400270 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500271 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400272
273 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400274 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400275 addState(mMaybeNotifyState, mDefaultState);
276 addState(mEvaluatingState, mMaybeNotifyState);
277 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400278 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700279 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400280
Paul Jensenca8f16a2014-05-09 12:47:55 -0400281 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400282
Paul Jensen869868be2014-05-15 10:33:05 -0400283 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
284 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900285 mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
286 Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400287
288 start();
289 }
290
Paul Jensen532b61432014-11-10 09:50:02 -0500291 @Override
292 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400293 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500294 }
295
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700296 private void validationLog(String s) {
297 if (DBG) log(s);
298 validationLogs.log(s);
299 }
300
301 public ReadOnlyLocalLog getValidationLogs() {
302 return validationLogs.readOnlyLocalLog();
303 }
304
Paul Jensen71b645f2014-10-13 14:13:07 -0400305 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
306 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400307 private class DefaultState extends State {
308 @Override
309 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400310 switch (message.what) {
311 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400312 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400313 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400314 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400315 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900316 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400317 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400318 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400319 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900320 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500321 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
322 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
323 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400324 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700325 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400326 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400327 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400328 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400329 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400330 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400331 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400332 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400333 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400334 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900335
336 // If the user has seen and acted on a captive portal notification, and the
337 // captive portal app is now closed, disable HTTPS probes. This avoids the
338 // following pathological situation:
339 //
340 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
341 // 2. User opens the app and logs into the captive portal.
342 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
343 // perhaps due to the network blocking HTTPS?
344 //
345 // In this case, we'll fail to validate the network even after the app is
346 // dismissed. There is now no way to use this network, because the app is now
347 // gone, so the user cannot select "Use this network as is".
348 mUseHttps = false;
349
Paul Jensen71b645f2014-10-13 14:13:07 -0400350 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400351 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400352 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500353 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400354 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400355 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500356 // TODO: Distinguish this from a network that actually validates.
357 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400358 transitionTo(mValidatedState);
359 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400360 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400361 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400362 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400363 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400364 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900365 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400366 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400367 mUidResponsibleForReeval = 0;
368 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400369 break;
370 }
371 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400372 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400373 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400374 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400375 }
376 }
377
Paul Jensen71b645f2014-10-13 14:13:07 -0400378 // Being in the ValidatedState State indicates a Network is:
379 // - Successfully validated, or
380 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400381 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400382 private class ValidatedState extends State {
383 @Override
384 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900385 maybeLogEvaluationResult(NetworkEvent.NETWORK_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -0400386 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400387 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400388 }
389
390 @Override
391 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400392 switch (message.what) {
393 case CMD_NETWORK_CONNECTED:
394 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400395 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400396 default:
397 return NOT_HANDLED;
398 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400399 }
400 }
401
Paul Jensen71b645f2014-10-13 14:13:07 -0400402 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
403 // is required. This State takes care to clear the notification upon exit from the State.
404 private class MaybeNotifyState extends State {
405 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500406 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500407 switch (message.what) {
408 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
409 final Intent intent = new Intent(
410 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
411 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400412 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
413 new CaptivePortal(new ICaptivePortal.Stub() {
414 @Override
415 public void appResponse(int response) {
416 if (response == APP_RETURN_WANTED_AS_IS) {
417 mContext.enforceCallingPermission(
418 android.Manifest.permission.CONNECTIVITY_INTERNAL,
419 "CaptivePortal");
420 }
421 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
422 }
423 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500424 intent.setFlags(
425 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
426 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
427 return HANDLED;
428 default:
429 return NOT_HANDLED;
430 }
431 }
432
433 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400434 public void exit() {
435 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
436 mNetworkAgentInfo.network.netId, null);
437 mConnectivityServiceHandler.sendMessage(message);
438 }
439 }
440
Paul Jensen232437312016-04-06 09:51:26 -0400441 /**
442 * Result of calling isCaptivePortal().
443 * @hide
444 */
445 @VisibleForTesting
446 public static final class CaptivePortalProbeResult {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900447 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599, null);
448
Paul Jensen232437312016-04-06 09:51:26 -0400449 final int mHttpResponseCode; // HTTP response code returned from Internet probe.
450 final String mRedirectUrl; // Redirect destination returned from Internet probe.
451
452 public CaptivePortalProbeResult(int httpResponseCode, String redirectUrl) {
453 mHttpResponseCode = httpResponseCode;
454 mRedirectUrl = redirectUrl;
455 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900456
457 boolean isSuccessful() { return mHttpResponseCode == 204; }
458 boolean isPortal() {
459 return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
460 }
Paul Jensen232437312016-04-06 09:51:26 -0400461 }
462
Paul Jensen71b645f2014-10-13 14:13:07 -0400463 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400464 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400465 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400466 private int mReevaluateDelayMs;
467 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400468
Paul Jensenca8f16a2014-05-09 12:47:55 -0400469 @Override
470 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900471 // If we have already started to track time spent in EvaluatingState
472 // don't reset the timer due simply to, say, commands or events that
473 // cause us to exit and re-enter EvaluatingState.
474 if (!mEvaluationTimer.isStarted()) {
475 mEvaluationTimer.start();
476 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400477 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400478 if (mUidResponsibleForReeval != INVALID_UID) {
479 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
480 mUidResponsibleForReeval = INVALID_UID;
481 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400482 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
483 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400484 }
485
486 @Override
487 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400488 switch (message.what) {
489 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400490 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400491 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500492 // Don't bother validating networks that don't satisify the default request.
493 // This includes:
494 // - VPNs which can be considered explicitly desired by the user and the
495 // user's desire trumps whether the network validates.
496 // - Networks that don't provide internet access. It's unclear how to
497 // validate such networks.
498 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
499 // such networks and the user didn't express interest in connecting to
500 // such networks (an app did) so the user may be unhappily surprised when
501 // asked to sign-in to a network they didn't want to connect to in the
502 // first place. Validation could be done to adjust the network scores
503 // however these networks are app-requested and may not be intended for
504 // general usage, in which case general validation may not be an accurate
505 // measure of the network's quality. Only the app knows how to evaluate
506 // the network so don't bother validating here. Furthermore sending HTTP
507 // packets over the network may be undesirable, for example an extremely
508 // expensive metered network, or unwanted leaking of the User Agent string.
509 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
510 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900511 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400512 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400513 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400514 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400515 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900516 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
517 // server's IP addresses could hit the DNS timeout, and attempting connections
518 // to each of the server's several IP addresses (currently one IPv4 and one
519 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
520 // will be unresponsive. isCaptivePortal() could be executed on another Thread
521 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400522 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900523 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400524 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900525 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400526 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Erik Klinea488c232016-04-15 15:49:42 +0900527 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.mRedirectUrl));
Paul Jensen71b645f2014-10-13 14:13:07 -0400528 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400529 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400530 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400531 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicfddd682016-05-31 16:28:06 +0900532 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400533 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900534 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
535 probeResult.mRedirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400536 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400537 // Don't continue to blame UID forever.
538 TrafficStats.clearThreadStatsUid();
539 }
540 mReevaluateDelayMs *= 2;
541 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
542 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
543 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400544 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400545 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400546 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400547 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
548 // ignore any re-evaluation requests. After, restart the
549 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900550 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400551 default:
552 return NOT_HANDLED;
553 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400554 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400555
556 @Override
557 public void exit() {
558 TrafficStats.clearThreadStatsUid();
559 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400560 }
561
Paul Jensendcbe8352014-09-16 16:28:34 -0400562 // BroadcastReceiver that waits for a particular Intent and then posts a message.
563 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400564 private final int mToken;
565 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400566 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400567 CustomIntentReceiver(String action, int token, int what) {
568 mToken = token;
569 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400570 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
571 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400572 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400573 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500574 final Intent intent = new Intent(mAction);
575 intent.setPackage(mContext.getPackageName());
576 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400577 }
578 @Override
579 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400580 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400581 }
582 }
Paul Jensen869868be2014-05-15 10:33:05 -0400583
Paul Jensen71b645f2014-10-13 14:13:07 -0400584 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
585 // has been shown a notification to sign-in.
586 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500587 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
588 "android.net.netmon.launchCaptivePortalApp";
589
Paul Jensen869868be2014-05-15 10:33:05 -0400590 @Override
591 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900592 maybeLogEvaluationResult(NetworkEvent.NETWORK_CAPTIVE_PORTAL_FOUND);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400593 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400594 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500595 // Create a CustomIntentReceiver that sends us a
596 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
597 // touches the notification.
598 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400599 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500600 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
601 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
602 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400603 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500604 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400605 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
606 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500607 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400608 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400609 // Retest for captive portal occasionally.
610 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
611 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400612 }
613
614 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400615 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700616 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400617 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400618 }
619
Paul Jensen71b645f2014-10-13 14:13:07 -0400620 // Being in the LingeringState State indicates a Network's validated bit is true and it once
621 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
Paul Jensencf4c2c62015-07-01 14:16:32 -0400622 // another Network satisfied the NetworkRequest with a higher score and hence this Network
Paul Jensen71b645f2014-10-13 14:13:07 -0400623 // is "lingered" for a fixed period of time before it is disconnected. This period of time
624 // allows apps to wrap up communication and allows for seamless reactivation if the other
625 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400626 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400627 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400628
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900629 private WakeupMessage mWakeupMessage;
Paul Jensen79a08052014-08-21 12:44:07 -0400630
Paul Jensenca8f16a2014-05-09 12:47:55 -0400631 @Override
632 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900633 mEvaluationTimer.reset();
634 final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetId;
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900635 mWakeupMessage = makeWakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
Paul Jensen79a08052014-08-21 12:44:07 -0400636 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900637 mWakeupMessage.schedule(wakeupTime);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400638 }
639
640 @Override
641 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400642 switch (message.what) {
643 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400644 log("Unlingered");
Paul Jensene0988542015-06-25 15:30:08 -0400645 // If already validated, go straight to validated state.
646 if (mNetworkAgentInfo.lastValidated) {
647 transitionTo(mValidatedState);
648 return HANDLED;
649 }
650 return NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400651 case CMD_LINGER_EXPIRED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400652 mConnectivityServiceHandler.sendMessage(
653 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400654 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400655 case CMD_FORCE_REEVALUATION:
656 // Ignore reevaluation attempts when lingering. A reevaluation could result
657 // in a transition to the validated state which would abort the linger
658 // timeout. Lingering is the result of score assessment; validity is
659 // irrelevant.
660 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400661 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
662 // Ignore user network determination as this could abort linger timeout.
663 // Networks are only lingered once validated because:
664 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
665 // - Once validated, a Network's validated bit is never cleared.
666 // Since networks are only lingered after being validated a user's
667 // determination will not change the death sentence that lingering entails:
668 // - If the user wants to use the network or bypasses the captive portal,
669 // the network's score will not be increased beyond its current value
670 // because it is already validated. Without a score increase there is no
671 // chance of reactivation (i.e. aborting linger timeout).
672 // - If the user does not want the network, lingering will disconnect the
673 // network anyhow.
674 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400675 default:
676 return NOT_HANDLED;
677 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400678 }
Paul Jensen79a08052014-08-21 12:44:07 -0400679
680 @Override
681 public void exit() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900682 mWakeupMessage.cancel();
Paul Jensen79a08052014-08-21 12:44:07 -0400683 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400684 }
685
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900686 private static String getCaptivePortalServerUrl(Context context, boolean isHttps) {
Udam Sainib7c24872016-01-04 12:16:14 -0800687 String server = Settings.Global.getString(context.getContentResolver(),
688 Settings.Global.CAPTIVE_PORTAL_SERVER);
689 if (server == null) server = DEFAULT_SERVER;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900690 return (isHttps ? "https" : "http") + "://" + server + "/generate_204";
691 }
692
693 public static String getCaptivePortalServerUrl(Context context) {
694 return getCaptivePortalServerUrl(context, false);
695 }
696
697 @VisibleForTesting
698 protected CaptivePortalProbeResult isCaptivePortal() {
699 if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
700
701 URL pacUrl = null, httpUrl = null, httpsUrl = null;
702
703 // On networks with a PAC instead of fetching a URL that should result in a 204
704 // response, we instead simply fetch the PAC script. This is done for a few reasons:
705 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
706 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
707 // Network.openConnection() will ignore network-specific PACs and instead fetch
708 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
709 // NO_PROXY is the fetch of the PAC itself.
710 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
711 // happen before the fetch can commence, namely:
712 // a) the PAC script be fetched
713 // b) a PAC script resolver service be fired up and resolve the captive portal
714 // server.
715 // Network validation could be delayed until these prerequisities are satisifed or
716 // could simply be left to race them. Neither is an optimal solution.
717 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
718 // fact block fetching of the generate_204 URL which would lead to false negative
719 // results for network validation.
720 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
721 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
722 try {
723 pacUrl = new URL(proxyInfo.getPacFileUrl().toString());
724 } catch (MalformedURLException e) {
725 validationLog("Invalid PAC URL: " + proxyInfo.getPacFileUrl().toString());
726 return CaptivePortalProbeResult.FAILED;
727 }
728 }
729
730 if (pacUrl == null) {
731 try {
732 httpUrl = new URL(getCaptivePortalServerUrl(mContext, false));
733 httpsUrl = new URL(getCaptivePortalServerUrl(mContext, true));
734 } catch (MalformedURLException e) {
735 validationLog("Bad validation URL: " + getCaptivePortalServerUrl(mContext, false));
736 return CaptivePortalProbeResult.FAILED;
737 }
738 }
739
740 long startTime = SystemClock.elapsedRealtime();
741
742 // Pre-resolve the captive portal server host so we can log it.
743 // Only do this if HttpURLConnection is about to, to avoid any potentially
744 // unnecessary resolution.
745 String hostToResolve = null;
746 if (pacUrl != null) {
747 hostToResolve = pacUrl.getHost();
748 } else if (proxyInfo != null) {
749 hostToResolve = proxyInfo.getHost();
750 } else {
751 hostToResolve = httpUrl.getHost();
752 }
753
754 if (!TextUtils.isEmpty(hostToResolve)) {
755 String probeName = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
756 final Stopwatch dnsTimer = new Stopwatch().start();
Hugo Benichicfddd682016-05-31 16:28:06 +0900757 int dnsResult;
758 long dnsLatency;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900759 try {
760 InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(hostToResolve);
Hugo Benichicfddd682016-05-31 16:28:06 +0900761 dnsResult = ValidationProbeEvent.DNS_SUCCESS;
762 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900763 final StringBuffer connectInfo = new StringBuffer(", " + hostToResolve + "=");
764 for (InetAddress address : addresses) {
765 connectInfo.append(address.getHostAddress());
766 if (address != addresses[addresses.length-1]) connectInfo.append(",");
767 }
768 validationLog(probeName + " OK " + dnsLatency + "ms" + connectInfo);
769 } catch (UnknownHostException e) {
Hugo Benichicfddd682016-05-31 16:28:06 +0900770 dnsResult = ValidationProbeEvent.DNS_FAILURE;
771 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900772 validationLog(probeName + " FAIL " + dnsLatency + "ms, " + hostToResolve);
773 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900774 logValidationProbe(dnsLatency, ValidationProbeEvent.PROBE_DNS, dnsResult);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900775 }
776
777 CaptivePortalProbeResult result;
778 if (pacUrl != null) {
779 result = sendHttpProbe(pacUrl, ValidationProbeEvent.PROBE_PAC);
780 } else if (mUseHttps) {
781 result = sendParallelHttpProbes(httpsUrl, httpUrl);
782 } else {
783 result = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
784 }
785
786 long endTime = SystemClock.elapsedRealtime();
787
788 sendNetworkConditionsBroadcast(true /* response received */,
789 result.isPortal() /* isCaptivePortal */,
790 startTime, endTime);
791
792 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800793 }
794
Paul Jensenca8f16a2014-05-09 12:47:55 -0400795 /**
796 * Do a URL fetch on a known server to see if we get the data we expect.
797 * Returns HTTP response code.
798 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400799 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900800 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400801 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400802 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400803 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900804 final Stopwatch probeTimer = new Stopwatch().start();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400805 try {
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700806 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900807 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400808 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
809 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
810 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400811
812 // Time how long it takes to get a response to our request
813 long requestTimestamp = SystemClock.elapsedRealtime();
814
Pierre Imaibe12d762016-03-10 17:00:50 +0900815 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400816 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400817
818 // Time how long it takes to get a response to our request
819 long responseTimestamp = SystemClock.elapsedRealtime();
820
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900821 validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url +
822 " time=" + (responseTimestamp - requestTimestamp) + "ms" +
823 " ret=" + httpResponseCode +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700824 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400825 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
826 // portal. The only example of this seen so far was a captive portal. For
827 // the time being go with prior behavior of assuming it's not a captive
828 // portal. If it is considered a captive portal, a different sign-in URL
829 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
830 // proxy server.
831
832 // Consider 200 response with "Content-length=0" to not be a captive portal.
833 // There's no point in considering this a captive portal as the user cannot
834 // sign-in to an empty page. Probably the result of a broken transparent proxy.
835 // See http://b/9972012.
836 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700837 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400838 httpResponseCode = 204;
839 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400840
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900841 if (httpResponseCode == 200 && probeType == ValidationProbeEvent.PROBE_PAC) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700842 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500843 httpResponseCode = 204;
844 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400845 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700846 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400847 if (httpResponseCode == 599) {
848 // TODO: Ping gateway and DNS server and log results.
849 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400850 } finally {
851 if (urlConnection != null) {
852 urlConnection.disconnect();
853 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400854 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900855 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Paul Jensen232437312016-04-06 09:51:26 -0400856 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400857 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400858
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900859 private CaptivePortalProbeResult sendParallelHttpProbes(URL httpsUrl, URL httpUrl) {
860 // Number of probes to wait for. We might wait for all of them, but we might also return if
861 // only one of them has replied. For example, we immediately return if the HTTP probe finds
862 // a captive portal, even if the HTTPS probe is timing out.
863 final CountDownLatch latch = new CountDownLatch(2);
864
865 // Which probe result we're going to use. This doesn't need to be atomic, but it does need
866 // to be final because otherwise we can't set it from the ProbeThreads.
867 final AtomicReference<CaptivePortalProbeResult> finalResult = new AtomicReference<>();
868
869 final class ProbeThread extends Thread {
870 private final boolean mIsHttps;
871 private volatile CaptivePortalProbeResult mResult;
872
873 public ProbeThread(boolean isHttps) {
874 mIsHttps = isHttps;
875 }
876
877 public CaptivePortalProbeResult getResult() {
878 return mResult;
879 }
880
881 @Override
882 public void run() {
883 if (mIsHttps) {
884 mResult = sendHttpProbe(httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
885 } else {
886 mResult = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
887 }
888 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
889 // HTTPS succeeded, or HTTP found a portal. Don't wait for the other probe.
890 finalResult.compareAndSet(null, mResult);
891 latch.countDown();
892 }
893 // Signal that one probe has completed. If we've already made a decision, or if this
894 // is the second probe, the latch will be at zero and we'll return a result.
895 latch.countDown();
896 }
897 }
898
899 ProbeThread httpsProbe = new ProbeThread(true);
900 ProbeThread httpProbe = new ProbeThread(false);
901 httpsProbe.start();
902 httpProbe.start();
903
904 try {
905 latch.await();
906 } catch (InterruptedException e) {
907 validationLog("Error: probe wait interrupted!");
908 return CaptivePortalProbeResult.FAILED;
909 }
910
911 // If there was no deciding probe, that means that both probes completed. Return HTTPS.
912 finalResult.compareAndSet(null, httpsProbe.getResult());
913
914 return finalResult.get();
915 }
916
Paul Jensen306f1a42014-08-04 10:59:01 -0400917 /**
918 * @param responseReceived - whether or not we received a valid HTTP response to our request.
919 * If false, isCaptivePortal and responseTimestampMs are ignored
920 * TODO: This should be moved to the transports. The latency could be passed to the transports
921 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
922 * perhaps this could just be added to the WiFi transport only.
923 */
924 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
925 long requestTimestampMs, long responseTimestampMs) {
926 if (Settings.Global.getInt(mContext.getContentResolver(),
927 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400928 return;
929 }
930
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700931 if (systemReady == false) return;
932
Paul Jensen306f1a42014-08-04 10:59:01 -0400933 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
934 switch (mNetworkAgentInfo.networkInfo.getType()) {
935 case ConnectivityManager.TYPE_WIFI:
936 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
937 if (currentWifiInfo != null) {
938 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
939 // surrounded by double quotation marks (thus violating the Javadoc), but this
940 // was changed to match the Javadoc in API 17. Since clients may have started
941 // sanitizing the output of this method since API 17 was released, we should
942 // not change it here as it would become impossible to tell whether the SSID is
943 // simply being surrounded by quotes due to the API, or whether those quotes
944 // are actually part of the SSID.
945 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
946 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
947 } else {
948 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
949 return;
950 }
951 break;
952 case ConnectivityManager.TYPE_MOBILE:
953 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
954 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
955 if (info == null) return;
956 int numRegisteredCellInfo = 0;
957 for (CellInfo cellInfo : info) {
958 if (cellInfo.isRegistered()) {
959 numRegisteredCellInfo++;
960 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400961 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400962 "tell which is active. Bailing.");
963 return;
964 }
965 if (cellInfo instanceof CellInfoCdma) {
966 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
967 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
968 } else if (cellInfo instanceof CellInfoGsm) {
969 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
970 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
971 } else if (cellInfo instanceof CellInfoLte) {
972 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
973 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
974 } else if (cellInfo instanceof CellInfoWcdma) {
975 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
976 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
977 } else {
978 if (DBG) logw("Registered cellinfo is unrecognized");
979 return;
980 }
981 }
982 }
983 break;
984 default:
985 return;
986 }
987 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
988 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
989 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
990
991 if (responseReceived) {
992 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
993 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
994 }
Paul Jensen55298582014-08-20 11:01:41 -0400995 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
996 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400997 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400998
999 // Allow tests to override linger time.
1000 @VisibleForTesting
1001 public static void SetDefaultLingerTime(int time_ms) {
1002 if (Process.myUid() == Process.SYSTEM_UID) {
1003 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
1004 }
1005 DEFAULT_LINGER_DELAY_MS = time_ms;
1006 }
Lorenzo Colittibfecba22016-02-21 01:09:26 +09001007
1008 @VisibleForTesting
1009 protected WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int i) {
1010 return new WakeupMessage(c, h, s, i);
1011 }
Hugo Benichicfddd682016-05-31 16:28:06 +09001012
1013 private void logNetworkEvent(int evtype) {
1014 mMetricsLog.log(new NetworkEvent(mNetId, evtype));
1015 }
1016
1017 private void maybeLogEvaluationResult(int evtype) {
1018 if (mEvaluationTimer.isRunning()) {
1019 mMetricsLog.log(new NetworkEvent(mNetId, evtype, mEvaluationTimer.stop()));
1020 mEvaluationTimer.reset();
1021 }
1022 }
1023
1024 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
1025 mMetricsLog.log(new ValidationProbeEvent(mNetId, durationMs, probeType, probeResult));
1026 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001027}