blob: ae5eda35cb8071ba3b138d66f951e6b282b54aba [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 Jensen869868be2014-05-15 10:33:05 -040019import android.app.PendingIntent;
20import android.content.BroadcastReceiver;
21import android.content.ComponentName;
Paul Jensenca8f16a2014-05-09 12:47:55 -040022import android.content.Context;
Paul Jensen869868be2014-05-15 10:33:05 -040023import android.content.Intent;
24import android.content.IntentFilter;
25import android.net.ConnectivityManager;
26import android.net.Network;
Paul Jensenca8f16a2014-05-09 12:47:55 -040027import android.net.NetworkCapabilities;
28import android.net.NetworkInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -040029import android.net.wifi.WifiInfo;
30import android.net.wifi.WifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040031import android.os.Handler;
32import android.os.Message;
Paul Jensen306f1a42014-08-04 10:59:01 -040033import android.os.SystemClock;
Paul Jensenca8f16a2014-05-09 12:47:55 -040034import android.os.SystemProperties;
Paul Jensen869868be2014-05-15 10:33:05 -040035import android.os.UserHandle;
Paul Jensenca8f16a2014-05-09 12:47:55 -040036import android.provider.Settings;
Paul Jensen306f1a42014-08-04 10:59:01 -040037import android.telephony.CellIdentityCdma;
38import android.telephony.CellIdentityGsm;
39import android.telephony.CellIdentityLte;
40import android.telephony.CellIdentityWcdma;
41import android.telephony.CellInfo;
42import android.telephony.CellInfoCdma;
43import android.telephony.CellInfoGsm;
44import android.telephony.CellInfoLte;
45import android.telephony.CellInfoWcdma;
46import android.telephony.TelephonyManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -040047
48import com.android.internal.util.Protocol;
49import com.android.internal.util.State;
50import com.android.internal.util.StateMachine;
Paul Jensen869868be2014-05-15 10:33:05 -040051import com.android.server.ConnectivityService;
Paul Jensenca8f16a2014-05-09 12:47:55 -040052import com.android.server.connectivity.NetworkAgentInfo;
53
Paul Jensenca8f16a2014-05-09 12:47:55 -040054import java.io.IOException;
Paul Jensenca8f16a2014-05-09 12:47:55 -040055import java.net.HttpURLConnection;
Paul Jensenca8f16a2014-05-09 12:47:55 -040056import java.net.URL;
Paul Jensen306f1a42014-08-04 10:59:01 -040057import java.util.List;
Paul Jensenca8f16a2014-05-09 12:47:55 -040058
59/**
60 * {@hide}
61 */
62public class NetworkMonitor extends StateMachine {
63 private static final boolean DBG = true;
64 private static final String TAG = "NetworkMonitor";
65 private static final String DEFAULT_SERVER = "clients3.google.com";
66 private static final int SOCKET_TIMEOUT_MS = 10000;
Paul Jensen306f1a42014-08-04 10:59:01 -040067 public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
68 "android.net.conn.NETWORK_CONDITIONS_MEASURED";
69 public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
70 public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
71 public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
72 public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
73 public static final String EXTRA_CELL_ID = "extra_cellid";
74 public static final String EXTRA_SSID = "extra_ssid";
75 public static final String EXTRA_BSSID = "extra_bssid";
76 /** real time since boot */
77 public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
78 public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
79
80 private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
81 "android.permission.ACCESS_NETWORK_CONDITIONS";
Paul Jensenca8f16a2014-05-09 12:47:55 -040082
Paul Jensen869868be2014-05-15 10:33:05 -040083 // Intent broadcast when user selects sign-in notification.
84 private static final String ACTION_SIGN_IN_REQUESTED =
85 "android.net.netmon.sign_in_requested";
86
87 // Keep these in sync with CaptivePortalLoginActivity.java.
88 // Intent broadcast from CaptivePortalLogin indicating sign-in is complete.
89 // Extras:
90 // EXTRA_TEXT = netId
91 // LOGGED_IN_RESULT = "1" if we should use network, "0" if not.
92 private static final String ACTION_CAPTIVE_PORTAL_LOGGED_IN =
93 "android.net.netmon.captive_portal_logged_in";
94 private static final String LOGGED_IN_RESULT = "result";
95
Paul Jensenca8f16a2014-05-09 12:47:55 -040096 private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
97
98 /**
99 * Inform NetworkMonitor that their network is connected.
100 * Initiates Network Validation.
101 */
102 public static final int CMD_NETWORK_CONNECTED = BASE + 1;
103
104 /**
105 * Inform ConnectivityService that the network is validated.
106 * obj = NetworkAgentInfo
107 */
108 public static final int EVENT_NETWORK_VALIDATED = BASE + 2;
109
110 /**
111 * Inform NetworkMonitor to linger a network. The Monitor should
112 * start a timer and/or start watching for zero live connections while
113 * moving towards LINGER_COMPLETE. After the Linger period expires
114 * (or other events mark the end of the linger state) the LINGER_COMPLETE
115 * event should be sent and the network will be shut down. If a
116 * CMD_NETWORK_CONNECTED happens before the LINGER completes
117 * it indicates further desire to keep the network alive and so
118 * the LINGER is aborted.
119 */
120 public static final int CMD_NETWORK_LINGER = BASE + 3;
121
122 /**
123 * Message to self indicating linger delay has expired.
124 * arg1 = Token to ignore old messages.
125 */
126 private static final int CMD_LINGER_EXPIRED = BASE + 4;
127
128 /**
129 * Inform ConnectivityService that the network LINGER period has
130 * expired.
131 * obj = NetworkAgentInfo
132 */
133 public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
134
135 /**
Paul Jensenca8f16a2014-05-09 12:47:55 -0400136 * Message to self indicating it's time to evaluate a network's connectivity.
137 * arg1 = Token to ignore old messages.
138 */
Paul Jensen869868be2014-05-15 10:33:05 -0400139 private static final int CMD_REEVALUATE = BASE + 6;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400140
141 /**
142 * Message to self indicating network evaluation is complete.
143 * arg1 = Token to ignore old messages.
144 * arg2 = HTTP response code of network evaluation.
145 */
Paul Jensen869868be2014-05-15 10:33:05 -0400146 private static final int EVENT_REEVALUATION_COMPLETE = BASE + 7;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400147
148 /**
149 * Inform NetworkMonitor that the network has disconnected.
150 */
Paul Jensen869868be2014-05-15 10:33:05 -0400151 public static final int CMD_NETWORK_DISCONNECTED = BASE + 8;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400152
153 /**
154 * Force evaluation even if it has succeeded in the past.
155 */
Paul Jensen869868be2014-05-15 10:33:05 -0400156 public static final int CMD_FORCE_REEVALUATION = BASE + 9;
157
158 /**
159 * Message to self indicating captive portal login is complete.
160 * arg1 = Token to ignore old messages.
161 * arg2 = 1 if we should use this network, 0 otherwise.
162 */
163 private static final int CMD_CAPTIVE_PORTAL_LOGGED_IN = BASE + 10;
164
165 /**
166 * Message to self indicating user desires to log into captive portal.
167 * arg1 = Token to ignore old messages.
168 */
169 private static final int CMD_USER_WANTS_SIGN_IN = BASE + 11;
170
171 /**
172 * Request ConnectivityService display provisioning notification.
173 * arg1 = Whether to make the notification visible.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400174 * arg2 = NetID.
175 * obj = Intent to be launched when notification selected by user, null if !arg1.
Paul Jensen869868be2014-05-15 10:33:05 -0400176 */
177 public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 12;
178
179 /**
180 * Message to self indicating sign-in app bypassed captive portal.
181 */
182 private static final int EVENT_APP_BYPASSED_CAPTIVE_PORTAL = BASE + 13;
183
184 /**
185 * Message to self indicating no sign-in app responded.
186 */
187 private static final int EVENT_NO_APP_RESPONSE = BASE + 14;
188
189 /**
190 * Message to self indicating sign-in app indicates sign-in is not possible.
191 */
192 private static final int EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE = BASE + 15;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400193
194 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
195 // Default to 30s linger time-out.
196 private static final int DEFAULT_LINGER_DELAY_MS = 30000;
197 private final int mLingerDelayMs;
198 private int mLingerToken = 0;
199
Paul Jensenca8f16a2014-05-09 12:47:55 -0400200 // Negative values disable reevaluation.
201 private static final String REEVALUATE_DELAY_PROPERTY = "persist.netmon.reeval_delay";
202 // Default to 5s reevaluation delay.
203 private static final int DEFAULT_REEVALUATE_DELAY_MS = 5000;
Paul Jensen869868be2014-05-15 10:33:05 -0400204 private static final int MAX_RETRIES = 10;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400205 private final int mReevaluateDelayMs;
206 private int mReevaluateToken = 0;
207
Paul Jensen869868be2014-05-15 10:33:05 -0400208 private int mCaptivePortalLoggedInToken = 0;
209 private int mUserPromptedToken = 0;
210
Paul Jensenca8f16a2014-05-09 12:47:55 -0400211 private final Context mContext;
212 private final Handler mConnectivityServiceHandler;
213 private final NetworkAgentInfo mNetworkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400214 private final TelephonyManager mTelephonyManager;
215 private final WifiManager mWifiManager;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400216
217 private String mServer;
218 private boolean mIsCaptivePortalCheckEnabled = false;
219
220 private State mDefaultState = new DefaultState();
221 private State mOfflineState = new OfflineState();
222 private State mValidatedState = new ValidatedState();
223 private State mEvaluatingState = new EvaluatingState();
Paul Jensen869868be2014-05-15 10:33:05 -0400224 private State mUninteractiveAppsPromptedState = new UninteractiveAppsPromptedState();
225 private State mUserPromptedState = new UserPromptedState();
226 private State mInteractiveAppsPromptedState = new InteractiveAppsPromptedState();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400227 private State mCaptivePortalState = new CaptivePortalState();
228 private State mLingeringState = new LingeringState();
229
230 public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo) {
231 // Add suffix indicating which NetworkMonitor we're talking about.
232 super(TAG + networkAgentInfo.name());
233
234 mContext = context;
235 mConnectivityServiceHandler = handler;
236 mNetworkAgentInfo = networkAgentInfo;
Paul Jensen306f1a42014-08-04 10:59:01 -0400237 mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
238 mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400239
240 addState(mDefaultState);
241 addState(mOfflineState, mDefaultState);
242 addState(mValidatedState, mDefaultState);
243 addState(mEvaluatingState, mDefaultState);
Paul Jensen869868be2014-05-15 10:33:05 -0400244 addState(mUninteractiveAppsPromptedState, mDefaultState);
245 addState(mUserPromptedState, mDefaultState);
246 addState(mInteractiveAppsPromptedState, mDefaultState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400247 addState(mCaptivePortalState, mDefaultState);
248 addState(mLingeringState, mDefaultState);
249 setInitialState(mOfflineState);
250
251 mServer = Settings.Global.getString(mContext.getContentResolver(),
252 Settings.Global.CAPTIVE_PORTAL_SERVER);
253 if (mServer == null) mServer = DEFAULT_SERVER;
254
255 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
256 mReevaluateDelayMs = SystemProperties.getInt(REEVALUATE_DELAY_PROPERTY,
257 DEFAULT_REEVALUATE_DELAY_MS);
258
Paul Jensen869868be2014-05-15 10:33:05 -0400259 mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
260 Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400261
262 start();
263 }
264
265 private class DefaultState extends State {
266 @Override
267 public boolean processMessage(Message message) {
268 if (DBG) log(getName() + message.toString());
269 switch (message.what) {
270 case CMD_NETWORK_LINGER:
271 if (DBG) log("Lingering");
272 transitionTo(mLingeringState);
273 break;
274 case CMD_NETWORK_CONNECTED:
275 if (DBG) log("Connected");
276 transitionTo(mEvaluatingState);
277 break;
278 case CMD_NETWORK_DISCONNECTED:
Robert Greenwalt1fd9aee2014-07-17 16:11:38 -0700279 if (DBG) log("Disconnected - quitting");
280 quit();
Paul Jensenca8f16a2014-05-09 12:47:55 -0400281 break;
282 case CMD_FORCE_REEVALUATION:
283 if (DBG) log("Forcing reevaluation");
284 transitionTo(mEvaluatingState);
285 break;
286 default:
287 break;
288 }
289 return HANDLED;
290 }
291 }
292
293 private class OfflineState extends State {
294 @Override
295 public boolean processMessage(Message message) {
296 if (DBG) log(getName() + message.toString());
297 return NOT_HANDLED;
298 }
299 }
300
301 private class ValidatedState extends State {
302 @Override
303 public void enter() {
304 if (DBG) log("Validated");
305 mConnectivityServiceHandler.sendMessage(
306 obtainMessage(EVENT_NETWORK_VALIDATED, mNetworkAgentInfo));
307 }
308
309 @Override
310 public boolean processMessage(Message message) {
311 if (DBG) log(getName() + message.toString());
312 switch (message.what) {
313 case CMD_NETWORK_CONNECTED:
314 transitionTo(mValidatedState);
315 break;
316 default:
317 return NOT_HANDLED;
318 }
319 return HANDLED;
320 }
321 }
322
323 private class EvaluatingState extends State {
Paul Jensen869868be2014-05-15 10:33:05 -0400324 private int mRetries;
325
Paul Jensenca8f16a2014-05-09 12:47:55 -0400326 private class EvaluateInternetConnectivity extends Thread {
327 private int mToken;
328 EvaluateInternetConnectivity(int token) {
329 mToken = token;
330 }
331 public void run() {
332 sendMessage(EVENT_REEVALUATION_COMPLETE, mToken, isCaptivePortal());
333 }
334 }
335
336 @Override
337 public void enter() {
Paul Jensen869868be2014-05-15 10:33:05 -0400338 mRetries = 0;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400339 sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
340 }
341
342 @Override
343 public boolean processMessage(Message message) {
344 if (DBG) log(getName() + message.toString());
345 switch (message.what) {
346 case CMD_REEVALUATE:
347 if (message.arg1 != mReevaluateToken)
348 break;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -0400349 if (mNetworkAgentInfo.isVPN()) {
350 transitionTo(mValidatedState);
351 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400352 // If network provides no internet connectivity adjust evaluation.
Paul Jensen869868be2014-05-15 10:33:05 -0400353 if (!mNetworkAgentInfo.networkCapabilities.hasCapability(
Paul Jensenca8f16a2014-05-09 12:47:55 -0400354 NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
355 // TODO: Try to verify something works. Do all gateways respond to pings?
356 transitionTo(mValidatedState);
357 }
358 // Kick off a thread to perform internet connectivity evaluation.
359 Thread thread = new EvaluateInternetConnectivity(mReevaluateToken);
360 thread.run();
361 break;
362 case EVENT_REEVALUATION_COMPLETE:
363 if (message.arg1 != mReevaluateToken)
364 break;
365 int httpResponseCode = message.arg2;
366 if (httpResponseCode == 204) {
367 transitionTo(mValidatedState);
368 } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
Paul Jensen869868be2014-05-15 10:33:05 -0400369 transitionTo(mUninteractiveAppsPromptedState);
370 } else if (++mRetries > MAX_RETRIES) {
371 transitionTo(mOfflineState);
372 } else if (mReevaluateDelayMs >= 0) {
373 Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
374 sendMessageDelayed(msg, mReevaluateDelayMs);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400375 }
376 break;
377 default:
378 return NOT_HANDLED;
379 }
380 return HANDLED;
381 }
382 }
383
Paul Jensen869868be2014-05-15 10:33:05 -0400384 private class AppRespondedBroadcastReceiver extends BroadcastReceiver {
385 private static final int CAPTIVE_PORTAL_UNINITIALIZED_RETURN_CODE = 0;
386 private boolean mCanceled;
387 AppRespondedBroadcastReceiver() {
388 mCanceled = false;
389 }
390 public void send(String action) {
391 Intent intent = new Intent(action);
392 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
393 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, null, this, getHandler(),
394 CAPTIVE_PORTAL_UNINITIALIZED_RETURN_CODE, null, null);
395 }
396 public void cancel() {
397 mCanceled = true;
398 }
399 @Override
400 public void onReceive(Context context, Intent intent) {
401 if (!mCanceled) {
402 cancel();
403 switch (getResultCode()) {
404 case ConnectivityManager.CAPTIVE_PORTAL_SIGNED_IN:
405 sendMessage(EVENT_APP_BYPASSED_CAPTIVE_PORTAL);
406 break;
407 case ConnectivityManager.CAPTIVE_PORTAL_DISCONNECT:
408 sendMessage(EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE);
409 break;
410 // NOTE: This case label makes compiler enforce no overlap between result codes.
411 case CAPTIVE_PORTAL_UNINITIALIZED_RETURN_CODE:
412 default:
413 sendMessage(EVENT_NO_APP_RESPONSE);
414 break;
415 }
416 }
417 }
418 }
419
420 private class UninteractiveAppsPromptedState extends State {
421 private AppRespondedBroadcastReceiver mReceiver;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400422 @Override
423 public void enter() {
Paul Jensen869868be2014-05-15 10:33:05 -0400424 mReceiver = new AppRespondedBroadcastReceiver();
425 mReceiver.send(ConnectivityManager.ACTION_CAPTIVE_PORTAL_DETECTED);
426 }
427 @Override
428 public boolean processMessage(Message message) {
429 if (DBG) log(getName() + message.toString());
430 switch (message.what) {
431 case EVENT_APP_BYPASSED_CAPTIVE_PORTAL:
432 transitionTo(mValidatedState);
433 break;
434 case EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE:
435 transitionTo(mOfflineState);
436 break;
437 case EVENT_NO_APP_RESPONSE:
438 transitionTo(mUserPromptedState);
439 break;
440 default:
441 return NOT_HANDLED;
442 }
443 return HANDLED;
444 }
445 public void exit() {
446 mReceiver.cancel();
447 }
448 }
449
450 private class UserPromptedState extends State {
451 private class UserRespondedBroadcastReceiver extends BroadcastReceiver {
452 private final int mToken;
453 UserRespondedBroadcastReceiver(int token) {
454 mToken = token;
455 }
456 @Override
457 public void onReceive(Context context, Intent intent) {
458 if (Integer.parseInt(intent.getStringExtra(Intent.EXTRA_TEXT)) ==
459 mNetworkAgentInfo.network.netId) {
460 sendMessage(obtainMessage(CMD_USER_WANTS_SIGN_IN, mToken));
461 }
462 }
463 }
464
465 private UserRespondedBroadcastReceiver mUserRespondedBroadcastReceiver;
466
467 @Override
468 public void enter() {
469 // Wait for user to select sign-in notifcation.
470 mUserRespondedBroadcastReceiver = new UserRespondedBroadcastReceiver(
471 ++mUserPromptedToken);
472 IntentFilter filter = new IntentFilter(ACTION_SIGN_IN_REQUESTED);
473 mContext.registerReceiver(mUserRespondedBroadcastReceiver, filter);
474 // Initiate notification to sign-in.
475 Intent intent = new Intent(ACTION_SIGN_IN_REQUESTED);
476 intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(mNetworkAgentInfo.network.netId));
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400477 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
478 mNetworkAgentInfo.network.netId,
Paul Jensen869868be2014-05-15 10:33:05 -0400479 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Paul Jensen869868be2014-05-15 10:33:05 -0400480 mConnectivityServiceHandler.sendMessage(message);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400481 }
482
483 @Override
484 public boolean processMessage(Message message) {
485 if (DBG) log(getName() + message.toString());
486 switch (message.what) {
Paul Jensen869868be2014-05-15 10:33:05 -0400487 case CMD_USER_WANTS_SIGN_IN:
488 if (message.arg1 != mUserPromptedToken)
Paul Jensenca8f16a2014-05-09 12:47:55 -0400489 break;
Paul Jensen869868be2014-05-15 10:33:05 -0400490 transitionTo(mInteractiveAppsPromptedState);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400491 break;
492 default:
493 return NOT_HANDLED;
494 }
495 return HANDLED;
496 }
Paul Jensen869868be2014-05-15 10:33:05 -0400497
498 @Override
499 public void exit() {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -0400500 Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
501 mNetworkAgentInfo.network.netId, null);
Paul Jensen869868be2014-05-15 10:33:05 -0400502 mConnectivityServiceHandler.sendMessage(message);
503 mContext.unregisterReceiver(mUserRespondedBroadcastReceiver);
504 mUserRespondedBroadcastReceiver = null;
505 }
506 }
507
508 private class InteractiveAppsPromptedState extends State {
509 private AppRespondedBroadcastReceiver mReceiver;
510 @Override
511 public void enter() {
512 mReceiver = new AppRespondedBroadcastReceiver();
513 mReceiver.send(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
514 }
515 @Override
516 public boolean processMessage(Message message) {
517 if (DBG) log(getName() + message.toString());
518 switch (message.what) {
519 case EVENT_APP_BYPASSED_CAPTIVE_PORTAL:
520 transitionTo(mValidatedState);
521 break;
522 case EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE:
523 transitionTo(mOfflineState);
524 break;
525 case EVENT_NO_APP_RESPONSE:
526 transitionTo(mCaptivePortalState);
527 break;
528 default:
529 return NOT_HANDLED;
530 }
531 return HANDLED;
532 }
533 public void exit() {
534 mReceiver.cancel();
535 }
536 }
537
538 private class CaptivePortalState extends State {
539 private class CaptivePortalLoggedInBroadcastReceiver extends BroadcastReceiver {
540 private final int mToken;
541
542 CaptivePortalLoggedInBroadcastReceiver(int token) {
543 mToken = token;
544 }
545
546 @Override
547 public void onReceive(Context context, Intent intent) {
548 if (Integer.parseInt(intent.getStringExtra(Intent.EXTRA_TEXT)) ==
549 mNetworkAgentInfo.network.netId) {
550 sendMessage(obtainMessage(CMD_CAPTIVE_PORTAL_LOGGED_IN, mToken,
551 Integer.parseInt(intent.getStringExtra(LOGGED_IN_RESULT))));
552 }
553 }
554 }
555
556 private CaptivePortalLoggedInBroadcastReceiver mCaptivePortalLoggedInBroadcastReceiver;
557
558 @Override
559 public void enter() {
560 Intent intent = new Intent(Intent.ACTION_SEND);
561 intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(mNetworkAgentInfo.network.netId));
562 intent.setType("text/plain");
563 intent.setComponent(new ComponentName("com.android.captiveportallogin",
564 "com.android.captiveportallogin.CaptivePortalLoginActivity"));
565 intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
566
567 // Wait for result.
568 mCaptivePortalLoggedInBroadcastReceiver = new CaptivePortalLoggedInBroadcastReceiver(
569 ++mCaptivePortalLoggedInToken);
570 IntentFilter filter = new IntentFilter(ACTION_CAPTIVE_PORTAL_LOGGED_IN);
571 mContext.registerReceiver(mCaptivePortalLoggedInBroadcastReceiver, filter);
572 // Initiate app to log in.
573 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
574 }
575
576 @Override
577 public boolean processMessage(Message message) {
578 if (DBG) log(getName() + message.toString());
579 switch (message.what) {
580 case CMD_CAPTIVE_PORTAL_LOGGED_IN:
581 if (message.arg1 != mCaptivePortalLoggedInToken)
582 break;
583 if (message.arg2 == 0) {
584 // TODO: Should teardown network.
585 transitionTo(mOfflineState);
586 } else {
587 transitionTo(mValidatedState);
588 }
589 break;
590 default:
591 return NOT_HANDLED;
592 }
593 return HANDLED;
594 }
595
596 @Override
597 public void exit() {
598 mContext.unregisterReceiver(mCaptivePortalLoggedInBroadcastReceiver);
599 mCaptivePortalLoggedInBroadcastReceiver = null;
600 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400601 }
602
603 private class LingeringState extends State {
604 @Override
605 public void enter() {
606 Message message = obtainMessage(CMD_LINGER_EXPIRED, ++mLingerToken, 0);
607 sendMessageDelayed(message, mLingerDelayMs);
608 }
609
610 @Override
611 public boolean processMessage(Message message) {
612 if (DBG) log(getName() + message.toString());
613 switch (message.what) {
614 case CMD_NETWORK_CONNECTED:
615 // Go straight to active as we've already evaluated.
616 transitionTo(mValidatedState);
617 break;
618 case CMD_LINGER_EXPIRED:
619 if (message.arg1 != mLingerToken)
620 break;
621 mConnectivityServiceHandler.sendMessage(
622 obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
623 break;
624 default:
625 return NOT_HANDLED;
626 }
627 return HANDLED;
628 }
629 }
630
631 /**
632 * Do a URL fetch on a known server to see if we get the data we expect.
633 * Returns HTTP response code.
634 */
635 private int isCaptivePortal() {
636 if (!mIsCaptivePortalCheckEnabled) return 204;
637
Paul Jensenca8f16a2014-05-09 12:47:55 -0400638 HttpURLConnection urlConnection = null;
Paul Jensen869868be2014-05-15 10:33:05 -0400639 int httpResponseCode = 599;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400640 try {
Paul Jensene547ff22014-08-04 09:12:24 -0400641 URL url = new URL("http", mServer, "/generate_204");
642 if (DBG) {
643 log("Checking " + url.toString() + " on " +
644 mNetworkAgentInfo.networkInfo.getExtraInfo());
Paul Jensenca8f16a2014-05-09 12:47:55 -0400645 }
Paul Jensene547ff22014-08-04 09:12:24 -0400646 url = mNetworkAgentInfo.network.getBoundURL(url);
647 urlConnection = (HttpURLConnection) url.openConnection();
648 urlConnection.setInstanceFollowRedirects(false);
649 urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
650 urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
651 urlConnection.setUseCaches(false);
Paul Jensen306f1a42014-08-04 10:59:01 -0400652
653 // Time how long it takes to get a response to our request
654 long requestTimestamp = SystemClock.elapsedRealtime();
655
Paul Jensene547ff22014-08-04 09:12:24 -0400656 urlConnection.getInputStream();
Paul Jensen306f1a42014-08-04 10:59:01 -0400657
658 // Time how long it takes to get a response to our request
659 long responseTimestamp = SystemClock.elapsedRealtime();
660
Paul Jensene547ff22014-08-04 09:12:24 -0400661 httpResponseCode = urlConnection.getResponseCode();
662 if (DBG) {
663 log("isCaptivePortal: ret=" + httpResponseCode +
664 " headers=" + urlConnection.getHeaderFields());
665 }
666 // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
667 // portal. The only example of this seen so far was a captive portal. For
668 // the time being go with prior behavior of assuming it's not a captive
669 // portal. If it is considered a captive portal, a different sign-in URL
670 // is needed (i.e. can't browse a 204). This could be the result of an HTTP
671 // proxy server.
672
673 // Consider 200 response with "Content-length=0" to not be a captive portal.
674 // There's no point in considering this a captive portal as the user cannot
675 // sign-in to an empty page. Probably the result of a broken transparent proxy.
676 // See http://b/9972012.
677 if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
678 if (DBG) log("Empty 200 response interpreted as 204 response.");
679 httpResponseCode = 204;
680 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400681
682 sendNetworkConditionsBroadcast(true /* response received */, httpResponseCode == 204,
683 requestTimestamp, responseTimestamp);
Paul Jensenca8f16a2014-05-09 12:47:55 -0400684 } catch (IOException e) {
685 if (DBG) log("Probably not a portal: exception " + e);
Paul Jensen869868be2014-05-15 10:33:05 -0400686 if (httpResponseCode == 599) {
687 // TODO: Ping gateway and DNS server and log results.
688 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400689 } finally {
690 if (urlConnection != null) {
691 urlConnection.disconnect();
692 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400693 }
694 return httpResponseCode;
695 }
Paul Jensen306f1a42014-08-04 10:59:01 -0400696
697 /**
698 * @param responseReceived - whether or not we received a valid HTTP response to our request.
699 * If false, isCaptivePortal and responseTimestampMs are ignored
700 * TODO: This should be moved to the transports. The latency could be passed to the transports
701 * along with the captive portal result. Currently the TYPE_MOBILE broadcasts appear unused so
702 * perhaps this could just be added to the WiFi transport only.
703 */
704 private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
705 long requestTimestampMs, long responseTimestampMs) {
706 if (Settings.Global.getInt(mContext.getContentResolver(),
707 Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
708 if (DBG) log("Don't send network conditions - lacking user consent.");
709 return;
710 }
711
712 Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
713 switch (mNetworkAgentInfo.networkInfo.getType()) {
714 case ConnectivityManager.TYPE_WIFI:
715 WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
716 if (currentWifiInfo != null) {
717 // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
718 // surrounded by double quotation marks (thus violating the Javadoc), but this
719 // was changed to match the Javadoc in API 17. Since clients may have started
720 // sanitizing the output of this method since API 17 was released, we should
721 // not change it here as it would become impossible to tell whether the SSID is
722 // simply being surrounded by quotes due to the API, or whether those quotes
723 // are actually part of the SSID.
724 latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
725 latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
726 } else {
727 if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
728 return;
729 }
730 break;
731 case ConnectivityManager.TYPE_MOBILE:
732 latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
733 List<CellInfo> info = mTelephonyManager.getAllCellInfo();
734 if (info == null) return;
735 int numRegisteredCellInfo = 0;
736 for (CellInfo cellInfo : info) {
737 if (cellInfo.isRegistered()) {
738 numRegisteredCellInfo++;
739 if (numRegisteredCellInfo > 1) {
740 if (DBG) log("more than one registered CellInfo. Can't " +
741 "tell which is active. Bailing.");
742 return;
743 }
744 if (cellInfo instanceof CellInfoCdma) {
745 CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
746 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
747 } else if (cellInfo instanceof CellInfoGsm) {
748 CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
749 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
750 } else if (cellInfo instanceof CellInfoLte) {
751 CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
752 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
753 } else if (cellInfo instanceof CellInfoWcdma) {
754 CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
755 latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
756 } else {
757 if (DBG) logw("Registered cellinfo is unrecognized");
758 return;
759 }
760 }
761 }
762 break;
763 default:
764 return;
765 }
766 latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
767 latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
768 latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
769
770 if (responseReceived) {
771 latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
772 latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
773 }
774 mContext.sendBroadcast(latencyBroadcast, PERMISSION_ACCESS_NETWORK_CONDITIONS);
775 }
Paul Jensenca8f16a2014-05-09 12:47:55 -0400776}