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