ConnectivityService.java revision 7094d22022c8e0c6ad71920b101434dded8a276e
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    public 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    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2642    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2643    // proxy is null then there is no proxy in place).
2644    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2645        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2646                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2647            proxy = null;
2648        }
2649        return proxy;
2650    }
2651
2652    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2653    // better for determining if a new proxy broadcast is necessary:
2654    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2655    //    avoid unnecessary broadcasts.
2656    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2657    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2658    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2659    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2660    //    all set.
2661    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2662        a = canonicalizeProxyInfo(a);
2663        b = canonicalizeProxyInfo(b);
2664        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2665        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2666        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2667    }
2668
2669    public void setGlobalProxy(ProxyInfo proxyProperties) {
2670        enforceConnectivityInternalPermission();
2671
2672        synchronized (mProxyLock) {
2673            if (proxyProperties == mGlobalProxy) return;
2674            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2675            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2676
2677            String host = "";
2678            int port = 0;
2679            String exclList = "";
2680            String pacFileUrl = "";
2681            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2682                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2683                if (!proxyProperties.isValid()) {
2684                    if (DBG)
2685                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2686                    return;
2687                }
2688                mGlobalProxy = new ProxyInfo(proxyProperties);
2689                host = mGlobalProxy.getHost();
2690                port = mGlobalProxy.getPort();
2691                exclList = mGlobalProxy.getExclusionListAsString();
2692                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2693                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2694                }
2695            } else {
2696                mGlobalProxy = null;
2697            }
2698            ContentResolver res = mContext.getContentResolver();
2699            final long token = Binder.clearCallingIdentity();
2700            try {
2701                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2702                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2703                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2704                        exclList);
2705                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2706            } finally {
2707                Binder.restoreCallingIdentity(token);
2708            }
2709
2710            if (mGlobalProxy == null) {
2711                proxyProperties = mDefaultProxy;
2712            }
2713            sendProxyBroadcast(proxyProperties);
2714        }
2715    }
2716
2717    private void loadGlobalProxy() {
2718        ContentResolver res = mContext.getContentResolver();
2719        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2720        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2721        String exclList = Settings.Global.getString(res,
2722                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2723        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2724        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2725            ProxyInfo proxyProperties;
2726            if (!TextUtils.isEmpty(pacFileUrl)) {
2727                proxyProperties = new ProxyInfo(pacFileUrl);
2728            } else {
2729                proxyProperties = new ProxyInfo(host, port, exclList);
2730            }
2731            if (!proxyProperties.isValid()) {
2732                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2733                return;
2734            }
2735
2736            synchronized (mProxyLock) {
2737                mGlobalProxy = proxyProperties;
2738            }
2739        }
2740    }
2741
2742    public ProxyInfo getGlobalProxy() {
2743        // this information is already available as a world read/writable jvm property
2744        // so this API change wouldn't have a benifit.  It also breaks the passing
2745        // of proxy info to all the JVMs.
2746        // enforceAccessPermission();
2747        synchronized (mProxyLock) {
2748            return mGlobalProxy;
2749        }
2750    }
2751
2752    private void handleApplyDefaultProxy(ProxyInfo proxy) {
2753        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2754                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
2755            proxy = null;
2756        }
2757        synchronized (mProxyLock) {
2758            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
2759            if (mDefaultProxy == proxy) return; // catches repeated nulls
2760            if (proxy != null &&  !proxy.isValid()) {
2761                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2762                return;
2763            }
2764
2765            // This call could be coming from the PacManager, containing the port of the local
2766            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
2767            // global (to get the correct local port), and send a broadcast.
2768            // TODO: Switch PacManager to have its own message to send back rather than
2769            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
2770            if ((mGlobalProxy != null) && (proxy != null)
2771                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
2772                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2773                mGlobalProxy = proxy;
2774                sendProxyBroadcast(mGlobalProxy);
2775                return;
2776            }
2777            mDefaultProxy = proxy;
2778
2779            if (mGlobalProxy != null) return;
2780            if (!mDefaultProxyDisabled) {
2781                sendProxyBroadcast(proxy);
2782            }
2783        }
2784    }
2785
2786    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2787    // This method gets called when any network changes proxy, but the broadcast only ever contains
2788    // the default proxy (even if it hasn't changed).
2789    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2790    // world where an app might be bound to a non-default network.
2791    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2792        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2793        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2794
2795        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2796            sendProxyBroadcast(getDefaultProxy());
2797        }
2798    }
2799
2800    private void handleDeprecatedGlobalHttpProxy() {
2801        String proxy = Settings.Global.getString(mContext.getContentResolver(),
2802                Settings.Global.HTTP_PROXY);
2803        if (!TextUtils.isEmpty(proxy)) {
2804            String data[] = proxy.split(":");
2805            if (data.length == 0) {
2806                return;
2807            }
2808
2809            String proxyHost =  data[0];
2810            int proxyPort = 8080;
2811            if (data.length > 1) {
2812                try {
2813                    proxyPort = Integer.parseInt(data[1]);
2814                } catch (NumberFormatException e) {
2815                    return;
2816                }
2817            }
2818            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
2819            setGlobalProxy(p);
2820        }
2821    }
2822
2823    private void sendProxyBroadcast(ProxyInfo proxy) {
2824        if (proxy == null) proxy = new ProxyInfo("", 0, "");
2825        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
2826        if (DBG) log("sending Proxy Broadcast for " + proxy);
2827        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
2828        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2829            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
2830        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
2831        final long ident = Binder.clearCallingIdentity();
2832        try {
2833            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2834        } finally {
2835            Binder.restoreCallingIdentity(ident);
2836        }
2837    }
2838
2839    private static class SettingsObserver extends ContentObserver {
2840        private int mWhat;
2841        private Handler mHandler;
2842        SettingsObserver(Handler handler, int what) {
2843            super(handler);
2844            mHandler = handler;
2845            mWhat = what;
2846        }
2847
2848        void observe(Context context) {
2849            ContentResolver resolver = context.getContentResolver();
2850            resolver.registerContentObserver(Settings.Global.getUriFor(
2851                    Settings.Global.HTTP_PROXY), false, this);
2852        }
2853
2854        @Override
2855        public void onChange(boolean selfChange) {
2856            mHandler.obtainMessage(mWhat).sendToTarget();
2857        }
2858    }
2859
2860    private static void log(String s) {
2861        Slog.d(TAG, s);
2862    }
2863
2864    private static void loge(String s) {
2865        Slog.e(TAG, s);
2866    }
2867
2868    private static <T> T checkNotNull(T value, String message) {
2869        if (value == null) {
2870            throw new NullPointerException(message);
2871        }
2872        return value;
2873    }
2874
2875    /**
2876     * Prepare for a VPN application.
2877     * Permissions are checked in Vpn class.
2878     * @hide
2879     */
2880    @Override
2881    public boolean prepareVpn(String oldPackage, String newPackage) {
2882        throwIfLockdownEnabled();
2883        int user = UserHandle.getUserId(Binder.getCallingUid());
2884        synchronized(mVpns) {
2885            return mVpns.get(user).prepare(oldPackage, newPackage);
2886        }
2887    }
2888
2889    /**
2890     * Set whether the current VPN package has the ability to launch VPNs without
2891     * user intervention. This method is used by system-privileged apps.
2892     * Permissions are checked in Vpn class.
2893     * @hide
2894     */
2895    @Override
2896    public void setVpnPackageAuthorization(boolean authorized) {
2897        int user = UserHandle.getUserId(Binder.getCallingUid());
2898        synchronized(mVpns) {
2899            mVpns.get(user).setPackageAuthorization(authorized);
2900        }
2901    }
2902
2903    /**
2904     * Configure a TUN interface and return its file descriptor. Parameters
2905     * are encoded and opaque to this class. This method is used by VpnBuilder
2906     * and not available in ConnectivityManager. Permissions are checked in
2907     * Vpn class.
2908     * @hide
2909     */
2910    @Override
2911    public ParcelFileDescriptor establishVpn(VpnConfig config) {
2912        throwIfLockdownEnabled();
2913        int user = UserHandle.getUserId(Binder.getCallingUid());
2914        synchronized(mVpns) {
2915            return mVpns.get(user).establish(config);
2916        }
2917    }
2918
2919    /**
2920     * Start legacy VPN, controlling native daemons as needed. Creates a
2921     * secondary thread to perform connection work, returning quickly.
2922     */
2923    @Override
2924    public void startLegacyVpn(VpnProfile profile) {
2925        throwIfLockdownEnabled();
2926        final LinkProperties egress = getActiveLinkProperties();
2927        if (egress == null) {
2928            throw new IllegalStateException("Missing active network connection");
2929        }
2930        int user = UserHandle.getUserId(Binder.getCallingUid());
2931        synchronized(mVpns) {
2932            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2933        }
2934    }
2935
2936    /**
2937     * Return the information of the ongoing legacy VPN. This method is used
2938     * by VpnSettings and not available in ConnectivityManager. Permissions
2939     * are checked in Vpn class.
2940     */
2941    @Override
2942    public LegacyVpnInfo getLegacyVpnInfo() {
2943        throwIfLockdownEnabled();
2944        int user = UserHandle.getUserId(Binder.getCallingUid());
2945        synchronized(mVpns) {
2946            return mVpns.get(user).getLegacyVpnInfo();
2947        }
2948    }
2949
2950    /**
2951     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
2952     * and not available in ConnectivityManager.
2953     */
2954    @Override
2955    public VpnInfo[] getAllVpnInfo() {
2956        enforceConnectivityInternalPermission();
2957        if (mLockdownEnabled) {
2958            return new VpnInfo[0];
2959        }
2960
2961        synchronized(mVpns) {
2962            List<VpnInfo> infoList = new ArrayList<>();
2963            for (int i = 0; i < mVpns.size(); i++) {
2964                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
2965                if (info != null) {
2966                    infoList.add(info);
2967                }
2968            }
2969            return infoList.toArray(new VpnInfo[infoList.size()]);
2970        }
2971    }
2972
2973    /**
2974     * @return VPN information for accounting, or null if we can't retrieve all required
2975     *         information, e.g primary underlying iface.
2976     */
2977    @Nullable
2978    private VpnInfo createVpnInfo(Vpn vpn) {
2979        VpnInfo info = vpn.getVpnInfo();
2980        if (info == null) {
2981            return null;
2982        }
2983        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
2984        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
2985        // the underlyingNetworks list.
2986        if (underlyingNetworks == null) {
2987            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
2988            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
2989                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
2990            }
2991        } else if (underlyingNetworks.length > 0) {
2992            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
2993            if (linkProperties != null) {
2994                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
2995            }
2996        }
2997        return info.primaryUnderlyingIface == null ? null : info;
2998    }
2999
3000    /**
3001     * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3002     * not available in ConnectivityManager.
3003     * Permissions are checked in Vpn class.
3004     * @hide
3005     */
3006    @Override
3007    public VpnConfig getVpnConfig() {
3008        int user = UserHandle.getUserId(Binder.getCallingUid());
3009        synchronized(mVpns) {
3010            return mVpns.get(user).getVpnConfig();
3011        }
3012    }
3013
3014    @Override
3015    public boolean updateLockdownVpn() {
3016        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3017            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3018            return false;
3019        }
3020
3021        // Tear down existing lockdown if profile was removed
3022        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3023        if (mLockdownEnabled) {
3024            if (!mKeyStore.isUnlocked()) {
3025                Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3026                return false;
3027            }
3028
3029            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3030            final VpnProfile profile = VpnProfile.decode(
3031                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3032            int user = UserHandle.getUserId(Binder.getCallingUid());
3033            synchronized(mVpns) {
3034                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3035                            profile));
3036            }
3037        } else {
3038            setLockdownTracker(null);
3039        }
3040
3041        return true;
3042    }
3043
3044    /**
3045     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3046     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3047     */
3048    private void setLockdownTracker(LockdownVpnTracker tracker) {
3049        // Shutdown any existing tracker
3050        final LockdownVpnTracker existing = mLockdownTracker;
3051        mLockdownTracker = null;
3052        if (existing != null) {
3053            existing.shutdown();
3054        }
3055
3056        try {
3057            if (tracker != null) {
3058                mNetd.setFirewallEnabled(true);
3059                mNetd.setFirewallInterfaceRule("lo", true);
3060                mLockdownTracker = tracker;
3061                mLockdownTracker.init();
3062            } else {
3063                mNetd.setFirewallEnabled(false);
3064            }
3065        } catch (RemoteException e) {
3066            // ignored; NMS lives inside system_server
3067        }
3068    }
3069
3070    private void throwIfLockdownEnabled() {
3071        if (mLockdownEnabled) {
3072            throw new IllegalStateException("Unavailable in lockdown mode");
3073        }
3074    }
3075
3076    @Override
3077    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3078        // TODO: Remove?  Any reason to trigger a provisioning check?
3079        return -1;
3080    }
3081
3082    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3083    private volatile boolean mIsNotificationVisible = false;
3084
3085    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3086        if (DBG) {
3087            log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
3088                + " action=" + action);
3089        }
3090        Intent intent = new Intent(action);
3091        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3092        // Concatenate the range of types onto the range of NetIDs.
3093        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3094        setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
3095    }
3096
3097    /**
3098     * Show or hide network provisioning notificaitons.
3099     *
3100     * @param id an identifier that uniquely identifies this notification.  This must match
3101     *         between show and hide calls.  We use the NetID value but for legacy callers
3102     *         we concatenate the range of types with the range of NetIDs.
3103     */
3104    private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
3105            String extraInfo, PendingIntent intent) {
3106        if (DBG) {
3107            log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3108                networkType + " extraInfo=" + extraInfo);
3109        }
3110
3111        Resources r = Resources.getSystem();
3112        NotificationManager notificationManager = (NotificationManager) mContext
3113            .getSystemService(Context.NOTIFICATION_SERVICE);
3114
3115        if (visible) {
3116            CharSequence title;
3117            CharSequence details;
3118            int icon;
3119            Notification notification = new Notification();
3120            switch (networkType) {
3121                case ConnectivityManager.TYPE_WIFI:
3122                    title = r.getString(R.string.wifi_available_sign_in, 0);
3123                    details = r.getString(R.string.network_available_sign_in_detailed,
3124                            extraInfo);
3125                    icon = R.drawable.stat_notify_wifi_in_range;
3126                    break;
3127                case ConnectivityManager.TYPE_MOBILE:
3128                case ConnectivityManager.TYPE_MOBILE_HIPRI:
3129                    title = r.getString(R.string.network_available_sign_in, 0);
3130                    // TODO: Change this to pull from NetworkInfo once a printable
3131                    // name has been added to it
3132                    details = mTelephonyManager.getNetworkOperatorName();
3133                    icon = R.drawable.stat_notify_rssi_in_range;
3134                    break;
3135                default:
3136                    title = r.getString(R.string.network_available_sign_in, 0);
3137                    details = r.getString(R.string.network_available_sign_in_detailed,
3138                            extraInfo);
3139                    icon = R.drawable.stat_notify_rssi_in_range;
3140                    break;
3141            }
3142
3143            notification.when = 0;
3144            notification.icon = icon;
3145            notification.flags = Notification.FLAG_AUTO_CANCEL;
3146            notification.tickerText = title;
3147            notification.color = mContext.getColor(
3148                    com.android.internal.R.color.system_notification_accent_color);
3149            notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
3150            notification.contentIntent = intent;
3151
3152            try {
3153                notificationManager.notify(NOTIFICATION_ID, id, notification);
3154            } catch (NullPointerException npe) {
3155                loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3156                npe.printStackTrace();
3157            }
3158        } else {
3159            try {
3160                notificationManager.cancel(NOTIFICATION_ID, id);
3161            } catch (NullPointerException npe) {
3162                loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3163                npe.printStackTrace();
3164            }
3165        }
3166        mIsNotificationVisible = visible;
3167    }
3168
3169    /** Location to an updatable file listing carrier provisioning urls.
3170     *  An example:
3171     *
3172     * <?xml version="1.0" encoding="utf-8"?>
3173     *  <provisioningUrls>
3174     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3175     *   <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3176     *  </provisioningUrls>
3177     */
3178    private static final String PROVISIONING_URL_PATH =
3179            "/data/misc/radio/provisioning_urls.xml";
3180    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3181
3182    /** XML tag for root element. */
3183    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3184    /** XML tag for individual url */
3185    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3186    /** XML tag for redirected url */
3187    private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3188    /** XML attribute for mcc */
3189    private static final String ATTR_MCC = "mcc";
3190    /** XML attribute for mnc */
3191    private static final String ATTR_MNC = "mnc";
3192
3193    private static final int REDIRECTED_PROVISIONING = 1;
3194    private static final int PROVISIONING = 2;
3195
3196    private String getProvisioningUrlBaseFromFile(int type) {
3197        FileReader fileReader = null;
3198        XmlPullParser parser = null;
3199        Configuration config = mContext.getResources().getConfiguration();
3200        String tagType;
3201
3202        switch (type) {
3203            case PROVISIONING:
3204                tagType = TAG_PROVISIONING_URL;
3205                break;
3206            case REDIRECTED_PROVISIONING:
3207                tagType = TAG_REDIRECTED_URL;
3208                break;
3209            default:
3210                throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3211                        type);
3212        }
3213
3214        try {
3215            fileReader = new FileReader(mProvisioningUrlFile);
3216            parser = Xml.newPullParser();
3217            parser.setInput(fileReader);
3218            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3219
3220            while (true) {
3221                XmlUtils.nextElement(parser);
3222
3223                String element = parser.getName();
3224                if (element == null) break;
3225
3226                if (element.equals(tagType)) {
3227                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3228                    try {
3229                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3230                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3231                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3232                                parser.next();
3233                                if (parser.getEventType() == XmlPullParser.TEXT) {
3234                                    return parser.getText();
3235                                }
3236                            }
3237                        }
3238                    } catch (NumberFormatException e) {
3239                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3240                    }
3241                }
3242            }
3243            return null;
3244        } catch (FileNotFoundException e) {
3245            loge("Carrier Provisioning Urls file not found");
3246        } catch (XmlPullParserException e) {
3247            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3248        } catch (IOException e) {
3249            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3250        } finally {
3251            if (fileReader != null) {
3252                try {
3253                    fileReader.close();
3254                } catch (IOException e) {}
3255            }
3256        }
3257        return null;
3258    }
3259
3260    @Override
3261    public String getMobileRedirectedProvisioningUrl() {
3262        enforceConnectivityInternalPermission();
3263        String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3264        if (TextUtils.isEmpty(url)) {
3265            url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3266        }
3267        return url;
3268    }
3269
3270    @Override
3271    public String getMobileProvisioningUrl() {
3272        enforceConnectivityInternalPermission();
3273        String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3274        if (TextUtils.isEmpty(url)) {
3275            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3276            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3277        } else {
3278            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3279        }
3280        // populate the iccid, imei and phone number in the provisioning url.
3281        if (!TextUtils.isEmpty(url)) {
3282            String phoneNumber = mTelephonyManager.getLine1Number();
3283            if (TextUtils.isEmpty(phoneNumber)) {
3284                phoneNumber = "0000000000";
3285            }
3286            url = String.format(url,
3287                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3288                    mTelephonyManager.getDeviceId() /* IMEI */,
3289                    phoneNumber /* Phone numer */);
3290        }
3291
3292        return url;
3293    }
3294
3295    @Override
3296    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3297            String action) {
3298        enforceConnectivityInternalPermission();
3299        final long ident = Binder.clearCallingIdentity();
3300        try {
3301            setProvNotificationVisible(visible, networkType, action);
3302        } finally {
3303            Binder.restoreCallingIdentity(ident);
3304        }
3305    }
3306
3307    @Override
3308    public void setAirplaneMode(boolean enable) {
3309        enforceConnectivityInternalPermission();
3310        final long ident = Binder.clearCallingIdentity();
3311        try {
3312            final ContentResolver cr = mContext.getContentResolver();
3313            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3314            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3315            intent.putExtra("state", enable);
3316            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3317        } finally {
3318            Binder.restoreCallingIdentity(ident);
3319        }
3320    }
3321
3322    private void onUserStart(int userId) {
3323        synchronized(mVpns) {
3324            Vpn userVpn = mVpns.get(userId);
3325            if (userVpn != null) {
3326                loge("Starting user already has a VPN");
3327                return;
3328            }
3329            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3330            mVpns.put(userId, userVpn);
3331        }
3332    }
3333
3334    private void onUserStop(int userId) {
3335        synchronized(mVpns) {
3336            Vpn userVpn = mVpns.get(userId);
3337            if (userVpn == null) {
3338                loge("Stopping user has no VPN");
3339                return;
3340            }
3341            mVpns.delete(userId);
3342        }
3343    }
3344
3345    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3346        @Override
3347        public void onReceive(Context context, Intent intent) {
3348            final String action = intent.getAction();
3349            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3350            if (userId == UserHandle.USER_NULL) return;
3351
3352            if (Intent.ACTION_USER_STARTING.equals(action)) {
3353                onUserStart(userId);
3354            } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3355                onUserStop(userId);
3356            }
3357        }
3358    };
3359
3360    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3361            new HashMap<Messenger, NetworkFactoryInfo>();
3362    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3363            new HashMap<NetworkRequest, NetworkRequestInfo>();
3364
3365    private static class NetworkFactoryInfo {
3366        public final String name;
3367        public final Messenger messenger;
3368        public final AsyncChannel asyncChannel;
3369
3370        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3371            this.name = name;
3372            this.messenger = messenger;
3373            this.asyncChannel = asyncChannel;
3374        }
3375    }
3376
3377    /**
3378     * Tracks info about the requester.
3379     * Also used to notice when the calling process dies so we can self-expire
3380     */
3381    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3382        static final boolean REQUEST = true;
3383        static final boolean LISTEN = false;
3384
3385        final NetworkRequest request;
3386        final PendingIntent mPendingIntent;
3387        boolean mPendingIntentSent;
3388        private final IBinder mBinder;
3389        final int mPid;
3390        final int mUid;
3391        final Messenger messenger;
3392        final boolean isRequest;
3393
3394        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3395            request = r;
3396            mPendingIntent = pi;
3397            messenger = null;
3398            mBinder = null;
3399            mPid = getCallingPid();
3400            mUid = getCallingUid();
3401            this.isRequest = isRequest;
3402        }
3403
3404        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3405            super();
3406            messenger = m;
3407            request = r;
3408            mBinder = binder;
3409            mPid = getCallingPid();
3410            mUid = getCallingUid();
3411            this.isRequest = isRequest;
3412            mPendingIntent = null;
3413
3414            try {
3415                mBinder.linkToDeath(this, 0);
3416            } catch (RemoteException e) {
3417                binderDied();
3418            }
3419        }
3420
3421        void unlinkDeathRecipient() {
3422            if (mBinder != null) {
3423                mBinder.unlinkToDeath(this, 0);
3424            }
3425        }
3426
3427        public void binderDied() {
3428            log("ConnectivityService NetworkRequestInfo binderDied(" +
3429                    request + ", " + mBinder + ")");
3430            releaseNetworkRequest(request);
3431        }
3432
3433        public String toString() {
3434            return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
3435                    mPid + " for " + request +
3436                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3437        }
3438    }
3439
3440    @Override
3441    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3442            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3443        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3444        enforceNetworkRequestPermissions(networkCapabilities);
3445        enforceMeteredApnPolicy(networkCapabilities);
3446
3447        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3448            throw new IllegalArgumentException("Bad timeout specified");
3449        }
3450
3451        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3452                nextNetworkRequestId());
3453        if (DBG) log("requestNetwork for " + networkRequest);
3454        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3455                NetworkRequestInfo.REQUEST);
3456
3457        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
3458        if (timeoutMs > 0) {
3459            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
3460                    nri), timeoutMs);
3461        }
3462        return networkRequest;
3463    }
3464
3465    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3466        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3467                == false) {
3468            enforceConnectivityInternalPermission();
3469        } else {
3470            enforceChangePermission();
3471        }
3472    }
3473
3474    @Override
3475    public boolean requestBandwidthUpdate(Network network) {
3476        enforceAccessPermission();
3477        NetworkAgentInfo nai = null;
3478        if (network == null) {
3479            return false;
3480        }
3481        synchronized (mNetworkForNetId) {
3482            nai = mNetworkForNetId.get(network.netId);
3483        }
3484        if (nai != null) {
3485            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3486            return true;
3487        }
3488        return false;
3489    }
3490
3491
3492    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3493        // if UID is restricted, don't allow them to bring up metered APNs
3494        if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3495                == false) {
3496            final int uidRules;
3497            final int uid = Binder.getCallingUid();
3498            synchronized(mRulesLock) {
3499                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3500            }
3501            if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
3502                // we could silently fail or we can filter the available nets to only give
3503                // them those they have access to.  Chose the more useful
3504                networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3505            }
3506        }
3507    }
3508
3509    @Override
3510    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3511            PendingIntent operation) {
3512        checkNotNull(operation, "PendingIntent cannot be null.");
3513        networkCapabilities = new NetworkCapabilities(networkCapabilities);
3514        enforceNetworkRequestPermissions(networkCapabilities);
3515        enforceMeteredApnPolicy(networkCapabilities);
3516
3517        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3518                nextNetworkRequestId());
3519        if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3520        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3521                NetworkRequestInfo.REQUEST);
3522        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3523                nri));
3524        return networkRequest;
3525    }
3526
3527    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3528        mHandler.sendMessageDelayed(
3529                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3530                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3531    }
3532
3533    @Override
3534    public void releasePendingNetworkRequest(PendingIntent operation) {
3535        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3536                getCallingUid(), 0, operation));
3537    }
3538
3539    // In order to implement the compatibility measure for pre-M apps that call
3540    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3541    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3542    // This ensures it has permission to do so.
3543    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3544        if (nc == null) {
3545            return false;
3546        }
3547        int[] transportTypes = nc.getTransportTypes();
3548        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3549            return false;
3550        }
3551        try {
3552            mContext.enforceCallingOrSelfPermission(
3553                    android.Manifest.permission.ACCESS_WIFI_STATE,
3554                    "ConnectivityService");
3555        } catch (SecurityException e) {
3556            return false;
3557        }
3558        return true;
3559    }
3560
3561    @Override
3562    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3563            Messenger messenger, IBinder binder) {
3564        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3565            enforceAccessPermission();
3566        }
3567
3568        NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3569                networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3570        if (DBG) log("listenForNetwork for " + networkRequest);
3571        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3572                NetworkRequestInfo.LISTEN);
3573
3574        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3575        return networkRequest;
3576    }
3577
3578    @Override
3579    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3580            PendingIntent operation) {
3581    }
3582
3583    @Override
3584    public void releaseNetworkRequest(NetworkRequest networkRequest) {
3585        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3586                0, networkRequest));
3587    }
3588
3589    @Override
3590    public void registerNetworkFactory(Messenger messenger, String name) {
3591        enforceConnectivityInternalPermission();
3592        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3593        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
3594    }
3595
3596    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
3597        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
3598        mNetworkFactoryInfos.put(nfi.messenger, nfi);
3599        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3600    }
3601
3602    @Override
3603    public void unregisterNetworkFactory(Messenger messenger) {
3604        enforceConnectivityInternalPermission();
3605        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3606    }
3607
3608    private void handleUnregisterNetworkFactory(Messenger messenger) {
3609        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3610        if (nfi == null) {
3611            loge("Failed to find Messenger in unregisterNetworkFactory");
3612            return;
3613        }
3614        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
3615    }
3616
3617    /**
3618     * NetworkAgentInfo supporting a request by requestId.
3619     * These have already been vetted (their Capabilities satisfy the request)
3620     * and the are the highest scored network available.
3621     * the are keyed off the Requests requestId.
3622     */
3623    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
3624    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3625            new SparseArray<NetworkAgentInfo>();
3626
3627    // NOTE: Accessed on multiple threads, must be synchronized on itself.
3628    @GuardedBy("mNetworkForNetId")
3629    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3630            new SparseArray<NetworkAgentInfo>();
3631    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3632    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3633    // there may not be a strict 1:1 correlation between the two.
3634    @GuardedBy("mNetworkForNetId")
3635    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
3636
3637    // NetworkAgentInfo keyed off its connecting messenger
3638    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3639    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
3640    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3641            new HashMap<Messenger, NetworkAgentInfo>();
3642
3643    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
3644    private final NetworkRequest mDefaultRequest;
3645
3646    private NetworkAgentInfo getDefaultNetwork() {
3647        return mNetworkForRequestId.get(mDefaultRequest.requestId);
3648    }
3649
3650    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
3651        return nai == getDefaultNetwork();
3652    }
3653
3654    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3655            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
3656            int currentScore, NetworkMisc networkMisc) {
3657        enforceConnectivityInternalPermission();
3658
3659        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3660        // satisfies mDefaultRequest.
3661        NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
3662                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3663                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3664                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
3665        synchronized (this) {
3666            nai.networkMonitor.systemReady = mSystemReady;
3667        }
3668        if (DBG) log("registerNetworkAgent " + nai);
3669        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3670        return nai.network.netId;
3671    }
3672
3673    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3674        if (VDBG) log("Got NetworkAgent Messenger");
3675        mNetworkAgentInfos.put(na.messenger, na);
3676        synchronized (mNetworkForNetId) {
3677            mNetworkForNetId.put(na.network.netId, na);
3678        }
3679        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3680        NetworkInfo networkInfo = na.networkInfo;
3681        na.networkInfo = null;
3682        updateNetworkInfo(na, networkInfo);
3683    }
3684
3685    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3686        LinkProperties newLp = networkAgent.linkProperties;
3687        int netId = networkAgent.network.netId;
3688
3689        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3690        // we do anything else, make sure its LinkProperties are accurate.
3691        if (networkAgent.clatd != null) {
3692            networkAgent.clatd.fixupLinkProperties(oldLp);
3693        }
3694
3695        updateInterfaces(newLp, oldLp, netId);
3696        updateMtu(newLp, oldLp);
3697        // TODO - figure out what to do for clat
3698//        for (LinkProperties lp : newLp.getStackedLinks()) {
3699//            updateMtu(lp, null);
3700//        }
3701        updateTcpBufferSizes(networkAgent);
3702
3703        // TODO: deprecate and remove mDefaultDns when we can do so safely.
3704        // For now, use it only when the network has Internet access. http://b/18327075
3705        final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3706                NetworkCapabilities.NET_CAPABILITY_INTERNET);
3707        final boolean flushDns = updateRoutes(newLp, oldLp, netId);
3708        updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3709
3710        updateClat(newLp, oldLp, networkAgent);
3711        if (isDefaultNetwork(networkAgent)) {
3712            handleApplyDefaultProxy(newLp.getHttpProxy());
3713        } else {
3714            updateProxy(newLp, oldLp, networkAgent);
3715        }
3716        // TODO - move this check to cover the whole function
3717        if (!Objects.equals(newLp, oldLp)) {
3718            notifyIfacesChanged();
3719            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3720        }
3721    }
3722
3723    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3724        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3725        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
3726
3727        if (!wasRunningClat && shouldRunClat) {
3728            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3729            nai.clatd.start();
3730        } else if (wasRunningClat && !shouldRunClat) {
3731            nai.clatd.stop();
3732        }
3733    }
3734
3735    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3736        CompareResult<String> interfaceDiff = new CompareResult<String>();
3737        if (oldLp != null) {
3738            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3739        } else if (newLp != null) {
3740            interfaceDiff.added = newLp.getAllInterfaceNames();
3741        }
3742        for (String iface : interfaceDiff.added) {
3743            try {
3744                if (DBG) log("Adding iface " + iface + " to network " + netId);
3745                mNetd.addInterfaceToNetwork(iface, netId);
3746            } catch (Exception e) {
3747                loge("Exception adding interface: " + e);
3748            }
3749        }
3750        for (String iface : interfaceDiff.removed) {
3751            try {
3752                if (DBG) log("Removing iface " + iface + " from network " + netId);
3753                mNetd.removeInterfaceFromNetwork(iface, netId);
3754            } catch (Exception e) {
3755                loge("Exception removing interface: " + e);
3756            }
3757        }
3758    }
3759
3760    /**
3761     * Have netd update routes from oldLp to newLp.
3762     * @return true if routes changed between oldLp and newLp
3763     */
3764    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
3765        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3766        if (oldLp != null) {
3767            routeDiff = oldLp.compareAllRoutes(newLp);
3768        } else if (newLp != null) {
3769            routeDiff.added = newLp.getAllRoutes();
3770        }
3771
3772        // add routes before removing old in case it helps with continuous connectivity
3773
3774        // do this twice, adding non-nexthop routes first, then routes they are dependent on
3775        for (RouteInfo route : routeDiff.added) {
3776            if (route.hasGateway()) continue;
3777            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3778            try {
3779                mNetd.addRoute(netId, route);
3780            } catch (Exception e) {
3781                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3782                    loge("Exception in addRoute for non-gateway: " + e);
3783                }
3784            }
3785        }
3786        for (RouteInfo route : routeDiff.added) {
3787            if (route.hasGateway() == false) continue;
3788            if (DBG) log("Adding Route [" + route + "] to network " + netId);
3789            try {
3790                mNetd.addRoute(netId, route);
3791            } catch (Exception e) {
3792                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3793                    loge("Exception in addRoute for gateway: " + e);
3794                }
3795            }
3796        }
3797
3798        for (RouteInfo route : routeDiff.removed) {
3799            if (DBG) log("Removing Route [" + route + "] from network " + netId);
3800            try {
3801                mNetd.removeRoute(netId, route);
3802            } catch (Exception e) {
3803                loge("Exception in removeRoute: " + e);
3804            }
3805        }
3806        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
3807    }
3808    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3809                             boolean flush, boolean useDefaultDns) {
3810        if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
3811            Collection<InetAddress> dnses = newLp.getDnsServers();
3812            if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
3813                dnses = new ArrayList();
3814                dnses.add(mDefaultDns);
3815                if (DBG) {
3816                    loge("no dns provided for netId " + netId + ", so using defaults");
3817                }
3818            }
3819            if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
3820            try {
3821                mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3822                    newLp.getDomains());
3823            } catch (Exception e) {
3824                loge("Exception in setDnsServersForNetwork: " + e);
3825            }
3826            NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3827            if (defaultNai != null && defaultNai.network.netId == netId) {
3828                setDefaultDnsSystemProperties(dnses);
3829            }
3830            flushVmDnsCache();
3831        } else if (flush) {
3832            try {
3833                mNetd.flushNetworkDnsCache(netId);
3834            } catch (Exception e) {
3835                loge("Exception in flushNetworkDnsCache: " + e);
3836            }
3837            flushVmDnsCache();
3838        }
3839    }
3840
3841    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3842        int last = 0;
3843        for (InetAddress dns : dnses) {
3844            ++last;
3845            String key = "net.dns" + last;
3846            String value = dns.getHostAddress();
3847            SystemProperties.set(key, value);
3848        }
3849        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3850            String key = "net.dns" + i;
3851            SystemProperties.set(key, "");
3852        }
3853        mNumDnsEntries = last;
3854    }
3855
3856    private void updateCapabilities(NetworkAgentInfo networkAgent,
3857            NetworkCapabilities networkCapabilities) {
3858        if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3859            synchronized (networkAgent) {
3860                networkAgent.networkCapabilities = networkCapabilities;
3861            }
3862            rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
3863            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
3864        }
3865    }
3866
3867    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3868        for (int i = 0; i < nai.networkRequests.size(); i++) {
3869            NetworkRequest nr = nai.networkRequests.valueAt(i);
3870            // Don't send listening requests to factories. b/17393458
3871            if (!isRequest(nr)) continue;
3872            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3873        }
3874    }
3875
3876    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3877        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
3878        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
3879            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3880                    networkRequest);
3881        }
3882    }
3883
3884    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3885            int notificationType) {
3886        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
3887            Intent intent = new Intent();
3888            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3889            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
3890            nri.mPendingIntentSent = true;
3891            sendIntent(nri.mPendingIntent, intent);
3892        }
3893        // else not handled
3894    }
3895
3896    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3897        mPendingIntentWakeLock.acquire();
3898        try {
3899            if (DBG) log("Sending " + pendingIntent);
3900            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3901        } catch (PendingIntent.CanceledException e) {
3902            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3903            mPendingIntentWakeLock.release();
3904            releasePendingNetworkRequest(pendingIntent);
3905        }
3906        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3907    }
3908
3909    @Override
3910    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3911            String resultData, Bundle resultExtras) {
3912        if (DBG) log("Finished sending " + pendingIntent);
3913        mPendingIntentWakeLock.release();
3914        // Release with a delay so the receiving client has an opportunity to put in its
3915        // own request.
3916        releasePendingNetworkRequestWithDelay(pendingIntent);
3917    }
3918
3919    private void callCallbackForRequest(NetworkRequestInfo nri,
3920            NetworkAgentInfo networkAgent, int notificationType) {
3921        if (nri.messenger == null) return;  // Default request has no msgr
3922        Bundle bundle = new Bundle();
3923        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3924                new NetworkRequest(nri.request));
3925        Message msg = Message.obtain();
3926        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3927                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3928            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3929        }
3930        switch (notificationType) {
3931            case ConnectivityManager.CALLBACK_LOSING: {
3932                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3933                break;
3934            }
3935            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
3936                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
3937                        new NetworkCapabilities(networkAgent.networkCapabilities));
3938                break;
3939            }
3940            case ConnectivityManager.CALLBACK_IP_CHANGED: {
3941                bundle.putParcelable(LinkProperties.class.getSimpleName(),
3942                        new LinkProperties(networkAgent.linkProperties));
3943                break;
3944            }
3945        }
3946        msg.what = notificationType;
3947        msg.setData(bundle);
3948        try {
3949            if (VDBG) {
3950                log("sending notification " + notifyTypeToName(notificationType) +
3951                        " for " + nri.request);
3952            }
3953            nri.messenger.send(msg);
3954        } catch (RemoteException e) {
3955            // may occur naturally in the race of binder death.
3956            loge("RemoteException caught trying to send a callback msg for " + nri.request);
3957        }
3958    }
3959
3960    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
3961        for (int i = 0; i < nai.networkRequests.size(); i++) {
3962            NetworkRequest nr = nai.networkRequests.valueAt(i);
3963            // Ignore listening requests.
3964            if (!isRequest(nr)) continue;
3965            loge("Dead network still had at least " + nr);
3966            break;
3967        }
3968        nai.asyncChannel.disconnect();
3969    }
3970
3971    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
3972        if (oldNetwork == null) {
3973            loge("Unknown NetworkAgentInfo in handleLingerComplete");
3974            return;
3975        }
3976        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
3977        teardownUnneededNetwork(oldNetwork);
3978    }
3979
3980    private void makeDefault(NetworkAgentInfo newNetwork) {
3981        if (DBG) log("Switching to new default network: " + newNetwork);
3982        setupDataActivityTracking(newNetwork);
3983        try {
3984            mNetd.setDefaultNetId(newNetwork.network.netId);
3985        } catch (Exception e) {
3986            loge("Exception setting default network :" + e);
3987        }
3988        notifyLockdownVpn(newNetwork);
3989        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
3990        updateTcpBufferSizes(newNetwork);
3991        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
3992    }
3993
3994    // Handles a network appearing or improving its score.
3995    //
3996    // - Evaluates all current NetworkRequests that can be
3997    //   satisfied by newNetwork, and reassigns to newNetwork
3998    //   any such requests for which newNetwork is the best.
3999    //
4000    // - Lingers any validated Networks that as a result are no longer
4001    //   needed. A network is needed if it is the best network for
4002    //   one or more NetworkRequests, or if it is a VPN.
4003    //
4004    // - Tears down newNetwork if it just became validated
4005    //   (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4006    //
4007    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4008    //   networks that have no chance (i.e. even if validated)
4009    //   of becoming the highest scoring network.
4010    //
4011    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4012    // it does not remove NetworkRequests that other Networks could better satisfy.
4013    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4014    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4015    // as it performs better by a factor of the number of Networks.
4016    //
4017    // @param newNetwork is the network to be matched against NetworkRequests.
4018    // @param nascent indicates if newNetwork just became validated, in which case it should be
4019    //               torn down if unneeded.
4020    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4021    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4022    //               validated) of becoming the highest scoring network.
4023    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4024            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4025        if (!newNetwork.created) return;
4026        if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
4027            loge("ERROR: nascent network not validated.");
4028        }
4029        boolean keep = newNetwork.isVPN();
4030        boolean isNewDefault = false;
4031        NetworkAgentInfo oldDefaultNetwork = null;
4032        if (DBG) log("rematching " + newNetwork.name());
4033        // Find and migrate to this Network any NetworkRequests for
4034        // which this network is now the best.
4035        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4036        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4037        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4038            NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4039            if (newNetwork == currentNetwork) {
4040                if (DBG) {
4041                    log("Network " + newNetwork.name() + " was already satisfying" +
4042                            " request " + nri.request.requestId + ". No change.");
4043                }
4044                keep = true;
4045                continue;
4046            }
4047
4048            // check if it satisfies the NetworkCapabilities
4049            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4050            if (newNetwork.satisfies(nri.request)) {
4051                if (!nri.isRequest) {
4052                    // This is not a request, it's a callback listener.
4053                    // Add it to newNetwork regardless of score.
4054                    newNetwork.addRequest(nri.request);
4055                    continue;
4056                }
4057
4058                // next check if it's better than any current network we're using for
4059                // this request
4060                if (VDBG) {
4061                    log("currentScore = " +
4062                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4063                            ", newScore = " + newNetwork.getCurrentScore());
4064                }
4065                if (currentNetwork == null ||
4066                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4067                    if (currentNetwork != null) {
4068                        if (DBG) log("   accepting network in place of " + currentNetwork.name());
4069                        currentNetwork.networkRequests.remove(nri.request.requestId);
4070                        currentNetwork.networkLingered.add(nri.request);
4071                        affectedNetworks.add(currentNetwork);
4072                    } else {
4073                        if (DBG) log("   accepting network in place of null");
4074                    }
4075                    unlinger(newNetwork);
4076                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4077                    newNetwork.addRequest(nri.request);
4078                    keep = true;
4079                    // Tell NetworkFactories about the new score, so they can stop
4080                    // trying to connect if they know they cannot match it.
4081                    // TODO - this could get expensive if we have alot of requests for this
4082                    // network.  Think about if there is a way to reduce this.  Push
4083                    // netid->request mapping to each factory?
4084                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4085                    if (mDefaultRequest.requestId == nri.request.requestId) {
4086                        isNewDefault = true;
4087                        oldDefaultNetwork = currentNetwork;
4088                    }
4089                }
4090            }
4091        }
4092        // Linger any networks that are no longer needed.
4093        for (NetworkAgentInfo nai : affectedNetworks) {
4094            if (nai.everValidated && unneeded(nai)) {
4095                nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4096                notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4097            } else {
4098                unlinger(nai);
4099            }
4100        }
4101        if (keep) {
4102            if (isNewDefault) {
4103                // Notify system services that this network is up.
4104                makeDefault(newNetwork);
4105                synchronized (ConnectivityService.this) {
4106                    // have a new default network, release the transition wakelock in
4107                    // a second if it's held.  The second pause is to allow apps
4108                    // to reconnect over the new network
4109                    if (mNetTransitionWakeLock.isHeld()) {
4110                        mHandler.sendMessageDelayed(mHandler.obtainMessage(
4111                                EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4112                                mNetTransitionWakeLockSerialNumber, 0),
4113                                1000);
4114                    }
4115                }
4116            }
4117
4118            // do this after the default net is switched, but
4119            // before LegacyTypeTracker sends legacy broadcasts
4120            notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4121
4122            if (isNewDefault) {
4123                // Maintain the illusion: since the legacy API only
4124                // understands one network at a time, we must pretend
4125                // that the current default network disconnected before
4126                // the new one connected.
4127                if (oldDefaultNetwork != null) {
4128                    mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4129                                              oldDefaultNetwork);
4130                }
4131                mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
4132                mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4133                notifyLockdownVpn(newNetwork);
4134            }
4135
4136            // Notify battery stats service about this network, both the normal
4137            // interface and any stacked links.
4138            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4139            try {
4140                final IBatteryStats bs = BatteryStatsService.getService();
4141                final int type = newNetwork.networkInfo.getType();
4142
4143                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4144                bs.noteNetworkInterfaceType(baseIface, type);
4145                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4146                    final String stackedIface = stacked.getInterfaceName();
4147                    bs.noteNetworkInterfaceType(stackedIface, type);
4148                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4149                }
4150            } catch (RemoteException ignored) {
4151            }
4152
4153            // This has to happen after the notifyNetworkCallbacks as that tickles each
4154            // ConnectivityManager instance so that legacy requests correctly bind dns
4155            // requests to this network.  The legacy users are listening for this bcast
4156            // and will generally do a dns request so they can ensureRouteToHost and if
4157            // they do that before the callbacks happen they'll use the default network.
4158            //
4159            // TODO: Is there still a race here? We send the broadcast
4160            // after sending the callback, but if the app can receive the
4161            // broadcast before the callback, it might still break.
4162            //
4163            // This *does* introduce a race where if the user uses the new api
4164            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4165            // they may get old info.  Reverse this after the old startUsing api is removed.
4166            // This is on top of the multiple intent sequencing referenced in the todo above.
4167            for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4168                NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4169                if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4170                    // legacy type tracker filters out repeat adds
4171                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4172                }
4173            }
4174
4175            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4176            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4177            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4178            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4179            if (newNetwork.isVPN()) {
4180                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4181            }
4182        } else if (nascent == NascentState.JUST_VALIDATED) {
4183            // Only tear down newly validated networks here.  Leave unvalidated to either become
4184            // validated (and get evaluated against peers, one losing here), or get reaped (see
4185            // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4186            // network.  Networks that have been up for a while and are validated should be torn
4187            // down via the lingering process so communication on that network is given time to
4188            // wrap up.
4189            if (DBG) log("Validated network turns out to be unwanted.  Tear it down.");
4190            teardownUnneededNetwork(newNetwork);
4191        }
4192        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4193            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4194                if (!nai.everValidated && unneeded(nai)) {
4195                    if (DBG) log("Reaping " + nai.name());
4196                    teardownUnneededNetwork(nai);
4197                }
4198            }
4199        }
4200    }
4201
4202    // Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4203    // being disconnected.
4204    // If only one Network's score or capabilities have been modified since the last time
4205    // this function was called, pass this Network in via the "changed" arugment, otherwise
4206    // pass null.
4207    // If only one Network has been changed but its NetworkCapabilities have not changed,
4208    // pass in the Network's score (from getCurrentScore()) prior to the change via
4209    // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4210    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4211        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4212        // to avoid the slowness.  It is not simply enough to process just "changed", for
4213        // example in the case where "changed"'s score decreases and another network should begin
4214        // satifying a NetworkRequest that "changed" currently satisfies.
4215
4216        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4217        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4218        // rematchNetworkAndRequests() handles.
4219        if (changed != null && oldScore < changed.getCurrentScore()) {
4220            rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4221                    ReapUnvalidatedNetworks.REAP);
4222        } else {
4223            for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4224                rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4225                        NascentState.NOT_JUST_VALIDATED,
4226                        // Only reap the last time through the loop.  Reaping before all rematching
4227                        // is complete could incorrectly teardown a network that hasn't yet been
4228                        // rematched.
4229                        i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4230                                : ReapUnvalidatedNetworks.REAP);
4231            }
4232        }
4233    }
4234
4235    private void updateInetCondition(NetworkAgentInfo nai) {
4236        // Don't bother updating until we've graduated to validated at least once.
4237        if (!nai.everValidated) return;
4238        // For now only update icons for default connection.
4239        // TODO: Update WiFi and cellular icons separately. b/17237507
4240        if (!isDefaultNetwork(nai)) return;
4241
4242        int newInetCondition = nai.lastValidated ? 100 : 0;
4243        // Don't repeat publish.
4244        if (newInetCondition == mDefaultInetConditionPublished) return;
4245
4246        mDefaultInetConditionPublished = newInetCondition;
4247        sendInetConditionBroadcast(nai.networkInfo);
4248    }
4249
4250    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4251        if (mLockdownTracker != null) {
4252            if (nai != null && nai.isVPN()) {
4253                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4254            } else {
4255                mLockdownTracker.onNetworkInfoChanged();
4256            }
4257        }
4258    }
4259
4260    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4261        NetworkInfo.State state = newInfo.getState();
4262        NetworkInfo oldInfo = null;
4263        synchronized (networkAgent) {
4264            oldInfo = networkAgent.networkInfo;
4265            networkAgent.networkInfo = newInfo;
4266        }
4267        notifyLockdownVpn(networkAgent);
4268
4269        if (oldInfo != null && oldInfo.getState() == state) {
4270            if (VDBG) log("ignoring duplicate network state non-change");
4271            return;
4272        }
4273        if (DBG) {
4274            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4275                    (oldInfo == null ? "null" : oldInfo.getState()) +
4276                    " to " + state);
4277        }
4278
4279        if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
4280            try {
4281                // This should never fail.  Specifying an already in use NetID will cause failure.
4282                if (networkAgent.isVPN()) {
4283                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4284                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4285                            (networkAgent.networkMisc == null ||
4286                                !networkAgent.networkMisc.allowBypass));
4287                } else {
4288                    mNetd.createPhysicalNetwork(networkAgent.network.netId);
4289                }
4290            } catch (Exception e) {
4291                loge("Error creating network " + networkAgent.network.netId + ": "
4292                        + e.getMessage());
4293                return;
4294            }
4295            networkAgent.created = true;
4296            updateLinkProperties(networkAgent, null);
4297            notifyIfacesChanged();
4298
4299            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4300            scheduleUnvalidatedPrompt(networkAgent);
4301
4302            if (networkAgent.isVPN()) {
4303                // Temporarily disable the default proxy (not global).
4304                synchronized (mProxyLock) {
4305                    if (!mDefaultProxyDisabled) {
4306                        mDefaultProxyDisabled = true;
4307                        if (mGlobalProxy == null && mDefaultProxy != null) {
4308                            sendProxyBroadcast(null);
4309                        }
4310                    }
4311                }
4312                // TODO: support proxy per network.
4313            }
4314
4315            // Consider network even though it is not yet validated.
4316            rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4317                    ReapUnvalidatedNetworks.REAP);
4318
4319            // This has to happen after matching the requests, because callbacks are just requests.
4320            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4321        } else if (state == NetworkInfo.State.DISCONNECTED ||
4322                state == NetworkInfo.State.SUSPENDED) {
4323            networkAgent.asyncChannel.disconnect();
4324            if (networkAgent.isVPN()) {
4325                synchronized (mProxyLock) {
4326                    if (mDefaultProxyDisabled) {
4327                        mDefaultProxyDisabled = false;
4328                        if (mGlobalProxy == null && mDefaultProxy != null) {
4329                            sendProxyBroadcast(mDefaultProxy);
4330                        }
4331                    }
4332                }
4333            }
4334        }
4335    }
4336
4337    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4338        if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4339        if (score < 0) {
4340            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4341                    ").  Bumping score to min of 0");
4342            score = 0;
4343        }
4344
4345        final int oldScore = nai.getCurrentScore();
4346        nai.setCurrentScore(score);
4347
4348        rematchAllNetworksAndRequests(nai, oldScore);
4349
4350        sendUpdatedScoreToFactories(nai);
4351    }
4352
4353    // notify only this one new request of the current state
4354    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4355        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4356        // TODO - read state from monitor to decide what to send.
4357//        if (nai.networkMonitor.isLingering()) {
4358//            notifyType = NetworkCallbacks.LOSING;
4359//        } else if (nai.networkMonitor.isEvaluating()) {
4360//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4361//        }
4362        if (nri.mPendingIntent == null) {
4363            callCallbackForRequest(nri, nai, notifyType);
4364        } else {
4365            sendPendingIntentForRequest(nri, nai, notifyType);
4366        }
4367    }
4368
4369    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
4370        // The NetworkInfo we actually send out has no bearing on the real
4371        // state of affairs. For example, if the default connection is mobile,
4372        // and a request for HIPRI has just gone away, we need to pretend that
4373        // HIPRI has just disconnected. So we need to set the type to HIPRI and
4374        // the state to DISCONNECTED, even though the network is of type MOBILE
4375        // and is still connected.
4376        NetworkInfo info = new NetworkInfo(nai.networkInfo);
4377        info.setType(type);
4378        if (connected) {
4379            info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
4380            sendConnectedBroadcast(info);
4381        } else {
4382            info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
4383            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4384            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4385            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4386            if (info.isFailover()) {
4387                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4388                nai.networkInfo.setFailover(false);
4389            }
4390            if (info.getReason() != null) {
4391                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4392            }
4393            if (info.getExtraInfo() != null) {
4394                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4395            }
4396            NetworkAgentInfo newDefaultAgent = null;
4397            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4398                newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4399                if (newDefaultAgent != null) {
4400                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4401                            newDefaultAgent.networkInfo);
4402                } else {
4403                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4404                }
4405            }
4406            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4407                    mDefaultInetConditionPublished);
4408            sendStickyBroadcast(intent);
4409            if (newDefaultAgent != null) {
4410                sendConnectedBroadcast(newDefaultAgent.networkInfo);
4411            }
4412        }
4413    }
4414
4415    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
4416        if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
4417        for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
4418            NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4419            NetworkRequestInfo nri = mNetworkRequests.get(nr);
4420            if (VDBG) log(" sending notification for " + nr);
4421            if (nri.mPendingIntent == null) {
4422                callCallbackForRequest(nri, networkAgent, notifyType);
4423            } else {
4424                sendPendingIntentForRequest(nri, networkAgent, notifyType);
4425            }
4426        }
4427    }
4428
4429    private String notifyTypeToName(int notifyType) {
4430        switch (notifyType) {
4431            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
4432            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
4433            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
4434            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
4435            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
4436            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4437            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
4438            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
4439        }
4440        return "UNKNOWN";
4441    }
4442
4443    /**
4444     * Notify other system services that set of active ifaces has changed.
4445     */
4446    private void notifyIfacesChanged() {
4447        try {
4448            mStatsService.forceUpdateIfaces();
4449        } catch (Exception ignored) {
4450        }
4451    }
4452
4453    @Override
4454    public boolean addVpnAddress(String address, int prefixLength) {
4455        throwIfLockdownEnabled();
4456        int user = UserHandle.getUserId(Binder.getCallingUid());
4457        synchronized (mVpns) {
4458            return mVpns.get(user).addAddress(address, prefixLength);
4459        }
4460    }
4461
4462    @Override
4463    public boolean removeVpnAddress(String address, int prefixLength) {
4464        throwIfLockdownEnabled();
4465        int user = UserHandle.getUserId(Binder.getCallingUid());
4466        synchronized (mVpns) {
4467            return mVpns.get(user).removeAddress(address, prefixLength);
4468        }
4469    }
4470
4471    @Override
4472    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4473        throwIfLockdownEnabled();
4474        int user = UserHandle.getUserId(Binder.getCallingUid());
4475        boolean success;
4476        synchronized (mVpns) {
4477            success = mVpns.get(user).setUnderlyingNetworks(networks);
4478        }
4479        if (success) {
4480            notifyIfacesChanged();
4481        }
4482        return success;
4483    }
4484
4485    @Override
4486    public void factoryReset() {
4487        enforceConnectivityInternalPermission();
4488        // Turn airplane mode off
4489        setAirplaneMode(false);
4490
4491        // Untether
4492        for (String tether : getTetheredIfaces()) {
4493            untether(tether);
4494        }
4495
4496        // Turn VPN off
4497        VpnConfig vpnConfig = getVpnConfig();
4498        if (vpnConfig != null) {
4499            if (vpnConfig.legacy) {
4500                prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN);
4501            } else {
4502                // Prevent this app from initiating VPN connections in the future without
4503                // user intervention.
4504                setVpnPackageAuthorization(false);
4505
4506                prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN);
4507            }
4508        }
4509    }
4510}
4511