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