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