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