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