blob: aa66917e48fd3393f5b6a3d850573b5e750d3389 [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;
Paul Jensenca8f16a2014-05-09 12:47:55 -040026import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040027import android.content.Intent;
28import android.content.IntentFilter;
Paul Jensen49e3edf2015-05-22 10:50:39 -040029import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040030import android.net.ConnectivityManager;
Paul Jensen49e3edf2015-05-22 10:50:39 -040031import android.net.ICaptivePortal;
Paul Jensen2c311d62014-11-17 12:34:51 -050032import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050033import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040034import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040035import android.net.Uri;
Hugo Benichicfddd682016-05-31 16:28:06 +090036import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090037import android.net.metrics.NetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090038import android.net.metrics.ValidationProbeEvent;
Hugo Benichid953bf82016-09-27 09:22:35 +090039import android.net.util.Stopwatch;
Paul Jensen306f1a42014-08-04 10:59:01 -040040import android.net.wifi.WifiInfo;
41import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040042import android.os.Handler;
43import android.os.Message;
Paul Jensen306f1a42014-08-04 10:59:01 -040044import android.os.SystemClock;
Paul Jensen869868be2014-05-15 10:33:05 -040045import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040046import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040047import android.telephony.CellIdentityCdma;
48import android.telephony.CellIdentityGsm;
49import android.telephony.CellIdentityLte;
50import android.telephony.CellIdentityWcdma;
51import android.telephony.CellInfo;
52import android.telephony.CellInfoCdma;
53import android.telephony.CellInfoGsm;
54import android.telephony.CellInfoLte;
55import android.telephony.CellInfoWcdma;
56import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040057import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070058import android.util.LocalLog;
59import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050060import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040061
Paul Jensend7b6ca92015-05-13 14:05:12 -040062import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040063import com.android.internal.util.Protocol;
64import com.android.internal.util.State;
65import com.android.internal.util.StateMachine;
Paul Jensenca8f16a2014-05-09 12:47:55 -040066
Paul Jensenca8f16a2014-05-09 12:47:55 -040067import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040068import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040069import java.net.InetAddress;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090070import java.net.MalformedURLException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.net.URL;
Hugo Benichid953bf82016-09-27 09:22:35 +090072import java.net.UnknownHostException;
Paul Jensen306f1a42014-08-04 10:59:01 -040073import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040074import java.util.Random;
Hugo Benichid953bf82016-09-27 09:22:35 +090075import java.util.concurrent.CountDownLatch;
76import java.util.concurrent.TimeUnit;
Paul Jensenca8f16a2014-05-09 12:47:55 -040077
78/**
79 * {@hide}
80 */
81public class NetworkMonitor extends StateMachine {
Erik Klinea488c232016-04-15 15:49:42 +090082 private static final String TAG = NetworkMonitor.class.getSimpleName();
Hugo Benichia4f17bc2016-11-21 13:50:05 +090083 private static final boolean DBG = true;
84 private static final boolean VDBG = false;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090085
Hugo Benichi11ae28f2016-09-27 13:16:19 +090086 // Default configuration values for captive portal detection probes.
87 // TODO: append a random length parameter to the default HTTPS url.
88 // TODO: randomize browser version ids in the default User-Agent String.
89 private static final String DEFAULT_HTTPS_URL = "https://www.google.com/generate_204";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090090 private static final String DEFAULT_HTTP_URL =
91 "http://connectivitycheck.gstatic.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +090092 private static final String DEFAULT_FALLBACK_URL = "http://www.google.com/gen_204";
93 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) "
94 + "AppleWebKit/537.36 (KHTML, like Gecko) "
95 + "Chrome/52.0.2743.82 Safari/537.36";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090096
Paul Jensenca8f16a2014-05-09 12:47:55 -040097 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090098 private static final int PROBE_TIMEOUT_MS = 3000;
99
Paul Jensen306f1a42014-08-04 10:59:01 -0400100 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
101 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
102 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
103 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
104 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
105 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
106 public static final String EXTRA_CELL_ID = "extra_cellid";
107 public static final String EXTRA_SSID = "extra_ssid";
108 public static final String EXTRA_BSSID = "extra_bssid";
109 /** real time since boot */
110 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
111 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
112
113 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
114 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400115
Paul Jensenad50a1f2014-09-05 12:06:44 -0400116 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
117 // The network should be used as a default internet connection. It was found to be:
118 // 1. a functioning network providing internet access, or
119 // 2. a captive portal and the user decided to use it as is.
120 public static final int NETWORK_TEST_RESULT_VALID = 0;
121 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
122 // The network should not be used as a default internet connection. It was found to be:
123 // 1. a captive portal and the user is prompted to sign-in, or
124 // 2. a captive portal and the user did not want to use it, or
125 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
126 public static final int NETWORK_TEST_RESULT_INVALID = 1;
127
Paul Jensenca8f16a2014-05-09 12:47:55 -0400128 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
129
130 /**
131 * Inform NetworkMonitor that their network is connected.
132 * Initiates Network Validation.
133 */
134 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
135
136 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400137 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400138 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400139 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400140 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400141 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400142 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400143
144 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400145 * Message to self indicating it's time to evaluate a network's connectivity.
146 * arg1 = Token to ignore old messages.
147 */
Paul Jensen869868be2014-05-15 10:33:05 -0400148 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400149
150 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400151 * Inform NetworkMonitor that the network has disconnected.
152 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400153 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400154
155 /**
156 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400157 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400158 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400159 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400160
161 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400162 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400163 * arg1 = one of: APP_RETURN_DISMISSED,
164 * APP_RETURN_UNWANTED,
165 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500166 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400167 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400168 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400169
170 /**
171 * Request ConnectivityService display provisioning notification.
172 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400173 * arg2 = NetID.
174 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400175 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400176 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400177
178 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500179 * Message to self indicating sign-in app should be launched.
180 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
181 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400182 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500183 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400184
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400185 /**
186 * Retest network to see if captive portal is still in place.
187 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
188 * 0 indicates self-initiated, so nobody to blame.
189 */
190 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
191
Paul Jensend0491e9a2015-05-05 14:52:22 -0400192 // Start mReevaluateDelayMs at this value and double.
193 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
194 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
195 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
196 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400197 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400198 private static final int INVALID_UID = -1;
199 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400200 // Stop blaming UID that requested re-evaluation after this many attempts.
201 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400202 // Delay between reevaluations once a captive portal has been found.
203 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400204
205 private final Context mContext;
206 private final Handler mConnectivityServiceHandler;
207 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900208 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400209 private final TelephonyManager mTelephonyManager;
210 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400211 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500212 private final NetworkRequest mDefaultRequest;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900213 private final IpConnectivityLog mMetricsLog;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400214
Calvin On4bc78eb2016-10-11 15:10:46 -0700215 @VisibleForTesting
216 protected boolean mIsCaptivePortalCheckEnabled;
217
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900218 private boolean mUseHttps;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400219
Paul Jensenad50a1f2014-09-05 12:06:44 -0400220 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
221 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400222 // Avoids surfacing "Sign in to network" notification.
223 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400224
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700225 public boolean systemReady = false;
226
Paul Jensen71b645f2014-10-13 14:13:07 -0400227 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400228 private final State mValidatedState = new ValidatedState();
229 private final State mMaybeNotifyState = new MaybeNotifyState();
230 private final State mEvaluatingState = new EvaluatingState();
231 private final State mCaptivePortalState = new CaptivePortalState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400232
Paul Jensen25a217c2015-02-27 22:55:47 -0500233 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400234
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700235 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
236
Erik Klinea488c232016-04-15 15:49:42 +0900237 private final Stopwatch mEvaluationTimer = new Stopwatch();
238
Hugo Benichid953bf82016-09-27 09:22:35 +0900239 // This variable is set before transitioning to the mCaptivePortalState.
240 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
241
Paul Jensen2c311d62014-11-17 12:34:51 -0500242 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
243 NetworkRequest defaultRequest) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900244 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog());
245 }
246
247 @VisibleForTesting
248 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
249 NetworkRequest defaultRequest, IpConnectivityLog logger) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400250 // Add suffix indicating which NetworkMonitor we're talking about.
251 super(TAG + networkAgentInfo.name());
252
253 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900254 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400255 mConnectivityServiceHandler = handler;
256 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900257 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400258 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
259 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400260 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500261 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400262
263 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400264 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400265 addState(mMaybeNotifyState, mDefaultState);
266 addState(mEvaluatingState, mMaybeNotifyState);
267 addState(mCaptivePortalState, mMaybeNotifyState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700268 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400269
Paul Jensen869868be2014-05-15 10:33:05 -0400270 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
Calvin On4bc78eb2016-10-11 15:10:46 -0700271 Settings.Global.CAPTIVE_PORTAL_MODE, Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT)
272 != Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900273 mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
274 Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400275
276 start();
277 }
278
Paul Jensen532b61432014-11-10 09:50:02 -0500279 @Override
280 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400281 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500282 }
283
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700284 private void validationLog(String s) {
285 if (DBG) log(s);
286 validationLogs.log(s);
287 }
288
289 public ReadOnlyLocalLog getValidationLogs() {
290 return validationLogs.readOnlyLocalLog();
291 }
292
Paul Jensen71b645f2014-10-13 14:13:07 -0400293 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
294 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400295 private class DefaultState extends State {
296 @Override
297 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400298 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400299 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900300 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400301 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400302 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400303 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900304 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500305 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
306 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
307 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400308 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700309 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400310 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400311 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400312 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400313 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400314 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400315 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400316 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400317 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400318 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900319
320 // If the user has seen and acted on a captive portal notification, and the
321 // captive portal app is now closed, disable HTTPS probes. This avoids the
322 // following pathological situation:
323 //
324 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
325 // 2. User opens the app and logs into the captive portal.
326 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
327 // perhaps due to the network blocking HTTPS?
328 //
329 // In this case, we'll fail to validate the network even after the app is
330 // dismissed. There is now no way to use this network, because the app is now
331 // gone, so the user cannot select "Use this network as is".
332 mUseHttps = false;
333
Paul Jensen71b645f2014-10-13 14:13:07 -0400334 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400335 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400336 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500337 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400338 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400339 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500340 // TODO: Distinguish this from a network that actually validates.
341 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400342 transitionTo(mValidatedState);
343 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400344 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400345 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400346 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400347 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400348 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900349 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400350 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400351 mUidResponsibleForReeval = 0;
352 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400353 break;
354 }
355 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400356 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400357 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400358 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400359 }
360 }
361
Paul Jensen71b645f2014-10-13 14:13:07 -0400362 // Being in the ValidatedState State indicates a Network is:
363 // - Successfully validated, or
364 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400365 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400366 private class ValidatedState extends State {
367 @Override
368 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900369 maybeLogEvaluationResult(NetworkEvent.NETWORK_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -0400370 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400371 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400372 }
373
374 @Override
375 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400376 switch (message.what) {
377 case CMD_NETWORK_CONNECTED:
378 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400379 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400380 default:
381 return NOT_HANDLED;
382 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400383 }
384 }
385
Paul Jensen71b645f2014-10-13 14:13:07 -0400386 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
387 // is required. This State takes care to clear the notification upon exit from the State.
388 private class MaybeNotifyState extends State {
389 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500390 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500391 switch (message.what) {
392 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
393 final Intent intent = new Intent(
394 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
395 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400396 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
397 new CaptivePortal(new ICaptivePortal.Stub() {
398 @Override
399 public void appResponse(int response) {
400 if (response == APP_RETURN_WANTED_AS_IS) {
401 mContext.enforceCallingPermission(
402 android.Manifest.permission.CONNECTIVITY_INTERNAL,
403 "CaptivePortal");
404 }
405 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
406 }
407 }));
Hugo Benichid953bf82016-09-27 09:22:35 +0900408 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL,
409 mLastPortalProbeResult.detectUrl);
Paul Jensen25a217c2015-02-27 22:55:47 -0500410 intent.setFlags(
411 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
412 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
413 return HANDLED;
414 default:
415 return NOT_HANDLED;
416 }
417 }
418
419 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400420 public void exit() {
421 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
422 mNetworkAgentInfo.network.netId, null);
423 mConnectivityServiceHandler.sendMessage(message);
424 }
425 }
426
Paul Jensen232437312016-04-06 09:51:26 -0400427 /**
428 * Result of calling isCaptivePortal().
429 * @hide
430 */
431 @VisibleForTesting
432 public static final class CaptivePortalProbeResult {
Hugo Benichid953bf82016-09-27 09:22:35 +0900433 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900434
Hugo Benichid953bf82016-09-27 09:22:35 +0900435 private final int mHttpResponseCode; // HTTP response code returned from Internet probe.
436 final String redirectUrl; // Redirect destination returned from Internet probe.
437 final String detectUrl; // URL where a 204 response code indicates
438 // captive portal has been appeased.
Paul Jensen232437312016-04-06 09:51:26 -0400439
Hugo Benichid953bf82016-09-27 09:22:35 +0900440 public CaptivePortalProbeResult(
441 int httpResponseCode, String redirectUrl, String detectUrl) {
Paul Jensen232437312016-04-06 09:51:26 -0400442 mHttpResponseCode = httpResponseCode;
Hugo Benichid953bf82016-09-27 09:22:35 +0900443 this.redirectUrl = redirectUrl;
444 this.detectUrl = detectUrl;
445 }
446
447 public CaptivePortalProbeResult(int httpResponseCode) {
448 this(httpResponseCode, null, null);
Paul Jensen232437312016-04-06 09:51:26 -0400449 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900450
451 boolean isSuccessful() { return mHttpResponseCode == 204; }
452 boolean isPortal() {
453 return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
454 }
Paul Jensen232437312016-04-06 09:51:26 -0400455 }
456
Paul Jensen71b645f2014-10-13 14:13:07 -0400457 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400458 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400459 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400460 private int mReevaluateDelayMs;
461 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400462
Paul Jensenca8f16a2014-05-09 12:47:55 -0400463 @Override
464 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900465 // If we have already started to track time spent in EvaluatingState
466 // don't reset the timer due simply to, say, commands or events that
467 // cause us to exit and re-enter EvaluatingState.
468 if (!mEvaluationTimer.isStarted()) {
469 mEvaluationTimer.start();
470 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400471 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400472 if (mUidResponsibleForReeval != INVALID_UID) {
473 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
474 mUidResponsibleForReeval = INVALID_UID;
475 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400476 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
477 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400478 }
479
480 @Override
481 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400482 switch (message.what) {
483 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400484 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400485 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500486 // Don't bother validating networks that don't satisify the default request.
487 // This includes:
488 // - VPNs which can be considered explicitly desired by the user and the
489 // user's desire trumps whether the network validates.
490 // - Networks that don't provide internet access. It's unclear how to
491 // validate such networks.
492 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
493 // such networks and the user didn't express interest in connecting to
494 // such networks (an app did) so the user may be unhappily surprised when
495 // asked to sign-in to a network they didn't want to connect to in the
496 // first place. Validation could be done to adjust the network scores
497 // however these networks are app-requested and may not be intended for
498 // general usage, in which case general validation may not be an accurate
499 // measure of the network's quality. Only the app knows how to evaluate
500 // the network so don't bother validating here. Furthermore sending HTTP
501 // packets over the network may be undesirable, for example an extremely
502 // expensive metered network, or unwanted leaking of the User Agent string.
503 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
504 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900505 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400506 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400507 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400508 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400509 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900510 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
511 // server's IP addresses could hit the DNS timeout, and attempting connections
512 // to each of the server's several IP addresses (currently one IPv4 and one
513 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
514 // will be unresponsive. isCaptivePortal() could be executed on another Thread
515 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400516 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900517 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400518 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900519 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400520 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Hugo Benichid953bf82016-09-27 09:22:35 +0900521 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.redirectUrl));
522 mLastPortalProbeResult = probeResult;
Paul Jensen71b645f2014-10-13 14:13:07 -0400523 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400524 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400525 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400526 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicfddd682016-05-31 16:28:06 +0900527 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400528 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900529 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
Hugo Benichid953bf82016-09-27 09:22:35 +0900530 probeResult.redirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400531 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400532 // Don't continue to blame UID forever.
533 TrafficStats.clearThreadStatsUid();
534 }
535 mReevaluateDelayMs *= 2;
536 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
537 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
538 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400539 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400540 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400541 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400542 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
543 // ignore any re-evaluation requests. After, restart the
544 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900545 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400546 default:
547 return NOT_HANDLED;
548 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400549 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400550
551 @Override
552 public void exit() {
553 TrafficStats.clearThreadStatsUid();
554 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400555 }
556
Paul Jensendcbe8352014-09-16 16:28:34 -0400557 // BroadcastReceiver that waits for a particular Intent and then posts a message.
558 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400559 private final int mToken;
560 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400561 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400562 CustomIntentReceiver(String action, int token, int what) {
563 mToken = token;
564 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400565 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
566 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400567 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400568 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500569 final Intent intent = new Intent(mAction);
570 intent.setPackage(mContext.getPackageName());
571 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400572 }
573 @Override
574 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400575 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400576 }
577 }
Paul Jensen869868be2014-05-15 10:33:05 -0400578
Paul Jensen71b645f2014-10-13 14:13:07 -0400579 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
580 // has been shown a notification to sign-in.
581 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500582 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
583 "android.net.netmon.launchCaptivePortalApp";
584
Paul Jensen869868be2014-05-15 10:33:05 -0400585 @Override
586 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900587 maybeLogEvaluationResult(NetworkEvent.NETWORK_CAPTIVE_PORTAL_FOUND);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400588 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400589 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500590 // Create a CustomIntentReceiver that sends us a
591 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
592 // touches the notification.
593 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400594 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500595 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
596 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
597 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400598 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500599 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400600 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
601 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500602 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400603 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400604 // Retest for captive portal occasionally.
605 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
606 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400607 }
608
609 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400610 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700611 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400612 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400613 }
614
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900615 private static String getCaptivePortalServerHttpsUrl(Context context) {
616 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTPS_URL, DEFAULT_HTTPS_URL);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900617 }
618
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900619 public static String getCaptivePortalServerHttpUrl(Context context) {
620 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTP_URL, DEFAULT_HTTP_URL);
621 }
622
623 private static String getCaptivePortalFallbackUrl(Context context) {
624 return getSetting(context,
625 Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL, DEFAULT_FALLBACK_URL);
626 }
627
628 private static String getCaptivePortalUserAgent(Context context) {
629 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT);
630 }
631
632 private static String getSetting(Context context, String symbol, String defaultValue) {
633 final String value = Settings.Global.getString(context.getContentResolver(), symbol);
634 return value != null ? value : defaultValue;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900635 }
636
637 @VisibleForTesting
638 protected CaptivePortalProbeResult isCaptivePortal() {
Calvin On4bc78eb2016-10-11 15:10:46 -0700639 if (!mIsCaptivePortalCheckEnabled) {
640 validationLog("Validation disabled.");
641 return new CaptivePortalProbeResult(204);
642 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900643
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900644 URL pacUrl = null, httpsUrl = null, httpUrl = null, fallbackUrl = null;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900645
646 // On networks with a PAC instead of fetching a URL that should result in a 204
647 // response, we instead simply fetch the PAC script. This is done for a few reasons:
648 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
649 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
650 // Network.openConnection() will ignore network-specific PACs and instead fetch
651 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
652 // NO_PROXY is the fetch of the PAC itself.
653 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
654 // happen before the fetch can commence, namely:
655 // a) the PAC script be fetched
656 // b) a PAC script resolver service be fired up and resolve the captive portal
657 // server.
658 // Network validation could be delayed until these prerequisities are satisifed or
659 // could simply be left to race them. Neither is an optimal solution.
660 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
661 // fact block fetching of the generate_204 URL which would lead to false negative
662 // results for network validation.
663 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
664 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900665 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString());
666 if (pacUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900667 return CaptivePortalProbeResult.FAILED;
668 }
669 }
670
671 if (pacUrl == null) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900672 httpsUrl = makeURL(getCaptivePortalServerHttpsUrl(mContext));
673 httpUrl = makeURL(getCaptivePortalServerHttpUrl(mContext));
674 fallbackUrl = makeURL(getCaptivePortalFallbackUrl(mContext));
675 if (httpUrl == null || httpsUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900676 return CaptivePortalProbeResult.FAILED;
677 }
678 }
679
680 long startTime = SystemClock.elapsedRealtime();
681
682 // Pre-resolve the captive portal server host so we can log it.
683 // Only do this if HttpURLConnection is about to, to avoid any potentially
684 // unnecessary resolution.
685 String hostToResolve = null;
686 if (pacUrl != null) {
687 hostToResolve = pacUrl.getHost();
688 } else if (proxyInfo != null) {
689 hostToResolve = proxyInfo.getHost();
690 } else {
691 hostToResolve = httpUrl.getHost();
692 }
693
694 if (!TextUtils.isEmpty(hostToResolve)) {
695 String probeName = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
696 final Stopwatch dnsTimer = new Stopwatch().start();
Hugo Benichicfddd682016-05-31 16:28:06 +0900697 int dnsResult;
698 long dnsLatency;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900699 try {
700 InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(hostToResolve);
Hugo Benichicfddd682016-05-31 16:28:06 +0900701 dnsResult = ValidationProbeEvent.DNS_SUCCESS;
702 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900703 final StringBuffer connectInfo = new StringBuffer(", " + hostToResolve + "=");
704 for (InetAddress address : addresses) {
705 connectInfo.append(address.getHostAddress());
706 if (address != addresses[addresses.length-1]) connectInfo.append(",");
707 }
708 validationLog(probeName + " OK " + dnsLatency + "ms" + connectInfo);
709 } catch (UnknownHostException e) {
Hugo Benichicfddd682016-05-31 16:28:06 +0900710 dnsResult = ValidationProbeEvent.DNS_FAILURE;
711 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900712 validationLog(probeName + " FAIL " + dnsLatency + "ms, " + hostToResolve);
713 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900714 logValidationProbe(dnsLatency, ValidationProbeEvent.PROBE_DNS, dnsResult);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900715 }
716
717 CaptivePortalProbeResult result;
718 if (pacUrl != null) {
719 result = sendHttpProbe(pacUrl, ValidationProbeEvent.PROBE_PAC);
720 } else if (mUseHttps) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900721 result = sendParallelHttpProbes(httpsUrl, httpUrl, fallbackUrl);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900722 } else {
723 result = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
724 }
725
726 long endTime = SystemClock.elapsedRealtime();
727
728 sendNetworkConditionsBroadcast(true /* response received */,
729 result.isPortal() /* isCaptivePortal */,
730 startTime, endTime);
731
732 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800733 }
734
Paul Jensenca8f16a2014-05-09 12:47:55 -0400735 /**
736 * Do a URL fetch on a known server to see if we get the data we expect.
737 * Returns HTTP response code.
738 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400739 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900740 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400741 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400742 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400743 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900744 final Stopwatch probeTimer = new Stopwatch().start();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400745 try {
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700746 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900747 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400748 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
749 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
750 urlConnection.setUseCaches(false);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900751 final String userAgent = getCaptivePortalUserAgent(mContext);
752 if (userAgent != null) {
753 urlConnection.setRequestProperty("User-Agent", userAgent);
754 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400755
756 // Time how long it takes to get a response to our request
757 long requestTimestamp = SystemClock.elapsedRealtime();
758
Pierre Imaibe12d762016-03-10 17:00:50 +0900759 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400760 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400761
762 // Time how long it takes to get a response to our request
763 long responseTimestamp = SystemClock.elapsedRealtime();
764
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900765 validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url +
766 " time=" + (responseTimestamp - requestTimestamp) + "ms" +
767 " ret=" + httpResponseCode +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700768 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400769 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
770 // portal. The only example of this seen so far was a captive portal. For
771 // the time being go with prior behavior of assuming it's not a captive
772 // portal. If it is considered a captive portal, a different sign-in URL
773 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
774 // proxy server.
775
776 // Consider 200 response with "Content-length=0" to not be a captive portal.
777 // There's no point in considering this a captive portal as the user cannot
778 // sign-in to an empty page. Probably the result of a broken transparent proxy.
779 // See http://b/9972012.
780 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700781 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400782 httpResponseCode = 204;
783 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400784
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900785 if (httpResponseCode == 200 && probeType == ValidationProbeEvent.PROBE_PAC) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700786 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500787 httpResponseCode = 204;
788 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400789 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700790 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400791 if (httpResponseCode == 599) {
792 // TODO: Ping gateway and DNS server and log results.
793 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400794 } finally {
795 if (urlConnection != null) {
796 urlConnection.disconnect();
797 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400798 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900799 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Hugo Benichid953bf82016-09-27 09:22:35 +0900800 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
Paul Jensenca8f16a2014-05-09 12:47:55 -0400801 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400802
Hugo Benichid953bf82016-09-27 09:22:35 +0900803 private CaptivePortalProbeResult sendParallelHttpProbes(
804 URL httpsUrl, URL httpUrl, URL fallbackUrl) {
805 // Number of probes to wait for. If a probe completes with a conclusive answer
806 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900807 final CountDownLatch latch = new CountDownLatch(2);
808
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900809 final class ProbeThread extends Thread {
810 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +0900811 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900812
813 public ProbeThread(boolean isHttps) {
814 mIsHttps = isHttps;
815 }
816
Hugo Benichid953bf82016-09-27 09:22:35 +0900817 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900818 return mResult;
819 }
820
821 @Override
822 public void run() {
823 if (mIsHttps) {
824 mResult = sendHttpProbe(httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
825 } else {
826 mResult = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
827 }
828 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900829 // Stop waiting immediately if https succeeds or if http finds a portal.
830 while (latch.getCount() > 0) {
831 latch.countDown();
832 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900833 }
Hugo Benichid953bf82016-09-27 09:22:35 +0900834 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900835 latch.countDown();
836 }
837 }
838
Hugo Benichid953bf82016-09-27 09:22:35 +0900839 final ProbeThread httpsProbe = new ProbeThread(true);
840 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900841
842 try {
Hugo Benichid953bf82016-09-27 09:22:35 +0900843 httpsProbe.start();
844 httpProbe.start();
845 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900846 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900847 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900848 return CaptivePortalProbeResult.FAILED;
849 }
850
Hugo Benichid953bf82016-09-27 09:22:35 +0900851 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
852 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900853
Hugo Benichid953bf82016-09-27 09:22:35 +0900854 // Look for a conclusive probe result first.
855 if (httpResult.isPortal()) {
856 return httpResult;
857 }
858 // httpsResult.isPortal() is not expected, but check it nonetheless.
859 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
860 return httpsResult;
861 }
862 // If a fallback url is specified, use a fallback probe to try again portal detection.
863 if (fallbackUrl != null) {
864 CaptivePortalProbeResult result =
865 sendHttpProbe(fallbackUrl, ValidationProbeEvent.PROBE_FALLBACK);
866 if (result.isPortal()) {
867 return result;
868 }
869 }
870 // Otherwise wait until https probe completes and use its result.
871 try {
872 httpsProbe.join();
873 } catch (InterruptedException e) {
874 validationLog("Error: https probe wait interrupted!");
875 return CaptivePortalProbeResult.FAILED;
876 }
877 return httpsProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900878 }
879
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900880 private URL makeURL(String url) {
881 if (url != null) {
882 try {
883 return new URL(url);
884 } catch (MalformedURLException e) {
885 validationLog("Bad URL: " + url);
886 }
887 }
888 return null;
889 }
890
Paul Jensen306f1a42014-08-04 10:59:01 -0400891 /**
892 * @param responseReceived - whether or not we received a valid HTTP response to our request.
893 * If false, isCaptivePortal and responseTimestampMs are ignored
894 * TODO: This should be moved to the transports. The latency could be passed to the transports
895 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
896 * perhaps this could just be added to the WiFi transport only.
897 */
898 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
899 long requestTimestampMs, long responseTimestampMs) {
900 if (Settings.Global.getInt(mContext.getContentResolver(),
901 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400902 return;
903 }
904
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700905 if (systemReady == false) return;
906
Paul Jensen306f1a42014-08-04 10:59:01 -0400907 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
908 switch (mNetworkAgentInfo.networkInfo.getType()) {
909 case ConnectivityManager.TYPE_WIFI:
910 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
911 if (currentWifiInfo != null) {
912 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
913 // surrounded by double quotation marks (thus violating the Javadoc), but this
914 // was changed to match the Javadoc in API 17. Since clients may have started
915 // sanitizing the output of this method since API 17 was released, we should
916 // not change it here as it would become impossible to tell whether the SSID is
917 // simply being surrounded by quotes due to the API, or whether those quotes
918 // are actually part of the SSID.
919 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
920 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
921 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900922 if (VDBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
Paul Jensen306f1a42014-08-04 10:59:01 -0400923 return;
924 }
925 break;
926 case ConnectivityManager.TYPE_MOBILE:
927 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
928 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
929 if (info == null) return;
930 int numRegisteredCellInfo = 0;
931 for (CellInfo cellInfo : info) {
932 if (cellInfo.isRegistered()) {
933 numRegisteredCellInfo++;
934 if (numRegisteredCellInfo > 1) {
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900935 if (VDBG) logw("more than one registered CellInfo." +
936 " Can't tell which is active. Bailing.");
Paul Jensen306f1a42014-08-04 10:59:01 -0400937 return;
938 }
939 if (cellInfo instanceof CellInfoCdma) {
940 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
941 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
942 } else if (cellInfo instanceof CellInfoGsm) {
943 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
944 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
945 } else if (cellInfo instanceof CellInfoLte) {
946 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
947 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
948 } else if (cellInfo instanceof CellInfoWcdma) {
949 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
950 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
951 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900952 if (VDBG) logw("Registered cellinfo is unrecognized");
Paul Jensen306f1a42014-08-04 10:59:01 -0400953 return;
954 }
955 }
956 }
957 break;
958 default:
959 return;
960 }
961 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
962 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
963 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
964
965 if (responseReceived) {
966 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
967 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
968 }
Paul Jensen55298582014-08-20 11:01:41 -0400969 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
970 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400971 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400972
Hugo Benichicfddd682016-05-31 16:28:06 +0900973 private void logNetworkEvent(int evtype) {
974 mMetricsLog.log(new NetworkEvent(mNetId, evtype));
975 }
976
977 private void maybeLogEvaluationResult(int evtype) {
978 if (mEvaluationTimer.isRunning()) {
979 mMetricsLog.log(new NetworkEvent(mNetId, evtype, mEvaluationTimer.stop()));
980 mEvaluationTimer.reset();
981 }
982 }
983
984 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
985 mMetricsLog.log(new ValidationProbeEvent(mNetId, durationMs, probeType, probeResult));
986 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400987}