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