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