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