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