blob: 3a10dbe3fc5054f1722e6f4a296ca827ca4a8e5a [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;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +090065import com.android.internal.util.WakeupMessage;
Paul Jensenca8f16a2014-05-09 12:47:55 -040066import com.android.server.connectivity.NetworkAgentInfo;
67
Paul Jensenca8f16a2014-05-09 12:47:55 -040068import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040069import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040070import java.net.InetAddress;
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040072import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040073import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040074
75/**
76 * {@hide}
77 */
78public class NetworkMonitor extends StateMachine {
79 private static final boolean DBG = true;
80 private static final String TAG = "NetworkMonitor";
Erik Klinee7d01792015-07-20 23:37:15 +090081 private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040082 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040083 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
84 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
85 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
86 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
87 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
88 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
89 public static final String EXTRA_CELL_ID = "extra_cellid";
90 public static final String EXTRA_SSID = "extra_ssid";
91 public static final String EXTRA_BSSID = "extra_bssid";
92 /** real time since boot */
93 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
94 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
95
96 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
97 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -040098
Paul Jensenad50a1f2014-09-05 12:06:44 -040099 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
100 // The network should be used as a default internet connection. It was found to be:
101 // 1. a functioning network providing internet access, or
102 // 2. a captive portal and the user decided to use it as is.
103 public static final int NETWORK_TEST_RESULT_VALID = 0;
104 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
105 // The network should not be used as a default internet connection. It was found to be:
106 // 1. a captive portal and the user is prompted to sign-in, or
107 // 2. a captive portal and the user did not want to use it, or
108 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
109 public static final int NETWORK_TEST_RESULT_INVALID = 1;
110
Paul Jensenca8f16a2014-05-09 12:47:55 -0400111 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
112
113 /**
114 * Inform NetworkMonitor that their network is connected.
115 * Initiates Network Validation.
116 */
117 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
118
119 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400120 * Inform ConnectivityService that the network has been tested.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400121 * obj = NetworkAgentInfo
Paul Jensenad50a1f2014-09-05 12:06:44 -0400122 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400123 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400124 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400125
126 /**
127 * Inform NetworkMonitor to linger a network. The Monitor should
128 * start a timer and/or start watching for zero live connections while
129 * moving towards LINGER_COMPLETE. After the Linger period expires
130 * (or other events mark the end of the linger state) the LINGER_COMPLETE
131 * event should be sent and the network will be shut down. If a
132 * CMD_NETWORK_CONNECTED happens before the LINGER completes
133 * it indicates further desire to keep the network alive and so
134 * the LINGER is aborted.
135 */
136 public static final int CMD_NETWORK_LINGER = BASE + 3;
137
138 /**
139 * Message to self indicating linger delay has expired.
140 * arg1 = Token to ignore old messages.
141 */
142 private static final int CMD_LINGER_EXPIRED = BASE + 4;
143
144 /**
145 * Inform ConnectivityService that the network LINGER period has
146 * expired.
147 * obj = NetworkAgentInfo
148 */
149 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
150
151 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400152 * Message to self indicating it's time to evaluate a network's connectivity.
153 * arg1 = Token to ignore old messages.
154 */
Paul Jensen869868be2014-05-15 10:33:05 -0400155 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400156
157 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400158 * Inform NetworkMonitor that the network has disconnected.
159 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400160 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400161
162 /**
163 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400164 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400165 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400166 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400167
168 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400169 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400170 * arg1 = one of: APP_RETURN_DISMISSED,
171 * APP_RETURN_UNWANTED,
172 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500173 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400174 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400175 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400176
177 /**
178 * Request ConnectivityService display provisioning notification.
179 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400180 * arg2 = NetID.
181 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400182 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400183 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400184
185 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500186 * Message to self indicating sign-in app should be launched.
187 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
188 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400189 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500190 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400191
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400192 /**
193 * Retest network to see if captive portal is still in place.
194 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
195 * 0 indicates self-initiated, so nobody to blame.
196 */
197 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
198
Paul Jensenca8f16a2014-05-09 12:47:55 -0400199 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400200 // Default to 30s linger time-out. Modifyable only for testing.
201 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400202 private final int mLingerDelayMs;
203 private int mLingerToken = 0;
204
Paul Jensend0491e9a2015-05-05 14:52:22 -0400205 // Start mReevaluateDelayMs at this value and double.
206 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
207 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
208 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
209 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400210 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400211 private static final int INVALID_UID = -1;
212 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400213 // Stop blaming UID that requested re-evaluation after this many attempts.
214 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400215 // Delay between reevaluations once a captive portal has been found.
216 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400217
218 private final Context mContext;
219 private final Handler mConnectivityServiceHandler;
220 private final NetworkAgentInfo mNetworkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400221 private final TelephonyManager mTelephonyManager;
222 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400223 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500224 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400225
226 private String mServer;
227 private boolean mIsCaptivePortalCheckEnabled = false;
228
Paul Jensenad50a1f2014-09-05 12:06:44 -0400229 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
230 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400231 // Avoids surfacing "Sign in to network" notification.
232 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400233
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700234 public boolean systemReady = false;
235
Paul Jensen71b645f2014-10-13 14:13:07 -0400236 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400237 private final State mValidatedState = new ValidatedState();
238 private final State mMaybeNotifyState = new MaybeNotifyState();
239 private final State mEvaluatingState = new EvaluatingState();
240 private final State mCaptivePortalState = new CaptivePortalState();
241 private final State mLingeringState = new LingeringState();
242
Paul Jensen25a217c2015-02-27 22:55:47 -0500243 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400244
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700245 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
246
Paul Jensen2c311d62014-11-17 12:34:51 -0500247 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
248 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400249 // Add suffix indicating which NetworkMonitor we're talking about.
250 super(TAG + networkAgentInfo.name());
251
252 mContext = context;
253 mConnectivityServiceHandler = handler;
254 mNetworkAgentInfo = networkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400255 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
256 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400257 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500258 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400259
260 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400261 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400262 addState(mMaybeNotifyState, mDefaultState);
263 addState(mEvaluatingState, mMaybeNotifyState);
264 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400265 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700266 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400267
268 mServer = Settings.Global.getString(mContext.getContentResolver(),
269 Settings.Global.CAPTIVE_PORTAL_SERVER);
270 if (mServer == null) mServer = DEFAULT_SERVER;
271
272 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400273
Paul Jensen869868be2014-05-15 10:33:05 -0400274 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
275 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400276
277 start();
278 }
279
Paul Jensen532b61432014-11-10 09:50:02 -0500280 @Override
281 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400282 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500283 }
284
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700285 private void validationLog(String s) {
286 if (DBG) log(s);
287 validationLogs.log(s);
288 }
289
290 public ReadOnlyLocalLog getValidationLogs() {
291 return validationLogs.readOnlyLocalLog();
292 }
293
Paul Jensen71b645f2014-10-13 14:13:07 -0400294 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
295 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400296 private class DefaultState extends State {
297 @Override
298 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400299 switch (message.what) {
300 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400301 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400302 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400303 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400304 case CMD_NETWORK_CONNECTED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400305 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400306 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400307 case CMD_NETWORK_DISCONNECTED:
Paul Jensen25a217c2015-02-27 22:55:47 -0500308 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
309 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
310 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400311 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700312 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400313 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400314 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400315 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400316 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400317 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400318 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400319 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400320 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400321 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen71b645f2014-10-13 14:13:07 -0400322 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400323 case 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;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400326 case 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 Jensen49e3edf2015-05-22 10:50:39 -0400332 case 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
Paul Jensencf4c2c62015-07-01 14:16:32 -0400353 // - Does not satisfy 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);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400383 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
384 new CaptivePortal(new ICaptivePortal.Stub() {
385 @Override
386 public void appResponse(int response) {
387 if (response == APP_RETURN_WANTED_AS_IS) {
388 mContext.enforceCallingPermission(
389 android.Manifest.permission.CONNECTIVITY_INTERNAL,
390 "CaptivePortal");
391 }
392 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
393 }
394 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500395 intent.setFlags(
396 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
397 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
398 return HANDLED;
399 default:
400 return NOT_HANDLED;
401 }
402 }
403
404 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400405 public void exit() {
406 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
407 mNetworkAgentInfo.network.netId, null);
408 mConnectivityServiceHandler.sendMessage(message);
409 }
410 }
411
412 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400413 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400414 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400415 private int mReevaluateDelayMs;
416 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400417
Paul Jensenca8f16a2014-05-09 12:47:55 -0400418 @Override
419 public void enter() {
420 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400421 if (mUidResponsibleForReeval != INVALID_UID) {
422 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
423 mUidResponsibleForReeval = INVALID_UID;
424 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400425 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
426 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400427 }
428
429 @Override
430 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400431 switch (message.what) {
432 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400433 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400434 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500435 // Don't bother validating networks that don't satisify the default request.
436 // This includes:
437 // - VPNs which can be considered explicitly desired by the user and the
438 // user's desire trumps whether the network validates.
439 // - Networks that don't provide internet access. It's unclear how to
440 // validate such networks.
441 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
442 // such networks and the user didn't express interest in connecting to
443 // such networks (an app did) so the user may be unhappily surprised when
444 // asked to sign-in to a network they didn't want to connect to in the
445 // first place. Validation could be done to adjust the network scores
446 // however these networks are app-requested and may not be intended for
447 // general usage, in which case general validation may not be an accurate
448 // measure of the network's quality. Only the app knows how to evaluate
449 // the network so don't bother validating here. Furthermore sending HTTP
450 // packets over the network may be undesirable, for example an extremely
451 // expensive metered network, or unwanted leaking of the User Agent string.
452 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
453 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400454 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400455 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400456 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400457 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900458 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
459 // server's IP addresses could hit the DNS timeout, and attempting connections
460 // to each of the server's several IP addresses (currently one IPv4 and one
461 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
462 // will be unresponsive. isCaptivePortal() could be executed on another Thread
463 // if this is found to cause problems.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400464 int httpResponseCode = isCaptivePortal();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400465 if (httpResponseCode == 204) {
466 transitionTo(mValidatedState);
467 } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400468 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400469 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400470 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400471 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensend9be23f2015-05-19 14:51:47 -0400472 mConnectivityServiceHandler.sendMessage(obtainMessage(
473 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
474 mNetworkAgentInfo));
475 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400476 // Don't continue to blame UID forever.
477 TrafficStats.clearThreadStatsUid();
478 }
479 mReevaluateDelayMs *= 2;
480 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
481 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
482 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400483 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400484 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400485 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400486 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
487 // ignore any re-evaluation requests. After, restart the
488 // evaluation process via EvaluatingState#enter.
489 return mAttempts < IGNORE_REEVALUATE_ATTEMPTS ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400490 default:
491 return NOT_HANDLED;
492 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400493 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400494
495 @Override
496 public void exit() {
497 TrafficStats.clearThreadStatsUid();
498 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400499 }
500
Paul Jensendcbe8352014-09-16 16:28:34 -0400501 // BroadcastReceiver that waits for a particular Intent and then posts a message.
502 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400503 private final int mToken;
504 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400505 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400506 CustomIntentReceiver(String action, int token, int what) {
507 mToken = token;
508 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400509 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
510 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400511 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400512 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500513 final Intent intent = new Intent(mAction);
514 intent.setPackage(mContext.getPackageName());
515 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400516 }
517 @Override
518 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400519 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400520 }
521 }
Paul Jensen869868be2014-05-15 10:33:05 -0400522
Paul Jensen71b645f2014-10-13 14:13:07 -0400523 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
524 // has been shown a notification to sign-in.
525 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500526 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
527 "android.net.netmon.launchCaptivePortalApp";
528
Paul Jensen869868be2014-05-15 10:33:05 -0400529 @Override
530 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400531 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
532 NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400533 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400534 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500535 // Create a CustomIntentReceiver that sends us a
536 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
537 // touches the notification.
538 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400539 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500540 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
541 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
542 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400543 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500544 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400545 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
546 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500547 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400548 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400549 // Retest for captive portal occasionally.
550 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
551 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400552 }
553
554 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400555 public void exit() {
556 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
557 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400558 }
559
Paul Jensen71b645f2014-10-13 14:13:07 -0400560 // Being in the LingeringState State indicates a Network's validated bit is true and it once
561 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
Paul Jensencf4c2c62015-07-01 14:16:32 -0400562 // another Network satisfied the NetworkRequest with a higher score and hence this Network
Paul Jensen71b645f2014-10-13 14:13:07 -0400563 // is "lingered" for a fixed period of time before it is disconnected. This period of time
564 // allows apps to wrap up communication and allows for seamless reactivation if the other
565 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400566 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400567 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400568
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900569 private WakeupMessage mWakeupMessage;
Paul Jensen79a08052014-08-21 12:44:07 -0400570
Paul Jensenca8f16a2014-05-09 12:47:55 -0400571 @Override
572 public void enter() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900573 final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetworkAgentInfo.network.netId;
574 mWakeupMessage = new WakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
Paul Jensen79a08052014-08-21 12:44:07 -0400575 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900576 mWakeupMessage.schedule(wakeupTime);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400577 }
578
579 @Override
580 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400581 switch (message.what) {
582 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400583 log("Unlingered");
Paul Jensene0988542015-06-25 15:30:08 -0400584 // If already validated, go straight to validated state.
585 if (mNetworkAgentInfo.lastValidated) {
586 transitionTo(mValidatedState);
587 return HANDLED;
588 }
589 return NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400590 case CMD_LINGER_EXPIRED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400591 mConnectivityServiceHandler.sendMessage(
592 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400593 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400594 case CMD_FORCE_REEVALUATION:
595 // Ignore reevaluation attempts when lingering. A reevaluation could result
596 // in a transition to the validated state which would abort the linger
597 // timeout. Lingering is the result of score assessment; validity is
598 // irrelevant.
599 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400600 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
601 // Ignore user network determination as this could abort linger timeout.
602 // Networks are only lingered once validated because:
603 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
604 // - Once validated, a Network's validated bit is never cleared.
605 // Since networks are only lingered after being validated a user's
606 // determination will not change the death sentence that lingering entails:
607 // - If the user wants to use the network or bypasses the captive portal,
608 // the network's score will not be increased beyond its current value
609 // because it is already validated. Without a score increase there is no
610 // chance of reactivation (i.e. aborting linger timeout).
611 // - If the user does not want the network, lingering will disconnect the
612 // network anyhow.
613 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400614 default:
615 return NOT_HANDLED;
616 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400617 }
Paul Jensen79a08052014-08-21 12:44:07 -0400618
619 @Override
620 public void exit() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900621 mWakeupMessage.cancel();
Paul Jensen79a08052014-08-21 12:44:07 -0400622 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400623 }
624
625 /**
626 * Do a URL fetch on a known server to see if we get the data we expect.
627 * Returns HTTP response code.
628 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400629 @VisibleForTesting
630 protected int isCaptivePortal() {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400631 if (!mIsCaptivePortalCheckEnabled) return 204;
632
Paul Jensenca8f16a2014-05-09 12:47:55 -0400633 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400634 int httpResponseCode = 599;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400635 try {
Paul Jensene547ff22014-08-04 09:12:24 -0400636 URL url = new URL("http", mServer, "/generate_204");
Paul Jensen8fe17422015-02-02 11:03:03 -0500637 // On networks with a PAC instead of fetching a URL that should result in a 204
638 // reponse, we instead simply fetch the PAC script. This is done for a few reasons:
639 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
640 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
641 // Network.openConnection() will ignore network-specific PACs and instead fetch
642 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
643 // NO_PROXY is the fetch of the PAC itself.
644 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
645 // happen before the fetch can commence, namely:
646 // a) the PAC script be fetched
647 // b) a PAC script resolver service be fired up and resolve mServer
648 // Network validation could be delayed until these prerequisities are satisifed or
649 // could simply be left to race them. Neither is an optimal solution.
650 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
651 // fact block fetching of the generate_204 URL which would lead to false negative
652 // results for network validation.
653 boolean fetchPac = false;
Paul Jensen2f0a8972015-06-25 10:07:14 -0400654 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
655 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
656 url = new URL(proxyInfo.getPacFileUrl().toString());
657 fetchPac = true;
658 }
659 final StringBuffer connectInfo = new StringBuffer();
660 String hostToResolve = null;
661 // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
662 // unnecessary resolution.
663 if (proxyInfo == null || fetchPac) {
664 hostToResolve = url.getHost();
665 } else if (proxyInfo != null) {
666 hostToResolve = proxyInfo.getHost();
667 }
668 if (!TextUtils.isEmpty(hostToResolve)) {
669 connectInfo.append(", " + hostToResolve + "=");
670 final InetAddress[] addresses =
671 mNetworkAgentInfo.network.getAllByName(hostToResolve);
672 for (InetAddress address : addresses) {
673 connectInfo.append(address.getHostAddress());
674 if (address != addresses[addresses.length-1]) connectInfo.append(",");
Paul Jensen8fe17422015-02-02 11:03:03 -0500675 }
676 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700677 validationLog("Checking " + url.toString() + " on " +
Paul Jensen2f0a8972015-06-25 10:07:14 -0400678 mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700679 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500680 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400681 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
682 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
683 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400684
685 // Time how long it takes to get a response to our request
686 long requestTimestamp = SystemClock.elapsedRealtime();
687
Paul Jensene547ff22014-08-04 09:12:24 -0400688 urlConnection.getInputStream();
Paul Jensen306f1a42014-08-04 10:59:01 -0400689
690 // Time how long it takes to get a response to our request
691 long responseTimestamp = SystemClock.elapsedRealtime();
692
Paul Jensene547ff22014-08-04 09:12:24 -0400693 httpResponseCode = urlConnection.getResponseCode();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700694 validationLog("isCaptivePortal: ret=" + httpResponseCode +
695 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400696 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
697 // portal. The only example of this seen so far was a captive portal. For
698 // the time being go with prior behavior of assuming it's not a captive
699 // portal. If it is considered a captive portal, a different sign-in URL
700 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
701 // proxy server.
702
703 // Consider 200 response with "Content-length=0" to not be a captive portal.
704 // There's no point in considering this a captive portal as the user cannot
705 // sign-in to an empty page. Probably the result of a broken transparent proxy.
706 // See http://b/9972012.
707 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700708 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400709 httpResponseCode = 204;
710 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400711
Paul Jensen8fe17422015-02-02 11:03:03 -0500712 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700713 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500714 httpResponseCode = 204;
715 }
716
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800717 sendNetworkConditionsBroadcast(true /* response received */,
718 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400719 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400720 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700721 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400722 if (httpResponseCode == 599) {
723 // TODO: Ping gateway and DNS server and log results.
724 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400725 } finally {
726 if (urlConnection != null) {
727 urlConnection.disconnect();
728 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400729 }
730 return httpResponseCode;
731 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400732
733 /**
734 * @param responseReceived - whether or not we received a valid HTTP response to our request.
735 * If false, isCaptivePortal and responseTimestampMs are ignored
736 * TODO: This should be moved to the transports. The latency could be passed to the transports
737 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
738 * perhaps this could just be added to the WiFi transport only.
739 */
740 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
741 long requestTimestampMs, long responseTimestampMs) {
742 if (Settings.Global.getInt(mContext.getContentResolver(),
743 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400744 return;
745 }
746
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700747 if (systemReady == false) return;
748
Paul Jensen306f1a42014-08-04 10:59:01 -0400749 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
750 switch (mNetworkAgentInfo.networkInfo.getType()) {
751 case ConnectivityManager.TYPE_WIFI:
752 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
753 if (currentWifiInfo != null) {
754 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
755 // surrounded by double quotation marks (thus violating the Javadoc), but this
756 // was changed to match the Javadoc in API 17. Since clients may have started
757 // sanitizing the output of this method since API 17 was released, we should
758 // not change it here as it would become impossible to tell whether the SSID is
759 // simply being surrounded by quotes due to the API, or whether those quotes
760 // are actually part of the SSID.
761 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
762 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
763 } else {
764 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
765 return;
766 }
767 break;
768 case ConnectivityManager.TYPE_MOBILE:
769 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
770 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
771 if (info == null) return;
772 int numRegisteredCellInfo = 0;
773 for (CellInfo cellInfo : info) {
774 if (cellInfo.isRegistered()) {
775 numRegisteredCellInfo++;
776 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400777 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400778 "tell which is active. Bailing.");
779 return;
780 }
781 if (cellInfo instanceof CellInfoCdma) {
782 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
783 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
784 } else if (cellInfo instanceof CellInfoGsm) {
785 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
786 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
787 } else if (cellInfo instanceof CellInfoLte) {
788 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
789 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
790 } else if (cellInfo instanceof CellInfoWcdma) {
791 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
792 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
793 } else {
794 if (DBG) logw("Registered cellinfo is unrecognized");
795 return;
796 }
797 }
798 }
799 break;
800 default:
801 return;
802 }
803 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
804 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
805 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
806
807 if (responseReceived) {
808 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
809 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
810 }
Paul Jensen55298582014-08-20 11:01:41 -0400811 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
812 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400813 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400814
815 // Allow tests to override linger time.
816 @VisibleForTesting
817 public static void SetDefaultLingerTime(int time_ms) {
818 if (Process.myUid() == Process.SYSTEM_UID) {
819 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
820 }
821 DEFAULT_LINGER_DELAY_MS = time_ms;
822 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400823}