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