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