blob: f7784acc09c7e873afbf2e84809a4a20ca86029f [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;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090037import android.net.metrics.ValidationProbeEvent;
38import android.net.metrics.NetworkEvent;
Paul Jensen306f1a42014-08-04 10:59:01 -040039import android.net.wifi.WifiInfo;
40import android.net.wifi.WifiManager;
Erik Klinea488c232016-04-15 15:49:42 +090041import android.net.util.Stopwatch;
Paul Jensenca8f16a2014-05-09 12:47:55 -040042import android.os.Handler;
43import android.os.Message;
Paul Jensend7b6ca92015-05-13 14:05:12 -040044import android.os.Process;
Paul Jensen306f1a42014-08-04 10:59:01 -040045import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040046import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040047import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040048import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040049import android.telephony.CellIdentityCdma;
50import android.telephony.CellIdentityGsm;
51import android.telephony.CellIdentityLte;
52import android.telephony.CellIdentityWcdma;
53import android.telephony.CellInfo;
54import android.telephony.CellInfoCdma;
55import android.telephony.CellInfoGsm;
56import android.telephony.CellInfoLte;
57import android.telephony.CellInfoWcdma;
58import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040059import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070060import android.util.LocalLog;
61import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050062import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040063
Paul Jensend7b6ca92015-05-13 14:05:12 -040064import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040065import com.android.internal.util.Protocol;
66import com.android.internal.util.State;
67import com.android.internal.util.StateMachine;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +090068import com.android.internal.util.WakeupMessage;
Paul Jensenca8f16a2014-05-09 12:47:55 -040069import com.android.server.connectivity.NetworkAgentInfo;
70
Paul Jensenca8f16a2014-05-09 12:47:55 -040071import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040072import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040073import java.net.InetAddress;
Paul Jensenca8f16a2014-05-09 12:47:55 -040074import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040075import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040076import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040077
78/**
79 * {@hide}
80 */
81public class NetworkMonitor extends StateMachine {
Joe Onorato12acbd72016-02-01 17:49:31 -080082 private static final boolean DBG = false;
Erik Klinea488c232016-04-15 15:49:42 +090083 private static final String TAG = NetworkMonitor.class.getSimpleName();
Erik Klinee7d01792015-07-20 23:37:15 +090084 private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040085 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040086 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
87 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
88 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
89 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
90 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
91 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
92 public static final String EXTRA_CELL_ID = "extra_cellid";
93 public static final String EXTRA_SSID = "extra_ssid";
94 public static final String EXTRA_BSSID = "extra_bssid";
95 /** real time since boot */
96 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
97 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
98
99 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
100 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400101
Paul Jensenad50a1f2014-09-05 12:06:44 -0400102 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
103 // The network should be used as a default internet connection. It was found to be:
104 // 1. a functioning network providing internet access, or
105 // 2. a captive portal and the user decided to use it as is.
106 public static final int NETWORK_TEST_RESULT_VALID = 0;
107 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
108 // The network should not be used as a default internet connection. It was found to be:
109 // 1. a captive portal and the user is prompted to sign-in, or
110 // 2. a captive portal and the user did not want to use it, or
111 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
112 public static final int NETWORK_TEST_RESULT_INVALID = 1;
113
Paul Jensenca8f16a2014-05-09 12:47:55 -0400114 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
115
116 /**
117 * Inform NetworkMonitor that their network is connected.
118 * Initiates Network Validation.
119 */
120 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
121
122 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400123 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400124 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400125 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400126 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400128 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400129
130 /**
131 * Inform NetworkMonitor to linger a network. The Monitor should
132 * start a timer and/or start watching for zero live connections while
133 * moving towards LINGER_COMPLETE. After the Linger period expires
134 * (or other events mark the end of the linger state) the LINGER_COMPLETE
135 * event should be sent and the network will be shut down. If a
136 * CMD_NETWORK_CONNECTED happens before the LINGER completes
137 * it indicates further desire to keep the network alive and so
138 * the LINGER is aborted.
139 */
140 public static final int CMD_NETWORK_LINGER = BASE + 3;
141
142 /**
143 * Message to self indicating linger delay has expired.
144 * arg1 = Token to ignore old messages.
145 */
146 private static final int CMD_LINGER_EXPIRED = BASE + 4;
147
148 /**
149 * Inform ConnectivityService that the network LINGER period has
150 * expired.
151 * obj = NetworkAgentInfo
152 */
153 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
154
155 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400156 * Message to self indicating it's time to evaluate a network's connectivity.
157 * arg1 = Token to ignore old messages.
158 */
Paul Jensen869868be2014-05-15 10:33:05 -0400159 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400160
161 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400162 * Inform NetworkMonitor that the network has disconnected.
163 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400164 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400165
166 /**
167 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400168 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400169 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400170 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400171
172 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400173 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400174 * arg1 = one of: APP_RETURN_DISMISSED,
175 * APP_RETURN_UNWANTED,
176 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500177 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400178 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400179 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400180
181 /**
182 * Request ConnectivityService display provisioning notification.
183 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400184 * arg2 = NetID.
185 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400186 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400187 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400188
189 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500190 * Message to self indicating sign-in app should be launched.
191 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
192 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400193 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500194 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400195
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400196 /**
197 * Retest network to see if captive portal is still in place.
198 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
199 * 0 indicates self-initiated, so nobody to blame.
200 */
201 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
202
Paul Jensenca8f16a2014-05-09 12:47:55 -0400203 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400204 // Default to 30s linger time-out. Modifyable only for testing.
205 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400206 private final int mLingerDelayMs;
207 private int mLingerToken = 0;
208
Paul Jensend0491e9a2015-05-05 14:52:22 -0400209 // Start mReevaluateDelayMs at this value and double.
210 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
211 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
212 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
213 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400214 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400215 private static final int INVALID_UID = -1;
216 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400217 // Stop blaming UID that requested re-evaluation after this many attempts.
218 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400219 // Delay between reevaluations once a captive portal has been found.
220 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400221
222 private final Context mContext;
223 private final Handler mConnectivityServiceHandler;
224 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900225 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400226 private final TelephonyManager mTelephonyManager;
227 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400228 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500229 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400230
Paul Jensenca8f16a2014-05-09 12:47:55 -0400231 private boolean mIsCaptivePortalCheckEnabled = false;
232
Paul Jensenad50a1f2014-09-05 12:06:44 -0400233 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
234 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400235 // Avoids surfacing "Sign in to network" notification.
236 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400237
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700238 public boolean systemReady = false;
239
Paul Jensen71b645f2014-10-13 14:13:07 -0400240 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400241 private final State mValidatedState = new ValidatedState();
242 private final State mMaybeNotifyState = new MaybeNotifyState();
243 private final State mEvaluatingState = new EvaluatingState();
244 private final State mCaptivePortalState = new CaptivePortalState();
245 private final State mLingeringState = new LingeringState();
246
Paul Jensen25a217c2015-02-27 22:55:47 -0500247 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400248
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700249 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
250
Erik Klinea488c232016-04-15 15:49:42 +0900251 private final Stopwatch mEvaluationTimer = new Stopwatch();
252
Paul Jensen2c311d62014-11-17 12:34:51 -0500253 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
254 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400255 // Add suffix indicating which NetworkMonitor we're talking about.
256 super(TAG + networkAgentInfo.name());
257
258 mContext = context;
259 mConnectivityServiceHandler = handler;
260 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900261 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400262 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
263 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400264 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500265 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400266
267 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400268 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400269 addState(mMaybeNotifyState, mDefaultState);
270 addState(mEvaluatingState, mMaybeNotifyState);
271 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400272 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700273 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400274
Paul Jensenca8f16a2014-05-09 12:47:55 -0400275 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400276
Paul Jensen869868be2014-05-15 10:33:05 -0400277 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
278 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400279
280 start();
281 }
282
Paul Jensen532b61432014-11-10 09:50:02 -0500283 @Override
284 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400285 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500286 }
287
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700288 private void validationLog(String s) {
289 if (DBG) log(s);
290 validationLogs.log(s);
291 }
292
293 public ReadOnlyLocalLog getValidationLogs() {
294 return validationLogs.readOnlyLocalLog();
295 }
296
Paul Jensen71b645f2014-10-13 14:13:07 -0400297 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
298 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400299 private class DefaultState extends State {
300 @Override
301 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400302 switch (message.what) {
303 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400304 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400305 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400306 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400307 case CMD_NETWORK_CONNECTED:
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900308 NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400309 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400310 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400311 case CMD_NETWORK_DISCONNECTED:
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900312 NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500313 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
314 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
315 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400316 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700317 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400318 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400319 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400320 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400321 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400322 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400323 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400324 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400325 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400326 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen71b645f2014-10-13 14:13:07 -0400327 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400328 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400329 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500330 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400331 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400332 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500333 // TODO: Distinguish this from a network that actually validates.
334 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400335 transitionTo(mValidatedState);
336 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400337 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400338 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400339 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400340 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400341 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900342 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400343 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400344 mUidResponsibleForReeval = 0;
345 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400346 break;
347 }
348 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400349 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400350 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400351 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400352 }
353 }
354
Paul Jensen71b645f2014-10-13 14:13:07 -0400355 // Being in the ValidatedState State indicates a Network is:
356 // - Successfully validated, or
357 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400358 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400359 private class ValidatedState extends State {
360 @Override
361 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900362 if (mEvaluationTimer.isRunning()) {
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900363 NetworkEvent.logValidated(mNetId, mEvaluationTimer.stop());
Erik Klinea488c232016-04-15 15:49:42 +0900364 mEvaluationTimer.reset();
365 }
Paul Jensenad50a1f2014-09-05 12:06:44 -0400366 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400367 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400368 }
369
370 @Override
371 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400372 switch (message.what) {
373 case CMD_NETWORK_CONNECTED:
374 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400375 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400376 default:
377 return NOT_HANDLED;
378 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400379 }
380 }
381
Paul Jensen71b645f2014-10-13 14:13:07 -0400382 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
383 // is required. This State takes care to clear the notification upon exit from the State.
384 private class MaybeNotifyState extends State {
385 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500386 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500387 switch (message.what) {
388 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
389 final Intent intent = new Intent(
390 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
391 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400392 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
393 new CaptivePortal(new ICaptivePortal.Stub() {
394 @Override
395 public void appResponse(int response) {
396 if (response == APP_RETURN_WANTED_AS_IS) {
397 mContext.enforceCallingPermission(
398 android.Manifest.permission.CONNECTIVITY_INTERNAL,
399 "CaptivePortal");
400 }
401 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
402 }
403 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500404 intent.setFlags(
405 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
406 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
407 return HANDLED;
408 default:
409 return NOT_HANDLED;
410 }
411 }
412
413 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400414 public void exit() {
415 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
416 mNetworkAgentInfo.network.netId, null);
417 mConnectivityServiceHandler.sendMessage(message);
418 }
419 }
420
Paul Jensen232437312016-04-06 09:51:26 -0400421 /**
422 * Result of calling isCaptivePortal().
423 * @hide
424 */
425 @VisibleForTesting
426 public static final class CaptivePortalProbeResult {
427 final int mHttpResponseCode; // HTTP response code returned from Internet probe.
428 final String mRedirectUrl; // Redirect destination returned from Internet probe.
429
430 public CaptivePortalProbeResult(int httpResponseCode, String redirectUrl) {
431 mHttpResponseCode = httpResponseCode;
432 mRedirectUrl = redirectUrl;
433 }
434 }
435
Paul Jensen71b645f2014-10-13 14:13:07 -0400436 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400437 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400438 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400439 private int mReevaluateDelayMs;
440 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400441
Paul Jensenca8f16a2014-05-09 12:47:55 -0400442 @Override
443 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900444 // If we have already started to track time spent in EvaluatingState
445 // don't reset the timer due simply to, say, commands or events that
446 // cause us to exit and re-enter EvaluatingState.
447 if (!mEvaluationTimer.isStarted()) {
448 mEvaluationTimer.start();
449 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400450 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400451 if (mUidResponsibleForReeval != INVALID_UID) {
452 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
453 mUidResponsibleForReeval = INVALID_UID;
454 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400455 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
456 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400457 }
458
459 @Override
460 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400461 switch (message.what) {
462 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400463 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400464 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500465 // Don't bother validating networks that don't satisify the default request.
466 // This includes:
467 // - VPNs which can be considered explicitly desired by the user and the
468 // user's desire trumps whether the network validates.
469 // - Networks that don't provide internet access. It's unclear how to
470 // validate such networks.
471 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
472 // such networks and the user didn't express interest in connecting to
473 // such networks (an app did) so the user may be unhappily surprised when
474 // asked to sign-in to a network they didn't want to connect to in the
475 // first place. Validation could be done to adjust the network scores
476 // however these networks are app-requested and may not be intended for
477 // general usage, in which case general validation may not be an accurate
478 // measure of the network's quality. Only the app knows how to evaluate
479 // the network so don't bother validating here. Furthermore sending HTTP
480 // packets over the network may be undesirable, for example an extremely
481 // expensive metered network, or unwanted leaking of the User Agent string.
482 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
483 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400484 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400485 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400486 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400487 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900488 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
489 // server's IP addresses could hit the DNS timeout, and attempting connections
490 // to each of the server's several IP addresses (currently one IPv4 and one
491 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
492 // will be unresponsive. isCaptivePortal() could be executed on another Thread
493 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400494 CaptivePortalProbeResult probeResult = isCaptivePortal();
Paul Jensen232437312016-04-06 09:51:26 -0400495 if (probeResult.mHttpResponseCode == 204) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400496 transitionTo(mValidatedState);
Paul Jensen232437312016-04-06 09:51:26 -0400497 } else if (probeResult.mHttpResponseCode >= 200 &&
498 probeResult.mHttpResponseCode <= 399) {
499 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Erik Klinea488c232016-04-15 15:49:42 +0900500 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.mRedirectUrl));
Paul Jensen71b645f2014-10-13 14:13:07 -0400501 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400502 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400503 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400504 sendMessageDelayed(msg, mReevaluateDelayMs);
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900505 NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_VALIDATION_FAILED);
Paul Jensend9be23f2015-05-19 14:51:47 -0400506 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900507 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
508 probeResult.mRedirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400509 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400510 // Don't continue to blame UID forever.
511 TrafficStats.clearThreadStatsUid();
512 }
513 mReevaluateDelayMs *= 2;
514 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
515 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
516 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400517 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400518 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400519 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400520 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
521 // ignore any re-evaluation requests. After, restart the
522 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900523 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400524 default:
525 return NOT_HANDLED;
526 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400527 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400528
529 @Override
530 public void exit() {
531 TrafficStats.clearThreadStatsUid();
532 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400533 }
534
Paul Jensendcbe8352014-09-16 16:28:34 -0400535 // BroadcastReceiver that waits for a particular Intent and then posts a message.
536 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400537 private final int mToken;
538 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400539 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400540 CustomIntentReceiver(String action, int token, int what) {
541 mToken = token;
542 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400543 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
544 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400545 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400546 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500547 final Intent intent = new Intent(mAction);
548 intent.setPackage(mContext.getPackageName());
549 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400550 }
551 @Override
552 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400553 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400554 }
555 }
Paul Jensen869868be2014-05-15 10:33:05 -0400556
Paul Jensen71b645f2014-10-13 14:13:07 -0400557 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
558 // has been shown a notification to sign-in.
559 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500560 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
561 "android.net.netmon.launchCaptivePortalApp";
562
Paul Jensen869868be2014-05-15 10:33:05 -0400563 @Override
564 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900565 if (mEvaluationTimer.isRunning()) {
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900566 NetworkEvent.logCaptivePortalFound(mNetId, mEvaluationTimer.stop());
Erik Klinea488c232016-04-15 15:49:42 +0900567 mEvaluationTimer.reset();
568 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400569 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400570 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500571 // Create a CustomIntentReceiver that sends us a
572 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
573 // touches the notification.
574 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400575 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500576 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
577 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
578 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400579 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500580 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400581 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
582 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500583 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400584 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400585 // Retest for captive portal occasionally.
586 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
587 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400588 }
589
590 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400591 public void exit() {
592 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
593 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400594 }
595
Paul Jensen71b645f2014-10-13 14:13:07 -0400596 // Being in the LingeringState State indicates a Network's validated bit is true and it once
597 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
Paul Jensencf4c2c62015-07-01 14:16:32 -0400598 // another Network satisfied the NetworkRequest with a higher score and hence this Network
Paul Jensen71b645f2014-10-13 14:13:07 -0400599 // is "lingered" for a fixed period of time before it is disconnected. This period of time
600 // allows apps to wrap up communication and allows for seamless reactivation if the other
601 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400602 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400603 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400604
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900605 private WakeupMessage mWakeupMessage;
Paul Jensen79a08052014-08-21 12:44:07 -0400606
Paul Jensenca8f16a2014-05-09 12:47:55 -0400607 @Override
608 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900609 mEvaluationTimer.reset();
610 final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetId;
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900611 mWakeupMessage = makeWakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
Paul Jensen79a08052014-08-21 12:44:07 -0400612 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900613 mWakeupMessage.schedule(wakeupTime);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400614 }
615
616 @Override
617 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400618 switch (message.what) {
619 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400620 log("Unlingered");
Paul Jensene0988542015-06-25 15:30:08 -0400621 // If already validated, go straight to validated state.
622 if (mNetworkAgentInfo.lastValidated) {
623 transitionTo(mValidatedState);
624 return HANDLED;
625 }
626 return NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400627 case CMD_LINGER_EXPIRED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400628 mConnectivityServiceHandler.sendMessage(
629 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400630 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400631 case CMD_FORCE_REEVALUATION:
632 // Ignore reevaluation attempts when lingering. A reevaluation could result
633 // in a transition to the validated state which would abort the linger
634 // timeout. Lingering is the result of score assessment; validity is
635 // irrelevant.
636 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400637 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
638 // Ignore user network determination as this could abort linger timeout.
639 // Networks are only lingered once validated because:
640 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
641 // - Once validated, a Network's validated bit is never cleared.
642 // Since networks are only lingered after being validated a user's
643 // determination will not change the death sentence that lingering entails:
644 // - If the user wants to use the network or bypasses the captive portal,
645 // the network's score will not be increased beyond its current value
646 // because it is already validated. Without a score increase there is no
647 // chance of reactivation (i.e. aborting linger timeout).
648 // - If the user does not want the network, lingering will disconnect the
649 // network anyhow.
650 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400651 default:
652 return NOT_HANDLED;
653 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400654 }
Paul Jensen79a08052014-08-21 12:44:07 -0400655
656 @Override
657 public void exit() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900658 mWakeupMessage.cancel();
Paul Jensen79a08052014-08-21 12:44:07 -0400659 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400660 }
661
Udam Sainib7c24872016-01-04 12:16:14 -0800662 public static String getCaptivePortalServerUrl(Context context) {
663 String server = Settings.Global.getString(context.getContentResolver(),
664 Settings.Global.CAPTIVE_PORTAL_SERVER);
665 if (server == null) server = DEFAULT_SERVER;
666 return "http://" + server + "/generate_204";
667 }
668
Paul Jensenca8f16a2014-05-09 12:47:55 -0400669 /**
670 * Do a URL fetch on a known server to see if we get the data we expect.
671 * Returns HTTP response code.
672 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400673 @VisibleForTesting
Paul Jensen232437312016-04-06 09:51:26 -0400674 protected CaptivePortalProbeResult isCaptivePortal() {
675 if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400676
Paul Jensenca8f16a2014-05-09 12:47:55 -0400677 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400678 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400679 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900680 final Stopwatch probeTimer = new Stopwatch().start();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400681 try {
Udam Sainib7c24872016-01-04 12:16:14 -0800682 URL url = new URL(getCaptivePortalServerUrl(mContext));
Paul Jensen8fe17422015-02-02 11:03:03 -0500683 // On networks with a PAC instead of fetching a URL that should result in a 204
Udam Sainib7c24872016-01-04 12:16:14 -0800684 // response, we instead simply fetch the PAC script. This is done for a few reasons:
Paul Jensen8fe17422015-02-02 11:03:03 -0500685 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
686 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
687 // Network.openConnection() will ignore network-specific PACs and instead fetch
688 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
689 // NO_PROXY is the fetch of the PAC itself.
690 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
691 // happen before the fetch can commence, namely:
692 // a) the PAC script be fetched
Udam Sainib7c24872016-01-04 12:16:14 -0800693 // b) a PAC script resolver service be fired up and resolve the captive portal
694 // server.
Paul Jensen8fe17422015-02-02 11:03:03 -0500695 // Network validation could be delayed until these prerequisities are satisifed or
696 // could simply be left to race them. Neither is an optimal solution.
697 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
698 // fact block fetching of the generate_204 URL which would lead to false negative
699 // results for network validation.
700 boolean fetchPac = false;
Paul Jensen2f0a8972015-06-25 10:07:14 -0400701 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
702 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
703 url = new URL(proxyInfo.getPacFileUrl().toString());
704 fetchPac = true;
705 }
706 final StringBuffer connectInfo = new StringBuffer();
707 String hostToResolve = null;
708 // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
709 // unnecessary resolution.
710 if (proxyInfo == null || fetchPac) {
711 hostToResolve = url.getHost();
712 } else if (proxyInfo != null) {
713 hostToResolve = proxyInfo.getHost();
714 }
715 if (!TextUtils.isEmpty(hostToResolve)) {
716 connectInfo.append(", " + hostToResolve + "=");
717 final InetAddress[] addresses =
718 mNetworkAgentInfo.network.getAllByName(hostToResolve);
719 for (InetAddress address : addresses) {
720 connectInfo.append(address.getHostAddress());
721 if (address != addresses[addresses.length-1]) connectInfo.append(",");
Paul Jensen8fe17422015-02-02 11:03:03 -0500722 }
723 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700724 validationLog("Checking " + url.toString() + " on " +
Paul Jensen2f0a8972015-06-25 10:07:14 -0400725 mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700726 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500727 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400728 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
729 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
730 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400731
732 // Time how long it takes to get a response to our request
733 long requestTimestamp = SystemClock.elapsedRealtime();
734
Pierre Imaibe12d762016-03-10 17:00:50 +0900735 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400736 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400737
738 // Time how long it takes to get a response to our request
739 long responseTimestamp = SystemClock.elapsedRealtime();
740
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700741 validationLog("isCaptivePortal: ret=" + httpResponseCode +
742 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400743 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
744 // portal. The only example of this seen so far was a captive portal. For
745 // the time being go with prior behavior of assuming it's not a captive
746 // portal. If it is considered a captive portal, a different sign-in URL
747 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
748 // proxy server.
749
750 // Consider 200 response with "Content-length=0" to not be a captive portal.
751 // There's no point in considering this a captive portal as the user cannot
752 // sign-in to an empty page. Probably the result of a broken transparent proxy.
753 // See http://b/9972012.
754 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700755 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400756 httpResponseCode = 204;
757 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400758
Paul Jensen8fe17422015-02-02 11:03:03 -0500759 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700760 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500761 httpResponseCode = 204;
762 }
763
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800764 sendNetworkConditionsBroadcast(true /* response received */,
765 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400766 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400767 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700768 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400769 if (httpResponseCode == 599) {
770 // TODO: Ping gateway and DNS server and log results.
771 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400772 } finally {
773 if (urlConnection != null) {
774 urlConnection.disconnect();
775 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400776 }
Hugo Benichicc92c6e2016-04-21 15:02:38 +0900777 final int probeType = ValidationProbeEvent.PROBE_HTTP;
778 ValidationProbeEvent.logEvent(mNetId, probeTimer.stop(), probeType, httpResponseCode);
Paul Jensen232437312016-04-06 09:51:26 -0400779 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400780 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400781
782 /**
783 * @param responseReceived - whether or not we received a valid HTTP response to our request.
784 * If false, isCaptivePortal and responseTimestampMs are ignored
785 * TODO: This should be moved to the transports. The latency could be passed to the transports
786 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
787 * perhaps this could just be added to the WiFi transport only.
788 */
789 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
790 long requestTimestampMs, long responseTimestampMs) {
791 if (Settings.Global.getInt(mContext.getContentResolver(),
792 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400793 return;
794 }
795
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700796 if (systemReady == false) return;
797
Paul Jensen306f1a42014-08-04 10:59:01 -0400798 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
799 switch (mNetworkAgentInfo.networkInfo.getType()) {
800 case ConnectivityManager.TYPE_WIFI:
801 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
802 if (currentWifiInfo != null) {
803 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
804 // surrounded by double quotation marks (thus violating the Javadoc), but this
805 // was changed to match the Javadoc in API 17. Since clients may have started
806 // sanitizing the output of this method since API 17 was released, we should
807 // not change it here as it would become impossible to tell whether the SSID is
808 // simply being surrounded by quotes due to the API, or whether those quotes
809 // are actually part of the SSID.
810 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
811 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
812 } else {
813 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
814 return;
815 }
816 break;
817 case ConnectivityManager.TYPE_MOBILE:
818 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
819 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
820 if (info == null) return;
821 int numRegisteredCellInfo = 0;
822 for (CellInfo cellInfo : info) {
823 if (cellInfo.isRegistered()) {
824 numRegisteredCellInfo++;
825 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400826 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400827 "tell which is active. Bailing.");
828 return;
829 }
830 if (cellInfo instanceof CellInfoCdma) {
831 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
832 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
833 } else if (cellInfo instanceof CellInfoGsm) {
834 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
835 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
836 } else if (cellInfo instanceof CellInfoLte) {
837 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
838 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
839 } else if (cellInfo instanceof CellInfoWcdma) {
840 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
841 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
842 } else {
843 if (DBG) logw("Registered cellinfo is unrecognized");
844 return;
845 }
846 }
847 }
848 break;
849 default:
850 return;
851 }
852 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
853 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
854 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
855
856 if (responseReceived) {
857 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
858 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
859 }
Paul Jensen55298582014-08-20 11:01:41 -0400860 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
861 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400862 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400863
864 // Allow tests to override linger time.
865 @VisibleForTesting
866 public static void SetDefaultLingerTime(int time_ms) {
867 if (Process.myUid() == Process.SYSTEM_UID) {
868 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
869 }
870 DEFAULT_LINGER_DELAY_MS = time_ms;
871 }
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900872
873 @VisibleForTesting
874 protected WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int i) {
875 return new WakeupMessage(c, h, s, i);
876 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400877}