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