blob: bbb162e7c16f4dc8341da88f0a363fbd8e28ee34 [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;
Pierre Imai55618be2016-02-19 15:25:54 +090037import android.net.metrics.CaptivePortalCheckResultEvent;
38import android.net.metrics.CaptivePortalStateChangeEvent;
Paul Jensen306f1a42014-08-04 10:59:01 -040039import android.net.wifi.WifiInfo;
40import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040041import android.os.Handler;
42import android.os.Message;
Paul Jensend7b6ca92015-05-13 14:05:12 -040043import android.os.Process;
Paul Jensen306f1a42014-08-04 10:59:01 -040044import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040045import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040046import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040047import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040048import android.telephony.CellIdentityCdma;
49import android.telephony.CellIdentityGsm;
50import android.telephony.CellIdentityLte;
51import android.telephony.CellIdentityWcdma;
52import android.telephony.CellInfo;
53import android.telephony.CellInfoCdma;
54import android.telephony.CellInfoGsm;
55import android.telephony.CellInfoLte;
56import android.telephony.CellInfoWcdma;
57import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040058import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070059import android.util.LocalLog;
60import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050061import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040062
Paul Jensend7b6ca92015-05-13 14:05:12 -040063import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040064import com.android.internal.util.Protocol;
65import com.android.internal.util.State;
66import com.android.internal.util.StateMachine;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +090067import com.android.internal.util.WakeupMessage;
Paul Jensenca8f16a2014-05-09 12:47:55 -040068import com.android.server.connectivity.NetworkAgentInfo;
69
Paul Jensenca8f16a2014-05-09 12:47:55 -040070import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040072import java.net.InetAddress;
Paul Jensenca8f16a2014-05-09 12:47:55 -040073import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040074import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040075import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040076
77/**
78 * {@hide}
79 */
80public class NetworkMonitor extends StateMachine {
Joe Onorato12acbd72016-02-01 17:49:31 -080081 private static final boolean DBG = false;
Paul Jensenca8f16a2014-05-09 12:47:55 -040082 private static final String TAG = "NetworkMonitor";
Erik Klinee7d01792015-07-20 23:37:15 +090083 private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040084 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040085 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
86 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
87 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
88 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
89 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
90 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
91 public static final String EXTRA_CELL_ID = "extra_cellid";
92 public static final String EXTRA_SSID = "extra_ssid";
93 public static final String EXTRA_BSSID = "extra_bssid";
94 /** real time since boot */
95 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
96 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
97
98 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
99 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400100
Paul Jensenad50a1f2014-09-05 12:06:44 -0400101 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
102 // The network should be used as a default internet connection. It was found to be:
103 // 1. a functioning network providing internet access, or
104 // 2. a captive portal and the user decided to use it as is.
105 public static final int NETWORK_TEST_RESULT_VALID = 0;
106 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
107 // The network should not be used as a default internet connection. It was found to be:
108 // 1. a captive portal and the user is prompted to sign-in, or
109 // 2. a captive portal and the user did not want to use it, or
110 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
111 public static final int NETWORK_TEST_RESULT_INVALID = 1;
112
Paul Jensenca8f16a2014-05-09 12:47:55 -0400113 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
114
115 /**
116 * Inform NetworkMonitor that their network is connected.
117 * Initiates Network Validation.
118 */
119 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
120
121 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400122 * Inform ConnectivityService that the network has been tested.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400123 * obj = NetworkAgentInfo
Paul Jensenad50a1f2014-09-05 12:06:44 -0400124 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400125 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400126 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127
128 /**
129 * Inform NetworkMonitor to linger a network. The Monitor should
130 * start a timer and/or start watching for zero live connections while
131 * moving towards LINGER_COMPLETE. After the Linger period expires
132 * (or other events mark the end of the linger state) the LINGER_COMPLETE
133 * event should be sent and the network will be shut down. If a
134 * CMD_NETWORK_CONNECTED happens before the LINGER completes
135 * it indicates further desire to keep the network alive and so
136 * the LINGER is aborted.
137 */
138 public static final int CMD_NETWORK_LINGER = BASE + 3;
139
140 /**
141 * Message to self indicating linger delay has expired.
142 * arg1 = Token to ignore old messages.
143 */
144 private static final int CMD_LINGER_EXPIRED = BASE + 4;
145
146 /**
147 * Inform ConnectivityService that the network LINGER period has
148 * expired.
149 * obj = NetworkAgentInfo
150 */
151 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
152
153 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400154 * Message to self indicating it's time to evaluate a network's connectivity.
155 * arg1 = Token to ignore old messages.
156 */
Paul Jensen869868be2014-05-15 10:33:05 -0400157 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400158
159 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400160 * Inform NetworkMonitor that the network has disconnected.
161 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400162 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400163
164 /**
165 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400166 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400167 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400168 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400169
170 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400171 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400172 * arg1 = one of: APP_RETURN_DISMISSED,
173 * APP_RETURN_UNWANTED,
174 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500175 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400176 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400177 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400178
179 /**
180 * Request ConnectivityService display provisioning notification.
181 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400182 * arg2 = NetID.
183 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400184 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400185 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400186
187 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500188 * Message to self indicating sign-in app should be launched.
189 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
190 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400191 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500192 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400193
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400194 /**
195 * Retest network to see if captive portal is still in place.
196 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
197 * 0 indicates self-initiated, so nobody to blame.
198 */
199 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
200
Paul Jensenca8f16a2014-05-09 12:47:55 -0400201 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400202 // Default to 30s linger time-out. Modifyable only for testing.
203 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400204 private final int mLingerDelayMs;
205 private int mLingerToken = 0;
206
Paul Jensend0491e9a2015-05-05 14:52:22 -0400207 // Start mReevaluateDelayMs at this value and double.
208 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
209 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
210 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
211 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400212 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400213 private static final int INVALID_UID = -1;
214 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400215 // Stop blaming UID that requested re-evaluation after this many attempts.
216 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400217 // Delay between reevaluations once a captive portal has been found.
218 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400219
220 private final Context mContext;
221 private final Handler mConnectivityServiceHandler;
222 private final NetworkAgentInfo mNetworkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400223 private final TelephonyManager mTelephonyManager;
224 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400225 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500226 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400227
Paul Jensenca8f16a2014-05-09 12:47:55 -0400228 private boolean mIsCaptivePortalCheckEnabled = false;
229
Paul Jensenad50a1f2014-09-05 12:06:44 -0400230 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
231 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400232 // Avoids surfacing "Sign in to network" notification.
233 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400234
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700235 public boolean systemReady = false;
236
Paul Jensen71b645f2014-10-13 14:13:07 -0400237 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400238 private final State mValidatedState = new ValidatedState();
239 private final State mMaybeNotifyState = new MaybeNotifyState();
240 private final State mEvaluatingState = new EvaluatingState();
241 private final State mCaptivePortalState = new CaptivePortalState();
242 private final State mLingeringState = new LingeringState();
243
Paul Jensen25a217c2015-02-27 22:55:47 -0500244 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400245
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700246 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
247
Paul Jensen2c311d62014-11-17 12:34:51 -0500248 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
249 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400250 // Add suffix indicating which NetworkMonitor we're talking about.
251 super(TAG + networkAgentInfo.name());
252
253 mContext = context;
254 mConnectivityServiceHandler = handler;
255 mNetworkAgentInfo = networkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400256 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
257 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400258 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500259 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400260
261 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400262 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400263 addState(mMaybeNotifyState, mDefaultState);
264 addState(mEvaluatingState, mMaybeNotifyState);
265 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400266 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700267 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400268
Paul Jensenca8f16a2014-05-09 12:47:55 -0400269 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400270
Paul Jensen869868be2014-05-15 10:33:05 -0400271 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
272 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400273
274 start();
275 }
276
Paul Jensen532b61432014-11-10 09:50:02 -0500277 @Override
278 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400279 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500280 }
281
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700282 private void validationLog(String s) {
283 if (DBG) log(s);
284 validationLogs.log(s);
285 }
286
287 public ReadOnlyLocalLog getValidationLogs() {
288 return validationLogs.readOnlyLocalLog();
289 }
290
Paul Jensen71b645f2014-10-13 14:13:07 -0400291 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
292 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400293 private class DefaultState extends State {
294 @Override
295 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400296 switch (message.what) {
297 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400298 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400299 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400300 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400301 case CMD_NETWORK_CONNECTED:
Pierre Imai55618be2016-02-19 15:25:54 +0900302 CaptivePortalStateChangeEvent.logEvent(
303 CaptivePortalStateChangeEvent.NETWORK_MONITOR_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:
Pierre Imai55618be2016-02-19 15:25:54 +0900307 CaptivePortalStateChangeEvent.logEvent(
308 CaptivePortalStateChangeEvent.NETWORK_MONITOR_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500309 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
310 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
311 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400312 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700313 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400314 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400315 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400316 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400317 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400318 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400319 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400320 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400321 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400322 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen71b645f2014-10-13 14:13:07 -0400323 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400324 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400325 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500326 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400327 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400328 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500329 // TODO: Distinguish this from a network that actually validates.
330 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400331 transitionTo(mValidatedState);
332 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400333 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400334 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400335 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400336 mConnectivityServiceHandler.sendMessage(obtainMessage(
337 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
338 mNetworkAgentInfo));
Paul Jensen71b645f2014-10-13 14:13:07 -0400339 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400340 mUidResponsibleForReeval = 0;
341 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400342 break;
343 }
344 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400345 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400346 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400347 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400348 }
349 }
350
Paul Jensen71b645f2014-10-13 14:13:07 -0400351 // Being in the ValidatedState State indicates a Network is:
352 // - Successfully validated, or
353 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400354 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400355 private class ValidatedState extends State {
356 @Override
357 public void enter() {
Pierre Imai55618be2016-02-19 15:25:54 +0900358 CaptivePortalStateChangeEvent.logEvent(
359 CaptivePortalStateChangeEvent.NETWORK_MONITOR_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -0400360 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
361 NETWORK_TEST_RESULT_VALID, 0, mNetworkAgentInfo));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400362 }
363
364 @Override
365 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400366 switch (message.what) {
367 case CMD_NETWORK_CONNECTED:
368 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400369 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400370 default:
371 return NOT_HANDLED;
372 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400373 }
374 }
375
Paul Jensen71b645f2014-10-13 14:13:07 -0400376 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
377 // is required. This State takes care to clear the notification upon exit from the State.
378 private class MaybeNotifyState extends State {
379 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500380 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500381 switch (message.what) {
382 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
383 final Intent intent = new Intent(
384 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
385 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400386 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
387 new CaptivePortal(new ICaptivePortal.Stub() {
388 @Override
389 public void appResponse(int response) {
390 if (response == APP_RETURN_WANTED_AS_IS) {
391 mContext.enforceCallingPermission(
392 android.Manifest.permission.CONNECTIVITY_INTERNAL,
393 "CaptivePortal");
394 }
395 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
396 }
397 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500398 intent.setFlags(
399 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
400 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
401 return HANDLED;
402 default:
403 return NOT_HANDLED;
404 }
405 }
406
407 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400408 public void exit() {
409 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
410 mNetworkAgentInfo.network.netId, null);
411 mConnectivityServiceHandler.sendMessage(message);
412 }
413 }
414
415 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400416 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400417 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400418 private int mReevaluateDelayMs;
419 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400420
Paul Jensenca8f16a2014-05-09 12:47:55 -0400421 @Override
422 public void enter() {
423 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400424 if (mUidResponsibleForReeval != INVALID_UID) {
425 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
426 mUidResponsibleForReeval = INVALID_UID;
427 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400428 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
429 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400430 }
431
432 @Override
433 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400434 switch (message.what) {
435 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400436 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400437 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500438 // Don't bother validating networks that don't satisify the default request.
439 // This includes:
440 // - VPNs which can be considered explicitly desired by the user and the
441 // user's desire trumps whether the network validates.
442 // - Networks that don't provide internet access. It's unclear how to
443 // validate such networks.
444 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
445 // such networks and the user didn't express interest in connecting to
446 // such networks (an app did) so the user may be unhappily surprised when
447 // asked to sign-in to a network they didn't want to connect to in the
448 // first place. Validation could be done to adjust the network scores
449 // however these networks are app-requested and may not be intended for
450 // general usage, in which case general validation may not be an accurate
451 // measure of the network's quality. Only the app knows how to evaluate
452 // the network so don't bother validating here. Furthermore sending HTTP
453 // packets over the network may be undesirable, for example an extremely
454 // expensive metered network, or unwanted leaking of the User Agent string.
455 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
456 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400457 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400458 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400459 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400460 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900461 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
462 // server's IP addresses could hit the DNS timeout, and attempting connections
463 // to each of the server's several IP addresses (currently one IPv4 and one
464 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
465 // will be unresponsive. isCaptivePortal() could be executed on another Thread
466 // if this is found to cause problems.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400467 int httpResponseCode = isCaptivePortal();
Pierre Imai55618be2016-02-19 15:25:54 +0900468 CaptivePortalCheckResultEvent.logEvent(mNetworkAgentInfo.network.netId,
469 httpResponseCode);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400470 if (httpResponseCode == 204) {
471 transitionTo(mValidatedState);
472 } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400473 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400474 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400475 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400476 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensend9be23f2015-05-19 14:51:47 -0400477 mConnectivityServiceHandler.sendMessage(obtainMessage(
478 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, 0,
479 mNetworkAgentInfo));
480 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400481 // Don't continue to blame UID forever.
482 TrafficStats.clearThreadStatsUid();
483 }
484 mReevaluateDelayMs *= 2;
485 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
486 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
487 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400488 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400489 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400490 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400491 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
492 // ignore any re-evaluation requests. After, restart the
493 // evaluation process via EvaluatingState#enter.
494 return mAttempts < IGNORE_REEVALUATE_ATTEMPTS ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400495 default:
496 return NOT_HANDLED;
497 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400498 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400499
500 @Override
501 public void exit() {
502 TrafficStats.clearThreadStatsUid();
503 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400504 }
505
Paul Jensendcbe8352014-09-16 16:28:34 -0400506 // BroadcastReceiver that waits for a particular Intent and then posts a message.
507 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400508 private final int mToken;
509 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400510 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400511 CustomIntentReceiver(String action, int token, int what) {
512 mToken = token;
513 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400514 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
515 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400516 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400517 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500518 final Intent intent = new Intent(mAction);
519 intent.setPackage(mContext.getPackageName());
520 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400521 }
522 @Override
523 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400524 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400525 }
526 }
Paul Jensen869868be2014-05-15 10:33:05 -0400527
Paul Jensen71b645f2014-10-13 14:13:07 -0400528 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
529 // has been shown a notification to sign-in.
530 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500531 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
532 "android.net.netmon.launchCaptivePortalApp";
533
Paul Jensen869868be2014-05-15 10:33:05 -0400534 @Override
535 public void enter() {
Paul Jensenad50a1f2014-09-05 12:06:44 -0400536 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
537 NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
Paul Jensend0491e9a2015-05-05 14:52:22 -0400538 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400539 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500540 // Create a CustomIntentReceiver that sends us a
541 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
542 // touches the notification.
543 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400544 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500545 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
546 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
547 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400548 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500549 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400550 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
551 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500552 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400553 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400554 // Retest for captive portal occasionally.
555 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
556 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400557 }
558
559 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400560 public void exit() {
561 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
562 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400563 }
564
Paul Jensen71b645f2014-10-13 14:13:07 -0400565 // Being in the LingeringState State indicates a Network's validated bit is true and it once
566 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
Paul Jensencf4c2c62015-07-01 14:16:32 -0400567 // another Network satisfied the NetworkRequest with a higher score and hence this Network
Paul Jensen71b645f2014-10-13 14:13:07 -0400568 // is "lingered" for a fixed period of time before it is disconnected. This period of time
569 // allows apps to wrap up communication and allows for seamless reactivation if the other
570 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400571 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400572 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400573
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900574 private WakeupMessage mWakeupMessage;
Paul Jensen79a08052014-08-21 12:44:07 -0400575
Paul Jensenca8f16a2014-05-09 12:47:55 -0400576 @Override
577 public void enter() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900578 final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetworkAgentInfo.network.netId;
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900579 mWakeupMessage = makeWakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
Paul Jensen79a08052014-08-21 12:44:07 -0400580 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900581 mWakeupMessage.schedule(wakeupTime);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400582 }
583
584 @Override
585 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400586 switch (message.what) {
587 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400588 log("Unlingered");
Paul Jensene0988542015-06-25 15:30:08 -0400589 // If already validated, go straight to validated state.
590 if (mNetworkAgentInfo.lastValidated) {
591 transitionTo(mValidatedState);
592 return HANDLED;
593 }
594 return NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400595 case CMD_LINGER_EXPIRED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400596 mConnectivityServiceHandler.sendMessage(
597 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400598 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400599 case CMD_FORCE_REEVALUATION:
600 // Ignore reevaluation attempts when lingering. A reevaluation could result
601 // in a transition to the validated state which would abort the linger
602 // timeout. Lingering is the result of score assessment; validity is
603 // irrelevant.
604 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400605 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
606 // Ignore user network determination as this could abort linger timeout.
607 // Networks are only lingered once validated because:
608 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
609 // - Once validated, a Network's validated bit is never cleared.
610 // Since networks are only lingered after being validated a user's
611 // determination will not change the death sentence that lingering entails:
612 // - If the user wants to use the network or bypasses the captive portal,
613 // the network's score will not be increased beyond its current value
614 // because it is already validated. Without a score increase there is no
615 // chance of reactivation (i.e. aborting linger timeout).
616 // - If the user does not want the network, lingering will disconnect the
617 // network anyhow.
618 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400619 default:
620 return NOT_HANDLED;
621 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400622 }
Paul Jensen79a08052014-08-21 12:44:07 -0400623
624 @Override
625 public void exit() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900626 mWakeupMessage.cancel();
Paul Jensen79a08052014-08-21 12:44:07 -0400627 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400628 }
629
Udam Sainib7c24872016-01-04 12:16:14 -0800630 public static String getCaptivePortalServerUrl(Context context) {
631 String server = Settings.Global.getString(context.getContentResolver(),
632 Settings.Global.CAPTIVE_PORTAL_SERVER);
633 if (server == null) server = DEFAULT_SERVER;
634 return "http://" + server + "/generate_204";
635 }
636
Paul Jensenca8f16a2014-05-09 12:47:55 -0400637 /**
638 * Do a URL fetch on a known server to see if we get the data we expect.
639 * Returns HTTP response code.
640 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400641 @VisibleForTesting
642 protected int isCaptivePortal() {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400643 if (!mIsCaptivePortalCheckEnabled) return 204;
644
Paul Jensenca8f16a2014-05-09 12:47:55 -0400645 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400646 int httpResponseCode = 599;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400647 try {
Udam Sainib7c24872016-01-04 12:16:14 -0800648 URL url = new URL(getCaptivePortalServerUrl(mContext));
Paul Jensen8fe17422015-02-02 11:03:03 -0500649 // On networks with a PAC instead of fetching a URL that should result in a 204
Udam Sainib7c24872016-01-04 12:16:14 -0800650 // response, we instead simply fetch the PAC script. This is done for a few reasons:
Paul Jensen8fe17422015-02-02 11:03:03 -0500651 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
652 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
653 // Network.openConnection() will ignore network-specific PACs and instead fetch
654 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
655 // NO_PROXY is the fetch of the PAC itself.
656 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
657 // happen before the fetch can commence, namely:
658 // a) the PAC script be fetched
Udam Sainib7c24872016-01-04 12:16:14 -0800659 // b) a PAC script resolver service be fired up and resolve the captive portal
660 // server.
Paul Jensen8fe17422015-02-02 11:03:03 -0500661 // Network validation could be delayed until these prerequisities are satisifed or
662 // could simply be left to race them. Neither is an optimal solution.
663 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
664 // fact block fetching of the generate_204 URL which would lead to false negative
665 // results for network validation.
666 boolean fetchPac = false;
Paul Jensen2f0a8972015-06-25 10:07:14 -0400667 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
668 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
669 url = new URL(proxyInfo.getPacFileUrl().toString());
670 fetchPac = true;
671 }
672 final StringBuffer connectInfo = new StringBuffer();
673 String hostToResolve = null;
674 // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
675 // unnecessary resolution.
676 if (proxyInfo == null || fetchPac) {
677 hostToResolve = url.getHost();
678 } else if (proxyInfo != null) {
679 hostToResolve = proxyInfo.getHost();
680 }
681 if (!TextUtils.isEmpty(hostToResolve)) {
682 connectInfo.append(", " + hostToResolve + "=");
683 final InetAddress[] addresses =
684 mNetworkAgentInfo.network.getAllByName(hostToResolve);
685 for (InetAddress address : addresses) {
686 connectInfo.append(address.getHostAddress());
687 if (address != addresses[addresses.length-1]) connectInfo.append(",");
Paul Jensen8fe17422015-02-02 11:03:03 -0500688 }
689 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700690 validationLog("Checking " + url.toString() + " on " +
Paul Jensen2f0a8972015-06-25 10:07:14 -0400691 mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700692 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500693 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400694 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
695 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
696 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400697
698 // Time how long it takes to get a response to our request
699 long requestTimestamp = SystemClock.elapsedRealtime();
700
Pierre Imaibe12d762016-03-10 17:00:50 +0900701 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen306f1a42014-08-04 10:59:01 -0400702
703 // Time how long it takes to get a response to our request
704 long responseTimestamp = SystemClock.elapsedRealtime();
705
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700706 validationLog("isCaptivePortal: ret=" + httpResponseCode +
707 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400708 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
709 // portal. The only example of this seen so far was a captive portal. For
710 // the time being go with prior behavior of assuming it's not a captive
711 // portal. If it is considered a captive portal, a different sign-in URL
712 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
713 // proxy server.
714
715 // Consider 200 response with "Content-length=0" to not be a captive portal.
716 // There's no point in considering this a captive portal as the user cannot
717 // sign-in to an empty page. Probably the result of a broken transparent proxy.
718 // See http://b/9972012.
719 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700720 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400721 httpResponseCode = 204;
722 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400723
Paul Jensen8fe17422015-02-02 11:03:03 -0500724 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700725 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500726 httpResponseCode = 204;
727 }
728
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800729 sendNetworkConditionsBroadcast(true /* response received */,
730 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400731 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400732 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700733 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400734 if (httpResponseCode == 599) {
735 // TODO: Ping gateway and DNS server and log results.
736 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400737 } finally {
738 if (urlConnection != null) {
739 urlConnection.disconnect();
740 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400741 }
742 return httpResponseCode;
743 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400744
745 /**
746 * @param responseReceived - whether or not we received a valid HTTP response to our request.
747 * If false, isCaptivePortal and responseTimestampMs are ignored
748 * TODO: This should be moved to the transports. The latency could be passed to the transports
749 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
750 * perhaps this could just be added to the WiFi transport only.
751 */
752 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
753 long requestTimestampMs, long responseTimestampMs) {
754 if (Settings.Global.getInt(mContext.getContentResolver(),
755 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400756 return;
757 }
758
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700759 if (systemReady == false) return;
760
Paul Jensen306f1a42014-08-04 10:59:01 -0400761 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
762 switch (mNetworkAgentInfo.networkInfo.getType()) {
763 case ConnectivityManager.TYPE_WIFI:
764 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
765 if (currentWifiInfo != null) {
766 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
767 // surrounded by double quotation marks (thus violating the Javadoc), but this
768 // was changed to match the Javadoc in API 17. Since clients may have started
769 // sanitizing the output of this method since API 17 was released, we should
770 // not change it here as it would become impossible to tell whether the SSID is
771 // simply being surrounded by quotes due to the API, or whether those quotes
772 // are actually part of the SSID.
773 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
774 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
775 } else {
776 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
777 return;
778 }
779 break;
780 case ConnectivityManager.TYPE_MOBILE:
781 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
782 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
783 if (info == null) return;
784 int numRegisteredCellInfo = 0;
785 for (CellInfo cellInfo : info) {
786 if (cellInfo.isRegistered()) {
787 numRegisteredCellInfo++;
788 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400789 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400790 "tell which is active. Bailing.");
791 return;
792 }
793 if (cellInfo instanceof CellInfoCdma) {
794 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
795 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
796 } else if (cellInfo instanceof CellInfoGsm) {
797 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
798 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
799 } else if (cellInfo instanceof CellInfoLte) {
800 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
801 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
802 } else if (cellInfo instanceof CellInfoWcdma) {
803 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
804 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
805 } else {
806 if (DBG) logw("Registered cellinfo is unrecognized");
807 return;
808 }
809 }
810 }
811 break;
812 default:
813 return;
814 }
815 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
816 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
817 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
818
819 if (responseReceived) {
820 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
821 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
822 }
Paul Jensen55298582014-08-20 11:01:41 -0400823 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
824 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400825 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400826
827 // Allow tests to override linger time.
828 @VisibleForTesting
829 public static void SetDefaultLingerTime(int time_ms) {
830 if (Process.myUid() == Process.SYSTEM_UID) {
831 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
832 }
833 DEFAULT_LINGER_DELAY_MS = time_ms;
834 }
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900835
836 @VisibleForTesting
837 protected WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int i) {
838 return new WakeupMessage(c, h, s, i);
839 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400840}