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