blob: d3c74e6d755abdb4516ccaae03263f90cf6d12d7 [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;
Hugo Benichi35025da2017-04-10 17:43:08 +090073import java.util.ArrayList;
Paul Jensen306f1a42014-08-04 10:59:01 -040074import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040075import java.util.Random;
Hugo Benichid953bf82016-09-27 09:22:35 +090076import java.util.concurrent.CountDownLatch;
77import java.util.concurrent.TimeUnit;
Paul Jensenca8f16a2014-05-09 12:47:55 -040078
79/**
80 * {@hide}
81 */
82public class NetworkMonitor extends StateMachine {
Erik Klinea488c232016-04-15 15:49:42 +090083 private static final String TAG = NetworkMonitor.class.getSimpleName();
Hugo Benichia4f17bc2016-11-21 13:50:05 +090084 private static final boolean DBG = true;
85 private static final boolean VDBG = false;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090086
Hugo Benichi11ae28f2016-09-27 13:16:19 +090087 // Default configuration values for captive portal detection probes.
88 // TODO: append a random length parameter to the default HTTPS url.
89 // TODO: randomize browser version ids in the default User-Agent String.
90 private static final String DEFAULT_HTTPS_URL = "https://www.google.com/generate_204";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090091 private static final String DEFAULT_HTTP_URL =
92 "http://connectivitycheck.gstatic.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +090093 private static final String DEFAULT_FALLBACK_URL = "http://www.google.com/gen_204";
Hugo Benichi35025da2017-04-10 17:43:08 +090094 private static final String DEFAULT_OTHER_FALLBACK_URLS =
95 "http://play.googleapis.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +090096 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) "
97 + "AppleWebKit/537.36 (KHTML, like Gecko) "
98 + "Chrome/52.0.2743.82 Safari/537.36";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090099
Paul Jensenca8f16a2014-05-09 12:47:55 -0400100 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900101 private static final int PROBE_TIMEOUT_MS = 3000;
102
Hugo Benichidd229822016-11-15 23:23:24 +0900103 static enum EvaluationResult {
104 VALIDATED(true),
105 CAPTIVE_PORTAL(false);
106 final boolean isValidated;
107 EvaluationResult(boolean isValidated) {
108 this.isValidated = isValidated;
109 }
110 }
111
112 static enum ValidationStage {
113 FIRST_VALIDATION(true),
114 REVALIDATION(false);
115 final boolean isFirstValidation;
116 ValidationStage(boolean isFirstValidation) {
117 this.isFirstValidation = isFirstValidation;
118 }
119 }
120
Paul Jensen306f1a42014-08-04 10:59:01 -0400121 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
122 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
123 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
124 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
125 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
126 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
127 public static final String EXTRA_CELL_ID = "extra_cellid";
128 public static final String EXTRA_SSID = "extra_ssid";
129 public static final String EXTRA_BSSID = "extra_bssid";
130 /** real time since boot */
131 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
132 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
133
134 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
135 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400136
Paul Jensenad50a1f2014-09-05 12:06:44 -0400137 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
138 // The network should be used as a default internet connection. It was found to be:
139 // 1. a functioning network providing internet access, or
140 // 2. a captive portal and the user decided to use it as is.
141 public static final int NETWORK_TEST_RESULT_VALID = 0;
142 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
143 // The network should not be used as a default internet connection. It was found to be:
144 // 1. a captive portal and the user is prompted to sign-in, or
145 // 2. a captive portal and the user did not want to use it, or
146 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
147 public static final int NETWORK_TEST_RESULT_INVALID = 1;
148
Paul Jensenca8f16a2014-05-09 12:47:55 -0400149 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
150
151 /**
152 * Inform NetworkMonitor that their network is connected.
153 * Initiates Network Validation.
154 */
155 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
156
157 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400158 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400159 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400160 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400161 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400162 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400163 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400164
165 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400166 * Message to self indicating it's time to evaluate a network's connectivity.
167 * arg1 = Token to ignore old messages.
168 */
Paul Jensen869868be2014-05-15 10:33:05 -0400169 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400170
171 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400172 * Inform NetworkMonitor that the network has disconnected.
173 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400174 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400175
176 /**
177 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400178 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400179 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400180 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400181
182 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400183 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400184 * arg1 = one of: APP_RETURN_DISMISSED,
185 * APP_RETURN_UNWANTED,
186 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500187 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400188 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400189 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400190
191 /**
192 * Request ConnectivityService display provisioning notification.
193 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400194 * arg2 = NetID.
195 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400196 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400197 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400198
199 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500200 * Message to self indicating sign-in app should be launched.
201 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
202 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400203 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500204 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400205
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400206 /**
207 * Retest network to see if captive portal is still in place.
208 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
209 * 0 indicates self-initiated, so nobody to blame.
210 */
211 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
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 Benichif9fdf872016-07-28 17:53:06 +0900234 private final IpConnectivityLog mMetricsLog;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400235
Calvin On4bc78eb2016-10-11 15:10:46 -0700236 @VisibleForTesting
237 protected boolean mIsCaptivePortalCheckEnabled;
238
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900239 private boolean mUseHttps;
Hugo Benichidd229822016-11-15 23:23:24 +0900240 // The total number of captive portal detection attempts for this NetworkMonitor instance.
241 private int mValidations = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400242
Paul Jensenad50a1f2014-09-05 12:06:44 -0400243 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
244 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400245 // Avoids surfacing "Sign in to network" notification.
246 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400247
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700248 public boolean systemReady = false;
249
Paul Jensen71b645f2014-10-13 14:13:07 -0400250 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400251 private final State mValidatedState = new ValidatedState();
252 private final State mMaybeNotifyState = new MaybeNotifyState();
253 private final State mEvaluatingState = new EvaluatingState();
254 private final State mCaptivePortalState = new CaptivePortalState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400255
Paul Jensen25a217c2015-02-27 22:55:47 -0500256 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400257
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700258 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
259
Erik Klinea488c232016-04-15 15:49:42 +0900260 private final Stopwatch mEvaluationTimer = new Stopwatch();
261
Hugo Benichid953bf82016-09-27 09:22:35 +0900262 // This variable is set before transitioning to the mCaptivePortalState.
263 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
264
Hugo Benichib2f960d2017-04-10 22:45:13 +0900265 // Configuration values for captive portal detection probes.
266 private final String mCaptivePortalUserAgent;
267 private final URL mCaptivePortalHttpsUrl;
268 private final URL mCaptivePortalHttpUrl;
Hugo Benichi35025da2017-04-10 17:43:08 +0900269 private final URL[] mCaptivePortalFallbackUrls;
270 private int mNextFallbackUrlIndex = 0;
Hugo Benichib2f960d2017-04-10 22:45:13 +0900271
Paul Jensen2c311d62014-11-17 12:34:51 -0500272 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
273 NetworkRequest defaultRequest) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900274 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog());
275 }
276
277 @VisibleForTesting
278 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
279 NetworkRequest defaultRequest, IpConnectivityLog logger) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400280 // Add suffix indicating which NetworkMonitor we're talking about.
281 super(TAG + networkAgentInfo.name());
282
283 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900284 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400285 mConnectivityServiceHandler = handler;
286 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900287 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400288 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
289 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400290 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500291 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400292
293 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400294 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400295 addState(mMaybeNotifyState, mDefaultState);
296 addState(mEvaluatingState, mMaybeNotifyState);
297 addState(mCaptivePortalState, mMaybeNotifyState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700298 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400299
Paul Jensen869868be2014-05-15 10:33:05 -0400300 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
Calvin On4bc78eb2016-10-11 15:10:46 -0700301 Settings.Global.CAPTIVE_PORTAL_MODE, Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT)
302 != Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900303 mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
304 Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400305
Hugo Benichib2f960d2017-04-10 22:45:13 +0900306 mCaptivePortalUserAgent = getCaptivePortalUserAgent(context);
307 mCaptivePortalHttpsUrl = makeURL(getCaptivePortalServerHttpsUrl(context));
308 mCaptivePortalHttpUrl = makeURL(getCaptivePortalServerHttpUrl(context));
Hugo Benichi35025da2017-04-10 17:43:08 +0900309 mCaptivePortalFallbackUrls = makeCaptivePortalFallbackUrls(context);
Hugo Benichib2f960d2017-04-10 22:45:13 +0900310
Paul Jensenca8f16a2014-05-09 12:47:55 -0400311 start();
312 }
313
Paul Jensen532b61432014-11-10 09:50:02 -0500314 @Override
315 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400316 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500317 }
318
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900319 private void validationLog(int probeType, Object url, String msg) {
320 String probeName = ValidationProbeEvent.getProbeName(probeType);
321 validationLog(String.format("%s %s %s", probeName, url, msg));
322 }
323
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700324 private void validationLog(String s) {
325 if (DBG) log(s);
326 validationLogs.log(s);
327 }
328
329 public ReadOnlyLocalLog getValidationLogs() {
330 return validationLogs.readOnlyLocalLog();
331 }
332
Hugo Benichidd229822016-11-15 23:23:24 +0900333 private ValidationStage validationStage() {
334 return 0 == mValidations ? ValidationStage.FIRST_VALIDATION : ValidationStage.REVALIDATION;
335 }
336
Paul Jensen71b645f2014-10-13 14:13:07 -0400337 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
338 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400339 private class DefaultState extends State {
340 @Override
341 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400342 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400343 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900344 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400345 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400346 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400347 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900348 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500349 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
350 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
351 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400352 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700353 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400354 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400355 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400356 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400357 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400358 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400359 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400360 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400361 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400362 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900363
364 // If the user has seen and acted on a captive portal notification, and the
365 // captive portal app is now closed, disable HTTPS probes. This avoids the
366 // following pathological situation:
367 //
368 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
369 // 2. User opens the app and logs into the captive portal.
370 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
371 // perhaps due to the network blocking HTTPS?
372 //
373 // In this case, we'll fail to validate the network even after the app is
374 // dismissed. There is now no way to use this network, because the app is now
375 // gone, so the user cannot select "Use this network as is".
376 mUseHttps = false;
377
Paul Jensen71b645f2014-10-13 14:13:07 -0400378 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400379 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400380 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500381 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400382 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400383 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500384 // TODO: Distinguish this from a network that actually validates.
385 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400386 transitionTo(mValidatedState);
387 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400388 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400389 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400390 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400391 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400392 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900393 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400394 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400395 mUidResponsibleForReeval = 0;
396 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400397 break;
398 }
399 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400400 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400401 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400402 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400403 }
404 }
405
Paul Jensen71b645f2014-10-13 14:13:07 -0400406 // Being in the ValidatedState State indicates a Network is:
407 // - Successfully validated, or
408 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400409 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400410 private class ValidatedState extends State {
411 @Override
412 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900413 maybeLogEvaluationResult(
414 networkEventType(validationStage(), EvaluationResult.VALIDATED));
Paul Jensenad50a1f2014-09-05 12:06:44 -0400415 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400416 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Hugo Benichidd229822016-11-15 23:23:24 +0900417 mValidations++;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400418 }
419
420 @Override
421 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400422 switch (message.what) {
423 case CMD_NETWORK_CONNECTED:
424 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400425 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400426 default:
427 return NOT_HANDLED;
428 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400429 }
430 }
431
Paul Jensen71b645f2014-10-13 14:13:07 -0400432 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
433 // is required. This State takes care to clear the notification upon exit from the State.
434 private class MaybeNotifyState extends State {
435 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500436 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500437 switch (message.what) {
438 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
439 final Intent intent = new Intent(
440 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
441 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400442 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
443 new CaptivePortal(new ICaptivePortal.Stub() {
444 @Override
445 public void appResponse(int response) {
446 if (response == APP_RETURN_WANTED_AS_IS) {
447 mContext.enforceCallingPermission(
448 android.Manifest.permission.CONNECTIVITY_INTERNAL,
449 "CaptivePortal");
450 }
451 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
452 }
453 }));
Hugo Benichid953bf82016-09-27 09:22:35 +0900454 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL,
455 mLastPortalProbeResult.detectUrl);
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900456 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT,
Hugo Benichi35025da2017-04-10 17:43:08 +0900457 mCaptivePortalUserAgent);
Paul Jensen25a217c2015-02-27 22:55:47 -0500458 intent.setFlags(
459 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
460 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
461 return HANDLED;
462 default:
463 return NOT_HANDLED;
464 }
465 }
466
467 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400468 public void exit() {
469 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
470 mNetworkAgentInfo.network.netId, null);
471 mConnectivityServiceHandler.sendMessage(message);
472 }
473 }
474
Paul Jensen232437312016-04-06 09:51:26 -0400475 /**
476 * Result of calling isCaptivePortal().
477 * @hide
478 */
479 @VisibleForTesting
480 public static final class CaptivePortalProbeResult {
Hugo Benichid953bf82016-09-27 09:22:35 +0900481 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900482
Hugo Benichid953bf82016-09-27 09:22:35 +0900483 private final int mHttpResponseCode; // HTTP response code returned from Internet probe.
484 final String redirectUrl; // Redirect destination returned from Internet probe.
485 final String detectUrl; // URL where a 204 response code indicates
486 // captive portal has been appeased.
Paul Jensen232437312016-04-06 09:51:26 -0400487
Hugo Benichid953bf82016-09-27 09:22:35 +0900488 public CaptivePortalProbeResult(
489 int httpResponseCode, String redirectUrl, String detectUrl) {
Paul Jensen232437312016-04-06 09:51:26 -0400490 mHttpResponseCode = httpResponseCode;
Hugo Benichid953bf82016-09-27 09:22:35 +0900491 this.redirectUrl = redirectUrl;
492 this.detectUrl = detectUrl;
493 }
494
495 public CaptivePortalProbeResult(int httpResponseCode) {
496 this(httpResponseCode, null, null);
Paul Jensen232437312016-04-06 09:51:26 -0400497 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900498
499 boolean isSuccessful() { return mHttpResponseCode == 204; }
500 boolean isPortal() {
501 return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
502 }
Paul Jensen232437312016-04-06 09:51:26 -0400503 }
504
Paul Jensen71b645f2014-10-13 14:13:07 -0400505 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400506 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400507 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400508 private int mReevaluateDelayMs;
509 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400510
Paul Jensenca8f16a2014-05-09 12:47:55 -0400511 @Override
512 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900513 // If we have already started to track time spent in EvaluatingState
514 // don't reset the timer due simply to, say, commands or events that
515 // cause us to exit and re-enter EvaluatingState.
516 if (!mEvaluationTimer.isStarted()) {
517 mEvaluationTimer.start();
518 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400519 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400520 if (mUidResponsibleForReeval != INVALID_UID) {
521 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
522 mUidResponsibleForReeval = INVALID_UID;
523 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400524 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
525 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400526 }
527
528 @Override
529 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400530 switch (message.what) {
531 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400532 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400533 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500534 // Don't bother validating networks that don't satisify the default request.
535 // This includes:
536 // - VPNs which can be considered explicitly desired by the user and the
537 // user's desire trumps whether the network validates.
538 // - Networks that don't provide internet access. It's unclear how to
539 // validate such networks.
540 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
541 // such networks and the user didn't express interest in connecting to
542 // such networks (an app did) so the user may be unhappily surprised when
543 // asked to sign-in to a network they didn't want to connect to in the
544 // first place. Validation could be done to adjust the network scores
545 // however these networks are app-requested and may not be intended for
546 // general usage, in which case general validation may not be an accurate
547 // measure of the network's quality. Only the app knows how to evaluate
548 // the network so don't bother validating here. Furthermore sending HTTP
549 // packets over the network may be undesirable, for example an extremely
550 // expensive metered network, or unwanted leaking of the User Agent string.
551 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
552 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900553 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400554 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400555 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400556 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400557 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900558 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
559 // server's IP addresses could hit the DNS timeout, and attempting connections
560 // to each of the server's several IP addresses (currently one IPv4 and one
561 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
562 // will be unresponsive. isCaptivePortal() could be executed on another Thread
563 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400564 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900565 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400566 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900567 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400568 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Hugo Benichid953bf82016-09-27 09:22:35 +0900569 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.redirectUrl));
570 mLastPortalProbeResult = probeResult;
Paul Jensen71b645f2014-10-13 14:13:07 -0400571 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400572 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400573 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400574 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicfddd682016-05-31 16:28:06 +0900575 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400576 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900577 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
Hugo Benichid953bf82016-09-27 09:22:35 +0900578 probeResult.redirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400579 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400580 // Don't continue to blame UID forever.
581 TrafficStats.clearThreadStatsUid();
582 }
583 mReevaluateDelayMs *= 2;
584 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
585 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
586 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400587 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400588 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400589 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400590 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
591 // ignore any re-evaluation requests. After, restart the
592 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900593 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400594 default:
595 return NOT_HANDLED;
596 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400597 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400598
599 @Override
600 public void exit() {
601 TrafficStats.clearThreadStatsUid();
602 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400603 }
604
Paul Jensendcbe8352014-09-16 16:28:34 -0400605 // BroadcastReceiver that waits for a particular Intent and then posts a message.
606 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400607 private final int mToken;
608 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400609 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400610 CustomIntentReceiver(String action, int token, int what) {
611 mToken = token;
612 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400613 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
614 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400615 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400616 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500617 final Intent intent = new Intent(mAction);
618 intent.setPackage(mContext.getPackageName());
619 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400620 }
621 @Override
622 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400623 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400624 }
625 }
Paul Jensen869868be2014-05-15 10:33:05 -0400626
Paul Jensen71b645f2014-10-13 14:13:07 -0400627 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
628 // has been shown a notification to sign-in.
629 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500630 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
631 "android.net.netmon.launchCaptivePortalApp";
632
Paul Jensen869868be2014-05-15 10:33:05 -0400633 @Override
634 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900635 maybeLogEvaluationResult(
636 networkEventType(validationStage(), EvaluationResult.CAPTIVE_PORTAL));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400637 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400638 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500639 // Create a CustomIntentReceiver that sends us a
640 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
641 // touches the notification.
642 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400643 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500644 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
645 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
646 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400647 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500648 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400649 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
650 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500651 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400652 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400653 // Retest for captive portal occasionally.
654 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
655 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Hugo Benichidd229822016-11-15 23:23:24 +0900656 mValidations++;
Paul Jensen869868be2014-05-15 10:33:05 -0400657 }
658
659 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400660 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700661 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400662 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400663 }
664
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900665 private static String getCaptivePortalServerHttpsUrl(Context context) {
666 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTPS_URL, DEFAULT_HTTPS_URL);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900667 }
668
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900669 public static String getCaptivePortalServerHttpUrl(Context context) {
670 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTP_URL, DEFAULT_HTTP_URL);
671 }
672
Hugo Benichi35025da2017-04-10 17:43:08 +0900673 private URL[] makeCaptivePortalFallbackUrls(Context context) {
674 String separator = ",";
675 String firstUrl = getSetting(context,
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900676 Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL, DEFAULT_FALLBACK_URL);
Hugo Benichi35025da2017-04-10 17:43:08 +0900677 String joinedUrls = firstUrl + separator + getSetting(context,
678 Settings.Global.CAPTIVE_PORTAL_OTHER_FALLBACK_URLS, DEFAULT_OTHER_FALLBACK_URLS);
679 List<URL> urls = new ArrayList<>();
680 for (String s : joinedUrls.split(separator)) {
681 URL u = makeURL(s);
682 if (u == null) {
683 continue;
684 }
685 urls.add(u);
686 }
687 if (urls.isEmpty()) {
688 Log.e(TAG, String.format("could not create any url from %s", joinedUrls));
689 }
690 return urls.toArray(new URL[urls.size()]);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900691 }
692
693 private static String getCaptivePortalUserAgent(Context context) {
694 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT);
695 }
696
697 private static String getSetting(Context context, String symbol, String defaultValue) {
698 final String value = Settings.Global.getString(context.getContentResolver(), symbol);
699 return value != null ? value : defaultValue;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900700 }
701
Hugo Benichi35025da2017-04-10 17:43:08 +0900702 private URL nextFallbackUrl() {
703 if (mCaptivePortalFallbackUrls.length == 0) {
704 return null;
705 }
706 int idx = Math.abs(mNextFallbackUrlIndex) % mCaptivePortalFallbackUrls.length;
707 mNextFallbackUrlIndex += new Random().nextInt(); // randomely change url without memory.
708 return mCaptivePortalFallbackUrls[idx];
709 }
710
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900711 @VisibleForTesting
712 protected CaptivePortalProbeResult isCaptivePortal() {
Calvin On4bc78eb2016-10-11 15:10:46 -0700713 if (!mIsCaptivePortalCheckEnabled) {
714 validationLog("Validation disabled.");
715 return new CaptivePortalProbeResult(204);
716 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900717
Hugo Benichib2f960d2017-04-10 22:45:13 +0900718 URL pacUrl = null;
719 URL httpsUrl = mCaptivePortalHttpsUrl;
720 URL httpUrl = mCaptivePortalHttpUrl;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900721
722 // On networks with a PAC instead of fetching a URL that should result in a 204
723 // response, we instead simply fetch the PAC script. This is done for a few reasons:
724 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
725 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
726 // Network.openConnection() will ignore network-specific PACs and instead fetch
727 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
728 // NO_PROXY is the fetch of the PAC itself.
729 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
730 // happen before the fetch can commence, namely:
731 // a) the PAC script be fetched
732 // b) a PAC script resolver service be fired up and resolve the captive portal
733 // server.
734 // Network validation could be delayed until these prerequisities are satisifed or
735 // could simply be left to race them. Neither is an optimal solution.
736 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
737 // fact block fetching of the generate_204 URL which would lead to false negative
738 // results for network validation.
739 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
740 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900741 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString());
742 if (pacUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900743 return CaptivePortalProbeResult.FAILED;
744 }
745 }
746
Hugo Benichib2f960d2017-04-10 22:45:13 +0900747 if ((pacUrl == null) && (httpUrl == null || httpsUrl == null)) {
748 return CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900749 }
750
751 long startTime = SystemClock.elapsedRealtime();
752
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900753 final CaptivePortalProbeResult result;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900754 if (pacUrl != null) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900755 result = sendDnsAndHttpProbes(null, pacUrl, ValidationProbeEvent.PROBE_PAC);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900756 } else if (mUseHttps) {
Hugo Benichi35025da2017-04-10 17:43:08 +0900757 result = sendParallelHttpProbes(proxyInfo, httpsUrl, httpUrl);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900758 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900759 result = sendDnsAndHttpProbes(proxyInfo, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900760 }
761
762 long endTime = SystemClock.elapsedRealtime();
763
764 sendNetworkConditionsBroadcast(true /* response received */,
765 result.isPortal() /* isCaptivePortal */,
766 startTime, endTime);
767
768 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800769 }
770
Paul Jensenca8f16a2014-05-09 12:47:55 -0400771 /**
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900772 * Do a DNS resolution and URL fetch on a known web server to see if we get the data we expect.
773 * @return a CaptivePortalProbeResult inferred from the HTTP response.
774 */
775 private CaptivePortalProbeResult sendDnsAndHttpProbes(ProxyInfo proxy, URL url, int probeType) {
776 // Pre-resolve the captive portal server host so we can log it.
777 // Only do this if HttpURLConnection is about to, to avoid any potentially
778 // unnecessary resolution.
779 final String host = (proxy != null) ? proxy.getHost() : url.getHost();
780 sendDnsProbe(host);
781 return sendHttpProbe(url, probeType);
782 }
783
784 /** Do a DNS resolution of the given server. */
785 private void sendDnsProbe(String host) {
786 if (TextUtils.isEmpty(host)) {
787 return;
788 }
789
790 final String name = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
791 final Stopwatch watch = new Stopwatch().start();
792 int result;
793 String connectInfo;
794 try {
795 InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(host);
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900796 StringBuffer buffer = new StringBuffer();
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900797 for (InetAddress address : addresses) {
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900798 buffer.append(',').append(address.getHostAddress());
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900799 }
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900800 result = ValidationProbeEvent.DNS_SUCCESS;
801 connectInfo = "OK " + buffer.substring(1);
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900802 } catch (UnknownHostException e) {
803 result = ValidationProbeEvent.DNS_FAILURE;
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900804 connectInfo = "FAIL";
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900805 }
806 final long latency = watch.stop();
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900807 validationLog(ValidationProbeEvent.PROBE_DNS, host,
808 String.format("%dms %s", latency, connectInfo));
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900809 logValidationProbe(latency, ValidationProbeEvent.PROBE_DNS, result);
810 }
811
812 /**
813 * Do a URL fetch on a known web server to see if we get the data we expect.
814 * @return a CaptivePortalProbeResult inferred from the HTTP response.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400815 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400816 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900817 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400818 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400819 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400820 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900821 final Stopwatch probeTimer = new Stopwatch().start();
Jeff Sharkey619a5112017-01-19 11:55:54 -0700822 final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400823 try {
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700824 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900825 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400826 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
827 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
828 urlConnection.setUseCaches(false);
Hugo Benichib2f960d2017-04-10 22:45:13 +0900829 if (mCaptivePortalUserAgent != null) {
830 urlConnection.setRequestProperty("User-Agent", mCaptivePortalUserAgent);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900831 }
Hugo Benichiec88fd62017-03-07 15:10:03 +0900832 // cannot read request header after connection
833 String requestHeader = urlConnection.getRequestProperties().toString();
Paul Jensen306f1a42014-08-04 10:59:01 -0400834
835 // Time how long it takes to get a response to our request
836 long requestTimestamp = SystemClock.elapsedRealtime();
837
Pierre Imaibe12d762016-03-10 17:00:50 +0900838 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400839 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400840
841 // Time how long it takes to get a response to our request
842 long responseTimestamp = SystemClock.elapsedRealtime();
843
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900844 validationLog(probeType, url, "time=" + (responseTimestamp - requestTimestamp) + "ms" +
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900845 " ret=" + httpResponseCode +
Hugo Benichiec88fd62017-03-07 15:10:03 +0900846 " request=" + requestHeader +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700847 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400848 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
849 // portal. The only example of this seen so far was a captive portal. For
850 // the time being go with prior behavior of assuming it's not a captive
851 // portal. If it is considered a captive portal, a different sign-in URL
852 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
853 // proxy server.
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900854 if (httpResponseCode == 200) {
855 if (probeType == ValidationProbeEvent.PROBE_PAC) {
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900856 validationLog(
857 probeType, url, "PAC fetch 200 response interpreted as 204 response.");
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900858 httpResponseCode = 204;
859 } else if (urlConnection.getContentLengthLong() == 0) {
860 // Consider 200 response with "Content-length=0" to not be a captive portal.
861 // There's no point in considering this a captive portal as the user cannot
862 // sign-in to an empty page. Probably the result of a broken transparent proxy.
863 // See http://b/9972012.
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900864 validationLog(probeType, url,
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900865 "200 response with Content-length=0 interpreted as 204 response.");
866 httpResponseCode = 204;
867 } else if (urlConnection.getContentLengthLong() == -1) {
868 // When no Content-length (default value == -1), attempt to read a byte from the
869 // response. Do not use available() as it is unreliable. See http://b/33498325.
870 if (urlConnection.getInputStream().read() == -1) {
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900871 validationLog(
872 probeType, url, "Empty 200 response interpreted as 204 response.");
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900873 httpResponseCode = 204;
874 }
875 }
Paul Jensen8fe17422015-02-02 11:03:03 -0500876 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400877 } catch (IOException e) {
Hugo Benichi19e3cbd2017-04-06 14:36:39 +0900878 validationLog(probeType, url, "Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400879 if (httpResponseCode == 599) {
880 // TODO: Ping gateway and DNS server and log results.
881 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400882 } finally {
883 if (urlConnection != null) {
884 urlConnection.disconnect();
885 }
Jeff Sharkey619a5112017-01-19 11:55:54 -0700886 TrafficStats.setThreadStatsTag(oldTag);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400887 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900888 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Hugo Benichid953bf82016-09-27 09:22:35 +0900889 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
Paul Jensenca8f16a2014-05-09 12:47:55 -0400890 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400891
Hugo Benichid953bf82016-09-27 09:22:35 +0900892 private CaptivePortalProbeResult sendParallelHttpProbes(
Hugo Benichi35025da2017-04-10 17:43:08 +0900893 ProxyInfo proxy, URL httpsUrl, URL httpUrl) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900894 // Number of probes to wait for. If a probe completes with a conclusive answer
895 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900896 final CountDownLatch latch = new CountDownLatch(2);
897
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900898 final class ProbeThread extends Thread {
899 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +0900900 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900901
902 public ProbeThread(boolean isHttps) {
903 mIsHttps = isHttps;
904 }
905
Hugo Benichid953bf82016-09-27 09:22:35 +0900906 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900907 return mResult;
908 }
909
910 @Override
911 public void run() {
912 if (mIsHttps) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900913 mResult =
914 sendDnsAndHttpProbes(proxy, httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900915 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900916 mResult = sendDnsAndHttpProbes(proxy, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900917 }
918 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900919 // Stop waiting immediately if https succeeds or if http finds a portal.
920 while (latch.getCount() > 0) {
921 latch.countDown();
922 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900923 }
Hugo Benichid953bf82016-09-27 09:22:35 +0900924 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900925 latch.countDown();
926 }
927 }
928
Hugo Benichid953bf82016-09-27 09:22:35 +0900929 final ProbeThread httpsProbe = new ProbeThread(true);
930 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900931
932 try {
Hugo Benichid953bf82016-09-27 09:22:35 +0900933 httpsProbe.start();
934 httpProbe.start();
935 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900936 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900937 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900938 return CaptivePortalProbeResult.FAILED;
939 }
940
Hugo Benichid953bf82016-09-27 09:22:35 +0900941 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
942 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900943
Hugo Benichid953bf82016-09-27 09:22:35 +0900944 // Look for a conclusive probe result first.
945 if (httpResult.isPortal()) {
946 return httpResult;
947 }
948 // httpsResult.isPortal() is not expected, but check it nonetheless.
949 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
950 return httpsResult;
951 }
Hugo Benichi35025da2017-04-10 17:43:08 +0900952 // If a fallback url exists, use a fallback probe to try again portal detection.
953 URL fallbackUrl = nextFallbackUrl();
Hugo Benichid953bf82016-09-27 09:22:35 +0900954 if (fallbackUrl != null) {
955 CaptivePortalProbeResult result =
956 sendHttpProbe(fallbackUrl, ValidationProbeEvent.PROBE_FALLBACK);
957 if (result.isPortal()) {
958 return result;
959 }
960 }
961 // Otherwise wait until https probe completes and use its result.
962 try {
963 httpsProbe.join();
964 } catch (InterruptedException e) {
965 validationLog("Error: https probe wait interrupted!");
966 return CaptivePortalProbeResult.FAILED;
967 }
968 return httpsProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900969 }
970
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900971 private URL makeURL(String url) {
972 if (url != null) {
973 try {
974 return new URL(url);
975 } catch (MalformedURLException e) {
976 validationLog("Bad URL: " + url);
977 }
978 }
979 return null;
980 }
981
Paul Jensen306f1a42014-08-04 10:59:01 -0400982 /**
983 * @param responseReceived - whether or not we received a valid HTTP response to our request.
984 * If false, isCaptivePortal and responseTimestampMs are ignored
985 * TODO: This should be moved to the transports. The latency could be passed to the transports
986 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
987 * perhaps this could just be added to the WiFi transport only.
988 */
989 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
990 long requestTimestampMs, long responseTimestampMs) {
991 if (Settings.Global.getInt(mContext.getContentResolver(),
992 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400993 return;
994 }
995
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700996 if (systemReady == false) return;
997
Paul Jensen306f1a42014-08-04 10:59:01 -0400998 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
999 switch (mNetworkAgentInfo.networkInfo.getType()) {
1000 case ConnectivityManager.TYPE_WIFI:
1001 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
1002 if (currentWifiInfo != null) {
1003 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
1004 // surrounded by double quotation marks (thus violating the Javadoc), but this
1005 // was changed to match the Javadoc in API 17. Since clients may have started
1006 // sanitizing the output of this method since API 17 was released, we should
1007 // not change it here as it would become impossible to tell whether the SSID is
1008 // simply being surrounded by quotes due to the API, or whether those quotes
1009 // are actually part of the SSID.
1010 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
1011 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
1012 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001013 if (VDBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
Paul Jensen306f1a42014-08-04 10:59:01 -04001014 return;
1015 }
1016 break;
1017 case ConnectivityManager.TYPE_MOBILE:
1018 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
1019 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
1020 if (info == null) return;
1021 int numRegisteredCellInfo = 0;
1022 for (CellInfo cellInfo : info) {
1023 if (cellInfo.isRegistered()) {
1024 numRegisteredCellInfo++;
1025 if (numRegisteredCellInfo > 1) {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001026 if (VDBG) logw("more than one registered CellInfo." +
1027 " Can't tell which is active. Bailing.");
Paul Jensen306f1a42014-08-04 10:59:01 -04001028 return;
1029 }
1030 if (cellInfo instanceof CellInfoCdma) {
1031 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
1032 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1033 } else if (cellInfo instanceof CellInfoGsm) {
1034 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
1035 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1036 } else if (cellInfo instanceof CellInfoLte) {
1037 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
1038 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1039 } else if (cellInfo instanceof CellInfoWcdma) {
1040 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
1041 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
1042 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +09001043 if (VDBG) logw("Registered cellinfo is unrecognized");
Paul Jensen306f1a42014-08-04 10:59:01 -04001044 return;
1045 }
1046 }
1047 }
1048 break;
1049 default:
1050 return;
1051 }
1052 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
1053 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
1054 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
1055
1056 if (responseReceived) {
1057 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
1058 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
1059 }
Paul Jensen55298582014-08-20 11:01:41 -04001060 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
1061 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -04001062 }
Paul Jensend7b6ca92015-05-13 14:05:12 -04001063
Hugo Benichicfddd682016-05-31 16:28:06 +09001064 private void logNetworkEvent(int evtype) {
1065 mMetricsLog.log(new NetworkEvent(mNetId, evtype));
1066 }
1067
Hugo Benichidd229822016-11-15 23:23:24 +09001068 private int networkEventType(ValidationStage s, EvaluationResult r) {
1069 if (s.isFirstValidation) {
1070 if (r.isValidated) {
1071 return NetworkEvent.NETWORK_FIRST_VALIDATION_SUCCESS;
1072 } else {
1073 return NetworkEvent.NETWORK_FIRST_VALIDATION_PORTAL_FOUND;
1074 }
1075 } else {
1076 if (r.isValidated) {
1077 return NetworkEvent.NETWORK_REVALIDATION_SUCCESS;
1078 } else {
1079 return NetworkEvent.NETWORK_REVALIDATION_PORTAL_FOUND;
1080 }
1081 }
1082 }
1083
Hugo Benichicfddd682016-05-31 16:28:06 +09001084 private void maybeLogEvaluationResult(int evtype) {
1085 if (mEvaluationTimer.isRunning()) {
1086 mMetricsLog.log(new NetworkEvent(mNetId, evtype, mEvaluationTimer.stop()));
1087 mEvaluationTimer.reset();
1088 }
1089 }
1090
1091 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
Hugo Benichia365bac2017-03-22 18:29:58 +09001092 int[] transports = mNetworkAgentInfo.networkCapabilities.getTransportTypes();
Hugo Benichif927f0c2017-03-17 15:42:40 +09001093 boolean isFirstValidation = validationStage().isFirstValidation;
1094 ValidationProbeEvent ev = new ValidationProbeEvent();
1095 ev.probeType = ValidationProbeEvent.makeProbeType(probeType, isFirstValidation);
1096 ev.returnCode = probeResult;
1097 ev.durationMs = durationMs;
1098 mMetricsLog.log(mNetId, transports, ev);
Hugo Benichicfddd682016-05-31 16:28:06 +09001099 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001100}