ConnectivityService.java revision 446598c083162d489a5a4576e7958ae87b900870
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                boolean wasKept = false;
2449                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2450                if (nai != null) {
2451                    nai.removeRequest(nri.request.requestId);
2452                    if (VDBG) {
2453                        log(" Removing from current network " + nai.name() +
2454                                ", leaving " + nai.numNetworkRequests() + " requests.");
2455                    }
2456                    if (unneeded(nai)) {
2457                        if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2458                        teardownUnneededNetwork(nai);
2459                    } else {
2460                        wasKept = true;
2461                    }
2462                    mNetworkForRequestId.remove(nri.request.requestId);
2463                }
2464
2465                // TODO: remove this code once we know that the Slog.wtf is never hit.
2466                //
2467                // Find all networks that are satisfying this request and remove the request
2468                // from their request lists.
2469                // TODO - it's my understanding that for a request there is only a single
2470                // network satisfying it, so this loop is wasteful
2471                for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2472                    if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2473                        Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2474                                otherNai.name() + ", but mNetworkAgentInfos says " +
2475                                (nai != null ? nai.name() : "null"));
2476                    }
2477                }
2478
2479                // Maintain the illusion.  When this request arrived, we might have pretended
2480                // that a network connected to serve it, even though the network was already
2481                // connected.  Now that this request has gone away, we might have to pretend
2482                // that the network disconnected.  LegacyTypeTracker will generate that
2483                // phantom disconnect for this type.
2484                if (nri.request.legacyType != TYPE_NONE && nai != null) {
2485                    boolean doRemove = true;
2486                    if (wasKept) {
2487                        // check if any of the remaining requests for this network are for the
2488                        // same legacy type - if so, don't remove the nai
2489                        for (int i = 0; i < nai.numNetworkRequests(); i++) {
2490                            NetworkRequest otherRequest = nai.requestAt(i);
2491                            if (otherRequest.legacyType == nri.request.legacyType &&
2492                                    otherRequest.isRequest()) {
2493                                if (DBG) log(" still have other legacy request - leaving");
2494                                doRemove = false;
2495                            }
2496                        }
2497                    }
2498
2499                    if (doRemove) {
2500                        mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
2501                    }
2502                }
2503
2504                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2505                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2506                            nri.request);
2507                }
2508            } else {
2509                // listens don't have a singular affectedNetwork.  Check all networks to see
2510                // if this listen request applies and remove it.
2511                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2512                    nai.removeRequest(nri.request.requestId);
2513                    if (nri.request.networkCapabilities.hasSignalStrength() &&
2514                            nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2515                        updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2516                    }
2517                }
2518            }
2519            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2520        }
2521    }
2522
2523    @Override
2524    public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2525        enforceConnectivityInternalPermission();
2526        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2527                accept ? 1 : 0, always ? 1: 0, network));
2528    }
2529
2530    private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2531        if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2532                " accept=" + accept + " always=" + always);
2533
2534        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2535        if (nai == null) {
2536            // Nothing to do.
2537            return;
2538        }
2539
2540        if (nai.everValidated) {
2541            // The network validated while the dialog box was up. Take no action.
2542            return;
2543        }
2544
2545        if (!nai.networkMisc.explicitlySelected) {
2546            Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2547        }
2548
2549        if (accept != nai.networkMisc.acceptUnvalidated) {
2550            int oldScore = nai.getCurrentScore();
2551            nai.networkMisc.acceptUnvalidated = accept;
2552            rematchAllNetworksAndRequests(nai, oldScore);
2553            sendUpdatedScoreToFactories(nai);
2554        }
2555
2556        if (always) {
2557            nai.asyncChannel.sendMessage(
2558                    NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2559        }
2560
2561        if (!accept) {
2562            // Tell the NetworkAgent to not automatically reconnect to the network.
2563            nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2564            // Teardown the nework.
2565            teardownUnneededNetwork(nai);
2566        }
2567
2568    }
2569
2570    private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2571        if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
2572        mHandler.sendMessageDelayed(
2573                mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2574                PROMPT_UNVALIDATED_DELAY_MS);
2575    }
2576
2577    private void handlePromptUnvalidated(Network network) {
2578        if (VDBG) log("handlePromptUnvalidated " + network);
2579        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2580
2581        // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2582        // we haven't already been told to switch to it regardless of whether it validated or not.
2583        // Also don't prompt on captive portals because we're already prompting the user to sign in.
2584        if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
2585                !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2586            return;
2587        }
2588
2589        Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2590        intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
2591        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2592        intent.setClassName("com.android.settings",
2593                "com.android.settings.wifi.WifiNoInternetDialog");
2594
2595        PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2596                mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2597
2598        setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
2599                nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
2600    }
2601
2602    private class InternalHandler extends Handler {
2603        public InternalHandler(Looper looper) {
2604            super(looper);
2605        }
2606
2607        @Override
2608        public void handleMessage(Message msg) {
2609            switch (msg.what) {
2610                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2611                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2612                    String causedBy = null;
2613                    synchronized (ConnectivityService.this) {
2614                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2615                                mNetTransitionWakeLock.isHeld()) {
2616                            mNetTransitionWakeLock.release();
2617                            causedBy = mNetTransitionWakeLockCausedBy;
2618                        } else {
2619                            break;
2620                        }
2621                    }
2622                    if (VDBG) {
2623                        if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2624                            log("Failed to find a new network - expiring NetTransition Wakelock");
2625                        } else {
2626                            log("NetTransition Wakelock (" +
2627                                    (causedBy == null ? "unknown" : causedBy) +
2628                                    " cleared because we found a replacement network");
2629                        }
2630                    }
2631                    break;
2632                }
2633                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2634                    handleDeprecatedGlobalHttpProxy();
2635                    break;
2636                }
2637                case EVENT_PROXY_HAS_CHANGED: {
2638                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2639                    break;
2640                }
2641                case EVENT_REGISTER_NETWORK_FACTORY: {
2642                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2643                    break;
2644                }
2645                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2646                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2647                    break;
2648                }
2649                case EVENT_REGISTER_NETWORK_AGENT: {
2650                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2651                    break;
2652                }
2653                case EVENT_REGISTER_NETWORK_REQUEST:
2654                case EVENT_REGISTER_NETWORK_LISTENER: {
2655                    handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
2656                    break;
2657                }
2658                case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2659                case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
2660                    handleRegisterNetworkRequestWithIntent(msg);
2661                    break;
2662                }
2663                case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2664                    handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2665                    break;
2666                }
2667                case EVENT_RELEASE_NETWORK_REQUEST: {
2668                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2669                    break;
2670                }
2671                case EVENT_SET_ACCEPT_UNVALIDATED: {
2672                    handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2673                    break;
2674                }
2675                case EVENT_PROMPT_UNVALIDATED: {
2676                    handlePromptUnvalidated((Network) msg.obj);
2677                    break;
2678                }
2679                case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2680                    handleMobileDataAlwaysOn();
2681                    break;
2682                }
2683                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2684                case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2685                    mKeepaliveTracker.handleStartKeepalive(msg);
2686                    break;
2687                }
2688                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2689                case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2690                    NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2691                    int slot = msg.arg1;
2692                    int reason = msg.arg2;
2693                    mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2694                    break;
2695                }
2696                case EVENT_SYSTEM_READY: {
2697                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2698                        nai.networkMonitor.systemReady = true;
2699                    }
2700                    break;
2701                }
2702            }
2703        }
2704    }
2705
2706    // javadoc from interface
2707    @Override
2708    public int tether(String iface) {
2709        ConnectivityManager.enforceTetherChangePermission(mContext);
2710        if (isTetheringSupported()) {
2711            final int status = mTethering.tether(iface);
2712            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2713                try {
2714                    mPolicyManager.onTetheringChanged(iface, true);
2715                } catch (RemoteException e) {
2716                }
2717            }
2718            return status;
2719        } else {
2720            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2721        }
2722    }
2723
2724    // javadoc from interface
2725    @Override
2726    public int untether(String iface) {
2727        ConnectivityManager.enforceTetherChangePermission(mContext);
2728
2729        if (isTetheringSupported()) {
2730            final int status = mTethering.untether(iface);
2731            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2732                try {
2733                    mPolicyManager.onTetheringChanged(iface, false);
2734                } catch (RemoteException e) {
2735                }
2736            }
2737            return status;
2738        } else {
2739            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2740        }
2741    }
2742
2743    // javadoc from interface
2744    @Override
2745    public int getLastTetherError(String iface) {
2746        enforceTetherAccessPermission();
2747
2748        if (isTetheringSupported()) {
2749            return mTethering.getLastTetherError(iface);
2750        } else {
2751            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2752        }
2753    }
2754
2755    // TODO - proper iface API for selection by property, inspection, etc
2756    @Override
2757    public String[] getTetherableUsbRegexs() {
2758        enforceTetherAccessPermission();
2759        if (isTetheringSupported()) {
2760            return mTethering.getTetherableUsbRegexs();
2761        } else {
2762            return new String[0];
2763        }
2764    }
2765
2766    @Override
2767    public String[] getTetherableWifiRegexs() {
2768        enforceTetherAccessPermission();
2769        if (isTetheringSupported()) {
2770            return mTethering.getTetherableWifiRegexs();
2771        } else {
2772            return new String[0];
2773        }
2774    }
2775
2776    @Override
2777    public String[] getTetherableBluetoothRegexs() {
2778        enforceTetherAccessPermission();
2779        if (isTetheringSupported()) {
2780            return mTethering.getTetherableBluetoothRegexs();
2781        } else {
2782            return new String[0];
2783        }
2784    }
2785
2786    @Override
2787    public int setUsbTethering(boolean enable) {
2788        ConnectivityManager.enforceTetherChangePermission(mContext);
2789        if (isTetheringSupported()) {
2790            return mTethering.setUsbTethering(enable);
2791        } else {
2792            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2793        }
2794    }
2795
2796    // TODO - move iface listing, queries, etc to new module
2797    // javadoc from interface
2798    @Override
2799    public String[] getTetherableIfaces() {
2800        enforceTetherAccessPermission();
2801        return mTethering.getTetherableIfaces();
2802    }
2803
2804    @Override
2805    public String[] getTetheredIfaces() {
2806        enforceTetherAccessPermission();
2807        return mTethering.getTetheredIfaces();
2808    }
2809
2810    @Override
2811    public String[] getTetheringErroredIfaces() {
2812        enforceTetherAccessPermission();
2813        return mTethering.getErroredIfaces();
2814    }
2815
2816    @Override
2817    public String[] getTetheredDhcpRanges() {
2818        enforceConnectivityInternalPermission();
2819        return mTethering.getTetheredDhcpRanges();
2820    }
2821
2822    // if ro.tether.denied = true we default to no tethering
2823    // gservices could set the secure setting to 1 though to enable it on a build where it
2824    // had previously been turned off.
2825    @Override
2826    public boolean isTetheringSupported() {
2827        enforceTetherAccessPermission();
2828        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2829        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2830                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2831                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2832        return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2833                ((mTethering.getTetherableUsbRegexs().length != 0 ||
2834                mTethering.getTetherableWifiRegexs().length != 0 ||
2835                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2836                mTethering.getUpstreamIfaceTypes().length != 0);
2837    }
2838
2839    @Override
2840    public void startTethering(int type, ResultReceiver receiver,
2841            boolean showProvisioningUi) {
2842        ConnectivityManager.enforceTetherChangePermission(mContext);
2843        if (!isTetheringSupported()) {
2844            receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2845            return;
2846        }
2847        mTethering.startTethering(type, receiver, showProvisioningUi);
2848    }
2849
2850    @Override
2851    public void stopTethering(int type) {
2852        ConnectivityManager.enforceTetherChangePermission(mContext);
2853        mTethering.stopTethering(type);
2854    }
2855
2856    // Called when we lose the default network and have no replacement yet.
2857    // This will automatically be cleared after X seconds or a new default network
2858    // becomes CONNECTED, whichever happens first.  The timer is started by the
2859    // first caller and not restarted by subsequent callers.
2860    private void requestNetworkTransitionWakelock(String forWhom) {
2861        int serialNum = 0;
2862        synchronized (this) {
2863            if (mNetTransitionWakeLock.isHeld()) return;
2864            serialNum = ++mNetTransitionWakeLockSerialNumber;
2865            mNetTransitionWakeLock.acquire();
2866            mNetTransitionWakeLockCausedBy = forWhom;
2867        }
2868        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2869                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2870                mNetTransitionWakeLockTimeout);
2871        return;
2872    }
2873
2874    // 100 percent is full good, 0 is full bad.
2875    @Override
2876    public void reportInetCondition(int networkType, int percentage) {
2877        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2878        if (nai == null) return;
2879        reportNetworkConnectivity(nai.network, percentage > 50);
2880    }
2881
2882    @Override
2883    public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2884        enforceAccessPermission();
2885        enforceInternetPermission();
2886
2887        NetworkAgentInfo nai;
2888        if (network == null) {
2889            nai = getDefaultNetwork();
2890        } else {
2891            nai = getNetworkAgentInfoForNetwork(network);
2892        }
2893        if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2894            nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2895            return;
2896        }
2897        // Revalidate if the app report does not match our current validated state.
2898        if (hasConnectivity == nai.lastValidated) return;
2899        final int uid = Binder.getCallingUid();
2900        if (DBG) {
2901            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2902                    ") by " + uid);
2903        }
2904        synchronized (nai) {
2905            // Validating a network that has not yet connected could result in a call to
2906            // rematchNetworkAndRequests() which is not meant to work on such networks.
2907            if (!nai.everConnected) return;
2908
2909            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
2910
2911            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2912        }
2913    }
2914
2915    private ProxyInfo getDefaultProxy() {
2916        // this information is already available as a world read/writable jvm property
2917        // so this API change wouldn't have a benifit.  It also breaks the passing
2918        // of proxy info to all the JVMs.
2919        // enforceAccessPermission();
2920        synchronized (mProxyLock) {
2921            ProxyInfo ret = mGlobalProxy;
2922            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2923            return ret;
2924        }
2925    }
2926
2927    @Override
2928    public ProxyInfo getProxyForNetwork(Network network) {
2929        if (network == null) return getDefaultProxy();
2930        final ProxyInfo globalProxy = getGlobalProxy();
2931        if (globalProxy != null) return globalProxy;
2932        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2933        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2934        // caller may not have.
2935        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2936        if (nai == null) return null;
2937        synchronized (nai) {
2938            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2939            if (proxyInfo == null) return null;
2940            return new ProxyInfo(proxyInfo);
2941        }
2942    }
2943
2944    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2945    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2946    // proxy is null then there is no proxy in place).
2947    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2948        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2949                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2950            proxy = null;
2951        }
2952        return proxy;
2953    }
2954
2955    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2956    // better for determining if a new proxy broadcast is necessary:
2957    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2958    //    avoid unnecessary broadcasts.
2959    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2960    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2961    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2962    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2963    //    all set.
2964    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2965        a = canonicalizeProxyInfo(a);
2966        b = canonicalizeProxyInfo(b);
2967        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2968        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2969        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2970    }
2971
2972    public void setGlobalProxy(ProxyInfo proxyProperties) {
2973        enforceConnectivityInternalPermission();
2974
2975        synchronized (mProxyLock) {
2976            if (proxyProperties == mGlobalProxy) return;
2977            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2978            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2979
2980            String host = "";
2981            int port = 0;
2982            String exclList = "";
2983            String pacFileUrl = "";
2984            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2985                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2986                if (!proxyProperties.isValid()) {
2987                    if (DBG)
2988                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2989                    return;
2990                }
2991                mGlobalProxy = new ProxyInfo(proxyProperties);
2992                host = mGlobalProxy.getHost();
2993                port = mGlobalProxy.getPort();
2994                exclList = mGlobalProxy.getExclusionListAsString();
2995                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2996                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2997                }
2998            } else {
2999                mGlobalProxy = null;
3000            }
3001            ContentResolver res = mContext.getContentResolver();
3002            final long token = Binder.clearCallingIdentity();
3003            try {
3004                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3005                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3006                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3007                        exclList);
3008                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
3009            } finally {
3010                Binder.restoreCallingIdentity(token);
3011            }
3012
3013            if (mGlobalProxy == null) {
3014                proxyProperties = mDefaultProxy;
3015            }
3016            sendProxyBroadcast(proxyProperties);
3017        }
3018    }
3019
3020    private void loadGlobalProxy() {
3021        ContentResolver res = mContext.getContentResolver();
3022        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3023        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3024        String exclList = Settings.Global.getString(res,
3025                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
3026        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3027        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
3028            ProxyInfo proxyProperties;
3029            if (!TextUtils.isEmpty(pacFileUrl)) {
3030                proxyProperties = new ProxyInfo(pacFileUrl);
3031            } else {
3032                proxyProperties = new ProxyInfo(host, port, exclList);
3033            }
3034            if (!proxyProperties.isValid()) {
3035                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3036                return;
3037            }
3038
3039            synchronized (mProxyLock) {
3040                mGlobalProxy = proxyProperties;
3041            }
3042        }
3043    }
3044
3045    public ProxyInfo getGlobalProxy() {
3046        // this information is already available as a world read/writable jvm property
3047        // so this API change wouldn't have a benifit.  It also breaks the passing
3048        // of proxy info to all the JVMs.
3049        // enforceAccessPermission();
3050        synchronized (mProxyLock) {
3051            return mGlobalProxy;
3052        }
3053    }
3054
3055    private void handleApplyDefaultProxy(ProxyInfo proxy) {
3056        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3057                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
3058            proxy = null;
3059        }
3060        synchronized (mProxyLock) {
3061            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3062            if (mDefaultProxy == proxy) return; // catches repeated nulls
3063            if (proxy != null &&  !proxy.isValid()) {
3064                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3065                return;
3066            }
3067
3068            // This call could be coming from the PacManager, containing the port of the local
3069            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
3070            // global (to get the correct local port), and send a broadcast.
3071            // TODO: Switch PacManager to have its own message to send back rather than
3072            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
3073            if ((mGlobalProxy != null) && (proxy != null)
3074                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
3075                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3076                mGlobalProxy = proxy;
3077                sendProxyBroadcast(mGlobalProxy);
3078                return;
3079            }
3080            mDefaultProxy = proxy;
3081
3082            if (mGlobalProxy != null) return;
3083            if (!mDefaultProxyDisabled) {
3084                sendProxyBroadcast(proxy);
3085            }
3086        }
3087    }
3088
3089    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3090    // This method gets called when any network changes proxy, but the broadcast only ever contains
3091    // the default proxy (even if it hasn't changed).
3092    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3093    // world where an app might be bound to a non-default network.
3094    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3095        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3096        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3097
3098        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3099            sendProxyBroadcast(getDefaultProxy());
3100        }
3101    }
3102
3103    private void handleDeprecatedGlobalHttpProxy() {
3104        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3105                Settings.Global.HTTP_PROXY);
3106        if (!TextUtils.isEmpty(proxy)) {
3107            String data[] = proxy.split(":");
3108            if (data.length == 0) {
3109                return;
3110            }
3111
3112            String proxyHost =  data[0];
3113            int proxyPort = 8080;
3114            if (data.length > 1) {
3115                try {
3116                    proxyPort = Integer.parseInt(data[1]);
3117                } catch (NumberFormatException e) {
3118                    return;
3119                }
3120            }
3121            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
3122            setGlobalProxy(p);
3123        }
3124    }
3125
3126    private void sendProxyBroadcast(ProxyInfo proxy) {
3127        if (proxy == null) proxy = new ProxyInfo("", 0, "");
3128        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3129        if (DBG) log("sending Proxy Broadcast for " + proxy);
3130        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3131        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3132            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3133        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3134        final long ident = Binder.clearCallingIdentity();
3135        try {
3136            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3137        } finally {
3138            Binder.restoreCallingIdentity(ident);
3139        }
3140    }
3141
3142    private static class SettingsObserver extends ContentObserver {
3143        final private HashMap<Uri, Integer> mUriEventMap;
3144        final private Context mContext;
3145        final private Handler mHandler;
3146
3147        SettingsObserver(Context context, Handler handler) {
3148            super(null);
3149            mUriEventMap = new HashMap<Uri, Integer>();
3150            mContext = context;
3151            mHandler = handler;
3152        }
3153
3154        void observe(Uri uri, int what) {
3155            mUriEventMap.put(uri, what);
3156            final ContentResolver resolver = mContext.getContentResolver();
3157            resolver.registerContentObserver(uri, false, this);
3158        }
3159
3160        @Override
3161        public void onChange(boolean selfChange) {
3162            Slog.wtf(TAG, "Should never be reached.");
3163        }
3164
3165        @Override
3166        public void onChange(boolean selfChange, Uri uri) {
3167            final Integer what = mUriEventMap.get(uri);
3168            if (what != null) {
3169                mHandler.obtainMessage(what.intValue()).sendToTarget();
3170            } else {
3171                loge("No matching event to send for URI=" + uri);
3172            }
3173        }
3174    }
3175
3176    private static void log(String s) {
3177        Slog.d(TAG, s);
3178    }
3179
3180    private static void loge(String s) {
3181        Slog.e(TAG, s);
3182    }
3183
3184    private static <T> T checkNotNull(T value, String message) {
3185        if (value == null) {
3186            throw new NullPointerException(message);
3187        }
3188        return value;
3189    }
3190
3191    /**
3192     * Prepare for a VPN application.
3193     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3194     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3195     *
3196     * @param oldPackage Package name of the application which currently controls VPN, which will
3197     *                   be replaced. If there is no such application, this should should either be
3198     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
3199     * @param newPackage Package name of the application which should gain control of VPN, or
3200     *                   {@code null} to disable.
3201     * @param userId User for whom to prepare the new VPN.
3202     *
3203     * @hide
3204     */
3205    @Override
3206    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3207            int userId) {
3208        enforceCrossUserPermission(userId);
3209        throwIfLockdownEnabled();
3210
3211        synchronized(mVpns) {
3212            Vpn vpn = mVpns.get(userId);
3213            if (vpn != null) {
3214                return vpn.prepare(oldPackage, newPackage);
3215            } else {
3216                return false;
3217            }
3218        }
3219    }
3220
3221    /**
3222     * Set whether the VPN package has the ability to launch VPNs without user intervention.
3223     * This method is used by system-privileged apps.
3224     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3225     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3226     *
3227     * @param packageName The package for which authorization state should change.
3228     * @param userId User for whom {@code packageName} is installed.
3229     * @param authorized {@code true} if this app should be able to start a VPN connection without
3230     *                   explicit user approval, {@code false} if not.
3231     *
3232     * @hide
3233     */
3234    @Override
3235    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3236        enforceCrossUserPermission(userId);
3237
3238        synchronized(mVpns) {
3239            Vpn vpn = mVpns.get(userId);
3240            if (vpn != null) {
3241                vpn.setPackageAuthorization(packageName, authorized);
3242            }
3243        }
3244    }
3245
3246    /**
3247     * Configure a TUN interface and return its file descriptor. Parameters
3248     * are encoded and opaque to this class. This method is used by VpnBuilder
3249     * and not available in ConnectivityManager. Permissions are checked in
3250     * Vpn class.
3251     * @hide
3252     */
3253    @Override
3254    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3255        throwIfLockdownEnabled();
3256        int user = UserHandle.getUserId(Binder.getCallingUid());
3257        synchronized(mVpns) {
3258            return mVpns.get(user).establish(config);
3259        }
3260    }
3261
3262    /**
3263     * Start legacy VPN, controlling native daemons as needed. Creates a
3264     * secondary thread to perform connection work, returning quickly.
3265     */
3266    @Override
3267    public void startLegacyVpn(VpnProfile profile) {
3268        throwIfLockdownEnabled();
3269        final LinkProperties egress = getActiveLinkProperties();
3270        if (egress == null) {
3271            throw new IllegalStateException("Missing active network connection");
3272        }
3273        int user = UserHandle.getUserId(Binder.getCallingUid());
3274        synchronized(mVpns) {
3275            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3276        }
3277    }
3278
3279    /**
3280     * Return the information of the ongoing legacy VPN. This method is used
3281     * by VpnSettings and not available in ConnectivityManager. Permissions
3282     * are checked in Vpn class.
3283     */
3284    @Override
3285    public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3286        enforceCrossUserPermission(userId);
3287
3288        synchronized(mVpns) {
3289            return mVpns.get(userId).getLegacyVpnInfo();
3290        }
3291    }
3292
3293    /**
3294     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3295     * and not available in ConnectivityManager.
3296     */
3297    @Override
3298    public VpnInfo[] getAllVpnInfo() {
3299        enforceConnectivityInternalPermission();
3300        if (mLockdownEnabled) {
3301            return new VpnInfo[0];
3302        }
3303
3304        synchronized(mVpns) {
3305            List<VpnInfo> infoList = new ArrayList<>();
3306            for (int i = 0; i < mVpns.size(); i++) {
3307                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3308                if (info != null) {
3309                    infoList.add(info);
3310                }
3311            }
3312            return infoList.toArray(new VpnInfo[infoList.size()]);
3313        }
3314    }
3315
3316    /**
3317     * @return VPN information for accounting, or null if we can't retrieve all required
3318     *         information, e.g primary underlying iface.
3319     */
3320    @Nullable
3321    private VpnInfo createVpnInfo(Vpn vpn) {
3322        VpnInfo info = vpn.getVpnInfo();
3323        if (info == null) {
3324            return null;
3325        }
3326        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3327        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3328        // the underlyingNetworks list.
3329        if (underlyingNetworks == null) {
3330            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3331            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3332                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3333            }
3334        } else if (underlyingNetworks.length > 0) {
3335            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3336            if (linkProperties != null) {
3337                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3338            }
3339        }
3340        return info.primaryUnderlyingIface == null ? null : info;
3341    }
3342
3343    /**
3344     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3345     * VpnDialogs and not available in ConnectivityManager.
3346     * Permissions are checked in Vpn class.
3347     * @hide
3348     */
3349    @Override
3350    public VpnConfig getVpnConfig(int userId) {
3351        enforceCrossUserPermission(userId);
3352        synchronized(mVpns) {
3353            Vpn vpn = mVpns.get(userId);
3354            if (vpn != null) {
3355                return vpn.getVpnConfig();
3356            } else {
3357                return null;
3358            }
3359        }
3360    }
3361
3362    @Override
3363    public boolean updateLockdownVpn() {
3364        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3365            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3366            return false;
3367        }
3368
3369        // Tear down existing lockdown if profile was removed
3370        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3371        if (mLockdownEnabled) {
3372            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3373            final VpnProfile profile = VpnProfile.decode(
3374                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3375            if (profile == null) {
3376                Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3377                setLockdownTracker(null);
3378                return true;
3379            }
3380            int user = UserHandle.getUserId(Binder.getCallingUid());
3381            synchronized(mVpns) {
3382                Vpn vpn = mVpns.get(user);
3383                if (vpn == null) {
3384                    Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3385                    return false;
3386                }
3387                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
3388            }
3389        } else {
3390            setLockdownTracker(null);
3391        }
3392
3393        return true;
3394    }
3395
3396    /**
3397     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3398     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3399     */
3400    private void setLockdownTracker(LockdownVpnTracker tracker) {
3401        // Shutdown any existing tracker
3402        final LockdownVpnTracker existing = mLockdownTracker;
3403        mLockdownTracker = null;
3404        if (existing != null) {
3405            existing.shutdown();
3406        }
3407
3408        try {
3409            if (tracker != null) {
3410                mNetd.setFirewallEnabled(true);
3411                mNetd.setFirewallInterfaceRule("lo", true);
3412                mLockdownTracker = tracker;
3413                mLockdownTracker.init();
3414            } else {
3415                mNetd.setFirewallEnabled(false);
3416            }
3417        } catch (RemoteException e) {
3418            // ignored; NMS lives inside system_server
3419        }
3420    }
3421
3422    private void throwIfLockdownEnabled() {
3423        if (mLockdownEnabled) {
3424            throw new IllegalStateException("Unavailable in lockdown mode");
3425        }
3426    }
3427
3428    /**
3429     * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3430     * some setup and then call {@code establish()} to connect.
3431     *
3432     * @return {@code true} if the service was started, the service was already connected, or there
3433     *         was no always-on VPN to start. {@code false} otherwise.
3434     */
3435    private boolean startAlwaysOnVpn(int userId) {
3436        synchronized (mVpns) {
3437            Vpn vpn = mVpns.get(userId);
3438            if (vpn == null) {
3439                // Shouldn't happen as all codepaths that point here should have checked the Vpn
3440                // exists already.
3441                Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3442                return false;
3443            }
3444
3445            return vpn.startAlwaysOnVpn();
3446        }
3447    }
3448
3449    @Override
3450    public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
3451        enforceConnectivityInternalPermission();
3452        enforceCrossUserPermission(userId);
3453
3454        // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3455        if (LockdownVpnTracker.isEnabled()) {
3456            return false;
3457        }
3458
3459        synchronized (mVpns) {
3460            Vpn vpn = mVpns.get(userId);
3461            if (vpn == null) {
3462                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3463                return false;
3464            }
3465            if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
3466                return false;
3467            }
3468            if (!startAlwaysOnVpn(userId)) {
3469                vpn.setAlwaysOnPackage(null, false);
3470                return false;
3471            }
3472
3473            vpn.saveAlwaysOnPackage();
3474        }
3475        return true;
3476    }
3477
3478    @Override
3479    public String getAlwaysOnVpnPackage(int userId) {
3480        enforceConnectivityInternalPermission();
3481        enforceCrossUserPermission(userId);
3482
3483        synchronized (mVpns) {
3484            Vpn vpn = mVpns.get(userId);
3485            if (vpn == null) {
3486                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3487                return null;
3488            }
3489            return vpn.getAlwaysOnPackage();
3490        }
3491    }
3492
3493    @Override
3494    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3495        // TODO: Remove?  Any reason to trigger a provisioning check?
3496        return -1;
3497    }
3498
3499    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3500    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3501
3502    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3503        Intent intent = new Intent(action);
3504        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3505        // Concatenate the range of types onto the range of NetIDs.
3506        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3507        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3508                networkType, null, pendingIntent, false);
3509    }
3510
3511    /**
3512     * Show or hide network provisioning notifications.
3513     *
3514     * We use notifications for two purposes: to notify that a network requires sign in
3515     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3516     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3517     * particular network we can display the notification type that was most recently requested.
3518     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3519     * might first display NO_INTERNET, and then when the captive portal check completes, display
3520     * SIGN_IN.
3521     *
3522     * @param id an identifier that uniquely identifies this notification.  This must match
3523     *         between show and hide calls.  We use the NetID value but for legacy callers
3524     *         we concatenate the range of types with the range of NetIDs.
3525     */
3526    private void setProvNotificationVisibleIntent(boolean visible, int id,
3527            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3528            boolean highPriority) {
3529        if (VDBG || (DBG && visible)) {
3530            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3531                    + " networkType=" + getNetworkTypeName(networkType)
3532                    + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
3533        }
3534
3535        Resources r = Resources.getSystem();
3536        NotificationManager notificationManager = (NotificationManager) mContext
3537            .getSystemService(Context.NOTIFICATION_SERVICE);
3538
3539        if (visible) {
3540            CharSequence title;
3541            CharSequence details;
3542            int icon;
3543            if (notifyType == NotificationType.NO_INTERNET &&
3544                    networkType == ConnectivityManager.TYPE_WIFI) {
3545                title = r.getString(R.string.wifi_no_internet, 0);
3546                details = r.getString(R.string.wifi_no_internet_detailed);
3547                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3548            } else if (notifyType == NotificationType.SIGN_IN) {
3549                switch (networkType) {
3550                    case ConnectivityManager.TYPE_WIFI:
3551                        title = r.getString(R.string.wifi_available_sign_in, 0);
3552                        details = r.getString(R.string.network_available_sign_in_detailed,
3553                                extraInfo);
3554                        icon = R.drawable.stat_notify_wifi_in_range;
3555                        break;
3556                    case ConnectivityManager.TYPE_MOBILE:
3557                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3558                        title = r.getString(R.string.network_available_sign_in, 0);
3559                        // TODO: Change this to pull from NetworkInfo once a printable
3560                        // name has been added to it
3561                        details = mTelephonyManager.getNetworkOperatorName();
3562                        icon = R.drawable.stat_notify_rssi_in_range;
3563                        break;
3564                    default:
3565                        title = r.getString(R.string.network_available_sign_in, 0);
3566                        details = r.getString(R.string.network_available_sign_in_detailed,
3567                                extraInfo);
3568                        icon = R.drawable.stat_notify_rssi_in_range;
3569                        break;
3570                }
3571            } else {
3572                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3573                        + getNetworkTypeName(networkType));
3574                return;
3575            }
3576
3577            Notification notification = new Notification.Builder(mContext)
3578                    .setWhen(0)
3579                    .setSmallIcon(icon)
3580                    .setAutoCancel(true)
3581                    .setTicker(title)
3582                    .setColor(mContext.getColor(
3583                            com.android.internal.R.color.system_notification_accent_color))
3584                    .setContentTitle(title)
3585                    .setContentText(details)
3586                    .setContentIntent(intent)
3587                    .setLocalOnly(true)
3588                    .setPriority(highPriority ?
3589                            Notification.PRIORITY_HIGH :
3590                            Notification.PRIORITY_DEFAULT)
3591                    .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
3592                    .setOnlyAlertOnce(true)
3593                    .build();
3594
3595            try {
3596                notificationManager.notifyAsUser(NOTIFICATION_ID, id, notification, UserHandle.ALL);
3597            } catch (NullPointerException npe) {
3598                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3599                npe.printStackTrace();
3600            }
3601        } else {
3602            try {
3603                notificationManager.cancelAsUser(NOTIFICATION_ID, id, UserHandle.ALL);
3604            } catch (NullPointerException npe) {
3605                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3606                npe.printStackTrace();
3607            }
3608        }
3609    }
3610
3611    /** Location to an updatable file listing carrier provisioning urls.
3612     *  An example:
3613     *
3614     * <?xml version="1.0" encoding="utf-8"?>
3615     *  <provisioningUrls>
3616     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3617     *  </provisioningUrls>
3618     */
3619    private static final String PROVISIONING_URL_PATH =
3620            "/data/misc/radio/provisioning_urls.xml";
3621    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3622
3623    /** XML tag for root element. */
3624    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3625    /** XML tag for individual url */
3626    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3627    /** XML attribute for mcc */
3628    private static final String ATTR_MCC = "mcc";
3629    /** XML attribute for mnc */
3630    private static final String ATTR_MNC = "mnc";
3631
3632    private String getProvisioningUrlBaseFromFile() {
3633        FileReader fileReader = null;
3634        XmlPullParser parser = null;
3635        Configuration config = mContext.getResources().getConfiguration();
3636
3637        try {
3638            fileReader = new FileReader(mProvisioningUrlFile);
3639            parser = Xml.newPullParser();
3640            parser.setInput(fileReader);
3641            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3642
3643            while (true) {
3644                XmlUtils.nextElement(parser);
3645
3646                String element = parser.getName();
3647                if (element == null) break;
3648
3649                if (element.equals(TAG_PROVISIONING_URL)) {
3650                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3651                    try {
3652                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3653                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3654                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3655                                parser.next();
3656                                if (parser.getEventType() == XmlPullParser.TEXT) {
3657                                    return parser.getText();
3658                                }
3659                            }
3660                        }
3661                    } catch (NumberFormatException e) {
3662                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3663                    }
3664                }
3665            }
3666            return null;
3667        } catch (FileNotFoundException e) {
3668            loge("Carrier Provisioning Urls file not found");
3669        } catch (XmlPullParserException e) {
3670            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3671        } catch (IOException e) {
3672            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3673        } finally {
3674            if (fileReader != null) {
3675                try {
3676                    fileReader.close();
3677                } catch (IOException e) {}
3678            }
3679        }
3680        return null;
3681    }
3682
3683    @Override
3684    public String getMobileProvisioningUrl() {
3685        enforceConnectivityInternalPermission();
3686        String url = getProvisioningUrlBaseFromFile();
3687        if (TextUtils.isEmpty(url)) {
3688            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3689            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3690        } else {
3691            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3692        }
3693        // populate the iccid, imei and phone number in the provisioning url.
3694        if (!TextUtils.isEmpty(url)) {
3695            String phoneNumber = mTelephonyManager.getLine1Number();
3696            if (TextUtils.isEmpty(phoneNumber)) {
3697                phoneNumber = "0000000000";
3698            }
3699            url = String.format(url,
3700                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3701                    mTelephonyManager.getDeviceId() /* IMEI */,
3702                    phoneNumber /* Phone numer */);
3703        }
3704
3705        return url;
3706    }
3707
3708    @Override
3709    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3710            String action) {
3711        enforceConnectivityInternalPermission();
3712        final long ident = Binder.clearCallingIdentity();
3713        try {
3714            setProvNotificationVisible(visible, networkType, action);
3715        } finally {
3716            Binder.restoreCallingIdentity(ident);
3717        }
3718    }
3719
3720    @Override
3721    public void setAirplaneMode(boolean enable) {
3722        enforceConnectivityInternalPermission();
3723        final long ident = Binder.clearCallingIdentity();
3724        try {
3725            final ContentResolver cr = mContext.getContentResolver();
3726            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3727            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3728            intent.putExtra("state", enable);
3729            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3730        } finally {
3731            Binder.restoreCallingIdentity(ident);
3732        }
3733    }
3734
3735    private void onUserStart(int userId) {
3736        synchronized(mVpns) {
3737            Vpn userVpn = mVpns.get(userId);
3738            if (userVpn != null) {
3739                loge("Starting user already has a VPN");
3740                return;
3741            }
3742            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3743            mVpns.put(userId, userVpn);
3744
3745            final ContentResolver cr = mContext.getContentResolver();
3746            String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3747                    Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3748            final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3749                    Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3750            if (alwaysOnPackage != null) {
3751                userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3752            }
3753        }
3754        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3755            updateLockdownVpn();
3756        }
3757    }
3758
3759    private void onUserStop(int userId) {
3760        synchronized(mVpns) {
3761            Vpn userVpn = mVpns.get(userId);
3762            if (userVpn == null) {
3763                loge("Stopped user has no VPN");
3764                return;
3765            }
3766            userVpn.onUserStopped();
3767            mVpns.delete(userId);
3768        }
3769    }
3770
3771    private void onUserAdded(int userId) {
3772        synchronized(mVpns) {
3773            final int vpnsSize = mVpns.size();
3774            for (int i = 0; i < vpnsSize; i++) {
3775                Vpn vpn = mVpns.valueAt(i);
3776                vpn.onUserAdded(userId);
3777            }
3778        }
3779    }
3780
3781    private void onUserRemoved(int userId) {
3782        synchronized(mVpns) {
3783            final int vpnsSize = mVpns.size();
3784            for (int i = 0; i < vpnsSize; i++) {
3785                Vpn vpn = mVpns.valueAt(i);
3786                vpn.onUserRemoved(userId);
3787            }
3788        }
3789    }
3790
3791    private void onUserUnlocked(int userId) {
3792        // User present may be sent because of an unlock, which might mean an unlocked keystore.
3793        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3794            updateLockdownVpn();
3795        } else {
3796            startAlwaysOnVpn(userId);
3797        }
3798    }
3799
3800    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3801        @Override
3802        public void onReceive(Context context, Intent intent) {
3803            final String action = intent.getAction();
3804            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3805            if (userId == UserHandle.USER_NULL) return;
3806
3807            if (Intent.ACTION_USER_STARTED.equals(action)) {
3808                onUserStart(userId);
3809            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3810                onUserStop(userId);
3811            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3812                onUserAdded(userId);
3813            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3814                onUserRemoved(userId);
3815            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3816                onUserUnlocked(userId);
3817            }
3818        }
3819    };
3820
3821    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3822            new HashMap<Messenger, NetworkFactoryInfo>();
3823    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3824            new HashMap<NetworkRequest, NetworkRequestInfo>();
3825
3826    private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3827    // Map from UID to number of NetworkRequests that UID has filed.
3828    @GuardedBy("mUidToNetworkRequestCount")
3829    private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3830
3831    private static class NetworkFactoryInfo {
3832        public final String name;
3833        public final Messenger messenger;
3834        public final AsyncChannel asyncChannel;
3835
3836        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3837            this.name = name;
3838            this.messenger = messenger;
3839            this.asyncChannel = asyncChannel;
3840        }
3841    }
3842
3843    private void ensureNetworkRequestHasType(NetworkRequest request) {
3844        if (request.type == NetworkRequest.Type.NONE) {
3845            throw new IllegalArgumentException(
3846                    "All NetworkRequests in ConnectivityService must have a type");
3847        }
3848    }
3849
3850    /**
3851     * Tracks info about the requester.
3852     * Also used to notice when the calling process dies so we can self-expire
3853     */
3854    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3855        final NetworkRequest request;
3856        final PendingIntent mPendingIntent;
3857        boolean mPendingIntentSent;
3858        private final IBinder mBinder;
3859        final int mPid;
3860        final int mUid;
3861        final Messenger messenger;
3862
3863        NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
3864            request = r;
3865            ensureNetworkRequestHasType(request);
3866            mPendingIntent = pi;
3867            messenger = null;
3868            mBinder = null;
3869            mPid = getCallingPid();
3870            mUid = getCallingUid();
3871            enforceRequestCountLimit();
3872        }
3873
3874        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
3875            super();
3876            messenger = m;
3877            request = r;
3878            ensureNetworkRequestHasType(request);
3879            mBinder = binder;
3880            mPid = getCallingPid();
3881            mUid = getCallingUid();
3882            mPendingIntent = null;
3883            enforceRequestCountLimit();
3884
3885            try {
3886                mBinder.linkToDeath(this, 0);
3887            } catch (RemoteException e) {
3888                binderDied();
3889            }
3890        }
3891
3892        private void enforceRequestCountLimit() {
3893            synchronized (mUidToNetworkRequestCount) {
3894                int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3895                if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3896                    throw new IllegalArgumentException("Too many NetworkRequests filed");
3897                }
3898                mUidToNetworkRequestCount.put(mUid, networkRequests);
3899            }
3900        }
3901
3902        void unlinkDeathRecipient() {
3903            if (mBinder != null) {
3904                mBinder.unlinkToDeath(this, 0);
3905            }
3906        }
3907
3908        public void binderDied() {
3909            log("ConnectivityService NetworkRequestInfo binderDied(" +
3910                    request + ", " + mBinder + ")");
3911            releaseNetworkRequest(request);
3912        }
3913
3914        public String toString() {
3915            return "uid/pid:" + mUid + "/" + mPid + " " + request +
3916                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3917        }
3918    }
3919
3920    private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3921        final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3922        if (badCapability != null) {
3923            throw new IllegalArgumentException("Cannot request network with " + badCapability);
3924        }
3925    }
3926
3927    private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
3928        final SortedSet<Integer> thresholds = new TreeSet();
3929        synchronized (nai) {
3930            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3931                if (nri.request.networkCapabilities.hasSignalStrength() &&
3932                        nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3933                    thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3934                }
3935            }
3936        }
3937        return new ArrayList<Integer>(thresholds);
3938    }
3939
3940    private void updateSignalStrengthThresholds(
3941            NetworkAgentInfo nai, String reason, NetworkRequest request) {
3942        ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
3943        Bundle thresholds = new Bundle();
3944        thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3945
3946        if (VDBG || (DBG && !"CONNECT".equals(reason))) {
3947            String detail;
3948            if (request != null && request.networkCapabilities.hasSignalStrength()) {
3949                detail = reason + " " + request.networkCapabilities.getSignalStrength();
3950            } else {
3951                detail = reason;
3952            }
3953            log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3954                    detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3955        }
3956
3957        nai.asyncChannel.sendMessage(
3958                android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
3959                0, 0, thresholds);
3960    }
3961
3962    @Override
3963    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3964            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3965        final NetworkRequest.Type type = (networkCapabilities == null)
3966                ? NetworkRequest.Type.TRACK_DEFAULT
3967                : NetworkRequest.Type.REQUEST;
3968        // If the requested networkCapabilities is null, take them instead from
3969        // the default network request. This allows callers to keep track of
3970        // the system default network.
3971        if (type == NetworkRequest.Type.TRACK_DEFAULT) {
3972            networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3973            enforceAccessPermission();
3974        } else {
3975            networkCapabilities = new NetworkCapabilities(networkCapabilities);
3976            enforceNetworkRequestPermissions(networkCapabilities);
3977            // TODO: this is incorrect. We mark the request as metered or not depending on the state
3978            // of the app when the request is filed, but we never change the request if the app
3979            // changes network state. http://b/29964605
3980            enforceMeteredApnPolicy(networkCapabilities);
3981        }
3982        ensureRequestableCapabilities(networkCapabilities);
3983
3984        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
3985            throw new IllegalArgumentException("Bad timeout specified");
3986        }
3987
3988        if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3989                .equals(networkCapabilities.getNetworkSpecifier())) {
3990            throw new IllegalArgumentException("Invalid network specifier - must not be '"
3991                    + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3992        }
3993
3994        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3995                nextNetworkRequestId(), type);
3996        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
3997        if (DBG) log("requestNetwork for " + nri);
3998
3999        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
4000        if (timeoutMs > 0) {
4001            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
4002                    nri), timeoutMs);
4003        }
4004        return networkRequest;
4005    }
4006
4007    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
4008        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
4009            enforceConnectivityInternalPermission();
4010        } else {
4011            enforceChangePermission();
4012        }
4013    }
4014
4015    @Override
4016    public boolean requestBandwidthUpdate(Network network) {
4017        enforceAccessPermission();
4018        NetworkAgentInfo nai = null;
4019        if (network == null) {
4020            return false;
4021        }
4022        synchronized (mNetworkForNetId) {
4023            nai = mNetworkForNetId.get(network.netId);
4024        }
4025        if (nai != null) {
4026            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4027            return true;
4028        }
4029        return false;
4030    }
4031
4032    private boolean isSystem(int uid) {
4033        return uid < Process.FIRST_APPLICATION_UID;
4034    }
4035
4036    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4037        final int uid = Binder.getCallingUid();
4038        if (isSystem(uid)) {
4039            return;
4040        }
4041        // if UID is restricted, don't allow them to bring up metered APNs
4042        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
4043            final int uidRules;
4044            synchronized(mRulesLock) {
4045                uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4046            }
4047            if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4048                    && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
4049                // we could silently fail or we can filter the available nets to only give
4050                // them those they have access to.  Chose the more useful option.
4051                networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
4052            }
4053        }
4054    }
4055
4056    @Override
4057    public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4058            PendingIntent operation) {
4059        checkNotNull(operation, "PendingIntent cannot be null.");
4060        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4061        enforceNetworkRequestPermissions(networkCapabilities);
4062        enforceMeteredApnPolicy(networkCapabilities);
4063        ensureRequestableCapabilities(networkCapabilities);
4064
4065        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4066                nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4067        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
4068        if (DBG) log("pendingRequest for " + nri);
4069        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4070                nri));
4071        return networkRequest;
4072    }
4073
4074    private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4075        mHandler.sendMessageDelayed(
4076                mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4077                getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4078    }
4079
4080    @Override
4081    public void releasePendingNetworkRequest(PendingIntent operation) {
4082        checkNotNull(operation, "PendingIntent cannot be null.");
4083        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4084                getCallingUid(), 0, operation));
4085    }
4086
4087    // In order to implement the compatibility measure for pre-M apps that call
4088    // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4089    // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4090    // This ensures it has permission to do so.
4091    private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4092        if (nc == null) {
4093            return false;
4094        }
4095        int[] transportTypes = nc.getTransportTypes();
4096        if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4097            return false;
4098        }
4099        try {
4100            mContext.enforceCallingOrSelfPermission(
4101                    android.Manifest.permission.ACCESS_WIFI_STATE,
4102                    "ConnectivityService");
4103        } catch (SecurityException e) {
4104            return false;
4105        }
4106        return true;
4107    }
4108
4109    @Override
4110    public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4111            Messenger messenger, IBinder binder) {
4112        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4113            enforceAccessPermission();
4114        }
4115
4116        NetworkRequest networkRequest = new NetworkRequest(
4117                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4118                NetworkRequest.Type.LISTEN);
4119        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
4120        if (VDBG) log("listenForNetwork for " + nri);
4121
4122        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4123        return networkRequest;
4124    }
4125
4126    @Override
4127    public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4128            PendingIntent operation) {
4129        checkNotNull(operation, "PendingIntent cannot be null.");
4130        if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4131            enforceAccessPermission();
4132        }
4133
4134        NetworkRequest networkRequest = new NetworkRequest(
4135                new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4136                NetworkRequest.Type.LISTEN);
4137        NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
4138        if (VDBG) log("pendingListenForNetwork for " + nri);
4139
4140        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4141    }
4142
4143    @Override
4144    public void releaseNetworkRequest(NetworkRequest networkRequest) {
4145        ensureNetworkRequestHasType(networkRequest);
4146        mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4147                0, networkRequest));
4148    }
4149
4150    @Override
4151    public void registerNetworkFactory(Messenger messenger, String name) {
4152        enforceConnectivityInternalPermission();
4153        NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4154        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
4155    }
4156
4157    private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
4158        if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
4159        mNetworkFactoryInfos.put(nfi.messenger, nfi);
4160        nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4161    }
4162
4163    @Override
4164    public void unregisterNetworkFactory(Messenger messenger) {
4165        enforceConnectivityInternalPermission();
4166        mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4167    }
4168
4169    private void handleUnregisterNetworkFactory(Messenger messenger) {
4170        NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4171        if (nfi == null) {
4172            loge("Failed to find Messenger in unregisterNetworkFactory");
4173            return;
4174        }
4175        if (DBG) log("unregisterNetworkFactory for " + nfi.name);
4176    }
4177
4178    /**
4179     * NetworkAgentInfo supporting a request by requestId.
4180     * These have already been vetted (their Capabilities satisfy the request)
4181     * and the are the highest scored network available.
4182     * the are keyed off the Requests requestId.
4183     */
4184    // TODO: Yikes, this is accessed on multiple threads: add synchronization.
4185    private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4186            new SparseArray<NetworkAgentInfo>();
4187
4188    // NOTE: Accessed on multiple threads, must be synchronized on itself.
4189    @GuardedBy("mNetworkForNetId")
4190    private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4191            new SparseArray<NetworkAgentInfo>();
4192    // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4193    // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4194    // there may not be a strict 1:1 correlation between the two.
4195    @GuardedBy("mNetworkForNetId")
4196    private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
4197
4198    // NetworkAgentInfo keyed off its connecting messenger
4199    // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
4200    // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
4201    private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4202            new HashMap<Messenger, NetworkAgentInfo>();
4203
4204    @GuardedBy("mBlockedAppUids")
4205    private final HashSet<Integer> mBlockedAppUids = new HashSet();
4206
4207    // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
4208    private final NetworkRequest mDefaultRequest;
4209
4210    // Request used to optionally keep mobile data active even when higher
4211    // priority networks like Wi-Fi are active.
4212    private final NetworkRequest mDefaultMobileDataRequest;
4213
4214    private NetworkAgentInfo getDefaultNetwork() {
4215        return mNetworkForRequestId.get(mDefaultRequest.requestId);
4216    }
4217
4218    private boolean isDefaultNetwork(NetworkAgentInfo nai) {
4219        return nai == getDefaultNetwork();
4220    }
4221
4222    public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
4223            LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
4224            int currentScore, NetworkMisc networkMisc) {
4225        enforceConnectivityInternalPermission();
4226
4227        // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4228        // satisfies mDefaultRequest.
4229        final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
4230                new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4231                linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
4232                mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
4233        synchronized (this) {
4234            nai.networkMonitor.systemReady = mSystemReady;
4235        }
4236        addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4237                networkInfo.getExtraInfo());
4238        if (DBG) log("registerNetworkAgent " + nai);
4239        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
4240        return nai.network.netId;
4241    }
4242
4243    private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4244        if (VDBG) log("Got NetworkAgent Messenger");
4245        mNetworkAgentInfos.put(na.messenger, na);
4246        synchronized (mNetworkForNetId) {
4247            mNetworkForNetId.put(na.network.netId, na);
4248        }
4249        na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4250        NetworkInfo networkInfo = na.networkInfo;
4251        na.networkInfo = null;
4252        updateNetworkInfo(na, networkInfo);
4253    }
4254
4255    private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4256        LinkProperties newLp = networkAgent.linkProperties;
4257        int netId = networkAgent.network.netId;
4258
4259        // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4260        // we do anything else, make sure its LinkProperties are accurate.
4261        if (networkAgent.clatd != null) {
4262            networkAgent.clatd.fixupLinkProperties(oldLp);
4263        }
4264
4265        updateInterfaces(newLp, oldLp, netId);
4266        updateMtu(newLp, oldLp);
4267        // TODO - figure out what to do for clat
4268//        for (LinkProperties lp : newLp.getStackedLinks()) {
4269//            updateMtu(lp, null);
4270//        }
4271        updateTcpBufferSizes(networkAgent);
4272
4273        updateRoutes(newLp, oldLp, netId);
4274        updateDnses(newLp, oldLp, netId);
4275
4276        updateClat(newLp, oldLp, networkAgent);
4277        if (isDefaultNetwork(networkAgent)) {
4278            handleApplyDefaultProxy(newLp.getHttpProxy());
4279        } else {
4280            updateProxy(newLp, oldLp, networkAgent);
4281        }
4282        // TODO - move this check to cover the whole function
4283        if (!Objects.equals(newLp, oldLp)) {
4284            notifyIfacesChangedForNetworkStats();
4285            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4286        }
4287
4288        mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
4289    }
4290
4291    private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4292        final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4293        final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
4294
4295        if (!wasRunningClat && shouldRunClat) {
4296            nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4297            nai.clatd.start();
4298        } else if (wasRunningClat && !shouldRunClat) {
4299            nai.clatd.stop();
4300        }
4301    }
4302
4303    private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4304        CompareResult<String> interfaceDiff = new CompareResult<String>();
4305        if (oldLp != null) {
4306            interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4307        } else if (newLp != null) {
4308            interfaceDiff.added = newLp.getAllInterfaceNames();
4309        }
4310        for (String iface : interfaceDiff.added) {
4311            try {
4312                if (DBG) log("Adding iface " + iface + " to network " + netId);
4313                mNetd.addInterfaceToNetwork(iface, netId);
4314            } catch (Exception e) {
4315                loge("Exception adding interface: " + e);
4316            }
4317        }
4318        for (String iface : interfaceDiff.removed) {
4319            try {
4320                if (DBG) log("Removing iface " + iface + " from network " + netId);
4321                mNetd.removeInterfaceFromNetwork(iface, netId);
4322            } catch (Exception e) {
4323                loge("Exception removing interface: " + e);
4324            }
4325        }
4326    }
4327
4328    /**
4329     * Have netd update routes from oldLp to newLp.
4330     * @return true if routes changed between oldLp and newLp
4331     */
4332    private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
4333        CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4334        if (oldLp != null) {
4335            routeDiff = oldLp.compareAllRoutes(newLp);
4336        } else if (newLp != null) {
4337            routeDiff.added = newLp.getAllRoutes();
4338        }
4339
4340        // add routes before removing old in case it helps with continuous connectivity
4341
4342        // do this twice, adding non-nexthop routes first, then routes they are dependent on
4343        for (RouteInfo route : routeDiff.added) {
4344            if (route.hasGateway()) continue;
4345            if (VDBG) log("Adding Route [" + route + "] to network " + netId);
4346            try {
4347                mNetd.addRoute(netId, route);
4348            } catch (Exception e) {
4349                if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4350                    loge("Exception in addRoute for non-gateway: " + e);
4351                }
4352            }
4353        }
4354        for (RouteInfo route : routeDiff.added) {
4355            if (route.hasGateway() == false) continue;
4356            if (VDBG) log("Adding Route [" + route + "] to network " + netId);
4357            try {
4358                mNetd.addRoute(netId, route);
4359            } catch (Exception e) {
4360                if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4361                    loge("Exception in addRoute for gateway: " + e);
4362                }
4363            }
4364        }
4365
4366        for (RouteInfo route : routeDiff.removed) {
4367            if (VDBG) log("Removing Route [" + route + "] from network " + netId);
4368            try {
4369                mNetd.removeRoute(netId, route);
4370            } catch (Exception e) {
4371                loge("Exception in removeRoute: " + e);
4372            }
4373        }
4374        return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
4375    }
4376
4377    private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4378        if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4379            return;  // no updating necessary
4380        }
4381
4382        Collection<InetAddress> dnses = newLp.getDnsServers();
4383        if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
4384        try {
4385            mNetd.setDnsConfigurationForNetwork(
4386                    netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4387        } catch (Exception e) {
4388            loge("Exception in setDnsConfigurationForNetwork: " + e);
4389        }
4390        final NetworkAgentInfo defaultNai = getDefaultNetwork();
4391        if (defaultNai != null && defaultNai.network.netId == netId) {
4392            setDefaultDnsSystemProperties(dnses);
4393        }
4394        flushVmDnsCache();
4395    }
4396
4397    private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4398        int last = 0;
4399        for (InetAddress dns : dnses) {
4400            ++last;
4401            String key = "net.dns" + last;
4402            String value = dns.getHostAddress();
4403            SystemProperties.set(key, value);
4404        }
4405        for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4406            String key = "net.dns" + i;
4407            SystemProperties.set(key, "");
4408        }
4409        mNumDnsEntries = last;
4410    }
4411
4412    /**
4413     * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4414     * augmented with any stateful capabilities implied from {@code networkAgent}
4415     * (e.g., validated status and captive portal status).
4416     *
4417     * @param nai the network having its capabilities updated.
4418     * @param networkCapabilities the new network capabilities.
4419     */
4420    private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
4421        // Don't modify caller's NetworkCapabilities.
4422        networkCapabilities = new NetworkCapabilities(networkCapabilities);
4423        if (nai.lastValidated) {
4424            networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4425        } else {
4426            networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4427        }
4428        if (nai.lastCaptivePortalDetected) {
4429            networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4430        } else {
4431            networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4432        }
4433        if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4434            final int oldScore = nai.getCurrentScore();
4435            if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4436                    networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4437                try {
4438                    mNetd.setNetworkPermission(nai.network.netId,
4439                            networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4440                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4441                } catch (RemoteException e) {
4442                    loge("Exception in setNetworkPermission: " + e);
4443                }
4444            }
4445            synchronized (nai) {
4446                nai.networkCapabilities = networkCapabilities;
4447            }
4448            rematchAllNetworksAndRequests(nai, oldScore);
4449            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4450        }
4451    }
4452
4453    private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4454        for (int i = 0; i < nai.numNetworkRequests(); i++) {
4455            NetworkRequest nr = nai.requestAt(i);
4456            // Don't send listening requests to factories. b/17393458
4457            if (!nr.isRequest()) continue;
4458            sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4459        }
4460    }
4461
4462    private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4463        if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
4464        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
4465            nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4466                    networkRequest);
4467        }
4468    }
4469
4470    private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4471            int notificationType) {
4472        if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
4473            Intent intent = new Intent();
4474            intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4475            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
4476            nri.mPendingIntentSent = true;
4477            sendIntent(nri.mPendingIntent, intent);
4478        }
4479        // else not handled
4480    }
4481
4482    private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4483        mPendingIntentWakeLock.acquire();
4484        try {
4485            if (DBG) log("Sending " + pendingIntent);
4486            pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4487        } catch (PendingIntent.CanceledException e) {
4488            if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4489            mPendingIntentWakeLock.release();
4490            releasePendingNetworkRequest(pendingIntent);
4491        }
4492        // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4493    }
4494
4495    @Override
4496    public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4497            String resultData, Bundle resultExtras) {
4498        if (DBG) log("Finished sending " + pendingIntent);
4499        mPendingIntentWakeLock.release();
4500        // Release with a delay so the receiving client has an opportunity to put in its
4501        // own request.
4502        releasePendingNetworkRequestWithDelay(pendingIntent);
4503    }
4504
4505    private void callCallbackForRequest(NetworkRequestInfo nri,
4506            NetworkAgentInfo networkAgent, int notificationType) {
4507        if (nri.messenger == null) return;  // Default request has no msgr
4508        Bundle bundle = new Bundle();
4509        bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4510                new NetworkRequest(nri.request));
4511        Message msg = Message.obtain();
4512        if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4513                notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4514            bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4515        }
4516        switch (notificationType) {
4517            case ConnectivityManager.CALLBACK_LOSING: {
4518                msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4519                break;
4520            }
4521            case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4522                bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4523                        new NetworkCapabilities(networkAgent.networkCapabilities));
4524                break;
4525            }
4526            case ConnectivityManager.CALLBACK_IP_CHANGED: {
4527                bundle.putParcelable(LinkProperties.class.getSimpleName(),
4528                        new LinkProperties(networkAgent.linkProperties));
4529                break;
4530            }
4531        }
4532        msg.what = notificationType;
4533        msg.setData(bundle);
4534        try {
4535            if (VDBG) {
4536                log("sending notification " + notifyTypeToName(notificationType) +
4537                        " for " + nri.request);
4538            }
4539            nri.messenger.send(msg);
4540        } catch (RemoteException e) {
4541            // may occur naturally in the race of binder death.
4542            loge("RemoteException caught trying to send a callback msg for " + nri.request);
4543        }
4544    }
4545
4546    private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4547        if (nai.numRequestNetworkRequests() != 0) {
4548            for (int i = 0; i < nai.numNetworkRequests(); i++) {
4549                NetworkRequest nr = nai.requestAt(i);
4550                // Ignore listening requests.
4551                if (!nr.isRequest()) continue;
4552                loge("Dead network still had at least " + nr);
4553                break;
4554            }
4555        }
4556        nai.asyncChannel.disconnect();
4557    }
4558
4559    private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4560        if (oldNetwork == null) {
4561            loge("Unknown NetworkAgentInfo in handleLingerComplete");
4562            return;
4563        }
4564        if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4565        teardownUnneededNetwork(oldNetwork);
4566    }
4567
4568    private void makeDefault(NetworkAgentInfo newNetwork) {
4569        if (DBG) log("Switching to new default network: " + newNetwork);
4570        setupDataActivityTracking(newNetwork);
4571        try {
4572            mNetd.setDefaultNetId(newNetwork.network.netId);
4573        } catch (Exception e) {
4574            loge("Exception setting default network :" + e);
4575        }
4576        notifyLockdownVpn(newNetwork);
4577        handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
4578        updateTcpBufferSizes(newNetwork);
4579        setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
4580    }
4581
4582    // Handles a network appearing or improving its score.
4583    //
4584    // - Evaluates all current NetworkRequests that can be
4585    //   satisfied by newNetwork, and reassigns to newNetwork
4586    //   any such requests for which newNetwork is the best.
4587    //
4588    // - Lingers any validated Networks that as a result are no longer
4589    //   needed. A network is needed if it is the best network for
4590    //   one or more NetworkRequests, or if it is a VPN.
4591    //
4592    // - Tears down newNetwork if it just became validated
4593    //   but turns out to be unneeded.
4594    //
4595    // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4596    //   networks that have no chance (i.e. even if validated)
4597    //   of becoming the highest scoring network.
4598    //
4599    // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4600    // it does not remove NetworkRequests that other Networks could better satisfy.
4601    // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4602    // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4603    // as it performs better by a factor of the number of Networks.
4604    //
4605    // @param newNetwork is the network to be matched against NetworkRequests.
4606    // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4607    //               performed to tear down unvalidated networks that have no chance (i.e. even if
4608    //               validated) of becoming the highest scoring network.
4609    private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
4610            ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
4611        if (!newNetwork.everConnected) return;
4612        boolean keep = newNetwork.isVPN();
4613        boolean isNewDefault = false;
4614        NetworkAgentInfo oldDefaultNetwork = null;
4615        if (VDBG) log("rematching " + newNetwork.name());
4616        // Find and migrate to this Network any NetworkRequests for
4617        // which this network is now the best.
4618        ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
4619        ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
4620        if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
4621        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4622            final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4623            final boolean satisfies = newNetwork.satisfies(nri.request);
4624            if (newNetwork == currentNetwork && satisfies) {
4625                if (VDBG) {
4626                    log("Network " + newNetwork.name() + " was already satisfying" +
4627                            " request " + nri.request.requestId + ". No change.");
4628                }
4629                keep = true;
4630                continue;
4631            }
4632
4633            // check if it satisfies the NetworkCapabilities
4634            if (VDBG) log("  checking if request is satisfied: " + nri.request);
4635            if (satisfies) {
4636                if (!nri.request.isRequest()) {
4637                    // This is not a request, it's a callback listener.
4638                    // Add it to newNetwork regardless of score.
4639                    if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
4640                    continue;
4641                }
4642
4643                // next check if it's better than any current network we're using for
4644                // this request
4645                if (VDBG) {
4646                    log("currentScore = " +
4647                            (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4648                            ", newScore = " + newNetwork.getCurrentScore());
4649                }
4650                if (currentNetwork == null ||
4651                        currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
4652                    if (VDBG) log("rematch for " + newNetwork.name());
4653                    if (currentNetwork != null) {
4654                        if (VDBG) log("   accepting network in place of " + currentNetwork.name());
4655                        currentNetwork.removeRequest(nri.request.requestId);
4656                        currentNetwork.networkLingered.add(nri.request);
4657                        affectedNetworks.add(currentNetwork);
4658                    } else {
4659                        if (VDBG) log("   accepting network in place of null");
4660                    }
4661                    unlinger(newNetwork);
4662                    mNetworkForRequestId.put(nri.request.requestId, newNetwork);
4663                    if (!newNetwork.addRequest(nri.request)) {
4664                        Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4665                    }
4666                    addedRequests.add(nri);
4667                    keep = true;
4668                    // Tell NetworkFactories about the new score, so they can stop
4669                    // trying to connect if they know they cannot match it.
4670                    // TODO - this could get expensive if we have alot of requests for this
4671                    // network.  Think about if there is a way to reduce this.  Push
4672                    // netid->request mapping to each factory?
4673                    sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
4674                    if (mDefaultRequest.requestId == nri.request.requestId) {
4675                        isNewDefault = true;
4676                        oldDefaultNetwork = currentNetwork;
4677                    }
4678                }
4679            } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
4680                // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4681                // mark it as no longer satisfying "nri".  Because networks are processed by
4682                // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4683                // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4684                // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4685                // This means this code doesn't have to handle the case where "currentNetwork" no
4686                // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4687                if (DBG) {
4688                    log("Network " + newNetwork.name() + " stopped satisfying" +
4689                            " request " + nri.request.requestId);
4690                }
4691                newNetwork.removeRequest(nri.request.requestId);
4692                if (currentNetwork == newNetwork) {
4693                    mNetworkForRequestId.remove(nri.request.requestId);
4694                    sendUpdatedScoreToFactories(nri.request, 0);
4695                } else {
4696                    if (nri.request.isRequest()) {
4697                        Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4698                                newNetwork.name() +
4699                                " without updating mNetworkForRequestId or factories!");
4700                    }
4701                }
4702                // TODO: technically, sending CALLBACK_LOST here is
4703                // incorrect if nri is a request (not a listen) and there
4704                // is a replacement network currently connected that can
4705                // satisfy it. However, the only capability that can both
4706                // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4707                // so this code is only incorrect for a network that loses
4708                // the TRUSTED capability, which is a rare case.
4709                callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
4710            }
4711        }
4712        // Linger any networks that are no longer needed.
4713        for (NetworkAgentInfo nai : affectedNetworks) {
4714            if (nai.lingering) {
4715                // Already lingered.  Nothing to do.  This can only happen if "nai" is in
4716                // "affectedNetworks" twice.  The reasoning being that to get added to
4717                // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4718                // (i.e. not lingered) so it could have only been lingered by this loop.
4719                // unneeded(nai) will be false and we'll call unlinger() below which would
4720                // be bad, so handle it here.
4721            } else if (unneeded(nai)) {
4722                linger(nai);
4723            } else {
4724                // Clear nai.networkLingered we might have added above.
4725                unlinger(nai);
4726            }
4727        }
4728        if (isNewDefault) {
4729            // Notify system services that this network is up.
4730            makeDefault(newNetwork);
4731            // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4732            logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
4733            synchronized (ConnectivityService.this) {
4734                // have a new default network, release the transition wakelock in
4735                // a second if it's held.  The second pause is to allow apps
4736                // to reconnect over the new network
4737                if (mNetTransitionWakeLock.isHeld()) {
4738                    mHandler.sendMessageDelayed(mHandler.obtainMessage(
4739                            EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4740                            mNetTransitionWakeLockSerialNumber, 0),
4741                            1000);
4742                }
4743            }
4744        }
4745
4746        // do this after the default net is switched, but
4747        // before LegacyTypeTracker sends legacy broadcasts
4748        for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4749
4750        if (isNewDefault) {
4751            // Maintain the illusion: since the legacy API only
4752            // understands one network at a time, we must pretend
4753            // that the current default network disconnected before
4754            // the new one connected.
4755            if (oldDefaultNetwork != null) {
4756                mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4757                                          oldDefaultNetwork, true);
4758            }
4759            mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4760            mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4761            notifyLockdownVpn(newNetwork);
4762        }
4763
4764        if (keep) {
4765            // Notify battery stats service about this network, both the normal
4766            // interface and any stacked links.
4767            // TODO: Avoid redoing this; this must only be done once when a network comes online.
4768            try {
4769                final IBatteryStats bs = BatteryStatsService.getService();
4770                final int type = newNetwork.networkInfo.getType();
4771
4772                final String baseIface = newNetwork.linkProperties.getInterfaceName();
4773                bs.noteNetworkInterfaceType(baseIface, type);
4774                for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4775                    final String stackedIface = stacked.getInterfaceName();
4776                    bs.noteNetworkInterfaceType(stackedIface, type);
4777                    NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4778                }
4779            } catch (RemoteException ignored) {
4780            }
4781
4782            // This has to happen after the notifyNetworkCallbacks as that tickles each
4783            // ConnectivityManager instance so that legacy requests correctly bind dns
4784            // requests to this network.  The legacy users are listening for this bcast
4785            // and will generally do a dns request so they can ensureRouteToHost and if
4786            // they do that before the callbacks happen they'll use the default network.
4787            //
4788            // TODO: Is there still a race here? We send the broadcast
4789            // after sending the callback, but if the app can receive the
4790            // broadcast before the callback, it might still break.
4791            //
4792            // This *does* introduce a race where if the user uses the new api
4793            // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4794            // they may get old info.  Reverse this after the old startUsing api is removed.
4795            // This is on top of the multiple intent sequencing referenced in the todo above.
4796            for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4797                NetworkRequest nr = newNetwork.requestAt(i);
4798                if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
4799                    // legacy type tracker filters out repeat adds
4800                    mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4801                }
4802            }
4803
4804            // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4805            // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4806            // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4807            // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4808            if (newNetwork.isVPN()) {
4809                mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4810            }
4811        }
4812        if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4813            for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
4814                if (unneeded(nai)) {
4815                    if (DBG) log("Reaping " + nai.name());
4816                    teardownUnneededNetwork(nai);
4817                }
4818            }
4819        }
4820    }
4821
4822    /**
4823     * Attempt to rematch all Networks with NetworkRequests.  This may result in Networks
4824     * being disconnected.
4825     * @param changed If only one Network's score or capabilities have been modified since the last
4826     *         time this function was called, pass this Network in this argument, otherwise pass
4827     *         null.
4828     * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4829     *         changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4830     *         this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4831     *         {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4832     *         network's score.
4833     */
4834    private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4835        // TODO: This may get slow.  The "changed" parameter is provided for future optimization
4836        // to avoid the slowness.  It is not simply enough to process just "changed", for
4837        // example in the case where "changed"'s score decreases and another network should begin
4838        // satifying a NetworkRequest that "changed" currently satisfies.
4839
4840        // Optimization: Only reprocess "changed" if its score improved.  This is safe because it
4841        // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4842        // rematchNetworkAndRequests() handles.
4843        if (changed != null && oldScore < changed.getCurrentScore()) {
4844            rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
4845        } else {
4846            final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4847                    new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4848            // Rematch higher scoring networks first to prevent requests first matching a lower
4849            // scoring network and then a higher scoring network, which could produce multiple
4850            // callbacks and inadvertently unlinger networks.
4851            Arrays.sort(nais);
4852            for (NetworkAgentInfo nai : nais) {
4853                rematchNetworkAndRequests(nai,
4854                        // Only reap the last time through the loop.  Reaping before all rematching
4855                        // is complete could incorrectly teardown a network that hasn't yet been
4856                        // rematched.
4857                        (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
4858                                : ReapUnvalidatedNetworks.REAP);
4859            }
4860        }
4861    }
4862
4863    private void updateInetCondition(NetworkAgentInfo nai) {
4864        // Don't bother updating until we've graduated to validated at least once.
4865        if (!nai.everValidated) return;
4866        // For now only update icons for default connection.
4867        // TODO: Update WiFi and cellular icons separately. b/17237507
4868        if (!isDefaultNetwork(nai)) return;
4869
4870        int newInetCondition = nai.lastValidated ? 100 : 0;
4871        // Don't repeat publish.
4872        if (newInetCondition == mDefaultInetConditionPublished) return;
4873
4874        mDefaultInetConditionPublished = newInetCondition;
4875        sendInetConditionBroadcast(nai.networkInfo);
4876    }
4877
4878    private void notifyLockdownVpn(NetworkAgentInfo nai) {
4879        if (mLockdownTracker != null) {
4880            if (nai != null && nai.isVPN()) {
4881                mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4882            } else {
4883                mLockdownTracker.onNetworkInfoChanged();
4884            }
4885        }
4886    }
4887
4888    private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4889        NetworkInfo.State state = newInfo.getState();
4890        NetworkInfo oldInfo = null;
4891        final int oldScore = networkAgent.getCurrentScore();
4892        synchronized (networkAgent) {
4893            oldInfo = networkAgent.networkInfo;
4894            networkAgent.networkInfo = newInfo;
4895        }
4896        notifyLockdownVpn(networkAgent);
4897
4898        if (oldInfo != null && oldInfo.getState() == state) {
4899            if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4900                if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4901                notifyIfacesChangedForNetworkStats();
4902            } else if (VDBG) log("ignoring duplicate network state non-change");
4903            // In either case, no further work should be needed.
4904            return;
4905        }
4906        if (DBG) {
4907            log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4908                    (oldInfo == null ? "null" : oldInfo.getState()) +
4909                    " to " + state);
4910        }
4911
4912        if (!networkAgent.created
4913                && (state == NetworkInfo.State.CONNECTED
4914                || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
4915            try {
4916                // This should never fail.  Specifying an already in use NetID will cause failure.
4917                if (networkAgent.isVPN()) {
4918                    mNetd.createVirtualNetwork(networkAgent.network.netId,
4919                            !networkAgent.linkProperties.getDnsServers().isEmpty(),
4920                            (networkAgent.networkMisc == null ||
4921                                !networkAgent.networkMisc.allowBypass));
4922                } else {
4923                    mNetd.createPhysicalNetwork(networkAgent.network.netId,
4924                            networkAgent.networkCapabilities.hasCapability(
4925                                    NET_CAPABILITY_NOT_RESTRICTED) ?
4926                                    null : NetworkManagementService.PERMISSION_SYSTEM);
4927                }
4928            } catch (Exception e) {
4929                loge("Error creating network " + networkAgent.network.netId + ": "
4930                        + e.getMessage());
4931                return;
4932            }
4933            networkAgent.created = true;
4934        }
4935
4936        if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4937            networkAgent.everConnected = true;
4938
4939            updateLinkProperties(networkAgent, null);
4940            notifyIfacesChangedForNetworkStats();
4941
4942            networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
4943            scheduleUnvalidatedPrompt(networkAgent);
4944
4945            if (networkAgent.isVPN()) {
4946                // Temporarily disable the default proxy (not global).
4947                synchronized (mProxyLock) {
4948                    if (!mDefaultProxyDisabled) {
4949                        mDefaultProxyDisabled = true;
4950                        if (mGlobalProxy == null && mDefaultProxy != null) {
4951                            sendProxyBroadcast(null);
4952                        }
4953                    }
4954                }
4955                // TODO: support proxy per network.
4956            }
4957
4958            // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4959            // be communicated to a particular NetworkAgent depends only on the network's immutable,
4960            // capabilities, so it only needs to be done once on initial connect, not every time the
4961            // network's capabilities change. Note that we do this before rematching the network,
4962            // so we could decide to tear it down immediately afterwards. That's fine though - on
4963            // disconnection NetworkAgents should stop any signal strength monitoring they have been
4964            // doing.
4965            updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
4966
4967            // Consider network even though it is not yet validated.
4968            rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
4969
4970            // This has to happen after matching the requests, because callbacks are just requests.
4971            notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
4972        } else if (state == NetworkInfo.State.DISCONNECTED) {
4973            networkAgent.asyncChannel.disconnect();
4974            if (networkAgent.isVPN()) {
4975                synchronized (mProxyLock) {
4976                    if (mDefaultProxyDisabled) {
4977                        mDefaultProxyDisabled = false;
4978                        if (mGlobalProxy == null && mDefaultProxy != null) {
4979                            sendProxyBroadcast(mDefaultProxy);
4980                        }
4981                    }
4982                }
4983            }
4984        } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4985                state == NetworkInfo.State.SUSPENDED) {
4986            // going into or coming out of SUSPEND: rescore and notify
4987            if (networkAgent.getCurrentScore() != oldScore) {
4988                rematchAllNetworksAndRequests(networkAgent, oldScore);
4989            }
4990            notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4991                    ConnectivityManager.CALLBACK_SUSPENDED :
4992                    ConnectivityManager.CALLBACK_RESUMED));
4993            mLegacyTypeTracker.update(networkAgent);
4994        }
4995    }
4996
4997    private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4998        if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
4999        if (score < 0) {
5000            loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5001                    ").  Bumping score to min of 0");
5002            score = 0;
5003        }
5004
5005        final int oldScore = nai.getCurrentScore();
5006        nai.setCurrentScore(score);
5007
5008        rematchAllNetworksAndRequests(nai, oldScore);
5009
5010        sendUpdatedScoreToFactories(nai);
5011    }
5012
5013    // notify only this one new request of the current state
5014    protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5015        int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5016        // TODO - read state from monitor to decide what to send.
5017//        if (nai.networkMonitor.isLingering()) {
5018//            notifyType = NetworkCallbacks.LOSING;
5019//        } else if (nai.networkMonitor.isEvaluating()) {
5020//            notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5021//        }
5022        if (nri.mPendingIntent == null) {
5023            callCallbackForRequest(nri, nai, notifyType);
5024        } else {
5025            sendPendingIntentForRequest(nri, nai, notifyType);
5026        }
5027    }
5028
5029    private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
5030        // The NetworkInfo we actually send out has no bearing on the real
5031        // state of affairs. For example, if the default connection is mobile,
5032        // and a request for HIPRI has just gone away, we need to pretend that
5033        // HIPRI has just disconnected. So we need to set the type to HIPRI and
5034        // the state to DISCONNECTED, even though the network is of type MOBILE
5035        // and is still connected.
5036        NetworkInfo info = new NetworkInfo(nai.networkInfo);
5037        info.setType(type);
5038        if (state != DetailedState.DISCONNECTED) {
5039            info.setDetailedState(state, null, info.getExtraInfo());
5040            sendConnectedBroadcast(info);
5041        } else {
5042            info.setDetailedState(state, info.getReason(), info.getExtraInfo());
5043            Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5044            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5045            intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5046            if (info.isFailover()) {
5047                intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5048                nai.networkInfo.setFailover(false);
5049            }
5050            if (info.getReason() != null) {
5051                intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5052            }
5053            if (info.getExtraInfo() != null) {
5054                intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5055            }
5056            NetworkAgentInfo newDefaultAgent = null;
5057            if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
5058                newDefaultAgent = getDefaultNetwork();
5059                if (newDefaultAgent != null) {
5060                    intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5061                            newDefaultAgent.networkInfo);
5062                } else {
5063                    intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5064                }
5065            }
5066            intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5067                    mDefaultInetConditionPublished);
5068            sendStickyBroadcast(intent);
5069            if (newDefaultAgent != null) {
5070                sendConnectedBroadcast(newDefaultAgent.networkInfo);
5071            }
5072        }
5073    }
5074
5075    protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5076        if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
5077        for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5078            NetworkRequest nr = networkAgent.requestAt(i);
5079            NetworkRequestInfo nri = mNetworkRequests.get(nr);
5080            if (VDBG) log(" sending notification for " + nr);
5081            if (nri.mPendingIntent == null) {
5082                callCallbackForRequest(nri, networkAgent, notifyType);
5083            } else {
5084                sendPendingIntentForRequest(nri, networkAgent, notifyType);
5085            }
5086        }
5087    }
5088
5089    private String notifyTypeToName(int notifyType) {
5090        switch (notifyType) {
5091            case ConnectivityManager.CALLBACK_PRECHECK:    return "PRECHECK";
5092            case ConnectivityManager.CALLBACK_AVAILABLE:   return "AVAILABLE";
5093            case ConnectivityManager.CALLBACK_LOSING:      return "LOSING";
5094            case ConnectivityManager.CALLBACK_LOST:        return "LOST";
5095            case ConnectivityManager.CALLBACK_UNAVAIL:     return "UNAVAILABLE";
5096            case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5097            case ConnectivityManager.CALLBACK_IP_CHANGED:  return "IP_CHANGED";
5098            case ConnectivityManager.CALLBACK_RELEASED:    return "RELEASED";
5099        }
5100        return "UNKNOWN";
5101    }
5102
5103    /**
5104     * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5105     * properties tracked by NetworkStatsService on an active iface has changed.
5106     */
5107    private void notifyIfacesChangedForNetworkStats() {
5108        try {
5109            mStatsService.forceUpdateIfaces();
5110        } catch (Exception ignored) {
5111        }
5112    }
5113
5114    @Override
5115    public boolean addVpnAddress(String address, int prefixLength) {
5116        throwIfLockdownEnabled();
5117        int user = UserHandle.getUserId(Binder.getCallingUid());
5118        synchronized (mVpns) {
5119            return mVpns.get(user).addAddress(address, prefixLength);
5120        }
5121    }
5122
5123    @Override
5124    public boolean removeVpnAddress(String address, int prefixLength) {
5125        throwIfLockdownEnabled();
5126        int user = UserHandle.getUserId(Binder.getCallingUid());
5127        synchronized (mVpns) {
5128            return mVpns.get(user).removeAddress(address, prefixLength);
5129        }
5130    }
5131
5132    @Override
5133    public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5134        throwIfLockdownEnabled();
5135        int user = UserHandle.getUserId(Binder.getCallingUid());
5136        boolean success;
5137        synchronized (mVpns) {
5138            success = mVpns.get(user).setUnderlyingNetworks(networks);
5139        }
5140        if (success) {
5141            notifyIfacesChangedForNetworkStats();
5142        }
5143        return success;
5144    }
5145
5146    @Override
5147    public String getCaptivePortalServerUrl() {
5148        return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5149    }
5150
5151    @Override
5152    public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5153            IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5154        enforceKeepalivePermission();
5155        mKeepaliveTracker.startNattKeepalive(
5156                getNetworkAgentInfoForNetwork(network),
5157                intervalSeconds, messenger, binder,
5158                srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5159    }
5160
5161    @Override
5162    public void stopKeepalive(Network network, int slot) {
5163        mHandler.sendMessage(mHandler.obtainMessage(
5164                NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5165    }
5166
5167    @Override
5168    public void factoryReset() {
5169        enforceConnectivityInternalPermission();
5170
5171        if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5172            return;
5173        }
5174
5175        final int userId = UserHandle.getCallingUserId();
5176
5177        // Turn airplane mode off
5178        setAirplaneMode(false);
5179
5180        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5181            // Untether
5182            for (String tether : getTetheredIfaces()) {
5183                untether(tether);
5184            }
5185        }
5186
5187        if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5188            // Remove always-on package
5189            synchronized (mVpns) {
5190                final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5191                if (alwaysOnPackage != null) {
5192                    setAlwaysOnVpnPackage(userId, null, false);
5193                    setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5194                }
5195            }
5196
5197            // Turn VPN off
5198            VpnConfig vpnConfig = getVpnConfig(userId);
5199            if (vpnConfig != null) {
5200                if (vpnConfig.legacy) {
5201                    prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5202                } else {
5203                    // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5204                    // in the future without user intervention.
5205                    setVpnPackageAuthorization(vpnConfig.user, userId, false);
5206
5207                    prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5208                }
5209            }
5210        }
5211    }
5212
5213    @VisibleForTesting
5214    public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5215            NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5216        return new NetworkMonitor(context, handler, nai, defaultRequest);
5217    }
5218
5219    private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5220        int newNetid = NETID_UNSET;
5221        int prevNetid = NETID_UNSET;
5222        int[] transports = new int[0];
5223        boolean hadIPv4 = false;
5224        boolean hadIPv6 = false;
5225
5226        if (newNai != null) {
5227            newNetid = newNai.network.netId;
5228            transports = newNai.networkCapabilities.getTransportTypes();
5229        }
5230        if (prevNai != null) {
5231            prevNetid = prevNai.network.netId;
5232            final LinkProperties lp = prevNai.linkProperties;
5233            hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5234            hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5235        }
5236
5237        mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5238    }
5239
5240    private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5241        mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
5242    }
5243}
5244