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