blob: fbda901ec402d121bc5dcfbeaf07f0b1e3099638 [file] [log] [blame]
Paul Jensenca8f16a2014-05-09 12:47:55 -04001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Paul Jensen49e3edf2015-05-22 10:50:39 -040019import static android.net.CaptivePortal.APP_RETURN_DISMISSED;
20import static android.net.CaptivePortal.APP_RETURN_UNWANTED;
21import static android.net.CaptivePortal.APP_RETURN_WANTED_AS_IS;
22
Paul Jensen79a08052014-08-21 12:44:07 -040023import android.app.AlarmManager;
Paul Jensen869868be2014-05-15 10:33:05 -040024import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
Paul Jensenca8f16a2014-05-09 12:47:55 -040026import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040027import android.content.Intent;
28import android.content.IntentFilter;
Paul Jensen49e3edf2015-05-22 10:50:39 -040029import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040030import android.net.ConnectivityManager;
Paul Jensen49e3edf2015-05-22 10:50:39 -040031import android.net.ICaptivePortal;
Paul Jensen2c311d62014-11-17 12:34:51 -050032import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050033import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040034import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040035import android.net.Uri;
Hugo Benichicfddd682016-05-31 16:28:06 +090036import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090037import android.net.metrics.NetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090038import android.net.metrics.ValidationProbeEvent;
Hugo Benichid953bf82016-09-27 09:22:35 +090039import android.net.util.Stopwatch;
Paul Jensen306f1a42014-08-04 10:59:01 -040040import android.net.wifi.WifiInfo;
41import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040042import android.os.Handler;
43import android.os.Message;
Paul Jensen306f1a42014-08-04 10:59:01 -040044import android.os.SystemClock;
Paul Jensen869868be2014-05-15 10:33:05 -040045import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040046import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040047import android.telephony.CellIdentityCdma;
48import android.telephony.CellIdentityGsm;
49import android.telephony.CellIdentityLte;
50import android.telephony.CellIdentityWcdma;
51import android.telephony.CellInfo;
52import android.telephony.CellInfoCdma;
53import android.telephony.CellInfoGsm;
54import android.telephony.CellInfoLte;
55import android.telephony.CellInfoWcdma;
56import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040057import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070058import android.util.LocalLog;
59import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050060import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040061
Paul Jensend7b6ca92015-05-13 14:05:12 -040062import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040063import com.android.internal.util.Protocol;
64import com.android.internal.util.State;
65import com.android.internal.util.StateMachine;
Paul Jensenca8f16a2014-05-09 12:47:55 -040066
Paul Jensenca8f16a2014-05-09 12:47:55 -040067import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040068import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040069import java.net.InetAddress;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090070import java.net.MalformedURLException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.net.URL;
Hugo Benichid953bf82016-09-27 09:22:35 +090072import java.net.UnknownHostException;
Paul Jensen306f1a42014-08-04 10:59:01 -040073import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040074import java.util.Random;
Hugo Benichid953bf82016-09-27 09:22:35 +090075import java.util.concurrent.CountDownLatch;
76import java.util.concurrent.TimeUnit;
Paul Jensenca8f16a2014-05-09 12:47:55 -040077
78/**
79 * {@hide}
80 */
81public class NetworkMonitor extends StateMachine {
Erik Klinea488c232016-04-15 15:49:42 +090082 private static final String TAG = NetworkMonitor.class.getSimpleName();
Hugo Benichia4f17bc2016-11-21 13:50:05 +090083 private static final boolean DBG = true;
84 private static final boolean VDBG = false;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090085
Hugo Benichi11ae28f2016-09-27 13:16:19 +090086 // Default configuration values for captive portal detection probes.
87 // TODO: append a random length parameter to the default HTTPS url.
88 // TODO: randomize browser version ids in the default User-Agent String.
89 private static final String DEFAULT_HTTPS_URL = "https://www.google.com/generate_204";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090090 private static final String DEFAULT_HTTP_URL =
91 "http://connectivitycheck.gstatic.com/generate_204";
Hugo Benichi11ae28f2016-09-27 13:16:19 +090092 private static final String DEFAULT_FALLBACK_URL = "http://www.google.com/gen_204";
93 private static final String DEFAULT_USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) "
94 + "AppleWebKit/537.36 (KHTML, like Gecko) "
95 + "Chrome/52.0.2743.82 Safari/537.36";
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090096
Paul Jensenca8f16a2014-05-09 12:47:55 -040097 private static final int SOCKET_TIMEOUT_MS = 10000;
Hugo Benichi92eb22fd2016-09-27 13:01:41 +090098 private static final int PROBE_TIMEOUT_MS = 3000;
99
Hugo Benichidd229822016-11-15 23:23:24 +0900100 static enum EvaluationResult {
101 VALIDATED(true),
102 CAPTIVE_PORTAL(false);
103 final boolean isValidated;
104 EvaluationResult(boolean isValidated) {
105 this.isValidated = isValidated;
106 }
107 }
108
109 static enum ValidationStage {
110 FIRST_VALIDATION(true),
111 REVALIDATION(false);
112 final boolean isFirstValidation;
113 ValidationStage(boolean isFirstValidation) {
114 this.isFirstValidation = isFirstValidation;
115 }
116 }
117
Paul Jensen306f1a42014-08-04 10:59:01 -0400118 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
119 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
120 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
121 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
122 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
123 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
124 public static final String EXTRA_CELL_ID = "extra_cellid";
125 public static final String EXTRA_SSID = "extra_ssid";
126 public static final String EXTRA_BSSID = "extra_bssid";
127 /** real time since boot */
128 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
129 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
130
131 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
132 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400133
Paul Jensenad50a1f2014-09-05 12:06:44 -0400134 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
135 // The network should be used as a default internet connection. It was found to be:
136 // 1. a functioning network providing internet access, or
137 // 2. a captive portal and the user decided to use it as is.
138 public static final int NETWORK_TEST_RESULT_VALID = 0;
139 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
140 // The network should not be used as a default internet connection. It was found to be:
141 // 1. a captive portal and the user is prompted to sign-in, or
142 // 2. a captive portal and the user did not want to use it, or
143 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
144 public static final int NETWORK_TEST_RESULT_INVALID = 1;
145
Paul Jensenca8f16a2014-05-09 12:47:55 -0400146 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
147
148 /**
149 * Inform NetworkMonitor that their network is connected.
150 * Initiates Network Validation.
151 */
152 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
153
154 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400155 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400156 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400157 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400158 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400159 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400160 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400161
162 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400163 * Message to self indicating it's time to evaluate a network's connectivity.
164 * arg1 = Token to ignore old messages.
165 */
Paul Jensen869868be2014-05-15 10:33:05 -0400166 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400167
168 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400169 * Inform NetworkMonitor that the network has disconnected.
170 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400171 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400172
173 /**
174 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400175 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400176 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400177 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400178
179 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400180 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400181 * arg1 = one of: APP_RETURN_DISMISSED,
182 * APP_RETURN_UNWANTED,
183 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500184 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400185 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400186 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400187
188 /**
189 * Request ConnectivityService display provisioning notification.
190 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400191 * arg2 = NetID.
192 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400193 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400194 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400195
196 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500197 * Message to self indicating sign-in app should be launched.
198 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
199 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400200 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500201 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400202
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400203 /**
204 * Retest network to see if captive portal is still in place.
205 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
206 * 0 indicates self-initiated, so nobody to blame.
207 */
208 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
209
Paul Jensend0491e9a2015-05-05 14:52:22 -0400210 // Start mReevaluateDelayMs at this value and double.
211 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
212 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
213 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
214 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400215 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400216 private static final int INVALID_UID = -1;
217 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400218 // Stop blaming UID that requested re-evaluation after this many attempts.
219 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400220 // Delay between reevaluations once a captive portal has been found.
221 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400222
223 private final Context mContext;
224 private final Handler mConnectivityServiceHandler;
225 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900226 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400227 private final TelephonyManager mTelephonyManager;
228 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400229 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500230 private final NetworkRequest mDefaultRequest;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900231 private final IpConnectivityLog mMetricsLog;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400232
Calvin On4bc78eb2016-10-11 15:10:46 -0700233 @VisibleForTesting
234 protected boolean mIsCaptivePortalCheckEnabled;
235
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900236 private boolean mUseHttps;
Hugo Benichidd229822016-11-15 23:23:24 +0900237 // The total number of captive portal detection attempts for this NetworkMonitor instance.
238 private int mValidations = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400239
Paul Jensenad50a1f2014-09-05 12:06:44 -0400240 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
241 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400242 // Avoids surfacing "Sign in to network" notification.
243 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400244
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700245 public boolean systemReady = false;
246
Paul Jensen71b645f2014-10-13 14:13:07 -0400247 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400248 private final State mValidatedState = new ValidatedState();
249 private final State mMaybeNotifyState = new MaybeNotifyState();
250 private final State mEvaluatingState = new EvaluatingState();
251 private final State mCaptivePortalState = new CaptivePortalState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400252
Paul Jensen25a217c2015-02-27 22:55:47 -0500253 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400254
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700255 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
256
Erik Klinea488c232016-04-15 15:49:42 +0900257 private final Stopwatch mEvaluationTimer = new Stopwatch();
258
Hugo Benichid953bf82016-09-27 09:22:35 +0900259 // This variable is set before transitioning to the mCaptivePortalState.
260 private CaptivePortalProbeResult mLastPortalProbeResult = CaptivePortalProbeResult.FAILED;
261
Paul Jensen2c311d62014-11-17 12:34:51 -0500262 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
263 NetworkRequest defaultRequest) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900264 this(context, handler, networkAgentInfo, defaultRequest, new IpConnectivityLog());
265 }
266
267 @VisibleForTesting
268 protected NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
269 NetworkRequest defaultRequest, IpConnectivityLog logger) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400270 // Add suffix indicating which NetworkMonitor we're talking about.
271 super(TAG + networkAgentInfo.name());
272
273 mContext = context;
Hugo Benichif9fdf872016-07-28 17:53:06 +0900274 mMetricsLog = logger;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400275 mConnectivityServiceHandler = handler;
276 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900277 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400278 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
279 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400280 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500281 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400282
283 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400284 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400285 addState(mMaybeNotifyState, mDefaultState);
286 addState(mEvaluatingState, mMaybeNotifyState);
287 addState(mCaptivePortalState, mMaybeNotifyState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700288 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400289
Paul Jensen869868be2014-05-15 10:33:05 -0400290 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
Calvin On4bc78eb2016-10-11 15:10:46 -0700291 Settings.Global.CAPTIVE_PORTAL_MODE, Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT)
292 != Settings.Global.CAPTIVE_PORTAL_MODE_IGNORE;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900293 mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
294 Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400295
296 start();
297 }
298
Paul Jensen532b61432014-11-10 09:50:02 -0500299 @Override
300 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400301 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500302 }
303
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700304 private void validationLog(String s) {
305 if (DBG) log(s);
306 validationLogs.log(s);
307 }
308
309 public ReadOnlyLocalLog getValidationLogs() {
310 return validationLogs.readOnlyLocalLog();
311 }
312
Hugo Benichidd229822016-11-15 23:23:24 +0900313 private ValidationStage validationStage() {
314 return 0 == mValidations ? ValidationStage.FIRST_VALIDATION : ValidationStage.REVALIDATION;
315 }
316
Paul Jensen71b645f2014-10-13 14:13:07 -0400317 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
318 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400319 private class DefaultState extends State {
320 @Override
321 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400322 switch (message.what) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400323 case CMD_NETWORK_CONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900324 logNetworkEvent(NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400325 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400326 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400327 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicfddd682016-05-31 16:28:06 +0900328 logNetworkEvent(NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500329 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
330 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
331 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400332 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700333 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400334 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400335 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400336 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400337 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400338 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400339 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400340 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400341 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400342 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900343
344 // If the user has seen and acted on a captive portal notification, and the
345 // captive portal app is now closed, disable HTTPS probes. This avoids the
346 // following pathological situation:
347 //
348 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
349 // 2. User opens the app and logs into the captive portal.
350 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
351 // perhaps due to the network blocking HTTPS?
352 //
353 // In this case, we'll fail to validate the network even after the app is
354 // dismissed. There is now no way to use this network, because the app is now
355 // gone, so the user cannot select "Use this network as is".
356 mUseHttps = false;
357
Paul Jensen71b645f2014-10-13 14:13:07 -0400358 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400359 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400360 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500361 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400362 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400363 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500364 // TODO: Distinguish this from a network that actually validates.
365 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400366 transitionTo(mValidatedState);
367 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400368 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400369 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400370 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400371 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400372 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900373 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400374 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400375 mUidResponsibleForReeval = 0;
376 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400377 break;
378 }
379 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400380 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400381 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400382 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400383 }
384 }
385
Paul Jensen71b645f2014-10-13 14:13:07 -0400386 // Being in the ValidatedState State indicates a Network is:
387 // - Successfully validated, or
388 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400389 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400390 private class ValidatedState extends State {
391 @Override
392 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900393 maybeLogEvaluationResult(
394 networkEventType(validationStage(), EvaluationResult.VALIDATED));
Paul Jensenad50a1f2014-09-05 12:06:44 -0400395 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400396 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Hugo Benichidd229822016-11-15 23:23:24 +0900397 mValidations++;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400398 }
399
400 @Override
401 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400402 switch (message.what) {
403 case CMD_NETWORK_CONNECTED:
404 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400405 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400406 default:
407 return NOT_HANDLED;
408 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400409 }
410 }
411
Paul Jensen71b645f2014-10-13 14:13:07 -0400412 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
413 // is required. This State takes care to clear the notification upon exit from the State.
414 private class MaybeNotifyState extends State {
415 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500416 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500417 switch (message.what) {
418 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
419 final Intent intent = new Intent(
420 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
421 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400422 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
423 new CaptivePortal(new ICaptivePortal.Stub() {
424 @Override
425 public void appResponse(int response) {
426 if (response == APP_RETURN_WANTED_AS_IS) {
427 mContext.enforceCallingPermission(
428 android.Manifest.permission.CONNECTIVITY_INTERNAL,
429 "CaptivePortal");
430 }
431 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
432 }
433 }));
Hugo Benichid953bf82016-09-27 09:22:35 +0900434 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_URL,
435 mLastPortalProbeResult.detectUrl);
Hugo Benichicdf3ba42016-12-14 08:23:40 +0900436 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_USER_AGENT,
437 getCaptivePortalUserAgent(mContext));
Paul Jensen25a217c2015-02-27 22:55:47 -0500438 intent.setFlags(
439 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
440 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
441 return HANDLED;
442 default:
443 return NOT_HANDLED;
444 }
445 }
446
447 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400448 public void exit() {
449 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
450 mNetworkAgentInfo.network.netId, null);
451 mConnectivityServiceHandler.sendMessage(message);
452 }
453 }
454
Paul Jensen232437312016-04-06 09:51:26 -0400455 /**
456 * Result of calling isCaptivePortal().
457 * @hide
458 */
459 @VisibleForTesting
460 public static final class CaptivePortalProbeResult {
Hugo Benichid953bf82016-09-27 09:22:35 +0900461 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900462
Hugo Benichid953bf82016-09-27 09:22:35 +0900463 private final int mHttpResponseCode; // HTTP response code returned from Internet probe.
464 final String redirectUrl; // Redirect destination returned from Internet probe.
465 final String detectUrl; // URL where a 204 response code indicates
466 // captive portal has been appeased.
Paul Jensen232437312016-04-06 09:51:26 -0400467
Hugo Benichid953bf82016-09-27 09:22:35 +0900468 public CaptivePortalProbeResult(
469 int httpResponseCode, String redirectUrl, String detectUrl) {
Paul Jensen232437312016-04-06 09:51:26 -0400470 mHttpResponseCode = httpResponseCode;
Hugo Benichid953bf82016-09-27 09:22:35 +0900471 this.redirectUrl = redirectUrl;
472 this.detectUrl = detectUrl;
473 }
474
475 public CaptivePortalProbeResult(int httpResponseCode) {
476 this(httpResponseCode, null, null);
Paul Jensen232437312016-04-06 09:51:26 -0400477 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900478
479 boolean isSuccessful() { return mHttpResponseCode == 204; }
480 boolean isPortal() {
481 return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
482 }
Paul Jensen232437312016-04-06 09:51:26 -0400483 }
484
Paul Jensen71b645f2014-10-13 14:13:07 -0400485 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400486 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400487 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400488 private int mReevaluateDelayMs;
489 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400490
Paul Jensenca8f16a2014-05-09 12:47:55 -0400491 @Override
492 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900493 // If we have already started to track time spent in EvaluatingState
494 // don't reset the timer due simply to, say, commands or events that
495 // cause us to exit and re-enter EvaluatingState.
496 if (!mEvaluationTimer.isStarted()) {
497 mEvaluationTimer.start();
498 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400499 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400500 if (mUidResponsibleForReeval != INVALID_UID) {
501 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
502 mUidResponsibleForReeval = INVALID_UID;
503 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400504 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
505 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400506 }
507
508 @Override
509 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400510 switch (message.what) {
511 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400512 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400513 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500514 // Don't bother validating networks that don't satisify the default request.
515 // This includes:
516 // - VPNs which can be considered explicitly desired by the user and the
517 // user's desire trumps whether the network validates.
518 // - Networks that don't provide internet access. It's unclear how to
519 // validate such networks.
520 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
521 // such networks and the user didn't express interest in connecting to
522 // such networks (an app did) so the user may be unhappily surprised when
523 // asked to sign-in to a network they didn't want to connect to in the
524 // first place. Validation could be done to adjust the network scores
525 // however these networks are app-requested and may not be intended for
526 // general usage, in which case general validation may not be an accurate
527 // measure of the network's quality. Only the app knows how to evaluate
528 // the network so don't bother validating here. Furthermore sending HTTP
529 // packets over the network may be undesirable, for example an extremely
530 // expensive metered network, or unwanted leaking of the User Agent string.
531 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
532 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900533 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400534 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400535 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400536 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400537 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900538 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
539 // server's IP addresses could hit the DNS timeout, and attempting connections
540 // to each of the server's several IP addresses (currently one IPv4 and one
541 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
542 // will be unresponsive. isCaptivePortal() could be executed on another Thread
543 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400544 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900545 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400546 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900547 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400548 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Hugo Benichid953bf82016-09-27 09:22:35 +0900549 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.redirectUrl));
550 mLastPortalProbeResult = probeResult;
Paul Jensen71b645f2014-10-13 14:13:07 -0400551 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400552 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400553 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400554 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicfddd682016-05-31 16:28:06 +0900555 logNetworkEvent(NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400556 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900557 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
Hugo Benichid953bf82016-09-27 09:22:35 +0900558 probeResult.redirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400559 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400560 // Don't continue to blame UID forever.
561 TrafficStats.clearThreadStatsUid();
562 }
563 mReevaluateDelayMs *= 2;
564 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
565 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
566 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400567 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400568 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400569 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400570 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
571 // ignore any re-evaluation requests. After, restart the
572 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900573 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400574 default:
575 return NOT_HANDLED;
576 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400577 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400578
579 @Override
580 public void exit() {
581 TrafficStats.clearThreadStatsUid();
582 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400583 }
584
Paul Jensendcbe8352014-09-16 16:28:34 -0400585 // BroadcastReceiver that waits for a particular Intent and then posts a message.
586 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400587 private final int mToken;
588 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400589 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400590 CustomIntentReceiver(String action, int token, int what) {
591 mToken = token;
592 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400593 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
594 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400595 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400596 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500597 final Intent intent = new Intent(mAction);
598 intent.setPackage(mContext.getPackageName());
599 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400600 }
601 @Override
602 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400603 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400604 }
605 }
Paul Jensen869868be2014-05-15 10:33:05 -0400606
Paul Jensen71b645f2014-10-13 14:13:07 -0400607 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
608 // has been shown a notification to sign-in.
609 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500610 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
611 "android.net.netmon.launchCaptivePortalApp";
612
Paul Jensen869868be2014-05-15 10:33:05 -0400613 @Override
614 public void enter() {
Hugo Benichidd229822016-11-15 23:23:24 +0900615 maybeLogEvaluationResult(
616 networkEventType(validationStage(), EvaluationResult.CAPTIVE_PORTAL));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400617 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400618 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500619 // Create a CustomIntentReceiver that sends us a
620 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
621 // touches the notification.
622 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400623 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500624 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
625 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
626 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400627 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500628 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400629 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
630 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500631 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400632 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400633 // Retest for captive portal occasionally.
634 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
635 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Hugo Benichidd229822016-11-15 23:23:24 +0900636 mValidations++;
Paul Jensen869868be2014-05-15 10:33:05 -0400637 }
638
639 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400640 public void exit() {
fionaxu1bf6ec22016-05-23 16:33:16 -0700641 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400642 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400643 }
644
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900645 private static String getCaptivePortalServerHttpsUrl(Context context) {
646 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTPS_URL, DEFAULT_HTTPS_URL);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900647 }
648
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900649 public static String getCaptivePortalServerHttpUrl(Context context) {
650 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_HTTP_URL, DEFAULT_HTTP_URL);
651 }
652
653 private static String getCaptivePortalFallbackUrl(Context context) {
654 return getSetting(context,
655 Settings.Global.CAPTIVE_PORTAL_FALLBACK_URL, DEFAULT_FALLBACK_URL);
656 }
657
658 private static String getCaptivePortalUserAgent(Context context) {
659 return getSetting(context, Settings.Global.CAPTIVE_PORTAL_USER_AGENT, DEFAULT_USER_AGENT);
660 }
661
662 private static String getSetting(Context context, String symbol, String defaultValue) {
663 final String value = Settings.Global.getString(context.getContentResolver(), symbol);
664 return value != null ? value : defaultValue;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900665 }
666
667 @VisibleForTesting
668 protected CaptivePortalProbeResult isCaptivePortal() {
Calvin On4bc78eb2016-10-11 15:10:46 -0700669 if (!mIsCaptivePortalCheckEnabled) {
670 validationLog("Validation disabled.");
671 return new CaptivePortalProbeResult(204);
672 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900673
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900674 URL pacUrl = null, httpsUrl = null, httpUrl = null, fallbackUrl = null;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900675
676 // On networks with a PAC instead of fetching a URL that should result in a 204
677 // response, we instead simply fetch the PAC script. This is done for a few reasons:
678 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
679 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
680 // Network.openConnection() will ignore network-specific PACs and instead fetch
681 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
682 // NO_PROXY is the fetch of the PAC itself.
683 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
684 // happen before the fetch can commence, namely:
685 // a) the PAC script be fetched
686 // b) a PAC script resolver service be fired up and resolve the captive portal
687 // server.
688 // Network validation could be delayed until these prerequisities are satisifed or
689 // could simply be left to race them. Neither is an optimal solution.
690 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
691 // fact block fetching of the generate_204 URL which would lead to false negative
692 // results for network validation.
693 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
694 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900695 pacUrl = makeURL(proxyInfo.getPacFileUrl().toString());
696 if (pacUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900697 return CaptivePortalProbeResult.FAILED;
698 }
699 }
700
701 if (pacUrl == null) {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900702 httpsUrl = makeURL(getCaptivePortalServerHttpsUrl(mContext));
703 httpUrl = makeURL(getCaptivePortalServerHttpUrl(mContext));
704 fallbackUrl = makeURL(getCaptivePortalFallbackUrl(mContext));
705 if (httpUrl == null || httpsUrl == null) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900706 return CaptivePortalProbeResult.FAILED;
707 }
708 }
709
710 long startTime = SystemClock.elapsedRealtime();
711
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900712 final CaptivePortalProbeResult result;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900713 if (pacUrl != null) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900714 result = sendDnsAndHttpProbes(null, pacUrl, ValidationProbeEvent.PROBE_PAC);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900715 } else if (mUseHttps) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900716 result = sendParallelHttpProbes(proxyInfo, httpsUrl, httpUrl, fallbackUrl);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900717 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900718 result = sendDnsAndHttpProbes(proxyInfo, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900719 }
720
721 long endTime = SystemClock.elapsedRealtime();
722
723 sendNetworkConditionsBroadcast(true /* response received */,
724 result.isPortal() /* isCaptivePortal */,
725 startTime, endTime);
726
727 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800728 }
729
Paul Jensenca8f16a2014-05-09 12:47:55 -0400730 /**
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900731 * Do a DNS resolution and URL fetch on a known web server to see if we get the data we expect.
732 * @return a CaptivePortalProbeResult inferred from the HTTP response.
733 */
734 private CaptivePortalProbeResult sendDnsAndHttpProbes(ProxyInfo proxy, URL url, int probeType) {
735 // Pre-resolve the captive portal server host so we can log it.
736 // Only do this if HttpURLConnection is about to, to avoid any potentially
737 // unnecessary resolution.
738 final String host = (proxy != null) ? proxy.getHost() : url.getHost();
739 sendDnsProbe(host);
740 return sendHttpProbe(url, probeType);
741 }
742
743 /** Do a DNS resolution of the given server. */
744 private void sendDnsProbe(String host) {
745 if (TextUtils.isEmpty(host)) {
746 return;
747 }
748
749 final String name = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
750 final Stopwatch watch = new Stopwatch().start();
751 int result;
752 String connectInfo;
753 try {
754 InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(host);
755 result = ValidationProbeEvent.DNS_SUCCESS;
756 StringBuffer buffer = new StringBuffer(host).append("=");
757 for (InetAddress address : addresses) {
758 buffer.append(address.getHostAddress());
759 if (address != addresses[addresses.length-1]) buffer.append(",");
760 }
761 connectInfo = buffer.toString();
762 } catch (UnknownHostException e) {
763 result = ValidationProbeEvent.DNS_FAILURE;
764 connectInfo = host;
765 }
766 final long latency = watch.stop();
767 String resultString = (ValidationProbeEvent.DNS_SUCCESS == result) ? "OK" : "FAIL";
768 validationLog(String.format("%s %s %dms, %s", name, resultString, latency, connectInfo));
769 logValidationProbe(latency, ValidationProbeEvent.PROBE_DNS, result);
770 }
771
772 /**
773 * Do a URL fetch on a known web server to see if we get the data we expect.
774 * @return a CaptivePortalProbeResult inferred from the HTTP response.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400775 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400776 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900777 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400778 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400779 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400780 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900781 final Stopwatch probeTimer = new Stopwatch().start();
Jeff Sharkey619a5112017-01-19 11:55:54 -0700782 final int oldTag = TrafficStats.getAndSetThreadStatsTag(TrafficStats.TAG_SYSTEM_PROBE);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400783 try {
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700784 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900785 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400786 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
787 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
788 urlConnection.setUseCaches(false);
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900789 final String userAgent = getCaptivePortalUserAgent(mContext);
790 if (userAgent != null) {
791 urlConnection.setRequestProperty("User-Agent", userAgent);
792 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400793
794 // Time how long it takes to get a response to our request
795 long requestTimestamp = SystemClock.elapsedRealtime();
796
Pierre Imaibe12d762016-03-10 17:00:50 +0900797 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400798 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400799
800 // Time how long it takes to get a response to our request
801 long responseTimestamp = SystemClock.elapsedRealtime();
802
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900803 validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url +
804 " time=" + (responseTimestamp - requestTimestamp) + "ms" +
805 " ret=" + httpResponseCode +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700806 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400807 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
808 // portal. The only example of this seen so far was a captive portal. For
809 // the time being go with prior behavior of assuming it's not a captive
810 // portal. If it is considered a captive portal, a different sign-in URL
811 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
812 // proxy server.
Hugo Benichicb4aa4d2017-01-11 16:23:26 +0900813 if (httpResponseCode == 200) {
814 if (probeType == ValidationProbeEvent.PROBE_PAC) {
815 validationLog("PAC fetch 200 response interpreted as 204 response.");
816 httpResponseCode = 204;
817 } else if (urlConnection.getContentLengthLong() == 0) {
818 // Consider 200 response with "Content-length=0" to not be a captive portal.
819 // There's no point in considering this a captive portal as the user cannot
820 // sign-in to an empty page. Probably the result of a broken transparent proxy.
821 // See http://b/9972012.
822 validationLog(
823 "200 response with Content-length=0 interpreted as 204 response.");
824 httpResponseCode = 204;
825 } else if (urlConnection.getContentLengthLong() == -1) {
826 // When no Content-length (default value == -1), attempt to read a byte from the
827 // response. Do not use available() as it is unreliable. See http://b/33498325.
828 if (urlConnection.getInputStream().read() == -1) {
829 validationLog("Empty 200 response interpreted as 204 response.");
830 httpResponseCode = 204;
831 }
832 }
Paul Jensen8fe17422015-02-02 11:03:03 -0500833 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400834 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700835 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400836 if (httpResponseCode == 599) {
837 // TODO: Ping gateway and DNS server and log results.
838 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400839 } finally {
840 if (urlConnection != null) {
841 urlConnection.disconnect();
842 }
Jeff Sharkey619a5112017-01-19 11:55:54 -0700843 TrafficStats.setThreadStatsTag(oldTag);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400844 }
Hugo Benichicfddd682016-05-31 16:28:06 +0900845 logValidationProbe(probeTimer.stop(), probeType, httpResponseCode);
Hugo Benichid953bf82016-09-27 09:22:35 +0900846 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl, url.toString());
Paul Jensenca8f16a2014-05-09 12:47:55 -0400847 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400848
Hugo Benichid953bf82016-09-27 09:22:35 +0900849 private CaptivePortalProbeResult sendParallelHttpProbes(
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900850 ProxyInfo proxy, URL httpsUrl, URL httpUrl, URL fallbackUrl) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900851 // Number of probes to wait for. If a probe completes with a conclusive answer
852 // it shortcuts the latch immediately by forcing the count to 0.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900853 final CountDownLatch latch = new CountDownLatch(2);
854
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900855 final class ProbeThread extends Thread {
856 private final boolean mIsHttps;
Hugo Benichid953bf82016-09-27 09:22:35 +0900857 private volatile CaptivePortalProbeResult mResult = CaptivePortalProbeResult.FAILED;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900858
859 public ProbeThread(boolean isHttps) {
860 mIsHttps = isHttps;
861 }
862
Hugo Benichid953bf82016-09-27 09:22:35 +0900863 public CaptivePortalProbeResult result() {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900864 return mResult;
865 }
866
867 @Override
868 public void run() {
869 if (mIsHttps) {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900870 mResult =
871 sendDnsAndHttpProbes(proxy, httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900872 } else {
Hugo Benichieb5e9aa2016-11-16 18:18:08 +0900873 mResult = sendDnsAndHttpProbes(proxy, httpUrl, ValidationProbeEvent.PROBE_HTTP);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900874 }
875 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900876 // Stop waiting immediately if https succeeds or if http finds a portal.
877 while (latch.getCount() > 0) {
878 latch.countDown();
879 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900880 }
Hugo Benichid953bf82016-09-27 09:22:35 +0900881 // Signal this probe has completed.
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900882 latch.countDown();
883 }
884 }
885
Hugo Benichid953bf82016-09-27 09:22:35 +0900886 final ProbeThread httpsProbe = new ProbeThread(true);
887 final ProbeThread httpProbe = new ProbeThread(false);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900888
889 try {
Hugo Benichid953bf82016-09-27 09:22:35 +0900890 httpsProbe.start();
891 httpProbe.start();
892 latch.await(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900893 } catch (InterruptedException e) {
Hugo Benichid953bf82016-09-27 09:22:35 +0900894 validationLog("Error: probes wait interrupted!");
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900895 return CaptivePortalProbeResult.FAILED;
896 }
897
Hugo Benichid953bf82016-09-27 09:22:35 +0900898 final CaptivePortalProbeResult httpsResult = httpsProbe.result();
899 final CaptivePortalProbeResult httpResult = httpProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900900
Hugo Benichid953bf82016-09-27 09:22:35 +0900901 // Look for a conclusive probe result first.
902 if (httpResult.isPortal()) {
903 return httpResult;
904 }
905 // httpsResult.isPortal() is not expected, but check it nonetheless.
906 if (httpsResult.isPortal() || httpsResult.isSuccessful()) {
907 return httpsResult;
908 }
909 // If a fallback url is specified, use a fallback probe to try again portal detection.
910 if (fallbackUrl != null) {
911 CaptivePortalProbeResult result =
912 sendHttpProbe(fallbackUrl, ValidationProbeEvent.PROBE_FALLBACK);
913 if (result.isPortal()) {
914 return result;
915 }
916 }
917 // Otherwise wait until https probe completes and use its result.
918 try {
919 httpsProbe.join();
920 } catch (InterruptedException e) {
921 validationLog("Error: https probe wait interrupted!");
922 return CaptivePortalProbeResult.FAILED;
923 }
924 return httpsProbe.result();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900925 }
926
Hugo Benichi92eb22fd2016-09-27 13:01:41 +0900927 private URL makeURL(String url) {
928 if (url != null) {
929 try {
930 return new URL(url);
931 } catch (MalformedURLException e) {
932 validationLog("Bad URL: " + url);
933 }
934 }
935 return null;
936 }
937
Paul Jensen306f1a42014-08-04 10:59:01 -0400938 /**
939 * @param responseReceived - whether or not we received a valid HTTP response to our request.
940 * If false, isCaptivePortal and responseTimestampMs are ignored
941 * TODO: This should be moved to the transports. The latency could be passed to the transports
942 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
943 * perhaps this could just be added to the WiFi transport only.
944 */
945 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
946 long requestTimestampMs, long responseTimestampMs) {
947 if (Settings.Global.getInt(mContext.getContentResolver(),
948 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400949 return;
950 }
951
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700952 if (systemReady == false) return;
953
Paul Jensen306f1a42014-08-04 10:59:01 -0400954 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
955 switch (mNetworkAgentInfo.networkInfo.getType()) {
956 case ConnectivityManager.TYPE_WIFI:
957 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
958 if (currentWifiInfo != null) {
959 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
960 // surrounded by double quotation marks (thus violating the Javadoc), but this
961 // was changed to match the Javadoc in API 17. Since clients may have started
962 // sanitizing the output of this method since API 17 was released, we should
963 // not change it here as it would become impossible to tell whether the SSID is
964 // simply being surrounded by quotes due to the API, or whether those quotes
965 // are actually part of the SSID.
966 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
967 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
968 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900969 if (VDBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
Paul Jensen306f1a42014-08-04 10:59:01 -0400970 return;
971 }
972 break;
973 case ConnectivityManager.TYPE_MOBILE:
974 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
975 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
976 if (info == null) return;
977 int numRegisteredCellInfo = 0;
978 for (CellInfo cellInfo : info) {
979 if (cellInfo.isRegistered()) {
980 numRegisteredCellInfo++;
981 if (numRegisteredCellInfo > 1) {
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900982 if (VDBG) logw("more than one registered CellInfo." +
983 " Can't tell which is active. Bailing.");
Paul Jensen306f1a42014-08-04 10:59:01 -0400984 return;
985 }
986 if (cellInfo instanceof CellInfoCdma) {
987 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
988 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
989 } else if (cellInfo instanceof CellInfoGsm) {
990 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
991 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
992 } else if (cellInfo instanceof CellInfoLte) {
993 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
994 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
995 } else if (cellInfo instanceof CellInfoWcdma) {
996 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
997 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
998 } else {
Hugo Benichia4f17bc2016-11-21 13:50:05 +0900999 if (VDBG) logw("Registered cellinfo is unrecognized");
Paul Jensen306f1a42014-08-04 10:59:01 -04001000 return;
1001 }
1002 }
1003 }
1004 break;
1005 default:
1006 return;
1007 }
1008 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
1009 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
1010 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
1011
1012 if (responseReceived) {
1013 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
1014 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
1015 }
Paul Jensen55298582014-08-20 11:01:41 -04001016 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
1017 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -04001018 }
Paul Jensend7b6ca92015-05-13 14:05:12 -04001019
Hugo Benichicfddd682016-05-31 16:28:06 +09001020 private void logNetworkEvent(int evtype) {
1021 mMetricsLog.log(new NetworkEvent(mNetId, evtype));
1022 }
1023
Hugo Benichidd229822016-11-15 23:23:24 +09001024 private int networkEventType(ValidationStage s, EvaluationResult r) {
1025 if (s.isFirstValidation) {
1026 if (r.isValidated) {
1027 return NetworkEvent.NETWORK_FIRST_VALIDATION_SUCCESS;
1028 } else {
1029 return NetworkEvent.NETWORK_FIRST_VALIDATION_PORTAL_FOUND;
1030 }
1031 } else {
1032 if (r.isValidated) {
1033 return NetworkEvent.NETWORK_REVALIDATION_SUCCESS;
1034 } else {
1035 return NetworkEvent.NETWORK_REVALIDATION_PORTAL_FOUND;
1036 }
1037 }
1038 }
1039
Hugo Benichicfddd682016-05-31 16:28:06 +09001040 private void maybeLogEvaluationResult(int evtype) {
1041 if (mEvaluationTimer.isRunning()) {
1042 mMetricsLog.log(new NetworkEvent(mNetId, evtype, mEvaluationTimer.stop()));
1043 mEvaluationTimer.reset();
1044 }
1045 }
1046
1047 private void logValidationProbe(long durationMs, int probeType, int probeResult) {
Hugo Benichidd229822016-11-15 23:23:24 +09001048 probeType =
1049 ValidationProbeEvent.makeProbeType(probeType, validationStage().isFirstValidation);
Hugo Benichicfddd682016-05-31 16:28:06 +09001050 mMetricsLog.log(new ValidationProbeEvent(mNetId, durationMs, probeType, probeResult));
1051 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001052}