ConnectivityService.java revision 17e6183b85ba3038acb935aaa01415058b2e6ddd
1/*
2 * Copyright (C) 2008 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;
18
19import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
20import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
21import static android.net.ConnectivityManager.NETID_UNSET;
22import static android.net.ConnectivityManager.TYPE_NONE;
23import static android.net.ConnectivityManager.TYPE_VPN;
24import static android.net.ConnectivityManager.getNetworkTypeName;
25import static android.net.ConnectivityManager.isNetworkTypeValid;
26import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
27import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
31import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
32import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
33import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
34import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
35import static android.net.NetworkPolicyManager.RULE_NONE;
36import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
37import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
38import static android.net.NetworkPolicyManager.uidRulesToString;
39
40import android.annotation.Nullable;
41import android.app.BroadcastOptions;
42import android.app.Notification;
43import android.app.NotificationManager;
44import android.app.PendingIntent;
45import android.content.BroadcastReceiver;
46import android.content.ContentResolver;
47import android.content.Context;
48import android.content.Intent;
49import android.content.IntentFilter;
50import android.content.pm.PackageManager;
51import android.content.res.Configuration;
52import android.content.res.Resources;
53import android.database.ContentObserver;
54import android.net.ConnectivityManager;
55import android.net.ConnectivityManager.PacketKeepalive;
56import android.net.IConnectivityManager;
57import android.net.INetworkManagementEventObserver;
58import android.net.INetworkPolicyListener;
59import android.net.INetworkPolicyManager;
60import android.net.INetworkStatsService;
61import android.net.LinkProperties;
62import android.net.LinkProperties.CompareResult;
63import android.net.Network;
64import android.net.NetworkAgent;
65import android.net.NetworkCapabilities;
66import android.net.NetworkConfig;
67import android.net.NetworkInfo;
68import android.net.NetworkInfo.DetailedState;
69import android.net.NetworkMisc;
70import android.net.NetworkQuotaInfo;
71import android.net.NetworkRequest;
72import android.net.NetworkState;
73import android.net.NetworkUtils;
74import android.net.Proxy;
75import android.net.ProxyInfo;
76import android.net.RouteInfo;
77import android.net.UidRange;
78import android.net.Uri;
79import android.net.metrics.DefaultNetworkEvent;
80import android.net.metrics.NetworkEvent;
81import android.os.Binder;
82import android.os.Build;
83import android.os.Bundle;
84import android.os.FileUtils;
85import android.os.Handler;
86import android.os.HandlerThread;
87import android.os.IBinder;
88import android.os.INetworkManagementService;
89import android.os.Looper;
90import android.os.Message;
91import android.os.Messenger;
92import android.os.ParcelFileDescriptor;
93import android.os.PowerManager;
94import android.os.Process;
95import android.os.RemoteException;
96import android.os.ResultReceiver;
97import android.os.SystemProperties;
98import android.os.UserHandle;
99import android.os.UserManager;
100import android.provider.Settings;
101import android.security.Credentials;
102import android.security.KeyStore;
103import android.telephony.TelephonyManager;
104import android.text.TextUtils;
105import android.util.ArraySet;
106import android.util.LocalLog;
107import android.util.LocalLog.ReadOnlyLocalLog;
108import android.util.Log;
109import android.util.Pair;
110import android.util.Slog;
111import android.util.SparseArray;
112import android.util.SparseBooleanArray;
113import android.util.SparseIntArray;
114import android.util.Xml;
115
116import com.android.internal.R;
117import com.android.internal.annotations.GuardedBy;
118import com.android.internal.annotations.VisibleForTesting;
119import com.android.internal.app.IBatteryStats;
120import com.android.internal.net.LegacyVpnInfo;
121import com.android.internal.net.NetworkStatsFactory;
122import com.android.internal.net.VpnConfig;
123import com.android.internal.net.VpnInfo;
124import com.android.internal.net.VpnProfile;
125import com.android.internal.util.AsyncChannel;
126import com.android.internal.util.IndentingPrintWriter;
127import com.android.internal.util.MessageUtils;
128import com.android.internal.util.XmlUtils;
129import com.android.server.am.BatteryStatsService;
130import com.android.server.connectivity.DataConnectionStats;
131import com.android.server.connectivity.KeepaliveTracker;
132import com.android.server.connectivity.Nat464Xlat;
133import com.android.server.connectivity.NetworkAgentInfo;
134import com.android.server.connectivity.NetworkDiagnostics;
135import com.android.server.connectivity.NetworkMonitor;
136import com.android.server.connectivity.PacManager;
137import com.android.server.connectivity.PermissionMonitor;
138import com.android.server.connectivity.Tethering;
139import com.android.server.connectivity.Vpn;
140import com.android.server.net.BaseNetworkObserver;
141import com.android.server.net.LockdownVpnTracker;
142
143import com.google.android.collect.Lists;
144
145import org.xmlpull.v1.XmlPullParser;
146import org.xmlpull.v1.XmlPullParserException;
147
148import java.io.File;
149import java.io.FileDescriptor;
150import java.io.FileNotFoundException;
151import java.io.FileReader;
152import java.io.IOException;
153import java.io.PrintWriter;
154import java.net.Inet4Address;
155import java.net.InetAddress;
156import java.net.UnknownHostException;
157import java.util.ArrayDeque;
158import java.util.ArrayList;
159import java.util.Arrays;
160import java.util.Collection;
161import java.util.HashMap;
162import java.util.HashSet;
163import java.util.List;
164import java.util.Map;
165import java.util.Objects;
166import java.util.SortedSet;
167import java.util.TreeSet;
168
169/**
170 * @hide
171 */
172public class ConnectivityService extends IConnectivityManager.Stub
173        implements PendingIntent.OnFinished {
174    private static final String TAG = "ConnectivityService";
175
176    private static final boolean DBG = true;
177    private static final boolean VDBG = false;
178
179    private static final boolean LOGD_RULES = false;
180    private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
181
182    // TODO: create better separation between radio types and network types
183
184    // how long to wait before switching back to a radio's default network
185    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
186    // system property that can override the above value
187    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
188            "android.telephony.apn-restore";
189
190    // How long to wait before putting up a "This network doesn't have an Internet connection,
191    // connect anyway?" dialog after the user selects a network that doesn't validate.
192    private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
193
194    // How long to delay to removal of a pending intent based request.
195    // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
196    private final int mReleasePendingIntentDelayMs;
197
198    private Tethering mTethering;
199
200    private final PermissionMonitor mPermissionMonitor;
201
202    private KeyStore mKeyStore;
203
204    @GuardedBy("mVpns")
205    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
206
207    private boolean mLockdownEnabled;
208    private LockdownVpnTracker mLockdownTracker;
209
210    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
211    private Object mRulesLock = new Object();
212    /** Currently active network rules by UID. */
213    @GuardedBy("mRulesLock")
214    private SparseIntArray mUidRules = new SparseIntArray();
215    /** Set of ifaces that are costly. */
216    @GuardedBy("mRulesLock")
217    private ArraySet<String> mMeteredIfaces = new ArraySet<>();
218    /** Flag indicating if background data is restricted. */
219    @GuardedBy("mRulesLock")
220    private boolean mRestrictBackground;
221    /** Flag indicating if background data is restricted due to battery savings. */
222    @GuardedBy("mRulesLock")
223    private boolean mRestrictPower;
224
225    final private Context mContext;
226    private int mNetworkPreference;
227    // 0 is full bad, 100 is full good
228    private int mDefaultInetConditionPublished = 0;
229
230    private int mNumDnsEntries;
231
232    private boolean mTestMode;
233    private static ConnectivityService sServiceInstance;
234
235    private INetworkManagementService mNetd;
236    private INetworkStatsService mStatsService;
237    private INetworkPolicyManager mPolicyManager;
238
239    private String mCurrentTcpBufferSizes;
240
241    private static final int ENABLED  = 1;
242    private static final int DISABLED = 0;
243
244    private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
245            new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
246
247    private enum ReapUnvalidatedNetworks {
248        // Tear down networks that have no chance (e.g. even if validated) of becoming
249        // the highest scoring network satisfying a NetworkRequest.  This should be passed when
250        // all networks have been rematched against all NetworkRequests.
251        REAP,
252        // Don't reap networks.  This should be passed when some networks have not yet been
253        // rematched against all NetworkRequests.
254        DONT_REAP
255    };
256
257    /**
258     * used internally to change our mobile data enabled flag
259     */
260    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
261
262    /**
263     * used internally to clear a wakelock when transitioning
264     * from one net to another.  Clear happens when we get a new
265     * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
266     * after a timeout if no network is found (typically 1 min).
267     */
268    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
269
270    /**
271     * used internally to reload global proxy settings
272     */
273    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
274
275    /**
276     * PAC manager has received new port.
277     */
278    private static final int EVENT_PROXY_HAS_CHANGED = 16;
279
280    /**
281     * used internally when registering NetworkFactories
282     * obj = NetworkFactoryInfo
283     */
284    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
285
286    /**
287     * used internally when registering NetworkAgents
288     * obj = Messenger
289     */
290    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
291
292    /**
293     * used to add a network request
294     * includes a NetworkRequestInfo
295     */
296    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
297
298    /**
299     * indicates a timeout period is over - check if we had a network yet or not
300     * and if not, call the timeout calback (but leave the request live until they
301     * cancel it.
302     * includes a NetworkRequestInfo
303     */
304    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
305
306    /**
307     * used to add a network listener - no request
308     * includes a NetworkRequestInfo
309     */
310    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
311
312    /**
313     * used to remove a network request, either a listener or a real request
314     * arg1 = UID of caller
315     * obj  = NetworkRequest
316     */
317    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
318
319    /**
320     * used internally when registering NetworkFactories
321     * obj = Messenger
322     */
323    private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
324
325    /**
326     * used internally to expire a wakelock when transitioning
327     * from one net to another.  Expire happens when we fail to find
328     * a new network (typically after 1 minute) -
329     * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
330     * a replacement network.
331     */
332    private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
333
334    /**
335     * Used internally to indicate the system is ready.
336     */
337    private static final int EVENT_SYSTEM_READY = 25;
338
339    /**
340     * used to add a network request with a pending intent
341     * obj = NetworkRequestInfo
342     */
343    private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
344
345    /**
346     * used to remove a pending intent and its associated network request.
347     * arg1 = UID of caller
348     * obj  = PendingIntent
349     */
350    private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
351
352    /**
353     * used to specify whether a network should be used even if unvalidated.
354     * arg1 = whether to accept the network if it's unvalidated (1 or 0)
355     * arg2 = whether to remember this choice in the future (1 or 0)
356     * obj  = network
357     */
358    private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
359
360    /**
361     * used to ask the user to confirm a connection to an unvalidated network.
362     * obj  = network
363     */
364    private static final int EVENT_PROMPT_UNVALIDATED = 29;
365
366    /**
367     * used internally to (re)configure mobile data always-on settings.
368     */
369    private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
370
371    /**
372     * used to add a network listener with a pending intent
373     * obj = NetworkRequestInfo
374     */
375    private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
376
377    /** Handler thread used for both of the handlers below. */
378    @VisibleForTesting
379    protected final HandlerThread mHandlerThread;
380    /** Handler used for internal events. */
381    final private InternalHandler mHandler;
382    /** Handler used for incoming {@link NetworkStateTracker} events. */
383    final private NetworkStateTrackerHandler mTrackerHandler;
384
385    private boolean mSystemReady;
386    private Intent mInitialBroadcast;
387
388    private PowerManager.WakeLock mNetTransitionWakeLock;
389    private String mNetTransitionWakeLockCausedBy = "";
390    private int mNetTransitionWakeLockSerialNumber;
391    private int mNetTransitionWakeLockTimeout;
392    private final PowerManager.WakeLock mPendingIntentWakeLock;
393
394    // used in DBG mode to track inet condition reports
395    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
396    private ArrayList mInetLog;
397
398    // track the current default http proxy - tell the world if we get a new one (real change)
399    private volatile ProxyInfo mDefaultProxy = null;
400    private Object mProxyLock = new Object();
401    private boolean mDefaultProxyDisabled = false;
402
403    // track the global proxy.
404    private ProxyInfo mGlobalProxy = null;
405
406    private PacManager mPacManager = null;
407
408    final private SettingsObserver mSettingsObserver;
409
410    private UserManager mUserManager;
411
412    NetworkConfig[] mNetConfigs;
413    int mNetworksDefined;
414
415    // the set of network types that can only be enabled by system/sig apps
416    List mProtectedNetworks;
417
418    private DataConnectionStats mDataConnectionStats;
419
420    TelephonyManager mTelephonyManager;
421
422    private KeepaliveTracker mKeepaliveTracker;
423
424    // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
425    private final static int MIN_NET_ID = 100; // some reserved marks
426    private final static int MAX_NET_ID = 65535;
427    private int mNextNetId = MIN_NET_ID;
428
429    // sequence number of NetworkRequests
430    private int mNextNetworkRequestId = 1;
431
432    // NetworkRequest activity String log entries.
433    private static final int MAX_NETWORK_REQUEST_LOGS = 20;
434    private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
435
436    // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
437    private static final int MAX_VALIDATION_LOGS = 10;
438    private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
439            new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
440
441    private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
442        synchronized(mValidationLogs) {
443            while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
444                mValidationLogs.removeLast();
445            }
446            mValidationLogs.addFirst(new Pair(network, log));
447        }
448    }
449
450    /**
451     * Implements support for the legacy "one network per network type" model.
452     *
453     * We used to have a static array of NetworkStateTrackers, one for each
454     * network type, but that doesn't work any more now that we can have,
455     * for example, more that one wifi network. This class stores all the
456     * NetworkAgentInfo objects that support a given type, but the legacy
457     * API will only see the first one.
458     *
459     * It serves two main purposes:
460     *
461     * 1. Provide information about "the network for a given type" (since this
462     *    API only supports one).
463     * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
464     *    the first network for a given type changes, or if the default network
465     *    changes.
466     */
467    private class LegacyTypeTracker {
468
469        private static final boolean DBG = true;
470        private static final boolean VDBG = false;
471
472        /**
473         * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
474         * Each list holds references to all NetworkAgentInfos that are used to
475         * satisfy requests for that network type.
476         *
477         * This array is built out at startup such that an unsupported network
478         * doesn't get an ArrayList instance, making this a tristate:
479         * unsupported, supported but not active and active.
480         *
481         * The actual lists are populated when we scan the network types that
482         * are supported on this device.
483         */
484        private ArrayList<NetworkAgentInfo> mTypeLists[];
485
486        public LegacyTypeTracker() {
487            mTypeLists = (ArrayList<NetworkAgentInfo>[])
488                    new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
489        }
490
491        public void addSupportedType(int type) {
492            if (mTypeLists[type] != null) {
493                throw new IllegalStateException(
494                        "legacy list for type " + type + "already initialized");
495            }
496            mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
497        }
498
499        public boolean isTypeSupported(int type) {
500            return isNetworkTypeValid(type) && mTypeLists[type] != null;
501        }
502
503        public NetworkAgentInfo getNetworkForType(int type) {
504            if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
505                return mTypeLists[type].get(0);
506            } else {
507                return null;
508            }
509        }
510
511        private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
512                boolean isDefaultNetwork) {
513            if (DBG) {
514                log("Sending " + state +
515                        " broadcast for type " + type + " " + nai.name() +
516                        " isDefaultNetwork=" + isDefaultNetwork);
517            }
518        }
519
520        /** Adds the given network to the specified legacy type list. */
521        public void add(int type, NetworkAgentInfo nai) {
522            if (!isTypeSupported(type)) {
523                return;  // Invalid network type.
524            }
525            if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
526
527            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
528            if (list.contains(nai)) {
529                return;
530            }
531
532            list.add(nai);
533
534            // Send a broadcast if this is the first network of its type or if it's the default.
535            final boolean isDefaultNetwork = isDefaultNetwork(nai);
536            if (list.size() == 1 || isDefaultNetwork) {
537                maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
538                sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
539            }
540        }
541
542        /** Removes the given network from the specified legacy type list. */
543        public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
544            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
545            if (list == null || list.isEmpty()) {
546                return;
547            }
548
549            final boolean wasFirstNetwork = list.get(0).equals(nai);
550
551            if (!list.remove(nai)) {
552                return;
553            }
554
555            final DetailedState state = DetailedState.DISCONNECTED;
556
557            if (wasFirstNetwork || wasDefault) {
558                maybeLogBroadcast(nai, state, type, wasDefault);
559                sendLegacyNetworkBroadcast(nai, state, type);
560            }
561
562            if (!list.isEmpty() && wasFirstNetwork) {
563                if (DBG) log("Other network available for type " + type +
564                              ", sending connected broadcast");
565                final NetworkAgentInfo replacement = list.get(0);
566                maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
567                sendLegacyNetworkBroadcast(replacement, state, type);
568            }
569        }
570
571        /** Removes the given network from all legacy type lists. */
572        public void remove(NetworkAgentInfo nai, boolean wasDefault) {
573            if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
574            for (int type = 0; type < mTypeLists.length; type++) {
575                remove(type, nai, wasDefault);
576            }
577        }
578
579        // send out another legacy broadcast - currently only used for suspend/unsuspend
580        // toggle
581        public void update(NetworkAgentInfo nai) {
582            final boolean isDefault = isDefaultNetwork(nai);
583            final DetailedState state = nai.networkInfo.getDetailedState();
584            for (int type = 0; type < mTypeLists.length; type++) {
585                final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
586                final boolean contains = (list != null && list.contains(nai));
587                final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
588                if (isFirst || (contains && isDefault)) {
589                    maybeLogBroadcast(nai, state, type, isDefault);
590                    sendLegacyNetworkBroadcast(nai, state, type);
591                }
592            }
593        }
594
595        private String naiToString(NetworkAgentInfo nai) {
596            String name = (nai != null) ? nai.name() : "null";
597            String state = (nai.networkInfo != null) ?
598                    nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
599                    "???/???";
600            return name + " " + state;
601        }
602
603        public void dump(IndentingPrintWriter pw) {
604            pw.println("mLegacyTypeTracker:");
605            pw.increaseIndent();
606            pw.print("Supported types:");
607            for (int type = 0; type < mTypeLists.length; type++) {
608                if (mTypeLists[type] != null) pw.print(" " + type);
609            }
610            pw.println();
611            pw.println("Current state:");
612            pw.increaseIndent();
613            for (int type = 0; type < mTypeLists.length; type++) {
614                if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
615                for (NetworkAgentInfo nai : mTypeLists[type]) {
616                    pw.println(type + " " + naiToString(nai));
617                }
618            }
619            pw.decreaseIndent();
620            pw.decreaseIndent();
621            pw.println();
622        }
623    }
624    private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
625
626    @VisibleForTesting
627    protected HandlerThread createHandlerThread() {
628        return new HandlerThread("ConnectivityServiceThread");
629    }
630
631    public ConnectivityService(Context context, INetworkManagementService netManager,
632            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
633        if (DBG) log("ConnectivityService starting up");
634
635        mDefaultRequest = createInternetRequestForTransport(-1);
636        NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
637                new Binder(), NetworkRequestType.REQUEST);
638        mNetworkRequests.put(mDefaultRequest, defaultNRI);
639        mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
640
641        mDefaultMobileDataRequest = createInternetRequestForTransport(
642                NetworkCapabilities.TRANSPORT_CELLULAR);
643
644        mHandlerThread = createHandlerThread();
645        mHandlerThread.start();
646        mHandler = new InternalHandler(mHandlerThread.getLooper());
647        mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
648
649        // setup our unique device name
650        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
651            String id = Settings.Secure.getString(context.getContentResolver(),
652                    Settings.Secure.ANDROID_ID);
653            if (id != null && id.length() > 0) {
654                String name = new String("android-").concat(id);
655                SystemProperties.set("net.hostname", name);
656            }
657        }
658
659        mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
660                Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
661
662        mContext = checkNotNull(context, "missing Context");
663        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
664        mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
665        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
666        mKeyStore = KeyStore.getInstance();
667        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
668
669        try {
670            mPolicyManager.setConnectivityListener(mPolicyListener);
671            mRestrictBackground = mPolicyManager.getRestrictBackground();
672            mRestrictPower = mPolicyManager.getRestrictPower();
673        } catch (RemoteException e) {
674            // ouch, no rules updates means some processes may never get network
675            loge("unable to register INetworkPolicyListener" + e);
676        }
677
678        final PowerManager powerManager = (PowerManager) context.getSystemService(
679                Context.POWER_SERVICE);
680        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
681        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
682                com.android.internal.R.integer.config_networkTransitionTimeout);
683        mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
684
685        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
686
687        // TODO: What is the "correct" way to do determine if this is a wifi only device?
688        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
689        log("wifiOnly=" + wifiOnly);
690        String[] naStrings = context.getResources().getStringArray(
691                com.android.internal.R.array.networkAttributes);
692        for (String naString : naStrings) {
693            try {
694                NetworkConfig n = new NetworkConfig(naString);
695                if (VDBG) log("naString=" + naString + " config=" + n);
696                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
697                    loge("Error in networkAttributes - ignoring attempt to define type " +
698                            n.type);
699                    continue;
700                }
701                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
702                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
703                            n.type);
704                    continue;
705                }
706                if (mNetConfigs[n.type] != null) {
707                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
708                            n.type);
709                    continue;
710                }
711                mLegacyTypeTracker.addSupportedType(n.type);
712
713                mNetConfigs[n.type] = n;
714                mNetworksDefined++;
715            } catch(Exception e) {
716                // ignore it - leave the entry null
717            }
718        }
719
720        // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
721        if (mNetConfigs[TYPE_VPN] == null) {
722            // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
723            // don't need to add TYPE_VPN to mNetConfigs.
724            mLegacyTypeTracker.addSupportedType(TYPE_VPN);
725            mNetworksDefined++;  // used only in the log() statement below.
726        }
727
728        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
729
730        mProtectedNetworks = new ArrayList<Integer>();
731        int[] protectedNetworks = context.getResources().getIntArray(
732                com.android.internal.R.array.config_protectedNetworks);
733        for (int p : protectedNetworks) {
734            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
735                mProtectedNetworks.add(p);
736            } else {
737                if (DBG) loge("Ignoring protectedNetwork " + p);
738            }
739        }
740
741        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
742                && SystemProperties.get("ro.build.type").equals("eng");
743
744        mTethering = new Tethering(mContext, mNetd, statsService);
745
746        mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
747
748        //set up the listener for user state for creating user VPNs
749        IntentFilter intentFilter = new IntentFilter();
750        intentFilter.addAction(Intent.ACTION_USER_STARTED);
751        intentFilter.addAction(Intent.ACTION_USER_STOPPED);
752        intentFilter.addAction(Intent.ACTION_USER_ADDED);
753        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
754        intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
755        mContext.registerReceiverAsUser(
756                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
757
758        try {
759            mNetd.registerObserver(mTethering);
760            mNetd.registerObserver(mDataActivityObserver);
761        } catch (RemoteException e) {
762            loge("Error registering observer :" + e);
763        }
764
765        if (DBG) {
766            mInetLog = new ArrayList();
767        }
768
769        mSettingsObserver = new SettingsObserver(mContext, mHandler);
770        registerSettingsCallbacks();
771
772        mDataConnectionStats = new DataConnectionStats(mContext);
773        mDataConnectionStats.startMonitoring();
774
775        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
776
777        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
778
779        mKeepaliveTracker = new KeepaliveTracker(mHandler);
780    }
781
782    private NetworkRequest createInternetRequestForTransport(int transportType) {
783        NetworkCapabilities netCap = new NetworkCapabilities();
784        netCap.addCapability(NET_CAPABILITY_INTERNET);
785        netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
786        if (transportType > -1) {
787            netCap.addTransportType(transportType);
788        }
789        return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
790    }
791
792    private void handleMobileDataAlwaysOn() {
793        final boolean enable = (Settings.Global.getInt(
794                mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
795        final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
796        if (enable == isEnabled) {
797            return;  // Nothing to do.
798        }
799
800        if (enable) {
801            handleRegisterNetworkRequest(new NetworkRequestInfo(
802                    null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
803        } else {
804            handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
805        }
806    }
807
808    private void registerSettingsCallbacks() {
809        // Watch for global HTTP proxy changes.
810        mSettingsObserver.observe(
811                Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
812                EVENT_APPLY_GLOBAL_HTTP_PROXY);
813
814        // Watch for whether or not to keep mobile data always on.
815        mSettingsObserver.observe(
816                Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
817                EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
818    }
819
820    private synchronized int nextNetworkRequestId() {
821        return mNextNetworkRequestId++;
822    }
823
824    @VisibleForTesting
825    protected int reserveNetId() {
826        synchronized (mNetworkForNetId) {
827            for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
828                int netId = mNextNetId;
829                if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
830                // Make sure NetID unused.  http://b/16815182
831                if (!mNetIdInUse.get(netId)) {
832                    mNetIdInUse.put(netId, true);
833                    return netId;
834                }
835            }
836        }
837        throw new IllegalStateException("No free netIds");
838    }
839
840    private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
841        if (mLegacyTypeTracker.isTypeSupported(networkType)) {
842            final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
843            final NetworkState state;
844            if (nai != null) {
845                state = nai.getNetworkState();
846                state.networkInfo.setType(networkType);
847            } else {
848                final NetworkInfo info = new NetworkInfo(networkType, 0,
849                        getNetworkTypeName(networkType), "");
850                info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
851                info.setIsAvailable(true);
852                state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
853                        null, null, null);
854            }
855            filterNetworkStateForUid(state, uid, ignoreBlocked);
856            return state;
857        } else {
858            return NetworkState.EMPTY;
859        }
860    }
861
862    private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
863        if (network == null) {
864            return null;
865        }
866        synchronized (mNetworkForNetId) {
867            return mNetworkForNetId.get(network.netId);
868        }
869    }
870
871    private Network[] getVpnUnderlyingNetworks(int uid) {
872        if (!mLockdownEnabled) {
873            int user = UserHandle.getUserId(uid);
874            synchronized (mVpns) {
875                Vpn vpn = mVpns.get(user);
876                if (vpn != null && vpn.appliesToUid(uid)) {
877                    return vpn.getUnderlyingNetworks();
878                }
879            }
880        }
881        return null;
882    }
883
884    private NetworkState getUnfilteredActiveNetworkState(int uid) {
885        NetworkAgentInfo nai = getDefaultNetwork();
886
887        final Network[] networks = getVpnUnderlyingNetworks(uid);
888        if (networks != null) {
889            // getUnderlyingNetworks() returns:
890            // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
891            // empty array => the VPN explicitly said "no default network".
892            // non-empty array => the VPN specified one or more default networks; we use the
893            //                    first one.
894            if (networks.length > 0) {
895                nai = getNetworkAgentInfoForNetwork(networks[0]);
896            } else {
897                nai = null;
898            }
899        }
900
901        if (nai != null) {
902            return nai.getNetworkState();
903        } else {
904            return NetworkState.EMPTY;
905        }
906    }
907
908    /**
909     * Check if UID should be blocked from using the network with the given LinkProperties.
910     */
911    private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
912            boolean ignoreBlocked) {
913        // Networks aren't blocked when ignoring blocked status
914        if (ignoreBlocked) return false;
915        // Networks are never blocked for system services
916        if (uid < Process.FIRST_APPLICATION_UID) return false;
917
918        final boolean networkMetered;
919        final int uidRules;
920
921        synchronized (mVpns) {
922            final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
923            if (vpn != null && vpn.isBlockingUid(uid)) {
924                return true;
925            }
926        }
927
928        final String iface = (lp == null ? "" : lp.getInterfaceName());
929        synchronized (mRulesLock) {
930            networkMetered = mMeteredIfaces.contains(iface);
931            uidRules = mUidRules.get(uid, RULE_NONE);
932        }
933
934        boolean allowed = true;
935        // Check Data Saver Mode first...
936        if (networkMetered) {
937            if ((uidRules & RULE_REJECT_METERED) != 0) {
938                if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
939                // Explicitly blacklisted.
940                allowed = false;
941            } else {
942                allowed = !mRestrictBackground
943                      || (uidRules & RULE_ALLOW_METERED) != 0
944                      || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
945                if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
946                        + " mRestrictBackground=" + mRestrictBackground
947                        + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
948                        + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
949                        + ": " + allowed);
950            }
951        }
952        // ...then Battery Saver Mode.
953        if (allowed && mRestrictPower) {
954            allowed = (uidRules & RULE_ALLOW_ALL) != 0;
955            if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
956                    + " mRestrictPower=" + mRestrictPower
957                    + ", whitelisted=" + ((uidRules & RULE_ALLOW_ALL) != 0)
958                    + ": " + allowed);
959        }
960        return !allowed;
961    }
962
963    private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
964        if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
965        boolean removed = false;
966        boolean added = false;
967        synchronized (mBlockedAppUids) {
968            if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
969                added = true;
970            } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
971                removed = true;
972            }
973        }
974        if (added) log("Returning blocked NetworkInfo to uid=" + uid);
975        else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
976    }
977
978    /**
979     * Apply any relevant filters to {@link NetworkState} for the given UID. For
980     * example, this may mark the network as {@link DetailedState#BLOCKED} based
981     * on {@link #isNetworkWithLinkPropertiesBlocked}, or
982     * {@link NetworkInfo#isMetered()} based on network policies.
983     */
984    private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
985        if (state == null || state.networkInfo == null || state.linkProperties == null) return;
986
987        if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
988            state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
989        }
990        if (mLockdownTracker != null) {
991            mLockdownTracker.augmentNetworkInfo(state.networkInfo);
992        }
993
994        // TODO: apply metered state closer to NetworkAgentInfo
995        final long token = Binder.clearCallingIdentity();
996        try {
997            state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
998        } catch (RemoteException e) {
999        } finally {
1000            Binder.restoreCallingIdentity(token);
1001        }
1002    }
1003
1004    /**
1005     * Return NetworkInfo for the active (i.e., connected) network interface.
1006     * It is assumed that at most one network is active at a time. If more
1007     * than one is active, it is indeterminate which will be returned.
1008     * @return the info for the active network, or {@code null} if none is
1009     * active
1010     */
1011    @Override
1012    public NetworkInfo getActiveNetworkInfo() {
1013        enforceAccessPermission();
1014        final int uid = Binder.getCallingUid();
1015        final NetworkState state = getUnfilteredActiveNetworkState(uid);
1016        filterNetworkStateForUid(state, uid, false);
1017        maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1018        return state.networkInfo;
1019    }
1020
1021    @Override
1022    public Network getActiveNetwork() {
1023        enforceAccessPermission();
1024        return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
1025    }
1026
1027    @Override
1028    public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1029        enforceConnectivityInternalPermission();
1030        return getActiveNetworkForUidInternal(uid, ignoreBlocked);
1031    }
1032
1033    private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
1034        final int user = UserHandle.getUserId(uid);
1035        int vpnNetId = NETID_UNSET;
1036        synchronized (mVpns) {
1037            final Vpn vpn = mVpns.get(user);
1038            if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1039        }
1040        NetworkAgentInfo nai;
1041        if (vpnNetId != NETID_UNSET) {
1042            synchronized (mNetworkForNetId) {
1043                nai = mNetworkForNetId.get(vpnNetId);
1044            }
1045            if (nai != null) return nai.network;
1046        }
1047        nai = getDefaultNetwork();
1048        if (nai != null
1049                && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1050            nai = null;
1051        }
1052        return nai != null ? nai.network : null;
1053    }
1054
1055    public NetworkInfo getActiveNetworkInfoUnfiltered() {
1056        enforceAccessPermission();
1057        final int uid = Binder.getCallingUid();
1058        NetworkState state = getUnfilteredActiveNetworkState(uid);
1059        return state.networkInfo;
1060    }
1061
1062    @Override
1063    public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1064        enforceConnectivityInternalPermission();
1065        final NetworkState state = getUnfilteredActiveNetworkState(uid);
1066        filterNetworkStateForUid(state, uid, ignoreBlocked);
1067        return state.networkInfo;
1068    }
1069
1070    @Override
1071    public NetworkInfo getNetworkInfo(int networkType) {
1072        enforceAccessPermission();
1073        final int uid = Binder.getCallingUid();
1074        if (getVpnUnderlyingNetworks(uid) != null) {
1075            // A VPN is active, so we may need to return one of its underlying networks. This
1076            // information is not available in LegacyTypeTracker, so we have to get it from
1077            // getUnfilteredActiveNetworkState.
1078            final NetworkState state = getUnfilteredActiveNetworkState(uid);
1079            if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1080                filterNetworkStateForUid(state, uid, false);
1081                return state.networkInfo;
1082            }
1083        }
1084        final NetworkState state = getFilteredNetworkState(networkType, uid, false);
1085        return state.networkInfo;
1086    }
1087
1088    @Override
1089    public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1090        enforceAccessPermission();
1091        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1092        if (nai != null) {
1093            final NetworkState state = nai.getNetworkState();
1094            filterNetworkStateForUid(state, uid, ignoreBlocked);
1095            return state.networkInfo;
1096        } else {
1097            return null;
1098        }
1099    }
1100
1101    @Override
1102    public NetworkInfo[] getAllNetworkInfo() {
1103        enforceAccessPermission();
1104        final ArrayList<NetworkInfo> result = Lists.newArrayList();
1105        for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1106                networkType++) {
1107            NetworkInfo info = getNetworkInfo(networkType);
1108            if (info != null) {
1109                result.add(info);
1110            }
1111        }
1112        return result.toArray(new NetworkInfo[result.size()]);
1113    }
1114
1115    @Override
1116    public Network getNetworkForType(int networkType) {
1117        enforceAccessPermission();
1118        final int uid = Binder.getCallingUid();
1119        NetworkState state = getFilteredNetworkState(networkType, uid, false);
1120        if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
1121            return state.network;
1122        }
1123        return null;
1124    }
1125
1126    @Override
1127    public Network[] getAllNetworks() {
1128        enforceAccessPermission();
1129        synchronized (mNetworkForNetId) {
1130            final Network[] result = new Network[mNetworkForNetId.size()];
1131            for (int i = 0; i < mNetworkForNetId.size(); i++) {
1132                result[i] = mNetworkForNetId.valueAt(i).network;
1133            }
1134            return result;
1135        }
1136    }
1137
1138    @Override
1139    public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1140        // The basic principle is: if an app's traffic could possibly go over a
1141        // network, without the app doing anything multinetwork-specific,
1142        // (hence, by "default"), then include that network's capabilities in
1143        // the array.
1144        //
1145        // In the normal case, app traffic only goes over the system's default
1146        // network connection, so that's the only network returned.
1147        //
1148        // With a VPN in force, some app traffic may go into the VPN, and thus
1149        // over whatever underlying networks the VPN specifies, while other app
1150        // traffic may go over the system default network (e.g.: a split-tunnel
1151        // VPN, or an app disallowed by the VPN), so the set of networks
1152        // returned includes the VPN's underlying networks and the system
1153        // default.
1154        enforceAccessPermission();
1155
1156        HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1157
1158        NetworkAgentInfo nai = getDefaultNetwork();
1159        NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1160        if (nc != null) {
1161            result.put(nai.network, nc);
1162        }
1163
1164        if (!mLockdownEnabled) {
1165            synchronized (mVpns) {
1166                Vpn vpn = mVpns.get(userId);
1167                if (vpn != null) {
1168                    Network[] networks = vpn.getUnderlyingNetworks();
1169                    if (networks != null) {
1170                        for (Network network : networks) {
1171                            nai = getNetworkAgentInfoForNetwork(network);
1172                            nc = getNetworkCapabilitiesInternal(nai);
1173                            if (nc != null) {
1174                                result.put(network, nc);
1175                            }
1176                        }
1177                    }
1178                }
1179            }
1180        }
1181
1182        NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1183        out = result.values().toArray(out);
1184        return out;
1185    }
1186
1187    @Override
1188    public boolean isNetworkSupported(int networkType) {
1189        enforceAccessPermission();
1190        return mLegacyTypeTracker.isTypeSupported(networkType);
1191    }
1192
1193    /**
1194     * Return LinkProperties for the active (i.e., connected) default
1195     * network interface.  It is assumed that at most one default network
1196     * is active at a time. If more than one is active, it is indeterminate
1197     * which will be returned.
1198     * @return the ip properties for the active network, or {@code null} if
1199     * none is active
1200     */
1201    @Override
1202    public LinkProperties getActiveLinkProperties() {
1203        enforceAccessPermission();
1204        final int uid = Binder.getCallingUid();
1205        NetworkState state = getUnfilteredActiveNetworkState(uid);
1206        return state.linkProperties;
1207    }
1208
1209    @Override
1210    public LinkProperties getLinkPropertiesForType(int networkType) {
1211        enforceAccessPermission();
1212        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1213        if (nai != null) {
1214            synchronized (nai) {
1215                return new LinkProperties(nai.linkProperties);
1216            }
1217        }
1218        return null;
1219    }
1220
1221    // TODO - this should be ALL networks
1222    @Override
1223    public LinkProperties getLinkProperties(Network network) {
1224        enforceAccessPermission();
1225        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1226        if (nai != null) {
1227            synchronized (nai) {
1228                return new LinkProperties(nai.linkProperties);
1229            }
1230        }
1231        return null;
1232    }
1233
1234    private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
1235        if (nai != null) {
1236            synchronized (nai) {
1237                if (nai.networkCapabilities != null) {
1238                    return new NetworkCapabilities(nai.networkCapabilities);
1239                }
1240            }
1241        }
1242        return null;
1243    }
1244
1245    @Override
1246    public NetworkCapabilities getNetworkCapabilities(Network network) {
1247        enforceAccessPermission();
1248        return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1249    }
1250
1251    @Override
1252    public NetworkState[] getAllNetworkState() {
1253        // Require internal since we're handing out IMSI details
1254        enforceConnectivityInternalPermission();
1255
1256        final ArrayList<NetworkState> result = Lists.newArrayList();
1257        for (Network network : getAllNetworks()) {
1258            final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1259            if (nai != null) {
1260                result.add(nai.getNetworkState());
1261            }
1262        }
1263        return result.toArray(new NetworkState[result.size()]);
1264    }
1265
1266    @Override
1267    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1268        enforceAccessPermission();
1269        final int uid = Binder.getCallingUid();
1270        final long token = Binder.clearCallingIdentity();
1271        try {
1272            final NetworkState state = getUnfilteredActiveNetworkState(uid);
1273            if (state.networkInfo != null) {
1274                try {
1275                    return mPolicyManager.getNetworkQuotaInfo(state);
1276                } catch (RemoteException e) {
1277                }
1278            }
1279            return null;
1280        } finally {
1281            Binder.restoreCallingIdentity(token);
1282        }
1283    }
1284
1285    @Override
1286    public boolean isActiveNetworkMetered() {
1287        enforceAccessPermission();
1288
1289        final NetworkInfo info = getActiveNetworkInfo();
1290        return (info != null) ? info.isMetered() : false;
1291    }
1292
1293    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1294        @Override
1295        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1296            int deviceType = Integer.parseInt(label);
1297            sendDataActivityBroadcast(deviceType, active, tsNanos);
1298        }
1299    };
1300
1301    /**
1302     * Ensure that a network route exists to deliver traffic to the specified
1303     * host via the specified network interface.
1304     * @param networkType the type of the network over which traffic to the
1305     * specified host is to be routed
1306     * @param hostAddress the IP address of the host to which the route is
1307     * desired
1308     * @return {@code true} on success, {@code false} on failure
1309     */
1310    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1311        enforceChangePermission();
1312        if (mProtectedNetworks.contains(networkType)) {
1313            enforceConnectivityInternalPermission();
1314        }
1315
1316        InetAddress addr;
1317        try {
1318            addr = InetAddress.getByAddress(hostAddress);
1319        } catch (UnknownHostException e) {
1320            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1321            return false;
1322        }
1323
1324        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1325            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1326            return false;
1327        }
1328
1329        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1330        if (nai == null) {
1331            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1332                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1333            } else {
1334                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1335            }
1336            return false;
1337        }
1338
1339        DetailedState netState;
1340        synchronized (nai) {
1341            netState = nai.networkInfo.getDetailedState();
1342        }
1343
1344        if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
1345            if (VDBG) {
1346                log("requestRouteToHostAddress on down network "
1347                        + "(" + networkType + ") - dropped"
1348                        + " netState=" + netState);
1349            }
1350            return false;
1351        }
1352
1353        final int uid = Binder.getCallingUid();
1354        final long token = Binder.clearCallingIdentity();
1355        try {
1356            LinkProperties lp;
1357            int netId;
1358            synchronized (nai) {
1359                lp = nai.linkProperties;
1360                netId = nai.network.netId;
1361            }
1362            boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
1363            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1364            return ok;
1365        } finally {
1366            Binder.restoreCallingIdentity(token);
1367        }
1368    }
1369
1370    private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
1371        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1372        if (bestRoute == null) {
1373            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1374        } else {
1375            String iface = bestRoute.getInterface();
1376            if (bestRoute.getGateway().equals(addr)) {
1377                // if there is no better route, add the implied hostroute for our gateway
1378                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1379            } else {
1380                // if we will connect to this through another route, add a direct route
1381                // to it's gateway
1382                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1383            }
1384        }
1385        if (DBG) log("Adding legacy route " + bestRoute +
1386                " for UID/PID " + uid + "/" + Binder.getCallingPid());
1387        try {
1388            mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1389        } catch (Exception e) {
1390            // never crash - catch them all
1391            if (DBG) loge("Exception trying to add a route: " + e);
1392            return false;
1393        }
1394        return true;
1395    }
1396
1397    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1398        @Override
1399        public void onUidRulesChanged(int uid, int uidRules) {
1400            // caller is NPMS, since we only register with them
1401            if (LOGD_RULES) {
1402                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1403            }
1404
1405            synchronized (mRulesLock) {
1406                // skip update when we've already applied rules
1407                final int oldRules = mUidRules.get(uid, RULE_NONE);
1408                if (oldRules == uidRules) return;
1409
1410                mUidRules.put(uid, uidRules);
1411            }
1412
1413            // TODO: notify UID when it has requested targeted updates
1414        }
1415
1416        @Override
1417        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1418            // caller is NPMS, since we only register with them
1419            if (LOGD_RULES) {
1420                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1421            }
1422
1423            synchronized (mRulesLock) {
1424                mMeteredIfaces.clear();
1425                for (String iface : meteredIfaces) {
1426                    mMeteredIfaces.add(iface);
1427                }
1428            }
1429        }
1430
1431        @Override
1432        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1433            // caller is NPMS, since we only register with them
1434            if (LOGD_RULES) {
1435                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1436            }
1437
1438            synchronized (mRulesLock) {
1439                mRestrictBackground = restrictBackground;
1440            }
1441
1442            if (restrictBackground) {
1443                log("onRestrictBackgroundChanged(true): disabling tethering");
1444                mTethering.untetherAll();
1445            }
1446        }
1447
1448        @Override
1449        public void onRestrictPowerChanged(boolean restrictPower) {
1450            // caller is NPMS, since we only register with them
1451            if (LOGD_RULES) {
1452                log("onRestrictPowerChanged(restrictPower=" + restrictPower + ")");
1453            }
1454
1455            synchronized (mRulesLock) {
1456                mRestrictPower = restrictPower;
1457            }
1458        }
1459
1460        @Override
1461        public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1462            if (LOGD_RULES) {
1463                // caller is NPMS, since we only register with them
1464                log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1465                        + whitelisted + ")");
1466            }
1467        }
1468    };
1469
1470    /**
1471     * Require that the caller is either in the same user or has appropriate permission to interact
1472     * across users.
1473     *
1474     * @param userId Target user for whatever operation the current IPC is supposed to perform.
1475     */
1476    private void enforceCrossUserPermission(int userId) {
1477        if (userId == UserHandle.getCallingUserId()) {
1478            // Not a cross-user call.
1479            return;
1480        }
1481        mContext.enforceCallingOrSelfPermission(
1482                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1483                "ConnectivityService");
1484    }
1485
1486    private void enforceInternetPermission() {
1487        mContext.enforceCallingOrSelfPermission(
1488                android.Manifest.permission.INTERNET,
1489                "ConnectivityService");
1490    }
1491
1492    private void enforceAccessPermission() {
1493        mContext.enforceCallingOrSelfPermission(
1494                android.Manifest.permission.ACCESS_NETWORK_STATE,
1495                "ConnectivityService");
1496    }
1497
1498    private void enforceChangePermission() {
1499        ConnectivityManager.enforceChangePermission(mContext);
1500    }
1501
1502    private void enforceTetherAccessPermission() {
1503        mContext.enforceCallingOrSelfPermission(
1504                android.Manifest.permission.ACCESS_NETWORK_STATE,
1505                "ConnectivityService");
1506    }
1507
1508    private void enforceConnectivityInternalPermission() {
1509        mContext.enforceCallingOrSelfPermission(
1510                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1511                "ConnectivityService");
1512    }
1513
1514    private void enforceKeepalivePermission() {
1515        mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
1516    }
1517
1518    public void sendConnectedBroadcast(NetworkInfo info) {
1519        enforceConnectivityInternalPermission();
1520        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1521    }
1522
1523    private void sendInetConditionBroadcast(NetworkInfo info) {
1524        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1525    }
1526
1527    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1528        if (mLockdownTracker != null) {
1529            info = new NetworkInfo(info);
1530            mLockdownTracker.augmentNetworkInfo(info);
1531        }
1532
1533        Intent intent = new Intent(bcastType);
1534        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1535        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1536        if (info.isFailover()) {
1537            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1538            info.setFailover(false);
1539        }
1540        if (info.getReason() != null) {
1541            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1542        }
1543        if (info.getExtraInfo() != null) {
1544            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1545                    info.getExtraInfo());
1546        }
1547        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1548        return intent;
1549    }
1550
1551    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1552        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1553    }
1554
1555    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
1556        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1557        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1558        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1559        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
1560        final long ident = Binder.clearCallingIdentity();
1561        try {
1562            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1563                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1564        } finally {
1565            Binder.restoreCallingIdentity(ident);
1566        }
1567    }
1568
1569    private void sendStickyBroadcast(Intent intent) {
1570        synchronized(this) {
1571            if (!mSystemReady) {
1572                mInitialBroadcast = new Intent(intent);
1573            }
1574            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1575            if (VDBG) {
1576                log("sendStickyBroadcast: action=" + intent.getAction());
1577            }
1578
1579            Bundle options = null;
1580            final long ident = Binder.clearCallingIdentity();
1581            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1582                final NetworkInfo ni = intent.getParcelableExtra(
1583                        ConnectivityManager.EXTRA_NETWORK_INFO);
1584                if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1585                    intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1586                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1587                } else {
1588                    BroadcastOptions opts = BroadcastOptions.makeBasic();
1589                    opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1590                    options = opts.toBundle();
1591                }
1592                final IBatteryStats bs = BatteryStatsService.getService();
1593                try {
1594                    bs.noteConnectivityChanged(intent.getIntExtra(
1595                            ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1596                            ni != null ? ni.getState().toString() : "?");
1597                } catch (RemoteException e) {
1598                }
1599            }
1600            try {
1601                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
1602            } finally {
1603                Binder.restoreCallingIdentity(ident);
1604            }
1605        }
1606    }
1607
1608    void systemReady() {
1609        loadGlobalProxy();
1610
1611        synchronized(this) {
1612            mSystemReady = true;
1613            if (mInitialBroadcast != null) {
1614                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
1615                mInitialBroadcast = null;
1616            }
1617        }
1618        // load the global proxy at startup
1619        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1620
1621        // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1622        // for user to unlock device too.
1623        updateLockdownVpn();
1624
1625        // Configure whether mobile data is always on.
1626        mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1627
1628        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
1629
1630        mPermissionMonitor.startMonitoring();
1631    }
1632
1633    /**
1634     * Setup data activity tracking for the given network.
1635     *
1636     * Every {@code setupDataActivityTracking} should be paired with a
1637     * {@link #removeDataActivityTracking} for cleanup.
1638     */
1639    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1640        final String iface = networkAgent.linkProperties.getInterfaceName();
1641
1642        final int timeout;
1643        int type = ConnectivityManager.TYPE_NONE;
1644
1645        if (networkAgent.networkCapabilities.hasTransport(
1646                NetworkCapabilities.TRANSPORT_CELLULAR)) {
1647            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1648                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
1649                                             10);
1650            type = ConnectivityManager.TYPE_MOBILE;
1651        } else if (networkAgent.networkCapabilities.hasTransport(
1652                NetworkCapabilities.TRANSPORT_WIFI)) {
1653            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1654                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
1655                                             15);
1656            type = ConnectivityManager.TYPE_WIFI;
1657        } else {
1658            // do not track any other networks
1659            timeout = 0;
1660        }
1661
1662        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
1663            try {
1664                mNetd.addIdleTimer(iface, timeout, type);
1665            } catch (Exception e) {
1666                // You shall not crash!
1667                loge("Exception in setupDataActivityTracking " + e);
1668            }
1669        }
1670    }
1671
1672    /**
1673     * Remove data activity tracking when network disconnects.
1674     */
1675    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1676        final String iface = networkAgent.linkProperties.getInterfaceName();
1677        final NetworkCapabilities caps = networkAgent.networkCapabilities;
1678
1679        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1680                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
1681            try {
1682                // the call fails silently if no idletimer setup for this interface
1683                mNetd.removeIdleTimer(iface);
1684            } catch (Exception e) {
1685                loge("Exception in removeDataActivityTracking " + e);
1686            }
1687        }
1688    }
1689
1690    /**
1691     * Reads the network specific MTU size from reources.
1692     * and set it on it's iface.
1693     */
1694    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1695        final String iface = newLp.getInterfaceName();
1696        final int mtu = newLp.getMtu();
1697        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1698            if (VDBG) log("identical MTU - not setting");
1699            return;
1700        }
1701
1702        if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
1703            if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
1704            return;
1705        }
1706
1707        // Cannot set MTU without interface name
1708        if (TextUtils.isEmpty(iface)) {
1709            loge("Setting MTU size with null iface.");
1710            return;
1711        }
1712
1713        try {
1714            if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
1715            mNetd.setMtu(iface, mtu);
1716        } catch (Exception e) {
1717            Slog.e(TAG, "exception in setMtu()" + e);
1718        }
1719    }
1720
1721    private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
1722    private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1723
1724    // Overridden for testing purposes to avoid writing to SystemProperties.
1725    @VisibleForTesting
1726    protected int getDefaultTcpRwnd() {
1727        return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1728    }
1729
1730    private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1731        if (isDefaultNetwork(nai) == false) {
1732            return;
1733        }
1734
1735        String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1736        String[] values = null;
1737        if (tcpBufferSizes != null) {
1738            values = tcpBufferSizes.split(",");
1739        }
1740
1741        if (values == null || values.length != 6) {
1742            if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
1743            tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1744            values = tcpBufferSizes.split(",");
1745        }
1746
1747        if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1748
1749        try {
1750            if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
1751
1752            final String prefix = "/sys/kernel/ipv4/tcp_";
1753            FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1754            FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1755            FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1756            FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1757            FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1758            FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1759            mCurrentTcpBufferSizes = tcpBufferSizes;
1760        } catch (IOException e) {
1761            loge("Can't set TCP buffer sizes:" + e);
1762        }
1763
1764        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1765            Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
1766        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1767        if (rwndValue != 0) {
1768            SystemProperties.set(sysctlKey, rwndValue.toString());
1769        }
1770    }
1771
1772    private void flushVmDnsCache() {
1773        /*
1774         * Tell the VMs to toss their DNS caches
1775         */
1776        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1777        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1778        /*
1779         * Connectivity events can happen before boot has completed ...
1780         */
1781        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1782        final long ident = Binder.clearCallingIdentity();
1783        try {
1784            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1785        } finally {
1786            Binder.restoreCallingIdentity(ident);
1787        }
1788    }
1789
1790    @Override
1791    public int getRestoreDefaultNetworkDelay(int networkType) {
1792        String restoreDefaultNetworkDelayStr = SystemProperties.get(
1793                NETWORK_RESTORE_DELAY_PROP_NAME);
1794        if(restoreDefaultNetworkDelayStr != null &&
1795                restoreDefaultNetworkDelayStr.length() != 0) {
1796            try {
1797                return Integer.parseInt(restoreDefaultNetworkDelayStr);
1798            } catch (NumberFormatException e) {
1799            }
1800        }
1801        // if the system property isn't set, use the value for the apn type
1802        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1803
1804        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1805                (mNetConfigs[networkType] != null)) {
1806            ret = mNetConfigs[networkType].restoreTime;
1807        }
1808        return ret;
1809    }
1810
1811    private boolean argsContain(String[] args, String target) {
1812        for (String arg : args) {
1813            if (arg.equals(target)) return true;
1814        }
1815        return false;
1816    }
1817
1818    private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1819        final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1820        final long DIAG_TIME_MS = 5000;
1821        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1822            // Start gathering diagnostic information.
1823            netDiags.add(new NetworkDiagnostics(
1824                    nai.network,
1825                    new LinkProperties(nai.linkProperties),  // Must be a copy.
1826                    DIAG_TIME_MS));
1827        }
1828
1829        for (NetworkDiagnostics netDiag : netDiags) {
1830            pw.println();
1831            netDiag.waitForMeasurements();
1832            netDiag.dump(pw);
1833        }
1834    }
1835
1836    @Override
1837    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1838        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1839        if (mContext.checkCallingOrSelfPermission(
1840                android.Manifest.permission.DUMP)
1841                != PackageManager.PERMISSION_GRANTED) {
1842            pw.println("Permission Denial: can't dump ConnectivityService " +
1843                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
1844                    Binder.getCallingUid());
1845            return;
1846        }
1847
1848        if (argsContain(args, "--diag")) {
1849            dumpNetworkDiagnostics(pw);
1850            return;
1851        }
1852
1853        pw.print("NetworkFactories for:");
1854        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1855            pw.print(" " + nfi.name);
1856        }
1857        pw.println();
1858        pw.println();
1859
1860        final NetworkAgentInfo defaultNai = getDefaultNetwork();
1861        pw.print("Active default network: ");
1862        if (defaultNai == null) {
1863            pw.println("none");
1864        } else {
1865            pw.println(defaultNai.network.netId);
1866        }
1867        pw.println();
1868
1869        pw.println("Current Networks:");
1870        pw.increaseIndent();
1871        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1872            pw.println(nai.toString());
1873            pw.increaseIndent();
1874            pw.println("Requests:");
1875            pw.increaseIndent();
1876            for (int i = 0; i < nai.networkRequests.size(); i++) {
1877                pw.println(nai.networkRequests.valueAt(i).toString());
1878            }
1879            pw.decreaseIndent();
1880            pw.println("Lingered:");
1881            pw.increaseIndent();
1882            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1883            pw.decreaseIndent();
1884            pw.decreaseIndent();
1885        }
1886        pw.decreaseIndent();
1887        pw.println();
1888
1889        pw.println("Metered Interfaces:");
1890        pw.increaseIndent();
1891        for (String value : mMeteredIfaces) {
1892            pw.println(value);
1893        }
1894        pw.decreaseIndent();
1895        pw.println();
1896
1897        pw.print("Restrict background: ");
1898        pw.println(mRestrictBackground);
1899        pw.println();
1900
1901        pw.print("Restrict power: ");
1902        pw.println(mRestrictPower);
1903        pw.println();
1904
1905        pw.println("Status for known UIDs:");
1906        pw.increaseIndent();
1907        final int size = mUidRules.size();
1908        for (int i = 0; i < size; i++) {
1909            final int uid = mUidRules.keyAt(i);
1910            pw.print("UID=");
1911            pw.print(uid);
1912            final int uidRules = mUidRules.get(uid, RULE_NONE);
1913            pw.print(" rules=");
1914            pw.print(uidRulesToString(uidRules));
1915            pw.println();
1916        }
1917        pw.println();
1918        pw.decreaseIndent();
1919
1920        pw.println("Network Requests:");
1921        pw.increaseIndent();
1922        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1923            pw.println(nri.toString());
1924        }
1925        pw.println();
1926        pw.decreaseIndent();
1927
1928        mLegacyTypeTracker.dump(pw);
1929
1930        synchronized (this) {
1931            pw.print("mNetTransitionWakeLock: currently " +
1932                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1933            if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1934                pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1935            } else {
1936                pw.println(", last requested never");
1937            }
1938        }
1939
1940        pw.println();
1941        mTethering.dump(fd, pw, args);
1942
1943        pw.println();
1944        mKeepaliveTracker.dump(pw);
1945
1946        pw.println();
1947
1948        if (mInetLog != null && mInetLog.size() > 0) {
1949            pw.println();
1950            pw.println("Inet condition reports:");
1951            pw.increaseIndent();
1952            for(int i = 0; i < mInetLog.size(); i++) {
1953                pw.println(mInetLog.get(i));
1954            }
1955            pw.decreaseIndent();
1956        }
1957
1958        if (argsContain(args, "--short") == false) {
1959            pw.println();
1960            synchronized (mValidationLogs) {
1961                pw.println("mValidationLogs (most recent first):");
1962                for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1963                    pw.println(p.first);
1964                    pw.increaseIndent();
1965                    p.second.dump(fd, pw, args);
1966                    pw.decreaseIndent();
1967                }
1968            }
1969
1970            pw.println();
1971            pw.println("mNetworkRequestInfoLogs (most recent first):");
1972            pw.increaseIndent();
1973            mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1974            pw.decreaseIndent();
1975        }
1976    }
1977
1978    private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
1979        if (nai.network == null) return false;
1980        final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
1981        if (officialNai != null && officialNai.equals(nai)) return true;
1982        if (officialNai != null || VDBG) {
1983            final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
1984            loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
1985                " - " + nai);
1986        }
1987        return false;
1988    }
1989
1990    private boolean isRequest(NetworkRequest request) {
1991        return mNetworkRequests.get(request).isRequest();
1992    }
1993
1994    // must be stateless - things change under us.
1995    private class NetworkStateTrackerHandler extends Handler {
1996        public NetworkStateTrackerHandler(Looper looper) {
1997            super(looper);
1998        }
1999
2000        private boolean maybeHandleAsyncChannelMessage(Message msg) {
2001            switch (msg.what) {
2002                default:
2003                    return false;
2004                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
2005                    handleAsyncChannelHalfConnect(msg);
2006                    break;
2007                }
2008                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2009                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2010                    if (nai != null) nai.asyncChannel.disconnect();
2011                    break;
2012                }
2013                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2014                    handleAsyncChannelDisconnected(msg);
2015                    break;
2016                }
2017            }
2018            return true;
2019        }
2020
2021        private void maybeHandleNetworkAgentMessage(Message msg) {
2022            NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2023            if (nai == null) {
2024                if (VDBG) {
2025                    final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2026                    log(String.format("%s from unknown NetworkAgent", what));
2027                }
2028                return;
2029            }
2030
2031            switch (msg.what) {
2032                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
2033                    final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2034                    if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2035                            networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2036                        Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
2037                    }
2038                    if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
2039                            networkCapabilities)) {
2040                        Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2041                                + nai.networkCapabilities + " -> " + networkCapabilities);
2042                    }
2043                    updateCapabilities(nai, networkCapabilities);
2044                    break;
2045                }
2046                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
2047                    if (VDBG) {
2048                        log("Update of LinkProperties for " + nai.name() +
2049                                "; created=" + nai.created +
2050                                "; everConnected=" + nai.everConnected);
2051                    }
2052                    LinkProperties oldLp = nai.linkProperties;
2053                    synchronized (nai) {
2054                        nai.linkProperties = (LinkProperties)msg.obj;
2055                    }
2056                    if (nai.everConnected) updateLinkProperties(nai, oldLp);
2057                    break;
2058                }
2059                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
2060                    NetworkInfo info = (NetworkInfo) msg.obj;
2061                    updateNetworkInfo(nai, info);
2062                    break;
2063                }
2064                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
2065                    Integer score = (Integer) msg.obj;
2066                    if (score != null) updateNetworkScore(nai, score.intValue());
2067                    break;
2068                }
2069                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2070                    try {
2071                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
2072                    } catch (Exception e) {
2073                        // Never crash!
2074                        loge("Exception in addVpnUidRanges: " + e);
2075                    }
2076                    break;
2077                }
2078                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2079                    try {
2080                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
2081                    } catch (Exception e) {
2082                        // Never crash!
2083                        loge("Exception in removeVpnUidRanges: " + e);
2084                    }
2085                    break;
2086                }
2087                case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2088                    if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2089                        loge("ERROR: already-connected network explicitly selected.");
2090                    }
2091                    nai.networkMisc.explicitlySelected = true;
2092                    nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
2093                    break;
2094                }
2095                case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2096                    mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2097                    break;
2098                }
2099            }
2100        }
2101
2102        private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2103            switch (msg.what) {
2104                default:
2105                    return false;
2106                case NetworkMonitor.EVENT_NETWORK_TESTED: {
2107                    final NetworkAgentInfo nai;
2108                    synchronized (mNetworkForNetId) {
2109                        nai = mNetworkForNetId.get(msg.arg2);
2110                    }
2111                    if (nai != null) {
2112                        final boolean valid =
2113                                (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2114                        if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2115                                (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
2116                        if (valid != nai.lastValidated) {
2117                            final int oldScore = nai.getCurrentScore();
2118                            nai.lastValidated = valid;
2119                            nai.everValidated |= valid;
2120                            updateCapabilities(nai, nai.networkCapabilities);
2121                            // If score has changed, rebroadcast to NetworkFactories. b/17726566
2122                            if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2123                        }
2124                        updateInetCondition(nai);
2125                        // Let the NetworkAgent know the state of its network
2126                        Bundle redirectUrlBundle = new Bundle();
2127                        redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
2128                        nai.asyncChannel.sendMessage(
2129                                NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2130                                (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2131                                0, redirectUrlBundle);
2132                    }
2133                    break;
2134                }
2135                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
2136                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
2137                    if (isLiveNetworkAgent(nai, msg.what)) {
2138                        handleLingerComplete(nai);
2139                    }
2140                    break;
2141                }
2142                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
2143                    final int netId = msg.arg2;
2144                    final boolean visible = (msg.arg1 != 0);
2145                    final NetworkAgentInfo nai;
2146                    synchronized (mNetworkForNetId) {
2147                        nai = mNetworkForNetId.get(netId);
2148                    }
2149                    // If captive portal status has changed, update capabilities.
2150                    if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2151                        nai.lastCaptivePortalDetected = visible;
2152                        nai.everCaptivePortalDetected |= visible;
2153                        updateCapabilities(nai, nai.networkCapabilities);
2154                    }
2155                    if (!visible) {
2156                        setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
2157                    } else {
2158                        if (nai == null) {
2159                            loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2160                            break;
2161                        }
2162                        setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2163                                nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2164                                (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
2165                    }
2166                    break;
2167                }
2168            }
2169            return true;
2170        }
2171
2172        @Override
2173        public void handleMessage(Message msg) {
2174            if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2175                maybeHandleNetworkAgentMessage(msg);
2176            }
2177        }
2178    }
2179
2180    private void linger(NetworkAgentInfo nai) {
2181        nai.lingering = true;
2182        NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
2183        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2184        notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2185    }
2186
2187    // Cancel any lingering so the linger timeout doesn't teardown a network.
2188    // This should be called when a network begins satisfying a NetworkRequest.
2189    // Note: depending on what state the NetworkMonitor is in (e.g.,
2190    // if it's awaiting captive portal login, or if validation failed), this
2191    // may trigger a re-evaluation of the network.
2192    private void unlinger(NetworkAgentInfo nai) {
2193        nai.networkLingered.clear();
2194        if (!nai.lingering) return;
2195        nai.lingering = false;
2196        NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
2197        if (VDBG) log("Canceling linger of " + nai.name());
2198        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2199    }
2200
2201    private void handleAsyncChannelHalfConnect(Message msg) {
2202        AsyncChannel ac = (AsyncChannel) msg.obj;
2203        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
2204            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2205                if (VDBG) log("NetworkFactory connected");
2206                // A network factory has connected.  Send it all current NetworkRequests.
2207                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2208                    if (!nri.isRequest()) continue;
2209                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2210                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
2211                            (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
2212                }
2213            } else {
2214                loge("Error connecting NetworkFactory");
2215                mNetworkFactoryInfos.remove(msg.obj);
2216            }
2217        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2218            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2219                if (VDBG) log("NetworkAgent connected");
2220                // A network agent has requested a connection.  Establish the connection.
2221                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2222                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2223            } else {
2224                loge("Error connecting NetworkAgent");
2225                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
2226                if (nai != null) {
2227                    final boolean wasDefault = isDefaultNetwork(nai);
2228                    synchronized (mNetworkForNetId) {
2229                        mNetworkForNetId.remove(nai.network.netId);
2230                        mNetIdInUse.delete(nai.network.netId);
2231                    }
2232                    // Just in case.
2233                    mLegacyTypeTracker.remove(nai, wasDefault);
2234                }
2235            }
2236        }
2237    }
2238
2239    private void handleAsyncChannelDisconnected(Message msg) {
2240        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2241        if (nai != null) {
2242            if (DBG) {
2243                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2244            }
2245            // A network agent has disconnected.
2246            // TODO - if we move the logic to the network agent (have them disconnect
2247            // because they lost all their requests or because their score isn't good)
2248            // then they would disconnect organically, report their new state and then
2249            // disconnect the channel.
2250            if (nai.networkInfo.isConnected()) {
2251                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2252                        null, null);
2253            }
2254            final boolean wasDefault = isDefaultNetwork(nai);
2255            if (wasDefault) {
2256                mDefaultInetConditionPublished = 0;
2257            }
2258            notifyIfacesChangedForNetworkStats();
2259            // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2260            // by other networks that are already connected. Perhaps that can be done by
2261            // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2262            // of rematchAllNetworksAndRequests
2263            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2264            mKeepaliveTracker.handleStopAllKeepalives(nai,
2265                    ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2266            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2267            mNetworkAgentInfos.remove(msg.replyTo);
2268            updateClat(null, nai.linkProperties, nai);
2269            synchronized (mNetworkForNetId) {
2270                // Remove the NetworkAgent, but don't mark the netId as
2271                // available until we've told netd to delete it below.
2272                mNetworkForNetId.remove(nai.network.netId);
2273            }
2274            // Remove all previously satisfied requests.
2275            for (int i = 0; i < nai.networkRequests.size(); i++) {
2276                NetworkRequest request = nai.networkRequests.valueAt(i);
2277                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2278                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2279                    mNetworkForRequestId.remove(request.requestId);
2280                    sendUpdatedScoreToFactories(request, 0);
2281                }
2282            }
2283            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2284                removeDataActivityTracking(nai);
2285                notifyLockdownVpn(nai);
2286                requestNetworkTransitionWakelock(nai.name());
2287            }
2288            mLegacyTypeTracker.remove(nai, wasDefault);
2289            rematchAllNetworksAndRequests(null, 0);
2290            if (wasDefault && getDefaultNetwork() == null) {
2291                // Log that we lost the default network and there is no replacement.
2292                logDefaultNetworkEvent(null, nai);
2293            }
2294            if (nai.created) {
2295                // Tell netd to clean up the configuration for this network
2296                // (routing rules, DNS, etc).
2297                // This may be slow as it requires a lot of netd shelling out to ip and
2298                // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2299                // after we've rematched networks with requests which should make a potential
2300                // fallback network the default or requested a new network from the
2301                // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2302                // long time.
2303                try {
2304                    mNetd.removeNetwork(nai.network.netId);
2305                } catch (Exception e) {
2306                    loge("Exception removing network: " + e);
2307                }
2308            }
2309            synchronized (mNetworkForNetId) {
2310                mNetIdInUse.delete(nai.network.netId);
2311            }
2312        } else {
2313            NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2314            if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
2315        }
2316    }
2317
2318    // If this method proves to be too slow then we can maintain a separate
2319    // pendingIntent => NetworkRequestInfo map.
2320    // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2321    private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2322        Intent intent = pendingIntent.getIntent();
2323        for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2324            PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2325            if (existingPendingIntent != null &&
2326                    existingPendingIntent.getIntent().filterEquals(intent)) {
2327                return entry.getValue();
2328            }
2329        }
2330        return null;
2331    }
2332
2333    private void handleRegisterNetworkRequestWithIntent(Message msg) {
2334        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2335
2336        NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2337        if (existingRequest != null) { // remove the existing request.
2338            if (DBG) log("Replacing " + existingRequest.request + " with "
2339                    + nri.request + " because their intents matched.");
2340            handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2341        }
2342        handleRegisterNetworkRequest(nri);
2343    }
2344
2345    private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
2346        mNetworkRequests.put(nri.request, nri);
2347        mNetworkRequestInfoLogs.log("REGISTER " + nri);
2348        if (!nri.isRequest()) {
2349            for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2350                if (nri.request.networkCapabilities.hasSignalStrength() &&
2351                        network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2352                    updateSignalStrengthThresholds(network, "REGISTER", nri.request);
2353                }
2354            }
2355        }
2356        rematchAllNetworksAndRequests(null, 0);
2357        if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
2358            sendUpdatedScoreToFactories(nri.request, 0);
2359        }
2360    }
2361
2362    private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2363            int callingUid) {
2364        NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2365        if (nri != null) {
2366            handleReleaseNetworkRequest(nri.request, callingUid);
2367        }
2368    }
2369
2370    // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2371    // This is whether it is satisfying any NetworkRequests or were it to become validated,
2372    // would it have a chance of satisfying any NetworkRequests.
2373    private boolean unneeded(NetworkAgentInfo nai) {
2374        if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
2375        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2376            // If this Network is already the highest scoring Network for a request, or if
2377            // there is hope for it to become one if it validated, then it is needed.
2378            if (nri.isRequest() && nai.satisfies(nri.request) &&
2379                    (nai.networkRequests.get(nri.request.requestId) != null ||
2380                    // Note that this catches two important cases:
2381                    // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2382                    //    is currently satisfying the request.  This is desirable when
2383                    //    cellular ends up validating but WiFi does not.
2384                    // 2. Unvalidated WiFi will not be reaped when validated cellular
2385                    //    is currently satisfying the request.  This is desirable when
2386                    //    WiFi ends up validating and out scoring cellular.
2387                    mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2388                            nai.getCurrentScoreAsValidated())) {
2389                return false;
2390            }
2391        }
2392        return true;
2393    }
2394
2395    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2396        NetworkRequestInfo nri = mNetworkRequests.get(request);
2397        if (nri != null) {
2398            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
2399                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2400                return;
2401            }
2402            if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
2403            nri.unlinkDeathRecipient();
2404            mNetworkRequests.remove(request);
2405            synchronized (mUidToNetworkRequestCount) {
2406                int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2407                if (requests < 1) {
2408                    Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2409                            nri.mUid);
2410                } else if (requests == 1) {
2411                    mUidToNetworkRequestCount.removeAt(
2412                            mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2413                } else {
2414                    mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2415                }
2416            }
2417            mNetworkRequestInfoLogs.log("RELEASE " + nri);
2418            if (nri.isRequest()) {
2419                // Find all networks that are satisfying this request and remove the request
2420                // from their request lists.
2421                // TODO - it's my understanding that for a request there is only a single
2422                // network satisfying it, so this loop is wasteful
2423                boolean wasKept = false;
2424                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2425                    if (nai.networkRequests.get(nri.request.requestId) != null) {
2426                        nai.networkRequests.remove(nri.request.requestId);
2427                        if (VDBG) {
2428                            log(" Removing from current network " + nai.name() +
2429                                    ", leaving " + nai.networkRequests.size() +
2430                                    " requests.");
2431                        }
2432                        if (unneeded(nai)) {
2433                            if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2434                            teardownUnneededNetwork(nai);
2435                        } else {
2436                            // suspect there should only be one pass through here
2437                            // but if any were kept do the check below
2438                            wasKept |= true;
2439                        }
2440                    }
2441                }
2442
2443                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2444                if (nai != null) {
2445                    mNetworkForRequestId.remove(nri.request.requestId);
2446                }
2447                // Maintain the illusion.  When this request arrived, we might have pretended
2448                // that a network connected to serve it, even though the network was already
2449                // connected.  Now that this request has gone away, we might have to pretend
2450                // that the network disconnected.  LegacyTypeTracker will generate that
2451                // phantom disconnect for this type.
2452                if (nri.request.legacyType != TYPE_NONE && nai != null) {
2453                    boolean doRemove = true;
2454                    if (wasKept) {
2455                        // check if any of the remaining requests for this network are for the
2456                        // same legacy type - if so, don't remove the nai
2457                        for (int i = 0; i < nai.networkRequests.size(); i++) {
2458                            NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2459                            if (otherRequest.legacyType == nri.request.legacyType &&
2460                                    isRequest(otherRequest)) {
2461                                if (DBG) log(" still have other legacy request - leaving");
2462                                doRemove = false;
2463                            }
2464                        }
2465                    }
2466
2467                    if (doRemove) {
2468                        mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
2469                    }
2470                }
2471
2472                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2473                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2474                            nri.request);
2475                }
2476            } else {
2477                // listens don't have a singular affectedNetwork.  Check all networks to see
2478                // if this listen request applies and remove it.
2479                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2480                    nai.networkRequests.remove(nri.request.requestId);
2481                    if (nri.request.networkCapabilities.hasSignalStrength() &&
2482                            nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2483                        updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2484                    }
2485                }
2486            }
2487            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2488        }
2489    }
2490
2491    public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2492        enforceConnectivityInternalPermission();
2493        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2494                accept ? 1 : 0, always ? 1: 0, network));
2495    }
2496
2497    private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2498        if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2499                " accept=" + accept + " always=" + always);
2500
2501        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2502        if (nai == null) {
2503            // Nothing to do.
2504            return;
2505        }
2506
2507        if (nai.everValidated) {
2508            // The network validated while the dialog box was up. Take no action.
2509            return;
2510        }
2511
2512        if (!nai.networkMisc.explicitlySelected) {
2513            Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2514        }
2515
2516        if (accept != nai.networkMisc.acceptUnvalidated) {
2517            int oldScore = nai.getCurrentScore();
2518            nai.networkMisc.acceptUnvalidated = accept;
2519            rematchAllNetworksAndRequests(nai, oldScore);
2520            sendUpdatedScoreToFactories(nai);
2521        }
2522
2523        if (always) {
2524            nai.asyncChannel.sendMessage(
2525                    NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2526        }
2527
2528        if (!accept) {
2529            // Tell the NetworkAgent to not automatically reconnect to the network.
2530            nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2531            // Teardown the nework.
2532            teardownUnneededNetwork(nai);
2533        }
2534
2535    }
2536
2537    private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2538        if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
2539        mHandler.sendMessageDelayed(
2540                mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2541                PROMPT_UNVALIDATED_DELAY_MS);
2542    }
2543
2544    private void handlePromptUnvalidated(Network network) {
2545        if (VDBG) log("handlePromptUnvalidated " + network);
2546        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2547
2548        // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2549        // we haven't already been told to switch to it regardless of whether it validated or not.
2550        // Also don't prompt on captive portals because we're already prompting the user to sign in.
2551        if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
2552                !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2553            return;
2554        }
2555
2556        Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2557        intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
2558        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2559        intent.setClassName("com.android.settings",
2560                "com.android.settings.wifi.WifiNoInternetDialog");
2561
2562        PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2563                mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2564        setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
2565                nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
2566    }
2567
2568    private class InternalHandler extends Handler {
2569        public InternalHandler(Looper looper) {
2570            super(looper);
2571        }
2572
2573        @Override
2574        public void handleMessage(Message msg) {
2575            switch (msg.what) {
2576                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2577                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2578                    String causedBy = null;
2579                    synchronized (ConnectivityService.this) {
2580                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2581                                mNetTransitionWakeLock.isHeld()) {
2582                            mNetTransitionWakeLock.release();
2583                            causedBy = mNetTransitionWakeLockCausedBy;
2584                        } else {
2585                            break;
2586                        }
2587                    }
2588                    if (VDBG) {
2589                        if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2590                            log("Failed to find a new network - expiring NetTransition Wakelock");
2591                        } else {
2592                            log("NetTransition Wakelock (" +
2593                                    (causedBy == null ? "unknown" : causedBy) +
2594                                    " cleared because we found a replacement network");
2595                        }
2596                    }
2597                    break;
2598                }
2599                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2600                    handleDeprecatedGlobalHttpProxy();
2601                    break;
2602                }
2603                case EVENT_PROXY_HAS_CHANGED: {
2604                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2605                    break;
2606                }
2607                case EVENT_REGISTER_NETWORK_FACTORY: {
2608                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2609                    break;
2610                }
2611                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2612                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2613                    break;
2614                }
2615                case EVENT_REGISTER_NETWORK_AGENT: {
2616                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2617                    break;
2618                }
2619                case EVENT_REGISTER_NETWORK_REQUEST:
2620                case EVENT_REGISTER_NETWORK_LISTENER: {
2621                    handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
2622                    break;
2623                }
2624                case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2625                case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
2626                    handleRegisterNetworkRequestWithIntent(msg);
2627                    break;
2628                }
2629                case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2630                    handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2631                    break;
2632                }
2633                case EVENT_RELEASE_NETWORK_REQUEST: {
2634                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2635                    break;
2636                }
2637                case EVENT_SET_ACCEPT_UNVALIDATED: {
2638                    handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2639                    break;
2640                }
2641                case EVENT_PROMPT_UNVALIDATED: {
2642                    handlePromptUnvalidated((Network) msg.obj);
2643                    break;
2644                }
2645                case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2646                    handleMobileDataAlwaysOn();
2647                    break;
2648                }
2649                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2650                case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2651                    mKeepaliveTracker.handleStartKeepalive(msg);
2652                    break;
2653                }
2654                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2655                case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2656                    NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2657                    int slot = msg.arg1;
2658                    int reason = msg.arg2;
2659                    mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2660                    break;
2661                }
2662                case EVENT_SYSTEM_READY: {
2663                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2664                        nai.networkMonitor.systemReady = true;
2665                    }
2666                    break;
2667                }
2668            }
2669        }
2670    }
2671
2672    // javadoc from interface
2673    public int tether(String iface) {
2674        ConnectivityManager.enforceTetherChangePermission(mContext);
2675        if (isTetheringSupported()) {
2676            final int status = mTethering.tether(iface);
2677            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2678                try {
2679                    mPolicyManager.onTetheringChanged(iface, true);
2680                } catch (RemoteException e) {
2681                }
2682            }
2683            return status;
2684        } else {
2685            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2686        }
2687    }
2688
2689    // javadoc from interface
2690    public int untether(String iface) {
2691        ConnectivityManager.enforceTetherChangePermission(mContext);
2692
2693        if (isTetheringSupported()) {
2694            final int status = mTethering.untether(iface);
2695            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2696                try {
2697                    mPolicyManager.onTetheringChanged(iface, false);
2698                } catch (RemoteException e) {
2699                }
2700            }
2701            return status;
2702        } else {
2703            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2704        }
2705    }
2706
2707    // javadoc from interface
2708    public int getLastTetherError(String iface) {
2709        enforceTetherAccessPermission();
2710
2711        if (isTetheringSupported()) {
2712            return mTethering.getLastTetherError(iface);
2713        } else {
2714            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2715        }
2716    }
2717
2718    // TODO - proper iface API for selection by property, inspection, etc
2719    public String[] getTetherableUsbRegexs() {
2720        enforceTetherAccessPermission();
2721        if (isTetheringSupported()) {
2722            return mTethering.getTetherableUsbRegexs();
2723        } else {
2724            return new String[0];
2725        }
2726    }
2727
2728    public String[] getTetherableWifiRegexs() {
2729        enforceTetherAccessPermission();
2730        if (isTetheringSupported()) {
2731            return mTethering.getTetherableWifiRegexs();
2732        } else {
2733            return new String[0];
2734        }
2735    }
2736
2737    public String[] getTetherableBluetoothRegexs() {
2738        enforceTetherAccessPermission();
2739        if (isTetheringSupported()) {
2740            return mTethering.getTetherableBluetoothRegexs();
2741        } else {
2742            return new String[0];
2743        }
2744    }
2745
2746    public int setUsbTethering(boolean enable) {
2747        ConnectivityManager.enforceTetherChangePermission(mContext);
2748        if (isTetheringSupported()) {
2749            return mTethering.setUsbTethering(enable);
2750        } else {
2751            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2752        }
2753    }
2754
2755    // TODO - move iface listing, queries, etc to new module
2756    // javadoc from interface
2757    public String[] getTetherableIfaces() {
2758        enforceTetherAccessPermission();
2759        return mTethering.getTetherableIfaces();
2760    }
2761
2762    public String[] getTetheredIfaces() {
2763        enforceTetherAccessPermission();
2764        return mTethering.getTetheredIfaces();
2765    }
2766
2767    public String[] getTetheringErroredIfaces() {
2768        enforceTetherAccessPermission();
2769        return mTethering.getErroredIfaces();
2770    }
2771
2772    public String[] getTetheredDhcpRanges() {
2773        enforceConnectivityInternalPermission();
2774        return mTethering.getTetheredDhcpRanges();
2775    }
2776
2777    // if ro.tether.denied = true we default to no tethering
2778    // gservices could set the secure setting to 1 though to enable it on a build where it
2779    // had previously been turned off.
2780    @Override
2781    public boolean isTetheringSupported() {
2782        enforceTetherAccessPermission();
2783        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2784        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2785                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2786                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2787        return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2788                ((mTethering.getTetherableUsbRegexs().length != 0 ||
2789                mTethering.getTetherableWifiRegexs().length != 0 ||
2790                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2791                mTethering.getUpstreamIfaceTypes().length != 0);
2792    }
2793
2794    @Override
2795    public void startTethering(int type, ResultReceiver receiver,
2796            boolean showProvisioningUi) {
2797        ConnectivityManager.enforceTetherChangePermission(mContext);
2798        if (!isTetheringSupported()) {
2799            receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2800            return;
2801        }
2802        mTethering.startTethering(type, receiver, showProvisioningUi);
2803    }
2804
2805    @Override
2806    public void stopTethering(int type) {
2807        ConnectivityManager.enforceTetherChangePermission(mContext);
2808        mTethering.stopTethering(type);
2809    }
2810
2811    // Called when we lose the default network and have no replacement yet.
2812    // This will automatically be cleared after X seconds or a new default network
2813    // becomes CONNECTED, whichever happens first.  The timer is started by the
2814    // first caller and not restarted by subsequent callers.
2815    private void requestNetworkTransitionWakelock(String forWhom) {
2816        int serialNum = 0;
2817        synchronized (this) {
2818            if (mNetTransitionWakeLock.isHeld()) return;
2819            serialNum = ++mNetTransitionWakeLockSerialNumber;
2820            mNetTransitionWakeLock.acquire();
2821            mNetTransitionWakeLockCausedBy = forWhom;
2822        }
2823        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2824                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2825                mNetTransitionWakeLockTimeout);
2826        return;
2827    }
2828
2829    // 100 percent is full good, 0 is full bad.
2830    public void reportInetCondition(int networkType, int percentage) {
2831        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2832        if (nai == null) return;
2833        reportNetworkConnectivity(nai.network, percentage > 50);
2834    }
2835
2836    public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2837        enforceAccessPermission();
2838        enforceInternetPermission();
2839
2840        NetworkAgentInfo nai;
2841        if (network == null) {
2842            nai = getDefaultNetwork();
2843        } else {
2844            nai = getNetworkAgentInfoForNetwork(network);
2845        }
2846        if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2847            nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2848            return;
2849        }
2850        // Revalidate if the app report does not match our current validated state.
2851        if (hasConnectivity == nai.lastValidated) return;
2852        final int uid = Binder.getCallingUid();
2853        if (DBG) {
2854            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2855                    ") by " + uid);
2856        }
2857        synchronized (nai) {
2858            // Validating a network that has not yet connected could result in a call to
2859            // rematchNetworkAndRequests() which is not meant to work on such networks.
2860            if (!nai.everConnected) return;
2861
2862            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
2863
2864            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2865        }
2866    }
2867
2868    private ProxyInfo getDefaultProxy() {
2869        // this information is already available as a world read/writable jvm property
2870        // so this API change wouldn't have a benifit.  It also breaks the passing
2871        // of proxy info to all the JVMs.
2872        // enforceAccessPermission();
2873        synchronized (mProxyLock) {
2874            ProxyInfo ret = mGlobalProxy;
2875            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2876            return ret;
2877        }
2878    }
2879
2880    public ProxyInfo getProxyForNetwork(Network network) {
2881        if (network == null) return getDefaultProxy();
2882        final ProxyInfo globalProxy = getGlobalProxy();
2883        if (globalProxy != null) return globalProxy;
2884        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2885        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2886        // caller may not have.
2887        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2888        if (nai == null) return null;
2889        synchronized (nai) {
2890            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2891            if (proxyInfo == null) return null;
2892            return new ProxyInfo(proxyInfo);
2893        }
2894    }
2895
2896    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2897    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2898    // proxy is null then there is no proxy in place).
2899    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2900        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2901                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2902            proxy = null;
2903        }
2904        return proxy;
2905    }
2906
2907    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2908    // better for determining if a new proxy broadcast is necessary:
2909    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2910    //    avoid unnecessary broadcasts.
2911    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2912    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2913    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2914    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2915    //    all set.
2916    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2917        a = canonicalizeProxyInfo(a);
2918        b = canonicalizeProxyInfo(b);
2919        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2920        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2921        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2922    }
2923
2924    public void setGlobalProxy(ProxyInfo proxyProperties) {
2925        enforceConnectivityInternalPermission();
2926
2927        synchronized (mProxyLock) {
2928            if (proxyProperties == mGlobalProxy) return;
2929            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2930            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2931
2932            String host = "";
2933            int port = 0;
2934            String exclList = "";
2935            String pacFileUrl = "";
2936            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2937                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2938                if (!proxyProperties.isValid()) {
2939                    if (DBG)
2940                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2941                    return;
2942                }
2943                mGlobalProxy = new ProxyInfo(proxyProperties);
2944                host = mGlobalProxy.getHost();
2945                port = mGlobalProxy.getPort();
2946                exclList = mGlobalProxy.getExclusionListAsString();
2947                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2948                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2949                }
2950            } else {
2951                mGlobalProxy = null;
2952            }
2953            ContentResolver res = mContext.getContentResolver();
2954            final long token = Binder.clearCallingIdentity();
2955            try {
2956                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2957                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2958                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2959                        exclList);
2960                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2961            } finally {
2962                Binder.restoreCallingIdentity(token);
2963            }
2964
2965            if (mGlobalProxy == null) {
2966                proxyProperties = mDefaultProxy;
2967            }
2968            sendProxyBroadcast(proxyProperties);
2969        }
2970    }
2971
2972    private void loadGlobalProxy() {
2973        ContentResolver res = mContext.getContentResolver();
2974        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2975        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2976        String exclList = Settings.Global.getString(res,
2977                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2978        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2979        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2980            ProxyInfo proxyProperties;
2981            if (!TextUtils.isEmpty(pacFileUrl)) {
2982                proxyProperties = new ProxyInfo(pacFileUrl);
2983            } else {
2984                proxyProperties = new ProxyInfo(host, port, exclList);
2985            }
2986            if (!proxyProperties.isValid()) {
2987                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2988                return;
2989            }
2990
2991            synchronized (mProxyLock) {
2992                mGlobalProxy = proxyProperties;
2993            }
2994        }
2995    }
2996
2997    public ProxyInfo getGlobalProxy() {
2998        // this information is already available as a world read/writable jvm property
2999        // so this API change wouldn't have a benifit.  It also breaks the passing
3000        // of proxy info to all the JVMs.
3001        // enforceAccessPermission();
3002        synchronized (mProxyLock) {
3003            return mGlobalProxy;
3004        }
3005    }
3006
3007    private void handleApplyDefaultProxy(ProxyInfo proxy) {
3008        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3009                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
3010            proxy = null;
3011        }
3012        synchronized (mProxyLock) {
3013            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3014            if (mDefaultProxy == proxy) return; // catches repeated nulls
3015            if (proxy != null &&  !proxy.isValid()) {
3016                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3017                return;
3018            }
3019
3020            // This call could be coming from the PacManager, containing the port of the local
3021            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
3022            // global (to get the correct local port), and send a broadcast.
3023            // TODO: Switch PacManager to have its own message to send back rather than
3024            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
3025            if ((mGlobalProxy != null) && (proxy != null)
3026                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
3027                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3028                mGlobalProxy = proxy;
3029                sendProxyBroadcast(mGlobalProxy);
3030                return;
3031            }
3032            mDefaultProxy = proxy;
3033
3034            if (mGlobalProxy != null) return;
3035            if (!mDefaultProxyDisabled) {
3036                sendProxyBroadcast(proxy);
3037            }
3038        }
3039    }
3040
3041    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3042    // This method gets called when any network changes proxy, but the broadcast only ever contains
3043    // the default proxy (even if it hasn't changed).
3044    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3045    // world where an app might be bound to a non-default network.
3046    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3047        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3048        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3049
3050        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3051            sendProxyBroadcast(getDefaultProxy());
3052        }
3053    }
3054
3055    private void handleDeprecatedGlobalHttpProxy() {
3056        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3057                Settings.Global.HTTP_PROXY);
3058        if (!TextUtils.isEmpty(proxy)) {
3059            String data[] = proxy.split(":");
3060            if (data.length == 0) {
3061                return;
3062            }
3063
3064            String proxyHost =  data[0];
3065            int proxyPort = 8080;
3066            if (data.length > 1) {
3067                try {
3068                    proxyPort = Integer.parseInt(data[1]);
3069                } catch (NumberFormatException e) {
3070                    return;
3071                }
3072            }
3073            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
3074            setGlobalProxy(p);
3075        }
3076    }
3077
3078    private void sendProxyBroadcast(ProxyInfo proxy) {
3079        if (proxy == null) proxy = new ProxyInfo("", 0, "");
3080        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3081        if (DBG) log("sending Proxy Broadcast for " + proxy);
3082        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3083        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3084            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3085        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3086        final long ident = Binder.clearCallingIdentity();
3087        try {
3088            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3089        } finally {
3090            Binder.restoreCallingIdentity(ident);
3091        }
3092    }
3093
3094    private static class SettingsObserver extends ContentObserver {
3095        final private HashMap<Uri, Integer> mUriEventMap;
3096        final private Context mContext;
3097        final private Handler mHandler;
3098
3099        SettingsObserver(Context context, Handler handler) {
3100            super(null);
3101            mUriEventMap = new HashMap<Uri, Integer>();
3102            mContext = context;
3103            mHandler = handler;
3104        }
3105
3106        void observe(Uri uri, int what) {
3107            mUriEventMap.put(uri, what);
3108            final ContentResolver resolver = mContext.getContentResolver();
3109            resolver.registerContentObserver(uri, false, this);
3110        }
3111
3112        @Override
3113        public void onChange(boolean selfChange) {
3114            Slog.wtf(TAG, "Should never be reached.");
3115        }
3116
3117        @Override
3118        public void onChange(boolean selfChange, Uri uri) {
3119            final Integer what = mUriEventMap.get(uri);
3120            if (what != null) {
3121                mHandler.obtainMessage(what.intValue()).sendToTarget();
3122            } else {
3123                loge("No matching event to send for URI=" + uri);
3124            }
3125        }
3126    }
3127
3128    private static void log(String s) {
3129        Slog.d(TAG, s);
3130    }
3131
3132    private static void loge(String s) {
3133        Slog.e(TAG, s);
3134    }
3135
3136    private static <T> T checkNotNull(T value, String message) {
3137        if (value == null) {
3138            throw new NullPointerException(message);
3139        }
3140        return value;
3141    }
3142
3143    /**
3144     * Prepare for a VPN application.
3145     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3146     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3147     *
3148     * @param oldPackage Package name of the application which currently controls VPN, which will
3149     *                   be replaced. If there is no such application, this should should either be
3150     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
3151     * @param newPackage Package name of the application which should gain control of VPN, or
3152     *                   {@code null} to disable.
3153     * @param userId User for whom to prepare the new VPN.
3154     *
3155     * @hide
3156     */
3157    @Override
3158    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3159            int userId) {
3160        enforceCrossUserPermission(userId);
3161        throwIfLockdownEnabled();
3162
3163        synchronized(mVpns) {
3164            Vpn vpn = mVpns.get(userId);
3165            if (vpn != null) {
3166                return vpn.prepare(oldPackage, newPackage);
3167            } else {
3168                return false;
3169            }
3170        }
3171    }
3172
3173    /**
3174     * Set whether the VPN package has the ability to launch VPNs without user intervention.
3175     * This method is used by system-privileged apps.
3176     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3177     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3178     *
3179     * @param packageName The package for which authorization state should change.
3180     * @param userId User for whom {@code packageName} is installed.
3181     * @param authorized {@code true} if this app should be able to start a VPN connection without
3182     *                   explicit user approval, {@code false} if not.
3183     *
3184     * @hide
3185     */
3186    @Override
3187    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3188        enforceCrossUserPermission(userId);
3189
3190        synchronized(mVpns) {
3191            Vpn vpn = mVpns.get(userId);
3192            if (vpn != null) {
3193                vpn.setPackageAuthorization(packageName, authorized);
3194            }
3195        }
3196    }
3197
3198    /**
3199     * Configure a TUN interface and return its file descriptor. Parameters
3200     * are encoded and opaque to this class. This method is used by VpnBuilder
3201     * and not available in ConnectivityManager. Permissions are checked in
3202     * Vpn class.
3203     * @hide
3204     */
3205    @Override
3206    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3207        throwIfLockdownEnabled();
3208        int user = UserHandle.getUserId(Binder.getCallingUid());
3209        synchronized(mVpns) {
3210            return mVpns.get(user).establish(config);
3211        }
3212    }
3213
3214    /**
3215     * Start legacy VPN, controlling native daemons as needed. Creates a
3216     * secondary thread to perform connection work, returning quickly.
3217     */
3218    @Override
3219    public void startLegacyVpn(VpnProfile profile) {
3220        throwIfLockdownEnabled();
3221        final LinkProperties egress = getActiveLinkProperties();
3222        if (egress == null) {
3223            throw new IllegalStateException("Missing active network connection");
3224        }
3225        int user = UserHandle.getUserId(Binder.getCallingUid());
3226        synchronized(mVpns) {
3227            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3228        }
3229    }
3230
3231    /**
3232     * Return the information of the ongoing legacy VPN. This method is used
3233     * by VpnSettings and not available in ConnectivityManager. Permissions
3234     * are checked in Vpn class.
3235     */
3236    @Override
3237    public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3238        enforceCrossUserPermission(userId);
3239        if (mLockdownEnabled) {
3240            return null;
3241        }
3242
3243        synchronized(mVpns) {
3244            return mVpns.get(userId).getLegacyVpnInfo();
3245        }
3246    }
3247
3248    /**
3249     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3250     * and not available in ConnectivityManager.
3251     */
3252    @Override
3253    public VpnInfo[] getAllVpnInfo() {
3254        enforceConnectivityInternalPermission();
3255        if (mLockdownEnabled) {
3256            return new VpnInfo[0];
3257        }
3258
3259        synchronized(mVpns) {
3260            List<VpnInfo> infoList = new ArrayList<>();
3261            for (int i = 0; i < mVpns.size(); i++) {
3262                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3263                if (info != null) {
3264                    infoList.add(info);
3265                }
3266            }
3267            return infoList.toArray(new VpnInfo[infoList.size()]);
3268        }
3269    }
3270
3271    /**
3272     * @return VPN information for accounting, or null if we can't retrieve all required
3273     *         information, e.g primary underlying iface.
3274     */
3275    @Nullable
3276    private VpnInfo createVpnInfo(Vpn vpn) {
3277        VpnInfo info = vpn.getVpnInfo();
3278        if (info == null) {
3279            return null;
3280        }
3281        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3282        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3283        // the underlyingNetworks list.
3284        if (underlyingNetworks == null) {
3285            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3286            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3287                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3288            }
3289        } else if (underlyingNetworks.length > 0) {
3290            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3291            if (linkProperties != null) {
3292                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3293            }
3294        }
3295        return info.primaryUnderlyingIface == null ? null : info;
3296    }
3297
3298    /**
3299     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3300     * VpnDialogs and not available in ConnectivityManager.
3301     * Permissions are checked in Vpn class.
3302     * @hide
3303     */
3304    @Override
3305    public VpnConfig getVpnConfig(int userId) {
3306        enforceCrossUserPermission(userId);
3307        synchronized(mVpns) {
3308            Vpn vpn = mVpns.get(userId);
3309            if (vpn != null) {
3310                return vpn.getVpnConfig();
3311            } else {
3312                return null;
3313            }
3314        }
3315    }
3316
3317    @Override
3318    public boolean updateLockdownVpn() {
3319        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3320            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3321            return false;
3322        }
3323
3324        // Tear down existing lockdown if profile was removed
3325        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3326        if (mLockdownEnabled) {
3327            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3328            final VpnProfile profile = VpnProfile.decode(
3329                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3330            if (profile == null) {
3331                Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3332                setLockdownTracker(null);
3333                return true;
3334            }
3335            int user = UserHandle.getUserId(Binder.getCallingUid());
3336            synchronized(mVpns) {
3337                Vpn vpn = mVpns.get(user);
3338                if (vpn == null) {
3339                    Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3340                    return false;
3341                }
3342                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
3343            }
3344        } else {
3345            setLockdownTracker(null);
3346        }
3347
3348        return true;
3349    }
3350
3351    /**
3352     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3353     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3354     */
3355    private void setLockdownTracker(LockdownVpnTracker tracker) {
3356        // Shutdown any existing tracker
3357        final LockdownVpnTracker existing = mLockdownTracker;
3358        mLockdownTracker = null;
3359        if (existing != null) {
3360            existing.shutdown();
3361        }
3362
3363        try {
3364            if (tracker != null) {
3365                mNetd.setFirewallEnabled(true);
3366                mNetd.setFirewallInterfaceRule("lo", true);
3367                mLockdownTracker = tracker;
3368                mLockdownTracker.init();
3369            } else {
3370                mNetd.setFirewallEnabled(false);
3371            }
3372        } catch (RemoteException e) {
3373            // ignored; NMS lives inside system_server
3374        }
3375    }
3376
3377    private void throwIfLockdownEnabled() {
3378        if (mLockdownEnabled) {
3379            throw new IllegalStateException("Unavailable in lockdown mode");
3380        }
3381    }
3382
3383    /**
3384     * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3385     * some setup and then call {@code establish()} to connect.
3386     *
3387     * @return {@code true} if the service was started, the service was already connected, or there
3388     *         was no always-on VPN to start. {@code false} otherwise.
3389     */
3390    private boolean startAlwaysOnVpn(int userId) {
3391        final String alwaysOnPackage;
3392        synchronized (mVpns) {
3393            Vpn vpn = mVpns.get(userId);
3394            if (vpn == null) {
3395                // Shouldn't happen as all codepaths that point here should have checked the Vpn
3396                // exists already.
3397                Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3398                return false;
3399            }
3400            alwaysOnPackage = vpn.getAlwaysOnPackage();
3401            // Skip if there is no service to start.
3402            if (alwaysOnPackage == null) {
3403                return true;
3404            }
3405            // Skip if the service is already established. This isn't bulletproof: it's not bound
3406            // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
3407            // which may restart the connection.
3408            if (vpn.getNetworkInfo().isConnected()) {
3409                return true;
3410            }
3411        }
3412
3413        // Start the VPN service declared in the app's manifest.
3414        Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3415        serviceIntent.setPackage(alwaysOnPackage);
3416        try {
3417            return mContext.startServiceAsUser(serviceIntent, UserHandle.of(userId)) != null;
3418        } catch (RuntimeException e) {
3419            Slog.w(TAG, "VpnService " + serviceIntent + " failed to start", e);
3420            return false;
3421        }
3422    }
3423
3424    @Override
3425    public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
3426        enforceConnectivityInternalPermission();
3427        enforceCrossUserPermission(userId);
3428
3429        // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3430        if (LockdownVpnTracker.isEnabled()) {
3431            return false;
3432        }
3433
3434        synchronized (mVpns) {
3435            Vpn vpn = mVpns.get(userId);
3436            if (vpn == null) {
3437                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3438                return false;
3439            }
3440            // If the current VPN package is the same as the new one, this is a no-op
3441            if (TextUtils.equals(packageName, vpn.getAlwaysOnPackage())) {
3442                return true;
3443            }
3444            if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
3445                return false;
3446            }
3447            if (!startAlwaysOnVpn(userId)) {
3448                vpn.setAlwaysOnPackage(null, false);
3449                return false;
3450            }
3451
3452            // Save the configuration
3453            final long token = Binder.clearCallingIdentity();
3454            try {
3455                final ContentResolver cr = mContext.getContentResolver();
3456                Settings.Secure.putStringForUser(cr, Settings.Secure.ALWAYS_ON_VPN_APP,
3457                        packageName, userId);
3458                Settings.Secure.putIntForUser(cr, Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
3459                        (lockdown ? 1 : 0), userId);
3460            } finally {
3461                Binder.restoreCallingIdentity(token);
3462            }
3463        }
3464        return true;
3465    }
3466
3467    @Override
3468    public String getAlwaysOnVpnPackage(int userId) {
3469        enforceConnectivityInternalPermission();
3470        enforceCrossUserPermission(userId);
3471
3472        synchronized (mVpns) {
3473            Vpn vpn = mVpns.get(userId);
3474            if (vpn == null) {
3475                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3476                return null;
3477            }
3478            return vpn.getAlwaysOnPackage();
3479        }
3480    }
3481
3482    @Override
3483    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3484        // TODO: Remove?  Any reason to trigger a provisioning check?
3485        return -1;
3486    }
3487
3488    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3489    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3490
3491    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3492        Intent intent = new Intent(action);
3493        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3494        // Concatenate the range of types onto the range of NetIDs.
3495        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3496        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3497                networkType, null, pendingIntent, false);
3498    }
3499
3500    /**
3501     * Show or hide network provisioning notifications.
3502     *
3503     * We use notifications for two purposes: to notify that a network requires sign in
3504     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3505     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3506     * particular network we can display the notification type that was most recently requested.
3507     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3508     * might first display NO_INTERNET, and then when the captive portal check completes, display
3509     * SIGN_IN.
3510     *
3511     * @param id an identifier that uniquely identifies this notification.  This must match
3512     *         between show and hide calls.  We use the NetID value but for legacy callers
3513     *         we concatenate the range of types with the range of NetIDs.
3514     */
3515    private void setProvNotificationVisibleIntent(boolean visible, int id,
3516            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3517            boolean highPriority) {
3518        if (VDBG || (DBG && visible)) {
3519            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3520                    + " networkType=" + getNetworkTypeName(networkType)
3521                    + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
3522        }
3523
3524        Resources r = Resources.getSystem();
3525        NotificationManager notificationManager = (NotificationManager) mContext
3526            .getSystemService(Context.NOTIFICATION_SERVICE);
3527
3528        if (visible) {
3529            CharSequence title;
3530            CharSequence details;
3531            int icon;
3532            if (notifyType == NotificationType.NO_INTERNET &&
3533                    networkType == ConnectivityManager.TYPE_WIFI) {
3534                title = r.getString(R.string.wifi_no_internet, 0);
3535                details = r.getString(R.string.wifi_no_internet_detailed);
3536                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3537            } else if (notifyType == NotificationType.SIGN_IN) {
3538                switch (networkType) {
3539                    case ConnectivityManager.TYPE_WIFI:
3540                        title = r.getString(R.string.wifi_available_sign_in, 0);
3541                        details = r.getString(R.string.network_available_sign_in_detailed,
3542                                extraInfo);
3543                        icon = R.drawable.stat_notify_wifi_in_range;
3544                        break;
3545                    case ConnectivityManager.TYPE_MOBILE:
3546                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3547                        title = r.getString(R.string.network_available_sign_in, 0);
3548                        // TODO: Change this to pull from NetworkInfo once a printable
3549                        // name has been added to it
3550                        details = mTelephonyManager.getNetworkOperatorName();
3551                        icon = R.drawable.stat_notify_rssi_in_range;
3552                        break;
3553                    default:
3554                        title = r.getString(R.string.network_available_sign_in, 0);
3555                        details = r.getString(R.string.network_available_sign_in_detailed,
3556                                extraInfo);
3557                        icon = R.drawable.stat_notify_rssi_in_range;
3558                        break;
3559                }
3560            } else {
3561                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3562                        + getNetworkTypeName(networkType));
3563                return;
3564            }
3565
3566            Notification notification = new Notification.Builder(mContext)
3567                    .setWhen(0)
3568                    .setSmallIcon(icon)
3569                    .setAutoCancel(true)
3570                    .setTicker(title)
3571                    .setColor(mContext.getColor(
3572                            com.android.internal.R.color.system_notification_accent_color))
3573                    .setContentTitle(title)
3574                    .setContentText(details)
3575                    .setContentIntent(intent)
3576                    .setLocalOnly(true)
3577                    .setPriority(highPriority ?
3578                            Notification.PRIORITY_HIGH :
3579                            Notification.PRIORITY_DEFAULT)
3580                    .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
3581                    .setOnlyAlertOnce(true)
3582                    .build();
3583
3584            try {
3585                notificationManager.notify(NOTIFICATION_ID, id, notification);
3586            } catch (NullPointerException npe) {
3587                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3588                npe.printStackTrace();
3589            }
3590        } else {
3591            try {
3592                notificationManager.cancel(NOTIFICATION_ID, id);
3593            } catch (NullPointerException npe) {
3594                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3595                npe.printStackTrace();
3596            }
3597        }
3598    }
3599
3600    /** Location to an updatable file listing carrier provisioning urls.
3601     *  An example:
3602     *
3603     * <?xml version="1.0" encoding="utf-8"?>
3604     *  <provisioningUrls>
3605     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3606     *  </provisioningUrls>
3607     */
3608    private static final String PROVISIONING_URL_PATH =
3609            "/data/misc/radio/provisioning_urls.xml";
3610    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3611
3612    /** XML tag for root element. */
3613    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3614    /** XML tag for individual url */
3615    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3616    /** XML attribute for mcc */
3617    private static final String ATTR_MCC = "mcc";
3618    /** XML attribute for mnc */
3619    private static final String ATTR_MNC = "mnc";
3620
3621    private String getProvisioningUrlBaseFromFile() {
3622        FileReader fileReader = null;
3623        XmlPullParser parser = null;
3624        Configuration config = mContext.getResources().getConfiguration();
3625
3626        try {
3627            fileReader = new FileReader(mProvisioningUrlFile);
3628            parser = Xml.newPullParser();
3629            parser.setInput(fileReader);
3630            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3631
3632            while (true) {
3633                XmlUtils.nextElement(parser);
3634
3635                String element = parser.getName();
3636                if (element == null) break;
3637
3638                if (element.equals(TAG_PROVISIONING_URL)) {
3639                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3640                    try {
3641                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3642                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3643                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3644                                parser.next();
3645                                if (parser.getEventType() == XmlPullParser.TEXT) {
3646                                    return parser.getText();
3647                                }
3648                            }
3649                        }
3650                    } catch (NumberFormatException e) {
3651                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3652                    }
3653                }
3654            }
3655            return null;
3656        } catch (FileNotFoundException e) {
3657            loge("Carrier Provisioning Urls file not found");
3658        } catch (XmlPullParserException e) {
3659            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3660        } catch (IOException e) {
3661            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3662        } finally {
3663            if (fileReader != null) {
3664                try {
3665                    fileReader.close();
3666                } catch (IOException e) {}
3667            }
3668        }
3669        return null;
3670    }
3671
3672    @Override
3673    public String getMobileProvisioningUrl() {
3674        enforceConnectivityInternalPermission();
3675        String url = getProvisioningUrlBaseFromFile();
3676        if (TextUtils.isEmpty(url)) {
3677            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3678            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3679        } else {
3680            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3681        }
3682        // populate the iccid, imei and phone number in the provisioning url.
3683        if (!TextUtils.isEmpty(url)) {
3684            String phoneNumber = mTelephonyManager.getLine1Number();
3685            if (TextUtils.isEmpty(phoneNumber)) {
3686                phoneNumber = "0000000000";
3687            }
3688            url = String.format(url,
3689                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3690                    mTelephonyManager.getDeviceId() /* IMEI */,
3691                    phoneNumber /* Phone numer */);
3692        }
3693
3694        return url;
3695    }
3696
3697    @Override
3698    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3699            String action) {
3700        enforceConnectivityInternalPermission();
3701        final long ident = Binder.clearCallingIdentity();
3702        try {
3703            setProvNotificationVisible(visible, networkType, action);
3704        } finally {
3705            Binder.restoreCallingIdentity(ident);
3706        }
3707    }
3708
3709    @Override
3710    public void setAirplaneMode(boolean enable) {
3711        enforceConnectivityInternalPermission();
3712        final long ident = Binder.clearCallingIdentity();
3713        try {
3714            final ContentResolver cr = mContext.getContentResolver();
3715            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3716            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3717            intent.putExtra("state", enable);
3718            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3719        } finally {
3720            Binder.restoreCallingIdentity(ident);
3721        }
3722    }
3723
3724    private void onUserStart(int userId) {
3725        synchronized(mVpns) {
3726            Vpn userVpn = mVpns.get(userId);
3727            if (userVpn != null) {
3728                loge("Starting user already has a VPN");
3729                return;
3730            }
3731            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3732            mVpns.put(userId, userVpn);
3733
3734            final ContentResolver cr = mContext.getContentResolver();
3735            String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3736                    Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3737            final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3738                    Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3739            if (alwaysOnPackage != null) {
3740                userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3741            }
3742        }
3743        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3744            updateLockdownVpn();
3745        }
3746    }
3747
3748    private void onUserStop(int userId) {
3749        synchronized(mVpns) {
3750            Vpn userVpn = mVpns.get(userId);
3751            if (userVpn == null) {
3752                loge("Stopped user has no VPN");
3753                return;
3754            }
3755            userVpn.onUserStopped();
3756            mVpns.delete(userId);
3757        }
3758    }
3759
3760    private void onUserAdded(int userId) {
3761        synchronized(mVpns) {
3762            final int vpnsSize = mVpns.size();
3763            for (int i = 0; i < vpnsSize; i++) {
3764                Vpn vpn = mVpns.valueAt(i);
3765                vpn.onUserAdded(userId);
3766            }
3767        }
3768    }
3769
3770    private void onUserRemoved(int userId) {
3771        synchronized(mVpns) {
3772            final int vpnsSize = mVpns.size();
3773            for (int i = 0; i < vpnsSize; i++) {
3774                Vpn vpn = mVpns.valueAt(i);
3775                vpn.onUserRemoved(userId);
3776            }
3777        }
3778    }
3779
3780    private void onUserUnlocked(int userId) {
3781        // User present may be sent because of an unlock, which might mean an unlocked keystore.
3782        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3783            updateLockdownVpn();
3784        } else {
3785            startAlwaysOnVpn(userId);
3786        }
3787    }
3788
3789    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3790        @Override
3791        public void onReceive(Context context, Intent intent) {
3792            final String action = intent.getAction();
3793            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3794            if (userId == UserHandle.USER_NULL) return;
3795
3796            if (Intent.ACTION_USER_STARTED.equals(action)) {
3797                onUserStart(userId);
3798            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3799                onUserStop(userId);
3800            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3801                onUserAdded(userId);
3802            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3803                onUserRemoved(userId);
3804            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3805                onUserUnlocked(userId);
3806            }
3807        }
3808    };
3809
3810    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3811            new HashMap<Messenger, NetworkFactoryInfo>();
3812    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3813            new HashMap<NetworkRequest, NetworkRequestInfo>();
3814
3815    private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3816    // Map from UID to number of NetworkRequests that UID has filed.
3817    @GuardedBy("mUidToNetworkRequestCount")
3818    private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3819
3820    private static class NetworkFactoryInfo {
3821        public final String name;
3822        public final Messenger messenger;
3823        public final AsyncChannel asyncChannel;
3824
3825        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3826            this.name = name;
3827            this.messenger = messenger;
3828            this.asyncChannel = asyncChannel;
3829        }
3830    }
3831
3832    /**
3833     * A NetworkRequest as registered by an application can be one of three
3834     * types:
3835     *
3836     *     - "listen", for which the framework will issue callbacks about any
3837     *       and all networks that match the specified NetworkCapabilities,
3838     *
3839     *     - "request", capable of causing a specific network to be created
3840     *       first (e.g. a telephony DUN request), the framework will issue
3841     *       callbacks about the single, highest scoring current network
3842     *       (if any) that matches the specified NetworkCapabilities, or
3843     *
3844     *     - "track the default network", a hybrid of the two designed such
3845     *       that the framework will issue callbacks for the single, highest
3846     *       scoring current network (if any) that matches the capabilities of
3847     *       the default Internet request (mDefaultRequest), but which cannot
3848     *       cause the framework to either create or retain the existence of
3849     *       any specific network.
3850     *
3851     */
3852    private static enum NetworkRequestType {
3853        LISTEN,
3854        TRACK_DEFAULT,
3855        REQUEST
3856    };
3857
3858    /**
3859     * Tracks info about the requester.
3860     * Also used to notice when the calling process dies so we can self-expire
3861     */
3862    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3863        final NetworkRequest request;
3864        final PendingIntent mPendingIntent;
3865        boolean mPendingIntentSent;
3866        private final IBinder mBinder;
3867        final int mPid;
3868        final int mUid;
3869        final Messenger messenger;
3870        private final NetworkRequestType mType;
3871
3872        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
3873            request = r;
3874            mPendingIntent = pi;
3875            messenger = null;
3876            mBinder = null;
3877            mPid = getCallingPid();
3878            mUid = getCallingUid();
3879            mType = type;
3880            enforceRequestCountLimit();
3881        }
3882
3883        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
3884            super();
3885            messenger = m;
3886            request = r;
3887            mBinder = binder;
3888            mPid = getCallingPid();
3889            mUid = getCallingUid();
3890            mType = type;
3891            mPendingIntent = null;
3892            enforceRequestCountLimit();
3893
3894            try {
3895                mBinder.linkToDeath(this, 0);
3896            } catch (RemoteException e) {
3897                binderDied();
3898            }
3899        }
3900
3901        private void enforceRequestCountLimit() {
3902            synchronized (mUidToNetworkRequestCount) {
3903                int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3904                if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3905                    throw new IllegalArgumentException("Too many NetworkRequests filed");
3906                }
3907                mUidToNetworkRequestCount.put(mUid, networkRequests);
3908            }
3909        }
3910
3911        private String typeString() {
3912            switch (mType) {
3913                case LISTEN: return "Listen";
3914                case REQUEST: return "Request";
3915                case TRACK_DEFAULT: return "Track default";
3916                default:
3917                    return "unknown type";
3918            }
3919        }
3920
3921        void unlinkDeathRecipient() {
3922            if (mBinder != null) {
3923                mBinder.unlinkToDeath(this, 0);
3924            }
3925        }
3926
3927        public void binderDied() {
3928            log("ConnectivityService NetworkRequestInfo binderDied(" +
3929                    request + ", " + mBinder + ")");
3930            releaseNetworkRequest(request);
3931        }
3932
3933        /**
3934         * Returns true iff. the contained NetworkRequest is one that:
3935         *
3936         *     - should be associated with at most one satisfying network
3937         *       at a time;
3938         *
3939         *     - should cause a network to be kept up if it is the only network
3940         *       which can satisfy the NetworkReqeust.
3941         *
3942         * For full detail of how isRequest() is used for pairing Networks with
3943         * NetworkRequests read rematchNetworkAndRequests().
3944         *
3945         * TODO: Rename to something more properly descriptive.
3946         */
3947        public boolean isRequest() {
3948            return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3949                   (mType == NetworkRequestType.REQUEST);
3950        }
3951
3952        public String toString() {
3953            return typeString() +
3954                    " from uid/pid:" + mUid + "/" + mPid +
3955                    " for " + request +
3956                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3957        }
3958    }
3959
3960    private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3961        final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3962        if (badCapability != null) {
3963            throw new IllegalArgumentException("Cannot request network with " + badCapability);
3964        }
3965    }
3966
3967    private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
3968        final SortedSet<Integer> thresholds = new TreeSet();
3969        synchronized (nai) {
3970            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3971                if (nri.request.networkCapabilities.hasSignalStrength() &&
3972                        nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3973                    thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3974                }
3975            }
3976        }
3977        return new ArrayList<Integer>(thresholds);
3978    }
3979
3980    private void updateSignalStrengthThresholds(
3981            NetworkAgentInfo nai, String reason, NetworkRequest request) {
3982        ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
3983        Bundle thresholds = new Bundle();
3984        thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3985
3986        if (VDBG || (DBG && !"CONNECT".equals(reason))) {
3987            String detail;
3988            if (request != null && request.networkCapabilities.hasSignalStrength()) {
3989                detail = reason + " " + request.networkCapabilities.getSignalStrength();
3990            } else {
3991                detail = reason;
3992            }
3993            log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3994                    detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3995        }
3996
3997        nai.asyncChannel.sendMessage(
3998                android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
3999                0, 0, thresholds);
4000    }
4001
4002    @Override
4003    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
4004            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
4005        final NetworkRequestType type = (networkCapabilities == null)
4006                ? NetworkRequestType.TRACK_DEFAULT
4007                : NetworkRequestType.REQUEST;
4008        // If the requested networkCapabilities is null, take them instead from
4009        // the default network request. This allows callers to keep track of
4010        // the system default network.
4011        if (type == NetworkRequestType.TRACK_DEFAULT) {
4012            networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4013            enforceAccessPermission();
4014        } else {
4015            networkCapabilities = new NetworkCapabilities(networkCapabilities);
4016            enforceNetworkRequestPermissions(networkCapabilities);
4017        }
4018        enforceMeteredApnPolicy(networkCapabilities);
4019        ensureRequestableCapabilities(networkCapabilities);
4020
4021        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
4022            throw new IllegalArgumentException("Bad timeout specified");
4023        }
4024
4025        if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4026                .equals(networkCapabilities.getNetworkSpecifier())) {
4027            throw new IllegalArgumentException("Invalid network specifier - must not be '"
4028                    + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4029        }
4030
4031        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4032                nextNetworkRequestId());
4033        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
4034        if (DBG) log("requestNetwork for " + nri);
4035
4036        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
4037        if (timeoutMs > 0) {
4038            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
4039                    nri), timeoutMs);
4040        }
4041        return networkRequest;
4042    }
4043
4044    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
4045        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
4046            enforceConnectivityInternalPermission();
4047        } else {
4048            enforceChangePermission();
4049        }
4050    }
4051
4052    @Override
4053    public boolean requestBandwidthUpdate(Network network) {
4054        enforceAccessPermission();
4055        NetworkAgentInfo nai = null;
4056        if (network == null) {
4057            return false;
4058        }
4059        synchronized (mNetworkForNetId) {
4060            nai = mNetworkForNetId.get(network.netId);
4061        }
4062        if (nai != null) {
4063            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4064            return true;
4065        }
4066        return false;
4067    }
4068
4069
4070    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4071        // if UID is restricted, don't allow them to bring up metered APNs
4072        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
4073            final int uidRules;
4074            final int uid = Binder.getCallingUid();
4075            synchronized(mRulesLock) {
4076                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4077            }
4078            if ((uidRules & RULE_ALLOW_ALL) == 0) {
4079                // we could silently fail or we can filter the available nets to only give
4080                // them those they have access to.  Chose the more useful option.
4081                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
4082            }
4083        }
4084    }
4085
4086    @Override
4087    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4088            PendingIntent operation) {
4089        checkNotNull(operation, "PendingIntent cannot be null.");
4090        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4091        enforceNetworkRequestPermissions(networkCapabilities);
4092        enforceMeteredApnPolicy(networkCapabilities);
4093        ensureRequestableCapabilities(networkCapabilities);
4094
4095        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4096                nextNetworkRequestId());
4097        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
4098                NetworkRequestType.REQUEST);
4099        if (DBG) log("pendingRequest for " + nri);
4100        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4101                nri));
4102        return networkRequest;
4103    }
4104
4105    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4106        mHandler.sendMessageDelayed(
4107                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4108                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4109    }
4110
4111    @Override
4112    public void releasePendingNetworkRequest(PendingIntent operation) {
4113        checkNotNull(operation, "PendingIntent cannot be null.");
4114        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4115                getCallingUid(), 0, operation));
4116    }
4117
4118    // In order to implement the compatibility measure for pre-M apps that call
4119    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4120    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4121    // This ensures it has permission to do so.
4122    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4123        if (nc == null) {
4124            return false;
4125        }
4126        int[] transportTypes = nc.getTransportTypes();
4127        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4128            return false;
4129        }
4130        try {
4131            mContext.enforceCallingOrSelfPermission(
4132                    android.Manifest.permission.ACCESS_WIFI_STATE,
4133                    "ConnectivityService");
4134        } catch (SecurityException e) {
4135            return false;
4136        }
4137        return true;
4138    }
4139
4140    @Override
4141    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4142            Messenger messenger, IBinder binder) {
4143        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4144            enforceAccessPermission();
4145        }
4146
4147        NetworkRequest networkRequest = new NetworkRequest(
4148                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
4149        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
4150                NetworkRequestType.LISTEN);
4151        if (VDBG) log("listenForNetwork for " + nri);
4152
4153        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4154        return networkRequest;
4155    }
4156
4157    @Override
4158    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4159            PendingIntent operation) {
4160        checkNotNull(operation, "PendingIntent cannot be null.");
4161        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4162            enforceAccessPermission();
4163        }
4164
4165        NetworkRequest networkRequest = new NetworkRequest(
4166                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
4167        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
4168                NetworkRequestType.LISTEN);
4169        if (VDBG) log("pendingListenForNetwork for " + nri);
4170
4171        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4172    }
4173
4174    @Override
4175    public void releaseNetworkRequest(NetworkRequest networkRequest) {
4176        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4177                0, networkRequest));
4178    }
4179
4180    @Override
4181    public void registerNetworkFactory(Messenger messenger, String name) {
4182        enforceConnectivityInternalPermission();
4183        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4184        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
4185    }
4186
4187    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
4188        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
4189        mNetworkFactoryInfos.put(nfi.messenger, nfi);
4190        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4191    }
4192
4193    @Override
4194    public void unregisterNetworkFactory(Messenger messenger) {
4195        enforceConnectivityInternalPermission();
4196        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4197    }
4198
4199    private void handleUnregisterNetworkFactory(Messenger messenger) {
4200        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4201        if (nfi == null) {
4202            loge("Failed to find Messenger in unregisterNetworkFactory");
4203            return;
4204        }
4205        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
4206    }
4207
4208    /**
4209     * NetworkAgentInfo supporting a request by requestId.
4210     * These have already been vetted (their Capabilities satisfy the request)
4211     * and the are the highest scored network available.
4212     * the are keyed off the Requests requestId.
4213     */
4214    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
4215    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4216            new SparseArray<NetworkAgentInfo>();
4217
4218    // NOTE: Accessed on multiple threads, must be synchronized on itself.
4219    @GuardedBy("mNetworkForNetId")
4220    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4221            new SparseArray<NetworkAgentInfo>();
4222    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4223    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4224    // there may not be a strict 1:1 correlation between the two.
4225    @GuardedBy("mNetworkForNetId")
4226    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
4227
4228    // NetworkAgentInfo keyed off its connecting messenger
4229    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
4230    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
4231    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4232            new HashMap<Messenger, NetworkAgentInfo>();
4233
4234    @GuardedBy("mBlockedAppUids")
4235    private final HashSet<Integer> mBlockedAppUids = new HashSet();
4236
4237    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
4238    private final NetworkRequest mDefaultRequest;
4239
4240    // Request used to optionally keep mobile data active even when higher
4241    // priority networks like Wi-Fi are active.
4242    private final NetworkRequest mDefaultMobileDataRequest;
4243
4244    private NetworkAgentInfo getDefaultNetwork() {
4245        return mNetworkForRequestId.get(mDefaultRequest.requestId);
4246    }
4247
4248    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
4249        return nai == getDefaultNetwork();
4250    }
4251
4252    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
4253            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
4254            int currentScore, NetworkMisc networkMisc) {
4255        enforceConnectivityInternalPermission();
4256
4257        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4258        // satisfies mDefaultRequest.
4259        final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
4260                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4261                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
4262                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
4263        synchronized (this) {
4264            nai.networkMonitor.systemReady = mSystemReady;
4265        }
4266        addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
4267        if (DBG) log("registerNetworkAgent " + nai);
4268        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
4269        return nai.network.netId;
4270    }
4271
4272    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4273        if (VDBG) log("Got NetworkAgent Messenger");
4274        mNetworkAgentInfos.put(na.messenger, na);
4275        synchronized (mNetworkForNetId) {
4276            mNetworkForNetId.put(na.network.netId, na);
4277        }
4278        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4279        NetworkInfo networkInfo = na.networkInfo;
4280        na.networkInfo = null;
4281        updateNetworkInfo(na, networkInfo);
4282    }
4283
4284    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4285        LinkProperties newLp = networkAgent.linkProperties;
4286        int netId = networkAgent.network.netId;
4287
4288        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4289        // we do anything else, make sure its LinkProperties are accurate.
4290        if (networkAgent.clatd != null) {
4291            networkAgent.clatd.fixupLinkProperties(oldLp);
4292        }
4293
4294        updateInterfaces(newLp, oldLp, netId);
4295        updateMtu(newLp, oldLp);
4296        // TODO - figure out what to do for clat
4297//        for (LinkProperties lp : newLp.getStackedLinks()) {
4298//            updateMtu(lp, null);
4299//        }
4300        updateTcpBufferSizes(networkAgent);
4301
4302        updateRoutes(newLp, oldLp, netId);
4303        updateDnses(newLp, oldLp, netId);
4304
4305        updateClat(newLp, oldLp, networkAgent);
4306        if (isDefaultNetwork(networkAgent)) {
4307            handleApplyDefaultProxy(newLp.getHttpProxy());
4308        } else {
4309            updateProxy(newLp, oldLp, networkAgent);
4310        }
4311        // TODO - move this check to cover the whole function
4312        if (!Objects.equals(newLp, oldLp)) {
4313            notifyIfacesChangedForNetworkStats();
4314            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4315        }
4316
4317        mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
4318    }
4319
4320    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4321        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4322        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
4323
4324        if (!wasRunningClat && shouldRunClat) {
4325            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4326            nai.clatd.start();
4327        } else if (wasRunningClat && !shouldRunClat) {
4328            nai.clatd.stop();
4329        }
4330    }
4331
4332    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4333        CompareResult<String> interfaceDiff = new CompareResult<String>();
4334        if (oldLp != null) {
4335            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4336        } else if (newLp != null) {
4337            interfaceDiff.added = newLp.getAllInterfaceNames();
4338        }
4339        for (String iface : interfaceDiff.added) {
4340            try {
4341                if (DBG) log("Adding iface " + iface + " to network " + netId);
4342                mNetd.addInterfaceToNetwork(iface, netId);
4343            } catch (Exception e) {
4344                loge("Exception adding interface: " + e);
4345            }
4346        }
4347        for (String iface : interfaceDiff.removed) {
4348            try {
4349                if (DBG) log("Removing iface " + iface + " from network " + netId);
4350                mNetd.removeInterfaceFromNetwork(iface, netId);
4351            } catch (Exception e) {
4352                loge("Exception removing interface: " + e);
4353            }
4354        }
4355    }
4356
4357    /**
4358     * Have netd update routes from oldLp to newLp.
4359     * @return true if routes changed between oldLp and newLp
4360     */
4361    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4362        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4363        if (oldLp != null) {
4364            routeDiff = oldLp.compareAllRoutes(newLp);
4365        } else if (newLp != null) {
4366            routeDiff.added = newLp.getAllRoutes();
4367        }
4368
4369        // add routes before removing old in case it helps with continuous connectivity
4370
4371        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4372        for (RouteInfo route : routeDiff.added) {
4373            if (route.hasGateway()) continue;
4374            if (VDBG) log("Adding Route [" + route + "] to network " + netId);
4375            try {
4376                mNetd.addRoute(netId, route);
4377            } catch (Exception e) {
4378                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4379                    loge("Exception in addRoute for non-gateway: " + e);
4380                }
4381            }
4382        }
4383        for (RouteInfo route : routeDiff.added) {
4384            if (route.hasGateway() == false) continue;
4385            if (VDBG) log("Adding Route [" + route + "] to network " + netId);
4386            try {
4387                mNetd.addRoute(netId, route);
4388            } catch (Exception e) {
4389                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4390                    loge("Exception in addRoute for gateway: " + e);
4391                }
4392            }
4393        }
4394
4395        for (RouteInfo route : routeDiff.removed) {
4396            if (VDBG) log("Removing Route [" + route + "] from network " + netId);
4397            try {
4398                mNetd.removeRoute(netId, route);
4399            } catch (Exception e) {
4400                loge("Exception in removeRoute: " + e);
4401            }
4402        }
4403        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4404    }
4405
4406    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4407        if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4408            return;  // no updating necessary
4409        }
4410
4411        Collection<InetAddress> dnses = newLp.getDnsServers();
4412        if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
4413        try {
4414            mNetd.setDnsConfigurationForNetwork(
4415                    netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4416        } catch (Exception e) {
4417            loge("Exception in setDnsConfigurationForNetwork: " + e);
4418        }
4419        final NetworkAgentInfo defaultNai = getDefaultNetwork();
4420        if (defaultNai != null && defaultNai.network.netId == netId) {
4421            setDefaultDnsSystemProperties(dnses);
4422        }
4423        flushVmDnsCache();
4424    }
4425
4426    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4427        int last = 0;
4428        for (InetAddress dns : dnses) {
4429            ++last;
4430            String key = "net.dns" + last;
4431            String value = dns.getHostAddress();
4432            SystemProperties.set(key, value);
4433        }
4434        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4435            String key = "net.dns" + i;
4436            SystemProperties.set(key, "");
4437        }
4438        mNumDnsEntries = last;
4439    }
4440
4441    /**
4442     * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4443     * augmented with any stateful capabilities implied from {@code networkAgent}
4444     * (e.g., validated status and captive portal status).
4445     *
4446     * @param nai the network having its capabilities updated.
4447     * @param networkCapabilities the new network capabilities.
4448     */
4449    private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
4450        // Don't modify caller's NetworkCapabilities.
4451        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4452        if (nai.lastValidated) {
4453            networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4454        } else {
4455            networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4456        }
4457        if (nai.lastCaptivePortalDetected) {
4458            networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4459        } else {
4460            networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4461        }
4462        if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4463            final int oldScore = nai.getCurrentScore();
4464            if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4465                    networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4466                try {
4467                    mNetd.setNetworkPermission(nai.network.netId,
4468                            networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4469                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4470                } catch (RemoteException e) {
4471                    loge("Exception in setNetworkPermission: " + e);
4472                }
4473            }
4474            synchronized (nai) {
4475                nai.networkCapabilities = networkCapabilities;
4476            }
4477            rematchAllNetworksAndRequests(nai, oldScore);
4478            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4479        }
4480    }
4481
4482    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4483        for (int i = 0; i < nai.networkRequests.size(); i++) {
4484            NetworkRequest nr = nai.networkRequests.valueAt(i);
4485            // Don't send listening requests to factories. b/17393458
4486            if (!isRequest(nr)) continue;
4487            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4488        }
4489    }
4490
4491    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4492        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4493        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4494            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4495                    networkRequest);
4496        }
4497    }
4498
4499    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4500            int notificationType) {
4501        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4502            Intent intent = new Intent();
4503            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4504            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4505            nri.mPendingIntentSent = true;
4506            sendIntent(nri.mPendingIntent, intent);
4507        }
4508        // else not handled
4509    }
4510
4511    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4512        mPendingIntentWakeLock.acquire();
4513        try {
4514            if (DBG) log("Sending " + pendingIntent);
4515            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4516        } catch (PendingIntent.CanceledException e) {
4517            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4518            mPendingIntentWakeLock.release();
4519            releasePendingNetworkRequest(pendingIntent);
4520        }
4521        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4522    }
4523
4524    @Override
4525    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4526            String resultData, Bundle resultExtras) {
4527        if (DBG) log("Finished sending " + pendingIntent);
4528        mPendingIntentWakeLock.release();
4529        // Release with a delay so the receiving client has an opportunity to put in its
4530        // own request.
4531        releasePendingNetworkRequestWithDelay(pendingIntent);
4532    }
4533
4534    private void callCallbackForRequest(NetworkRequestInfo nri,
4535            NetworkAgentInfo networkAgent, int notificationType) {
4536        if (nri.messenger == null) return;  // Default request has no msgr
4537        Bundle bundle = new Bundle();
4538        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4539                new NetworkRequest(nri.request));
4540        Message msg = Message.obtain();
4541        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4542                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4543            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4544        }
4545        switch (notificationType) {
4546            case ConnectivityManager.CALLBACK_LOSING: {
4547                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4548                break;
4549            }
4550            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4551                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4552                        new NetworkCapabilities(networkAgent.networkCapabilities));
4553                break;
4554            }
4555            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4556                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4557                        new LinkProperties(networkAgent.linkProperties));
4558                break;
4559            }
4560        }
4561        msg.what = notificationType;
4562        msg.setData(bundle);
4563        try {
4564            if (VDBG) {
4565                log("sending notification " + notifyTypeToName(notificationType) +
4566                        " for " + nri.request);
4567            }
4568            nri.messenger.send(msg);
4569        } catch (RemoteException e) {
4570            // may occur naturally in the race of binder death.
4571            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4572        }
4573    }
4574
4575    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4576        for (int i = 0; i < nai.networkRequests.size(); i++) {
4577            NetworkRequest nr = nai.networkRequests.valueAt(i);
4578            // Ignore listening requests.
4579            if (!isRequest(nr)) continue;
4580            loge("Dead network still had at least " + nr);
4581            break;
4582        }
4583        nai.asyncChannel.disconnect();
4584    }
4585
4586    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4587        if (oldNetwork == null) {
4588            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4589            return;
4590        }
4591        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4592        teardownUnneededNetwork(oldNetwork);
4593    }
4594
4595    private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
4596        if (DBG) log("Switching to new default network: " + newNetwork);
4597        setupDataActivityTracking(newNetwork);
4598        try {
4599            mNetd.setDefaultNetId(newNetwork.network.netId);
4600        } catch (Exception e) {
4601            loge("Exception setting default network :" + e);
4602        }
4603        notifyLockdownVpn(newNetwork);
4604        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4605        updateTcpBufferSizes(newNetwork);
4606        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4607        logDefaultNetworkEvent(newNetwork, prevNetwork);
4608    }
4609
4610    // Handles a network appearing or improving its score.
4611    //
4612    // - Evaluates all current NetworkRequests that can be
4613    //   satisfied by newNetwork, and reassigns to newNetwork
4614    //   any such requests for which newNetwork is the best.
4615    //
4616    // - Lingers any validated Networks that as a result are no longer
4617    //   needed. A network is needed if it is the best network for
4618    //   one or more NetworkRequests, or if it is a VPN.
4619    //
4620    // - Tears down newNetwork if it just became validated
4621    //   but turns out to be unneeded.
4622    //
4623    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4624    //   networks that have no chance (i.e. even if validated)
4625    //   of becoming the highest scoring network.
4626    //
4627    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4628    // it does not remove NetworkRequests that other Networks could better satisfy.
4629    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4630    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4631    // as it performs better by a factor of the number of Networks.
4632    //
4633    // @param newNetwork is the network to be matched against NetworkRequests.
4634    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4635    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4636    //               validated) of becoming the highest scoring network.
4637    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
4638            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4639        if (!newNetwork.everConnected) return;
4640        boolean keep = newNetwork.isVPN();
4641        boolean isNewDefault = false;
4642        NetworkAgentInfo oldDefaultNetwork = null;
4643        if (VDBG) log("rematching " + newNetwork.name());
4644        // Find and migrate to this Network any NetworkRequests for
4645        // which this network is now the best.
4646        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4647        ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
4648        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4649        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4650            final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4651            final boolean satisfies = newNetwork.satisfies(nri.request);
4652            if (newNetwork == currentNetwork && satisfies) {
4653                if (VDBG) {
4654                    log("Network " + newNetwork.name() + " was already satisfying" +
4655                            " request " + nri.request.requestId + ". No change.");
4656                }
4657                keep = true;
4658                continue;
4659            }
4660
4661            // check if it satisfies the NetworkCapabilities
4662            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4663            if (satisfies) {
4664                if (!nri.isRequest()) {
4665                    // This is not a request, it's a callback listener.
4666                    // Add it to newNetwork regardless of score.
4667                    if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
4668                    continue;
4669                }
4670
4671                // next check if it's better than any current network we're using for
4672                // this request
4673                if (VDBG) {
4674                    log("currentScore = " +
4675                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4676                            ", newScore = " + newNetwork.getCurrentScore());
4677                }
4678                if (currentNetwork == null ||
4679                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4680                    if (VDBG) log("rematch for " + newNetwork.name());
4681                    if (currentNetwork != null) {
4682                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
4683                        currentNetwork.networkRequests.remove(nri.request.requestId);
4684                        currentNetwork.networkLingered.add(nri.request);
4685                        affectedNetworks.add(currentNetwork);
4686                    } else {
4687                        if (VDBG) log("   accepting network in place of null");
4688                    }
4689                    unlinger(newNetwork);
4690                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4691                    if (!newNetwork.addRequest(nri.request)) {
4692                        Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4693                    }
4694                    addedRequests.add(nri);
4695                    keep = true;
4696                    // Tell NetworkFactories about the new score, so they can stop
4697                    // trying to connect if they know they cannot match it.
4698                    // TODO - this could get expensive if we have alot of requests for this
4699                    // network.  Think about if there is a way to reduce this.  Push
4700                    // netid->request mapping to each factory?
4701                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4702                    if (mDefaultRequest.requestId == nri.request.requestId) {
4703                        isNewDefault = true;
4704                        oldDefaultNetwork = currentNetwork;
4705                    }
4706                }
4707            } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4708                // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4709                // mark it as no longer satisfying "nri".  Because networks are processed by
4710                // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4711                // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4712                // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4713                // This means this code doesn't have to handle the case where "currentNetwork" no
4714                // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4715                if (DBG) {
4716                    log("Network " + newNetwork.name() + " stopped satisfying" +
4717                            " request " + nri.request.requestId);
4718                }
4719                newNetwork.networkRequests.remove(nri.request.requestId);
4720                if (currentNetwork == newNetwork) {
4721                    mNetworkForRequestId.remove(nri.request.requestId);
4722                    sendUpdatedScoreToFactories(nri.request, 0);
4723                } else {
4724                    if (nri.isRequest()) {
4725                        Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4726                                newNetwork.name() +
4727                                " without updating mNetworkForRequestId or factories!");
4728                    }
4729                }
4730                // TODO: technically, sending CALLBACK_LOST here is
4731                // incorrect if nri is a request (not a listen) and there
4732                // is a replacement network currently connected that can
4733                // satisfy it. However, the only capability that can both
4734                // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4735                // so this code is only incorrect for a network that loses
4736                // the TRUSTED capability, which is a rare case.
4737                callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
4738            }
4739        }
4740        // Linger any networks that are no longer needed.
4741        for (NetworkAgentInfo nai : affectedNetworks) {
4742            if (nai.lingering) {
4743                // Already lingered.  Nothing to do.  This can only happen if "nai" is in
4744                // "affectedNetworks" twice.  The reasoning being that to get added to
4745                // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4746                // (i.e. not lingered) so it could have only been lingered by this loop.
4747                // unneeded(nai) will be false and we'll call unlinger() below which would
4748                // be bad, so handle it here.
4749            } else if (unneeded(nai)) {
4750                linger(nai);
4751            } else {
4752                // Clear nai.networkLingered we might have added above.
4753                unlinger(nai);
4754            }
4755        }
4756        if (isNewDefault) {
4757            // Notify system services that this network is up.
4758            makeDefault(newNetwork, oldDefaultNetwork);
4759            synchronized (ConnectivityService.this) {
4760                // have a new default network, release the transition wakelock in
4761                // a second if it's held.  The second pause is to allow apps
4762                // to reconnect over the new network
4763                if (mNetTransitionWakeLock.isHeld()) {
4764                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
4765                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4766                            mNetTransitionWakeLockSerialNumber, 0),
4767                            1000);
4768                }
4769            }
4770        }
4771
4772        // do this after the default net is switched, but
4773        // before LegacyTypeTracker sends legacy broadcasts
4774        for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4775
4776        if (isNewDefault) {
4777            // Maintain the illusion: since the legacy API only
4778            // understands one network at a time, we must pretend
4779            // that the current default network disconnected before
4780            // the new one connected.
4781            if (oldDefaultNetwork != null) {
4782                mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4783                                          oldDefaultNetwork, true);
4784            }
4785            mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4786            mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4787            notifyLockdownVpn(newNetwork);
4788        }
4789
4790        if (keep) {
4791            // Notify battery stats service about this network, both the normal
4792            // interface and any stacked links.
4793            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4794            try {
4795                final IBatteryStats bs = BatteryStatsService.getService();
4796                final int type = newNetwork.networkInfo.getType();
4797
4798                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4799                bs.noteNetworkInterfaceType(baseIface, type);
4800                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4801                    final String stackedIface = stacked.getInterfaceName();
4802                    bs.noteNetworkInterfaceType(stackedIface, type);
4803                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4804                }
4805            } catch (RemoteException ignored) {
4806            }
4807
4808            // This has to happen after the notifyNetworkCallbacks as that tickles each
4809            // ConnectivityManager instance so that legacy requests correctly bind dns
4810            // requests to this network.  The legacy users are listening for this bcast
4811            // and will generally do a dns request so they can ensureRouteToHost and if
4812            // they do that before the callbacks happen they'll use the default network.
4813            //
4814            // TODO: Is there still a race here? We send the broadcast
4815            // after sending the callback, but if the app can receive the
4816            // broadcast before the callback, it might still break.
4817            //
4818            // This *does* introduce a race where if the user uses the new api
4819            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4820            // they may get old info.  Reverse this after the old startUsing api is removed.
4821            // This is on top of the multiple intent sequencing referenced in the todo above.
4822            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4823                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4824                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4825                    // legacy type tracker filters out repeat adds
4826                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4827                }
4828            }
4829
4830            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4831            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4832            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4833            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4834            if (newNetwork.isVPN()) {
4835                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4836            }
4837        }
4838        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4839            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4840                if (unneeded(nai)) {
4841                    if (DBG) log("Reaping " + nai.name());
4842                    teardownUnneededNetwork(nai);
4843                }
4844            }
4845        }
4846    }
4847
4848    /**
4849     * Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4850     * being disconnected.
4851     * @param changed If only one Network's score or capabilities have been modified since the last
4852     *         time this function was called, pass this Network in this argument, otherwise pass
4853     *         null.
4854     * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4855     *         changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4856     *         this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4857     *         {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4858     *         network's score.
4859     */
4860    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4861        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4862        // to avoid the slowness.  It is not simply enough to process just "changed", for
4863        // example in the case where "changed"'s score decreases and another network should begin
4864        // satifying a NetworkRequest that "changed" currently satisfies.
4865
4866        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4867        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4868        // rematchNetworkAndRequests() handles.
4869        if (changed != null && oldScore < changed.getCurrentScore()) {
4870            rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
4871        } else {
4872            final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4873                    new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4874            // Rematch higher scoring networks first to prevent requests first matching a lower
4875            // scoring network and then a higher scoring network, which could produce multiple
4876            // callbacks and inadvertently unlinger networks.
4877            Arrays.sort(nais);
4878            for (NetworkAgentInfo nai : nais) {
4879                rematchNetworkAndRequests(nai,
4880                        // Only reap the last time through the loop.  Reaping before all rematching
4881                        // is complete could incorrectly teardown a network that hasn't yet been
4882                        // rematched.
4883                        (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
4884                                : ReapUnvalidatedNetworks.REAP);
4885            }
4886        }
4887    }
4888
4889    private void updateInetCondition(NetworkAgentInfo nai) {
4890        // Don't bother updating until we've graduated to validated at least once.
4891        if (!nai.everValidated) return;
4892        // For now only update icons for default connection.
4893        // TODO: Update WiFi and cellular icons separately. b/17237507
4894        if (!isDefaultNetwork(nai)) return;
4895
4896        int newInetCondition = nai.lastValidated ? 100 : 0;
4897        // Don't repeat publish.
4898        if (newInetCondition == mDefaultInetConditionPublished) return;
4899
4900        mDefaultInetConditionPublished = newInetCondition;
4901        sendInetConditionBroadcast(nai.networkInfo);
4902    }
4903
4904    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4905        if (mLockdownTracker != null) {
4906            if (nai != null && nai.isVPN()) {
4907                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4908            } else {
4909                mLockdownTracker.onNetworkInfoChanged();
4910            }
4911        }
4912    }
4913
4914    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4915        NetworkInfo.State state = newInfo.getState();
4916        NetworkInfo oldInfo = null;
4917        final int oldScore = networkAgent.getCurrentScore();
4918        synchronized (networkAgent) {
4919            oldInfo = networkAgent.networkInfo;
4920            networkAgent.networkInfo = newInfo;
4921        }
4922        notifyLockdownVpn(networkAgent);
4923
4924        if (oldInfo != null && oldInfo.getState() == state) {
4925            if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4926                if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4927                notifyIfacesChangedForNetworkStats();
4928            } else if (VDBG) log("ignoring duplicate network state non-change");
4929            // In either case, no further work should be needed.
4930            return;
4931        }
4932        if (DBG) {
4933            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4934                    (oldInfo == null ? "null" : oldInfo.getState()) +
4935                    " to " + state);
4936        }
4937
4938        if (!networkAgent.created
4939                && (state == NetworkInfo.State.CONNECTED
4940                || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
4941            try {
4942                // This should never fail.  Specifying an already in use NetID will cause failure.
4943                if (networkAgent.isVPN()) {
4944                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4945                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4946                            (networkAgent.networkMisc == null ||
4947                                !networkAgent.networkMisc.allowBypass));
4948                } else {
4949                    mNetd.createPhysicalNetwork(networkAgent.network.netId,
4950                            networkAgent.networkCapabilities.hasCapability(
4951                                    NET_CAPABILITY_NOT_RESTRICTED) ?
4952                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4953                }
4954            } catch (Exception e) {
4955                loge("Error creating network " + networkAgent.network.netId + ": "
4956                        + e.getMessage());
4957                return;
4958            }
4959            networkAgent.created = true;
4960        }
4961
4962        if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4963            networkAgent.everConnected = true;
4964
4965            updateLinkProperties(networkAgent, null);
4966            notifyIfacesChangedForNetworkStats();
4967
4968            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4969            scheduleUnvalidatedPrompt(networkAgent);
4970
4971            if (networkAgent.isVPN()) {
4972                // Temporarily disable the default proxy (not global).
4973                synchronized (mProxyLock) {
4974                    if (!mDefaultProxyDisabled) {
4975                        mDefaultProxyDisabled = true;
4976                        if (mGlobalProxy == null && mDefaultProxy != null) {
4977                            sendProxyBroadcast(null);
4978                        }
4979                    }
4980                }
4981                // TODO: support proxy per network.
4982            }
4983
4984            // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4985            // be communicated to a particular NetworkAgent depends only on the network's immutable,
4986            // capabilities, so it only needs to be done once on initial connect, not every time the
4987            // network's capabilities change. Note that we do this before rematching the network,
4988            // so we could decide to tear it down immediately afterwards. That's fine though - on
4989            // disconnection NetworkAgents should stop any signal strength monitoring they have been
4990            // doing.
4991            updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
4992
4993            // Consider network even though it is not yet validated.
4994            rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
4995
4996            // This has to happen after matching the requests, because callbacks are just requests.
4997            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4998        } else if (state == NetworkInfo.State.DISCONNECTED) {
4999            networkAgent.asyncChannel.disconnect();
5000            if (networkAgent.isVPN()) {
5001                synchronized (mProxyLock) {
5002                    if (mDefaultProxyDisabled) {
5003                        mDefaultProxyDisabled = false;
5004                        if (mGlobalProxy == null && mDefaultProxy != null) {
5005                            sendProxyBroadcast(mDefaultProxy);
5006                        }
5007                    }
5008                }
5009            }
5010        } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5011                state == NetworkInfo.State.SUSPENDED) {
5012            // going into or coming out of SUSPEND: rescore and notify
5013            if (networkAgent.getCurrentScore() != oldScore) {
5014                rematchAllNetworksAndRequests(networkAgent, oldScore);
5015            }
5016            notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5017                    ConnectivityManager.CALLBACK_SUSPENDED :
5018                    ConnectivityManager.CALLBACK_RESUMED));
5019            mLegacyTypeTracker.update(networkAgent);
5020        }
5021    }
5022
5023    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
5024        if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
5025        if (score < 0) {
5026            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5027                    ").  Bumping score to min of 0");
5028            score = 0;
5029        }
5030
5031        final int oldScore = nai.getCurrentScore();
5032        nai.setCurrentScore(score);
5033
5034        rematchAllNetworksAndRequests(nai, oldScore);
5035
5036        sendUpdatedScoreToFactories(nai);
5037    }
5038
5039    // notify only this one new request of the current state
5040    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5041        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5042        // TODO - read state from monitor to decide what to send.
5043//        if (nai.networkMonitor.isLingering()) {
5044//            notifyType = NetworkCallbacks.LOSING;
5045//        } else if (nai.networkMonitor.isEvaluating()) {
5046//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5047//        }
5048        if (nri.mPendingIntent == null) {
5049            callCallbackForRequest(nri, nai, notifyType);
5050        } else {
5051            sendPendingIntentForRequest(nri, nai, notifyType);
5052        }
5053    }
5054
5055    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
5056        // The NetworkInfo we actually send out has no bearing on the real
5057        // state of affairs. For example, if the default connection is mobile,
5058        // and a request for HIPRI has just gone away, we need to pretend that
5059        // HIPRI has just disconnected. So we need to set the type to HIPRI and
5060        // the state to DISCONNECTED, even though the network is of type MOBILE
5061        // and is still connected.
5062        NetworkInfo info = new NetworkInfo(nai.networkInfo);
5063        info.setType(type);
5064        if (state != DetailedState.DISCONNECTED) {
5065            info.setDetailedState(state, null, info.getExtraInfo());
5066            sendConnectedBroadcast(info);
5067        } else {
5068            info.setDetailedState(state, info.getReason(), info.getExtraInfo());
5069            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5070            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5071            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5072            if (info.isFailover()) {
5073                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5074                nai.networkInfo.setFailover(false);
5075            }
5076            if (info.getReason() != null) {
5077                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5078            }
5079            if (info.getExtraInfo() != null) {
5080                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5081            }
5082            NetworkAgentInfo newDefaultAgent = null;
5083            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
5084                newDefaultAgent = getDefaultNetwork();
5085                if (newDefaultAgent != null) {
5086                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5087                            newDefaultAgent.networkInfo);
5088                } else {
5089                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5090                }
5091            }
5092            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5093                    mDefaultInetConditionPublished);
5094            sendStickyBroadcast(intent);
5095            if (newDefaultAgent != null) {
5096                sendConnectedBroadcast(newDefaultAgent.networkInfo);
5097            }
5098        }
5099    }
5100
5101    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5102        if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
5103        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
5104            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5105            NetworkRequestInfo nri = mNetworkRequests.get(nr);
5106            if (VDBG) log(" sending notification for " + nr);
5107            if (nri.mPendingIntent == null) {
5108                callCallbackForRequest(nri, networkAgent, notifyType);
5109            } else {
5110                sendPendingIntentForRequest(nri, networkAgent, notifyType);
5111            }
5112        }
5113    }
5114
5115    private String notifyTypeToName(int notifyType) {
5116        switch (notifyType) {
5117            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
5118            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
5119            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
5120            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
5121            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
5122            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5123            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
5124            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
5125        }
5126        return "UNKNOWN";
5127    }
5128
5129    /**
5130     * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5131     * properties tracked by NetworkStatsService on an active iface has changed.
5132     */
5133    private void notifyIfacesChangedForNetworkStats() {
5134        try {
5135            mStatsService.forceUpdateIfaces();
5136        } catch (Exception ignored) {
5137        }
5138    }
5139
5140    @Override
5141    public boolean addVpnAddress(String address, int prefixLength) {
5142        throwIfLockdownEnabled();
5143        int user = UserHandle.getUserId(Binder.getCallingUid());
5144        synchronized (mVpns) {
5145            return mVpns.get(user).addAddress(address, prefixLength);
5146        }
5147    }
5148
5149    @Override
5150    public boolean removeVpnAddress(String address, int prefixLength) {
5151        throwIfLockdownEnabled();
5152        int user = UserHandle.getUserId(Binder.getCallingUid());
5153        synchronized (mVpns) {
5154            return mVpns.get(user).removeAddress(address, prefixLength);
5155        }
5156    }
5157
5158    @Override
5159    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5160        throwIfLockdownEnabled();
5161        int user = UserHandle.getUserId(Binder.getCallingUid());
5162        boolean success;
5163        synchronized (mVpns) {
5164            success = mVpns.get(user).setUnderlyingNetworks(networks);
5165        }
5166        if (success) {
5167            notifyIfacesChangedForNetworkStats();
5168        }
5169        return success;
5170    }
5171
5172    @Override
5173    public String getCaptivePortalServerUrl() {
5174        return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5175    }
5176
5177    @Override
5178    public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5179            IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5180        enforceKeepalivePermission();
5181        mKeepaliveTracker.startNattKeepalive(
5182                getNetworkAgentInfoForNetwork(network),
5183                intervalSeconds, messenger, binder,
5184                srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5185    }
5186
5187    @Override
5188    public void stopKeepalive(Network network, int slot) {
5189        mHandler.sendMessage(mHandler.obtainMessage(
5190                NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5191    }
5192
5193    @Override
5194    public void factoryReset() {
5195        enforceConnectivityInternalPermission();
5196
5197        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5198            return;
5199        }
5200
5201        final int userId = UserHandle.getCallingUserId();
5202
5203        // Turn airplane mode off
5204        setAirplaneMode(false);
5205
5206        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5207            // Untether
5208            for (String tether : getTetheredIfaces()) {
5209                untether(tether);
5210            }
5211        }
5212
5213        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5214            // Turn VPN off
5215            VpnConfig vpnConfig = getVpnConfig(userId);
5216            if (vpnConfig != null) {
5217                if (vpnConfig.legacy) {
5218                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5219                } else {
5220                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5221                    // in the future without user intervention.
5222                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
5223
5224                    prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5225                }
5226            }
5227        }
5228    }
5229
5230    @VisibleForTesting
5231    public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5232            NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5233        return new NetworkMonitor(context, handler, nai, defaultRequest);
5234    }
5235
5236    private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5237        int newNetid = NETID_UNSET;
5238        int prevNetid = NETID_UNSET;
5239        int[] transports = new int[0];
5240        boolean hadIPv4 = false;
5241        boolean hadIPv6 = false;
5242
5243        if (newNai != null) {
5244            newNetid = newNai.network.netId;
5245            transports = newNai.networkCapabilities.getTransportTypes();
5246        }
5247        if (prevNai != null) {
5248            prevNetid = prevNai.network.netId;
5249            final LinkProperties lp = prevNai.linkProperties;
5250            hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5251            hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5252        }
5253
5254        DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
5255    }
5256}
5257