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