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