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