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