blob: 381a110dd20b4bf7a1398e832eceafeaa201a107 [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;
Erik Klinea488c232016-04-15 15:49:42 +090039import android.net.metrics.NetworkMonitorEvent;
Paul Jensen306f1a42014-08-04 10:59:01 -040040import android.net.wifi.WifiInfo;
41import android.net.wifi.WifiManager;
Erik Klinea488c232016-04-15 15:49:42 +090042import android.net.util.Stopwatch;
Paul Jensenca8f16a2014-05-09 12:47:55 -040043import android.os.Handler;
44import android.os.Message;
Paul Jensend7b6ca92015-05-13 14:05:12 -040045import android.os.Process;
Paul Jensen306f1a42014-08-04 10:59:01 -040046import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040047import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040048import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040049import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040050import android.telephony.CellIdentityCdma;
51import android.telephony.CellIdentityGsm;
52import android.telephony.CellIdentityLte;
53import android.telephony.CellIdentityWcdma;
54import android.telephony.CellInfo;
55import android.telephony.CellInfoCdma;
56import android.telephony.CellInfoGsm;
57import android.telephony.CellInfoLte;
58import android.telephony.CellInfoWcdma;
59import android.telephony.TelephonyManager;
Paul Jensen2f0a8972015-06-25 10:07:14 -040060import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070061import android.util.LocalLog;
62import android.util.LocalLog.ReadOnlyLocalLog;
Paul Jensen532b61432014-11-10 09:50:02 -050063import android.util.Log;
Paul Jensenca8f16a2014-05-09 12:47:55 -040064
Paul Jensend7b6ca92015-05-13 14:05:12 -040065import com.android.internal.annotations.VisibleForTesting;
Paul Jensenca8f16a2014-05-09 12:47:55 -040066import com.android.internal.util.Protocol;
67import com.android.internal.util.State;
68import com.android.internal.util.StateMachine;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +090069import com.android.internal.util.WakeupMessage;
Paul Jensenca8f16a2014-05-09 12:47:55 -040070import com.android.server.connectivity.NetworkAgentInfo;
71
Paul Jensenca8f16a2014-05-09 12:47:55 -040072import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040073import java.net.HttpURLConnection;
Paul Jensen2f0a8972015-06-25 10:07:14 -040074import java.net.InetAddress;
Paul Jensenca8f16a2014-05-09 12:47:55 -040075import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040076import java.util.List;
Paul Jensen71b645f2014-10-13 14:13:07 -040077import java.util.Random;
Paul Jensenca8f16a2014-05-09 12:47:55 -040078
79/**
80 * {@hide}
81 */
82public class NetworkMonitor extends StateMachine {
Joe Onorato12acbd72016-02-01 17:49:31 -080083 private static final boolean DBG = false;
Erik Klinea488c232016-04-15 15:49:42 +090084 private static final String TAG = NetworkMonitor.class.getSimpleName();
Erik Klinee7d01792015-07-20 23:37:15 +090085 private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
Paul Jensenca8f16a2014-05-09 12:47:55 -040086 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040087 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
88 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
89 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
90 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
91 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
92 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
93 public static final String EXTRA_CELL_ID = "extra_cellid";
94 public static final String EXTRA_SSID = "extra_ssid";
95 public static final String EXTRA_BSSID = "extra_bssid";
96 /** real time since boot */
97 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
98 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
99
100 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
101 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -0400102
Paul Jensenad50a1f2014-09-05 12:06:44 -0400103 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
104 // The network should be used as a default internet connection. It was found to be:
105 // 1. a functioning network providing internet access, or
106 // 2. a captive portal and the user decided to use it as is.
107 public static final int NETWORK_TEST_RESULT_VALID = 0;
108 // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
109 // The network should not be used as a default internet connection. It was found to be:
110 // 1. a captive portal and the user is prompted to sign-in, or
111 // 2. a captive portal and the user did not want to use it, or
112 // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
113 public static final int NETWORK_TEST_RESULT_INVALID = 1;
114
Paul Jensenca8f16a2014-05-09 12:47:55 -0400115 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
116
117 /**
118 * Inform NetworkMonitor that their network is connected.
119 * Initiates Network Validation.
120 */
121 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
122
123 /**
Paul Jensenad50a1f2014-09-05 12:06:44 -0400124 * Inform ConnectivityService that the network has been tested.
Paul Jensen232437312016-04-06 09:51:26 -0400125 * obj = String representing URL that Internet probe was redirect to, if it was redirected.
Paul Jensenad50a1f2014-09-05 12:06:44 -0400126 * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
Paul Jensen232437312016-04-06 09:51:26 -0400127 * arg2 = NetID.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400128 */
Paul Jensenad50a1f2014-09-05 12:06:44 -0400129 public static final int EVENT_NETWORK_TESTED = BASE + 2;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400130
131 /**
132 * Inform NetworkMonitor to linger a network. The Monitor should
133 * start a timer and/or start watching for zero live connections while
134 * moving towards LINGER_COMPLETE. After the Linger period expires
135 * (or other events mark the end of the linger state) the LINGER_COMPLETE
136 * event should be sent and the network will be shut down. If a
137 * CMD_NETWORK_CONNECTED happens before the LINGER completes
138 * it indicates further desire to keep the network alive and so
139 * the LINGER is aborted.
140 */
141 public static final int CMD_NETWORK_LINGER = BASE + 3;
142
143 /**
144 * Message to self indicating linger delay has expired.
145 * arg1 = Token to ignore old messages.
146 */
147 private static final int CMD_LINGER_EXPIRED = BASE + 4;
148
149 /**
150 * Inform ConnectivityService that the network LINGER period has
151 * expired.
152 * obj = NetworkAgentInfo
153 */
154 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
155
156 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400157 * Message to self indicating it's time to evaluate a network's connectivity.
158 * arg1 = Token to ignore old messages.
159 */
Paul Jensen869868be2014-05-15 10:33:05 -0400160 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400161
162 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400163 * Inform NetworkMonitor that the network has disconnected.
164 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400165 public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400166
167 /**
168 * Force evaluation even if it has succeeded in the past.
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400169 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400170 */
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400171 public static final int CMD_FORCE_REEVALUATION = BASE + 8;
Paul Jensen869868be2014-05-15 10:33:05 -0400172
173 /**
Paul Jensen71b645f2014-10-13 14:13:07 -0400174 * Message to self indicating captive portal app finished.
Paul Jensen49e3edf2015-05-22 10:50:39 -0400175 * arg1 = one of: APP_RETURN_DISMISSED,
176 * APP_RETURN_UNWANTED,
177 * APP_RETURN_WANTED_AS_IS
Paul Jensen25a217c2015-02-27 22:55:47 -0500178 * obj = mCaptivePortalLoggedInResponseToken as String
Paul Jensen869868be2014-05-15 10:33:05 -0400179 */
Paul Jensen49e3edf2015-05-22 10:50:39 -0400180 private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
Paul Jensen869868be2014-05-15 10:33:05 -0400181
182 /**
183 * Request ConnectivityService display provisioning notification.
184 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400185 * arg2 = NetID.
186 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400187 */
Paul Jensen71b645f2014-10-13 14:13:07 -0400188 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
Paul Jensen869868be2014-05-15 10:33:05 -0400189
190 /**
Paul Jensen25a217c2015-02-27 22:55:47 -0500191 * Message to self indicating sign-in app should be launched.
192 * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
193 * user touches the sign in notification.
Paul Jensen869868be2014-05-15 10:33:05 -0400194 */
Paul Jensen25a217c2015-02-27 22:55:47 -0500195 private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400196
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400197 /**
198 * Retest network to see if captive portal is still in place.
199 * arg1 = UID responsible for requesting this reeval. Will be billed for data.
200 * 0 indicates self-initiated, so nobody to blame.
201 */
202 private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
203
Paul Jensenca8f16a2014-05-09 12:47:55 -0400204 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
Paul Jensend7b6ca92015-05-13 14:05:12 -0400205 // Default to 30s linger time-out. Modifyable only for testing.
206 private static int DEFAULT_LINGER_DELAY_MS = 30000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400207 private final int mLingerDelayMs;
208 private int mLingerToken = 0;
209
Paul Jensend0491e9a2015-05-05 14:52:22 -0400210 // Start mReevaluateDelayMs at this value and double.
211 private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
212 private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
213 // Before network has been evaluated this many times, ignore repeated reevaluate requests.
214 private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400215 private int mReevaluateToken = 0;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400216 private static final int INVALID_UID = -1;
217 private int mUidResponsibleForReeval = INVALID_UID;
Paul Jensend9be23f2015-05-19 14:51:47 -0400218 // Stop blaming UID that requested re-evaluation after this many attempts.
219 private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400220 // Delay between reevaluations once a captive portal has been found.
221 private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400222
223 private final Context mContext;
224 private final Handler mConnectivityServiceHandler;
225 private final NetworkAgentInfo mNetworkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900226 private final int mNetId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400227 private final TelephonyManager mTelephonyManager;
228 private final WifiManager mWifiManager;
Paul Jensen79a08052014-08-21 12:44:07 -0400229 private final AlarmManager mAlarmManager;
Paul Jensen2c311d62014-11-17 12:34:51 -0500230 private final NetworkRequest mDefaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400231
Paul Jensenca8f16a2014-05-09 12:47:55 -0400232 private boolean mIsCaptivePortalCheckEnabled = false;
233
Paul Jensenad50a1f2014-09-05 12:06:44 -0400234 // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
235 private boolean mUserDoesNotWant = false;
Paul Jensen700f2362015-05-05 14:56:10 -0400236 // Avoids surfacing "Sign in to network" notification.
237 private boolean mDontDisplaySigninNotification = false;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400238
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700239 public boolean systemReady = false;
240
Paul Jensen71b645f2014-10-13 14:13:07 -0400241 private final State mDefaultState = new DefaultState();
Paul Jensen71b645f2014-10-13 14:13:07 -0400242 private final State mValidatedState = new ValidatedState();
243 private final State mMaybeNotifyState = new MaybeNotifyState();
244 private final State mEvaluatingState = new EvaluatingState();
245 private final State mCaptivePortalState = new CaptivePortalState();
246 private final State mLingeringState = new LingeringState();
247
Paul Jensen25a217c2015-02-27 22:55:47 -0500248 private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400249
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700250 private final LocalLog validationLogs = new LocalLog(20); // 20 lines
251
Erik Klinea488c232016-04-15 15:49:42 +0900252 private final Stopwatch mEvaluationTimer = new Stopwatch();
253
Paul Jensen2c311d62014-11-17 12:34:51 -0500254 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
255 NetworkRequest defaultRequest) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400256 // Add suffix indicating which NetworkMonitor we're talking about.
257 super(TAG + networkAgentInfo.name());
258
259 mContext = context;
260 mConnectivityServiceHandler = handler;
261 mNetworkAgentInfo = networkAgentInfo;
Erik Klinea488c232016-04-15 15:49:42 +0900262 mNetId = mNetworkAgentInfo.network.netId;
Paul Jensen306f1a42014-08-04 10:59:01 -0400263 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
264 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensen79a08052014-08-21 12:44:07 -0400265 mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Paul Jensen2c311d62014-11-17 12:34:51 -0500266 mDefaultRequest = defaultRequest;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400267
268 addState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400269 addState(mValidatedState, mDefaultState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400270 addState(mMaybeNotifyState, mDefaultState);
271 addState(mEvaluatingState, mMaybeNotifyState);
272 addState(mCaptivePortalState, mMaybeNotifyState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400273 addState(mLingeringState, mDefaultState);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -0700274 setInitialState(mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400275
Paul Jensenca8f16a2014-05-09 12:47:55 -0400276 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400277
Paul Jensen869868be2014-05-15 10:33:05 -0400278 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
279 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400280
281 start();
282 }
283
Paul Jensen532b61432014-11-10 09:50:02 -0500284 @Override
285 protected void log(String s) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400286 if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
Paul Jensen532b61432014-11-10 09:50:02 -0500287 }
288
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700289 private void validationLog(String s) {
290 if (DBG) log(s);
291 validationLogs.log(s);
292 }
293
294 public ReadOnlyLocalLog getValidationLogs() {
295 return validationLogs.readOnlyLocalLog();
296 }
297
Paul Jensen71b645f2014-10-13 14:13:07 -0400298 // DefaultState is the parent of all States. It exists only to handle CMD_* messages but
299 // does not entail any real state (hence no enter() or exit() routines).
Paul Jensenca8f16a2014-05-09 12:47:55 -0400300 private class DefaultState extends State {
301 @Override
302 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400303 switch (message.what) {
304 case CMD_NETWORK_LINGER:
Paul Jensen22e547a2015-06-25 09:17:53 -0400305 log("Lingering");
Paul Jensenca8f16a2014-05-09 12:47:55 -0400306 transitionTo(mLingeringState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400307 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400308 case CMD_NETWORK_CONNECTED:
Erik Klinea488c232016-04-15 15:49:42 +0900309 CaptivePortalStateChangeEvent.logEvent(mNetId,
Pierre Imai55618be2016-02-19 15:25:54 +0900310 CaptivePortalStateChangeEvent.NETWORK_MONITOR_CONNECTED);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400311 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400312 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400313 case CMD_NETWORK_DISCONNECTED:
Erik Klinea488c232016-04-15 15:49:42 +0900314 CaptivePortalStateChangeEvent.logEvent(mNetId,
Pierre Imai55618be2016-02-19 15:25:54 +0900315 CaptivePortalStateChangeEvent.NETWORK_MONITOR_DISCONNECTED);
Paul Jensen25a217c2015-02-27 22:55:47 -0500316 if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
317 mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
318 mLaunchCaptivePortalAppBroadcastReceiver = null;
Paul Jensen71b645f2014-10-13 14:13:07 -0400319 }
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700320 quit();
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400321 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400322 case CMD_FORCE_REEVALUATION:
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400323 case CMD_CAPTIVE_PORTAL_RECHECK:
Paul Jensen22e547a2015-06-25 09:17:53 -0400324 log("Forcing reevaluation for UID " + message.arg1);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400325 mUidResponsibleForReeval = message.arg1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400326 transitionTo(mEvaluatingState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400327 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400328 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400329 log("CaptivePortal App responded with " + message.arg1);
Paul Jensen71b645f2014-10-13 14:13:07 -0400330 switch (message.arg1) {
Paul Jensen49e3edf2015-05-22 10:50:39 -0400331 case APP_RETURN_DISMISSED:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400332 sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
Paul Jensen25a217c2015-02-27 22:55:47 -0500333 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400334 case APP_RETURN_WANTED_AS_IS:
Paul Jensen700f2362015-05-05 14:56:10 -0400335 mDontDisplaySigninNotification = true;
Paul Jensen25a217c2015-02-27 22:55:47 -0500336 // TODO: Distinguish this from a network that actually validates.
337 // Displaying the "!" on the system UI icon may still be a good idea.
Paul Jensen71b645f2014-10-13 14:13:07 -0400338 transitionTo(mValidatedState);
339 break;
Paul Jensen49e3edf2015-05-22 10:50:39 -0400340 case APP_RETURN_UNWANTED:
Paul Jensen700f2362015-05-05 14:56:10 -0400341 mDontDisplaySigninNotification = true;
Paul Jensen71b645f2014-10-13 14:13:07 -0400342 mUserDoesNotWant = true;
Paul Jensend0491e9a2015-05-05 14:52:22 -0400343 mConnectivityServiceHandler.sendMessage(obtainMessage(
Paul Jensen232437312016-04-06 09:51:26 -0400344 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
Erik Klinea488c232016-04-15 15:49:42 +0900345 mNetId, null));
Paul Jensen71b645f2014-10-13 14:13:07 -0400346 // TODO: Should teardown network.
Paul Jensend0491e9a2015-05-05 14:52:22 -0400347 mUidResponsibleForReeval = 0;
348 transitionTo(mEvaluatingState);
Paul Jensen71b645f2014-10-13 14:13:07 -0400349 break;
350 }
351 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400352 default:
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400353 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400354 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400355 }
356 }
357
Paul Jensen71b645f2014-10-13 14:13:07 -0400358 // Being in the ValidatedState State indicates a Network is:
359 // - Successfully validated, or
360 // - Wanted "as is" by the user, or
Paul Jensencf4c2c62015-07-01 14:16:32 -0400361 // - Does not satisfy the default NetworkRequest and so validation has been skipped.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400362 private class ValidatedState extends State {
363 @Override
364 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900365 if (mEvaluationTimer.isRunning()) {
366 NetworkMonitorEvent.logValidated(mNetId, mEvaluationTimer.stop());
367 mEvaluationTimer.reset();
368 }
369 CaptivePortalStateChangeEvent.logEvent(mNetId,
Pierre Imai55618be2016-02-19 15:25:54 +0900370 CaptivePortalStateChangeEvent.NETWORK_MONITOR_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -0400371 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Paul Jensen232437312016-04-06 09:51:26 -0400372 NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
Paul Jensenca8f16a2014-05-09 12:47:55 -0400373 }
374
375 @Override
376 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400377 switch (message.what) {
378 case CMD_NETWORK_CONNECTED:
379 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400380 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400381 default:
382 return NOT_HANDLED;
383 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400384 }
385 }
386
Paul Jensen71b645f2014-10-13 14:13:07 -0400387 // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
388 // is required. This State takes care to clear the notification upon exit from the State.
389 private class MaybeNotifyState extends State {
390 @Override
Paul Jensen25a217c2015-02-27 22:55:47 -0500391 public boolean processMessage(Message message) {
Paul Jensen25a217c2015-02-27 22:55:47 -0500392 switch (message.what) {
393 case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
394 final Intent intent = new Intent(
395 ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
396 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
Paul Jensen49e3edf2015-05-22 10:50:39 -0400397 intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
398 new CaptivePortal(new ICaptivePortal.Stub() {
399 @Override
400 public void appResponse(int response) {
401 if (response == APP_RETURN_WANTED_AS_IS) {
402 mContext.enforceCallingPermission(
403 android.Manifest.permission.CONNECTIVITY_INTERNAL,
404 "CaptivePortal");
405 }
406 sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
407 }
408 }));
Paul Jensen25a217c2015-02-27 22:55:47 -0500409 intent.setFlags(
410 Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
411 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
412 return HANDLED;
413 default:
414 return NOT_HANDLED;
415 }
416 }
417
418 @Override
Paul Jensen71b645f2014-10-13 14:13:07 -0400419 public void exit() {
420 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
421 mNetworkAgentInfo.network.netId, null);
422 mConnectivityServiceHandler.sendMessage(message);
423 }
424 }
425
Paul Jensen232437312016-04-06 09:51:26 -0400426 /**
427 * Result of calling isCaptivePortal().
428 * @hide
429 */
430 @VisibleForTesting
431 public static final class CaptivePortalProbeResult {
432 final int mHttpResponseCode; // HTTP response code returned from Internet probe.
433 final String mRedirectUrl; // Redirect destination returned from Internet probe.
434
435 public CaptivePortalProbeResult(int httpResponseCode, String redirectUrl) {
436 mHttpResponseCode = httpResponseCode;
437 mRedirectUrl = redirectUrl;
438 }
439 }
440
Paul Jensen71b645f2014-10-13 14:13:07 -0400441 // Being in the EvaluatingState State indicates the Network is being evaluated for internet
Paul Jensend0491e9a2015-05-05 14:52:22 -0400442 // connectivity, or that the user has indicated that this network is unwanted.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400443 private class EvaluatingState extends State {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400444 private int mReevaluateDelayMs;
445 private int mAttempts;
Paul Jensen869868be2014-05-15 10:33:05 -0400446
Paul Jensenca8f16a2014-05-09 12:47:55 -0400447 @Override
448 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900449 // If we have already started to track time spent in EvaluatingState
450 // don't reset the timer due simply to, say, commands or events that
451 // cause us to exit and re-enter EvaluatingState.
452 if (!mEvaluationTimer.isStarted()) {
453 mEvaluationTimer.start();
454 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400455 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400456 if (mUidResponsibleForReeval != INVALID_UID) {
457 TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
458 mUidResponsibleForReeval = INVALID_UID;
459 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400460 mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
461 mAttempts = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400462 }
463
464 @Override
465 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400466 switch (message.what) {
467 case CMD_REEVALUATE:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400468 if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400469 return HANDLED;
Paul Jensen2c311d62014-11-17 12:34:51 -0500470 // Don't bother validating networks that don't satisify the default request.
471 // This includes:
472 // - VPNs which can be considered explicitly desired by the user and the
473 // user's desire trumps whether the network validates.
474 // - Networks that don't provide internet access. It's unclear how to
475 // validate such networks.
476 // - Untrusted networks. It's unsafe to prompt the user to sign-in to
477 // such networks and the user didn't express interest in connecting to
478 // such networks (an app did) so the user may be unhappily surprised when
479 // asked to sign-in to a network they didn't want to connect to in the
480 // first place. Validation could be done to adjust the network scores
481 // however these networks are app-requested and may not be intended for
482 // general usage, in which case general validation may not be an accurate
483 // measure of the network's quality. Only the app knows how to evaluate
484 // the network so don't bother validating here. Furthermore sending HTTP
485 // packets over the network may be undesirable, for example an extremely
486 // expensive metered network, or unwanted leaking of the User Agent string.
487 if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
488 mNetworkAgentInfo.networkCapabilities)) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400489 transitionTo(mValidatedState);
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400490 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400491 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400492 mAttempts++;
Lorenzo Colitti351bfad2015-01-22 22:36:50 +0900493 // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
494 // server's IP addresses could hit the DNS timeout, and attempting connections
495 // to each of the server's several IP addresses (currently one IPv4 and one
496 // IPv6) could each take SOCKET_TIMEOUT_MS. During this time this StateMachine
497 // will be unresponsive. isCaptivePortal() could be executed on another Thread
498 // if this is found to cause problems.
Paul Jensen232437312016-04-06 09:51:26 -0400499 CaptivePortalProbeResult probeResult = isCaptivePortal();
Erik Klinea488c232016-04-15 15:49:42 +0900500 CaptivePortalCheckResultEvent.logEvent(mNetId, probeResult.mHttpResponseCode);
Paul Jensen232437312016-04-06 09:51:26 -0400501 if (probeResult.mHttpResponseCode == 204) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400502 transitionTo(mValidatedState);
Paul Jensen232437312016-04-06 09:51:26 -0400503 } else if (probeResult.mHttpResponseCode >= 200 &&
504 probeResult.mHttpResponseCode <= 399) {
505 mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
Erik Klinea488c232016-04-15 15:49:42 +0900506 NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.mRedirectUrl));
Paul Jensen71b645f2014-10-13 14:13:07 -0400507 transitionTo(mCaptivePortalState);
Paul Jensend0491e9a2015-05-05 14:52:22 -0400508 } else {
Paul Jensend9be23f2015-05-19 14:51:47 -0400509 final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
Paul Jensen869868be2014-05-15 10:33:05 -0400510 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensend9be23f2015-05-19 14:51:47 -0400511 mConnectivityServiceHandler.sendMessage(obtainMessage(
Erik Klinea488c232016-04-15 15:49:42 +0900512 EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
513 probeResult.mRedirectUrl));
Paul Jensend9be23f2015-05-19 14:51:47 -0400514 if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
Paul Jensend0491e9a2015-05-05 14:52:22 -0400515 // Don't continue to blame UID forever.
516 TrafficStats.clearThreadStatsUid();
517 }
518 mReevaluateDelayMs *= 2;
519 if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
520 mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
521 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400522 }
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400523 return HANDLED;
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400524 case CMD_FORCE_REEVALUATION:
Paul Jensend0491e9a2015-05-05 14:52:22 -0400525 // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
526 // ignore any re-evaluation requests. After, restart the
527 // evaluation process via EvaluatingState#enter.
Erik Klinea488c232016-04-15 15:49:42 +0900528 return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400529 default:
530 return NOT_HANDLED;
531 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400532 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400533
534 @Override
535 public void exit() {
536 TrafficStats.clearThreadStatsUid();
537 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400538 }
539
Paul Jensendcbe8352014-09-16 16:28:34 -0400540 // BroadcastReceiver that waits for a particular Intent and then posts a message.
541 private class CustomIntentReceiver extends BroadcastReceiver {
Paul Jensen71b645f2014-10-13 14:13:07 -0400542 private final int mToken;
543 private final int mWhat;
Paul Jensendcbe8352014-09-16 16:28:34 -0400544 private final String mAction;
Paul Jensen71b645f2014-10-13 14:13:07 -0400545 CustomIntentReceiver(String action, int token, int what) {
546 mToken = token;
547 mWhat = what;
Paul Jensendcbe8352014-09-16 16:28:34 -0400548 mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
549 mContext.registerReceiver(this, new IntentFilter(mAction));
Paul Jensen869868be2014-05-15 10:33:05 -0400550 }
Paul Jensendcbe8352014-09-16 16:28:34 -0400551 public PendingIntent getPendingIntent() {
Paul Jensen25a217c2015-02-27 22:55:47 -0500552 final Intent intent = new Intent(mAction);
553 intent.setPackage(mContext.getPackageName());
554 return PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensendcbe8352014-09-16 16:28:34 -0400555 }
556 @Override
557 public void onReceive(Context context, Intent intent) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400558 if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
Paul Jensendcbe8352014-09-16 16:28:34 -0400559 }
560 }
Paul Jensen869868be2014-05-15 10:33:05 -0400561
Paul Jensen71b645f2014-10-13 14:13:07 -0400562 // Being in the CaptivePortalState State indicates a captive portal was detected and the user
563 // has been shown a notification to sign-in.
564 private class CaptivePortalState extends State {
Paul Jensen25a217c2015-02-27 22:55:47 -0500565 private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
566 "android.net.netmon.launchCaptivePortalApp";
567
Paul Jensen869868be2014-05-15 10:33:05 -0400568 @Override
569 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900570 if (mEvaluationTimer.isRunning()) {
571 NetworkMonitorEvent.logCaptivePortalFound(mNetId, mEvaluationTimer.stop());
572 mEvaluationTimer.reset();
573 }
Paul Jensend0491e9a2015-05-05 14:52:22 -0400574 // Don't annoy user with sign-in notifications.
Paul Jensen700f2362015-05-05 14:56:10 -0400575 if (mDontDisplaySigninNotification) return;
Paul Jensen25a217c2015-02-27 22:55:47 -0500576 // Create a CustomIntentReceiver that sends us a
577 // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
578 // touches the notification.
579 if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
Paul Jensen71b645f2014-10-13 14:13:07 -0400580 // Wait for result.
Paul Jensen25a217c2015-02-27 22:55:47 -0500581 mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
582 ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
583 CMD_LAUNCH_CAPTIVE_PORTAL_APP);
Paul Jensen71b645f2014-10-13 14:13:07 -0400584 }
Paul Jensen25a217c2015-02-27 22:55:47 -0500585 // Display the sign in notification.
Paul Jensen71b645f2014-10-13 14:13:07 -0400586 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
587 mNetworkAgentInfo.network.netId,
Paul Jensen25a217c2015-02-27 22:55:47 -0500588 mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
Paul Jensen71b645f2014-10-13 14:13:07 -0400589 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400590 // Retest for captive portal occasionally.
591 sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
592 CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
Paul Jensen869868be2014-05-15 10:33:05 -0400593 }
594
595 @Override
Paul Jensenee3e2ce2015-06-17 15:02:54 -0400596 public void exit() {
597 removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
598 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400599 }
600
Paul Jensen71b645f2014-10-13 14:13:07 -0400601 // Being in the LingeringState State indicates a Network's validated bit is true and it once
602 // was the highest scoring Network satisfying a particular NetworkRequest, but since then
Paul Jensencf4c2c62015-07-01 14:16:32 -0400603 // another Network satisfied the NetworkRequest with a higher score and hence this Network
Paul Jensen71b645f2014-10-13 14:13:07 -0400604 // is "lingered" for a fixed period of time before it is disconnected. This period of time
605 // allows apps to wrap up communication and allows for seamless reactivation if the other
606 // higher scoring Network happens to disconnect.
Paul Jensenca8f16a2014-05-09 12:47:55 -0400607 private class LingeringState extends State {
Paul Jensen79a08052014-08-21 12:44:07 -0400608 private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
Paul Jensen79a08052014-08-21 12:44:07 -0400609
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900610 private WakeupMessage mWakeupMessage;
Paul Jensen79a08052014-08-21 12:44:07 -0400611
Paul Jensenca8f16a2014-05-09 12:47:55 -0400612 @Override
613 public void enter() {
Erik Klinea488c232016-04-15 15:49:42 +0900614 mEvaluationTimer.reset();
615 final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetId;
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900616 mWakeupMessage = makeWakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
Paul Jensen79a08052014-08-21 12:44:07 -0400617 long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900618 mWakeupMessage.schedule(wakeupTime);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400619 }
620
621 @Override
622 public boolean processMessage(Message message) {
Paul Jensenca8f16a2014-05-09 12:47:55 -0400623 switch (message.what) {
624 case CMD_NETWORK_CONNECTED:
Paul Jensen22e547a2015-06-25 09:17:53 -0400625 log("Unlingered");
Paul Jensene0988542015-06-25 15:30:08 -0400626 // If already validated, go straight to validated state.
627 if (mNetworkAgentInfo.lastValidated) {
628 transitionTo(mValidatedState);
629 return HANDLED;
630 }
631 return NOT_HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400632 case CMD_LINGER_EXPIRED:
Paul Jensenca8f16a2014-05-09 12:47:55 -0400633 mConnectivityServiceHandler.sendMessage(
634 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
Paul Jensend6a3f7e2014-08-19 09:40:11 -0400635 return HANDLED;
Paul Jensenad50a1f2014-09-05 12:06:44 -0400636 case CMD_FORCE_REEVALUATION:
637 // Ignore reevaluation attempts when lingering. A reevaluation could result
638 // in a transition to the validated state which would abort the linger
639 // timeout. Lingering is the result of score assessment; validity is
640 // irrelevant.
641 return HANDLED;
Paul Jensen71b645f2014-10-13 14:13:07 -0400642 case CMD_CAPTIVE_PORTAL_APP_FINISHED:
643 // Ignore user network determination as this could abort linger timeout.
644 // Networks are only lingered once validated because:
645 // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
646 // - Once validated, a Network's validated bit is never cleared.
647 // Since networks are only lingered after being validated a user's
648 // determination will not change the death sentence that lingering entails:
649 // - If the user wants to use the network or bypasses the captive portal,
650 // the network's score will not be increased beyond its current value
651 // because it is already validated. Without a score increase there is no
652 // chance of reactivation (i.e. aborting linger timeout).
653 // - If the user does not want the network, lingering will disconnect the
654 // network anyhow.
655 return HANDLED;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400656 default:
657 return NOT_HANDLED;
658 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400659 }
Paul Jensen79a08052014-08-21 12:44:07 -0400660
661 @Override
662 public void exit() {
Lorenzo Colitti9d3aadb2015-12-02 17:51:28 +0900663 mWakeupMessage.cancel();
Paul Jensen79a08052014-08-21 12:44:07 -0400664 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400665 }
666
Udam Sainib7c24872016-01-04 12:16:14 -0800667 public static String getCaptivePortalServerUrl(Context context) {
668 String server = Settings.Global.getString(context.getContentResolver(),
669 Settings.Global.CAPTIVE_PORTAL_SERVER);
670 if (server == null) server = DEFAULT_SERVER;
671 return "http://" + server + "/generate_204";
672 }
673
Paul Jensenca8f16a2014-05-09 12:47:55 -0400674 /**
675 * Do a URL fetch on a known server to see if we get the data we expect.
676 * Returns HTTP response code.
677 */
Paul Jensencf4c2c62015-07-01 14:16:32 -0400678 @VisibleForTesting
Paul Jensen232437312016-04-06 09:51:26 -0400679 protected CaptivePortalProbeResult isCaptivePortal() {
680 if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400681
Paul Jensenca8f16a2014-05-09 12:47:55 -0400682 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400683 int httpResponseCode = 599;
Paul Jensen232437312016-04-06 09:51:26 -0400684 String redirectUrl = null;
Erik Klinea488c232016-04-15 15:49:42 +0900685 final Stopwatch probeTimer = new Stopwatch().start();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400686 try {
Udam Sainib7c24872016-01-04 12:16:14 -0800687 URL url = new URL(getCaptivePortalServerUrl(mContext));
Paul Jensen8fe17422015-02-02 11:03:03 -0500688 // On networks with a PAC instead of fetching a URL that should result in a 204
Udam Sainib7c24872016-01-04 12:16:14 -0800689 // response, we instead simply fetch the PAC script. This is done for a few reasons:
Paul Jensen8fe17422015-02-02 11:03:03 -0500690 // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
691 // until something like https://android-review.googlesource.com/#/c/115180/ lands.
692 // Network.openConnection() will ignore network-specific PACs and instead fetch
693 // using NO_PROXY. If a PAC is in place, the only fetch we know will succeed with
694 // NO_PROXY is the fetch of the PAC itself.
695 // 2. To proxy the generate_204 fetch through a PAC would require a number of things
696 // happen before the fetch can commence, namely:
697 // a) the PAC script be fetched
Udam Sainib7c24872016-01-04 12:16:14 -0800698 // b) a PAC script resolver service be fired up and resolve the captive portal
699 // server.
Paul Jensen8fe17422015-02-02 11:03:03 -0500700 // Network validation could be delayed until these prerequisities are satisifed or
701 // could simply be left to race them. Neither is an optimal solution.
702 // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
703 // fact block fetching of the generate_204 URL which would lead to false negative
704 // results for network validation.
705 boolean fetchPac = false;
Paul Jensen2f0a8972015-06-25 10:07:14 -0400706 final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
707 if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
708 url = new URL(proxyInfo.getPacFileUrl().toString());
709 fetchPac = true;
710 }
711 final StringBuffer connectInfo = new StringBuffer();
712 String hostToResolve = null;
713 // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
714 // unnecessary resolution.
715 if (proxyInfo == null || fetchPac) {
716 hostToResolve = url.getHost();
717 } else if (proxyInfo != null) {
718 hostToResolve = proxyInfo.getHost();
719 }
720 if (!TextUtils.isEmpty(hostToResolve)) {
721 connectInfo.append(", " + hostToResolve + "=");
722 final InetAddress[] addresses =
723 mNetworkAgentInfo.network.getAllByName(hostToResolve);
724 for (InetAddress address : addresses) {
725 connectInfo.append(address.getHostAddress());
726 if (address != addresses[addresses.length-1]) connectInfo.append(",");
Paul Jensen8fe17422015-02-02 11:03:03 -0500727 }
728 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700729 validationLog("Checking " + url.toString() + " on " +
Paul Jensen2f0a8972015-06-25 10:07:14 -0400730 mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
Lorenzo Colitti9f1274b2014-08-21 11:45:54 -0700731 urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
Paul Jensen8fe17422015-02-02 11:03:03 -0500732 urlConnection.setInstanceFollowRedirects(fetchPac);
Paul Jensene547ff22014-08-04 09:12:24 -0400733 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
734 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
735 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400736
737 // Time how long it takes to get a response to our request
738 long requestTimestamp = SystemClock.elapsedRealtime();
739
Pierre Imaibe12d762016-03-10 17:00:50 +0900740 httpResponseCode = urlConnection.getResponseCode();
Paul Jensen232437312016-04-06 09:51:26 -0400741 redirectUrl = urlConnection.getHeaderField("location");
Paul Jensen306f1a42014-08-04 10:59:01 -0400742
743 // Time how long it takes to get a response to our request
744 long responseTimestamp = SystemClock.elapsedRealtime();
745
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700746 validationLog("isCaptivePortal: ret=" + httpResponseCode +
747 " headers=" + urlConnection.getHeaderFields());
Paul Jensene547ff22014-08-04 09:12:24 -0400748 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
749 // portal. The only example of this seen so far was a captive portal. For
750 // the time being go with prior behavior of assuming it's not a captive
751 // portal. If it is considered a captive portal, a different sign-in URL
752 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
753 // proxy server.
754
755 // Consider 200 response with "Content-length=0" to not be a captive portal.
756 // There's no point in considering this a captive portal as the user cannot
757 // sign-in to an empty page. Probably the result of a broken transparent proxy.
758 // See http://b/9972012.
759 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700760 validationLog("Empty 200 response interpreted as 204 response.");
Paul Jensene547ff22014-08-04 09:12:24 -0400761 httpResponseCode = 204;
762 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400763
Paul Jensen8fe17422015-02-02 11:03:03 -0500764 if (httpResponseCode == 200 && fetchPac) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700765 validationLog("PAC fetch 200 response interpreted as 204 response.");
Paul Jensen8fe17422015-02-02 11:03:03 -0500766 httpResponseCode = 204;
767 }
768
Jeff Davidsonf9fff922014-12-05 16:56:08 -0800769 sendNetworkConditionsBroadcast(true /* response received */,
770 httpResponseCode != 204 /* isCaptivePortal */,
Paul Jensen306f1a42014-08-04 10:59:01 -0400771 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400772 } catch (IOException e) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700773 validationLog("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400774 if (httpResponseCode == 599) {
775 // TODO: Ping gateway and DNS server and log results.
776 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400777 } finally {
778 if (urlConnection != null) {
779 urlConnection.disconnect();
780 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400781 }
Erik Klinea488c232016-04-15 15:49:42 +0900782 NetworkMonitorEvent.logPortalProbeEvent(mNetId, probeTimer.stop(), httpResponseCode);
Paul Jensen232437312016-04-06 09:51:26 -0400783 return new CaptivePortalProbeResult(httpResponseCode, redirectUrl);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400784 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400785
786 /**
787 * @param responseReceived - whether or not we received a valid HTTP response to our request.
788 * If false, isCaptivePortal and responseTimestampMs are ignored
789 * TODO: This should be moved to the transports. The latency could be passed to the transports
790 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
791 * perhaps this could just be added to the WiFi transport only.
792 */
793 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
794 long requestTimestampMs, long responseTimestampMs) {
795 if (Settings.Global.getInt(mContext.getContentResolver(),
796 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
Paul Jensen306f1a42014-08-04 10:59:01 -0400797 return;
798 }
799
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700800 if (systemReady == false) return;
801
Paul Jensen306f1a42014-08-04 10:59:01 -0400802 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
803 switch (mNetworkAgentInfo.networkInfo.getType()) {
804 case ConnectivityManager.TYPE_WIFI:
805 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
806 if (currentWifiInfo != null) {
807 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
808 // surrounded by double quotation marks (thus violating the Javadoc), but this
809 // was changed to match the Javadoc in API 17. Since clients may have started
810 // sanitizing the output of this method since API 17 was released, we should
811 // not change it here as it would become impossible to tell whether the SSID is
812 // simply being surrounded by quotes due to the API, or whether those quotes
813 // are actually part of the SSID.
814 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
815 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
816 } else {
817 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
818 return;
819 }
820 break;
821 case ConnectivityManager.TYPE_MOBILE:
822 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
823 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
824 if (info == null) return;
825 int numRegisteredCellInfo = 0;
826 for (CellInfo cellInfo : info) {
827 if (cellInfo.isRegistered()) {
828 numRegisteredCellInfo++;
829 if (numRegisteredCellInfo > 1) {
Paul Jensen22e547a2015-06-25 09:17:53 -0400830 log("more than one registered CellInfo. Can't " +
Paul Jensen306f1a42014-08-04 10:59:01 -0400831 "tell which is active. Bailing.");
832 return;
833 }
834 if (cellInfo instanceof CellInfoCdma) {
835 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
836 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
837 } else if (cellInfo instanceof CellInfoGsm) {
838 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
839 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
840 } else if (cellInfo instanceof CellInfoLte) {
841 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
842 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
843 } else if (cellInfo instanceof CellInfoWcdma) {
844 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
845 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
846 } else {
847 if (DBG) logw("Registered cellinfo is unrecognized");
848 return;
849 }
850 }
851 }
852 break;
853 default:
854 return;
855 }
856 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
857 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
858 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
859
860 if (responseReceived) {
861 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
862 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
863 }
Paul Jensen55298582014-08-20 11:01:41 -0400864 mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
865 PERMISSION_ACCESS_NETWORK_CONDITIONS);
Paul Jensen306f1a42014-08-04 10:59:01 -0400866 }
Paul Jensend7b6ca92015-05-13 14:05:12 -0400867
868 // Allow tests to override linger time.
869 @VisibleForTesting
870 public static void SetDefaultLingerTime(int time_ms) {
871 if (Process.myUid() == Process.SYSTEM_UID) {
872 throw new SecurityException("SetDefaultLingerTime only for internal testing.");
873 }
874 DEFAULT_LINGER_DELAY_MS = time_ms;
875 }
Lorenzo Colittibfecba22016-02-21 01:09:26 +0900876
877 @VisibleForTesting
878 protected WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int i) {
879 return new WakeupMessage(c, h, s, i);
880 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400881}