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