blob: 01a2cad77e41e4d94b58aa967480423f57db4043 [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 {
Joe Onorato12acbd72016-02-01 17:49:31 -080082 private static final boolean DBG = false;
Erik Klinea488c232016-04-15 15:49:42 +090083 private static final String TAG = NetworkMonitor.class.getSimpleName();
Erik Klinee7d01792015-07-20 23:37:15 +090084 private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040085 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichid953bf82016-09-27 09:22:35 +090086 private static final int PROBE_TIMEOUT_MS = 3000;
Paul Jensen306f1a42014-08-04 10:59:01 -040087 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
88 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
89 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
90 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
91 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
92 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
93 public static final String EXTRA_CELL_ID = "extra_cellid";
94 public static final String EXTRA_SSID = "extra_ssid";
95 public static final String EXTRA_BSSID = "extra_bssid";
96 /** real time since boot */
97 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
98 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
99
100 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
101 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400102
Paul Jensenad50a1f2014-09-05 12:06:44 -0400103 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
104 // The network should be used as a default internet connection. It was found to be:
105 // 1. a functioning network providing internet access, or
106 // 2. a captive portal and the user decided to use it as is.
107 public static final int NETWORK_TEST_RESULT_VALID = 0;
108 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
109 // The network should not be used as a default internet connection. It was found to be:
110 // 1. a captive portal and the user is prompted to sign-in, or
111 // 2. a captive portal and the user did not want to use it, or
112 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
113 public static final int NETWORK_TEST_RESULT_INVALID = 1;
114
Paul Jensenca8f16a2014-05-09 12:47:55 -0400115 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
116
117 /**
118 * Inform NetworkMonitor that their network is connected.
119 * Initiates Network Validation.
120 */
121 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
122
123 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400124 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400125 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400126 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400127 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400128 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400129 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400130
131 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400132 * Message to self indicating it's time to evaluate a network's connectivity.
133 * arg1 = Token to ignore old messages.
134 */
Paul Jensen869868be2014-05-15 10:33:05 -0400135 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400136
137 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400138 * Inform NetworkMonitor that the network has disconnected.
139 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400140 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400141
142 /**
143 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400144 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400145 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400146 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400147
148 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400149 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400150 * arg1 = one of: APP_RETURN_DISMISSED,
151 * APP_RETURN_UNWANTED,
152 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500153 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400154 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400155 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400156
157 /**
158 * Request ConnectivityService display provisioning notification.
159 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400160 * arg2 = NetID.
161 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400162 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400163 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400164
165 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500166 * Message to self indicating sign-in app should be launched.
167 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
168 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400169 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500170 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400171
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400172 /**
173 * Retest network to see if captive portal is still in place.
174 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
175 * 0 indicates self-initiated, so nobody to blame.
176 */
177 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
178
Paul Jensend0491e9a2015-05-05 14:52:22 -0400179 // Start mReevaluateDelayMs at this value and double.
180 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
181 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
182 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
183 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400184 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400185 private static final int INVALID_UID = -1;
186 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400187 // Stop blaming UID that requested re-evaluation after this many attempts.
188 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400189 // Delay between reevaluations once a captive portal has been found.
190 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400191
192 private final Context mContext;
193 private final Handler mConnectivityServiceHandler;
194 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900195 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400196 private final TelephonyManager mTelephonyManager;
197 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400198 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500199 private final NetworkRequest mDefaultRequest;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900200 private final IpConnectivityLog mMetricsLog;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400201
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900202 private boolean mIsCaptivePortalCheckEnabled;
203 private boolean mUseHttps;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400204
Paul Jensenad50a1f2014-09-05 12:06:44 -0400205 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
206 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400207 // Avoids surfacing "Sign in to network" notification.
208 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400209
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700210 public boolean systemReady = false;
211
Paul Jensen71b645f2014-10-13 14:13:07 -0400212 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400213 private final State mValidatedState = new ValidatedState();
214 private final State mMaybeNotifyState = new MaybeNotifyState();
215 private final State mEvaluatingState = new EvaluatingState();
216 private final State mCaptivePortalState = new CaptivePortalState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400217
Paul Jensen25a217c2015-02-27 22:55:47 -0500218 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400219
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700220 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
221
Erik Klinea488c232016-04-15 15:49:42 +0900222 private final Stopwatch mEvaluationTimer = new Stopwatch();
223
Hugo Benichid953bf82016-09-27 09:22:35 +0900224 // This variable is set before transitioning to the mCaptivePortalState.
225 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
226
Paul Jensen2c311d62014-11-17 12:34:51 -0500227 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
228 NetworkRequest defaultRequest) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900229 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog());
230 }
231
232 @VisibleForTesting
233 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
234 NetworkRequest defaultRequest, IpConnectivityLog logger) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400235 // Add suffix indicating which NetworkMonitor we're talking about.
236 super(TAG + networkAgentInfo.name());
237
238 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900239 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400240 mConnectivityServiceHandler = handler;
241 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900242 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400243 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
244 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400245 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500246 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400247
248 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400249 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400250 addState(mMaybeNotifyState, mDefaultState);
251 addState(mEvaluatingState, mMaybeNotifyState);
252 addState(mCaptivePortalState, mMaybeNotifyState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700253 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400254
Paul Jensen869868be2014-05-15 10:33:05 -0400255 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
256 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900257 mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
258 Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400259
260 start();
261 }
262
Paul Jensen532b61432014-11-10 09:50:02 -0500263 @Override
264 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400265 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500266 }
267
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700268 private void validationLog(String s) {
269 if (DBG) log(s);
270 validationLogs.log(s);
271 }
272
273 public ReadOnlyLocalLog getValidationLogs() {
274 return validationLogs.readOnlyLocalLog();
275 }
276
Paul Jensen71b645f2014-10-13 14:13:07 -0400277 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
278 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400279 private class DefaultState extends State {
280 @Override
281 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400282 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400283 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900284 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400285 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400286 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400287 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900288 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500289 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
290 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
291 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400292 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700293 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400294 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400295 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400296 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400297 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400298 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400299 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400300 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400301 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400302 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900303
304 // If the user has seen and acted on a captive portal notification, and the
305 // captive portal app is now closed, disable HTTPS probes. This avoids the
306 // following pathological situation:
307 //
308 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
309 // 2. User opens the app and logs into the captive portal.
310 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
311 // perhaps due to the network blocking HTTPS?
312 //
313 // In this case, we'll fail to validate the network even after the app is
314 // dismissed. There is now no way to use this network, because the app is now
315 // gone, so the user cannot select "Use this network as is".
316 mUseHttps = false;
317
Paul Jensen71b645f2014-10-13 14:13:07 -0400318 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400319 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400320 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500321 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400322 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400323 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500324 // TODO: Distinguish this from a network that actually validates.
325 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400326 transitionTo(mValidatedState);
327 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400328 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400329 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400330 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400331 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400332 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900333 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400334 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400335 mUidResponsibleForReeval = 0;
336 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400337 break;
338 }
339 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400340 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400341 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400342 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400343 }
344 }
345
Paul Jensen71b645f2014-10-13 14:13:07 -0400346 // Being in the ValidatedState State indicates a Network is:
347 // - Successfully validated, or
348 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400349 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400350 private class ValidatedState extends State {
351 @Override
352 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900353 maybeLogEvaluationResult(NetworkEvent.NETWORK_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -0400354 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400355 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400356 }
357
358 @Override
359 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400360 switch (message.what) {
361 case CMD_NETWORK_CONNECTED:
362 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400363 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400364 default:
365 return NOT_HANDLED;
366 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400367 }
368 }
369
Paul Jensen71b645f2014-10-13 14:13:07 -0400370 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
371 // is required. This State takes care to clear the notification upon exit from the State.
372 private class MaybeNotifyState extends State {
373 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500374 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500375 switch (message.what) {
376 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
377 final Intent intent = new Intent(
378 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
379 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400380 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
381 new CaptivePortal(new ICaptivePortal.Stub() {
382 @Override
383 public void appResponse(int response) {
384 if (response == APP_RETURN_WANTED_AS_IS) {
385 mContext.enforceCallingPermission(
386 android.Manifest.permission.CONNECTIVITY_INTERNAL,
387 "CaptivePortal");
388 }
389 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
390 }
391 }));
Hugo Benichid953bf82016-09-27 09:22:35 +0900392 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL,
393 mLastPortalProbeResult.detectUrl);
Paul Jensen25a217c2015-02-27 22:55:47 -0500394 intent.setFlags(
395 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
396 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
397 return HANDLED;
398 default:
399 return NOT_HANDLED;
400 }
401 }
402
403 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400404 public void exit() {
405 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
406 mNetworkAgentInfo.network.netId, null);
407 mConnectivityServiceHandler.sendMessage(message);
408 }
409 }
410
Paul Jensen232437312016-04-06 09:51:26 -0400411 /**
412 * Result of calling isCaptivePortal().
413 * @hide
414 */
415 @VisibleForTesting
416 public static final class CaptivePortalProbeResult {
Hugo Benichid953bf82016-09-27 09:22:35 +0900417 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900418
Hugo Benichid953bf82016-09-27 09:22:35 +0900419 private final int mHttpResponseCode; // HTTP response code returned from Internet probe.
420 final String redirectUrl; // Redirect destination returned from Internet probe.
421 final String detectUrl; // URL where a 204 response code indicates
422 // captive portal has been appeased.
Paul Jensen232437312016-04-06 09:51:26 -0400423
Hugo Benichid953bf82016-09-27 09:22:35 +0900424 public CaptivePortalProbeResult(
425 int httpResponseCode, String redirectUrl, String detectUrl) {
Paul Jensen232437312016-04-06 09:51:26 -0400426 mHttpResponseCode = httpResponseCode;
Hugo Benichid953bf82016-09-27 09:22:35 +0900427 this.redirectUrl = redirectUrl;
428 this.detectUrl = detectUrl;
429 }
430
431 public CaptivePortalProbeResult(int httpResponseCode) {
432 this(httpResponseCode, null, null);
Paul Jensen232437312016-04-06 09:51:26 -0400433 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900434
435 boolean isSuccessful() { return mHttpResponseCode == 204; }
436 boolean isPortal() {
437 return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
438 }
Paul Jensen232437312016-04-06 09:51:26 -0400439 }
440
Paul Jensen71b645f2014-10-13 14:13:07 -0400441 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400442 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400443 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400444 private int mReevaluateDelayMs;
445 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400446
Paul Jensenca8f16a2014-05-09 12:47:55 -0400447 @Override
448 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900449 // If we have already started to track time spent in EvaluatingState
450 // don't reset the timer due simply to, say, commands or events that
451 // cause us to exit and re-enter EvaluatingState.
452 if (!mEvaluationTimer.isStarted()) {
453 mEvaluationTimer.start();
454 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400455 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400456 if (mUidResponsibleForReeval != INVALID_UID) {
457 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
458 mUidResponsibleForReeval = INVALID_UID;
459 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400460 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
461 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400462 }
463
464 @Override
465 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400466 switch (message.what) {
467 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400468 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400469 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500470 // Don't bother validating networks that don't satisify the default request.
471 // This includes:
472 // - VPNs which can be considered explicitly desired by the user and the
473 // user's desire trumps whether the network validates.
474 // - Networks that don't provide internet access. It's unclear how to
475 // validate such networks.
476 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
477 // such networks and the user didn't express interest in connecting to
478 // such networks (an app did) so the user may be unhappily surprised when
479 // asked to sign-in to a network they didn't want to connect to in the
480 // first place. Validation could be done to adjust the network scores
481 // however these networks are app-requested and may not be intended for
482 // general usage, in which case general validation may not be an accurate
483 // measure of the network's quality. Only the app knows how to evaluate
484 // the network so don't bother validating here. Furthermore sending HTTP
485 // packets over the network may be undesirable, for example an extremely
486 // expensive metered network, or unwanted leaking of the User Agent string.
487 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
488 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900489 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400490 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400491 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400492 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400493 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900494 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
495 // server's IP addresses could hit the DNS timeout, and attempting connections
496 // to each of the server's several IP addresses (currently one IPv4 and one
497 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
498 // will be unresponsive. isCaptivePortal() could be executed on another Thread
499 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400500 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900501 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400502 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900503 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400504 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Hugo Benichid953bf82016-09-27 09:22:35 +0900505 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.redirectUrl));
506 mLastPortalProbeResult = probeResult;
Paul Jensen71b645f2014-10-13 14:13:07 -0400507 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400508 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400509 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400510 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicfddd682016-05-31 16:28:06 +0900511 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400512 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900513 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
Hugo Benichid953bf82016-09-27 09:22:35 +0900514 probeResult.redirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400515 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400516 // Don't continue to blame UID forever.
517 TrafficStats.clearThreadStatsUid();
518 }
519 mReevaluateDelayMs *= 2;
520 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
521 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
522 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400523 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400524 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400525 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400526 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
527 // ignore any re-evaluation requests. After, restart the
528 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900529 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400530 default:
531 return NOT_HANDLED;
532 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400533 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400534
535 @Override
536 public void exit() {
537 TrafficStats.clearThreadStatsUid();
538 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400539 }
540
Paul Jensendcbe8352014-09-16 16:28:34 -0400541 // BroadcastReceiver that waits for a particular Intent and then posts a message.
542 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400543 private final int mToken;
544 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400545 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400546 CustomIntentReceiver(String action, int token, int what) {
547 mToken = token;
548 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400549 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
550 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400551 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400552 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500553 final Intent intent = new Intent(mAction);
554 intent.setPackage(mContext.getPackageName());
555 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400556 }
557 @Override
558 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400559 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400560 }
561 }
Paul Jensen869868be2014-05-15 10:33:05 -0400562
Paul Jensen71b645f2014-10-13 14:13:07 -0400563 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
564 // has been shown a notification to sign-in.
565 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500566 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
567 "android.net.netmon.launchCaptivePortalApp";
568
Paul Jensen869868be2014-05-15 10:33:05 -0400569 @Override
570 public void enter() {
Hugo Benichicfddd682016-05-31 16:28:06 +0900571 maybeLogEvaluationResult(NetworkEvent.NETWORK_CAPTIVE_PORTAL_FOUND);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400572 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400573 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500574 // Create a CustomIntentReceiver that sends us a
575 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
576 // touches the notification.
577 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400578 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500579 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
580 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
581 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400582 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500583 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400584 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
585 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500586 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400587 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400588 // Retest for captive portal occasionally.
589 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
590 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400591 }
592
593 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400594 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700595 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400596 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400597 }
598
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900599 private static String getCaptivePortalServerUrl(Context context, boolean isHttps) {
Udam Sainib7c24872016-01-04 12:16:14 -0800600 String server = Settings.Global.getString(context.getContentResolver(),
601 Settings.Global.CAPTIVE_PORTAL_SERVER);
602 if (server == null) server = DEFAULT_SERVER;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900603 return (isHttps ? "https" : "http") + "://" + server + "/generate_204";
604 }
605
606 public static String getCaptivePortalServerUrl(Context context) {
607 return getCaptivePortalServerUrl(context, false);
608 }
609
610 @VisibleForTesting
611 protected CaptivePortalProbeResult isCaptivePortal() {
Hugo Benichid953bf82016-09-27 09:22:35 +0900612 if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900613
614 URL pacUrl = null, httpUrl = null, httpsUrl = null;
615
616 // On networks with a PAC instead of fetching a URL that should result in a 204
617 // response, we instead simply fetch the PAC script. This is done for a few reasons:
618 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
619 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
620 // Network.openConnection() will ignore network-specific PACs and instead fetch
621 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
622 // NO_PROXY is the fetch of the PAC itself.
623 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
624 // happen before the fetch can commence, namely:
625 // a) the PAC script be fetched
626 // b) a PAC script resolver service be fired up and resolve the captive portal
627 // server.
628 // Network validation could be delayed until these prerequisities are satisifed or
629 // could simply be left to race them. Neither is an optimal solution.
630 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
631 // fact block fetching of the generate_204 URL which would lead to false negative
632 // results for network validation.
633 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
634 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
635 try {
636 pacUrl = new URL(proxyInfo.getPacFileUrl().toString());
637 } catch (MalformedURLException e) {
638 validationLog("Invalid PAC URL: " + proxyInfo.getPacFileUrl().toString());
639 return CaptivePortalProbeResult.FAILED;
640 }
641 }
642
643 if (pacUrl == null) {
644 try {
645 httpUrl = new URL(getCaptivePortalServerUrl(mContext, false));
646 httpsUrl = new URL(getCaptivePortalServerUrl(mContext, true));
647 } catch (MalformedURLException e) {
648 validationLog("Bad validation URL: " + getCaptivePortalServerUrl(mContext, false));
649 return CaptivePortalProbeResult.FAILED;
650 }
651 }
652
653 long startTime = SystemClock.elapsedRealtime();
654
655 // Pre-resolve the captive portal server host so we can log it.
656 // Only do this if HttpURLConnection is about to, to avoid any potentially
657 // unnecessary resolution.
658 String hostToResolve = null;
659 if (pacUrl != null) {
660 hostToResolve = pacUrl.getHost();
661 } else if (proxyInfo != null) {
662 hostToResolve = proxyInfo.getHost();
663 } else {
664 hostToResolve = httpUrl.getHost();
665 }
666
667 if (!TextUtils.isEmpty(hostToResolve)) {
668 String probeName = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
669 final Stopwatch dnsTimer = new Stopwatch().start();
Hugo Benichicfddd682016-05-31 16:28:06 +0900670 int dnsResult;
671 long dnsLatency;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900672 try {
673 InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(hostToResolve);
Hugo Benichicfddd682016-05-31 16:28:06 +0900674 dnsResult = ValidationProbeEvent.DNS_SUCCESS;
675 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900676 final StringBuffer connectInfo = new StringBuffer(", " + hostToResolve + "=");
677 for (InetAddress address : addresses) {
678 connectInfo.append(address.getHostAddress());
679 if (address != addresses[addresses.length-1]) connectInfo.append(",");
680 }
681 validationLog(probeName + " OK " + dnsLatency + "ms" + connectInfo);
682 } catch (UnknownHostException e) {
Hugo Benichicfddd682016-05-31 16:28:06 +0900683 dnsResult = ValidationProbeEvent.DNS_FAILURE;
684 dnsLatency = dnsTimer.stop();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900685 validationLog(probeName + " FAIL " + dnsLatency + "ms, " + hostToResolve);
686 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900687 logValidationProbe(dnsLatency, ValidationProbeEvent.PROBE_DNS, dnsResult);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900688 }
689
690 CaptivePortalProbeResult result;
691 if (pacUrl != null) {
692 result = sendHttpProbe(pacUrl, ValidationProbeEvent.PROBE_PAC);
693 } else if (mUseHttps) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900694 result = sendParallelHttpProbes(httpsUrl, httpUrl, null);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900695 } else {
696 result = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
697 }
698
699 long endTime = SystemClock.elapsedRealtime();
700
701 sendNetworkConditionsBroadcast(true /* response received */,
702 result.isPortal() /* isCaptivePortal */,
703 startTime, endTime);
704
705 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800706 }
707
Paul Jensenca8f16a2014-05-09 12:47:55 -0400708 /**
709 * Do a URL fetch on a known server to see if we get the data we expect.
710 * Returns HTTP response code.
711 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400712 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900713 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400714 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400715 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400716 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900717 final Stopwatch probeTimer = new Stopwatch().start();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400718 try {
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700719 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900720 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400721 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
722 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
723 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400724
725 // Time how long it takes to get a response to our request
726 long requestTimestamp = SystemClock.elapsedRealtime();
727
Pierre Imaibe12d762016-03-10 17:00:50 +0900728 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400729 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400730
731 // Time how long it takes to get a response to our request
732 long responseTimestamp = SystemClock.elapsedRealtime();
733
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900734 validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url +
735 " time=" + (responseTimestamp - requestTimestamp) + "ms" +
736 " ret=" + httpResponseCode +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700737 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400738 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
739 // portal. The only example of this seen so far was a captive portal. For
740 // the time being go with prior behavior of assuming it's not a captive
741 // portal. If it is considered a captive portal, a different sign-in URL
742 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
743 // proxy server.
744
745 // Consider 200 response with "Content-length=0" to not be a captive portal.
746 // There's no point in considering this a captive portal as the user cannot
747 // sign-in to an empty page. Probably the result of a broken transparent proxy.
748 // See http://b/9972012.
749 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700750 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400751 httpResponseCode = 204;
752 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400753
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900754 if (httpResponseCode == 200 && probeType == ValidationProbeEvent.PROBE_PAC) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700755 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500756 httpResponseCode = 204;
757 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400758 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700759 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400760 if (httpResponseCode == 599) {
761 // TODO: Ping gateway and DNS server and log results.
762 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400763 } finally {
764 if (urlConnection != null) {
765 urlConnection.disconnect();
766 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400767 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900768 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Hugo Benichid953bf82016-09-27 09:22:35 +0900769 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
Paul Jensenca8f16a2014-05-09 12:47:55 -0400770 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400771
Hugo Benichid953bf82016-09-27 09:22:35 +0900772 private CaptivePortalProbeResult sendParallelHttpProbes(
773 URL httpsUrl, URL httpUrl, URL fallbackUrl) {
774 // Number of probes to wait for. If a probe completes with a conclusive answer
775 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900776 final CountDownLatch latch = new CountDownLatch(2);
777
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900778 final class ProbeThread extends Thread {
779 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +0900780 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900781
782 public ProbeThread(boolean isHttps) {
783 mIsHttps = isHttps;
784 }
785
Hugo Benichid953bf82016-09-27 09:22:35 +0900786 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900787 return mResult;
788 }
789
790 @Override
791 public void run() {
792 if (mIsHttps) {
793 mResult = sendHttpProbe(httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
794 } else {
795 mResult = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
796 }
797 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900798 // Stop waiting immediately if https succeeds or if http finds a portal.
799 while (latch.getCount() > 0) {
800 latch.countDown();
801 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900802 }
Hugo Benichid953bf82016-09-27 09:22:35 +0900803 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900804 latch.countDown();
805 }
806 }
807
Hugo Benichid953bf82016-09-27 09:22:35 +0900808 final ProbeThread httpsProbe = new ProbeThread(true);
809 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900810
811 try {
Hugo Benichid953bf82016-09-27 09:22:35 +0900812 httpsProbe.start();
813 httpProbe.start();
814 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900815 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900816 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900817 return CaptivePortalProbeResult.FAILED;
818 }
819
Hugo Benichid953bf82016-09-27 09:22:35 +0900820 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
821 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900822
Hugo Benichid953bf82016-09-27 09:22:35 +0900823 // Look for a conclusive probe result first.
824 if (httpResult.isPortal()) {
825 return httpResult;
826 }
827 // httpsResult.isPortal() is not expected, but check it nonetheless.
828 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
829 return httpsResult;
830 }
831 // If a fallback url is specified, use a fallback probe to try again portal detection.
832 if (fallbackUrl != null) {
833 CaptivePortalProbeResult result =
834 sendHttpProbe(fallbackUrl, ValidationProbeEvent.PROBE_FALLBACK);
835 if (result.isPortal()) {
836 return result;
837 }
838 }
839 // Otherwise wait until https probe completes and use its result.
840 try {
841 httpsProbe.join();
842 } catch (InterruptedException e) {
843 validationLog("Error: https probe wait interrupted!");
844 return CaptivePortalProbeResult.FAILED;
845 }
846 return httpsProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900847 }
848
Paul Jensen306f1a42014-08-04 10:59:01 -0400849 /**
850 * @param responseReceived - whether or not we received a valid HTTP response to our request.
851 * If false, isCaptivePortal and responseTimestampMs are ignored
852 * TODO: This should be moved to the transports. The latency could be passed to the transports
853 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
854 * perhaps this could just be added to the WiFi transport only.
855 */
856 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
857 long requestTimestampMs, long responseTimestampMs) {
858 if (Settings.Global.getInt(mContext.getContentResolver(),
859 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400860 return;
861 }
862
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700863 if (systemReady == false) return;
864
Paul Jensen306f1a42014-08-04 10:59:01 -0400865 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
866 switch (mNetworkAgentInfo.networkInfo.getType()) {
867 case ConnectivityManager.TYPE_WIFI:
868 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
869 if (currentWifiInfo != null) {
870 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
871 // surrounded by double quotation marks (thus violating the Javadoc), but this
872 // was changed to match the Javadoc in API 17. Since clients may have started
873 // sanitizing the output of this method since API 17 was released, we should
874 // not change it here as it would become impossible to tell whether the SSID is
875 // simply being surrounded by quotes due to the API, or whether those quotes
876 // are actually part of the SSID.
877 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
878 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
879 } else {
880 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
881 return;
882 }
883 break;
884 case ConnectivityManager.TYPE_MOBILE:
885 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
886 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
887 if (info == null) return;
888 int numRegisteredCellInfo = 0;
889 for (CellInfo cellInfo : info) {
890 if (cellInfo.isRegistered()) {
891 numRegisteredCellInfo++;
892 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400893 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400894 "tell which is active. Bailing.");
895 return;
896 }
897 if (cellInfo instanceof CellInfoCdma) {
898 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
899 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
900 } else if (cellInfo instanceof CellInfoGsm) {
901 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
902 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
903 } else if (cellInfo instanceof CellInfoLte) {
904 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
905 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
906 } else if (cellInfo instanceof CellInfoWcdma) {
907 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
908 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
909 } else {
910 if (DBG) logw("Registered cellinfo is unrecognized");
911 return;
912 }
913 }
914 }
915 break;
916 default:
917 return;
918 }
919 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
920 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
921 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
922
923 if (responseReceived) {
924 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
925 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
926 }
Paul Jensen55298582014-08-20 11:01:41 -0400927 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
928 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400929 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400930
Hugo Benichicfddd682016-05-31 16:28:06 +0900931 private void logNetworkEvent(int evtype) {
932 mMetricsLog.log(new NetworkEvent(mNetId, evtype));
933 }
934
935 private void maybeLogEvaluationResult(int evtype) {
936 if (mEvaluationTimer.isRunning()) {
937 mMetricsLog.log(new NetworkEvent(mNetId, evtype, mEvaluationTimer.stop()));
938 mEvaluationTimer.reset();
939 }
940 }
941
942 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
943 mMetricsLog.log(new ValidationProbeEvent(mNetId, durationMs, probeType, probeResult));
944 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400945}