NetworkMonitor.java revision 49f63fbed4cd84f5da182c85e8b999037dc64f3b
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.AlarmManager;
20import android.app.PendingIntent;
21import android.content.BroadcastReceiver;
22import android.content.ComponentName;
23import android.content.Context;
24import android.content.Intent;
25import android.content.IntentFilter;
26import android.net.ConnectivityManager;
27import android.net.Network;
28import android.net.NetworkCapabilities;
29import android.net.NetworkInfo;
30import android.net.TrafficStats;
31import android.net.wifi.WifiInfo;
32import android.net.wifi.WifiManager;
33import android.os.Handler;
34import android.os.Message;
35import android.os.SystemClock;
36import android.os.SystemProperties;
37import android.os.UserHandle;
38import android.provider.Settings;
39import android.telephony.CellIdentityCdma;
40import android.telephony.CellIdentityGsm;
41import android.telephony.CellIdentityLte;
42import android.telephony.CellIdentityWcdma;
43import android.telephony.CellInfo;
44import android.telephony.CellInfoCdma;
45import android.telephony.CellInfoGsm;
46import android.telephony.CellInfoLte;
47import android.telephony.CellInfoWcdma;
48import android.telephony.TelephonyManager;
49
50import com.android.internal.util.Protocol;
51import com.android.internal.util.State;
52import com.android.internal.util.StateMachine;
53import com.android.server.ConnectivityService;
54import com.android.server.connectivity.NetworkAgentInfo;
55
56import java.io.IOException;
57import java.net.HttpURLConnection;
58import java.net.URL;
59import java.util.List;
60
61/**
62 * {@hide}
63 */
64public class NetworkMonitor extends StateMachine {
65    private static final boolean DBG = true;
66    private static final String TAG = "NetworkMonitor";
67    private static final String DEFAULT_SERVER = "clients3.google.com";
68    private static final int SOCKET_TIMEOUT_MS = 10000;
69    public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
70            "android.net.conn.NETWORK_CONDITIONS_MEASURED";
71    public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
72    public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
73    public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
74    public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
75    public static final String EXTRA_CELL_ID = "extra_cellid";
76    public static final String EXTRA_SSID = "extra_ssid";
77    public static final String EXTRA_BSSID = "extra_bssid";
78    /** real time since boot */
79    public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
80    public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
81
82    private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
83            "android.permission.ACCESS_NETWORK_CONDITIONS";
84
85    // Intent broadcast when user selects sign-in notification.
86    private static final String ACTION_SIGN_IN_REQUESTED =
87            "android.net.netmon.sign_in_requested";
88
89    // Keep these in sync with CaptivePortalLoginActivity.java.
90    // Intent broadcast from CaptivePortalLogin indicating sign-in is complete.
91    // Extras:
92    //     EXTRA_TEXT       = netId
93    //     LOGGED_IN_RESULT = "1" if we should use network, "0" if not.
94    private static final String ACTION_CAPTIVE_PORTAL_LOGGED_IN =
95            "android.net.netmon.captive_portal_logged_in";
96    private static final String LOGGED_IN_RESULT = "result";
97
98    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
99    // The network should be used as a default internet connection.  It was found to be:
100    // 1. a functioning network providing internet access, or
101    // 2. a captive portal and the user decided to use it as is.
102    public static final int NETWORK_TEST_RESULT_VALID = 0;
103    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
104    // The network should not be used as a default internet connection.  It was found to be:
105    // 1. a captive portal and the user is prompted to sign-in, or
106    // 2. a captive portal and the user did not want to use it, or
107    // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
108    public static final int NETWORK_TEST_RESULT_INVALID = 1;
109
110    private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
111
112    /**
113     * Inform NetworkMonitor that their network is connected.
114     * Initiates Network Validation.
115     */
116    public static final int CMD_NETWORK_CONNECTED = BASE + 1;
117
118    /**
119     * Inform ConnectivityService that the network has been tested.
120     * obj = NetworkAgentInfo
121     * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
122     */
123    public static final int EVENT_NETWORK_TESTED = BASE + 2;
124
125    /**
126     * Inform NetworkMonitor to linger a network.  The Monitor should
127     * start a timer and/or start watching for zero live connections while
128     * moving towards LINGER_COMPLETE.  After the Linger period expires
129     * (or other events mark the end of the linger state) the LINGER_COMPLETE
130     * event should be sent and the network will be shut down.  If a
131     * CMD_NETWORK_CONNECTED happens before the LINGER completes
132     * it indicates further desire to keep the network alive and so
133     * the LINGER is aborted.
134     */
135    public static final int CMD_NETWORK_LINGER = BASE + 3;
136
137    /**
138     * Message to self indicating linger delay has expired.
139     * arg1 = Token to ignore old messages.
140     */
141    private static final int CMD_LINGER_EXPIRED = BASE + 4;
142
143    /**
144     * Inform ConnectivityService that the network LINGER period has
145     * expired.
146     * obj = NetworkAgentInfo
147     */
148    public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
149
150    /**
151     * Message to self indicating it's time to evaluate a network's connectivity.
152     * arg1 = Token to ignore old messages.
153     */
154    private static final int CMD_REEVALUATE = BASE + 6;
155
156    /**
157     * Inform NetworkMonitor that the network has disconnected.
158     */
159    public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
160
161    /**
162     * Force evaluation even if it has succeeded in the past.
163     * arg1 = UID responsible for requesting this reeval.  Will be billed for data.
164     */
165    public static final int CMD_FORCE_REEVALUATION = BASE + 8;
166
167    /**
168     * Message to self indicating captive portal login is complete.
169     * arg1 = Token to ignore old messages.
170     * arg2 = 1 if we should use this network, 0 otherwise.
171     */
172    private static final int CMD_CAPTIVE_PORTAL_LOGGED_IN = BASE + 9;
173
174    /**
175     * Message to self indicating user desires to log into captive portal.
176     * arg1 = Token to ignore old messages.
177     */
178    private static final int CMD_USER_WANTS_SIGN_IN = BASE + 10;
179
180    /**
181     * Request ConnectivityService display provisioning notification.
182     * arg1    = Whether to make the notification visible.
183     * arg2    = NetID.
184     * obj     = Intent to be launched when notification selected by user, null if !arg1.
185     */
186    public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 11;
187
188    /**
189     * Message to self indicating sign-in app bypassed captive portal.
190     */
191    private static final int EVENT_APP_BYPASSED_CAPTIVE_PORTAL = BASE + 12;
192
193    /**
194     * Message to self indicating no sign-in app responded.
195     */
196    private static final int EVENT_NO_APP_RESPONSE = BASE + 13;
197
198    /**
199     * Message to self indicating sign-in app indicates sign-in is not possible.
200     */
201    private static final int EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE = BASE + 14;
202
203    private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
204    // Default to 30s linger time-out.
205    private static final int DEFAULT_LINGER_DELAY_MS = 30000;
206    private final int mLingerDelayMs;
207    private int mLingerToken = 0;
208
209    // Negative values disable reevaluation.
210    private static final String REEVALUATE_DELAY_PROPERTY = "persist.netmon.reeval_delay";
211    // Default to 5s reevaluation delay.
212    private static final int DEFAULT_REEVALUATE_DELAY_MS = 5000;
213    private static final int MAX_RETRIES = 10;
214    private final int mReevaluateDelayMs;
215    private int mReevaluateToken = 0;
216    private static final int INVALID_UID = -1;
217    private int mUidResponsibleForReeval = INVALID_UID;
218
219    private int mCaptivePortalLoggedInToken = 0;
220    private int mUserPromptedToken = 0;
221
222    private final Context mContext;
223    private final Handler mConnectivityServiceHandler;
224    private final NetworkAgentInfo mNetworkAgentInfo;
225    private final TelephonyManager mTelephonyManager;
226    private final WifiManager mWifiManager;
227    private final AlarmManager mAlarmManager;
228
229    private String mServer;
230    private boolean mIsCaptivePortalCheckEnabled = false;
231
232    // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
233    private boolean mUserDoesNotWant = false;
234
235    public boolean systemReady = false;
236
237    private State mDefaultState = new DefaultState();
238    private State mOfflineState = new OfflineState();
239    private State mValidatedState = new ValidatedState();
240    private State mEvaluatingState = new EvaluatingState();
241    private State mUserPromptedState = new UserPromptedState();
242    private State mCaptivePortalState = new CaptivePortalState();
243    private State mLingeringState = new LingeringState();
244
245    public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo) {
246        // Add suffix indicating which NetworkMonitor we're talking about.
247        super(TAG + networkAgentInfo.name());
248
249        mContext = context;
250        mConnectivityServiceHandler = handler;
251        mNetworkAgentInfo = networkAgentInfo;
252        mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
253        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
254        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
255
256        addState(mDefaultState);
257        addState(mOfflineState, mDefaultState);
258        addState(mValidatedState, mDefaultState);
259        addState(mEvaluatingState, mDefaultState);
260        addState(mUserPromptedState, mDefaultState);
261        addState(mCaptivePortalState, mDefaultState);
262        addState(mLingeringState, mDefaultState);
263        setInitialState(mDefaultState);
264
265        mServer = Settings.Global.getString(mContext.getContentResolver(),
266                Settings.Global.CAPTIVE_PORTAL_SERVER);
267        if (mServer == null) mServer = DEFAULT_SERVER;
268
269        mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
270        mReevaluateDelayMs = SystemProperties.getInt(REEVALUATE_DELAY_PROPERTY,
271                DEFAULT_REEVALUATE_DELAY_MS);
272
273        mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
274                Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
275
276        start();
277    }
278
279    private class DefaultState extends State {
280        @Override
281        public boolean processMessage(Message message) {
282            if (DBG) log(getName() + message.toString());
283            switch (message.what) {
284                case CMD_NETWORK_LINGER:
285                    if (DBG) log("Lingering");
286                    transitionTo(mLingeringState);
287                    return HANDLED;
288                case CMD_NETWORK_CONNECTED:
289                    if (DBG) log("Connected");
290                    transitionTo(mEvaluatingState);
291                    return HANDLED;
292                case CMD_NETWORK_DISCONNECTED:
293                    if (DBG) log("Disconnected - quitting");
294                    quit();
295                    return HANDLED;
296                case CMD_FORCE_REEVALUATION:
297                    if (DBG) log("Forcing reevaluation");
298                    mUidResponsibleForReeval = message.arg1;
299                    transitionTo(mEvaluatingState);
300                    return HANDLED;
301                default:
302                    return HANDLED;
303            }
304        }
305    }
306
307    private class OfflineState extends State {
308        @Override
309        public void enter() {
310            mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
311                    NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
312        }
313
314        @Override
315        public boolean processMessage(Message message) {
316            if (DBG) log(getName() + message.toString());
317                        switch (message.what) {
318                case CMD_FORCE_REEVALUATION:
319                    // If the user has indicated they explicitly do not want to use this network,
320                    // don't allow a reevaluation as this will be pointless and could result in
321                    // the user being annoyed with repeated unwanted notifications.
322                    return mUserDoesNotWant ? HANDLED : NOT_HANDLED;
323                default:
324                    return NOT_HANDLED;
325            }
326        }
327    }
328
329    private class ValidatedState extends State {
330        @Override
331        public void enter() {
332            if (DBG) log("Validated");
333            mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
334                    NETWORK_TEST_RESULT_VALID, 0, mNetworkAgentInfo));
335        }
336
337        @Override
338        public boolean processMessage(Message message) {
339            if (DBG) log(getName() + message.toString());
340            switch (message.what) {
341                case CMD_NETWORK_CONNECTED:
342                    transitionTo(mValidatedState);
343                    return HANDLED;
344                default:
345                    return NOT_HANDLED;
346            }
347        }
348    }
349
350    private class EvaluatingState extends State {
351        private int mRetries;
352
353        @Override
354        public void enter() {
355            mRetries = 0;
356            sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
357            if (mUidResponsibleForReeval != INVALID_UID) {
358                TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
359                mUidResponsibleForReeval = INVALID_UID;
360            }
361        }
362
363        @Override
364        public boolean processMessage(Message message) {
365            if (DBG) log(getName() + message.toString());
366            switch (message.what) {
367                case CMD_REEVALUATE:
368                    if (message.arg1 != mReevaluateToken)
369                        return HANDLED;
370                    if (mNetworkAgentInfo.isVPN()) {
371                        transitionTo(mValidatedState);
372                        return HANDLED;
373                    }
374                    // If network provides no internet connectivity adjust evaluation.
375                    if (!mNetworkAgentInfo.networkCapabilities.hasCapability(
376                            NetworkCapabilities.NET_CAPABILITY_INTERNET)) {
377                        // TODO: Try to verify something works.  Do all gateways respond to pings?
378                        transitionTo(mValidatedState);
379                        return HANDLED;
380                    }
381                    int httpResponseCode = isCaptivePortal();
382                    if (httpResponseCode == 204) {
383                        transitionTo(mValidatedState);
384                    } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
385                        transitionTo(mUserPromptedState);
386                    } else if (++mRetries > MAX_RETRIES) {
387                        transitionTo(mOfflineState);
388                    } else if (mReevaluateDelayMs >= 0) {
389                        Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
390                        sendMessageDelayed(msg, mReevaluateDelayMs);
391                    }
392                    return HANDLED;
393                case CMD_FORCE_REEVALUATION:
394                    // Ignore duplicate requests.
395                    return HANDLED;
396                default:
397                    return NOT_HANDLED;
398            }
399        }
400
401        @Override
402        public void exit() {
403            TrafficStats.clearThreadStatsUid();
404        }
405    }
406
407    private class UserPromptedState extends State {
408        private class UserRespondedBroadcastReceiver extends BroadcastReceiver {
409            private final int mToken;
410            UserRespondedBroadcastReceiver(int token) {
411                mToken = token;
412            }
413            @Override
414            public void onReceive(Context context, Intent intent) {
415                if (Integer.parseInt(intent.getStringExtra(Intent.EXTRA_TEXT)) ==
416                        mNetworkAgentInfo.network.netId) {
417                    sendMessage(obtainMessage(CMD_USER_WANTS_SIGN_IN, mToken));
418                }
419            }
420        }
421
422        private UserRespondedBroadcastReceiver mUserRespondedBroadcastReceiver;
423
424        @Override
425        public void enter() {
426            mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
427                    NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
428            // Wait for user to select sign-in notifcation.
429            mUserRespondedBroadcastReceiver = new UserRespondedBroadcastReceiver(
430                    ++mUserPromptedToken);
431            IntentFilter filter = new IntentFilter(ACTION_SIGN_IN_REQUESTED);
432            mContext.registerReceiver(mUserRespondedBroadcastReceiver, filter);
433            // Initiate notification to sign-in.
434            Intent intent = new Intent(ACTION_SIGN_IN_REQUESTED);
435            intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(mNetworkAgentInfo.network.netId));
436            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
437                    mNetworkAgentInfo.network.netId,
438                    PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
439            mConnectivityServiceHandler.sendMessage(message);
440        }
441
442        @Override
443        public boolean processMessage(Message message) {
444            if (DBG) log(getName() + message.toString());
445            switch (message.what) {
446                case CMD_USER_WANTS_SIGN_IN:
447                    if (message.arg1 != mUserPromptedToken)
448                        return HANDLED;
449                    transitionTo(mCaptivePortalState);
450                    return HANDLED;
451                default:
452                    return NOT_HANDLED;
453            }
454        }
455
456        @Override
457        public void exit() {
458            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
459                    mNetworkAgentInfo.network.netId, null);
460            mConnectivityServiceHandler.sendMessage(message);
461            mContext.unregisterReceiver(mUserRespondedBroadcastReceiver);
462            mUserRespondedBroadcastReceiver = null;
463        }
464    }
465
466    private class CaptivePortalState extends State {
467        private class CaptivePortalLoggedInBroadcastReceiver extends BroadcastReceiver {
468            private final int mToken;
469
470            CaptivePortalLoggedInBroadcastReceiver(int token) {
471                mToken = token;
472            }
473
474            @Override
475            public void onReceive(Context context, Intent intent) {
476                if (Integer.parseInt(intent.getStringExtra(Intent.EXTRA_TEXT)) ==
477                        mNetworkAgentInfo.network.netId) {
478                    sendMessage(obtainMessage(CMD_CAPTIVE_PORTAL_LOGGED_IN, mToken,
479                            Integer.parseInt(intent.getStringExtra(LOGGED_IN_RESULT))));
480                }
481            }
482        }
483
484        private CaptivePortalLoggedInBroadcastReceiver mCaptivePortalLoggedInBroadcastReceiver;
485
486        @Override
487        public void enter() {
488            Intent intent = new Intent(Intent.ACTION_SEND);
489            intent.putExtra(Intent.EXTRA_TEXT, String.valueOf(mNetworkAgentInfo.network.netId));
490            intent.setType("text/plain");
491            intent.setComponent(new ComponentName("com.android.captiveportallogin",
492                    "com.android.captiveportallogin.CaptivePortalLoginActivity"));
493            intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
494
495            // Wait for result.
496            mCaptivePortalLoggedInBroadcastReceiver = new CaptivePortalLoggedInBroadcastReceiver(
497                    ++mCaptivePortalLoggedInToken);
498            IntentFilter filter = new IntentFilter(ACTION_CAPTIVE_PORTAL_LOGGED_IN);
499            mContext.registerReceiver(mCaptivePortalLoggedInBroadcastReceiver, filter);
500            // Initiate app to log in.
501            mContext.startActivityAsUser(intent, UserHandle.CURRENT);
502        }
503
504        @Override
505        public boolean processMessage(Message message) {
506            if (DBG) log(getName() + message.toString());
507            switch (message.what) {
508                case CMD_CAPTIVE_PORTAL_LOGGED_IN:
509                    if (message.arg1 != mCaptivePortalLoggedInToken)
510                        return HANDLED;
511                    if (message.arg2 == 0) {
512                        mUserDoesNotWant = true;
513                        // TODO: Should teardown network.
514                        transitionTo(mOfflineState);
515                    } else {
516                        transitionTo(mValidatedState);
517                    }
518                    return HANDLED;
519                default:
520                    return NOT_HANDLED;
521            }
522        }
523
524        @Override
525        public void exit() {
526            mContext.unregisterReceiver(mCaptivePortalLoggedInBroadcastReceiver);
527            mCaptivePortalLoggedInBroadcastReceiver = null;
528        }
529    }
530
531    private class LingeringState extends State {
532        private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
533        private static final String EXTRA_NETID = "lingerExpiredNetId";
534        private static final String EXTRA_TOKEN = "lingerExpiredToken";
535
536        private class LingerExpiredBroadcastReceiver extends BroadcastReceiver {
537            @Override
538            public void onReceive(Context context, Intent intent) {
539                if (intent.getAction().equals(ACTION_LINGER_EXPIRED) &&
540                        Integer.parseInt(intent.getStringExtra(EXTRA_NETID)) ==
541                        mNetworkAgentInfo.network.netId) {
542                    sendMessage(CMD_LINGER_EXPIRED,
543                            Integer.parseInt(intent.getStringExtra(EXTRA_TOKEN)));
544                }
545            }
546        }
547
548        private BroadcastReceiver mBroadcastReceiver;
549        private PendingIntent mIntent;
550
551        @Override
552        public void enter() {
553            mBroadcastReceiver = new LingerExpiredBroadcastReceiver();
554            mContext.registerReceiver(mBroadcastReceiver, new IntentFilter(ACTION_LINGER_EXPIRED));
555
556            Intent intent = new Intent(ACTION_LINGER_EXPIRED, null);
557            intent.putExtra(EXTRA_NETID, String.valueOf(mNetworkAgentInfo.network.netId));
558            intent.putExtra(EXTRA_TOKEN, String.valueOf(++mLingerToken));
559            mIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
560            long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
561            mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime,
562                    // Give a specific window so we aren't subject to unknown inexactitude.
563                    mLingerDelayMs / 6, mIntent);
564        }
565
566        @Override
567        public boolean processMessage(Message message) {
568            if (DBG) log(getName() + message.toString());
569            switch (message.what) {
570                case CMD_NETWORK_CONNECTED:
571                    // Go straight to active as we've already evaluated.
572                    transitionTo(mValidatedState);
573                    return HANDLED;
574                case CMD_LINGER_EXPIRED:
575                    if (message.arg1 != mLingerToken)
576                        return HANDLED;
577                    mConnectivityServiceHandler.sendMessage(
578                            obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
579                    return HANDLED;
580                case CMD_FORCE_REEVALUATION:
581                    // Ignore reevaluation attempts when lingering.  A reevaluation could result
582                    // in a transition to the validated state which would abort the linger
583                    // timeout.  Lingering is the result of score assessment; validity is
584                    // irrelevant.
585                    return HANDLED;
586                default:
587                    return NOT_HANDLED;
588            }
589        }
590
591        @Override
592        public void exit() {
593            mAlarmManager.cancel(mIntent);
594            mContext.unregisterReceiver(mBroadcastReceiver);
595        }
596    }
597
598    /**
599     * Do a URL fetch on a known server to see if we get the data we expect.
600     * Returns HTTP response code.
601     */
602    private int isCaptivePortal() {
603        if (!mIsCaptivePortalCheckEnabled) return 204;
604
605        HttpURLConnection urlConnection = null;
606        int httpResponseCode = 599;
607        try {
608            URL url = new URL("http", mServer, "/generate_204");
609            if (DBG) {
610                log("Checking " + url.toString() + " on " +
611                        mNetworkAgentInfo.networkInfo.getExtraInfo());
612            }
613            urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
614            urlConnection.setInstanceFollowRedirects(false);
615            urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
616            urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
617            urlConnection.setUseCaches(false);
618
619            // Time how long it takes to get a response to our request
620            long requestTimestamp = SystemClock.elapsedRealtime();
621
622            urlConnection.getInputStream();
623
624            // Time how long it takes to get a response to our request
625            long responseTimestamp = SystemClock.elapsedRealtime();
626
627            httpResponseCode = urlConnection.getResponseCode();
628            if (DBG) {
629                log("isCaptivePortal: ret=" + httpResponseCode +
630                        " headers=" + urlConnection.getHeaderFields());
631            }
632            // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
633            // portal.  The only example of this seen so far was a captive portal.  For
634            // the time being go with prior behavior of assuming it's not a captive
635            // portal.  If it is considered a captive portal, a different sign-in URL
636            // is needed (i.e. can't browse a 204).  This could be the result of an HTTP
637            // proxy server.
638
639            // Consider 200 response with "Content-length=0" to not be a captive portal.
640            // There's no point in considering this a captive portal as the user cannot
641            // sign-in to an empty page.  Probably the result of a broken transparent proxy.
642            // See http://b/9972012.
643            if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
644                if (DBG) log("Empty 200 response interpreted as 204 response.");
645                httpResponseCode = 204;
646            }
647
648            sendNetworkConditionsBroadcast(true /* response received */, httpResponseCode == 204,
649                    requestTimestamp, responseTimestamp);
650        } catch (IOException e) {
651            if (DBG) log("Probably not a portal: exception " + e);
652            if (httpResponseCode == 599) {
653                // TODO: Ping gateway and DNS server and log results.
654            }
655        } finally {
656            if (urlConnection != null) {
657                urlConnection.disconnect();
658            }
659        }
660        return httpResponseCode;
661    }
662
663    /**
664     * @param responseReceived - whether or not we received a valid HTTP response to our request.
665     * If false, isCaptivePortal and responseTimestampMs are ignored
666     * TODO: This should be moved to the transports.  The latency could be passed to the transports
667     * along with the captive portal result.  Currently the TYPE_MOBILE broadcasts appear unused so
668     * perhaps this could just be added to the WiFi transport only.
669     */
670    private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
671            long requestTimestampMs, long responseTimestampMs) {
672        if (Settings.Global.getInt(mContext.getContentResolver(),
673                Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
674            if (DBG) log("Don't send network conditions - lacking user consent.");
675            return;
676        }
677
678        if (systemReady == false) return;
679
680        Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
681        switch (mNetworkAgentInfo.networkInfo.getType()) {
682            case ConnectivityManager.TYPE_WIFI:
683                WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
684                if (currentWifiInfo != null) {
685                    // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
686                    // surrounded by double quotation marks (thus violating the Javadoc), but this
687                    // was changed to match the Javadoc in API 17. Since clients may have started
688                    // sanitizing the output of this method since API 17 was released, we should
689                    // not change it here as it would become impossible to tell whether the SSID is
690                    // simply being surrounded by quotes due to the API, or whether those quotes
691                    // are actually part of the SSID.
692                    latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
693                    latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
694                } else {
695                    if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
696                    return;
697                }
698                break;
699            case ConnectivityManager.TYPE_MOBILE:
700                latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
701                List<CellInfo> info = mTelephonyManager.getAllCellInfo();
702                if (info == null) return;
703                int numRegisteredCellInfo = 0;
704                for (CellInfo cellInfo : info) {
705                    if (cellInfo.isRegistered()) {
706                        numRegisteredCellInfo++;
707                        if (numRegisteredCellInfo > 1) {
708                            if (DBG) log("more than one registered CellInfo.  Can't " +
709                                    "tell which is active.  Bailing.");
710                            return;
711                        }
712                        if (cellInfo instanceof CellInfoCdma) {
713                            CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
714                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
715                        } else if (cellInfo instanceof CellInfoGsm) {
716                            CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
717                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
718                        } else if (cellInfo instanceof CellInfoLte) {
719                            CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
720                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
721                        } else if (cellInfo instanceof CellInfoWcdma) {
722                            CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
723                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
724                        } else {
725                            if (DBG) logw("Registered cellinfo is unrecognized");
726                            return;
727                        }
728                    }
729                }
730                break;
731            default:
732                return;
733        }
734        latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
735        latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
736        latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
737
738        if (responseReceived) {
739            latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
740            latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
741        }
742        mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
743                PERMISSION_ACCESS_NETWORK_CONDITIONS);
744    }
745}
746