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