ConnectivityService.java revision a1540899f7c5a5e7b9c117baa2a87710e9d881e6
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.RULE_NONE;
34import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
35import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
36import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
37import static android.net.NetworkPolicyManager.uidRulesToString;
38
39import android.annotation.Nullable;
40import android.app.BroadcastOptions;
41import android.app.Notification;
42import android.app.NotificationManager;
43import android.app.PendingIntent;
44import android.content.BroadcastReceiver;
45import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
48import android.content.IntentFilter;
49import android.content.pm.PackageManager;
50import android.content.res.Configuration;
51import android.content.res.Resources;
52import android.database.ContentObserver;
53import android.net.ConnectivityManager;
54import android.net.ConnectivityManager.PacketKeepalive;
55import android.net.IConnectivityManager;
56import android.net.INetworkManagementEventObserver;
57import android.net.INetworkPolicyListener;
58import android.net.INetworkPolicyManager;
59import android.net.INetworkStatsService;
60import android.net.LinkProperties;
61import android.net.LinkProperties.CompareResult;
62import android.net.Network;
63import android.net.NetworkAgent;
64import android.net.NetworkCapabilities;
65import android.net.NetworkConfig;
66import android.net.NetworkInfo;
67import android.net.NetworkInfo.DetailedState;
68import android.net.NetworkMisc;
69import android.net.NetworkQuotaInfo;
70import android.net.NetworkRequest;
71import android.net.NetworkState;
72import android.net.NetworkUtils;
73import android.net.Proxy;
74import android.net.ProxyInfo;
75import android.net.RouteInfo;
76import android.net.UidRange;
77import android.net.Uri;
78import android.net.metrics.DefaultNetworkEvent;
79import android.net.metrics.NetworkEvent;
80import android.os.Binder;
81import android.os.Build;
82import android.os.Bundle;
83import android.os.FileUtils;
84import android.os.Handler;
85import android.os.HandlerThread;
86import android.os.IBinder;
87import android.os.INetworkManagementService;
88import android.os.Looper;
89import android.os.Message;
90import android.os.Messenger;
91import android.os.ParcelFileDescriptor;
92import android.os.PowerManager;
93import android.os.Process;
94import android.os.RemoteException;
95import android.os.ResultReceiver;
96import android.os.SystemProperties;
97import android.os.UserHandle;
98import android.os.UserManager;
99import android.provider.Settings;
100import android.security.Credentials;
101import android.security.KeyStore;
102import android.telephony.TelephonyManager;
103import android.text.TextUtils;
104import android.util.ArraySet;
105import android.util.LocalLog;
106import android.util.LocalLog.ReadOnlyLocalLog;
107import android.util.Log;
108import android.util.Pair;
109import android.util.Slog;
110import android.util.SparseArray;
111import android.util.SparseBooleanArray;
112import android.util.SparseIntArray;
113import android.util.Xml;
114
115import com.android.internal.R;
116import com.android.internal.annotations.GuardedBy;
117import com.android.internal.annotations.VisibleForTesting;
118import com.android.internal.app.IBatteryStats;
119import com.android.internal.net.LegacyVpnInfo;
120import com.android.internal.net.NetworkStatsFactory;
121import com.android.internal.net.VpnConfig;
122import com.android.internal.net.VpnInfo;
123import com.android.internal.net.VpnProfile;
124import com.android.internal.util.AsyncChannel;
125import com.android.internal.util.IndentingPrintWriter;
126import com.android.internal.util.MessageUtils;
127import com.android.internal.util.XmlUtils;
128import com.android.server.am.BatteryStatsService;
129import com.android.server.connectivity.DataConnectionStats;
130import com.android.server.connectivity.KeepaliveTracker;
131import com.android.server.connectivity.Nat464Xlat;
132import com.android.server.connectivity.NetworkAgentInfo;
133import com.android.server.connectivity.NetworkDiagnostics;
134import com.android.server.connectivity.NetworkMonitor;
135import com.android.server.connectivity.PacManager;
136import com.android.server.connectivity.PermissionMonitor;
137import com.android.server.connectivity.Tethering;
138import com.android.server.connectivity.Vpn;
139import com.android.server.net.BaseNetworkObserver;
140import com.android.server.net.LockdownVpnTracker;
141
142import com.google.android.collect.Lists;
143
144import org.xmlpull.v1.XmlPullParser;
145import org.xmlpull.v1.XmlPullParserException;
146
147import java.io.File;
148import java.io.FileDescriptor;
149import java.io.FileNotFoundException;
150import java.io.FileReader;
151import java.io.IOException;
152import java.io.PrintWriter;
153import java.net.Inet4Address;
154import java.net.InetAddress;
155import java.net.UnknownHostException;
156import java.util.ArrayDeque;
157import java.util.ArrayList;
158import java.util.Arrays;
159import java.util.Collection;
160import java.util.HashMap;
161import java.util.HashSet;
162import java.util.List;
163import java.util.Map;
164import java.util.Objects;
165import java.util.SortedSet;
166import java.util.TreeSet;
167
168/**
169 * @hide
170 */
171public class ConnectivityService extends IConnectivityManager.Stub
172        implements PendingIntent.OnFinished {
173    private static final String TAG = "ConnectivityService";
174
175    private static final boolean DBG = true;
176    private static final boolean VDBG = false;
177
178    private static final boolean LOGD_RULES = false;
179    private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
180
181    // TODO: create better separation between radio types and network types
182
183    // how long to wait before switching back to a radio's default network
184    private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
185    // system property that can override the above value
186    private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
187            "android.telephony.apn-restore";
188
189    // How long to wait before putting up a "This network doesn't have an Internet connection,
190    // connect anyway?" dialog after the user selects a network that doesn't validate.
191    private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
192
193    // How long to delay to removal of a pending intent based request.
194    // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
195    private final int mReleasePendingIntentDelayMs;
196
197    private Tethering mTethering;
198
199    private final PermissionMonitor mPermissionMonitor;
200
201    private KeyStore mKeyStore;
202
203    @GuardedBy("mVpns")
204    private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
205
206    private boolean mLockdownEnabled;
207    private LockdownVpnTracker mLockdownTracker;
208
209    /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
210    private Object mRulesLock = new Object();
211    /** Currently active network rules by UID. */
212    @GuardedBy("mRulesLock")
213    private SparseIntArray mUidRules = new SparseIntArray();
214    /** Set of ifaces that are costly. */
215    @GuardedBy("mRulesLock")
216    private ArraySet<String> mMeteredIfaces = new ArraySet<>();
217    /** Flag indicating if background data is restricted. */
218    @GuardedBy("mRulesLock")
219    private boolean mRestrictBackground;
220
221    final private Context mContext;
222    private int mNetworkPreference;
223    // 0 is full bad, 100 is full good
224    private int mDefaultInetConditionPublished = 0;
225
226    private int mNumDnsEntries;
227
228    private boolean mTestMode;
229    private static ConnectivityService sServiceInstance;
230
231    private INetworkManagementService mNetd;
232    private INetworkStatsService mStatsService;
233    private INetworkPolicyManager mPolicyManager;
234
235    private String mCurrentTcpBufferSizes;
236
237    private static final int ENABLED  = 1;
238    private static final int DISABLED = 0;
239
240    private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
241            new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
242
243    private enum ReapUnvalidatedNetworks {
244        // Tear down networks that have no chance (e.g. even if validated) of becoming
245        // the highest scoring network satisfying a NetworkRequest.  This should be passed when
246        // all networks have been rematched against all NetworkRequests.
247        REAP,
248        // Don't reap networks.  This should be passed when some networks have not yet been
249        // rematched against all NetworkRequests.
250        DONT_REAP
251    };
252
253    /**
254     * used internally to change our mobile data enabled flag
255     */
256    private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
257
258    /**
259     * used internally to clear a wakelock when transitioning
260     * from one net to another.  Clear happens when we get a new
261     * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
262     * after a timeout if no network is found (typically 1 min).
263     */
264    private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
265
266    /**
267     * used internally to reload global proxy settings
268     */
269    private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
270
271    /**
272     * PAC manager has received new port.
273     */
274    private static final int EVENT_PROXY_HAS_CHANGED = 16;
275
276    /**
277     * used internally when registering NetworkFactories
278     * obj = NetworkFactoryInfo
279     */
280    private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
281
282    /**
283     * used internally when registering NetworkAgents
284     * obj = Messenger
285     */
286    private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
287
288    /**
289     * used to add a network request
290     * includes a NetworkRequestInfo
291     */
292    private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
293
294    /**
295     * indicates a timeout period is over - check if we had a network yet or not
296     * and if not, call the timeout calback (but leave the request live until they
297     * cancel it.
298     * includes a NetworkRequestInfo
299     */
300    private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
301
302    /**
303     * used to add a network listener - no request
304     * includes a NetworkRequestInfo
305     */
306    private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
307
308    /**
309     * used to remove a network request, either a listener or a real request
310     * arg1 = UID of caller
311     * obj  = NetworkRequest
312     */
313    private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
314
315    /**
316     * used internally when registering NetworkFactories
317     * obj = Messenger
318     */
319    private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
320
321    /**
322     * used internally to expire a wakelock when transitioning
323     * from one net to another.  Expire happens when we fail to find
324     * a new network (typically after 1 minute) -
325     * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
326     * a replacement network.
327     */
328    private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
329
330    /**
331     * Used internally to indicate the system is ready.
332     */
333    private static final int EVENT_SYSTEM_READY = 25;
334
335    /**
336     * used to add a network request with a pending intent
337     * obj = NetworkRequestInfo
338     */
339    private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
340
341    /**
342     * used to remove a pending intent and its associated network request.
343     * arg1 = UID of caller
344     * obj  = PendingIntent
345     */
346    private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
347
348    /**
349     * used to specify whether a network should be used even if unvalidated.
350     * arg1 = whether to accept the network if it's unvalidated (1 or 0)
351     * arg2 = whether to remember this choice in the future (1 or 0)
352     * obj  = network
353     */
354    private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
355
356    /**
357     * used to ask the user to confirm a connection to an unvalidated network.
358     * obj  = network
359     */
360    private static final int EVENT_PROMPT_UNVALIDATED = 29;
361
362    /**
363     * used internally to (re)configure mobile data always-on settings.
364     */
365    private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
366
367    /**
368     * used to add a network listener with a pending intent
369     * obj = NetworkRequestInfo
370     */
371    private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
372
373    /** Handler thread used for both of the handlers below. */
374    @VisibleForTesting
375    protected final HandlerThread mHandlerThread;
376    /** Handler used for internal events. */
377    final private InternalHandler mHandler;
378    /** Handler used for incoming {@link NetworkStateTracker} events. */
379    final private NetworkStateTrackerHandler mTrackerHandler;
380
381    private boolean mSystemReady;
382    private Intent mInitialBroadcast;
383
384    private PowerManager.WakeLock mNetTransitionWakeLock;
385    private String mNetTransitionWakeLockCausedBy = "";
386    private int mNetTransitionWakeLockSerialNumber;
387    private int mNetTransitionWakeLockTimeout;
388    private final PowerManager.WakeLock mPendingIntentWakeLock;
389
390    // used in DBG mode to track inet condition reports
391    private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
392    private ArrayList mInetLog;
393
394    // track the current default http proxy - tell the world if we get a new one (real change)
395    private volatile ProxyInfo mDefaultProxy = null;
396    private Object mProxyLock = new Object();
397    private boolean mDefaultProxyDisabled = false;
398
399    // track the global proxy.
400    private ProxyInfo mGlobalProxy = null;
401
402    private PacManager mPacManager = null;
403
404    final private SettingsObserver mSettingsObserver;
405
406    private UserManager mUserManager;
407
408    NetworkConfig[] mNetConfigs;
409    int mNetworksDefined;
410
411    // the set of network types that can only be enabled by system/sig apps
412    List mProtectedNetworks;
413
414    private DataConnectionStats mDataConnectionStats;
415
416    TelephonyManager mTelephonyManager;
417
418    private KeepaliveTracker mKeepaliveTracker;
419
420    // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
421    private final static int MIN_NET_ID = 100; // some reserved marks
422    private final static int MAX_NET_ID = 65535;
423    private int mNextNetId = MIN_NET_ID;
424
425    // sequence number of NetworkRequests
426    private int mNextNetworkRequestId = 1;
427
428    // NetworkRequest activity String log entries.
429    private static final int MAX_NETWORK_REQUEST_LOGS = 20;
430    private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
431
432    // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
433    private static final int MAX_VALIDATION_LOGS = 10;
434    private static class ValidationLog {
435        final Network mNetwork;
436        final String mNetworkExtraInfo;
437        final ReadOnlyLocalLog mLog;
438
439        ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
440            mNetwork = network;
441            mNetworkExtraInfo = networkExtraInfo;
442            mLog = log;
443        }
444    }
445    private final ArrayDeque<ValidationLog> mValidationLogs =
446            new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
447
448    private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
449        synchronized(mValidationLogs) {
450            while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
451                mValidationLogs.removeLast();
452            }
453            mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
454        }
455    }
456
457    /**
458     * Implements support for the legacy "one network per network type" model.
459     *
460     * We used to have a static array of NetworkStateTrackers, one for each
461     * network type, but that doesn't work any more now that we can have,
462     * for example, more that one wifi network. This class stores all the
463     * NetworkAgentInfo objects that support a given type, but the legacy
464     * API will only see the first one.
465     *
466     * It serves two main purposes:
467     *
468     * 1. Provide information about "the network for a given type" (since this
469     *    API only supports one).
470     * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
471     *    the first network for a given type changes, or if the default network
472     *    changes.
473     */
474    private class LegacyTypeTracker {
475
476        private static final boolean DBG = true;
477        private static final boolean VDBG = false;
478
479        /**
480         * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
481         * Each list holds references to all NetworkAgentInfos that are used to
482         * satisfy requests for that network type.
483         *
484         * This array is built out at startup such that an unsupported network
485         * doesn't get an ArrayList instance, making this a tristate:
486         * unsupported, supported but not active and active.
487         *
488         * The actual lists are populated when we scan the network types that
489         * are supported on this device.
490         */
491        private ArrayList<NetworkAgentInfo> mTypeLists[];
492
493        public LegacyTypeTracker() {
494            mTypeLists = (ArrayList<NetworkAgentInfo>[])
495                    new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
496        }
497
498        public void addSupportedType(int type) {
499            if (mTypeLists[type] != null) {
500                throw new IllegalStateException(
501                        "legacy list for type " + type + "already initialized");
502            }
503            mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
504        }
505
506        public boolean isTypeSupported(int type) {
507            return isNetworkTypeValid(type) && mTypeLists[type] != null;
508        }
509
510        public NetworkAgentInfo getNetworkForType(int type) {
511            if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
512                return mTypeLists[type].get(0);
513            } else {
514                return null;
515            }
516        }
517
518        private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
519                boolean isDefaultNetwork) {
520            if (DBG) {
521                log("Sending " + state +
522                        " broadcast for type " + type + " " + nai.name() +
523                        " isDefaultNetwork=" + isDefaultNetwork);
524            }
525        }
526
527        /** Adds the given network to the specified legacy type list. */
528        public void add(int type, NetworkAgentInfo nai) {
529            if (!isTypeSupported(type)) {
530                return;  // Invalid network type.
531            }
532            if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
533
534            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
535            if (list.contains(nai)) {
536                return;
537            }
538
539            list.add(nai);
540
541            // Send a broadcast if this is the first network of its type or if it's the default.
542            final boolean isDefaultNetwork = isDefaultNetwork(nai);
543            if (list.size() == 1 || isDefaultNetwork) {
544                maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
545                sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
546            }
547        }
548
549        /** Removes the given network from the specified legacy type list. */
550        public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
551            ArrayList<NetworkAgentInfo> list = mTypeLists[type];
552            if (list == null || list.isEmpty()) {
553                return;
554            }
555
556            final boolean wasFirstNetwork = list.get(0).equals(nai);
557
558            if (!list.remove(nai)) {
559                return;
560            }
561
562            final DetailedState state = DetailedState.DISCONNECTED;
563
564            if (wasFirstNetwork || wasDefault) {
565                maybeLogBroadcast(nai, state, type, wasDefault);
566                sendLegacyNetworkBroadcast(nai, state, type);
567            }
568
569            if (!list.isEmpty() && wasFirstNetwork) {
570                if (DBG) log("Other network available for type " + type +
571                              ", sending connected broadcast");
572                final NetworkAgentInfo replacement = list.get(0);
573                maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
574                sendLegacyNetworkBroadcast(replacement, state, type);
575            }
576        }
577
578        /** Removes the given network from all legacy type lists. */
579        public void remove(NetworkAgentInfo nai, boolean wasDefault) {
580            if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
581            for (int type = 0; type < mTypeLists.length; type++) {
582                remove(type, nai, wasDefault);
583            }
584        }
585
586        // send out another legacy broadcast - currently only used for suspend/unsuspend
587        // toggle
588        public void update(NetworkAgentInfo nai) {
589            final boolean isDefault = isDefaultNetwork(nai);
590            final DetailedState state = nai.networkInfo.getDetailedState();
591            for (int type = 0; type < mTypeLists.length; type++) {
592                final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
593                final boolean contains = (list != null && list.contains(nai));
594                final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
595                if (isFirst || (contains && isDefault)) {
596                    maybeLogBroadcast(nai, state, type, isDefault);
597                    sendLegacyNetworkBroadcast(nai, state, type);
598                }
599            }
600        }
601
602        private String naiToString(NetworkAgentInfo nai) {
603            String name = (nai != null) ? nai.name() : "null";
604            String state = (nai.networkInfo != null) ?
605                    nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
606                    "???/???";
607            return name + " " + state;
608        }
609
610        public void dump(IndentingPrintWriter pw) {
611            pw.println("mLegacyTypeTracker:");
612            pw.increaseIndent();
613            pw.print("Supported types:");
614            for (int type = 0; type < mTypeLists.length; type++) {
615                if (mTypeLists[type] != null) pw.print(" " + type);
616            }
617            pw.println();
618            pw.println("Current state:");
619            pw.increaseIndent();
620            for (int type = 0; type < mTypeLists.length; type++) {
621                if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
622                for (NetworkAgentInfo nai : mTypeLists[type]) {
623                    pw.println(type + " " + naiToString(nai));
624                }
625            }
626            pw.decreaseIndent();
627            pw.decreaseIndent();
628            pw.println();
629        }
630    }
631    private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
632
633    @VisibleForTesting
634    protected HandlerThread createHandlerThread() {
635        return new HandlerThread("ConnectivityServiceThread");
636    }
637
638    public ConnectivityService(Context context, INetworkManagementService netManager,
639            INetworkStatsService statsService, INetworkPolicyManager policyManager) {
640        if (DBG) log("ConnectivityService starting up");
641
642        mDefaultRequest = createInternetRequestForTransport(-1);
643        NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
644                new Binder(), NetworkRequestType.REQUEST);
645        mNetworkRequests.put(mDefaultRequest, defaultNRI);
646        mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
647
648        mDefaultMobileDataRequest = createInternetRequestForTransport(
649                NetworkCapabilities.TRANSPORT_CELLULAR);
650
651        mHandlerThread = createHandlerThread();
652        mHandlerThread.start();
653        mHandler = new InternalHandler(mHandlerThread.getLooper());
654        mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
655
656        // setup our unique device name
657        if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
658            String id = Settings.Secure.getString(context.getContentResolver(),
659                    Settings.Secure.ANDROID_ID);
660            if (id != null && id.length() > 0) {
661                String name = new String("android-").concat(id);
662                SystemProperties.set("net.hostname", name);
663            }
664        }
665
666        mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
667                Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
668
669        mContext = checkNotNull(context, "missing Context");
670        mNetd = checkNotNull(netManager, "missing INetworkManagementService");
671        mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
672        mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
673        mKeyStore = KeyStore.getInstance();
674        mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
675
676        try {
677            mPolicyManager.setConnectivityListener(mPolicyListener);
678            mRestrictBackground = mPolicyManager.getRestrictBackground();
679        } catch (RemoteException e) {
680            // ouch, no rules updates means some processes may never get network
681            loge("unable to register INetworkPolicyListener" + e);
682        }
683
684        final PowerManager powerManager = (PowerManager) context.getSystemService(
685                Context.POWER_SERVICE);
686        mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
687        mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
688                com.android.internal.R.integer.config_networkTransitionTimeout);
689        mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
690
691        mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
692
693        // TODO: What is the "correct" way to do determine if this is a wifi only device?
694        boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
695        log("wifiOnly=" + wifiOnly);
696        String[] naStrings = context.getResources().getStringArray(
697                com.android.internal.R.array.networkAttributes);
698        for (String naString : naStrings) {
699            try {
700                NetworkConfig n = new NetworkConfig(naString);
701                if (VDBG) log("naString=" + naString + " config=" + n);
702                if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
703                    loge("Error in networkAttributes - ignoring attempt to define type " +
704                            n.type);
705                    continue;
706                }
707                if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
708                    log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
709                            n.type);
710                    continue;
711                }
712                if (mNetConfigs[n.type] != null) {
713                    loge("Error in networkAttributes - ignoring attempt to redefine type " +
714                            n.type);
715                    continue;
716                }
717                mLegacyTypeTracker.addSupportedType(n.type);
718
719                mNetConfigs[n.type] = n;
720                mNetworksDefined++;
721            } catch(Exception e) {
722                // ignore it - leave the entry null
723            }
724        }
725
726        // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
727        if (mNetConfigs[TYPE_VPN] == null) {
728            // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
729            // don't need to add TYPE_VPN to mNetConfigs.
730            mLegacyTypeTracker.addSupportedType(TYPE_VPN);
731            mNetworksDefined++;  // used only in the log() statement below.
732        }
733
734        if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
735
736        mProtectedNetworks = new ArrayList<Integer>();
737        int[] protectedNetworks = context.getResources().getIntArray(
738                com.android.internal.R.array.config_protectedNetworks);
739        for (int p : protectedNetworks) {
740            if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
741                mProtectedNetworks.add(p);
742            } else {
743                if (DBG) loge("Ignoring protectedNetwork " + p);
744            }
745        }
746
747        mTestMode = SystemProperties.get("cm.test.mode").equals("true")
748                && SystemProperties.get("ro.build.type").equals("eng");
749
750        mTethering = new Tethering(mContext, mNetd, statsService);
751
752        mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
753
754        //set up the listener for user state for creating user VPNs
755        IntentFilter intentFilter = new IntentFilter();
756        intentFilter.addAction(Intent.ACTION_USER_STARTED);
757        intentFilter.addAction(Intent.ACTION_USER_STOPPED);
758        intentFilter.addAction(Intent.ACTION_USER_ADDED);
759        intentFilter.addAction(Intent.ACTION_USER_REMOVED);
760        intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
761        mContext.registerReceiverAsUser(
762                mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
763
764        try {
765            mNetd.registerObserver(mTethering);
766            mNetd.registerObserver(mDataActivityObserver);
767        } catch (RemoteException e) {
768            loge("Error registering observer :" + e);
769        }
770
771        if (DBG) {
772            mInetLog = new ArrayList();
773        }
774
775        mSettingsObserver = new SettingsObserver(mContext, mHandler);
776        registerSettingsCallbacks();
777
778        mDataConnectionStats = new DataConnectionStats(mContext);
779        mDataConnectionStats.startMonitoring();
780
781        mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
782
783        mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
784
785        mKeepaliveTracker = new KeepaliveTracker(mHandler);
786    }
787
788    private NetworkRequest createInternetRequestForTransport(int transportType) {
789        NetworkCapabilities netCap = new NetworkCapabilities();
790        netCap.addCapability(NET_CAPABILITY_INTERNET);
791        netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
792        if (transportType > -1) {
793            netCap.addTransportType(transportType);
794        }
795        return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
796    }
797
798    // Used only for testing.
799    // TODO: Delete this and either:
800    // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
801    //    changing ContentResolver to make registerContentObserver non-final).
802    // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
803    //    by subclassing SettingsObserver.
804    @VisibleForTesting
805    void updateMobileDataAlwaysOn() {
806        mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
807    }
808
809    private void handleMobileDataAlwaysOn() {
810        final boolean enable = (Settings.Global.getInt(
811                mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
812        final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
813        if (enable == isEnabled) {
814            return;  // Nothing to do.
815        }
816
817        if (enable) {
818            handleRegisterNetworkRequest(new NetworkRequestInfo(
819                    null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
820        } else {
821            handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
822        }
823    }
824
825    private void registerSettingsCallbacks() {
826        // Watch for global HTTP proxy changes.
827        mSettingsObserver.observe(
828                Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
829                EVENT_APPLY_GLOBAL_HTTP_PROXY);
830
831        // Watch for whether or not to keep mobile data always on.
832        mSettingsObserver.observe(
833                Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
834                EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
835    }
836
837    private synchronized int nextNetworkRequestId() {
838        return mNextNetworkRequestId++;
839    }
840
841    @VisibleForTesting
842    protected int reserveNetId() {
843        synchronized (mNetworkForNetId) {
844            for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
845                int netId = mNextNetId;
846                if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
847                // Make sure NetID unused.  http://b/16815182
848                if (!mNetIdInUse.get(netId)) {
849                    mNetIdInUse.put(netId, true);
850                    return netId;
851                }
852            }
853        }
854        throw new IllegalStateException("No free netIds");
855    }
856
857    private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
858        if (mLegacyTypeTracker.isTypeSupported(networkType)) {
859            final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
860            final NetworkState state;
861            if (nai != null) {
862                state = nai.getNetworkState();
863                state.networkInfo.setType(networkType);
864            } else {
865                final NetworkInfo info = new NetworkInfo(networkType, 0,
866                        getNetworkTypeName(networkType), "");
867                info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
868                info.setIsAvailable(true);
869                state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
870                        null, null, null);
871            }
872            filterNetworkStateForUid(state, uid, ignoreBlocked);
873            return state;
874        } else {
875            return NetworkState.EMPTY;
876        }
877    }
878
879    private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
880        if (network == null) {
881            return null;
882        }
883        synchronized (mNetworkForNetId) {
884            return mNetworkForNetId.get(network.netId);
885        }
886    }
887
888    private Network[] getVpnUnderlyingNetworks(int uid) {
889        if (!mLockdownEnabled) {
890            int user = UserHandle.getUserId(uid);
891            synchronized (mVpns) {
892                Vpn vpn = mVpns.get(user);
893                if (vpn != null && vpn.appliesToUid(uid)) {
894                    return vpn.getUnderlyingNetworks();
895                }
896            }
897        }
898        return null;
899    }
900
901    private NetworkState getUnfilteredActiveNetworkState(int uid) {
902        NetworkAgentInfo nai = getDefaultNetwork();
903
904        final Network[] networks = getVpnUnderlyingNetworks(uid);
905        if (networks != null) {
906            // getUnderlyingNetworks() returns:
907            // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
908            // empty array => the VPN explicitly said "no default network".
909            // non-empty array => the VPN specified one or more default networks; we use the
910            //                    first one.
911            if (networks.length > 0) {
912                nai = getNetworkAgentInfoForNetwork(networks[0]);
913            } else {
914                nai = null;
915            }
916        }
917
918        if (nai != null) {
919            return nai.getNetworkState();
920        } else {
921            return NetworkState.EMPTY;
922        }
923    }
924
925    /**
926     * Check if UID should be blocked from using the network with the given LinkProperties.
927     */
928    private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
929            boolean ignoreBlocked) {
930        // Networks aren't blocked when ignoring blocked status
931        if (ignoreBlocked) return false;
932        // Networks are never blocked for system services
933        if (isSystem(uid)) return false;
934
935        final boolean networkMetered;
936        final int uidRules;
937
938        synchronized (mVpns) {
939            final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
940            if (vpn != null && vpn.isBlockingUid(uid)) {
941                return true;
942            }
943        }
944
945        final String iface = (lp == null ? "" : lp.getInterfaceName());
946        synchronized (mRulesLock) {
947            networkMetered = mMeteredIfaces.contains(iface);
948            uidRules = mUidRules.get(uid, RULE_NONE);
949        }
950
951        boolean allowed = true;
952        // Check Data Saver Mode first...
953        if (networkMetered) {
954            if ((uidRules & RULE_REJECT_METERED) != 0) {
955                if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
956                // Explicitly blacklisted.
957                allowed = false;
958            } else {
959                allowed = !mRestrictBackground
960                      || (uidRules & RULE_ALLOW_METERED) != 0
961                      || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
962                if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
963                        + " mRestrictBackground=" + mRestrictBackground
964                        + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
965                        + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
966                        + ": " + allowed);
967            }
968        }
969        // ...then power restrictions.
970        if (allowed) {
971            allowed = (uidRules & RULE_REJECT_ALL) == 0;
972            if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
973                    + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
974        }
975        return !allowed;
976    }
977
978    private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
979        if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
980        boolean removed = false;
981        boolean added = false;
982        synchronized (mBlockedAppUids) {
983            if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
984                added = true;
985            } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
986                removed = true;
987            }
988        }
989        if (added) log("Returning blocked NetworkInfo to uid=" + uid);
990        else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
991    }
992
993    /**
994     * Apply any relevant filters to {@link NetworkState} for the given UID. For
995     * example, this may mark the network as {@link DetailedState#BLOCKED} based
996     * on {@link #isNetworkWithLinkPropertiesBlocked}, or
997     * {@link NetworkInfo#isMetered()} based on network policies.
998     */
999    private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
1000        if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1001
1002        if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
1003            state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
1004        }
1005        if (mLockdownTracker != null) {
1006            mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1007        }
1008
1009        // TODO: apply metered state closer to NetworkAgentInfo
1010        final long token = Binder.clearCallingIdentity();
1011        try {
1012            state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1013        } catch (RemoteException e) {
1014        } finally {
1015            Binder.restoreCallingIdentity(token);
1016        }
1017    }
1018
1019    /**
1020     * Return NetworkInfo for the active (i.e., connected) network interface.
1021     * It is assumed that at most one network is active at a time. If more
1022     * than one is active, it is indeterminate which will be returned.
1023     * @return the info for the active network, or {@code null} if none is
1024     * active
1025     */
1026    @Override
1027    public NetworkInfo getActiveNetworkInfo() {
1028        enforceAccessPermission();
1029        final int uid = Binder.getCallingUid();
1030        final NetworkState state = getUnfilteredActiveNetworkState(uid);
1031        filterNetworkStateForUid(state, uid, false);
1032        maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1033        return state.networkInfo;
1034    }
1035
1036    @Override
1037    public Network getActiveNetwork() {
1038        enforceAccessPermission();
1039        return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
1040    }
1041
1042    @Override
1043    public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
1044        enforceConnectivityInternalPermission();
1045        return getActiveNetworkForUidInternal(uid, ignoreBlocked);
1046    }
1047
1048    private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
1049        final int user = UserHandle.getUserId(uid);
1050        int vpnNetId = NETID_UNSET;
1051        synchronized (mVpns) {
1052            final Vpn vpn = mVpns.get(user);
1053            if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1054        }
1055        NetworkAgentInfo nai;
1056        if (vpnNetId != NETID_UNSET) {
1057            synchronized (mNetworkForNetId) {
1058                nai = mNetworkForNetId.get(vpnNetId);
1059            }
1060            if (nai != null) return nai.network;
1061        }
1062        nai = getDefaultNetwork();
1063        if (nai != null
1064                && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1065            nai = null;
1066        }
1067        return nai != null ? nai.network : null;
1068    }
1069
1070    public NetworkInfo getActiveNetworkInfoUnfiltered() {
1071        enforceAccessPermission();
1072        final int uid = Binder.getCallingUid();
1073        NetworkState state = getUnfilteredActiveNetworkState(uid);
1074        return state.networkInfo;
1075    }
1076
1077    @Override
1078    public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
1079        enforceConnectivityInternalPermission();
1080        final NetworkState state = getUnfilteredActiveNetworkState(uid);
1081        filterNetworkStateForUid(state, uid, ignoreBlocked);
1082        return state.networkInfo;
1083    }
1084
1085    @Override
1086    public NetworkInfo getNetworkInfo(int networkType) {
1087        enforceAccessPermission();
1088        final int uid = Binder.getCallingUid();
1089        if (getVpnUnderlyingNetworks(uid) != null) {
1090            // A VPN is active, so we may need to return one of its underlying networks. This
1091            // information is not available in LegacyTypeTracker, so we have to get it from
1092            // getUnfilteredActiveNetworkState.
1093            final NetworkState state = getUnfilteredActiveNetworkState(uid);
1094            if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1095                filterNetworkStateForUid(state, uid, false);
1096                return state.networkInfo;
1097            }
1098        }
1099        final NetworkState state = getFilteredNetworkState(networkType, uid, false);
1100        return state.networkInfo;
1101    }
1102
1103    @Override
1104    public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
1105        enforceAccessPermission();
1106        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1107        if (nai != null) {
1108            final NetworkState state = nai.getNetworkState();
1109            filterNetworkStateForUid(state, uid, ignoreBlocked);
1110            return state.networkInfo;
1111        } else {
1112            return null;
1113        }
1114    }
1115
1116    @Override
1117    public NetworkInfo[] getAllNetworkInfo() {
1118        enforceAccessPermission();
1119        final ArrayList<NetworkInfo> result = Lists.newArrayList();
1120        for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1121                networkType++) {
1122            NetworkInfo info = getNetworkInfo(networkType);
1123            if (info != null) {
1124                result.add(info);
1125            }
1126        }
1127        return result.toArray(new NetworkInfo[result.size()]);
1128    }
1129
1130    @Override
1131    public Network getNetworkForType(int networkType) {
1132        enforceAccessPermission();
1133        final int uid = Binder.getCallingUid();
1134        NetworkState state = getFilteredNetworkState(networkType, uid, false);
1135        if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
1136            return state.network;
1137        }
1138        return null;
1139    }
1140
1141    @Override
1142    public Network[] getAllNetworks() {
1143        enforceAccessPermission();
1144        synchronized (mNetworkForNetId) {
1145            final Network[] result = new Network[mNetworkForNetId.size()];
1146            for (int i = 0; i < mNetworkForNetId.size(); i++) {
1147                result[i] = mNetworkForNetId.valueAt(i).network;
1148            }
1149            return result;
1150        }
1151    }
1152
1153    @Override
1154    public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1155        // The basic principle is: if an app's traffic could possibly go over a
1156        // network, without the app doing anything multinetwork-specific,
1157        // (hence, by "default"), then include that network's capabilities in
1158        // the array.
1159        //
1160        // In the normal case, app traffic only goes over the system's default
1161        // network connection, so that's the only network returned.
1162        //
1163        // With a VPN in force, some app traffic may go into the VPN, and thus
1164        // over whatever underlying networks the VPN specifies, while other app
1165        // traffic may go over the system default network (e.g.: a split-tunnel
1166        // VPN, or an app disallowed by the VPN), so the set of networks
1167        // returned includes the VPN's underlying networks and the system
1168        // default.
1169        enforceAccessPermission();
1170
1171        HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1172
1173        NetworkAgentInfo nai = getDefaultNetwork();
1174        NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
1175        if (nc != null) {
1176            result.put(nai.network, nc);
1177        }
1178
1179        if (!mLockdownEnabled) {
1180            synchronized (mVpns) {
1181                Vpn vpn = mVpns.get(userId);
1182                if (vpn != null) {
1183                    Network[] networks = vpn.getUnderlyingNetworks();
1184                    if (networks != null) {
1185                        for (Network network : networks) {
1186                            nai = getNetworkAgentInfoForNetwork(network);
1187                            nc = getNetworkCapabilitiesInternal(nai);
1188                            if (nc != null) {
1189                                result.put(network, nc);
1190                            }
1191                        }
1192                    }
1193                }
1194            }
1195        }
1196
1197        NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1198        out = result.values().toArray(out);
1199        return out;
1200    }
1201
1202    @Override
1203    public boolean isNetworkSupported(int networkType) {
1204        enforceAccessPermission();
1205        return mLegacyTypeTracker.isTypeSupported(networkType);
1206    }
1207
1208    /**
1209     * Return LinkProperties for the active (i.e., connected) default
1210     * network interface.  It is assumed that at most one default network
1211     * is active at a time. If more than one is active, it is indeterminate
1212     * which will be returned.
1213     * @return the ip properties for the active network, or {@code null} if
1214     * none is active
1215     */
1216    @Override
1217    public LinkProperties getActiveLinkProperties() {
1218        enforceAccessPermission();
1219        final int uid = Binder.getCallingUid();
1220        NetworkState state = getUnfilteredActiveNetworkState(uid);
1221        return state.linkProperties;
1222    }
1223
1224    @Override
1225    public LinkProperties getLinkPropertiesForType(int networkType) {
1226        enforceAccessPermission();
1227        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1228        if (nai != null) {
1229            synchronized (nai) {
1230                return new LinkProperties(nai.linkProperties);
1231            }
1232        }
1233        return null;
1234    }
1235
1236    // TODO - this should be ALL networks
1237    @Override
1238    public LinkProperties getLinkProperties(Network network) {
1239        enforceAccessPermission();
1240        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1241        if (nai != null) {
1242            synchronized (nai) {
1243                return new LinkProperties(nai.linkProperties);
1244            }
1245        }
1246        return null;
1247    }
1248
1249    private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
1250        if (nai != null) {
1251            synchronized (nai) {
1252                if (nai.networkCapabilities != null) {
1253                    return new NetworkCapabilities(nai.networkCapabilities);
1254                }
1255            }
1256        }
1257        return null;
1258    }
1259
1260    @Override
1261    public NetworkCapabilities getNetworkCapabilities(Network network) {
1262        enforceAccessPermission();
1263        return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1264    }
1265
1266    @Override
1267    public NetworkState[] getAllNetworkState() {
1268        // Require internal since we're handing out IMSI details
1269        enforceConnectivityInternalPermission();
1270
1271        final ArrayList<NetworkState> result = Lists.newArrayList();
1272        for (Network network : getAllNetworks()) {
1273            final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1274            if (nai != null) {
1275                result.add(nai.getNetworkState());
1276            }
1277        }
1278        return result.toArray(new NetworkState[result.size()]);
1279    }
1280
1281    @Override
1282    public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1283        enforceAccessPermission();
1284        final int uid = Binder.getCallingUid();
1285        final long token = Binder.clearCallingIdentity();
1286        try {
1287            final NetworkState state = getUnfilteredActiveNetworkState(uid);
1288            if (state.networkInfo != null) {
1289                try {
1290                    return mPolicyManager.getNetworkQuotaInfo(state);
1291                } catch (RemoteException e) {
1292                }
1293            }
1294            return null;
1295        } finally {
1296            Binder.restoreCallingIdentity(token);
1297        }
1298    }
1299
1300    @Override
1301    public boolean isActiveNetworkMetered() {
1302        enforceAccessPermission();
1303
1304        final NetworkInfo info = getActiveNetworkInfo();
1305        return (info != null) ? info.isMetered() : false;
1306    }
1307
1308    private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1309        @Override
1310        public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
1311            int deviceType = Integer.parseInt(label);
1312            sendDataActivityBroadcast(deviceType, active, tsNanos);
1313        }
1314    };
1315
1316    /**
1317     * Ensure that a network route exists to deliver traffic to the specified
1318     * host via the specified network interface.
1319     * @param networkType the type of the network over which traffic to the
1320     * specified host is to be routed
1321     * @param hostAddress the IP address of the host to which the route is
1322     * desired
1323     * @return {@code true} on success, {@code false} on failure
1324     */
1325    public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
1326        enforceChangePermission();
1327        if (mProtectedNetworks.contains(networkType)) {
1328            enforceConnectivityInternalPermission();
1329        }
1330
1331        InetAddress addr;
1332        try {
1333            addr = InetAddress.getByAddress(hostAddress);
1334        } catch (UnknownHostException e) {
1335            if (DBG) log("requestRouteToHostAddress got " + e.toString());
1336            return false;
1337        }
1338
1339        if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
1340            if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
1341            return false;
1342        }
1343
1344        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1345        if (nai == null) {
1346            if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1347                if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1348            } else {
1349                if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1350            }
1351            return false;
1352        }
1353
1354        DetailedState netState;
1355        synchronized (nai) {
1356            netState = nai.networkInfo.getDetailedState();
1357        }
1358
1359        if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
1360            if (VDBG) {
1361                log("requestRouteToHostAddress on down network "
1362                        + "(" + networkType + ") - dropped"
1363                        + " netState=" + netState);
1364            }
1365            return false;
1366        }
1367
1368        final int uid = Binder.getCallingUid();
1369        final long token = Binder.clearCallingIdentity();
1370        try {
1371            LinkProperties lp;
1372            int netId;
1373            synchronized (nai) {
1374                lp = nai.linkProperties;
1375                netId = nai.network.netId;
1376            }
1377            boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
1378            if (DBG) log("requestRouteToHostAddress ok=" + ok);
1379            return ok;
1380        } finally {
1381            Binder.restoreCallingIdentity(token);
1382        }
1383    }
1384
1385    private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
1386        RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
1387        if (bestRoute == null) {
1388            bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
1389        } else {
1390            String iface = bestRoute.getInterface();
1391            if (bestRoute.getGateway().equals(addr)) {
1392                // if there is no better route, add the implied hostroute for our gateway
1393                bestRoute = RouteInfo.makeHostRoute(addr, iface);
1394            } else {
1395                // if we will connect to this through another route, add a direct route
1396                // to it's gateway
1397                bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
1398            }
1399        }
1400        if (DBG) log("Adding legacy route " + bestRoute +
1401                " for UID/PID " + uid + "/" + Binder.getCallingPid());
1402        try {
1403            mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1404        } catch (Exception e) {
1405            // never crash - catch them all
1406            if (DBG) loge("Exception trying to add a route: " + e);
1407            return false;
1408        }
1409        return true;
1410    }
1411
1412    private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1413        @Override
1414        public void onUidRulesChanged(int uid, int uidRules) {
1415            // caller is NPMS, since we only register with them
1416            if (LOGD_RULES) {
1417                log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
1418            }
1419
1420            synchronized (mRulesLock) {
1421                // skip update when we've already applied rules
1422                final int oldRules = mUidRules.get(uid, RULE_NONE);
1423                if (oldRules == uidRules) return;
1424
1425                if (uidRules == RULE_NONE) {
1426                    mUidRules.delete(uid);
1427                } else {
1428                    mUidRules.put(uid, uidRules);
1429                }
1430            }
1431
1432            // TODO: notify UID when it has requested targeted updates
1433        }
1434
1435        @Override
1436        public void onMeteredIfacesChanged(String[] meteredIfaces) {
1437            // caller is NPMS, since we only register with them
1438            if (LOGD_RULES) {
1439                log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
1440            }
1441
1442            synchronized (mRulesLock) {
1443                mMeteredIfaces.clear();
1444                for (String iface : meteredIfaces) {
1445                    mMeteredIfaces.add(iface);
1446                }
1447            }
1448        }
1449
1450        @Override
1451        public void onRestrictBackgroundChanged(boolean restrictBackground) {
1452            // caller is NPMS, since we only register with them
1453            if (LOGD_RULES) {
1454                log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1455            }
1456
1457            synchronized (mRulesLock) {
1458                mRestrictBackground = restrictBackground;
1459            }
1460
1461            if (restrictBackground) {
1462                log("onRestrictBackgroundChanged(true): disabling tethering");
1463                mTethering.untetherAll();
1464            }
1465        }
1466
1467        @Override
1468        public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1469            if (LOGD_RULES) {
1470                // caller is NPMS, since we only register with them
1471                log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1472                        + whitelisted + ")");
1473            }
1474        }
1475        @Override
1476        public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1477            if (LOGD_RULES) {
1478                // caller is NPMS, since we only register with them
1479                log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1480                        + blacklisted + ")");
1481            }
1482        }
1483    };
1484
1485    /**
1486     * Require that the caller is either in the same user or has appropriate permission to interact
1487     * across users.
1488     *
1489     * @param userId Target user for whatever operation the current IPC is supposed to perform.
1490     */
1491    private void enforceCrossUserPermission(int userId) {
1492        if (userId == UserHandle.getCallingUserId()) {
1493            // Not a cross-user call.
1494            return;
1495        }
1496        mContext.enforceCallingOrSelfPermission(
1497                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1498                "ConnectivityService");
1499    }
1500
1501    private void enforceInternetPermission() {
1502        mContext.enforceCallingOrSelfPermission(
1503                android.Manifest.permission.INTERNET,
1504                "ConnectivityService");
1505    }
1506
1507    private void enforceAccessPermission() {
1508        mContext.enforceCallingOrSelfPermission(
1509                android.Manifest.permission.ACCESS_NETWORK_STATE,
1510                "ConnectivityService");
1511    }
1512
1513    private void enforceChangePermission() {
1514        ConnectivityManager.enforceChangePermission(mContext);
1515    }
1516
1517    private void enforceTetherAccessPermission() {
1518        mContext.enforceCallingOrSelfPermission(
1519                android.Manifest.permission.ACCESS_NETWORK_STATE,
1520                "ConnectivityService");
1521    }
1522
1523    private void enforceConnectivityInternalPermission() {
1524        mContext.enforceCallingOrSelfPermission(
1525                android.Manifest.permission.CONNECTIVITY_INTERNAL,
1526                "ConnectivityService");
1527    }
1528
1529    private void enforceKeepalivePermission() {
1530        mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
1531    }
1532
1533    public void sendConnectedBroadcast(NetworkInfo info) {
1534        enforceConnectivityInternalPermission();
1535        sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
1536    }
1537
1538    private void sendInetConditionBroadcast(NetworkInfo info) {
1539        sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1540    }
1541
1542    private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
1543        if (mLockdownTracker != null) {
1544            info = new NetworkInfo(info);
1545            mLockdownTracker.augmentNetworkInfo(info);
1546        }
1547
1548        Intent intent = new Intent(bcastType);
1549        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
1550        intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
1551        if (info.isFailover()) {
1552            intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1553            info.setFailover(false);
1554        }
1555        if (info.getReason() != null) {
1556            intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1557        }
1558        if (info.getExtraInfo() != null) {
1559            intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1560                    info.getExtraInfo());
1561        }
1562        intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
1563        return intent;
1564    }
1565
1566    private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1567        sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1568    }
1569
1570    private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
1571        Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1572        intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1573        intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
1574        intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
1575        final long ident = Binder.clearCallingIdentity();
1576        try {
1577            mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1578                    RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1579        } finally {
1580            Binder.restoreCallingIdentity(ident);
1581        }
1582    }
1583
1584    private void sendStickyBroadcast(Intent intent) {
1585        synchronized(this) {
1586            if (!mSystemReady) {
1587                mInitialBroadcast = new Intent(intent);
1588            }
1589            intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1590            if (VDBG) {
1591                log("sendStickyBroadcast: action=" + intent.getAction());
1592            }
1593
1594            Bundle options = null;
1595            final long ident = Binder.clearCallingIdentity();
1596            if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1597                final NetworkInfo ni = intent.getParcelableExtra(
1598                        ConnectivityManager.EXTRA_NETWORK_INFO);
1599                if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1600                    intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1601                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1602                } else {
1603                    BroadcastOptions opts = BroadcastOptions.makeBasic();
1604                    opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1605                    options = opts.toBundle();
1606                }
1607                final IBatteryStats bs = BatteryStatsService.getService();
1608                try {
1609                    bs.noteConnectivityChanged(intent.getIntExtra(
1610                            ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1611                            ni != null ? ni.getState().toString() : "?");
1612                } catch (RemoteException e) {
1613                }
1614            }
1615            try {
1616                mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
1617            } finally {
1618                Binder.restoreCallingIdentity(ident);
1619            }
1620        }
1621    }
1622
1623    void systemReady() {
1624        loadGlobalProxy();
1625
1626        synchronized(this) {
1627            mSystemReady = true;
1628            if (mInitialBroadcast != null) {
1629                mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
1630                mInitialBroadcast = null;
1631            }
1632        }
1633        // load the global proxy at startup
1634        mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
1635
1636        // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1637        // for user to unlock device too.
1638        updateLockdownVpn();
1639
1640        // Configure whether mobile data is always on.
1641        mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1642
1643        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
1644
1645        mPermissionMonitor.startMonitoring();
1646    }
1647
1648    /**
1649     * Setup data activity tracking for the given network.
1650     *
1651     * Every {@code setupDataActivityTracking} should be paired with a
1652     * {@link #removeDataActivityTracking} for cleanup.
1653     */
1654    private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1655        final String iface = networkAgent.linkProperties.getInterfaceName();
1656
1657        final int timeout;
1658        int type = ConnectivityManager.TYPE_NONE;
1659
1660        if (networkAgent.networkCapabilities.hasTransport(
1661                NetworkCapabilities.TRANSPORT_CELLULAR)) {
1662            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1663                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
1664                                             10);
1665            type = ConnectivityManager.TYPE_MOBILE;
1666        } else if (networkAgent.networkCapabilities.hasTransport(
1667                NetworkCapabilities.TRANSPORT_WIFI)) {
1668            timeout = Settings.Global.getInt(mContext.getContentResolver(),
1669                                             Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
1670                                             15);
1671            type = ConnectivityManager.TYPE_WIFI;
1672        } else {
1673            // do not track any other networks
1674            timeout = 0;
1675        }
1676
1677        if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
1678            try {
1679                mNetd.addIdleTimer(iface, timeout, type);
1680            } catch (Exception e) {
1681                // You shall not crash!
1682                loge("Exception in setupDataActivityTracking " + e);
1683            }
1684        }
1685    }
1686
1687    /**
1688     * Remove data activity tracking when network disconnects.
1689     */
1690    private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1691        final String iface = networkAgent.linkProperties.getInterfaceName();
1692        final NetworkCapabilities caps = networkAgent.networkCapabilities;
1693
1694        if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1695                              caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
1696            try {
1697                // the call fails silently if no idletimer setup for this interface
1698                mNetd.removeIdleTimer(iface);
1699            } catch (Exception e) {
1700                loge("Exception in removeDataActivityTracking " + e);
1701            }
1702        }
1703    }
1704
1705    /**
1706     * Reads the network specific MTU size from reources.
1707     * and set it on it's iface.
1708     */
1709    private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1710        final String iface = newLp.getInterfaceName();
1711        final int mtu = newLp.getMtu();
1712        if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1713            if (VDBG) log("identical MTU - not setting");
1714            return;
1715        }
1716
1717        if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
1718            if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
1719            return;
1720        }
1721
1722        // Cannot set MTU without interface name
1723        if (TextUtils.isEmpty(iface)) {
1724            loge("Setting MTU size with null iface.");
1725            return;
1726        }
1727
1728        try {
1729            if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
1730            mNetd.setMtu(iface, mtu);
1731        } catch (Exception e) {
1732            Slog.e(TAG, "exception in setMtu()" + e);
1733        }
1734    }
1735
1736    private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
1737    private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1738
1739    // Overridden for testing purposes to avoid writing to SystemProperties.
1740    @VisibleForTesting
1741    protected int getDefaultTcpRwnd() {
1742        return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1743    }
1744
1745    private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1746        if (isDefaultNetwork(nai) == false) {
1747            return;
1748        }
1749
1750        String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1751        String[] values = null;
1752        if (tcpBufferSizes != null) {
1753            values = tcpBufferSizes.split(",");
1754        }
1755
1756        if (values == null || values.length != 6) {
1757            if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
1758            tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1759            values = tcpBufferSizes.split(",");
1760        }
1761
1762        if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1763
1764        try {
1765            if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
1766
1767            final String prefix = "/sys/kernel/ipv4/tcp_";
1768            FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1769            FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1770            FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1771            FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1772            FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1773            FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1774            mCurrentTcpBufferSizes = tcpBufferSizes;
1775        } catch (IOException e) {
1776            loge("Can't set TCP buffer sizes:" + e);
1777        }
1778
1779        Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1780            Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
1781        final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1782        if (rwndValue != 0) {
1783            SystemProperties.set(sysctlKey, rwndValue.toString());
1784        }
1785    }
1786
1787    private void flushVmDnsCache() {
1788        /*
1789         * Tell the VMs to toss their DNS caches
1790         */
1791        Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1792        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
1793        /*
1794         * Connectivity events can happen before boot has completed ...
1795         */
1796        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
1797        final long ident = Binder.clearCallingIdentity();
1798        try {
1799            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1800        } finally {
1801            Binder.restoreCallingIdentity(ident);
1802        }
1803    }
1804
1805    @Override
1806    public int getRestoreDefaultNetworkDelay(int networkType) {
1807        String restoreDefaultNetworkDelayStr = SystemProperties.get(
1808                NETWORK_RESTORE_DELAY_PROP_NAME);
1809        if(restoreDefaultNetworkDelayStr != null &&
1810                restoreDefaultNetworkDelayStr.length() != 0) {
1811            try {
1812                return Integer.parseInt(restoreDefaultNetworkDelayStr);
1813            } catch (NumberFormatException e) {
1814            }
1815        }
1816        // if the system property isn't set, use the value for the apn type
1817        int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1818
1819        if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1820                (mNetConfigs[networkType] != null)) {
1821            ret = mNetConfigs[networkType].restoreTime;
1822        }
1823        return ret;
1824    }
1825
1826    private boolean argsContain(String[] args, String target) {
1827        for (String arg : args) {
1828            if (arg.equals(target)) return true;
1829        }
1830        return false;
1831    }
1832
1833    private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1834        final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1835        final long DIAG_TIME_MS = 5000;
1836        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1837            // Start gathering diagnostic information.
1838            netDiags.add(new NetworkDiagnostics(
1839                    nai.network,
1840                    new LinkProperties(nai.linkProperties),  // Must be a copy.
1841                    DIAG_TIME_MS));
1842        }
1843
1844        for (NetworkDiagnostics netDiag : netDiags) {
1845            pw.println();
1846            netDiag.waitForMeasurements();
1847            netDiag.dump(pw);
1848        }
1849    }
1850
1851    @Override
1852    protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1853        final IndentingPrintWriter pw = new IndentingPrintWriter(writer, "  ");
1854        if (mContext.checkCallingOrSelfPermission(
1855                android.Manifest.permission.DUMP)
1856                != PackageManager.PERMISSION_GRANTED) {
1857            pw.println("Permission Denial: can't dump ConnectivityService " +
1858                    "from from pid=" + Binder.getCallingPid() + ", uid=" +
1859                    Binder.getCallingUid());
1860            return;
1861        }
1862
1863        if (argsContain(args, "--diag")) {
1864            dumpNetworkDiagnostics(pw);
1865            return;
1866        }
1867
1868        pw.print("NetworkFactories for:");
1869        for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1870            pw.print(" " + nfi.name);
1871        }
1872        pw.println();
1873        pw.println();
1874
1875        final NetworkAgentInfo defaultNai = getDefaultNetwork();
1876        pw.print("Active default network: ");
1877        if (defaultNai == null) {
1878            pw.println("none");
1879        } else {
1880            pw.println(defaultNai.network.netId);
1881        }
1882        pw.println();
1883
1884        pw.println("Current Networks:");
1885        pw.increaseIndent();
1886        for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1887            pw.println(nai.toString());
1888            pw.increaseIndent();
1889            pw.println("Requests:");
1890            pw.increaseIndent();
1891            for (int i = 0; i < nai.networkRequests.size(); i++) {
1892                pw.println(nai.networkRequests.valueAt(i).toString());
1893            }
1894            pw.decreaseIndent();
1895            pw.println("Lingered:");
1896            pw.increaseIndent();
1897            for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1898            pw.decreaseIndent();
1899            pw.decreaseIndent();
1900        }
1901        pw.decreaseIndent();
1902        pw.println();
1903
1904        pw.println("Metered Interfaces:");
1905        pw.increaseIndent();
1906        for (String value : mMeteredIfaces) {
1907            pw.println(value);
1908        }
1909        pw.decreaseIndent();
1910        pw.println();
1911
1912        pw.print("Restrict background: ");
1913        pw.println(mRestrictBackground);
1914        pw.println();
1915
1916        pw.println("Status for known UIDs:");
1917        pw.increaseIndent();
1918        final int size = mUidRules.size();
1919        for (int i = 0; i < size; i++) {
1920            final int uid = mUidRules.keyAt(i);
1921            pw.print("UID=");
1922            pw.print(uid);
1923            final int uidRules = mUidRules.get(uid, RULE_NONE);
1924            pw.print(" rules=");
1925            pw.print(uidRulesToString(uidRules));
1926            pw.println();
1927        }
1928        pw.println();
1929        pw.decreaseIndent();
1930
1931        pw.println("Network Requests:");
1932        pw.increaseIndent();
1933        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1934            pw.println(nri.toString());
1935        }
1936        pw.println();
1937        pw.decreaseIndent();
1938
1939        mLegacyTypeTracker.dump(pw);
1940
1941        synchronized (this) {
1942            pw.print("mNetTransitionWakeLock: currently " +
1943                    (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1944            if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1945                pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1946            } else {
1947                pw.println(", last requested never");
1948            }
1949        }
1950
1951        pw.println();
1952        mTethering.dump(fd, pw, args);
1953
1954        pw.println();
1955        mKeepaliveTracker.dump(pw);
1956
1957        pw.println();
1958
1959        if (mInetLog != null && mInetLog.size() > 0) {
1960            pw.println();
1961            pw.println("Inet condition reports:");
1962            pw.increaseIndent();
1963            for(int i = 0; i < mInetLog.size(); i++) {
1964                pw.println(mInetLog.get(i));
1965            }
1966            pw.decreaseIndent();
1967        }
1968
1969        if (argsContain(args, "--short") == false) {
1970            pw.println();
1971            synchronized (mValidationLogs) {
1972                pw.println("mValidationLogs (most recent first):");
1973                for (ValidationLog p : mValidationLogs) {
1974                    pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
1975                    pw.increaseIndent();
1976                    p.mLog.dump(fd, pw, args);
1977                    pw.decreaseIndent();
1978                }
1979            }
1980
1981            pw.println();
1982            pw.println("mNetworkRequestInfoLogs (most recent first):");
1983            pw.increaseIndent();
1984            mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1985            pw.decreaseIndent();
1986        }
1987    }
1988
1989    private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
1990        if (nai.network == null) return false;
1991        final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
1992        if (officialNai != null && officialNai.equals(nai)) return true;
1993        if (officialNai != null || VDBG) {
1994            final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
1995            loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
1996                " - " + nai);
1997        }
1998        return false;
1999    }
2000
2001    private boolean isRequest(NetworkRequest request) {
2002        return mNetworkRequests.get(request).isRequest();
2003    }
2004
2005    // must be stateless - things change under us.
2006    private class NetworkStateTrackerHandler extends Handler {
2007        public NetworkStateTrackerHandler(Looper looper) {
2008            super(looper);
2009        }
2010
2011        private boolean maybeHandleAsyncChannelMessage(Message msg) {
2012            switch (msg.what) {
2013                default:
2014                    return false;
2015                case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
2016                    handleAsyncChannelHalfConnect(msg);
2017                    break;
2018                }
2019                case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2020                    NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2021                    if (nai != null) nai.asyncChannel.disconnect();
2022                    break;
2023                }
2024                case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2025                    handleAsyncChannelDisconnected(msg);
2026                    break;
2027                }
2028            }
2029            return true;
2030        }
2031
2032        private void maybeHandleNetworkAgentMessage(Message msg) {
2033            NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2034            if (nai == null) {
2035                if (VDBG) {
2036                    final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2037                    log(String.format("%s from unknown NetworkAgent", what));
2038                }
2039                return;
2040            }
2041
2042            switch (msg.what) {
2043                case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
2044                    final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2045                    if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2046                            networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2047                        Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
2048                    }
2049                    if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
2050                            networkCapabilities)) {
2051                        Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2052                                + nai.networkCapabilities + " -> " + networkCapabilities);
2053                    }
2054                    updateCapabilities(nai, networkCapabilities);
2055                    break;
2056                }
2057                case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
2058                    if (VDBG) {
2059                        log("Update of LinkProperties for " + nai.name() +
2060                                "; created=" + nai.created +
2061                                "; everConnected=" + nai.everConnected);
2062                    }
2063                    LinkProperties oldLp = nai.linkProperties;
2064                    synchronized (nai) {
2065                        nai.linkProperties = (LinkProperties)msg.obj;
2066                    }
2067                    if (nai.everConnected) updateLinkProperties(nai, oldLp);
2068                    break;
2069                }
2070                case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
2071                    NetworkInfo info = (NetworkInfo) msg.obj;
2072                    updateNetworkInfo(nai, info);
2073                    break;
2074                }
2075                case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
2076                    Integer score = (Integer) msg.obj;
2077                    if (score != null) updateNetworkScore(nai, score.intValue());
2078                    break;
2079                }
2080                case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2081                    try {
2082                        mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
2083                    } catch (Exception e) {
2084                        // Never crash!
2085                        loge("Exception in addVpnUidRanges: " + e);
2086                    }
2087                    break;
2088                }
2089                case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2090                    try {
2091                        mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
2092                    } catch (Exception e) {
2093                        // Never crash!
2094                        loge("Exception in removeVpnUidRanges: " + e);
2095                    }
2096                    break;
2097                }
2098                case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2099                    if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2100                        loge("ERROR: already-connected network explicitly selected.");
2101                    }
2102                    nai.networkMisc.explicitlySelected = true;
2103                    nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
2104                    break;
2105                }
2106                case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2107                    mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2108                    break;
2109                }
2110            }
2111        }
2112
2113        private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2114            switch (msg.what) {
2115                default:
2116                    return false;
2117                case NetworkMonitor.EVENT_NETWORK_TESTED: {
2118                    final NetworkAgentInfo nai;
2119                    synchronized (mNetworkForNetId) {
2120                        nai = mNetworkForNetId.get(msg.arg2);
2121                    }
2122                    if (nai != null) {
2123                        final boolean valid =
2124                                (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2125                        if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2126                                (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
2127                        if (valid != nai.lastValidated) {
2128                            final int oldScore = nai.getCurrentScore();
2129                            nai.lastValidated = valid;
2130                            nai.everValidated |= valid;
2131                            updateCapabilities(nai, nai.networkCapabilities);
2132                            // If score has changed, rebroadcast to NetworkFactories. b/17726566
2133                            if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2134                        }
2135                        updateInetCondition(nai);
2136                        // Let the NetworkAgent know the state of its network
2137                        Bundle redirectUrlBundle = new Bundle();
2138                        redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
2139                        nai.asyncChannel.sendMessage(
2140                                NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2141                                (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2142                                0, redirectUrlBundle);
2143                    }
2144                    break;
2145                }
2146                case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
2147                    NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
2148                    if (isLiveNetworkAgent(nai, msg.what)) {
2149                        handleLingerComplete(nai);
2150                    }
2151                    break;
2152                }
2153                case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
2154                    final int netId = msg.arg2;
2155                    final boolean visible = (msg.arg1 != 0);
2156                    final NetworkAgentInfo nai;
2157                    synchronized (mNetworkForNetId) {
2158                        nai = mNetworkForNetId.get(netId);
2159                    }
2160                    // If captive portal status has changed, update capabilities.
2161                    if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2162                        nai.lastCaptivePortalDetected = visible;
2163                        nai.everCaptivePortalDetected |= visible;
2164                        updateCapabilities(nai, nai.networkCapabilities);
2165                    }
2166                    if (!visible) {
2167                        setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
2168                    } else {
2169                        if (nai == null) {
2170                            loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2171                            break;
2172                        }
2173                        if (!nai.networkMisc.provisioningNotificationDisabled) {
2174                            setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2175                                    nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2176                                    (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
2177                        }
2178                    }
2179                    break;
2180                }
2181            }
2182            return true;
2183        }
2184
2185        @Override
2186        public void handleMessage(Message msg) {
2187            if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2188                maybeHandleNetworkAgentMessage(msg);
2189            }
2190        }
2191    }
2192
2193    private void linger(NetworkAgentInfo nai) {
2194        nai.lingering = true;
2195        NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
2196        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2197        notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2198    }
2199
2200    // Cancel any lingering so the linger timeout doesn't teardown a network.
2201    // This should be called when a network begins satisfying a NetworkRequest.
2202    // Note: depending on what state the NetworkMonitor is in (e.g.,
2203    // if it's awaiting captive portal login, or if validation failed), this
2204    // may trigger a re-evaluation of the network.
2205    private void unlinger(NetworkAgentInfo nai) {
2206        nai.networkLingered.clear();
2207        if (!nai.lingering) return;
2208        nai.lingering = false;
2209        NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
2210        if (VDBG) log("Canceling linger of " + nai.name());
2211        nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2212    }
2213
2214    private void handleAsyncChannelHalfConnect(Message msg) {
2215        AsyncChannel ac = (AsyncChannel) msg.obj;
2216        if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
2217            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2218                if (VDBG) log("NetworkFactory connected");
2219                // A network factory has connected.  Send it all current NetworkRequests.
2220                for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2221                    if (!nri.isRequest()) continue;
2222                    NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2223                    ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
2224                            (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
2225                }
2226            } else {
2227                loge("Error connecting NetworkFactory");
2228                mNetworkFactoryInfos.remove(msg.obj);
2229            }
2230        } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2231            if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2232                if (VDBG) log("NetworkAgent connected");
2233                // A network agent has requested a connection.  Establish the connection.
2234                mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2235                        sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2236            } else {
2237                loge("Error connecting NetworkAgent");
2238                NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
2239                if (nai != null) {
2240                    final boolean wasDefault = isDefaultNetwork(nai);
2241                    synchronized (mNetworkForNetId) {
2242                        mNetworkForNetId.remove(nai.network.netId);
2243                        mNetIdInUse.delete(nai.network.netId);
2244                    }
2245                    // Just in case.
2246                    mLegacyTypeTracker.remove(nai, wasDefault);
2247                }
2248            }
2249        }
2250    }
2251
2252    private void handleAsyncChannelDisconnected(Message msg) {
2253        NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2254        if (nai != null) {
2255            if (DBG) {
2256                log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2257            }
2258            // A network agent has disconnected.
2259            // TODO - if we move the logic to the network agent (have them disconnect
2260            // because they lost all their requests or because their score isn't good)
2261            // then they would disconnect organically, report their new state and then
2262            // disconnect the channel.
2263            if (nai.networkInfo.isConnected()) {
2264                nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2265                        null, null);
2266            }
2267            final boolean wasDefault = isDefaultNetwork(nai);
2268            if (wasDefault) {
2269                mDefaultInetConditionPublished = 0;
2270                // Log default network disconnection before required book-keeping.
2271                // Let rematchAllNetworksAndRequests() below record a new default network event
2272                // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2273                // whose timestamps tell how long it takes to recover a default network.
2274                logDefaultNetworkEvent(null, nai);
2275            }
2276            notifyIfacesChangedForNetworkStats();
2277            // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2278            // by other networks that are already connected. Perhaps that can be done by
2279            // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2280            // of rematchAllNetworksAndRequests
2281            notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
2282            mKeepaliveTracker.handleStopAllKeepalives(nai,
2283                    ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
2284            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
2285            mNetworkAgentInfos.remove(msg.replyTo);
2286            updateClat(null, nai.linkProperties, nai);
2287            synchronized (mNetworkForNetId) {
2288                // Remove the NetworkAgent, but don't mark the netId as
2289                // available until we've told netd to delete it below.
2290                mNetworkForNetId.remove(nai.network.netId);
2291            }
2292            // Remove all previously satisfied requests.
2293            for (int i = 0; i < nai.networkRequests.size(); i++) {
2294                NetworkRequest request = nai.networkRequests.valueAt(i);
2295                NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2296                if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2297                    mNetworkForRequestId.remove(request.requestId);
2298                    sendUpdatedScoreToFactories(request, 0);
2299                }
2300            }
2301            if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2302                removeDataActivityTracking(nai);
2303                notifyLockdownVpn(nai);
2304                requestNetworkTransitionWakelock(nai.name());
2305            }
2306            mLegacyTypeTracker.remove(nai, wasDefault);
2307            rematchAllNetworksAndRequests(null, 0);
2308            if (nai.created) {
2309                // Tell netd to clean up the configuration for this network
2310                // (routing rules, DNS, etc).
2311                // This may be slow as it requires a lot of netd shelling out to ip and
2312                // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2313                // after we've rematched networks with requests which should make a potential
2314                // fallback network the default or requested a new network from the
2315                // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2316                // long time.
2317                try {
2318                    mNetd.removeNetwork(nai.network.netId);
2319                } catch (Exception e) {
2320                    loge("Exception removing network: " + e);
2321                }
2322            }
2323            synchronized (mNetworkForNetId) {
2324                mNetIdInUse.delete(nai.network.netId);
2325            }
2326        } else {
2327            NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2328            if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
2329        }
2330    }
2331
2332    // If this method proves to be too slow then we can maintain a separate
2333    // pendingIntent => NetworkRequestInfo map.
2334    // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2335    private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2336        Intent intent = pendingIntent.getIntent();
2337        for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2338            PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2339            if (existingPendingIntent != null &&
2340                    existingPendingIntent.getIntent().filterEquals(intent)) {
2341                return entry.getValue();
2342            }
2343        }
2344        return null;
2345    }
2346
2347    private void handleRegisterNetworkRequestWithIntent(Message msg) {
2348        final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2349
2350        NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2351        if (existingRequest != null) { // remove the existing request.
2352            if (DBG) log("Replacing " + existingRequest.request + " with "
2353                    + nri.request + " because their intents matched.");
2354            handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2355        }
2356        handleRegisterNetworkRequest(nri);
2357    }
2358
2359    private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
2360        mNetworkRequests.put(nri.request, nri);
2361        mNetworkRequestInfoLogs.log("REGISTER " + nri);
2362        if (!nri.isRequest()) {
2363            for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
2364                if (nri.request.networkCapabilities.hasSignalStrength() &&
2365                        network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2366                    updateSignalStrengthThresholds(network, "REGISTER", nri.request);
2367                }
2368            }
2369        }
2370        rematchAllNetworksAndRequests(null, 0);
2371        if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
2372            sendUpdatedScoreToFactories(nri.request, 0);
2373        }
2374    }
2375
2376    private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2377            int callingUid) {
2378        NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2379        if (nri != null) {
2380            handleReleaseNetworkRequest(nri.request, callingUid);
2381        }
2382    }
2383
2384    // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2385    // This is whether it is satisfying any NetworkRequests or were it to become validated,
2386    // would it have a chance of satisfying any NetworkRequests.
2387    private boolean unneeded(NetworkAgentInfo nai) {
2388        if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
2389        for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2390            // If this Network is already the highest scoring Network for a request, or if
2391            // there is hope for it to become one if it validated, then it is needed.
2392            if (nri.isRequest() && nai.satisfies(nri.request) &&
2393                    (nai.networkRequests.get(nri.request.requestId) != null ||
2394                    // Note that this catches two important cases:
2395                    // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2396                    //    is currently satisfying the request.  This is desirable when
2397                    //    cellular ends up validating but WiFi does not.
2398                    // 2. Unvalidated WiFi will not be reaped when validated cellular
2399                    //    is currently satisfying the request.  This is desirable when
2400                    //    WiFi ends up validating and out scoring cellular.
2401                    mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2402                            nai.getCurrentScoreAsValidated())) {
2403                return false;
2404            }
2405        }
2406        return true;
2407    }
2408
2409    private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2410        NetworkRequestInfo nri = mNetworkRequests.get(request);
2411        if (nri != null) {
2412            if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
2413                if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2414                return;
2415            }
2416            if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
2417            nri.unlinkDeathRecipient();
2418            mNetworkRequests.remove(request);
2419            synchronized (mUidToNetworkRequestCount) {
2420                int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2421                if (requests < 1) {
2422                    Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2423                            nri.mUid);
2424                } else if (requests == 1) {
2425                    mUidToNetworkRequestCount.removeAt(
2426                            mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2427                } else {
2428                    mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2429                }
2430            }
2431            mNetworkRequestInfoLogs.log("RELEASE " + nri);
2432            if (nri.isRequest()) {
2433                // Find all networks that are satisfying this request and remove the request
2434                // from their request lists.
2435                // TODO - it's my understanding that for a request there is only a single
2436                // network satisfying it, so this loop is wasteful
2437                boolean wasKept = false;
2438                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2439                    if (nai.networkRequests.get(nri.request.requestId) != null) {
2440                        nai.networkRequests.remove(nri.request.requestId);
2441                        if (VDBG) {
2442                            log(" Removing from current network " + nai.name() +
2443                                    ", leaving " + nai.networkRequests.size() +
2444                                    " requests.");
2445                        }
2446                        if (unneeded(nai)) {
2447                            if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2448                            teardownUnneededNetwork(nai);
2449                        } else {
2450                            // suspect there should only be one pass through here
2451                            // but if any were kept do the check below
2452                            wasKept |= true;
2453                        }
2454                    }
2455                }
2456
2457                NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2458                if (nai != null) {
2459                    mNetworkForRequestId.remove(nri.request.requestId);
2460                }
2461                // Maintain the illusion.  When this request arrived, we might have pretended
2462                // that a network connected to serve it, even though the network was already
2463                // connected.  Now that this request has gone away, we might have to pretend
2464                // that the network disconnected.  LegacyTypeTracker will generate that
2465                // phantom disconnect for this type.
2466                if (nri.request.legacyType != TYPE_NONE && nai != null) {
2467                    boolean doRemove = true;
2468                    if (wasKept) {
2469                        // check if any of the remaining requests for this network are for the
2470                        // same legacy type - if so, don't remove the nai
2471                        for (int i = 0; i < nai.networkRequests.size(); i++) {
2472                            NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2473                            if (otherRequest.legacyType == nri.request.legacyType &&
2474                                    isRequest(otherRequest)) {
2475                                if (DBG) log(" still have other legacy request - leaving");
2476                                doRemove = false;
2477                            }
2478                        }
2479                    }
2480
2481                    if (doRemove) {
2482                        mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
2483                    }
2484                }
2485
2486                for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2487                    nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2488                            nri.request);
2489                }
2490            } else {
2491                // listens don't have a singular affectedNetwork.  Check all networks to see
2492                // if this listen request applies and remove it.
2493                for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2494                    nai.networkRequests.remove(nri.request.requestId);
2495                    if (nri.request.networkCapabilities.hasSignalStrength() &&
2496                            nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2497                        updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2498                    }
2499                }
2500            }
2501            callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2502        }
2503    }
2504
2505    public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2506        enforceConnectivityInternalPermission();
2507        mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2508                accept ? 1 : 0, always ? 1: 0, network));
2509    }
2510
2511    private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2512        if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2513                " accept=" + accept + " always=" + always);
2514
2515        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2516        if (nai == null) {
2517            // Nothing to do.
2518            return;
2519        }
2520
2521        if (nai.everValidated) {
2522            // The network validated while the dialog box was up. Take no action.
2523            return;
2524        }
2525
2526        if (!nai.networkMisc.explicitlySelected) {
2527            Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2528        }
2529
2530        if (accept != nai.networkMisc.acceptUnvalidated) {
2531            int oldScore = nai.getCurrentScore();
2532            nai.networkMisc.acceptUnvalidated = accept;
2533            rematchAllNetworksAndRequests(nai, oldScore);
2534            sendUpdatedScoreToFactories(nai);
2535        }
2536
2537        if (always) {
2538            nai.asyncChannel.sendMessage(
2539                    NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2540        }
2541
2542        if (!accept) {
2543            // Tell the NetworkAgent to not automatically reconnect to the network.
2544            nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2545            // Teardown the nework.
2546            teardownUnneededNetwork(nai);
2547        }
2548
2549    }
2550
2551    private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2552        if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
2553        mHandler.sendMessageDelayed(
2554                mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2555                PROMPT_UNVALIDATED_DELAY_MS);
2556    }
2557
2558    private void handlePromptUnvalidated(Network network) {
2559        if (VDBG) log("handlePromptUnvalidated " + network);
2560        NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2561
2562        // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2563        // we haven't already been told to switch to it regardless of whether it validated or not.
2564        // Also don't prompt on captive portals because we're already prompting the user to sign in.
2565        if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
2566                !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2567            return;
2568        }
2569
2570        Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2571        intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
2572        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2573        intent.setClassName("com.android.settings",
2574                "com.android.settings.wifi.WifiNoInternetDialog");
2575
2576        PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2577                mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2578
2579        setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
2580                nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
2581    }
2582
2583    private class InternalHandler extends Handler {
2584        public InternalHandler(Looper looper) {
2585            super(looper);
2586        }
2587
2588        @Override
2589        public void handleMessage(Message msg) {
2590            switch (msg.what) {
2591                case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
2592                case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
2593                    String causedBy = null;
2594                    synchronized (ConnectivityService.this) {
2595                        if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2596                                mNetTransitionWakeLock.isHeld()) {
2597                            mNetTransitionWakeLock.release();
2598                            causedBy = mNetTransitionWakeLockCausedBy;
2599                        } else {
2600                            break;
2601                        }
2602                    }
2603                    if (VDBG) {
2604                        if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2605                            log("Failed to find a new network - expiring NetTransition Wakelock");
2606                        } else {
2607                            log("NetTransition Wakelock (" +
2608                                    (causedBy == null ? "unknown" : causedBy) +
2609                                    " cleared because we found a replacement network");
2610                        }
2611                    }
2612                    break;
2613                }
2614                case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
2615                    handleDeprecatedGlobalHttpProxy();
2616                    break;
2617                }
2618                case EVENT_PROXY_HAS_CHANGED: {
2619                    handleApplyDefaultProxy((ProxyInfo)msg.obj);
2620                    break;
2621                }
2622                case EVENT_REGISTER_NETWORK_FACTORY: {
2623                    handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2624                    break;
2625                }
2626                case EVENT_UNREGISTER_NETWORK_FACTORY: {
2627                    handleUnregisterNetworkFactory((Messenger)msg.obj);
2628                    break;
2629                }
2630                case EVENT_REGISTER_NETWORK_AGENT: {
2631                    handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2632                    break;
2633                }
2634                case EVENT_REGISTER_NETWORK_REQUEST:
2635                case EVENT_REGISTER_NETWORK_LISTENER: {
2636                    handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
2637                    break;
2638                }
2639                case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2640                case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
2641                    handleRegisterNetworkRequestWithIntent(msg);
2642                    break;
2643                }
2644                case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2645                    handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2646                    break;
2647                }
2648                case EVENT_RELEASE_NETWORK_REQUEST: {
2649                    handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
2650                    break;
2651                }
2652                case EVENT_SET_ACCEPT_UNVALIDATED: {
2653                    handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2654                    break;
2655                }
2656                case EVENT_PROMPT_UNVALIDATED: {
2657                    handlePromptUnvalidated((Network) msg.obj);
2658                    break;
2659                }
2660                case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2661                    handleMobileDataAlwaysOn();
2662                    break;
2663                }
2664                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2665                case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2666                    mKeepaliveTracker.handleStartKeepalive(msg);
2667                    break;
2668                }
2669                // Sent by KeepaliveTracker to process an app request on the state machine thread.
2670                case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2671                    NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2672                    int slot = msg.arg1;
2673                    int reason = msg.arg2;
2674                    mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2675                    break;
2676                }
2677                case EVENT_SYSTEM_READY: {
2678                    for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2679                        nai.networkMonitor.systemReady = true;
2680                    }
2681                    break;
2682                }
2683            }
2684        }
2685    }
2686
2687    // javadoc from interface
2688    public int tether(String iface) {
2689        ConnectivityManager.enforceTetherChangePermission(mContext);
2690        if (isTetheringSupported()) {
2691            final int status = mTethering.tether(iface);
2692            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2693                try {
2694                    mPolicyManager.onTetheringChanged(iface, true);
2695                } catch (RemoteException e) {
2696                }
2697            }
2698            return status;
2699        } else {
2700            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2701        }
2702    }
2703
2704    // javadoc from interface
2705    public int untether(String iface) {
2706        ConnectivityManager.enforceTetherChangePermission(mContext);
2707
2708        if (isTetheringSupported()) {
2709            final int status = mTethering.untether(iface);
2710            if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2711                try {
2712                    mPolicyManager.onTetheringChanged(iface, false);
2713                } catch (RemoteException e) {
2714                }
2715            }
2716            return status;
2717        } else {
2718            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2719        }
2720    }
2721
2722    // javadoc from interface
2723    public int getLastTetherError(String iface) {
2724        enforceTetherAccessPermission();
2725
2726        if (isTetheringSupported()) {
2727            return mTethering.getLastTetherError(iface);
2728        } else {
2729            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2730        }
2731    }
2732
2733    // TODO - proper iface API for selection by property, inspection, etc
2734    public String[] getTetherableUsbRegexs() {
2735        enforceTetherAccessPermission();
2736        if (isTetheringSupported()) {
2737            return mTethering.getTetherableUsbRegexs();
2738        } else {
2739            return new String[0];
2740        }
2741    }
2742
2743    public String[] getTetherableWifiRegexs() {
2744        enforceTetherAccessPermission();
2745        if (isTetheringSupported()) {
2746            return mTethering.getTetherableWifiRegexs();
2747        } else {
2748            return new String[0];
2749        }
2750    }
2751
2752    public String[] getTetherableBluetoothRegexs() {
2753        enforceTetherAccessPermission();
2754        if (isTetheringSupported()) {
2755            return mTethering.getTetherableBluetoothRegexs();
2756        } else {
2757            return new String[0];
2758        }
2759    }
2760
2761    public int setUsbTethering(boolean enable) {
2762        ConnectivityManager.enforceTetherChangePermission(mContext);
2763        if (isTetheringSupported()) {
2764            return mTethering.setUsbTethering(enable);
2765        } else {
2766            return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2767        }
2768    }
2769
2770    // TODO - move iface listing, queries, etc to new module
2771    // javadoc from interface
2772    public String[] getTetherableIfaces() {
2773        enforceTetherAccessPermission();
2774        return mTethering.getTetherableIfaces();
2775    }
2776
2777    public String[] getTetheredIfaces() {
2778        enforceTetherAccessPermission();
2779        return mTethering.getTetheredIfaces();
2780    }
2781
2782    public String[] getTetheringErroredIfaces() {
2783        enforceTetherAccessPermission();
2784        return mTethering.getErroredIfaces();
2785    }
2786
2787    public String[] getTetheredDhcpRanges() {
2788        enforceConnectivityInternalPermission();
2789        return mTethering.getTetheredDhcpRanges();
2790    }
2791
2792    // if ro.tether.denied = true we default to no tethering
2793    // gservices could set the secure setting to 1 though to enable it on a build where it
2794    // had previously been turned off.
2795    @Override
2796    public boolean isTetheringSupported() {
2797        enforceTetherAccessPermission();
2798        int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
2799        boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
2800                Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2801                && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
2802        return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2803                ((mTethering.getTetherableUsbRegexs().length != 0 ||
2804                mTethering.getTetherableWifiRegexs().length != 0 ||
2805                mTethering.getTetherableBluetoothRegexs().length != 0) &&
2806                mTethering.getUpstreamIfaceTypes().length != 0);
2807    }
2808
2809    @Override
2810    public void startTethering(int type, ResultReceiver receiver,
2811            boolean showProvisioningUi) {
2812        ConnectivityManager.enforceTetherChangePermission(mContext);
2813        if (!isTetheringSupported()) {
2814            receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2815            return;
2816        }
2817        mTethering.startTethering(type, receiver, showProvisioningUi);
2818    }
2819
2820    @Override
2821    public void stopTethering(int type) {
2822        ConnectivityManager.enforceTetherChangePermission(mContext);
2823        mTethering.stopTethering(type);
2824    }
2825
2826    // Called when we lose the default network and have no replacement yet.
2827    // This will automatically be cleared after X seconds or a new default network
2828    // becomes CONNECTED, whichever happens first.  The timer is started by the
2829    // first caller and not restarted by subsequent callers.
2830    private void requestNetworkTransitionWakelock(String forWhom) {
2831        int serialNum = 0;
2832        synchronized (this) {
2833            if (mNetTransitionWakeLock.isHeld()) return;
2834            serialNum = ++mNetTransitionWakeLockSerialNumber;
2835            mNetTransitionWakeLock.acquire();
2836            mNetTransitionWakeLockCausedBy = forWhom;
2837        }
2838        mHandler.sendMessageDelayed(mHandler.obtainMessage(
2839                EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
2840                mNetTransitionWakeLockTimeout);
2841        return;
2842    }
2843
2844    // 100 percent is full good, 0 is full bad.
2845    public void reportInetCondition(int networkType, int percentage) {
2846        NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
2847        if (nai == null) return;
2848        reportNetworkConnectivity(nai.network, percentage > 50);
2849    }
2850
2851    public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
2852        enforceAccessPermission();
2853        enforceInternetPermission();
2854
2855        NetworkAgentInfo nai;
2856        if (network == null) {
2857            nai = getDefaultNetwork();
2858        } else {
2859            nai = getNetworkAgentInfoForNetwork(network);
2860        }
2861        if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2862            nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2863            return;
2864        }
2865        // Revalidate if the app report does not match our current validated state.
2866        if (hasConnectivity == nai.lastValidated) return;
2867        final int uid = Binder.getCallingUid();
2868        if (DBG) {
2869            log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2870                    ") by " + uid);
2871        }
2872        synchronized (nai) {
2873            // Validating a network that has not yet connected could result in a call to
2874            // rematchNetworkAndRequests() which is not meant to work on such networks.
2875            if (!nai.everConnected) return;
2876
2877            if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
2878
2879            nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2880        }
2881    }
2882
2883    private ProxyInfo getDefaultProxy() {
2884        // this information is already available as a world read/writable jvm property
2885        // so this API change wouldn't have a benifit.  It also breaks the passing
2886        // of proxy info to all the JVMs.
2887        // enforceAccessPermission();
2888        synchronized (mProxyLock) {
2889            ProxyInfo ret = mGlobalProxy;
2890            if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2891            return ret;
2892        }
2893    }
2894
2895    public ProxyInfo getProxyForNetwork(Network network) {
2896        if (network == null) return getDefaultProxy();
2897        final ProxyInfo globalProxy = getGlobalProxy();
2898        if (globalProxy != null) return globalProxy;
2899        if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2900        // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2901        // caller may not have.
2902        final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2903        if (nai == null) return null;
2904        synchronized (nai) {
2905            final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2906            if (proxyInfo == null) return null;
2907            return new ProxyInfo(proxyInfo);
2908        }
2909    }
2910
2911    // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2912    // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2913    // proxy is null then there is no proxy in place).
2914    private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2915        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2916                && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2917            proxy = null;
2918        }
2919        return proxy;
2920    }
2921
2922    // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2923    // better for determining if a new proxy broadcast is necessary:
2924    // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2925    //    avoid unnecessary broadcasts.
2926    // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2927    //    is in place.  This is important so legacy PAC resolver (see com.android.proxyhandler)
2928    //    changes aren't missed.  The legacy PAC resolver pretends to be a simple HTTP proxy but
2929    //    actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2930    //    all set.
2931    private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2932        a = canonicalizeProxyInfo(a);
2933        b = canonicalizeProxyInfo(b);
2934        // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2935        // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2936        return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2937    }
2938
2939    public void setGlobalProxy(ProxyInfo proxyProperties) {
2940        enforceConnectivityInternalPermission();
2941
2942        synchronized (mProxyLock) {
2943            if (proxyProperties == mGlobalProxy) return;
2944            if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2945            if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2946
2947            String host = "";
2948            int port = 0;
2949            String exclList = "";
2950            String pacFileUrl = "";
2951            if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
2952                    !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
2953                if (!proxyProperties.isValid()) {
2954                    if (DBG)
2955                        log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2956                    return;
2957                }
2958                mGlobalProxy = new ProxyInfo(proxyProperties);
2959                host = mGlobalProxy.getHost();
2960                port = mGlobalProxy.getPort();
2961                exclList = mGlobalProxy.getExclusionListAsString();
2962                if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
2963                    pacFileUrl = proxyProperties.getPacFileUrl().toString();
2964                }
2965            } else {
2966                mGlobalProxy = null;
2967            }
2968            ContentResolver res = mContext.getContentResolver();
2969            final long token = Binder.clearCallingIdentity();
2970            try {
2971                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2972                Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2973                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2974                        exclList);
2975                Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
2976            } finally {
2977                Binder.restoreCallingIdentity(token);
2978            }
2979
2980            if (mGlobalProxy == null) {
2981                proxyProperties = mDefaultProxy;
2982            }
2983            sendProxyBroadcast(proxyProperties);
2984        }
2985    }
2986
2987    private void loadGlobalProxy() {
2988        ContentResolver res = mContext.getContentResolver();
2989        String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2990        int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2991        String exclList = Settings.Global.getString(res,
2992                Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
2993        String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2994        if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
2995            ProxyInfo proxyProperties;
2996            if (!TextUtils.isEmpty(pacFileUrl)) {
2997                proxyProperties = new ProxyInfo(pacFileUrl);
2998            } else {
2999                proxyProperties = new ProxyInfo(host, port, exclList);
3000            }
3001            if (!proxyProperties.isValid()) {
3002                if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3003                return;
3004            }
3005
3006            synchronized (mProxyLock) {
3007                mGlobalProxy = proxyProperties;
3008            }
3009        }
3010    }
3011
3012    public ProxyInfo getGlobalProxy() {
3013        // this information is already available as a world read/writable jvm property
3014        // so this API change wouldn't have a benifit.  It also breaks the passing
3015        // of proxy info to all the JVMs.
3016        // enforceAccessPermission();
3017        synchronized (mProxyLock) {
3018            return mGlobalProxy;
3019        }
3020    }
3021
3022    private void handleApplyDefaultProxy(ProxyInfo proxy) {
3023        if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3024                && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
3025            proxy = null;
3026        }
3027        synchronized (mProxyLock) {
3028            if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
3029            if (mDefaultProxy == proxy) return; // catches repeated nulls
3030            if (proxy != null &&  !proxy.isValid()) {
3031                if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3032                return;
3033            }
3034
3035            // This call could be coming from the PacManager, containing the port of the local
3036            // proxy.  If this new proxy matches the global proxy then copy this proxy to the
3037            // global (to get the correct local port), and send a broadcast.
3038            // TODO: Switch PacManager to have its own message to send back rather than
3039            // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
3040            if ((mGlobalProxy != null) && (proxy != null)
3041                    && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
3042                    && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3043                mGlobalProxy = proxy;
3044                sendProxyBroadcast(mGlobalProxy);
3045                return;
3046            }
3047            mDefaultProxy = proxy;
3048
3049            if (mGlobalProxy != null) return;
3050            if (!mDefaultProxyDisabled) {
3051                sendProxyBroadcast(proxy);
3052            }
3053        }
3054    }
3055
3056    // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3057    // This method gets called when any network changes proxy, but the broadcast only ever contains
3058    // the default proxy (even if it hasn't changed).
3059    // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3060    // world where an app might be bound to a non-default network.
3061    private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3062        ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3063        ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3064
3065        if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3066            sendProxyBroadcast(getDefaultProxy());
3067        }
3068    }
3069
3070    private void handleDeprecatedGlobalHttpProxy() {
3071        String proxy = Settings.Global.getString(mContext.getContentResolver(),
3072                Settings.Global.HTTP_PROXY);
3073        if (!TextUtils.isEmpty(proxy)) {
3074            String data[] = proxy.split(":");
3075            if (data.length == 0) {
3076                return;
3077            }
3078
3079            String proxyHost =  data[0];
3080            int proxyPort = 8080;
3081            if (data.length > 1) {
3082                try {
3083                    proxyPort = Integer.parseInt(data[1]);
3084                } catch (NumberFormatException e) {
3085                    return;
3086                }
3087            }
3088            ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
3089            setGlobalProxy(p);
3090        }
3091    }
3092
3093    private void sendProxyBroadcast(ProxyInfo proxy) {
3094        if (proxy == null) proxy = new ProxyInfo("", 0, "");
3095        if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
3096        if (DBG) log("sending Proxy Broadcast for " + proxy);
3097        Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
3098        intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3099            Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
3100        intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
3101        final long ident = Binder.clearCallingIdentity();
3102        try {
3103            mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3104        } finally {
3105            Binder.restoreCallingIdentity(ident);
3106        }
3107    }
3108
3109    private static class SettingsObserver extends ContentObserver {
3110        final private HashMap<Uri, Integer> mUriEventMap;
3111        final private Context mContext;
3112        final private Handler mHandler;
3113
3114        SettingsObserver(Context context, Handler handler) {
3115            super(null);
3116            mUriEventMap = new HashMap<Uri, Integer>();
3117            mContext = context;
3118            mHandler = handler;
3119        }
3120
3121        void observe(Uri uri, int what) {
3122            mUriEventMap.put(uri, what);
3123            final ContentResolver resolver = mContext.getContentResolver();
3124            resolver.registerContentObserver(uri, false, this);
3125        }
3126
3127        @Override
3128        public void onChange(boolean selfChange) {
3129            Slog.wtf(TAG, "Should never be reached.");
3130        }
3131
3132        @Override
3133        public void onChange(boolean selfChange, Uri uri) {
3134            final Integer what = mUriEventMap.get(uri);
3135            if (what != null) {
3136                mHandler.obtainMessage(what.intValue()).sendToTarget();
3137            } else {
3138                loge("No matching event to send for URI=" + uri);
3139            }
3140        }
3141    }
3142
3143    private static void log(String s) {
3144        Slog.d(TAG, s);
3145    }
3146
3147    private static void loge(String s) {
3148        Slog.e(TAG, s);
3149    }
3150
3151    private static <T> T checkNotNull(T value, String message) {
3152        if (value == null) {
3153            throw new NullPointerException(message);
3154        }
3155        return value;
3156    }
3157
3158    /**
3159     * Prepare for a VPN application.
3160     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3161     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3162     *
3163     * @param oldPackage Package name of the application which currently controls VPN, which will
3164     *                   be replaced. If there is no such application, this should should either be
3165     *                   {@code null} or {@link VpnConfig.LEGACY_VPN}.
3166     * @param newPackage Package name of the application which should gain control of VPN, or
3167     *                   {@code null} to disable.
3168     * @param userId User for whom to prepare the new VPN.
3169     *
3170     * @hide
3171     */
3172    @Override
3173    public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3174            int userId) {
3175        enforceCrossUserPermission(userId);
3176        throwIfLockdownEnabled();
3177
3178        synchronized(mVpns) {
3179            Vpn vpn = mVpns.get(userId);
3180            if (vpn != null) {
3181                return vpn.prepare(oldPackage, newPackage);
3182            } else {
3183                return false;
3184            }
3185        }
3186    }
3187
3188    /**
3189     * Set whether the VPN package has the ability to launch VPNs without user intervention.
3190     * This method is used by system-privileged apps.
3191     * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3192     * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3193     *
3194     * @param packageName The package for which authorization state should change.
3195     * @param userId User for whom {@code packageName} is installed.
3196     * @param authorized {@code true} if this app should be able to start a VPN connection without
3197     *                   explicit user approval, {@code false} if not.
3198     *
3199     * @hide
3200     */
3201    @Override
3202    public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3203        enforceCrossUserPermission(userId);
3204
3205        synchronized(mVpns) {
3206            Vpn vpn = mVpns.get(userId);
3207            if (vpn != null) {
3208                vpn.setPackageAuthorization(packageName, authorized);
3209            }
3210        }
3211    }
3212
3213    /**
3214     * Configure a TUN interface and return its file descriptor. Parameters
3215     * are encoded and opaque to this class. This method is used by VpnBuilder
3216     * and not available in ConnectivityManager. Permissions are checked in
3217     * Vpn class.
3218     * @hide
3219     */
3220    @Override
3221    public ParcelFileDescriptor establishVpn(VpnConfig config) {
3222        throwIfLockdownEnabled();
3223        int user = UserHandle.getUserId(Binder.getCallingUid());
3224        synchronized(mVpns) {
3225            return mVpns.get(user).establish(config);
3226        }
3227    }
3228
3229    /**
3230     * Start legacy VPN, controlling native daemons as needed. Creates a
3231     * secondary thread to perform connection work, returning quickly.
3232     */
3233    @Override
3234    public void startLegacyVpn(VpnProfile profile) {
3235        throwIfLockdownEnabled();
3236        final LinkProperties egress = getActiveLinkProperties();
3237        if (egress == null) {
3238            throw new IllegalStateException("Missing active network connection");
3239        }
3240        int user = UserHandle.getUserId(Binder.getCallingUid());
3241        synchronized(mVpns) {
3242            mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3243        }
3244    }
3245
3246    /**
3247     * Return the information of the ongoing legacy VPN. This method is used
3248     * by VpnSettings and not available in ConnectivityManager. Permissions
3249     * are checked in Vpn class.
3250     */
3251    @Override
3252    public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3253        enforceCrossUserPermission(userId);
3254
3255        synchronized(mVpns) {
3256            return mVpns.get(userId).getLegacyVpnInfo();
3257        }
3258    }
3259
3260    /**
3261     * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3262     * and not available in ConnectivityManager.
3263     */
3264    @Override
3265    public VpnInfo[] getAllVpnInfo() {
3266        enforceConnectivityInternalPermission();
3267        if (mLockdownEnabled) {
3268            return new VpnInfo[0];
3269        }
3270
3271        synchronized(mVpns) {
3272            List<VpnInfo> infoList = new ArrayList<>();
3273            for (int i = 0; i < mVpns.size(); i++) {
3274                VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3275                if (info != null) {
3276                    infoList.add(info);
3277                }
3278            }
3279            return infoList.toArray(new VpnInfo[infoList.size()]);
3280        }
3281    }
3282
3283    /**
3284     * @return VPN information for accounting, or null if we can't retrieve all required
3285     *         information, e.g primary underlying iface.
3286     */
3287    @Nullable
3288    private VpnInfo createVpnInfo(Vpn vpn) {
3289        VpnInfo info = vpn.getVpnInfo();
3290        if (info == null) {
3291            return null;
3292        }
3293        Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3294        // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3295        // the underlyingNetworks list.
3296        if (underlyingNetworks == null) {
3297            NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3298            if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3299                info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3300            }
3301        } else if (underlyingNetworks.length > 0) {
3302            LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3303            if (linkProperties != null) {
3304                info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3305            }
3306        }
3307        return info.primaryUnderlyingIface == null ? null : info;
3308    }
3309
3310    /**
3311     * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3312     * VpnDialogs and not available in ConnectivityManager.
3313     * Permissions are checked in Vpn class.
3314     * @hide
3315     */
3316    @Override
3317    public VpnConfig getVpnConfig(int userId) {
3318        enforceCrossUserPermission(userId);
3319        synchronized(mVpns) {
3320            Vpn vpn = mVpns.get(userId);
3321            if (vpn != null) {
3322                return vpn.getVpnConfig();
3323            } else {
3324                return null;
3325            }
3326        }
3327    }
3328
3329    @Override
3330    public boolean updateLockdownVpn() {
3331        if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3332            Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3333            return false;
3334        }
3335
3336        // Tear down existing lockdown if profile was removed
3337        mLockdownEnabled = LockdownVpnTracker.isEnabled();
3338        if (mLockdownEnabled) {
3339            final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3340            final VpnProfile profile = VpnProfile.decode(
3341                    profileName, mKeyStore.get(Credentials.VPN + profileName));
3342            if (profile == null) {
3343                Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3344                setLockdownTracker(null);
3345                return true;
3346            }
3347            int user = UserHandle.getUserId(Binder.getCallingUid());
3348            synchronized(mVpns) {
3349                Vpn vpn = mVpns.get(user);
3350                if (vpn == null) {
3351                    Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3352                    return false;
3353                }
3354                setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
3355            }
3356        } else {
3357            setLockdownTracker(null);
3358        }
3359
3360        return true;
3361    }
3362
3363    /**
3364     * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3365     * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3366     */
3367    private void setLockdownTracker(LockdownVpnTracker tracker) {
3368        // Shutdown any existing tracker
3369        final LockdownVpnTracker existing = mLockdownTracker;
3370        mLockdownTracker = null;
3371        if (existing != null) {
3372            existing.shutdown();
3373        }
3374
3375        try {
3376            if (tracker != null) {
3377                mNetd.setFirewallEnabled(true);
3378                mNetd.setFirewallInterfaceRule("lo", true);
3379                mLockdownTracker = tracker;
3380                mLockdownTracker.init();
3381            } else {
3382                mNetd.setFirewallEnabled(false);
3383            }
3384        } catch (RemoteException e) {
3385            // ignored; NMS lives inside system_server
3386        }
3387    }
3388
3389    private void throwIfLockdownEnabled() {
3390        if (mLockdownEnabled) {
3391            throw new IllegalStateException("Unavailable in lockdown mode");
3392        }
3393    }
3394
3395    /**
3396     * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3397     * some setup and then call {@code establish()} to connect.
3398     *
3399     * @return {@code true} if the service was started, the service was already connected, or there
3400     *         was no always-on VPN to start. {@code false} otherwise.
3401     */
3402    private boolean startAlwaysOnVpn(int userId) {
3403        synchronized (mVpns) {
3404            Vpn vpn = mVpns.get(userId);
3405            if (vpn == null) {
3406                // Shouldn't happen as all codepaths that point here should have checked the Vpn
3407                // exists already.
3408                Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3409                return false;
3410            }
3411
3412            return vpn.startAlwaysOnVpn();
3413        }
3414    }
3415
3416    @Override
3417    public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
3418        enforceConnectivityInternalPermission();
3419        enforceCrossUserPermission(userId);
3420
3421        // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3422        if (LockdownVpnTracker.isEnabled()) {
3423            return false;
3424        }
3425
3426        synchronized (mVpns) {
3427            Vpn vpn = mVpns.get(userId);
3428            if (vpn == null) {
3429                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3430                return false;
3431            }
3432            if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
3433                return false;
3434            }
3435            if (!startAlwaysOnVpn(userId)) {
3436                vpn.setAlwaysOnPackage(null, false);
3437                return false;
3438            }
3439
3440            vpn.saveAlwaysOnPackage();
3441        }
3442        return true;
3443    }
3444
3445    @Override
3446    public String getAlwaysOnVpnPackage(int userId) {
3447        enforceConnectivityInternalPermission();
3448        enforceCrossUserPermission(userId);
3449
3450        synchronized (mVpns) {
3451            Vpn vpn = mVpns.get(userId);
3452            if (vpn == null) {
3453                Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3454                return null;
3455            }
3456            return vpn.getAlwaysOnPackage();
3457        }
3458    }
3459
3460    @Override
3461    public int checkMobileProvisioning(int suggestedTimeOutMs) {
3462        // TODO: Remove?  Any reason to trigger a provisioning check?
3463        return -1;
3464    }
3465
3466    private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3467    private static enum NotificationType { SIGN_IN, NO_INTERNET; };
3468
3469    private void setProvNotificationVisible(boolean visible, int networkType, String action) {
3470        Intent intent = new Intent(action);
3471        PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
3472        // Concatenate the range of types onto the range of NetIDs.
3473        int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3474        setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3475                networkType, null, pendingIntent, false);
3476    }
3477
3478    /**
3479     * Show or hide network provisioning notifications.
3480     *
3481     * We use notifications for two purposes: to notify that a network requires sign in
3482     * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3483     * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3484     * particular network we can display the notification type that was most recently requested.
3485     * So for example if a captive portal fails to reply within a few seconds of connecting, we
3486     * might first display NO_INTERNET, and then when the captive portal check completes, display
3487     * SIGN_IN.
3488     *
3489     * @param id an identifier that uniquely identifies this notification.  This must match
3490     *         between show and hide calls.  We use the NetID value but for legacy callers
3491     *         we concatenate the range of types with the range of NetIDs.
3492     */
3493    private void setProvNotificationVisibleIntent(boolean visible, int id,
3494            NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3495            boolean highPriority) {
3496        if (VDBG || (DBG && visible)) {
3497            log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3498                    + " networkType=" + getNetworkTypeName(networkType)
3499                    + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
3500        }
3501
3502        Resources r = Resources.getSystem();
3503        NotificationManager notificationManager = (NotificationManager) mContext
3504            .getSystemService(Context.NOTIFICATION_SERVICE);
3505
3506        if (visible) {
3507            CharSequence title;
3508            CharSequence details;
3509            int icon;
3510            if (notifyType == NotificationType.NO_INTERNET &&
3511                    networkType == ConnectivityManager.TYPE_WIFI) {
3512                title = r.getString(R.string.wifi_no_internet, 0);
3513                details = r.getString(R.string.wifi_no_internet_detailed);
3514                icon = R.drawable.stat_notify_wifi_in_range;  // TODO: Need new icon.
3515            } else if (notifyType == NotificationType.SIGN_IN) {
3516                switch (networkType) {
3517                    case ConnectivityManager.TYPE_WIFI:
3518                        title = r.getString(R.string.wifi_available_sign_in, 0);
3519                        details = r.getString(R.string.network_available_sign_in_detailed,
3520                                extraInfo);
3521                        icon = R.drawable.stat_notify_wifi_in_range;
3522                        break;
3523                    case ConnectivityManager.TYPE_MOBILE:
3524                    case ConnectivityManager.TYPE_MOBILE_HIPRI:
3525                        title = r.getString(R.string.network_available_sign_in, 0);
3526                        // TODO: Change this to pull from NetworkInfo once a printable
3527                        // name has been added to it
3528                        details = mTelephonyManager.getNetworkOperatorName();
3529                        icon = R.drawable.stat_notify_rssi_in_range;
3530                        break;
3531                    default:
3532                        title = r.getString(R.string.network_available_sign_in, 0);
3533                        details = r.getString(R.string.network_available_sign_in_detailed,
3534                                extraInfo);
3535                        icon = R.drawable.stat_notify_rssi_in_range;
3536                        break;
3537                }
3538            } else {
3539                Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3540                        + getNetworkTypeName(networkType));
3541                return;
3542            }
3543
3544            Notification notification = new Notification.Builder(mContext)
3545                    .setWhen(0)
3546                    .setSmallIcon(icon)
3547                    .setAutoCancel(true)
3548                    .setTicker(title)
3549                    .setColor(mContext.getColor(
3550                            com.android.internal.R.color.system_notification_accent_color))
3551                    .setContentTitle(title)
3552                    .setContentText(details)
3553                    .setContentIntent(intent)
3554                    .setLocalOnly(true)
3555                    .setPriority(highPriority ?
3556                            Notification.PRIORITY_HIGH :
3557                            Notification.PRIORITY_DEFAULT)
3558                    .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
3559                    .setOnlyAlertOnce(true)
3560                    .build();
3561
3562            try {
3563                notificationManager.notifyAsUser(NOTIFICATION_ID, id, notification, UserHandle.ALL);
3564            } catch (NullPointerException npe) {
3565                loge("setNotificationVisible: visible notificationManager npe=" + npe);
3566                npe.printStackTrace();
3567            }
3568        } else {
3569            try {
3570                notificationManager.cancelAsUser(NOTIFICATION_ID, id, UserHandle.ALL);
3571            } catch (NullPointerException npe) {
3572                loge("setNotificationVisible: cancel notificationManager npe=" + npe);
3573                npe.printStackTrace();
3574            }
3575        }
3576    }
3577
3578    /** Location to an updatable file listing carrier provisioning urls.
3579     *  An example:
3580     *
3581     * <?xml version="1.0" encoding="utf-8"?>
3582     *  <provisioningUrls>
3583     *   <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&iccid=%1$s&imei=%2$s</provisioningUrl>
3584     *  </provisioningUrls>
3585     */
3586    private static final String PROVISIONING_URL_PATH =
3587            "/data/misc/radio/provisioning_urls.xml";
3588    private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
3589
3590    /** XML tag for root element. */
3591    private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3592    /** XML tag for individual url */
3593    private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3594    /** XML attribute for mcc */
3595    private static final String ATTR_MCC = "mcc";
3596    /** XML attribute for mnc */
3597    private static final String ATTR_MNC = "mnc";
3598
3599    private String getProvisioningUrlBaseFromFile() {
3600        FileReader fileReader = null;
3601        XmlPullParser parser = null;
3602        Configuration config = mContext.getResources().getConfiguration();
3603
3604        try {
3605            fileReader = new FileReader(mProvisioningUrlFile);
3606            parser = Xml.newPullParser();
3607            parser.setInput(fileReader);
3608            XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3609
3610            while (true) {
3611                XmlUtils.nextElement(parser);
3612
3613                String element = parser.getName();
3614                if (element == null) break;
3615
3616                if (element.equals(TAG_PROVISIONING_URL)) {
3617                    String mcc = parser.getAttributeValue(null, ATTR_MCC);
3618                    try {
3619                        if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3620                            String mnc = parser.getAttributeValue(null, ATTR_MNC);
3621                            if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3622                                parser.next();
3623                                if (parser.getEventType() == XmlPullParser.TEXT) {
3624                                    return parser.getText();
3625                                }
3626                            }
3627                        }
3628                    } catch (NumberFormatException e) {
3629                        loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3630                    }
3631                }
3632            }
3633            return null;
3634        } catch (FileNotFoundException e) {
3635            loge("Carrier Provisioning Urls file not found");
3636        } catch (XmlPullParserException e) {
3637            loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3638        } catch (IOException e) {
3639            loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3640        } finally {
3641            if (fileReader != null) {
3642                try {
3643                    fileReader.close();
3644                } catch (IOException e) {}
3645            }
3646        }
3647        return null;
3648    }
3649
3650    @Override
3651    public String getMobileProvisioningUrl() {
3652        enforceConnectivityInternalPermission();
3653        String url = getProvisioningUrlBaseFromFile();
3654        if (TextUtils.isEmpty(url)) {
3655            url = mContext.getResources().getString(R.string.mobile_provisioning_url);
3656            log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
3657        } else {
3658            log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
3659        }
3660        // populate the iccid, imei and phone number in the provisioning url.
3661        if (!TextUtils.isEmpty(url)) {
3662            String phoneNumber = mTelephonyManager.getLine1Number();
3663            if (TextUtils.isEmpty(phoneNumber)) {
3664                phoneNumber = "0000000000";
3665            }
3666            url = String.format(url,
3667                    mTelephonyManager.getSimSerialNumber() /* ICCID */,
3668                    mTelephonyManager.getDeviceId() /* IMEI */,
3669                    phoneNumber /* Phone numer */);
3670        }
3671
3672        return url;
3673    }
3674
3675    @Override
3676    public void setProvisioningNotificationVisible(boolean visible, int networkType,
3677            String action) {
3678        enforceConnectivityInternalPermission();
3679        final long ident = Binder.clearCallingIdentity();
3680        try {
3681            setProvNotificationVisible(visible, networkType, action);
3682        } finally {
3683            Binder.restoreCallingIdentity(ident);
3684        }
3685    }
3686
3687    @Override
3688    public void setAirplaneMode(boolean enable) {
3689        enforceConnectivityInternalPermission();
3690        final long ident = Binder.clearCallingIdentity();
3691        try {
3692            final ContentResolver cr = mContext.getContentResolver();
3693            Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3694            Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3695            intent.putExtra("state", enable);
3696            mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3697        } finally {
3698            Binder.restoreCallingIdentity(ident);
3699        }
3700    }
3701
3702    private void onUserStart(int userId) {
3703        synchronized(mVpns) {
3704            Vpn userVpn = mVpns.get(userId);
3705            if (userVpn != null) {
3706                loge("Starting user already has a VPN");
3707                return;
3708            }
3709            userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
3710            mVpns.put(userId, userVpn);
3711
3712            final ContentResolver cr = mContext.getContentResolver();
3713            String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3714                    Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3715            final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3716                    Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3717            if (alwaysOnPackage != null) {
3718                userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3719            }
3720        }
3721        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3722            updateLockdownVpn();
3723        }
3724    }
3725
3726    private void onUserStop(int userId) {
3727        synchronized(mVpns) {
3728            Vpn userVpn = mVpns.get(userId);
3729            if (userVpn == null) {
3730                loge("Stopped user has no VPN");
3731                return;
3732            }
3733            userVpn.onUserStopped();
3734            mVpns.delete(userId);
3735        }
3736    }
3737
3738    private void onUserAdded(int userId) {
3739        synchronized(mVpns) {
3740            final int vpnsSize = mVpns.size();
3741            for (int i = 0; i < vpnsSize; i++) {
3742                Vpn vpn = mVpns.valueAt(i);
3743                vpn.onUserAdded(userId);
3744            }
3745        }
3746    }
3747
3748    private void onUserRemoved(int userId) {
3749        synchronized(mVpns) {
3750            final int vpnsSize = mVpns.size();
3751            for (int i = 0; i < vpnsSize; i++) {
3752                Vpn vpn = mVpns.valueAt(i);
3753                vpn.onUserRemoved(userId);
3754            }
3755        }
3756    }
3757
3758    private void onUserUnlocked(int userId) {
3759        // User present may be sent because of an unlock, which might mean an unlocked keystore.
3760        if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3761            updateLockdownVpn();
3762        } else {
3763            startAlwaysOnVpn(userId);
3764        }
3765    }
3766
3767    private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3768        @Override
3769        public void onReceive(Context context, Intent intent) {
3770            final String action = intent.getAction();
3771            final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3772            if (userId == UserHandle.USER_NULL) return;
3773
3774            if (Intent.ACTION_USER_STARTED.equals(action)) {
3775                onUserStart(userId);
3776            } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3777                onUserStop(userId);
3778            } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3779                onUserAdded(userId);
3780            } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3781                onUserRemoved(userId);
3782            } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3783                onUserUnlocked(userId);
3784            }
3785        }
3786    };
3787
3788    private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3789            new HashMap<Messenger, NetworkFactoryInfo>();
3790    private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3791            new HashMap<NetworkRequest, NetworkRequestInfo>();
3792
3793    private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3794    // Map from UID to number of NetworkRequests that UID has filed.
3795    @GuardedBy("mUidToNetworkRequestCount")
3796    private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3797
3798    private static class NetworkFactoryInfo {
3799        public final String name;
3800        public final Messenger messenger;
3801        public final AsyncChannel asyncChannel;
3802
3803        public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3804            this.name = name;
3805            this.messenger = messenger;
3806            this.asyncChannel = asyncChannel;
3807        }
3808    }
3809
3810    /**
3811     * A NetworkRequest as registered by an application can be one of three
3812     * types:
3813     *
3814     *     - "listen", for which the framework will issue callbacks about any
3815     *       and all networks that match the specified NetworkCapabilities,
3816     *
3817     *     - "request", capable of causing a specific network to be created
3818     *       first (e.g. a telephony DUN request), the framework will issue
3819     *       callbacks about the single, highest scoring current network
3820     *       (if any) that matches the specified NetworkCapabilities, or
3821     *
3822     *     - "track the default network", a hybrid of the two designed such
3823     *       that the framework will issue callbacks for the single, highest
3824     *       scoring current network (if any) that matches the capabilities of
3825     *       the default Internet request (mDefaultRequest), but which cannot
3826     *       cause the framework to either create or retain the existence of
3827     *       any specific network.
3828     *
3829     */
3830    private static enum NetworkRequestType {
3831        LISTEN,
3832        TRACK_DEFAULT,
3833        REQUEST
3834    };
3835
3836    /**
3837     * Tracks info about the requester.
3838     * Also used to notice when the calling process dies so we can self-expire
3839     */
3840    private class NetworkRequestInfo implements IBinder.DeathRecipient {
3841        final NetworkRequest request;
3842        final PendingIntent mPendingIntent;
3843        boolean mPendingIntentSent;
3844        private final IBinder mBinder;
3845        final int mPid;
3846        final int mUid;
3847        final Messenger messenger;
3848        private final NetworkRequestType mType;
3849
3850        NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
3851            request = r;
3852            mPendingIntent = pi;
3853            messenger = null;
3854            mBinder = null;
3855            mPid = getCallingPid();
3856            mUid = getCallingUid();
3857            mType = type;
3858            enforceRequestCountLimit();
3859        }
3860
3861        NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
3862            super();
3863            messenger = m;
3864            request = r;
3865            mBinder = binder;
3866            mPid = getCallingPid();
3867            mUid = getCallingUid();
3868            mType = type;
3869            mPendingIntent = null;
3870            enforceRequestCountLimit();
3871
3872            try {
3873                mBinder.linkToDeath(this, 0);
3874            } catch (RemoteException e) {
3875                binderDied();
3876            }
3877        }
3878
3879        private void enforceRequestCountLimit() {
3880            synchronized (mUidToNetworkRequestCount) {
3881                int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3882                if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3883                    throw new IllegalArgumentException("Too many NetworkRequests filed");
3884                }
3885                mUidToNetworkRequestCount.put(mUid, networkRequests);
3886            }
3887        }
3888
3889        private String typeString() {
3890            switch (mType) {
3891                case LISTEN: return "Listen";
3892                case REQUEST: return "Request";
3893                case TRACK_DEFAULT: return "Track default";
3894                default:
3895                    return "unknown type";
3896            }
3897        }
3898
3899        void unlinkDeathRecipient() {
3900            if (mBinder != null) {
3901                mBinder.unlinkToDeath(this, 0);
3902            }
3903        }
3904
3905        public void binderDied() {
3906            log("ConnectivityService NetworkRequestInfo binderDied(" +
3907                    request + ", " + mBinder + ")");
3908            releaseNetworkRequest(request);
3909        }
3910
3911        /**
3912         * Returns true iff. the contained NetworkRequest is one that:
3913         *
3914         *     - should be associated with at most one satisfying network
3915         *       at a time;
3916         *
3917         *     - should cause a network to be kept up if it is the only network
3918         *       which can satisfy the NetworkReqeust.
3919         *
3920         * For full detail of how isRequest() is used for pairing Networks with
3921         * NetworkRequests read rematchNetworkAndRequests().
3922         *
3923         * TODO: Rename to something more properly descriptive.
3924         */
3925        public boolean isRequest() {
3926            return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3927                   (mType == NetworkRequestType.REQUEST);
3928        }
3929
3930        public String toString() {
3931            return typeString() +
3932                    " from uid/pid:" + mUid + "/" + mPid +
3933                    " for " + request +
3934                    (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
3935        }
3936    }
3937
3938    private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3939        final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3940        if (badCapability != null) {
3941            throw new IllegalArgumentException("Cannot request network with " + badCapability);
3942        }
3943    }
3944
3945    private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
3946        final SortedSet<Integer> thresholds = new TreeSet();
3947        synchronized (nai) {
3948            for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3949                if (nri.request.networkCapabilities.hasSignalStrength() &&
3950                        nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3951                    thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3952                }
3953            }
3954        }
3955        return new ArrayList<Integer>(thresholds);
3956    }
3957
3958    private void updateSignalStrengthThresholds(
3959            NetworkAgentInfo nai, String reason, NetworkRequest request) {
3960        ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
3961        Bundle thresholds = new Bundle();
3962        thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3963
3964        if (VDBG || (DBG && !"CONNECT".equals(reason))) {
3965            String detail;
3966            if (request != null && request.networkCapabilities.hasSignalStrength()) {
3967                detail = reason + " " + request.networkCapabilities.getSignalStrength();
3968            } else {
3969                detail = reason;
3970            }
3971            log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3972                    detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3973        }
3974
3975        nai.asyncChannel.sendMessage(
3976                android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
3977                0, 0, thresholds);
3978    }
3979
3980    @Override
3981    public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
3982            Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
3983        final NetworkRequestType type = (networkCapabilities == null)
3984                ? NetworkRequestType.TRACK_DEFAULT
3985                : NetworkRequestType.REQUEST;
3986        // If the requested networkCapabilities is null, take them instead from
3987        // the default network request. This allows callers to keep track of
3988        // the system default network.
3989        if (type == NetworkRequestType.TRACK_DEFAULT) {
3990            networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3991            enforceAccessPermission();
3992        } else {
3993            networkCapabilities = new NetworkCapabilities(networkCapabilities);
3994            enforceNetworkRequestPermissions(networkCapabilities);
3995        }
3996        enforceMeteredApnPolicy(networkCapabilities);
3997        ensureRequestableCapabilities(networkCapabilities);
3998
3999        if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
4000            throw new IllegalArgumentException("Bad timeout specified");
4001        }
4002
4003        if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4004                .equals(networkCapabilities.getNetworkSpecifier())) {
4005            throw new IllegalArgumentException("Invalid network specifier - must not be '"
4006                    + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4007        }
4008
4009        NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4010                nextNetworkRequestId());
4011        NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
4012        if (DBG) log("requestNetwork for " + nri);
4013
4014        mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
4015        if (timeoutMs > 0) {
4016            mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
4017                    nri), timeoutMs);
4018        }
4019        return networkRequest;
4020    }
4021
4022    private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
4023        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
4024            enforceConnectivityInternalPermission();
4025        } else {
4026            enforceChangePermission();
4027        }
4028    }
4029
4030    @Override
4031    public boolean requestBandwidthUpdate(Network network) {
4032        enforceAccessPermission();
4033        NetworkAgentInfo nai = null;
4034        if (network == null) {
4035            return false;
4036        }
4037        synchronized (mNetworkForNetId) {
4038            nai = mNetworkForNetId.get(network.netId);
4039        }
4040        if (nai != null) {
4041            nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4042            return true;
4043        }
4044        return false;
4045    }
4046
4047    private boolean isSystem(int uid) {
4048        return uid < Process.FIRST_APPLICATION_UID;
4049    }
4050
4051    private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4052        final int uid = Binder.getCallingUid();
4053        if (isSystem(uid)) {
4054            return;
4055        }
4056        // if UID is restricted, don't allow them to bring up metered APNs
4057        if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
4058            final int uidRules;
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