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