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