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