NetworkMonitor.java revision 351bfad339ede00a81862b3b57234d7a32067279
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.NetworkRequest;
31import android.net.TrafficStats;
32import android.net.Uri;
33import android.net.wifi.WifiInfo;
34import android.net.wifi.WifiManager;
35import android.os.Handler;
36import android.os.Message;
37import android.os.SystemClock;
38import android.os.SystemProperties;
39import android.os.UserHandle;
40import android.provider.Settings;
41import android.telephony.CellIdentityCdma;
42import android.telephony.CellIdentityGsm;
43import android.telephony.CellIdentityLte;
44import android.telephony.CellIdentityWcdma;
45import android.telephony.CellInfo;
46import android.telephony.CellInfoCdma;
47import android.telephony.CellInfoGsm;
48import android.telephony.CellInfoLte;
49import android.telephony.CellInfoWcdma;
50import android.telephony.TelephonyManager;
51import android.util.Log;
52
53import com.android.internal.util.Protocol;
54import com.android.internal.util.State;
55import com.android.internal.util.StateMachine;
56import com.android.server.ConnectivityService;
57import com.android.server.connectivity.NetworkAgentInfo;
58
59import java.io.IOException;
60import java.net.HttpURLConnection;
61import java.net.URL;
62import java.util.List;
63import java.util.Random;
64
65/**
66 * {@hide}
67 */
68public class NetworkMonitor extends StateMachine {
69    private static final boolean DBG = true;
70    private static final String TAG = "NetworkMonitor";
71    private static final String DEFAULT_SERVER = "connectivitycheck.android.com";
72    private static final int SOCKET_TIMEOUT_MS = 10000;
73    public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
74            "android.net.conn.NETWORK_CONDITIONS_MEASURED";
75    public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
76    public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
77    public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
78    public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
79    public static final String EXTRA_CELL_ID = "extra_cellid";
80    public static final String EXTRA_SSID = "extra_ssid";
81    public static final String EXTRA_BSSID = "extra_bssid";
82    /** real time since boot */
83    public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
84    public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
85
86    private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
87            "android.permission.ACCESS_NETWORK_CONDITIONS";
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 = one of the CAPTIVE_PORTAL_APP_RETURN_* values below.
94    //     RESPONSE_TOKEN   = data fragment from launching Intent
95    private static final String ACTION_CAPTIVE_PORTAL_LOGGED_IN =
96            "android.net.netmon.captive_portal_logged_in";
97    private static final String LOGGED_IN_RESULT = "result";
98    private static final String RESPONSE_TOKEN = "response_token";
99
100    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
101    // The network should be used as a default internet connection.  It was found to be:
102    // 1. a functioning network providing internet access, or
103    // 2. a captive portal and the user decided to use it as is.
104    public static final int NETWORK_TEST_RESULT_VALID = 0;
105    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
106    // The network should not be used as a default internet connection.  It was found to be:
107    // 1. a captive portal and the user is prompted to sign-in, or
108    // 2. a captive portal and the user did not want to use it, or
109    // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
110    public static final int NETWORK_TEST_RESULT_INVALID = 1;
111
112    private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
113
114    /**
115     * Inform NetworkMonitor that their network is connected.
116     * Initiates Network Validation.
117     */
118    public static final int CMD_NETWORK_CONNECTED = BASE + 1;
119
120    /**
121     * Inform ConnectivityService that the network has been tested.
122     * obj = NetworkAgentInfo
123     * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
124     */
125    public static final int EVENT_NETWORK_TESTED = BASE + 2;
126
127    /**
128     * Inform NetworkMonitor to linger a network.  The Monitor should
129     * start a timer and/or start watching for zero live connections while
130     * moving towards LINGER_COMPLETE.  After the Linger period expires
131     * (or other events mark the end of the linger state) the LINGER_COMPLETE
132     * event should be sent and the network will be shut down.  If a
133     * CMD_NETWORK_CONNECTED happens before the LINGER completes
134     * it indicates further desire to keep the network alive and so
135     * the LINGER is aborted.
136     */
137    public static final int CMD_NETWORK_LINGER = BASE + 3;
138
139    /**
140     * Message to self indicating linger delay has expired.
141     * arg1 = Token to ignore old messages.
142     */
143    private static final int CMD_LINGER_EXPIRED = BASE + 4;
144
145    /**
146     * Inform ConnectivityService that the network LINGER period has
147     * expired.
148     * obj = NetworkAgentInfo
149     */
150    public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
151
152    /**
153     * Message to self indicating it's time to evaluate a network's connectivity.
154     * arg1 = Token to ignore old messages.
155     */
156    private static final int CMD_REEVALUATE = BASE + 6;
157
158    /**
159     * Inform NetworkMonitor that the network has disconnected.
160     */
161    public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
162
163    /**
164     * Force evaluation even if it has succeeded in the past.
165     * arg1 = UID responsible for requesting this reeval.  Will be billed for data.
166     * arg2 = Number of evaluation attempts to make. (If 0, make INITIAL_ATTEMPTS attempts.)
167     */
168    public static final int CMD_FORCE_REEVALUATION = BASE + 8;
169
170    /**
171     * Message to self indicating captive portal app finished.
172     * arg1 = one of: CAPTIVE_PORTAL_APP_RETURN_APPEASED,
173     *                CAPTIVE_PORTAL_APP_RETURN_UNWANTED,
174     *                CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS
175     */
176    private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
177
178    /**
179     * Request ConnectivityService display provisioning notification.
180     * arg1    = Whether to make the notification visible.
181     * arg2    = NetID.
182     * obj     = Intent to be launched when notification selected by user, null if !arg1.
183     */
184    public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
185
186    /**
187     * Message to self indicating sign-in app bypassed captive portal.
188     */
189    private static final int EVENT_APP_BYPASSED_CAPTIVE_PORTAL = BASE + 11;
190
191    /**
192     * Message to self indicating no sign-in app responded.
193     */
194    private static final int EVENT_NO_APP_RESPONSE = BASE + 12;
195
196    /**
197     * Message to self indicating sign-in app indicates sign-in is not possible.
198     */
199    private static final int EVENT_APP_INDICATES_SIGN_IN_IMPOSSIBLE = BASE + 13;
200
201    /**
202     * Return codes from captive portal sign-in app.
203     */
204    public static final int CAPTIVE_PORTAL_APP_RETURN_APPEASED = 0;
205    public static final int CAPTIVE_PORTAL_APP_RETURN_UNWANTED = 1;
206    public static final int CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS = 2;
207
208    private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
209    // Default to 30s linger time-out.
210    private static final int DEFAULT_LINGER_DELAY_MS = 30000;
211    private final int mLingerDelayMs;
212    private int mLingerToken = 0;
213
214    // Negative values disable reevaluation.
215    private static final String REEVALUATE_DELAY_PROPERTY = "persist.netmon.reeval_delay";
216    // When connecting, attempt to validate 3 times, pausing 5s between them.
217    private static final int DEFAULT_REEVALUATE_DELAY_MS = 5000;
218    private static final int INITIAL_ATTEMPTS = 3;
219    // If a network is not validated, make one attempt every 10 mins to see if it starts working.
220    private static final int REEVALUATE_PAUSE_MS = 10*60*1000;
221    private static final int PERIODIC_ATTEMPTS = 1;
222    // When an application calls reportBadNetwork, only make one attempt.
223    private static final int REEVALUATE_ATTEMPTS = 1;
224    private final int mReevaluateDelayMs;
225    private int mReevaluateToken = 0;
226    private static final int INVALID_UID = -1;
227    private int mUidResponsibleForReeval = INVALID_UID;
228
229    private final Context mContext;
230    private final Handler mConnectivityServiceHandler;
231    private final NetworkAgentInfo mNetworkAgentInfo;
232    private final TelephonyManager mTelephonyManager;
233    private final WifiManager mWifiManager;
234    private final AlarmManager mAlarmManager;
235    private final NetworkRequest mDefaultRequest;
236
237    private String mServer;
238    private boolean mIsCaptivePortalCheckEnabled = false;
239
240    // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
241    private boolean mUserDoesNotWant = false;
242
243    // How many times we should attempt validation. Only checked in EvaluatingState; must be set
244    // before entering EvaluatingState. Note that whatever code causes us to transition to
245    // EvaluatingState last decides how many attempts will be made, so if one codepath were to
246    // enter EvaluatingState with a specific number of attempts, and then another were to enter it
247    // with a different number of attempts, the second number would be used. This is not currently
248    // a problem because EvaluatingState is not reentrant.
249    private int mMaxAttempts;
250
251    public boolean systemReady = false;
252
253    private final State mDefaultState = new DefaultState();
254    private final State mOfflineState = new OfflineState();
255    private final State mValidatedState = new ValidatedState();
256    private final State mMaybeNotifyState = new MaybeNotifyState();
257    private final State mEvaluatingState = new EvaluatingState();
258    private final State mCaptivePortalState = new CaptivePortalState();
259    private final State mLingeringState = new LingeringState();
260
261    private CaptivePortalLoggedInBroadcastReceiver mCaptivePortalLoggedInBroadcastReceiver = null;
262    private String mCaptivePortalLoggedInResponseToken = null;
263
264    public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
265            NetworkRequest defaultRequest) {
266        // Add suffix indicating which NetworkMonitor we're talking about.
267        super(TAG + networkAgentInfo.name());
268
269        mContext = context;
270        mConnectivityServiceHandler = handler;
271        mNetworkAgentInfo = networkAgentInfo;
272        mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
273        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
274        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
275        mDefaultRequest = defaultRequest;
276
277        addState(mDefaultState);
278        addState(mOfflineState, mDefaultState);
279        addState(mValidatedState, mDefaultState);
280        addState(mMaybeNotifyState, mDefaultState);
281            addState(mEvaluatingState, mMaybeNotifyState);
282            addState(mCaptivePortalState, mMaybeNotifyState);
283        addState(mLingeringState, mDefaultState);
284        setInitialState(mDefaultState);
285
286        mServer = Settings.Global.getString(mContext.getContentResolver(),
287                Settings.Global.CAPTIVE_PORTAL_SERVER);
288        if (mServer == null) mServer = DEFAULT_SERVER;
289
290        mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
291        mReevaluateDelayMs = SystemProperties.getInt(REEVALUATE_DELAY_PROPERTY,
292                DEFAULT_REEVALUATE_DELAY_MS);
293
294        mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
295                Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
296
297        mCaptivePortalLoggedInResponseToken = String.valueOf(new Random().nextLong());
298
299        start();
300    }
301
302    @Override
303    protected void log(String s) {
304        Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
305    }
306
307    // DefaultState is the parent of all States.  It exists only to handle CMD_* messages but
308    // does not entail any real state (hence no enter() or exit() routines).
309    private class DefaultState extends State {
310        @Override
311        public boolean processMessage(Message message) {
312            if (DBG) log(getName() + message.toString());
313            switch (message.what) {
314                case CMD_NETWORK_LINGER:
315                    if (DBG) log("Lingering");
316                    transitionTo(mLingeringState);
317                    return HANDLED;
318                case CMD_NETWORK_CONNECTED:
319                    if (DBG) log("Connected");
320                    mMaxAttempts = INITIAL_ATTEMPTS;
321                    transitionTo(mEvaluatingState);
322                    return HANDLED;
323                case CMD_NETWORK_DISCONNECTED:
324                    if (DBG) log("Disconnected - quitting");
325                    if (mCaptivePortalLoggedInBroadcastReceiver != null) {
326                        mContext.unregisterReceiver(mCaptivePortalLoggedInBroadcastReceiver);
327                        mCaptivePortalLoggedInBroadcastReceiver = null;
328                    }
329                    quit();
330                    return HANDLED;
331                case CMD_FORCE_REEVALUATION:
332                    if (DBG) log("Forcing reevaluation");
333                    mUidResponsibleForReeval = message.arg1;
334                    mMaxAttempts = message.arg2 != 0 ? message.arg2 : REEVALUATE_ATTEMPTS;
335                    transitionTo(mEvaluatingState);
336                    return HANDLED;
337                case CMD_CAPTIVE_PORTAL_APP_FINISHED:
338                    // Previous token was broadcast, come up with a new one.
339                    mCaptivePortalLoggedInResponseToken = String.valueOf(new Random().nextLong());
340                    switch (message.arg1) {
341                        case CAPTIVE_PORTAL_APP_RETURN_APPEASED:
342                        case CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS:
343                            transitionTo(mValidatedState);
344                            break;
345                        case CAPTIVE_PORTAL_APP_RETURN_UNWANTED:
346                            mUserDoesNotWant = true;
347                            // TODO: Should teardown network.
348                            transitionTo(mOfflineState);
349                            break;
350                    }
351                    return HANDLED;
352                default:
353                    return HANDLED;
354            }
355        }
356    }
357
358    // Being in the OfflineState State indicates a Network is unwanted or failed validation.
359    private class OfflineState extends State {
360        @Override
361        public void enter() {
362            mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
363                    NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
364            if (!mUserDoesNotWant) {
365                sendMessageDelayed(CMD_FORCE_REEVALUATION, 0 /* no UID */,
366                        PERIODIC_ATTEMPTS, REEVALUATE_PAUSE_MS);
367            }
368        }
369
370        @Override
371        public boolean processMessage(Message message) {
372            if (DBG) log(getName() + message.toString());
373                        switch (message.what) {
374                case CMD_FORCE_REEVALUATION:
375                    // If the user has indicated they explicitly do not want to use this network,
376                    // don't allow a reevaluation as this will be pointless and could result in
377                    // the user being annoyed with repeated unwanted notifications.
378                    return mUserDoesNotWant ? HANDLED : NOT_HANDLED;
379                default:
380                    return NOT_HANDLED;
381            }
382        }
383
384        @Override
385        public void exit() {
386             // NOTE: This removes the delayed message posted by enter() but will inadvertently
387             // remove any other CMD_FORCE_REEVALUATION in the message queue.  At the moment this
388             // is harmless.  If in the future this becomes problematic a different message could
389             // be used.
390             removeMessages(CMD_FORCE_REEVALUATION);
391        }
392    }
393
394    // Being in the ValidatedState State indicates a Network is:
395    // - Successfully validated, or
396    // - Wanted "as is" by the user, or
397    // - Does not satsify the default NetworkRequest and so validation has been skipped.
398    private class ValidatedState extends State {
399        @Override
400        public void enter() {
401            if (DBG) log("Validated");
402            mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
403                    NETWORK_TEST_RESULT_VALID, 0, mNetworkAgentInfo));
404        }
405
406        @Override
407        public boolean processMessage(Message message) {
408            if (DBG) log(getName() + message.toString());
409            switch (message.what) {
410                case CMD_NETWORK_CONNECTED:
411                    transitionTo(mValidatedState);
412                    return HANDLED;
413                default:
414                    return NOT_HANDLED;
415            }
416        }
417    }
418
419    // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
420    // is required.  This State takes care to clear the notification upon exit from the State.
421    private class MaybeNotifyState extends State {
422        @Override
423        public void exit() {
424            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
425                    mNetworkAgentInfo.network.netId, null);
426            mConnectivityServiceHandler.sendMessage(message);
427        }
428    }
429
430    // Being in the EvaluatingState State indicates the Network is being evaluated for internet
431    // connectivity.
432    private class EvaluatingState extends State {
433        private int mAttempt;
434
435        @Override
436        public void enter() {
437            mAttempt = 1;
438            sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
439            if (mUidResponsibleForReeval != INVALID_UID) {
440                TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
441                mUidResponsibleForReeval = INVALID_UID;
442            }
443        }
444
445        @Override
446        public boolean processMessage(Message message) {
447            if (DBG) log(getName() + message.toString());
448            switch (message.what) {
449                case CMD_REEVALUATE:
450                    if (message.arg1 != mReevaluateToken)
451                        return HANDLED;
452                    // Don't bother validating networks that don't satisify the default request.
453                    // This includes:
454                    //  - VPNs which can be considered explicitly desired by the user and the
455                    //    user's desire trumps whether the network validates.
456                    //  - Networks that don't provide internet access.  It's unclear how to
457                    //    validate such networks.
458                    //  - Untrusted networks.  It's unsafe to prompt the user to sign-in to
459                    //    such networks and the user didn't express interest in connecting to
460                    //    such networks (an app did) so the user may be unhappily surprised when
461                    //    asked to sign-in to a network they didn't want to connect to in the
462                    //    first place.  Validation could be done to adjust the network scores
463                    //    however these networks are app-requested and may not be intended for
464                    //    general usage, in which case general validation may not be an accurate
465                    //    measure of the network's quality.  Only the app knows how to evaluate
466                    //    the network so don't bother validating here.  Furthermore sending HTTP
467                    //    packets over the network may be undesirable, for example an extremely
468                    //    expensive metered network, or unwanted leaking of the User Agent string.
469                    if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
470                            mNetworkAgentInfo.networkCapabilities)) {
471                        transitionTo(mValidatedState);
472                        return HANDLED;
473                    }
474                    // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
475                    // server's IP addresses could hit the DNS timeout, and attempting connections
476                    // to each of the server's several IP addresses (currently one IPv4 and one
477                    // IPv6) could each take SOCKET_TIMEOUT_MS.  During this time this StateMachine
478                    // will be unresponsive. isCaptivePortal() could be executed on another Thread
479                    // if this is found to cause problems.
480                    int httpResponseCode = isCaptivePortal();
481                    if (httpResponseCode == 204) {
482                        transitionTo(mValidatedState);
483                    } else if (httpResponseCode >= 200 && httpResponseCode <= 399) {
484                        transitionTo(mCaptivePortalState);
485                    } else if (++mAttempt > mMaxAttempts) {
486                        transitionTo(mOfflineState);
487                    } else if (mReevaluateDelayMs >= 0) {
488                        Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
489                        sendMessageDelayed(msg, mReevaluateDelayMs);
490                    }
491                    return HANDLED;
492                case CMD_FORCE_REEVALUATION:
493                    // Ignore duplicate requests.
494                    return HANDLED;
495                default:
496                    return NOT_HANDLED;
497            }
498        }
499
500        @Override
501        public void exit() {
502            TrafficStats.clearThreadStatsUid();
503        }
504    }
505
506    // BroadcastReceiver that waits for a particular Intent and then posts a message.
507    private class CustomIntentReceiver extends BroadcastReceiver {
508        private final int mToken;
509        private final int mWhat;
510        private final String mAction;
511        CustomIntentReceiver(String action, int token, int what) {
512            mToken = token;
513            mWhat = what;
514            mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
515            mContext.registerReceiver(this, new IntentFilter(mAction));
516        }
517        public PendingIntent getPendingIntent() {
518            return PendingIntent.getBroadcast(mContext, 0, new Intent(mAction), 0);
519        }
520        @Override
521        public void onReceive(Context context, Intent intent) {
522            if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
523        }
524    }
525
526    private class CaptivePortalLoggedInBroadcastReceiver extends BroadcastReceiver {
527        @Override
528        public void onReceive(Context context, Intent intent) {
529            if (Integer.parseInt(intent.getStringExtra(Intent.EXTRA_TEXT)) ==
530                    mNetworkAgentInfo.network.netId &&
531                    mCaptivePortalLoggedInResponseToken.equals(
532                            intent.getStringExtra(RESPONSE_TOKEN))) {
533                sendMessage(obtainMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED,
534                        Integer.parseInt(intent.getStringExtra(LOGGED_IN_RESULT)), 0));
535            }
536        }
537    }
538
539    // Being in the CaptivePortalState State indicates a captive portal was detected and the user
540    // has been shown a notification to sign-in.
541    private class CaptivePortalState extends State {
542        @Override
543        public void enter() {
544            mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
545                    NETWORK_TEST_RESULT_INVALID, 0, mNetworkAgentInfo));
546
547            // Assemble Intent to launch captive portal sign-in app.
548            final Intent intent = new Intent(Intent.ACTION_SEND);
549            // Intent cannot use extras because PendingIntent.getActivity will merge matching
550            // Intents erasing extras.  Use data instead of extras to encode NetID.
551            intent.setData(Uri.fromParts("netid", Integer.toString(mNetworkAgentInfo.network.netId),
552                    mCaptivePortalLoggedInResponseToken));
553            intent.setComponent(new ComponentName("com.android.captiveportallogin",
554                    "com.android.captiveportallogin.CaptivePortalLoginActivity"));
555            intent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
556
557            if (mCaptivePortalLoggedInBroadcastReceiver == null) {
558                // Wait for result.
559                mCaptivePortalLoggedInBroadcastReceiver =
560                        new CaptivePortalLoggedInBroadcastReceiver();
561                final IntentFilter filter = new IntentFilter(ACTION_CAPTIVE_PORTAL_LOGGED_IN);
562                mContext.registerReceiver(mCaptivePortalLoggedInBroadcastReceiver, filter);
563            }
564            // Initiate notification to sign-in.
565            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
566                    mNetworkAgentInfo.network.netId,
567                    PendingIntent.getActivity(mContext, 0, intent, 0));
568            mConnectivityServiceHandler.sendMessage(message);
569        }
570
571        @Override
572        public boolean processMessage(Message message) {
573            if (DBG) log(getName() + message.toString());
574            return NOT_HANDLED;
575        }
576    }
577
578    // Being in the LingeringState State indicates a Network's validated bit is true and it once
579    // was the highest scoring Network satisfying a particular NetworkRequest, but since then
580    // another Network satsified the NetworkRequest with a higher score and hence this Network
581    // is "lingered" for a fixed period of time before it is disconnected.  This period of time
582    // allows apps to wrap up communication and allows for seamless reactivation if the other
583    // higher scoring Network happens to disconnect.
584    private class LingeringState extends State {
585        private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
586
587        private CustomIntentReceiver mBroadcastReceiver;
588        private PendingIntent mIntent;
589
590        @Override
591        public void enter() {
592            mLingerToken = new Random().nextInt();
593            mBroadcastReceiver = new CustomIntentReceiver(ACTION_LINGER_EXPIRED, mLingerToken,
594                    CMD_LINGER_EXPIRED);
595            mIntent = mBroadcastReceiver.getPendingIntent();
596            long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
597            mAlarmManager.setWindow(AlarmManager.ELAPSED_REALTIME_WAKEUP, wakeupTime,
598                    // Give a specific window so we aren't subject to unknown inexactitude.
599                    mLingerDelayMs / 6, mIntent);
600        }
601
602        @Override
603        public boolean processMessage(Message message) {
604            if (DBG) log(getName() + message.toString());
605            switch (message.what) {
606                case CMD_NETWORK_CONNECTED:
607                    // Go straight to active as we've already evaluated.
608                    transitionTo(mValidatedState);
609                    return HANDLED;
610                case CMD_LINGER_EXPIRED:
611                    if (message.arg1 != mLingerToken)
612                        return HANDLED;
613                    mConnectivityServiceHandler.sendMessage(
614                            obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
615                    return HANDLED;
616                case CMD_FORCE_REEVALUATION:
617                    // Ignore reevaluation attempts when lingering.  A reevaluation could result
618                    // in a transition to the validated state which would abort the linger
619                    // timeout.  Lingering is the result of score assessment; validity is
620                    // irrelevant.
621                    return HANDLED;
622                case CMD_CAPTIVE_PORTAL_APP_FINISHED:
623                    // Ignore user network determination as this could abort linger timeout.
624                    // Networks are only lingered once validated because:
625                    // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
626                    // - Once validated, a Network's validated bit is never cleared.
627                    // Since networks are only lingered after being validated a user's
628                    // determination will not change the death sentence that lingering entails:
629                    // - If the user wants to use the network or bypasses the captive portal,
630                    //   the network's score will not be increased beyond its current value
631                    //   because it is already validated.  Without a score increase there is no
632                    //   chance of reactivation (i.e. aborting linger timeout).
633                    // - If the user does not want the network, lingering will disconnect the
634                    //   network anyhow.
635                    return HANDLED;
636                default:
637                    return NOT_HANDLED;
638            }
639        }
640
641        @Override
642        public void exit() {
643            mAlarmManager.cancel(mIntent);
644            mContext.unregisterReceiver(mBroadcastReceiver);
645        }
646    }
647
648    /**
649     * Do a URL fetch on a known server to see if we get the data we expect.
650     * Returns HTTP response code.
651     */
652    private int isCaptivePortal() {
653        if (!mIsCaptivePortalCheckEnabled) return 204;
654
655        HttpURLConnection urlConnection = null;
656        int httpResponseCode = 599;
657        try {
658            URL url = new URL("http", mServer, "/generate_204");
659            if (DBG) {
660                log("Checking " + url.toString() + " on " +
661                        mNetworkAgentInfo.networkInfo.getExtraInfo());
662            }
663            urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
664            urlConnection.setInstanceFollowRedirects(false);
665            urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
666            urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
667            urlConnection.setUseCaches(false);
668
669            // Time how long it takes to get a response to our request
670            long requestTimestamp = SystemClock.elapsedRealtime();
671
672            urlConnection.getInputStream();
673
674            // Time how long it takes to get a response to our request
675            long responseTimestamp = SystemClock.elapsedRealtime();
676
677            httpResponseCode = urlConnection.getResponseCode();
678            if (DBG) {
679                log("isCaptivePortal: ret=" + httpResponseCode +
680                        " headers=" + urlConnection.getHeaderFields());
681            }
682            // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
683            // portal.  The only example of this seen so far was a captive portal.  For
684            // the time being go with prior behavior of assuming it's not a captive
685            // portal.  If it is considered a captive portal, a different sign-in URL
686            // is needed (i.e. can't browse a 204).  This could be the result of an HTTP
687            // proxy server.
688
689            // Consider 200 response with "Content-length=0" to not be a captive portal.
690            // There's no point in considering this a captive portal as the user cannot
691            // sign-in to an empty page.  Probably the result of a broken transparent proxy.
692            // See http://b/9972012.
693            if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
694                if (DBG) log("Empty 200 response interpreted as 204 response.");
695                httpResponseCode = 204;
696            }
697
698            sendNetworkConditionsBroadcast(true /* response received */,
699                    httpResponseCode != 204 /* isCaptivePortal */,
700                    requestTimestamp, responseTimestamp);
701        } catch (IOException e) {
702            if (DBG) log("Probably not a portal: exception " + e);
703            if (httpResponseCode == 599) {
704                // TODO: Ping gateway and DNS server and log results.
705            }
706        } finally {
707            if (urlConnection != null) {
708                urlConnection.disconnect();
709            }
710        }
711        return httpResponseCode;
712    }
713
714    /**
715     * @param responseReceived - whether or not we received a valid HTTP response to our request.
716     * If false, isCaptivePortal and responseTimestampMs are ignored
717     * TODO: This should be moved to the transports.  The latency could be passed to the transports
718     * along with the captive portal result.  Currently the TYPE_MOBILE broadcasts appear unused so
719     * perhaps this could just be added to the WiFi transport only.
720     */
721    private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
722            long requestTimestampMs, long responseTimestampMs) {
723        if (Settings.Global.getInt(mContext.getContentResolver(),
724                Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
725            if (DBG) log("Don't send network conditions - lacking user consent.");
726            return;
727        }
728
729        if (systemReady == false) return;
730
731        Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
732        switch (mNetworkAgentInfo.networkInfo.getType()) {
733            case ConnectivityManager.TYPE_WIFI:
734                WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
735                if (currentWifiInfo != null) {
736                    // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
737                    // surrounded by double quotation marks (thus violating the Javadoc), but this
738                    // was changed to match the Javadoc in API 17. Since clients may have started
739                    // sanitizing the output of this method since API 17 was released, we should
740                    // not change it here as it would become impossible to tell whether the SSID is
741                    // simply being surrounded by quotes due to the API, or whether those quotes
742                    // are actually part of the SSID.
743                    latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
744                    latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
745                } else {
746                    if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
747                    return;
748                }
749                break;
750            case ConnectivityManager.TYPE_MOBILE:
751                latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
752                List<CellInfo> info = mTelephonyManager.getAllCellInfo();
753                if (info == null) return;
754                int numRegisteredCellInfo = 0;
755                for (CellInfo cellInfo : info) {
756                    if (cellInfo.isRegistered()) {
757                        numRegisteredCellInfo++;
758                        if (numRegisteredCellInfo > 1) {
759                            if (DBG) log("more than one registered CellInfo.  Can't " +
760                                    "tell which is active.  Bailing.");
761                            return;
762                        }
763                        if (cellInfo instanceof CellInfoCdma) {
764                            CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
765                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
766                        } else if (cellInfo instanceof CellInfoGsm) {
767                            CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
768                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
769                        } else if (cellInfo instanceof CellInfoLte) {
770                            CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
771                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
772                        } else if (cellInfo instanceof CellInfoWcdma) {
773                            CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
774                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
775                        } else {
776                            if (DBG) logw("Registered cellinfo is unrecognized");
777                            return;
778                        }
779                    }
780                }
781                break;
782            default:
783                return;
784        }
785        latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
786        latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
787        latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
788
789        if (responseReceived) {
790            latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
791            latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
792        }
793        mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
794                PERMISSION_ACCESS_NETWORK_CONDITIONS);
795    }
796}
797