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