blob: c73d1dd954375aa7acab1ce6d6c10c220d71ba4b [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 Benichi92eb22fd2016-09-27 13:01:41 +090083 private static final boolean DBG = false;
84
Hugo Benichi11ae28f2016-09-27 13:16:19 +090085 // Default configuration values for captive portal detection probes.
86 // TODO: append a random length parameter to the default HTTPS url.
87 // TODO: randomize browser version ids in the default User-Agent String.
88 private static final String DEFAULT_HTTPS_URL = "https://www.google.com/generate_204";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090089 private static final String DEFAULT_HTTP_URL =
90 "http://connectivitycheck.gstatic.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +090091 private static final String DEFAULT_FALLBACK_URL = "http://www.google.com/gen_204";
92 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) "
93 + "AppleWebKit/537.36 (KHTML, like Gecko) "
94 + "Chrome/52.0.2743.82 Safari/537.36";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090095
Paul Jensenca8f16a2014-05-09 12:47:55 -040096 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090097 private static final int PROBE_TIMEOUT_MS = 3000;
98
Paul Jensen306f1a42014-08-04 10:59:01 -040099 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
100 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
101 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
102 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
103 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
104 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
105 public static final String EXTRA_CELL_ID = "extra_cellid";
106 public static final String EXTRA_SSID = "extra_ssid";
107 public static final String EXTRA_BSSID = "extra_bssid";
108 /** real time since boot */
109 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
110 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
111
112 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
113 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400114
Paul Jensenad50a1f2014-09-05 12:06:44 -0400115 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
116 // The network should be used as a default internet connection. It was found to be:
117 // 1. a functioning network providing internet access, or
118 // 2. a captive portal and the user decided to use it as is.
119 public static final int NETWORK_TEST_RESULT_VALID = 0;
120 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
121 // The network should not be used as a default internet connection. It was found to be:
122 // 1. a captive portal and the user is prompted to sign-in, or
123 // 2. a captive portal and the user did not want to use it, or
124 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
125 public static final int NETWORK_TEST_RESULT_INVALID = 1;
126
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
128
129 /**
130 * Inform NetworkMonitor that their network is connected.
131 * Initiates Network Validation.
132 */
133 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
134
135 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400136 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400137 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400138 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400139 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400140 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400141 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400142
143 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400144 * Message to self indicating it's time to evaluate a network's connectivity.
145 * arg1 = Token to ignore old messages.
146 */
Paul Jensen869868be2014-05-15 10:33:05 -0400147 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400148
149 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400150 * Inform NetworkMonitor that the network has disconnected.
151 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400152 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400153
154 /**
155 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400156 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400157 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400158 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400159
160 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400161 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400162 * arg1 = one of: APP_RETURN_DISMISSED,
163 * APP_RETURN_UNWANTED,
164 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500165 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400166 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400167 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400168
169 /**
170 * Request ConnectivityService display provisioning notification.
171 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400172 * arg2 = NetID.
173 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400174 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400175 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400176
177 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500178 * Message to self indicating sign-in app should be launched.
179 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
180 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400181 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500182 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400183
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400184 /**
185 * Retest network to see if captive portal is still in place.
186 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
187 * 0 indicates self-initiated, so nobody to blame.
188 */
189 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
190
Paul Jensend0491e9a2015-05-05 14:52:22 -0400191 // Start mReevaluateDelayMs at this value and double.
192 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
193 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
194 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
195 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400196 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400197 private static final int INVALID_UID = -1;
198 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400199 // Stop blaming UID that requested re-evaluation after this many attempts.
200 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400201 // Delay between reevaluations once a captive portal has been found.
202 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400203
204 private final Context mContext;
205 private final Handler mConnectivityServiceHandler;
206 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900207 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400208 private final TelephonyManager mTelephonyManager;
209 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400210 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500211 private final NetworkRequest mDefaultRequest;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900212 private final IpConnectivityLog mMetricsLog;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400213
Calvin On4bc78eb2016-10-11 15:10:46 -0700214 @VisibleForTesting
215 protected boolean mIsCaptivePortalCheckEnabled;
216
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900217 private boolean mUseHttps;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400218
Paul Jensenad50a1f2014-09-05 12:06:44 -0400219 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
220 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400221 // Avoids surfacing "Sign in to network" notification.
222 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400223
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700224 public boolean systemReady = false;
225
Paul Jensen71b645f2014-10-13 14:13:07 -0400226 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400227 private final State mValidatedState = new ValidatedState();
228 private final State mMaybeNotifyState = new MaybeNotifyState();
229 private final State mEvaluatingState = new EvaluatingState();
230 private final State mCaptivePortalState = new CaptivePortalState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400231
Paul Jensen25a217c2015-02-27 22:55:47 -0500232 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400233
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700234 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
235
Erik Klinea488c232016-04-15 15:49:42 +0900236 private final Stopwatch mEvaluationTimer = new Stopwatch();
237
Hugo Benichid953bf82016-09-27 09:22:35 +0900238 // This variable is set before transitioning to the mCaptivePortalState.
239 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
240
Paul Jensen2c311d62014-11-17 12:34:51 -0500241 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
242 NetworkRequest defaultRequest) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900243 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog());
244 }
245
246 @VisibleForTesting
247 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
248 NetworkRequest defaultRequest, IpConnectivityLog logger) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400249 // Add suffix indicating which NetworkMonitor we're talking about.
250 super(TAG + networkAgentInfo.name());
251
252 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900253 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400254 mConnectivityServiceHandler = handler;
255 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900256 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400257 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
258 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400259 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500260 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400261
262 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400263 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400264 addState(mMaybeNotifyState, mDefaultState);
265 addState(mEvaluatingState, mMaybeNotifyState);
266 addState(mCaptivePortalState, mMaybeNotifyState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700267 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400268
Paul Jensen869868be2014-05-15 10:33:05 -0400269 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
Calvin On4bc78eb2016-10-11 15:10:46 -0700270 Settings.Global.CAPTIVE_PORTAL_MODE, Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT)
271 != Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900272 mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
273 Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400274
275 start();
276 }
277
Paul Jensen532b61432014-11-10 09:50:02 -0500278 @Override
279 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400280 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500281 }
282
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700283 private void validationLog(String s) {
284 if (DBG) log(s);
285 validationLogs.log(s);
286 }
287
288 public ReadOnlyLocalLog getValidationLogs() {
289 return validationLogs.readOnlyLocalLog();
290 }
291
Paul Jensen71b645f2014-10-13 14:13:07 -0400292 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
293 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400294 private class DefaultState extends State {
295 @Override
296 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400297 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400298 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900299 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400300 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400301 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400302 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900303 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500304 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
305 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
306 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400307 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700308 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400309 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400310 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400311 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400312 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400313 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400314 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400315 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400316 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400317 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900318
319 // If the user has seen and acted on a captive portal notification, and the
320 // captive portal app is now closed, disable HTTPS probes. This avoids the
321 // following pathological situation:
322 //
323 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
324 // 2. User opens the app and logs into the captive portal.
325 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
326 // perhaps due to the network blocking HTTPS?
327 //
328 // In this case, we'll fail to validate the network even after the app is
329 // dismissed. There is now no way to use this network, because the app is now
330 // gone, so the user cannot select "Use this network as is".
331 mUseHttps = false;
332
Paul Jensen71b645f2014-10-13 14:13:07 -0400333 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400334 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400335 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500336 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400337 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400338 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500339 // TODO: Distinguish this from a network that actually validates.
340 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400341 transitionTo(mValidatedState);
342 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400343 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400344 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400345 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400346 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400347 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900348 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400349 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400350 mUidResponsibleForReeval = 0;
351 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400352 break;
353 }
354 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400355 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400356 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400357 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400358 }
359 }
360
Paul Jensen71b645f2014-10-13 14:13:07 -0400361 // Being in the ValidatedState State indicates a Network is:
362 // - Successfully validated, or
363 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400364 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400365 private class ValidatedState extends State {
366 @Override
367 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900368 maybeLogEvaluationResult(NetworkEvent.NETWORK_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -0400369 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400370 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400371 }
372
373 @Override
374 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400375 switch (message.what) {
376 case CMD_NETWORK_CONNECTED:
377 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400378 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400379 default:
380 return NOT_HANDLED;
381 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400382 }
383 }
384
Paul Jensen71b645f2014-10-13 14:13:07 -0400385 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
386 // is required. This State takes care to clear the notification upon exit from the State.
387 private class MaybeNotifyState extends State {
388 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500389 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500390 switch (message.what) {
391 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
392 final Intent intent = new Intent(
393 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
394 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400395 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
396 new CaptivePortal(new ICaptivePortal.Stub() {
397 @Override
398 public void appResponse(int response) {
399 if (response == APP_RETURN_WANTED_AS_IS) {
400 mContext.enforceCallingPermission(
401 android.Manifest.permission.CONNECTIVITY_INTERNAL,
402 "CaptivePortal");
403 }
404 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
405 }
406 }));
Hugo Benichid953bf82016-09-27 09:22:35 +0900407 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL,
408 mLastPortalProbeResult.detectUrl);
Paul Jensen25a217c2015-02-27 22:55:47 -0500409 intent.setFlags(
410 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
411 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
412 return HANDLED;
413 default:
414 return NOT_HANDLED;
415 }
416 }
417
418 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400419 public void exit() {
420 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
421 mNetworkAgentInfo.network.netId, null);
422 mConnectivityServiceHandler.sendMessage(message);
423 }
424 }
425
Paul Jensen232437312016-04-06 09:51:26 -0400426 /**
427 * Result of calling isCaptivePortal().
428 * @hide
429 */
430 @VisibleForTesting
431 public static final class CaptivePortalProbeResult {
Hugo Benichid953bf82016-09-27 09:22:35 +0900432 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900433
Hugo Benichid953bf82016-09-27 09:22:35 +0900434 private final int mHttpResponseCode; // HTTP response code returned from Internet probe.
435 final String redirectUrl; // Redirect destination returned from Internet probe.
436 final String detectUrl; // URL where a 204 response code indicates
437 // captive portal has been appeased.
Paul Jensen232437312016-04-06 09:51:26 -0400438
Hugo Benichid953bf82016-09-27 09:22:35 +0900439 public CaptivePortalProbeResult(
440 int httpResponseCode, String redirectUrl, String detectUrl) {
Paul Jensen232437312016-04-06 09:51:26 -0400441 mHttpResponseCode = httpResponseCode;
Hugo Benichid953bf82016-09-27 09:22:35 +0900442 this.redirectUrl = redirectUrl;
443 this.detectUrl = detectUrl;
444 }
445
446 public CaptivePortalProbeResult(int httpResponseCode) {
447 this(httpResponseCode, null, null);
Paul Jensen232437312016-04-06 09:51:26 -0400448 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900449
450 boolean isSuccessful() { return mHttpResponseCode == 204; }
451 boolean isPortal() {
452 return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
453 }
Paul Jensen232437312016-04-06 09:51:26 -0400454 }
455
Paul Jensen71b645f2014-10-13 14:13:07 -0400456 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400457 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400458 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400459 private int mReevaluateDelayMs;
460 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400461
Paul Jensenca8f16a2014-05-09 12:47:55 -0400462 @Override
463 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900464 // If we have already started to track time spent in EvaluatingState
465 // don't reset the timer due simply to, say, commands or events that
466 // cause us to exit and re-enter EvaluatingState.
467 if (!mEvaluationTimer.isStarted()) {
468 mEvaluationTimer.start();
469 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400470 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400471 if (mUidResponsibleForReeval != INVALID_UID) {
472 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
473 mUidResponsibleForReeval = INVALID_UID;
474 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400475 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
476 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400477 }
478
479 @Override
480 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400481 switch (message.what) {
482 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400483 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400484 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500485 // Don't bother validating networks that don't satisify the default request.
486 // This includes:
487 // - VPNs which can be considered explicitly desired by the user and the
488 // user's desire trumps whether the network validates.
489 // - Networks that don't provide internet access. It's unclear how to
490 // validate such networks.
491 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
492 // such networks and the user didn't express interest in connecting to
493 // such networks (an app did) so the user may be unhappily surprised when
494 // asked to sign-in to a network they didn't want to connect to in the
495 // first place. Validation could be done to adjust the network scores
496 // however these networks are app-requested and may not be intended for
497 // general usage, in which case general validation may not be an accurate
498 // measure of the network's quality. Only the app knows how to evaluate
499 // the network so don't bother validating here. Furthermore sending HTTP
500 // packets over the network may be undesirable, for example an extremely
501 // expensive metered network, or unwanted leaking of the User Agent string.
502 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
503 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900504 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400505 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400506 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400507 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400508 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900509 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
510 // server's IP addresses could hit the DNS timeout, and attempting connections
511 // to each of the server's several IP addresses (currently one IPv4 and one
512 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
513 // will be unresponsive. isCaptivePortal() could be executed on another Thread
514 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400515 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900516 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400517 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900518 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400519 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Hugo Benichid953bf82016-09-27 09:22:35 +0900520 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.redirectUrl));
521 mLastPortalProbeResult = probeResult;
Paul Jensen71b645f2014-10-13 14:13:07 -0400522 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400523 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400524 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400525 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicfddd682016-05-31 16:28:06 +0900526 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400527 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900528 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
Hugo Benichid953bf82016-09-27 09:22:35 +0900529 probeResult.redirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400530 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400531 // Don't continue to blame UID forever.
532 TrafficStats.clearThreadStatsUid();
533 }
534 mReevaluateDelayMs *= 2;
535 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
536 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
537 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400538 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400539 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400540 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400541 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
542 // ignore any re-evaluation requests. After, restart the
543 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900544 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400545 default:
546 return NOT_HANDLED;
547 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400548 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400549
550 @Override
551 public void exit() {
552 TrafficStats.clearThreadStatsUid();
553 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400554 }
555
Paul Jensendcbe8352014-09-16 16:28:34 -0400556 // BroadcastReceiver that waits for a particular Intent and then posts a message.
557 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400558 private final int mToken;
559 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400560 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400561 CustomIntentReceiver(String action, int token, int what) {
562 mToken = token;
563 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400564 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
565 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400566 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400567 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500568 final Intent intent = new Intent(mAction);
569 intent.setPackage(mContext.getPackageName());
570 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400571 }
572 @Override
573 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400574 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400575 }
576 }
Paul Jensen869868be2014-05-15 10:33:05 -0400577
Paul Jensen71b645f2014-10-13 14:13:07 -0400578 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
579 // has been shown a notification to sign-in.
580 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500581 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
582 "android.net.netmon.launchCaptivePortalApp";
583
Paul Jensen869868be2014-05-15 10:33:05 -0400584 @Override
585 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900586 maybeLogEvaluationResult(NetworkEvent.NETWORK_CAPTIVE_PORTAL_FOUND);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400587 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400588 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500589 // Create a CustomIntentReceiver that sends us a
590 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
591 // touches the notification.
592 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400593 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500594 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
595 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
596 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400597 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500598 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400599 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
600 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500601 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400602 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400603 // Retest for captive portal occasionally.
604 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
605 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400606 }
607
608 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400609 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700610 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400611 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400612 }
613
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900614 private static String getCaptivePortalServerHttpsUrl(Context context) {
615 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTPS_URL, DEFAULT_HTTPS_URL);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900616 }
617
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900618 public static String getCaptivePortalServerHttpUrl(Context context) {
619 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTP_URL, DEFAULT_HTTP_URL);
620 }
621
622 private static String getCaptivePortalFallbackUrl(Context context) {
623 return getSetting(context,
624 Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL, DEFAULT_FALLBACK_URL);
625 }
626
627 private static String getCaptivePortalUserAgent(Context context) {
628 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT);
629 }
630
631 private static String getSetting(Context context, String symbol, String defaultValue) {
632 final String value = Settings.Global.getString(context.getContentResolver(), symbol);
633 return value != null ? value : defaultValue;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900634 }
635
636 @VisibleForTesting
637 protected CaptivePortalProbeResult isCaptivePortal() {
Calvin On4bc78eb2016-10-11 15:10:46 -0700638 if (!mIsCaptivePortalCheckEnabled) {
639 validationLog("Validation disabled.");
640 return new CaptivePortalProbeResult(204);
641 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900642
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900643 URL pacUrl = null, httpsUrl = null, httpUrl = null, fallbackUrl = null;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900644
645 // On networks with a PAC instead of fetching a URL that should result in a 204
646 // response, we instead simply fetch the PAC script. This is done for a few reasons:
647 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
648 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
649 // Network.openConnection() will ignore network-specific PACs and instead fetch
650 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
651 // NO_PROXY is the fetch of the PAC itself.
652 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
653 // happen before the fetch can commence, namely:
654 // a) the PAC script be fetched
655 // b) a PAC script resolver service be fired up and resolve the captive portal
656 // server.
657 // Network validation could be delayed until these prerequisities are satisifed or
658 // could simply be left to race them. Neither is an optimal solution.
659 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
660 // fact block fetching of the generate_204 URL which would lead to false negative
661 // results for network validation.
662 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
663 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900664 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString());
665 if (pacUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900666 return CaptivePortalProbeResult.FAILED;
667 }
668 }
669
670 if (pacUrl == null) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900671 httpsUrl = makeURL(getCaptivePortalServerHttpsUrl(mContext));
672 httpUrl = makeURL(getCaptivePortalServerHttpUrl(mContext));
673 fallbackUrl = makeURL(getCaptivePortalFallbackUrl(mContext));
674 if (httpUrl == null || httpsUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900675 return CaptivePortalProbeResult.FAILED;
676 }
677 }
678
679 long startTime = SystemClock.elapsedRealtime();
680
681 // Pre-resolve the captive portal server host so we can log it.
682 // Only do this if HttpURLConnection is about to, to avoid any potentially
683 // unnecessary resolution.
684 String hostToResolve = null;
685 if (pacUrl != null) {
686 hostToResolve = pacUrl.getHost();
687 } else if (proxyInfo != null) {
688 hostToResolve = proxyInfo.getHost();
689 } else {
690 hostToResolve = httpUrl.getHost();
691 }
692
693 if (!TextUtils.isEmpty(hostToResolve)) {
694 String probeName = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
695 final Stopwatch dnsTimer = new Stopwatch().start();
Hugo Benichicfddd682016-05-31 16:28:06 +0900696 int dnsResult;
697 long dnsLatency;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900698 try {
699 InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(hostToResolve);
Hugo Benichicfddd682016-05-31 16:28:06 +0900700 dnsResult = ValidationProbeEvent.DNS_SUCCESS;
701 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900702 final StringBuffer connectInfo = new StringBuffer(", " + hostToResolve + "=");
703 for (InetAddress address : addresses) {
704 connectInfo.append(address.getHostAddress());
705 if (address != addresses[addresses.length-1]) connectInfo.append(",");
706 }
707 validationLog(probeName + " OK " + dnsLatency + "ms" + connectInfo);
708 } catch (UnknownHostException e) {
Hugo Benichicfddd682016-05-31 16:28:06 +0900709 dnsResult = ValidationProbeEvent.DNS_FAILURE;
710 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900711 validationLog(probeName + " FAIL " + dnsLatency + "ms, " + hostToResolve);
712 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900713 logValidationProbe(dnsLatency, ValidationProbeEvent.PROBE_DNS, dnsResult);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900714 }
715
716 CaptivePortalProbeResult result;
717 if (pacUrl != null) {
718 result = sendHttpProbe(pacUrl, ValidationProbeEvent.PROBE_PAC);
719 } else if (mUseHttps) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900720 result = sendParallelHttpProbes(httpsUrl, httpUrl, fallbackUrl);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900721 } else {
722 result = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
723 }
724
725 long endTime = SystemClock.elapsedRealtime();
726
727 sendNetworkConditionsBroadcast(true /* response received */,
728 result.isPortal() /* isCaptivePortal */,
729 startTime, endTime);
730
731 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800732 }
733
Paul Jensenca8f16a2014-05-09 12:47:55 -0400734 /**
735 * Do a URL fetch on a known server to see if we get the data we expect.
736 * Returns HTTP response code.
737 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400738 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900739 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400740 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400741 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400742 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900743 final Stopwatch probeTimer = new Stopwatch().start();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400744 try {
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700745 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900746 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400747 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
748 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
749 urlConnection.setUseCaches(false);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900750 final String userAgent = getCaptivePortalUserAgent(mContext);
751 if (userAgent != null) {
752 urlConnection.setRequestProperty("User-Agent", userAgent);
753 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400754
755 // Time how long it takes to get a response to our request
756 long requestTimestamp = SystemClock.elapsedRealtime();
757
Pierre Imaibe12d762016-03-10 17:00:50 +0900758 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400759 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400760
761 // Time how long it takes to get a response to our request
762 long responseTimestamp = SystemClock.elapsedRealtime();
763
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900764 validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url +
765 " time=" + (responseTimestamp - requestTimestamp) + "ms" +
766 " ret=" + httpResponseCode +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700767 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400768 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
769 // portal. The only example of this seen so far was a captive portal. For
770 // the time being go with prior behavior of assuming it's not a captive
771 // portal. If it is considered a captive portal, a different sign-in URL
772 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
773 // proxy server.
774
775 // Consider 200 response with "Content-length=0" to not be a captive portal.
776 // There's no point in considering this a captive portal as the user cannot
777 // sign-in to an empty page. Probably the result of a broken transparent proxy.
778 // See http://b/9972012.
779 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700780 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400781 httpResponseCode = 204;
782 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400783
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900784 if (httpResponseCode == 200 && probeType == ValidationProbeEvent.PROBE_PAC) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700785 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500786 httpResponseCode = 204;
787 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400788 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700789 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400790 if (httpResponseCode == 599) {
791 // TODO: Ping gateway and DNS server and log results.
792 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400793 } finally {
794 if (urlConnection != null) {
795 urlConnection.disconnect();
796 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400797 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900798 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Hugo Benichid953bf82016-09-27 09:22:35 +0900799 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
Paul Jensenca8f16a2014-05-09 12:47:55 -0400800 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400801
Hugo Benichid953bf82016-09-27 09:22:35 +0900802 private CaptivePortalProbeResult sendParallelHttpProbes(
803 URL httpsUrl, URL httpUrl, URL fallbackUrl) {
804 // Number of probes to wait for. If a probe completes with a conclusive answer
805 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900806 final CountDownLatch latch = new CountDownLatch(2);
807
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900808 final class ProbeThread extends Thread {
809 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +0900810 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900811
812 public ProbeThread(boolean isHttps) {
813 mIsHttps = isHttps;
814 }
815
Hugo Benichid953bf82016-09-27 09:22:35 +0900816 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900817 return mResult;
818 }
819
820 @Override
821 public void run() {
822 if (mIsHttps) {
823 mResult = sendHttpProbe(httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
824 } else {
825 mResult = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
826 }
827 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900828 // Stop waiting immediately if https succeeds or if http finds a portal.
829 while (latch.getCount() > 0) {
830 latch.countDown();
831 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900832 }
Hugo Benichid953bf82016-09-27 09:22:35 +0900833 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900834 latch.countDown();
835 }
836 }
837
Hugo Benichid953bf82016-09-27 09:22:35 +0900838 final ProbeThread httpsProbe = new ProbeThread(true);
839 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900840
841 try {
Hugo Benichid953bf82016-09-27 09:22:35 +0900842 httpsProbe.start();
843 httpProbe.start();
844 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900845 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900846 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900847 return CaptivePortalProbeResult.FAILED;
848 }
849
Hugo Benichid953bf82016-09-27 09:22:35 +0900850 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
851 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900852
Hugo Benichid953bf82016-09-27 09:22:35 +0900853 // Look for a conclusive probe result first.
854 if (httpResult.isPortal()) {
855 return httpResult;
856 }
857 // httpsResult.isPortal() is not expected, but check it nonetheless.
858 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
859 return httpsResult;
860 }
861 // If a fallback url is specified, use a fallback probe to try again portal detection.
862 if (fallbackUrl != null) {
863 CaptivePortalProbeResult result =
864 sendHttpProbe(fallbackUrl, ValidationProbeEvent.PROBE_FALLBACK);
865 if (result.isPortal()) {
866 return result;
867 }
868 }
869 // Otherwise wait until https probe completes and use its result.
870 try {
871 httpsProbe.join();
872 } catch (InterruptedException e) {
873 validationLog("Error: https probe wait interrupted!");
874 return CaptivePortalProbeResult.FAILED;
875 }
876 return httpsProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900877 }
878
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900879 private URL makeURL(String url) {
880 if (url != null) {
881 try {
882 return new URL(url);
883 } catch (MalformedURLException e) {
884 validationLog("Bad URL: " + url);
885 }
886 }
887 return null;
888 }
889
Paul Jensen306f1a42014-08-04 10:59:01 -0400890 /**
891 * @param responseReceived - whether or not we received a valid HTTP response to our request.
892 * If false, isCaptivePortal and responseTimestampMs are ignored
893 * TODO: This should be moved to the transports. The latency could be passed to the transports
894 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
895 * perhaps this could just be added to the WiFi transport only.
896 */
897 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
898 long requestTimestampMs, long responseTimestampMs) {
899 if (Settings.Global.getInt(mContext.getContentResolver(),
900 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400901 return;
902 }
903
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700904 if (systemReady == false) return;
905
Paul Jensen306f1a42014-08-04 10:59:01 -0400906 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
907 switch (mNetworkAgentInfo.networkInfo.getType()) {
908 case ConnectivityManager.TYPE_WIFI:
909 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
910 if (currentWifiInfo != null) {
911 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
912 // surrounded by double quotation marks (thus violating the Javadoc), but this
913 // was changed to match the Javadoc in API 17. Since clients may have started
914 // sanitizing the output of this method since API 17 was released, we should
915 // not change it here as it would become impossible to tell whether the SSID is
916 // simply being surrounded by quotes due to the API, or whether those quotes
917 // are actually part of the SSID.
918 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
919 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
920 } else {
921 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
922 return;
923 }
924 break;
925 case ConnectivityManager.TYPE_MOBILE:
926 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
927 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
928 if (info == null) return;
929 int numRegisteredCellInfo = 0;
930 for (CellInfo cellInfo : info) {
931 if (cellInfo.isRegistered()) {
932 numRegisteredCellInfo++;
933 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400934 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400935 "tell which is active. Bailing.");
936 return;
937 }
938 if (cellInfo instanceof CellInfoCdma) {
939 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
940 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
941 } else if (cellInfo instanceof CellInfoGsm) {
942 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
943 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
944 } else if (cellInfo instanceof CellInfoLte) {
945 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
946 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
947 } else if (cellInfo instanceof CellInfoWcdma) {
948 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
949 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
950 } else {
951 if (DBG) logw("Registered cellinfo is unrecognized");
952 return;
953 }
954 }
955 }
956 break;
957 default:
958 return;
959 }
960 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
961 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
962 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
963
964 if (responseReceived) {
965 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
966 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
967 }
Paul Jensen55298582014-08-20 11:01:41 -0400968 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
969 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400970 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400971
Hugo Benichicfddd682016-05-31 16:28:06 +0900972 private void logNetworkEvent(int evtype) {
973 mMetricsLog.log(new NetworkEvent(mNetId, evtype));
974 }
975
976 private void maybeLogEvaluationResult(int evtype) {
977 if (mEvaluationTimer.isRunning()) {
978 mMetricsLog.log(new NetworkEvent(mNetId, evtype, mEvaluationTimer.stop()));
979 mEvaluationTimer.reset();
980 }
981 }
982
983 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
984 mMetricsLog.log(new ValidationProbeEvent(mNetId, durationMs, probeType, probeResult));
985 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400986}