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