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