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