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