blob: d33075634ca04fe27f01c2681548af781640166f [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 Jensen232437312016-04-06 09:51:26 -0400123 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400124 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400125 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400126 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400127 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400128
129 /**
130 * Inform NetworkMonitor to linger a network. The Monitor should
131 * start a timer and/or start watching for zero live connections while
132 * moving towards LINGER_COMPLETE. After the Linger period expires
133 * (or other events mark the end of the linger state) the LINGER_COMPLETE
134 * event should be sent and the network will be shut down. If a
135 * CMD_NETWORK_CONNECTED happens before the LINGER completes
136 * it indicates further desire to keep the network alive and so
137 * the LINGER is aborted.
138 */
139 public static final int CMD_NETWORK_LINGER = BASE + 3;
140
141 /**
142 * Message to self indicating linger delay has expired.
143 * arg1 = Token to ignore old messages.
144 */
145 private static final int CMD_LINGER_EXPIRED = BASE + 4;
146
147 /**
148 * Inform ConnectivityService that the network LINGER period has
149 * expired.
150 * obj = NetworkAgentInfo
151 */
152 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
153
154 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400155 * Message to self indicating it's time to evaluate a network's connectivity.
156 * arg1 = Token to ignore old messages.
157 */
Paul Jensen869868be2014-05-15 10:33:05 -0400158 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400159
160 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400161 * Inform NetworkMonitor that the network has disconnected.
162 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400163 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400164
165 /**
166 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400167 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400168 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400169 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400170
171 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400172 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400173 * arg1 = one of: APP_RETURN_DISMISSED,
174 * APP_RETURN_UNWANTED,
175 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500176 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400177 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400178 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400179
180 /**
181 * Request ConnectivityService display provisioning notification.
182 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400183 * arg2 = NetID.
184 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400185 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400186 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400187
188 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500189 * Message to self indicating sign-in app should be launched.
190 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
191 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400192 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500193 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400194
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400195 /**
196 * Retest network to see if captive portal is still in place.
197 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
198 * 0 indicates self-initiated, so nobody to blame.
199 */
200 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
201
Paul Jensenca8f16a2014-05-09 12:47:55 -0400202 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400203 // Default to 30s linger time-out. Modifyable only for testing.
204 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400205 private final int mLingerDelayMs;
206 private int mLingerToken = 0;
207
Paul Jensend0491e9a2015-05-05 14:52:22 -0400208 // Start mReevaluateDelayMs at this value and double.
209 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
210 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
211 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
212 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400213 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400214 private static final int INVALID_UID = -1;
215 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400216 // Stop blaming UID that requested re-evaluation after this many attempts.
217 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400218 // Delay between reevaluations once a captive portal has been found.
219 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400220
221 private final Context mContext;
222 private final Handler mConnectivityServiceHandler;
223 private final NetworkAgentInfo mNetworkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400224 private final TelephonyManager mTelephonyManager;
225 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400226 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500227 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400228
Paul Jensenca8f16a2014-05-09 12:47:55 -0400229 private boolean mIsCaptivePortalCheckEnabled = false;
230
Paul Jensenad50a1f2014-09-05 12:06:44 -0400231 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
232 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400233 // Avoids surfacing "Sign in to network" notification.
234 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400235
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700236 public boolean systemReady = false;
237
Paul Jensen71b645f2014-10-13 14:13:07 -0400238 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400239 private final State mValidatedState = new ValidatedState();
240 private final State mMaybeNotifyState = new MaybeNotifyState();
241 private final State mEvaluatingState = new EvaluatingState();
242 private final State mCaptivePortalState = new CaptivePortalState();
243 private final State mLingeringState = new LingeringState();
244
Paul Jensen25a217c2015-02-27 22:55:47 -0500245 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400246
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700247 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
248
Paul Jensen2c311d62014-11-17 12:34:51 -0500249 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
250 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400251 // Add suffix indicating which NetworkMonitor we're talking about.
252 super(TAG + networkAgentInfo.name());
253
254 mContext = context;
255 mConnectivityServiceHandler = handler;
256 mNetworkAgentInfo = networkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400257 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
258 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400259 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500260 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400261
262 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400263 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400264 addState(mMaybeNotifyState, mDefaultState);
265 addState(mEvaluatingState, mMaybeNotifyState);
266 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400267 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700268 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400269
Paul Jensenca8f16a2014-05-09 12:47:55 -0400270 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400271
Paul Jensen869868be2014-05-15 10:33:05 -0400272 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
273 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400274
275 start();
276 }
277
Paul Jensen532b61432014-11-10 09:50:02 -0500278 @Override
279 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400280 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500281 }
282
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700283 private void validationLog(String s) {
284 if (DBG) log(s);
285 validationLogs.log(s);
286 }
287
288 public ReadOnlyLocalLog getValidationLogs() {
289 return validationLogs.readOnlyLocalLog();
290 }
291
Paul Jensen71b645f2014-10-13 14:13:07 -0400292 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
293 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400294 private class DefaultState extends State {
295 @Override
296 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400297 switch (message.what) {
298 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400299 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400300 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400301 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400302 case CMD_NETWORK_CONNECTED:
Pierre Imai55618be2016-02-19 15:25:54 +0900303 CaptivePortalStateChangeEvent.logEvent(
304 CaptivePortalStateChangeEvent.NETWORK_MONITOR_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:
Pierre Imai55618be2016-02-19 15:25:54 +0900308 CaptivePortalStateChangeEvent.logEvent(
309 CaptivePortalStateChangeEvent.NETWORK_MONITOR_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500310 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
311 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
312 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400313 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700314 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400315 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400316 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400317 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400318 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400319 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400320 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400321 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400322 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400323 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen71b645f2014-10-13 14:13:07 -0400324 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400325 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400326 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500327 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400328 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400329 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500330 // TODO: Distinguish this from a network that actually validates.
331 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400332 transitionTo(mValidatedState);
333 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400334 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400335 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400336 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400337 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400338 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
339 mNetworkAgentInfo.network.netId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400340 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400341 mUidResponsibleForReeval = 0;
342 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400343 break;
344 }
345 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400346 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400347 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400348 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400349 }
350 }
351
Paul Jensen71b645f2014-10-13 14:13:07 -0400352 // Being in the ValidatedState State indicates a Network is:
353 // - Successfully validated, or
354 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400355 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400356 private class ValidatedState extends State {
357 @Override
358 public void enter() {
Pierre Imai55618be2016-02-19 15:25:54 +0900359 CaptivePortalStateChangeEvent.logEvent(
360 CaptivePortalStateChangeEvent.NETWORK_MONITOR_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -0400361 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400362 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400363 }
364
365 @Override
366 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400367 switch (message.what) {
368 case CMD_NETWORK_CONNECTED:
369 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400370 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400371 default:
372 return NOT_HANDLED;
373 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400374 }
375 }
376
Paul Jensen71b645f2014-10-13 14:13:07 -0400377 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
378 // is required. This State takes care to clear the notification upon exit from the State.
379 private class MaybeNotifyState extends State {
380 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500381 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500382 switch (message.what) {
383 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
384 final Intent intent = new Intent(
385 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
386 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400387 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
388 new CaptivePortal(new ICaptivePortal.Stub() {
389 @Override
390 public void appResponse(int response) {
391 if (response == APP_RETURN_WANTED_AS_IS) {
392 mContext.enforceCallingPermission(
393 android.Manifest.permission.CONNECTIVITY_INTERNAL,
394 "CaptivePortal");
395 }
396 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
397 }
398 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500399 intent.setFlags(
400 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
401 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
402 return HANDLED;
403 default:
404 return NOT_HANDLED;
405 }
406 }
407
408 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400409 public void exit() {
410 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
411 mNetworkAgentInfo.network.netId, null);
412 mConnectivityServiceHandler.sendMessage(message);
413 }
414 }
415
Paul Jensen232437312016-04-06 09:51:26 -0400416 /**
417 * Result of calling isCaptivePortal().
418 * @hide
419 */
420 @VisibleForTesting
421 public static final class CaptivePortalProbeResult {
422 final int mHttpResponseCode; // HTTP response code returned from Internet probe.
423 final String mRedirectUrl; // Redirect destination returned from Internet probe.
424
425 public CaptivePortalProbeResult(int httpResponseCode, String redirectUrl) {
426 mHttpResponseCode = httpResponseCode;
427 mRedirectUrl = redirectUrl;
428 }
429 }
430
Paul Jensen71b645f2014-10-13 14:13:07 -0400431 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400432 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400433 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400434 private int mReevaluateDelayMs;
435 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400436
Paul Jensenca8f16a2014-05-09 12:47:55 -0400437 @Override
438 public void enter() {
439 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400440 if (mUidResponsibleForReeval != INVALID_UID) {
441 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
442 mUidResponsibleForReeval = INVALID_UID;
443 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400444 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
445 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400446 }
447
448 @Override
449 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400450 switch (message.what) {
451 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400452 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400453 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500454 // Don't bother validating networks that don't satisify the default request.
455 // This includes:
456 // - VPNs which can be considered explicitly desired by the user and the
457 // user's desire trumps whether the network validates.
458 // - Networks that don't provide internet access. It's unclear how to
459 // validate such networks.
460 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
461 // such networks and the user didn't express interest in connecting to
462 // such networks (an app did) so the user may be unhappily surprised when
463 // asked to sign-in to a network they didn't want to connect to in the
464 // first place. Validation could be done to adjust the network scores
465 // however these networks are app-requested and may not be intended for
466 // general usage, in which case general validation may not be an accurate
467 // measure of the network's quality. Only the app knows how to evaluate
468 // the network so don't bother validating here. Furthermore sending HTTP
469 // packets over the network may be undesirable, for example an extremely
470 // expensive metered network, or unwanted leaking of the User Agent string.
471 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
472 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400473 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400474 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400475 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400476 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900477 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
478 // server's IP addresses could hit the DNS timeout, and attempting connections
479 // to each of the server's several IP addresses (currently one IPv4 and one
480 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
481 // will be unresponsive. isCaptivePortal() could be executed on another Thread
482 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400483 CaptivePortalProbeResult probeResult = isCaptivePortal();
Pierre Imai55618be2016-02-19 15:25:54 +0900484 CaptivePortalCheckResultEvent.logEvent(mNetworkAgentInfo.network.netId,
Paul Jensen232437312016-04-06 09:51:26 -0400485 probeResult.mHttpResponseCode);
486 if (probeResult.mHttpResponseCode == 204) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400487 transitionTo(mValidatedState);
Paul Jensen232437312016-04-06 09:51:26 -0400488 } else if (probeResult.mHttpResponseCode >= 200 &&
489 probeResult.mHttpResponseCode <= 399) {
490 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
491 NETWORK_TEST_RESULT_INVALID, mNetworkAgentInfo.network.netId,
492 probeResult.mRedirectUrl));
Paul Jensen71b645f2014-10-13 14:13:07 -0400493 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400494 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400495 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400496 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensend9be23f2015-05-19 14:51:47 -0400497 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400498 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
499 mNetworkAgentInfo.network.netId, probeResult.mRedirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400500 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400501 // Don't continue to blame UID forever.
502 TrafficStats.clearThreadStatsUid();
503 }
504 mReevaluateDelayMs *= 2;
505 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
506 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
507 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400508 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400509 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400510 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400511 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
512 // ignore any re-evaluation requests. After, restart the
513 // evaluation process via EvaluatingState#enter.
514 return mAttempts < IGNORE_REEVALUATE_ATTEMPTS ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400515 default:
516 return NOT_HANDLED;
517 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400518 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400519
520 @Override
521 public void exit() {
522 TrafficStats.clearThreadStatsUid();
523 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400524 }
525
Paul Jensendcbe8352014-09-16 16:28:34 -0400526 // BroadcastReceiver that waits for a particular Intent and then posts a message.
527 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400528 private final int mToken;
529 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400530 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400531 CustomIntentReceiver(String action, int token, int what) {
532 mToken = token;
533 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400534 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
535 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400536 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400537 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500538 final Intent intent = new Intent(mAction);
539 intent.setPackage(mContext.getPackageName());
540 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400541 }
542 @Override
543 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400544 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400545 }
546 }
Paul Jensen869868be2014-05-15 10:33:05 -0400547
Paul Jensen71b645f2014-10-13 14:13:07 -0400548 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
549 // has been shown a notification to sign-in.
550 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500551 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
552 "android.net.netmon.launchCaptivePortalApp";
553
Paul Jensen869868be2014-05-15 10:33:05 -0400554 @Override
555 public void enter() {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400556 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400557 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500558 // Create a CustomIntentReceiver that sends us a
559 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
560 // touches the notification.
561 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400562 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500563 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
564 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
565 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400566 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500567 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400568 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
569 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500570 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400571 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400572 // Retest for captive portal occasionally.
573 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
574 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400575 }
576
577 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400578 public void exit() {
579 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
580 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400581 }
582
Paul Jensen71b645f2014-10-13 14:13:07 -0400583 // Being in the LingeringState State indicates a Network's validated bit is true and it once
584 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
Paul Jensencf4c2c62015-07-01 14:16:32 -0400585 // another Network satisfied the NetworkRequest with a higher score and hence this Network
Paul Jensen71b645f2014-10-13 14:13:07 -0400586 // is "lingered" for a fixed period of time before it is disconnected. This period of time
587 // allows apps to wrap up communication and allows for seamless reactivation if the other
588 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400589 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400590 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400591
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900592 private WakeupMessage mWakeupMessage;
Paul Jensen79a08052014-08-21 12:44:07 -0400593
Paul Jensenca8f16a2014-05-09 12:47:55 -0400594 @Override
595 public void enter() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900596 final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetworkAgentInfo.network.netId;
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900597 mWakeupMessage = makeWakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
Paul Jensen79a08052014-08-21 12:44:07 -0400598 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900599 mWakeupMessage.schedule(wakeupTime);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400600 }
601
602 @Override
603 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400604 switch (message.what) {
605 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400606 log("Unlingered");
Paul Jensene0988542015-06-25 15:30:08 -0400607 // If already validated, go straight to validated state.
608 if (mNetworkAgentInfo.lastValidated) {
609 transitionTo(mValidatedState);
610 return HANDLED;
611 }
612 return NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400613 case CMD_LINGER_EXPIRED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400614 mConnectivityServiceHandler.sendMessage(
615 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400616 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400617 case CMD_FORCE_REEVALUATION:
618 // Ignore reevaluation attempts when lingering. A reevaluation could result
619 // in a transition to the validated state which would abort the linger
620 // timeout. Lingering is the result of score assessment; validity is
621 // irrelevant.
622 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400623 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
624 // Ignore user network determination as this could abort linger timeout.
625 // Networks are only lingered once validated because:
626 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
627 // - Once validated, a Network's validated bit is never cleared.
628 // Since networks are only lingered after being validated a user's
629 // determination will not change the death sentence that lingering entails:
630 // - If the user wants to use the network or bypasses the captive portal,
631 // the network's score will not be increased beyond its current value
632 // because it is already validated. Without a score increase there is no
633 // chance of reactivation (i.e. aborting linger timeout).
634 // - If the user does not want the network, lingering will disconnect the
635 // network anyhow.
636 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400637 default:
638 return NOT_HANDLED;
639 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400640 }
Paul Jensen79a08052014-08-21 12:44:07 -0400641
642 @Override
643 public void exit() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900644 mWakeupMessage.cancel();
Paul Jensen79a08052014-08-21 12:44:07 -0400645 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400646 }
647
Udam Sainib7c24872016-01-04 12:16:14 -0800648 public static String getCaptivePortalServerUrl(Context context) {
649 String server = Settings.Global.getString(context.getContentResolver(),
650 Settings.Global.CAPTIVE_PORTAL_SERVER);
651 if (server == null) server = DEFAULT_SERVER;
652 return "http://" + server + "/generate_204";
653 }
654
Paul Jensenca8f16a2014-05-09 12:47:55 -0400655 /**
656 * Do a URL fetch on a known server to see if we get the data we expect.
657 * Returns HTTP response code.
658 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400659 @VisibleForTesting
Paul Jensen232437312016-04-06 09:51:26 -0400660 protected CaptivePortalProbeResult isCaptivePortal() {
661 if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400662
Paul Jensenca8f16a2014-05-09 12:47:55 -0400663 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400664 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400665 String redirectUrl = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400666 try {
Udam Sainib7c24872016-01-04 12:16:14 -0800667 URL url = new URL(getCaptivePortalServerUrl(mContext));
Paul Jensen8fe17422015-02-02 11:03:03 -0500668 // On networks with a PAC instead of fetching a URL that should result in a 204
Udam Sainib7c24872016-01-04 12:16:14 -0800669 // response, we instead simply fetch the PAC script. This is done for a few reasons:
Paul Jensen8fe17422015-02-02 11:03:03 -0500670 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
671 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
672 // Network.openConnection() will ignore network-specific PACs and instead fetch
673 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
674 // NO_PROXY is the fetch of the PAC itself.
675 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
676 // happen before the fetch can commence, namely:
677 // a) the PAC script be fetched
Udam Sainib7c24872016-01-04 12:16:14 -0800678 // b) a PAC script resolver service be fired up and resolve the captive portal
679 // server.
Paul Jensen8fe17422015-02-02 11:03:03 -0500680 // Network validation could be delayed until these prerequisities are satisifed or
681 // could simply be left to race them. Neither is an optimal solution.
682 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
683 // fact block fetching of the generate_204 URL which would lead to false negative
684 // results for network validation.
685 boolean fetchPac = false;
Paul Jensen2f0a8972015-06-25 10:07:14 -0400686 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
687 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
688 url = new URL(proxyInfo.getPacFileUrl().toString());
689 fetchPac = true;
690 }
691 final StringBuffer connectInfo = new StringBuffer();
692 String hostToResolve = null;
693 // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
694 // unnecessary resolution.
695 if (proxyInfo == null || fetchPac) {
696 hostToResolve = url.getHost();
697 } else if (proxyInfo != null) {
698 hostToResolve = proxyInfo.getHost();
699 }
700 if (!TextUtils.isEmpty(hostToResolve)) {
701 connectInfo.append(", " + hostToResolve + "=");
702 final InetAddress[] addresses =
703 mNetworkAgentInfo.network.getAllByName(hostToResolve);
704 for (InetAddress address : addresses) {
705 connectInfo.append(address.getHostAddress());
706 if (address != addresses[addresses.length-1]) connectInfo.append(",");
Paul Jensen8fe17422015-02-02 11:03:03 -0500707 }
708 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700709 validationLog("Checking " + url.toString() + " on " +
Paul Jensen2f0a8972015-06-25 10:07:14 -0400710 mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700711 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500712 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400713 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
714 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
715 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400716
717 // Time how long it takes to get a response to our request
718 long requestTimestamp = SystemClock.elapsedRealtime();
719
Pierre Imaibe12d762016-03-10 17:00:50 +0900720 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400721 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400722
723 // Time how long it takes to get a response to our request
724 long responseTimestamp = SystemClock.elapsedRealtime();
725
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700726 validationLog("isCaptivePortal: ret=" + httpResponseCode +
727 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400728 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
729 // portal. The only example of this seen so far was a captive portal. For
730 // the time being go with prior behavior of assuming it's not a captive
731 // portal. If it is considered a captive portal, a different sign-in URL
732 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
733 // proxy server.
734
735 // Consider 200 response with "Content-length=0" to not be a captive portal.
736 // There's no point in considering this a captive portal as the user cannot
737 // sign-in to an empty page. Probably the result of a broken transparent proxy.
738 // See http://b/9972012.
739 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700740 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400741 httpResponseCode = 204;
742 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400743
Paul Jensen8fe17422015-02-02 11:03:03 -0500744 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700745 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500746 httpResponseCode = 204;
747 }
748
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800749 sendNetworkConditionsBroadcast(true /* response received */,
750 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400751 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400752 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700753 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400754 if (httpResponseCode == 599) {
755 // TODO: Ping gateway and DNS server and log results.
756 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400757 } finally {
758 if (urlConnection != null) {
759 urlConnection.disconnect();
760 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400761 }
Paul Jensen232437312016-04-06 09:51:26 -0400762 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400763 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400764
765 /**
766 * @param responseReceived - whether or not we received a valid HTTP response to our request.
767 * If false, isCaptivePortal and responseTimestampMs are ignored
768 * TODO: This should be moved to the transports. The latency could be passed to the transports
769 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
770 * perhaps this could just be added to the WiFi transport only.
771 */
772 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
773 long requestTimestampMs, long responseTimestampMs) {
774 if (Settings.Global.getInt(mContext.getContentResolver(),
775 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400776 return;
777 }
778
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700779 if (systemReady == false) return;
780
Paul Jensen306f1a42014-08-04 10:59:01 -0400781 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
782 switch (mNetworkAgentInfo.networkInfo.getType()) {
783 case ConnectivityManager.TYPE_WIFI:
784 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
785 if (currentWifiInfo != null) {
786 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
787 // surrounded by double quotation marks (thus violating the Javadoc), but this
788 // was changed to match the Javadoc in API 17. Since clients may have started
789 // sanitizing the output of this method since API 17 was released, we should
790 // not change it here as it would become impossible to tell whether the SSID is
791 // simply being surrounded by quotes due to the API, or whether those quotes
792 // are actually part of the SSID.
793 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
794 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
795 } else {
796 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
797 return;
798 }
799 break;
800 case ConnectivityManager.TYPE_MOBILE:
801 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
802 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
803 if (info == null) return;
804 int numRegisteredCellInfo = 0;
805 for (CellInfo cellInfo : info) {
806 if (cellInfo.isRegistered()) {
807 numRegisteredCellInfo++;
808 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400809 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400810 "tell which is active. Bailing.");
811 return;
812 }
813 if (cellInfo instanceof CellInfoCdma) {
814 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
815 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
816 } else if (cellInfo instanceof CellInfoGsm) {
817 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
818 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
819 } else if (cellInfo instanceof CellInfoLte) {
820 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
821 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
822 } else if (cellInfo instanceof CellInfoWcdma) {
823 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
824 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
825 } else {
826 if (DBG) logw("Registered cellinfo is unrecognized");
827 return;
828 }
829 }
830 }
831 break;
832 default:
833 return;
834 }
835 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
836 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
837 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
838
839 if (responseReceived) {
840 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
841 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
842 }
Paul Jensen55298582014-08-20 11:01:41 -0400843 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
844 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400845 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400846
847 // Allow tests to override linger time.
848 @VisibleForTesting
849 public static void SetDefaultLingerTime(int time_ms) {
850 if (Process.myUid() == Process.SYSTEM_UID) {
851 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
852 }
853 DEFAULT_LINGER_DELAY_MS = time_ms;
854 }
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900855
856 @VisibleForTesting
857 protected WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int i) {
858 return new WakeupMessage(c, h, s, i);
859 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400860}