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