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