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