blob: 8b661e3a5d18cd151761ad18d7ae0f1429bc55e8 [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 Jensen79a08052014-08-21 12:44:07 -040019import android.app.AlarmManager;
Paul Jensen869868be2014-05-15 10:33:05 -040020import android.app.PendingIntent;
21import android.content.BroadcastReceiver;
22import android.content.ComponentName;
Paul Jensenca8f16a2014-05-09 12:47:55 -040023import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040024import android.content.Intent;
25import android.content.IntentFilter;
26import android.net.ConnectivityManager;
Paul Jensen2c311d62014-11-17 12:34:51 -050027import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050028import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040029import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040030import android.net.Uri;
Paul Jensen306f1a42014-08-04 10:59:01 -040031import android.net.wifi.WifiInfo;
32import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040033import android.os.Handler;
34import android.os.Message;
Paul Jensend7b6ca92015-05-13 14:05:12 -040035import android.os.Process;
Paul Jensen306f1a42014-08-04 10:59:01 -040036import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040037import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040038import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040039import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040040import android.telephony.CellIdentityCdma;
41import android.telephony.CellIdentityGsm;
42import android.telephony.CellIdentityLte;
43import android.telephony.CellIdentityWcdma;
44import android.telephony.CellInfo;
45import android.telephony.CellInfoCdma;
46import android.telephony.CellInfoGsm;
47import android.telephony.CellInfoLte;
48import android.telephony.CellInfoWcdma;
49import android.telephony.TelephonyManager;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070050import android.util.LocalLog;
51import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050052import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040053
Paul Jensend7b6ca92015-05-13 14:05:12 -040054import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040055import com.android.internal.util.Protocol;
56import com.android.internal.util.State;
57import com.android.internal.util.StateMachine;
58import com.android.server.connectivity.NetworkAgentInfo;
59
Paul Jensenca8f16a2014-05-09 12:47:55 -040060import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040061import java.net.HttpURLConnection;
Paul Jensenca8f16a2014-05-09 12:47:55 -040062import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040063import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040064import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040065
66/**
67 * {@hide}
68 */
69public class NetworkMonitor extends StateMachine {
70 private static final boolean DBG = true;
71 private static final String TAG = "NetworkMonitor";
Lorenzo Colitticd29cb62015-01-14 00:16:03 +090072 private static final String DEFAULT_SERVER = "connectivitycheck.android.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040073 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040074 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
75 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
76 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
77 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
78 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
79 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
80 public static final String EXTRA_CELL_ID = "extra_cellid";
81 public static final String EXTRA_SSID = "extra_ssid";
82 public static final String EXTRA_BSSID = "extra_bssid";
83 /** real time since boot */
84 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
85 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
86
87 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
88 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -040089
Paul Jensenad50a1f2014-09-05 12:06:44 -040090 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
91 // The network should be used as a default internet connection. It was found to be:
92 // 1. a functioning network providing internet access, or
93 // 2. a captive portal and the user decided to use it as is.
94 public static final int NETWORK_TEST_RESULT_VALID = 0;
95 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
96 // The network should not be used as a default internet connection. It was found to be:
97 // 1. a captive portal and the user is prompted to sign-in, or
98 // 2. a captive portal and the user did not want to use it, or
99 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
100 public static final int NETWORK_TEST_RESULT_INVALID = 1;
101
Paul Jensenca8f16a2014-05-09 12:47:55 -0400102 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
103
104 /**
105 * Inform NetworkMonitor that their network is connected.
106 * Initiates Network Validation.
107 */
108 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
109
110 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400111 * Inform ConnectivityService that the network has been tested.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400112 * obj = NetworkAgentInfo
Paul Jensenad50a1f2014-09-05 12:06:44 -0400113 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400114 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400115 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400116
117 /**
118 * Inform NetworkMonitor to linger a network. The Monitor should
119 * start a timer and/or start watching for zero live connections while
120 * moving towards LINGER_COMPLETE. After the Linger period expires
121 * (or other events mark the end of the linger state) the LINGER_COMPLETE
122 * event should be sent and the network will be shut down. If a
123 * CMD_NETWORK_CONNECTED happens before the LINGER completes
124 * it indicates further desire to keep the network alive and so
125 * the LINGER is aborted.
126 */
127 public static final int CMD_NETWORK_LINGER = BASE + 3;
128
129 /**
130 * Message to self indicating linger delay has expired.
131 * arg1 = Token to ignore old messages.
132 */
133 private static final int CMD_LINGER_EXPIRED = BASE + 4;
134
135 /**
136 * Inform ConnectivityService that the network LINGER period has
137 * expired.
138 * obj = NetworkAgentInfo
139 */
140 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
141
142 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400143 * Message to self indicating it's time to evaluate a network's connectivity.
144 * arg1 = Token to ignore old messages.
145 */
Paul Jensen869868be2014-05-15 10:33:05 -0400146 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400147
148 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400149 * Inform NetworkMonitor that the network has disconnected.
150 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400151 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400152
153 /**
154 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400155 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400156 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400157 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400158
159 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400160 * Message to self indicating captive portal app finished.
Paul Jensen25a217c2015-02-27 22:55:47 -0500161 * arg1 = one of: CAPTIVE_PORTAL_APP_RETURN_DISMISSED,
Paul Jensen71b645f2014-10-13 14:13:07 -0400162 * CAPTIVE_PORTAL_APP_RETURN_UNWANTED,
163 * CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500164 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400165 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500166 public static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400167
168 /**
169 * Request ConnectivityService display provisioning notification.
170 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400171 * arg2 = NetID.
172 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400173 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400174 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400175
176 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500177 * Message to self indicating sign-in app should be launched.
178 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
179 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400180 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500181 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400182
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400183 /**
184 * Retest network to see if captive portal is still in place.
185 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
186 * 0 indicates self-initiated, so nobody to blame.
187 */
188 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
189
Paul Jensenca8f16a2014-05-09 12:47:55 -0400190 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400191 // Default to 30s linger time-out. Modifyable only for testing.
192 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400193 private final int mLingerDelayMs;
194 private int mLingerToken = 0;
195
Paul Jensend0491e9a2015-05-05 14:52:22 -0400196 // Start mReevaluateDelayMs at this value and double.
197 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
198 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
199 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
200 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400201 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400202 private static final int INVALID_UID = -1;
203 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400204 // Stop blaming UID that requested re-evaluation after this many attempts.
205 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400206 // Delay between reevaluations once a captive portal has been found.
207 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400208
209 private final Context mContext;
210 private final Handler mConnectivityServiceHandler;
211 private final NetworkAgentInfo mNetworkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400212 private final TelephonyManager mTelephonyManager;
213 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400214 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500215 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400216
217 private String mServer;
218 private boolean mIsCaptivePortalCheckEnabled = false;
219
Paul Jensenad50a1f2014-09-05 12:06:44 -0400220 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
221 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400222 // Avoids surfacing "Sign in to network" notification.
223 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400224
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700225 public boolean systemReady = false;
226
Paul Jensen71b645f2014-10-13 14:13:07 -0400227 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400228 private final State mValidatedState = new ValidatedState();
229 private final State mMaybeNotifyState = new MaybeNotifyState();
230 private final State mEvaluatingState = new EvaluatingState();
231 private final State mCaptivePortalState = new CaptivePortalState();
232 private final State mLingeringState = new LingeringState();
233
Paul Jensen25a217c2015-02-27 22:55:47 -0500234 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400235 private String mCaptivePortalLoggedInResponseToken = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400236
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700237 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
238
Paul Jensen2c311d62014-11-17 12:34:51 -0500239 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
240 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400241 // Add suffix indicating which NetworkMonitor we're talking about.
242 super(TAG + networkAgentInfo.name());
243
244 mContext = context;
245 mConnectivityServiceHandler = handler;
246 mNetworkAgentInfo = networkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400247 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
248 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400249 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500250 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400251
252 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400253 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400254 addState(mMaybeNotifyState, mDefaultState);
255 addState(mEvaluatingState, mMaybeNotifyState);
256 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400257 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700258 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400259
260 mServer = Settings.Global.getString(mContext.getContentResolver(),
261 Settings.Global.CAPTIVE_PORTAL_SERVER);
262 if (mServer == null) mServer = DEFAULT_SERVER;
263
264 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400265
Paul Jensen869868be2014-05-15 10:33:05 -0400266 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
267 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400268
Paul Jensen71b645f2014-10-13 14:13:07 -0400269 mCaptivePortalLoggedInResponseToken = String.valueOf(new Random().nextLong());
270
Paul Jensenca8f16a2014-05-09 12:47:55 -0400271 start();
272 }
273
Paul Jensen532b61432014-11-10 09:50:02 -0500274 @Override
275 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400276 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500277 }
278
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700279 private void validationLog(String s) {
280 if (DBG) log(s);
281 validationLogs.log(s);
282 }
283
284 public ReadOnlyLocalLog getValidationLogs() {
285 return validationLogs.readOnlyLocalLog();
286 }
287
Paul Jensen71b645f2014-10-13 14:13:07 -0400288 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
289 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400290 private class DefaultState extends State {
291 @Override
292 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400293 switch (message.what) {
294 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400295 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400296 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400297 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400298 case CMD_NETWORK_CONNECTED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400299 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400300 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400301 case CMD_NETWORK_DISCONNECTED:
Paul Jensen25a217c2015-02-27 22:55:47 -0500302 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
303 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
304 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400305 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700306 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400307 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400308 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400309 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400310 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400311 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400312 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400313 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400314 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen25a217c2015-02-27 22:55:47 -0500315 if (!mCaptivePortalLoggedInResponseToken.equals((String)message.obj))
316 return HANDLED;
Paul Jensen22e547a2015-06-25 09:17:53 -0400317 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen25a217c2015-02-27 22:55:47 -0500318 // Previous token was sent out, come up with a new one.
Paul Jensen71b645f2014-10-13 14:13:07 -0400319 mCaptivePortalLoggedInResponseToken = String.valueOf(new Random().nextLong());
320 switch (message.arg1) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500321 case ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400322 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500323 break;
324 case ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400325 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500326 // TODO: Distinguish this from a network that actually validates.
327 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400328 transitionTo(mValidatedState);
329 break;
Paul Jensen25a217c2015-02-27 22:55:47 -0500330 case ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400331 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400332 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400333 mConnectivityServiceHandler.sendMessage(obtainMessage(
334 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
335 mNetworkAgentInfo));
Paul Jensen71b645f2014-10-13 14:13:07 -0400336 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400337 mUidResponsibleForReeval = 0;
338 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400339 break;
340 }
341 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400342 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400343 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400344 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400345 }
346 }
347
Paul Jensen71b645f2014-10-13 14:13:07 -0400348 // Being in the ValidatedState State indicates a Network is:
349 // - Successfully validated, or
350 // - Wanted "as is" by the user, or
351 // - Does not satsify the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400352 private class ValidatedState extends State {
353 @Override
354 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400355 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
356 NETWORK_TEST_RESULT_VALID, 0, mNetworkAgentInfo));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400357 }
358
359 @Override
360 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400361 switch (message.what) {
362 case CMD_NETWORK_CONNECTED:
363 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400364 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400365 default:
366 return NOT_HANDLED;
367 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400368 }
369 }
370
Paul Jensen71b645f2014-10-13 14:13:07 -0400371 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
372 // is required. This State takes care to clear the notification upon exit from the State.
373 private class MaybeNotifyState extends State {
374 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500375 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500376 switch (message.what) {
377 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
378 final Intent intent = new Intent(
379 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
380 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
381 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_TOKEN,
382 mCaptivePortalLoggedInResponseToken);
383 intent.setFlags(
384 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
385 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
386 return HANDLED;
387 default:
388 return NOT_HANDLED;
389 }
390 }
391
392 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400393 public void exit() {
394 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
395 mNetworkAgentInfo.network.netId, null);
396 mConnectivityServiceHandler.sendMessage(message);
397 }
398 }
399
400 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400401 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400402 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400403 private int mReevaluateDelayMs;
404 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400405
Paul Jensenca8f16a2014-05-09 12:47:55 -0400406 @Override
407 public void enter() {
408 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400409 if (mUidResponsibleForReeval != INVALID_UID) {
410 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
411 mUidResponsibleForReeval = INVALID_UID;
412 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400413 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
414 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400415 }
416
417 @Override
418 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400419 switch (message.what) {
420 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400421 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400422 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500423 // Don't bother validating networks that don't satisify the default request.
424 // This includes:
425 // - VPNs which can be considered explicitly desired by the user and the
426 // user's desire trumps whether the network validates.
427 // - Networks that don't provide internet access. It's unclear how to
428 // validate such networks.
429 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
430 // such networks and the user didn't express interest in connecting to
431 // such networks (an app did) so the user may be unhappily surprised when
432 // asked to sign-in to a network they didn't want to connect to in the
433 // first place. Validation could be done to adjust the network scores
434 // however these networks are app-requested and may not be intended for
435 // general usage, in which case general validation may not be an accurate
436 // measure of the network's quality. Only the app knows how to evaluate
437 // the network so don't bother validating here. Furthermore sending HTTP
438 // packets over the network may be undesirable, for example an extremely
439 // expensive metered network, or unwanted leaking of the User Agent string.
440 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
441 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400442 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400443 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400444 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400445 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900446 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
447 // server's IP addresses could hit the DNS timeout, and attempting connections
448 // to each of the server's several IP addresses (currently one IPv4 and one
449 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
450 // will be unresponsive. isCaptivePortal() could be executed on another Thread
451 // if this is found to cause problems.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400452 int httpResponseCode = isCaptivePortal();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400453 if (httpResponseCode == 204) {
454 transitionTo(mValidatedState);
455 } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400456 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400457 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400458 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400459 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensend9be23f2015-05-19 14:51:47 -0400460 mConnectivityServiceHandler.sendMessage(obtainMessage(
461 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
462 mNetworkAgentInfo));
463 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400464 // Don't continue to blame UID forever.
465 TrafficStats.clearThreadStatsUid();
466 }
467 mReevaluateDelayMs *= 2;
468 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
469 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
470 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400471 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400472 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400473 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400474 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
475 // ignore any re-evaluation requests. After, restart the
476 // evaluation process via EvaluatingState#enter.
477 return mAttempts < IGNORE_REEVALUATE_ATTEMPTS ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400478 default:
479 return NOT_HANDLED;
480 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400481 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400482
483 @Override
484 public void exit() {
485 TrafficStats.clearThreadStatsUid();
486 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400487 }
488
Paul Jensendcbe8352014-09-16 16:28:34 -0400489 // BroadcastReceiver that waits for a particular Intent and then posts a message.
490 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400491 private final int mToken;
492 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400493 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400494 CustomIntentReceiver(String action, int token, int what) {
495 mToken = token;
496 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400497 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
498 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400499 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400500 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500501 final Intent intent = new Intent(mAction);
502 intent.setPackage(mContext.getPackageName());
503 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400504 }
505 @Override
506 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400507 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400508 }
509 }
Paul Jensen869868be2014-05-15 10:33:05 -0400510
Paul Jensen71b645f2014-10-13 14:13:07 -0400511 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
512 // has been shown a notification to sign-in.
513 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500514 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
515 "android.net.netmon.launchCaptivePortalApp";
516
Paul Jensen869868be2014-05-15 10:33:05 -0400517 @Override
518 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400519 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
520 NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400521 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400522 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500523 // Create a CustomIntentReceiver that sends us a
524 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
525 // touches the notification.
526 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400527 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500528 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
529 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
530 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400531 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500532 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400533 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
534 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500535 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400536 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400537 // Retest for captive portal occasionally.
538 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
539 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400540 }
541
542 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400543 public void exit() {
544 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
545 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400546 }
547
Paul Jensen71b645f2014-10-13 14:13:07 -0400548 // Being in the LingeringState State indicates a Network's validated bit is true and it once
549 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
550 // another Network satsified the NetworkRequest with a higher score and hence this Network
551 // is "lingered" for a fixed period of time before it is disconnected. This period of time
552 // allows apps to wrap up communication and allows for seamless reactivation if the other
553 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400554 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400555 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400556
Paul Jensendcbe8352014-09-16 16:28:34 -0400557 private CustomIntentReceiver mBroadcastReceiver;
Paul Jensen79a08052014-08-21 12:44:07 -0400558 private PendingIntent mIntent;
559
Paul Jensenca8f16a2014-05-09 12:47:55 -0400560 @Override
561 public void enter() {
Paul Jensen71b645f2014-10-13 14:13:07 -0400562 mLingerToken = new Random().nextInt();
563 mBroadcastReceiver = new CustomIntentReceiver(ACTION_LINGER_EXPIRED, mLingerToken,
Paul Jensendcbe8352014-09-16 16:28:34 -0400564 CMD_LINGER_EXPIRED);
565 mIntent = mBroadcastReceiver.getPendingIntent();
Paul Jensen79a08052014-08-21 12:44:07 -0400566 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
567 mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime,
568 // Give a specific window so we aren't subject to unknown inexactitude.
569 mLingerDelayMs / 6, mIntent);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400570 }
571
572 @Override
573 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400574 switch (message.what) {
575 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400576 log("Unlingered");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400577 // Go straight to active as we've already evaluated.
578 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400579 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400580 case CMD_LINGER_EXPIRED:
581 if (message.arg1 != mLingerToken)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400582 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400583 mConnectivityServiceHandler.sendMessage(
584 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400585 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400586 case CMD_FORCE_REEVALUATION:
587 // Ignore reevaluation attempts when lingering. A reevaluation could result
588 // in a transition to the validated state which would abort the linger
589 // timeout. Lingering is the result of score assessment; validity is
590 // irrelevant.
591 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400592 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
593 // Ignore user network determination as this could abort linger timeout.
594 // Networks are only lingered once validated because:
595 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
596 // - Once validated, a Network's validated bit is never cleared.
597 // Since networks are only lingered after being validated a user's
598 // determination will not change the death sentence that lingering entails:
599 // - If the user wants to use the network or bypasses the captive portal,
600 // the network's score will not be increased beyond its current value
601 // because it is already validated. Without a score increase there is no
602 // chance of reactivation (i.e. aborting linger timeout).
603 // - If the user does not want the network, lingering will disconnect the
604 // network anyhow.
605 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400606 default:
607 return NOT_HANDLED;
608 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400609 }
Paul Jensen79a08052014-08-21 12:44:07 -0400610
611 @Override
612 public void exit() {
613 mAlarmManager.cancel(mIntent);
614 mContext.unregisterReceiver(mBroadcastReceiver);
615 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400616 }
617
618 /**
619 * Do a URL fetch on a known server to see if we get the data we expect.
620 * Returns HTTP response code.
621 */
622 private int isCaptivePortal() {
623 if (!mIsCaptivePortalCheckEnabled) return 204;
624
Paul Jensenca8f16a2014-05-09 12:47:55 -0400625 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400626 int httpResponseCode = 599;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400627 try {
Paul Jensene547ff22014-08-04 09:12:24 -0400628 URL url = new URL("http", mServer, "/generate_204");
Paul Jensen8fe17422015-02-02 11:03:03 -0500629 // On networks with a PAC instead of fetching a URL that should result in a 204
630 // reponse, we instead simply fetch the PAC script. This is done for a few reasons:
631 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
632 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
633 // Network.openConnection() will ignore network-specific PACs and instead fetch
634 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
635 // NO_PROXY is the fetch of the PAC itself.
636 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
637 // happen before the fetch can commence, namely:
638 // a) the PAC script be fetched
639 // b) a PAC script resolver service be fired up and resolve mServer
640 // Network validation could be delayed until these prerequisities are satisifed or
641 // could simply be left to race them. Neither is an optimal solution.
642 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
643 // fact block fetching of the generate_204 URL which would lead to false negative
644 // results for network validation.
645 boolean fetchPac = false;
646 {
647 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
648 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
649 url = new URL(proxyInfo.getPacFileUrl().toString());
650 fetchPac = true;
651 }
652 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700653 validationLog("Checking " + url.toString() + " on " +
654 mNetworkAgentInfo.networkInfo.getExtraInfo());
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700655 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500656 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400657 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
658 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
659 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400660
661 // Time how long it takes to get a response to our request
662 long requestTimestamp = SystemClock.elapsedRealtime();
663
Paul Jensene547ff22014-08-04 09:12:24 -0400664 urlConnection.getInputStream();
Paul Jensen306f1a42014-08-04 10:59:01 -0400665
666 // Time how long it takes to get a response to our request
667 long responseTimestamp = SystemClock.elapsedRealtime();
668
Paul Jensene547ff22014-08-04 09:12:24 -0400669 httpResponseCode = urlConnection.getResponseCode();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700670 validationLog("isCaptivePortal: ret=" + httpResponseCode +
671 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400672 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
673 // portal. The only example of this seen so far was a captive portal. For
674 // the time being go with prior behavior of assuming it's not a captive
675 // portal. If it is considered a captive portal, a different sign-in URL
676 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
677 // proxy server.
678
679 // Consider 200 response with "Content-length=0" to not be a captive portal.
680 // There's no point in considering this a captive portal as the user cannot
681 // sign-in to an empty page. Probably the result of a broken transparent proxy.
682 // See http://b/9972012.
683 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700684 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400685 httpResponseCode = 204;
686 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400687
Paul Jensen8fe17422015-02-02 11:03:03 -0500688 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700689 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500690 httpResponseCode = 204;
691 }
692
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800693 sendNetworkConditionsBroadcast(true /* response received */,
694 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400695 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400696 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700697 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400698 if (httpResponseCode == 599) {
699 // TODO: Ping gateway and DNS server and log results.
700 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400701 } finally {
702 if (urlConnection != null) {
703 urlConnection.disconnect();
704 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400705 }
706 return httpResponseCode;
707 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400708
709 /**
710 * @param responseReceived - whether or not we received a valid HTTP response to our request.
711 * If false, isCaptivePortal and responseTimestampMs are ignored
712 * TODO: This should be moved to the transports. The latency could be passed to the transports
713 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
714 * perhaps this could just be added to the WiFi transport only.
715 */
716 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
717 long requestTimestampMs, long responseTimestampMs) {
718 if (Settings.Global.getInt(mContext.getContentResolver(),
719 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400720 return;
721 }
722
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700723 if (systemReady == false) return;
724
Paul Jensen306f1a42014-08-04 10:59:01 -0400725 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
726 switch (mNetworkAgentInfo.networkInfo.getType()) {
727 case ConnectivityManager.TYPE_WIFI:
728 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
729 if (currentWifiInfo != null) {
730 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
731 // surrounded by double quotation marks (thus violating the Javadoc), but this
732 // was changed to match the Javadoc in API 17. Since clients may have started
733 // sanitizing the output of this method since API 17 was released, we should
734 // not change it here as it would become impossible to tell whether the SSID is
735 // simply being surrounded by quotes due to the API, or whether those quotes
736 // are actually part of the SSID.
737 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
738 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
739 } else {
740 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
741 return;
742 }
743 break;
744 case ConnectivityManager.TYPE_MOBILE:
745 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
746 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
747 if (info == null) return;
748 int numRegisteredCellInfo = 0;
749 for (CellInfo cellInfo : info) {
750 if (cellInfo.isRegistered()) {
751 numRegisteredCellInfo++;
752 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400753 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400754 "tell which is active. Bailing.");
755 return;
756 }
757 if (cellInfo instanceof CellInfoCdma) {
758 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
759 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
760 } else if (cellInfo instanceof CellInfoGsm) {
761 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
762 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
763 } else if (cellInfo instanceof CellInfoLte) {
764 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
765 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
766 } else if (cellInfo instanceof CellInfoWcdma) {
767 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
768 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
769 } else {
770 if (DBG) logw("Registered cellinfo is unrecognized");
771 return;
772 }
773 }
774 }
775 break;
776 default:
777 return;
778 }
779 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
780 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
781 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
782
783 if (responseReceived) {
784 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
785 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
786 }
Paul Jensen55298582014-08-20 11:01:41 -0400787 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
788 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400789 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400790
791 // Allow tests to override linger time.
792 @VisibleForTesting
793 public static void SetDefaultLingerTime(int time_ms) {
794 if (Process.myUid() == Process.SYSTEM_UID) {
795 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
796 }
797 DEFAULT_LINGER_DELAY_MS = time_ms;
798 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400799}