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