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