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