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