NetworkMonitor.java revision cc92c6e87773df9d5a84922066716ae9bb09cd6d
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 static android.net.CaptivePortal.APP_RETURN_DISMISSED;
20import static android.net.CaptivePortal.APP_RETURN_UNWANTED;
21import static android.net.CaptivePortal.APP_RETURN_WANTED_AS_IS;
22
23import android.app.AlarmManager;
24import android.app.PendingIntent;
25import android.content.BroadcastReceiver;
26import android.content.ComponentName;
27import android.content.Context;
28import android.content.Intent;
29import android.content.IntentFilter;
30import android.net.CaptivePortal;
31import android.net.ConnectivityManager;
32import android.net.ICaptivePortal;
33import android.net.NetworkRequest;
34import android.net.ProxyInfo;
35import android.net.TrafficStats;
36import android.net.Uri;
37import android.net.metrics.ValidationProbeEvent;
38import android.net.metrics.NetworkEvent;
39import android.net.wifi.WifiInfo;
40import android.net.wifi.WifiManager;
41import android.net.util.Stopwatch;
42import android.os.Handler;
43import android.os.Message;
44import android.os.Process;
45import android.os.SystemClock;
46import android.os.SystemProperties;
47import android.os.UserHandle;
48import android.provider.Settings;
49import android.telephony.CellIdentityCdma;
50import android.telephony.CellIdentityGsm;
51import android.telephony.CellIdentityLte;
52import android.telephony.CellIdentityWcdma;
53import android.telephony.CellInfo;
54import android.telephony.CellInfoCdma;
55import android.telephony.CellInfoGsm;
56import android.telephony.CellInfoLte;
57import android.telephony.CellInfoWcdma;
58import android.telephony.TelephonyManager;
59import android.text.TextUtils;
60import android.util.LocalLog;
61import android.util.LocalLog.ReadOnlyLocalLog;
62import android.util.Log;
63
64import com.android.internal.annotations.VisibleForTesting;
65import com.android.internal.util.Protocol;
66import com.android.internal.util.State;
67import com.android.internal.util.StateMachine;
68import com.android.internal.util.WakeupMessage;
69import com.android.server.connectivity.NetworkAgentInfo;
70
71import java.io.IOException;
72import java.net.HttpURLConnection;
73import java.net.InetAddress;
74import java.net.URL;
75import java.util.List;
76import java.util.Random;
77
78/**
79 * {@hide}
80 */
81public class NetworkMonitor extends StateMachine {
82    private static final boolean DBG = false;
83    private static final String TAG = NetworkMonitor.class.getSimpleName();
84    private static final String DEFAULT_SERVER = "connectivitycheck.gstatic.com";
85    private static final int SOCKET_TIMEOUT_MS = 10000;
86    public static final String ACTION_NETWORK_CONDITIONS_MEASURED =
87            "android.net.conn.NETWORK_CONDITIONS_MEASURED";
88    public static final String EXTRA_CONNECTIVITY_TYPE = "extra_connectivity_type";
89    public static final String EXTRA_NETWORK_TYPE = "extra_network_type";
90    public static final String EXTRA_RESPONSE_RECEIVED = "extra_response_received";
91    public static final String EXTRA_IS_CAPTIVE_PORTAL = "extra_is_captive_portal";
92    public static final String EXTRA_CELL_ID = "extra_cellid";
93    public static final String EXTRA_SSID = "extra_ssid";
94    public static final String EXTRA_BSSID = "extra_bssid";
95    /** real time since boot */
96    public static final String EXTRA_REQUEST_TIMESTAMP_MS = "extra_request_timestamp_ms";
97    public static final String EXTRA_RESPONSE_TIMESTAMP_MS = "extra_response_timestamp_ms";
98
99    private static final String PERMISSION_ACCESS_NETWORK_CONDITIONS =
100            "android.permission.ACCESS_NETWORK_CONDITIONS";
101
102    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
103    // The network should be used as a default internet connection.  It was found to be:
104    // 1. a functioning network providing internet access, or
105    // 2. a captive portal and the user decided to use it as is.
106    public static final int NETWORK_TEST_RESULT_VALID = 0;
107    // After a network has been tested this result can be sent with EVENT_NETWORK_TESTED.
108    // The network should not be used as a default internet connection.  It was found to be:
109    // 1. a captive portal and the user is prompted to sign-in, or
110    // 2. a captive portal and the user did not want to use it, or
111    // 3. a broken network (e.g. DNS failed, connect failed, HTTP request failed).
112    public static final int NETWORK_TEST_RESULT_INVALID = 1;
113
114    private static final int BASE = Protocol.BASE_NETWORK_MONITOR;
115
116    /**
117     * Inform NetworkMonitor that their network is connected.
118     * Initiates Network Validation.
119     */
120    public static final int CMD_NETWORK_CONNECTED = BASE + 1;
121
122    /**
123     * Inform ConnectivityService that the network has been tested.
124     * obj = String representing URL that Internet probe was redirect to, if it was redirected.
125     * arg1 = One of the NETWORK_TESTED_RESULT_* constants.
126     * arg2 = NetID.
127     */
128    public static final int EVENT_NETWORK_TESTED = BASE + 2;
129
130    /**
131     * Inform NetworkMonitor to linger a network.  The Monitor should
132     * start a timer and/or start watching for zero live connections while
133     * moving towards LINGER_COMPLETE.  After the Linger period expires
134     * (or other events mark the end of the linger state) the LINGER_COMPLETE
135     * event should be sent and the network will be shut down.  If a
136     * CMD_NETWORK_CONNECTED happens before the LINGER completes
137     * it indicates further desire to keep the network alive and so
138     * the LINGER is aborted.
139     */
140    public static final int CMD_NETWORK_LINGER = BASE + 3;
141
142    /**
143     * Message to self indicating linger delay has expired.
144     * arg1 = Token to ignore old messages.
145     */
146    private static final int CMD_LINGER_EXPIRED = BASE + 4;
147
148    /**
149     * Inform ConnectivityService that the network LINGER period has
150     * expired.
151     * obj = NetworkAgentInfo
152     */
153    public static final int EVENT_NETWORK_LINGER_COMPLETE = BASE + 5;
154
155    /**
156     * Message to self indicating it's time to evaluate a network's connectivity.
157     * arg1 = Token to ignore old messages.
158     */
159    private static final int CMD_REEVALUATE = BASE + 6;
160
161    /**
162     * Inform NetworkMonitor that the network has disconnected.
163     */
164    public static final int CMD_NETWORK_DISCONNECTED = BASE + 7;
165
166    /**
167     * Force evaluation even if it has succeeded in the past.
168     * arg1 = UID responsible for requesting this reeval.  Will be billed for data.
169     */
170    public static final int CMD_FORCE_REEVALUATION = BASE + 8;
171
172    /**
173     * Message to self indicating captive portal app finished.
174     * arg1 = one of: APP_RETURN_DISMISSED,
175     *                APP_RETURN_UNWANTED,
176     *                APP_RETURN_WANTED_AS_IS
177     * obj = mCaptivePortalLoggedInResponseToken as String
178     */
179    private static final int CMD_CAPTIVE_PORTAL_APP_FINISHED = BASE + 9;
180
181    /**
182     * Request ConnectivityService display provisioning notification.
183     * arg1    = Whether to make the notification visible.
184     * arg2    = NetID.
185     * obj     = Intent to be launched when notification selected by user, null if !arg1.
186     */
187    public static final int EVENT_PROVISIONING_NOTIFICATION = BASE + 10;
188
189    /**
190     * Message to self indicating sign-in app should be launched.
191     * Sent by mLaunchCaptivePortalAppBroadcastReceiver when the
192     * user touches the sign in notification.
193     */
194    private static final int CMD_LAUNCH_CAPTIVE_PORTAL_APP = BASE + 11;
195
196    /**
197     * Retest network to see if captive portal is still in place.
198     * arg1 = UID responsible for requesting this reeval.  Will be billed for data.
199     *        0 indicates self-initiated, so nobody to blame.
200     */
201    private static final int CMD_CAPTIVE_PORTAL_RECHECK = BASE + 12;
202
203    private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
204    // Default to 30s linger time-out.  Modifyable only for testing.
205    private static int DEFAULT_LINGER_DELAY_MS = 30000;
206    private final int mLingerDelayMs;
207    private int mLingerToken = 0;
208
209    // Start mReevaluateDelayMs at this value and double.
210    private static final int INITIAL_REEVALUATE_DELAY_MS = 1000;
211    private static final int MAX_REEVALUATE_DELAY_MS = 10*60*1000;
212    // Before network has been evaluated this many times, ignore repeated reevaluate requests.
213    private static final int IGNORE_REEVALUATE_ATTEMPTS = 5;
214    private int mReevaluateToken = 0;
215    private static final int INVALID_UID = -1;
216    private int mUidResponsibleForReeval = INVALID_UID;
217    // Stop blaming UID that requested re-evaluation after this many attempts.
218    private static final int BLAME_FOR_EVALUATION_ATTEMPTS = 5;
219    // Delay between reevaluations once a captive portal has been found.
220    private static final int CAPTIVE_PORTAL_REEVALUATE_DELAY_MS = 10*60*1000;
221
222    private final Context mContext;
223    private final Handler mConnectivityServiceHandler;
224    private final NetworkAgentInfo mNetworkAgentInfo;
225    private final int mNetId;
226    private final TelephonyManager mTelephonyManager;
227    private final WifiManager mWifiManager;
228    private final AlarmManager mAlarmManager;
229    private final NetworkRequest mDefaultRequest;
230
231    private boolean mIsCaptivePortalCheckEnabled = false;
232
233    // Set if the user explicitly selected "Do not use this network" in captive portal sign-in app.
234    private boolean mUserDoesNotWant = false;
235    // Avoids surfacing "Sign in to network" notification.
236    private boolean mDontDisplaySigninNotification = false;
237
238    public boolean systemReady = false;
239
240    private final State mDefaultState = new DefaultState();
241    private final State mValidatedState = new ValidatedState();
242    private final State mMaybeNotifyState = new MaybeNotifyState();
243    private final State mEvaluatingState = new EvaluatingState();
244    private final State mCaptivePortalState = new CaptivePortalState();
245    private final State mLingeringState = new LingeringState();
246
247    private CustomIntentReceiver mLaunchCaptivePortalAppBroadcastReceiver = null;
248
249    private final LocalLog validationLogs = new LocalLog(20); // 20 lines
250
251    private final Stopwatch mEvaluationTimer = new Stopwatch();
252
253    public NetworkMonitor(Context context, Handler handler, NetworkAgentInfo networkAgentInfo,
254            NetworkRequest defaultRequest) {
255        // Add suffix indicating which NetworkMonitor we're talking about.
256        super(TAG + networkAgentInfo.name());
257
258        mContext = context;
259        mConnectivityServiceHandler = handler;
260        mNetworkAgentInfo = networkAgentInfo;
261        mNetId = mNetworkAgentInfo.network.netId;
262        mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
263        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
264        mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
265        mDefaultRequest = defaultRequest;
266
267        addState(mDefaultState);
268        addState(mValidatedState, mDefaultState);
269        addState(mMaybeNotifyState, mDefaultState);
270            addState(mEvaluatingState, mMaybeNotifyState);
271            addState(mCaptivePortalState, mMaybeNotifyState);
272        addState(mLingeringState, mDefaultState);
273        setInitialState(mDefaultState);
274
275        mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
276
277        mIsCaptivePortalCheckEnabled = Settings.Global.getInt(mContext.getContentResolver(),
278                Settings.Global.CAPTIVE_PORTAL_DETECTION_ENABLED, 1) == 1;
279
280        start();
281    }
282
283    @Override
284    protected void log(String s) {
285        if (DBG) Log.d(TAG + "/" + mNetworkAgentInfo.name(), s);
286    }
287
288    private void validationLog(String s) {
289        if (DBG) log(s);
290        validationLogs.log(s);
291    }
292
293    public ReadOnlyLocalLog getValidationLogs() {
294        return validationLogs.readOnlyLocalLog();
295    }
296
297    // DefaultState is the parent of all States.  It exists only to handle CMD_* messages but
298    // does not entail any real state (hence no enter() or exit() routines).
299    private class DefaultState extends State {
300        @Override
301        public boolean processMessage(Message message) {
302            switch (message.what) {
303                case CMD_NETWORK_LINGER:
304                    log("Lingering");
305                    transitionTo(mLingeringState);
306                    return HANDLED;
307                case CMD_NETWORK_CONNECTED:
308                    NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_CONNECTED);
309                    transitionTo(mEvaluatingState);
310                    return HANDLED;
311                case CMD_NETWORK_DISCONNECTED:
312                    NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_DISCONNECTED);
313                    if (mLaunchCaptivePortalAppBroadcastReceiver != null) {
314                        mContext.unregisterReceiver(mLaunchCaptivePortalAppBroadcastReceiver);
315                        mLaunchCaptivePortalAppBroadcastReceiver = null;
316                    }
317                    quit();
318                    return HANDLED;
319                case CMD_FORCE_REEVALUATION:
320                case CMD_CAPTIVE_PORTAL_RECHECK:
321                    log("Forcing reevaluation for UID " + message.arg1);
322                    mUidResponsibleForReeval = message.arg1;
323                    transitionTo(mEvaluatingState);
324                    return HANDLED;
325                case CMD_CAPTIVE_PORTAL_APP_FINISHED:
326                    log("CaptivePortal App responded with " + message.arg1);
327                    switch (message.arg1) {
328                        case APP_RETURN_DISMISSED:
329                            sendMessage(CMD_FORCE_REEVALUATION, 0 /* no UID */, 0);
330                            break;
331                        case APP_RETURN_WANTED_AS_IS:
332                            mDontDisplaySigninNotification = true;
333                            // TODO: Distinguish this from a network that actually validates.
334                            // Displaying the "!" on the system UI icon may still be a good idea.
335                            transitionTo(mValidatedState);
336                            break;
337                        case APP_RETURN_UNWANTED:
338                            mDontDisplaySigninNotification = true;
339                            mUserDoesNotWant = true;
340                            mConnectivityServiceHandler.sendMessage(obtainMessage(
341                                    EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID,
342                                    mNetId, null));
343                            // TODO: Should teardown network.
344                            mUidResponsibleForReeval = 0;
345                            transitionTo(mEvaluatingState);
346                            break;
347                    }
348                    return HANDLED;
349                default:
350                    return HANDLED;
351            }
352        }
353    }
354
355    // Being in the ValidatedState State indicates a Network is:
356    // - Successfully validated, or
357    // - Wanted "as is" by the user, or
358    // - Does not satisfy the default NetworkRequest and so validation has been skipped.
359    private class ValidatedState extends State {
360        @Override
361        public void enter() {
362            if (mEvaluationTimer.isRunning()) {
363                NetworkEvent.logValidated(mNetId, mEvaluationTimer.stop());
364                mEvaluationTimer.reset();
365            }
366            mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
367                    NETWORK_TEST_RESULT_VALID, mNetworkAgentInfo.network.netId, null));
368        }
369
370        @Override
371        public boolean processMessage(Message message) {
372            switch (message.what) {
373                case CMD_NETWORK_CONNECTED:
374                    transitionTo(mValidatedState);
375                    return HANDLED;
376                default:
377                    return NOT_HANDLED;
378            }
379        }
380    }
381
382    // Being in the MaybeNotifyState State indicates the user may have been notified that sign-in
383    // is required.  This State takes care to clear the notification upon exit from the State.
384    private class MaybeNotifyState extends State {
385        @Override
386        public boolean processMessage(Message message) {
387            switch (message.what) {
388                case CMD_LAUNCH_CAPTIVE_PORTAL_APP:
389                    final Intent intent = new Intent(
390                            ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
391                    intent.putExtra(ConnectivityManager.EXTRA_NETWORK, mNetworkAgentInfo.network);
392                    intent.putExtra(ConnectivityManager.EXTRA_CAPTIVE_PORTAL,
393                            new CaptivePortal(new ICaptivePortal.Stub() {
394                                @Override
395                                public void appResponse(int response) {
396                                    if (response == APP_RETURN_WANTED_AS_IS) {
397                                        mContext.enforceCallingPermission(
398                                                android.Manifest.permission.CONNECTIVITY_INTERNAL,
399                                                "CaptivePortal");
400                                    }
401                                    sendMessage(CMD_CAPTIVE_PORTAL_APP_FINISHED, response);
402                                }
403                            }));
404                    intent.setFlags(
405                            Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
406                    mContext.startActivityAsUser(intent, UserHandle.CURRENT);
407                    return HANDLED;
408                default:
409                    return NOT_HANDLED;
410            }
411        }
412
413        @Override
414        public void exit() {
415            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 0,
416                    mNetworkAgentInfo.network.netId, null);
417            mConnectivityServiceHandler.sendMessage(message);
418        }
419    }
420
421    /**
422     * Result of calling isCaptivePortal().
423     * @hide
424     */
425    @VisibleForTesting
426    public static final class CaptivePortalProbeResult {
427        final int mHttpResponseCode; // HTTP response code returned from Internet probe.
428        final String mRedirectUrl;   // Redirect destination returned from Internet probe.
429
430        public CaptivePortalProbeResult(int httpResponseCode, String redirectUrl) {
431            mHttpResponseCode = httpResponseCode;
432            mRedirectUrl = redirectUrl;
433        }
434    }
435
436    // Being in the EvaluatingState State indicates the Network is being evaluated for internet
437    // connectivity, or that the user has indicated that this network is unwanted.
438    private class EvaluatingState extends State {
439        private int mReevaluateDelayMs;
440        private int mAttempts;
441
442        @Override
443        public void enter() {
444            // If we have already started to track time spent in EvaluatingState
445            // don't reset the timer due simply to, say, commands or events that
446            // cause us to exit and re-enter EvaluatingState.
447            if (!mEvaluationTimer.isStarted()) {
448                mEvaluationTimer.start();
449            }
450            sendMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
451            if (mUidResponsibleForReeval != INVALID_UID) {
452                TrafficStats.setThreadStatsUid(mUidResponsibleForReeval);
453                mUidResponsibleForReeval = INVALID_UID;
454            }
455            mReevaluateDelayMs = INITIAL_REEVALUATE_DELAY_MS;
456            mAttempts = 0;
457        }
458
459        @Override
460        public boolean processMessage(Message message) {
461            switch (message.what) {
462                case CMD_REEVALUATE:
463                    if (message.arg1 != mReevaluateToken || mUserDoesNotWant)
464                        return HANDLED;
465                    // Don't bother validating networks that don't satisify the default request.
466                    // This includes:
467                    //  - VPNs which can be considered explicitly desired by the user and the
468                    //    user's desire trumps whether the network validates.
469                    //  - Networks that don't provide internet access.  It's unclear how to
470                    //    validate such networks.
471                    //  - Untrusted networks.  It's unsafe to prompt the user to sign-in to
472                    //    such networks and the user didn't express interest in connecting to
473                    //    such networks (an app did) so the user may be unhappily surprised when
474                    //    asked to sign-in to a network they didn't want to connect to in the
475                    //    first place.  Validation could be done to adjust the network scores
476                    //    however these networks are app-requested and may not be intended for
477                    //    general usage, in which case general validation may not be an accurate
478                    //    measure of the network's quality.  Only the app knows how to evaluate
479                    //    the network so don't bother validating here.  Furthermore sending HTTP
480                    //    packets over the network may be undesirable, for example an extremely
481                    //    expensive metered network, or unwanted leaking of the User Agent string.
482                    if (!mDefaultRequest.networkCapabilities.satisfiedByNetworkCapabilities(
483                            mNetworkAgentInfo.networkCapabilities)) {
484                        transitionTo(mValidatedState);
485                        return HANDLED;
486                    }
487                    mAttempts++;
488                    // Note: This call to isCaptivePortal() could take up to a minute. Resolving the
489                    // server's IP addresses could hit the DNS timeout, and attempting connections
490                    // to each of the server's several IP addresses (currently one IPv4 and one
491                    // IPv6) could each take SOCKET_TIMEOUT_MS.  During this time this StateMachine
492                    // will be unresponsive. isCaptivePortal() could be executed on another Thread
493                    // if this is found to cause problems.
494                    CaptivePortalProbeResult probeResult = isCaptivePortal();
495                    if (probeResult.mHttpResponseCode == 204) {
496                        transitionTo(mValidatedState);
497                    } else if (probeResult.mHttpResponseCode >= 200 &&
498                            probeResult.mHttpResponseCode <= 399) {
499                        mConnectivityServiceHandler.sendMessage(obtainMessage(EVENT_NETWORK_TESTED,
500                                NETWORK_TEST_RESULT_INVALID, mNetId, probeResult.mRedirectUrl));
501                        transitionTo(mCaptivePortalState);
502                    } else {
503                        final Message msg = obtainMessage(CMD_REEVALUATE, ++mReevaluateToken, 0);
504                        sendMessageDelayed(msg, mReevaluateDelayMs);
505                        NetworkEvent.logEvent(mNetId, NetworkEvent.NETWORK_VALIDATION_FAILED);
506                        mConnectivityServiceHandler.sendMessage(obtainMessage(
507                                EVENT_NETWORK_TESTED, NETWORK_TEST_RESULT_INVALID, mNetId,
508                                probeResult.mRedirectUrl));
509                        if (mAttempts >= BLAME_FOR_EVALUATION_ATTEMPTS) {
510                            // Don't continue to blame UID forever.
511                            TrafficStats.clearThreadStatsUid();
512                        }
513                        mReevaluateDelayMs *= 2;
514                        if (mReevaluateDelayMs > MAX_REEVALUATE_DELAY_MS) {
515                            mReevaluateDelayMs = MAX_REEVALUATE_DELAY_MS;
516                        }
517                    }
518                    return HANDLED;
519                case CMD_FORCE_REEVALUATION:
520                    // Before IGNORE_REEVALUATE_ATTEMPTS attempts are made,
521                    // ignore any re-evaluation requests. After, restart the
522                    // evaluation process via EvaluatingState#enter.
523                    return (mAttempts < IGNORE_REEVALUATE_ATTEMPTS) ? HANDLED : NOT_HANDLED;
524                default:
525                    return NOT_HANDLED;
526            }
527        }
528
529        @Override
530        public void exit() {
531            TrafficStats.clearThreadStatsUid();
532        }
533    }
534
535    // BroadcastReceiver that waits for a particular Intent and then posts a message.
536    private class CustomIntentReceiver extends BroadcastReceiver {
537        private final int mToken;
538        private final int mWhat;
539        private final String mAction;
540        CustomIntentReceiver(String action, int token, int what) {
541            mToken = token;
542            mWhat = what;
543            mAction = action + "_" + mNetworkAgentInfo.network.netId + "_" + token;
544            mContext.registerReceiver(this, new IntentFilter(mAction));
545        }
546        public PendingIntent getPendingIntent() {
547            final Intent intent = new Intent(mAction);
548            intent.setPackage(mContext.getPackageName());
549            return PendingIntent.getBroadcast(mContext, 0, intent, 0);
550        }
551        @Override
552        public void onReceive(Context context, Intent intent) {
553            if (intent.getAction().equals(mAction)) sendMessage(obtainMessage(mWhat, mToken));
554        }
555    }
556
557    // Being in the CaptivePortalState State indicates a captive portal was detected and the user
558    // has been shown a notification to sign-in.
559    private class CaptivePortalState extends State {
560        private static final String ACTION_LAUNCH_CAPTIVE_PORTAL_APP =
561                "android.net.netmon.launchCaptivePortalApp";
562
563        @Override
564        public void enter() {
565            if (mEvaluationTimer.isRunning()) {
566                NetworkEvent.logCaptivePortalFound(mNetId, mEvaluationTimer.stop());
567                mEvaluationTimer.reset();
568            }
569            // Don't annoy user with sign-in notifications.
570            if (mDontDisplaySigninNotification) return;
571            // Create a CustomIntentReceiver that sends us a
572            // CMD_LAUNCH_CAPTIVE_PORTAL_APP message when the user
573            // touches the notification.
574            if (mLaunchCaptivePortalAppBroadcastReceiver == null) {
575                // Wait for result.
576                mLaunchCaptivePortalAppBroadcastReceiver = new CustomIntentReceiver(
577                        ACTION_LAUNCH_CAPTIVE_PORTAL_APP, new Random().nextInt(),
578                        CMD_LAUNCH_CAPTIVE_PORTAL_APP);
579            }
580            // Display the sign in notification.
581            Message message = obtainMessage(EVENT_PROVISIONING_NOTIFICATION, 1,
582                    mNetworkAgentInfo.network.netId,
583                    mLaunchCaptivePortalAppBroadcastReceiver.getPendingIntent());
584            mConnectivityServiceHandler.sendMessage(message);
585            // Retest for captive portal occasionally.
586            sendMessageDelayed(CMD_CAPTIVE_PORTAL_RECHECK, 0 /* no UID */,
587                    CAPTIVE_PORTAL_REEVALUATE_DELAY_MS);
588        }
589
590        @Override
591        public void exit() {
592             removeMessages(CMD_CAPTIVE_PORTAL_RECHECK);
593        }
594    }
595
596    // Being in the LingeringState State indicates a Network's validated bit is true and it once
597    // was the highest scoring Network satisfying a particular NetworkRequest, but since then
598    // another Network satisfied the NetworkRequest with a higher score and hence this Network
599    // is "lingered" for a fixed period of time before it is disconnected.  This period of time
600    // allows apps to wrap up communication and allows for seamless reactivation if the other
601    // higher scoring Network happens to disconnect.
602    private class LingeringState extends State {
603        private static final String ACTION_LINGER_EXPIRED = "android.net.netmon.lingerExpired";
604
605        private WakeupMessage mWakeupMessage;
606
607        @Override
608        public void enter() {
609            mEvaluationTimer.reset();
610            final String cmdName = ACTION_LINGER_EXPIRED + "." + mNetId;
611            mWakeupMessage = makeWakeupMessage(mContext, getHandler(), cmdName, CMD_LINGER_EXPIRED);
612            long wakeupTime = SystemClock.elapsedRealtime() + mLingerDelayMs;
613            mWakeupMessage.schedule(wakeupTime);
614        }
615
616        @Override
617        public boolean processMessage(Message message) {
618            switch (message.what) {
619                case CMD_NETWORK_CONNECTED:
620                    log("Unlingered");
621                    // If already validated, go straight to validated state.
622                    if (mNetworkAgentInfo.lastValidated) {
623                        transitionTo(mValidatedState);
624                        return HANDLED;
625                    }
626                    return NOT_HANDLED;
627                case CMD_LINGER_EXPIRED:
628                    mConnectivityServiceHandler.sendMessage(
629                            obtainMessage(EVENT_NETWORK_LINGER_COMPLETE, mNetworkAgentInfo));
630                    return HANDLED;
631                case CMD_FORCE_REEVALUATION:
632                    // Ignore reevaluation attempts when lingering.  A reevaluation could result
633                    // in a transition to the validated state which would abort the linger
634                    // timeout.  Lingering is the result of score assessment; validity is
635                    // irrelevant.
636                    return HANDLED;
637                case CMD_CAPTIVE_PORTAL_APP_FINISHED:
638                    // Ignore user network determination as this could abort linger timeout.
639                    // Networks are only lingered once validated because:
640                    // - Unvalidated networks are never lingered (see rematchNetworkAndRequests).
641                    // - Once validated, a Network's validated bit is never cleared.
642                    // Since networks are only lingered after being validated a user's
643                    // determination will not change the death sentence that lingering entails:
644                    // - If the user wants to use the network or bypasses the captive portal,
645                    //   the network's score will not be increased beyond its current value
646                    //   because it is already validated.  Without a score increase there is no
647                    //   chance of reactivation (i.e. aborting linger timeout).
648                    // - If the user does not want the network, lingering will disconnect the
649                    //   network anyhow.
650                    return HANDLED;
651                default:
652                    return NOT_HANDLED;
653            }
654        }
655
656        @Override
657        public void exit() {
658            mWakeupMessage.cancel();
659        }
660    }
661
662    public static String getCaptivePortalServerUrl(Context context) {
663        String server = Settings.Global.getString(context.getContentResolver(),
664                Settings.Global.CAPTIVE_PORTAL_SERVER);
665        if (server == null) server = DEFAULT_SERVER;
666        return "http://" + server + "/generate_204";
667    }
668
669    /**
670     * Do a URL fetch on a known server to see if we get the data we expect.
671     * Returns HTTP response code.
672     */
673    @VisibleForTesting
674    protected CaptivePortalProbeResult isCaptivePortal() {
675        if (!mIsCaptivePortalCheckEnabled) return new CaptivePortalProbeResult(204, null);
676
677        HttpURLConnection urlConnection = null;
678        int httpResponseCode = 599;
679        String redirectUrl = null;
680        final Stopwatch probeTimer = new Stopwatch().start();
681        try {
682            URL url = new URL(getCaptivePortalServerUrl(mContext));
683            // On networks with a PAC instead of fetching a URL that should result in a 204
684            // response, we instead simply fetch the PAC script.  This is done for a few reasons:
685            // 1. At present our PAC code does not yet handle multiple PACs on multiple networks
686            //    until something like https://android-review.googlesource.com/#/c/115180/ lands.
687            //    Network.openConnection() will ignore network-specific PACs and instead fetch
688            //    using NO_PROXY.  If a PAC is in place, the only fetch we know will succeed with
689            //    NO_PROXY is the fetch of the PAC itself.
690            // 2. To proxy the generate_204 fetch through a PAC would require a number of things
691            //    happen before the fetch can commence, namely:
692            //        a) the PAC script be fetched
693            //        b) a PAC script resolver service be fired up and resolve the captive portal
694            //           server.
695            //    Network validation could be delayed until these prerequisities are satisifed or
696            //    could simply be left to race them.  Neither is an optimal solution.
697            // 3. PAC scripts are sometimes used to block or restrict Internet access and may in
698            //    fact block fetching of the generate_204 URL which would lead to false negative
699            //    results for network validation.
700            boolean fetchPac = false;
701            final ProxyInfo proxyInfo = mNetworkAgentInfo.linkProperties.getHttpProxy();
702            if (proxyInfo != null && !Uri.EMPTY.equals(proxyInfo.getPacFileUrl())) {
703                url = new URL(proxyInfo.getPacFileUrl().toString());
704                fetchPac = true;
705            }
706            final StringBuffer connectInfo = new StringBuffer();
707            String hostToResolve = null;
708            // Only resolve a host if HttpURLConnection is about to, to avoid any potentially
709            // unnecessary resolution.
710            if (proxyInfo == null || fetchPac) {
711                hostToResolve = url.getHost();
712            } else if (proxyInfo != null) {
713                hostToResolve = proxyInfo.getHost();
714            }
715            if (!TextUtils.isEmpty(hostToResolve)) {
716                connectInfo.append(", " + hostToResolve + "=");
717                final InetAddress[] addresses =
718                        mNetworkAgentInfo.network.getAllByName(hostToResolve);
719                for (InetAddress address : addresses) {
720                    connectInfo.append(address.getHostAddress());
721                    if (address != addresses[addresses.length-1]) connectInfo.append(",");
722                }
723            }
724            validationLog("Checking " + url.toString() + " on " +
725                    mNetworkAgentInfo.networkInfo.getExtraInfo() + connectInfo);
726            urlConnection = (HttpURLConnection) mNetworkAgentInfo.network.openConnection(url);
727            urlConnection.setInstanceFollowRedirects(fetchPac);
728            urlConnection.setConnectTimeout(SOCKET_TIMEOUT_MS);
729            urlConnection.setReadTimeout(SOCKET_TIMEOUT_MS);
730            urlConnection.setUseCaches(false);
731
732            // Time how long it takes to get a response to our request
733            long requestTimestamp = SystemClock.elapsedRealtime();
734
735            httpResponseCode = urlConnection.getResponseCode();
736            redirectUrl = urlConnection.getHeaderField("location");
737
738            // Time how long it takes to get a response to our request
739            long responseTimestamp = SystemClock.elapsedRealtime();
740
741            validationLog("isCaptivePortal: ret=" + httpResponseCode +
742                    " headers=" + urlConnection.getHeaderFields());
743            // NOTE: We may want to consider an "HTTP/1.0 204" response to be a captive
744            // portal.  The only example of this seen so far was a captive portal.  For
745            // the time being go with prior behavior of assuming it's not a captive
746            // portal.  If it is considered a captive portal, a different sign-in URL
747            // is needed (i.e. can't browse a 204).  This could be the result of an HTTP
748            // proxy server.
749
750            // Consider 200 response with "Content-length=0" to not be a captive portal.
751            // There's no point in considering this a captive portal as the user cannot
752            // sign-in to an empty page.  Probably the result of a broken transparent proxy.
753            // See http://b/9972012.
754            if (httpResponseCode == 200 && urlConnection.getContentLength() == 0) {
755                validationLog("Empty 200 response interpreted as 204 response.");
756                httpResponseCode = 204;
757            }
758
759            if (httpResponseCode == 200 && fetchPac) {
760                validationLog("PAC fetch 200 response interpreted as 204 response.");
761                httpResponseCode = 204;
762            }
763
764            sendNetworkConditionsBroadcast(true /* response received */,
765                    httpResponseCode != 204 /* isCaptivePortal */,
766                    requestTimestamp, responseTimestamp);
767        } catch (IOException e) {
768            validationLog("Probably not a portal: exception " + e);
769            if (httpResponseCode == 599) {
770                // TODO: Ping gateway and DNS server and log results.
771            }
772        } finally {
773            if (urlConnection != null) {
774                urlConnection.disconnect();
775            }
776        }
777        final int probeType = ValidationProbeEvent.PROBE_HTTP;
778        ValidationProbeEvent.logEvent(mNetId, probeTimer.stop(), probeType, httpResponseCode);
779        return new CaptivePortalProbeResult(httpResponseCode, redirectUrl);
780    }
781
782    /**
783     * @param responseReceived - whether or not we received a valid HTTP response to our request.
784     * If false, isCaptivePortal and responseTimestampMs are ignored
785     * TODO: This should be moved to the transports.  The latency could be passed to the transports
786     * along with the captive portal result.  Currently the TYPE_MOBILE broadcasts appear unused so
787     * perhaps this could just be added to the WiFi transport only.
788     */
789    private void sendNetworkConditionsBroadcast(boolean responseReceived, boolean isCaptivePortal,
790            long requestTimestampMs, long responseTimestampMs) {
791        if (Settings.Global.getInt(mContext.getContentResolver(),
792                Settings.Global.WIFI_SCAN_ALWAYS_AVAILABLE, 0) == 0) {
793            return;
794        }
795
796        if (systemReady == false) return;
797
798        Intent latencyBroadcast = new Intent(ACTION_NETWORK_CONDITIONS_MEASURED);
799        switch (mNetworkAgentInfo.networkInfo.getType()) {
800            case ConnectivityManager.TYPE_WIFI:
801                WifiInfo currentWifiInfo = mWifiManager.getConnectionInfo();
802                if (currentWifiInfo != null) {
803                    // NOTE: getSSID()'s behavior changed in API 17; before that, SSIDs were not
804                    // surrounded by double quotation marks (thus violating the Javadoc), but this
805                    // was changed to match the Javadoc in API 17. Since clients may have started
806                    // sanitizing the output of this method since API 17 was released, we should
807                    // not change it here as it would become impossible to tell whether the SSID is
808                    // simply being surrounded by quotes due to the API, or whether those quotes
809                    // are actually part of the SSID.
810                    latencyBroadcast.putExtra(EXTRA_SSID, currentWifiInfo.getSSID());
811                    latencyBroadcast.putExtra(EXTRA_BSSID, currentWifiInfo.getBSSID());
812                } else {
813                    if (DBG) logw("network info is TYPE_WIFI but no ConnectionInfo found");
814                    return;
815                }
816                break;
817            case ConnectivityManager.TYPE_MOBILE:
818                latencyBroadcast.putExtra(EXTRA_NETWORK_TYPE, mTelephonyManager.getNetworkType());
819                List<CellInfo> info = mTelephonyManager.getAllCellInfo();
820                if (info == null) return;
821                int numRegisteredCellInfo = 0;
822                for (CellInfo cellInfo : info) {
823                    if (cellInfo.isRegistered()) {
824                        numRegisteredCellInfo++;
825                        if (numRegisteredCellInfo > 1) {
826                            log("more than one registered CellInfo.  Can't " +
827                                    "tell which is active.  Bailing.");
828                            return;
829                        }
830                        if (cellInfo instanceof CellInfoCdma) {
831                            CellIdentityCdma cellId = ((CellInfoCdma) cellInfo).getCellIdentity();
832                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
833                        } else if (cellInfo instanceof CellInfoGsm) {
834                            CellIdentityGsm cellId = ((CellInfoGsm) cellInfo).getCellIdentity();
835                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
836                        } else if (cellInfo instanceof CellInfoLte) {
837                            CellIdentityLte cellId = ((CellInfoLte) cellInfo).getCellIdentity();
838                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
839                        } else if (cellInfo instanceof CellInfoWcdma) {
840                            CellIdentityWcdma cellId = ((CellInfoWcdma) cellInfo).getCellIdentity();
841                            latencyBroadcast.putExtra(EXTRA_CELL_ID, cellId);
842                        } else {
843                            if (DBG) logw("Registered cellinfo is unrecognized");
844                            return;
845                        }
846                    }
847                }
848                break;
849            default:
850                return;
851        }
852        latencyBroadcast.putExtra(EXTRA_CONNECTIVITY_TYPE, mNetworkAgentInfo.networkInfo.getType());
853        latencyBroadcast.putExtra(EXTRA_RESPONSE_RECEIVED, responseReceived);
854        latencyBroadcast.putExtra(EXTRA_REQUEST_TIMESTAMP_MS, requestTimestampMs);
855
856        if (responseReceived) {
857            latencyBroadcast.putExtra(EXTRA_IS_CAPTIVE_PORTAL, isCaptivePortal);
858            latencyBroadcast.putExtra(EXTRA_RESPONSE_TIMESTAMP_MS, responseTimestampMs);
859        }
860        mContext.sendBroadcastAsUser(latencyBroadcast, UserHandle.CURRENT,
861                PERMISSION_ACCESS_NETWORK_CONDITIONS);
862    }
863
864    // Allow tests to override linger time.
865    @VisibleForTesting
866    public static void SetDefaultLingerTime(int time_ms) {
867        if (Process.myUid() == Process.SYSTEM_UID) {
868            throw new SecurityException("SetDefaultLingerTime only for internal testing.");
869        }
870        DEFAULT_LINGER_DELAY_MS = time_ms;
871    }
872
873    @VisibleForTesting
874    protected WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int i) {
875        return new WakeupMessage(c, h, s, i);
876    }
877}
878