blob: f4e14246cd8a2d31725ce6ae9e661a9231b70e79 [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;
26import android.content.ComponentName;
Paul Jensenca8f16a2014-05-09 12:47:55 -040027import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040028import android.content.Intent;
29import android.content.IntentFilter;
Paul Jensen49e3edf2015-05-22 10:50:39 -040030import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040031import android.net.ConnectivityManager;
Paul Jensen49e3edf2015-05-22 10:50:39 -040032import android.net.ICaptivePortal;
Paul Jensen2c311d62014-11-17 12:34:51 -050033import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050034import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040035import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040036import android.net.Uri;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090037import android.net.metrics.ValidationProbeEvent;
38import android.net.metrics.NetworkEvent;
Paul Jensen306f1a42014-08-04 10:59:01 -040039import android.net.wifi.WifiInfo;
40import android.net.wifi.WifiManager;
Erik Klinea488c232016-04-15 15:49:42 +090041import android.net.util.Stopwatch;
Paul Jensenca8f16a2014-05-09 12:47:55 -040042import android.os.Handler;
43import android.os.Message;
Paul Jensend7b6ca92015-05-13 14:05:12 -040044import android.os.Process;
Paul Jensen306f1a42014-08-04 10:59:01 -040045import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040046import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040047import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040048import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040049import android.telephony.CellIdentityCdma;
50import android.telephony.CellIdentityGsm;
51import android.telephony.CellIdentityLte;
52import android.telephony.CellIdentityWcdma;
53import android.telephony.CellInfo;
54import android.telephony.CellInfoCdma;
55import android.telephony.CellInfoGsm;
56import android.telephony.CellInfoLte;
57import android.telephony.CellInfoWcdma;
58import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040059import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070060import android.util.LocalLog;
61import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050062import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040063
Paul Jensend7b6ca92015-05-13 14:05:12 -040064import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040065import com.android.internal.util.Protocol;
66import com.android.internal.util.State;
67import com.android.internal.util.StateMachine;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +090068import com.android.internal.util.WakeupMessage;
Paul Jensenca8f16a2014-05-09 12:47:55 -040069import com.android.server.connectivity.NetworkAgentInfo;
70
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040072import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040073import java.net.InetAddress;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090074import java.net.MalformedURLException;
75import java.net.UnknownHostException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040076import java.net.URL;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +090077import java.util.concurrent.CountDownLatch;
78import java.util.concurrent.atomic.AtomicReference;
Paul Jensen306f1a42014-08-04 10:59:01 -040079import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040080import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040081
82/**
83 * {@hide}
84 */
85public class NetworkMonitor extends StateMachine {
Joe Onorato12acbd72016-02-01 17:49:31 -080086 private static final boolean DBG = false;
Erik Klinea488c232016-04-15 15:49:42 +090087 private static final String TAG = NetworkMonitor.class.getSimpleName();
Erik Klinee7d01792015-07-20 23:37:15 +090088 private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040089 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040090 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
91 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
92 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
93 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
94 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
95 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
96 public static final String EXTRA_CELL_ID = "extra_cellid";
97 public static final String EXTRA_SSID = "extra_ssid";
98 public static final String EXTRA_BSSID = "extra_bssid";
99 /** real time since boot */
100 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
101 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
102
103 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
104 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400105
Paul Jensenad50a1f2014-09-05 12:06:44 -0400106 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
107 // The network should be used as a default internet connection. It was found to be:
108 // 1. a functioning network providing internet access, or
109 // 2. a captive portal and the user decided to use it as is.
110 public static final int NETWORK_TEST_RESULT_VALID = 0;
111 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
112 // The network should not be used as a default internet connection. It was found to be:
113 // 1. a captive portal and the user is prompted to sign-in, or
114 // 2. a captive portal and the user did not want to use it, or
115 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
116 public static final int NETWORK_TEST_RESULT_INVALID = 1;
117
Paul Jensenca8f16a2014-05-09 12:47:55 -0400118 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
119
120 /**
121 * Inform NetworkMonitor that their network is connected.
122 * Initiates Network Validation.
123 */
124 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
125
126 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400127 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400128 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400129 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400130 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400131 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400132 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400133
134 /**
135 * Inform NetworkMonitor to linger a network. The Monitor should
136 * start a timer and/or start watching for zero live connections while
137 * moving towards LINGER_COMPLETE. After the Linger period expires
138 * (or other events mark the end of the linger state) the LINGER_COMPLETE
139 * event should be sent and the network will be shut down. If a
140 * CMD_NETWORK_CONNECTED happens before the LINGER completes
141 * it indicates further desire to keep the network alive and so
142 * the LINGER is aborted.
143 */
144 public static final int CMD_NETWORK_LINGER = BASE + 3;
145
146 /**
147 * Message to self indicating linger delay has expired.
148 * arg1 = Token to ignore old messages.
149 */
150 private static final int CMD_LINGER_EXPIRED = BASE + 4;
151
152 /**
153 * Inform ConnectivityService that the network LINGER period has
154 * expired.
155 * obj = NetworkAgentInfo
156 */
157 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
158
159 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400160 * Message to self indicating it's time to evaluate a network's connectivity.
161 * arg1 = Token to ignore old messages.
162 */
Paul Jensen869868be2014-05-15 10:33:05 -0400163 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400164
165 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400166 * Inform NetworkMonitor that the network has disconnected.
167 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400168 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400169
170 /**
171 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400172 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400173 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400174 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400175
176 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400177 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400178 * arg1 = one of: APP_RETURN_DISMISSED,
179 * APP_RETURN_UNWANTED,
180 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500181 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400182 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400183 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400184
185 /**
186 * Request ConnectivityService display provisioning notification.
187 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400188 * arg2 = NetID.
189 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400190 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400191 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400192
193 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500194 * Message to self indicating sign-in app should be launched.
195 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
196 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400197 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500198 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400199
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400200 /**
201 * Retest network to see if captive portal is still in place.
202 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
203 * 0 indicates self-initiated, so nobody to blame.
204 */
205 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
206
Paul Jensenca8f16a2014-05-09 12:47:55 -0400207 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400208 // Default to 30s linger time-out. Modifyable only for testing.
209 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400210 private final int mLingerDelayMs;
211 private int mLingerToken = 0;
212
Paul Jensend0491e9a2015-05-05 14:52:22 -0400213 // Start mReevaluateDelayMs at this value and double.
214 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
215 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
216 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
217 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400218 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400219 private static final int INVALID_UID = -1;
220 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400221 // Stop blaming UID that requested re-evaluation after this many attempts.
222 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400223 // Delay between reevaluations once a captive portal has been found.
224 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400225
226 private final Context mContext;
227 private final Handler mConnectivityServiceHandler;
228 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900229 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400230 private final TelephonyManager mTelephonyManager;
231 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400232 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500233 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400234
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900235 private boolean mIsCaptivePortalCheckEnabled;
236 private boolean mUseHttps;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400237
Paul Jensenad50a1f2014-09-05 12:06:44 -0400238 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
239 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400240 // Avoids surfacing "Sign in to network" notification.
241 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400242
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700243 public boolean systemReady = false;
244
Paul Jensen71b645f2014-10-13 14:13:07 -0400245 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400246 private final State mValidatedState = new ValidatedState();
247 private final State mMaybeNotifyState = new MaybeNotifyState();
248 private final State mEvaluatingState = new EvaluatingState();
249 private final State mCaptivePortalState = new CaptivePortalState();
250 private final State mLingeringState = new LingeringState();
251
Paul Jensen25a217c2015-02-27 22:55:47 -0500252 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400253
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700254 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
255
Erik Klinea488c232016-04-15 15:49:42 +0900256 private final Stopwatch mEvaluationTimer = new Stopwatch();
257
Paul Jensen2c311d62014-11-17 12:34:51 -0500258 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
259 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400260 // Add suffix indicating which NetworkMonitor we're talking about.
261 super(TAG + networkAgentInfo.name());
262
263 mContext = context;
264 mConnectivityServiceHandler = handler;
265 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900266 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400267 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
268 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400269 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500270 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400271
272 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400273 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400274 addState(mMaybeNotifyState, mDefaultState);
275 addState(mEvaluatingState, mMaybeNotifyState);
276 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400277 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700278 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400279
Paul Jensenca8f16a2014-05-09 12:47:55 -0400280 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400281
Paul Jensen869868be2014-05-15 10:33:05 -0400282 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
283 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900284 mUseHttps = Settings.Global.getInt(mContext.getContentResolver(),
285 Settings.Global.CAPTIVE_PORTAL_USE_HTTPS, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400286
287 start();
288 }
289
Paul Jensen532b61432014-11-10 09:50:02 -0500290 @Override
291 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400292 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500293 }
294
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700295 private void validationLog(String s) {
296 if (DBG) log(s);
297 validationLogs.log(s);
298 }
299
300 public ReadOnlyLocalLog getValidationLogs() {
301 return validationLogs.readOnlyLocalLog();
302 }
303
Paul Jensen71b645f2014-10-13 14:13:07 -0400304 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
305 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400306 private class DefaultState extends State {
307 @Override
308 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400309 switch (message.what) {
310 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400311 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400312 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400313 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400314 case CMD_NETWORK_CONNECTED:
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900315 NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400316 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400317 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400318 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900319 NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500320 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
321 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
322 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400323 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700324 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400325 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400326 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400327 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400328 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400329 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400330 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400331 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400332 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400333 log("CaptivePortal App responded with " + message.arg1);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900334
335 // If the user has seen and acted on a captive portal notification, and the
336 // captive portal app is now closed, disable HTTPS probes. This avoids the
337 // following pathological situation:
338 //
339 // 1. HTTP probe returns a captive portal, HTTPS probe fails or times out.
340 // 2. User opens the app and logs into the captive portal.
341 // 3. HTTP starts working, but HTTPS still doesn't work for some other reason -
342 // perhaps due to the network blocking HTTPS?
343 //
344 // In this case, we'll fail to validate the network even after the app is
345 // dismissed. There is now no way to use this network, because the app is now
346 // gone, so the user cannot select "Use this network as is".
347 mUseHttps = false;
348
Paul Jensen71b645f2014-10-13 14:13:07 -0400349 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400350 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400351 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500352 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400353 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400354 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500355 // TODO: Distinguish this from a network that actually validates.
356 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400357 transitionTo(mValidatedState);
358 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400359 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400360 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400361 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400362 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400363 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900364 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400365 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400366 mUidResponsibleForReeval = 0;
367 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400368 break;
369 }
370 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400371 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400372 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400373 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400374 }
375 }
376
Paul Jensen71b645f2014-10-13 14:13:07 -0400377 // Being in the ValidatedState State indicates a Network is:
378 // - Successfully validated, or
379 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400380 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400381 private class ValidatedState extends State {
382 @Override
383 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900384 if (mEvaluationTimer.isRunning()) {
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900385 NetworkEvent.logValidated(mNetId, mEvaluationTimer.stop());
Erik Klinea488c232016-04-15 15:49:42 +0900386 mEvaluationTimer.reset();
387 }
Paul Jensenad50a1f2014-09-05 12:06:44 -0400388 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400389 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400390 }
391
392 @Override
393 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400394 switch (message.what) {
395 case CMD_NETWORK_CONNECTED:
396 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400397 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400398 default:
399 return NOT_HANDLED;
400 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400401 }
402 }
403
Paul Jensen71b645f2014-10-13 14:13:07 -0400404 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
405 // is required. This State takes care to clear the notification upon exit from the State.
406 private class MaybeNotifyState extends State {
407 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500408 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500409 switch (message.what) {
410 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
411 final Intent intent = new Intent(
412 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
413 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400414 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
415 new CaptivePortal(new ICaptivePortal.Stub() {
416 @Override
417 public void appResponse(int response) {
418 if (response == APP_RETURN_WANTED_AS_IS) {
419 mContext.enforceCallingPermission(
420 android.Manifest.permission.CONNECTIVITY_INTERNAL,
421 "CaptivePortal");
422 }
423 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
424 }
425 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500426 intent.setFlags(
427 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
428 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
429 return HANDLED;
430 default:
431 return NOT_HANDLED;
432 }
433 }
434
435 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400436 public void exit() {
437 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
438 mNetworkAgentInfo.network.netId, null);
439 mConnectivityServiceHandler.sendMessage(message);
440 }
441 }
442
Paul Jensen232437312016-04-06 09:51:26 -0400443 /**
444 * Result of calling isCaptivePortal().
445 * @hide
446 */
447 @VisibleForTesting
448 public static final class CaptivePortalProbeResult {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900449 static final CaptivePortalProbeResult FAILED = new CaptivePortalProbeResult(599, null);
450
Paul Jensen232437312016-04-06 09:51:26 -0400451 final int mHttpResponseCode; // HTTP response code returned from Internet probe.
452 final String mRedirectUrl; // Redirect destination returned from Internet probe.
453
454 public CaptivePortalProbeResult(int httpResponseCode, String redirectUrl) {
455 mHttpResponseCode = httpResponseCode;
456 mRedirectUrl = redirectUrl;
457 }
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900458
459 boolean isSuccessful() { return mHttpResponseCode == 204; }
460 boolean isPortal() {
461 return !isSuccessful() && mHttpResponseCode >= 200 && mHttpResponseCode <= 399;
462 }
Paul Jensen232437312016-04-06 09:51:26 -0400463 }
464
Paul Jensen71b645f2014-10-13 14:13:07 -0400465 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400466 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400467 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400468 private int mReevaluateDelayMs;
469 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400470
Paul Jensenca8f16a2014-05-09 12:47:55 -0400471 @Override
472 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900473 // If we have already started to track time spent in EvaluatingState
474 // don't reset the timer due simply to, say, commands or events that
475 // cause us to exit and re-enter EvaluatingState.
476 if (!mEvaluationTimer.isStarted()) {
477 mEvaluationTimer.start();
478 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400479 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400480 if (mUidResponsibleForReeval != INVALID_UID) {
481 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
482 mUidResponsibleForReeval = INVALID_UID;
483 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400484 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
485 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400486 }
487
488 @Override
489 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400490 switch (message.what) {
491 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400492 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400493 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500494 // Don't bother validating networks that don't satisify the default request.
495 // This includes:
496 // - VPNs which can be considered explicitly desired by the user and the
497 // user's desire trumps whether the network validates.
498 // - Networks that don't provide internet access. It's unclear how to
499 // validate such networks.
500 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
501 // such networks and the user didn't express interest in connecting to
502 // such networks (an app did) so the user may be unhappily surprised when
503 // asked to sign-in to a network they didn't want to connect to in the
504 // first place. Validation could be done to adjust the network scores
505 // however these networks are app-requested and may not be intended for
506 // general usage, in which case general validation may not be an accurate
507 // measure of the network's quality. Only the app knows how to evaluate
508 // the network so don't bother validating here. Furthermore sending HTTP
509 // packets over the network may be undesirable, for example an extremely
510 // expensive metered network, or unwanted leaking of the User Agent string.
511 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
512 mNetworkAgentInfo.networkCapabilities)) {
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900513 validationLog("Network would not satisfy default request, not validating");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400514 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400515 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400516 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400517 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900518 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
519 // server's IP addresses could hit the DNS timeout, and attempting connections
520 // to each of the server's several IP addresses (currently one IPv4 and one
521 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
522 // will be unresponsive. isCaptivePortal() could be executed on another Thread
523 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400524 CaptivePortalProbeResult probeResult = isCaptivePortal();
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900525 if (probeResult.isSuccessful()) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400526 transitionTo(mValidatedState);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900527 } else if (probeResult.isPortal()) {
Paul Jensen232437312016-04-06 09:51:26 -0400528 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Erik Klinea488c232016-04-15 15:49:42 +0900529 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.mRedirectUrl));
Paul Jensen71b645f2014-10-13 14:13:07 -0400530 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400531 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400532 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400533 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900534 NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400535 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900536 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
537 probeResult.mRedirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400538 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400539 // Don't continue to blame UID forever.
540 TrafficStats.clearThreadStatsUid();
541 }
542 mReevaluateDelayMs *= 2;
543 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
544 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
545 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400546 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400547 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400548 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400549 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
550 // ignore any re-evaluation requests. After, restart the
551 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900552 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400553 default:
554 return NOT_HANDLED;
555 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400556 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400557
558 @Override
559 public void exit() {
560 TrafficStats.clearThreadStatsUid();
561 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400562 }
563
Paul Jensendcbe8352014-09-16 16:28:34 -0400564 // BroadcastReceiver that waits for a particular Intent and then posts a message.
565 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400566 private final int mToken;
567 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400568 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400569 CustomIntentReceiver(String action, int token, int what) {
570 mToken = token;
571 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400572 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
573 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400574 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400575 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500576 final Intent intent = new Intent(mAction);
577 intent.setPackage(mContext.getPackageName());
578 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400579 }
580 @Override
581 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400582 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400583 }
584 }
Paul Jensen869868be2014-05-15 10:33:05 -0400585
Paul Jensen71b645f2014-10-13 14:13:07 -0400586 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
587 // has been shown a notification to sign-in.
588 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500589 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
590 "android.net.netmon.launchCaptivePortalApp";
591
Paul Jensen869868be2014-05-15 10:33:05 -0400592 @Override
593 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900594 if (mEvaluationTimer.isRunning()) {
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900595 NetworkEvent.logCaptivePortalFound(mNetId, mEvaluationTimer.stop());
Erik Klinea488c232016-04-15 15:49:42 +0900596 mEvaluationTimer.reset();
597 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400598 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400599 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500600 // Create a CustomIntentReceiver that sends us a
601 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
602 // touches the notification.
603 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400604 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500605 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
606 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
607 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400608 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500609 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400610 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
611 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500612 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400613 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400614 // Retest for captive portal occasionally.
615 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
616 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400617 }
618
619 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400620 public void exit() {
621 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
622 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400623 }
624
Paul Jensen71b645f2014-10-13 14:13:07 -0400625 // Being in the LingeringState State indicates a Network's validated bit is true and it once
626 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
Paul Jensencf4c2c62015-07-01 14:16:32 -0400627 // another Network satisfied the NetworkRequest with a higher score and hence this Network
Paul Jensen71b645f2014-10-13 14:13:07 -0400628 // is "lingered" for a fixed period of time before it is disconnected. This period of time
629 // allows apps to wrap up communication and allows for seamless reactivation if the other
630 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400631 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400632 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400633
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900634 private WakeupMessage mWakeupMessage;
Paul Jensen79a08052014-08-21 12:44:07 -0400635
Paul Jensenca8f16a2014-05-09 12:47:55 -0400636 @Override
637 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900638 mEvaluationTimer.reset();
639 final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetId;
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900640 mWakeupMessage = makeWakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
Paul Jensen79a08052014-08-21 12:44:07 -0400641 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900642 mWakeupMessage.schedule(wakeupTime);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400643 }
644
645 @Override
646 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400647 switch (message.what) {
648 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400649 log("Unlingered");
Paul Jensene0988542015-06-25 15:30:08 -0400650 // If already validated, go straight to validated state.
651 if (mNetworkAgentInfo.lastValidated) {
652 transitionTo(mValidatedState);
653 return HANDLED;
654 }
655 return NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400656 case CMD_LINGER_EXPIRED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400657 mConnectivityServiceHandler.sendMessage(
658 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400659 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400660 case CMD_FORCE_REEVALUATION:
661 // Ignore reevaluation attempts when lingering. A reevaluation could result
662 // in a transition to the validated state which would abort the linger
663 // timeout. Lingering is the result of score assessment; validity is
664 // irrelevant.
665 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400666 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
667 // Ignore user network determination as this could abort linger timeout.
668 // Networks are only lingered once validated because:
669 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
670 // - Once validated, a Network's validated bit is never cleared.
671 // Since networks are only lingered after being validated a user's
672 // determination will not change the death sentence that lingering entails:
673 // - If the user wants to use the network or bypasses the captive portal,
674 // the network's score will not be increased beyond its current value
675 // because it is already validated. Without a score increase there is no
676 // chance of reactivation (i.e. aborting linger timeout).
677 // - If the user does not want the network, lingering will disconnect the
678 // network anyhow.
679 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400680 default:
681 return NOT_HANDLED;
682 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400683 }
Paul Jensen79a08052014-08-21 12:44:07 -0400684
685 @Override
686 public void exit() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900687 mWakeupMessage.cancel();
Paul Jensen79a08052014-08-21 12:44:07 -0400688 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400689 }
690
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900691 private static String getCaptivePortalServerUrl(Context context, boolean isHttps) {
Udam Sainib7c24872016-01-04 12:16:14 -0800692 String server = Settings.Global.getString(context.getContentResolver(),
693 Settings.Global.CAPTIVE_PORTAL_SERVER);
694 if (server == null) server = DEFAULT_SERVER;
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900695 return (isHttps ? "https" : "http") + "://" + server + "/generate_204";
696 }
697
698 public static String getCaptivePortalServerUrl(Context context) {
699 return getCaptivePortalServerUrl(context, false);
700 }
701
702 @VisibleForTesting
703 protected CaptivePortalProbeResult isCaptivePortal() {
704 if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
705
706 URL pacUrl = null, httpUrl = null, httpsUrl = null;
707
708 // On networks with a PAC instead of fetching a URL that should result in a 204
709 // response, we instead simply fetch the PAC script. This is done for a few reasons:
710 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
711 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
712 // Network.openConnection() will ignore network-specific PACs and instead fetch
713 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
714 // NO_PROXY is the fetch of the PAC itself.
715 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
716 // happen before the fetch can commence, namely:
717 // a) the PAC script be fetched
718 // b) a PAC script resolver service be fired up and resolve the captive portal
719 // server.
720 // Network validation could be delayed until these prerequisities are satisifed or
721 // could simply be left to race them. Neither is an optimal solution.
722 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
723 // fact block fetching of the generate_204 URL which would lead to false negative
724 // results for network validation.
725 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
726 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
727 try {
728 pacUrl = new URL(proxyInfo.getPacFileUrl().toString());
729 } catch (MalformedURLException e) {
730 validationLog("Invalid PAC URL: " + proxyInfo.getPacFileUrl().toString());
731 return CaptivePortalProbeResult.FAILED;
732 }
733 }
734
735 if (pacUrl == null) {
736 try {
737 httpUrl = new URL(getCaptivePortalServerUrl(mContext, false));
738 httpsUrl = new URL(getCaptivePortalServerUrl(mContext, true));
739 } catch (MalformedURLException e) {
740 validationLog("Bad validation URL: " + getCaptivePortalServerUrl(mContext, false));
741 return CaptivePortalProbeResult.FAILED;
742 }
743 }
744
745 long startTime = SystemClock.elapsedRealtime();
746
747 // Pre-resolve the captive portal server host so we can log it.
748 // Only do this if HttpURLConnection is about to, to avoid any potentially
749 // unnecessary resolution.
750 String hostToResolve = null;
751 if (pacUrl != null) {
752 hostToResolve = pacUrl.getHost();
753 } else if (proxyInfo != null) {
754 hostToResolve = proxyInfo.getHost();
755 } else {
756 hostToResolve = httpUrl.getHost();
757 }
758
759 if (!TextUtils.isEmpty(hostToResolve)) {
760 String probeName = ValidationProbeEvent.getProbeName(ValidationProbeEvent.PROBE_DNS);
761 final Stopwatch dnsTimer = new Stopwatch().start();
762 try {
763 InetAddress[] addresses = mNetworkAgentInfo.network.getAllByName(hostToResolve);
764 long dnsLatency = dnsTimer.stop();
765 ValidationProbeEvent.logEvent(mNetId, dnsLatency,
766 ValidationProbeEvent.PROBE_DNS, ValidationProbeEvent.DNS_SUCCESS);
767 final StringBuffer connectInfo = new StringBuffer(", " + hostToResolve + "=");
768 for (InetAddress address : addresses) {
769 connectInfo.append(address.getHostAddress());
770 if (address != addresses[addresses.length-1]) connectInfo.append(",");
771 }
772 validationLog(probeName + " OK " + dnsLatency + "ms" + connectInfo);
773 } catch (UnknownHostException e) {
774 long dnsLatency = dnsTimer.stop();
775 ValidationProbeEvent.logEvent(mNetId, dnsLatency,
776 ValidationProbeEvent.PROBE_DNS, ValidationProbeEvent.DNS_FAILURE);
777 validationLog(probeName + " FAIL " + dnsLatency + "ms, " + hostToResolve);
778 }
779 }
780
781 CaptivePortalProbeResult result;
782 if (pacUrl != null) {
783 result = sendHttpProbe(pacUrl, ValidationProbeEvent.PROBE_PAC);
784 } else if (mUseHttps) {
785 result = sendParallelHttpProbes(httpsUrl, httpUrl);
786 } else {
787 result = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
788 }
789
790 long endTime = SystemClock.elapsedRealtime();
791
792 sendNetworkConditionsBroadcast(true /* response received */,
793 result.isPortal() /* isCaptivePortal */,
794 startTime, endTime);
795
796 return result;
Udam Sainib7c24872016-01-04 12:16:14 -0800797 }
798
Paul Jensenca8f16a2014-05-09 12:47:55 -0400799 /**
800 * Do a URL fetch on a known server to see if we get the data we expect.
801 * Returns HTTP response code.
802 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400803 @VisibleForTesting
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900804 protected CaptivePortalProbeResult sendHttpProbe(URL url, int probeType) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400805 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400806 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400807 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900808 final Stopwatch probeTimer = new Stopwatch().start();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400809 try {
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700810 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900811 urlConnection.setInstanceFollowRedirects(probeType == ValidationProbeEvent.PROBE_PAC);
Paul Jensene547ff22014-08-04 09:12:24 -0400812 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
813 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
814 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400815
816 // Time how long it takes to get a response to our request
817 long requestTimestamp = SystemClock.elapsedRealtime();
818
Pierre Imaibe12d762016-03-10 17:00:50 +0900819 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400820 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400821
822 // Time how long it takes to get a response to our request
823 long responseTimestamp = SystemClock.elapsedRealtime();
824
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900825 validationLog(ValidationProbeEvent.getProbeName(probeType) + " " + url +
826 " time=" + (responseTimestamp - requestTimestamp) + "ms" +
827 " ret=" + httpResponseCode +
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700828 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400829 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
830 // portal. The only example of this seen so far was a captive portal. For
831 // the time being go with prior behavior of assuming it's not a captive
832 // portal. If it is considered a captive portal, a different sign-in URL
833 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
834 // proxy server.
835
836 // Consider 200 response with "Content-length=0" to not be a captive portal.
837 // There's no point in considering this a captive portal as the user cannot
838 // sign-in to an empty page. Probably the result of a broken transparent proxy.
839 // See http://b/9972012.
840 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700841 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400842 httpResponseCode = 204;
843 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400844
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900845 if (httpResponseCode == 200 && probeType == ValidationProbeEvent.PROBE_PAC) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700846 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500847 httpResponseCode = 204;
848 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400849 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700850 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400851 if (httpResponseCode == 599) {
852 // TODO: Ping gateway and DNS server and log results.
853 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400854 } finally {
855 if (urlConnection != null) {
856 urlConnection.disconnect();
857 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400858 }
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900859 ValidationProbeEvent.logEvent(mNetId, probeTimer.stop(), probeType, httpResponseCode);
Paul Jensen232437312016-04-06 09:51:26 -0400860 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400861 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400862
Lorenzo Colittic5be12e2016-04-19 21:57:31 +0900863 private CaptivePortalProbeResult sendParallelHttpProbes(URL httpsUrl, URL httpUrl) {
864 // Number of probes to wait for. We might wait for all of them, but we might also return if
865 // only one of them has replied. For example, we immediately return if the HTTP probe finds
866 // a captive portal, even if the HTTPS probe is timing out.
867 final CountDownLatch latch = new CountDownLatch(2);
868
869 // Which probe result we're going to use. This doesn't need to be atomic, but it does need
870 // to be final because otherwise we can't set it from the ProbeThreads.
871 final AtomicReference<CaptivePortalProbeResult> finalResult = new AtomicReference<>();
872
873 final class ProbeThread extends Thread {
874 private final boolean mIsHttps;
875 private volatile CaptivePortalProbeResult mResult;
876
877 public ProbeThread(boolean isHttps) {
878 mIsHttps = isHttps;
879 }
880
881 public CaptivePortalProbeResult getResult() {
882 return mResult;
883 }
884
885 @Override
886 public void run() {
887 if (mIsHttps) {
888 mResult = sendHttpProbe(httpsUrl, ValidationProbeEvent.PROBE_HTTPS);
889 } else {
890 mResult = sendHttpProbe(httpUrl, ValidationProbeEvent.PROBE_HTTP);
891 }
892 if ((mIsHttps && mResult.isSuccessful()) || (!mIsHttps && mResult.isPortal())) {
893 // HTTPS succeeded, or HTTP found a portal. Don't wait for the other probe.
894 finalResult.compareAndSet(null, mResult);
895 latch.countDown();
896 }
897 // Signal that one probe has completed. If we've already made a decision, or if this
898 // is the second probe, the latch will be at zero and we'll return a result.
899 latch.countDown();
900 }
901 }
902
903 ProbeThread httpsProbe = new ProbeThread(true);
904 ProbeThread httpProbe = new ProbeThread(false);
905 httpsProbe.start();
906 httpProbe.start();
907
908 try {
909 latch.await();
910 } catch (InterruptedException e) {
911 validationLog("Error: probe wait interrupted!");
912 return CaptivePortalProbeResult.FAILED;
913 }
914
915 // If there was no deciding probe, that means that both probes completed. Return HTTPS.
916 finalResult.compareAndSet(null, httpsProbe.getResult());
917
918 return finalResult.get();
919 }
920
Paul Jensen306f1a42014-08-04 10:59:01 -0400921 /**
922 * @param responseReceived - whether or not we received a valid HTTP response to our request.
923 * If false, isCaptivePortal and responseTimestampMs are ignored
924 * TODO: This should be moved to the transports. The latency could be passed to the transports
925 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
926 * perhaps this could just be added to the WiFi transport only.
927 */
928 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
929 long requestTimestampMs, long responseTimestampMs) {
930 if (Settings.Global.getInt(mContext.getContentResolver(),
931 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400932 return;
933 }
934
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700935 if (systemReady == false) return;
936
Paul Jensen306f1a42014-08-04 10:59:01 -0400937 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
938 switch (mNetworkAgentInfo.networkInfo.getType()) {
939 case ConnectivityManager.TYPE_WIFI:
940 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
941 if (currentWifiInfo != null) {
942 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
943 // surrounded by double quotation marks (thus violating the Javadoc), but this
944 // was changed to match the Javadoc in API 17. Since clients may have started
945 // sanitizing the output of this method since API 17 was released, we should
946 // not change it here as it would become impossible to tell whether the SSID is
947 // simply being surrounded by quotes due to the API, or whether those quotes
948 // are actually part of the SSID.
949 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
950 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
951 } else {
952 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
953 return;
954 }
955 break;
956 case ConnectivityManager.TYPE_MOBILE:
957 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
958 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
959 if (info == null) return;
960 int numRegisteredCellInfo = 0;
961 for (CellInfo cellInfo : info) {
962 if (cellInfo.isRegistered()) {
963 numRegisteredCellInfo++;
964 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400965 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400966 "tell which is active. Bailing.");
967 return;
968 }
969 if (cellInfo instanceof CellInfoCdma) {
970 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
971 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
972 } else if (cellInfo instanceof CellInfoGsm) {
973 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
974 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
975 } else if (cellInfo instanceof CellInfoLte) {
976 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
977 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
978 } else if (cellInfo instanceof CellInfoWcdma) {
979 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
980 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
981 } else {
982 if (DBG) logw("Registered cellinfo is unrecognized");
983 return;
984 }
985 }
986 }
987 break;
988 default:
989 return;
990 }
991 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
992 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
993 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
994
995 if (responseReceived) {
996 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
997 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
998 }
Paul Jensen55298582014-08-20 11:01:41 -0400999 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
1000 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -04001001 }
Paul Jensend7b6ca92015-05-13 14:05:12 -04001002
1003 // Allow tests to override linger time.
1004 @VisibleForTesting
1005 public static void SetDefaultLingerTime(int time_ms) {
1006 if (Process.myUid() == Process.SYSTEM_UID) {
1007 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
1008 }
1009 DEFAULT_LINGER_DELAY_MS = time_ms;
1010 }
Lorenzo Colittibfecba22016-02-21 01:09:26 +09001011
1012 @VisibleForTesting
1013 protected WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int i) {
1014 return new WakeupMessage(c, h, s, i);
1015 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001016}