NetworkMonitor.java revision d6a3f7ed90d7fa861f579968f12cc30015b3a989
1/*
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
19import android.app.PendingIntent;
20import android.content.BroadcastReceiver;
21import android.content.ComponentName;
22import android.content.Context;
23import android.content.Intent;
24import android.content.IntentFilter;
25import android.net.ConnectivityManager;
26import android.net.Network;
27import android.net.NetworkCapabilities;
28import android.net.NetworkInfo;
29import android.net.wifi.WifiInfo;
30import android.net.wifi.WifiManager;
31import android.os.Handler;
32import android.os.Message;
33import android.os.SystemClock;
34import android.os.SystemProperties;
35import android.os.UserHandle;
36import android.provider.Settings;
37import 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;
47
48import com.android.internal.util.Protocol;
49import com.android.internal.util.State;
50import com.android.internal.util.StateMachine;
51import com.android.server.ConnectivityService;
52import com.android.server.connectivity.NetworkAgentInfo;
53
54import java.io.IOException;
55import java.net.HttpURLConnection;
56import java.net.URL;
57import java.util.List;
58
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;
67    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";
82
83    // 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
96    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    /**
136     * Message to self indicating it's time to evaluate a network's connectivity.
137     * arg1 = Token to ignore old messages.
138     */
139    private static final int CMD_REEVALUATE = BASE + 6;
140
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     */
146    private static final int EVENT_REEVALUATION_COMPLETE = BASE + 7;
147
148    /**
149     * Inform NetworkMonitor that the network has disconnected.
150     */
151    public static final int CMD_NETWORK_DISCONNECTED = BASE + 8;
152
153    /**
154     * Force evaluation even if it has succeeded in the past.
155     */
156    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.
174     * arg2    = NetID.
175     * obj     = Intent to be launched when notification selected by user, null if !arg1.
176     */
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;
193
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
200    // 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;
204    private static final int MAX_RETRIES = 10;
205    private final int mReevaluateDelayMs;
206    private int mReevaluateToken = 0;
207
208    private int mCaptivePortalLoggedInToken = 0;
209    private int mUserPromptedToken = 0;
210
211    private final Context mContext;
212    private final Handler mConnectivityServiceHandler;
213    private final NetworkAgentInfo mNetworkAgentInfo;
214    private final TelephonyManager mTelephonyManager;
215    private final WifiManager mWifiManager;
216
217    private String mServer;
218    private boolean mIsCaptivePortalCheckEnabled = false;
219
220    public boolean systemReady = false;
221
222    private State mDefaultState = new DefaultState();
223    private State mOfflineState = new OfflineState();
224    private State mValidatedState = new ValidatedState();
225    private State mEvaluatingState = new EvaluatingState();
226    private State mUninteractiveAppsPromptedState = new UninteractiveAppsPromptedState();
227    private State mUserPromptedState = new UserPromptedState();
228    private State mInteractiveAppsPromptedState = new InteractiveAppsPromptedState();
229    private State mCaptivePortalState = new CaptivePortalState();
230    private State mLingeringState = new LingeringState();
231
232    public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo) {
233        // Add suffix indicating which NetworkMonitor we're talking about.
234        super(TAG + networkAgentInfo.name());
235
236        mContext = context;
237        mConnectivityServiceHandler = handler;
238        mNetworkAgentInfo = networkAgentInfo;
239        mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
240        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
241
242        addState(mDefaultState);
243        addState(mOfflineState, mDefaultState);
244        addState(mValidatedState, mDefaultState);
245        addState(mEvaluatingState, mDefaultState);
246        addState(mUninteractiveAppsPromptedState, mDefaultState);
247        addState(mUserPromptedState, mDefaultState);
248        addState(mInteractiveAppsPromptedState, mDefaultState);
249        addState(mCaptivePortalState, mDefaultState);
250        addState(mLingeringState, mDefaultState);
251        setInitialState(mOfflineState);
252
253        mServer = Settings.Global.getString(mContext.getContentResolver(),
254                Settings.Global.CAPTIVE_PORTAL_SERVER);
255        if (mServer == null) mServer = DEFAULT_SERVER;
256
257        mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
258        mReevaluateDelayMs = SystemProperties.getInt(REEVALUATE_DELAY_PROPERTY,
259                DEFAULT_REEVALUATE_DELAY_MS);
260
261        mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
262                Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
263
264        start();
265    }
266
267    private class DefaultState extends State {
268        @Override
269        public boolean processMessage(Message message) {
270            if (DBG) log(getName() + message.toString());
271            switch (message.what) {
272                case CMD_NETWORK_LINGER:
273                    if (DBG) log("Lingering");
274                    transitionTo(mLingeringState);
275                    return HANDLED;
276                case CMD_NETWORK_CONNECTED:
277                    if (DBG) log("Connected");
278                    transitionTo(mEvaluatingState);
279                    return HANDLED;
280                case CMD_NETWORK_DISCONNECTED:
281                    if (DBG) log("Disconnected - quitting");
282                    quit();
283                    return HANDLED;
284                case CMD_FORCE_REEVALUATION:
285                    if (DBG) log("Forcing reevaluation");
286                    transitionTo(mEvaluatingState);
287                    return HANDLED;
288                default:
289                    return HANDLED;
290            }
291        }
292    }
293
294    private class OfflineState extends State {
295        @Override
296        public boolean processMessage(Message message) {
297            if (DBG) log(getName() + message.toString());
298            return NOT_HANDLED;
299        }
300    }
301
302    private class ValidatedState extends State {
303        @Override
304        public void enter() {
305            if (DBG) log("Validated");
306            mConnectivityServiceHandler.sendMessage(
307                    obtainMessage(EVENT_NETWORK_VALIDATED, mNetworkAgentInfo));
308        }
309
310        @Override
311        public boolean processMessage(Message message) {
312            if (DBG) log(getName() + message.toString());
313            switch (message.what) {
314                case CMD_NETWORK_CONNECTED:
315                    transitionTo(mValidatedState);
316                    return HANDLED;
317                default:
318                    return NOT_HANDLED;
319            }
320        }
321    }
322
323    private class EvaluatingState extends State {
324        private int mRetries;
325
326        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() {
338            mRetries = 0;
339            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                        return HANDLED;
349                    if (mNetworkAgentInfo.isVPN()) {
350                        transitionTo(mValidatedState);
351                        return HANDLED;
352                    }
353                    // If network provides no internet connectivity adjust evaluation.
354                    if (!mNetworkAgentInfo.networkCapabilities.hasCapability(
355                            NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
356                        // TODO: Try to verify something works.  Do all gateways respond to pings?
357                        transitionTo(mValidatedState);
358                        return HANDLED;
359                    }
360                    // Kick off a thread to perform internet connectivity evaluation.
361                    Thread thread = new EvaluateInternetConnectivity(mReevaluateToken);
362                    thread.run();
363                    return HANDLED;
364                case EVENT_REEVALUATION_COMPLETE:
365                    if (message.arg1 != mReevaluateToken)
366                        return HANDLED;
367                    int httpResponseCode = message.arg2;
368                    if (httpResponseCode == 204) {
369                        transitionTo(mValidatedState);
370                    } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
371                        transitionTo(mUninteractiveAppsPromptedState);
372                    } else if (++mRetries > MAX_RETRIES) {
373                        transitionTo(mOfflineState);
374                    } else if (mReevaluateDelayMs >= 0) {
375                        Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
376                        sendMessageDelayed(msg, mReevaluateDelayMs);
377                    }
378                    return HANDLED;
379                default:
380                    return NOT_HANDLED;
381            }
382        }
383    }
384
385    private class AppRespondedBroadcastReceiver extends BroadcastReceiver {
386        private static final int CAPTIVE_PORTAL_UNINITIALIZED_RETURN_CODE = 0;
387        private boolean mCanceled;
388        AppRespondedBroadcastReceiver() {
389            mCanceled = false;
390        }
391        public void send(String action) {
392            Intent intent = new Intent(action);
393            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
394            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL, null, this, getHandler(),
395                    CAPTIVE_PORTAL_UNINITIALIZED_RETURN_CODE, null, null);
396        }
397        public void cancel() {
398            mCanceled = true;
399        }
400        @Override
401        public void onReceive(Context context, Intent intent) {
402            if (!mCanceled) {
403                cancel();
404                switch (getResultCode()) {
405                    case ConnectivityManager.CAPTIVE_PORTAL_SIGNED_IN:
406                        sendMessage(EVENT_APP_BYPASSED_CAPTIVE_PORTAL);
407                        break;
408                    case ConnectivityManager.CAPTIVE_PORTAL_DISCONNECT:
409                        sendMessage(EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE);
410                        break;
411                    // NOTE: This case label makes compiler enforce no overlap between result codes.
412                    case CAPTIVE_PORTAL_UNINITIALIZED_RETURN_CODE:
413                    default:
414                        sendMessage(EVENT_NO_APP_RESPONSE);
415                        break;
416                }
417            }
418        }
419    }
420
421    private class UninteractiveAppsPromptedState extends State {
422        private AppRespondedBroadcastReceiver mReceiver;
423        @Override
424        public void enter() {
425            mReceiver = new AppRespondedBroadcastReceiver();
426            mReceiver.send(ConnectivityManager.ACTION_CAPTIVE_PORTAL_DETECTED);
427        }
428        @Override
429        public boolean processMessage(Message message) {
430            if (DBG) log(getName() + message.toString());
431            switch (message.what) {
432                case EVENT_APP_BYPASSED_CAPTIVE_PORTAL:
433                    transitionTo(mValidatedState);
434                    return HANDLED;
435                case EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE:
436                    transitionTo(mOfflineState);
437                    return HANDLED;
438                case EVENT_NO_APP_RESPONSE:
439                    transitionTo(mUserPromptedState);
440                    return HANDLED;
441                default:
442                    return NOT_HANDLED;
443            }
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));
477            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
478                    mNetworkAgentInfo.network.netId,
479                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
480            mConnectivityServiceHandler.sendMessage(message);
481        }
482
483        @Override
484        public boolean processMessage(Message message) {
485            if (DBG) log(getName() + message.toString());
486            switch (message.what) {
487                case CMD_USER_WANTS_SIGN_IN:
488                    if (message.arg1 != mUserPromptedToken)
489                        return HANDLED;
490                    transitionTo(mInteractiveAppsPromptedState);
491                    return HANDLED;
492                default:
493                    return NOT_HANDLED;
494            }
495        }
496
497        @Override
498        public void exit() {
499            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
500                    mNetworkAgentInfo.network.netId, null);
501            mConnectivityServiceHandler.sendMessage(message);
502            mContext.unregisterReceiver(mUserRespondedBroadcastReceiver);
503            mUserRespondedBroadcastReceiver = null;
504        }
505    }
506
507    private class InteractiveAppsPromptedState extends State {
508        private AppRespondedBroadcastReceiver mReceiver;
509        @Override
510        public void enter() {
511            mReceiver = new AppRespondedBroadcastReceiver();
512            mReceiver.send(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
513        }
514        @Override
515        public boolean processMessage(Message message) {
516            if (DBG) log(getName() + message.toString());
517            switch (message.what) {
518                case EVENT_APP_BYPASSED_CAPTIVE_PORTAL:
519                    transitionTo(mValidatedState);
520                    return HANDLED;
521                case EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE:
522                    transitionTo(mOfflineState);
523                    return HANDLED;
524                case EVENT_NO_APP_RESPONSE:
525                    transitionTo(mCaptivePortalState);
526                    return HANDLED;
527                default:
528                    return NOT_HANDLED;
529            }
530        }
531        public void exit() {
532            mReceiver.cancel();
533        }
534    }
535
536    private class CaptivePortalState extends State {
537        private class CaptivePortalLoggedInBroadcastReceiver extends BroadcastReceiver {
538            private final int mToken;
539
540            CaptivePortalLoggedInBroadcastReceiver(int token) {
541                mToken = token;
542            }
543
544            @Override
545            public void onReceive(Context context, Intent intent) {
546                if (Integer.parseInt(intent.getStringExtra(Intent.EXTRA_TEXT)) ==
547                        mNetworkAgentInfo.network.netId) {
548                    sendMessage(obtainMessage(CMD_CAPTIVE_PORTAL_LOGGED_IN, mToken,
549                            Integer.parseInt(intent.getStringExtra(LOGGED_IN_RESULT))));
550                }
551            }
552        }
553
554        private CaptivePortalLoggedInBroadcastReceiver mCaptivePortalLoggedInBroadcastReceiver;
555
556        @Override
557        public void enter() {
558            Intent intent = new Intent(Intent.ACTION_SEND);
559            intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(mNetworkAgentInfo.network.netId));
560            intent.setType("text/plain");
561            intent.setComponent(new ComponentName("com.android.captiveportallogin",
562                    "com.android.captiveportallogin.CaptivePortalLoginActivity"));
563            intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
564
565            // Wait for result.
566            mCaptivePortalLoggedInBroadcastReceiver = new CaptivePortalLoggedInBroadcastReceiver(
567                    ++mCaptivePortalLoggedInToken);
568            IntentFilter filter = new IntentFilter(ACTION_CAPTIVE_PORTAL_LOGGED_IN);
569            mContext.registerReceiver(mCaptivePortalLoggedInBroadcastReceiver, filter);
570            // Initiate app to log in.
571            mContext.startActivityAsUser(intent, UserHandle.CURRENT);
572        }
573
574        @Override
575        public boolean processMessage(Message message) {
576            if (DBG) log(getName() + message.toString());
577            switch (message.what) {
578                case CMD_CAPTIVE_PORTAL_LOGGED_IN:
579                    if (message.arg1 != mCaptivePortalLoggedInToken)
580                        return HANDLED;
581                    if (message.arg2 == 0) {
582                        // TODO: Should teardown network.
583                        transitionTo(mOfflineState);
584                    } else {
585                        transitionTo(mValidatedState);
586                    }
587                    return HANDLED;
588                default:
589                    return NOT_HANDLED;
590            }
591        }
592
593        @Override
594        public void exit() {
595            mContext.unregisterReceiver(mCaptivePortalLoggedInBroadcastReceiver);
596            mCaptivePortalLoggedInBroadcastReceiver = null;
597        }
598    }
599
600    private class LingeringState extends State {
601        @Override
602        public void enter() {
603            Message message = obtainMessage(CMD_LINGER_EXPIRED, ++mLingerToken, 0);
604            sendMessageDelayed(message, mLingerDelayMs);
605        }
606
607        @Override
608        public boolean processMessage(Message message) {
609            if (DBG) log(getName() + message.toString());
610            switch (message.what) {
611                case CMD_NETWORK_CONNECTED:
612                    // Go straight to active as we've already evaluated.
613                    transitionTo(mValidatedState);
614                    return HANDLED;
615                case CMD_LINGER_EXPIRED:
616                    if (message.arg1 != mLingerToken)
617                        return HANDLED;
618                    mConnectivityServiceHandler.sendMessage(
619                            obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
620                    return HANDLED;
621                default:
622                    return NOT_HANDLED;
623            }
624        }
625    }
626
627    /**
628     * Do a URL fetch on a known server to see if we get the data we expect.
629     * Returns HTTP response code.
630     */
631    private int isCaptivePortal() {
632        if (!mIsCaptivePortalCheckEnabled) return 204;
633
634        HttpURLConnection urlConnection = null;
635        int httpResponseCode = 599;
636        try {
637            URL url = new URL("http", mServer, "/generate_204");
638            if (DBG) {
639                log("Checking " + url.toString() + " on " +
640                        mNetworkAgentInfo.networkInfo.getExtraInfo());
641            }
642            url = mNetworkAgentInfo.network.getBoundURL(url);
643            urlConnection = (HttpURLConnection) url.openConnection();
644            urlConnection.setInstanceFollowRedirects(false);
645            urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
646            urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
647            urlConnection.setUseCaches(false);
648
649            // Time how long it takes to get a response to our request
650            long requestTimestamp = SystemClock.elapsedRealtime();
651
652            urlConnection.getInputStream();
653
654            // Time how long it takes to get a response to our request
655            long responseTimestamp = SystemClock.elapsedRealtime();
656
657            httpResponseCode = urlConnection.getResponseCode();
658            if (DBG) {
659                log("isCaptivePortal: ret=" + httpResponseCode +
660                        " headers=" + urlConnection.getHeaderFields());
661            }
662            // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
663            // portal.  The only example of this seen so far was a captive portal.  For
664            // the time being go with prior behavior of assuming it's not a captive
665            // portal.  If it is considered a captive portal, a different sign-in URL
666            // is needed (i.e. can't browse a 204).  This could be the result of an HTTP
667            // proxy server.
668
669            // Consider 200 response with "Content-length=0" to not be a captive portal.
670            // There's no point in considering this a captive portal as the user cannot
671            // sign-in to an empty page.  Probably the result of a broken transparent proxy.
672            // See http://b/9972012.
673            if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
674                if (DBG) log("Empty 200 response interpreted as 204 response.");
675                httpResponseCode = 204;
676            }
677
678            sendNetworkConditionsBroadcast(true /* response received */, httpResponseCode == 204,
679                    requestTimestamp, responseTimestamp);
680        } catch (IOException e) {
681            if (DBG) log("Probably not a portal: exception " + e);
682            if (httpResponseCode == 599) {
683                // TODO: Ping gateway and DNS server and log results.
684            }
685        } finally {
686            if (urlConnection != null) {
687                urlConnection.disconnect();
688            }
689        }
690        return httpResponseCode;
691    }
692
693    /**
694     * @param responseReceived - whether or not we received a valid HTTP response to our request.
695     * If false, isCaptivePortal and responseTimestampMs are ignored
696     * TODO: This should be moved to the transports.  The latency could be passed to the transports
697     * along with the captive portal result.  Currently the TYPE_MOBILE broadcasts appear unused so
698     * perhaps this could just be added to the WiFi transport only.
699     */
700    private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
701            long requestTimestampMs, long responseTimestampMs) {
702        if (Settings.Global.getInt(mContext.getContentResolver(),
703                Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
704            if (DBG) log("Don't send network conditions - lacking user consent.");
705            return;
706        }
707
708        if (systemReady == false) return;
709
710        Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
711        switch (mNetworkAgentInfo.networkInfo.getType()) {
712            case ConnectivityManager.TYPE_WIFI:
713                WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
714                if (currentWifiInfo != null) {
715                    // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
716                    // surrounded by double quotation marks (thus violating the Javadoc), but this
717                    // was changed to match the Javadoc in API 17. Since clients may have started
718                    // sanitizing the output of this method since API 17 was released, we should
719                    // not change it here as it would become impossible to tell whether the SSID is
720                    // simply being surrounded by quotes due to the API, or whether those quotes
721                    // are actually part of the SSID.
722                    latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
723                    latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
724                } else {
725                    if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
726                    return;
727                }
728                break;
729            case ConnectivityManager.TYPE_MOBILE:
730                latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
731                List<CellInfo> info = mTelephonyManager.getAllCellInfo();
732                if (info == null) return;
733                int numRegisteredCellInfo = 0;
734                for (CellInfo cellInfo : info) {
735                    if (cellInfo.isRegistered()) {
736                        numRegisteredCellInfo++;
737                        if (numRegisteredCellInfo > 1) {
738                            if (DBG) log("more than one registered CellInfo.  Can't " +
739                                    "tell which is active.  Bailing.");
740                            return;
741                        }
742                        if (cellInfo instanceof CellInfoCdma) {
743                            CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
744                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
745                        } else if (cellInfo instanceof CellInfoGsm) {
746                            CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
747                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
748                        } else if (cellInfo instanceof CellInfoLte) {
749                            CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
750                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
751                        } else if (cellInfo instanceof CellInfoWcdma) {
752                            CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
753                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
754                        } else {
755                            if (DBG) logw("Registered cellinfo is unrecognized");
756                            return;
757                        }
758                    }
759                }
760                break;
761            default:
762                return;
763        }
764        latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
765        latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
766        latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
767
768        if (responseReceived) {
769            latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
770            latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
771        }
772        mContext.sendBroadcast(latencyBroadcast, PERMISSION_ACCESS_NETWORK_CONDITIONS);
773    }
774}
775