blob: a6dc6a30eda2fe640451a2b77763567cdf22c9a5 [file] [log] [blame]
Paul Jensenca8f16a2014-05-09 12:47:55 -04001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.connectivity;
18
Paul Jensen49e3edf2015-05-22 10:50:39 -040019import static android.net.CaptivePortal.APP_RETURN_DISMISSED;
20import static android.net.CaptivePortal.APP_RETURN_UNWANTED;
21import static android.net.CaptivePortal.APP_RETURN_WANTED_AS_IS;
22
Paul Jensen79a08052014-08-21 12:44:07 -040023import android.app.AlarmManager;
Paul Jensen869868be2014-05-15 10:33:05 -040024import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
Paul Jensenca8f16a2014-05-09 12:47:55 -040027import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040028import android.content.Intent;
29import android.content.IntentFilter;
Paul Jensen49e3edf2015-05-22 10:50:39 -040030import android.net.CaptivePortal;
Paul Jensen869868be2014-05-15 10:33:05 -040031import android.net.ConnectivityManager;
Paul Jensen49e3edf2015-05-22 10:50:39 -040032import android.net.ICaptivePortal;
Paul Jensen2c311d62014-11-17 12:34:51 -050033import android.net.NetworkRequest;
Paul Jensen8fe17422015-02-02 11:03:03 -050034import android.net.ProxyInfo;
Paul Jensen7ccd3df2014-08-29 09:54:01 -040035import android.net.TrafficStats;
Paul Jensen71b645f2014-10-13 14:13:07 -040036import android.net.Uri;
Paul Jensen306f1a42014-08-04 10:59:01 -040037import android.net.wifi.WifiInfo;
38import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040039import android.os.Handler;
40import android.os.Message;
Paul Jensend7b6ca92015-05-13 14:05:12 -040041import android.os.Process;
Paul Jensen306f1a42014-08-04 10:59:01 -040042import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040043import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040044import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040045import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040046import android.telephony.CellIdentityCdma;
47import android.telephony.CellIdentityGsm;
48import android.telephony.CellIdentityLte;
49import android.telephony.CellIdentityWcdma;
50import android.telephony.CellInfo;
51import android.telephony.CellInfoCdma;
52import android.telephony.CellInfoGsm;
53import android.telephony.CellInfoLte;
54import android.telephony.CellInfoWcdma;
55import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040056import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070057import android.util.LocalLog;
58import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050059import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040060
Paul Jensend7b6ca92015-05-13 14:05:12 -040061import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040062import com.android.internal.util.Protocol;
63import com.android.internal.util.State;
64import com.android.internal.util.StateMachine;
65import com.android.server.connectivity.NetworkAgentInfo;
66
Paul Jensenca8f16a2014-05-09 12:47:55 -040067import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040068import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040069import java.net.InetAddress;
Paul Jensenca8f16a2014-05-09 12:47:55 -040070import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040071import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040072import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040073
74/**
75 * {@hide}
76 */
77public class NetworkMonitor extends StateMachine {
78 private static final boolean DBG = true;
79 private static final String TAG = "NetworkMonitor";
Lorenzo Colitticd29cb62015-01-14 00:16:03 +090080 private static final String DEFAULT_SERVER = "connectivitycheck.android.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040081 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040082 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
83 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
84 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
85 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
86 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
87 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
88 public static final String EXTRA_CELL_ID = "extra_cellid";
89 public static final String EXTRA_SSID = "extra_ssid";
90 public static final String EXTRA_BSSID = "extra_bssid";
91 /** real time since boot */
92 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
93 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
94
95 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
96 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -040097
Paul Jensenad50a1f2014-09-05 12:06:44 -040098 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
99 // The network should be used as a default internet connection. It was found to be:
100 // 1. a functioning network providing internet access, or
101 // 2. a captive portal and the user decided to use it as is.
102 public static final int NETWORK_TEST_RESULT_VALID = 0;
103 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
104 // The network should not be used as a default internet connection. It was found to be:
105 // 1. a captive portal and the user is prompted to sign-in, or
106 // 2. a captive portal and the user did not want to use it, or
107 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
108 public static final int NETWORK_TEST_RESULT_INVALID = 1;
109
Paul Jensenca8f16a2014-05-09 12:47:55 -0400110 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
111
112 /**
113 * Inform NetworkMonitor that their network is connected.
114 * Initiates Network Validation.
115 */
116 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
117
118 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400119 * Inform ConnectivityService that the network has been tested.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400120 * obj = NetworkAgentInfo
Paul Jensenad50a1f2014-09-05 12:06:44 -0400121 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400122 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400123 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400124
125 /**
126 * Inform NetworkMonitor to linger a network. The Monitor should
127 * start a timer and/or start watching for zero live connections while
128 * moving towards LINGER_COMPLETE. After the Linger period expires
129 * (or other events mark the end of the linger state) the LINGER_COMPLETE
130 * event should be sent and the network will be shut down. If a
131 * CMD_NETWORK_CONNECTED happens before the LINGER completes
132 * it indicates further desire to keep the network alive and so
133 * the LINGER is aborted.
134 */
135 public static final int CMD_NETWORK_LINGER = BASE + 3;
136
137 /**
138 * Message to self indicating linger delay has expired.
139 * arg1 = Token to ignore old messages.
140 */
141 private static final int CMD_LINGER_EXPIRED = BASE + 4;
142
143 /**
144 * Inform ConnectivityService that the network LINGER period has
145 * expired.
146 * obj = NetworkAgentInfo
147 */
148 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
149
150 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400151 * Message to self indicating it's time to evaluate a network's connectivity.
152 * arg1 = Token to ignore old messages.
153 */
Paul Jensen869868be2014-05-15 10:33:05 -0400154 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400155
156 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400157 * Inform NetworkMonitor that the network has disconnected.
158 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400159 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400160
161 /**
162 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400163 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400164 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400165 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400166
167 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400168 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400169 * arg1 = one of: APP_RETURN_DISMISSED,
170 * APP_RETURN_UNWANTED,
171 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500172 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400173 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400174 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400175
176 /**
177 * Request ConnectivityService display provisioning notification.
178 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400179 * arg2 = NetID.
180 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400181 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400182 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400183
184 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500185 * Message to self indicating sign-in app should be launched.
186 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
187 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400188 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500189 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400190
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400191 /**
192 * Retest network to see if captive portal is still in place.
193 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
194 * 0 indicates self-initiated, so nobody to blame.
195 */
196 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
197
Paul Jensenca8f16a2014-05-09 12:47:55 -0400198 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400199 // Default to 30s linger time-out. Modifyable only for testing.
200 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400201 private final int mLingerDelayMs;
202 private int mLingerToken = 0;
203
Paul Jensend0491e9a2015-05-05 14:52:22 -0400204 // Start mReevaluateDelayMs at this value and double.
205 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
206 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
207 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
208 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400209 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400210 private static final int INVALID_UID = -1;
211 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400212 // Stop blaming UID that requested re-evaluation after this many attempts.
213 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400214 // Delay between reevaluations once a captive portal has been found.
215 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400216
217 private final Context mContext;
218 private final Handler mConnectivityServiceHandler;
219 private final NetworkAgentInfo mNetworkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400220 private final TelephonyManager mTelephonyManager;
221 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400222 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500223 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400224
225 private String mServer;
226 private boolean mIsCaptivePortalCheckEnabled = false;
227
Paul Jensenad50a1f2014-09-05 12:06:44 -0400228 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
229 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400230 // Avoids surfacing "Sign in to network" notification.
231 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400232
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700233 public boolean systemReady = false;
234
Paul Jensen71b645f2014-10-13 14:13:07 -0400235 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400236 private final State mValidatedState = new ValidatedState();
237 private final State mMaybeNotifyState = new MaybeNotifyState();
238 private final State mEvaluatingState = new EvaluatingState();
239 private final State mCaptivePortalState = new CaptivePortalState();
240 private final State mLingeringState = new LingeringState();
241
Paul Jensen25a217c2015-02-27 22:55:47 -0500242 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400243
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700244 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
245
Paul Jensen2c311d62014-11-17 12:34:51 -0500246 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
247 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400248 // Add suffix indicating which NetworkMonitor we're talking about.
249 super(TAG + networkAgentInfo.name());
250
251 mContext = context;
252 mConnectivityServiceHandler = handler;
253 mNetworkAgentInfo = networkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400254 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
255 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400256 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500257 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400258
259 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400260 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400261 addState(mMaybeNotifyState, mDefaultState);
262 addState(mEvaluatingState, mMaybeNotifyState);
263 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400264 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700265 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400266
267 mServer = Settings.Global.getString(mContext.getContentResolver(),
268 Settings.Global.CAPTIVE_PORTAL_SERVER);
269 if (mServer == null) mServer = DEFAULT_SERVER;
270
271 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400272
Paul Jensen869868be2014-05-15 10:33:05 -0400273 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
274 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400275
276 start();
277 }
278
Paul Jensen532b61432014-11-10 09:50:02 -0500279 @Override
280 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400281 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500282 }
283
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700284 private void validationLog(String s) {
285 if (DBG) log(s);
286 validationLogs.log(s);
287 }
288
289 public ReadOnlyLocalLog getValidationLogs() {
290 return validationLogs.readOnlyLocalLog();
291 }
292
Paul Jensen71b645f2014-10-13 14:13:07 -0400293 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
294 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400295 private class DefaultState extends State {
296 @Override
297 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400298 switch (message.what) {
299 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400300 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400301 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400302 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400303 case CMD_NETWORK_CONNECTED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400304 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400305 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400306 case CMD_NETWORK_DISCONNECTED:
Paul Jensen25a217c2015-02-27 22:55:47 -0500307 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
308 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
309 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400310 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700311 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400312 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400313 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400314 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400315 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400316 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400317 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400318 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400319 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400320 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen71b645f2014-10-13 14:13:07 -0400321 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400322 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400323 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500324 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400325 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400326 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500327 // TODO: Distinguish this from a network that actually validates.
328 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400329 transitionTo(mValidatedState);
330 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400331 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400332 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400333 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400334 mConnectivityServiceHandler.sendMessage(obtainMessage(
335 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
336 mNetworkAgentInfo));
Paul Jensen71b645f2014-10-13 14:13:07 -0400337 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400338 mUidResponsibleForReeval = 0;
339 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400340 break;
341 }
342 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400343 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400344 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400345 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400346 }
347 }
348
Paul Jensen71b645f2014-10-13 14:13:07 -0400349 // Being in the ValidatedState State indicates a Network is:
350 // - Successfully validated, or
351 // - Wanted "as is" by the user, or
352 // - Does not satsify the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400353 private class ValidatedState extends State {
354 @Override
355 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400356 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
357 NETWORK_TEST_RESULT_VALID, 0, mNetworkAgentInfo));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400358 }
359
360 @Override
361 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400362 switch (message.what) {
363 case CMD_NETWORK_CONNECTED:
364 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400365 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400366 default:
367 return NOT_HANDLED;
368 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400369 }
370 }
371
Paul Jensen71b645f2014-10-13 14:13:07 -0400372 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
373 // is required. This State takes care to clear the notification upon exit from the State.
374 private class MaybeNotifyState extends State {
375 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500376 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500377 switch (message.what) {
378 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
379 final Intent intent = new Intent(
380 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
381 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400382 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
383 new CaptivePortal(new ICaptivePortal.Stub() {
384 @Override
385 public void appResponse(int response) {
386 if (response == APP_RETURN_WANTED_AS_IS) {
387 mContext.enforceCallingPermission(
388 android.Manifest.permission.CONNECTIVITY_INTERNAL,
389 "CaptivePortal");
390 }
391 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
392 }
393 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500394 intent.setFlags(
395 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
396 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
397 return HANDLED;
398 default:
399 return NOT_HANDLED;
400 }
401 }
402
403 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400404 public void exit() {
405 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
406 mNetworkAgentInfo.network.netId, null);
407 mConnectivityServiceHandler.sendMessage(message);
408 }
409 }
410
411 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400412 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400413 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400414 private int mReevaluateDelayMs;
415 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400416
Paul Jensenca8f16a2014-05-09 12:47:55 -0400417 @Override
418 public void enter() {
419 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400420 if (mUidResponsibleForReeval != INVALID_UID) {
421 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
422 mUidResponsibleForReeval = INVALID_UID;
423 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400424 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
425 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400426 }
427
428 @Override
429 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400430 switch (message.what) {
431 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400432 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400433 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500434 // Don't bother validating networks that don't satisify the default request.
435 // This includes:
436 // - VPNs which can be considered explicitly desired by the user and the
437 // user's desire trumps whether the network validates.
438 // - Networks that don't provide internet access. It's unclear how to
439 // validate such networks.
440 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
441 // such networks and the user didn't express interest in connecting to
442 // such networks (an app did) so the user may be unhappily surprised when
443 // asked to sign-in to a network they didn't want to connect to in the
444 // first place. Validation could be done to adjust the network scores
445 // however these networks are app-requested and may not be intended for
446 // general usage, in which case general validation may not be an accurate
447 // measure of the network's quality. Only the app knows how to evaluate
448 // the network so don't bother validating here. Furthermore sending HTTP
449 // packets over the network may be undesirable, for example an extremely
450 // expensive metered network, or unwanted leaking of the User Agent string.
451 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
452 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400453 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400454 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400455 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400456 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900457 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
458 // server's IP addresses could hit the DNS timeout, and attempting connections
459 // to each of the server's several IP addresses (currently one IPv4 and one
460 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
461 // will be unresponsive. isCaptivePortal() could be executed on another Thread
462 // if this is found to cause problems.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400463 int httpResponseCode = isCaptivePortal();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400464 if (httpResponseCode == 204) {
465 transitionTo(mValidatedState);
466 } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400467 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400468 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400469 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400470 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensend9be23f2015-05-19 14:51:47 -0400471 mConnectivityServiceHandler.sendMessage(obtainMessage(
472 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
473 mNetworkAgentInfo));
474 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400475 // Don't continue to blame UID forever.
476 TrafficStats.clearThreadStatsUid();
477 }
478 mReevaluateDelayMs *= 2;
479 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
480 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
481 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400482 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400483 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400484 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400485 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
486 // ignore any re-evaluation requests. After, restart the
487 // evaluation process via EvaluatingState#enter.
488 return mAttempts < IGNORE_REEVALUATE_ATTEMPTS ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400489 default:
490 return NOT_HANDLED;
491 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400492 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400493
494 @Override
495 public void exit() {
496 TrafficStats.clearThreadStatsUid();
497 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400498 }
499
Paul Jensendcbe8352014-09-16 16:28:34 -0400500 // BroadcastReceiver that waits for a particular Intent and then posts a message.
501 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400502 private final int mToken;
503 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400504 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400505 CustomIntentReceiver(String action, int token, int what) {
506 mToken = token;
507 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400508 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
509 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400510 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400511 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500512 final Intent intent = new Intent(mAction);
513 intent.setPackage(mContext.getPackageName());
514 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400515 }
516 @Override
517 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400518 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400519 }
520 }
Paul Jensen869868be2014-05-15 10:33:05 -0400521
Paul Jensen71b645f2014-10-13 14:13:07 -0400522 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
523 // has been shown a notification to sign-in.
524 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500525 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
526 "android.net.netmon.launchCaptivePortalApp";
527
Paul Jensen869868be2014-05-15 10:33:05 -0400528 @Override
529 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400530 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
531 NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400532 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400533 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500534 // Create a CustomIntentReceiver that sends us a
535 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
536 // touches the notification.
537 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400538 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500539 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
540 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
541 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400542 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500543 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400544 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
545 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500546 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400547 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400548 // Retest for captive portal occasionally.
549 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
550 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400551 }
552
553 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400554 public void exit() {
555 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
556 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400557 }
558
Paul Jensen71b645f2014-10-13 14:13:07 -0400559 // Being in the LingeringState State indicates a Network's validated bit is true and it once
560 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
561 // another Network satsified the NetworkRequest with a higher score and hence this Network
562 // is "lingered" for a fixed period of time before it is disconnected. This period of time
563 // allows apps to wrap up communication and allows for seamless reactivation if the other
564 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400565 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400566 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400567
Paul Jensendcbe8352014-09-16 16:28:34 -0400568 private CustomIntentReceiver mBroadcastReceiver;
Paul Jensen79a08052014-08-21 12:44:07 -0400569 private PendingIntent mIntent;
570
Paul Jensenca8f16a2014-05-09 12:47:55 -0400571 @Override
572 public void enter() {
Paul Jensen71b645f2014-10-13 14:13:07 -0400573 mLingerToken = new Random().nextInt();
574 mBroadcastReceiver = new CustomIntentReceiver(ACTION_LINGER_EXPIRED, mLingerToken,
Paul Jensendcbe8352014-09-16 16:28:34 -0400575 CMD_LINGER_EXPIRED);
576 mIntent = mBroadcastReceiver.getPendingIntent();
Paul Jensen79a08052014-08-21 12:44:07 -0400577 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
578 mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime,
579 // Give a specific window so we aren't subject to unknown inexactitude.
580 mLingerDelayMs / 6, mIntent);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400581 }
582
583 @Override
584 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400585 switch (message.what) {
586 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400587 log("Unlingered");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400588 // Go straight to active as we've already evaluated.
589 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400590 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400591 case CMD_LINGER_EXPIRED:
592 if (message.arg1 != mLingerToken)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400593 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400594 mConnectivityServiceHandler.sendMessage(
595 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400596 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400597 case CMD_FORCE_REEVALUATION:
598 // Ignore reevaluation attempts when lingering. A reevaluation could result
599 // in a transition to the validated state which would abort the linger
600 // timeout. Lingering is the result of score assessment; validity is
601 // irrelevant.
602 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400603 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
604 // Ignore user network determination as this could abort linger timeout.
605 // Networks are only lingered once validated because:
606 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
607 // - Once validated, a Network's validated bit is never cleared.
608 // Since networks are only lingered after being validated a user's
609 // determination will not change the death sentence that lingering entails:
610 // - If the user wants to use the network or bypasses the captive portal,
611 // the network's score will not be increased beyond its current value
612 // because it is already validated. Without a score increase there is no
613 // chance of reactivation (i.e. aborting linger timeout).
614 // - If the user does not want the network, lingering will disconnect the
615 // network anyhow.
616 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400617 default:
618 return NOT_HANDLED;
619 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400620 }
Paul Jensen79a08052014-08-21 12:44:07 -0400621
622 @Override
623 public void exit() {
624 mAlarmManager.cancel(mIntent);
625 mContext.unregisterReceiver(mBroadcastReceiver);
626 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400627 }
628
629 /**
630 * Do a URL fetch on a known server to see if we get the data we expect.
631 * Returns HTTP response code.
632 */
633 private int isCaptivePortal() {
634 if (!mIsCaptivePortalCheckEnabled) return 204;
635
Paul Jensenca8f16a2014-05-09 12:47:55 -0400636 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400637 int httpResponseCode = 599;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400638 try {
Paul Jensene547ff22014-08-04 09:12:24 -0400639 URL url = new URL("http", mServer, "/generate_204");
Paul Jensen8fe17422015-02-02 11:03:03 -0500640 // On networks with a PAC instead of fetching a URL that should result in a 204
641 // reponse, we instead simply fetch the PAC script. This is done for a few reasons:
642 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
643 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
644 // Network.openConnection() will ignore network-specific PACs and instead fetch
645 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
646 // NO_PROXY is the fetch of the PAC itself.
647 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
648 // happen before the fetch can commence, namely:
649 // a) the PAC script be fetched
650 // b) a PAC script resolver service be fired up and resolve mServer
651 // Network validation could be delayed until these prerequisities are satisifed or
652 // could simply be left to race them. Neither is an optimal solution.
653 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
654 // fact block fetching of the generate_204 URL which would lead to false negative
655 // results for network validation.
656 boolean fetchPac = false;
Paul Jensen2f0a8972015-06-25 10:07:14 -0400657 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
658 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
659 url = new URL(proxyInfo.getPacFileUrl().toString());
660 fetchPac = true;
661 }
662 final StringBuffer connectInfo = new StringBuffer();
663 String hostToResolve = null;
664 // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
665 // unnecessary resolution.
666 if (proxyInfo == null || fetchPac) {
667 hostToResolve = url.getHost();
668 } else if (proxyInfo != null) {
669 hostToResolve = proxyInfo.getHost();
670 }
671 if (!TextUtils.isEmpty(hostToResolve)) {
672 connectInfo.append(", " + hostToResolve + "=");
673 final InetAddress[] addresses =
674 mNetworkAgentInfo.network.getAllByName(hostToResolve);
675 for (InetAddress address : addresses) {
676 connectInfo.append(address.getHostAddress());
677 if (address != addresses[addresses.length-1]) connectInfo.append(",");
Paul Jensen8fe17422015-02-02 11:03:03 -0500678 }
679 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700680 validationLog("Checking " + url.toString() + " on " +
Paul Jensen2f0a8972015-06-25 10:07:14 -0400681 mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700682 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500683 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400684 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
685 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
686 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400687
688 // Time how long it takes to get a response to our request
689 long requestTimestamp = SystemClock.elapsedRealtime();
690
Paul Jensene547ff22014-08-04 09:12:24 -0400691 urlConnection.getInputStream();
Paul Jensen306f1a42014-08-04 10:59:01 -0400692
693 // Time how long it takes to get a response to our request
694 long responseTimestamp = SystemClock.elapsedRealtime();
695
Paul Jensene547ff22014-08-04 09:12:24 -0400696 httpResponseCode = urlConnection.getResponseCode();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700697 validationLog("isCaptivePortal: ret=" + httpResponseCode +
698 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400699 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
700 // portal. The only example of this seen so far was a captive portal. For
701 // the time being go with prior behavior of assuming it's not a captive
702 // portal. If it is considered a captive portal, a different sign-in URL
703 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
704 // proxy server.
705
706 // Consider 200 response with "Content-length=0" to not be a captive portal.
707 // There's no point in considering this a captive portal as the user cannot
708 // sign-in to an empty page. Probably the result of a broken transparent proxy.
709 // See http://b/9972012.
710 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700711 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400712 httpResponseCode = 204;
713 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400714
Paul Jensen8fe17422015-02-02 11:03:03 -0500715 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700716 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500717 httpResponseCode = 204;
718 }
719
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800720 sendNetworkConditionsBroadcast(true /* response received */,
721 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400722 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400723 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700724 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400725 if (httpResponseCode == 599) {
726 // TODO: Ping gateway and DNS server and log results.
727 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400728 } finally {
729 if (urlConnection != null) {
730 urlConnection.disconnect();
731 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400732 }
733 return httpResponseCode;
734 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400735
736 /**
737 * @param responseReceived - whether or not we received a valid HTTP response to our request.
738 * If false, isCaptivePortal and responseTimestampMs are ignored
739 * TODO: This should be moved to the transports. The latency could be passed to the transports
740 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
741 * perhaps this could just be added to the WiFi transport only.
742 */
743 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
744 long requestTimestampMs, long responseTimestampMs) {
745 if (Settings.Global.getInt(mContext.getContentResolver(),
746 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400747 return;
748 }
749
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700750 if (systemReady == false) return;
751
Paul Jensen306f1a42014-08-04 10:59:01 -0400752 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
753 switch (mNetworkAgentInfo.networkInfo.getType()) {
754 case ConnectivityManager.TYPE_WIFI:
755 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
756 if (currentWifiInfo != null) {
757 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
758 // surrounded by double quotation marks (thus violating the Javadoc), but this
759 // was changed to match the Javadoc in API 17. Since clients may have started
760 // sanitizing the output of this method since API 17 was released, we should
761 // not change it here as it would become impossible to tell whether the SSID is
762 // simply being surrounded by quotes due to the API, or whether those quotes
763 // are actually part of the SSID.
764 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
765 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
766 } else {
767 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
768 return;
769 }
770 break;
771 case ConnectivityManager.TYPE_MOBILE:
772 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
773 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
774 if (info == null) return;
775 int numRegisteredCellInfo = 0;
776 for (CellInfo cellInfo : info) {
777 if (cellInfo.isRegistered()) {
778 numRegisteredCellInfo++;
779 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400780 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400781 "tell which is active. Bailing.");
782 return;
783 }
784 if (cellInfo instanceof CellInfoCdma) {
785 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
786 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
787 } else if (cellInfo instanceof CellInfoGsm) {
788 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
789 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
790 } else if (cellInfo instanceof CellInfoLte) {
791 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
792 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
793 } else if (cellInfo instanceof CellInfoWcdma) {
794 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
795 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
796 } else {
797 if (DBG) logw("Registered cellinfo is unrecognized");
798 return;
799 }
800 }
801 }
802 break;
803 default:
804 return;
805 }
806 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
807 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
808 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
809
810 if (responseReceived) {
811 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
812 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
813 }
Paul Jensen55298582014-08-20 11:01:41 -0400814 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
815 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400816 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400817
818 // Allow tests to override linger time.
819 @VisibleForTesting
820 public static void SetDefaultLingerTime(int time_ms) {
821 if (Process.myUid() == Process.SYSTEM_UID) {
822 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
823 }
824 DEFAULT_LINGER_DELAY_MS = time_ms;
825 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400826}