blob: e47292866d9c3a469a25ea70cb8127784a30040b [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;
Paul Jensen2f0a8972015-06-25 10:07:14 -040050import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070051import android.util.LocalLog;
52import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050053import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040054
Paul Jensend7b6ca92015-05-13 14:05:12 -040055import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040056import com.android.internal.util.Protocol;
57import com.android.internal.util.State;
58import com.android.internal.util.StateMachine;
59import com.android.server.connectivity.NetworkAgentInfo;
60
Paul Jensenca8f16a2014-05-09 12:47:55 -040061import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040062import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040063import java.net.InetAddress;
Paul Jensenca8f16a2014-05-09 12:47:55 -040064import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040065import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040066import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040067
68/**
69 * {@hide}
70 */
71public class NetworkMonitor extends StateMachine {
72 private static final boolean DBG = true;
73 private static final String TAG = "NetworkMonitor";
Lorenzo Colitticd29cb62015-01-14 00:16:03 +090074 private static final String DEFAULT_SERVER = "connectivitycheck.android.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040075 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040076 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
77 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
78 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
79 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
80 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
81 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
82 public static final String EXTRA_CELL_ID = "extra_cellid";
83 public static final String EXTRA_SSID = "extra_ssid";
84 public static final String EXTRA_BSSID = "extra_bssid";
85 /** real time since boot */
86 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
87 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
88
89 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
90 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -040091
Paul Jensenad50a1f2014-09-05 12:06:44 -040092 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
93 // The network should be used as a default internet connection. It was found to be:
94 // 1. a functioning network providing internet access, or
95 // 2. a captive portal and the user decided to use it as is.
96 public static final int NETWORK_TEST_RESULT_VALID = 0;
97 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
98 // The network should not be used as a default internet connection. It was found to be:
99 // 1. a captive portal and the user is prompted to sign-in, or
100 // 2. a captive portal and the user did not want to use it, or
101 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
102 public static final int NETWORK_TEST_RESULT_INVALID = 1;
103
Paul Jensenca8f16a2014-05-09 12:47:55 -0400104 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
105
106 /**
107 * Inform NetworkMonitor that their network is connected.
108 * Initiates Network Validation.
109 */
110 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
111
112 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400113 * Inform ConnectivityService that the network has been tested.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400114 * obj = NetworkAgentInfo
Paul Jensenad50a1f2014-09-05 12:06:44 -0400115 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400116 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400117 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400118
119 /**
120 * Inform NetworkMonitor to linger a network. The Monitor should
121 * start a timer and/or start watching for zero live connections while
122 * moving towards LINGER_COMPLETE. After the Linger period expires
123 * (or other events mark the end of the linger state) the LINGER_COMPLETE
124 * event should be sent and the network will be shut down. If a
125 * CMD_NETWORK_CONNECTED happens before the LINGER completes
126 * it indicates further desire to keep the network alive and so
127 * the LINGER is aborted.
128 */
129 public static final int CMD_NETWORK_LINGER = BASE + 3;
130
131 /**
132 * Message to self indicating linger delay has expired.
133 * arg1 = Token to ignore old messages.
134 */
135 private static final int CMD_LINGER_EXPIRED = BASE + 4;
136
137 /**
138 * Inform ConnectivityService that the network LINGER period has
139 * expired.
140 * obj = NetworkAgentInfo
141 */
142 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
143
144 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400145 * Message to self indicating it's time to evaluate a network's connectivity.
146 * arg1 = Token to ignore old messages.
147 */
Paul Jensen869868be2014-05-15 10:33:05 -0400148 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400149
150 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400151 * Inform NetworkMonitor that the network has disconnected.
152 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400153 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400154
155 /**
156 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400157 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400158 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400159 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400160
161 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400162 * Message to self indicating captive portal app finished.
Paul Jensen25a217c2015-02-27 22:55:47 -0500163 * arg1 = one of: CAPTIVE_PORTAL_APP_RETURN_DISMISSED,
Paul Jensen71b645f2014-10-13 14:13:07 -0400164 * CAPTIVE_PORTAL_APP_RETURN_UNWANTED,
165 * CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500166 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400167 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500168 public static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400169
170 /**
171 * Request ConnectivityService display provisioning notification.
172 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400173 * arg2 = NetID.
174 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400175 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400176 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400177
178 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500179 * Message to self indicating sign-in app should be launched.
180 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
181 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400182 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500183 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400184
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400185 /**
186 * Retest network to see if captive portal is still in place.
187 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
188 * 0 indicates self-initiated, so nobody to blame.
189 */
190 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
191
Paul Jensenca8f16a2014-05-09 12:47:55 -0400192 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400193 // Default to 30s linger time-out. Modifyable only for testing.
194 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400195 private final int mLingerDelayMs;
196 private int mLingerToken = 0;
197
Paul Jensend0491e9a2015-05-05 14:52:22 -0400198 // Start mReevaluateDelayMs at this value and double.
199 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
200 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
201 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
202 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400203 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400204 private static final int INVALID_UID = -1;
205 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400206 // Stop blaming UID that requested re-evaluation after this many attempts.
207 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400208 // Delay between reevaluations once a captive portal has been found.
209 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400210
211 private final Context mContext;
212 private final Handler mConnectivityServiceHandler;
213 private final NetworkAgentInfo mNetworkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400214 private final TelephonyManager mTelephonyManager;
215 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400216 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500217 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400218
219 private String mServer;
220 private boolean mIsCaptivePortalCheckEnabled = false;
221
Paul Jensenad50a1f2014-09-05 12:06:44 -0400222 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
223 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400224 // Avoids surfacing "Sign in to network" notification.
225 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400226
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700227 public boolean systemReady = false;
228
Paul Jensen71b645f2014-10-13 14:13:07 -0400229 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400230 private final State mValidatedState = new ValidatedState();
231 private final State mMaybeNotifyState = new MaybeNotifyState();
232 private final State mEvaluatingState = new EvaluatingState();
233 private final State mCaptivePortalState = new CaptivePortalState();
234 private final State mLingeringState = new LingeringState();
235
Paul Jensen25a217c2015-02-27 22:55:47 -0500236 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400237 private String mCaptivePortalLoggedInResponseToken = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400238
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700239 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
240
Paul Jensen2c311d62014-11-17 12:34:51 -0500241 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
242 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400243 // Add suffix indicating which NetworkMonitor we're talking about.
244 super(TAG + networkAgentInfo.name());
245
246 mContext = context;
247 mConnectivityServiceHandler = handler;
248 mNetworkAgentInfo = networkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400249 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
250 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400251 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500252 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400253
254 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400255 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400256 addState(mMaybeNotifyState, mDefaultState);
257 addState(mEvaluatingState, mMaybeNotifyState);
258 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400259 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700260 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400261
262 mServer = Settings.Global.getString(mContext.getContentResolver(),
263 Settings.Global.CAPTIVE_PORTAL_SERVER);
264 if (mServer == null) mServer = DEFAULT_SERVER;
265
266 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400267
Paul Jensen869868be2014-05-15 10:33:05 -0400268 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
269 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400270
Paul Jensen71b645f2014-10-13 14:13:07 -0400271 mCaptivePortalLoggedInResponseToken = String.valueOf(new Random().nextLong());
272
Paul Jensenca8f16a2014-05-09 12:47:55 -0400273 start();
274 }
275
Paul Jensen532b61432014-11-10 09:50:02 -0500276 @Override
277 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400278 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500279 }
280
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700281 private void validationLog(String s) {
282 if (DBG) log(s);
283 validationLogs.log(s);
284 }
285
286 public ReadOnlyLocalLog getValidationLogs() {
287 return validationLogs.readOnlyLocalLog();
288 }
289
Paul Jensen71b645f2014-10-13 14:13:07 -0400290 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
291 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400292 private class DefaultState extends State {
293 @Override
294 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400295 switch (message.what) {
296 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400297 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400298 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400299 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400300 case CMD_NETWORK_CONNECTED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400301 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400302 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400303 case CMD_NETWORK_DISCONNECTED:
Paul Jensen25a217c2015-02-27 22:55:47 -0500304 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
305 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
306 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400307 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700308 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400309 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400310 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400311 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400312 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400313 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400314 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400315 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400316 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen25a217c2015-02-27 22:55:47 -0500317 if (!mCaptivePortalLoggedInResponseToken.equals((String)message.obj))
318 return HANDLED;
Paul Jensen22e547a2015-06-25 09:17:53 -0400319 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen25a217c2015-02-27 22:55:47 -0500320 // Previous token was sent out, come up with a new one.
Paul Jensen71b645f2014-10-13 14:13:07 -0400321 mCaptivePortalLoggedInResponseToken = String.valueOf(new Random().nextLong());
322 switch (message.arg1) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500323 case ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400324 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500325 break;
326 case ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400327 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500328 // TODO: Distinguish this from a network that actually validates.
329 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400330 transitionTo(mValidatedState);
331 break;
Paul Jensen25a217c2015-02-27 22:55:47 -0500332 case ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400333 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400334 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400335 mConnectivityServiceHandler.sendMessage(obtainMessage(
336 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
337 mNetworkAgentInfo));
Paul Jensen71b645f2014-10-13 14:13:07 -0400338 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400339 mUidResponsibleForReeval = 0;
340 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400341 break;
342 }
343 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400344 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400345 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400346 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400347 }
348 }
349
Paul Jensen71b645f2014-10-13 14:13:07 -0400350 // Being in the ValidatedState State indicates a Network is:
351 // - Successfully validated, or
352 // - Wanted "as is" by the user, or
353 // - Does not satsify the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400354 private class ValidatedState extends State {
355 @Override
356 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400357 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
358 NETWORK_TEST_RESULT_VALID, 0, mNetworkAgentInfo));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400359 }
360
361 @Override
362 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400363 switch (message.what) {
364 case CMD_NETWORK_CONNECTED:
365 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400366 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400367 default:
368 return NOT_HANDLED;
369 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400370 }
371 }
372
Paul Jensen71b645f2014-10-13 14:13:07 -0400373 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
374 // is required. This State takes care to clear the notification upon exit from the State.
375 private class MaybeNotifyState extends State {
376 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500377 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500378 switch (message.what) {
379 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
380 final Intent intent = new Intent(
381 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
382 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
383 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL_TOKEN,
384 mCaptivePortalLoggedInResponseToken);
385 intent.setFlags(
386 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
387 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
388 return HANDLED;
389 default:
390 return NOT_HANDLED;
391 }
392 }
393
394 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400395 public void exit() {
396 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
397 mNetworkAgentInfo.network.netId, null);
398 mConnectivityServiceHandler.sendMessage(message);
399 }
400 }
401
402 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400403 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400404 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400405 private int mReevaluateDelayMs;
406 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400407
Paul Jensenca8f16a2014-05-09 12:47:55 -0400408 @Override
409 public void enter() {
410 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400411 if (mUidResponsibleForReeval != INVALID_UID) {
412 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
413 mUidResponsibleForReeval = INVALID_UID;
414 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400415 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
416 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400417 }
418
419 @Override
420 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400421 switch (message.what) {
422 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400423 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400424 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500425 // Don't bother validating networks that don't satisify the default request.
426 // This includes:
427 // - VPNs which can be considered explicitly desired by the user and the
428 // user's desire trumps whether the network validates.
429 // - Networks that don't provide internet access. It's unclear how to
430 // validate such networks.
431 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
432 // such networks and the user didn't express interest in connecting to
433 // such networks (an app did) so the user may be unhappily surprised when
434 // asked to sign-in to a network they didn't want to connect to in the
435 // first place. Validation could be done to adjust the network scores
436 // however these networks are app-requested and may not be intended for
437 // general usage, in which case general validation may not be an accurate
438 // measure of the network's quality. Only the app knows how to evaluate
439 // the network so don't bother validating here. Furthermore sending HTTP
440 // packets over the network may be undesirable, for example an extremely
441 // expensive metered network, or unwanted leaking of the User Agent string.
442 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
443 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400444 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400445 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400446 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400447 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900448 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
449 // server's IP addresses could hit the DNS timeout, and attempting connections
450 // to each of the server's several IP addresses (currently one IPv4 and one
451 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
452 // will be unresponsive. isCaptivePortal() could be executed on another Thread
453 // if this is found to cause problems.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400454 int httpResponseCode = isCaptivePortal();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400455 if (httpResponseCode == 204) {
456 transitionTo(mValidatedState);
457 } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400458 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400459 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400460 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400461 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensend9be23f2015-05-19 14:51:47 -0400462 mConnectivityServiceHandler.sendMessage(obtainMessage(
463 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
464 mNetworkAgentInfo));
465 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400466 // Don't continue to blame UID forever.
467 TrafficStats.clearThreadStatsUid();
468 }
469 mReevaluateDelayMs *= 2;
470 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
471 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
472 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400473 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400474 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400475 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400476 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
477 // ignore any re-evaluation requests. After, restart the
478 // evaluation process via EvaluatingState#enter.
479 return mAttempts < IGNORE_REEVALUATE_ATTEMPTS ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400480 default:
481 return NOT_HANDLED;
482 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400483 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400484
485 @Override
486 public void exit() {
487 TrafficStats.clearThreadStatsUid();
488 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400489 }
490
Paul Jensendcbe8352014-09-16 16:28:34 -0400491 // BroadcastReceiver that waits for a particular Intent and then posts a message.
492 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400493 private final int mToken;
494 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400495 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400496 CustomIntentReceiver(String action, int token, int what) {
497 mToken = token;
498 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400499 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
500 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400501 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400502 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500503 final Intent intent = new Intent(mAction);
504 intent.setPackage(mContext.getPackageName());
505 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400506 }
507 @Override
508 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400509 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400510 }
511 }
Paul Jensen869868be2014-05-15 10:33:05 -0400512
Paul Jensen71b645f2014-10-13 14:13:07 -0400513 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
514 // has been shown a notification to sign-in.
515 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500516 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
517 "android.net.netmon.launchCaptivePortalApp";
518
Paul Jensen869868be2014-05-15 10:33:05 -0400519 @Override
520 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400521 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
522 NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400523 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400524 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500525 // Create a CustomIntentReceiver that sends us a
526 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
527 // touches the notification.
528 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400529 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500530 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
531 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
532 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400533 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500534 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400535 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
536 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500537 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400538 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400539 // Retest for captive portal occasionally.
540 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
541 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400542 }
543
544 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400545 public void exit() {
546 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
547 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400548 }
549
Paul Jensen71b645f2014-10-13 14:13:07 -0400550 // Being in the LingeringState State indicates a Network's validated bit is true and it once
551 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
552 // another Network satsified the NetworkRequest with a higher score and hence this Network
553 // is "lingered" for a fixed period of time before it is disconnected. This period of time
554 // allows apps to wrap up communication and allows for seamless reactivation if the other
555 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400556 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400557 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400558
Paul Jensendcbe8352014-09-16 16:28:34 -0400559 private CustomIntentReceiver mBroadcastReceiver;
Paul Jensen79a08052014-08-21 12:44:07 -0400560 private PendingIntent mIntent;
561
Paul Jensenca8f16a2014-05-09 12:47:55 -0400562 @Override
563 public void enter() {
Paul Jensen71b645f2014-10-13 14:13:07 -0400564 mLingerToken = new Random().nextInt();
565 mBroadcastReceiver = new CustomIntentReceiver(ACTION_LINGER_EXPIRED, mLingerToken,
Paul Jensendcbe8352014-09-16 16:28:34 -0400566 CMD_LINGER_EXPIRED);
567 mIntent = mBroadcastReceiver.getPendingIntent();
Paul Jensen79a08052014-08-21 12:44:07 -0400568 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
569 mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime,
570 // Give a specific window so we aren't subject to unknown inexactitude.
571 mLingerDelayMs / 6, mIntent);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400572 }
573
574 @Override
575 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400576 switch (message.what) {
577 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400578 log("Unlingered");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400579 // Go straight to active as we've already evaluated.
580 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400581 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400582 case CMD_LINGER_EXPIRED:
583 if (message.arg1 != mLingerToken)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400584 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400585 mConnectivityServiceHandler.sendMessage(
586 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400587 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400588 case CMD_FORCE_REEVALUATION:
589 // Ignore reevaluation attempts when lingering. A reevaluation could result
590 // in a transition to the validated state which would abort the linger
591 // timeout. Lingering is the result of score assessment; validity is
592 // irrelevant.
593 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400594 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
595 // Ignore user network determination as this could abort linger timeout.
596 // Networks are only lingered once validated because:
597 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
598 // - Once validated, a Network's validated bit is never cleared.
599 // Since networks are only lingered after being validated a user's
600 // determination will not change the death sentence that lingering entails:
601 // - If the user wants to use the network or bypasses the captive portal,
602 // the network's score will not be increased beyond its current value
603 // because it is already validated. Without a score increase there is no
604 // chance of reactivation (i.e. aborting linger timeout).
605 // - If the user does not want the network, lingering will disconnect the
606 // network anyhow.
607 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400608 default:
609 return NOT_HANDLED;
610 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400611 }
Paul Jensen79a08052014-08-21 12:44:07 -0400612
613 @Override
614 public void exit() {
615 mAlarmManager.cancel(mIntent);
616 mContext.unregisterReceiver(mBroadcastReceiver);
617 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400618 }
619
620 /**
621 * Do a URL fetch on a known server to see if we get the data we expect.
622 * Returns HTTP response code.
623 */
624 private int isCaptivePortal() {
625 if (!mIsCaptivePortalCheckEnabled) return 204;
626
Paul Jensenca8f16a2014-05-09 12:47:55 -0400627 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400628 int httpResponseCode = 599;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400629 try {
Paul Jensene547ff22014-08-04 09:12:24 -0400630 URL url = new URL("http", mServer, "/generate_204");
Paul Jensen8fe17422015-02-02 11:03:03 -0500631 // On networks with a PAC instead of fetching a URL that should result in a 204
632 // reponse, we instead simply fetch the PAC script. This is done for a few reasons:
633 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
634 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
635 // Network.openConnection() will ignore network-specific PACs and instead fetch
636 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
637 // NO_PROXY is the fetch of the PAC itself.
638 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
639 // happen before the fetch can commence, namely:
640 // a) the PAC script be fetched
641 // b) a PAC script resolver service be fired up and resolve mServer
642 // Network validation could be delayed until these prerequisities are satisifed or
643 // could simply be left to race them. Neither is an optimal solution.
644 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
645 // fact block fetching of the generate_204 URL which would lead to false negative
646 // results for network validation.
647 boolean fetchPac = false;
Paul Jensen2f0a8972015-06-25 10:07:14 -0400648 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
649 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
650 url = new URL(proxyInfo.getPacFileUrl().toString());
651 fetchPac = true;
652 }
653 final StringBuffer connectInfo = new StringBuffer();
654 String hostToResolve = null;
655 // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
656 // unnecessary resolution.
657 if (proxyInfo == null || fetchPac) {
658 hostToResolve = url.getHost();
659 } else if (proxyInfo != null) {
660 hostToResolve = proxyInfo.getHost();
661 }
662 if (!TextUtils.isEmpty(hostToResolve)) {
663 connectInfo.append(", " + hostToResolve + "=");
664 final InetAddress[] addresses =
665 mNetworkAgentInfo.network.getAllByName(hostToResolve);
666 for (InetAddress address : addresses) {
667 connectInfo.append(address.getHostAddress());
668 if (address != addresses[addresses.length-1]) connectInfo.append(",");
Paul Jensen8fe17422015-02-02 11:03:03 -0500669 }
670 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700671 validationLog("Checking " + url.toString() + " on " +
Paul Jensen2f0a8972015-06-25 10:07:14 -0400672 mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700673 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500674 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400675 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
676 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
677 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400678
679 // Time how long it takes to get a response to our request
680 long requestTimestamp = SystemClock.elapsedRealtime();
681
Paul Jensene547ff22014-08-04 09:12:24 -0400682 urlConnection.getInputStream();
Paul Jensen306f1a42014-08-04 10:59:01 -0400683
684 // Time how long it takes to get a response to our request
685 long responseTimestamp = SystemClock.elapsedRealtime();
686
Paul Jensene547ff22014-08-04 09:12:24 -0400687 httpResponseCode = urlConnection.getResponseCode();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700688 validationLog("isCaptivePortal: ret=" + httpResponseCode +
689 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400690 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
691 // portal. The only example of this seen so far was a captive portal. For
692 // the time being go with prior behavior of assuming it's not a captive
693 // portal. If it is considered a captive portal, a different sign-in URL
694 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
695 // proxy server.
696
697 // Consider 200 response with "Content-length=0" to not be a captive portal.
698 // There's no point in considering this a captive portal as the user cannot
699 // sign-in to an empty page. Probably the result of a broken transparent proxy.
700 // See http://b/9972012.
701 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700702 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400703 httpResponseCode = 204;
704 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400705
Paul Jensen8fe17422015-02-02 11:03:03 -0500706 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700707 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500708 httpResponseCode = 204;
709 }
710
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800711 sendNetworkConditionsBroadcast(true /* response received */,
712 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400713 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400714 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700715 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400716 if (httpResponseCode == 599) {
717 // TODO: Ping gateway and DNS server and log results.
718 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400719 } finally {
720 if (urlConnection != null) {
721 urlConnection.disconnect();
722 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400723 }
724 return httpResponseCode;
725 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400726
727 /**
728 * @param responseReceived - whether or not we received a valid HTTP response to our request.
729 * If false, isCaptivePortal and responseTimestampMs are ignored
730 * TODO: This should be moved to the transports. The latency could be passed to the transports
731 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
732 * perhaps this could just be added to the WiFi transport only.
733 */
734 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
735 long requestTimestampMs, long responseTimestampMs) {
736 if (Settings.Global.getInt(mContext.getContentResolver(),
737 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400738 return;
739 }
740
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700741 if (systemReady == false) return;
742
Paul Jensen306f1a42014-08-04 10:59:01 -0400743 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
744 switch (mNetworkAgentInfo.networkInfo.getType()) {
745 case ConnectivityManager.TYPE_WIFI:
746 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
747 if (currentWifiInfo != null) {
748 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
749 // surrounded by double quotation marks (thus violating the Javadoc), but this
750 // was changed to match the Javadoc in API 17. Since clients may have started
751 // sanitizing the output of this method since API 17 was released, we should
752 // not change it here as it would become impossible to tell whether the SSID is
753 // simply being surrounded by quotes due to the API, or whether those quotes
754 // are actually part of the SSID.
755 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
756 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
757 } else {
758 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
759 return;
760 }
761 break;
762 case ConnectivityManager.TYPE_MOBILE:
763 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
764 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
765 if (info == null) return;
766 int numRegisteredCellInfo = 0;
767 for (CellInfo cellInfo : info) {
768 if (cellInfo.isRegistered()) {
769 numRegisteredCellInfo++;
770 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400771 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400772 "tell which is active. Bailing.");
773 return;
774 }
775 if (cellInfo instanceof CellInfoCdma) {
776 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
777 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
778 } else if (cellInfo instanceof CellInfoGsm) {
779 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
780 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
781 } else if (cellInfo instanceof CellInfoLte) {
782 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
783 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
784 } else if (cellInfo instanceof CellInfoWcdma) {
785 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
786 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
787 } else {
788 if (DBG) logw("Registered cellinfo is unrecognized");
789 return;
790 }
791 }
792 }
793 break;
794 default:
795 return;
796 }
797 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
798 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
799 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
800
801 if (responseReceived) {
802 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
803 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
804 }
Paul Jensen55298582014-08-20 11:01:41 -0400805 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
806 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400807 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400808
809 // Allow tests to override linger time.
810 @VisibleForTesting
811 public static void SetDefaultLingerTime(int time_ms) {
812 if (Process.myUid() == Process.SYSTEM_UID) {
813 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
814 }
815 DEFAULT_LINGER_DELAY_MS = time_ms;
816 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400817}